@saturn-universe/tools 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/container-sandbox.d.ts +168 -0
  3. package/dist/container-sandbox.js +1241 -0
  4. package/dist/counter.d.ts +5 -0
  5. package/dist/counter.js +82 -0
  6. package/dist/data-review.d.ts +4 -0
  7. package/dist/data-review.js +146 -0
  8. package/dist/execution-backend.d.ts +55 -0
  9. package/dist/execution-backend.js +339 -0
  10. package/dist/executor.d.ts +25 -0
  11. package/dist/executor.js +978 -0
  12. package/dist/file-window.d.ts +3 -0
  13. package/dist/file-window.js +12 -0
  14. package/dist/index.d.ts +27 -0
  15. package/dist/index.js +17 -0
  16. package/dist/mcp-headers.d.ts +3 -0
  17. package/dist/mcp-headers.js +51 -0
  18. package/dist/mcp-http.d.ts +3 -0
  19. package/dist/mcp-http.js +253 -0
  20. package/dist/mcp-stdio.d.ts +2 -0
  21. package/dist/mcp-stdio.js +147 -0
  22. package/dist/mcp-wire.d.ts +33 -0
  23. package/dist/mcp-wire.js +85 -0
  24. package/dist/mcp.d.ts +19 -0
  25. package/dist/mcp.js +325 -0
  26. package/dist/path-containment.d.ts +3 -0
  27. package/dist/path-containment.js +11 -0
  28. package/dist/planner.d.ts +3 -0
  29. package/dist/planner.js +162 -0
  30. package/dist/process-manager.d.ts +67 -0
  31. package/dist/process-manager.js +423 -0
  32. package/dist/process-output.d.ts +34 -0
  33. package/dist/process-output.js +162 -0
  34. package/dist/process-worker.d.ts +1 -0
  35. package/dist/process-worker.js +202 -0
  36. package/dist/registry.d.ts +33 -0
  37. package/dist/registry.js +227 -0
  38. package/dist/search.d.ts +9 -0
  39. package/dist/search.js +96 -0
  40. package/dist/team.d.ts +36 -0
  41. package/dist/team.js +284 -0
  42. package/dist/text-patch.d.ts +15 -0
  43. package/dist/text-patch.js +81 -0
  44. package/dist/todo.d.ts +3 -0
  45. package/dist/todo.js +105 -0
  46. package/dist/workspace-discovery.d.ts +42 -0
  47. package/dist/workspace-discovery.js +404 -0
  48. package/dist/workspace-snapshot.d.ts +28 -0
  49. package/dist/workspace-snapshot.js +371 -0
  50. package/dist/workspace.d.ts +22 -0
  51. package/dist/workspace.js +1819 -0
  52. package/package.json +16 -3
  53. package/README.md +0 -3
@@ -0,0 +1,978 @@
1
+ import { canonicalJson, earlierDeadline, isLimited, reportDiagnostic, resolveSubagentWallTimeMs, RuntimeError, tightenToolPermission, validateArtifactRef, validateStartedRun, } from '@saturn-universe/core';
2
+ import { createHash } from 'node:crypto';
3
+ import { z } from 'zod';
4
+ import { outsideWorkspacePrefix, processTimeoutMs } from './workspace.js';
5
+ const artifact = z.unknown().refine((value) => value !== undefined, 'artifact is required');
6
+ const toolContent = z.array(z.discriminatedUnion('type', [
7
+ z.strictObject({ type: z.literal('text'), text: z.string() }),
8
+ z.strictObject({ type: z.literal('image'), artifact, alt: z.string().optional() }),
9
+ z.strictObject({ type: z.literal('file'), artifact, name: z.string() }),
10
+ ]));
11
+ const observationSchema = z.strictObject({
12
+ effect: z.enum(['none', 'applied', 'unknown']),
13
+ evidenceRef: z.string().optional(),
14
+ outcome: z.discriminatedUnion('status', [
15
+ z.strictObject({ status: z.literal('success'), content: toolContent, data: z.json().optional() }),
16
+ z.strictObject({
17
+ status: z.enum(['error', 'denied', 'cancelled']),
18
+ error: z.strictObject({ code: z.string(), message: z.string(), retryable: z.boolean() }),
19
+ data: z.json().optional(),
20
+ }),
21
+ ]),
22
+ });
23
+ export function createToolExecutor(d) {
24
+ const teamPermits = new Map();
25
+ const fileSnapshotsByRun = new Map();
26
+ function fileSnapshots(input) {
27
+ let sessions = fileSnapshotsByRun.get(input.runId);
28
+ if (!sessions)
29
+ fileSnapshotsByRun.set(input.runId, (sessions = new Map()));
30
+ let files = sessions.get(input.agentSessionId);
31
+ if (!files)
32
+ sessions.set(input.agentSessionId, (files = new Map()));
33
+ return files;
34
+ }
35
+ async function executeBatch(input, stopReason) {
36
+ const env = await d.environment.load(input.runId, input.agentSessionId);
37
+ let calls = (await d.reader.pending(input.turnId))
38
+ .filter((call) => call.call.assistantMessageId === input.assistantMessageId)
39
+ .sort((a, b) => a.call.callIndex - b.call.callIndex);
40
+ if (!input.signal.aborted && (await d.state.run(input.runId)).status !== 'cancelling') {
41
+ for (const call of calls) {
42
+ if (call.definition &&
43
+ call.approval?.status !== 'denied' &&
44
+ (env.config.pluginBindings ||
45
+ env.config.toolSnapshot ||
46
+ call.approval ||
47
+ call.status === 'running' ||
48
+ call.status === 'outcome_unknown'))
49
+ await d.registry.resolveFrozen(call.definition);
50
+ }
51
+ }
52
+ for (const call of calls.filter((call) => call.status === 'running'))
53
+ await unknown(d, env, call, 'Host lost an in-flight tool attempt');
54
+ calls = await reload(d, input, calls);
55
+ if (!stopReason)
56
+ await reconcileUnknown(input, env, calls);
57
+ calls = await reload(d, input, calls);
58
+ const run = await d.state.run(input.runId);
59
+ const stopped = input.signal.aborted || run.status === 'cancelling' ? 'cancelled' : stopReason;
60
+ if (stopped) {
61
+ for (const call of calls.filter((call) => call.status !== 'outcome_unknown' && call.status !== 'settled')) {
62
+ const pending = call.approval?.status === 'pending' ? call.approval.request : undefined;
63
+ const expired = Boolean(pending && Date.parse(d.clock.now()) >= Date.parse(pending.expiresAt));
64
+ if (pending)
65
+ await d.journal.append(`approval:${pending.approvalId}:stopped`, [
66
+ d.journal.event('tool.approval.resolved', env.route, {
67
+ decision: {
68
+ approvalId: pending.approvalId,
69
+ toolCallId: call.call.id,
70
+ approved: false,
71
+ decidedBy: 'runtime',
72
+ decidedAt: d.clock.now(),
73
+ reason: expired ? 'Approval expired' : 'Run stopped',
74
+ },
75
+ }),
76
+ ]);
77
+ if (pending && expired)
78
+ await reject(d, env, call, 'APPROVAL_EXPIRED', 'Approval expired', true, pending.approvalId);
79
+ else if (stopped !== 'cancelled')
80
+ await exhausted(d, env, call);
81
+ else
82
+ await settle(d, env, call, {
83
+ status: 'cancelled',
84
+ error: {
85
+ code: 'CANCELLED',
86
+ message: 'Cancelled before tool execution',
87
+ retryable: false,
88
+ },
89
+ }, 'none');
90
+ }
91
+ if (stopped !== 'cancelled')
92
+ return { status: 'interrupted', reason: stopped, callIds: calls.map((call) => call.call.id) };
93
+ return {
94
+ status: 'cancelled',
95
+ unresolvedCallIds: calls
96
+ .filter((call) => call.status === 'outcome_unknown')
97
+ .map((call) => call.call.id),
98
+ };
99
+ }
100
+ if (!calls.length)
101
+ return { status: 'settled', callIds: [] };
102
+ const startedRun = validateStartedRun(run, env.config.limits);
103
+ const turn = await d.state.turn(input.turnId);
104
+ const deadlineAt = earlierDeadline(startedRun.deadlineAt, turn.deadlineAt);
105
+ const subagentWall = resolveSubagentWallTimeMs(env.config.limits);
106
+ const limitWallTimeMs = turn.deadlineAt && isLimited(subagentWall)
107
+ ? subagentWall
108
+ : isLimited(env.config.limits.wallTimeMs)
109
+ ? env.config.limits.wallTimeMs
110
+ : undefined;
111
+ if (calls.some((call) => call.status === 'outcome_unknown'))
112
+ return pause(d, env, input, 'tool_outcome_unknown', calls);
113
+ const validated = new Map();
114
+ const approvals = [];
115
+ for (const call of calls) {
116
+ if (call.status === 'settled')
117
+ continue;
118
+ if (call.approval?.status === 'pending') {
119
+ if (Date.parse(d.clock.now()) >= Date.parse(call.approval.request.expiresAt))
120
+ await resolveApproval({
121
+ approvalId: call.approval.request.approvalId,
122
+ toolCallId: call.call.id,
123
+ approved: false,
124
+ decidedBy: 'runtime',
125
+ decidedAt: d.clock.now(),
126
+ reason: 'Approval expired',
127
+ }, `approval:${call.approval.request.approvalId}:expired`, true, true);
128
+ }
129
+ const current = await d.reader.read(call.call.id);
130
+ if (current.approval?.status === 'pending')
131
+ continue;
132
+ if (current.approval?.status === 'denied') {
133
+ const expired = current.approval.decision.decidedBy === 'runtime' &&
134
+ current.approval.decision.reason === 'Approval expired';
135
+ await reject(d, env, current, expired ? 'APPROVAL_EXPIRED' : 'APPROVAL_DENIED', current.approval.decision.reason, true, current.approval.request.approvalId);
136
+ continue;
137
+ }
138
+ const binding = current.definition
139
+ ? await d.registry.resolveFrozen(current.definition).catch((error) => {
140
+ if (error instanceof RuntimeError &&
141
+ error.code === 'PLUGIN_VERSION_UNAVAILABLE' &&
142
+ !env.config.pluginBindings &&
143
+ !env.config.toolSnapshot &&
144
+ !current.approval &&
145
+ !current.attempts.length)
146
+ return undefined;
147
+ throw error;
148
+ })
149
+ : undefined;
150
+ if (!binding || !current.definition) {
151
+ await reject(d, env, current, 'TOOL_UNAVAILABLE', 'Frozen tool version unavailable');
152
+ continue;
153
+ }
154
+ if (current.call.arguments.kind === 'invalid' ||
155
+ !d.registry.validateInput(current.call.toolName, current.call.toolVersion, current.call.arguments.value, current.definition.scopeKey)) {
156
+ const detail = current.call.arguments.kind === 'invalid'
157
+ ? 'Tool arguments must be valid JSON'
158
+ : d.registry.describeInvalidInput(current.call.toolName, current.call.toolVersion, current.call.arguments.value, current.definition.scopeKey);
159
+ await reject(d, env, current, 'INVALID_ARGUMENTS', detail ?? 'Tool arguments rejected');
160
+ continue;
161
+ }
162
+ validated.set(current.call.id, current.call.arguments.value);
163
+ if (!current.attempts.length && !current.approval) {
164
+ let resources;
165
+ try {
166
+ resources = await resolveResources(binding.handler, current.call.arguments.value, env);
167
+ }
168
+ catch (error) {
169
+ if (!(error instanceof RuntimeError))
170
+ throw error;
171
+ await reject(d, env, current, error.code, error.message, true);
172
+ continue;
173
+ }
174
+ const request = {
175
+ toolCallId: current.call.id,
176
+ definition: current.definition,
177
+ argumentsHash: d.hash(current.call.arguments),
178
+ resources,
179
+ policyVersion: env.config.policyVersion,
180
+ runId: input.runId,
181
+ };
182
+ let permission = await d.policy.evaluate(request);
183
+ if (env.membership?.searchBranchId &&
184
+ resources.some((value) => value.startsWith(outsideWorkspacePrefix)))
185
+ permission = { decision: 'deny', reason: 'Search branches are confined to their workspace' };
186
+ const hook = d.hooks?.(env.config, env).evaluateToolPermission;
187
+ if (hook) {
188
+ try {
189
+ permission = tightenToolPermission(permission, await hook(structuredClone(request), structuredClone(permission)));
190
+ }
191
+ catch (error) {
192
+ const diagnosticId = d.id();
193
+ reportDiagnostic(d.logger, error, diagnosticId, 'TOOL_PERMISSION_HOOK_FAILED', {
194
+ runId: input.runId,
195
+ toolCallId: current.call.id,
196
+ });
197
+ permission = { decision: 'deny', reason: `Tool permission hook failed (${diagnosticId})` };
198
+ }
199
+ }
200
+ if (permission.decision === 'deny') {
201
+ const code = env.config.policyVersion === '1' &&
202
+ resources.some((value) => value.startsWith(outsideWorkspacePrefix))
203
+ ? 'WORKSPACE_PATH_INVALID'
204
+ : 'PERMISSION_DENIED';
205
+ await reject(d, env, current, code, permission.reason, true);
206
+ continue;
207
+ }
208
+ if (permission.decision === 'ask') {
209
+ const approvalId = d.id();
210
+ const teamWorker = env.membership?.role === 'worker' && env.membership.teamMemberId !== undefined;
211
+ const approvalDeadline = teamWorker ? startedRun.deadlineAt : deadlineAt;
212
+ const expiresAt = approvalDeadline ?? new Date(Date.parse(d.clock.now()) + 24 * 60 * 60 * 1000).toISOString();
213
+ approvals.push(d.journal.event('tool.approval.requested', env.route, {
214
+ request: {
215
+ approvalId,
216
+ toolCallId: current.call.id,
217
+ argumentsHash: d.hash(current.call.arguments),
218
+ toolVersion: current.call.toolVersion,
219
+ policyVersion: env.config.policyVersion,
220
+ resources,
221
+ reason: permission.reason,
222
+ expiresAt,
223
+ },
224
+ }));
225
+ }
226
+ }
227
+ }
228
+ calls = await reload(d, input, calls);
229
+ const pending = calls.filter((call) => call.status !== 'settled');
230
+ const state = await d.state.run(input.runId);
231
+ const hasPendingApproval = calls.some((call) => call.approval?.status === 'pending');
232
+ const newCalls = pending.filter((call) => !call.attempts.length).length;
233
+ const limits = env.config.limits;
234
+ const budgets = [
235
+ ...(deadlineAt && limitWallTimeMs !== undefined
236
+ ? [
237
+ {
238
+ resource: 'timeMs',
239
+ used: Math.max(0, limitWallTimeMs + Date.parse(d.clock.now()) - Date.parse(deadlineAt)),
240
+ max: limitWallTimeMs,
241
+ },
242
+ ]
243
+ : []),
244
+ ...(isLimited(limits.maxToolCalls)
245
+ ? [
246
+ {
247
+ resource: 'toolCalls',
248
+ used: state.toolCallsStarted,
249
+ max: limits.maxToolCalls,
250
+ required: state.toolCallsStarted + newCalls,
251
+ },
252
+ ]
253
+ : []),
254
+ ...(isLimited(limits.maxSteps)
255
+ ? [
256
+ {
257
+ resource: 'steps',
258
+ used: state.stepsStarted,
259
+ max: limits.maxSteps,
260
+ required: state.stepsStarted + pending.length,
261
+ },
262
+ ]
263
+ : []),
264
+ ...(isLimited(limits.maxTotalTokens)
265
+ ? [
266
+ {
267
+ resource: 'tokens',
268
+ used: state.chargedUsage.inputTokens + state.chargedUsage.outputTokens,
269
+ max: limits.maxTotalTokens,
270
+ },
271
+ ]
272
+ : []),
273
+ ];
274
+ const exhaustedBudget = budgets.find(({ used, max, required }) => required === undefined ? used >= max : required > max);
275
+ if (!hasPendingApproval && exhaustedBudget) {
276
+ for (const call of pending)
277
+ await exhausted(d, env, call);
278
+ return {
279
+ status: 'interrupted',
280
+ reason: exhaustedBudget.resource === 'timeMs' ? 'timeout' : 'limit',
281
+ budget: exhaustedBudget,
282
+ callIds: calls.map((call) => call.call.id),
283
+ };
284
+ }
285
+ if (approvals.length || hasPendingApproval)
286
+ return pause(d, env, input, 'approval', calls, approvals);
287
+ if (state.status === 'paused')
288
+ return { status: 'paused', reason: state.pauseReason, callIds: pending.map((call) => call.call.id) };
289
+ let cursor = 0;
290
+ let blocked = false;
291
+ let serial = Promise.resolve();
292
+ const snapshots = fileSnapshots(input);
293
+ const isolated = Boolean(d.isAgentIsolated?.(input.runId, input.agentSessionId));
294
+ const permitKey = isolated ? `${input.runId}:${input.agentSessionId}` : input.runId;
295
+ const workers = Array.from({ length: Math.min(env.config.limits.maxParallelTools, pending.length) }, async () => {
296
+ while (cursor < pending.length && !blocked) {
297
+ const call = pending[cursor++];
298
+ const serialCall = call.definition.concurrency === 'serial_per_run';
299
+ if (env.config.team) {
300
+ let permits = teamPermits.get(permitKey);
301
+ if (!permits) {
302
+ permits = new ToolPermits(env.config.limits.maxParallelTools);
303
+ teamPermits.set(permitKey, permits);
304
+ }
305
+ if (permits.wouldWait(serialCall)) {
306
+ input.onToolWaiting?.(call.call.toolName, d.clock.now());
307
+ }
308
+ const release = await permits.acquire(serialCall);
309
+ try {
310
+ await invoke(d, env, input, call, validated.get(call.call.id), deadlineAt, snapshots);
311
+ }
312
+ finally {
313
+ release();
314
+ if (permits.idle)
315
+ teamPermits.delete(permitKey);
316
+ }
317
+ }
318
+ else if (serialCall) {
319
+ const work = serial.then(() => invoke(d, env, input, call, validated.get(call.call.id), deadlineAt, snapshots));
320
+ serial = work;
321
+ await work;
322
+ }
323
+ else
324
+ await invoke(d, env, input, call, validated.get(call.call.id), deadlineAt, snapshots);
325
+ if ((await d.reader.read(call.call.id)).status === 'outcome_unknown')
326
+ blocked = true;
327
+ }
328
+ });
329
+ if (env.config.team) {
330
+ for (const result of await Promise.allSettled(workers))
331
+ if (result.status === 'rejected')
332
+ throw result.reason;
333
+ }
334
+ else
335
+ await Promise.all(workers);
336
+ calls = await reload(d, input, calls);
337
+ if (input.signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
338
+ return {
339
+ status: 'cancelled',
340
+ unresolvedCallIds: calls
341
+ .filter((call) => call.status === 'outcome_unknown')
342
+ .map((call) => call.call.id),
343
+ };
344
+ if (calls.some((call) => call.status === 'outcome_unknown')) {
345
+ await reconcileUnknown(input, env, calls);
346
+ calls = await reload(d, input, calls);
347
+ if (calls.some((call) => call.status === 'outcome_unknown'))
348
+ return pause(d, env, input, 'tool_outcome_unknown', calls);
349
+ return executeBatch(input);
350
+ }
351
+ if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt))
352
+ return { status: 'interrupted', reason: 'timeout', callIds: calls.map((call) => call.call.id) };
353
+ return { status: 'settled', callIds: calls.map((call) => call.call.id) };
354
+ }
355
+ async function reconcileUnknown(input, env, calls) {
356
+ for (const call of calls.filter((call) => call.status === 'outcome_unknown')) {
357
+ if (input.signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
358
+ return;
359
+ try {
360
+ if (!call.definition)
361
+ continue;
362
+ const binding = await d.registry.resolveFrozen(call.definition);
363
+ let decision;
364
+ if (call.definition?.effects === 'read')
365
+ decision = { kind: 'not_applied', evidenceRef: 'read-only:no-write-side-effect' };
366
+ else if (call.definition?.supportsReconcile && binding.handler.reconcile)
367
+ decision = await abortable(binding.handler.reconcile(call.executionKey, context(d, env, call, input.signal)), input.signal);
368
+ if (decision)
369
+ await reconcile(call.call.id, decision, `recover:${call.attempts.at(-1).id}:reconcile`);
370
+ }
371
+ catch (error) {
372
+ if (input.signal.aborted)
373
+ return;
374
+ if (error instanceof RuntimeError && error.code === 'PLUGIN_VERSION_UNAVAILABLE')
375
+ throw error;
376
+ reportDiagnostic(d.logger, error, d.id(), 'TOOL_RECONCILIATION_FAILED', {
377
+ toolCallId: call.call.id,
378
+ runId: call.runId,
379
+ });
380
+ }
381
+ }
382
+ }
383
+ async function resolveApproval(decision, commandId, resume = true, automatic = false) {
384
+ const { decidedAt: _, ...identity } = decision;
385
+ const command = {
386
+ type: 'tool.approval.resolve',
387
+ decision: automatic ? identity : decision,
388
+ ...(resume ? {} : { resume: false }),
389
+ };
390
+ if (await d.journal.receipt(commandId, command))
391
+ return;
392
+ const approval = await d.reader.approval(decision.approvalId);
393
+ const call = await d.reader.read(decision.toolCallId);
394
+ const turn = await d.state.turn(call.turnId);
395
+ const env = await d.environment.load(turn.runId, turn.agentSessionId);
396
+ const run = await d.state.run(turn.runId);
397
+ if (approval.request.toolCallId !== call.call.id ||
398
+ ['cancelling', 'cancelled', 'completed', 'failed'].includes(run.status))
399
+ throw new RuntimeError('APPROVAL_CONFLICT', 'Approval is no longer actionable');
400
+ if (approval.status !== 'pending')
401
+ throw new RuntimeError('APPROVAL_CONFLICT', 'Approval already resolved');
402
+ if (decision.approved && Date.parse(d.clock.now()) >= Date.parse(approval.request.expiresAt))
403
+ throw new RuntimeError('APPROVAL_EXPIRED', 'Approval expired');
404
+ await d.journal.append(commandId, [
405
+ d.journal.event('tool.approval.resolved', env.route, {
406
+ decision,
407
+ ...(resume ? {} : { deferResume: true }),
408
+ }),
409
+ ], undefined, command);
410
+ }
411
+ async function reconcile(callId, decision, commandId) {
412
+ const command = { type: 'tool.reconcile', toolCallId: callId, decision };
413
+ if (await d.journal.receipt(commandId, command))
414
+ return;
415
+ const call = await d.reader.read(callId);
416
+ const turn = await d.state.turn(call.turnId);
417
+ const env = await d.environment.load(turn.runId, turn.agentSessionId);
418
+ if (call.status !== 'outcome_unknown')
419
+ throw new RuntimeError('RECONCILE_CONFLICT', 'Tool is not awaiting reconciliation');
420
+ if (decision.kind === 'completed' &&
421
+ (decision.result.toolCallId !== callId || decision.result.effect === 'unknown'))
422
+ throw new RuntimeError('RECONCILE_CONFLICT', 'Reconciliation must describe a known result for the same call');
423
+ if (decision.kind === 'completed')
424
+ await verifySuccessfulResult(d, call, decision.result);
425
+ const events = [
426
+ d.journal.event('tool.call.reconciled', env.route, {
427
+ toolCallId: callId,
428
+ attemptId: call.attempts.at(-1).id,
429
+ decision,
430
+ }),
431
+ ];
432
+ const run = await d.state.run(env.route.runId);
433
+ if (decision.kind === 'not_applied' &&
434
+ ['cancelling', 'cancelled', 'failed', 'completed'].includes(run.status))
435
+ events.push(settlement(d, env, call, {
436
+ toolCallId: callId,
437
+ outcome: {
438
+ status: 'cancelled',
439
+ error: {
440
+ code: 'CANCELLED',
441
+ message: 'Reconciled as not applied after the Run stopped',
442
+ retryable: false,
443
+ },
444
+ },
445
+ effect: 'none',
446
+ }));
447
+ else if (decision.kind !== 'not_applied') {
448
+ const result = decision.kind === 'completed'
449
+ ? decision.result
450
+ : {
451
+ toolCallId: callId,
452
+ outcome: {
453
+ status: 'error',
454
+ error: { code: 'ABANDONED_UNKNOWN', message: decision.reason, retryable: false },
455
+ },
456
+ effect: 'unknown',
457
+ };
458
+ events.push(settlement(d, env, call, result));
459
+ }
460
+ await d.journal.append(commandId, events, undefined, command);
461
+ }
462
+ async function recover(input) {
463
+ // Recovery cancellation stops the recovery coordinator; persistent Run cancellation is state-driven.
464
+ return executeBatch({ ...input, signal: new AbortController().signal });
465
+ }
466
+ return {
467
+ executeBatch,
468
+ recover,
469
+ resolveApproval,
470
+ reconcile,
471
+ clearFileSnapshots: (runId) => fileSnapshotsByRun.delete(runId),
472
+ };
473
+ }
474
+ class ToolPermits {
475
+ limit;
476
+ active = 0;
477
+ runningSerial = false;
478
+ pending = [];
479
+ constructor(limit) {
480
+ this.limit = limit;
481
+ }
482
+ get idle() {
483
+ return !this.active && !this.pending.length;
484
+ }
485
+ wouldWait(serial) {
486
+ return this.active >= this.limit || (serial && this.runningSerial);
487
+ }
488
+ acquire(serial) {
489
+ return new Promise((resolve) => {
490
+ this.pending.push({ serial, resolve });
491
+ this.dispatch();
492
+ });
493
+ }
494
+ dispatch() {
495
+ while (this.active < this.limit) {
496
+ const index = this.pending.findIndex(({ serial }) => !serial || !this.runningSerial);
497
+ if (index < 0)
498
+ return;
499
+ const { serial, resolve } = this.pending.splice(index, 1)[0];
500
+ this.active++;
501
+ if (serial)
502
+ this.runningSerial = true;
503
+ resolve(() => {
504
+ this.active--;
505
+ if (serial)
506
+ this.runningSerial = false;
507
+ this.dispatch();
508
+ });
509
+ }
510
+ }
511
+ }
512
+ async function invoke(d, env, input, original, value, deadlineAt, fileSnapshots) {
513
+ let call = original;
514
+ const { handler } = await d.registry.resolveFrozen(call.definition);
515
+ while (true) {
516
+ const run = await d.state.run(input.runId);
517
+ if ((await d.state.pendingTools(input.turnId)).some((item) => item.status === 'outcome_unknown'))
518
+ return;
519
+ if (input.signal.aborted || run.status === 'cancelling') {
520
+ await settle(d, env, call, {
521
+ status: 'cancelled',
522
+ error: { code: 'CANCELLED', message: 'Cancelled before execution', retryable: false },
523
+ }, 'none');
524
+ return;
525
+ }
526
+ if (call.attempts.length >= env.config.retry.toolMaxAttemptsPerCall ||
527
+ (!call.attempts.length &&
528
+ isLimited(env.config.limits.maxToolCalls) &&
529
+ run.toolCallsStarted >= env.config.limits.maxToolCalls) ||
530
+ (isLimited(env.config.limits.maxSteps) && run.stepsStarted >= env.config.limits.maxSteps) ||
531
+ (deadlineAt !== undefined && Date.parse(d.clock.now()) >= Date.parse(deadlineAt)) ||
532
+ (isLimited(env.config.limits.maxTotalTokens) &&
533
+ run.chargedUsage.inputTokens + run.chargedUsage.outputTokens >= env.config.limits.maxTotalTokens)) {
534
+ await exhausted(d, env, call);
535
+ return;
536
+ }
537
+ if (!(await waitForRetry(d, env, input, call, deadlineAt)))
538
+ return;
539
+ let resources;
540
+ if (handler.resolveResources) {
541
+ try {
542
+ resources = await resolveResources(handler, value, env);
543
+ const approved = call.approval?.request;
544
+ if (resources.some((resource) => resource.startsWith(outsideWorkspacePrefix)) &&
545
+ (env.membership?.searchBranchId ||
546
+ env.config.policyVersion === '1' ||
547
+ (env.config.policyVersion !== 'interactive-full-v2' && call.approval?.status !== 'approved')))
548
+ throw new RuntimeError('APPROVAL_SCOPE_CHANGED', 'Outside workspace access requires approval');
549
+ if (approved &&
550
+ (approved.argumentsHash !== d.hash(call.call.arguments) ||
551
+ approved.policyVersion !== env.config.policyVersion ||
552
+ approved.toolVersion !== call.call.toolVersion ||
553
+ canonicalJson(approved.resources) !== canonicalJson(resources)))
554
+ throw new RuntimeError('APPROVAL_SCOPE_CHANGED', 'Approved tool resources have changed');
555
+ }
556
+ catch (error) {
557
+ if (!(error instanceof RuntimeError))
558
+ throw error;
559
+ if (!call.attempts.length)
560
+ await reject(d, env, call, error.code, error.message);
561
+ else
562
+ await settle(d, env, call, {
563
+ status: 'error',
564
+ error: { code: error.code, message: error.message, retryable: false },
565
+ }, 'none');
566
+ return;
567
+ }
568
+ }
569
+ const attempt = await startToolAttempt(d, env, input, call, deadlineAt);
570
+ if (!attempt)
571
+ return;
572
+ const { id: attemptId } = attempt;
573
+ call = await d.reader.read(call.call.id);
574
+ const observation = await invokeObservation(d, env, input, call, value, deadlineAt, handler, attemptId, fileSnapshots, resources);
575
+ if (!observation)
576
+ return;
577
+ if (!(await commitToolObservation(d, env, input, call, attempt, observation)))
578
+ return;
579
+ call = await d.reader.read(call.call.id);
580
+ }
581
+ }
582
+ async function resolveResources(handler, value, env) {
583
+ return handler.resolveResources
584
+ ? handler.resolveResources(value, env.workingDirectory, {
585
+ runId: env.route.runId,
586
+ agentSessionId: env.route.agentSessionId,
587
+ })
588
+ : [env.workingDirectory];
589
+ }
590
+ async function waitForRetry(d, env, input, call, deadlineAt) {
591
+ if (call.retryAt) {
592
+ const delay = Math.max(0, Date.parse(call.retryAt) - Date.parse(d.clock.now()));
593
+ if (deadlineAt !== undefined && delay >= Date.parse(deadlineAt) - Date.parse(d.clock.now())) {
594
+ await exhausted(d, env, call);
595
+ return false;
596
+ }
597
+ try {
598
+ await d.clock.delay(delay, input.signal);
599
+ }
600
+ catch {
601
+ await settle(d, env, call, {
602
+ status: 'cancelled',
603
+ error: { code: 'CANCELLED', message: 'Cancelled during retry wait', retryable: false },
604
+ }, 'none');
605
+ return false;
606
+ }
607
+ }
608
+ return true;
609
+ }
610
+ async function startToolAttempt(d, env, input, call, deadlineAt) {
611
+ const stepId = d.id();
612
+ const attemptId = d.id();
613
+ const attempt = {
614
+ id: attemptId,
615
+ toolCallId: call.call.id,
616
+ stepId,
617
+ number: call.attempts.length + 1,
618
+ executionKey: call.executionKey,
619
+ executorInstanceId: d.instanceId,
620
+ hostEpoch: d.epoch,
621
+ startedAt: d.clock.now(),
622
+ };
623
+ try {
624
+ const receipt = await d.journal.append(`attempt:${attemptId}:start`, (ordinal) => [
625
+ d.journal.event('step.started', env.route, {
626
+ step: { id: stepId, turnId: input.turnId, ordinal, kind: 'tool', status: 'running' },
627
+ }),
628
+ d.journal.event('tool.call.started', env.route, { attempt }),
629
+ ], input.turnId);
630
+ const step = receipt.events[0];
631
+ if (step?.type === 'step.started')
632
+ input.onToolStarted?.(call.call.toolName, step.payload.step.ordinal, attempt.startedAt);
633
+ }
634
+ catch (error) {
635
+ const current = await d.state.run(input.runId);
636
+ if (current.status === 'cancelling') {
637
+ await settle(d, env, call, {
638
+ status: 'cancelled',
639
+ error: { code: 'CANCELLED', message: 'Tool scheduling stopped', retryable: false },
640
+ }, 'none');
641
+ return;
642
+ }
643
+ if (current.status === 'paused' ||
644
+ (env.config.team
645
+ ? (await d.state.pendingTools(input.turnId)).some((item) => item.status === 'outcome_unknown')
646
+ : current.unresolvedCallIds.length))
647
+ return;
648
+ if ((!call.attempts.length &&
649
+ isLimited(env.config.limits.maxToolCalls) &&
650
+ current.toolCallsStarted >= env.config.limits.maxToolCalls) ||
651
+ (isLimited(env.config.limits.maxSteps) && current.stepsStarted >= env.config.limits.maxSteps) ||
652
+ (deadlineAt !== undefined && Date.parse(d.clock.now()) >= Date.parse(deadlineAt)) ||
653
+ (isLimited(env.config.limits.maxTotalTokens) &&
654
+ current.chargedUsage.inputTokens + current.chargedUsage.outputTokens >=
655
+ env.config.limits.maxTotalTokens)) {
656
+ await exhausted(d, env, call);
657
+ return;
658
+ }
659
+ throw error;
660
+ }
661
+ return attempt;
662
+ }
663
+ async function invokeObservation(d, env, input, call, value, deadlineAt, handler, attemptId, fileSnapshots, resources) {
664
+ const remaining = deadlineAt !== undefined ? Date.parse(deadlineAt) - Date.parse(d.clock.now()) : Infinity;
665
+ if (remaining <= 0 || input.signal.aborted)
666
+ return {
667
+ effect: 'none',
668
+ outcome: {
669
+ status: 'error',
670
+ error: input.signal.aborted
671
+ ? { code: 'CANCELLED', message: 'Cancelled before invocation', retryable: false }
672
+ : { code: 'TIMEOUT', message: 'Run deadline elapsed before invocation', retryable: false },
673
+ },
674
+ };
675
+ const definition = call.definition;
676
+ const { toolTimeoutMs, shellTimeoutMs } = env.config.limits;
677
+ let invocationLimit = toolTimeoutMs;
678
+ if (definition.name === 'shell' && definition.source.kind === 'builtin') {
679
+ const requested = value && typeof value === 'object' && 'timeout_ms' in value ? value.timeout_ms : undefined;
680
+ // Shorter timeouts still apply to the child process after it acquires the workspace write queue.
681
+ const shellLimit = typeof requested === 'number' ? Math.max(requested, processTimeoutMs) : processTimeoutMs;
682
+ invocationLimit = Math.min(shellLimit, shellTimeoutMs ?? toolTimeoutMs);
683
+ }
684
+ const timeout = Math.max(1, Math.min(definition.timeoutMs, invocationLimit, remaining));
685
+ const timeoutController = new AbortController();
686
+ const timer = setTimeout(() => timeoutController.abort(new DOMException('Tool invocation timed out', 'TimeoutError')), timeout);
687
+ const signal = AbortSignal.any([input.signal, timeoutController.signal]);
688
+ let observation;
689
+ try {
690
+ observation = await abortable(handler.invoke(value, {
691
+ ...context(d, env, call, signal),
692
+ fileSnapshots,
693
+ ...(resources ? { resources } : {}),
694
+ }), signal, call.definition.abortGraceMs);
695
+ const validation = observationSchema.safeParse(observation);
696
+ if (!validation.success) {
697
+ const missingArtifact = validation.error.issues.every((issue) => issue.code === 'custom' &&
698
+ issue.path[0] === 'outcome' &&
699
+ issue.path[1] === 'content' &&
700
+ issue.path.at(-1) === 'artifact');
701
+ if (missingArtifact && observation.effect !== 'unknown')
702
+ return {
703
+ effect: observation.effect,
704
+ outcome: {
705
+ status: 'error',
706
+ error: {
707
+ code: 'ARTIFACT_REF_INVALID',
708
+ message: 'Tool content requires an artifact reference',
709
+ retryable: false,
710
+ },
711
+ },
712
+ };
713
+ await unknown(d, env, call, 'Adapter returned an invalid observation');
714
+ return;
715
+ }
716
+ if (observation.effect === 'unknown') {
717
+ await unknown(d, env, call, 'Adapter reported an unknown outcome');
718
+ return;
719
+ }
720
+ }
721
+ catch (error) {
722
+ const diagnosticId = d.id();
723
+ reportDiagnostic(d.logger, error, diagnosticId, 'TOOL_INVOCATION_FAILED', {
724
+ runId: call.runId,
725
+ turnId: call.turnId,
726
+ toolCallId: call.call.id,
727
+ attemptId,
728
+ });
729
+ await unknown(d, env, call, `Tool invocation ended without a known result (${diagnosticId})`);
730
+ return;
731
+ }
732
+ finally {
733
+ clearTimeout(timer);
734
+ }
735
+ return observation;
736
+ }
737
+ async function commitToolObservation(d, env, input, call, attempt, observation) {
738
+ const { id: attemptId, stepId } = attempt;
739
+ const result = { toolCallId: call.call.id, ...observation };
740
+ if (observation.outcome.status === 'success') {
741
+ try {
742
+ await verifySuccessfulResult(d, call, result);
743
+ }
744
+ catch (error) {
745
+ const artifactError = {
746
+ code: error instanceof RuntimeError ? error.code : 'ARTIFACT_INVALID',
747
+ message: error instanceof Error ? error.message : 'artifact validation failed',
748
+ retryable: false,
749
+ };
750
+ const effect = observation.effect === 'applied' ? 'applied' : 'none';
751
+ const invalidResult = {
752
+ toolCallId: call.call.id,
753
+ outcome: { status: 'error', error: artifactError },
754
+ effect,
755
+ };
756
+ await d.journal.append(`attempt:${attemptId}:artifact-failed`, [
757
+ d.journal.event('tool.call.failed', env.route, {
758
+ attemptId,
759
+ toolCallId: call.call.id,
760
+ error: artifactError,
761
+ effect,
762
+ }),
763
+ d.journal.event('step.failed', env.route, { stepId, error: artifactError }),
764
+ settlement(d, env, call, invalidResult),
765
+ ]);
766
+ return false;
767
+ }
768
+ await d.journal.append(`attempt:${attemptId}:complete`, [
769
+ d.journal.event('tool.call.completed', env.route, { attemptId, result }),
770
+ settlement(d, env, call, result),
771
+ d.journal.event('step.completed', env.route, { stepId }),
772
+ ]);
773
+ return false;
774
+ }
775
+ const error = observation.outcome.error;
776
+ const retry = observation.outcome.status === 'error' &&
777
+ error.retryable &&
778
+ observation.effect === 'none' &&
779
+ attempt.number < env.config.retry.toolMaxAttemptsPerCall &&
780
+ !input.signal.aborted;
781
+ const delay = Math.min(env.config.retry.maxDelayMs, env.config.retry.baseDelayMs * 2 ** (attempt.number - 1));
782
+ const retryAt = retry ? new Date(Date.parse(d.clock.now()) + delay).toISOString() : undefined;
783
+ await d.journal.append(`attempt:${attemptId}:failed`, [
784
+ d.journal.event('tool.call.failed', env.route, {
785
+ attemptId,
786
+ toolCallId: call.call.id,
787
+ error,
788
+ effect: observation.effect,
789
+ ...(retryAt ? { retryAt } : {}),
790
+ }),
791
+ d.journal.event('step.failed', env.route, { stepId, error }),
792
+ ...(retryAt ? [] : [settlement(d, env, call, result)]),
793
+ ]);
794
+ return Boolean(retryAt);
795
+ }
796
+ async function pause(d, env, input, reason, calls, events = []) {
797
+ const run = await d.state.run(input.runId);
798
+ if (run.status === 'cancelling' || input.signal.aborted)
799
+ return {
800
+ status: 'cancelled',
801
+ unresolvedCallIds: calls
802
+ .filter((call) => call.status === 'outcome_unknown')
803
+ .map((call) => call.call.id),
804
+ };
805
+ if (run.status === 'running' &&
806
+ (!env.config.team || (await d.state.turn(input.turnId)).status === 'running')) {
807
+ events.push(d.journal.event('turn.paused', env.route, { turnId: input.turnId, reason }));
808
+ if (!env.config.team)
809
+ events.push(d.journal.event('run.paused', {
810
+ kind: 'run',
811
+ workspaceId: env.route.workspaceId,
812
+ sessionId: env.route.sessionId,
813
+ runId: input.runId,
814
+ }, { reason, blockedTurnId: input.turnId }));
815
+ }
816
+ if (events.length)
817
+ try {
818
+ await d.journal.append(`pause:${input.turnId}:${input.assistantMessageId}:${reason}:${calls.map((c) => c.attempts.length).join('-')}`, events);
819
+ }
820
+ catch (error) {
821
+ if ((await d.state.run(input.runId)).status === 'cancelling')
822
+ return {
823
+ status: 'cancelled',
824
+ unresolvedCallIds: calls
825
+ .filter((call) => call.status === 'outcome_unknown')
826
+ .map((call) => call.call.id),
827
+ };
828
+ throw error;
829
+ }
830
+ return {
831
+ status: 'paused',
832
+ reason,
833
+ callIds: calls.filter((call) => call.status !== 'settled').map((call) => call.call.id),
834
+ };
835
+ }
836
+ async function unknown(d, env, call, reason) {
837
+ const attempt = call.attempts.at(-1);
838
+ await d.journal.append(`recover:${attempt.id}:unknown`, [
839
+ d.journal.event('tool.call.outcome_unknown', env.route, {
840
+ toolCallId: call.call.id,
841
+ attemptId: attempt.id,
842
+ reason,
843
+ }),
844
+ d.journal.event('step.interrupted', env.route, { stepId: attempt.stepId, reason }),
845
+ ]);
846
+ }
847
+ function context(d, env, call, signal) {
848
+ const checkpointSourceRunId = env.config.checkpoint?.sourceRunId;
849
+ return {
850
+ ...env.route,
851
+ ...(checkpointSourceRunId ? { checkpointSourceRunId } : {}),
852
+ turnId: call.turnId,
853
+ attemptId: call.attempts.at(-1).id,
854
+ executionKey: call.executionKey,
855
+ workingDirectory: env.workingDirectory,
856
+ signal,
857
+ logger: {
858
+ info(fields, message) {
859
+ d.logger.info({
860
+ ...fields,
861
+ runId: call.runId,
862
+ turnId: call.turnId,
863
+ toolCallId: call.call.id,
864
+ attemptId: call.attempts.at(-1)?.id ?? '',
865
+ }, message);
866
+ },
867
+ error(fields, message) {
868
+ d.logger.error({
869
+ ...fields,
870
+ runId: call.runId,
871
+ turnId: call.turnId,
872
+ toolCallId: call.call.id,
873
+ attemptId: call.attempts.at(-1)?.id ?? '',
874
+ }, message);
875
+ },
876
+ },
877
+ };
878
+ }
879
+ function settlement(d, env, call, result) {
880
+ return d.journal.event('tool.call.settled', env.route, {
881
+ message: {
882
+ id: d.id(),
883
+ agentSessionId: env.route.agentSessionId,
884
+ runId: env.route.runId,
885
+ turnId: call.turnId,
886
+ role: 'tool',
887
+ result,
888
+ },
889
+ });
890
+ }
891
+ async function settle(d, env, call, outcome, effect) {
892
+ await d.journal.append(`call:${call.call.id}:settle`, [
893
+ settlement(d, env, call, { toolCallId: call.call.id, outcome, effect }),
894
+ ]);
895
+ }
896
+ async function reject(d, env, call, code, message, denied = false, approvalId) {
897
+ const error = { code, message, retryable: false };
898
+ await d.journal.append(`call:${call.call.id}:reject`, [
899
+ denied
900
+ ? d.journal.event('tool.call.denied', env.route, {
901
+ toolCallId: call.call.id,
902
+ ...(approvalId ? { approvalId } : {}),
903
+ reason: message,
904
+ })
905
+ : d.journal.event('tool.call.rejected', env.route, { toolCallId: call.call.id, error }),
906
+ settlement(d, env, call, {
907
+ toolCallId: call.call.id,
908
+ outcome: { status: denied ? 'denied' : 'error', error },
909
+ effect: 'none',
910
+ }),
911
+ ]);
912
+ }
913
+ async function exhausted(d, env, call) {
914
+ if (!call.attempts.length) {
915
+ await reject(d, env, call, 'LIMIT', 'Tool group cannot fit the remaining run budget');
916
+ return;
917
+ }
918
+ const error = call.lastFailure?.error ?? {
919
+ code: 'LIMIT',
920
+ message: 'Tool attempt limit reached',
921
+ retryable: false,
922
+ };
923
+ await settle(d, env, call, { status: 'error', error }, call.lastFailure?.effect ?? 'none');
924
+ }
925
+ async function reload(d, _input, calls) {
926
+ return Promise.all(calls.map((call) => d.reader.read(call.call.id)));
927
+ }
928
+ async function abortable(work, signal, abortGraceMs = 0) {
929
+ let abort = () => { };
930
+ let timer;
931
+ try {
932
+ return await Promise.race([
933
+ work.then((result) => {
934
+ if (abortGraceMs === 0)
935
+ signal.throwIfAborted();
936
+ return result;
937
+ }),
938
+ new Promise((_, reject) => {
939
+ abort = () => {
940
+ if (abortGraceMs > 0)
941
+ timer = setTimeout(() => reject(signal.reason), abortGraceMs);
942
+ else
943
+ reject(signal.reason);
944
+ };
945
+ if (signal.aborted)
946
+ abort();
947
+ else
948
+ signal.addEventListener('abort', abort, { once: true });
949
+ }),
950
+ ]);
951
+ }
952
+ finally {
953
+ signal.removeEventListener('abort', abort);
954
+ clearTimeout(timer);
955
+ }
956
+ }
957
+ async function verifyArtifacts(d, result) {
958
+ if (result.outcome.status !== 'success' || result.outcome.content.length === 0)
959
+ return;
960
+ for (const part of result.outcome.content)
961
+ if (part.type !== 'text') {
962
+ if (!d.artifactReader)
963
+ throw new RuntimeError('UNSUPPORTED_ARTIFACT', 'tool artifact reader is unavailable');
964
+ const ref = validateArtifactRef(part.artifact);
965
+ const bytes = await d.artifactReader.read(ref);
966
+ if (bytes.byteLength !== ref.byteLength ||
967
+ createHash('sha256').update(bytes).digest('hex') !== ref.sha256)
968
+ throw new RuntimeError('ARTIFACT_CORRUPT', 'tool artifact digest or byteLength mismatch');
969
+ }
970
+ }
971
+ async function verifySuccessfulResult(d, call, result) {
972
+ if (result.outcome.status !== 'success')
973
+ return;
974
+ const schema = call.definition?.outputSchema;
975
+ if (schema && !z.fromJSONSchema(schema).safeParse(result.outcome.data ?? null).success)
976
+ throw new RuntimeError('INVALID_TOOL_OUTPUT', 'Tool output schema rejected');
977
+ await verifyArtifacts(d, result);
978
+ }