deepline 0.3.530 → 0.3.531

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 (139) hide show
  1. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  2. package/dist/bundling-sources/shared_libs/monitors/fleets/limits.ts +6 -0
  3. package/dist/bundling-sources/shared_libs/play-data-plane/r2.ts +10 -8
  4. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +95 -9
  5. package/dist/bundling-sources/shared_libs/play-runtime/ctx-types.ts +7 -0
  6. package/dist/bundling-sources/shared_libs/play-runtime/durable-summary-events.ts +615 -0
  7. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +16 -1
  8. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +26 -8
  9. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +27 -0
  10. package/dist/bundling-sources/shared_libs/play-runtime/tool-call-retry-facts.ts +317 -0
  11. package/dist/bundling-sources/shared_libs/play-runtime/tool-execute-retry-policy.ts +129 -39
  12. package/dist/cli/{auth-LRWNDQFT.mjs → auth-33B3OEM4.mjs} +5 -5
  13. package/dist/cli/auth-3UDRBF5D.js +43 -0
  14. package/dist/cli/{billing-7T73MRYF.mjs → billing-X4OQRH6D.mjs} +7 -7
  15. package/dist/cli/{billing-5FDPWGCG.js → billing-Y2M2ABLW.js} +82 -82
  16. package/dist/cli/{chunk-5DJUNUHN.mjs → chunk-2CUPFDW5.mjs} +5 -5
  17. package/dist/cli/{chunk-V4EK7ZZX.js → chunk-2WWTIR2G.js} +98 -98
  18. package/dist/cli/{chunk-YI7QOP6L.js → chunk-3PMVNMG4.js} +16 -16
  19. package/dist/cli/{chunk-2FLODRM2.js → chunk-4M4AASO3.js} +13 -13
  20. package/dist/cli/{chunk-KUHH7RW4.js → chunk-4O7UET74.js} +44 -44
  21. package/dist/cli/{chunk-VYSQ76RP.js → chunk-4WPHK2R3.js} +7 -7
  22. package/dist/cli/{chunk-YVLPGYRS.mjs → chunk-567HD6G6.mjs} +1 -1
  23. package/dist/cli/{chunk-QWEPCX6L.mjs → chunk-57PPAYDB.mjs} +2 -2
  24. package/dist/cli/{chunk-SJQ7Z3NI.js → chunk-5M24K577.js} +132 -81
  25. package/dist/cli/{chunk-4VQ63Y6S.mjs → chunk-623FFVZU.mjs} +5 -5
  26. package/dist/cli/{chunk-QI2LKPW5.mjs → chunk-6W73VXMK.mjs} +2 -2
  27. package/dist/cli/{chunk-7E7CP5KA.js → chunk-BUK6WHY2.js} +4 -4
  28. package/dist/cli/{chunk-QQ4LNSY5.mjs → chunk-CVOFP6BU.mjs} +1 -1
  29. package/dist/cli/{chunk-4WPIORJX.js → chunk-D5BLTX5L.js} +1 -1
  30. package/dist/cli/{chunk-E6L3NEFV.js → chunk-DWYX5DFJ.js} +41 -41
  31. package/dist/cli/{chunk-K4Y6CNFV.mjs → chunk-EURLINZT.mjs} +1 -1
  32. package/dist/cli/{chunk-7FCD34YS.mjs → chunk-EVXRQXNV.mjs} +3 -2
  33. package/dist/cli/{chunk-L4QR7CYL.js → chunk-H26ZSNLX.js} +14 -14
  34. package/dist/cli/{chunk-6NG3FRJB.mjs → chunk-HYPLMUMA.mjs} +5 -5
  35. package/dist/cli/{chunk-M4Q4LEMM.js → chunk-IOOWKPF7.js} +2 -2
  36. package/dist/cli/{chunk-MHR3XVJD.js → chunk-IXOEKHOY.js} +5 -5
  37. package/dist/cli/{chunk-32NTC5UD.js → chunk-JFTO33FK.js} +7 -7
  38. package/dist/cli/{chunk-VKVLJTW5.js → chunk-L4XVL4LW.js} +9 -9
  39. package/dist/cli/{chunk-MVF7ZBJX.mjs → chunk-MGWYYTZN.mjs} +1 -1
  40. package/dist/cli/{chunk-2LKVNWRA.mjs → chunk-MYTA37IL.mjs} +10 -10
  41. package/dist/cli/{chunk-D7Y7I4EE.js → chunk-NXEQMKSM.js} +2 -2
  42. package/dist/cli/{chunk-EADHDZW2.js → chunk-O267YGUV.js} +6 -6
  43. package/dist/cli/{chunk-X547OW3I.js → chunk-O4NTPEQV.js} +16 -16
  44. package/dist/cli/{chunk-LNZILMVK.mjs → chunk-O7EFJR6Y.mjs} +4 -4
  45. package/dist/cli/{chunk-GW76IDID.js → chunk-PTKSHGUM.js} +22 -22
  46. package/dist/cli/{chunk-J6XSBTEX.mjs → chunk-PTOPMO22.mjs} +1 -1
  47. package/dist/cli/{chunk-WWLIDAVT.js → chunk-RBPCXQBE.js} +11 -11
  48. package/dist/cli/{chunk-5B37ER3C.js → chunk-RLRPEHQ3.js} +3 -3
  49. package/dist/cli/{chunk-C44RZGM5.js → chunk-RZXSCWEB.js} +26 -26
  50. package/dist/cli/{chunk-OUM2V7R6.mjs → chunk-SPODXGBZ.mjs} +6 -6
  51. package/dist/cli/{chunk-KEXGBXUG.js → chunk-TDJCNVDE.js} +5 -5
  52. package/dist/cli/{chunk-KI63L5H3.mjs → chunk-TU7HU5K2.mjs} +2 -2
  53. package/dist/cli/{chunk-HCWPX2UP.mjs → chunk-U5YBINPF.mjs} +2 -2
  54. package/dist/cli/{chunk-ERMDXXP5.mjs → chunk-UNTFERUX.mjs} +1 -1
  55. package/dist/cli/{chunk-WL6GAZBD.js → chunk-V6LUMGVI.js} +3 -2
  56. package/dist/cli/{chunk-3MAHDV5C.mjs → chunk-VGWUCBNA.mjs} +1 -1
  57. package/dist/cli/{chunk-5KX3TWBK.mjs → chunk-VHIHGMZD.mjs} +1 -1
  58. package/dist/cli/{chunk-A5MYJM4K.mjs → chunk-VWOOOU6G.mjs} +2 -2
  59. package/dist/cli/{chunk-WYI3VMTO.js → chunk-WDLY4HST.js} +6 -6
  60. package/dist/cli/{chunk-7WGMCOM6.js → chunk-WHAMLN6B.js} +2 -2
  61. package/dist/cli/{chunk-BVY4QRVT.mjs → chunk-XOXKVLJZ.mjs} +82 -31
  62. package/dist/cli/{chunk-2FLRKNME.mjs → chunk-XQGLHKDI.mjs} +2 -2
  63. package/dist/cli/{chunk-XNWS2WJG.mjs → chunk-XWQI4TMS.mjs} +1 -1
  64. package/dist/cli/{chunk-VQMGCNX2.mjs → chunk-YMGQP7WI.mjs} +5 -5
  65. package/dist/cli/{chunk-WAWOMHWO.mjs → chunk-YVOFNLGN.mjs} +2 -2
  66. package/dist/cli/{chunk-MVFKZQ7E.js → chunk-ZBL4CP75.js} +3 -3
  67. package/dist/cli/{chunk-I2YXEHDO.mjs → chunk-ZJQITGPV.mjs} +3 -3
  68. package/dist/cli/command-docs.js +2 -2
  69. package/dist/cli/command-docs.mjs +1 -1
  70. package/dist/cli/{csv-VY2S7KKV.mjs → csv-CMUWCM46.mjs} +4 -4
  71. package/dist/cli/{csv-EFIEDJA2.js → csv-N4P2XOKP.js} +13 -13
  72. package/dist/cli/{db-3DLI5TYW.js → db-GFI45WV5.js} +27 -27
  73. package/dist/cli/{db-D32CBDTN.mjs → db-J5HFGOUO.mjs} +6 -6
  74. package/dist/cli/describe-HFUWQN3A.js +50 -0
  75. package/dist/cli/{describe-6MYKK2P3.mjs → describe-NKHH3VVI.mjs} +18 -18
  76. package/dist/cli/{executions-U6TPX4RX.mjs → executions-54QEYYE6.mjs} +6 -6
  77. package/dist/cli/{executions-QG3DEEY3.js → executions-FMWHU72C.js} +8 -8
  78. package/dist/cli/{feedback-YZ6H4VMQ.mjs → feedback-HA4QUWMU.mjs} +6 -6
  79. package/dist/cli/{feedback-ZSPW6NXL.js → feedback-R7C3AZKN.js} +14 -14
  80. package/dist/cli/git-ETBABM6D.js +25 -0
  81. package/dist/cli/{git-ENN72IK4.mjs → git-OVG63PJV.mjs} +5 -5
  82. package/dist/cli/index.js +145 -145
  83. package/dist/cli/index.mjs +44 -44
  84. package/dist/cli/{legacy-noops-Q6EVYIGN.js → legacy-noops-GM2F7GMV.js} +9 -9
  85. package/dist/cli/{legacy-noops-MNA6LWJU.mjs → legacy-noops-PLQWYZ7A.mjs} +6 -6
  86. package/dist/cli/{monitors-KENWEEWC.mjs → monitors-QXK7JTRG.mjs} +7 -7
  87. package/dist/cli/{monitors-BUH54HXJ.js → monitors-SJBIPV4K.js} +100 -100
  88. package/dist/cli/{org-HWOHKYP3.mjs → org-OFMMMVYT.mjs} +6 -6
  89. package/dist/cli/{org-AHWQJMV7.js → org-XKO7BBT4.js} +86 -86
  90. package/dist/cli/{pages-I7DYTCW6.mjs → pages-NDI2K34M.mjs} +6 -6
  91. package/dist/cli/{pages-Z5R7NYEF.js → pages-ZGXRON5S.js} +18 -18
  92. package/dist/cli/{play-3LXZB4ED.js → play-2YD5NTH6.js} +317 -317
  93. package/dist/cli/{play-ET7CRVWJ.mjs → play-SMKNTBRK.mjs} +18 -18
  94. package/dist/cli/{providers-ZV2E7NGX.js → providers-52PIA36O.js} +9 -9
  95. package/dist/cli/{providers-GZSAZVHZ.mjs → providers-6SKF5W4Y.mjs} +6 -6
  96. package/dist/cli/{quickstart-VJZAT4RY.js → quickstart-4Z22WVLK.js} +6 -6
  97. package/dist/cli/{quickstart-5746NBS2.mjs → quickstart-RVA335ED.mjs} +4 -4
  98. package/dist/cli/{run-WGUAVYZC.js → run-FDTSTMDM.js} +41 -41
  99. package/dist/cli/{run-WOQ6XMTT.mjs → run-GMN4TCVV.mjs} +23 -23
  100. package/dist/cli/{search-NNPFJYEW.mjs → search-2FG2USCF.mjs} +8 -8
  101. package/dist/cli/search-63X5FPDM.js +33 -0
  102. package/dist/cli/{search-output-K4ISMPKD.js → search-output-5FKQYLFW.js} +6 -6
  103. package/dist/cli/{search-output-65HDEEFS.mjs → search-output-AC3AAV6E.mjs} +4 -4
  104. package/dist/cli/{secrets-NBKGWMF4.js → secrets-5A7AY2YU.js} +15 -15
  105. package/dist/cli/{secrets-RK44OV3X.mjs → secrets-MA4ZTNVG.mjs} +6 -6
  106. package/dist/cli/{sessions-ULQJJN3J.mjs → sessions-LBYKV5O4.mjs} +6 -6
  107. package/dist/cli/sessions-SMWWKKD4.js +22 -0
  108. package/dist/cli/{settings-V5ZRL2EF.mjs → settings-6MQVNROV.mjs} +13 -13
  109. package/dist/cli/{settings-IHNA7X3Y.js → settings-HA3D4GNZ.js} +86 -86
  110. package/dist/cli/{setup-HTEBFMOQ.js → setup-3JWTNSOK.js} +78 -63
  111. package/dist/cli/{setup-54VZPJGM.mjs → setup-BXCUZOZH.mjs} +28 -13
  112. package/dist/cli/{skills-3FCPWMHX.mjs → skills-7ASML2WZ.mjs} +8 -8
  113. package/dist/cli/skills-OJ7NZL6S.js +37 -0
  114. package/dist/cli/{tools-2NTDNUQT.mjs → tools-7IJWJXZ3.mjs} +17 -17
  115. package/dist/cli/tools-Y2VMPUSI.js +57 -0
  116. package/dist/cli/{update-25MTBTGU.mjs → update-JFKH4SVK.mjs} +10 -10
  117. package/dist/cli/update-JURCS2FE.js +35 -0
  118. package/dist/cli/{views-OBE5LUSW.mjs → views-2EURG3P5.mjs} +6 -6
  119. package/dist/cli/{views-37K4JNNS.js → views-XTAIIX2Y.js} +18 -18
  120. package/dist/cli/{workflow-HAPCL4K6.mjs → workflow-7FCQ34QD.mjs} +7 -7
  121. package/dist/cli/{workflow-6YTIHHJH.js → workflow-AXOF74HO.js} +17 -17
  122. package/dist/index.js +9 -9
  123. package/dist/index.mjs +6 -6
  124. package/dist/install-integrity.json +108 -106
  125. package/dist/release.d.mts +1 -1
  126. package/dist/release.d.ts +1 -1
  127. package/dist/release.js +2 -2
  128. package/dist/release.mjs +1 -1
  129. package/dist/server.js +5 -5
  130. package/dist/server.mjs +3 -3
  131. package/package.json +1 -1
  132. package/dist/cli/auth-QFIXECQV.js +0 -43
  133. package/dist/cli/describe-U6HM52X6.js +0 -50
  134. package/dist/cli/git-OBV73OVY.js +0 -25
  135. package/dist/cli/search-IGHNMXI4.js +0 -33
  136. package/dist/cli/sessions-ZJNV4SEL.js +0 -22
  137. package/dist/cli/skills-ZCJ6FOOK.js +0 -37
  138. package/dist/cli/tools-Q75XC2BS.js +0 -57
  139. package/dist/cli/update-3G3GO7IE.js +0 -35
@@ -41,6 +41,10 @@ import {
41
41
  durableReplayRefusalFromRunLogLine,
42
42
  emitPlayRunReplayRefusal,
43
43
  } from '../runtime-telemetry';
44
+ import {
45
+ durableCallSummaryFromRunLogLine,
46
+ emitPlayCallFinished,
47
+ } from '../durable-summary-events';
44
48
  import {
45
49
  buildPlayRunLedgerEventsFromStatusPatch,
46
50
  createEmptyPlayRunLedgerSnapshot,
@@ -768,19 +772,33 @@ export function createPostgresSchedulerProgressReporter(input: {
768
772
  void flush({ force }).catch(() => undefined);
769
773
  };
770
774
 
771
- /** Re-emit runner replay refusals to this process's shipped log stream. */
772
- const forwardReplayRefusal = (
775
+ /**
776
+ * Re-emit the runner's durable records to this process's shipped log
777
+ * stream: replay refusals, and the outcome of each call that hit trouble.
778
+ */
779
+ const forwardDurableRecords = (
773
780
  line: string,
774
781
  attempt: number | null | undefined = producerAttempt,
775
782
  ) => {
776
783
  const refusal = durableReplayRefusalFromRunLogLine(line);
777
- if (!refusal) return;
778
- emitPlayRunReplayRefusal({
784
+ if (refusal) {
785
+ emitPlayRunReplayRefusal({
786
+ orgId: launch.orgId ?? null,
787
+ runId: launch.runId,
788
+ playName: launch.playName ?? null,
789
+ attempt: attempt ?? null,
790
+ refusal,
791
+ });
792
+ return;
793
+ }
794
+ const call = durableCallSummaryFromRunLogLine(line);
795
+ if (!call) return;
796
+ emitPlayCallFinished({
779
797
  orgId: launch.orgId ?? null,
780
798
  runId: launch.runId,
781
799
  playName: launch.playName ?? null,
782
800
  attempt: attempt ?? null,
783
- refusal,
801
+ call,
784
802
  });
785
803
  };
786
804
 
@@ -1489,7 +1507,7 @@ export function createPostgresSchedulerProgressReporter(input: {
1489
1507
  logEvent.entryId,
1490
1508
  logEvent.metadata,
1491
1509
  );
1492
- forwardReplayRefusal(rawLine);
1510
+ forwardDurableRecords(rawLine);
1493
1511
  }
1494
1512
  markMapStartedFromLog(rawLine);
1495
1513
  markMapStartedFromPerfLog(rawLine);
@@ -1796,9 +1814,9 @@ export function createPostgresSchedulerProgressReporter(input: {
1796
1814
  replayAllTerminalLogs: options.replayAllTerminalLogs === true,
1797
1815
  producerAttempt: terminalReplayAttempt,
1798
1816
  });
1799
- // A detached runner that streamed no events delivers its refusals here.
1817
+ // A detached runner that streamed no events delivers its records here.
1800
1818
  for (const line of terminalLogReplay?.lines ?? []) {
1801
- forwardReplayRefusal(line, terminalReplayAttempt);
1819
+ forwardDurableRecords(line, terminalReplayAttempt);
1802
1820
  }
1803
1821
  await flush({
1804
1822
  force: true,
@@ -295,6 +295,10 @@ import {
295
295
  emitPlayRunLaunchConflictTelemetry,
296
296
  emitPlayTelemetry,
297
297
  } from '../runtime-telemetry';
298
+ import {
299
+ emitPlayRunFinished,
300
+ playRunFailureDetailsOf,
301
+ } from '../durable-summary-events';
298
302
  import { buildAbsurdPlayRunTask } from './absurd-play-run-task';
299
303
  import {
300
304
  buildAbsurdCronFireTask,
@@ -18474,6 +18478,18 @@ export async function executePostgresSchedulerClaim(
18474
18478
  `Postgres scheduler worker lost lease for ${claim.runId}/${claim.attempt}.`,
18475
18479
  );
18476
18480
  }
18481
+ // The fenced statement committed this run's terminal transition.
18482
+ emitPlayRunFinished({
18483
+ orgId: claim.launch.orgId ?? null,
18484
+ runId: claim.runId,
18485
+ playName: claim.launch.playName ?? null,
18486
+ attempt: claim.attempt,
18487
+ outcome: 'completed',
18488
+ failure: null,
18489
+ runtimeBackend: claim.launch.runtimeBackend ?? null,
18490
+ triggerSource: claim.launch.triggerSource ?? null,
18491
+ committedBy: 'worker',
18492
+ });
18477
18493
  return {
18478
18494
  status: 'completed',
18479
18495
  runId: claim.runId,
@@ -18558,6 +18574,17 @@ export async function executePostgresSchedulerClaim(
18558
18574
  `Postgres scheduler worker failed after losing lease for ${claim.runId}/${claim.attempt}: ${message}`,
18559
18575
  );
18560
18576
  }
18577
+ emitPlayRunFinished({
18578
+ orgId: claim.launch.orgId ?? null,
18579
+ runId: claim.runId,
18580
+ playName: claim.launch.playName ?? null,
18581
+ attempt: claim.attempt,
18582
+ outcome: 'failed',
18583
+ failure: playRunFailureDetailsOf(terminalFailureResult),
18584
+ runtimeBackend: claim.launch.runtimeBackend ?? null,
18585
+ triggerSource: claim.launch.triggerSource ?? null,
18586
+ committedBy: 'worker',
18587
+ });
18561
18588
  // The failure statement already stamps every sandbox and persists its
18562
18589
  // cleanup/billing obligations. Return to terminal projection without
18563
18590
  // reacquiring custody locks or reading resources that this caller never uses.
@@ -0,0 +1,317 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import type { ToolExecuteHttpRetryDecision } from './tool-execute-retry-policy';
3
+ import { ToolExecutionError } from '../plays/tool-execution-error';
4
+
5
+ /**
6
+ * What one logical tool call went through on its way to a result, as a few
7
+ * fixed-size counters.
8
+ *
9
+ * The retry loop in `callToolExecutionAPI` records structured facts it already
10
+ * holds (its classified failure, the wait it is about to take); nothing here
11
+ * parses text, awaits, or grows with the call's history. The counters cover
12
+ * this runner process only: a call resumed from a checkpoint starts again at
13
+ * zero. The facts ride the existing `tool_call_completed` and
14
+ * `tool_call_failed` run-log lines as optional fields, and the ingesting
15
+ * server reads them back (`durable-summary-events.ts`).
16
+ */
17
+
18
+ /**
19
+ * Every reason a failed delivery can be classified with: the retry policy's
20
+ * HTTP reasons, plus the two transport outcomes the loop handles itself.
21
+ */
22
+ export const TOOL_CALL_RETRY_REASONS = [
23
+ 'rate_limit',
24
+ 'concurrency_backpressure',
25
+ 'runtime_scheduler_capacity',
26
+ 'provider_pacing_wait',
27
+ 'idempotency_in_progress',
28
+ 'gateway_invocation_in_progress',
29
+ 'customer_db_storage_unavailable',
30
+ 'billing_unavailable_before_dispatch',
31
+ 'retry_safe_transient_5xx',
32
+ 'edge_gateway_transient',
33
+ 'unsafe_transient_5xx',
34
+ 'provider_server_error',
35
+ 'hard_billing_error',
36
+ 'non_retryable_status',
37
+ /** The request may have been written, and no response came back. */
38
+ 'transport',
39
+ /** No connection opened, so no byte of the request was written. */
40
+ 'connect',
41
+ ] as const;
42
+
43
+ export type ToolCallRetryReason = (typeof TOOL_CALL_RETRY_REASONS)[number];
44
+
45
+ // The list above must name every HTTP reason the policy can return, and
46
+ // nothing the policy cannot: adding a policy reason fails this check until
47
+ // the list (and the server's mapping) learns it.
48
+ type HttpRetryReason = ToolExecuteHttpRetryDecision['reason'];
49
+ type ListedHttpReason = Exclude<ToolCallRetryReason, 'transport' | 'connect'>;
50
+ const httpRetryReasonsAreListed: [HttpRetryReason] extends [ListedHttpReason]
51
+ ? [ListedHttpReason] extends [HttpRetryReason]
52
+ ? true
53
+ : never
54
+ : never = true;
55
+ void httpRetryReasonsAreListed;
56
+
57
+ export const TOOL_CALL_ERROR_ORIGINS = [
58
+ 'caller',
59
+ 'provider',
60
+ 'deepline',
61
+ 'unknown',
62
+ ] as const;
63
+ export type ToolCallErrorOrigin = (typeof TOOL_CALL_ERROR_ORIGINS)[number];
64
+
65
+ export const TOOL_CALL_NETWORK_KINDS = [
66
+ 'timeout',
67
+ 'dns',
68
+ 'connect',
69
+ 'reset',
70
+ 'unavailable',
71
+ 'unknown',
72
+ ] as const;
73
+ export type ToolCallNetworkKind = (typeof TOOL_CALL_NETWORK_KINDS)[number];
74
+
75
+ export type ToolCallRetryFacts = {
76
+ /** The provider the call's requests went to, from its last send. */
77
+ provider: string | null;
78
+ /** Requests this process dispatched for the call. */
79
+ sends: number;
80
+ /** Waits taken before sending again. */
81
+ retries: number;
82
+ /** Total of those waits, as planned when each began. */
83
+ retryWaitMs: number;
84
+ /** Any failed response carried a `Retry-After` header. */
85
+ retryAfterSeen: boolean;
86
+ /** The failure that caused the first retry. */
87
+ firstRetryReason: ToolCallRetryReason | null;
88
+ firstRetryStatus: number | null;
89
+ firstRetryOrigin: ToolCallErrorOrigin | null;
90
+ /** The most recent failure, retried or not. */
91
+ lastErrorReason: ToolCallRetryReason | null;
92
+ lastErrorStatus: number | null;
93
+ lastErrorOrigin: ToolCallErrorOrigin | null;
94
+ /** The last failure's network kind (`ToolExecutionError.networkKind`). */
95
+ lastErrorNetworkKind: ToolCallNetworkKind | null;
96
+ /**
97
+ * Whether the last failed request reached the provider: false when the
98
+ * failure proves it was never sent, null when that is not known.
99
+ */
100
+ lastErrorDispatched: false | null;
101
+ };
102
+
103
+ export function createToolCallRetryFacts(): ToolCallRetryFacts {
104
+ return {
105
+ provider: null,
106
+ sends: 0,
107
+ retries: 0,
108
+ retryWaitMs: 0,
109
+ retryAfterSeen: false,
110
+ firstRetryReason: null,
111
+ firstRetryStatus: null,
112
+ firstRetryOrigin: null,
113
+ lastErrorReason: null,
114
+ lastErrorStatus: null,
115
+ lastErrorOrigin: null,
116
+ lastErrorNetworkKind: null,
117
+ lastErrorDispatched: null,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * The logical call whose facts a provider request records into. `executeTool`
123
+ * opens it around a call. A dispatcher that sends on behalf of queued calls
124
+ * runs outside their async scope, so it names its members' facts explicitly
125
+ * (`ToolExecutionApiOptions.retryFactsTargets`) instead of reading this.
126
+ */
127
+ export const toolCallRetryFactsScope =
128
+ new AsyncLocalStorage<ToolCallRetryFacts>();
129
+
130
+ /** One physical request, or a native batch sending for several calls. */
131
+ export type ToolCallRetryFactsTargets =
132
+ | ToolCallRetryFacts
133
+ | readonly ToolCallRetryFacts[]
134
+ | null
135
+ | undefined;
136
+
137
+ function forEachTarget(
138
+ targets: ToolCallRetryFactsTargets,
139
+ record: (facts: ToolCallRetryFacts) => void,
140
+ ): void {
141
+ if (!targets) return;
142
+ if (Array.isArray(targets)) {
143
+ for (const facts of targets as readonly ToolCallRetryFacts[]) {
144
+ record(facts);
145
+ }
146
+ return;
147
+ }
148
+ record(targets as ToolCallRetryFacts);
149
+ }
150
+
151
+ /**
152
+ * Targets as an explicit list, for a companion request (an async poll or
153
+ * finish) that may run outside the calling scope.
154
+ */
155
+ export function toolCallRetryFactsTargetList(
156
+ targets: ToolCallRetryFactsTargets,
157
+ ): readonly ToolCallRetryFacts[] {
158
+ const list: ToolCallRetryFacts[] = [];
159
+ forEachTarget(targets, (facts) => list.push(facts));
160
+ return list;
161
+ }
162
+
163
+ const PROVIDER_NAME = /^[a-z0-9][a-z0-9_.-]{0,63}$/u;
164
+
165
+ export function recordToolCallSend(
166
+ targets: ToolCallRetryFactsTargets,
167
+ provider: string,
168
+ ): void {
169
+ const name = PROVIDER_NAME.test(provider) ? provider : null;
170
+ forEachTarget(targets, (facts) => {
171
+ facts.sends += 1;
172
+ facts.provider = name;
173
+ });
174
+ }
175
+
176
+ function errorOrigin(value: unknown): ToolCallErrorOrigin | null {
177
+ return typeof value === 'string' &&
178
+ (TOOL_CALL_ERROR_ORIGINS as readonly string[]).includes(value)
179
+ ? (value as ToolCallErrorOrigin)
180
+ : null;
181
+ }
182
+
183
+ function httpStatus(value: unknown): number | null {
184
+ return typeof value === 'number' &&
185
+ Number.isSafeInteger(value) &&
186
+ value >= 100 &&
187
+ value <= 599
188
+ ? value
189
+ : null;
190
+ }
191
+
192
+ /** A failed delivery, before the loop decides whether to retry it. */
193
+ export function recordToolCallError(
194
+ targets: ToolCallRetryFactsTargets,
195
+ input: {
196
+ reason: ToolCallRetryReason;
197
+ status: number | null;
198
+ /** The classified error, whose `origin` is recorded when it has one. */
199
+ error?: unknown;
200
+ retryAfterPresent?: boolean;
201
+ /** The failure proves the request was never sent to the provider. */
202
+ knownNotDispatched?: boolean;
203
+ },
204
+ ): void {
205
+ const status = httpStatus(input.status);
206
+ const origin =
207
+ input.error instanceof ToolExecutionError
208
+ ? errorOrigin(input.error.origin)
209
+ : null;
210
+ const networkKind =
211
+ input.error instanceof ToolExecutionError &&
212
+ typeof input.error.networkKind === 'string' &&
213
+ (TOOL_CALL_NETWORK_KINDS as readonly string[]).includes(
214
+ input.error.networkKind,
215
+ )
216
+ ? (input.error.networkKind as ToolCallNetworkKind)
217
+ : null;
218
+ const dispatched = input.knownNotDispatched === true ? false : null;
219
+ forEachTarget(targets, (facts) => {
220
+ facts.lastErrorReason = input.reason;
221
+ facts.lastErrorStatus = status;
222
+ facts.lastErrorOrigin = origin;
223
+ facts.lastErrorNetworkKind = networkKind;
224
+ facts.lastErrorDispatched = dispatched;
225
+ if (input.retryAfterPresent === true) facts.retryAfterSeen = true;
226
+ });
227
+ }
228
+
229
+ /** The loop is about to wait and send again after the last recorded failure. */
230
+ export function recordToolCallRetry(
231
+ targets: ToolCallRetryFactsTargets,
232
+ waitMs: number,
233
+ ): void {
234
+ const wait =
235
+ typeof waitMs === 'number' && Number.isFinite(waitMs) && waitMs > 0
236
+ ? Math.round(waitMs)
237
+ : 0;
238
+ forEachTarget(targets, (facts) => {
239
+ facts.retries += 1;
240
+ facts.retryWaitMs += wait;
241
+ if (facts.firstRetryReason === null) {
242
+ facts.firstRetryReason = facts.lastErrorReason;
243
+ facts.firstRetryStatus = facts.lastErrorStatus;
244
+ facts.firstRetryOrigin = facts.lastErrorOrigin;
245
+ }
246
+ });
247
+ }
248
+
249
+ /**
250
+ * The optional fields a `tool_call_completed` / `tool_call_failed` line
251
+ * carries. Every field is a count, a boolean, a status, or a closed-vocabulary
252
+ * string, so the line stays a fixed size.
253
+ */
254
+ export function toolCallRetryFactsLogFields(
255
+ facts: ToolCallRetryFacts,
256
+ ): Record<string, number | boolean | string | null> {
257
+ return {
258
+ provider: facts.provider,
259
+ sends: facts.sends,
260
+ retries: facts.retries,
261
+ retry_wait_ms: facts.retryWaitMs,
262
+ retry_after_seen: facts.retryAfterSeen,
263
+ first_retry_reason: facts.firstRetryReason,
264
+ first_retry_status: facts.firstRetryStatus,
265
+ first_retry_origin: facts.firstRetryOrigin,
266
+ last_error_reason: facts.lastErrorReason,
267
+ last_error_status: facts.lastErrorStatus,
268
+ last_error_origin: facts.lastErrorOrigin,
269
+ last_error_network_kind: facts.lastErrorNetworkKind,
270
+ last_error_dispatched: facts.lastErrorDispatched,
271
+ };
272
+ }
273
+
274
+ const ERROR_CODE = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/u;
275
+ const ERROR_CLASS = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
276
+
277
+ function boundedToken(value: unknown, pattern: RegExp): string | null {
278
+ return typeof value === 'string' && pattern.test(value) ? value : null;
279
+ }
280
+
281
+ /**
282
+ * The structured identity of the error a call failed with: its class name
283
+ * and, for a tool execution failure, its code, category, origin, HTTP status
284
+ * and network kind. Never the message.
285
+ */
286
+ export function toolCallFailureLogFields(
287
+ error: unknown,
288
+ ): Record<string, number | string | null> {
289
+ const errorClass =
290
+ error instanceof Error
291
+ ? boundedToken(error.name, ERROR_CLASS)
292
+ : error === null || error === undefined
293
+ ? null
294
+ : 'NonError';
295
+ if (error instanceof ToolExecutionError) {
296
+ return {
297
+ error_class: errorClass,
298
+ error_code: boundedToken(error.code, ERROR_CODE),
299
+ error_category: boundedToken(error.category, ERROR_CLASS),
300
+ error_origin: errorOrigin(error.origin),
301
+ error_status: httpStatus(error.statusCode),
302
+ error_network_kind: boundedToken(error.networkKind, ERROR_CLASS),
303
+ };
304
+ }
305
+ const code =
306
+ error !== null && typeof error === 'object'
307
+ ? (error as { code?: unknown }).code
308
+ : undefined;
309
+ return {
310
+ error_class: errorClass,
311
+ error_code: boundedToken(code, ERROR_CODE),
312
+ error_category: null,
313
+ error_origin: null,
314
+ error_status: null,
315
+ error_network_kind: null,
316
+ };
317
+ }