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



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
290
291
292
293
294
295
296
297
# File 'lib/phronomy/agent/execution_coordinator.rb', line 254

def admit_execution(raw_message, thread_id:)
  execution = nil
  root = nil
  @agent.persistence.transaction do |tx|
    root = tx.agents.load(@agent.agent_id)
    raise Phronomy::Error, "agent is closed: #{@agent.agent_id}" if root.lifecycle_status == :closed
    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)
    root = next_root
  end
  [execution, root]
end

#commit_preparation_failure(execution, error) ⇒ Object



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
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/phronomy/agent/execution_coordinator.rb', line 299

def commit_preparation_failure(execution, error)
  translated_error = translated(error)
  root = nil
  @agent.persistence.transaction do |tx|
    current = tx.executions.load(execution.execution_id)
    root = tx.agents.load(@agent.agent_id)
    error_ref = tx.contents.put_json(
      "class" => translated_error.class.name,
      "message" => translated_error.message
    )
    audit_records = current.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: current.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 = current.with(
      status: terminal_status,
      phase: terminal_status,
      working_records: [],
      error_ref: error_ref,
      terminal_reason: translated_error.class.name
    )
    tx.executions.save(
      current.execution_id,
      expected_revision: current.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)
    root = next_root
  end
  @agent.__replace_root(root)
end

#deliver_on_event_loop(command) ⇒ Object



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/phronomy/agent/execution_coordinator.rb', line 422

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



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/phronomy/agent/execution_coordinator.rb', line 398

def finish(activation, result_task, invocation, error)
  runtime = Phronomy::Runtime.instance
  operation = runtime.blocking_io.submit 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}
      )
    )
    settle_without_listener(activation, result_task, outcome, commit_error) unless posted
  end
rescue => caught
  fail_task(result_task, translated(caught))
end

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



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
193
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
# File 'lib/phronomy/agent/execution_coordinator.rb', line 161

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)

  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 = nil
    manifest_ref = nil
    active_execution = nil

    @agent.persistence.transaction do |tx|
      root = tx.agents.load(@agent.agent_id)
      current = tx.executions.load(execution.execution_id)
      filtered_ref = tx.contents.put_text(filtered_message)
      input_record = JournalRecord.new(
        agent_id: @agent.agent_id,
        execution_id: current.execution_id,
        kind: :external_message,
        channel: :external,
        role: :user,
        content_ref: filtered_ref,
        correlation_id: thread_id,
        context_generation: root.transcript_generation,
        context_candidate: true
      )
      staged = current.with(
        execution_revision: current.execution_revision,
        working_records: current.working_records + [input_record],
        metadata: current..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)
      ).build_initial(
        input: filtered_input,
        agent_root: 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_id,
        expected_revision: current.execution_revision,
        execution: active_execution
      )
    end

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

#prepare_next_llm_call(activation) ⇒ Object

Persists all Runtime events from the previous call, fixes the next Canonical LLM Input Manifest, and materializes the next Runtime Projection. This method is executed on the blocking adapter pool, never on EventLoop.



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
# File 'lib/phronomy/agent/execution_coordinator.rb', line 111

def prepare_next_llm_call(activation)
  snapshot = activation.runtime_snapshot
  manifest = manifest_ref = updated = root = nil

  @agent.persistence.transaction do |tx|
    root = tx.agents.load(@agent.agent_id)
    current = tx.executions.load(activation.execution_id)
    encoded_records, call_records = encode_runtime_records(
      activation, tx: tx, snapshot: snapshot, context_candidate: true
    )
    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)
    ).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



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
396
# File 'lib/phronomy/agent/execution_coordinator.rb', line 350

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
  )
  @agent.persistence.activations.register(activation)
  runtime = Phronomy::Runtime.instance
  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



45
46
47
48
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
# File 'lib/phronomy/agent/execution_coordinator.rb', line 45

def resume(
  execution_id,
  approval_request_id:,
  approved:,
  config: {}
)
  result_task = Phronomy::Task.deferred(
    name: "agent-approval-resume:#{execution_id}"
  )
  runtime = Phronomy::Runtime.instance
  preparation = runtime.blocking_io.submit do
    execution = @agent.persistence.executions.load(execution_id)
    unless execution.agent_id == @agent.agent_id && execution.status == :suspended
      raise ArgumentError,
        "execution is not a suspended execution of this agent: #{execution_id}"
    end

    activation = @agent.persistence.activations.fetch(execution_id)
    unless activation
      raise Phronomy::ExecutionRehydrationRequiredError,
        "no live activation for #{execution_id}; durable rehydration is required"
    end

    mark_resuming!(
      execution_id,
      approval_request_id: approval_request_id,
      approved: approved
    )
    activation
  end
  preparation.on_complete do |activation, error|
    if error
      fail_task(result_task, translated(error))
      next
    end

    begin
      start_resume(
        activation,
        result_task,
        approved: approved,
        config: config
      )
    rescue => start_error
      commit = runtime.blocking_io.submit do
        commit_failed(activation, activation.invocation, start_error)
      end
      commit.on_complete do |terminal, commit_error|
        if commit_error
          fail_task(result_task, commit_error)
        else
          @agent.persistence.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))
  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
# 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.blocking_io.submit 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