@kodax-ai/kodax 0.7.42 → 0.7.44

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 (56) hide show
  1. package/CHANGELOG.md +65 -6
  2. package/README.md +87 -56
  3. package/README_CN.md +46 -25
  4. package/dist/chunks/chunk-35BDEEC5.js +2 -0
  5. package/dist/chunks/chunk-4YPL2UVZ.js +848 -0
  6. package/dist/chunks/chunk-DI2G3YWL.js +31 -0
  7. package/dist/chunks/chunk-HHQ7YTGM.js +425 -0
  8. package/dist/chunks/chunk-QHILHQBB.js +519 -0
  9. package/dist/chunks/{chunk-IYJ5EPRV.js → chunk-RUDYNAK7.js} +1 -1
  10. package/dist/chunks/compaction-config-NAPRF7XR.js +2 -0
  11. package/dist/chunks/{construction-bootstrap-J2WOCYEK.js → construction-bootstrap-PHTGBRNU.js} +4 -4
  12. package/dist/chunks/dist-CCYBJJZY.js +2 -0
  13. package/dist/chunks/dist-RHIHZAYX.js +2 -0
  14. package/dist/chunks/utils-TV3UYCHQ.js +2 -0
  15. package/dist/index.d.ts +11 -11
  16. package/dist/index.js +2 -2
  17. package/dist/kodax_cli.js +1159 -1102
  18. package/dist/provider-capabilities.json +167 -0
  19. package/dist/sdk-agent.d.ts +905 -48
  20. package/dist/sdk-agent.js +1 -1
  21. package/dist/sdk-coding.d.ts +995 -755
  22. package/dist/sdk-coding.js +1 -1
  23. package/dist/sdk-llm.d.ts +5 -3
  24. package/dist/sdk-llm.js +1 -1
  25. package/dist/sdk-mcp.d.ts +1 -1
  26. package/dist/sdk-mcp.js +1 -1
  27. package/dist/sdk-repl.d.ts +10 -9
  28. package/dist/sdk-repl.js +1 -1
  29. package/dist/sdk-session.d.ts +23 -11
  30. package/dist/sdk-session.js +1 -1
  31. package/dist/sdk-skills.js +1 -1
  32. package/dist/types-chunks/{cost-tracker.d-B6vMoLLF.d.ts → base.d-FUJahC0i.d.ts} +2 -110
  33. package/dist/types-chunks/{bash-prefix-extractor.d-CkhaqKkg.d.ts → bash-prefix-extractor.d-DdoSeghD.d.ts} +442 -131
  34. package/dist/types-chunks/cost-tracker.d-wRtyEW9d.d.ts +110 -0
  35. package/dist/types-chunks/file-tracker.d-DOfaoCbJ.d.ts +633 -0
  36. package/dist/types-chunks/manager.d-87belpiS.d.ts +370 -0
  37. package/dist/types-chunks/{resolver.d-DX9au4NJ.d.ts → resolver.d-B7ZnVuuf.d.ts} +157 -10
  38. package/dist/types-chunks/{session-storage.d-Cci897iM.d.ts → storage.d-DFD9ln5c.d.ts} +49 -2
  39. package/dist/types-chunks/{history-cleanup.d-DznrzEiU.d.ts → types.d-DM8zEJgF.d.ts} +1084 -282
  40. package/dist/types-chunks/{types.d-mM8vqvhT.d.ts → types.d-HBbWT-iA.d.ts} +41 -3
  41. package/dist/types-chunks/{storage.d-Bc5DoAwp.d.ts → utils.d-C5fzCE9W.d.ts} +25 -47
  42. package/package.json +7 -6
  43. package/dist/chunks/chunk-3RKBXWZS.js +0 -2
  44. package/dist/chunks/chunk-7JLYVWAF.js +0 -1033
  45. package/dist/chunks/chunk-CD3R5YBH.js +0 -16
  46. package/dist/chunks/chunk-DKXUY5F2.js +0 -209
  47. package/dist/chunks/chunk-HMYEQJGT.js +0 -31
  48. package/dist/chunks/chunk-KUX5LRPP.js +0 -2
  49. package/dist/chunks/chunk-OWSKU55I.js +0 -13
  50. package/dist/chunks/chunk-ZZ4KRK2B.js +0 -465
  51. package/dist/chunks/compaction-config-FIFFP4FT.js +0 -2
  52. package/dist/chunks/dist-2ZHWDXMQ.js +0 -2
  53. package/dist/chunks/dist-W4CJWLIH.js +0 -2
  54. package/dist/chunks/utils-A5MWDTWZ.js +0 -2
  55. package/dist/types-chunks/instance-discovery.d-BsKnIwpg.d.ts +0 -990
  56. package/dist/types-chunks/transport.d-DuyjG30t.d.ts +0 -180
@@ -1,990 +0,0 @@
1
- import { X as KodaXToolDefinition, m as KodaXMessage, D as KodaXReasoningMode, Z as KodaXToolResultContentItem, T as KodaXThinkingBlock, G as KodaXRedactedThinkingBlock } from './types.d-B1uGoVTE.js';
2
-
3
- /**
4
- * Layer A Primitive: Agent / Handoff / Guardrail / AgentReasoningProfile
5
- *
6
- * FEATURE_080 (v0.7.23): Agent-as-data types. Declarative dataclass shape.
7
- * The runtime counterpart is `Runner` in `./runner.ts`.
8
- *
9
- * History: extracted to `@kodax-ai/core` in FEATURE_082 (v0.7.24); merged back
10
- * into `@kodax-ai/agent` in v0.7.35.1 FEATURE_142 (single-consumer rule —
11
- * @kodax-ai/core had only @kodax-ai/coding as consumer). `@kodax-ai/coding` retains
12
- * a barrel re-export for batteries-included consumers.
13
- *
14
- * Status: @experimental — API shape may be refined during v0.7.x. Used by
15
- * the task-engine rewrite in FEATURE_084 (v0.7.26).
16
- *
17
- * Guardrail and AgentReasoningProfile are declared here but their runtime
18
- * behavior is deferred:
19
- * - Guardrail runtime → FEATURE_085 (v0.7.26)
20
- * - AgentReasoningProfile behavior → FEATURE_078 (v0.7.29)
21
- */
22
-
23
- /**
24
- * Reasoning depth / mode selector. Alias for `KodaXReasoningMode` to keep the
25
- * Layer A surface independent of the `KodaX*` brand; unified during the prefix
26
- * cleanup in FEATURE_086 (v0.7.27).
27
- */
28
- type ReasoningDepth = KodaXReasoningMode;
29
- /**
30
- * Tool binding accepted by an `Agent`. Layer A treats tools as opaque
31
- * definitions; the executor lives in `@kodax-ai/coding` and is wired up by the
32
- * Runner when it dispatches through `runKodaX`.
33
- */
34
- type AgentTool = KodaXToolDefinition;
35
- /**
36
- * Transport-level message reused from the AI layer. Kept as an alias so
37
- * consumers of the Layer A primitives do not need to import from `@kodax-ai/llm`
38
- * directly.
39
- */
40
- type AgentMessage = KodaXMessage;
41
- /**
42
- * Declarative reasoning profile attached to an Agent.
43
- *
44
- * In v0.7.23 this is a placeholder shape — only the `default` depth is read
45
- * when the Runner dispatches to `runKodaX`. Escalation on revise/replan and
46
- * max clamping are implemented in FEATURE_078 (v0.7.29).
47
- */
48
- interface AgentReasoningProfile {
49
- readonly default: ReasoningDepth;
50
- readonly max?: ReasoningDepth;
51
- readonly escalateOnRevise?: boolean;
52
- }
53
- /**
54
- * Declarative middleware reference attached to an Agent.
55
- *
56
- * FEATURE_100 (v0.7.29) introduces this field so the coding preset
57
- * can declare the four substrate middlewares (auto-reroute,
58
- * mutation-reflection, pre-answer-judge, post-tool-judge) on the
59
- * Agent declaration itself. Today these middlewares fire inside
60
- * the substrate body; the declaration field serves as the
61
- * machine-readable contract that the substrate honours, and lets
62
- * SDK consumers introspect / override middleware policy without
63
- * touching `runKodaX` internals.
64
- *
65
- * `enabled` is the only knob today; future versions add config
66
- * payload as additional fields (kept declarative — no fn callbacks).
67
- */
68
- interface AgentMiddlewareDeclaration {
69
- readonly name: string;
70
- readonly enabled: boolean;
71
- }
72
- /**
73
- * Guardrail placeholder. Layer A declares the slot; the actual
74
- * input/output/tool-call gating runtime lives in FEATURE_085 (v0.7.26).
75
- *
76
- * A guardrail targets one of three hook points:
77
- * - `input`: inspect / veto prompts before they enter the agent loop.
78
- * - `output`: inspect / rewrite assistant messages before they leave.
79
- * - `tool`: inspect / veto tool invocations during the loop.
80
- */
81
- interface Guardrail {
82
- readonly kind: 'input' | 'output' | 'tool';
83
- readonly name: string;
84
- }
85
- /**
86
- * Handoff between Agents.
87
- *
88
- * - `continuation`: ownership of the conversation transfers to `target` and
89
- * the caller exits. Mirrors the Scout → Generator upgrade path.
90
- * - `as-tool`: `target` is invoked like a tool from within the caller loop;
91
- * only the generated input is passed, and control returns on completion.
92
- * Mirrors FEATURE_067 `dispatch_child_task`.
93
- *
94
- * `inputFilter` is applied to the visible history before the target runs;
95
- * default is no filtering.
96
- */
97
- interface Handoff<TTo = unknown> {
98
- readonly target: Agent<TTo>;
99
- readonly kind: 'continuation' | 'as-tool';
100
- readonly description?: string;
101
- readonly inputFilter?: (history: readonly AgentMessage[]) => readonly AgentMessage[];
102
- }
103
- /**
104
- * Agent-as-data. A declarative specification of "who is running, with which
105
- * instructions, tools, handoffs, and reasoning profile."
106
- *
107
- * Runtime note: in v0.7.23 the only Agent that is fully executed is the
108
- * built-in coding preset (`createDefaultCodingAgent()`), which dispatches
109
- * through `runKodaX`. Custom Agents defined by SDK consumers run through a
110
- * generic Runner loop with limited capabilities (LLM call + Agent-declared
111
- * tools only — no extensions, no managed-task harness). The full runtime
112
- * arrives with FEATURE_084 (v0.7.26).
113
- */
114
- interface Agent<TContext = unknown> {
115
- readonly name: string;
116
- readonly instructions: string | ((ctx: TContext) => string);
117
- readonly tools?: readonly AgentTool[];
118
- readonly handoffs?: readonly Handoff[];
119
- readonly reasoning?: AgentReasoningProfile;
120
- readonly guardrails?: readonly Guardrail[];
121
- /** Reserved for structured-output agents; not consumed in v0.7.23. */
122
- readonly outputSchema?: unknown;
123
- readonly model?: string;
124
- readonly provider?: string;
125
- /**
126
- * FEATURE_100 (v0.7.29) substrate executor: when set, `Runner.run`
127
- * delegates execution to this function instead of consulting the
128
- * preset-dispatcher registry or running the generic LLM loop. The
129
- * coding preset attaches `runKodaX`'s full execution pipeline here so
130
- * the SDK surface `Runner.run(createDefaultCodingAgent(), prompt, opts)`
131
- * directly drives substrate without a `registerPresetDispatcher`
132
- * indirection (the v0.7.23 "Option Y" facade).
133
- *
134
- * Type is intentionally `unknown` to avoid a `core/agent.ts` ↔
135
- * `core/runner.ts` module cycle. `Runner.run` casts to the
136
- * `PresetDispatcher` shape declared in `runner.ts` at the call site.
137
- */
138
- readonly substrateExecutor?: unknown;
139
- /**
140
- * FEATURE_100 (v0.7.29) declarative middleware list. The coding
141
- * preset declares the four substrate middlewares it ships with
142
- * (auto-reroute, mutation-reflection, pre-answer-judge,
143
- * post-tool-judge). Substrate consults this list on entry and
144
- * skips the corresponding step when `enabled === false`. SDK
145
- * consumers can introspect or override declared middleware
146
- * without touching the substrate body.
147
- */
148
- readonly middleware?: readonly AgentMiddlewareDeclaration[];
149
- }
150
- /**
151
- * Ergonomic factory. Equivalent to a plain object literal but freezes the
152
- * shape so tests cannot mutate a shared Agent by accident.
153
- */
154
- declare function createAgent<TContext = unknown>(spec: Agent<TContext>): Agent<TContext>;
155
- /**
156
- * Ergonomic factory for Handoff.
157
- */
158
- declare function createHandoff<TTo = unknown>(spec: Handoff<TTo>): Handoff<TTo>;
159
-
160
- /**
161
- * SpanData variants — payload shapes carried by each `Span`.
162
- *
163
- * FEATURE_083 (v0.7.24): the Agent-era tracing model uses a discriminated
164
- * union so consumers (OpenTelemetry adapter, Langfuse adapter, KodaX
165
- * built-in file processor) can render each span kind with type safety.
166
- *
167
- * Variants mirror the semantic events KodaX emits today:
168
- * - AgentSpanData : one `Runner.run(agent, ...)` round
169
- * - GenerationSpanData: one provider LLM call
170
- * - ToolCallSpanData : one tool invocation (including MCP tool)
171
- * - HandoffSpanData : continuation or as-tool handoff between agents
172
- * - CompactionSpanData: one compaction pass (token-threshold or lineage)
173
- * - GuardrailSpanData : one guardrail check at input/output/tool
174
- * - EvidenceSpanData : repo-intelligence / evidence acquisition
175
- * - FanoutSpanData : parallel fanout bracket (winner-cancel capable)
176
- *
177
- * API surface is `@experimental` until v0.8.0 — shape may be refined as
178
- * FEATURE_084 (v0.7.26) starts emitting these.
179
- */
180
- interface AgentSpanData {
181
- readonly kind: 'agent';
182
- readonly agentName: string;
183
- readonly model?: string;
184
- readonly provider?: string;
185
- readonly tools?: readonly string[];
186
- readonly handoffs?: readonly string[];
187
- readonly outputMessages?: number;
188
- readonly error?: string;
189
- }
190
- interface GenerationSpanData {
191
- readonly kind: 'generation';
192
- readonly agentName: string;
193
- readonly provider: string;
194
- readonly model: string;
195
- readonly inputMessages?: number;
196
- readonly outputTokens?: number;
197
- readonly inputTokens?: number;
198
- readonly reasoningTokens?: number;
199
- readonly cachedTokens?: number;
200
- readonly usage?: {
201
- readonly inputTokens?: number;
202
- readonly outputTokens?: number;
203
- readonly totalTokens?: number;
204
- readonly reasoningTokens?: number;
205
- readonly cachedTokens?: number;
206
- readonly costUsd?: number;
207
- };
208
- readonly finishReason?: string;
209
- readonly error?: string;
210
- }
211
- interface ToolCallSpanData {
212
- readonly kind: 'tool_call';
213
- readonly toolName: string;
214
- readonly providerId?: string;
215
- readonly capabilityId?: string;
216
- readonly inputPreview?: string;
217
- readonly outputPreview?: string;
218
- readonly status: 'ok' | 'error';
219
- readonly error?: string;
220
- }
221
- interface HandoffSpanData {
222
- readonly kind: 'handoff';
223
- readonly fromAgent: string;
224
- readonly toAgent: string;
225
- readonly handoffKind: 'continuation' | 'as-tool';
226
- readonly description?: string;
227
- }
228
- interface CompactionSpanData {
229
- readonly kind: 'compaction';
230
- readonly policyName: string;
231
- readonly tokensUsed: number;
232
- readonly budget: number;
233
- readonly replacedMessageCount: number;
234
- readonly summaryLength: number;
235
- readonly error?: string;
236
- }
237
- interface GuardrailSpanData {
238
- readonly kind: 'guardrail';
239
- readonly guardrailName: string;
240
- readonly hookPoint: 'input' | 'output' | 'tool';
241
- readonly decision: 'pass' | 'veto' | 'rewrite' | 'error';
242
- readonly reason?: string;
243
- readonly error?: string;
244
- }
245
- interface EvidenceSpanData {
246
- readonly kind: 'evidence';
247
- readonly source: string;
248
- readonly queryPreview?: string;
249
- readonly resultCount?: number;
250
- readonly cacheHit?: boolean;
251
- readonly error?: string;
252
- }
253
- interface FanoutSpanData {
254
- readonly kind: 'fanout';
255
- readonly agentName: string;
256
- readonly childCount: number;
257
- readonly winnerChildId?: string;
258
- readonly cancelledChildIds?: readonly string[];
259
- }
260
- /**
261
- * FEATURE_184 (v0.7.45) — Stop hook observability.
262
- *
263
- * Emitted when the Runner's `RunOptions.stopHook` is invoked or fails.
264
- * `outcome` records what the hook returned (or `'error'` for thrown
265
- * exceptions — fail-open path), `reanimateCount` is the running count
266
- * after this invocation. `reason` carries the abort/reanimate text
267
- * when relevant, truncated by consumers as needed.
268
- */
269
- interface StopHookSpanData {
270
- readonly kind: 'stop-hook';
271
- readonly outcome: 'accept' | 'reanimate' | 'abort' | 'budget-exhausted' | 'error';
272
- readonly reanimateCount: number;
273
- readonly reanimateBudget: number;
274
- readonly reason?: string;
275
- readonly error?: string;
276
- }
277
- /**
278
- * Discriminated union of all span payload shapes. Additional variants may
279
- * be added in future features — consumers should check `kind` before
280
- * reading specific fields.
281
- */
282
- type SpanData = AgentSpanData | GenerationSpanData | ToolCallSpanData | HandoffSpanData | CompactionSpanData | GuardrailSpanData | EvidenceSpanData | FanoutSpanData | StopHookSpanData;
283
-
284
- /**
285
- * Span — a single timed unit of work inside a Trace.
286
- *
287
- * FEATURE_083 (v0.7.24): minimal Span implementation modeled after the
288
- * openai-agents-python Trace/Span pattern.
289
- *
290
- * Design constraints:
291
- * - Span creation must be cheap (no await, no serialisation). Processors
292
- * do their own batching / flushing.
293
- * - `addChild()` is synchronous and immediately visible in the Trace tree.
294
- * - `end()` is idempotent; calling it twice is a no-op.
295
- * - `error` is an optional field that sets a flag on the span without
296
- * throwing. The consumer decides how to surface errors.
297
- */
298
-
299
- interface SpanError {
300
- readonly message: string;
301
- readonly stack?: string;
302
- readonly data?: unknown;
303
- }
304
- /**
305
- * Public Span interface. Concrete implementation is `SpanImpl`.
306
- */
307
- interface Span {
308
- readonly id: string;
309
- readonly traceId: string;
310
- readonly parentId?: string;
311
- readonly name: string;
312
- readonly data: SpanData;
313
- readonly startedAt: number;
314
- readonly endedAt?: number;
315
- readonly error?: SpanError;
316
- readonly children: readonly Span[];
317
- addChild(name: string, data: SpanData): Span;
318
- setError(err: SpanError | Error): void;
319
- end(): void;
320
- }
321
-
322
- /**
323
- * Runner Tool Loop — FEATURE_084 Shard 1 (v0.7.26).
324
- *
325
- * Extends the Layer A Runner generic-dispatch path with tool-call support.
326
- * Before Shard 1 the Runner could only do a single `system+user → assistant`
327
- * turn. Now the injected LLM callback may return a structured result that
328
- * declares tool calls; the Runner executes them, appends tool_use +
329
- * tool_result content blocks, and loops until the LLM stops emitting tool
330
- * calls (or MAX_TOOL_LOOP_ITERATIONS is reached).
331
- *
332
- * This Shard only lands the capability. No built-in Agent consumes it yet —
333
- * the coding preset (SA path) continues to dispatch through
334
- * `registerPresetDispatcher` unchanged.
335
- *
336
- * @experimental Shape may be refined during the v0.7.26 shard rollout.
337
- */
338
-
339
- /**
340
- * Hard ceiling on tool-loop iterations. A single run may invoke at most this
341
- * many LLM turns (counting the initial turn); if the model keeps returning
342
- * tool calls past this limit we abort to prevent runaway behaviour.
343
- */
344
- declare const MAX_TOOL_LOOP_ITERATIONS = 20;
345
- /**
346
- * One tool invocation requested by the LLM.
347
- */
348
- interface RunnerToolCall {
349
- readonly id: string;
350
- readonly name: string;
351
- readonly input: Record<string, unknown>;
352
- }
353
- /**
354
- * Structured LLM result. Returning this instead of a plain string lets the
355
- * Runner drive a tool loop. If `toolCalls` is empty or omitted the loop
356
- * terminates and `text` becomes the final output.
357
- */
358
- interface RunnerLlmResult {
359
- readonly text: string;
360
- readonly toolCalls?: readonly RunnerToolCall[];
361
- readonly stopReason?: string;
362
- /**
363
- * v0.7.26 parity: extended-thinking blocks from the provider stream.
364
- * Must be preserved on the assistant message so (a) session resume can
365
- * re-render them and (b) Anthropic's extended-thinking API contract is
366
- * honoured — provider rejects the next turn with a 400 when a tool_use
367
- * turn's `thinking` block is missing from prior assistant history.
368
- */
369
- readonly thinkingBlocks?: readonly (KodaXThinkingBlock | KodaXRedactedThinkingBlock)[];
370
- }
371
- /**
372
- * LLM callback return type. `string` preserves the v0.7.23 single-turn
373
- * behaviour; `RunnerLlmResult` opts into the tool loop.
374
- */
375
- type RunnerLlmReturn = string | RunnerLlmResult;
376
- /**
377
- * Observer callbacks fired around every tool invocation. Preset
378
- * dispatchers (e.g. the coding Runner-driven path) pass these through
379
- * `RunOptions.toolObserver` so REPL / CLI consumers see live
380
- * `onToolCall` / `onToolResult` events, matching the legacy task-engine
381
- * event surface (v0.7.22 agent.ts fired `events.onToolResult` at three
382
- * sites per invocation).
383
- */
384
- interface RunnerToolObserver {
385
- /**
386
- * Permission / policy gate fired BEFORE each tool invocation. Return
387
- * `true` (or `undefined`) to allow, `false` to block with a generic
388
- * message, or a `string` to block with that message as the tool result.
389
- * Used to hook plan-mode / accept-edits / extension `tool:before`
390
- * policies onto the Runner-driven path (v0.7.22 parity — legacy
391
- * `events.beforeToolExecute` surface).
392
- */
393
- readonly beforeTool?: (call: RunnerToolCall) => Promise<boolean | string | undefined>;
394
- readonly onToolCall?: (call: RunnerToolCall) => void;
395
- readonly onToolResult?: (call: RunnerToolCall, result: RunnerToolResult) => void;
396
- }
397
- /**
398
- * Context passed to a RunnableTool's `execute` function.
399
- */
400
- interface RunnerToolContext {
401
- readonly agent: Agent;
402
- readonly abortSignal?: AbortSignal;
403
- /** The agent's Span, so tool implementations can nest custom spans if needed. */
404
- readonly agentSpan?: Span | null;
405
- /**
406
- * Current tool_use call id. Passed through so tool wrappers can correlate
407
- * progress events (`onToolProgress`) and other per-call side-effects with
408
- * the REPL's tool-block in the transcript. Populated by `executeRunnerToolCall`.
409
- */
410
- readonly toolCallId?: string;
411
- }
412
- /**
413
- * Value returned by `RunnableTool.execute`. The `content` is what the LLM
414
- * sees in the next turn as `tool_result`:
415
- *
416
- * - `string` — plain text (the default for most tools).
417
- * - `readonly KodaXToolResultContentItem[]` — an array of typed items
418
- * (text + image), used by multimodal tools like `read` on an image
419
- * path. Provider serializers lower each item to the wire format
420
- * (Anthropic accepts inline; OpenAI-compat downgrades image to text
421
- * placeholder).
422
- */
423
- interface RunnerToolResult {
424
- readonly content: string | readonly KodaXToolResultContentItem[];
425
- readonly isError?: boolean;
426
- readonly metadata?: Record<string, unknown>;
427
- }
428
- /**
429
- * A tool bundled with its executor. Extends `AgentTool` (the wire-format
430
- * `KodaXToolDefinition`) so it can be passed through to the provider
431
- * unchanged while also carrying a function the Runner can invoke.
432
- */
433
- interface RunnableTool extends AgentTool {
434
- readonly execute: (input: Record<string, unknown>, ctx: RunnerToolContext) => Promise<RunnerToolResult>;
435
- }
436
- /**
437
- * Narrowing helper — distinguishes a `RunnableTool` from a plain
438
- * `AgentTool`. An agent may declare both: the Runner only executes the
439
- * tools that carry an `execute` function.
440
- */
441
- declare function isRunnableTool(tool: AgentTool): tool is RunnableTool;
442
- /**
443
- * Narrowing helper for the LLM callback return shape.
444
- */
445
- declare function isRunnerLlmResult(value: unknown): value is RunnerLlmResult;
446
- /**
447
- * Execute one tool call against the agent's declared tools. Emits a
448
- * ToolCallSpan under `ctx.agentSpan` when tracing is active. Returns a
449
- * `RunnerToolResult` — tool errors do not throw, they are surfaced with
450
- * `isError: true` so the LLM can see them in the next turn and react.
451
- */
452
- declare function executeRunnerToolCall(call: RunnerToolCall, agent: Agent, ctx: RunnerToolContext): Promise<RunnerToolResult>;
453
- /**
454
- * Build the assistant message that captures one LLM turn. Preserves
455
- * thinking blocks (extended-thinking contract), text blocks, and tool_use
456
- * blocks in the order Anthropic's wire format expects: thinking → text →
457
- * tool_use. This mirrors v0.7.22 `agent.ts:2230`
458
- * (`[...thinkingBlocks, ...textBlocks, ...visibleToolBlocks]`) which the
459
- * Runner-driven path must preserve — without it Anthropic returns 400 on
460
- * the next turn when extended thinking is active, and session resume
461
- * loses the reasoning trace.
462
- */
463
- declare function buildAssistantMessageFromLlmResult(result: RunnerLlmResult): AgentMessage;
464
- /**
465
- * Build the user message that carries tool_result blocks back to the LLM.
466
- * Provider serializers (Anthropic, OpenAI) both accept tool_result on the
467
- * user turn.
468
- */
469
- declare function buildToolResultMessage(calls: readonly RunnerToolCall[], results: readonly RunnerToolResult[]): AgentMessage;
470
-
471
- /**
472
- * Guardrail Runtime — FEATURE_085 (v0.7.26).
473
- *
474
- * Three-tier runtime for Agent guardrails:
475
- *
476
- * - `InputGuardrail`: runs once before the first LLM turn, inspects the
477
- * full input transcript, may allow / rewrite / block / escalate.
478
- * - `OutputGuardrail`: runs once before returning, inspects the final
479
- * assistant message, may allow / rewrite / block / escalate.
480
- * - `ToolGuardrail`: runs before and/or after each tool invocation,
481
- * inspects the call / result, may allow / rewrite / block / escalate.
482
- *
483
- * The four verdict actions:
484
- *
485
- * - `allow`: continue with the current value.
486
- * - `rewrite`: replace the current value with `payload`.
487
- * - `block`: throw `GuardrailBlockedError` (for input/output) or surface
488
- * an error tool_result (for tool-before); the LLM / caller sees a
489
- * rejection and must adapt.
490
- * - `escalate`: throw `GuardrailEscalateError`; the SDK consumer catches
491
- * and decides whether to prompt the user, retry under different
492
- * constraints, etc.
493
- *
494
- * Every guardrail invocation emits a `GuardrailSpan` under the agent's
495
- * span when tracing is active.
496
- *
497
- * @experimental API shape may adjust during v0.7.x rollout.
498
- */
499
-
500
- /**
501
- * Shared execution context passed to every guardrail.
502
- *
503
- * `messages` is the live conversation transcript at the moment this
504
- * guardrail fires. For tool-side guardrails this is the transcript at
505
- * call-site time — it does NOT yet include the assistant turn that
506
- * emitted the current tool_use, since that turn is appended only after
507
- * the full tool batch settles. Optional so existing guardrails that
508
- * don't read context still type-check; populated by the Runner for all
509
- * production hook points.
510
- *
511
- * Added in FEATURE_092 (v0.7.33) so the auto-mode classifier guardrail
512
- * can extract intent context (user prompt + prior tool_use / tool_result
513
- * blocks) without reaching into Runner internals.
514
- */
515
- interface GuardrailContext {
516
- readonly agent: Agent;
517
- readonly abortSignal?: AbortSignal;
518
- readonly messages?: readonly AgentMessage[];
519
- }
520
- /**
521
- * Outcome of a single guardrail check. `payload` shape depends on the hook
522
- * point — see the specific guardrail interface for the expected type.
523
- */
524
- type GuardrailVerdict = {
525
- readonly action: 'allow';
526
- } | {
527
- readonly action: 'rewrite';
528
- readonly payload: unknown;
529
- readonly reason?: string;
530
- } | {
531
- readonly action: 'block';
532
- readonly reason: string;
533
- } | {
534
- readonly action: 'escalate';
535
- readonly reason: string;
536
- };
537
- /**
538
- * Input-side guardrail. Expected `rewrite` payload shape:
539
- * `readonly AgentMessage[]` — the replacement transcript.
540
- */
541
- interface InputGuardrail extends Guardrail {
542
- readonly kind: 'input';
543
- check(input: readonly AgentMessage[], ctx: GuardrailContext): Promise<GuardrailVerdict>;
544
- }
545
- /**
546
- * Output-side guardrail. Expected `rewrite` payload shape:
547
- * `AgentMessage` — the replacement final assistant message.
548
- */
549
- interface OutputGuardrail extends Guardrail {
550
- readonly kind: 'output';
551
- check(output: AgentMessage, ctx: GuardrailContext): Promise<GuardrailVerdict>;
552
- }
553
- /**
554
- * Tool-side guardrail. `beforeTool` rewrite payload shape: `RunnerToolCall`
555
- * (replacement call). `afterTool` rewrite payload shape: `RunnerToolResult`
556
- * (replacement result). Either hook is optional.
557
- */
558
- interface ToolGuardrail extends Guardrail {
559
- readonly kind: 'tool';
560
- beforeTool?(call: RunnerToolCall, ctx: GuardrailContext): Promise<GuardrailVerdict>;
561
- afterTool?(call: RunnerToolCall, result: RunnerToolResult, ctx: GuardrailContext): Promise<GuardrailVerdict>;
562
- }
563
- /**
564
- * Thrown when any guardrail returns `{ action: 'block' }`. The Runner
565
- * propagates this up to the caller — the run is aborted at that point.
566
- */
567
- declare class GuardrailBlockedError extends Error {
568
- readonly guardrailName: string;
569
- readonly hookPoint: 'input' | 'output' | 'tool';
570
- constructor(guardrailName: string, hookPoint: 'input' | 'output' | 'tool', reason: string);
571
- }
572
- /**
573
- * Thrown when any guardrail returns `{ action: 'escalate' }`. Callers can
574
- * catch and prompt the user or apply a stricter policy before retrying.
575
- */
576
- declare class GuardrailEscalateError extends Error {
577
- readonly guardrailName: string;
578
- readonly hookPoint: 'input' | 'output' | 'tool';
579
- constructor(guardrailName: string, hookPoint: 'input' | 'output' | 'tool', reason: string);
580
- }
581
- /** Filter a guardrail list by hook-point. */
582
- declare function collectGuardrails(guardrails: readonly Guardrail[] | undefined): {
583
- input: readonly InputGuardrail[];
584
- output: readonly OutputGuardrail[];
585
- tool: readonly ToolGuardrail[];
586
- };
587
- /**
588
- * Run all input guardrails in declaration order. Returns the (possibly
589
- * rewritten) transcript. Throws on block / escalate.
590
- */
591
- declare function runInputGuardrails(transcript: readonly AgentMessage[], guardrails: readonly InputGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<readonly AgentMessage[]>;
592
- /**
593
- * Run all output guardrails in declaration order. Returns the (possibly
594
- * rewritten) final assistant message. Throws on block / escalate.
595
- */
596
- declare function runOutputGuardrails(output: AgentMessage, guardrails: readonly OutputGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<AgentMessage>;
597
- /**
598
- * Outcome of the before-tool guardrail stage.
599
- * - `{ kind: 'allow', call }`: continue to executeRunnerToolCall with `call`
600
- * - `{ kind: 'block', result }`: skip execution; return `result` as the
601
- * tool_result to the LLM (so it sees the rejection and can adapt)
602
- */
603
- type ToolBeforeOutcome = {
604
- readonly kind: 'allow';
605
- readonly call: RunnerToolCall;
606
- } | {
607
- readonly kind: 'block';
608
- readonly result: RunnerToolResult;
609
- };
610
- /**
611
- * Run before-tool guardrails in declaration order. Rewrite replaces the
612
- * tool call. Block surfaces an error tool_result to the LLM instead of
613
- * throwing — the LLM sees the rejection and adapts. Escalate still throws.
614
- */
615
- declare function runToolBeforeGuardrails(call: RunnerToolCall, guardrails: readonly ToolGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<ToolBeforeOutcome>;
616
- /**
617
- * Run after-tool guardrails in declaration order. Rewrite replaces the
618
- * result content. Block replaces with an error result. Escalate throws.
619
- */
620
- declare function runToolAfterGuardrails(call: RunnerToolCall, result: RunnerToolResult, guardrails: readonly ToolGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<RunnerToolResult>;
621
-
622
- /**
623
- * Child task registry primitive — generic fan-out tracking.
624
- *
625
- * FEATURE_120 v0.7.39 Step 0 (package-attribution migration, ADR-021).
626
- * Lifted from `@kodax-ai/coding`'s `KodaXToolExecutionContext.childTaskRegistry`
627
- * field + inline cleanup chain in `tools/dispatch-child-tasks.ts`. The
628
- * coding side now consumes this primitive specialized to its
629
- * `KodaXChildExecutionResult` type; any other agent-flavor downstream
630
- * can specialize on its own child-result type without re-implementing
631
- * the cleanup contract.
632
- *
633
- * The shape is intentionally minimal: a Map plus a `register` helper
634
- * that bundles the v0.7.38 FEATURE_155 Bug A hotfix (`c1bdaf4e`)
635
- * cleanup chain into a single call site. The helper exists because
636
- * the cleanup is **not optional** — without it, every settled promise
637
- * stays in the registry forever, gets re-wrapped by the next
638
- * idle-yield `waitForWakeEvent` call, and fires spurious
639
- * `child-completed` wakes (production symptom: Evaluator gets
640
- * bombarded by duplicate `<task-completed>` notifications, consuming
641
- * an LLM turn each up to `IDLE_YIELD_MAX_ITERATIONS=64`).
642
- */
643
- /**
644
- * Map of `task_id` → in-flight child-execution promise. Generic over
645
- * the child-result type so the agent layer doesn't depend on any
646
- * specific agent flavor's result shape.
647
- *
648
- * Mutation contract:
649
- * - Owned by the runner's per-turn execution context. The dispatch
650
- * tool writes via `registerChildTask`; the idle-yield outer loop
651
- * reads via `Map.prototype.entries()` / `.size`.
652
- * - **Never delete entries manually** — call `registerChildTask`
653
- * and the cleanup chain it installs will run on settle.
654
- */
655
- type ChildTaskRegistry<T> = Map<string, Promise<T>>;
656
- /**
657
- * Register an in-flight child-execution promise in the registry and
658
- * install the cleanup chain that removes the entry once the promise
659
- * settles (success or failure).
660
- *
661
- * The cleanup chain is two stages:
662
- * 1. `.finally(() => registry.delete(childId))` — runs on settle
663
- * regardless of outcome, removing the entry before the next
664
- * idle-yield outer-loop iteration observes the registry.
665
- * 2. `.catch(() => {})` — swallows the rejection on the cleanup
666
- * chain so a child that crashes before any consumer awaits it
667
- * doesn't surface as `unhandledRejection` on Node. Must come
668
- * AFTER `.finally` because `.finally` returns a NEW promise
669
- * that rejects with the same reason.
670
- *
671
- * The original `promise` argument is **not** returned — the helper's
672
- * value-add is the cleanup side-effect, not promise transformation.
673
- * Callers that need to await the result read from `registry.get(id)`
674
- * or hold their own reference.
675
- *
676
- * @throws Error when `childId` already exists in the registry. Caller
677
- * should report this to the LLM as a tool-error (duplicate task_id);
678
- * the helper does NOT swallow the conflict because that would
679
- * silently overwrite an in-flight child's tracking entry.
680
- */
681
- declare function registerChildTask<T>(registry: ChildTaskRegistry<T>, childId: string, promise: Promise<T>): void;
682
-
683
- /**
684
- * Generic per-task abort primitive — `requestTaskStop`.
685
- *
686
- * FEATURE_120 v0.7.39 Phase 3a (ADR-021). Coordinator-style agents need
687
- * to request that a specific in-flight child task exit gracefully. The
688
- * @kodax-ai/agent layer owns the abort-controller registry shape and
689
- * the abort-dispatch decision; agent-flavor wrappers (e.g. the coding
690
- * `task_stop` tool, Phase 3b) layer in domain framing such as the
691
- * `<coordinator-stop-request>` message tag.
692
- *
693
- * What this primitive owns:
694
- * - A `TaskAbortRegistry` type alias = `Map<string, AbortController>`.
695
- * The map is owned + mutated by the caller; the primitive only
696
- * reads it. Callers use `registry.set(id, controller)` /
697
- * `registry.delete(id)` directly — the standard `Map` mutators
698
- * are simple enough that wrapping them adds no value.
699
- * - `requestTaskStop({taskId, registry, reason?})` — looks up the
700
- * controller, decides whether to abort, calls `controller.abort`,
701
- * returns a structured outcome.
702
- *
703
- * Abort semantics (matches the existing FEATURE_115 soft-pause
704
- * principle): aborting fires the signal but does NOT interrupt any
705
- * synchronous tool that's already executing. The child's next abort
706
- * check (`signal.throwIfAborted()` or an `signal.aborted` poll)
707
- * surfaces the abort. This matches Node's AbortController contract.
708
- *
709
- * What this primitive does NOT do (deliberate):
710
- * - Enqueue a coordinator-stop-request message — that's a
711
- * coding-flavor convenience and uses the existing
712
- * `routeMessage` primitive at the tool layer.
713
- * - Track abort lifecycle / auto-cleanup the registry — the
714
- * controller's lifetime is tied to its owning task's Promise;
715
- * the caller removes the registry entry when the task settles
716
- * (typically in a `.finally` chain alongside the child-task
717
- * registry cleanup).
718
- * - Time-out enforcement / retry — orthogonal concerns owned at
719
- * higher layers if needed.
720
- */
721
- /**
722
- * Registry mapping task ids to their owning AbortController.
723
- * Lifetime: created per parent-run, populated at child dispatch,
724
- * cleared when the child Promise settles.
725
- */
726
- type TaskAbortRegistry = Map<string, AbortController>;
727
- interface RequestTaskStopOptions {
728
- /** Target task id. Must exist as a key in `registry`. */
729
- readonly taskId: string;
730
- /** Registry of in-flight task abort controllers. */
731
- readonly registry: ReadonlyMap<string, AbortController>;
732
- /**
733
- * Optional cause forwarded to `AbortController.abort(reason)`.
734
- * - Error → passed through verbatim (preserves stack / custom
735
- * subclasses).
736
- * - string → wrapped in `new Error(reason)`.
737
- * - undefined → a default Error mentioning the taskId is
738
- * fabricated so the child receives a non-empty signal.reason.
739
- */
740
- readonly reason?: string | Error;
741
- }
742
- type RequestTaskStopResult = {
743
- readonly ok: true;
744
- readonly taskId: string;
745
- } | {
746
- readonly ok: false;
747
- readonly reason: 'unknown-target';
748
- readonly taskId: string;
749
- } | {
750
- readonly ok: false;
751
- readonly reason: 'already-aborted';
752
- readonly taskId: string;
753
- };
754
- /**
755
- * Look up `taskId` in `registry`. If found and not yet aborted, abort
756
- * the controller with the supplied reason. Returns a discriminated
757
- * outcome so callers can render success / error UX without string
758
- * matching.
759
- *
760
- * `already-aborted` is reported separately from success because the
761
- * first-abort `signal.reason` is preserved verbatim — debugging
762
- * chains depend on the original cause not being overwritten by
763
- * subsequent stop requests.
764
- *
765
- * Synchronous: `AbortController.abort` is synchronous; no async work
766
- * is performed by this primitive.
767
- */
768
- declare function requestTaskStop(opts: RequestTaskStopOptions): RequestTaskStopResult;
769
-
770
- /**
771
- * FEATURE_125 (v0.7.41) — Team Mode Layer 1: per-instance state broadcast.
772
- *
773
- * Each running KodaX session registers a directory under
774
- * `<agentConfigHome>/instances/<pid>/` containing three files:
775
- *
776
- * meta.json — written once at registration; cwd / startedAt /
777
- * optional git branch + remote. Static for the session.
778
- * state.json — re-written whenever the session's `currentIntent`,
779
- * `agentPhase`, or active/recently-modified file set
780
- * changes. Read by sibling sessions for context.
781
- * heartbeat — empty file whose mtime is touched on every refresh.
782
- * Sibling sessions use the mtime to declare an instance
783
- * stale (default 30s of no heartbeat → cleanup).
784
- *
785
- * Atomic write strategy:
786
- * - state.json is written via `<path>.tmp` + `rename()`. On POSIX the
787
- * rename is atomic; on Windows it is atomic when source + target sit
788
- * on the same filesystem (always true for `<agentConfigHome>/...`).
789
- * - heartbeat is touched via `utimesSync()`. Cheap, no rename needed.
790
- *
791
- * Lifecycle:
792
- * - `createStateWriter` writes meta.json + state.json + heartbeat once,
793
- * then starts an interval timer (default 1000ms) that refreshes
794
- * state.json and touches heartbeat.
795
- * - `update(patch)` shallow-merges the patch into the in-memory state
796
- * and flushes immediately so peer sessions see the change at the
797
- * next tool boundary, not at the next heartbeat tick.
798
- * - `shutdown()` clears the timer, removes the instance directory,
799
- * and resolves. Idempotent — safe to call multiple times.
800
- *
801
- * Crash recovery:
802
- * - If a process is killed mid-run, the directory is left on disk.
803
- * The next session's discovery scan (S2, `instance-discovery.ts`)
804
- * detects the stale heartbeat and removes the directory.
805
- *
806
- * DI-clean: every fs / clock dependency is injectable for hermetic tests.
807
- */
808
- /**
809
- * Live session state surfaced to sibling KodaX sessions. Mirrors the
810
- * shape documented in `docs/features/v0.7.41.md#feature_125-step-1`.
811
- */
812
- interface SessionStateSnapshot {
813
- readonly agentPhase: 'idle' | 'awaiting_llm' | 'running_tool';
814
- /** Single-line description of what the agent is currently doing. */
815
- readonly currentIntent?: string;
816
- /** Files the session is actively editing right now. */
817
- readonly activeFiles?: readonly string[];
818
- /** Files modified in the recent past (sibling sessions read this to detect "their content may be stale"). */
819
- readonly recentlyModifiedFiles?: readonly RecentlyModifiedFile[];
820
- /**
821
- * FEATURE_170 (v0.7.41) — optional one-line summary of the active
822
- * todo list. Lets sibling sessions display "they're currently
823
- * working on: <X>" without owning the todo store.
824
- */
825
- readonly currentTodoSummary?: CurrentTodoSummary;
826
- }
827
- interface RecentlyModifiedFile {
828
- readonly path: string;
829
- readonly modifiedAt: number;
830
- }
831
- interface CurrentTodoSummary {
832
- readonly inProgress?: string;
833
- readonly pendingCount: number;
834
- readonly completedCount: number;
835
- }
836
- interface SessionMeta {
837
- readonly cwd: string;
838
- readonly startedAt: number;
839
- readonly gitBranch?: string;
840
- readonly gitRemote?: string;
841
- }
842
- /**
843
- * Stored shape of `state.json` on disk — additive over SessionStateSnapshot.
844
- *
845
- * Reader contract (S2 `instance-discovery.ts`): parse the JSON, verify
846
- * `version === '1'` before reading any other field. On an unknown
847
- * version, log + skip the instance — this lets a newer writer coexist
848
- * with an older reader during an in-place upgrade.
849
- *
850
- * Fields are camelCase + a nested `meta` object (cwd / startedAt /
851
- * gitBranch / gitRemote). Do NOT assume the snake_case / flat shape
852
- * shown in early design-doc drafts — the typed interface here is the
853
- * ground truth; the doc has been updated to match.
854
- */
855
- interface PersistedSessionState extends SessionStateSnapshot {
856
- readonly version: '1';
857
- readonly pid: number;
858
- readonly updatedAt: number;
859
- readonly meta: SessionMeta;
860
- }
861
- /** Minimal injectable fs surface — lets tests drive the writer without disk I/O. */
862
- interface StateWriterFs {
863
- mkdirSync(dirPath: string, options: {
864
- recursive: true;
865
- }): void;
866
- writeFileSync(filePath: string, data: string): void;
867
- /** Atomic write helper: writes to `${filePath}.tmp` then renames. */
868
- atomicWriteSync(filePath: string, data: string): void;
869
- utimesSync(filePath: string, atime: number, mtime: number): void;
870
- rmSync(dirPath: string, options: {
871
- recursive: true;
872
- force: true;
873
- }): void;
874
- existsSync(targetPath: string): boolean;
875
- }
876
- interface StateWriterOptions {
877
- /** Defaults to `process.pid`. Tests / multi-instance fixtures override. */
878
- readonly pid?: number;
879
- readonly meta: SessionMeta;
880
- readonly initialState: SessionStateSnapshot;
881
- /** Defaults to 1000ms. Tests pass a faster tick. */
882
- readonly heartbeatIntervalMs?: number;
883
- /** Defaults to `Date.now`. Tests inject a controllable clock. */
884
- readonly clock?: () => number;
885
- /** Defaults to {@link REAL_FS}. Tests inject an in-memory fs. */
886
- readonly fs?: StateWriterFs;
887
- /**
888
- * Root directory under which `<pid>/` is created. Defaults to
889
- * `getAgentConfigPath('instances')`. Tests can point at a temp dir.
890
- */
891
- readonly instancesRoot?: string;
892
- }
893
- interface StateWriter {
894
- readonly pid: number;
895
- readonly instanceDir: string;
896
- /** Apply a partial update to the in-memory state and flush to disk. */
897
- update(patch: Partial<SessionStateSnapshot>): void;
898
- /** Touch the heartbeat and re-write state.json without changing state. */
899
- refresh(): void;
900
- /** Stop the interval, remove the instance directory, resolve when done. */
901
- shutdown(): Promise<void>;
902
- /** Read-only snapshot of the current state. Useful for tests. */
903
- getState(): SessionStateSnapshot;
904
- }
905
- /**
906
- * Construct a writer, register the instance directory, and start the
907
- * heartbeat interval. Returns synchronously so the caller can rely on
908
- * `instanceDir` being live the moment the function returns.
909
- */
910
- declare function createStateWriter(options: StateWriterOptions): StateWriter;
911
-
912
- /**
913
- * FEATURE_125 (v0.7.41) — Team Mode Layer 2a: sibling instance discovery.
914
- *
915
- * Scans `<agentConfigHome>/instances/`, filters out the caller's own
916
- * pid, drops any directory whose `heartbeat` file is stale (>30s of no
917
- * touch), parses `state.json`, validates `version === '1'`, and returns
918
- * a typed list of live sibling instances. Stale directories are
919
- * optionally reaped (`reapStale: true`) — the next session entering
920
- * Team Mode does the cleanup so crashed processes don't accumulate
921
- * forever.
922
- *
923
- * Per-instance failures (corrupt JSON, vanished file mid-read, permission
924
- * error) are isolated: the bad directory is logged + skipped, the rest
925
- * of the scan completes. Discovery NEVER throws to its caller — a
926
- * Team-Mode-disabled return is `[]`, not an exception. This keeps the
927
- * worker LLM call path resilient to one peer session's bad state.
928
- *
929
- * DI-clean: every fs / clock / logger dependency is injectable so
930
- * hermetic tests can simulate stale / corrupt / mid-scan-deletion
931
- * scenarios without real disk.
932
- */
933
-
934
- /** A sibling KodaX session that passed stale + version-guard checks. */
935
- interface DiscoveredInstance {
936
- readonly pid: number;
937
- readonly state: PersistedSessionState;
938
- /** Heartbeat mtime in ms (epoch). Useful for ordering "freshest first". */
939
- readonly heartbeatMtimeMs: number;
940
- }
941
- /** Minimal injectable fs surface used by `discoverInstances`. */
942
- interface InstanceDiscoveryFs {
943
- existsSync(targetPath: string): boolean;
944
- readdirSync(dirPath: string): string[];
945
- /** Returns the mtime of the path in ms, or `null` if missing / unreadable. */
946
- statMtimeMs(filePath: string): number | null;
947
- readFileSync(filePath: string, encoding: 'utf8'): string;
948
- rmSync(dirPath: string, options: {
949
- recursive: true;
950
- force: true;
951
- }): void;
952
- }
953
- interface DiscoveryOptions {
954
- /**
955
- * pid to exclude from the result. Defaults to `process.pid` — the
956
- * caller's own state.json should not appear in its own sibling list.
957
- */
958
- readonly excludePid?: number;
959
- /**
960
- * Heartbeat mtime older than `now - staleThresholdMs` → directory is
961
- * stale. Default 30_000 (matches v0.7.41 spec).
962
- */
963
- readonly staleThresholdMs?: number;
964
- /**
965
- * When true, stale directories are removed during the scan (best-
966
- * effort `rmSync(force:true)`; failure is swallowed). When false,
967
- * stale directories are skipped but left on disk. Defaults to false
968
- * — wire from the session-startup path with `true` so crashed-process
969
- * dirs don't accumulate.
970
- */
971
- readonly reapStale?: boolean;
972
- readonly clock?: () => number;
973
- readonly fs?: InstanceDiscoveryFs;
974
- readonly instancesRoot?: string;
975
- /** Per-instance failure log; defaults to a no-op. Pass `console.warn` in dev. */
976
- readonly logger?: (message: string) => void;
977
- }
978
- /**
979
- * Synchronous discovery scan. Returns a freshness-sorted array
980
- * (newest heartbeat first) so callers that want only the N most-recent
981
- * siblings can slice without re-sorting.
982
- *
983
- * Never throws. A missing `<instancesRoot>` directory means the user
984
- * is the first session ever on this machine → `[]`. A scan failure on
985
- * one entry is logged + skipped, not propagated.
986
- */
987
- declare function discoverInstances(options?: DiscoveryOptions): DiscoveredInstance[];
988
-
989
- export { requestTaskStop as $, buildAssistantMessageFromLlmResult as K, buildToolResultMessage as L, MAX_TOOL_LOOP_ITERATIONS as M, collectGuardrails as N, createAgent as Q, createHandoff as U, createStateWriter as V, discoverInstances as W, executeRunnerToolCall as X, isRunnableTool as Y, isRunnerLlmResult as Z, registerChildTask as _, runInputGuardrails as a0, runOutputGuardrails as a1, runToolAfterGuardrails as a2, runToolBeforeGuardrails as a3, GuardrailBlockedError as g, GuardrailEscalateError as i };
990
- export type { Agent as A, StateWriterFs as B, ChildTaskRegistry as C, DiscoveredInstance as D, StateWriterOptions as E, ToolBeforeOutcome as F, Guardrail as G, Handoff as H, InputGuardrail as I, ToolGuardrail as J, OutputGuardrail as O, PersistedSessionState as P, ReasoningDepth as R, SessionMeta as S, TaskAbortRegistry as T, AgentMessage as a, AgentMiddlewareDeclaration as b, AgentReasoningProfile as c, AgentTool as d, CurrentTodoSummary as e, DiscoveryOptions as f, GuardrailContext as h, GuardrailVerdict as j, InstanceDiscoveryFs as k, RecentlyModifiedFile as l, RequestTaskStopOptions as m, RequestTaskStopResult as n, RunnableTool as o, RunnerLlmResult as p, RunnerLlmReturn as q, RunnerToolCall as r, RunnerToolContext as s, RunnerToolObserver as t, RunnerToolResult as u, SessionStateSnapshot as v, Span as w, SpanData as x, SpanError as y, StateWriter as z };