omk-agent-core 0.90.8 → 0.90.9

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 (58) hide show
  1. package/README.md +97 -1
  2. package/dist/agent-loop.d.ts +25 -2
  3. package/dist/agent-loop.d.ts.map +1 -1
  4. package/dist/agent-loop.js +492 -187
  5. package/dist/agent-loop.js.map +1 -1
  6. package/dist/agent.d.ts +29 -7
  7. package/dist/agent.d.ts.map +1 -1
  8. package/dist/agent.js +81 -46
  9. package/dist/agent.js.map +1 -1
  10. package/dist/builtin-tool-resource-claims.d.ts +19 -0
  11. package/dist/builtin-tool-resource-claims.d.ts.map +1 -0
  12. package/dist/builtin-tool-resource-claims.js +200 -0
  13. package/dist/builtin-tool-resource-claims.js.map +1 -0
  14. package/dist/index.d.ts +4 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +7 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/node-resource-resolver.d.ts +42 -0
  19. package/dist/node-resource-resolver.d.ts.map +1 -0
  20. package/dist/node-resource-resolver.js +149 -0
  21. package/dist/node-resource-resolver.js.map +1 -0
  22. package/dist/node.d.ts +1 -0
  23. package/dist/node.d.ts.map +1 -1
  24. package/dist/node.js +2 -0
  25. package/dist/node.js.map +1 -1
  26. package/dist/path-segments.d.ts +8 -0
  27. package/dist/path-segments.d.ts.map +1 -1
  28. package/dist/path-segments.js +62 -9
  29. package/dist/path-segments.js.map +1 -1
  30. package/dist/plain-data.d.ts +7 -0
  31. package/dist/plain-data.d.ts.map +1 -0
  32. package/dist/plain-data.js +70 -0
  33. package/dist/plain-data.js.map +1 -0
  34. package/dist/tool-dag-scheduler.d.ts +86 -0
  35. package/dist/tool-dag-scheduler.d.ts.map +1 -0
  36. package/dist/tool-dag-scheduler.js +171 -0
  37. package/dist/tool-dag-scheduler.js.map +1 -0
  38. package/dist/tool-execution-boundary.d.ts +52 -0
  39. package/dist/tool-execution-boundary.d.ts.map +1 -0
  40. package/dist/tool-execution-boundary.js +185 -0
  41. package/dist/tool-execution-boundary.js.map +1 -0
  42. package/dist/tool-resource-claims.d.ts +31 -0
  43. package/dist/tool-resource-claims.d.ts.map +1 -0
  44. package/dist/tool-resource-claims.js +128 -0
  45. package/dist/tool-resource-claims.js.map +1 -0
  46. package/dist/tool-timeout.d.ts +96 -0
  47. package/dist/tool-timeout.d.ts.map +1 -0
  48. package/dist/tool-timeout.js +173 -0
  49. package/dist/tool-timeout.js.map +1 -0
  50. package/dist/tool-transcript-integrity.d.ts +65 -0
  51. package/dist/tool-transcript-integrity.d.ts.map +1 -0
  52. package/dist/tool-transcript-integrity.js +223 -0
  53. package/dist/tool-transcript-integrity.js.map +1 -0
  54. package/dist/types.d.ts +219 -10
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +50 -1
  57. package/dist/types.js.map +1 -1
  58. package/package.json +2 -2
package/dist/agent.js CHANGED
@@ -1,16 +1,9 @@
1
1
  import { streamSimple, } from "omk-ai";
2
- import { runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";
2
+ import { planFailureTermination, runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";
3
+ import { createImmutableSnapshot } from "./tool-execution-boundary.js";
3
4
  function defaultConvertToLlm(messages) {
4
5
  return messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
5
6
  }
6
- const EMPTY_USAGE = {
7
- input: 0,
8
- output: 0,
9
- cacheRead: 0,
10
- cacheWrite: 0,
11
- totalTokens: 0,
12
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
13
- };
14
7
  const DEFAULT_MODEL = {
15
8
  id: "unknown",
16
9
  name: "unknown",
@@ -108,6 +101,22 @@ export class Agent {
108
101
  maxRetryDelayMs;
109
102
  /** Tool execution strategy for assistant messages that contain multiple tool calls. */
110
103
  toolExecution;
104
+ /** Default execution timeout for tools; provider request timeout remains separate. */
105
+ toolTimeoutMs;
106
+ /** Per-tool-name execution timeout overrides. */
107
+ toolTimeouts;
108
+ /** Deterministic tool scheduler selection. */
109
+ toolScheduler;
110
+ /** Optional dag-v2 concurrency cap. */
111
+ maxToolConcurrency;
112
+ /** Require explicit resource claims for parallel extension tools. */
113
+ strictExtensionClaims;
114
+ /** Working directory used to resolve path-scoped resource claims. */
115
+ cwd;
116
+ /** Optional dag-v2 platform identity resolver for path-claim aliases. */
117
+ resourceKeyResolver;
118
+ /** Execution-policy defaults (late-settlement audit policy). */
119
+ toolExecutionPolicy;
111
120
  constructor(options = {}) {
112
121
  this._state = createMutableAgentState(options.initialState);
113
122
  this.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;
@@ -126,16 +135,22 @@ export class Agent {
126
135
  this.transport = options.transport ?? "auto";
127
136
  this.maxRetryDelayMs = options.maxRetryDelayMs;
128
137
  this.toolExecution = options.toolExecution ?? "parallel";
138
+ this.toolTimeoutMs = options.toolTimeoutMs;
139
+ this.toolTimeouts = options.toolTimeouts;
140
+ this.toolScheduler = options.toolScheduler ?? "waves-v1";
141
+ this.maxToolConcurrency = options.maxToolConcurrency;
142
+ this.strictExtensionClaims = options.strictExtensionClaims ?? false;
143
+ this.cwd = options.cwd;
144
+ this.resourceKeyResolver = options.resourceKeyResolver;
145
+ this.toolExecutionPolicy = options.toolExecutionPolicy;
129
146
  }
130
147
  /**
131
148
  * Subscribe to agent lifecycle events.
132
149
  *
133
- * Listener promises are awaited in subscription order and are included in
134
- * the current run's settlement. Listeners also receive the active abort
135
- * signal for the current run.
136
- *
137
- * `agent_end` is the final emitted event for a run, but the agent does not
138
- * become idle until all awaited listeners for that event have settled.
150
+ * Listener promises are awaited in subscription order except for
151
+ * observation-only `tool_execution_update` delivery, which is detached so a
152
+ * listener cannot delay timeout/abort closure. Listeners receive the active
153
+ * abort signal. `agent_end` remains awaited before the agent becomes idle.
139
154
  */
140
155
  subscribe(listener) {
141
156
  this.listeners.add(listener);
@@ -302,6 +317,14 @@ export class Agent {
302
317
  thinkingBudgets: this.thinkingBudgets,
303
318
  maxRetryDelayMs: this.maxRetryDelayMs,
304
319
  toolExecution: this.toolExecution,
320
+ toolTimeoutMs: this.toolTimeoutMs,
321
+ toolTimeouts: this.toolTimeouts,
322
+ toolScheduler: this.toolScheduler,
323
+ maxToolConcurrency: this.maxToolConcurrency,
324
+ strictExtensionClaims: this.strictExtensionClaims,
325
+ cwd: this.cwd,
326
+ resourceKeyResolver: this.resourceKeyResolver,
327
+ toolExecutionPolicy: this.toolExecutionPolicy,
305
328
  beforeToolCall: this.beforeToolCall,
306
329
  afterToolCall: this.afterToolCall,
307
330
  prepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,
@@ -335,28 +358,30 @@ export class Agent {
335
358
  await executor(abortController.signal);
336
359
  }
337
360
  catch (error) {
338
- await this.handleRunFailure(error, abortController.signal.aborted);
361
+ const failure = error instanceof Error ? error : new Error(String(error));
362
+ await this.handleRunFailure(failure, abortController.signal.aborted);
339
363
  }
340
364
  finally {
341
365
  this.finishRun();
342
366
  }
343
367
  }
344
368
  async handleRunFailure(error, aborted) {
345
- const failureMessage = {
346
- role: "assistant",
347
- content: [{ type: "text", text: "" }],
348
- api: this._state.model.api,
349
- provider: this._state.model.provider,
350
- model: this._state.model.id,
351
- usage: EMPTY_USAGE,
352
- stopReason: aborted ? "aborted" : "error",
353
- errorMessage: error instanceof Error ? error.message : String(error),
354
- timestamp: Date.now(),
355
- };
356
- await this.processEvents({ type: "message_start", message: failureMessage });
357
- await this.processEvents({ type: "message_end", message: failureMessage });
358
- await this.processEvents({ type: "turn_end", message: failureMessage, toolResults: [] });
359
- await this.processEvents({ type: "agent_end", messages: [failureMessage] });
369
+ // Apply the same failure-termination contract as the low-level loop so the
370
+ // disposition of any unresolved tool calls matches transcript repair:
371
+ // an unambiguous open turn is closed with exactly one synthetic result per
372
+ // missing call before a single coherent failure assistant, and an ambiguous
373
+ // transcript fails closed without fabricating a turn over corruption.
374
+ const plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);
375
+ for (const result of plan.closureResults) {
376
+ await this.processEvents({ type: "message_start", message: result });
377
+ await this.processEvents({ type: "message_end", message: result });
378
+ }
379
+ if (plan.failureMessage) {
380
+ await this.processEvents({ type: "message_start", message: plan.failureMessage });
381
+ await this.processEvents({ type: "message_end", message: plan.failureMessage });
382
+ await this.processEvents({ type: "turn_end", message: plan.failureMessage, toolResults: [] });
383
+ }
384
+ await this.processEvents({ type: "agent_end", messages: plan.messages });
360
385
  }
361
386
  finishRun() {
362
387
  this._state.isStreaming = false;
@@ -365,14 +390,9 @@ export class Agent {
365
390
  this.activeRun?.resolve();
366
391
  this.activeRun = undefined;
367
392
  }
368
- /**
369
- * Reduce internal state for a loop event, then await listeners.
370
- *
371
- * `agent_end` only means no further loop events will be emitted. The run is
372
- * considered idle later, after all awaited listeners for `agent_end` finish
373
- * and `finishRun()` clears runtime-owned state.
374
- */
375
- async processEvents(event) {
393
+ /** Reduce state, detach update observation, and await all terminal listeners. */
394
+ async processEvents(sourceEvent) {
395
+ const event = createImmutableSnapshot(sourceEvent);
376
396
  switch (event.type) {
377
397
  case "message_start":
378
398
  this._state.streamingMessage = event.message;
@@ -384,12 +404,9 @@ export class Agent {
384
404
  this._state.streamingMessage = undefined;
385
405
  this._state.messages.push(event.message);
386
406
  break;
387
- case "tool_execution_start": {
388
- const pendingToolCalls = new Set(this._state.pendingToolCalls);
389
- pendingToolCalls.add(event.toolCallId);
390
- this._state.pendingToolCalls = pendingToolCalls;
407
+ case "tool_execution_start":
408
+ this._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);
391
409
  break;
392
- }
393
410
  case "tool_execution_end": {
394
411
  const pendingToolCalls = new Set(this._state.pendingToolCalls);
395
412
  pendingToolCalls.delete(event.toolCallId);
@@ -407,11 +424,29 @@ export class Agent {
407
424
  }
408
425
  const signal = this.activeRun?.abortController.signal;
409
426
  if (!signal) {
427
+ // A tool's real promise may settle after the run already ended. The
428
+ // late-settlement event is audit-only by contract, so it is still
429
+ // delivered (with an inert signal) instead of being dropped; every
430
+ // other event outside an active run remains a hard invariant break.
431
+ if (event.type === "tool_execution_late_settlement") {
432
+ const inertSignal = new AbortController().signal;
433
+ for (const listener of this.listeners)
434
+ await listener(createImmutableSnapshot(event), inertSignal);
435
+ return;
436
+ }
410
437
  throw new Error("Agent listener invoked outside active run");
411
438
  }
412
- for (const listener of this.listeners) {
413
- await listener(event, signal);
439
+ if (event.type === "tool_execution_update") {
440
+ for (const listener of this.listeners) {
441
+ const snapshot = createImmutableSnapshot(event);
442
+ void Promise.resolve()
443
+ .then(() => listener(snapshot, signal))
444
+ .catch(() => undefined);
445
+ }
446
+ return;
414
447
  }
448
+ for (const listener of this.listeners)
449
+ await listener(createImmutableSnapshot(event), signal);
415
450
  }
416
451
  }
417
452
  //# sourceMappingURL=agent.js.map
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,YAAY,GAIZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAoBrE,SAAS,mBAAmB,CAAC,QAAwB,EAAa;IACjE,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,CACrG,CAAC;AAAA,CACF;AAED,MAAM,WAAW,GAAG;IACnB,KAAK,EAAE,CAAC;IACR,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,K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CAAC,CAAC;gBAC/D,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBACvC,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;gBAChD,MAAM;YACP,CAAC;YAED,KAAK,oBAAoB,EAAE,CAAC;gBAC3B,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;gBAC/D,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBAC1C,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;gBAChD,MAAM;YACP,CAAC;YAED,KAAK,UAAU;gBACd,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC;oBACtE,IAAI,CAAC,MAAM,CAAC,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC;gBACvD,CAAC;gBACD,MAAM;YAEP,KAAK,WAAW;gBACf,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,SAAS,CAAC;gBACzC,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IAAA,CACD;CACD","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,YAAY,GAIZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8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CAAC,SAAS;oBAAE,MAAM,QAAQ,CAAC,uBAAuB,CAAC,KAAK,CAAC,EAAE,WAAW,CAAC,CAAC;gBACnG,OAAO;YACR,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,EAAE,CAAC;YAC5C,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;gBACvC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;gBAChD,KAAK,OAAO,CAAC,OAAO,EAAE;qBACpB,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;qBACtC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAC1B,CAAC;YACD,OAAO;QACR,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS;YAAE,MAAM,QAAQ,CAAC,uBAAuB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,CAAC;IAAA,CAC9F;CACD","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"omk-ai\";\nimport { planFailureTermination, runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { createImmutableSnapshot } from \"./tool-execution-boundary.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n\ttoolTimeoutMs?: AgentLoopConfig[\"toolTimeoutMs\"];\n\ttoolTimeouts?: AgentLoopConfig[\"toolTimeouts\"];\n\ttoolScheduler?: AgentLoopConfig[\"toolScheduler\"];\n\tmaxToolConcurrency?: AgentLoopConfig[\"maxToolConcurrency\"];\n\tstrictExtensionClaims?: AgentLoopConfig[\"strictExtensionClaims\"];\n\tcwd?: AgentLoopConfig[\"cwd\"];\n\tresourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\ttoolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\t/** Default execution timeout for tools; provider request timeout remains separate. */\n\tpublic toolTimeoutMs?: number;\n\t/** Per-tool-name execution timeout overrides. */\n\tpublic toolTimeouts?: Record<string, number>;\n\t/** Deterministic tool scheduler selection. */\n\tpublic toolScheduler: NonNullable<AgentLoopConfig[\"toolScheduler\"]>;\n\t/** Optional dag-v2 concurrency cap. */\n\tpublic maxToolConcurrency?: number;\n\t/** Require explicit resource claims for parallel extension tools. */\n\tpublic strictExtensionClaims: boolean;\n\t/** Working directory used to resolve path-scoped resource claims. */\n\tpublic cwd?: string;\n\t/** Optional dag-v2 platform identity resolver for path-claim aliases. */\n\tpublic resourceKeyResolver?: AgentLoopConfig[\"resourceKeyResolver\"];\n\t/** Execution-policy defaults (late-settlement audit policy). */\n\tpublic toolExecutionPolicy?: AgentLoopConfig[\"toolExecutionPolicy\"];\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.onResponse = options.onResponse;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.prepareNextTurn = options.prepareNextTurn;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t\tthis.toolTimeoutMs = options.toolTimeoutMs;\n\t\tthis.toolTimeouts = options.toolTimeouts;\n\t\tthis.toolScheduler = options.toolScheduler ?? \"waves-v1\";\n\t\tthis.maxToolConcurrency = options.maxToolConcurrency;\n\t\tthis.strictExtensionClaims = options.strictExtensionClaims ?? false;\n\t\tthis.cwd = options.cwd;\n\t\tthis.resourceKeyResolver = options.resourceKeyResolver;\n\t\tthis.toolExecutionPolicy = options.toolExecutionPolicy;\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order except for\n\t * observation-only `tool_execution_update` delivery, which is detached so a\n\t * listener cannot delay timeout/abort closure. Listeners receive the active\n\t * abort signal. `agent_end` remains awaited before the agent becomes idle.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Last message is a completed assistant turn. Two sub-cases:\n\t\t\t// 1. The assistant message carries pending tool calls without matching\n\t\t\t// tool results -> the provider will reject this, so fail fast with a\n\t\t\t// clear, actionable error.\n\t\t\t// 2. The assistant message is plain text/thinking (no tool calls). This is\n\t\t\t// a finished turn (e.g. after compaction, session resume, or an\n\t\t\t// explicit \"continue\" request). We honour it by injecting an empty\n\t\t\t// user prompt so the model can extend its previous answer rather than\n\t\t\t// throwing the opaque \"Cannot continue from message role: assistant\".\n\t\t\tconst hasPendingToolCalls = lastMessage.content.some((c) => c.type === \"toolCall\");\n\t\t\tif (hasPendingToolCalls) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Cannot continue: the last assistant message has pending tool calls without results. \" +\n\t\t\t\t\t\t\"Provide tool results (or a new user message) before continuing.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait this.runPromptMessages([{ role: \"user\", content: [{ type: \"text\", text: \"\" }], timestamp: Date.now() }]);\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\ttoolTimeoutMs: this.toolTimeoutMs,\n\t\t\ttoolTimeouts: this.toolTimeouts,\n\t\t\ttoolScheduler: this.toolScheduler,\n\t\t\tmaxToolConcurrency: this.maxToolConcurrency,\n\t\t\tstrictExtensionClaims: this.strictExtensionClaims,\n\t\t\tcwd: this.cwd,\n\t\t\tresourceKeyResolver: this.resourceKeyResolver,\n\t\t\ttoolExecutionPolicy: this.toolExecutionPolicy,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tprepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.handleRunFailure(failure, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\t// Apply the same failure-termination contract as the low-level loop so the\n\t\t// disposition of any unresolved tool calls matches transcript repair:\n\t\t// an unambiguous open turn is closed with exactly one synthetic result per\n\t\t// missing call before a single coherent failure assistant, and an ambiguous\n\t\t// transcript fails closed without fabricating a turn over corruption.\n\t\tconst plan = planFailureTermination(this._state.messages, this._state.model, error, aborted);\n\n\t\tfor (const result of plan.closureResults) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: result });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: result });\n\t\t}\n\n\t\tif (plan.failureMessage) {\n\t\t\tawait this.processEvents({ type: \"message_start\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"message_end\", message: plan.failureMessage });\n\t\t\tawait this.processEvents({ type: \"turn_end\", message: plan.failureMessage, toolResults: [] });\n\t\t}\n\n\t\tawait this.processEvents({ type: \"agent_end\", messages: plan.messages });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/** Reduce state, detach update observation, and await all terminal listeners. */\n\tprivate async processEvents(sourceEvent: AgentEvent): Promise<void> {\n\t\tconst event = createImmutableSnapshot(sourceEvent);\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis._state.pendingToolCalls = new Set(this._state.pendingToolCalls).add(event.toolCallId);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\t// A tool's real promise may settle after the run already ended. The\n\t\t\t// late-settlement event is audit-only by contract, so it is still\n\t\t\t// delivered (with an inert signal) instead of being dropped; every\n\t\t\t// other event outside an active run remains a hard invariant break.\n\t\t\tif (event.type === \"tool_execution_late_settlement\") {\n\t\t\t\tconst inertSignal = new AbortController().signal;\n\t\t\t\tfor (const listener of this.listeners) await listener(createImmutableSnapshot(event), inertSignal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tif (event.type === \"tool_execution_update\") {\n\t\t\tfor (const listener of this.listeners) {\n\t\t\t\tconst snapshot = createImmutableSnapshot(event);\n\t\t\t\tvoid Promise.resolve()\n\t\t\t\t\t.then(() => listener(snapshot, signal))\n\t\t\t\t\t.catch(() => undefined);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const listener of this.listeners) await listener(createImmutableSnapshot(event), signal);\n\t}\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import type { ToolParallelPolicy } from "./parallel-tool-batch.ts";
2
+ import type { ClaimableToolCall, RegisteredToolClaimDefinition, ResolveToolClaimsOptions, ToolClaimResolution } from "./tool-resource-claims.ts";
3
+ import type { AgentTool, ToolResourceAccess, ToolResourceClaim } from "./types.ts";
4
+ export declare function isPlainArguments(value: unknown): value is Record<string, unknown>;
5
+ export declare function findRegisteredToolClaimDefinition(name: string, registeredTools: readonly RegisteredToolClaimDefinition[] | undefined): RegisteredToolClaimDefinition | undefined;
6
+ /** Bind a fixed call identity without spreading away prototype tool methods. */
7
+ export declare function bindToolIdentity(candidate: AgentTool, name: string): AgentTool;
8
+ export declare function resolveToolPolicy(name: string, options: ResolveToolClaimsOptions): ToolParallelPolicy | undefined;
9
+ export declare function isBuiltinPathClaimTool(name: string): boolean;
10
+ export declare function resolvePathClaimKey(toolName: string, args: Record<string, unknown>, cwd: string): string | null;
11
+ export declare function resolvePathClaimWithIdentity(rawPath: unknown, access: ToolResourceAccess, options: ResolveToolClaimsOptions): Promise<ToolClaimResolution>;
12
+ export declare function resolveBuiltinPathClaimWithIdentity(toolCall: ClaimableToolCall, options: ResolveToolClaimsOptions): Promise<ToolClaimResolution>;
13
+ export declare function resolveToolClaims(toolCall: ClaimableToolCall, options: ResolveToolClaimsOptions): ToolClaimResolution;
14
+ export declare function pathClaimsOverlap(left: Extract<ToolResourceClaim, {
15
+ kind: "path";
16
+ }>, right: Extract<ToolResourceClaim, {
17
+ kind: "path";
18
+ }>): boolean;
19
+ //# sourceMappingURL=builtin-tool-resource-claims.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builtin-tool-resource-claims.d.ts","sourceRoot":"","sources":["../src/builtin-tool-resource-claims.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAQnE,OAAO,KAAK,EACX,iBAAiB,EACjB,6BAA6B,EAC7B,wBAAwB,EACxB,mBAAmB,EACnB,MAAM,2BAA2B,CAAC;AACn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AAK,EAAE,OAAO,CAAC,iBAAiB,EAAE;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,GACjD,OAAO,CAKT","sourcesContent":["import type { ToolParallelPolicy } from \"./parallel-tool-batch.ts\";\nimport { NEVER_PARALLEL_TOOLS, PARALLEL_SAFE_TOOLS, PATH_SCOPED_TOOLS } from \"./parallel-tool-batch.ts\";\nimport {\n\tcanonicalizeLexicalPath,\n\tjoinPathSegments,\n\tnormalizePathSlashes,\n\tpathSegmentsOverlap,\n} from \"./path-segments.ts\";\nimport type {\n\tClaimableToolCall,\n\tRegisteredToolClaimDefinition,\n\tResolveToolClaimsOptions,\n\tToolClaimResolution,\n} from \"./tool-resource-claims.ts\";\nimport type { AgentTool, ResolvedResourceKeys, ToolResourceAccess, ToolResourceClaim } from \"./types.ts\";\n\nconst SEARCH_PATH_TOOLS = new Set<string>([\"grep\", \"find\", \"ls\", \"search_files\"]);\n\nexport function isPlainArguments(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function findRegisteredToolClaimDefinition(\n\tname: string,\n\tregisteredTools: readonly RegisteredToolClaimDefinition[] | undefined,\n): RegisteredToolClaimDefinition | undefined {\n\treturn registeredTools?.find((tool) => tool.name === name);\n}\n\n/** Bind a fixed call identity without spreading away prototype tool methods. */\nexport function bindToolIdentity(candidate: AgentTool, name: string): AgentTool {\n\tconst tool: AgentTool = Object.create(candidate);\n\tObject.defineProperty(tool, \"name\", { enumerable: true, value: name });\n\tObject.defineProperty(tool, \"execute\", { value: candidate.execute.bind(candidate) });\n\tif (candidate.prepareArguments) {\n\t\tObject.defineProperty(tool, \"prepareArguments\", { value: candidate.prepareArguments.bind(candidate) });\n\t}\n\tif (candidate.resourceClaims) {\n\t\tObject.defineProperty(tool, \"resourceClaims\", { value: candidate.resourceClaims.bind(candidate) });\n\t}\n\treturn Object.freeze(tool);\n}\n\nexport function resolveToolPolicy(name: string, options: ResolveToolClaimsOptions): ToolParallelPolicy | undefined {\n\treturn (\n\t\tfindRegisteredToolClaimDefinition(name, options.registeredTools)?.executionMode ?? options.toolPolicies?.get(name)\n\t);\n}\n\nexport function isBuiltinPathClaimTool(name: string): boolean {\n\treturn PATH_SCOPED_TOOLS.has(name) || SEARCH_PATH_TOOLS.has(name);\n}\n\nfunction normalizeLeadingSlashes(rawPath: string): string {\n\tconst normalized = normalizePathSlashes(rawPath);\n\treturn /^\\/{3,}/.test(normalized) ? normalized.replace(/^\\/+/, \"/\") : normalized;\n}\n\nfunction resolveCanonicalPathKey(rawPath: unknown, cwd: unknown): string | null {\n\tif (typeof rawPath !== \"string\" || rawPath.trim().length === 0 || typeof cwd !== \"string\") return null;\n\tconst normalized = normalizeLeadingSlashes(rawPath);\n\tconst canonicalCwd = canonicalizeLexicalPath(cwd);\n\tif (\n\t\tnormalized.startsWith(\"//\") ||\n\t\t/^[A-Za-z]:(?!\\/)/.test(normalized) ||\n\t\tcanonicalCwd === null ||\n\t\t!(canonicalCwd.startsWith(\"/\") || /^[A-Za-z]:\\//.test(canonicalCwd))\n\t) {\n\t\treturn null;\n\t}\n\n\tlet resolved: string;\n\tif (/^[A-Za-z]:\\//.test(normalized)) {\n\t\tresolved = normalized;\n\t} else if (normalized.startsWith(\"/\")) {\n\t\tconst cwdDrive = /^([A-Za-z]:)\\//.exec(canonicalCwd);\n\t\tresolved = cwdDrive ? `${cwdDrive[1]}${normalized}` : normalized;\n\t} else {\n\t\tresolved = joinPathSegments(canonicalCwd, normalized);\n\t}\n\tconst canonical = canonicalizeLexicalPath(resolved);\n\treturn canonical !== null && (canonical.startsWith(\"/\") || /^[A-Za-z]:\\//.test(canonical)) ? canonical : null;\n}\n\nfunction builtinRawPath(toolName: string, args: Record<string, unknown>, cwd: string): unknown {\n\tif (PATH_SCOPED_TOOLS.has(toolName)) return args.path;\n\tif (!SEARCH_PATH_TOOLS.has(toolName)) return undefined;\n\treturn typeof args.path === \"string\" && args.path.trim().length > 0 ? args.path : cwd;\n}\n\nfunction builtinPathAccess(toolName: string): ToolResourceAccess {\n\treturn toolName === \"read\" || SEARCH_PATH_TOOLS.has(toolName) ? \"read\" : \"write\";\n}\n\nexport function resolvePathClaimKey(toolName: string, args: Record<string, unknown>, cwd: string): string | null {\n\treturn isBuiltinPathClaimTool(toolName) ? resolveCanonicalPathKey(builtinRawPath(toolName, args, cwd), cwd) : null;\n}\n\nfunction canonicalizeResolvedPathKey(rawPath: unknown): string | null {\n\tif (typeof rawPath !== \"string\" || rawPath.trim().length === 0) return null;\n\tconst normalized = normalizeLeadingSlashes(rawPath);\n\tif (normalized.startsWith(\"//\")) {\n\t\tconst match = /^\\/\\/+([^/]+)\\/+([^/]+)(?:\\/+(.*))?$/.exec(normalized);\n\t\tif (!match) return null;\n\t\tconst suffix = match[3] ?? \"\";\n\t\tconst canonicalSuffix = suffix.length === 0 ? \"\" : canonicalizeLexicalPath(suffix);\n\t\tif (canonicalSuffix === null) return null;\n\t\tconst root = `//${match[1].toLowerCase()}/${match[2].toLowerCase()}`;\n\t\treturn canonicalSuffix.length === 0 ? root : `${root}/${canonicalSuffix}`;\n\t}\n\tconst canonical = canonicalizeLexicalPath(normalized);\n\tif (canonical === null) return null;\n\tconst drive = /^([A-Za-z]:)\\/(.*)$/.exec(canonical);\n\tif (drive) return `${drive[1].toLowerCase()}/${drive[2]}`;\n\treturn canonical.startsWith(\"/\") ? canonical : null;\n}\n\nfunction normalizeResolvedResourceKeys(value: unknown): ResolvedResourceKeys | null {\n\tif (!isPlainArguments(value)) return null;\n\tconst lexicalKey = canonicalizeResolvedPathKey(value.lexicalKey);\n\tif (lexicalKey === null) return null;\n\tconst realKey = value.realKey === undefined ? undefined : canonicalizeResolvedPathKey(value.realKey);\n\tif (realKey === null || (value.inodeKey !== undefined && (typeof value.inodeKey !== \"string\" || !value.inodeKey))) {\n\t\treturn null;\n\t}\n\tconst inodeKey = value.inodeKey;\n\tif (\n\t\t(lexicalKey.startsWith(\"//\") || /^[a-z]:\\//.test(lexicalKey)) &&\n\t\trealKey === undefined &&\n\t\tinodeKey === undefined\n\t) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tlexicalKey,\n\t\t...(realKey === undefined ? {} : { realKey }),\n\t\t...(inodeKey === undefined ? {} : { inodeKey }),\n\t};\n}\n\nexport async function resolvePathClaimWithIdentity(\n\trawPath: unknown,\n\taccess: ToolResourceAccess,\n\toptions: ResolveToolClaimsOptions,\n): Promise<ToolClaimResolution> {\n\tif (typeof rawPath !== \"string\" || rawPath.trim().length === 0) return { kind: \"exclusive\" };\n\tconst resolver = options.resourceKeyResolver;\n\tif (!resolver) {\n\t\tconst key = resolveCanonicalPathKey(rawPath, options.cwd);\n\t\treturn key === null ? { kind: \"exclusive\" } : { kind: \"claims\", claims: [{ kind: \"path\", key, access }] };\n\t}\n\ttry {\n\t\tconst keys = normalizeResolvedResourceKeys(await resolver.resolvePath(rawPath, options.cwd));\n\t\tif (keys === null) return { kind: \"exclusive\" };\n\t\treturn {\n\t\t\tkind: \"claims\",\n\t\t\tclaims: [\n\t\t\t\t{\n\t\t\t\t\tkind: \"path\",\n\t\t\t\t\tkey: keys.lexicalKey,\n\t\t\t\t\taccess,\n\t\t\t\t\t...(keys.realKey === undefined ? {} : { realKey: keys.realKey }),\n\t\t\t\t\t...(keys.inodeKey === undefined ? {} : { inodeKey: keys.inodeKey }),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t} catch {\n\t\treturn { kind: \"exclusive\" };\n\t}\n}\n\nexport function resolveBuiltinPathClaimWithIdentity(\n\ttoolCall: ClaimableToolCall,\n\toptions: ResolveToolClaimsOptions,\n): Promise<ToolClaimResolution> {\n\tif (!isPlainArguments(toolCall.arguments)) return Promise.resolve({ kind: \"exclusive\" });\n\treturn resolvePathClaimWithIdentity(\n\t\tbuiltinRawPath(toolCall.name, toolCall.arguments, options.cwd),\n\t\tbuiltinPathAccess(toolCall.name),\n\t\toptions,\n\t);\n}\n\nexport function resolveToolClaims(toolCall: ClaimableToolCall, options: ResolveToolClaimsOptions): ToolClaimResolution {\n\tif (!isPlainArguments(toolCall.arguments)) return { kind: \"exclusive\" };\n\tconst name = toolCall.name;\n\tif (NEVER_PARALLEL_TOOLS.has(name) || name === \"bash\" || resolveToolPolicy(name, options) === \"sequential\") {\n\t\treturn { kind: \"exclusive\" };\n\t}\n\tif (isBuiltinPathClaimTool(name)) {\n\t\tconst key = resolvePathClaimKey(name, toolCall.arguments, options.cwd);\n\t\treturn key === null\n\t\t\t? { kind: \"exclusive\" }\n\t\t\t: { kind: \"claims\", claims: [{ access: builtinPathAccess(name), kind: \"path\", key }] };\n\t}\n\tif (PARALLEL_SAFE_TOOLS.has(name)) return { kind: \"claims\", claims: [] };\n\tif (resolveToolPolicy(name, options) === \"parallel\") {\n\t\treturn options.strictExtensionClaims ? { kind: \"exclusive\" } : { kind: \"claims\", claims: [] };\n\t}\n\treturn { kind: \"exclusive\" };\n}\n\nfunction pathClaimKeys(claim: Extract<ToolResourceClaim, { kind: \"path\" }>): string[] {\n\treturn claim.realKey === undefined || claim.realKey === claim.key ? [claim.key] : [claim.key, claim.realKey];\n}\n\nfunction uncSegments(key: string): string[] | null {\n\treturn key.startsWith(\"//\")\n\t\t? key\n\t\t\t\t.slice(2)\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter((segment) => segment.length > 0)\n\t\t\t\t.map((segment) => segment.toLowerCase())\n\t\t: null;\n}\n\nfunction identityPathKeysOverlap(left: string, right: string): boolean {\n\tconst leftUnc = uncSegments(left);\n\tconst rightUnc = uncSegments(right);\n\tif (leftUnc === null || rightUnc === null) {\n\t\treturn leftUnc === null && rightUnc === null && pathSegmentsOverlap(left, right);\n\t}\n\tconst commonLength = Math.min(leftUnc.length, rightUnc.length);\n\tfor (let index = 0; index < commonLength; index++) {\n\t\tif (leftUnc[index] !== rightUnc[index]) return false;\n\t}\n\treturn true;\n}\n\nexport function pathClaimsOverlap(\n\tleft: Extract<ToolResourceClaim, { kind: \"path\" }>,\n\tright: Extract<ToolResourceClaim, { kind: \"path\" }>,\n): boolean {\n\tif (left.inodeKey !== undefined && left.inodeKey === right.inodeKey) return true;\n\treturn pathClaimKeys(left).some((leftKey) =>\n\t\tpathClaimKeys(right).some((rightKey) => identityPathKeysOverlap(leftKey, rightKey)),\n\t);\n}\n"]}
@@ -0,0 +1,200 @@
1
+ import { NEVER_PARALLEL_TOOLS, PARALLEL_SAFE_TOOLS, PATH_SCOPED_TOOLS } from "./parallel-tool-batch.js";
2
+ import { canonicalizeLexicalPath, joinPathSegments, normalizePathSlashes, pathSegmentsOverlap, } from "./path-segments.js";
3
+ const SEARCH_PATH_TOOLS = new Set(["grep", "find", "ls", "search_files"]);
4
+ export function isPlainArguments(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ export function findRegisteredToolClaimDefinition(name, registeredTools) {
8
+ return registeredTools?.find((tool) => tool.name === name);
9
+ }
10
+ /** Bind a fixed call identity without spreading away prototype tool methods. */
11
+ export function bindToolIdentity(candidate, name) {
12
+ const tool = Object.create(candidate);
13
+ Object.defineProperty(tool, "name", { enumerable: true, value: name });
14
+ Object.defineProperty(tool, "execute", { value: candidate.execute.bind(candidate) });
15
+ if (candidate.prepareArguments) {
16
+ Object.defineProperty(tool, "prepareArguments", { value: candidate.prepareArguments.bind(candidate) });
17
+ }
18
+ if (candidate.resourceClaims) {
19
+ Object.defineProperty(tool, "resourceClaims", { value: candidate.resourceClaims.bind(candidate) });
20
+ }
21
+ return Object.freeze(tool);
22
+ }
23
+ export function resolveToolPolicy(name, options) {
24
+ return (findRegisteredToolClaimDefinition(name, options.registeredTools)?.executionMode ?? options.toolPolicies?.get(name));
25
+ }
26
+ export function isBuiltinPathClaimTool(name) {
27
+ return PATH_SCOPED_TOOLS.has(name) || SEARCH_PATH_TOOLS.has(name);
28
+ }
29
+ function normalizeLeadingSlashes(rawPath) {
30
+ const normalized = normalizePathSlashes(rawPath);
31
+ return /^\/{3,}/.test(normalized) ? normalized.replace(/^\/+/, "/") : normalized;
32
+ }
33
+ function resolveCanonicalPathKey(rawPath, cwd) {
34
+ if (typeof rawPath !== "string" || rawPath.trim().length === 0 || typeof cwd !== "string")
35
+ return null;
36
+ const normalized = normalizeLeadingSlashes(rawPath);
37
+ const canonicalCwd = canonicalizeLexicalPath(cwd);
38
+ if (normalized.startsWith("//") ||
39
+ /^[A-Za-z]:(?!\/)/.test(normalized) ||
40
+ canonicalCwd === null ||
41
+ !(canonicalCwd.startsWith("/") || /^[A-Za-z]:\//.test(canonicalCwd))) {
42
+ return null;
43
+ }
44
+ let resolved;
45
+ if (/^[A-Za-z]:\//.test(normalized)) {
46
+ resolved = normalized;
47
+ }
48
+ else if (normalized.startsWith("/")) {
49
+ const cwdDrive = /^([A-Za-z]:)\//.exec(canonicalCwd);
50
+ resolved = cwdDrive ? `${cwdDrive[1]}${normalized}` : normalized;
51
+ }
52
+ else {
53
+ resolved = joinPathSegments(canonicalCwd, normalized);
54
+ }
55
+ const canonical = canonicalizeLexicalPath(resolved);
56
+ return canonical !== null && (canonical.startsWith("/") || /^[A-Za-z]:\//.test(canonical)) ? canonical : null;
57
+ }
58
+ function builtinRawPath(toolName, args, cwd) {
59
+ if (PATH_SCOPED_TOOLS.has(toolName))
60
+ return args.path;
61
+ if (!SEARCH_PATH_TOOLS.has(toolName))
62
+ return undefined;
63
+ return typeof args.path === "string" && args.path.trim().length > 0 ? args.path : cwd;
64
+ }
65
+ function builtinPathAccess(toolName) {
66
+ return toolName === "read" || SEARCH_PATH_TOOLS.has(toolName) ? "read" : "write";
67
+ }
68
+ export function resolvePathClaimKey(toolName, args, cwd) {
69
+ return isBuiltinPathClaimTool(toolName) ? resolveCanonicalPathKey(builtinRawPath(toolName, args, cwd), cwd) : null;
70
+ }
71
+ function canonicalizeResolvedPathKey(rawPath) {
72
+ if (typeof rawPath !== "string" || rawPath.trim().length === 0)
73
+ return null;
74
+ const normalized = normalizeLeadingSlashes(rawPath);
75
+ if (normalized.startsWith("//")) {
76
+ const match = /^\/\/+([^/]+)\/+([^/]+)(?:\/+(.*))?$/.exec(normalized);
77
+ if (!match)
78
+ return null;
79
+ const suffix = match[3] ?? "";
80
+ const canonicalSuffix = suffix.length === 0 ? "" : canonicalizeLexicalPath(suffix);
81
+ if (canonicalSuffix === null)
82
+ return null;
83
+ const root = `//${match[1].toLowerCase()}/${match[2].toLowerCase()}`;
84
+ return canonicalSuffix.length === 0 ? root : `${root}/${canonicalSuffix}`;
85
+ }
86
+ const canonical = canonicalizeLexicalPath(normalized);
87
+ if (canonical === null)
88
+ return null;
89
+ const drive = /^([A-Za-z]:)\/(.*)$/.exec(canonical);
90
+ if (drive)
91
+ return `${drive[1].toLowerCase()}/${drive[2]}`;
92
+ return canonical.startsWith("/") ? canonical : null;
93
+ }
94
+ function normalizeResolvedResourceKeys(value) {
95
+ if (!isPlainArguments(value))
96
+ return null;
97
+ const lexicalKey = canonicalizeResolvedPathKey(value.lexicalKey);
98
+ if (lexicalKey === null)
99
+ return null;
100
+ const realKey = value.realKey === undefined ? undefined : canonicalizeResolvedPathKey(value.realKey);
101
+ if (realKey === null || (value.inodeKey !== undefined && (typeof value.inodeKey !== "string" || !value.inodeKey))) {
102
+ return null;
103
+ }
104
+ const inodeKey = value.inodeKey;
105
+ if ((lexicalKey.startsWith("//") || /^[a-z]:\//.test(lexicalKey)) &&
106
+ realKey === undefined &&
107
+ inodeKey === undefined) {
108
+ return null;
109
+ }
110
+ return {
111
+ lexicalKey,
112
+ ...(realKey === undefined ? {} : { realKey }),
113
+ ...(inodeKey === undefined ? {} : { inodeKey }),
114
+ };
115
+ }
116
+ export async function resolvePathClaimWithIdentity(rawPath, access, options) {
117
+ if (typeof rawPath !== "string" || rawPath.trim().length === 0)
118
+ return { kind: "exclusive" };
119
+ const resolver = options.resourceKeyResolver;
120
+ if (!resolver) {
121
+ const key = resolveCanonicalPathKey(rawPath, options.cwd);
122
+ return key === null ? { kind: "exclusive" } : { kind: "claims", claims: [{ kind: "path", key, access }] };
123
+ }
124
+ try {
125
+ const keys = normalizeResolvedResourceKeys(await resolver.resolvePath(rawPath, options.cwd));
126
+ if (keys === null)
127
+ return { kind: "exclusive" };
128
+ return {
129
+ kind: "claims",
130
+ claims: [
131
+ {
132
+ kind: "path",
133
+ key: keys.lexicalKey,
134
+ access,
135
+ ...(keys.realKey === undefined ? {} : { realKey: keys.realKey }),
136
+ ...(keys.inodeKey === undefined ? {} : { inodeKey: keys.inodeKey }),
137
+ },
138
+ ],
139
+ };
140
+ }
141
+ catch {
142
+ return { kind: "exclusive" };
143
+ }
144
+ }
145
+ export function resolveBuiltinPathClaimWithIdentity(toolCall, options) {
146
+ if (!isPlainArguments(toolCall.arguments))
147
+ return Promise.resolve({ kind: "exclusive" });
148
+ return resolvePathClaimWithIdentity(builtinRawPath(toolCall.name, toolCall.arguments, options.cwd), builtinPathAccess(toolCall.name), options);
149
+ }
150
+ export function resolveToolClaims(toolCall, options) {
151
+ if (!isPlainArguments(toolCall.arguments))
152
+ return { kind: "exclusive" };
153
+ const name = toolCall.name;
154
+ if (NEVER_PARALLEL_TOOLS.has(name) || name === "bash" || resolveToolPolicy(name, options) === "sequential") {
155
+ return { kind: "exclusive" };
156
+ }
157
+ if (isBuiltinPathClaimTool(name)) {
158
+ const key = resolvePathClaimKey(name, toolCall.arguments, options.cwd);
159
+ return key === null
160
+ ? { kind: "exclusive" }
161
+ : { kind: "claims", claims: [{ access: builtinPathAccess(name), kind: "path", key }] };
162
+ }
163
+ if (PARALLEL_SAFE_TOOLS.has(name))
164
+ return { kind: "claims", claims: [] };
165
+ if (resolveToolPolicy(name, options) === "parallel") {
166
+ return options.strictExtensionClaims ? { kind: "exclusive" } : { kind: "claims", claims: [] };
167
+ }
168
+ return { kind: "exclusive" };
169
+ }
170
+ function pathClaimKeys(claim) {
171
+ return claim.realKey === undefined || claim.realKey === claim.key ? [claim.key] : [claim.key, claim.realKey];
172
+ }
173
+ function uncSegments(key) {
174
+ return key.startsWith("//")
175
+ ? key
176
+ .slice(2)
177
+ .split("/")
178
+ .filter((segment) => segment.length > 0)
179
+ .map((segment) => segment.toLowerCase())
180
+ : null;
181
+ }
182
+ function identityPathKeysOverlap(left, right) {
183
+ const leftUnc = uncSegments(left);
184
+ const rightUnc = uncSegments(right);
185
+ if (leftUnc === null || rightUnc === null) {
186
+ return leftUnc === null && rightUnc === null && pathSegmentsOverlap(left, right);
187
+ }
188
+ const commonLength = Math.min(leftUnc.length, rightUnc.length);
189
+ for (let index = 0; index < commonLength; index++) {
190
+ if (leftUnc[index] !== rightUnc[index])
191
+ return false;
192
+ }
193
+ return true;
194
+ }
195
+ export function pathClaimsOverlap(left, right) {
196
+ if (left.inodeKey !== undefined && left.inodeKey === right.inodeKey)
197
+ return true;
198
+ return pathClaimKeys(left).some((leftKey) => pathClaimKeys(right).some((rightKey) => identityPathKeysOverlap(leftKey, rightKey)));
199
+ }
200
+ //# sourceMappingURL=builtin-tool-resource-claims.js.map