Class: Phronomy::Agent::ExecutionCoordinator

Inherits:
Object
  • Object
show all
Defined in:
lib/phronomy/agent/execution_coordinator.rb

Defined Under Namespace

Classes: AgentTerminalCommand, PrepFailureCommand, Prepared

Instance Method Summary collapse

Constructor Details

#initialize(agent) ⇒ ExecutionCoordinator

Returns a new instance of ExecutionCoordinator.



12
13
14
# File 'lib/phronomy/agent/execution_coordinator.rb', line 12

def initialize(agent)
  @agent = agent
end

Instance Method Details

#admit_execution(raw_message, thread_id:) ⇒ Object

Raises:



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/phronomy/agent/execution_coordinator.rb', line 291

def admit_execution(raw_message, thread_id:)
  root = @agent.agent_root
  raise Phronomy::Error, "agent is closed: #{@agent.agent_id}" if root.lifecycle_status == :closed

  execution = next_root = nil
  @agent.persistence.transaction do |tx|
    input_ref = tx.contents.put_text(raw_message)
    input_record = JournalRecord.new(
      agent_id: @agent.agent_id,
      kind: :input_received,
      channel: :external,
      role: :user,
      content_ref: input_ref,
      correlation_id: thread_id,
      context_generation: root.transcript_generation,
      context_candidate: false
    )
    policy_descriptor = ContextPolicies::Default.new.descriptor
    execution = AgentExecution.start(
      agent_root: root,
      input_record: input_record,
      metadata: {
        "thread_id" => thread_id,
        "current_input_ref" => input_ref,
        "context_policy" => policy_descriptor.to_h
      }.compact
    )
    input_record = JournalRecord.from_h(
      input_record.to_h.merge("execution_id" => execution.execution_id)
    )
    execution = execution.with(
      execution_revision: 0,
      working_records: [input_record]
    )
    tx.executions.create_active(execution)
    next_root = root.with(
      agent_revision: root.agent_revision + 1,
      lifecycle_status: :active
    )
    tx.agents.save(
      root.agent_id,
      expected_revision: root.agent_revision,
      root: next_root
    )
  end
  [execution, next_root]
end

#commit_preparation_failure(execution, error) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/phronomy/agent/execution_coordinator.rb', line 339

def commit_preparation_failure(execution, error)
  translated_error = translated(error)
  root = @agent.agent_root
  failed = next_root = appended = nil

  @agent.persistence.transaction do |tx|
    error_ref = tx.contents.put_json(
      "class" => translated_error.class.name,
      "message" => translated_error.message
    )
    audit_records = execution.working_records.map do |record|
      JournalRecord.from_h(
        record.to_h.merge("context_candidate" => false)
      )
    end
    terminal_status = terminal_status_for(translated_error)
    audit_records << JournalRecord.new(
      agent_id: @agent.agent_id,
      execution_id: execution.execution_id,
      kind: execution_terminal_kind(terminal_status),
      channel: :audit,
      content_ref: error_ref,
      context_generation: root.transcript_generation,
      context_candidate: false
    )
    appended = tx.journals.append(
      root.agent_id,
      expected_position: root.journal_position,
      records: audit_records
    )
    failed = execution.with(
      status: terminal_status,
      phase: terminal_status,
      working_records: [],
      error_ref: error_ref,
      terminal_reason: translated_error.class.name
    )
    tx.executions.save(
      execution.execution_id,
      expected_revision: execution.execution_revision,
      execution: failed
    )
    next_root = root.with(
      agent_revision: root.agent_revision + 1,
      journal_position: root.journal_position + appended.length,
      lifecycle_status: :idle
    )
    tx.agents.save(
      root.agent_id,
      expected_revision: root.agent_revision,
      root: next_root
    )
  end
  @agent.send(:_append_journal_records, appended)
  @agent.__replace_root(next_root)
  failed
end

#deliver_on_event_loop(command) ⇒ Object



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/phronomy/agent/execution_coordinator.rb', line 475

def deliver_on_event_loop(command)
  case command
  when PrepFailureCommand
    callback_error = @agent.send(
      :_deliver_stream_event,
      command.on_event_listener,
      StreamEvent.new(
        type: terminal_event_type(command.error),
        payload: {error: command.error}
      )
    )
    settle_after_terminal(
      command.result_task,
      callback_error,
      terminal_event_type(command.error),
      nil,
      command.error
    )
  when AgentTerminalCommand
    deliver_execution_terminal(command)
  else
    raise Phronomy::Error, "unknown terminal command: #{command.class}"
  end
end

#finish(activation, result_task, invocation, error) ⇒ Object



447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/phronomy/agent/execution_coordinator.rb', line 447

def finish(activation, result_task, invocation, error)
  runtime = Phronomy::Runtime.instance
  operation = runtime.offload.submit(on_full: :raise) do
    compute_terminal(activation, invocation, error)
  end
  operation.on_complete do |outcome, commit_error|
    command = AgentTerminalCommand.new(
      self, activation, result_task, outcome, commit_error
    )
    posted = runtime.event_loop.post(
      Phronomy::Event.new(
        type: :agent_terminal_ready,
        target_id: Phronomy::EventLoop::SYSTEM_CHANNEL_ID,
        payload: {command: command}
      )
    )
    unless posted
      settle_without_listener(
        activation, result_task, outcome, commit_error
      )
    end
  end
rescue => caught
  fail_task(result_task, translated(caught))
end

#prepare(input, thread_id:, config:) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/phronomy/agent/execution_coordinator.rb', line 194

def prepare(input, thread_id:, config:)
  raw_message = @agent.send(:extract_message, input)
  execution, active_root = admit_execution(
    raw_message,
    thread_id: thread_id
  )
  @agent.__replace_root(active_root)
  current_execution = execution

  begin
    effective_config = thread_id ? config.merge(thread_id: thread_id) : config
    @agent.send(
      :check_cancellation!,
      effective_config,
      "invocation cancelled before input filtering"
    )
    filtered_input = @agent.send(:run_input_filters!, input)
    @agent.send(
      :check_cancellation!,
      effective_config,
      "invocation cancelled before context assembly"
    )
    filtered_message = @agent.send(:extract_message, filtered_input)
    manifest = manifest_ref = active_execution = nil
    local_journal = @agent.send(:_journal_records_snapshot)

    @agent.persistence.transaction do |tx|
      assert_local_durable_base!(tx, active_root)
      filtered_ref = tx.contents.put_text(filtered_message)
      input_record = JournalRecord.new(
        agent_id: @agent.agent_id,
        execution_id: current_execution.execution_id,
        kind: :external_message,
        channel: :external,
        role: :user,
        content_ref: filtered_ref,
        correlation_id: thread_id,
        context_generation: active_root.transcript_generation,
        context_candidate: true
      )
      staged = current_execution.with(
        execution_revision: current_execution.execution_revision,
        working_records: current_execution.working_records + [input_record],
        metadata: current_execution..merge(
          "current_input_ref" => filtered_ref,
          "current_input_record_id" => input_record.record_id
        )
      )
      manifest, manifest_ref = ContextAssembler.new(
        agent: @agent,
        persistence: tx,
        policy: context_policy_for(staged),
        journal_records: local_journal
      ).build_initial(
        input: filtered_input,
        agent_root: active_root,
        execution: staged,
        config: effective_config,
        patch: @agent.send(
          :run_before_llm_input_hooks,
          call_sequence: 1,
          config: effective_config
        )
      )
      active_execution = staged.with(
        status: :active,
        phase: :calling_llm,
        metadata: staged..merge(
          "base_manifest_ref" => manifest_ref,
          "manifest_ref" => manifest_ref,
          "manifest_refs" => [manifest_ref]
        )
      )
      tx.executions.save(
        current_execution.execution_id,
        expected_revision: current_execution.execution_revision,
        execution: active_execution
      )
    end
    current_execution = active_execution

    projection = RubyLLMMaterializer.new(
      agent: @agent,
      persistence: @agent.persistence
    ).materialize(manifest: manifest, manifest_ref: manifest_ref)
    Phronomy::Agent::ExecutionCoordinator::Prepared.new(
      execution: active_execution,
      runtime_projection: projection,
      filtered_input: filtered_input,
      config: effective_config
    )
  rescue => error
    commit_preparation_failure(current_execution, error)
    raise
  end
end

#prepare_next_llm_call(activation) ⇒ Object

Persists facts from the previous Provider/Tool cycle and fixes the next Manifest from the current local Agent state. This runs on OffloadPool.



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/phronomy/agent/execution_coordinator.rb', line 128

def prepare_next_llm_call(activation)
  snapshot = activation.runtime_snapshot
  root = @agent.agent_root
  current = activation.execution
  journal_records = @agent.send(:_journal_records_snapshot)
  manifest = manifest_ref = updated = nil

  @agent.persistence.transaction do |tx|
    assert_local_durable_base!(tx, root)
    encoded_records, call_records = encode_runtime_records(
      activation,
      tx: tx,
      snapshot: snapshot,
      context_candidate: true,
      agent_root: root
    )
    staged = current.with(
      execution_revision: current.execution_revision,
      phase: :preparing_llm_call,
      working_records: current.working_records + encoded_records,
      llm_calls: current.llm_calls + call_records
    )
    invocation_config = activation.invocation&.config || {}
    patch = @agent.send(
      :run_before_llm_input_hooks,
      call_sequence: staged.llm_calls.length + 1,
      config: invocation_config
    )
    manifest, manifest_ref = ContextAssembler.new(
      agent: @agent,
      persistence: tx,
      policy: context_policy_for(staged),
      journal_records: journal_records
    ).build_followup(
      base_manifest: activation.base_manifest,
      agent_root: root,
      execution: staged,
      config: invocation_config,
      patch: patch
    )
    refs = Array(staged.["manifest_refs"]) + [manifest_ref]
    updated = staged.with(
      phase: :calling_llm,
      metadata: staged..merge(
        "manifest_ref" => manifest_ref,
        "manifest_refs" => refs
      )
    )
    tx.executions.save(
      current.execution_id,
      expected_revision: current.execution_revision,
      execution: updated
    )
  end

  activation.replace_execution(updated)
  activation.acknowledge_runtime_snapshot(snapshot)

  projection = RubyLLMMaterializer.new(
    agent: @agent,
    persistence: @agent.persistence
  ).materialize(manifest: manifest, manifest_ref: manifest_ref)
  activation.replace_runtime_projection(projection)
  projection
end

#register(prepared, result_task, mode:, approval_policy:, approval_listener:, on_event:) ⇒ Object



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/phronomy/agent/execution_coordinator.rb', line 397

def register(prepared, result_task, mode:, approval_policy:, approval_listener:, on_event:)
  activation = AgentExecutionActivation.new(
    execution: prepared.execution,
    agent: @agent,
    runtime_projection: prepared.runtime_projection,
    coordinator: self,
    application_listener: on_event
  )
  runtime = Phronomy::Runtime.instance
  runtime.__agent_activations.register(activation)
  event_loop = runtime.event_loop
  effective_config = prepared.config.merge(
    phronomy_activation: activation,
    phronomy_runtime_projection: prepared.runtime_projection,
    phronomy_filtered_input: prepared.filtered_input,
    execution_id: prepared.execution.execution_id
  )
  session = Agent::AgentInvocationSessionBuilder.build(
    agent: @agent,
    input: prepared.filtered_input,
    config: effective_config,
    approval_policy: approval_policy,
    approval_listener: approval_listener,
    mode: mode,
    on_event: ->(event) { activation.record_event(event) },
    runtime: runtime
  )
  activation.invocation = session.context
  activation.session = session
  source_task = Phronomy::Task.deferred(name: "#{result_task.name}-source")
  source_task.on_complete do |invocation, error|
    finish(
      activation,
      result_task,
      invocation || session.context,
      error
    )
  end
  event_loop.register(session, completion: source_task)
rescue => error
  activation ||= AgentExecutionActivation.new(
    execution: prepared.execution,
    agent: @agent,
    runtime_projection: prepared.runtime_projection,
    coordinator: self,
    application_listener: on_event
  )
  finish(activation, result_task, activation.invocation, error)
end

#resume(execution_id, approval_request_id:, approved:, config: {}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/phronomy/agent/execution_coordinator.rb', line 49

def resume(
  execution_id,
  approval_request_id:,
  approved:,
  config: {}
)
  result_task = Phronomy::Task.deferred(
    name: "agent-approval-resume:#{execution_id}"
  )
  runtime = Phronomy::Runtime.instance
  activation = runtime.__agent_activations.fetch(execution_id)
  unless activation
    fail_task(
      result_task,
      Phronomy::ExecutionRehydrationRequiredError.new(
        "no live activation for #{execution_id}; durable rehydration is required"
      )
    )
    return result_task
  end

  unless activation.agent.equal?(@agent) &&
      activation.execution.status == :suspended
    fail_task(
      result_task,
      ArgumentError.new(
        "execution is not a suspended execution of this agent: #{execution_id}"
      )
    )
    return result_task
  end

  preparation = runtime.offload.submit(on_full: :raise) do
    mark_resuming!(
      activation,
      approval_request_id: approval_request_id,
      approved: approved
    )
    activation
  end
  preparation.on_complete do |prepared_activation, error|
    if error
      fail_task(result_task, translated(error))
      next
    end

    begin
      start_resume(
        prepared_activation,
        result_task,
        approved: approved,
        config: config
      )
    rescue => start_error
      commit = runtime.offload.submit(on_full: :raise) do
        commit_failed(
          prepared_activation,
          prepared_activation.invocation,
          start_error
        )
      end
      commit.on_complete do |terminal, commit_error|
        if commit_error
          fail_task(result_task, commit_error)
        else
          runtime.__agent_activations.delete(execution_id)
          fail_task(result_task, terminal.fetch(:error))
        end
      end
    end
  end
  result_task
rescue => error
  fail_task(result_task, translated(error)) if result_task
  result_task
end

#start(input, thread_id: nil, config: {}, mode: :invoke, approval_policy: nil, approval_listener: nil, on_event: nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/phronomy/agent/execution_coordinator.rb', line 16

def start(
  input, thread_id: nil, config: {}, mode: :invoke,
  approval_policy: nil, approval_listener: nil, on_event: nil
)
  result_task = Phronomy::Task.deferred(name: "agent-#{@agent.agent_id}-#{mode}")
  runtime = Phronomy::Runtime.instance
  preparation = runtime.offload.submit(on_full: :raise) do
    prepare(input, thread_id: thread_id, config: config)
  end
  preparation.on_complete do |prepared, error|
    if error
      post_prep_failure(runtime, on_event, result_task, translated(error))
    else
      register(
        prepared,
        result_task,
        mode: mode,
        approval_policy: approval_policy,
        approval_listener: approval_listener,
        on_event: on_event
      )
    end
  end
  result_task
rescue => error
  if defined?(runtime) && runtime
    post_prep_failure(runtime, on_event, result_task, translated(error))
  else
    fail_task(result_task, translated(error))
  end
  result_task
end