@tangle-network/agent-app 4.0.8 → 4.0.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 (45) hide show
  1. package/dist/assistant/index.js +2 -1
  2. package/dist/assistant/index.js.map +1 -1
  3. package/dist/chat-routes/detached-turn.d.ts +2 -0
  4. package/dist/chat-routes/failure-wording.d.ts +56 -0
  5. package/dist/chat-routes/index.js +13 -5
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/chat-routes/sandbox-producer.d.ts +6 -14
  8. package/dist/chat-routes/turn-event-stream.d.ts +5 -0
  9. package/dist/chat-routes/turn-route-contracts.d.ts +23 -0
  10. package/dist/chat-routes/turn-routes.d.ts +3 -1
  11. package/dist/{chunk-ASWAPIJM.js → chunk-AYTNVTDP.js} +2 -2
  12. package/dist/{chunk-FZOHBYGV.js → chunk-KPCNNFBO.js} +13 -2
  13. package/dist/chunk-KPCNNFBO.js.map +1 -0
  14. package/dist/{chunk-QXPOBDPU.js → chunk-M4LA7JMU.js} +1 -21
  15. package/dist/chunk-M4LA7JMU.js.map +1 -0
  16. package/dist/chunk-QUV5M7SZ.js +23 -0
  17. package/dist/chunk-QUV5M7SZ.js.map +1 -0
  18. package/dist/{chunk-A2M75YRP.js → chunk-VTMMTQ4P.js} +2 -2
  19. package/dist/chunk-VTMMTQ4P.js.map +1 -0
  20. package/dist/{chunk-4OR7NNYB.js → chunk-XZ37VCTP.js} +364 -264
  21. package/dist/chunk-XZ37VCTP.js.map +1 -0
  22. package/dist/journeys/cli.js +1 -1
  23. package/dist/journeys/index.js +1 -1
  24. package/dist/preset-cloudflare/index.js +1 -1
  25. package/dist/public-consultation/index.js +4 -3
  26. package/dist/public-consultation/index.js.map +1 -1
  27. package/dist/sandbox/index.js +2 -2
  28. package/dist/turn-health/index.js +2 -1
  29. package/dist/turn-health/index.js.map +1 -1
  30. package/dist/turn-health/sweep.d.ts +1 -1
  31. package/dist/turn-stream/adapters.d.ts +14 -1
  32. package/dist/turn-stream/core.d.ts +2 -0
  33. package/dist/turn-stream/do.d.ts +17 -0
  34. package/dist/turn-stream/index.d.ts +1 -1
  35. package/dist/turn-stream/index.js +11 -2
  36. package/dist/turn-stream/index.js.map +1 -1
  37. package/dist/web-react/index.d.ts +1 -1
  38. package/dist/web-react/index.js +4 -2
  39. package/package.json +1 -1
  40. package/dist/chunk-4OR7NNYB.js.map +0 -1
  41. package/dist/chunk-A2M75YRP.js.map +0 -1
  42. package/dist/chunk-FZOHBYGV.js.map +0 -1
  43. package/dist/chunk-QXPOBDPU.js.map +0 -1
  44. /package/dist/{chunk-ASWAPIJM.js.map → chunk-AYTNVTDP.js.map} +0 -0
  45. /package/dist/{web-react → web}/turn-funding-recovery.d.ts +0 -0
@@ -1,3 +1,6 @@
1
+ import {
2
+ getChatFundingRecovery
3
+ } from "./chunk-QUV5M7SZ.js";
1
4
  import {
2
5
  createInteractionAnswerRoute
3
6
  } from "./chunk-SBHFMDR7.js";
@@ -31,7 +34,7 @@ import {
31
34
  sandboxRunFailureDetail,
32
35
  streamSandboxPrompt,
33
36
  turnStorageBindings
34
- } from "./chunk-ASWAPIJM.js";
37
+ } from "./chunk-AYTNVTDP.js";
35
38
  import {
36
39
  redactErrorMessage
37
40
  } from "./chunk-MH74DY2I.js";
@@ -78,6 +81,9 @@ import {
78
81
  import {
79
82
  parseJsonObjectBody
80
83
  } from "./chunk-ALIWB2P3.js";
84
+ import {
85
+ forwardTurnToHost
86
+ } from "./chunk-KPCNNFBO.js";
81
87
  import {
82
88
  DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
83
89
  coalesceDeltas,
@@ -1370,6 +1376,316 @@ function createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstRe
1370
1376
  return { drainOnce };
1371
1377
  }
1372
1378
 
1379
+ // src/chat-routes/turn-event-stream.ts
1380
+ var WITHHELD_FAILURE = /* @__PURE__ */ Symbol("withheld failure");
1381
+ function serverFailureData(data) {
1382
+ const original = data?.[WITHHELD_FAILURE];
1383
+ return original !== null && typeof original === "object" ? original : data;
1384
+ }
1385
+ function failureReasonOf(data) {
1386
+ if (!data) return void 0;
1387
+ const message = data.message ?? data.error ?? data.reason;
1388
+ if (typeof message === "string" && message.length > 0) return message;
1389
+ return void 0;
1390
+ }
1391
+ function failureCodeOf(data) {
1392
+ const code = data?.code;
1393
+ return typeof code === "string" && code.length > 0 ? code : void 0;
1394
+ }
1395
+ function isVisibleText(event) {
1396
+ const value = event;
1397
+ if (event.type === "text") return typeof value.text === "string" ? value.text.trim().length > 0 : true;
1398
+ if (event.type !== "message.part.updated") return false;
1399
+ const part = event.data?.part;
1400
+ const delta = event.data?.delta;
1401
+ return part?.type === "text" && typeof delta === "string" && delta.trim().length > 0;
1402
+ }
1403
+ function isVisibleOutput(event) {
1404
+ if (isVisibleText(event)) return true;
1405
+ const value = event;
1406
+ if (event.type === "reasoning") return typeof value.text === "string" && value.text.trim().length > 0;
1407
+ if (event.type === "tool_call" || event.type === "tool.call" || event.type === "tool_result" || event.type === "tool.result" || event.type === "tool.event") return true;
1408
+ if (event.type !== "message.part.updated") return false;
1409
+ const part = event.data?.part;
1410
+ if (part?.type === "tool") return true;
1411
+ if (part?.type !== "reasoning" && part?.type !== "text") return false;
1412
+ const text = event.data?.delta ?? part.text;
1413
+ return typeof text === "string" && text.trim().length > 0;
1414
+ }
1415
+ async function* tapRawEvents(source, onRawEvent, log) {
1416
+ for await (const event of source) {
1417
+ try {
1418
+ await onRawEvent(event);
1419
+ } catch (err) {
1420
+ log("[chat-routes] onRawEvent failed", { error: err instanceof Error ? err.message : String(err) });
1421
+ }
1422
+ yield event;
1423
+ }
1424
+ }
1425
+ async function* withStreamHeartbeat(source, intervalMs, makeEvent) {
1426
+ const iterator = source[Symbol.asyncIterator]();
1427
+ try {
1428
+ let pending = iterator.next();
1429
+ let windowStart = Date.now();
1430
+ let tick = 0;
1431
+ for (; ; ) {
1432
+ let timer;
1433
+ let winner;
1434
+ try {
1435
+ const heartbeat = new Promise((resolve) => {
1436
+ timer = setTimeout(() => resolve("heartbeat"), intervalMs);
1437
+ });
1438
+ winner = await Promise.race([pending.then(() => "event"), heartbeat]);
1439
+ } finally {
1440
+ if (timer !== void 0) clearTimeout(timer);
1441
+ }
1442
+ if (winner === "heartbeat") {
1443
+ tick += 1;
1444
+ yield makeEvent({ elapsedMs: Date.now() - windowStart, tick });
1445
+ continue;
1446
+ }
1447
+ const result = await pending;
1448
+ if (result.done) return;
1449
+ yield result.value;
1450
+ pending = iterator.next();
1451
+ windowStart = Date.now();
1452
+ tick = 0;
1453
+ }
1454
+ } finally {
1455
+ await iterator.return?.();
1456
+ }
1457
+ }
1458
+ function concatStreams(streams) {
1459
+ let index = 0;
1460
+ let reader = null;
1461
+ return new ReadableStream({
1462
+ async pull(controller) {
1463
+ for (; ; ) {
1464
+ if (!reader) {
1465
+ const next = streams[index++];
1466
+ if (!next) {
1467
+ controller.close();
1468
+ return;
1469
+ }
1470
+ reader = next.getReader();
1471
+ }
1472
+ const { done, value } = await reader.read();
1473
+ if (done) {
1474
+ reader = null;
1475
+ continue;
1476
+ }
1477
+ controller.enqueue(value);
1478
+ return;
1479
+ }
1480
+ },
1481
+ async cancel(reason) {
1482
+ await reader?.cancel(reason);
1483
+ for (const stream of streams.slice(index)) await stream.cancel(reason);
1484
+ }
1485
+ });
1486
+ }
1487
+ async function* abortOnSignal(source, signal) {
1488
+ const iterator = source[Symbol.asyncIterator]();
1489
+ try {
1490
+ for (; ; ) {
1491
+ const next = await nextWithAbort(iterator, signal);
1492
+ if (next.done) return;
1493
+ yield next.value;
1494
+ }
1495
+ } finally {
1496
+ await closeIteratorAfterAbort(iterator);
1497
+ }
1498
+ }
1499
+ function nextWithAbort(iterator, signal) {
1500
+ if (signal.aborted) return Promise.reject(new Error("chat turn cancelled"));
1501
+ return new Promise((resolve, reject) => {
1502
+ let settled = false;
1503
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
1504
+ const onAbort = () => {
1505
+ if (settled) return;
1506
+ settled = true;
1507
+ cleanup();
1508
+ reject(new Error("chat turn cancelled"));
1509
+ };
1510
+ signal.addEventListener("abort", onAbort, { once: true });
1511
+ if (signal.aborted) {
1512
+ onAbort();
1513
+ return;
1514
+ }
1515
+ Promise.resolve().then(() => iterator.next()).then(
1516
+ (result) => {
1517
+ if (settled) return;
1518
+ settled = true;
1519
+ cleanup();
1520
+ resolve(result);
1521
+ },
1522
+ (error) => {
1523
+ if (settled) return;
1524
+ settled = true;
1525
+ cleanup();
1526
+ reject(error);
1527
+ }
1528
+ );
1529
+ });
1530
+ }
1531
+ var ABORT_CLEANUP_TIMEOUT_MS = 50;
1532
+ async function closeIteratorAfterAbort(iterator) {
1533
+ let closing;
1534
+ try {
1535
+ const result = iterator.return?.();
1536
+ if (result) closing = Promise.resolve(result);
1537
+ } catch {
1538
+ return;
1539
+ }
1540
+ if (!closing) return;
1541
+ let timeout;
1542
+ try {
1543
+ await Promise.race([
1544
+ Promise.resolve(closing).catch(() => void 0),
1545
+ new Promise((resolve) => {
1546
+ timeout = setTimeout(resolve, ABORT_CLEANUP_TIMEOUT_MS);
1547
+ })
1548
+ ]);
1549
+ } finally {
1550
+ if (timeout !== void 0) clearTimeout(timeout);
1551
+ }
1552
+ }
1553
+
1554
+ // src/chat-routes/failure-wording.ts
1555
+ var utcTime = (at) => `${at.toISOString().slice(11, 19)} UTC`;
1556
+ function providerRetryNotice(event) {
1557
+ const retry = event.type === "raw" ? asRecord(asRecord(event.data)?.event) : void 0;
1558
+ if (retry?.type !== "retry" || !(Number(retry.next) > 0)) return void 0;
1559
+ const cause = asString(retry.message)?.trim() || "no reason given";
1560
+ return `The model provider refused the call (${cause}), so the turn retries at ${utcTime(new Date(Number(retry.next)))}.`;
1561
+ }
1562
+ function providerResetSentence(message) {
1563
+ const at = new Date(message.match(/reset at (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/)?.[1] ?? NaN);
1564
+ if (Number.isNaN(at.getTime())) return void 0;
1565
+ const cause = message.split("; the provider asked")[0]?.trim();
1566
+ return `The model provider refused the call (${cause}); try again after ${utcTime(at)} on ${at.toISOString().slice(0, 10)}.`;
1567
+ }
1568
+ var MODEL_KEY_REFUSED_CODE = "model.key_refused";
1569
+ function modelKeyRefusedSentence(message) {
1570
+ if (!/\binvalid api key\b|\b401\b[^\n]*\b(?:unauthori[sz]ed|api key)\b/i.test(message)) return void 0;
1571
+ return "The assistant's model refused its access key, so this message was not answered. If the assistant has just started, send it again in a minute; if this repeats, tell the team.";
1572
+ }
1573
+ var ROUTER_REFUSAL = new RegExp([
1574
+ "This key's (?:monthly|lifetime) budget is exhausted",
1575
+ "(?:This key's remaining budget|Your available balance), after other in-flight requests, is below \\$"
1576
+ ].join("|"));
1577
+ function routerRefusalSentence(message) {
1578
+ const at = message.search(ROUTER_REFUSAL);
1579
+ return at < 0 ? void 0 : message.slice(at).split("\n")[0].replace(/\s*\((?:exit code|killed by)[^)]*\)\s*$/, "").trim();
1580
+ }
1581
+ function plainFailureSentence(message) {
1582
+ return providerResetSentence(message) ?? modelKeyRefusedSentence(message) ?? routerRefusalSentence(message);
1583
+ }
1584
+ function sandboxStreamErrorMessage(data) {
1585
+ const record = asRecord(data);
1586
+ const message = asString(record?.message) ?? asString(record?.error);
1587
+ if (message) return message;
1588
+ try {
1589
+ return JSON.stringify(data) || "Sandbox stream returned an error event without details.";
1590
+ } catch {
1591
+ return "Sandbox stream returned an error event without details.";
1592
+ }
1593
+ }
1594
+ function sandboxStreamErrorCode(data) {
1595
+ return asString(asRecord(data)?.code) ?? "sandbox.stream_error";
1596
+ }
1597
+ function plainFailureEvent(event) {
1598
+ const data = asRecord(event.data);
1599
+ if (!data || !["error", "warning", "done", "session.run.failed"].includes(String(event.type))) return event;
1600
+ const reasons = ["message", "error", "reason"].filter((key) => typeof data[key] === "string" && data[key]);
1601
+ const raw = reasons.map((key) => data[key]).join(" | ");
1602
+ const plain = reasons.map((key) => plainFailureSentence(data[key])).find((sentence) => sentence !== void 0);
1603
+ if (!plain) return event;
1604
+ return { ...event, data: { ...data, ...Object.fromEntries(reasons.map((key) => [key, plain])), details: { ...asRecord(data.details), raw } } };
1605
+ }
1606
+ var FAILED_TURN_TEXT = "That answer stopped before it finished. Please send your question again.";
1607
+ var REFUSAL_CODES = /* @__PURE__ */ new Set([
1608
+ "PAYMENT_REQUIRED",
1609
+ "MODEL_REFUSED",
1610
+ "model_policy_denied",
1611
+ "grant_model_unsupported",
1612
+ "grant_activation_missing",
1613
+ "profile_unsupported"
1614
+ ]);
1615
+ function withheld(log, reason, code, status, meta = {}) {
1616
+ const passes = Number(status) === 402 || REFUSAL_CODES.has(code ?? "") || plainFailureSentence(reason) || getChatFundingRecovery({ code, message: reason });
1617
+ if (!passes) {
1618
+ (log ?? console.warn)(
1619
+ "[chat-routes] turn failure withheld from the person",
1620
+ { failureClass: "runtime_failure", code, error: reason, ...meta }
1621
+ );
1622
+ }
1623
+ return !passes;
1624
+ }
1625
+ function failureIds(source) {
1626
+ const record = asRecord(source);
1627
+ return Object.fromEntries(["turnId", "threadId", "sessionId", "executionId"].flatMap((key) => typeof record?.[key] === "string" && record[key] ? [[key, record[key]]] : []));
1628
+ }
1629
+ var TEXT_DETAILS = /* @__PURE__ */ new Set(["supportDetails", "hint", "failureNote", "raw"]);
1630
+ function withheldFailureEvent(event, text) {
1631
+ const data = asRecord(event.data) ?? {};
1632
+ const details = Object.entries(asRecord(data.details) ?? {}).filter(([key]) => !TEXT_DETAILS.has(key));
1633
+ const shown = { ...data, message: text };
1634
+ delete shown.details;
1635
+ for (const key of ["error", "reason"]) if (typeof shown[key] === "string") shown[key] = text;
1636
+ if (details.length > 0) shown.details = Object.fromEntries(details);
1637
+ return { ...event, data: Object.assign(shown, { [WITHHELD_FAILURE]: data }) };
1638
+ }
1639
+ function noModelAllowed(error) {
1640
+ return error.attempts.length > 0 && error.attempts.every((attempt) => attempt.reason?.includes(" is not admitted by policy: "));
1641
+ }
1642
+ function sandboxStreamFailureDiagnostic(error) {
1643
+ const streamMessage = error?.streamMessage;
1644
+ const message = typeof streamMessage === "string" ? streamMessage : error instanceof Error ? error.message : "Sandbox stream failed";
1645
+ const diagnostics = asRecord(error?.diagnostics);
1646
+ let diagnosticText;
1647
+ if (diagnostics) {
1648
+ try {
1649
+ diagnosticText = JSON.stringify(diagnostics);
1650
+ } catch {
1651
+ diagnosticText = "[unserializable diagnostics]";
1652
+ }
1653
+ }
1654
+ const failureNote = diagnosticText ? `sandbox-stream: ${message}; ${diagnosticText}` : `sandbox-stream: ${message}`;
1655
+ const ownCode = asString(asRecord(error)?.code);
1656
+ let code = "sandbox.stream_failed";
1657
+ if (error instanceof SandboxRunError) {
1658
+ code = error.code;
1659
+ } else if (error instanceof ModelFailoverTimeoutError) {
1660
+ code = error.code;
1661
+ } else if (error instanceof ModelFailoverExhaustedError) {
1662
+ code = noModelAllowed(error) ? "model_policy_denied" : error.upstreamCode ?? code;
1663
+ } else if (ownCode && REFUSAL_CODES.has(ownCode)) {
1664
+ code = ownCode;
1665
+ }
1666
+ if (modelKeyRefusedSentence(message)) code = MODEL_KEY_REFUSED_CODE;
1667
+ const userMessage = plainFailureSentence(message) ?? (REFUSAL_CODES.has(code) ? message : [
1668
+ "The sandbox model stream stopped before a clean completion.",
1669
+ `Error: ${message}`,
1670
+ "Please retry. If it repeats, send these support details to the team."
1671
+ ].join("\n\n"));
1672
+ return { userMessage, failureNote, code, reason: message };
1673
+ }
1674
+ var UNAVAILABLE_TOOL_TEXT = "That tool isn't available.";
1675
+ function withoutToolListTail(value) {
1676
+ if (typeof value === "string") return value.includes("Available tools:") ? value.replace(/\s*Available tools:[\s\S]*$/, "") : value;
1677
+ if (Array.isArray(value)) return value.map(withoutToolListTail);
1678
+ const record = asRecord(value);
1679
+ return record ? Object.fromEntries(Object.entries(record).map(([key, item]) => [key, withoutToolListTail(item)])) : value;
1680
+ }
1681
+ function withoutToolList(part) {
1682
+ const shown = withoutToolListTail(part);
1683
+ if (shown.tool !== "invalid") return shown;
1684
+ const state = { ...asRecord(shown.state), input: { ...asRecord(asRecord(shown.state)?.input), error: UNAVAILABLE_TOOL_TEXT } };
1685
+ for (const key of ["output", "error"]) if (typeof state[key] === "string") state[key] = UNAVAILABLE_TOOL_TEXT;
1686
+ return { ...shown, state };
1687
+ }
1688
+
1373
1689
  // src/chat-routes/sandbox-model-source.ts
1374
1690
  function parseEffectiveBackend(data) {
1375
1691
  const backend = asRecord(data.effectiveBackend);
@@ -1426,11 +1742,10 @@ function createSandboxModelSource(options, log) {
1426
1742
  id: `model-fallback-${modelNoticeCount}`,
1427
1743
  // Named models on both sides: a quality regression after a downgrade
1428
1744
  // must be attributable to the model that actually answered. The
1429
- // REASON is condensed — a real edge 5xx arrives as Cloudflare's HTML
1430
- // error page, and the raw text put `<!DOCTYPE html><!--[if lt IE 7]>…`
1431
- // into the customer's transcript. The verbatim text is still on
1432
- // `modelFailover.attempts[].reason` for the operator.
1433
- text: `${info.from} was unavailable (${summarizeFailoverReason(info.reason)}) \u2014 answered with ${info.to} instead.`
1745
+ // reason stays off the transcript (an upstream's own text can be an
1746
+ // HTML error page or a harness report); the failover stream logs it,
1747
+ // and `modelFailover.attempts[].reason` keeps it for the operator.
1748
+ text: `The model ${info.from} stopped; trying ${info.to}.`
1434
1749
  });
1435
1750
  options.onModelFallback?.(info);
1436
1751
  }
@@ -1524,82 +1839,13 @@ function applyTerminalUsage(reported, usage) {
1524
1839
  if (reported.cacheWriteTokens !== void 0) usage.cacheWriteTokens = reported.cacheWriteTokens;
1525
1840
  if (reported.harnessCostUsd !== void 0) usage.harnessCostUsd = reported.harnessCostUsd;
1526
1841
  }
1527
- var utcTime = (at) => `${at.toISOString().slice(11, 19)} UTC`;
1528
- function providerRetryNotice(event) {
1529
- const retry = event.type === "raw" ? asRecord(asRecord(event.data)?.event) : void 0;
1530
- if (retry?.type !== "retry" || !(Number(retry.next) > 0)) return void 0;
1531
- const cause = asString(retry.message)?.trim() || "no reason given";
1532
- return `The model provider refused the call (${cause}), so the turn retries at ${utcTime(new Date(Number(retry.next)))}.`;
1533
- }
1534
- function providerResetSentence(message) {
1535
- const at = new Date(message.match(/reset at (\d{4}-\d{2}-\d{2}T[\d:.]+Z)/)?.[1] ?? NaN);
1536
- if (Number.isNaN(at.getTime())) return void 0;
1537
- const cause = message.split("; the provider asked")[0]?.trim();
1538
- return `The model provider refused the call (${cause}); try again after ${utcTime(at)} on ${at.toISOString().slice(0, 10)}.`;
1539
- }
1540
- var MODEL_KEY_REFUSED_CODE = "model.key_refused";
1541
- function modelKeyRefusedSentence(message) {
1542
- if (!/\binvalid api key\b|\b401\b[^\n]*\b(?:unauthori[sz]ed|api key)\b/i.test(message)) return void 0;
1543
- return "The assistant's model refused its access key, so this message was not answered. If the assistant has just started, send it again in a minute; if this repeats, tell the team.";
1544
- }
1545
- function sandboxStreamErrorMessage(data) {
1546
- const record = asRecord(data);
1547
- const message = asString(record?.message) ?? asString(record?.error);
1548
- if (message) return message;
1549
- try {
1550
- return JSON.stringify(data) || "Sandbox stream returned an error event without details.";
1551
- } catch {
1552
- return "Sandbox stream returned an error event without details.";
1553
- }
1554
- }
1555
- function sandboxStreamErrorCode(data) {
1556
- return asString(asRecord(data)?.code) ?? "sandbox.stream_error";
1557
- }
1558
1842
  function toProducerWireEvent(event) {
1559
1843
  return event;
1560
1844
  }
1561
- function plainFailureEvent(event) {
1562
- const data = asRecord(event.data);
1563
- if (!data || !["error", "warning", "done", "session.run.failed"].includes(String(event.type))) return event;
1564
- const reasons = ["message", "error", "reason"].filter((key) => typeof data[key] === "string" && data[key]);
1565
- const raw = reasons.map((key) => data[key]).join(" | ");
1566
- const plain = raw ? providerResetSentence(raw) ?? modelKeyRefusedSentence(raw) : void 0;
1567
- if (!plain) return event;
1568
- return { ...event, data: { ...data, ...Object.fromEntries(reasons.map((key) => [key, plain])), details: { ...asRecord(data.details), raw } } };
1569
- }
1570
- function sandboxStreamFailureDiagnostic(error) {
1571
- const streamMessage = error?.streamMessage;
1572
- const message = typeof streamMessage === "string" ? streamMessage : error instanceof Error ? error.message : "Sandbox stream failed";
1573
- const diagnostics = asRecord(error?.diagnostics);
1574
- let diagnosticText;
1575
- if (diagnostics) {
1576
- try {
1577
- diagnosticText = JSON.stringify(diagnostics);
1578
- } catch {
1579
- diagnosticText = "[unserializable diagnostics]";
1580
- }
1581
- }
1582
- const keyRefused = modelKeyRefusedSentence(message);
1583
- const userMessage = providerResetSentence(message) ?? keyRefused ?? [
1584
- "The sandbox model stream stopped before a clean completion.",
1585
- `Error: ${message}`,
1586
- "Please retry. If it repeats, send these support details to the team."
1587
- ].join("\n\n");
1588
- const failureNote = diagnosticText ? `sandbox-stream: ${message}; ${diagnosticText}` : `sandbox-stream: ${message}`;
1589
- let code = "sandbox.stream_failed";
1590
- if (error instanceof SandboxRunError) {
1591
- code = error.code;
1592
- } else if (error instanceof ModelFailoverTimeoutError) {
1593
- code = error.code;
1594
- } else if (error instanceof ModelFailoverExhaustedError) {
1595
- code = error.upstreamCode ?? code;
1596
- }
1597
- if (keyRefused) code = MODEL_KEY_REFUSED_CODE;
1598
- return { userMessage, failureNote, code };
1599
- }
1600
1845
  function createSandboxChatProducer(options) {
1601
1846
  const log = options.log ?? ((message, meta) => console.error(message, meta ?? ""));
1602
1847
  const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind;
1848
+ const failedTurnText = options.failedTurnText ?? FAILED_TURN_TEXT;
1603
1849
  const { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState, openAttempts } = createSandboxModelSource(options, log);
1604
1850
  const projectionState = {
1605
1851
  fullText: "",
@@ -1702,7 +1948,7 @@ function createSandboxChatProducer(options) {
1702
1948
  }
1703
1949
  if (event.type === "warning") {
1704
1950
  const message = asString(event.data?.message);
1705
- const plainFailure = message && (providerResetSentence(message) ?? modelKeyRefusedSentence(message));
1951
+ const plainFailure = message && plainFailureSentence(message);
1706
1952
  if (plainFailure) log("[chat-routes] failure warning folded into its error notice", { code: asString(event.data?.code), error: message });
1707
1953
  if (message && !plainFailure) {
1708
1954
  projectionState.warningCount += 1;
@@ -1756,7 +2002,8 @@ function createSandboxChatProducer(options) {
1756
2002
  const message = sandboxStreamErrorMessage(event.data);
1757
2003
  const keyRefused = modelKeyRefusedSentence(message);
1758
2004
  if (keyRefused) log("[chat-routes] model key refused", { code: MODEL_KEY_REFUSED_CODE, error: message });
1759
- const errorContent = providerResetSentence(message) ?? keyRefused ?? (projectionState.fullText.trim() ? `The sandbox model stream stopped before a clean completion.
2005
+ const hidden = withheld(options.log, message, asString(event.data?.code), event.data?.statusCode ?? event.data?.status, failureIds(event.data));
2006
+ const errorContent = hidden ? failedTurnText : plainFailureSentence(message) ?? (projectionState.fullText.trim() ? `The sandbox model stream stopped before a clean completion.
1760
2007
 
1761
2008
  Error: ${message}` : `The sandbox agent returned an error before producing a visible answer.
1762
2009
 
@@ -1773,7 +2020,7 @@ ${errorContent}` : errorContent;
1773
2020
  }
1774
2021
  projectionState.interactionOutcome = "expired";
1775
2022
  yield* emitTerminalizedTools();
1776
- yield toProducerWireEvent(plainFailureEvent(record));
2023
+ yield toProducerWireEvent(hidden ? withheldFailureEvent(record, failedTurnText) : plainFailureEvent(record));
1777
2024
  continue;
1778
2025
  }
1779
2026
  yield toProducerWireEvent(plainFailureEvent(record));
@@ -1782,30 +2029,36 @@ ${errorContent}` : errorContent;
1782
2029
  } catch (streamErr) {
1783
2030
  preflightRefused = !observedSourceEvent && openAttempts() === 1 && streamErr instanceof SandboxRunError && streamErr.code === "sandbox_unavailable";
1784
2031
  const diagnostic = sandboxStreamFailureDiagnostic(streamErr);
1785
- log("[chat-routes] sandbox stream failed", {
2032
+ const hidden = withheld(
2033
+ options.log,
2034
+ diagnostic.reason,
2035
+ diagnostic.code,
2036
+ asRecord(streamErr)?.statusCode ?? asRecord(streamErr)?.status,
2037
+ { ...failureIds(asRecord(streamErr)?.diagnostics), failureNote: diagnostic.failureNote }
2038
+ );
2039
+ if (!hidden) log("[chat-routes] sandbox stream failed", {
1786
2040
  failureNote: diagnostic.failureNote,
1787
2041
  error: streamErr instanceof Error ? streamErr.message : String(streamErr)
1788
2042
  });
2043
+ const userMessage = hidden ? failedTurnText : diagnostic.userMessage;
1789
2044
  if (options.errorNotice) {
1790
- yield* emitErrorNotice(diagnostic.userMessage, diagnostic.code);
2045
+ yield* emitErrorNotice(userMessage, diagnostic.code);
1791
2046
  } else if (options.includeErrorText !== false) {
1792
2047
  const errorDelta = projectionState.fullText ? `
1793
2048
 
1794
2049
  ---
1795
- ${diagnostic.userMessage}` : diagnostic.userMessage;
2050
+ ${userMessage}` : userMessage;
1796
2051
  projectionState.fullText += errorDelta;
1797
2052
  yield { type: "text", text: errorDelta };
1798
2053
  }
1799
2054
  projectionState.interactionOutcome = "expired";
1800
2055
  yield* emitTerminalizedTools();
1801
- yield {
1802
- type: "error",
1803
- data: {
1804
- message: diagnostic.userMessage,
1805
- code: diagnostic.code,
1806
- details: { failureNote: diagnostic.failureNote }
1807
- }
1808
- };
2056
+ const failure = { type: "error", data: {
2057
+ message: hidden ? diagnostic.reason : userMessage,
2058
+ code: diagnostic.code,
2059
+ details: { failureNote: diagnostic.failureNote }
2060
+ } };
2061
+ yield toProducerWireEvent(hidden ? withheldFailureEvent(failure, failedTurnText) : failure);
1809
2062
  } finally {
1810
2063
  reasoningClock.settle();
1811
2064
  }
@@ -1941,7 +2194,7 @@ async function* projectSandboxMessagePart(event, tracker, recordPersistedPart, r
1941
2194
  }
1942
2195
  if (partType === "tool") {
1943
2196
  reasoningClock.settle();
1944
- recordPersistedPart(part, void 0);
2197
+ recordPersistedPart(withoutToolList(part), void 0);
1945
2198
  const persisted = partMap.get(getPartKey(part));
1946
2199
  const state = asRecord(persisted?.state);
1947
2200
  const toolId = String(persisted?.id ?? "");
@@ -2747,176 +3000,6 @@ function dispatchFirstFor(selected, args, trace) {
2747
3000
  return selected.router && !args.userMessageId ? dispatchProducerFirst(selected.produce, args, trace) : void 0;
2748
3001
  }
2749
3002
 
2750
- // src/chat-routes/turn-event-stream.ts
2751
- function failureReasonOf(data) {
2752
- if (!data) return void 0;
2753
- const message = data.message ?? data.error ?? data.reason;
2754
- if (typeof message === "string" && message.length > 0) return message;
2755
- return void 0;
2756
- }
2757
- function failureCodeOf(data) {
2758
- const code = data?.code;
2759
- return typeof code === "string" && code.length > 0 ? code : void 0;
2760
- }
2761
- function isVisibleText(event) {
2762
- const value = event;
2763
- if (event.type === "text") return typeof value.text === "string" ? value.text.trim().length > 0 : true;
2764
- if (event.type !== "message.part.updated") return false;
2765
- const part = event.data?.part;
2766
- const delta = event.data?.delta;
2767
- return part?.type === "text" && typeof delta === "string" && delta.trim().length > 0;
2768
- }
2769
- function isVisibleOutput(event) {
2770
- if (isVisibleText(event)) return true;
2771
- const value = event;
2772
- if (event.type === "reasoning") return typeof value.text === "string" && value.text.trim().length > 0;
2773
- if (event.type === "tool_call" || event.type === "tool.call" || event.type === "tool_result" || event.type === "tool.result" || event.type === "tool.event") return true;
2774
- if (event.type !== "message.part.updated") return false;
2775
- const part = event.data?.part;
2776
- if (part?.type === "tool") return true;
2777
- if (part?.type !== "reasoning" && part?.type !== "text") return false;
2778
- const text = event.data?.delta ?? part.text;
2779
- return typeof text === "string" && text.trim().length > 0;
2780
- }
2781
- async function* tapRawEvents(source, onRawEvent, log) {
2782
- for await (const event of source) {
2783
- try {
2784
- await onRawEvent(event);
2785
- } catch (err) {
2786
- log("[chat-routes] onRawEvent failed", { error: err instanceof Error ? err.message : String(err) });
2787
- }
2788
- yield event;
2789
- }
2790
- }
2791
- async function* withStreamHeartbeat(source, intervalMs, makeEvent) {
2792
- const iterator = source[Symbol.asyncIterator]();
2793
- try {
2794
- let pending = iterator.next();
2795
- let windowStart = Date.now();
2796
- let tick = 0;
2797
- for (; ; ) {
2798
- let timer;
2799
- let winner;
2800
- try {
2801
- const heartbeat = new Promise((resolve) => {
2802
- timer = setTimeout(() => resolve("heartbeat"), intervalMs);
2803
- });
2804
- winner = await Promise.race([pending.then(() => "event"), heartbeat]);
2805
- } finally {
2806
- if (timer !== void 0) clearTimeout(timer);
2807
- }
2808
- if (winner === "heartbeat") {
2809
- tick += 1;
2810
- yield makeEvent({ elapsedMs: Date.now() - windowStart, tick });
2811
- continue;
2812
- }
2813
- const result = await pending;
2814
- if (result.done) return;
2815
- yield result.value;
2816
- pending = iterator.next();
2817
- windowStart = Date.now();
2818
- tick = 0;
2819
- }
2820
- } finally {
2821
- await iterator.return?.();
2822
- }
2823
- }
2824
- function concatStreams(streams) {
2825
- let index = 0;
2826
- let reader = null;
2827
- return new ReadableStream({
2828
- async pull(controller) {
2829
- for (; ; ) {
2830
- if (!reader) {
2831
- const next = streams[index++];
2832
- if (!next) {
2833
- controller.close();
2834
- return;
2835
- }
2836
- reader = next.getReader();
2837
- }
2838
- const { done, value } = await reader.read();
2839
- if (done) {
2840
- reader = null;
2841
- continue;
2842
- }
2843
- controller.enqueue(value);
2844
- return;
2845
- }
2846
- },
2847
- async cancel(reason) {
2848
- await reader?.cancel(reason);
2849
- for (const stream of streams.slice(index)) await stream.cancel(reason);
2850
- }
2851
- });
2852
- }
2853
- async function* abortOnSignal(source, signal) {
2854
- const iterator = source[Symbol.asyncIterator]();
2855
- try {
2856
- for (; ; ) {
2857
- const next = await nextWithAbort(iterator, signal);
2858
- if (next.done) return;
2859
- yield next.value;
2860
- }
2861
- } finally {
2862
- await closeIteratorAfterAbort(iterator);
2863
- }
2864
- }
2865
- function nextWithAbort(iterator, signal) {
2866
- if (signal.aborted) return Promise.reject(new Error("chat turn cancelled"));
2867
- return new Promise((resolve, reject) => {
2868
- let settled = false;
2869
- const cleanup = () => signal.removeEventListener("abort", onAbort);
2870
- const onAbort = () => {
2871
- if (settled) return;
2872
- settled = true;
2873
- cleanup();
2874
- reject(new Error("chat turn cancelled"));
2875
- };
2876
- signal.addEventListener("abort", onAbort, { once: true });
2877
- if (signal.aborted) {
2878
- onAbort();
2879
- return;
2880
- }
2881
- Promise.resolve().then(() => iterator.next()).then(
2882
- (result) => {
2883
- if (settled) return;
2884
- settled = true;
2885
- cleanup();
2886
- resolve(result);
2887
- },
2888
- (error) => {
2889
- if (settled) return;
2890
- settled = true;
2891
- cleanup();
2892
- reject(error);
2893
- }
2894
- );
2895
- });
2896
- }
2897
- var ABORT_CLEANUP_TIMEOUT_MS = 50;
2898
- async function closeIteratorAfterAbort(iterator) {
2899
- let closing;
2900
- try {
2901
- const result = iterator.return?.();
2902
- if (result) closing = Promise.resolve(result);
2903
- } catch {
2904
- return;
2905
- }
2906
- if (!closing) return;
2907
- let timeout;
2908
- try {
2909
- await Promise.race([
2910
- Promise.resolve(closing).catch(() => void 0),
2911
- new Promise((resolve) => {
2912
- timeout = setTimeout(resolve, ABORT_CLEANUP_TIMEOUT_MS);
2913
- })
2914
- ]);
2915
- } finally {
2916
- if (timeout !== void 0) clearTimeout(timeout);
2917
- }
2918
- }
2919
-
2920
3003
  // src/chat-routes/turn-execution.ts
2921
3004
  async function readTurnHistory(store, threadId) {
2922
3005
  return (await store.listMessages(threadId)).map((m) => ({
@@ -3451,7 +3534,7 @@ function createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, tr
3451
3534
  }
3452
3535
  if (event.type === "session.run.failed" || event.type === "error") {
3453
3536
  state.runFailed = true;
3454
- state.lastFailureData = event.data;
3537
+ state.lastFailureData = serverFailureData(event.data);
3455
3538
  }
3456
3539
  await state.tap.onEvent(event);
3457
3540
  if (!state.completionHandoff) state.draft?.notify(event);
@@ -3866,6 +3949,22 @@ function createChatTurnRoutes(input) {
3866
3949
  startIntentLine,
3867
3950
  log
3868
3951
  });
3952
+ const turnHost = input.turnHost && { locationHint: turnStorageBindings(input)?.region, ...input.turnHost };
3953
+ async function hostTurn(host, request, ctx) {
3954
+ try {
3955
+ const response = await forwardTurnToHost(host, request.clone());
3956
+ void request.body?.cancel().catch(() => {
3957
+ });
3958
+ return response;
3959
+ } catch (err) {
3960
+ if (err?.remote === true) throw err;
3961
+ log("[chat-routes] turn host unavailable; the turn runs in this request", {
3962
+ class: "turn_host_unavailable",
3963
+ error: err instanceof Error ? err.name : typeof err
3964
+ });
3965
+ return withD1QueryCount(() => turn(request, ctx));
3966
+ }
3967
+ }
3869
3968
  async function turn(request, ctx) {
3870
3969
  const requestContext = ctx?.waitUntil ? { ...ctx, waitUntil: ctx.waitUntil.bind(ctx) } : ctx;
3871
3970
  const admitted = await admitTurn(request, createTurnTrace({ d1QueryCounter: currentD1QueryCounter() }), options, requestContext?.waitUntil);
@@ -4035,7 +4134,8 @@ function createChatTurnRoutes(input) {
4035
4134
  }
4036
4135
  return {
4037
4136
  prewarm: createChatPrewarm(input, backend?.prewarm),
4038
- turn: (request, ctx) => withD1QueryCount(() => turn(request, ctx)),
4137
+ // A request with no credential runs here, where `authorize` refuses it, so it never costs an object.
4138
+ turn: (request, ctx) => turnHost && !ctx?.hosted && ctx?.executionLimits === void 0 && ctx?.cancelOnDisconnect !== true && (request.headers.has("cookie") || request.headers.has("authorization")) ? hostTurn(turnHost, request, ctx) : withD1QueryCount(() => turn(request, ctx)),
4039
4139
  cancel: (request) => cancelChatTurn(request, { authorize: options.authorize, cancel: options.cancel, log }),
4040
4140
  replay,
4041
4141
  running,
@@ -4270,4 +4370,4 @@ export {
4270
4370
  createChatTurnRoutes,
4271
4371
  streamChatRouteAsSandboxEvents
4272
4372
  };
4273
- //# sourceMappingURL=chunk-4OR7NNYB.js.map
4373
+ //# sourceMappingURL=chunk-XZ37VCTP.js.map