@rowan-agent/agent 0.5.6 → 0.6.1

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 +338 -326
  2. package/dist/index.d.ts +758 -914
  3. package/dist/index.js +2551 -557
  4. package/package.json +4 -5
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _rowan_agent_models from '@rowan-agent/models';
2
- import { LlmRequest, LlmResponse, LlmModelRef, LlmModelUsage, AgentMessage, ContentBlock, ToolCall, ToolResult, Outcome, ProviderConfig, Skill as Skill$1, StreamFn, AgentEventListener, Protocol, ModelCost, AgentEvent, LlmMessage } from '@rowan-agent/models';
3
- export { AgentEvent, AgentEventListener, AgentMessage, LlmModelRef, Outcome, Skill, StreamFn, ToolResult, createDispatchStream, registerBuiltInApiProviders } 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
4
  import Type from 'typebox';
5
5
 
6
6
  type ExecutionTurn = {
@@ -10,19 +10,241 @@ type ExecutionTurn = {
10
10
  phase: string;
11
11
  requestedAtMs: number;
12
12
  completedAtMs: number;
13
- model: LlmModelRef;
13
+ model: ModelRef;
14
14
  usage?: LlmModelUsage;
15
15
  };
16
- type StepFilter = {
17
- phase?: string;
18
- afterMs?: number;
19
- };
20
16
  /** Raw model input/output for session persistence. */
21
17
  type ModelTranscript = {
22
18
  request: LlmRequest;
23
19
  response: LlmResponse;
24
20
  };
25
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 RuntimeMessageState = "queued" | "leased" | "acknowledged" | "dead_lettered";
34
+ type AgentRunState = "queued" | "running" | "suspended" | "completed" | "failed" | "cancelled";
35
+ /** Opaque execution checkpoint owned by the Agent loop and persisted by Runtime. */
36
+ type AgentRunExecutionState = Readonly<Record<string, unknown>>;
37
+ /** Host-owned correlation data persisted with a Run and echoed by Runtime Events. */
38
+ type AgentRunMetadata = Readonly<Record<string, unknown>>;
39
+ type AgentInputRequest = {
40
+ phase: string;
41
+ prompt: string;
42
+ requestedAt: string;
43
+ };
44
+ type RuntimeToolCallState = "queued" | "running" | "completed" | "failed" | "indeterminate";
45
+ type AgentRecord = {
46
+ id: AgentId;
47
+ sessionId: string;
48
+ state: AgentLifecycleState;
49
+ createdAt: string;
50
+ updatedAt: string;
51
+ };
52
+ type RuntimeLease = {
53
+ id: LeaseId;
54
+ runId: AgentRunId;
55
+ workerId: string;
56
+ leasedAt: string;
57
+ expiresAt: string;
58
+ };
59
+ type RuntimeMessage = {
60
+ id: RuntimeMessageId;
61
+ agentId: AgentId;
62
+ kind: "agent_input";
63
+ input: AgentMessage;
64
+ state: RuntimeMessageState;
65
+ attempts: number;
66
+ runId?: AgentRunId;
67
+ lease?: RuntimeLease;
68
+ deadLetterReason?: string;
69
+ createdAt: string;
70
+ updatedAt: string;
71
+ };
72
+ type AgentRunRecord = {
73
+ id: AgentRunId;
74
+ agentId: AgentId;
75
+ messageId: RuntimeMessageId;
76
+ state: AgentRunState;
77
+ attempt: number;
78
+ leaseId?: LeaseId;
79
+ outcome?: Outcome;
80
+ suspensionReason?: string;
81
+ inputRequest?: AgentInputRequest;
82
+ executionState?: AgentRunExecutionState;
83
+ metadata?: AgentRunMetadata;
84
+ createdAt: string;
85
+ updatedAt: string;
86
+ };
87
+ type RuntimeEventKind = "agent_created" | "agent_paused" | "agent_resumed" | "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";
88
+ type RuntimeEvent = {
89
+ id: RuntimeEventId;
90
+ sequence: number;
91
+ kind: RuntimeEventKind;
92
+ agentId?: AgentId;
93
+ messageId?: RuntimeMessageId;
94
+ runId?: AgentRunId;
95
+ toolCallId?: RuntimeToolCallId;
96
+ payload?: unknown;
97
+ createdAt: string;
98
+ };
99
+ type RuntimeEventCursor = {
100
+ after?: RuntimeEventId;
101
+ limit?: number;
102
+ };
103
+ type RuntimeEventCheckpoint = {
104
+ consumerId: string;
105
+ sequence: number;
106
+ eventId?: RuntimeEventId;
107
+ updatedAt: string;
108
+ };
109
+ type RuntimeToolCall = {
110
+ id: RuntimeToolCallId;
111
+ agentId: AgentId;
112
+ runId: AgentRunId;
113
+ name: string;
114
+ args: unknown;
115
+ state: RuntimeToolCallState;
116
+ result?: ToolResult;
117
+ indeterminateReason?: string;
118
+ createdAt: string;
119
+ updatedAt: string;
120
+ };
121
+
122
+ type BeforePhaseHook = (phaseId: string, input: PhaseContext) => Promise<BeforePhaseHookResult>;
123
+ type AfterPhaseHook = (phaseId: string, output: PhaseOutput) => Promise<AfterPhaseHookResult>;
124
+ type BeforePromptHook = (phaseId: string, input: PhaseContext) => Promise<PhaseContext>;
125
+ type LoopMetrics = {
126
+ /** Number of phase iterations executed. */
127
+ iterations: number;
128
+ /** Phase transition history. */
129
+ phaseTransitions: Array<{
130
+ from: string;
131
+ to: string;
132
+ ts: string;
133
+ }>;
134
+ /** Number of times compaction was triggered. */
135
+ compactionCount: number;
136
+ /** Number of retry attempts due to transient errors. */
137
+ retryCount: number;
138
+ /** Loop start timestamp. */
139
+ startedAt: string;
140
+ /** Loop start time as epoch ms (for duration calculation). */
141
+ startedAtMs: number;
142
+ /** Loop end timestamp (set on completion). */
143
+ endedAt?: string;
144
+ /** Total wall-clock duration in ms. */
145
+ durationMs?: number;
146
+ };
147
+ type SessionState = {
148
+ currentPhase: string;
149
+ attempt: number;
150
+ metrics: LoopMetrics;
151
+ status: "idle" | "running" | "suspended" | "completed" | "aborted" | "failed";
152
+ continuation?: SessionContinuationState;
153
+ };
154
+ type SessionContinuationState = {
155
+ isContinuing: boolean;
156
+ previousPayload?: unknown;
157
+ previousResults: Array<{
158
+ name: string;
159
+ output?: unknown;
160
+ }>;
161
+ pendingInstruction?: string;
162
+ previousPhaseMessageId?: string;
163
+ };
164
+ type AgentConfig = {
165
+ model: ModelRef;
166
+ stream: StreamFn;
167
+ context: AgentContext;
168
+ sessionId?: string;
169
+ sessionState?: SessionState;
170
+ maxAttempts?: number;
171
+ runtime?: AgentRuntimePort;
172
+ emit?: AgentEventListener;
173
+ signal?: AbortSignal;
174
+ beforeToolCall?: BeforeToolCall;
175
+ afterToolCall?: AfterToolCall;
176
+ beforePhase?: BeforePhaseHook;
177
+ afterPhase?: AfterPhaseHook;
178
+ beforePrompt?: BeforePromptHook;
179
+ onModelTranscript?: (transcript: ModelTranscript, meta: {
180
+ phase: string;
181
+ model: ModelRef;
182
+ }) => Promise<void>;
183
+ onMessage?: (message: AgentMessage) => Promise<void>;
184
+ onOutcome?: (outcome: Outcome) => Promise<void>;
185
+ /** Internal: await next user messages before retrying the same phase. */
186
+ waitForInput?: (state?: SessionState, inputRequest?: AgentInputRequest) => Promise<AgentMessage[]>;
187
+ };
188
+ type ToolRunnerInput = {
189
+ config: AgentConfig;
190
+ toolCall: ToolCall;
191
+ };
192
+ type ToolRunner = (input: ToolRunnerInput) => Promise<ToolResult>;
193
+ type AgentRuntimePort = {
194
+ tools?: ToolRunner;
195
+ };
196
+
197
+ type ToolContext = Pick<AgentContext, "skills"> & {
198
+ toolCallId: string;
199
+ };
200
+ type ToolExecutionMode = "sequential" | "parallel";
201
+ type Tool<TArgs = unknown> = {
202
+ name: string;
203
+ description: string;
204
+ parameters: Type.TSchema;
205
+ /** One-line snippet shown in the system prompt tool list. */
206
+ promptSnippet?: string;
207
+ /** Additional guidelines appended to the system prompt when this tool is active. */
208
+ promptGuidelines?: string[];
209
+ /** Whether this tool can run concurrently with others. Default: "parallel". */
210
+ executionMode?: ToolExecutionMode;
211
+ execute(args: TArgs, context: ToolContext, signal?: AbortSignal): Promise<ToolResult>;
212
+ };
213
+ /** Context snapshot passed into the low-level agent loop. */
214
+ type AgentContext = {
215
+ /** System prompt included with the request. */
216
+ systemPrompt: string;
217
+ /** Transcript visible to the model. */
218
+ messages: AgentMessage[];
219
+ /** Tools available for this run. */
220
+ tools: Tool[];
221
+ /** Skills available for this run. */
222
+ skills: Skill$1[];
223
+ /** Custom phases for this run. Agent normalizes this with the built-in default phase. */
224
+ phases?: PhaseRegistry;
225
+ };
226
+ type BeforeToolCall = (input: {
227
+ tool: Tool;
228
+ args: unknown;
229
+ }) => Promise<{
230
+ allow: true;
231
+ } | {
232
+ allow: false;
233
+ reason: string;
234
+ }>;
235
+ type AfterToolCall = (input: {
236
+ tool: Tool;
237
+ result: ToolResult;
238
+ }) => Promise<ToolResult>;
239
+ type RunResult = {
240
+ sessionId: string;
241
+ messages: AgentMessage[];
242
+ outcome: Outcome;
243
+ metrics: LoopMetrics;
244
+ };
245
+ type Unsubscribe = () => void;
246
+ declare function createMessage(role: AgentMessage["role"], content: AgentMessage["content"], metadata?: Record<string, unknown>): AgentMessage;
247
+
26
248
  type ModelInvokeOutput = {
27
249
  text: string;
28
250
  contentBlocks: ContentBlock[];
@@ -46,19 +268,106 @@ type PhaseExecution = {
46
268
  executeTool(context: AgentContext, toolCall: ToolCall): Promise<ToolResult>;
47
269
  };
48
270
 
271
+ /** Unified phase output — model decides routing via route. */
272
+ type PhaseOutput = {
273
+ message: string;
274
+ /** Route to next phase, or "continue" to re-execute current phase, or "stop" to end */
275
+ route: string;
276
+ /** Phase name that produced this output */
277
+ phase?: string;
278
+ /** Tool calls from the model invocation (used by framework for route extraction) */
279
+ toolCalls?: Array<{
280
+ id: string;
281
+ name: string;
282
+ args: unknown;
283
+ }>;
284
+ /** Route reason extracted from route tool call (for hooks to inspect) */
285
+ routeReason?: string;
286
+ /** Structured data from this phase, passed to the next phase */
287
+ payload?: unknown;
288
+ };
289
+ /** Phase machine state — tracks position and inter-phase data */
290
+ interface PhaseState {
291
+ current: string;
292
+ available: string[];
293
+ iterations: number;
294
+ payload?: unknown;
295
+ }
296
+ type PhaseInvocation = {
297
+ mode: "serial";
298
+ instanceId: string;
299
+ } | {
300
+ mode: "parallel";
301
+ instanceId: string;
302
+ groupId: string;
303
+ index: number;
304
+ count: number;
305
+ sourcePhaseId: string;
306
+ };
307
+ /** Everything a phase needs to execute */
308
+ interface PhaseContext {
309
+ systemPrompt: string;
310
+ messages: AgentMessage[];
311
+ /** Phase-filtered tools */
312
+ tools: Tool[];
313
+ /** Phase-filtered skills */
314
+ skills: Skill$1[];
315
+ /** Phase machine state */
316
+ state: PhaseState;
317
+ /** Identity and dispatch metadata for this phase execution */
318
+ readonly invocation: PhaseInvocation;
319
+ /** Additional guideline bullets appended to the system prompt */
320
+ promptGuidelines?: string[];
321
+ /** Text to append after the system prompt */
322
+ appendSystemPrompt?: string;
323
+ }
324
+ /**
325
+ * Loaded Phase object
326
+ */
327
+ interface Phase {
328
+ /** Unique identifier */
329
+ id: string;
330
+ /** Display name */
331
+ name: string;
332
+ /** Description */
333
+ description: string;
334
+ /** Restricted tools (undefined = all tools available) */
335
+ tools?: string[];
336
+ /** Restricted skills (undefined = all skills available) */
337
+ skills?: string[];
338
+ /** Forced next phase */
339
+ target?: string;
340
+ /** Expected input fields (key → description) */
341
+ input?: Record<string, string>;
342
+ /** If true, phase gets a fresh context when executed in parallel */
343
+ isolated?: boolean;
344
+ /** Path to PHASE.md file */
345
+ filePath: string;
346
+ /** Phase directory path */
347
+ baseDir: string;
348
+ /** PHASE.md body content */
349
+ content: string;
350
+ /** Model override for this phase (resolved from frontmatter) */
351
+ model?: ModelRef;
352
+ /** ExtensionAPI factory function (default export pattern) */
353
+ factory?: (api: ExtensionAPI) => Promise<void>;
354
+ /** Direct run function */
355
+ run?: (context: PhaseContext, execution: PhaseExecution) => Promise<PhaseOutput | void>;
356
+ }
357
+ /**
358
+ * Phase registry containing all loaded phases
359
+ */
360
+ interface PhaseRegistry {
361
+ /** Map of phase id to Phase object */
362
+ phases: Map<string, Phase>;
363
+ /** Entry phase id (null until Agent applies its default phase) */
364
+ entryPhaseId: string | null;
365
+ }
366
+
49
367
  /**
50
368
  * Extension types — simplified for the new hook-based system.
51
369
  */
52
370
 
53
- interface SourceInfo {
54
- source: string;
55
- baseDir?: string;
56
- displayName?: string;
57
- }
58
- declare function createSourceInfo(extensionPath: string, options?: {
59
- source?: string;
60
- baseDir?: string;
61
- }): SourceInfo;
62
371
  /** Phase run function type for extensions */
63
372
  type PhaseRun = (context: PhaseContext, execution: PhaseExecution) => Promise<PhaseOutput | void>;
64
373
  /** Phase definition shape used by extensions */
@@ -77,24 +386,6 @@ type PhaseRegistration = Partial<Omit<PhaseDefinition, 'run'>> & {
77
386
  /** Optional execution override — takes over model invocation */
78
387
  run?: PhaseRun;
79
388
  };
80
- type RegisteredPhase = {
81
- definition: PhaseDefinition;
82
- source: {
83
- extensionPath: string;
84
- };
85
- };
86
- type ExtensionPackageManifest = {
87
- rowan?: {
88
- extensions?: string[];
89
- phase?: {
90
- id?: string;
91
- name?: string;
92
- description?: string;
93
- tools?: string[];
94
- skills?: string[];
95
- };
96
- };
97
- };
98
389
  /**
99
390
  * Tool definition for registering LLM-callable tools via `api.registerTool()`.
100
391
  *
@@ -135,28 +426,6 @@ interface ToolExecutionResult {
135
426
  /** Whether this is an error result */
136
427
  isError?: boolean;
137
428
  }
138
- /**
139
- * Registered tool with source metadata.
140
- */
141
- interface RegisteredTool {
142
- definition: ToolDefinition;
143
- sourceInfo: SourceInfo;
144
- }
145
- /**
146
- * Structured extension error with attribution.
147
- */
148
- interface ExtensionError {
149
- /** Path of the extension that caused the error */
150
- extensionPath: string;
151
- /** Event or operation that caused the error */
152
- event: string;
153
- /** Error message */
154
- error: string;
155
- /** Optional stack trace */
156
- stack?: string;
157
- }
158
- /** Error listener callback type. */
159
- type ExtensionErrorListener = (error: ExtensionError) => void;
160
429
  type ExecOptions = {
161
430
  /** Working directory for the command. Defaults to cwd passed to runtime. */
162
431
  cwd?: string;
@@ -185,65 +454,6 @@ type AfterPhaseHookResult = {
185
454
  retry?: PhaseContext;
186
455
  output?: PhaseOutput;
187
456
  };
188
- type HandlerFn = (...args: unknown[]) => Promise<unknown>;
189
- /**
190
- * Loaded extension with all registered items.
191
- * Tracks what each extension registered for attribution and cleanup.
192
- */
193
- interface Extension {
194
- /** Extension path (may be synthetic like `<inline>`) */
195
- path: string;
196
- /** Source info for error messages */
197
- sourceInfo: SourceInfo;
198
- /** Event handlers registered by this extension */
199
- handlers: Map<string, HandlerFn[]>;
200
- /** Tools registered by this extension */
201
- tools: Map<string, RegisteredTool>;
202
- /** Phases registered by this extension */
203
- phases: Map<string, RegisteredPhase>;
204
- }
205
- /**
206
- * Create an Extension object with empty collections.
207
- */
208
- declare function createExtension(extensionPath: string, sourceInfo: SourceInfo): Extension;
209
- /**
210
- * Shared runtime state created by loader, used during registration and runtime.
211
- * All ExtensionAPI instances reference this shared state.
212
- *
213
- * Key features:
214
- * - `invalidate()` / `assertActive()` — prevents stale context usage
215
- * - Pending provider registration queue
216
- * - Shared action implementations replaceable post-bind
217
- */
218
- interface ExtensionRuntime {
219
- /** Throws when this extension instance is stale after runtime replacement. */
220
- assertActive: () => void;
221
- /** Marks this extension instance as stale after runtime replacement or reload. */
222
- invalidate: (message?: string) => void;
223
- /** Provider registrations queued during extension loading, processed when runner binds */
224
- pendingProviderRegistrations: Array<{
225
- name: string;
226
- config: ProviderConfig;
227
- extensionPath: string;
228
- }>;
229
- /**
230
- * Register a provider.
231
- * Before bind(): queues registrations.
232
- * After bind(): calls provider registration directly.
233
- */
234
- registerProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;
235
- /**
236
- * Unregister a provider.
237
- * Before bind(): removes from queue.
238
- * After bind(): calls provider unregistration directly.
239
- */
240
- unregisterProvider: (name: string, extensionPath?: string) => void;
241
- }
242
- /**
243
- * Create an ExtensionRuntime with throwing stubs.
244
- * Runner.bind() replaces these with real implementations.
245
- */
246
- declare function createExtensionRuntime(): ExtensionRuntime;
247
457
  /**
248
458
  * Result of loading extensions from filesystem.
249
459
  * The runner takes these and creates Extension tracking objects.
@@ -308,7 +518,6 @@ interface EventBus {
308
518
  /** Get listener count for an event. */
309
519
  count(event: string): number;
310
520
  }
311
- declare function createEventBus(): EventBus;
312
521
 
313
522
  /**
314
523
  * @module extensions/hooks
@@ -683,108 +892,23 @@ type HookEventType = HookEvent["type"];
683
892
  type HookHandler<K extends HookEventType> = (event: Extract<HookEvent, {
684
893
  type: K;
685
894
  }>) => HookResultMap[K] | Promise<HookResultMap[K]> | void | Promise<void>;
895
+
686
896
  /**
687
- * Hook execution error
897
+ * @module extensions/context
898
+ *
899
+ * Extension context types — runtime state and phase execution context.
900
+ *
901
+ * For ExtensionAPI and createExtensionAPI, see ./api.ts
688
902
  */
689
- declare class HookError extends Error {
690
- /** Event type that caused the error */
691
- readonly eventType: string;
692
- constructor(
693
- /** Event type that caused the error */
694
- eventType: string, message: string, cause?: Error);
695
- }
903
+
696
904
  /**
697
- * Type-safe hook manager.
905
+ * Runtime context available to extensions during event handler execution.
698
906
  *
699
- * ## Usage
907
+ * Provides access to agent state, working directory, and utility methods.
908
+ * Values are resolved lazily via getters, so changes via `runner.bind()` are
909
+ * reflected immediately without recreating the context.
700
910
  *
701
- * ```typescript
702
- * const hooks = new HooksManager();
703
- *
704
- * // Register hook
705
- * hooks.on("before_tool_call", (event) => {
706
- * return { allow: false, reason: "Blocked" };
707
- * });
708
- *
709
- * // Emit event (listen-only)
710
- * await hooks.emit("agent_start", { type: "agent_start", sessionId: "123" });
711
- *
712
- * // Emit event and collect result
713
- * const result = await hooks.emitFirst("before_tool_call", { type: "before_tool_call", tool, args });
714
- * ```
715
- */
716
- declare class HooksManager {
717
- private handlers;
718
- /**
719
- * Register a hook handler.
720
- * Handlers execute in registration order.
721
- *
722
- * @param eventType - Event type
723
- * @param handler - Handler function
724
- */
725
- on<K extends HookEventType>(eventType: K, handler: HookHandler<K>): void;
726
- /**
727
- * Unregister a hook handler.
728
- */
729
- off<K extends HookEventType>(eventType: K, handler: HookHandler<K>): void;
730
- /**
731
- * Clear all handlers, or clear handlers for specified event type.
732
- */
733
- clear(eventType?: HookEventType): void;
734
- /**
735
- * Check if there are handlers registered for specified event type.
736
- */
737
- has(eventType: HookEventType): boolean;
738
- /**
739
- * Get handler count for specified event type.
740
- */
741
- count(eventType: HookEventType): number;
742
- /**
743
- * Emit event (listen-only, ignore return values).
744
- * Errors are collected and thrown.
745
- *
746
- * @param eventType - Event type
747
- * @param event - Event object
748
- */
749
- emit<K extends HookEventType>(eventType: K, event: Extract<HookEvent, {
750
- type: K;
751
- }>): Promise<void>;
752
- /**
753
- * Emit event and return first non-undefined result (short-circuit).
754
- *
755
- * @param eventType - Event type
756
- * @param event - Event object
757
- * @returns First non-undefined result, or undefined
758
- */
759
- emitFirst<K extends HookEventType>(eventType: K, event: Extract<HookEvent, {
760
- type: K;
761
- }>): Promise<HookResultMap[K] | undefined>;
762
- }
763
- /**
764
- * Get global hooks manager instance (singleton).
765
- */
766
- declare function getGlobalHooks(): HooksManager;
767
- /**
768
- * Reset global hooks manager (mainly for testing).
769
- */
770
- declare function resetGlobalHooks(): void;
771
-
772
- /**
773
- * @module extensions/context
774
- *
775
- * Extension context types — runtime state and phase execution context.
776
- *
777
- * For ExtensionAPI and createExtensionAPI, see ./api.ts
778
- */
779
-
780
- /**
781
- * Runtime context available to extensions during event handler execution.
782
- *
783
- * Provides access to agent state, working directory, and utility methods.
784
- * Values are resolved lazily via getters, so changes via `runner.bind()` are
785
- * reflected immediately without recreating the context.
786
- *
787
- * @example
911
+ * @example
788
912
  * ```typescript
789
913
  * api.on("before_tool_call", (event, ctx) => {
790
914
  * console.log(`cwd: ${ctx.cwd}`);
@@ -924,445 +1048,42 @@ interface ExtensionAPI {
924
1048
  * Receives ExtensionAPI for registering hooks, phases, and providers.
925
1049
  */
926
1050
  type ExtensionFactory = (api: ExtensionAPI) => void | Promise<void>;
927
- /**
928
- * @internal
929
- * Create ExtensionAPI instance.
930
- * Works for both extension context (with hooks/runtime/eventBus) and phase context (without).
931
- */
932
- declare function createExtensionAPI(hooks?: HooksManager, _extensionPath?: string, options?: {
933
- registerPhase?: (registration: PhaseRegistration) => void;
934
- registerProvider?: (config: _rowan_agent_models.ProviderConfig) => void;
935
- unregisterProvider?: (name: string) => void;
936
- registerTool?: (tool: ToolDefinition) => void;
937
- context?: ExtensionContext;
938
- manifest?: ExtensionManifest;
939
- phase?: PhaseContext;
940
- session?: AgentContext;
941
- }, runtime?: ExtensionRuntime, eventBus?: EventBus): ExtensionAPI;
942
-
943
- /**
944
- * Extension runner — manages extension loading and hook execution.
945
- *
946
- * Architecture reference: PI's ExtensionRunner
947
- * - Per-extension tracking via Extension objects
948
- * - Shared ExtensionRuntime with invalidate/assertActive
949
- * - Direct `on()` API for hook registration
950
- * - Error listener pattern for structured error handling
951
- * - Tool registration support
952
- */
953
1051
 
954
- type ExtensionRunnerOptions = {
955
- entryPhaseId?: string | null;
956
- cwd?: string;
957
- };
958
1052
  /**
959
- * Manages extensions and provides hooks for the agent loop.
960
- *
961
- * Features:
962
- * - Per-extension tracking (handlers, tools, phases)
963
- * - Shared runtime with lifecycle protection (invalidate/assertActive)
964
- * - Error listener pattern for structured error handling
965
- * - Direct hook API and extension-loaded hook API
966
- * - Tool registration for LLM-callable tools
967
- * - EventBus for inter-extension communication
968
- *
969
- * @example
970
- * ```ts
971
- * const runner = createExtensionRunner();
1053
+ * Load all phases from the target directory.
972
1054
  *
973
- * // Direct hook registration
974
- * const unsub = runner.on("before_tool_call", (event) => {
975
- * return { allow: false, reason: "Blocked" };
976
- * });
977
- *
978
- * // Error handling
979
- * runner.onError((error) => {
980
- * console.error(`Extension error in ${error.extensionPath}:`, error.error);
981
- * });
1055
+ * Scans for subdirectories containing PHASE.md files.
1056
+ * Returns PhaseRegistry with entryPhaseId:
1057
+ * - null by default (caller must explicitly set to start from a specific phase)
1058
+ * - Set to a specific phase id to start from that phase
982
1059
  *
983
- * // Load extensions
984
- * await runner.loadExtensions(extensions);
985
- * runner.bind();
986
- * ```
1060
+ * When entryPhaseId is null, Agent normalizes the registry to start from its default phase.
987
1061
  */
988
- declare class ExtensionRunner {
989
- readonly hooks: HooksManager;
990
- readonly runtime: ExtensionRuntime;
991
- readonly events: EventBus;
992
- private readonly cwd;
993
- private readonly abortController;
994
- private _idle;
995
- private readonly extensions;
996
- private readonly phases;
997
- private _phaseCache;
998
- private readonly pendingProviders;
999
- private bound;
1000
- private readonly errorListeners;
1001
- private readonly loadedExtensions;
1002
- /** Current agent context — set by the agent before each phase */
1003
- currentContext?: AgentContext;
1004
- constructor(options?: ExtensionRunnerOptions);
1005
- /** Whether the agent is currently idle (not streaming). */
1006
- get isIdle(): boolean;
1007
- /** Set idle state — called by the agent loop. */
1008
- setIdle(idle: boolean): void;
1009
- /** Abort signal for the current runner instance. */
1010
- get signal(): AbortSignal;
1011
- /** Abort the current runner operation. */
1012
- abort(): void;
1013
- /**
1014
- * Register an error listener.
1015
- * Returns an unsubscribe function.
1016
- */
1017
- onError(listener: ExtensionErrorListener): () => void;
1018
- /**
1019
- * Emit a structured extension error to all listeners.
1020
- */
1021
- emitError(error: ExtensionError): void;
1022
- /**
1023
- * Mark all extension contexts as stale.
1024
- * After calling this, any captured ExtensionAPI or ExtensionContext will throw
1025
- * on use. Used during session replacement or reload.
1026
- */
1027
- invalidate(message?: string): void;
1028
- /**
1029
- * Subscribe to a specific hook event type.
1030
- * Returns an unsubscribe function.
1031
- *
1032
- * @example
1033
- * ```ts
1034
- * const unsub = runner.on("before_tool_call", (event) => {
1035
- * return { allow: false, reason: "Blocked" };
1036
- * });
1037
- * unsub(); // Cancel subscription
1038
- * ```
1039
- */
1040
- on<K extends HookEventType>(type: K, handler: HookHandler<K>): () => void;
1041
- /**
1042
- * Subscribe to all events (read-only).
1043
- * Returns an unsubscribe function.
1044
- *
1045
- * @example
1046
- * ```ts
1047
- * const unsub = runner.subscribe((event) => {
1048
- * console.log(event.type);
1049
- * });
1050
- * ```
1051
- */
1052
- subscribe(listener: (event: {
1053
- type: HookEventType;
1054
- }) => void): () => void;
1055
- private getAllEventTypes;
1056
- /**
1057
- * Load and initialize extensions.
1058
- * Creates Extension tracking objects and calls each factory with an ExtensionAPI.
1059
- */
1060
- loadExtensions(extensions: LoadedExtension[]): Promise<void>;
1061
- /**
1062
- * Get all registered tools from all extensions (first registration per name wins).
1063
- */
1064
- getAllRegisteredTools(): RegisteredTool[];
1065
- /**
1066
- * Get a tool definition by name. Returns undefined if not found.
1067
- */
1068
- getToolDefinition(toolName: string): RegisteredTool["definition"] | undefined;
1069
- /**
1070
- * Check if there are handlers registered for specified event type.
1071
- */
1072
- hasHandlers(eventType: HookEventType): boolean;
1073
- /**
1074
- * Get the number of handlers for specified event type.
1075
- */
1076
- handlerCount(eventType: HookEventType): number;
1077
- getPhase(id: string): Phase | undefined;
1078
- getPhases(): Phase[];
1079
- createPhaseRegistry(input?: {
1080
- entryPhaseId?: string | null;
1081
- }): PhaseRegistry;
1082
- /** Adapt an extension RegisteredPhase to the core Phase type. */
1083
- private adaptToPhase;
1084
- /**
1085
- * Bind the runner — flushes pending provider registrations and
1086
- * replaces runtime stubs with real implementations.
1087
- */
1088
- bind(): void;
1089
- /**
1090
- * Generic emit — fire-and-forget for any event type.
1091
- */
1092
- emit<K extends HookEventType>(eventType: K, event: Parameters<HookHandler<K>>[0]): Promise<void>;
1093
- /**
1094
- * Unified hook emission — returns the first non-undefined result.
1095
- */
1096
- private emitHook;
1097
- emitBeforePhase(phaseId: string, input: PhaseContext): Promise<{
1098
- abort?: any;
1099
- skip?: any;
1100
- input?: PhaseContext;
1101
- }>;
1102
- emitAfterPhase(phaseId: string, output: PhaseOutput): Promise<{
1103
- abort?: any;
1104
- retry?: PhaseContext;
1105
- output?: PhaseOutput;
1106
- }>;
1107
- emitBeforePrompt(phaseId: string, input: PhaseContext): Promise<PhaseContext>;
1108
- emitBeforeToolCall(tool: Tool, args: unknown): Promise<{
1109
- allow: boolean;
1110
- reason?: string;
1111
- }>;
1112
- emitAfterToolCall(tool: Tool, result: ToolResult): Promise<ToolResult>;
1113
- emitAgentStart(sessionId: string): Promise<void>;
1114
- emitAgentEnd(sessionId: string, outcome: any, messages: any[]): Promise<void>;
1115
- emitTurnStart(messages: any[]): Promise<void>;
1116
- emitTurnEnd(messages: any[], outcome?: any): Promise<void>;
1117
- emitMessageStart(message: any): Promise<void>;
1118
- emitMessageUpdate(message: any, delta: string): Promise<void>;
1119
- emitMessageEnd(message: any): Promise<void>;
1120
- emitToolExecutionStart(toolCallId: string, toolName: string, args: unknown): Promise<void>;
1121
- emitToolExecutionUpdate(toolCallId: string, toolName: string, _progress?: string): Promise<void>;
1122
- emitToolExecutionEnd(toolCallId: string, toolName: string, result: ToolResult): Promise<void>;
1123
- emitSavePoint(hadPendingMutations: boolean): Promise<void>;
1124
- emitAbort(reason?: string): Promise<void>;
1125
- emitSettled(): Promise<void>;
1126
- /**
1127
- * Emit an AgentEvent by routing to the appropriate typed hook.
1128
- */
1129
- emitAgentEvent(event: any): Promise<void>;
1130
- /**
1131
- * Create an ExtensionAPI for a specific extension.
1132
- * Registration methods write to the extension tracking object.
1133
- * Action methods delegate to the shared runtime.
1134
- */
1135
- private createExtensionAPI;
1136
- private registerTool;
1137
- private registerPhase;
1138
- private registerProvider;
1139
- private unregisterProvider;
1140
- private flushPendingProviders;
1141
- private getRegisteredPhase;
1142
- private collectRegisteredPhases;
1143
- }
1144
- declare function createExtensionRunner(options?: ExtensionRunnerOptions): ExtensionRunner;
1062
+ declare function loadPhases(targetPath: string): Promise<PhaseRegistry>;
1145
1063
 
1146
- type LoopMetrics = {
1147
- /** Number of phase iterations executed. */
1148
- iterations: number;
1149
- /** Phase transition history. */
1150
- phaseTransitions: Array<{
1151
- from: string;
1152
- to: string;
1153
- ts: string;
1154
- }>;
1155
- /** Number of times compaction was triggered. */
1156
- compactionCount: number;
1157
- /** Number of retry attempts due to transient errors. */
1158
- retryCount: number;
1159
- /** Loop start timestamp. */
1160
- startedAt: string;
1161
- /** Loop start time as epoch ms (for duration calculation). */
1162
- startedAtMs: number;
1163
- /** Loop end timestamp (set on completion). */
1164
- endedAt?: string;
1165
- /** Total wall-clock duration in ms. */
1166
- durationMs?: number;
1167
- };
1168
- type SessionState = {
1169
- currentPhase: string;
1170
- attempt: number;
1171
- metrics: LoopMetrics;
1172
- status: "idle" | "running" | "completed" | "aborted" | "failed";
1173
- };
1174
-
1175
- type ToolContext = Pick<AgentContext, "skills"> & {
1176
- toolCallId: string;
1177
- };
1178
- type ToolExecutionMode = "sequential" | "parallel";
1179
- type Tool<TArgs = unknown> = {
1180
- name: string;
1181
- description: string;
1182
- parameters: Type.TSchema;
1183
- /** One-line snippet shown in the system prompt tool list. */
1184
- promptSnippet?: string;
1185
- /** Additional guidelines appended to the system prompt when this tool is active. */
1186
- promptGuidelines?: string[];
1187
- /** Whether this tool can run concurrently with others. Default: "parallel". */
1188
- executionMode?: ToolExecutionMode;
1189
- execute(args: TArgs, context: ToolContext, signal?: AbortSignal): Promise<ToolResult>;
1190
- };
1191
- /** Context snapshot passed into the low-level agent loop. */
1192
- type AgentContext = {
1193
- /** System prompt included with the request. */
1194
- systemPrompt: string;
1195
- /** Transcript visible to the model. */
1196
- messages: AgentMessage[];
1197
- /** Tools available for this run. */
1198
- tools: Tool[];
1199
- /** Skills available for this run. */
1200
- skills: Skill$1[];
1201
- /** Custom phases for this run. Agent normalizes this with the built-in default phase. */
1202
- phases?: PhaseRegistry;
1203
- };
1204
- type BeforeToolCall = (input: {
1205
- tool: Tool;
1206
- args: unknown;
1207
- }) => Promise<{
1208
- allow: true;
1209
- } | {
1210
- allow: false;
1211
- reason: string;
1212
- }>;
1213
- type AfterToolCall = (input: {
1214
- tool: Tool;
1215
- result: ToolResult;
1216
- }) => Promise<ToolResult>;
1217
- type RunResult = {
1218
- sessionId: string;
1219
- messages: AgentMessage[];
1220
- outcome: Outcome;
1221
- metrics: LoopMetrics;
1222
- };
1223
- type Unsubscribe = () => void;
1224
- declare function createMessage(role: AgentMessage["role"], content: AgentMessage["content"], metadata?: Record<string, unknown>): AgentMessage;
1225
- declare function messageContentText(content: AgentMessage["content"]): string;
1226
-
1227
- /** Unified phase output — model decides routing via route. */
1228
- type PhaseOutput = {
1229
- message: string;
1230
- /** Route to next phase, or "continue" to re-execute current phase, or "stop" to end */
1231
- route: string;
1232
- /** Phase name that produced this output */
1233
- phase?: string;
1234
- /** Tool calls from the model invocation (used by framework for route extraction) */
1235
- toolCalls?: Array<{
1236
- id: string;
1237
- name: string;
1238
- args: unknown;
1239
- }>;
1240
- /** Route reason extracted from route tool call (for hooks to inspect) */
1241
- routeReason?: string;
1242
- /** Structured data from this phase, passed to the next phase */
1243
- payload?: unknown;
1244
- };
1245
- /** Phase machine state — tracks position and inter-phase data */
1246
- interface PhaseState {
1247
- current: string;
1248
- available: string[];
1249
- iterations: number;
1250
- payload?: unknown;
1251
- }
1252
- /** Everything a phase needs to execute */
1253
- interface PhaseContext {
1254
- systemPrompt: string;
1255
- messages: AgentMessage[];
1256
- /** Phase-filtered tools */
1257
- tools: Tool[];
1258
- /** Phase-filtered skills */
1259
- skills: Skill$1[];
1260
- /** Phase machine state */
1261
- state: PhaseState;
1262
- /** Additional guideline bullets appended to the system prompt */
1263
- promptGuidelines?: string[];
1264
- /** Text to append after the system prompt */
1265
- appendSystemPrompt?: string;
1266
- }
1267
- /**
1268
- * Loaded Phase object
1269
- */
1270
- interface Phase {
1271
- /** Unique identifier */
1272
- id: string;
1273
- /** Display name */
1274
- name: string;
1275
- /** Description */
1276
- description: string;
1277
- /** Restricted tools (undefined = all tools available) */
1278
- tools?: string[];
1279
- /** Restricted skills (undefined = all skills available) */
1280
- skills?: string[];
1281
- /** Forced next phase */
1282
- target?: string;
1283
- /** Expected input fields (key → description) */
1284
- input?: Record<string, string>;
1285
- /** If true, phase gets a fresh context when executed in parallel */
1286
- isolated?: boolean;
1287
- /** Path to PHASE.md file */
1288
- filePath: string;
1289
- /** Phase directory path */
1290
- baseDir: string;
1291
- /** PHASE.md body content */
1292
- content: string;
1293
- /** Model override for this phase (resolved from frontmatter) */
1294
- model?: LlmModelRef;
1295
- /** ExtensionAPI factory function (default export pattern) */
1296
- factory?: (api: ExtensionAPI) => Promise<void>;
1297
- /** Legacy run function */
1298
- run?: (context: PhaseContext, execution: PhaseExecution) => Promise<PhaseOutput | void>;
1299
- }
1300
- /**
1301
- * Phase registry containing all loaded phases
1302
- */
1303
- interface PhaseRegistry {
1304
- /** Map of phase id to Phase object */
1305
- phases: Map<string, Phase>;
1306
- /** Entry phase id (null until Agent applies its default phase) */
1307
- entryPhaseId: string | null;
1308
- }
1309
-
1310
- type WorkspacePaths = {
1311
- cwd: string;
1312
- rowanDir: string;
1313
- };
1314
- type ResolveWorkspaceOptions = {
1315
- cwd?: string;
1316
- env?: NodeJS.ProcessEnv;
1317
- homeDir?: string;
1318
- rowanDir?: string;
1319
- };
1320
- declare function resolveWorkspacePaths(options?: ResolveWorkspaceOptions): WorkspacePaths;
1321
- declare function resolveInWorkspace(path: string, rootOrPaths: string | Pick<WorkspacePaths, "cwd">): string;
1322
-
1323
- type PhaseLoadTarget = string | Pick<WorkspacePaths, "rowanDir">;
1324
- /**
1325
- * Load a single phase from a PHASE.md file or phase directory.
1326
- *
1327
- * If a directory is provided, the loader reads its PHASE.md.
1328
- */
1329
- declare function loadPhase(targetPath: string): Promise<Phase>;
1330
- declare function loadPhases(targetPath: PhaseLoadTarget): Promise<PhaseRegistry>;
1331
- /**
1332
- * Re-read all file-based phases from disk and update the registry in place.
1333
- * Extension-registered phases (with empty filePath) are preserved as-is.
1334
- */
1335
- declare function reloadPhases(registry: PhaseRegistry): Promise<void>;
1336
-
1337
- type AgentOptions = {
1338
- context: AgentContext;
1339
- model: LlmModelRef;
1340
- stream: StreamFn;
1341
- cwd?: string;
1342
- extensions?: LoadedExtension[];
1064
+ type AgentExecutionOptions = StreamAgentOptions & {
1343
1065
  sessionId?: string;
1344
- maxAttempts?: number;
1345
- beforeToolCall?: BeforeToolCall;
1346
- afterToolCall?: AfterToolCall;
1347
- onMessage?: (message: AgentMessage) => Promise<void>;
1348
- onOutcome?: (outcome: Outcome) => Promise<void>;
1349
- onModelTranscript?: (transcript: ModelTranscript, meta: {
1350
- phase: string;
1351
- model: LlmModelRef;
1352
- }) => Promise<void>;
1066
+ agentId?: AgentId;
1067
+ sessionState?: SessionState;
1068
+ onInput?: (message: AgentMessage) => Promise<void>;
1069
+ runtime?: AgentRuntimePort;
1070
+ };
1071
+ type RunOptions = Partial<AgentExecutionOptions>;
1072
+ type RuntimeRunHooks = {
1073
+ onSuspend?: (reason?: string, state?: SessionState, inputRequest?: AgentInputRequest) => Promise<void> | void;
1353
1074
  };
1354
- type RunOptions = Partial<AgentOptions>;
1355
1075
  type AgentStatus = {
1076
+ agentId?: AgentId;
1356
1077
  sessionId?: string;
1357
1078
  context: AgentContext;
1358
- model: LlmModelRef;
1079
+ model: ModelRef;
1359
1080
  tools: Tool[];
1360
1081
  initialized: boolean;
1361
1082
  running: boolean;
1362
1083
  currentResult?: RunResult;
1363
1084
  error?: string;
1364
1085
  };
1365
- declare class Agent {
1086
+ declare class AgentExecution {
1366
1087
  readonly state: AgentStatus;
1367
1088
  private options;
1368
1089
  private readonly listeners;
@@ -1372,16 +1093,21 @@ declare class Agent {
1372
1093
  private extensionRunner?;
1373
1094
  private loadedExtensions?;
1374
1095
  private loadedExtensionsCwd?;
1096
+ private runtimeRunId?;
1097
+ get id(): AgentId;
1098
+ get sessionId(): string;
1375
1099
  static loadSkills(targetPath: string): Promise<AgentContext["skills"]>;
1376
1100
  static loadPhases(targetPath: Parameters<typeof loadPhases>[0]): Promise<PhaseRegistry>;
1377
1101
  static loadExtensions(targetPath: string): Promise<LoadExtensionsResult>;
1378
- constructor(options: AgentOptions);
1102
+ constructor(options: AgentExecutionOptions);
1379
1103
  subscribe(listener: AgentEventListener): Unsubscribe;
1380
1104
  appendUserMessage(input: string): void;
1381
1105
  appendMessage(message: AgentMessage): void;
1382
1106
  appendMessages(messages: AgentMessage[]): void;
1383
1107
  runWithUserInput(input: string, options?: RunOptions): Promise<RunResult>;
1384
- runWithMessage(message: AgentMessage, options?: RunOptions): Promise<RunResult>;
1108
+ runWithMessage(message: AgentMessage, options?: RunOptions, internalHooks?: RuntimeRunHooks): Promise<RunResult>;
1109
+ /** Internal Runtime seam: executes one leased Agent Input. */
1110
+ executeAgentInput(input: AgentMessage, runId: AgentRunId, control: AgentRunControl, executionState?: AgentRunExecutionState): Promise<Outcome>;
1385
1111
  resetInitialization(): void;
1386
1112
  getContext(): AgentContext;
1387
1113
  setContext(context: AgentContext): void;
@@ -1392,18 +1118,21 @@ declare class Agent {
1392
1118
  clearMessages(): void;
1393
1119
  getTranscript(): AgentMessage[];
1394
1120
  replaceTranscript(messages: AgentMessage[]): void;
1395
- getConfig(): AgentOptions;
1396
- setConfig(config: AgentOptions): void;
1397
- updateConfig(updater: (config: AgentOptions) => AgentOptions): void;
1121
+ getConfig(): AgentExecutionOptions;
1122
+ setConfig(config: AgentExecutionOptions): void;
1123
+ updateConfig(updater: (config: AgentExecutionOptions) => AgentExecutionOptions): void;
1398
1124
  setSessionId(sessionId: string): void;
1399
1125
  getSessionId(): string | undefined;
1400
- setModel(model: LlmModelRef): void;
1126
+ getAgentId(): AgentId | undefined;
1127
+ /** Internal Runtime hook for associating Tool Calls with the leased Run. */
1128
+ getRuntimeRunId(): AgentRunId | undefined;
1129
+ setModel(model: ModelRef): void;
1401
1130
  setTools(tools: Tool[]): void;
1402
1131
  setSkills(skills: Skill$1[]): void;
1403
1132
  setPhases(phases: PhaseRegistry): void;
1404
1133
  setCwd(cwd: string): void;
1405
1134
  setStream(stream: StreamFn): void;
1406
- getModel(): LlmModelRef;
1135
+ getModel(): ModelRef;
1407
1136
  getTools(): Tool[];
1408
1137
  getSkills(): Skill$1[];
1409
1138
  getPhases(): PhaseRegistry | undefined;
@@ -1440,8 +1169,12 @@ declare class Agent {
1440
1169
  private runWithLifecycle;
1441
1170
  private finishRun;
1442
1171
  private loadExtensions;
1443
- run(config?: RunOptions): Promise<RunResult>;
1172
+ run(config?: RunOptions, internalHooks?: RuntimeRunHooks): Promise<RunResult>;
1444
1173
  abort(reason?: string): void;
1174
+ isSuspended(): boolean;
1175
+ private abortLocal;
1176
+ /** Internal Runtime hook; public callers abort a precise AgentRun. */
1177
+ abortFromRuntime(reason?: string): void;
1445
1178
  /**
1446
1179
  * Get formatted skill content for LLM consumption.
1447
1180
  *
@@ -1469,9 +1202,6 @@ declare class Agent {
1469
1202
  private cloneOptions;
1470
1203
  }
1471
1204
 
1472
- declare function createId(prefix: string): string;
1473
- declare function createTimestamp(date?: Date): string;
1474
-
1475
1205
  declare const SkillSchema: Type.TObject<{
1476
1206
  name: Type.TString;
1477
1207
  description: Type.TString;
@@ -1481,89 +1211,7 @@ declare const SkillSchema: Type.TObject<{
1481
1211
  disableModelInvocation: Type.TBoolean;
1482
1212
  }>;
1483
1213
  type Skill = Type.Static<typeof SkillSchema>;
1484
- type Session<TLogEvent = never> = {
1485
- version: string;
1486
- id: string;
1487
- parentSessionId?: string;
1488
- systemPrompt: string;
1489
- input: string;
1490
- messages: AgentMessage[];
1491
- log: TLogEvent[];
1492
- skills: Skill[];
1493
- createdAt: string;
1494
- updatedAt: string;
1495
- title?: string;
1496
- };
1497
- declare function createSession<TLogEvent = never>(input: {
1498
- id?: string;
1499
- systemPrompt: string;
1500
- input: string;
1501
- skills?: Skill[];
1502
- parentSessionId?: string;
1503
- title?: string;
1504
- }): Session<TLogEvent>;
1505
- declare function appendUserTurn<TLogEvent>(session: Session<TLogEvent>, input: string): Session<TLogEvent>;
1506
1214
 
1507
- type SessionHeader = {
1508
- type: "header";
1509
- id: string;
1510
- version: string;
1511
- createdAt: string;
1512
- updatedAt: string;
1513
- systemPrompt: string;
1514
- input: string;
1515
- parentSessionId?: string;
1516
- skills: Skill[];
1517
- title?: string;
1518
- currentLeafId?: string | null;
1519
- };
1520
- type SessionEntryBase = {
1521
- id: string;
1522
- parentId: string | null;
1523
- timestamp: string;
1524
- };
1525
- type MessageSessionEntry = SessionEntryBase & {
1526
- type: "message";
1527
- message: AgentMessage;
1528
- };
1529
- type OutcomeSessionEntry = SessionEntryBase & {
1530
- type: "outcome";
1531
- outcome: Outcome;
1532
- };
1533
- type ExecutionTurnSessionEntry = SessionEntryBase & {
1534
- type: "execution_turn";
1535
- turn: ExecutionTurn;
1536
- };
1537
- type CompactionSessionEntry = SessionEntryBase & {
1538
- type: "compaction";
1539
- summary: string;
1540
- firstKeptEntryId: string;
1541
- };
1542
- type BranchSummarySessionEntry = SessionEntryBase & {
1543
- type: "branch_summary";
1544
- fromId: string;
1545
- summary: string;
1546
- };
1547
- type SessionInfoSessionEntry = SessionEntryBase & {
1548
- type: "session_info";
1549
- title: string;
1550
- };
1551
- type CustomSessionEntry = SessionEntryBase & {
1552
- type: "custom";
1553
- customType: string;
1554
- data: unknown;
1555
- };
1556
- type SessionStateSessionEntry = SessionEntryBase & {
1557
- type: "session_state";
1558
- state: SessionState;
1559
- };
1560
- type ModelTranscriptSessionEntry = SessionEntryBase & {
1561
- type: "model_transcript";
1562
- transcript: ModelTranscript;
1563
- phase?: string;
1564
- model?: LlmModelRef;
1565
- };
1566
- type SessionEntry = MessageSessionEntry | OutcomeSessionEntry | ExecutionTurnSessionEntry | CompactionSessionEntry | BranchSummarySessionEntry | SessionInfoSessionEntry | CustomSessionEntry | SessionStateSessionEntry | ModelTranscriptSessionEntry;
1567
1215
  type SessionAgentContext<TTool = unknown> = {
1568
1216
  systemPrompt: string;
1569
1217
  messages: AgentMessage[];
@@ -1593,79 +1241,306 @@ type SessionListItem = {
1593
1241
  };
1594
1242
  type SessionManager = {
1595
1243
  getSessionId(): string;
1596
- getSessionFile(): string | undefined;
1597
- getHeader(): Promise<SessionHeader>;
1598
1244
  appendMessage(message: AgentMessage): Promise<string>;
1599
1245
  appendOutcome(outcome: Outcome): Promise<string>;
1600
- appendExecutionTurn(turn: ExecutionTurn): Promise<string>;
1601
- appendCompaction(input: {
1602
- summary: string;
1603
- firstKeptEntryId: string;
1604
- }): Promise<string>;
1605
- appendBranchSummary(input: {
1606
- fromId: string;
1607
- summary: string;
1608
- }): Promise<string>;
1609
- appendSessionInfo(input: {
1610
- title: string;
1611
- }): Promise<string>;
1612
- appendCustom(input: {
1613
- customType: string;
1614
- data: unknown;
1615
- }): Promise<string>;
1616
- appendSessionState(state: SessionState): Promise<string>;
1617
1246
  appendModelTranscript(transcript: ModelTranscript, meta?: {
1618
1247
  phase?: string;
1619
- model?: LlmModelRef;
1248
+ model?: ModelRef;
1620
1249
  }): Promise<string>;
1621
- getSessionState(): Promise<SessionState | undefined>;
1622
- branch(entryId: string | null): Promise<void>;
1623
1250
  buildAgentContext<TTool = unknown>(input?: BuildAgentContextInput<TTool>): Promise<SessionAgentContext<TTool>>;
1624
- listEntries(): Promise<SessionEntry[]>;
1625
- loadExecutionTurns(filter?: StepFilter): Promise<ExecutionTurn[]>;
1251
+ };
1252
+ type SessionManagerProvider = {
1253
+ create(input: CreateSessionManagerInput): Promise<SessionManager>;
1254
+ open(sessionId: string): Promise<SessionManager | undefined>;
1626
1255
  };
1627
1256
 
1628
- declare class LocalJsonlSessionManager implements SessionManager {
1629
- private readonly sessionsDir;
1630
- private readonly filePath;
1631
- private readonly inner;
1257
+ type CreateAgentInput = {
1258
+ sessionId: string;
1259
+ };
1260
+ type EnqueueAgentInput = {
1261
+ agentId: AgentId;
1262
+ input: AgentMessage;
1263
+ };
1264
+ type AcknowledgeEventAndEnqueueAgentInput = EnqueueAgentInput & {
1265
+ consumerId: string;
1266
+ eventId: RuntimeEventId;
1267
+ };
1268
+ type EnqueuedAgentInput = {
1269
+ message: RuntimeMessage;
1270
+ run: AgentRunRecord;
1271
+ resumed: boolean;
1272
+ };
1273
+ type AcknowledgeEventAndEnqueueAgentInputResult = {
1274
+ checkpoint: RuntimeEventCheckpoint;
1275
+ enqueued?: EnqueuedAgentInput;
1276
+ };
1277
+ type ListRunsInput = {
1278
+ agentId?: AgentId;
1279
+ states?: AgentRunRecord["state"][];
1280
+ };
1281
+ type RecordRuntimeEventInput = {
1282
+ kind: RuntimeEventKind;
1283
+ related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">;
1284
+ payload?: unknown;
1285
+ };
1286
+ type LeaseRunInput = {
1287
+ runId: AgentRunId;
1288
+ workerId: string;
1289
+ leaseDurationMs: number;
1290
+ now?: Date;
1291
+ };
1292
+ type LeasedRun = {
1293
+ run: AgentRunRecord;
1294
+ message: RuntimeMessage;
1295
+ lease: RuntimeLease;
1296
+ };
1297
+ type RenewLeaseInput = {
1298
+ runId: AgentRunId;
1299
+ leaseId: LeaseId;
1300
+ leaseDurationMs: number;
1301
+ now?: Date;
1302
+ };
1303
+ type SuspendRunInput = {
1304
+ runId: AgentRunId;
1305
+ reason?: string;
1306
+ inputRequest?: AgentInputRequest;
1307
+ executionState?: AgentRunExecutionState;
1308
+ };
1309
+ type CompleteRunInput = {
1310
+ runId: AgentRunId;
1311
+ outcome: Outcome;
1312
+ state?: Extract<AgentRunRecord["state"], "completed" | "failed" | "cancelled">;
1313
+ };
1314
+ type RetryRunInput = {
1315
+ runId: AgentRunId;
1316
+ reason: string;
1317
+ };
1318
+ type ExhaustRunInput = {
1319
+ runId: AgentRunId;
1320
+ outcome: Outcome;
1321
+ reason: string;
1322
+ };
1323
+ type AbortRunInput = {
1324
+ runId: AgentRunId;
1325
+ outcome: Outcome;
1326
+ };
1327
+ type CreateToolCallInput = {
1328
+ agentId: AgentId;
1329
+ runId: AgentRunId;
1330
+ name: string;
1331
+ args: unknown;
1332
+ };
1333
+ type CompleteToolCallInput = {
1334
+ toolCallId: RuntimeToolCallId;
1335
+ result: ToolResult;
1336
+ state?: Extract<RuntimeToolCall["state"], "completed" | "failed">;
1337
+ };
1338
+ type IndeterminateToolCallInput = {
1339
+ toolCallId: RuntimeToolCallId;
1340
+ reason: string;
1341
+ };
1342
+ interface RuntimeStateStore {
1343
+ createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1344
+ getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1345
+ listAgents(): Promise<AgentRecord[]>;
1346
+ setAgentState(agentId: AgentId, state: AgentLifecycleState): Promise<AgentRecord>;
1347
+ enqueueAgentInput(input: EnqueueAgentInput): Promise<EnqueuedAgentInput>;
1348
+ getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1349
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1350
+ listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1351
+ listActiveRuns(): Promise<AgentRunRecord[]>;
1352
+ leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1353
+ renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1354
+ suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1355
+ completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1356
+ retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1357
+ exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1358
+ abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1359
+ recoverExpiredLeases(now?: Date): Promise<AgentRunRecord[]>;
1360
+ recoverLeases(): Promise<AgentRunRecord[]>;
1361
+ createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1362
+ startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1363
+ completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1364
+ markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1365
+ getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1366
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1367
+ recordEvent(input: RecordRuntimeEventInput): Promise<RuntimeEvent>;
1368
+ getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1369
+ acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1370
+ acknowledgeEventAndEnqueueAgentInput(input: AcknowledgeEventAndEnqueueAgentInput): Promise<AcknowledgeEventAndEnqueueAgentInputResult>;
1371
+ }
1372
+
1373
+ type ToolRuntimePolicy = {
1374
+ /** A narrowing allow-list. It can never add a Tool to an Agent. */
1375
+ allowedTools?: readonly string[];
1376
+ maxConcurrent?: number;
1377
+ perToolMaxConcurrent?: Readonly<Record<string, number>>;
1378
+ };
1379
+
1380
+ type AgentRuntimeOptions = {
1381
+ stateStore: RuntimeStateStore;
1382
+ sessionProvider?: SessionManagerProvider;
1383
+ toolPolicy?: ToolRuntimePolicy;
1384
+ maxConcurrentRuns?: number;
1385
+ maxInfrastructureAttempts?: number;
1386
+ leaseDurationMs?: number;
1387
+ leaseRenewalIntervalMs?: number;
1388
+ };
1389
+ type RuntimeRunHandle = {
1390
+ notify(run: AgentRunRecord): void;
1391
+ };
1392
+ type RuntimeEventDisposition = {
1393
+ type: "enqueue";
1394
+ agentId: AgentId;
1395
+ input: AgentMessage;
1396
+ };
1397
+ type RuntimeEventListener = (event: RuntimeEvent) => RuntimeEventDisposition | void | Promise<RuntimeEventDisposition | void>;
1398
+ type RuntimeEventConsumer = {
1399
+ caughtUp: Promise<void>;
1400
+ stop(): void;
1401
+ };
1402
+ declare class AgentRuntime {
1403
+ private readonly stateStore;
1404
+ private readonly sessionProvider?;
1405
+ private readonly maxConcurrentRuns;
1406
+ private readonly maxInfrastructureAttempts;
1407
+ private readonly leaseDurationMs;
1408
+ private readonly leaseRenewalIntervalMs;
1409
+ private readonly toolRuntime;
1410
+ private readonly bindings;
1411
+ private readonly agents;
1412
+ private readonly runHandles;
1413
+ private readonly runWaiters;
1414
+ private readonly pendingRuns;
1415
+ private readonly scheduledRunIds;
1416
+ private readonly runningAgents;
1417
+ private readonly pausedAgents;
1418
+ private readonly eventSubscriptions;
1419
+ private readonly activeDispatches;
1420
+ private runningRuns;
1421
+ private pumping;
1422
+ private nextWorkerId;
1423
+ private stopped;
1632
1424
  private constructor();
1633
- static create(sessionsDir: string, input: CreateSessionManagerInput): Promise<LocalJsonlSessionManager>;
1634
- static open(sessionsDir: string, id: string): Promise<LocalJsonlSessionManager | undefined>;
1635
- static list(sessionsDir: string): Promise<SessionListItem[]>;
1636
- static delete(sessionsDir: string, id: string): Promise<boolean>;
1637
- getSessionId(): string;
1638
- getSessionFile(): string | undefined;
1639
- getHeader(): Promise<SessionHeader>;
1640
- appendMessage(message: AgentMessage): Promise<string>;
1641
- appendOutcome(outcome: Outcome): Promise<string>;
1642
- appendExecutionTurn(turn: ExecutionTurn): Promise<string>;
1643
- appendCompaction(input: {
1644
- summary: string;
1645
- firstKeptEntryId: string;
1646
- }): Promise<string>;
1647
- appendBranchSummary(input: {
1648
- fromId: string;
1649
- summary: string;
1650
- }): Promise<string>;
1651
- appendSessionInfo(input: {
1652
- title: string;
1653
- }): Promise<string>;
1654
- appendCustom(input: {
1655
- customType: string;
1656
- data: unknown;
1657
- }): Promise<string>;
1658
- appendSessionState(state: SessionState): Promise<string>;
1659
- appendModelTranscript(transcript: ModelTranscript, meta?: {
1660
- phase?: string;
1661
- model?: LlmModelRef;
1662
- }): Promise<string>;
1663
- getSessionState(): Promise<SessionState | undefined>;
1664
- branch(entryId: string | null): Promise<void>;
1665
- buildAgentContext<TTool = unknown>(input?: BuildAgentContextInput<TTool>): Promise<SessionAgentContext<TTool>>;
1666
- listEntries(): Promise<SessionEntry[]>;
1667
- loadExecutionTurns(filter?: StepFilter): Promise<ExecutionTurn[]>;
1668
- private appendThroughInner;
1425
+ static start(options: AgentRuntimeOptions): Promise<AgentRuntime>;
1426
+ createAgent(options: AgentOptions): Promise<Agent>;
1427
+ reconstructAgent(agentId: AgentId, options: AgentOptions): Promise<Agent>;
1428
+ stop(): Promise<void>;
1429
+ private bindAgent;
1430
+ private registerRunHandle;
1431
+ private waitForRunChange;
1432
+ private scheduleRun;
1433
+ pauseAgent(agentId: AgentId): Promise<void>;
1434
+ resumeAgent(agentId: AgentId): Promise<void>;
1435
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1436
+ listActiveRuns(): Promise<AgentRunRecord[]>;
1437
+ listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1438
+ getAgent(agentId: AgentId): Agent | undefined;
1439
+ getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1440
+ getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1441
+ abortRun(runId: AgentRunId, reason?: string): Promise<void>;
1442
+ consumeEvents(consumerId: string, listener: RuntimeEventListener): RuntimeEventConsumer;
1443
+ private registerEventConsumer;
1444
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1445
+ private recover;
1446
+ private scheduleQueuedRuns;
1447
+ private attachAgent;
1448
+ private submitAgentInput;
1449
+ private pump;
1450
+ private dispatchRun;
1451
+ private finishRun;
1452
+ private finishFailedRun;
1453
+ private notifyRun;
1454
+ private publishEvents;
1455
+ private deliverEvents;
1456
+ private assertRunning;
1457
+ }
1458
+
1459
+ type AgentRunListener = (state: AgentRunState) => void | Promise<void>;
1460
+ type AgentRunHost = {
1461
+ register(handle: RuntimeRunHandle): void;
1462
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1463
+ waitForRunChange(runId: AgentRunId, state: AgentRunState, updatedAt: string): Promise<void>;
1464
+ abortRun(runId: AgentRunId, reason: string): Promise<void>;
1465
+ consumeEvents(consumerId: string, listener: RuntimeEventListener): RuntimeEventConsumer;
1466
+ };
1467
+ declare const CREATE_AGENT_RUN: unique symbol;
1468
+ declare class AgentRun implements RuntimeRunHandle {
1469
+ private readonly host;
1470
+ private readonly publicMessageId;
1471
+ private current;
1472
+ private readonly listeners;
1473
+ private constructor();
1474
+ static [CREATE_AGENT_RUN](host: AgentRunHost, initial: AgentRunRecord, publicMessageId: string): AgentRun;
1475
+ get id(): AgentRunId;
1476
+ get messageId(): string;
1477
+ get status(): AgentRunState;
1478
+ get state(): AgentRunState;
1479
+ get inputRequest(): AgentInputRequest | undefined;
1480
+ getStatus(): Promise<AgentRunState>;
1481
+ subscribe(listener: AgentRunListener): () => void;
1482
+ consumeRuntimeEvents(consumerId: string, listener: RuntimeEventListener): RuntimeEventConsumer;
1483
+ result(): Promise<Outcome>;
1484
+ abort(reason?: string): Promise<void>;
1485
+ notify(run: AgentRunRecord): void;
1486
+ }
1487
+
1488
+ type AgentCommonOptions = {
1489
+ context: AgentContext;
1490
+ cwd?: string;
1491
+ extensions?: LoadedExtension[];
1492
+ maxAttempts?: number;
1493
+ beforeToolCall?: BeforeToolCall;
1494
+ afterToolCall?: AfterToolCall;
1495
+ onMessage?: (message: AgentMessage) => Promise<void>;
1496
+ onOutcome?: (outcome: Outcome) => Promise<void>;
1497
+ onModelTranscript?: (transcript: ModelTranscript, meta: {
1498
+ phase: string;
1499
+ model: ModelRef;
1500
+ }) => Promise<void>;
1501
+ };
1502
+ type AgentModelOptions = {
1503
+ model: ModelConfig;
1504
+ stream?: never;
1505
+ } | {
1506
+ model: ModelRef;
1507
+ stream: StreamFn;
1508
+ };
1509
+ type AgentOptions = AgentCommonOptions & AgentModelOptions;
1510
+ type StreamAgentOptions = AgentCommonOptions & {
1511
+ model: ModelRef;
1512
+ stream: StreamFn;
1513
+ };
1514
+ type AgentRunControl = {
1515
+ suspend(reason?: string, state?: AgentRunExecutionState, inputRequest?: AgentInputRequest): Promise<void>;
1516
+ };
1517
+ declare const ATTACH_AGENT: unique symbol;
1518
+ declare class Agent {
1519
+ readonly id: AgentId;
1520
+ readonly sessionId: string;
1521
+ private readonly execution;
1522
+ private readonly submitInput;
1523
+ private constructor();
1524
+ static [ATTACH_AGENT](id: AgentId, sessionId: string, execution: AgentExecution, submitInput: (input: AgentMessage) => Promise<AgentRun>): Agent;
1525
+ static loadSkills(targetPath: string): Promise<AgentContext["skills"]>;
1526
+ static loadPhases(targetPath: Parameters<typeof AgentExecution.loadPhases>[0]): Promise<PhaseRegistry>;
1527
+ static loadExtensions(targetPath: string): Promise<LoadExtensionsResult>;
1528
+ subscribe(listener: AgentEventListener): Unsubscribe;
1529
+ flushEvents(): Promise<void>;
1530
+ send(input: string | AgentMessage): Promise<AgentRun>;
1531
+ }
1532
+
1533
+ declare class InMemorySessionStore implements SessionManagerProvider {
1534
+ private readonly sessions;
1535
+ create(input: CreateSessionManagerInput): Promise<SessionManager>;
1536
+ open(sessionId: string): Promise<SessionManager | undefined>;
1537
+ }
1538
+ declare class JsonlSessionStore implements SessionManagerProvider {
1539
+ private readonly sessionsDir;
1540
+ constructor(sessionsDir: string);
1541
+ create(input: CreateSessionManagerInput): Promise<SessionManager>;
1542
+ open(sessionId: string): Promise<SessionManager | undefined>;
1543
+ list(): Promise<SessionListItem[]>;
1669
1544
  }
1670
1545
 
1671
1546
  type CoreToolContext = {
@@ -1676,129 +1551,98 @@ type CoreToolContext = {
1676
1551
  };
1677
1552
  declare function createCoreTools(input?: CoreToolContext): Tool[];
1678
1553
 
1679
- type ModelConfigFromFile = {
1680
- id: string;
1681
- name?: string;
1682
- primary?: boolean;
1683
- reasoning?: boolean;
1684
- input?: ("text" | "image")[];
1685
- contextWindow?: number;
1686
- maxTokens?: number;
1687
- cost?: Partial<ModelCost>;
1688
- };
1689
- type ProviderConfigFromFile = {
1690
- id: string;
1691
- name?: string;
1692
- baseUrl: string;
1693
- apiKey: string;
1694
- protocol: Protocol;
1695
- timeoutMs?: number;
1696
- maxRetries?: number;
1697
- retryDelayMs?: number;
1698
- headers?: Record<string, string>;
1699
- models: ModelConfigFromFile[];
1700
- };
1701
- type AgentConfigFile = {
1702
- model?: {
1703
- provider: string;
1704
- id: string;
1705
- };
1706
- logLevel?: "debug" | "info" | "warn" | "error" | "silent";
1707
- providers: ProviderConfigFromFile[];
1708
- };
1709
- declare function interpolateEnvVars(value: string): string;
1710
- declare function loadConfigFile(workspace: WorkspacePaths): Promise<AgentConfigFile | undefined>;
1711
- declare function resolveDefaultModel(config: AgentConfigFile): LlmModelRef | undefined;
1712
- declare function registerConfigModels(config: AgentConfigFile): void;
1713
- declare function parseModelRef(input?: string): LlmModelRef | undefined;
1714
-
1715
- /**
1716
- * Push-based async iterable with a final result.
1717
- *
1718
- * Producers call `push(event)` to deliver events. Consumers iterate with
1719
- * `for await (const event of stream)`. The stream terminates when an event
1720
- * matches the `isComplete` predicate; `result()` resolves with the extracted
1721
- * final value.
1722
- */
1723
- declare class EventStream<T, R = T> implements AsyncIterable<T> {
1724
- private queue;
1725
- private waiting;
1726
- private done;
1727
- private finalResultPromise;
1728
- private resolveFinalResult;
1729
- private isComplete;
1730
- private extractResult;
1731
- constructor(isComplete: (event: T) => boolean, extractResult: (event: T) => R);
1732
- push(event: T): void;
1733
- end(result?: R): void;
1734
- [Symbol.asyncIterator](): AsyncIterator<T>;
1735
- result(): Promise<R>;
1736
- }
1737
- /**
1738
- * Agent-level event stream that terminates on `agent_end`.
1739
- * `result()` resolves with the final messages array.
1740
- */
1741
- declare class AgentEventStream extends EventStream<AgentEvent, AgentMessage[]> {
1742
- constructor();
1743
- }
1744
-
1745
- /** Error thrown when the model returns an empty response (no text, no tool calls). */
1746
- declare class EmptyResponseError extends Error {
1747
- readonly code = "empty_response";
1748
- constructor(message?: string);
1554
+ declare class InMemoryRuntimeStateStore implements RuntimeStateStore {
1555
+ private readonly agents;
1556
+ private readonly messages;
1557
+ private readonly runs;
1558
+ private readonly toolCalls;
1559
+ private readonly events;
1560
+ private readonly eventCheckpoints;
1561
+ createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1562
+ getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1563
+ listAgents(): Promise<AgentRecord[]>;
1564
+ setAgentState(agentId: AgentId, state: AgentRecord["state"]): Promise<AgentRecord>;
1565
+ enqueueAgentInput(input: EnqueueAgentInput): Promise<EnqueuedAgentInput>;
1566
+ private enqueueAgentInputState;
1567
+ getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1568
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1569
+ listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1570
+ listActiveRuns(): Promise<AgentRunRecord[]>;
1571
+ leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1572
+ renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1573
+ suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1574
+ completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1575
+ retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1576
+ exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1577
+ abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1578
+ recoverExpiredLeases(input?: Date): Promise<AgentRunRecord[]>;
1579
+ recoverLeases(): Promise<AgentRunRecord[]>;
1580
+ createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1581
+ startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1582
+ completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1583
+ markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1584
+ getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1585
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1586
+ recordEvent(input: RecordRuntimeEventInput | RuntimeEventKind, related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">, payload?: unknown): Promise<RuntimeEvent>;
1587
+ getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1588
+ acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1589
+ acknowledgeEventAndEnqueueAgentInput(input: AcknowledgeEventAndEnqueueAgentInput): Promise<AcknowledgeEventAndEnqueueAgentInputResult>;
1590
+ private requireAgent;
1591
+ private requireMessage;
1592
+ private requireRun;
1593
+ private requireToolCall;
1594
+ private recordEventInternal;
1749
1595
  }
1750
1596
 
1751
- interface SystemPromptOptions {
1752
- /** Base system prompt. */
1753
- systemPrompt: string;
1754
- /** Additional guideline bullets appended to the default runtime instructions. */
1755
- promptGuidelines?: string[];
1756
- /** Text to append after the default runtime instructions. */
1757
- appendSystemPrompt?: string;
1758
- /** Active tools — snippets and guidelines are included in the prompt. */
1759
- tools?: Array<{
1760
- name: string;
1761
- description?: string;
1762
- promptSnippet?: string;
1763
- promptGuidelines?: string[];
1764
- }>;
1765
- /** Loaded skills — serialized into the prompt. */
1766
- skills?: Array<{
1767
- name: string;
1768
- description: string;
1769
- filePath: string;
1770
- disableModelInvocation?: boolean;
1771
- }>;
1772
- /** Working directory. */
1773
- cwd?: string;
1597
+ declare class SqliteRuntimeStateStore implements RuntimeStateStore {
1598
+ private readonly database;
1599
+ constructor(filename?: string);
1600
+ close(): void;
1601
+ createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1602
+ getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1603
+ listAgents(): Promise<AgentRecord[]>;
1604
+ setAgentState(agentId: AgentId, state: AgentRecord["state"]): Promise<AgentRecord>;
1605
+ enqueueAgentInput(input: EnqueueAgentInput): Promise<EnqueuedAgentInput>;
1606
+ private enqueueAgentInputState;
1607
+ getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1608
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1609
+ listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1610
+ listActiveRuns(): Promise<AgentRunRecord[]>;
1611
+ leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1612
+ renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1613
+ suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1614
+ completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1615
+ retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1616
+ exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1617
+ abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1618
+ recoverExpiredLeases(input?: Date): Promise<AgentRunRecord[]>;
1619
+ recoverLeases(): Promise<AgentRunRecord[]>;
1620
+ createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1621
+ startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1622
+ completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1623
+ markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1624
+ getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1625
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1626
+ recordEvent(input: RecordRuntimeEventInput | RuntimeEventKind, related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">, payload?: unknown): Promise<RuntimeEvent>;
1627
+ getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1628
+ acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1629
+ acknowledgeEventAndEnqueueAgentInput(input: AcknowledgeEventAndEnqueueAgentInput): Promise<AcknowledgeEventAndEnqueueAgentInputResult>;
1630
+ private acknowledgeEventState;
1631
+ private insertMessage;
1632
+ private agentFromRow;
1633
+ private messageFromRow;
1634
+ private runFromRow;
1635
+ private eventFromRow;
1636
+ private toolCallFromRow;
1637
+ private messageRow;
1638
+ private runRow;
1639
+ private requireAgent;
1640
+ private requireMessage;
1641
+ private requireRun;
1642
+ private requireToolCall;
1643
+ private requireEvent;
1644
+ private eventCheckpoint;
1645
+ private recordEventInternal;
1774
1646
  }
1775
- declare function buildSystemPrompt(options: SystemPromptOptions): string;
1776
-
1777
- declare function serializeSkills(skills: Skill$1[]): Array<{
1778
- name: string;
1779
- description: string;
1780
- filePath: string;
1781
- disableModelInvocation?: boolean;
1782
- }>;
1783
- declare function latestUserInput(messages: AgentMessage[]): string;
1784
- declare function conversationMessages(messages: AgentMessage[]): LlmMessage[];
1785
- /** Input for building an LLM request — generic, not phase-specific. */
1786
- type ModelRequestInput = {
1787
- systemPrompt: string;
1788
- messages: AgentMessage[];
1789
- tools: Array<{
1790
- name: string;
1791
- description: string;
1792
- parameters: unknown;
1793
- promptSnippet?: string;
1794
- promptGuidelines?: string[];
1795
- }>;
1796
- skills: Skill$1[];
1797
- promptGuidelines?: string[];
1798
- appendSystemPrompt?: string;
1799
- };
1800
- declare function buildModelRequest(input: ModelRequestInput, options?: {
1801
- model?: LlmModelRef;
1802
- }): LlmRequest;
1803
1647
 
1804
- export { type AbortEvent, type AfterPhaseEvent, type AfterPhaseHookResult, type AfterPhaseResult, type AfterToolCallEvent, type AfterToolCallResult, Agent, type AgentConfigFile, type AgentContext, type AgentEndEvent, AgentEventStream, type AgentOptions, type AgentStartEvent, type AgentStatus, type BeforePhaseEvent, type BeforePhaseHookResult, type BeforePhaseResult, type BeforePromptEvent, type BeforePromptResult, type BeforeToolCallEvent, type BeforeToolCallResult, EmptyResponseError, type EventBus, EventStream, type ExecOptions, type ExecResult, type ExecutionTurn, type Extension, type ExtensionAPI, type ExtensionContext, type ExtensionError, type ExtensionErrorListener, type ExtensionFactory, type ExtensionManifest, type ExtensionPackageManifest, ExtensionRunner, type ExtensionRunnerOptions, type ExtensionRuntime, type ExtensionUtils, HookError, type HookEvent, type HookEventType, type HookHandler, type HookResultMap, HooksManager, type LoadExtensionsResult, type LoadedExtension, LocalJsonlSessionManager, type LoopMetrics, type MessageEndEvent, type MessageStartEvent, type MessageUpdateEvent, type ModelConfigFromFile, type ModelTranscript, type Phase, type PhaseContext, type PhaseDefinition, type PhaseExecution, type PhaseOutput, type PhaseRegistration, type PhaseRegistry, type PhaseRun, type PhaseState, type ProviderConfigFromFile, type QueueUpdateEvent, type RegisteredPhase, type RegisteredTool, type RunOptions, type RunResult, type SavePointEvent, type Session, type SessionListItem, type SettledEvent, type SourceInfo, type Tool, type ToolDefinition, type ToolExecutionEndEvent, type ToolExecutionResult, type ToolExecutionStartEvent, type ToolExecutionUpdateEvent, type TurnEndEvent, type TurnStartEvent, type WorkspacePaths, appendUserTurn, buildModelRequest, buildSystemPrompt, conversationMessages, createCoreTools, createEventBus, createExtension, createExtensionAPI, createExtensionRunner, createExtensionRuntime, createId, createMessage, createSession, createSourceInfo, createTimestamp, getGlobalHooks, interpolateEnvVars, latestUserInput, loadConfigFile, loadPhase, loadPhases, messageContentText, parseModelRef, registerConfigModels, reloadPhases, resetGlobalHooks, resolveDefaultModel, resolveInWorkspace, resolveWorkspacePaths, serializeSkills };
1648
+ 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 RuntimeToolCall, type RuntimeToolCallId, type SessionManagerProvider, SqliteRuntimeStateStore, type Tool, type ToolContext, type ToolDefinition, type ToolExecutionMode, type ToolExecutionResult, type ToolRuntimePolicy, type Unsubscribe, createCoreTools, createMessage };