@rowan-agent/agent 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +52 -759
  2. package/dist/index.d.ts +1302 -1283
  3. package/dist/index.js +4602 -5844
  4. package/package.json +2 -2
package/dist/index.d.ts CHANGED
@@ -1,252 +1,54 @@
1
- import * as _rowan_agent_models from '@rowan-agent/models';
2
- import { LlmRequest, LlmResponse, ModelRef, LlmModelUsage, Outcome, AgentMessage, ToolResult, StreamFn, AgentEventListener, ToolCall, Skill as Skill$1, ContentBlock, ModelConfig } from '@rowan-agent/models';
3
- export { AgentEvent, AgentEventListener, AgentMessage, ModelConfig, ModelRef, Outcome, Skill, StreamFn, ToolResult } from '@rowan-agent/models';
4
1
  import Type from 'typebox';
2
+ import * as _rowan_agent_models from '@rowan-agent/models';
3
+ import { LlmContentPart, ContentBlock, ModelRef, ModelConfig, StreamFn } from '@rowan-agent/models';
4
+ export { ModelConfig, ModelRef, StreamFn } from '@rowan-agent/models';
5
5
 
6
- type ExecutionTurn = {
6
+ type AgentMessage = {
7
7
  id: string;
8
- sessionId: string;
9
- parentSessionId?: string;
10
- phase: string;
11
- requestedAtMs: number;
12
- completedAtMs: number;
13
- model: ModelRef;
14
- usage?: LlmModelUsage;
15
- };
16
- /** Raw model input/output for session persistence. */
17
- type ModelTranscript = {
18
- request: LlmRequest;
19
- response: LlmResponse;
20
- };
21
-
22
- declare const opaqueIdBrand: unique symbol;
23
- type OpaqueId<Kind extends string> = string & {
24
- readonly [opaqueIdBrand]: Kind;
25
- };
26
- type AgentId = OpaqueId<"AgentId">;
27
- type AgentRunId = OpaqueId<"AgentRunId">;
28
- type RuntimeMessageId = OpaqueId<"RuntimeMessageId">;
29
- type RuntimeEventId = OpaqueId<"RuntimeEventId">;
30
- type LeaseId = OpaqueId<"LeaseId">;
31
- type RuntimeToolCallId = OpaqueId<"RuntimeToolCallId">;
32
- type AgentLifecycleState = "active" | "paused";
33
- type SessionLifecycleState = "active" | "archived" | "deleting";
34
- type RuntimeMessageState = "queued" | "leased" | "acknowledged" | "dead_lettered";
35
- type AgentRunState = "queued" | "running" | "suspended" | "completed" | "failed" | "cancelled";
36
- /** Opaque execution checkpoint owned by the Agent loop and persisted by Runtime. */
37
- type AgentRunExecutionState = Readonly<Record<string, unknown>>;
38
- /** Host-owned correlation data persisted with a Run and echoed by Runtime Events. */
39
- type AgentRunMetadata = Readonly<Record<string, unknown>>;
40
- type AgentInputRequest = {
41
- phase: string;
42
- prompt: string;
43
- requestedAt: string;
44
- };
45
- type RuntimeToolCallState = "queued" | "running" | "completed" | "failed" | "indeterminate";
46
- type AgentRecord = {
47
- id: AgentId;
48
- sessionId: string;
49
- state: AgentLifecycleState;
50
- lifecycleState: SessionLifecycleState;
51
- parentSessionId?: string;
52
- createdAt: string;
53
- updatedAt: string;
54
- };
55
- type RuntimeLease = {
56
- id: LeaseId;
57
- runId: AgentRunId;
58
- workerId: string;
59
- leasedAt: string;
60
- expiresAt: string;
61
- };
62
- type RuntimeMessage = {
63
- id: RuntimeMessageId;
64
- agentId: AgentId;
65
- kind: "agent_input";
66
- input: AgentMessage;
67
- state: RuntimeMessageState;
68
- attempts: number;
69
- runId?: AgentRunId;
70
- lease?: RuntimeLease;
71
- deadLetterReason?: string;
8
+ role: "system" | "user" | "assistant" | "tool";
9
+ content: string | LlmContentPart[];
72
10
  createdAt: string;
73
- updatedAt: string;
11
+ metadata?: Record<string, unknown> & {
12
+ phase?: string;
13
+ };
74
14
  };
75
- type AgentRunRecord = {
76
- id: AgentRunId;
77
- agentId: AgentId;
78
- messageId: RuntimeMessageId;
79
- state: AgentRunState;
80
- attempt: number;
81
- leaseId?: LeaseId;
82
- outcome?: Outcome;
83
- suspensionReason?: string;
84
- inputRequest?: AgentInputRequest;
85
- executionState?: AgentRunExecutionState;
86
- metadata?: AgentRunMetadata;
87
- createdAt: string;
88
- updatedAt: string;
15
+ type Skill = {
16
+ name: string;
17
+ description: string;
18
+ /** Absolute path to the SKILL.md file */
19
+ filePath: string;
20
+ /** Directory containing the SKILL.md file */
21
+ baseDir: string;
22
+ /** Full body content of the SKILL.md (after frontmatter) */
23
+ content: string;
24
+ disableModelInvocation: boolean;
89
25
  };
90
- type RuntimeEventKind = "agent_created" | "agent_paused" | "agent_resumed" | "session_archived" | "session_unarchived" | "message_enqueued" | "run_enqueued" | "run_leased" | "lease_expired" | "lease_recovered" | "run_suspended" | "run_retry_scheduled" | "run_completed" | "run_aborted" | "message_acknowledged" | "message_dead_lettered" | "tool_call_created" | "tool_call_started" | "tool_call_failed" | "tool_call_completed" | "tool_call_indeterminate";
91
- type RuntimeEvent = {
92
- id: RuntimeEventId;
93
- sequence: number;
94
- kind: RuntimeEventKind;
95
- agentId?: AgentId;
96
- messageId?: RuntimeMessageId;
97
- runId?: AgentRunId;
98
- toolCallId?: RuntimeToolCallId;
26
+ type Outcome$1 = {
27
+ id: string;
28
+ message: string;
29
+ /** Publish this outcome's message as an assistant message before completing the run. */
30
+ display?: boolean;
99
31
  payload?: unknown;
100
- createdAt: string;
101
- };
102
- type RuntimeEventCursor = {
103
- after?: RuntimeEventId;
104
- limit?: number;
105
- };
106
- type RuntimeEventCheckpoint = {
107
- consumerId: string;
108
- sequence: number;
109
- eventId?: RuntimeEventId;
110
- updatedAt: string;
32
+ toolResults?: Array<{
33
+ toolCallId: string;
34
+ toolName: string;
35
+ ok: boolean;
36
+ content: unknown;
37
+ error?: string;
38
+ }>;
111
39
  };
112
- type RuntimeToolCall = {
113
- id: RuntimeToolCallId;
114
- agentId: AgentId;
115
- runId: AgentRunId;
40
+ type ToolCall = {
41
+ id: string;
116
42
  name: string;
117
43
  args: unknown;
118
- state: RuntimeToolCallState;
119
- result?: ToolResult;
120
- indeterminateReason?: string;
121
- createdAt: string;
122
- updatedAt: string;
123
- };
124
-
125
- type BeforePhaseHook = (phaseId: string, input: PhaseContext) => Promise<BeforePhaseHookResult>;
126
- type AfterPhaseHook = (phaseId: string, output: PhaseOutput) => Promise<AfterPhaseHookResult>;
127
- type BeforePromptHook = (phaseId: string, input: PhaseContext) => Promise<PhaseContext>;
128
- type LoopMetrics = {
129
- /** Number of phase iterations executed. */
130
- iterations: number;
131
- /** Phase transition history. */
132
- phaseTransitions: Array<{
133
- from: string;
134
- to: string;
135
- ts: string;
136
- }>;
137
- /** Number of times compaction was triggered. */
138
- compactionCount: number;
139
- /** Number of retry attempts due to transient errors. */
140
- retryCount: number;
141
- /** Loop start timestamp. */
142
- startedAt: string;
143
- /** Loop start time as epoch ms (for duration calculation). */
144
- startedAtMs: number;
145
- /** Loop end timestamp (set on completion). */
146
- endedAt?: string;
147
- /** Total wall-clock duration in ms. */
148
- durationMs?: number;
149
- };
150
- type SessionState = {
151
- currentPhase: string;
152
- attempt: number;
153
- metrics: LoopMetrics;
154
- status: "idle" | "running" | "suspended" | "completed" | "aborted" | "failed";
155
- continuation?: SessionContinuationState;
156
- };
157
- type SessionContinuationState = {
158
- isContinuing: boolean;
159
- previousPayload?: unknown;
160
- previousResults: Array<{
161
- name: string;
162
- output?: unknown;
163
- }>;
164
- pendingInstruction?: string;
165
- previousPhaseMessageId?: string;
166
- };
167
- type AgentConfig = {
168
- model: ModelRef;
169
- stream: StreamFn;
170
- context: AgentContext;
171
- sessionId?: string;
172
- sessionState?: SessionState;
173
- maxAttempts?: number;
174
- runtime?: AgentRuntimePort;
175
- emit?: AgentEventListener;
176
- signal?: AbortSignal;
177
- beforeToolCall?: BeforeToolCall;
178
- afterToolCall?: AfterToolCall;
179
- beforePhase?: BeforePhaseHook;
180
- afterPhase?: AfterPhaseHook;
181
- beforePrompt?: BeforePromptHook;
182
- onModelTranscript?: (transcript: ModelTranscript, meta: {
183
- phase: string;
184
- model: ModelRef;
185
- }) => Promise<void>;
186
- onMessage?: (message: AgentMessage) => Promise<void>;
187
- onOutcome?: (outcome: Outcome) => Promise<void>;
188
- /** Internal: await next user messages before retrying the same phase. */
189
- waitForInput?: (state?: SessionState, inputRequest?: AgentInputRequest) => Promise<AgentMessage[]>;
190
- };
191
- type ToolRunnerInput = {
192
- config: AgentConfig;
193
- toolCall: ToolCall;
194
- };
195
- type ToolRunner = (input: ToolRunnerInput) => Promise<ToolResult>;
196
- type AgentRuntimePort = {
197
- tools?: ToolRunner;
198
44
  };
199
-
200
- type ToolContext = Pick<AgentContext, "skills"> & {
45
+ type ToolResult = {
201
46
  toolCallId: string;
47
+ toolName: string;
48
+ ok: boolean;
49
+ content: unknown;
50
+ error?: string;
202
51
  };
203
- type ToolExecutionMode = "sequential" | "parallel";
204
- type Tool<TArgs = unknown> = {
205
- name: string;
206
- description: string;
207
- parameters: Type.TSchema;
208
- /** One-line snippet shown in the system prompt tool list. */
209
- promptSnippet?: string;
210
- /** Additional guidelines appended to the system prompt when this tool is active. */
211
- promptGuidelines?: string[];
212
- /** Whether this tool can run concurrently with others. Default: "parallel". */
213
- executionMode?: ToolExecutionMode;
214
- execute(args: TArgs, context: ToolContext, signal?: AbortSignal): Promise<ToolResult>;
215
- };
216
- /** Context snapshot passed into the low-level agent loop. */
217
- type AgentContext = {
218
- /** System prompt included with the request. */
219
- systemPrompt: string;
220
- /** Transcript visible to the model. */
221
- messages: AgentMessage[];
222
- /** Tools available for this run. */
223
- tools: Tool[];
224
- /** Skills available for this run. */
225
- skills: Skill$1[];
226
- /** Custom phases for this run. Agent normalizes this with the built-in default phase. */
227
- phases?: PhaseRegistry;
228
- };
229
- type BeforeToolCall = (input: {
230
- tool: Tool;
231
- args: unknown;
232
- }) => Promise<{
233
- allow: true;
234
- } | {
235
- allow: false;
236
- reason: string;
237
- }>;
238
- type AfterToolCall = (input: {
239
- tool: Tool;
240
- result: ToolResult;
241
- }) => Promise<ToolResult>;
242
- type RunResult = {
243
- sessionId: string;
244
- messages: AgentMessage[];
245
- outcome: Outcome;
246
- metrics: LoopMetrics;
247
- };
248
- type Unsubscribe = () => void;
249
- declare function createMessage(role: AgentMessage["role"], content: AgentMessage["content"], metadata?: Record<string, unknown>): AgentMessage;
250
52
 
251
53
  type ModelInvokeOutput = {
252
54
  text: string;
@@ -271,100 +73,6 @@ type PhaseExecution = {
271
73
  executeTool(context: AgentContext, toolCall: ToolCall): Promise<ToolResult>;
272
74
  };
273
75
 
274
- /** Unified phase output — model decides routing via route. */
275
- type PhaseOutput = {
276
- message: string;
277
- /** Route to next phase, or "continue" to re-execute current phase, or "stop" to end */
278
- route: string;
279
- /** Phase name that produced this output */
280
- phase?: string;
281
- /** Tool calls from the model invocation (used by framework for route extraction) */
282
- toolCalls?: Array<{
283
- id: string;
284
- name: string;
285
- args: unknown;
286
- }>;
287
- /** Route reason extracted from route tool call (for hooks to inspect) */
288
- routeReason?: string;
289
- /** Structured data from this phase, passed to the next phase */
290
- payload?: unknown;
291
- };
292
- /** Phase machine state — tracks position and inter-phase data */
293
- interface PhaseState {
294
- current: string;
295
- available: string[];
296
- iterations: number;
297
- payload?: unknown;
298
- }
299
- type PhaseInvocation = {
300
- mode: "serial";
301
- instanceId: string;
302
- } | {
303
- mode: "parallel";
304
- instanceId: string;
305
- groupId: string;
306
- index: number;
307
- count: number;
308
- sourcePhaseId: string;
309
- };
310
- /** Everything a phase needs to execute */
311
- interface PhaseContext {
312
- systemPrompt: string;
313
- messages: AgentMessage[];
314
- /** Phase-filtered tools */
315
- tools: Tool[];
316
- /** Phase-filtered skills */
317
- skills: Skill$1[];
318
- /** Phase machine state */
319
- state: PhaseState;
320
- /** Identity and dispatch metadata for this phase execution */
321
- readonly invocation: PhaseInvocation;
322
- /** Additional guideline bullets appended to the system prompt */
323
- promptGuidelines?: string[];
324
- /** Text to append after the system prompt */
325
- appendSystemPrompt?: string;
326
- }
327
- /**
328
- * Loaded Phase object
329
- */
330
- interface Phase {
331
- /** Unique phase identity and display name. */
332
- name: string;
333
- /** Description */
334
- description: string;
335
- /** Restricted tools (undefined = all tools available) */
336
- tools?: string[];
337
- /** Restricted skills (undefined = all skills available) */
338
- skills?: string[];
339
- /** Forced next phase */
340
- target?: string;
341
- /** Expected input fields (key → description) */
342
- input?: Record<string, string>;
343
- /** If true, phase gets a fresh context when executed in parallel */
344
- isolated?: boolean;
345
- /** Path to PHASE.md file */
346
- filePath: string;
347
- /** Phase directory path */
348
- baseDir: string;
349
- /** PHASE.md body content */
350
- content: string;
351
- /** Model override for this phase (resolved from frontmatter) */
352
- model?: ModelRef;
353
- /** ExtensionAPI factory function (default export pattern) */
354
- factory?: (api: ExtensionAPI) => Promise<void>;
355
- /** Direct run function */
356
- run?: (context: PhaseContext, execution: PhaseExecution) => Promise<PhaseOutput | void>;
357
- }
358
- /**
359
- * Phase registry containing all loaded phases
360
- */
361
- interface PhaseRegistry {
362
- /** Map of phase name to Phase object */
363
- phases: Map<string, Phase>;
364
- /** Entry phase name (null until Agent applies its default phase) */
365
- entryPhaseId: string | null;
366
- }
367
-
368
76
  /**
369
77
  * Extension types — simplified for the new hook-based system.
370
78
  */
@@ -409,14 +117,14 @@ interface ToolDefinition {
409
117
  /** Parameter schema (JSON Schema) */
410
118
  parameters: Record<string, unknown>;
411
119
  /** Execute the tool */
412
- execute: (args: unknown, signal?: AbortSignal) => Promise<ToolExecutionResult>;
120
+ execute: (args: unknown, signal?: AbortSignal) => Promise<ToolExecutionResult$1>;
413
121
  /** Optional: per-tool execution mode override */
414
122
  executionMode?: "sequential" | "parallel";
415
123
  }
416
124
  /**
417
125
  * Result from tool execution.
418
126
  */
419
- interface ToolExecutionResult {
127
+ interface ToolExecutionResult$1 {
420
128
  /** Content blocks to return to the LLM */
421
129
  content: Array<{
422
130
  type: string;
@@ -441,19 +149,6 @@ type ExecResult = {
441
149
  stdout: string;
442
150
  stderr: string;
443
151
  };
444
- type BeforePhaseHookResult = {
445
- abort?: Outcome;
446
- skip?: {
447
- route: string;
448
- message: string;
449
- };
450
- input?: PhaseContext;
451
- };
452
- type AfterPhaseHookResult = {
453
- abort?: Outcome;
454
- retry?: PhaseContext;
455
- output?: PhaseOutput;
456
- };
457
152
  /**
458
153
  * Result of loading extensions from filesystem.
459
154
  * The runner takes these and creates Extension tracking objects.
@@ -518,376 +213,63 @@ interface EventBus {
518
213
  count(event: string): number;
519
214
  }
520
215
 
521
- /**
522
- * @module extensions/hooks
523
- *
524
- * Type-safe hook system
525
- *
526
- * ## Overview
527
- *
528
- * The hook system allows extensions to intercept and modify Agent behavior at specific points.
529
- *
530
- * ## Hook Categories
531
- *
532
- * ### Modifiable (return result to change behavior)
533
- *
534
- * | Hook | Return | Effect |
535
- * |------|--------|--------|
536
- * | `before_phase` | `{ abort?, skip?, input? }` | Abort, skip, or modify phase input |
537
- * | `after_phase` | `{ abort?, retry?, output? }` | Abort, retry, or replace phase output |
538
- * | `before_prompt` | `{ input? }` | Modify input sent to LLM |
539
- * | `before_tool_call` | `{ allow, reason? }` | Allow/block tool execution |
540
- * | `after_tool_call` | `{ result? }` | Modify tool execution result |
541
- *
542
- * ### Listen-only (return void)
543
- *
544
- * | Hook | Trigger |
545
- * |------|---------|
546
- * | `agent_start` | Agent starts |
547
- * | `agent_end` | Agent ends |
548
- * | `turn_start` | Conversation turn starts |
549
- * | `turn_end` | Conversation turn ends |
550
- * | `message_start` | Message streaming starts |
551
- * | `message_update` | Message streaming update |
552
- * | `message_end` | Message completes |
553
- * | `tool_execution_start` | Tool execution starts |
554
- * | `tool_execution_update` | Tool execution progress update |
555
- * | `tool_execution_end` | Tool execution completes |
556
- * | `queue_update` | Queue state update |
557
- * | `save_point` | Session save point |
558
- * | `abort` | Agent aborted |
559
- * | `settled` | Agent idle |
560
- *
561
- * ## Usage Example
562
- *
563
- * ```typescript
564
- * import type { ExtensionAPI } from "@rowan-agent/agent";
565
- *
566
- * export default function(api: ExtensionAPI) {
567
- * // Block dangerous tools
568
- * api.on("before_tool_call", (event) => {
569
- * if (event.tool.name === "bash") {
570
- * const cmd = (event.args as any).command;
571
- * if (cmd.includes("rm -rf")) {
572
- * return { allow: false, reason: "Dangerous command" };
573
- * }
574
- * }
575
- * return { allow: true };
576
- * });
577
- *
578
- * // Inject context
579
- * api.on("before_prompt", (event) => {
580
- * return {
581
- * input: {
582
- * ...event.input,
583
- * systemPrompt: event.input.systemPrompt + "\n\nExtra context",
584
- * },
585
- * };
586
- * });
587
- *
588
- * // Log tool calls
589
- * api.on("tool_execution_end", (event) => {
590
- * console.log(`Tool ${event.toolName}: ${event.result.ok ? "success" : "failed"}`);
591
- * });
592
- * }
593
- * ```
594
- */
595
-
596
- /**
597
- * before_phase event - triggered before phase execution
598
- *
599
- * Return `{ abort }` to abort the agent.
600
- * Return `{ skip: { route, message } }` to skip the phase.
601
- * Return `{ input }` to replace the phase input.
602
- */
603
216
  interface BeforePhaseEvent {
604
217
  type: "before_phase";
605
- /** Phase name about to execute */
606
218
  phaseId: string;
607
- /** Phase input */
608
219
  input: PhaseContext;
609
220
  }
610
- /**
611
- * after_phase event - triggered after phase execution
612
- *
613
- * Return `{ abort }` to abort the agent.
614
- * Return `{ retry }` to re-execute the phase with new input.
615
- * Return `{ output }` to replace the phase output.
616
- */
617
221
  interface AfterPhaseEvent {
618
222
  type: "after_phase";
619
- /** Phase name that completed */
620
223
  phaseId: string;
621
- /** Phase output */
622
224
  output: PhaseOutput;
623
225
  }
624
- /**
625
- * before_prompt event - triggered before building LLM request
626
- *
627
- * Return `{ input }` to replace the input sent to LLM.
628
- */
629
226
  interface BeforePromptEvent {
630
227
  type: "before_prompt";
631
- /** Current phase name */
632
228
  phaseId: string;
633
- /** Phase input (modifiable) */
634
229
  input: PhaseContext;
635
230
  }
636
- /**
637
- * before_tool_call event - triggered before tool execution
638
- *
639
- * Return `{ allow: false, reason }` to block execution.
640
- * Return `{ allow: true }` to allow execution.
641
- */
642
231
  interface BeforeToolCallEvent {
643
232
  type: "before_tool_call";
644
- /** Tool definition */
645
- tool: Tool;
646
- /** Tool arguments */
233
+ tool: Tool$1;
647
234
  args: unknown;
648
235
  }
649
- /**
650
- * after_tool_call event - triggered after tool execution
651
- *
652
- * Return `{ result }` to replace the tool execution result.
653
- */
654
236
  interface AfterToolCallEvent {
655
237
  type: "after_tool_call";
656
- /** Tool definition */
657
- tool: Tool;
658
- /** Tool execution result */
238
+ tool: Tool$1;
659
239
  result: ToolResult;
660
240
  }
661
- /**
662
- * agent_start event - triggered when agent starts
663
- */
664
- interface AgentStartEvent {
665
- type: "agent_start";
666
- /** Session ID */
667
- sessionId: string;
241
+ type HookEvent = BeforePhaseEvent | AfterPhaseEvent | BeforePromptEvent | BeforeToolCallEvent | AfterToolCallEvent;
242
+ interface BeforePhaseResult {
243
+ abort?: Outcome$1;
244
+ skip?: {
245
+ route: string;
246
+ message: string;
247
+ };
248
+ input?: PhaseContext;
668
249
  }
669
- /**
670
- * agent_end event - triggered when agent ends
671
- */
672
- interface AgentEndEvent {
673
- type: "agent_end";
674
- /** Session ID */
675
- sessionId: string;
676
- /** Execution outcome */
677
- outcome: Outcome;
678
- /** All messages */
679
- messages: AgentMessage[];
250
+ interface AfterPhaseResult {
251
+ abort?: Outcome$1;
252
+ retry?: PhaseContext;
253
+ output?: PhaseOutput;
680
254
  }
681
- /**
682
- * turn_start event - triggered when conversation turn starts
683
- */
684
- interface TurnStartEvent {
685
- type: "turn_start";
686
- /** Current message list */
687
- messages: AgentMessage[];
688
- }
689
- /**
690
- * turn_end event - triggered when conversation turn ends
691
- */
692
- interface TurnEndEvent {
693
- type: "turn_end";
694
- /** Message list */
695
- messages: AgentMessage[];
696
- /** Turn outcome (optional) */
697
- outcome?: Outcome;
698
- }
699
- /**
700
- * message_start event - triggered when message streaming starts
701
- */
702
- interface MessageStartEvent {
703
- type: "message_start";
704
- /** Message object */
705
- message: AgentMessage;
706
- }
707
- /**
708
- * message_update event - triggered on message streaming update
709
- */
710
- interface MessageUpdateEvent {
711
- type: "message_update";
712
- /** Message object */
713
- message: AgentMessage;
714
- /** Delta text */
715
- delta: string;
716
- }
717
- /**
718
- * message_end event - triggered when message completes
719
- */
720
- interface MessageEndEvent {
721
- type: "message_end";
722
- /** Message object */
723
- message: AgentMessage;
724
- }
725
- /**
726
- * tool_execution_start event - triggered when tool execution starts
727
- */
728
- interface ToolExecutionStartEvent {
729
- type: "tool_execution_start";
730
- /** Tool call ID */
731
- toolCallId: string;
732
- /** Tool name */
733
- toolName: string;
734
- /** Tool arguments */
735
- args: unknown;
736
- }
737
- /**
738
- * tool_execution_update event - triggered on tool execution progress
739
- */
740
- interface ToolExecutionUpdateEvent {
741
- type: "tool_execution_update";
742
- /** Tool call ID */
743
- toolCallId: string;
744
- /** Tool name */
745
- toolName: string;
746
- }
747
- /**
748
- * tool_execution_end event - triggered when tool execution completes
749
- */
750
- interface ToolExecutionEndEvent {
751
- type: "tool_execution_end";
752
- /** Tool call ID */
753
- toolCallId: string;
754
- /** Tool name */
755
- toolName: string;
756
- /** Tool execution result */
757
- result: ToolResult;
758
- }
759
- /**
760
- * queue_update event - triggered on queue state update
761
- */
762
- interface QueueUpdateEvent {
763
- type: "queue_update";
764
- /** Pending message count */
765
- pendingCount: number;
766
- }
767
- /**
768
- * save_point event - triggered at session save point
769
- */
770
- interface SavePointEvent {
771
- type: "save_point";
772
- /** Whether there are pending mutations */
773
- hadPendingMutations: boolean;
774
- }
775
- /**
776
- * abort event - triggered when agent is aborted
777
- */
778
- interface AbortEvent {
779
- type: "abort";
780
- /** Abort reason */
781
- reason?: string;
782
- }
783
- /**
784
- * settled event - triggered when agent is idle
785
- */
786
- interface SettledEvent {
787
- type: "settled";
788
- }
789
- /** Union type of all hook events */
790
- type HookEvent = BeforePhaseEvent | AfterPhaseEvent | BeforePromptEvent | BeforeToolCallEvent | AfterToolCallEvent | AgentStartEvent | AgentEndEvent | TurnStartEvent | TurnEndEvent | MessageStartEvent | MessageUpdateEvent | MessageEndEvent | ToolExecutionStartEvent | ToolExecutionUpdateEvent | ToolExecutionEndEvent | QueueUpdateEvent | SavePointEvent | AbortEvent | SettledEvent;
791
- /**
792
- * before_phase hook return value
793
- *
794
- * - `abort`: Abort the entire agent
795
- * - `skip`: Skip current phase, route to specified phase
796
- * - `input`: Replace phase input
797
- */
798
- interface BeforePhaseResult {
799
- /** Abort agent */
800
- abort?: Outcome;
801
- /** Skip current phase */
802
- skip?: {
803
- route: string;
804
- message: string;
805
- };
806
- /** Replace phase input */
807
- input?: PhaseContext;
808
- }
809
- /**
810
- * after_phase hook return value
811
- *
812
- * - `abort`: Abort the entire agent
813
- * - `retry`: Re-execute phase with new input
814
- * - `output`: Replace phase output
815
- */
816
- interface AfterPhaseResult {
817
- /** Abort agent */
818
- abort?: Outcome;
819
- /** Re-execute phase */
820
- retry?: PhaseContext;
821
- /** Replace phase output */
822
- output?: PhaseOutput;
823
- }
824
- /**
825
- * before_prompt hook return value
826
- *
827
- * - `input`: Replace input sent to LLM
828
- */
829
255
  interface BeforePromptResult {
830
- /** Replace phase input */
831
256
  input?: PhaseContext;
832
257
  }
833
- /**
834
- * before_tool_call hook return value
835
- *
836
- * - `allow`: Whether to allow execution
837
- * - `reason`: Rejection reason (when allow=false)
838
- */
839
258
  interface BeforeToolCallResult {
840
- /** Whether to allow execution */
841
259
  allow: boolean;
842
- /** Rejection reason */
843
260
  reason?: string;
844
261
  }
845
- /**
846
- * after_tool_call hook return value
847
- *
848
- * - `result`: Replace tool execution result
849
- */
850
262
  interface AfterToolCallResult {
851
- /** Replace tool execution result */
852
263
  result?: ToolResult;
853
264
  }
854
- /**
855
- * Hook result mapping table.
856
- *
857
- * Defines the return type for each hook event:
858
- * - Modifiable hooks return specific objects
859
- * - Listen-only hooks return undefined
860
- */
861
265
  interface HookResultMap {
862
266
  before_phase: BeforePhaseResult | undefined;
863
267
  after_phase: AfterPhaseResult | undefined;
864
268
  before_prompt: BeforePromptResult | undefined;
865
269
  before_tool_call: BeforeToolCallResult | undefined;
866
270
  after_tool_call: AfterToolCallResult | undefined;
867
- agent_start: undefined;
868
- agent_end: undefined;
869
- turn_start: undefined;
870
- turn_end: undefined;
871
- message_start: undefined;
872
- message_update: undefined;
873
- message_end: undefined;
874
- tool_execution_start: undefined;
875
- tool_execution_update: undefined;
876
- tool_execution_end: undefined;
877
- queue_update: undefined;
878
- save_point: undefined;
879
- abort: undefined;
880
- settled: undefined;
881
271
  }
882
- /** Hook event type string */
883
272
  type HookEventType = HookEvent["type"];
884
- /**
885
- * Hook handler type.
886
- *
887
- * @typeParam K - Hook event type
888
- * @param event - Event object
889
- * @returns Result object or void
890
- */
891
273
  type HookHandler<K extends HookEventType> = (event: Extract<HookEvent, {
892
274
  type: K;
893
275
  }>) => HookResultMap[K] | Promise<HookResultMap[K]> | void | Promise<void>;
@@ -1019,11 +401,6 @@ interface ExtensionAPI {
1019
401
  context: ExtensionContext;
1020
402
  /** Shared event bus for inter-extension communication. */
1021
403
  events: EventBus;
1022
- /** Session context — provides access to the session-level AgentContext. */
1023
- session: {
1024
- /** Get the current session AgentContext */
1025
- getContext(): AgentContext;
1026
- };
1027
404
  /** Phase execution capabilities — rovides Phase In/Out, phase identity, and phase routing. */
1028
405
  phase: {
1029
406
  /** Phase In: get payload from previous phase */
@@ -1048,657 +425,1299 @@ interface ExtensionAPI {
1048
425
  */
1049
426
  type ExtensionFactory = (api: ExtensionAPI) => void | Promise<void>;
1050
427
 
1051
- /**
1052
- * Load all phases from the target directory.
1053
- *
1054
- * Scans for subdirectories containing PHASE.md files.
1055
- * Returns PhaseRegistry with entryPhaseId:
1056
- * - null by default (caller must explicitly set to start from a specific phase)
1057
- * - Set to a specific phase name to start from that phase
1058
- *
1059
- * When entryPhaseId is null, Agent normalizes the registry to start from its default phase.
1060
- */
1061
- declare function loadPhases(targetPath: string): Promise<PhaseRegistry>;
1062
-
1063
- type AgentExecutionOptions = StreamAgentOptions & {
1064
- sessionId?: string;
1065
- agentId?: AgentId;
1066
- sessionState?: SessionState;
1067
- onInput?: (message: AgentMessage) => Promise<void>;
1068
- runtime?: AgentRuntimePort;
1069
- };
1070
- type RunOptions = Partial<AgentExecutionOptions>;
1071
- type RuntimeRunHooks = {
1072
- onSuspend?: (reason?: string, state?: SessionState, inputRequest?: AgentInputRequest) => Promise<void> | void;
1073
- };
1074
- type AgentStatus = {
1075
- agentId?: AgentId;
1076
- sessionId?: string;
1077
- context: AgentContext;
1078
- model: ModelRef;
1079
- tools: Tool[];
1080
- initialized: boolean;
1081
- running: boolean;
1082
- currentResult?: RunResult;
1083
- error?: string;
428
+ /** Unified phase output — model decides routing via route. */
429
+ type PhaseOutput = {
430
+ message: string;
431
+ /** Route to next phase, or "continue" to re-execute current phase, or "stop" to end */
432
+ route: string;
433
+ /** Phase name that produced this output */
434
+ phase?: string;
435
+ /** Tool calls from the model invocation (used by framework for route extraction) */
436
+ toolCalls?: Array<{
437
+ id: string;
438
+ name: string;
439
+ args: unknown;
440
+ }>;
441
+ /** Route reason extracted from route tool call (for hooks to inspect) */
442
+ routeReason?: string;
443
+ /** Structured data from this phase, passed to the next phase */
444
+ payload?: unknown;
1084
445
  };
1085
- declare class AgentExecution {
1086
- readonly state: AgentStatus;
1087
- private options;
1088
- private readonly listeners;
1089
- private readonly pendingListenerTasks;
1090
- private readonly listenerErrors;
1091
- private activeRun?;
1092
- private extensionRunner?;
1093
- private loadedExtensions?;
1094
- private loadedExtensionsCwd?;
1095
- private runtimeRunId?;
1096
- get id(): AgentId;
1097
- get sessionId(): string;
1098
- static loadSkills(targetPath: string): Promise<AgentContext["skills"]>;
1099
- static loadPhases(targetPath: Parameters<typeof loadPhases>[0]): Promise<PhaseRegistry>;
1100
- static loadExtensions(targetPath: string): Promise<LoadExtensionsResult>;
1101
- constructor(options: AgentExecutionOptions);
1102
- subscribe(listener: AgentEventListener): Unsubscribe;
1103
- appendUserMessage(input: string): void;
1104
- appendMessage(message: AgentMessage): void;
1105
- appendMessages(messages: AgentMessage[]): void;
1106
- runWithUserInput(input: string, options?: RunOptions): Promise<RunResult>;
1107
- runWithMessage(message: AgentMessage, options?: RunOptions, internalHooks?: RuntimeRunHooks): Promise<RunResult>;
1108
- /** Internal Runtime seam: executes one leased Agent Input. */
1109
- executeAgentInput(input: AgentMessage, runId: AgentRunId, control: AgentRunControl, executionState?: AgentRunExecutionState): Promise<Outcome>;
1110
- resetInitialization(): void;
1111
- getContext(): AgentContext;
1112
- setContext(context: AgentContext): void;
1113
- updateContext(updater: (context: AgentContext) => AgentContext): void;
1114
- forkContext(overrides?: Partial<AgentContext>): AgentContext;
1115
- getMessages(): AgentMessage[];
1116
- setMessages(messages: AgentMessage[]): void;
1117
- clearMessages(): void;
1118
- getTranscript(): AgentMessage[];
1119
- replaceTranscript(messages: AgentMessage[]): void;
1120
- getConfig(): AgentExecutionOptions;
1121
- setConfig(config: AgentExecutionOptions): void;
1122
- updateConfig(updater: (config: AgentExecutionOptions) => AgentExecutionOptions): void;
1123
- setSessionId(sessionId: string): void;
1124
- getSessionId(): string | undefined;
1125
- getAgentId(): AgentId | undefined;
1126
- /** Internal Runtime hook for associating Tool Calls with the leased Run. */
1127
- getRuntimeRunId(): AgentRunId | undefined;
1128
- setModel(model: ModelRef): void;
1129
- setTools(tools: Tool[]): void;
1130
- setSkills(skills: Skill$1[]): void;
1131
- setPhases(phases: PhaseRegistry): void;
1132
- setCwd(cwd: string): void;
1133
- setStream(stream: StreamFn): void;
1134
- getModel(): ModelRef;
1135
- getTools(): Tool[];
1136
- getSkills(): Skill$1[];
1137
- getPhases(): PhaseRegistry | undefined;
1138
- getCwd(): string | undefined;
1139
- private emitToListeners;
1140
- flushEvents(): Promise<void>;
1141
- private processEvents;
1142
- /**
1143
- * Hook for before_tool_call — called before a tool executes.
1144
- * Extensions can block execution by setting allow=false.
1145
- */
1146
- private handleBeforeToolCall;
1147
- /**
1148
- * Hook for after_tool_call — called after a tool executes.
1149
- * Extensions can mutate the result.
1150
- */
1151
- private handleAfterToolCall;
1152
- /**
1153
- * Hook for before_phase — called before a phase executes.
1154
- * Extensions can abort, skip, or replace the phase input.
1155
- */
1156
- private handleBeforePhase;
1157
- /**
1158
- * Hook for after_phase — called after a phase executes.
1159
- * Extensions can abort, retry, or replace the output.
1160
- */
1161
- private handleAfterPhase;
1162
- /**
1163
- * Hook for before_prompt — called before model request, allowing extensions to transform PhaseContext.
1164
- * Extensions can transform the PhaseContext (messages, tools, systemPrompt, etc.).
1165
- */
1166
- private handleBeforePrompt;
1167
- private handleRunFailure;
1168
- private runWithLifecycle;
1169
- private finishRun;
1170
- private loadExtensions;
1171
- run(config?: RunOptions, internalHooks?: RuntimeRunHooks): Promise<RunResult>;
1172
- abort(reason?: string): void;
1173
- isSuspended(): boolean;
1174
- private abortLocal;
1175
- /** Internal Runtime hook; public callers abort a precise AgentRun. */
1176
- abortFromRuntime(reason?: string): void;
1177
- /**
1178
- * Get formatted skill content for LLM consumption.
1179
- *
1180
- * Finds the skill by name and returns the formatted content using `formatSkillInvocation`.
1181
- * This is a programmatic API for developers to invoke skills directly.
1182
- *
1183
- * @param name - The skill name to look up
1184
- * @param additionalInstructions - Optional additional instructions to append
1185
- * @returns Formatted skill content string
1186
- */
1187
- skill(name: string, additionalInstructions?: string): string;
1188
- /**
1189
- * Get formatted phase content for LLM consumption.
1190
- *
1191
- * Finds the phase by name and returns the formatted content.
1192
- * This is a programmatic API for developers to invoke phases directly.
1193
- *
1194
- * @param name - The phase name to look up
1195
- * @returns Formatted phase content string, or empty string if not found
1196
- */
1197
- phase(name: string): Promise<string>;
1198
- waitForIdle(): Promise<void>;
1199
- private resolveRunConfig;
1200
- private createContextSnapshot;
1201
- private cloneOptions;
446
+ /** Phase machine state — tracks position and inter-phase data */
447
+ interface PhaseState {
448
+ current: string;
449
+ available: string[];
450
+ iterations: number;
451
+ payload?: unknown;
1202
452
  }
1203
-
1204
- declare const SkillSchema: Type.TObject<{
1205
- name: Type.TString;
1206
- description: Type.TString;
1207
- filePath: Type.TString;
1208
- baseDir: Type.TString;
1209
- content: Type.TString;
1210
- disableModelInvocation: Type.TBoolean;
1211
- }>;
1212
- type Skill = Type.Static<typeof SkillSchema>;
1213
-
1214
- type SessionHeader = {
1215
- type: "header";
1216
- id: string;
1217
- version: string;
1218
- createdAt: string;
1219
- updatedAt: string;
1220
- systemPrompt: string;
1221
- input: string;
1222
- parentSessionId?: string;
1223
- skills: Skill[];
1224
- title?: string;
1225
- currentLeafId?: string | null;
453
+ type PhaseInvocation = {
454
+ mode: "serial";
455
+ instanceId: string;
456
+ } | {
457
+ mode: "parallel";
458
+ instanceId: string;
459
+ groupId: string;
460
+ index: number;
461
+ count: number;
462
+ sourcePhaseId: string;
1226
463
  };
1227
- type SessionAgentContext<TTool = unknown> = {
464
+ /** Everything a phase needs to execute */
465
+ interface PhaseContext {
1228
466
  systemPrompt: string;
1229
467
  messages: AgentMessage[];
1230
- tools: TTool[];
468
+ /** Phase-filtered tools */
469
+ tools: Tool$1[];
470
+ /** Phase-filtered skills */
1231
471
  skills: Skill[];
1232
- };
1233
- type BuildAgentContextInput<TTool = unknown> = {
1234
- leafId?: string | null;
1235
- tools?: TTool[];
1236
- skills?: Skill[];
1237
- };
1238
- type CreateSessionManagerInput = {
1239
- id?: string;
1240
- systemPrompt: string;
1241
- input: string;
1242
- parentSessionId?: string;
1243
- skills?: Skill[];
1244
- title?: string;
1245
- };
1246
- type SessionListItem = {
1247
- id: string;
1248
- title?: string;
1249
- createdAt: string;
1250
- updatedAt: string;
1251
- messageCount: number;
1252
- latestMessage?: string;
1253
- };
1254
- type SessionManager = {
1255
- getSessionId(): string;
1256
- getHeader(): Promise<SessionHeader>;
1257
- appendMessage(message: AgentMessage): Promise<string>;
1258
- appendOutcome(outcome: Outcome): Promise<string>;
1259
- appendModelTranscript(transcript: ModelTranscript, meta?: {
1260
- phase?: string;
1261
- model?: ModelRef;
1262
- }): Promise<string>;
1263
- buildAgentContext<TTool = unknown>(input?: BuildAgentContextInput<TTool>): Promise<SessionAgentContext<TTool>>;
1264
- };
1265
- type SessionManagerProvider = {
1266
- create(input: CreateSessionManagerInput): Promise<SessionManager>;
1267
- open(sessionId: string): Promise<SessionManager | undefined>;
1268
- list(): Promise<SessionListItem[]>;
1269
- delete(sessionId: string): Promise<boolean>;
1270
- };
472
+ /** Phase machine state */
473
+ state: PhaseState;
474
+ /** Identity and dispatch metadata for this phase execution */
475
+ readonly invocation: PhaseInvocation;
476
+ /** Additional guideline bullets appended to the system prompt */
477
+ promptGuidelines?: string[];
478
+ /** Text to append after the system prompt */
479
+ appendSystemPrompt?: string;
480
+ }
481
+ /**
482
+ * Loaded Phase object
483
+ */
484
+ interface Phase {
485
+ /** Unique phase identity and display name. */
486
+ name: string;
487
+ /** Description */
488
+ description: string;
489
+ /** Restricted tools (undefined = all tools available) */
490
+ tools?: string[];
491
+ /** Restricted skills (undefined = all skills available) */
492
+ skills?: string[];
493
+ /** Forced next phase */
494
+ target?: string;
495
+ /** Expected input fields (key → description) */
496
+ input?: Record<string, string>;
497
+ /** If true, phase gets a fresh context when executed in parallel */
498
+ isolated?: boolean;
499
+ /** Path to PHASE.md file */
500
+ filePath: string;
501
+ /** Phase directory path */
502
+ baseDir: string;
503
+ /** PHASE.md body content */
504
+ content: string;
505
+ /** Model override for this phase (resolved from frontmatter) */
506
+ model?: ModelRef;
507
+ /** ExtensionAPI factory function (default export pattern) */
508
+ factory?: (api: ExtensionAPI) => Promise<void>;
509
+ /** Direct run function */
510
+ run?: (context: PhaseContext, execution: PhaseExecution) => Promise<PhaseOutput | void>;
511
+ }
512
+ /**
513
+ * Phase registry containing all loaded phases
514
+ */
515
+ interface PhaseRegistry {
516
+ /** Map of phase name to Phase object */
517
+ phases: Map<string, Phase>;
518
+ /** Entry phase name (null until Agent applies its default phase) */
519
+ entryPhaseId: string | null;
520
+ }
1271
521
 
1272
- type CreateAgentInput = {
1273
- sessionId: string;
1274
- parentSessionId?: string;
1275
- };
1276
- type EnqueueAgentInput = {
1277
- agentId: AgentId;
1278
- input: AgentMessage;
1279
- };
1280
- type AcknowledgeEventAndEnqueueAgentInput = EnqueueAgentInput & {
1281
- consumerId: string;
1282
- eventId: RuntimeEventId;
1283
- };
1284
- type EnqueuedAgentInput = {
1285
- message: RuntimeMessage;
1286
- run: AgentRunRecord;
1287
- resumed: boolean;
1288
- };
1289
- type AcknowledgeEventAndEnqueueAgentInputResult = {
1290
- checkpoint: RuntimeEventCheckpoint;
1291
- enqueued?: EnqueuedAgentInput;
1292
- };
1293
- type ListRunsInput = {
1294
- agentId?: AgentId;
1295
- states?: AgentRunRecord["state"][];
1296
- };
1297
- type RecordRuntimeEventInput = {
1298
- kind: RuntimeEventKind;
1299
- related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">;
1300
- payload?: unknown;
1301
- };
1302
- type LeaseRunInput = {
1303
- runId: AgentRunId;
1304
- workerId: string;
1305
- leaseDurationMs: number;
1306
- now?: Date;
1307
- };
1308
- type LeasedRun = {
1309
- run: AgentRunRecord;
1310
- message: RuntimeMessage;
1311
- lease: RuntimeLease;
1312
- };
1313
- type RenewLeaseInput = {
1314
- runId: AgentRunId;
1315
- leaseId: LeaseId;
1316
- leaseDurationMs: number;
1317
- now?: Date;
1318
- };
1319
- type SuspendRunInput = {
1320
- runId: AgentRunId;
1321
- reason?: string;
1322
- inputRequest?: AgentInputRequest;
1323
- executionState?: AgentRunExecutionState;
1324
- };
1325
- type CompleteRunInput = {
1326
- runId: AgentRunId;
1327
- outcome: Outcome;
1328
- state?: Extract<AgentRunRecord["state"], "completed" | "failed" | "cancelled">;
1329
- };
1330
- type RetryRunInput = {
1331
- runId: AgentRunId;
1332
- reason: string;
1333
- };
1334
- type ExhaustRunInput = {
1335
- runId: AgentRunId;
1336
- outcome: Outcome;
1337
- reason: string;
1338
- };
1339
- type AbortRunInput = {
1340
- runId: AgentRunId;
1341
- outcome: Outcome;
522
+ type ToolContext = Pick<AgentContext, "skills"> & {
523
+ toolCallId: string;
1342
524
  };
1343
- type CreateToolCallInput = {
1344
- agentId: AgentId;
1345
- runId: AgentRunId;
525
+ type ToolExecutionMode = "sequential" | "parallel";
526
+ type Tool$1<TArgs = unknown> = {
1346
527
  name: string;
1347
- args: unknown;
1348
- };
1349
- type CompleteToolCallInput = {
1350
- toolCallId: RuntimeToolCallId;
1351
- result: ToolResult;
1352
- state?: Extract<RuntimeToolCall["state"], "completed" | "failed">;
528
+ description: string;
529
+ parameters: Type.TSchema;
530
+ /** One-line snippet shown in the system prompt tool list. */
531
+ promptSnippet?: string;
532
+ /** Additional guidelines appended to the system prompt when this tool is active. */
533
+ promptGuidelines?: string[];
534
+ /** Whether this tool can run concurrently with others. Default: "parallel". */
535
+ executionMode?: ToolExecutionMode;
536
+ execute(args: TArgs, context: ToolContext, signal?: AbortSignal): Promise<ToolResult>;
1353
537
  };
1354
- type IndeterminateToolCallInput = {
1355
- toolCallId: RuntimeToolCallId;
1356
- reason: string;
538
+ /** Context snapshot passed into the low-level agent loop. */
539
+ type AgentContext = {
540
+ /** System prompt included with the request. */
541
+ systemPrompt: string;
542
+ /** Transcript visible to the model. */
543
+ messages: AgentMessage[];
544
+ /** Tools available for this run. */
545
+ tools: Tool$1[];
546
+ /** Skills available for this run. */
547
+ skills: Skill[];
548
+ /** Custom phases for this run. Agent normalizes this with the built-in default phase. */
549
+ phases?: PhaseRegistry;
1357
550
  };
1358
- interface RuntimeStateStore {
1359
- createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1360
- getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1361
- listAgents(): Promise<AgentRecord[]>;
1362
- setAgentState(agentId: AgentId, state: AgentLifecycleState): Promise<AgentRecord>;
1363
- setAgentLifecycleState(agentId: AgentId, state: SessionLifecycleState): Promise<AgentRecord>;
1364
- getAgentBySessionId(sessionId: string): Promise<AgentRecord | undefined>;
1365
- deleteAgentData(agentId: AgentId): Promise<void>;
1366
- enqueueAgentInput(input: EnqueueAgentInput): Promise<EnqueuedAgentInput>;
1367
- getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1368
- getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1369
- listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1370
- listActiveRuns(): Promise<AgentRunRecord[]>;
1371
- leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1372
- renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1373
- suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1374
- completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1375
- retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1376
- exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1377
- abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1378
- recoverExpiredLeases(now?: Date): Promise<AgentRunRecord[]>;
1379
- recoverLeases(): Promise<AgentRunRecord[]>;
1380
- createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1381
- startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1382
- completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1383
- markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1384
- getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1385
- listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1386
- recordEvent(input: RecordRuntimeEventInput): Promise<RuntimeEvent>;
1387
- getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1388
- acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1389
- acknowledgeEventAndEnqueueAgentInput(input: AcknowledgeEventAndEnqueueAgentInput): Promise<AcknowledgeEventAndEnqueueAgentInputResult>;
1390
- }
1391
551
 
1392
- type ToolRuntimePolicy = {
1393
- /** A narrowing allow-list. It can never add a Tool to an Agent. */
1394
- allowedTools?: readonly string[];
1395
- maxConcurrent?: number;
1396
- perToolMaxConcurrent?: Readonly<Record<string, number>>;
552
+ type CoreToolContext = {
553
+ root?: string;
554
+ maxReadBytes?: number;
555
+ bashTimeoutMs?: number;
556
+ maxBashOutputBytes?: number;
1397
557
  };
1398
558
 
1399
- type AgentRuntimeOptions = {
1400
- stateStore: RuntimeStateStore;
1401
- sessionProvider?: SessionManagerProvider;
1402
- toolPolicy?: ToolRuntimePolicy;
1403
- maxConcurrentRuns?: number;
1404
- maxInfrastructureAttempts?: number;
1405
- leaseDurationMs?: number;
1406
- leaseRenewalIntervalMs?: number;
1407
- };
1408
- type RuntimeRunHandle = {
1409
- notify(run: AgentRunRecord): void;
559
+ /** Durable and transient DTOs owned by the event-driven Agent Runtime. */
560
+ declare const opaqueIdBrand: unique symbol;
561
+ type OpaqueId<Kind extends string> = string & {
562
+ readonly [opaqueIdBrand]: Kind;
1410
563
  };
1411
- type RuntimeEventDisposition = {
1412
- type: "enqueue";
564
+ type AgentId = OpaqueId<"AgentId">;
565
+ type RunId = OpaqueId<"RunId">;
566
+ type MessageId = OpaqueId<"MessageId">;
567
+ type InputRequestId = OpaqueId<"InputRequestId">;
568
+ type ToolCallId = OpaqueId<"ToolCallId">;
569
+ type EventId = OpaqueId<"EventId">;
570
+ type ExecutionId = OpaqueId<"ExecutionId">;
571
+ type OutcomeId = OpaqueId<"OutcomeId">;
572
+ type ConfigToken = OpaqueId<"ConfigToken">;
573
+ type OwnerToken = OpaqueId<"OwnerToken">;
574
+ type EventCursor = OpaqueId<"EventCursor">;
575
+ type AgentListCursor = OpaqueId<"AgentListCursor">;
576
+ type RunListCursor = OpaqueId<"RunListCursor">;
577
+ type JsonPrimitive = null | boolean | number | string;
578
+ type JsonValue = JsonPrimitive | readonly JsonValue[] | {
579
+ readonly [key: string]: JsonValue;
580
+ };
581
+ type JsonObject = Readonly<Record<string, JsonValue>>;
582
+ type Metadata = JsonObject;
583
+ type TextContent = Readonly<{
584
+ type: "text";
585
+ text: string;
586
+ }>;
587
+ type ImageContent = Readonly<{
588
+ type: "image";
589
+ data: string;
590
+ mimeType: string;
591
+ }>;
592
+ type ThinkingContent = Readonly<{
593
+ type: "thinking";
594
+ thinking: string;
595
+ signature?: string;
596
+ }>;
597
+ type ToolUseContent = Readonly<{
598
+ type: "tool_use";
599
+ toolCallId: ToolCallId;
600
+ name: string;
601
+ input: JsonValue;
602
+ }>;
603
+ type ToolExecutionResult = Readonly<{
604
+ ok: true;
605
+ content: JsonValue;
606
+ }> | Readonly<{
607
+ ok: false;
608
+ content: JsonValue;
609
+ error: string;
610
+ }>;
611
+ type DurableToolResult = Readonly<{
612
+ toolCallId: ToolCallId;
613
+ toolName: string;
614
+ }> & ToolExecutionResult;
615
+ type ToolResultContent = Readonly<{
616
+ type: "tool_result";
617
+ toolCallId: ToolCallId;
618
+ result: ToolExecutionResult;
619
+ }>;
620
+ type UserContent = string | readonly (TextContent | ImageContent)[];
621
+ type AssistantContent = string | readonly (TextContent | ThinkingContent | ToolUseContent)[];
622
+ type ToolMessageContent = readonly [ToolResultContent, ...ToolResultContent[]];
623
+ type MessageContent = UserContent | AssistantContent | ToolMessageContent;
624
+ type MessageBase = Readonly<{
625
+ id: MessageId;
1413
626
  agentId: AgentId;
1414
- input: AgentMessage;
1415
- };
1416
- type RuntimeEventListener = (event: RuntimeEvent) => RuntimeEventDisposition | void | Promise<RuntimeEventDisposition | void>;
1417
- type RuntimeEventConsumer = {
1418
- caughtUp: Promise<void>;
1419
- stop(): void;
1420
- };
1421
- type RuntimeSessionSummary = {
1422
- id: string;
1423
- state: SessionLifecycleState;
627
+ runId: RunId;
628
+ metadata?: Metadata;
629
+ sequenceWithinRun: number;
630
+ createdAt: string;
631
+ }>;
632
+ type UserMessage = MessageBase & Readonly<{
633
+ role: "user";
634
+ content: UserContent;
635
+ }>;
636
+ type AssistantMessage = MessageBase & Readonly<{
637
+ role: "assistant";
638
+ content: AssistantContent;
639
+ }>;
640
+ type ToolMessage = MessageBase & Readonly<{
641
+ role: "tool";
642
+ content: ToolMessageContent;
643
+ }>;
644
+ type Message = UserMessage | AssistantMessage | ToolMessage;
645
+ type Outcome = Readonly<{
646
+ id: OutcomeId;
647
+ message: string;
648
+ payload?: JsonValue;
649
+ toolResults?: readonly DurableToolResult[];
650
+ }>;
651
+ type RunState = "queued" | "running" | "input_required" | "completed" | "failed" | "cancelled";
652
+ type RunFailure = Readonly<{
653
+ code: "configuration_unavailable";
654
+ message: string;
655
+ }> | Readonly<{
656
+ code: "checkpoint_incompatible";
657
+ message: string;
658
+ expected: Readonly<{
659
+ codec: string;
660
+ versions: readonly number[];
661
+ }>;
662
+ actual: Readonly<{
663
+ codec: string;
664
+ version: number;
665
+ }>;
666
+ }> | Readonly<{
667
+ code: "runtime_interrupted";
668
+ message: string;
669
+ ownerEpoch: number;
670
+ }> | Readonly<{
671
+ code: "tool_indeterminate";
672
+ message: string;
673
+ toolCallIds: readonly [ToolCallId, ...ToolCallId[]];
674
+ }> | Readonly<{
675
+ code: "execution_failed";
676
+ message: string;
677
+ details?: JsonValue;
678
+ }>;
679
+ type QueuedRunFailure = Extract<RunFailure, {
680
+ code: "configuration_unavailable" | "checkpoint_incompatible";
681
+ }>;
682
+ type RunningRunFailure = Extract<RunFailure, {
683
+ code: "runtime_interrupted" | "tool_indeterminate" | "execution_failed";
684
+ }>;
685
+ type ToolCallState = "pending" | "running" | "completed" | "failed" | "indeterminate";
686
+ type ToolCallSnapshotBase = Readonly<{
687
+ id: ToolCallId;
688
+ agentId: AgentId;
689
+ runId: RunId;
690
+ executionId: ExecutionId;
691
+ requestMessageId: MessageId;
692
+ name: string;
693
+ args: JsonValue;
1424
694
  createdAt: string;
1425
695
  updatedAt: string;
1426
- archivedAt?: string;
1427
- parentSessionId?: string;
696
+ }>;
697
+ type ToolCallSnapshot = ToolCallSnapshotBase & (Readonly<{
698
+ state: "pending";
699
+ }> | Readonly<{
700
+ state: "running";
701
+ }> | Readonly<{
702
+ state: "completed";
703
+ result: DurableToolResult & Readonly<{
704
+ ok: true;
705
+ }>;
706
+ resultMessageId: MessageId;
707
+ }> | Readonly<{
708
+ state: "failed";
709
+ result: DurableToolResult & Readonly<{
710
+ ok: false;
711
+ }>;
712
+ resultMessageId: MessageId;
713
+ }> | Readonly<{
714
+ state: "indeterminate";
715
+ result: DurableToolResult & Readonly<{
716
+ ok: false;
717
+ }>;
718
+ resultMessageId: MessageId;
719
+ reason: string;
720
+ }>);
721
+ type DurableEventBase = Readonly<{
722
+ id: EventId;
723
+ schemaVersion: 1;
724
+ cursor: EventCursor;
725
+ durability: "durable";
1428
726
  agentId: AgentId;
1429
- activeRunCount: number;
1430
- title?: string;
1431
- };
1432
- declare class AgentRuntime {
1433
- private readonly stateStore;
1434
- private readonly sessionProvider?;
1435
- private readonly maxConcurrentRuns;
1436
- private readonly maxInfrastructureAttempts;
1437
- private readonly leaseDurationMs;
1438
- private readonly leaseRenewalIntervalMs;
1439
- private readonly toolRuntime;
1440
- private readonly bindings;
1441
- private readonly agents;
1442
- private readonly invalidatedAgents;
1443
- private readonly runHandles;
1444
- private readonly runWaiters;
1445
- private readonly pendingRuns;
1446
- private readonly scheduledRunIds;
1447
- private readonly runningAgents;
1448
- private readonly pausedAgents;
1449
- private readonly eventSubscriptions;
1450
- private readonly activeDispatches;
1451
- private runningRuns;
1452
- private pumping;
1453
- private nextWorkerId;
1454
- private leaseRecoveryTimer;
1455
- private stopped;
1456
- private constructor();
1457
- static start(options: AgentRuntimeOptions): Promise<AgentRuntime>;
1458
- createAgent(options: AgentOptions): Promise<Agent>;
1459
- reconstructAgent(agentId: AgentId, options: AgentOptions): Promise<Agent>;
1460
- stop(): Promise<void>;
1461
- private bindAgent;
1462
- private registerRunHandle;
1463
- private waitForRunChange;
1464
- private scheduleRun;
1465
- pauseAgent(agentId: AgentId): Promise<void>;
1466
- resumeAgent(agentId: AgentId): Promise<void>;
1467
- getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1468
- listActiveRuns(): Promise<AgentRunRecord[]>;
1469
- listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1470
- listSessions(input?: {
1471
- state?: SessionLifecycleState;
1472
- }): Promise<RuntimeSessionSummary[]>;
1473
- archiveSession(sessionId: string): Promise<void>;
1474
- unarchiveSession(sessionId: string): Promise<void>;
1475
- deleteSession(sessionId: string): Promise<void>;
1476
- private requireSessionAgent;
1477
- getAgent(agentId: AgentId): Agent | undefined;
1478
- getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1479
- getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1480
- abortRun(runId: AgentRunId, reason?: string): Promise<void>;
1481
- consumeEvents(consumerId: string, listener: RuntimeEventListener): RuntimeEventConsumer;
1482
- private registerEventConsumer;
1483
- listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1484
- private recover;
1485
- private startLeaseRecovery;
1486
- private recoverExpiredLeases;
1487
- private scheduleQueuedRuns;
1488
- private attachAgent;
1489
- private submitAgentInput;
1490
- private pump;
1491
- private dispatchRun;
1492
- private finishRun;
1493
- private finishFailedRun;
1494
- private notifyRun;
1495
- private publishEvents;
1496
- private deliverEvents;
1497
- private assertRunning;
1498
- }
1499
-
1500
- type AgentRunListener = (state: AgentRunState) => void | Promise<void>;
1501
- type AgentRunHost = {
1502
- register(handle: RuntimeRunHandle): void;
1503
- getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1504
- waitForRunChange(runId: AgentRunId, state: AgentRunState, updatedAt: string): Promise<void>;
1505
- abortRun(runId: AgentRunId, reason: string): Promise<void>;
1506
- consumeEvents(consumerId: string, listener: RuntimeEventListener): RuntimeEventConsumer;
1507
- };
1508
- declare const CREATE_AGENT_RUN: unique symbol;
1509
- declare class AgentRun implements RuntimeRunHandle {
1510
- private readonly host;
1511
- private readonly publicMessageId;
1512
- private current;
1513
- private readonly listeners;
1514
- private constructor();
1515
- static [CREATE_AGENT_RUN](host: AgentRunHost, initial: AgentRunRecord, publicMessageId: string): AgentRun;
1516
- get id(): AgentRunId;
1517
- get messageId(): string;
1518
- get status(): AgentRunState;
1519
- get state(): AgentRunState;
1520
- get inputRequest(): AgentInputRequest | undefined;
1521
- getStatus(): Promise<AgentRunState>;
1522
- subscribe(listener: AgentRunListener): () => void;
1523
- consumeRuntimeEvents(consumerId: string, listener: RuntimeEventListener): RuntimeEventConsumer;
1524
- result(): Promise<Outcome>;
1525
- abort(reason?: string): Promise<void>;
1526
- notify(run: AgentRunRecord): void;
1527
- }
727
+ runId: RunId;
728
+ runRevision: number;
729
+ metadata?: Metadata;
730
+ createdAt: string;
731
+ }>;
732
+ type MessageCommitted = DurableEventBase & Readonly<{
733
+ kind: "message_committed";
734
+ message: Message;
735
+ }>;
736
+ type RunTransitioned = DurableEventBase & (Readonly<{
737
+ kind: "run_transitioned";
738
+ from: null;
739
+ to: "queued";
740
+ }> | Readonly<{
741
+ kind: "run_transitioned";
742
+ from: "input_required";
743
+ to: "queued";
744
+ }> | Readonly<{
745
+ kind: "run_transitioned";
746
+ from: "queued";
747
+ to: "running";
748
+ }> | Readonly<{
749
+ kind: "run_transitioned";
750
+ from: "running";
751
+ to: "input_required";
752
+ request: Readonly<{
753
+ id: InputRequestId;
754
+ prompt: AssistantMessage;
755
+ }>;
756
+ }> | Readonly<{
757
+ kind: "run_transitioned";
758
+ from: "running";
759
+ to: "completed";
760
+ outcome: Outcome;
761
+ output?: AssistantMessage;
762
+ }> | Readonly<{
763
+ kind: "run_transitioned";
764
+ from: "queued";
765
+ to: "failed";
766
+ failure: QueuedRunFailure;
767
+ }> | Readonly<{
768
+ kind: "run_transitioned";
769
+ from: "running";
770
+ to: "failed";
771
+ failure: RunningRunFailure;
772
+ }> | Readonly<{
773
+ kind: "run_transitioned";
774
+ from: "queued" | "running" | "input_required";
775
+ to: "cancelled";
776
+ reason?: string;
777
+ }>);
778
+ type ToolStateChanged = DurableEventBase & (Readonly<{
779
+ kind: "tool_state_changed";
780
+ transition: Readonly<{
781
+ from: null;
782
+ to: "pending";
783
+ }>;
784
+ toolCall: Extract<ToolCallSnapshot, {
785
+ state: "pending";
786
+ }>;
787
+ }> | Readonly<{
788
+ kind: "tool_state_changed";
789
+ transition: Readonly<{
790
+ from: "pending";
791
+ to: "running";
792
+ }>;
793
+ toolCall: Extract<ToolCallSnapshot, {
794
+ state: "running";
795
+ }>;
796
+ }> | Readonly<{
797
+ kind: "tool_state_changed";
798
+ transition: Readonly<{
799
+ from: "pending";
800
+ to: "failed";
801
+ }>;
802
+ toolCall: Extract<ToolCallSnapshot, {
803
+ state: "failed";
804
+ }>;
805
+ }> | Readonly<{
806
+ kind: "tool_state_changed";
807
+ transition: Readonly<{
808
+ from: "running";
809
+ to: "completed";
810
+ }>;
811
+ toolCall: Extract<ToolCallSnapshot, {
812
+ state: "completed";
813
+ }>;
814
+ }> | Readonly<{
815
+ kind: "tool_state_changed";
816
+ transition: Readonly<{
817
+ from: "running";
818
+ to: "failed";
819
+ }>;
820
+ toolCall: Extract<ToolCallSnapshot, {
821
+ state: "failed";
822
+ }>;
823
+ }> | Readonly<{
824
+ kind: "tool_state_changed";
825
+ transition: Readonly<{
826
+ from: "running";
827
+ to: "indeterminate";
828
+ }>;
829
+ toolCall: Extract<ToolCallSnapshot, {
830
+ state: "indeterminate";
831
+ }>;
832
+ }>);
833
+ type DurableRunEvent = MessageCommitted | RunTransitioned | ToolStateChanged;
1528
834
 
1529
- type AgentCommonOptions = {
1530
- context: AgentContext;
835
+ type UserInput = string | Readonly<{
836
+ content: UserContent;
837
+ metadata?: Metadata;
838
+ }>;
839
+ type ToolInvocationContext = Readonly<{
840
+ agentId: AgentId;
841
+ runId: RunId;
842
+ toolCallId: ToolCallId;
843
+ }>;
844
+ type Tool = Readonly<{
845
+ name: string;
846
+ description: string;
847
+ parameters: Type.TSchema;
848
+ execute(args: JsonValue, context: ToolInvocationContext, signal: AbortSignal): Promise<ToolExecutionResult>;
849
+ }>;
850
+ type BeforeToolCall = (input: Readonly<{
851
+ tool: Tool;
852
+ args: JsonValue;
853
+ context: ToolInvocationContext;
854
+ signal: AbortSignal;
855
+ }>) => Readonly<{
856
+ allow: true;
857
+ }> | Readonly<{
858
+ allow: false;
859
+ reason: string;
860
+ }> | Promise<Readonly<{
861
+ allow: true;
862
+ }> | Readonly<{
863
+ allow: false;
864
+ reason: string;
865
+ }>>;
866
+ type AfterToolCall = (input: Readonly<{
867
+ tool: Tool;
868
+ result: ToolExecutionResult;
869
+ context: ToolInvocationContext;
870
+ signal: AbortSignal;
871
+ }>) => ToolExecutionResult | Promise<ToolExecutionResult>;
872
+ type AgentDefinitionContext = Readonly<{
873
+ systemPrompt: string;
874
+ tools: readonly Tool[];
875
+ skills: readonly Skill[];
876
+ phases?: PhaseRegistry;
877
+ }>;
878
+ type AgentConfig = Readonly<{
879
+ identity: string;
880
+ context: AgentDefinitionContext;
1531
881
  cwd?: string;
1532
- extensions?: LoadedExtension[];
882
+ extensions?: readonly LoadedExtension[];
1533
883
  maxAttempts?: number;
1534
884
  beforeToolCall?: BeforeToolCall;
1535
885
  afterToolCall?: AfterToolCall;
1536
- onMessage?: (message: AgentMessage) => Promise<void>;
1537
- onOutcome?: (outcome: Outcome) => Promise<void>;
1538
- onModelTranscript?: (transcript: ModelTranscript, meta: {
1539
- phase: string;
1540
- model: ModelRef;
1541
- }) => Promise<void>;
1542
- };
1543
- type AgentModelOptions = {
886
+ } & ({
1544
887
  model: ModelConfig;
1545
888
  stream?: never;
1546
889
  } | {
1547
890
  model: ModelRef;
1548
891
  stream: StreamFn;
1549
- };
1550
- type AgentOptions = AgentCommonOptions & AgentModelOptions;
1551
- type StreamAgentOptions = AgentCommonOptions & {
1552
- model: ModelRef;
1553
- stream: StreamFn;
1554
- };
1555
- type AgentRunControl = {
1556
- suspend(reason?: string, state?: AgentRunExecutionState, inputRequest?: AgentInputRequest): Promise<void>;
1557
- };
1558
- declare const ATTACH_AGENT: unique symbol;
1559
- declare class Agent {
1560
- readonly id: AgentId;
1561
- readonly sessionId: string;
1562
- private readonly execution;
1563
- private readonly submitInput;
1564
- private constructor();
1565
- static [ATTACH_AGENT](id: AgentId, sessionId: string, execution: AgentExecution, submitInput: (input: AgentMessage) => Promise<AgentRun>): Agent;
1566
- static loadSkills(targetPath: string): Promise<AgentContext["skills"]>;
1567
- static loadPhases(targetPath: Parameters<typeof AgentExecution.loadPhases>[0]): Promise<PhaseRegistry>;
1568
- static loadExtensions(targetPath: string): Promise<LoadExtensionsResult>;
1569
- subscribe(listener: AgentEventListener): Unsubscribe;
1570
- flushEvents(): Promise<void>;
1571
- send(input: string | AgentMessage): Promise<AgentRun>;
892
+ })>;
893
+ type AgentRecord = Readonly<{
894
+ id: AgentId;
895
+ metadata?: Metadata;
896
+ currentConfigToken?: ConfigToken;
897
+ currentConfigIdentity?: string;
898
+ createdAt: string;
899
+ activatedAt?: string;
900
+ updatedAt: string;
901
+ }>;
902
+ type ExecutionToken = Readonly<{
903
+ runId: RunId;
904
+ ownerEpoch: number;
905
+ executionId: ExecutionId;
906
+ }>;
907
+ type ExecutionCheckpoint = Readonly<{
908
+ codec: string;
909
+ version: number;
910
+ data: JsonValue;
911
+ }>;
912
+ type InputRequest = Readonly<{
913
+ id: InputRequestId;
914
+ messageId: MessageId;
915
+ createdAt: string;
916
+ }>;
917
+ type OwnerLease = Readonly<{
918
+ ownerId: string;
919
+ token: OwnerToken;
920
+ epoch: number;
921
+ expiresAt: string;
922
+ }>;
923
+ type RunClaim = Readonly<{
924
+ run: RunRecord;
925
+ execution: ExecutionToken;
926
+ history: readonly Message[];
927
+ }>;
928
+ type InputRequiredCommit = Readonly<{
929
+ run: RunRecord;
930
+ prompt: AssistantMessage;
931
+ request: InputRequest;
932
+ }>;
933
+ type ToolCommit = Readonly<{
934
+ run: RunRecord;
935
+ toolCall: ToolCallSnapshot;
936
+ }>;
937
+ type RunRecord = Readonly<{
938
+ id: RunId;
939
+ agentId: AgentId;
940
+ agentSequence: number;
941
+ readySequence: number;
942
+ revision: number;
943
+ state: RunState;
944
+ input: UserInput;
945
+ metadata?: Metadata;
946
+ pinnedConfigToken?: ConfigToken;
947
+ checkpoint?: ExecutionCheckpoint;
948
+ openInputRequest?: InputRequest;
949
+ execution?: ExecutionToken;
950
+ outcome?: Outcome;
951
+ failure?: RunFailure;
952
+ cancellationReason?: string;
953
+ createdAt: string;
954
+ updatedAt: string;
955
+ }>;
956
+ type AgentSummary = Readonly<{
957
+ id: AgentId;
958
+ metadata?: Metadata;
959
+ currentConfigIdentity?: string;
960
+ createdAt: string;
961
+ activatedAt: string;
962
+ updatedAt: string;
963
+ }>;
964
+ type RunSummary = Readonly<{
965
+ id: RunId;
966
+ agentId: AgentId;
967
+ agentSequence: number;
968
+ state: RunState;
969
+ metadata?: Metadata;
970
+ createdAt: string;
971
+ updatedAt: string;
972
+ }>;
973
+ type Page<T, Cursor> = Readonly<{
974
+ items: readonly T[];
975
+ next?: Cursor;
976
+ }>;
977
+ type RunSnapshotBase = Readonly<{
978
+ runId: RunId;
979
+ agentId: AgentId;
980
+ agentSequence: number;
981
+ revision: number;
982
+ input: UserInput;
983
+ metadata?: Metadata;
984
+ messageCount: number;
985
+ toolCallCount: number;
986
+ createdAt: string;
987
+ updatedAt: string;
988
+ cursor: EventCursor;
989
+ }>;
990
+ type RunSnapshot = RunSnapshotBase & (Readonly<{
991
+ state: "queued" | "running";
992
+ }> | Readonly<{
993
+ state: "input_required";
994
+ request: Readonly<{
995
+ id: InputRequestId;
996
+ prompt: AssistantMessage;
997
+ }>;
998
+ }> | Readonly<{
999
+ state: "completed";
1000
+ outcome: Outcome;
1001
+ output?: AssistantMessage;
1002
+ }> | Readonly<{
1003
+ state: "failed";
1004
+ failure: RunFailure;
1005
+ }> | Readonly<{
1006
+ state: "cancelled";
1007
+ reason?: string;
1008
+ }>);
1009
+ type RunBoundary = Readonly<{
1010
+ type: "input_required";
1011
+ requestId: InputRequestId;
1012
+ prompt: AssistantMessage;
1013
+ }> | Readonly<{
1014
+ type: "completed";
1015
+ outcome: Outcome;
1016
+ output?: AssistantMessage;
1017
+ }> | Readonly<{
1018
+ type: "failed";
1019
+ failure: RunFailure;
1020
+ }> | Readonly<{
1021
+ type: "cancelled";
1022
+ reason?: string;
1023
+ }>;
1024
+ type ConfigResolution = Readonly<{
1025
+ kind: "available";
1026
+ config: AgentConfig;
1027
+ } | {
1028
+ kind: "deferred";
1029
+ retryAfterMs?: number;
1030
+ } | {
1031
+ kind: "unavailable";
1032
+ reason: string;
1033
+ }>;
1034
+ type ConfigPutResult = Readonly<{
1035
+ kind: "stored";
1036
+ token: string;
1037
+ } | {
1038
+ kind: "identity_conflict";
1039
+ }>;
1040
+ interface ConfigProvider {
1041
+ put(input: {
1042
+ agentId: AgentId;
1043
+ agentMetadata?: Metadata;
1044
+ config: AgentConfig;
1045
+ operationId: string;
1046
+ signal: AbortSignal;
1047
+ }): Promise<ConfigPutResult>;
1048
+ resolve(input: {
1049
+ agentId: AgentId;
1050
+ agentMetadata?: Metadata;
1051
+ token: ConfigToken;
1052
+ signal: AbortSignal;
1053
+ }): Promise<ConfigResolution>;
1572
1054
  }
1573
-
1574
- declare class InMemorySessionStore implements SessionManagerProvider {
1575
- private readonly sessions;
1576
- create(input: CreateSessionManagerInput): Promise<SessionManager>;
1577
- open(sessionId: string): Promise<SessionManager | undefined>;
1578
- list(): Promise<{
1579
- id: string;
1580
- title: string | undefined;
1581
- createdAt: string;
1582
- updatedAt: string;
1583
- messageCount: any;
1584
- }[]>;
1585
- delete(sessionId: string): Promise<boolean>;
1055
+ interface OwnedStore {
1056
+ readonly lease: OwnerLease;
1057
+ reserveAgent(input: {
1058
+ idempotencyKey: string;
1059
+ metadata?: Metadata;
1060
+ configIdentity?: string;
1061
+ }): Promise<AgentRecord>;
1062
+ activateAgent(agentId: AgentId, configToken?: ConfigToken, configIdentity?: string): Promise<AgentRecord>;
1063
+ updateAgentConfigToken(input: {
1064
+ agentId: AgentId;
1065
+ token: ConfigToken;
1066
+ configIdentity?: string;
1067
+ idempotencyKey: string;
1068
+ }): Promise<AgentRecord>;
1069
+ createRun(input: {
1070
+ agentId: AgentId;
1071
+ input: UserInput;
1072
+ metadata?: Metadata;
1073
+ idempotencyKey: string;
1074
+ }): Promise<RunRecord>;
1075
+ claimRun(input: {
1076
+ runId: RunId;
1077
+ expectedRevision: number;
1078
+ executionId?: ExecutionId;
1079
+ messageId?: MessageId;
1080
+ configToken?: ConfigToken;
1081
+ }): Promise<RunClaim>;
1082
+ failQueuedRun(input: {
1083
+ runId: RunId;
1084
+ expectedRevision: number;
1085
+ failure: QueuedRunFailure;
1086
+ }): Promise<RunRecord>;
1087
+ commitInputRequired(input: {
1088
+ runId: RunId;
1089
+ execution: ExecutionToken;
1090
+ expectedRevision: number;
1091
+ requestId?: InputRequestId;
1092
+ prompt: AssistantMessage;
1093
+ checkpoint: ExecutionCheckpoint;
1094
+ }): Promise<InputRequiredCommit>;
1095
+ answerInput(input: {
1096
+ runId: RunId;
1097
+ requestId: InputRequestId;
1098
+ expectedRevision: number;
1099
+ input: UserInput;
1100
+ messageId?: MessageId;
1101
+ }): Promise<RunRecord>;
1102
+ commitOutcome(input: {
1103
+ runId: RunId;
1104
+ execution: ExecutionToken;
1105
+ expectedRevision: number;
1106
+ outcome?: Outcome;
1107
+ failure?: RunFailure;
1108
+ output?: AssistantMessage;
1109
+ }): Promise<RunRecord>;
1110
+ reserveToolCall(input: {
1111
+ runId: RunId;
1112
+ execution: ExecutionToken;
1113
+ expectedRevision: number;
1114
+ requestMessageId: MessageId;
1115
+ name: string;
1116
+ args: JsonValue;
1117
+ toolCallId?: ToolCallId;
1118
+ }): Promise<ToolCommit>;
1119
+ startToolCall(input: {
1120
+ runId: RunId;
1121
+ execution: ExecutionToken;
1122
+ expectedRevision: number;
1123
+ toolCallId: ToolCallId;
1124
+ }): Promise<ToolCommit>;
1125
+ commitToolResult(input: {
1126
+ runId: RunId;
1127
+ execution: ExecutionToken;
1128
+ expectedRevision: number;
1129
+ toolCallId: ToolCallId;
1130
+ result: ToolExecutionResult;
1131
+ state: "completed" | "failed" | "indeterminate";
1132
+ reason?: string;
1133
+ }): Promise<ToolCommit>;
1134
+ cancelRun(input: {
1135
+ runId: RunId;
1136
+ expectedRevision?: number;
1137
+ reason?: string;
1138
+ }): Promise<RunRecord>;
1139
+ snapshotRun(runId: RunId): Promise<RunSnapshot>;
1140
+ listAgents(): Promise<readonly AgentRecord[]>;
1141
+ listRuns(input?: {
1142
+ agentId?: AgentId;
1143
+ states?: readonly RunState[];
1144
+ }): Promise<readonly RunRecord[]>;
1145
+ listEvents(input?: {
1146
+ after?: EventCursor;
1147
+ }): Promise<readonly DurableRunEvent[]>;
1148
+ openConsumer(consumerId: string): Promise<ConsumerRegistration>;
1149
+ advanceConsumerCheckpoint(input: {
1150
+ consumerId: string;
1151
+ cursor: EventCursor;
1152
+ }): Promise<void>;
1153
+ renewOwner(leaseMs: number): Promise<OwnerLease>;
1154
+ sealAndReleaseOwner(): Promise<void>;
1155
+ }
1156
+ interface DurableStore {
1157
+ openOwner(input: {
1158
+ ownerId: string;
1159
+ leaseMs: number;
1160
+ }): Promise<OwnedStore>;
1161
+ }
1162
+ type AgentRuntimeOptions = Readonly<{
1163
+ store: DurableStore;
1164
+ configs?: ConfigProvider;
1165
+ concurrency?: number;
1166
+ }>;
1167
+ type DurableConsumer = Readonly<{
1168
+ caughtUp: Promise<void>;
1169
+ done: Promise<void>;
1170
+ stop(): void;
1171
+ }>;
1172
+ interface AgentRun {
1173
+ readonly id: RunId;
1174
+ snapshot(): Promise<RunSnapshot>;
1175
+ observe(options?: {
1176
+ after?: EventCursor;
1177
+ signal?: AbortSignal;
1178
+ }): AsyncIterable<DurableRunEvent>;
1179
+ wait(options?: {
1180
+ signal?: AbortSignal;
1181
+ }): Promise<RunBoundary>;
1182
+ respond(input: {
1183
+ requestId: InputRequestId;
1184
+ input: UserInput;
1185
+ }): Promise<void>;
1186
+ cancel(reason?: string): Promise<RunBoundary>;
1586
1187
  }
1587
- declare class JsonlSessionStore implements SessionManagerProvider {
1588
- private readonly sessionsDir;
1589
- constructor(sessionsDir: string);
1590
- create(input: CreateSessionManagerInput): Promise<SessionManager>;
1591
- open(sessionId: string): Promise<SessionManager | undefined>;
1592
- list(): Promise<SessionListItem[]>;
1593
- delete(sessionId: string): Promise<boolean>;
1188
+ interface AgentRuntime$1 {
1189
+ createAgent(config: AgentConfig, options?: {
1190
+ idempotencyKey?: string;
1191
+ metadata?: Metadata;
1192
+ }): Promise<AgentId>;
1193
+ updateAgentConfig(agentId: AgentId, config: AgentConfig, options: {
1194
+ idempotencyKey: string;
1195
+ }): Promise<void>;
1196
+ start(agentId: AgentId, input: UserInput, options: {
1197
+ idempotencyKey: string;
1198
+ metadata?: Metadata;
1199
+ }): Promise<AgentRun>;
1200
+ run(runId: RunId): AgentRun;
1201
+ listAgents(input?: {
1202
+ after?: AgentListCursor;
1203
+ limit?: number;
1204
+ }): Promise<Page<AgentSummary, AgentListCursor>>;
1205
+ listRuns(input?: {
1206
+ agentId?: AgentId;
1207
+ states?: readonly RunState[];
1208
+ after?: RunListCursor;
1209
+ limit?: number;
1210
+ }): Promise<Page<RunSummary, RunListCursor>>;
1211
+ consume(input: {
1212
+ consumerId: string;
1213
+ signal: AbortSignal;
1214
+ onEvent(event: DurableRunEvent, context: Readonly<{
1215
+ signal: AbortSignal;
1216
+ }>): void | Promise<void>;
1217
+ }): Promise<DurableConsumer>;
1218
+ close(): Promise<void>;
1594
1219
  }
1220
+ type ConsumerRegistration = Readonly<{
1221
+ cursor?: EventCursor;
1222
+ waterline: EventCursor;
1223
+ }>;
1595
1224
 
1596
- type CoreToolContext = {
1597
- root?: string;
1598
- maxReadBytes?: number;
1599
- bashTimeoutMs?: number;
1600
- maxBashOutputBytes?: number;
1601
- };
1602
- declare function createCoreTools(input?: CoreToolContext): Tool[];
1225
+ declare class AgentRuntime implements AgentRuntime$1 {
1226
+ private readonly concurrency;
1227
+ private readonly owned;
1228
+ private readonly commands;
1229
+ private readonly storeIncarnation;
1230
+ private readonly activeAgents;
1231
+ private readonly executions;
1232
+ private readonly consumers;
1233
+ private heartbeat?;
1234
+ private pumping;
1235
+ private closed;
1236
+ private constructor();
1237
+ static init(options: AgentRuntimeOptions): Promise<AgentRuntime>;
1238
+ createAgent(config: AgentConfig, options?: {
1239
+ idempotencyKey?: string;
1240
+ metadata?: Metadata;
1241
+ }): Promise<AgentId>;
1242
+ updateAgentConfig(agentId: AgentId, config: AgentConfig, options: {
1243
+ idempotencyKey: string;
1244
+ }): Promise<void>;
1245
+ start(agentId: AgentId, input: UserInput, options: {
1246
+ idempotencyKey: string;
1247
+ metadata?: Metadata;
1248
+ }): Promise<AgentRun>;
1249
+ run(runId: RunId): AgentRun;
1250
+ listAgents(input?: {
1251
+ after?: AgentListCursor;
1252
+ limit?: number;
1253
+ }): Promise<Page<AgentSummary, AgentListCursor>>;
1254
+ listRuns(input?: {
1255
+ agentId?: AgentId;
1256
+ states?: readonly RunState[];
1257
+ after?: RunListCursor;
1258
+ limit?: number;
1259
+ }): Promise<Page<RunSummary, RunListCursor>>;
1260
+ consume(input: {
1261
+ consumerId: string;
1262
+ signal: AbortSignal;
1263
+ onEvent(event: DurableRunEvent, context: Readonly<{
1264
+ signal: AbortSignal;
1265
+ }>): void | Promise<void>;
1266
+ }): Promise<DurableConsumer>;
1267
+ close(): Promise<void>;
1268
+ snapshot(runId: RunId): Promise<RunSnapshot>;
1269
+ respond(runId: RunId, input: {
1270
+ requestId: InputRequestId;
1271
+ input: UserInput;
1272
+ }): Promise<void>;
1273
+ cancel(runId: RunId, reason?: string): Promise<RunBoundary>;
1274
+ private pump;
1275
+ private execute;
1276
+ private failQueued;
1277
+ private executeTool;
1278
+ private requireAgent;
1279
+ private runConsumer;
1280
+ observe(runId: RunId, options?: {
1281
+ after?: EventCursor;
1282
+ signal?: AbortSignal;
1283
+ }): AsyncIterable<DurableRunEvent>;
1284
+ wait(runId: RunId, options?: {
1285
+ signal?: AbortSignal;
1286
+ }): Promise<RunBoundary>;
1287
+ private assertOpen;
1288
+ private startHeartbeat;
1289
+ }
1603
1290
 
1604
- declare class InMemoryRuntimeStateStore implements RuntimeStateStore {
1291
+ type IdempotencyReceipt = {
1292
+ payload: string;
1293
+ result: unknown;
1294
+ };
1295
+ type InMemoryStoreState = Readonly<{
1296
+ incarnation: string;
1297
+ agents: readonly AgentRecord[];
1298
+ runs: readonly RunRecord[];
1299
+ messages: readonly Message[];
1300
+ toolCalls: readonly ToolCallSnapshot[];
1301
+ events: readonly DurableRunEvent[];
1302
+ idempotency: readonly (readonly [string, IdempotencyReceipt])[];
1303
+ operationReceipts: readonly (readonly [string, IdempotencyReceipt])[];
1304
+ consumerCheckpoints: readonly (readonly [string, EventCursor])[];
1305
+ nextAgentSequence: readonly (readonly [AgentId, number])[];
1306
+ nextReadySequence: readonly (readonly [AgentId, number])[];
1307
+ eventSequence: number;
1308
+ }>;
1309
+ declare class InMemoryStore implements DurableStore {
1310
+ private readonly incarnation;
1605
1311
  private readonly agents;
1606
- private readonly messages;
1607
1312
  private readonly runs;
1313
+ private readonly messages;
1608
1314
  private readonly toolCalls;
1609
1315
  private readonly events;
1610
- private readonly eventCheckpoints;
1611
- createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1612
- getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1613
- getAgentBySessionId(sessionId: string): Promise<AgentRecord | undefined>;
1614
- listAgents(): Promise<AgentRecord[]>;
1615
- setAgentState(agentId: AgentId, state: AgentRecord["state"]): Promise<AgentRecord>;
1616
- setAgentLifecycleState(agentId: AgentId, state: AgentRecord["lifecycleState"]): Promise<AgentRecord>;
1617
- deleteAgentData(agentId: AgentId): Promise<void>;
1618
- enqueueAgentInput(input: EnqueueAgentInput): Promise<EnqueuedAgentInput>;
1619
- private enqueueAgentInputState;
1620
- getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1621
- getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1622
- listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1623
- listActiveRuns(): Promise<AgentRunRecord[]>;
1624
- leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1625
- renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1626
- suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1627
- completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1628
- retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1629
- exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1630
- abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1631
- recoverExpiredLeases(input?: Date): Promise<AgentRunRecord[]>;
1632
- recoverLeases(): Promise<AgentRunRecord[]>;
1633
- createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1634
- startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1635
- completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1636
- markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1637
- getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1638
- listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1639
- recordEvent(input: RecordRuntimeEventInput | RuntimeEventKind, related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">, payload?: unknown): Promise<RuntimeEvent>;
1640
- getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1641
- acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1642
- acknowledgeEventAndEnqueueAgentInput(input: AcknowledgeEventAndEnqueueAgentInput): Promise<AcknowledgeEventAndEnqueueAgentInputResult>;
1316
+ private readonly idempotency;
1317
+ private readonly operationReceipts;
1318
+ private readonly consumerCheckpoints;
1319
+ private readonly nextAgentSequence;
1320
+ private readonly nextReadySequence;
1321
+ private owner?;
1322
+ private ownerEpoch;
1323
+ private eventSequence;
1324
+ constructor(options?: {
1325
+ incarnation?: string;
1326
+ });
1327
+ static fromState(state: InMemoryStoreState): InMemoryStore;
1328
+ exportState(): InMemoryStoreState;
1329
+ attachOwner(lease: OwnerLease): void;
1330
+ interruptOwner(ownerEpoch: number, message?: string): void;
1331
+ openOwner(input: {
1332
+ ownerId: string;
1333
+ leaseMs: number;
1334
+ }): Promise<OwnedStore>;
1335
+ assertOwner(lease: OwnerLease): void;
1336
+ renewOwner(lease: OwnerLease, leaseMs: number): OwnerLease;
1337
+ releaseOwner(lease: OwnerLease): void;
1338
+ reserveAgent(lease: OwnerLease, input: {
1339
+ idempotencyKey: string;
1340
+ metadata?: Metadata;
1341
+ configIdentity?: string;
1342
+ }): AgentRecord;
1343
+ activateAgent(lease: OwnerLease, agentId: AgentId, configToken?: ConfigToken, configIdentity?: string): AgentRecord;
1344
+ updateAgentConfigToken(lease: OwnerLease, input: {
1345
+ agentId: AgentId;
1346
+ token: ConfigToken;
1347
+ configIdentity?: string;
1348
+ idempotencyKey: string;
1349
+ }): AgentRecord;
1350
+ createRun(lease: OwnerLease, input: {
1351
+ agentId: AgentId;
1352
+ input: UserInput;
1353
+ metadata?: Metadata;
1354
+ idempotencyKey: string;
1355
+ }): RunRecord;
1356
+ claimRun(lease: OwnerLease, input: {
1357
+ runId: RunId;
1358
+ expectedRevision: number;
1359
+ executionId?: ExecutionId;
1360
+ messageId?: MessageId;
1361
+ configToken?: ConfigToken;
1362
+ }): RunClaim;
1363
+ failQueuedRun(lease: OwnerLease, input: {
1364
+ runId: RunId;
1365
+ expectedRevision: number;
1366
+ failure: Extract<RunFailure, {
1367
+ code: "configuration_unavailable" | "checkpoint_incompatible";
1368
+ }>;
1369
+ }): RunRecord;
1370
+ commitInputRequired(lease: OwnerLease, input: {
1371
+ runId: RunId;
1372
+ execution: ExecutionToken;
1373
+ expectedRevision: number;
1374
+ requestId?: InputRequestId;
1375
+ prompt: AssistantMessage;
1376
+ checkpoint: ExecutionCheckpoint;
1377
+ }): InputRequiredCommit;
1378
+ answerInput(lease: OwnerLease, input: {
1379
+ runId: RunId;
1380
+ requestId: InputRequestId;
1381
+ expectedRevision: number;
1382
+ input: UserInput;
1383
+ messageId?: MessageId;
1384
+ }): RunRecord;
1385
+ reserveToolCall(lease: OwnerLease, input: {
1386
+ runId: RunId;
1387
+ execution: ExecutionToken;
1388
+ expectedRevision: number;
1389
+ requestMessageId: MessageId;
1390
+ name: string;
1391
+ args: JsonValue;
1392
+ toolCallId?: ToolCallId;
1393
+ }): ToolCommit;
1394
+ startToolCall(lease: OwnerLease, input: {
1395
+ runId: RunId;
1396
+ execution: ExecutionToken;
1397
+ expectedRevision: number;
1398
+ toolCallId: ToolCallId;
1399
+ }): ToolCommit;
1400
+ commitToolResult(lease: OwnerLease, input: {
1401
+ runId: RunId;
1402
+ execution: ExecutionToken;
1403
+ expectedRevision: number;
1404
+ toolCallId: ToolCallId;
1405
+ result: ToolExecutionResult;
1406
+ state: "completed" | "failed" | "indeterminate";
1407
+ reason?: string;
1408
+ }): ToolCommit;
1409
+ commitOutcome(lease: OwnerLease, input: {
1410
+ runId: RunId;
1411
+ execution: ExecutionToken;
1412
+ expectedRevision: number;
1413
+ outcome?: Outcome;
1414
+ failure?: RunFailure;
1415
+ output?: AssistantMessage;
1416
+ }): RunRecord;
1417
+ cancelRun(lease: OwnerLease, input: {
1418
+ runId: RunId;
1419
+ expectedRevision?: number;
1420
+ reason?: string;
1421
+ }): RunRecord;
1422
+ snapshotRun(lease: OwnerLease, runId: RunId): RunSnapshot;
1423
+ listAgents(lease: OwnerLease): readonly AgentRecord[];
1424
+ listRuns(lease: OwnerLease, input?: {
1425
+ agentId?: AgentId;
1426
+ states?: readonly RunState[];
1427
+ }): readonly RunRecord[];
1428
+ listEvents(lease: OwnerLease, input?: {
1429
+ after?: EventCursor;
1430
+ }): readonly DurableRunEvent[];
1431
+ openConsumer(lease: OwnerLease, consumerId: string): ConsumerRegistration;
1432
+ advanceConsumerCheckpoint(lease: OwnerLease, input: {
1433
+ consumerId: string;
1434
+ cursor: EventCursor;
1435
+ }): void;
1436
+ private replay;
1437
+ private writeReceipt;
1438
+ private replayOperation;
1439
+ private writeOperationReceipt;
1643
1440
  private requireAgent;
1644
- private requireMessage;
1645
1441
  private requireRun;
1646
1442
  private requireToolCall;
1647
- private recordEventInternal;
1443
+ private assertNoOpenTools;
1444
+ private interruptToolCall;
1445
+ private assertState;
1446
+ private assertRevision;
1447
+ private assertExecution;
1448
+ private nextSequence;
1449
+ private nextReady;
1450
+ private nextMessageSequence;
1451
+ private messagesForRun;
1452
+ private history;
1453
+ private appendMessage;
1454
+ private appendTransition;
1455
+ private appendToolTransition;
1456
+ private baseEvent;
1457
+ private cursorForRun;
1458
+ private parseCursor;
1648
1459
  }
1649
1460
 
1650
- declare class SqliteRuntimeStateStore implements RuntimeStateStore {
1461
+ declare class SqliteStore implements DurableStore {
1651
1462
  private readonly database;
1463
+ private closed;
1464
+ private configured;
1652
1465
  constructor(filename?: string);
1466
+ openOwner(input: {
1467
+ ownerId: string;
1468
+ leaseMs: number;
1469
+ }): Promise<OwnedStore>;
1653
1470
  close(): void;
1654
- createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1655
- getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1656
- getAgentBySessionId(sessionId: string): Promise<AgentRecord | undefined>;
1657
- listAgents(): Promise<AgentRecord[]>;
1658
- setAgentState(agentId: AgentId, state: AgentRecord["state"]): Promise<AgentRecord>;
1659
- setAgentLifecycleState(agentId: AgentId, state: AgentRecord["lifecycleState"]): Promise<AgentRecord>;
1660
- deleteAgentData(agentId: AgentId): Promise<void>;
1661
- enqueueAgentInput(input: EnqueueAgentInput): Promise<EnqueuedAgentInput>;
1662
- private enqueueAgentInputState;
1663
- getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1664
- getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1665
- listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1666
- listActiveRuns(): Promise<AgentRunRecord[]>;
1667
- leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1668
- renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1669
- suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1670
- completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1671
- retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1672
- exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1673
- abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1674
- recoverExpiredLeases(input?: Date): Promise<AgentRunRecord[]>;
1675
- recoverLeases(): Promise<AgentRunRecord[]>;
1676
- createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1677
- startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1678
- completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1679
- markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1680
- getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1681
- listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1682
- recordEvent(input: RecordRuntimeEventInput | RuntimeEventKind, related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">, payload?: unknown): Promise<RuntimeEvent>;
1683
- getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1684
- acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1685
- acknowledgeEventAndEnqueueAgentInput(input: AcknowledgeEventAndEnqueueAgentInput): Promise<AcknowledgeEventAndEnqueueAgentInputResult>;
1686
- private acknowledgeEventState;
1687
- private insertMessage;
1688
- private agentFromRow;
1689
- private messageFromRow;
1690
- private runFromRow;
1691
- private eventFromRow;
1692
- private toolCallFromRow;
1693
- private messageRow;
1694
- private runRow;
1695
- private requireAgent;
1696
- private requireMessage;
1697
- private requireRun;
1698
- private requireToolCall;
1699
- private requireEvent;
1700
- private eventCheckpoint;
1701
- private recordEventInternal;
1471
+ reserveAgent(lease: OwnerLease, input: {
1472
+ idempotencyKey: string;
1473
+ metadata?: Metadata;
1474
+ configIdentity?: string;
1475
+ }): Promise<AgentRecord>;
1476
+ activateAgent(lease: OwnerLease, agentId: AgentId, configToken?: ConfigToken, configIdentity?: string): Promise<AgentRecord>;
1477
+ updateAgentConfigToken(lease: OwnerLease, input: {
1478
+ agentId: AgentId;
1479
+ token: ConfigToken;
1480
+ configIdentity?: string;
1481
+ idempotencyKey: string;
1482
+ }): Promise<AgentRecord>;
1483
+ createRun(lease: OwnerLease, input: {
1484
+ agentId: AgentId;
1485
+ input: UserInput;
1486
+ metadata?: Metadata;
1487
+ idempotencyKey: string;
1488
+ }): Promise<RunRecord>;
1489
+ claimRun(lease: OwnerLease, input: {
1490
+ runId: RunId;
1491
+ expectedRevision: number;
1492
+ executionId?: ExecutionId;
1493
+ messageId?: MessageId;
1494
+ configToken?: ConfigToken;
1495
+ }): Promise<RunClaim>;
1496
+ failQueuedRun(lease: OwnerLease, input: {
1497
+ runId: RunId;
1498
+ expectedRevision: number;
1499
+ failure: Extract<RunFailure, {
1500
+ code: "configuration_unavailable" | "checkpoint_incompatible";
1501
+ }>;
1502
+ }): Promise<RunRecord>;
1503
+ commitInputRequired(lease: OwnerLease, input: {
1504
+ runId: RunId;
1505
+ execution: ExecutionToken;
1506
+ expectedRevision: number;
1507
+ requestId?: InputRequestId;
1508
+ prompt: AssistantMessage;
1509
+ checkpoint: ExecutionCheckpoint;
1510
+ }): Promise<InputRequiredCommit>;
1511
+ answerInput(lease: OwnerLease, input: {
1512
+ runId: RunId;
1513
+ requestId: InputRequestId;
1514
+ expectedRevision: number;
1515
+ input: UserInput;
1516
+ messageId?: MessageId;
1517
+ }): Promise<RunRecord>;
1518
+ commitOutcome(lease: OwnerLease, input: {
1519
+ runId: RunId;
1520
+ execution: ExecutionToken;
1521
+ expectedRevision: number;
1522
+ outcome?: Outcome;
1523
+ failure?: RunFailure;
1524
+ output?: AssistantMessage;
1525
+ }): Promise<RunRecord>;
1526
+ reserveToolCall(lease: OwnerLease, input: {
1527
+ runId: RunId;
1528
+ execution: ExecutionToken;
1529
+ expectedRevision: number;
1530
+ requestMessageId: MessageId;
1531
+ name: string;
1532
+ args: JsonValue;
1533
+ toolCallId?: ToolCallId;
1534
+ }): Promise<ToolCommit>;
1535
+ startToolCall(lease: OwnerLease, input: {
1536
+ runId: RunId;
1537
+ execution: ExecutionToken;
1538
+ expectedRevision: number;
1539
+ toolCallId: ToolCallId;
1540
+ }): Promise<ToolCommit>;
1541
+ commitToolResult(lease: OwnerLease, input: {
1542
+ runId: RunId;
1543
+ execution: ExecutionToken;
1544
+ expectedRevision: number;
1545
+ toolCallId: ToolCallId;
1546
+ result: ToolExecutionResult;
1547
+ state: "completed" | "failed" | "indeterminate";
1548
+ reason?: string;
1549
+ }): Promise<ToolCommit>;
1550
+ cancelRun(lease: OwnerLease, input: {
1551
+ runId: RunId;
1552
+ expectedRevision?: number;
1553
+ reason?: string;
1554
+ }): Promise<RunRecord>;
1555
+ snapshotRun(lease: OwnerLease, runId: RunId): Promise<RunSnapshot>;
1556
+ listAgents(lease: OwnerLease): Promise<readonly AgentRecord[]>;
1557
+ listRuns(lease: OwnerLease, input?: {
1558
+ agentId?: AgentId;
1559
+ states?: readonly RunState[];
1560
+ }): Promise<readonly RunRecord[]>;
1561
+ listEvents(lease: OwnerLease, input?: {
1562
+ after?: EventCursor;
1563
+ }): Promise<readonly DurableRunEvent[]>;
1564
+ openConsumer(lease: OwnerLease, consumerId: string): Promise<ConsumerRegistration>;
1565
+ advanceConsumerCheckpoint(lease: OwnerLease, input: {
1566
+ consumerId: string;
1567
+ cursor: EventCursor;
1568
+ }): Promise<void>;
1569
+ renewOwner(lease: OwnerLease, leaseMs: number): Promise<OwnerLease>;
1570
+ sealAndReleaseOwner(lease: OwnerLease): Promise<void>;
1571
+ private invoke;
1572
+ private ensureSchema;
1573
+ private isCurrentSchema;
1574
+ private configure;
1575
+ private catalog;
1576
+ private readOwner;
1577
+ private writeOwner;
1578
+ private readState;
1579
+ private writeState;
1580
+ private persistState;
1581
+ private requireMatchingOwner;
1582
+ private immediateTransaction;
1583
+ private assertOpen;
1584
+ }
1585
+
1586
+ /** A deterministic provider for tests and embedded hosts without a separate registry. */
1587
+ declare class InMemoryConfigProvider implements ConfigProvider {
1588
+ private readonly entries;
1589
+ private readonly operations;
1590
+ put(input: {
1591
+ agentId: AgentId;
1592
+ agentMetadata?: Metadata;
1593
+ config: AgentConfig;
1594
+ operationId: string;
1595
+ signal: AbortSignal;
1596
+ }): Promise<ConfigPutResult>;
1597
+ resolve(input: {
1598
+ agentId: AgentId;
1599
+ agentMetadata?: Metadata;
1600
+ token: ConfigToken;
1601
+ signal: AbortSignal;
1602
+ }): Promise<ConfigResolution>;
1702
1603
  }
1604
+ declare function brandConfigToken(raw: unknown): ConfigToken;
1605
+
1606
+ type RuntimeErrorCode = "invalid_argument" | "runtime_closed" | "runtime_already_owned" | "runtime_ownership_lost" | "agent_not_found" | "run_not_found" | "run_state_conflict" | "input_request_conflict" | "idempotency_conflict" | "configuration_unavailable" | "checkpoint_incompatible" | "consumer_already_active" | "invalid_cursor" | "store_unavailable" | "unsupported_store_version";
1607
+ type RuntimeErrorDetails = {
1608
+ invalid_argument: Readonly<{
1609
+ argument: string;
1610
+ reason: string;
1611
+ }>;
1612
+ runtime_closed: null;
1613
+ runtime_already_owned: Readonly<{
1614
+ expiresAt: string;
1615
+ retryAfterMs: number;
1616
+ }>;
1617
+ runtime_ownership_lost: Readonly<{
1618
+ reason: "expired" | "released" | "epoch_advanced";
1619
+ expectedEpoch: number;
1620
+ actualEpoch: number;
1621
+ expiresAt?: string;
1622
+ }>;
1623
+ agent_not_found: Readonly<{
1624
+ agentId: AgentId;
1625
+ }>;
1626
+ run_not_found: Readonly<{
1627
+ runId: RunId;
1628
+ }>;
1629
+ run_state_conflict: Readonly<{
1630
+ runId: RunId;
1631
+ expected: readonly RunState[];
1632
+ actual: RunState;
1633
+ }>;
1634
+ input_request_conflict: Readonly<{
1635
+ runId: RunId;
1636
+ requestId: InputRequestId;
1637
+ reason: "not_found" | "wrong_run" | "different_answer";
1638
+ }>;
1639
+ idempotency_conflict: Readonly<{
1640
+ scope: "create_agent" | "update_agent_config" | "start_run";
1641
+ idempotencyKey: string;
1642
+ }>;
1643
+ configuration_unavailable: Readonly<{
1644
+ agentId: AgentId;
1645
+ runId?: RunId;
1646
+ retryable: boolean;
1647
+ reason: string;
1648
+ }>;
1649
+ checkpoint_incompatible: Readonly<{
1650
+ runId: RunId;
1651
+ expected: Readonly<{
1652
+ codec: string;
1653
+ versions: readonly number[];
1654
+ }>;
1655
+ actual: Readonly<{
1656
+ codec: string;
1657
+ version: number;
1658
+ }>;
1659
+ }>;
1660
+ consumer_already_active: Readonly<{
1661
+ consumerId: string;
1662
+ }>;
1663
+ invalid_cursor: Readonly<{
1664
+ cursorType: "agent_list" | "run_list" | "event";
1665
+ reason: "malformed" | "wrong_store" | "wrong_collection" | "filter_mismatch" | "beyond_waterline";
1666
+ }>;
1667
+ store_unavailable: Readonly<{
1668
+ operation: string;
1669
+ retryable: boolean;
1670
+ reason: string;
1671
+ }>;
1672
+ unsupported_store_version: Readonly<{
1673
+ found: string | null;
1674
+ supported: string;
1675
+ }>;
1676
+ };
1677
+ type AnyRuntimeError = {
1678
+ [Code in RuntimeErrorCode]: RuntimeError<Code>;
1679
+ }[RuntimeErrorCode];
1680
+ declare class RuntimeError<Code extends RuntimeErrorCode = RuntimeErrorCode> extends Error {
1681
+ readonly code: Code;
1682
+ readonly details: RuntimeErrorDetails[Code];
1683
+ constructor(code: Code, details: RuntimeErrorDetails[Code], message?: Code);
1684
+ }
1685
+ declare function isRuntimeError(value: unknown): value is AnyRuntimeError;
1686
+
1687
+ declare function loadSkills(targetPath: string): Promise<Skill[]>;
1688
+
1689
+ /**
1690
+ * Load all phases from the target directory.
1691
+ *
1692
+ * Scans for subdirectories containing PHASE.md files.
1693
+ * Returns PhaseRegistry with entryPhaseId:
1694
+ * - null by default (caller must explicitly set to start from a specific phase)
1695
+ * - Set to a specific phase name to start from that phase
1696
+ *
1697
+ * When entryPhaseId is null, Agent normalizes the registry to start from its default phase.
1698
+ */
1699
+ declare function loadPhases(targetPath: string): Promise<PhaseRegistry>;
1700
+
1701
+ /**
1702
+ * Extension loader — discovers and loads extensions from the filesystem.
1703
+ *
1704
+ * Uses the new LoadedExtension type that works with ExtensionRunner.
1705
+ */
1706
+
1707
+ /**
1708
+ * Load extensions from the exact target path.
1709
+ *
1710
+ * If the target is a directory with its own extension entry, load that extension.
1711
+ * Otherwise, scan its immediate children for extension packages/files.
1712
+ */
1713
+ declare function loadExtensionsFromPath(path: string): Promise<{
1714
+ extensions: LoadedExtension[];
1715
+ errors: Array<{
1716
+ path: string;
1717
+ error: string;
1718
+ }>;
1719
+ }>;
1720
+
1721
+ declare function createCoreTools(input?: CoreToolContext): Tool[];
1703
1722
 
1704
- export { type AfterToolCall, Agent, type AgentContext, type AgentId, type AgentInputRequest, type AgentOptions, AgentRun, type AgentRunExecutionState, type AgentRunId, type AgentRunListener, type AgentRunMetadata, type AgentRunRecord, type AgentRunState, AgentRuntime, type AgentRuntimeOptions, type BeforeToolCall, type CoreToolContext, type ExecutionTurn, type ExtensionAPI, type ExtensionFactory, type HookEvent, type HookEventType, type HookHandler, InMemoryRuntimeStateStore, InMemorySessionStore, JsonlSessionStore, type LoadExtensionsResult, type LoadedExtension, type LoopMetrics, type ModelTranscript, type Phase, type PhaseContext, type PhaseExecution, type PhaseInvocation, type PhaseOutput, type PhaseRegistration, type PhaseRegistry, type PhaseState, type RuntimeEvent, type RuntimeEventConsumer, type RuntimeEventCursor, type RuntimeEventDisposition, type RuntimeEventKind, type RuntimeEventListener, type RuntimeMessage, type RuntimeMessageId, type RuntimeSessionSummary, type RuntimeToolCall, type RuntimeToolCallId, type SessionLifecycleState, type SessionManagerProvider, SqliteRuntimeStateStore, type Tool, type ToolContext, type ToolDefinition, type ToolExecutionMode, type ToolExecutionResult, type ToolRuntimePolicy, type Unsubscribe, createCoreTools, createMessage };
1723
+ export { type AfterToolCall, type AgentConfig, type AgentDefinitionContext, type AgentId, type AgentListCursor, type AgentRecord, type AgentRun, AgentRuntime, type AgentRuntimeOptions, type AgentSummary, type AnyRuntimeError, type AssistantContent, type AssistantMessage, type BeforeToolCall, type ConfigProvider, type ConfigPutResult, type ConfigResolution, type ConfigToken, type CoreToolContext, type DurableConsumer, type DurableRunEvent, type DurableStore, type DurableToolResult, type EventCursor, type EventId, type ExecutionCheckpoint, type ExecutionId, type ExecutionToken, type ExtensionAPI, type ExtensionFactory, type HookEvent, type HookEventType, type HookHandler, InMemoryConfigProvider, InMemoryStore, type InputRequest, type InputRequestId, type InputRequiredCommit, type JsonObject, type JsonPrimitive, type JsonValue, type LoadExtensionsResult, type LoadedExtension, type Message, type MessageBase, type MessageCommitted, type MessageContent, type MessageId, type Metadata, type OpaqueId, type Outcome, type OwnerLease, type OwnerToken, type Page, type Phase, type PhaseContext, type PhaseInvocation, type PhaseOutput, type PhaseRegistry, type PhaseState, type RunBoundary, type RunClaim, type RunFailure, type RunId, type RunListCursor, type RunRecord, type RunSnapshot, type RunState, type RunSummary, type RunTransitioned, RuntimeError, type RuntimeErrorCode, type RuntimeErrorDetails, type Skill, SqliteStore, type TextContent, type ThinkingContent, type Tool, type ToolCallId, type ToolCallSnapshot, type ToolCallState, type ToolDefinition, type ToolExecutionResult, type ToolInvocationContext, type ToolMessage, type ToolMessageContent, type ToolResultContent, type ToolStateChanged, type ToolUseContent, type UserContent, type UserInput, type UserMessage, brandConfigToken, createCoreTools, isRuntimeError, loadExtensionsFromPath as loadExtensions, loadPhases, loadSkills };