@tangle-network/agent-app 0.63.33 → 0.63.35

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.
@@ -38,7 +38,7 @@
38
38
  import type { SandboxInstance } from '@tangle-network/sandbox';
39
39
  import type { RouterTurnTool } from '../runtime/router-turn';
40
40
  import { type EscalationHint, type EscalationInput } from '../sandbox/escalation-speculator';
41
- import { type SandboxRunToolOptions } from '../sandbox/sandbox-run-tool';
41
+ import { SandboxRunError, type SandboxRunToolOptions } from '../sandbox/sandbox-run-tool';
42
42
  import { type ComputerStepOptions } from '../sandbox/computer-step';
43
43
  import type { PersistedChatMessageForTurn } from '../stream/index';
44
44
  import { type RouterTurnProducerOptions } from './router-producer';
@@ -64,6 +64,10 @@ export interface HybridTurnBox {
64
64
  /** Every computer failure with its cause. The producer already persists the redacted cause chain on the turn's
65
65
  * warning notice (`detail`), and logs it when this is omitted. */
66
66
  onFailure?: SandboxRunToolOptions['onFailure'];
67
+ /** What the turn's warning notice keeps as `detail` for a failed call. Members read that notice in the transcript.
68
+ * Default: the redacted cause chain ({@link sandboxRunFailureDetail}). Return undefined to keep a cause that holds
69
+ * private platform diagnostics off the transcript; `onFailure` still receives the full error. */
70
+ failureDetail?(error: SandboxRunError): string | undefined;
67
71
  /** The tool's name and description. Default `sandbox_run` and its shared description. */
68
72
  name?: string;
69
73
  description?: string;
@@ -79,7 +79,7 @@ import {
79
79
  turnCarriesFiles,
80
80
  turnPromptText,
81
81
  withProducerStream
82
- } from "../chunk-4CEIZZTH.js";
82
+ } from "../chunk-KYBE4UYT.js";
83
83
  import "../chunk-CWO2LHXH.js";
84
84
  import {
85
85
  sniffMimeFromName
@@ -235,136 +235,174 @@ function protectedTurnSettings(profile, toolNames) {
235
235
  ...total !== void 0 ? { maxCompletionTokens: total } : {}
236
236
  };
237
237
  }
238
- function protectedToolResultText(outcome) {
239
- if (!outcome.ok) return `error: ${outcome.message}`;
240
- return JSON.stringify(outcome.result) ?? "null";
241
- }
242
238
  function createProtectedRuntimeChatProducer(options) {
243
- if (!Number.isSafeInteger(options.maxToolCalls) || options.maxToolCalls < 0) {
244
- throw new Error("maxToolCalls must be a non-negative integer");
245
- }
239
+ if (!Number.isSafeInteger(options.maxToolCalls) || options.maxToolCalls < 0) throw new Error("maxToolCalls must be a non-negative integer");
246
240
  options = {
247
241
  ...options,
248
242
  grant: { ...options.grant, resolve: structuredClone(options.grant.resolve), reserve: structuredClone(options.grant.reserve) },
249
243
  tools: options.tools.map((tool) => ({ ...tool, inputSchema: structuredClone(tool.inputSchema) })),
250
- // Chat history rows carry storage fields (id, parts, timestamps). The
251
- // provider receives exactly role and content; Anthropic rejects extra keys.
244
+ // Providers reject the storage fields carried by chat history rows.
252
245
  priorMessages: options.priorMessages?.map(({ role, content }) => ({ role, content }))
253
246
  };
254
- const tools = new Map(options.tools.map((tool) => [tool.name, tool]));
247
+ const tools = new Set(options.tools.map((tool) => tool.name));
255
248
  if (tools.size !== options.tools.length) throw new Error("Duplicate protected tool name");
256
249
  const profile = structuredClone(options.profile);
257
250
  let toolCalls = 0;
258
251
  let usage = {};
259
252
  let started = false;
260
253
  let model;
261
- let budgetEnforced = false;
262
- let toolTokens;
254
+ const controller = new AbortController();
255
+ const pendingTools = /* @__PURE__ */ new Set();
256
+ let execution;
257
+ let reader;
258
+ let writer;
259
+ let terminalObserved = false;
260
+ let closing;
261
+ function close(reason) {
262
+ controller.abort(reason);
263
+ closing ??= (async () => {
264
+ const errors = [];
265
+ try {
266
+ await reader?.cancel();
267
+ } catch (error) {
268
+ errors.push(error);
269
+ }
270
+ try {
271
+ await execution;
272
+ } catch (error) {
273
+ errors.push(error);
274
+ }
275
+ while (pendingTools.size) await Promise.allSettled([...pendingTools]);
276
+ try {
277
+ reader?.releaseLock();
278
+ } catch (error) {
279
+ errors.push(error);
280
+ }
281
+ try {
282
+ writer?.releaseLock();
283
+ } catch (error) {
284
+ errors.push(error);
285
+ }
286
+ terminalObserved = true;
287
+ if (errors.length) throw errors[0];
288
+ })();
289
+ return closing;
290
+ }
263
291
  async function* events() {
264
292
  if (started) throw new Error("A protected chat producer can only execute once");
265
293
  started = true;
266
- options.signal?.throwIfAborted();
267
- if (Date.now() >= options.grant.deadlineAtMs) throw new Error("Protected execution deadline expired");
268
- const settings = protectedTurnSettings(profile, new Set(tools.keys()));
269
- const controller = new AbortController();
270
- const signal = AbortSignal.any([
271
- controller.signal,
272
- AbortSignal.timeout(Math.max(1, options.grant.deadlineAtMs - Date.now())),
273
- ...options.signal ? [options.signal] : []
274
- ]);
275
- const channel = new TransformStream();
276
- const writer = channel.writable.getWriter();
277
- const reader = channel.readable.getReader();
278
- const emit = (event) => writer.write(event);
279
- const segments = [];
280
- const execution = runProtectedRouterTurn({
281
- ...settings,
282
- grant: options.grant,
283
- userMessage: options.prompt,
284
- history: [...options.priorMessages ?? []],
285
- signal,
286
- // The grant's ledger expects one buffered completion per model call.
287
- stream: false,
288
- maxToolCalls: options.maxToolCalls,
289
- // The grant bounds model calls; the loop must not stop the turn earlier.
290
- maxToolTurns: options.grant.reserve.limits.maxModelCalls,
291
- tools: options.tools.map((tool) => ({
292
- name: tool.name,
293
- description: tool.description,
294
- inputSchema: tool.inputSchema,
295
- run: async (args) => {
296
- signal.throwIfAborted();
297
- toolCalls += 1;
298
- const id = `tool-${toolCalls}`;
299
- await emit({ type: "tool_call", data: { id, name: tool.name, arguments: args } });
300
- try {
301
- const result = await tool.run(args, { signal });
302
- await emit({ type: "tool_result", data: { id, name: tool.name, output: result } });
303
- return result;
304
- } catch (error) {
305
- const message = error instanceof Error ? error.message : "Tool failed";
306
- await emit({ type: "tool_result", data: { id, name: tool.name, error: message } });
307
- throw error;
294
+ try {
295
+ controller.signal.throwIfAborted();
296
+ options.signal?.throwIfAborted();
297
+ if (Date.now() >= options.grant.deadlineAtMs) throw new Error("Protected execution deadline expired");
298
+ const signal = AbortSignal.any([
299
+ controller.signal,
300
+ AbortSignal.timeout(Math.max(1, options.grant.deadlineAtMs - Date.now())),
301
+ ...options.signal ? [options.signal] : []
302
+ ]);
303
+ const channel = new TransformStream();
304
+ const channelWriter = writer = channel.writable.getWriter();
305
+ reader = channel.readable.getReader();
306
+ const emit = (event) => channelWriter.write(event);
307
+ const segments = [];
308
+ execution = runProtectedRouterTurn({
309
+ ...protectedTurnSettings(profile, tools),
310
+ grant: options.grant,
311
+ userMessage: options.prompt,
312
+ history: [...options.priorMessages ?? []],
313
+ signal,
314
+ // The grant's ledger expects one buffered completion per model call.
315
+ stream: false,
316
+ maxToolCalls: options.maxToolCalls,
317
+ maxToolTurns: options.grant.reserve.limits.maxModelCalls,
318
+ tools: options.tools.map((tool) => ({
319
+ name: tool.name,
320
+ description: tool.description,
321
+ inputSchema: tool.inputSchema,
322
+ run: (args) => {
323
+ const work = (async () => {
324
+ signal.throwIfAborted();
325
+ toolCalls += 1;
326
+ const id = `tool-${toolCalls}`;
327
+ await emit({ type: "tool_call", data: { id, name: tool.name, arguments: args } });
328
+ signal.throwIfAborted();
329
+ try {
330
+ const result = await tool.run(args, { signal });
331
+ await emit({ type: "tool_result", data: { id, name: tool.name, output: result } });
332
+ return result;
333
+ } catch (error) {
334
+ const message = error instanceof Error ? error.message : "Tool failed";
335
+ await emit({ type: "tool_result", data: { id, name: tool.name, error: message } });
336
+ throw error;
337
+ }
338
+ })();
339
+ pendingTools.add(work);
340
+ void work.then(() => pendingTools.delete(work), () => pendingTools.delete(work));
341
+ return work;
308
342
  }
343
+ })),
344
+ toolError: (error) => ({ code: "tool_failed", message: error instanceof Error ? error.message : "Tool failed" }),
345
+ renderToolResult: (_toolName, outcome) => outcome.ok ? JSON.stringify(outcome.result) ?? "null" : `error: ${outcome.message}`,
346
+ onEvent: (event) => {
347
+ if (event.type === "text") segments[event.segment - 1] = (segments[event.segment - 1] ?? "") + event.delta;
309
348
  }
310
- })),
311
- toolError: (error) => ({ code: "tool_failed", message: error instanceof Error ? error.message : "Tool failed" }),
312
- renderToolResult: (_toolName, outcome) => protectedToolResultText(outcome),
313
- onEvent: (event) => {
314
- if (event.type === "text") segments[event.segment - 1] = (segments[event.segment - 1] ?? "") + event.delta;
315
- }
316
- }).then(async (outcome) => {
317
- if (outcome.settlement) {
318
- usage = { ...outcome.settlement.usage };
319
- budgetEnforced = outcome.settlement.budgetEnforced;
320
- model = outcome.settlement.model;
321
- toolTokens = 0;
322
- }
323
- if (!outcome.failure || outcome.failure.code.startsWith("settlement_")) {
324
- const finalText = segments.filter(Boolean).at(-1) ?? "";
325
- if (finalText) await emit({ type: "message.part.updated", data: { part: { id: "text_delta", type: "text" }, delta: finalText } });
326
- await emit({ type: "result", data: { finalText } });
327
- }
328
- if (outcome.failure) throw new Error(outcome.failure.message);
329
- await writer.close();
330
- }).catch((error) => writer.abort(error));
331
- try {
349
+ }).then(async (outcome) => {
350
+ if (outcome.settlement) {
351
+ usage = { ...outcome.settlement.usage };
352
+ model = outcome.settlement.model;
353
+ await emit({ type: "usage", usage: {
354
+ promptTokens: usage.inputTokens,
355
+ completionTokens: usage.outputTokens,
356
+ providerCostUsd: usage.costUsd,
357
+ reasoningTokens: usage.reasoningTokens,
358
+ toolTokens: 0,
359
+ toolCallCount: toolCalls,
360
+ budgetEnforced: outcome.settlement.budgetEnforced
361
+ } });
362
+ }
363
+ if (!outcome.failure || outcome.failure.code.startsWith("settlement_")) {
364
+ const finalText = segments.filter(Boolean).at(-1) ?? "";
365
+ if (finalText) await emit({ type: "message.part.updated", data: { part: { id: "text_delta", type: "text" }, delta: finalText } });
366
+ await emit({ type: "result", data: { finalText } });
367
+ }
368
+ if (outcome.failure) throw new Error(outcome.failure.message);
369
+ await channelWriter.close();
370
+ }).catch((error) => channelWriter.abort(error));
332
371
  for (; ; ) {
333
372
  const next = await reader.read();
334
373
  if (next.done) break;
335
374
  yield next.value;
336
375
  }
337
- await execution;
338
376
  } finally {
339
- controller.abort();
340
- await reader.cancel().catch(() => void 0);
341
- await execution;
342
- reader.releaseLock();
343
- writer.releaseLock();
377
+ await close();
344
378
  }
345
379
  }
346
380
  const producer = createSandboxChatProducer({ events: events(), model: profile.model?.default });
381
+ const stream = producer.stream;
382
+ const end = stream.return.bind(stream);
383
+ const fail = stream.throw.bind(stream);
384
+ stream.return = async (value) => {
385
+ const stopped = close(new Error("The chat route stopped reading this turn"));
386
+ void stopped.catch(() => void 0);
387
+ try {
388
+ return await end(value);
389
+ } finally {
390
+ await stopped;
391
+ }
392
+ };
393
+ stream.throw = async (error) => {
394
+ const stopped = close(error);
395
+ void stopped.catch(() => void 0);
396
+ try {
397
+ return await fail(error);
398
+ } finally {
399
+ await stopped;
400
+ }
401
+ };
347
402
  return {
348
403
  ...producer,
349
- stream: (async function* () {
350
- let failure;
351
- for await (const event of producer.stream) {
352
- if (event.type === "error") failure = event;
353
- else yield event;
354
- }
355
- if (usage.inputTokens !== void 0 && usage.outputTokens !== void 0 && usage.costUsd !== void 0) {
356
- yield { type: "usage", usage: {
357
- promptTokens: usage.inputTokens,
358
- completionTokens: usage.outputTokens,
359
- providerCostUsd: usage.costUsd,
360
- reasoningTokens: usage.reasoningTokens,
361
- toolTokens,
362
- toolCallCount: toolCalls,
363
- budgetEnforced
364
- } };
365
- }
366
- if (failure) yield failure;
367
- })(),
404
+ stream,
405
+ terminalObserved: () => terminalObserved,
368
406
  get model() {
369
407
  return model ?? profile.model?.default;
370
408
  },