@rowan-agent/agent 0.5.5 → 0.6.0

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 +256 -320
  2. package/dist/index.d.ts +666 -886
  3. package/dist/index.js +2213 -499
  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, LlmModelRef, LlmModelUsage, StreamFn, AgentEventListener, AgentMessage, Outcome, ToolCall, ToolResult, Skill as Skill$1, ContentBlock } from '@rowan-agent/models';
3
+ export { AgentEvent, AgentEventListener, AgentMessage, LlmModelRef, Outcome, Skill, StreamFn, ToolResult } from '@rowan-agent/models';
4
4
  import Type from 'typebox';
5
5
 
6
6
  type ExecutionTurn = {
@@ -13,16 +13,127 @@ type ExecutionTurn = {
13
13
  model: LlmModelRef;
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
+ type BeforePhaseHook = (phaseId: string, input: PhaseContext) => Promise<BeforePhaseHookResult>;
23
+ type AfterPhaseHook = (phaseId: string, output: PhaseOutput) => Promise<AfterPhaseHookResult>;
24
+ type BeforePromptHook = (phaseId: string, input: PhaseContext) => Promise<PhaseContext>;
25
+ type LoopMetrics = {
26
+ /** Number of phase iterations executed. */
27
+ iterations: number;
28
+ /** Phase transition history. */
29
+ phaseTransitions: Array<{
30
+ from: string;
31
+ to: string;
32
+ ts: string;
33
+ }>;
34
+ /** Number of times compaction was triggered. */
35
+ compactionCount: number;
36
+ /** Number of retry attempts due to transient errors. */
37
+ retryCount: number;
38
+ /** Loop start timestamp. */
39
+ startedAt: string;
40
+ /** Loop start time as epoch ms (for duration calculation). */
41
+ startedAtMs: number;
42
+ /** Loop end timestamp (set on completion). */
43
+ endedAt?: string;
44
+ /** Total wall-clock duration in ms. */
45
+ durationMs?: number;
46
+ };
47
+ type SessionState = {
48
+ currentPhase: string;
49
+ attempt: number;
50
+ metrics: LoopMetrics;
51
+ status: "idle" | "running" | "completed" | "aborted" | "failed";
52
+ };
53
+ type AgentConfig = {
54
+ model: LlmModelRef;
55
+ stream: StreamFn;
56
+ context: AgentContext;
57
+ sessionId?: string;
58
+ sessionState?: SessionState;
59
+ maxAttempts?: number;
60
+ runtime?: AgentRuntimePort;
61
+ emit?: AgentEventListener;
62
+ signal?: AbortSignal;
63
+ beforeToolCall?: BeforeToolCall;
64
+ afterToolCall?: AfterToolCall;
65
+ beforePhase?: BeforePhaseHook;
66
+ afterPhase?: AfterPhaseHook;
67
+ beforePrompt?: BeforePromptHook;
68
+ onModelTranscript?: (transcript: ModelTranscript, meta: {
69
+ phase: string;
70
+ model: LlmModelRef;
71
+ }) => Promise<void>;
72
+ onMessage?: (message: AgentMessage) => Promise<void>;
73
+ onOutcome?: (outcome: Outcome) => Promise<void>;
74
+ /** Internal: await next user messages before retrying the same phase. */
75
+ waitForInput?: () => Promise<AgentMessage[]>;
76
+ };
77
+ type ToolRunnerInput = {
78
+ config: AgentConfig;
79
+ toolCall: ToolCall;
80
+ };
81
+ type ToolRunner = (input: ToolRunnerInput) => Promise<ToolResult>;
82
+ type AgentRuntimePort = {
83
+ tools?: ToolRunner;
84
+ };
85
+
86
+ type ToolContext = Pick<AgentContext, "skills"> & {
87
+ toolCallId: string;
88
+ };
89
+ type ToolExecutionMode = "sequential" | "parallel";
90
+ type Tool<TArgs = unknown> = {
91
+ name: string;
92
+ description: string;
93
+ parameters: Type.TSchema;
94
+ /** One-line snippet shown in the system prompt tool list. */
95
+ promptSnippet?: string;
96
+ /** Additional guidelines appended to the system prompt when this tool is active. */
97
+ promptGuidelines?: string[];
98
+ /** Whether this tool can run concurrently with others. Default: "parallel". */
99
+ executionMode?: ToolExecutionMode;
100
+ execute(args: TArgs, context: ToolContext, signal?: AbortSignal): Promise<ToolResult>;
101
+ };
102
+ /** Context snapshot passed into the low-level agent loop. */
103
+ type AgentContext = {
104
+ /** System prompt included with the request. */
105
+ systemPrompt: string;
106
+ /** Transcript visible to the model. */
107
+ messages: AgentMessage[];
108
+ /** Tools available for this run. */
109
+ tools: Tool[];
110
+ /** Skills available for this run. */
111
+ skills: Skill$1[];
112
+ /** Custom phases for this run. Agent normalizes this with the built-in default phase. */
113
+ phases?: PhaseRegistry;
114
+ };
115
+ type BeforeToolCall = (input: {
116
+ tool: Tool;
117
+ args: unknown;
118
+ }) => Promise<{
119
+ allow: true;
120
+ } | {
121
+ allow: false;
122
+ reason: string;
123
+ }>;
124
+ type AfterToolCall = (input: {
125
+ tool: Tool;
126
+ result: ToolResult;
127
+ }) => Promise<ToolResult>;
128
+ type RunResult = {
129
+ sessionId: string;
130
+ messages: AgentMessage[];
131
+ outcome: Outcome;
132
+ metrics: LoopMetrics;
133
+ };
134
+ type Unsubscribe = () => void;
135
+ declare function createMessage(role: AgentMessage["role"], content: AgentMessage["content"], metadata?: Record<string, unknown>): AgentMessage;
136
+
26
137
  type ModelInvokeOutput = {
27
138
  text: string;
28
139
  contentBlocks: ContentBlock[];
@@ -46,19 +157,93 @@ type PhaseExecution = {
46
157
  executeTool(context: AgentContext, toolCall: ToolCall): Promise<ToolResult>;
47
158
  };
48
159
 
160
+ /** Unified phase output — model decides routing via route. */
161
+ type PhaseOutput = {
162
+ message: string;
163
+ /** Route to next phase, or "continue" to re-execute current phase, or "stop" to end */
164
+ route: string;
165
+ /** Phase name that produced this output */
166
+ phase?: string;
167
+ /** Tool calls from the model invocation (used by framework for route extraction) */
168
+ toolCalls?: Array<{
169
+ id: string;
170
+ name: string;
171
+ args: unknown;
172
+ }>;
173
+ /** Route reason extracted from route tool call (for hooks to inspect) */
174
+ routeReason?: string;
175
+ /** Structured data from this phase, passed to the next phase */
176
+ payload?: unknown;
177
+ };
178
+ /** Phase machine state — tracks position and inter-phase data */
179
+ interface PhaseState {
180
+ current: string;
181
+ available: string[];
182
+ iterations: number;
183
+ payload?: unknown;
184
+ }
185
+ /** Everything a phase needs to execute */
186
+ interface PhaseContext {
187
+ systemPrompt: string;
188
+ messages: AgentMessage[];
189
+ /** Phase-filtered tools */
190
+ tools: Tool[];
191
+ /** Phase-filtered skills */
192
+ skills: Skill$1[];
193
+ /** Phase machine state */
194
+ state: PhaseState;
195
+ /** Additional guideline bullets appended to the system prompt */
196
+ promptGuidelines?: string[];
197
+ /** Text to append after the system prompt */
198
+ appendSystemPrompt?: string;
199
+ }
200
+ /**
201
+ * Loaded Phase object
202
+ */
203
+ interface Phase {
204
+ /** Unique identifier */
205
+ id: string;
206
+ /** Display name */
207
+ name: string;
208
+ /** Description */
209
+ description: string;
210
+ /** Restricted tools (undefined = all tools available) */
211
+ tools?: string[];
212
+ /** Restricted skills (undefined = all skills available) */
213
+ skills?: string[];
214
+ /** Forced next phase */
215
+ target?: string;
216
+ /** Expected input fields (key → description) */
217
+ input?: Record<string, string>;
218
+ /** If true, phase gets a fresh context when executed in parallel */
219
+ isolated?: boolean;
220
+ /** Path to PHASE.md file */
221
+ filePath: string;
222
+ /** Phase directory path */
223
+ baseDir: string;
224
+ /** PHASE.md body content */
225
+ content: string;
226
+ /** Model override for this phase (resolved from frontmatter) */
227
+ model?: LlmModelRef;
228
+ /** ExtensionAPI factory function (default export pattern) */
229
+ factory?: (api: ExtensionAPI) => Promise<void>;
230
+ /** Legacy run function */
231
+ run?: (context: PhaseContext, execution: PhaseExecution) => Promise<PhaseOutput | void>;
232
+ }
233
+ /**
234
+ * Phase registry containing all loaded phases
235
+ */
236
+ interface PhaseRegistry {
237
+ /** Map of phase id to Phase object */
238
+ phases: Map<string, Phase>;
239
+ /** Entry phase id (null until Agent applies its default phase) */
240
+ entryPhaseId: string | null;
241
+ }
242
+
49
243
  /**
50
244
  * Extension types — simplified for the new hook-based system.
51
245
  */
52
246
 
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
247
  /** Phase run function type for extensions */
63
248
  type PhaseRun = (context: PhaseContext, execution: PhaseExecution) => Promise<PhaseOutput | void>;
64
249
  /** Phase definition shape used by extensions */
@@ -77,24 +262,6 @@ type PhaseRegistration = Partial<Omit<PhaseDefinition, 'run'>> & {
77
262
  /** Optional execution override — takes over model invocation */
78
263
  run?: PhaseRun;
79
264
  };
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
265
  /**
99
266
  * Tool definition for registering LLM-callable tools via `api.registerTool()`.
100
267
  *
@@ -135,28 +302,6 @@ interface ToolExecutionResult {
135
302
  /** Whether this is an error result */
136
303
  isError?: boolean;
137
304
  }
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
305
  type ExecOptions = {
161
306
  /** Working directory for the command. Defaults to cwd passed to runtime. */
162
307
  cwd?: string;
@@ -185,65 +330,6 @@ type AfterPhaseHookResult = {
185
330
  retry?: PhaseContext;
186
331
  output?: PhaseOutput;
187
332
  };
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
333
  /**
248
334
  * Result of loading extensions from filesystem.
249
335
  * The runner takes these and creates Extension tracking objects.
@@ -308,7 +394,6 @@ interface EventBus {
308
394
  /** Get listener count for an event. */
309
395
  count(event: string): number;
310
396
  }
311
- declare function createEventBus(): EventBus;
312
397
 
313
398
  /**
314
399
  * @module extensions/hooks
@@ -683,91 +768,6 @@ type HookEventType = HookEvent["type"];
683
768
  type HookHandler<K extends HookEventType> = (event: Extract<HookEvent, {
684
769
  type: K;
685
770
  }>) => HookResultMap[K] | Promise<HookResultMap[K]> | void | Promise<void>;
686
- /**
687
- * Hook execution error
688
- */
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
- }
696
- /**
697
- * Type-safe hook manager.
698
- *
699
- * ## Usage
700
- *
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
771
 
772
772
  /**
773
773
  * @module extensions/context
@@ -924,435 +924,120 @@ interface ExtensionAPI {
924
924
  * Receives ExtensionAPI for registering hooks, phases, and providers.
925
925
  */
926
926
  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
927
 
954
- type ExtensionRunnerOptions = {
955
- entryPhaseId?: string | null;
956
- cwd?: string;
928
+ declare const opaqueIdBrand: unique symbol;
929
+ type OpaqueId<Kind extends string> = string & {
930
+ readonly [opaqueIdBrand]: Kind;
957
931
  };
958
- /**
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();
972
- *
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
- * });
982
- *
983
- * // Load extensions
984
- * await runner.loadExtensions(extensions);
985
- * runner.bind();
986
- * ```
987
- */
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;
1145
-
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;
932
+ type AgentId = OpaqueId<"AgentId">;
933
+ type AgentRunId = OpaqueId<"AgentRunId">;
934
+ type RuntimeMessageId = OpaqueId<"RuntimeMessageId">;
935
+ type RuntimeEventId = OpaqueId<"RuntimeEventId">;
936
+ type LeaseId = OpaqueId<"LeaseId">;
937
+ type RuntimeToolCallId = OpaqueId<"RuntimeToolCallId">;
938
+ type AgentLifecycleState = "active" | "paused";
939
+ type RuntimeMessageState = "queued" | "leased" | "acknowledged" | "dead_lettered";
940
+ type AgentRunState = "queued" | "running" | "suspended" | "completed" | "failed" | "cancelled";
941
+ type RuntimeToolCallState = "queued" | "running" | "completed" | "failed" | "indeterminate";
942
+ type AgentRecord = {
943
+ id: AgentId;
944
+ sessionId: string;
945
+ factoryId?: string;
946
+ state: AgentLifecycleState;
947
+ createdAt: string;
948
+ updatedAt: string;
1167
949
  };
1168
- type SessionState = {
1169
- currentPhase: string;
1170
- attempt: number;
1171
- metrics: LoopMetrics;
1172
- status: "idle" | "running" | "completed" | "aborted" | "failed";
950
+ type RuntimeLease = {
951
+ id: LeaseId;
952
+ runId: AgentRunId;
953
+ workerId: string;
954
+ leasedAt: string;
955
+ expiresAt: string;
1173
956
  };
1174
-
1175
- type ToolContext = Pick<AgentContext, "skills"> & {
1176
- toolCallId: string;
957
+ type RuntimeMessage = {
958
+ id: RuntimeMessageId;
959
+ agentId: AgentId;
960
+ kind: "agent_input";
961
+ input: AgentMessage;
962
+ state: RuntimeMessageState;
963
+ attempts: number;
964
+ runId?: AgentRunId;
965
+ lease?: RuntimeLease;
966
+ deadLetterReason?: string;
967
+ createdAt: string;
968
+ updatedAt: string;
1177
969
  };
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>;
970
+ type AgentRunRecord = {
971
+ id: AgentRunId;
972
+ agentId: AgentId;
973
+ messageId: RuntimeMessageId;
974
+ state: AgentRunState;
975
+ attempt: number;
976
+ leaseId?: LeaseId;
977
+ outcome?: Outcome;
978
+ suspensionReason?: string;
979
+ createdAt: string;
980
+ updatedAt: string;
1190
981
  };
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;
982
+ type RuntimeEventKind = "agent_created" | "agent_paused" | "agent_resumed" | "agent_recovered" | "agent_recovery_failed" | "factory_missing" | "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";
983
+ type RuntimeEvent = {
984
+ id: RuntimeEventId;
985
+ sequence: number;
986
+ kind: RuntimeEventKind;
987
+ agentId?: AgentId;
988
+ messageId?: RuntimeMessageId;
989
+ runId?: AgentRunId;
990
+ toolCallId?: RuntimeToolCallId;
991
+ payload?: unknown;
992
+ createdAt: string;
1203
993
  };
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;
994
+ type RuntimeEventCursor = {
995
+ after?: RuntimeEventId;
996
+ limit?: number;
1222
997
  };
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;
998
+ type RuntimeEventCheckpoint = {
999
+ consumerId: string;
1000
+ sequence: number;
1001
+ eventId?: RuntimeEventId;
1002
+ updatedAt: string;
1244
1003
  };
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 */
1004
+ type RuntimeToolCall = {
1005
+ id: RuntimeToolCallId;
1006
+ agentId: AgentId;
1007
+ runId: AgentRunId;
1274
1008
  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;
1009
+ args: unknown;
1010
+ state: RuntimeToolCallState;
1011
+ result?: ToolResult;
1012
+ indeterminateReason?: string;
1013
+ createdAt: string;
1014
+ updatedAt: string;
1319
1015
  };
1320
- declare function resolveWorkspacePaths(options?: ResolveWorkspaceOptions): WorkspacePaths;
1321
- declare function resolveInWorkspace(path: string, rootOrPaths: string | Pick<WorkspacePaths, "cwd">): string;
1322
1016
 
1323
- type PhaseLoadTarget = string | Pick<WorkspacePaths, "rowanDir">;
1324
1017
  /**
1325
- * Load a single phase from a PHASE.md file or phase directory.
1018
+ * Load all phases from the target directory.
1326
1019
  *
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.
1020
+ * Scans for subdirectories containing PHASE.md files.
1021
+ * Returns PhaseRegistry with entryPhaseId:
1022
+ * - null by default (caller must explicitly set to start from a specific phase)
1023
+ * - Set to a specific phase id to start from that phase
1024
+ *
1025
+ * When entryPhaseId is null, Agent normalizes the registry to start from its default phase.
1334
1026
  */
1335
- declare function reloadPhases(registry: PhaseRegistry): Promise<void>;
1027
+ declare function loadPhases(targetPath: string): Promise<PhaseRegistry>;
1336
1028
 
1337
- type AgentOptions = {
1338
- context: AgentContext;
1339
- model: LlmModelRef;
1340
- stream: StreamFn;
1341
- cwd?: string;
1342
- extensions?: LoadedExtension[];
1029
+ type AgentExecutionOptions = AgentOptions & {
1343
1030
  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>;
1031
+ agentId?: AgentId;
1032
+ onInput?: (message: AgentMessage) => Promise<void>;
1033
+ runtime?: AgentRuntimePort;
1034
+ };
1035
+ type RunOptions = Partial<AgentExecutionOptions>;
1036
+ type RuntimeRunHooks = {
1037
+ onSuspend?: (reason?: string) => Promise<void> | void;
1353
1038
  };
1354
- type RunOptions = Partial<AgentOptions>;
1355
1039
  type AgentStatus = {
1040
+ agentId?: AgentId;
1356
1041
  sessionId?: string;
1357
1042
  context: AgentContext;
1358
1043
  model: LlmModelRef;
@@ -1362,7 +1047,7 @@ type AgentStatus = {
1362
1047
  currentResult?: RunResult;
1363
1048
  error?: string;
1364
1049
  };
1365
- declare class Agent {
1050
+ declare class AgentExecution {
1366
1051
  readonly state: AgentStatus;
1367
1052
  private options;
1368
1053
  private readonly listeners;
@@ -1372,16 +1057,21 @@ declare class Agent {
1372
1057
  private extensionRunner?;
1373
1058
  private loadedExtensions?;
1374
1059
  private loadedExtensionsCwd?;
1060
+ private runtimeRunId?;
1061
+ get id(): AgentId;
1062
+ get sessionId(): string;
1375
1063
  static loadSkills(targetPath: string): Promise<AgentContext["skills"]>;
1376
1064
  static loadPhases(targetPath: Parameters<typeof loadPhases>[0]): Promise<PhaseRegistry>;
1377
1065
  static loadExtensions(targetPath: string): Promise<LoadExtensionsResult>;
1378
- constructor(options: AgentOptions);
1066
+ constructor(options: AgentExecutionOptions);
1379
1067
  subscribe(listener: AgentEventListener): Unsubscribe;
1380
1068
  appendUserMessage(input: string): void;
1381
1069
  appendMessage(message: AgentMessage): void;
1382
1070
  appendMessages(messages: AgentMessage[]): void;
1383
1071
  runWithUserInput(input: string, options?: RunOptions): Promise<RunResult>;
1384
- runWithMessage(message: AgentMessage, options?: RunOptions): Promise<RunResult>;
1072
+ runWithMessage(message: AgentMessage, options?: RunOptions, internalHooks?: RuntimeRunHooks): Promise<RunResult>;
1073
+ /** Internal Runtime seam: executes one leased Agent Input. */
1074
+ executeAgentInput(input: AgentMessage, runId: AgentRunId, control: AgentRunControl): Promise<Outcome>;
1385
1075
  resetInitialization(): void;
1386
1076
  getContext(): AgentContext;
1387
1077
  setContext(context: AgentContext): void;
@@ -1392,11 +1082,14 @@ declare class Agent {
1392
1082
  clearMessages(): void;
1393
1083
  getTranscript(): AgentMessage[];
1394
1084
  replaceTranscript(messages: AgentMessage[]): void;
1395
- getConfig(): AgentOptions;
1396
- setConfig(config: AgentOptions): void;
1397
- updateConfig(updater: (config: AgentOptions) => AgentOptions): void;
1085
+ getConfig(): AgentExecutionOptions;
1086
+ setConfig(config: AgentExecutionOptions): void;
1087
+ updateConfig(updater: (config: AgentExecutionOptions) => AgentExecutionOptions): void;
1398
1088
  setSessionId(sessionId: string): void;
1399
1089
  getSessionId(): string | undefined;
1090
+ getAgentId(): AgentId | undefined;
1091
+ /** Internal Runtime hook for associating Tool Calls with the leased Run. */
1092
+ getRuntimeRunId(): AgentRunId | undefined;
1400
1093
  setModel(model: LlmModelRef): void;
1401
1094
  setTools(tools: Tool[]): void;
1402
1095
  setSkills(skills: Skill$1[]): void;
@@ -1440,8 +1133,11 @@ declare class Agent {
1440
1133
  private runWithLifecycle;
1441
1134
  private finishRun;
1442
1135
  private loadExtensions;
1443
- run(config?: RunOptions): Promise<RunResult>;
1136
+ run(config?: RunOptions, internalHooks?: RuntimeRunHooks): Promise<RunResult>;
1444
1137
  abort(reason?: string): void;
1138
+ private abortLocal;
1139
+ /** Internal Runtime hook; public callers abort a precise AgentRun. */
1140
+ abortFromRuntime(reason?: string): void;
1445
1141
  /**
1446
1142
  * Get formatted skill content for LLM consumption.
1447
1143
  *
@@ -1469,9 +1165,6 @@ declare class Agent {
1469
1165
  private cloneOptions;
1470
1166
  }
1471
1167
 
1472
- declare function createId(prefix: string): string;
1473
- declare function createTimestamp(date?: Date): string;
1474
-
1475
1168
  declare const SkillSchema: Type.TObject<{
1476
1169
  name: Type.TString;
1477
1170
  description: Type.TString;
@@ -1481,89 +1174,7 @@ declare const SkillSchema: Type.TObject<{
1481
1174
  disableModelInvocation: Type.TBoolean;
1482
1175
  }>;
1483
1176
  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
1177
 
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
1178
  type SessionAgentContext<TTool = unknown> = {
1568
1179
  systemPrompt: string;
1569
1180
  messages: AgentMessage[];
@@ -1593,79 +1204,278 @@ type SessionListItem = {
1593
1204
  };
1594
1205
  type SessionManager = {
1595
1206
  getSessionId(): string;
1596
- getSessionFile(): string | undefined;
1597
- getHeader(): Promise<SessionHeader>;
1598
1207
  appendMessage(message: AgentMessage): Promise<string>;
1599
1208
  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
1209
  appendModelTranscript(transcript: ModelTranscript, meta?: {
1618
1210
  phase?: string;
1619
1211
  model?: LlmModelRef;
1620
1212
  }): Promise<string>;
1621
- getSessionState(): Promise<SessionState | undefined>;
1622
- branch(entryId: string | null): Promise<void>;
1623
1213
  buildAgentContext<TTool = unknown>(input?: BuildAgentContextInput<TTool>): Promise<SessionAgentContext<TTool>>;
1624
- listEntries(): Promise<SessionEntry[]>;
1625
- loadExecutionTurns(filter?: StepFilter): Promise<ExecutionTurn[]>;
1214
+ };
1215
+ type SessionManagerProvider = {
1216
+ create(input: CreateSessionManagerInput): Promise<SessionManager>;
1217
+ open(sessionId: string): Promise<SessionManager | undefined>;
1626
1218
  };
1627
1219
 
1628
- declare class LocalJsonlSessionManager implements SessionManager {
1629
- private readonly sessionsDir;
1630
- private readonly filePath;
1631
- private readonly inner;
1220
+ type CreateAgentInput = {
1221
+ sessionId: string;
1222
+ factoryId?: string;
1223
+ };
1224
+ type EnqueueAgentInput = {
1225
+ agentId: AgentId;
1226
+ input: AgentMessage;
1227
+ };
1228
+ type ListRunsInput = {
1229
+ agentId?: AgentId;
1230
+ states?: AgentRunRecord["state"][];
1231
+ };
1232
+ type RecordRuntimeEventInput = {
1233
+ kind: RuntimeEventKind;
1234
+ related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">;
1235
+ payload?: unknown;
1236
+ };
1237
+ type LeaseRunInput = {
1238
+ runId: AgentRunId;
1239
+ workerId: string;
1240
+ leaseDurationMs: number;
1241
+ now?: Date;
1242
+ };
1243
+ type LeasedRun = {
1244
+ run: AgentRunRecord;
1245
+ message: RuntimeMessage;
1246
+ lease: RuntimeLease;
1247
+ };
1248
+ type RenewLeaseInput = {
1249
+ runId: AgentRunId;
1250
+ leaseId: LeaseId;
1251
+ leaseDurationMs: number;
1252
+ now?: Date;
1253
+ };
1254
+ type SuspendRunInput = {
1255
+ runId: AgentRunId;
1256
+ reason?: string;
1257
+ };
1258
+ type CompleteRunInput = {
1259
+ runId: AgentRunId;
1260
+ outcome: Outcome;
1261
+ state?: Extract<AgentRunRecord["state"], "completed" | "failed" | "cancelled">;
1262
+ };
1263
+ type RetryRunInput = {
1264
+ runId: AgentRunId;
1265
+ reason: string;
1266
+ };
1267
+ type ExhaustRunInput = {
1268
+ runId: AgentRunId;
1269
+ outcome: Outcome;
1270
+ reason: string;
1271
+ };
1272
+ type AbortRunInput = {
1273
+ runId: AgentRunId;
1274
+ outcome: Outcome;
1275
+ };
1276
+ type CreateToolCallInput = {
1277
+ agentId: AgentId;
1278
+ runId: AgentRunId;
1279
+ name: string;
1280
+ args: unknown;
1281
+ };
1282
+ type CompleteToolCallInput = {
1283
+ toolCallId: RuntimeToolCallId;
1284
+ result: ToolResult;
1285
+ state?: Extract<RuntimeToolCall["state"], "completed" | "failed">;
1286
+ };
1287
+ type IndeterminateToolCallInput = {
1288
+ toolCallId: RuntimeToolCallId;
1289
+ reason: string;
1290
+ };
1291
+ interface RuntimeStateStore {
1292
+ createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1293
+ getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1294
+ listAgents(): Promise<AgentRecord[]>;
1295
+ setAgentState(agentId: AgentId, state: AgentLifecycleState): Promise<AgentRecord>;
1296
+ enqueueAgentInput(input: EnqueueAgentInput): Promise<{
1297
+ message: RuntimeMessage;
1298
+ run: AgentRunRecord;
1299
+ resumed: boolean;
1300
+ }>;
1301
+ getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1302
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1303
+ listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1304
+ leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1305
+ renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1306
+ suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1307
+ completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1308
+ retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1309
+ exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1310
+ abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1311
+ recoverExpiredLeases(now?: Date): Promise<AgentRunRecord[]>;
1312
+ recoverLeases(): Promise<AgentRunRecord[]>;
1313
+ createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1314
+ startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1315
+ completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1316
+ markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1317
+ getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1318
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1319
+ recordEvent(input: RecordRuntimeEventInput): Promise<RuntimeEvent>;
1320
+ getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1321
+ acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1322
+ }
1323
+
1324
+ type ToolRuntimePolicy = {
1325
+ /** A narrowing allow-list. It can never add a Tool to an Agent. */
1326
+ allowedTools?: readonly string[];
1327
+ maxConcurrent?: number;
1328
+ perToolMaxConcurrent?: Readonly<Record<string, number>>;
1329
+ };
1330
+
1331
+ type AgentFactoryIdentity = {
1332
+ agentId: AgentId;
1333
+ sessionId: string;
1334
+ factoryId: string;
1335
+ };
1336
+ type AgentFactory = (identity: AgentFactoryIdentity) => Promise<AgentOptions | undefined> | AgentOptions | undefined;
1337
+ type AgentRuntimeOptions = {
1338
+ stateStore: RuntimeStateStore;
1339
+ sessionProvider?: SessionManagerProvider;
1340
+ factories?: ReadonlyMap<string, AgentFactory> | Readonly<Record<string, AgentFactory>>;
1341
+ toolPolicy?: ToolRuntimePolicy;
1342
+ maxConcurrentRuns?: number;
1343
+ maxInfrastructureAttempts?: number;
1344
+ leaseDurationMs?: number;
1345
+ leaseRenewalIntervalMs?: number;
1346
+ };
1347
+ type RuntimeRunHandle = {
1348
+ notify(run: AgentRunRecord): void;
1349
+ };
1350
+ type RuntimeEventListener = (event: RuntimeEvent) => void | Promise<void>;
1351
+ declare class AgentRuntime {
1352
+ private readonly stateStore;
1353
+ private readonly sessionProvider?;
1354
+ private readonly maxConcurrentRuns;
1355
+ private readonly maxInfrastructureAttempts;
1356
+ private readonly leaseDurationMs;
1357
+ private readonly leaseRenewalIntervalMs;
1358
+ private readonly toolRuntime;
1359
+ private readonly factories;
1360
+ private readonly bindings;
1361
+ private readonly runHandles;
1362
+ private readonly runWaiters;
1363
+ private readonly pendingRuns;
1364
+ private readonly scheduledRunIds;
1365
+ private readonly runningAgents;
1366
+ private readonly pausedAgents;
1367
+ private readonly eventSubscriptions;
1368
+ private readonly activeDispatches;
1369
+ private runningRuns;
1370
+ private pumping;
1371
+ private nextWorkerId;
1372
+ private stopped;
1632
1373
  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;
1374
+ static start(options: AgentRuntimeOptions): Promise<AgentRuntime>;
1375
+ createAgent(options: AgentCreateOptions): Promise<Agent>;
1376
+ reconstructAgent(agentId: AgentId, options: AgentOptions): Promise<Agent>;
1377
+ stop(): Promise<void>;
1378
+ private bindAgent;
1379
+ private registerRunHandle;
1380
+ private waitForRunChange;
1381
+ private scheduleRun;
1382
+ pauseAgent(agentId: AgentId): Promise<void>;
1383
+ resumeAgent(agentId: AgentId): Promise<void>;
1384
+ abortRun(runId: AgentRunId, reason?: string): Promise<void>;
1385
+ consumeEvents(consumerId: string, listener: RuntimeEventListener): () => void;
1386
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1387
+ private recover;
1388
+ private scheduleQueuedRuns;
1389
+ private attachAgent;
1390
+ private submitAgentInput;
1391
+ private pump;
1392
+ private dispatchRun;
1393
+ private finishRun;
1394
+ private finishFailedRun;
1395
+ private notifyRun;
1396
+ private publishEvents;
1397
+ private deliverEvents;
1398
+ private assertRunning;
1399
+ }
1400
+
1401
+ type AgentRunListener = (state: AgentRunState) => void | Promise<void>;
1402
+ type AgentRunHost = {
1403
+ register(handle: RuntimeRunHandle): void;
1404
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1405
+ waitForRunChange(runId: AgentRunId, state: AgentRunState, updatedAt: string): Promise<void>;
1406
+ abortRun(runId: AgentRunId, reason: string): Promise<void>;
1407
+ consumeEvents(consumerId: string, listener: RuntimeEventListener): () => void;
1408
+ };
1409
+ declare const CREATE_AGENT_RUN: unique symbol;
1410
+ declare class AgentRun implements RuntimeRunHandle {
1411
+ private readonly host;
1412
+ private readonly publicMessageId;
1413
+ private current;
1414
+ private readonly listeners;
1415
+ private constructor();
1416
+ static [CREATE_AGENT_RUN](host: AgentRunHost, initial: AgentRunRecord, publicMessageId: string): AgentRun;
1417
+ get id(): AgentRunId;
1418
+ get messageId(): string;
1419
+ get status(): AgentRunState;
1420
+ get state(): AgentRunState;
1421
+ getStatus(): Promise<AgentRunState>;
1422
+ subscribe(listener: AgentRunListener): () => void;
1423
+ consumeRuntimeEvents(consumerId: string, listener: RuntimeEventListener): () => void;
1424
+ result(): Promise<Outcome>;
1425
+ abort(reason?: string): Promise<void>;
1426
+ notify(run: AgentRunRecord): void;
1427
+ }
1428
+
1429
+ type AgentOptions = {
1430
+ context: AgentContext;
1431
+ model: LlmModelRef;
1432
+ stream: StreamFn;
1433
+ cwd?: string;
1434
+ extensions?: LoadedExtension[];
1435
+ maxAttempts?: number;
1436
+ beforeToolCall?: BeforeToolCall;
1437
+ afterToolCall?: AfterToolCall;
1438
+ onMessage?: (message: AgentMessage) => Promise<void>;
1439
+ onOutcome?: (outcome: Outcome) => Promise<void>;
1440
+ onModelTranscript?: (transcript: ModelTranscript, meta: {
1441
+ phase: string;
1442
+ model: LlmModelRef;
1443
+ }) => Promise<void>;
1444
+ };
1445
+ type AgentCreateOptions = AgentOptions & {
1446
+ input?: string;
1447
+ factoryId?: string;
1448
+ };
1449
+ type AgentRunControl = {
1450
+ suspend(reason?: string): Promise<void>;
1451
+ };
1452
+ declare const ATTACH_AGENT: unique symbol;
1453
+ declare class Agent {
1454
+ readonly id: AgentId;
1455
+ readonly sessionId: string;
1456
+ private readonly execution;
1457
+ private readonly submitInput;
1458
+ private constructor();
1459
+ static [ATTACH_AGENT](id: AgentId, sessionId: string, execution: AgentExecution, submitInput: (input: AgentMessage) => Promise<AgentRun>): Agent;
1460
+ static loadSkills(targetPath: string): Promise<AgentContext["skills"]>;
1461
+ static loadPhases(targetPath: Parameters<typeof AgentExecution.loadPhases>[0]): Promise<PhaseRegistry>;
1462
+ static loadExtensions(targetPath: string): Promise<LoadExtensionsResult>;
1463
+ subscribe(listener: AgentEventListener): Unsubscribe;
1464
+ flushEvents(): Promise<void>;
1465
+ send(input: string | AgentMessage): Promise<AgentRun>;
1466
+ }
1467
+
1468
+ declare class InMemorySessionProvider implements SessionManagerProvider {
1469
+ private readonly sessions;
1470
+ create(input: CreateSessionManagerInput): Promise<SessionManager>;
1471
+ open(sessionId: string): Promise<SessionManager | undefined>;
1472
+ }
1473
+ declare class LocalJsonlSessionProvider implements SessionManagerProvider {
1474
+ private readonly sessionsDir;
1475
+ constructor(sessionsDir: string);
1476
+ create(input: CreateSessionManagerInput): Promise<SessionManager>;
1477
+ open(sessionId: string): Promise<SessionManager | undefined>;
1478
+ list(): Promise<SessionListItem[]>;
1669
1479
  }
1670
1480
 
1671
1481
  type CoreToolContext = {
@@ -1676,129 +1486,99 @@ type CoreToolContext = {
1676
1486
  };
1677
1487
  declare function createCoreTools(input?: CoreToolContext): Tool[];
1678
1488
 
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);
1749
- }
1750
-
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[];
1489
+ declare class InMemoryRuntimeStateStore implements RuntimeStateStore {
1490
+ private readonly agents;
1491
+ private readonly messages;
1492
+ private readonly runs;
1493
+ private readonly toolCalls;
1494
+ private readonly events;
1495
+ private readonly eventCheckpoints;
1496
+ createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1497
+ getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1498
+ listAgents(): Promise<AgentRecord[]>;
1499
+ setAgentState(agentId: AgentId, state: AgentRecord["state"]): Promise<AgentRecord>;
1500
+ enqueueAgentInput(input: EnqueueAgentInput): Promise<{
1501
+ message: RuntimeMessage;
1502
+ run: AgentRunRecord;
1503
+ resumed: boolean;
1764
1504
  }>;
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;
1505
+ getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1506
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1507
+ listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1508
+ leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1509
+ renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1510
+ suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1511
+ completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1512
+ retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1513
+ exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1514
+ abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1515
+ recoverExpiredLeases(input?: Date): Promise<AgentRunRecord[]>;
1516
+ recoverLeases(): Promise<AgentRunRecord[]>;
1517
+ createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1518
+ startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1519
+ completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1520
+ markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1521
+ getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1522
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1523
+ recordEvent(input: RecordRuntimeEventInput | RuntimeEventKind, related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">, payload?: unknown): Promise<RuntimeEvent>;
1524
+ getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1525
+ acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1526
+ private requireAgent;
1527
+ private requireMessage;
1528
+ private requireRun;
1529
+ private requireToolCall;
1530
+ private recordEventInternal;
1774
1531
  }
1775
- declare function buildSystemPrompt(options: SystemPromptOptions): string;
1776
1532
 
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[];
1533
+ declare class SqliteRuntimeStateStore implements RuntimeStateStore {
1534
+ private readonly database;
1535
+ constructor(filename?: string);
1536
+ close(): void;
1537
+ createAgent(input: CreateAgentInput): Promise<AgentRecord>;
1538
+ getAgent(agentId: AgentId): Promise<AgentRecord | undefined>;
1539
+ listAgents(): Promise<AgentRecord[]>;
1540
+ setAgentState(agentId: AgentId, state: AgentRecord["state"]): Promise<AgentRecord>;
1541
+ enqueueAgentInput(input: EnqueueAgentInput): Promise<{
1542
+ message: RuntimeMessage;
1543
+ run: AgentRunRecord;
1544
+ resumed: boolean;
1795
1545
  }>;
1796
- skills: Skill$1[];
1797
- promptGuidelines?: string[];
1798
- appendSystemPrompt?: string;
1799
- };
1800
- declare function buildModelRequest(input: ModelRequestInput, options?: {
1801
- model?: LlmModelRef;
1802
- }): LlmRequest;
1546
+ getMessage(messageId: RuntimeMessageId): Promise<RuntimeMessage | undefined>;
1547
+ getRun(runId: AgentRunId): Promise<AgentRunRecord | undefined>;
1548
+ listRuns(input?: ListRunsInput): Promise<AgentRunRecord[]>;
1549
+ leaseRun(input: LeaseRunInput): Promise<LeasedRun>;
1550
+ renewLease(input: RenewLeaseInput): Promise<RuntimeLease>;
1551
+ suspendRun(input: SuspendRunInput): Promise<AgentRunRecord>;
1552
+ completeRun(input: CompleteRunInput): Promise<AgentRunRecord>;
1553
+ retryRun(input: RetryRunInput): Promise<AgentRunRecord>;
1554
+ exhaustRun(input: ExhaustRunInput): Promise<AgentRunRecord>;
1555
+ abortRun(input: AbortRunInput): Promise<AgentRunRecord>;
1556
+ recoverExpiredLeases(input?: Date): Promise<AgentRunRecord[]>;
1557
+ recoverLeases(): Promise<AgentRunRecord[]>;
1558
+ createToolCall(input: CreateToolCallInput): Promise<RuntimeToolCall>;
1559
+ startToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall>;
1560
+ completeToolCall(input: CompleteToolCallInput): Promise<RuntimeToolCall>;
1561
+ markToolCallIndeterminate(input: IndeterminateToolCallInput): Promise<RuntimeToolCall>;
1562
+ getToolCall(toolCallId: RuntimeToolCallId): Promise<RuntimeToolCall | undefined>;
1563
+ listEvents(cursor?: RuntimeEventCursor): Promise<RuntimeEvent[]>;
1564
+ recordEvent(input: RecordRuntimeEventInput | RuntimeEventKind, related?: Pick<RuntimeEvent, "agentId" | "messageId" | "runId" | "toolCallId">, payload?: unknown): Promise<RuntimeEvent>;
1565
+ getEventCheckpoint(consumerId: string): Promise<RuntimeEventCheckpoint>;
1566
+ acknowledgeEvent(consumerId: string, eventId: RuntimeEventId): Promise<RuntimeEventCheckpoint>;
1567
+ private insertMessage;
1568
+ private agentFromRow;
1569
+ private messageFromRow;
1570
+ private runFromRow;
1571
+ private eventFromRow;
1572
+ private toolCallFromRow;
1573
+ private messageRow;
1574
+ private runRow;
1575
+ private requireAgent;
1576
+ private requireMessage;
1577
+ private requireRun;
1578
+ private requireToolCall;
1579
+ private requireEvent;
1580
+ private eventCheckpoint;
1581
+ private recordEventInternal;
1582
+ }
1803
1583
 
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 };
1584
+ export { type AfterToolCall, Agent, type AgentContext, type AgentCreateOptions, type AgentFactory, type AgentFactoryIdentity, type AgentId, type AgentOptions, AgentRun, type AgentRunId, type AgentRunListener, type AgentRunState, AgentRuntime, type AgentRuntimeOptions, type BeforeToolCall, type CoreToolContext, type ExecutionTurn, type ExtensionAPI, type ExtensionFactory, type HookEvent, type HookEventType, type HookHandler, InMemoryRuntimeStateStore, InMemorySessionProvider, type LoadExtensionsResult, type LoadedExtension, LocalJsonlSessionProvider, type LoopMetrics, type ModelTranscript, type Phase, type PhaseContext, type PhaseExecution, type PhaseOutput, type PhaseRegistration, type PhaseRegistry, type PhaseState, type RuntimeEvent, type RuntimeEventCursor, type RuntimeEventKind, type RuntimeEventListener, type SessionManagerProvider, SqliteRuntimeStateStore, type Tool, type ToolContext, type ToolDefinition, type ToolExecutionMode, type ToolExecutionResult, type ToolRuntimePolicy, type Unsubscribe, createCoreTools, createMessage };