@openrouter/agent 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +483 -5
  2. package/esm/index.d.ts +19 -4
  3. package/esm/index.d.ts.map +1 -1
  4. package/esm/index.js +9 -2
  5. package/esm/index.js.map +1 -1
  6. package/esm/inner-loop/call-model.d.ts.map +1 -1
  7. package/esm/inner-loop/call-model.js +40 -41
  8. package/esm/inner-loop/call-model.js.map +1 -1
  9. package/esm/inner-loop/resume-tool-results.d.ts +128 -0
  10. package/esm/inner-loop/resume-tool-results.d.ts.map +1 -0
  11. package/esm/inner-loop/resume-tool-results.js +244 -0
  12. package/esm/inner-loop/resume-tool-results.js.map +1 -0
  13. package/esm/lib/agent-tool.d.ts +92 -0
  14. package/esm/lib/agent-tool.d.ts.map +1 -0
  15. package/esm/lib/agent-tool.js +211 -0
  16. package/esm/lib/agent-tool.js.map +1 -0
  17. package/esm/lib/async-params.d.ts +82 -0
  18. package/esm/lib/async-params.d.ts.map +1 -1
  19. package/esm/lib/async-params.js +5 -0
  20. package/esm/lib/async-params.js.map +1 -1
  21. package/esm/lib/async-tool-registry.d.ts +134 -0
  22. package/esm/lib/async-tool-registry.d.ts.map +1 -0
  23. package/esm/lib/async-tool-registry.js +352 -0
  24. package/esm/lib/async-tool-registry.js.map +1 -0
  25. package/esm/lib/async-tools.d.ts +23 -0
  26. package/esm/lib/async-tools.d.ts.map +1 -0
  27. package/esm/lib/async-tools.js +19 -0
  28. package/esm/lib/async-tools.js.map +1 -0
  29. package/esm/lib/conversation-state.d.ts +1 -0
  30. package/esm/lib/conversation-state.d.ts.map +1 -1
  31. package/esm/lib/conversation-state.js +8 -0
  32. package/esm/lib/conversation-state.js.map +1 -1
  33. package/esm/lib/doom-loop.d.ts +533 -0
  34. package/esm/lib/doom-loop.d.ts.map +1 -0
  35. package/esm/lib/doom-loop.js +1221 -0
  36. package/esm/lib/doom-loop.js.map +1 -0
  37. package/esm/lib/hooks-schemas.d.ts +33 -0
  38. package/esm/lib/hooks-schemas.d.ts.map +1 -1
  39. package/esm/lib/hooks-schemas.js +54 -0
  40. package/esm/lib/hooks-schemas.js.map +1 -1
  41. package/esm/lib/hooks-types.d.ts +6 -2
  42. package/esm/lib/hooks-types.d.ts.map +1 -1
  43. package/esm/lib/hooks-types.js.map +1 -1
  44. package/esm/lib/model-result.d.ts +646 -10
  45. package/esm/lib/model-result.d.ts.map +1 -1
  46. package/esm/lib/model-result.js +2749 -153
  47. package/esm/lib/model-result.js.map +1 -1
  48. package/esm/lib/reusable-stream.d.ts +9 -0
  49. package/esm/lib/reusable-stream.d.ts.map +1 -1
  50. package/esm/lib/reusable-stream.js +17 -0
  51. package/esm/lib/reusable-stream.js.map +1 -1
  52. package/esm/lib/stream-transformers.d.ts +20 -0
  53. package/esm/lib/stream-transformers.d.ts.map +1 -1
  54. package/esm/lib/stream-transformers.js +45 -0
  55. package/esm/lib/stream-transformers.js.map +1 -1
  56. package/esm/lib/tool-check.d.ts +76 -0
  57. package/esm/lib/tool-check.d.ts.map +1 -0
  58. package/esm/lib/tool-check.js +241 -0
  59. package/esm/lib/tool-check.js.map +1 -0
  60. package/esm/lib/tool-concurrency.d.ts +42 -0
  61. package/esm/lib/tool-concurrency.d.ts.map +1 -0
  62. package/esm/lib/tool-concurrency.js +80 -0
  63. package/esm/lib/tool-concurrency.js.map +1 -0
  64. package/esm/lib/tool-context.d.ts +45 -1
  65. package/esm/lib/tool-context.d.ts.map +1 -1
  66. package/esm/lib/tool-context.js +60 -1
  67. package/esm/lib/tool-context.js.map +1 -1
  68. package/esm/lib/tool-executor.d.ts +52 -9
  69. package/esm/lib/tool-executor.d.ts.map +1 -1
  70. package/esm/lib/tool-executor.js +253 -21
  71. package/esm/lib/tool-executor.js.map +1 -1
  72. package/esm/lib/tool-orchestrator.d.ts.map +1 -1
  73. package/esm/lib/tool-orchestrator.js +87 -50
  74. package/esm/lib/tool-orchestrator.js.map +1 -1
  75. package/esm/lib/tool-task.d.ts +157 -0
  76. package/esm/lib/tool-task.d.ts.map +1 -0
  77. package/esm/lib/tool-task.js +206 -0
  78. package/esm/lib/tool-task.js.map +1 -0
  79. package/esm/lib/tool-types.d.ts +473 -14
  80. package/esm/lib/tool-types.d.ts.map +1 -1
  81. package/esm/lib/tool-types.js +59 -10
  82. package/esm/lib/tool-types.js.map +1 -1
  83. package/esm/lib/tool.d.ts +184 -2
  84. package/esm/lib/tool.d.ts.map +1 -1
  85. package/esm/lib/tool.js +193 -3
  86. package/esm/lib/tool.js.map +1 -1
  87. package/package.json +30 -2
@@ -0,0 +1,92 @@
1
+ import type { $ZodObject, $ZodShape, $ZodType, infer as zodInfer } from 'zod/v4/core';
2
+ import type { CallModelInput } from './async-params.js';
3
+ import type { ModelResult } from './model-result.js';
4
+ import type { TaskTranscriptSource } from './tool-task.js';
5
+ import type { AsyncToolAck, ContextFromSchema, ConversationState, NextTurnParamsFunctions, Tool, ToolApprovalCheck, ToolCheckConfig, ToolExecuteContext, ToolLoopKey, UnifiedTool } from './tool-types.js';
6
+ /**
7
+ * The child run spec an agent tool produces per call.
8
+ *
9
+ * Exclusions and why:
10
+ * - `state`: the engine supplies an internal in-memory accessor (it is what
11
+ * makes the live transcript possible). A child persisting to the parent's
12
+ * accessor would clobber the parent conversation; durable child sessions
13
+ * are a separate feature.
14
+ * - `signal`: the engine supplies it (parent abort / timeout / cancelTask
15
+ * propagate into the child).
16
+ * - `approveToolCalls`/`rejectToolCalls`: approval decisions belong to a
17
+ * durable session.
18
+ *
19
+ * `hooks` IS allowed — a child may declare its own hooks explicitly. The
20
+ * parent's hooks are never inherited (they are written against the parent's
21
+ * tool vocabulary and their session accounting would double-fire per child).
22
+ */
23
+ export type AgentRunSpec<TChildTools extends readonly Tool[] = readonly Tool[]> = Omit<CallModelInput<TChildTools>, 'state' | 'approveToolCalls' | 'rejectToolCalls' | 'signal'>;
24
+ /**
25
+ * Live transcript over an agent child's conversation, rendered from the
26
+ * child's (internal, in-memory) conversation state — the actual message
27
+ * history, robust regardless of streaming vs non-streaming transport.
28
+ */
29
+ export declare class AgentTranscriptSource implements TaskTranscriptSource {
30
+ private readonly readState;
31
+ private turnsStarted;
32
+ private turnsEnded;
33
+ private currentActivity;
34
+ constructor(readState: () => ConversationState | null);
35
+ noteTurnStart(): void;
36
+ noteTurnEnd(lastText: string): void;
37
+ setActivity(activity: string): void;
38
+ statusExtras(): Record<string, unknown>;
39
+ render(maxChars: number): string;
40
+ }
41
+ /** Configuration for `tool.agent()`. */
42
+ export type AgentToolConfig<TInput extends $ZodObject<$ZodShape>, TOutput extends $ZodType, TChildTools extends readonly Tool[] = readonly Tool[], TCtx extends $ZodObject<$ZodShape> = $ZodObject<$ZodShape>, TName extends string = string> = {
43
+ name: TName;
44
+ description?: string;
45
+ inputSchema: TInput;
46
+ /**
47
+ * Whether providers should enforce strict schema adherence for this agent
48
+ * tool's generated arguments. OpenAI-style strict mode requires every
49
+ * property to be required; those providers may reject `.optional()` fields,
50
+ * so use `.nullable()` when the key may conceptually have no value.
51
+ */
52
+ strict?: boolean | null;
53
+ /**
54
+ * Required. The mapped child result is validated against it — the same
55
+ * rule every long-running tool obeys (results settle after the round).
56
+ */
57
+ outputSchema: TOutput;
58
+ /** Build the child run spec from this call's arguments. */
59
+ agent: (params: zodInfer<TInput>, context?: ToolExecuteContext<TName, ContextFromSchema<TCtx>>) => AgentRunSpec<TChildTools> | Promise<AgentRunSpec<TChildTools>>;
60
+ /**
61
+ * Map the finished child run to this tool's output. Default:
62
+ * `{ text: await child.getText() }` — so the natural outputSchema is
63
+ * `z.object({ text: z.string() })`.
64
+ */
65
+ result?: (child: ModelResult<TChildTools>) => Promise<zodInfer<TOutput>> | zodInfer<TOutput>;
66
+ /** Hold the round this long before placeholdering. Default 250ms. */
67
+ graceMs?: number;
68
+ /** Deadline for the whole child run, in ms. */
69
+ timeoutMs?: number;
70
+ /** Max simultaneous child runs of this tool. */
71
+ maxConcurrency?: number;
72
+ /** Model-facing acknowledgement merged into the pending placeholder. */
73
+ ack?: AsyncToolAck<zodInfer<TInput>>;
74
+ /** Check-in config (the SDK default reports turns + activity). */
75
+ check?: ToolCheckConfig;
76
+ contextSchema?: TCtx;
77
+ nextTurnParams?: NextTurnParamsFunctions<zodInfer<TInput>>;
78
+ requireApproval?: boolean | ToolApprovalCheck<zodInfer<TInput>>;
79
+ loopKey?: ToolLoopKey<zodInfer<TInput>>;
80
+ };
81
+ /**
82
+ * Create an agent tool: a long-running tool whose work IS a child
83
+ * `callModel` conversation. The child runs as a background task — the
84
+ * parent loop keeps going, its per-turn activity feeds the task log (one
85
+ * entry per child turn), its conversation is the check-in transcript, and
86
+ * its final answer (via the `result` mapper) is delivered like any
87
+ * background result. Steering messages (`sendToTask`, or a check call's
88
+ * `task.send`) are injected into the child as user messages at its next
89
+ * turn boundary. `cancelTask` / parent abort cancel the child run.
90
+ */
91
+ export declare function agentToolBuilder<TInput extends $ZodObject<$ZodShape>, TOutput extends $ZodType, TChildTools extends readonly Tool[] = readonly Tool[], TCtx extends $ZodObject<$ZodShape> = $ZodObject<$ZodShape>, TName extends string = string>(config: AgentToolConfig<TInput, TOutput, TChildTools, TCtx, TName>): UnifiedTool<TInput, TOutput, $ZodType<unknown>, Record<string, unknown>, TCtx>;
92
+ //# sourceMappingURL=agent-tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-tool.d.ts","sourceRoot":"","sources":["../../src/lib/agent-tool.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,KAAK,IAAI,QAAQ,EAAE,MAAM,aAAa,CAAC;AACtF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OA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IAAI,EAAE,GAAG,SAAS,IAAI,EAAE,EACrD,IAAI,SAAS,UAAU,CAAC,SAAS,CAAC,GAAG,UAAU,CAAC,SAAS,CAAC,EAC1D,KAAK,SAAS,MAAM,GAAG,MAAM,EAE7B,MAAM,EAAE,eAAe,CAAC,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,CAAC,GACjE,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,CA8JhF"}
@@ -0,0 +1,211 @@
1
+ import { extractTextFromResponse } from './conversation-state.js';
2
+ import { TASK_TOOL_NAME } from './tool-check.js';
3
+ import { truncateTranscriptTail } from './tool-task.js';
4
+ import { SHARED_CONTEXT_KEY, ToolType } from './tool-types.js';
5
+ const TEXT_PREVIEW_CHARS = 200;
6
+ const ARGS_PREVIEW_CHARS = 80;
7
+ function preview(value, maxChars) {
8
+ const text = typeof value === 'string' ? value : (JSON.stringify(value) ?? String(value));
9
+ return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
10
+ }
11
+ /**
12
+ * Live transcript over an agent child's conversation, rendered from the
13
+ * child's (internal, in-memory) conversation state — the actual message
14
+ * history, robust regardless of streaming vs non-streaming transport.
15
+ */
16
+ export class AgentTranscriptSource {
17
+ constructor(readState) {
18
+ this.readState = readState;
19
+ this.turnsStarted = 0;
20
+ this.turnsEnded = 0;
21
+ this.currentActivity = 'starting';
22
+ }
23
+ noteTurnStart() {
24
+ this.turnsStarted++;
25
+ this.currentActivity = `turn ${this.turnsStarted} in progress`;
26
+ }
27
+ noteTurnEnd(lastText) {
28
+ this.turnsEnded++;
29
+ this.currentActivity = lastText ? `responded: ${preview(lastText, 80)}` : 'thinking';
30
+ }
31
+ setActivity(activity) {
32
+ this.currentActivity = activity;
33
+ }
34
+ statusExtras() {
35
+ return {
36
+ // Ended turns only — an in-flight turn shows up in turnsStarted and
37
+ // currentActivity, but is not counted as completed.
38
+ turnsCompleted: this.turnsEnded,
39
+ turnsStarted: this.turnsStarted,
40
+ currentActivity: this.currentActivity,
41
+ };
42
+ }
43
+ render(maxChars) {
44
+ const state = this.readState();
45
+ if (!state || !Array.isArray(state.messages)) {
46
+ return '';
47
+ }
48
+ const lines = [];
49
+ for (const item of state.messages) {
50
+ const type = item['type'];
51
+ const role = item['role'];
52
+ if (role === 'user' && typeof item['content'] === 'string') {
53
+ lines.push(`user: ${preview(item['content'], TEXT_PREVIEW_CHARS)}`);
54
+ }
55
+ else if (type === 'message' && role === 'assistant') {
56
+ const content = item['content'];
57
+ const text = Array.isArray(content)
58
+ ? content
59
+ .map((c) => c.text ?? '')
60
+ .join('')
61
+ .trim()
62
+ : '';
63
+ if (text) {
64
+ lines.push(`assistant: ${preview(text, TEXT_PREVIEW_CHARS)}`);
65
+ }
66
+ }
67
+ else if (type === 'function_call') {
68
+ lines.push(`→ ${String(item['name'])}(${preview(item['arguments'], ARGS_PREVIEW_CHARS)})`);
69
+ }
70
+ else if (type === 'function_call_output') {
71
+ lines.push(` ⇒ ${preview(item['output'], ARGS_PREVIEW_CHARS)}`);
72
+ }
73
+ }
74
+ const full = lines.join('\n');
75
+ return truncateTranscriptTail(full, maxChars);
76
+ }
77
+ }
78
+ /** Paused child statuses that an in-memory agent child cannot recover from. */
79
+ const CHILD_PAUSE_STATUSES = new Set([
80
+ 'awaiting_approval',
81
+ 'awaiting_hitl',
82
+ 'awaiting_client_tools',
83
+ 'awaiting_async_tools',
84
+ ]);
85
+ /**
86
+ * Create an agent tool: a long-running tool whose work IS a child
87
+ * `callModel` conversation. The child runs as a background task — the
88
+ * parent loop keeps going, its per-turn activity feeds the task log (one
89
+ * entry per child turn), its conversation is the check-in transcript, and
90
+ * its final answer (via the `result` mapper) is delivered like any
91
+ * background result. Steering messages (`sendToTask`, or a check call's
92
+ * `task.send`) are injected into the child as user messages at its next
93
+ * turn boundary. `cancelTask` / parent abort cancel the child run.
94
+ */
95
+ export function agentToolBuilder(config) {
96
+ // Same reserved-name guards as tool() — a subagent named 'shared' would
97
+ // collide with the shared-context store key, one named 'task' would
98
+ // disable the built-in task-interaction tool.
99
+ if (config.name === SHARED_CONTEXT_KEY) {
100
+ throw new Error(`Tool name "${SHARED_CONTEXT_KEY}" is reserved for shared context. Choose a different name.`);
101
+ }
102
+ if (config.name === TASK_TOOL_NAME) {
103
+ throw new Error(`Tool name "${TASK_TOOL_NAME}" is reserved for the built-in task-interaction tool. Choose a different name.`);
104
+ }
105
+ if (config.outputSchema === undefined) {
106
+ throw new Error(`Agent tool "${config.name}" must declare an outputSchema. The child's mapped result is validated when it settles.`);
107
+ }
108
+ const defaultResult = async (child) => ({
109
+ text: await child.getText(),
110
+ });
111
+ const mapResult = config.result ?? defaultResult;
112
+ // The synthesized run: a plain async fn driving the child to completion.
113
+ // Turn activity surfaces through ctx.log (task log + preliminary events);
114
+ // the transcript reads the child's live in-memory conversation state.
115
+ async function run(params, ctx) {
116
+ const client = ctx?.client;
117
+ if (!client) {
118
+ throw new Error(`Agent tool "${config.name}": no client available on the run context. Agent tools must execute inside a callModel run.`);
119
+ }
120
+ const spec = await config.agent(params, ctx);
121
+ // Internal in-memory accessor: the child's message history IS the
122
+ // transcript, and getState() enables the pause-detection below. Never
123
+ // the caller's accessor — a child persisting there would clobber the
124
+ // parent conversation.
125
+ let childState = null;
126
+ const childAccessor = {
127
+ load: async () => childState,
128
+ save: async (state) => {
129
+ childState = state;
130
+ },
131
+ };
132
+ const transcript = new AgentTranscriptSource(() => childState);
133
+ if (ctx?.taskTranscript) {
134
+ ctx.taskTranscript.transcriptSource = transcript;
135
+ }
136
+ // Lazy import: agent-tool → call-model → model-result would otherwise
137
+ // be a static cycle (same pattern as bindDeferredCompletion).
138
+ const { callModel } = await import('../inner-loop/call-model.js');
139
+ const userOnTurnStart = spec.onTurnStart;
140
+ const userOnTurnEnd = spec.onTurnEnd;
141
+ const child = callModel(client, {
142
+ ...spec,
143
+ state: childAccessor,
144
+ ...(ctx?.signal !== undefined && {
145
+ signal: ctx.signal,
146
+ }),
147
+ onTurnStart: async (turnContext) => {
148
+ transcript.noteTurnStart();
149
+ await userOnTurnStart?.(turnContext);
150
+ },
151
+ onTurnEnd: async (turnContext, response) => {
152
+ const text = extractTextFromResponse(response);
153
+ transcript.noteTurnEnd(text);
154
+ // One log entry per child turn — feeds tailLogs and preliminary
155
+ // results on the parent stream.
156
+ ctx?.log?.({
157
+ turn: turnContext.numberOfTurns,
158
+ textPreview: preview(text.trim(), TEXT_PREVIEW_CHARS),
159
+ });
160
+ await userOnTurnEnd?.(turnContext, response);
161
+ },
162
+ });
163
+ // Steering: forward inbound task messages into the child conversation
164
+ // as user messages at its next safe turn boundary.
165
+ ctx?.onMessage?.((message) => {
166
+ child.queueUserMessage(typeof message === 'string' ? message : JSON.stringify(message));
167
+ });
168
+ // Drive the child to completion.
169
+ await child.getResponse();
170
+ transcript.setActivity('finished');
171
+ // In-memory children cannot pause durably: a paused child means a tool
172
+ // inside it awaits input that will never arrive. Fail loudly instead of
173
+ // silently returning a partial answer.
174
+ const finalStatus = childState !== null ? childState.status : undefined;
175
+ if (finalStatus !== undefined && CHILD_PAUSE_STATUSES.has(finalStatus)) {
176
+ throw new Error(`Agent tool "${config.name}": the child run paused with status '${finalStatus}'. Agent children run in-memory and cannot pause — avoid HITL/manual/deferred/approval tools inside agents (use lifecycle: 'deferred' on the parent tool instead).`);
177
+ }
178
+ return await mapResult(child);
179
+ }
180
+ const fn = {
181
+ lifecycle: 'background',
182
+ kind: 'agent',
183
+ name: config.name,
184
+ inputSchema: config.inputSchema,
185
+ outputSchema: config.outputSchema,
186
+ run,
187
+ };
188
+ const optionalFields = [
189
+ 'description',
190
+ 'strict',
191
+ 'contextSchema',
192
+ 'nextTurnParams',
193
+ 'requireApproval',
194
+ 'loopKey',
195
+ 'timeoutMs',
196
+ 'maxConcurrency',
197
+ 'ack',
198
+ 'graceMs',
199
+ 'check',
200
+ ];
201
+ for (const field of optionalFields) {
202
+ if (config[field] !== undefined) {
203
+ fn[field] = config[field];
204
+ }
205
+ }
206
+ return {
207
+ type: ToolType.Function,
208
+ function: fn,
209
+ };
210
+ }
211
+ //# sourceMappingURL=agent-tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-tool.js","sourceRoot":"","sources":["../../src/lib/agent-tool.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAcxD,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAwB/D,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAE9B,SAAS,OAAO,CAAC,KAAc,EAAE,QAAgB;IAC/C,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC1F,OAAO,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AACvE,CAAC;AAED;;;;GAIG;AACH,MAAM,OAAO,qBAAqB;IAKhC,YAA6B,SAAyC;QAAzC,cAAS,GAAT,SAAS,CAAgC;QAJ9D,iBAAY,GAAG,CAAC,CAAC;QACjB,eAAU,GAAG,CAAC,CAAC;QACf,oBAAe,GAAG,UAAU,CAAC;IAEoC,CAAC;IAE1E,aAAa;QACX,IAAI,CAAC,YAAY,EAAE,CAAC;QACpB,IAAI,CAAC,eAAe,GAAG,QAAQ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KAAK,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,EAAE,QAAQ,CAAC,QAAQ;QACvB,QAAQ,EAAE,EAMG;KACd,CAAC;AACJ,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import type * as models from '@openrouter/sdk/models';
2
2
  import type { OpenResponsesResult } from '@openrouter/sdk/models';
3
+ import type { DoomLoopOption } from './doom-loop.js';
3
4
  import type { HooksManager } from './hooks-manager.js';
4
5
  import type { InlineHookConfig } from './hooks-types.js';
5
6
  import type { Item } from './item-types.js';
@@ -71,6 +72,87 @@ type BaseCallModelInput<TTools extends readonly Tool[] = readonly Tool[], TShare
71
72
  strictFinalResponse?: boolean;
72
73
  /** Hook system for lifecycle events. Accepts inline config or a HooksManager instance. */
73
74
  hooks?: InlineHookConfig | HooksManager;
75
+ /**
76
+ * Doom-loop detection: catch runs that repeat the same tool call with
77
+ * identical arguments (including repeated empty or unparseable calls) or
78
+ * emit the same text over and over, and respond with a graduated ladder
79
+ * (observe → steer → block → stop; defaults observe@2, block@3, stop@6
80
+ * consecutive repetitions). `true` enables recommended defaults; an
81
+ * object tunes thresholds and text detection. Off by default.
82
+ *
83
+ * Tools declare precise call identity via `loopKey`: a computed function
84
+ * (return the search query, `({ command, cwd }) => ({ command, cwd })`,
85
+ * ...), a field-name array (`['command', 'cwd']` — serializable, used by
86
+ * MCP tool caches), or `false` to exempt a tool (legitimate polling);
87
+ * without one the full arguments object is the identity. Detection is
88
+ * deterministic: the same transcript always produces the same verdicts.
89
+ */
90
+ doomLoop?: DoomLoopOption;
91
+ /**
92
+ * Cancel the whole run. Aborting stops the tool-execution loop at the
93
+ * next turn boundary AND aborts the in-flight API request/stream, so a
94
+ * stalled provider fails fast instead of hanging until an outer test or
95
+ * caller timeout kills the process. The run's promises reject with the
96
+ * signal's abort reason.
97
+ *
98
+ * Composes with per-request `RequestOptions.timeoutMs` (the third
99
+ * `callModel` argument): when both are set, each request is bounded by
100
+ * whichever fires first. (Passing a raw `signal` through `RequestOptions`
101
+ * instead would silently disable the SDK's `timeoutMs` wiring.)
102
+ *
103
+ * Aborting also fires every in-flight tool's `ctx.signal` and aborts
104
+ * background tasks, so cooperative tool bodies stop working.
105
+ */
106
+ signal?: AbortSignal;
107
+ /**
108
+ * Default per-tool execution deadline in milliseconds; a tool-level
109
+ * `timeoutMs` overrides it. When the deadline elapses the round stops
110
+ * waiting — the model receives `{ error, code: 'tool_timeout' }`
111
+ * immediately and the tool's `ctx.signal` aborts. Bounds the round's
112
+ * WAIT, not the tool body: a body that ignores its signal keeps running
113
+ * detached and its result is discarded.
114
+ */
115
+ toolTimeoutMs?: number;
116
+ /**
117
+ * Concurrency limits for tool execution. A bare number is shorthand for
118
+ * `{ round: n }`.
119
+ * - `round`: max simultaneous tool executions within one tool round.
120
+ * Unbounded by default (matching previous behavior).
121
+ * - `background`: max simultaneous detached background-tool executions
122
+ * (`tool.background` work that outlived its grace window). Default 16.
123
+ * When full, work queues FIFO; queue wait counts against `timeoutMs`.
124
+ * Execution order may change under a cap; OUTPUT order never does
125
+ * (results stay in call order for prompt-cache stability).
126
+ */
127
+ toolConcurrency?: number | {
128
+ round?: number;
129
+ background?: number;
130
+ };
131
+ /**
132
+ * Behavior for async tools (`tool.background` / `tool.deferred`).
133
+ *
134
+ * `onRunEnd` decides what happens when the run would finish while
135
+ * background tasks are still in flight:
136
+ * - `'drain'` (default): wait up to `drainTimeoutMs` (default 30s),
137
+ * inject settled results, and grant up to `maxDrainTurns` (default 2)
138
+ * extra no-tool turns so the final answer incorporates them;
139
+ * - `'detach'`: return immediately — tasks keep running, results are
140
+ * dropped (persisted as `orphaned` when a StateAccessor exists);
141
+ * - `'cancel'`: abort in-flight tasks and finish.
142
+ */
143
+ asyncTools?: {
144
+ onRunEnd?: 'drain' | 'detach' | 'cancel';
145
+ drainTimeoutMs?: number;
146
+ maxDrainTurns?: number;
147
+ /**
148
+ * Whether the single universal `task` tool is registered so the model
149
+ * can check/steer/result/cancel running tasks by taskId. Default true
150
+ * when any long-running tool is present.
151
+ */
152
+ checkins?: boolean;
153
+ /** Max characters for the `transcript` check view. Default 20_000. */
154
+ maxTranscriptChars?: number;
155
+ };
74
156
  };
75
157
  /**
76
158
  * Approval params when state is provided (allows approve/reject)
@@ -1 +1 @@
1
- {"version":3,"file":"async-params.d.ts","sourceRoot":"","sources":["../../src/lib/async-params.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,QAAQ,EACR,IAAI,EACJ,wBAAwB,EACxB,WAAW,EACZ,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AA6B5C;;GAEG;AACH,MAAM,MAAM,oBAAoB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,WAAW,KAAK,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;AAErF;;GAEG;AACH,KAAK,kBAAkB,CACrB,MAAM,SAAS,SAAS,IAAI,EAAE,GAAG,SAAS,IAAI,EAAE,EAChD,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAC7D;KACD,CAAC,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,QAAQ,GAAG,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,EAAE,o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,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAC7D,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAAC;AAE1E;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG;IACvF,KAAK,CAAC,EAAE,KAAK,CAAC;CACf,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,qBAAqB,CAAC,MAAM,SAAS,SAAS,IAAI,EAAE,GAAG,SAAS,IAAI,EAAE,EAC1F,KAAK,EAAE,cAAc,CAAC,MAAM,CAAC,EAC7B,OAAO,EAAE,WAAW,GACnB,OAAO,CAAC,sBAAsB,CAAC,CAgEjC;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAKzD"}
@@ -50,6 +50,11 @@ export async function resolveAsyncFunctions(input, context) {
50
50
  'allowFinalResponse', // Client-side: tunes the default toolChoice:'none' final turn when stopWhen breaks the loop
51
51
  'strictFinalResponse', // Client-side: restore throw on empty final after tool rounds
52
52
  'hooks', // Client-side hook system
53
+ 'doomLoop', // Client-side doom-loop detection config
54
+ 'signal', // Client-side run cancellation
55
+ 'toolTimeoutMs', // Client-side per-tool deadline default
56
+ 'toolConcurrency', // Client-side tool concurrency limits
57
+ 'asyncTools', // Client-side async tool (background/deferred) behavior
53
58
  ]);
54
59
  // Iterate over all keys in the input
55
60
  for (const [key, value] of Object.entries(input)) {
@@ -1 +1 @@
1
- {"version":3,"file":"async-params.js","sourceRoot":"","sources":["../../src/lib/async-params.ts"],"names":[],"mappings":"AAkBA;;;GAGG;AACH,SAAS,mBAAmB,CAC1B,KAAc;IAEd,OAAO,OAAO,KAAK,KAAK,UAAU,CAAC;AACrC,CAAC;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5B,eAAe,CAAC,IAAI,CAAC;gBACnB,GAAG;gBACH,KAAK;aACG,CAAC,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,oBAAoB,CAAC,eAAe,CAAC,CAAC;AAC/C,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC9C,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC;AAC3E,CAAC"}
@@ -0,0 +1,134 @@
1
+ import type { TaskLogEntry } from './tool-task.js';
2
+ import { ToolTask } from './tool-task.js';
3
+ import type { PendingAsyncTool } from './tool-types.js';
4
+ /**
5
+ * Outcome of a settled async tool task, harvested by the engine at turn
6
+ * boundaries (`flushAsyncToolDeliveries`) or during end-of-run drain.
7
+ */
8
+ export interface SettledToolTask {
9
+ callId: string;
10
+ taskId: string;
11
+ name: string;
12
+ status: 'completed' | 'failed' | 'cancelled' | 'timed_out';
13
+ /** Present when status is 'completed'. */
14
+ result?: unknown;
15
+ /** Present otherwise. */
16
+ error?: string;
17
+ /** The call's arguments, when tracked — feeds PostToolUse at settle. */
18
+ input?: Record<string, unknown>;
19
+ /** Wall-clock ms from task start to settlement — feeds PostToolUse. */
20
+ durationMs: number;
21
+ }
22
+ /**
23
+ * Per-run registry of async tool tasks (background, deferred, agent).
24
+ *
25
+ * Owns the in-process half of async tool support:
26
+ * - background/agent tasks: tracks the in-flight work + ToolTask (logs,
27
+ * inbox, transcript source), queues settled outcomes for turn-boundary
28
+ * harvesting, supports drain / cancel / abort-all at run end;
29
+ * - deferred tasks: tracks identity only (the work lives outside the
30
+ * process); the durable copy is mirrored to
31
+ * `ConversationState.pendingAsyncTools` by the engine.
32
+ *
33
+ * The registry knows nothing about the tool loop or concurrency pools — the
34
+ * engine (`ModelResult`) owns semaphores and decides when to harvest and how
35
+ * to deliver. Settlement is first-writer-wins: a task settles exactly once
36
+ * (cancel racing completion is safe), and settled tasks drop their
37
+ * controller references so they cannot retain the run graph.
38
+ */
39
+ export declare class AsyncToolRegistry {
40
+ private readonly tasks;
41
+ /** Settled outcomes not yet harvested by the engine. */
42
+ private settledQueue;
43
+ private taskCounter;
44
+ /** Resolvers waiting on "any task settled" (drain support). */
45
+ private settleWaiters;
46
+ /** Generate a task id for background/agent tasks (deferred bring their own). */
47
+ generateTaskId(): string;
48
+ /**
49
+ * Register a task so it is visible to steering / cancel / snapshots.
50
+ * Used for background tasks DURING their grace window — the work is in
51
+ * flight but not yet committed to async delivery. `untrack` removes it
52
+ * again when the work settles in-window (the call behaved
53
+ * synchronously; no async machinery should remain visible).
54
+ */
55
+ register(task: ToolTask): void;
56
+ /**
57
+ * Remove a task registered via `register` whose work settled inside the
58
+ * grace window, along with any settlement queued for it in the meantime
59
+ * (e.g. a cancelTask racing the in-window completion) — the call is
60
+ * yielding a synchronous output, so a later envelope for the same callId
61
+ * would be a double delivery.
62
+ */
63
+ untrack(callId: string): void;
64
+ /**
65
+ * Track an already-started background/agent task. `work` is the tool's
66
+ * in-flight run promise (output-validated). When `timeoutMs` is set the
67
+ * task is raced against it, so a body that ignores its abort signal still
68
+ * settles as `timed_out` instead of hanging the drain. The deadline is
69
+ * anchored at `task.startedAt` (the work started before tracking — a
70
+ * grace window may already have elapsed), so `timeoutMs` bounds the
71
+ * task's TOTAL runtime, matching the documented contract.
72
+ */
73
+ trackBackground(task: ToolTask, work: Promise<unknown>, options?: {
74
+ timeoutMs?: number;
75
+ }): void;
76
+ /** Track a deferred task (identity only; work lives outside the process). */
77
+ trackDeferred(entry: {
78
+ callId: string;
79
+ taskId: string;
80
+ name: string;
81
+ expiresAt?: number;
82
+ pollAfterMs?: number;
83
+ }): ToolTask;
84
+ private settle;
85
+ /** Harvest (and clear) settled outcomes queued since the last call. */
86
+ takeSettled(): SettledToolTask[];
87
+ /** True when any background/agent task is still in flight. */
88
+ hasInFlight(): boolean;
89
+ /** True when any settled outcome awaits harvesting. */
90
+ hasUnharvestedSettled(): boolean;
91
+ /** True when any task (any mode) has been tracked this run. */
92
+ hasTasks(): boolean;
93
+ /** Find the live task for a task id. */
94
+ getTask(taskId: string): ToolTask | undefined;
95
+ /** Find the live task for a call id. */
96
+ findByCallId(callId: string): ToolTask | undefined;
97
+ /** All live tasks. */
98
+ listTasks(): ToolTask[];
99
+ /** Append a log entry to a task by call id (engine log sink). */
100
+ appendLog(callId: string, data: unknown, kind?: TaskLogEntry['kind']): void;
101
+ /** Mark every still-working background/agent task as orphaned (detach mode). */
102
+ markWorkingAsOrphaned(): PendingAsyncTool[];
103
+ /** Snapshot of every tracked task (for `getAsyncTasks()` / persistence). */
104
+ snapshot(): PendingAsyncTool[];
105
+ /**
106
+ * Send a steering message to a working task's run body. Deferred tasks
107
+ * are owned by an external system — steering them is the caller's job.
108
+ * @returns true when a working in-process task received the message.
109
+ */
110
+ sendToTask(taskId: string, message: unknown): boolean;
111
+ /**
112
+ * Cancel one task by task id. Settles it as 'cancelled' immediately
113
+ * (first-writer-wins makes the racing body's own settlement a no-op) and
114
+ * aborts the controller so cooperative bodies stop working.
115
+ *
116
+ * Deferred tasks: cancellation is LOCAL-ONLY — the conversation records
117
+ * the cancel, but the external system is not notified (mirror of the
118
+ * sendToTask contract; tell the external system yourself, or use the
119
+ * tool's `.cancel()` method which persists the terminal status for
120
+ * cross-process callers).
121
+ * @returns true when a working task was found and cancelled.
122
+ */
123
+ cancelTask(taskId: string, reason?: string): boolean;
124
+ /** Abort every in-flight background/agent task (run abort / onRunEnd: 'cancel'). */
125
+ abortAll(reason?: string): void;
126
+ /**
127
+ * Wait until every in-flight task settles or `timeoutMs` elapses,
128
+ * whichever comes first. Returns true when everything settled.
129
+ */
130
+ drain(timeoutMs: number): Promise<boolean>;
131
+ /** Resolve true on the next settle event, or false after `timeoutMs`. */
132
+ private waitForSettle;
133
+ }
134
+ //# sourceMappingURL=async-tool-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async-tool-registry.d.ts","sourceRoot":"","sources":["../../src/lib/async-tool-registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,GAAG,WAAW,CAAC;IAC3D,0CAA0C;IAC1C,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,yBAAyB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wEAAwE;IACxE,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,uEAAuE;IACvE,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA+B;IACrD,wDAAwD;IACxD,OAAO,CAAC,YAAY,CAAyB;IAC7C,OAAO,CAAC,WAAW,CAAK;IACxB,+DAA+D;IAC/D,OAAO,CAAC,aAAa,CAAyB;IAE9C,gFAAgF;IAChF,cAAc,IAAI,MAAM;IAQxB;;;;;;OAMG;IACH,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,IAAI;IAI9B;;;;;;OAMG;IACH,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAK7B;;;;;;;;OAQG;IACH,eAAe,CACb,IAAI,EAAE,QAAQ,EACd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