@herbertgao/pi-extensions 2026.11.19 → 2026.11.21

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 (185) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +10 -10
  3. package/THIRD_PARTY_NOTICES.md +3 -3
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +8 -0
  5. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +9 -5
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +11 -1
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +1 -1
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +71 -13
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +148 -47
  10. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +7 -0
  11. package/node_modules/@narumitw/pi-btw/dist/chunks/{main-tree-picker-3PXJARQW.ts → main-tree-picker-WMTVRTR2.ts} +1 -1
  12. package/node_modules/@narumitw/pi-btw/dist/chunks/main-tree-picker-WMTVRTR2.ts.map +7 -0
  13. package/node_modules/@narumitw/pi-btw/dist/index.ts +1 -1
  14. package/node_modules/@narumitw/pi-btw/docs/core-alignment.md +6 -0
  15. package/node_modules/@narumitw/pi-btw/package.json +5 -5
  16. package/node_modules/@narumitw/pi-btw/src/main-tree-picker.ts +1 -1
  17. package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +7 -0
  18. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  19. package/node_modules/pi-lens/CHANGELOG-USER.md +6 -6
  20. package/node_modules/pi-lens/CHANGELOG.md +121 -0
  21. package/node_modules/pi-lens/README.md +9 -2
  22. package/node_modules/pi-lens/dist/{chunk-ZVQUYCBU.js → chunk-2ERVW2UF.js} +161 -100
  23. package/node_modules/pi-lens/dist/{chunk-AFSG6YUB.js → chunk-2K7BUOKS.js} +13 -13
  24. package/node_modules/pi-lens/dist/{chunk-BJGWP4UX.js → chunk-3JJ4OAJI.js} +10 -10
  25. package/node_modules/pi-lens/dist/{chunk-GIK6VUCY.js → chunk-3UHGSUVL.js} +1 -1
  26. package/node_modules/pi-lens/dist/{chunk-EKQDQPX6.js → chunk-463WN3VP.js} +1 -1
  27. package/node_modules/pi-lens/dist/{chunk-F7BFIENK.js → chunk-4X3ML2UQ.js} +29 -32
  28. package/node_modules/pi-lens/dist/{chunk-7JMEPY6P.js → chunk-5BI5YP57.js} +10 -10
  29. package/node_modules/pi-lens/dist/{chunk-MKW7ZUTT.js → chunk-5Z4XLUFF.js} +3 -3
  30. package/node_modules/pi-lens/dist/{chunk-NIZKGBOU.js → chunk-62AJH3IN.js} +12 -14
  31. package/node_modules/pi-lens/dist/{chunk-4GLSO2EM.js → chunk-6F34GMP7.js} +12 -12
  32. package/node_modules/pi-lens/dist/{chunk-35UJUF27.js → chunk-6LIUVGOR.js} +13 -3
  33. package/node_modules/pi-lens/dist/{chunk-WJ7GY5WJ.js → chunk-6REF4GCO.js} +1 -1
  34. package/node_modules/pi-lens/dist/{chunk-HFIFEH46.js → chunk-7KRR24GO.js} +3 -3
  35. package/node_modules/pi-lens/dist/{chunk-WAK2AXQQ.js → chunk-7OMOMBEQ.js} +9 -9
  36. package/node_modules/pi-lens/dist/{chunk-S7KUDW73.js → chunk-7ZFXICNN.js} +15 -15
  37. package/node_modules/pi-lens/dist/{chunk-VEF3GFOL.js → chunk-ABKRQVOY.js} +28 -52
  38. package/node_modules/pi-lens/dist/{chunk-Y2LIOCA7.js → chunk-ANSLRJBG.js} +1 -1
  39. package/node_modules/pi-lens/dist/{chunk-ARTCVE6I.js → chunk-AWMFBPGJ.js} +9 -9
  40. package/node_modules/pi-lens/dist/{chunk-H6DNTQ4V.js → chunk-BG7KHGNX.js} +2 -2
  41. package/node_modules/pi-lens/dist/{chunk-FD4LJQ6Y.js → chunk-BK2R2223.js} +10 -8
  42. package/node_modules/pi-lens/dist/{chunk-TWAQFMLW.js → chunk-BXXC6KRR.js} +31 -34
  43. package/node_modules/pi-lens/dist/{chunk-S247BOH2.js → chunk-CKJS2AUI.js} +4 -4
  44. package/node_modules/pi-lens/dist/{chunk-GNK2IHVG.js → chunk-COGU5KQJ.js} +15 -15
  45. package/node_modules/pi-lens/dist/{chunk-P7EV5ISR.js → chunk-CQNXALZJ.js} +12 -6
  46. package/node_modules/pi-lens/dist/{chunk-IO6P3NBP.js → chunk-CSZESDPP.js} +1 -1
  47. package/node_modules/pi-lens/dist/chunk-CZ5TCJPB.js +98 -0
  48. package/node_modules/pi-lens/dist/{chunk-DLGJYQML.js → chunk-D2LFEA5U.js} +9 -2
  49. package/node_modules/pi-lens/dist/chunk-D3KLF5CD.js +50 -0
  50. package/node_modules/pi-lens/dist/{chunk-W2JPGW7Q.js → chunk-ENJ2M76Y.js} +20 -20
  51. package/node_modules/pi-lens/dist/{chunk-2DWNYVUN.js → chunk-EQKF6BAK.js} +3 -3
  52. package/node_modules/pi-lens/dist/{chunk-KIQSNH3F.js → chunk-F2SAP2FM.js} +38 -45
  53. package/node_modules/pi-lens/dist/{chunk-BYIEU4E4.js → chunk-F6QAJXQV.js} +2 -2
  54. package/node_modules/pi-lens/dist/chunk-GR2QDWH5.js +25 -0
  55. package/node_modules/pi-lens/dist/{chunk-T2D2WWP6.js → chunk-GVE5VZYQ.js} +5 -5
  56. package/node_modules/pi-lens/dist/{chunk-HMXWZUQW.js → chunk-GWZZOJD2.js} +1 -1
  57. package/node_modules/pi-lens/dist/chunk-GZS6VPIE.js +27 -0
  58. package/node_modules/pi-lens/dist/chunk-H4B4SC7I.js +71 -0
  59. package/node_modules/pi-lens/dist/{chunk-2RQREVGO.js → chunk-HA6TUJOE.js} +1 -1
  60. package/node_modules/pi-lens/dist/{chunk-NAACKIKT.js → chunk-HKPJTI47.js} +2 -2
  61. package/node_modules/pi-lens/dist/{chunk-NHHS5T52.js → chunk-HPKC55MA.js} +1 -1
  62. package/node_modules/pi-lens/dist/{chunk-B2QO7GHY.js → chunk-I65CQLCG.js} +1 -1
  63. package/node_modules/pi-lens/dist/{chunk-BQ72NQQM.js → chunk-IDKLWVKY.js} +11 -11
  64. package/node_modules/pi-lens/dist/chunk-IUM2Q7NF.js +25 -0
  65. package/node_modules/pi-lens/dist/{chunk-PVV27TOX.js → chunk-J24IS3KZ.js} +5 -5
  66. package/node_modules/pi-lens/dist/{chunk-DKXIUGNA.js → chunk-J2DAHH4T.js} +2 -2
  67. package/node_modules/pi-lens/dist/{chunk-CDAJQBKJ.js → chunk-JBDZVOFL.js} +11 -11
  68. package/node_modules/pi-lens/dist/{chunk-T7KHGEJ5.js → chunk-JC6NFC57.js} +3 -3
  69. package/node_modules/pi-lens/dist/{chunk-BWGNVM33.js → chunk-JTHEUTW7.js} +11 -11
  70. package/node_modules/pi-lens/dist/{chunk-WWZLT6AM.js → chunk-JWW3ODBN.js} +2 -2
  71. package/node_modules/pi-lens/dist/{chunk-Q32RJDYC.js → chunk-K3ZIYLHT.js} +4 -4
  72. package/node_modules/pi-lens/dist/{chunk-LDPY22FS.js → chunk-KDPZA2UE.js} +2 -3
  73. package/node_modules/pi-lens/dist/{chunk-YIEHUKX2.js → chunk-KMY2OU4T.js} +489 -285
  74. package/node_modules/pi-lens/dist/{chunk-WH6O4IFD.js → chunk-KQF7VT26.js} +10 -10
  75. package/node_modules/pi-lens/dist/{chunk-OG3UCAHV.js → chunk-KVGA7X76.js} +3 -3
  76. package/node_modules/pi-lens/dist/{chunk-TABDCX35.js → chunk-KW7O72AK.js} +2 -2
  77. package/node_modules/pi-lens/dist/{chunk-AOEVZXR6.js → chunk-LEQTVRSV.js} +9 -9
  78. package/node_modules/pi-lens/dist/{chunk-7BWPQZHE.js → chunk-LKPSBM6S.js} +3 -3
  79. package/node_modules/pi-lens/dist/{chunk-WA6U2URH.js → chunk-LKW2HFSZ.js} +6 -6
  80. package/node_modules/pi-lens/dist/{chunk-M3QGXGY4.js → chunk-LURFD4HD.js} +624 -97
  81. package/node_modules/pi-lens/dist/{chunk-2YQ5LI7R.js → chunk-M6ELTECW.js} +4 -4
  82. package/node_modules/pi-lens/dist/{chunk-OHTHVILU.js → chunk-MGVVYYKW.js} +12 -12
  83. package/node_modules/pi-lens/dist/{chunk-W2YHHNY3.js → chunk-MQBKGRSB.js} +7 -7
  84. package/node_modules/pi-lens/dist/{chunk-MET776XM.js → chunk-MVG2ZEAO.js} +6 -6
  85. package/node_modules/pi-lens/dist/{chunk-2XALJI2K.js → chunk-MY4XNNTX.js} +39 -41
  86. package/node_modules/pi-lens/dist/{chunk-GFCPPCNR.js → chunk-N4AJVFRF.js} +11 -11
  87. package/node_modules/pi-lens/dist/{chunk-UARVPNAU.js → chunk-OFKKMXWM.js} +31 -36
  88. package/node_modules/pi-lens/dist/{chunk-DHFJS2I4.js → chunk-OFZE4ANN.js} +8 -8
  89. package/node_modules/pi-lens/dist/chunk-OLXBUTJR.js +61 -0
  90. package/node_modules/pi-lens/dist/{chunk-SJ2SR432.js → chunk-OZGEHOSG.js} +38 -17
  91. package/node_modules/pi-lens/dist/{chunk-6MDWNZ7E.js → chunk-PKGOROPQ.js} +40 -2
  92. package/node_modules/pi-lens/dist/{chunk-3IWMNN2S.js → chunk-Q6D5QKRG.js} +17 -17
  93. package/node_modules/pi-lens/dist/{chunk-JGCBMCCS.js → chunk-QECLJFHI.js} +12 -17
  94. package/node_modules/pi-lens/dist/{chunk-KXKM2DFP.js → chunk-QJA33VD5.js} +4 -4
  95. package/node_modules/pi-lens/dist/{chunk-YV7XVYSJ.js → chunk-R5XVJ6AN.js} +11 -11
  96. package/node_modules/pi-lens/dist/{chunk-62PIU4TO.js → chunk-REZL4OM4.js} +1 -1
  97. package/node_modules/pi-lens/dist/{chunk-NNDZ7DOP.js → chunk-RK5RBREN.js} +74 -107
  98. package/node_modules/pi-lens/dist/chunk-RP5ZQTHO.js +86 -0
  99. package/node_modules/pi-lens/dist/{chunk-HKRESBMC.js → chunk-RURPX2YV.js} +23 -23
  100. package/node_modules/pi-lens/dist/chunk-TB5MGZLS.js +53 -0
  101. package/node_modules/pi-lens/dist/chunk-TC63XRYP.js +27 -0
  102. package/node_modules/pi-lens/dist/chunk-TJOYHAXJ.js +69 -0
  103. package/node_modules/pi-lens/dist/{chunk-NZ7NSKIW.js → chunk-TRXKDCBP.js} +13 -13
  104. package/node_modules/pi-lens/dist/{chunk-7WAQ3K26.js → chunk-TTK37D7R.js} +22 -23
  105. package/node_modules/pi-lens/dist/{chunk-ALTHJUZO.js → chunk-UH3QHLR5.js} +2 -2
  106. package/node_modules/pi-lens/dist/{chunk-6MZLS6CK.js → chunk-UNTJJ7GN.js} +7 -7
  107. package/node_modules/pi-lens/dist/{chunk-XRLZ75YY.js → chunk-UPAFSETJ.js} +54 -59
  108. package/node_modules/pi-lens/dist/{chunk-N2U644ZW.js → chunk-UX75PTQW.js} +50 -17
  109. package/node_modules/pi-lens/dist/{chunk-EXHSWN3P.js → chunk-V353PYMK.js} +423 -233
  110. package/node_modules/pi-lens/dist/{chunk-SL4G67AP.js → chunk-V4TFQY5G.js} +2 -2
  111. package/node_modules/pi-lens/dist/{chunk-YOMLAKU6.js → chunk-VC3W54G3.js} +289 -138
  112. package/node_modules/pi-lens/dist/{chunk-KSQJBGRO.js → chunk-VSBCJVPC.js} +5 -5
  113. package/node_modules/pi-lens/dist/{chunk-EBXCYEII.js → chunk-WAQQGXVV.js} +3 -3
  114. package/node_modules/pi-lens/dist/{chunk-7ORBRDFY.js → chunk-WLEVWR7Y.js} +2 -2
  115. package/node_modules/pi-lens/dist/{chunk-Q4UQNTLB.js → chunk-WPMPVP5I.js} +4 -4
  116. package/node_modules/pi-lens/dist/{chunk-TQKWR5AZ.js → chunk-WXNLFOC2.js} +7 -7
  117. package/node_modules/pi-lens/dist/{chunk-HOWHAKXO.js → chunk-Y3ZNOZZS.js} +6 -6
  118. package/node_modules/pi-lens/dist/{chunk-DNJJVKJZ.js → chunk-YL6JQTWC.js} +29 -32
  119. package/node_modules/pi-lens/dist/{chunk-HUWW77QY.js → chunk-YVE5Q2UU.js} +86 -217
  120. package/node_modules/pi-lens/dist/{chunk-25CAONWT.js → chunk-YZNARDMM.js} +12 -9
  121. package/node_modules/pi-lens/dist/{chunk-HERQPNY6.js → chunk-ZDWNFZJ2.js} +8 -8
  122. package/node_modules/pi-lens/dist/{chunk-MKQFSW2Q.js → chunk-ZEUF7BIN.js} +2 -2
  123. package/node_modules/pi-lens/dist/{chunk-AB26NAHA.js → chunk-ZIF4WLWR.js} +45 -25
  124. package/node_modules/pi-lens/dist/{chunk-6MWX2J5H.js → chunk-ZSPVF7KI.js} +227 -24
  125. package/node_modules/pi-lens/dist/{chunk-QQGZY2BR.js → chunk-ZX6OKBVO.js} +2 -2
  126. package/node_modules/pi-lens/dist/index.js +6455 -5243
  127. package/node_modules/pi-lens/dist/mcp/analyze-cli.js +8 -8
  128. package/node_modules/pi-lens/dist/mcp/cli.js +39 -41
  129. package/node_modules/pi-lens/dist/mcp/server.js +870 -559
  130. package/node_modules/pi-lens/dist/mcp/worker.js +68 -59
  131. package/node_modules/pi-lens/dist/probes/installer.js +19 -20
  132. package/node_modules/pi-lens/docs/configuration.md +24 -10
  133. package/node_modules/pi-lens/docs/defect-shapes.md +18 -2
  134. package/node_modules/pi-lens/docs/environment-variables.md +18 -9
  135. package/node_modules/pi-lens/docs/globalconfig.md +16 -0
  136. package/node_modules/pi-lens/docs/invariants/dispatch-runners.md +7 -0
  137. package/node_modules/pi-lens/docs/invariants/lsp-trust-exec.md +33 -3
  138. package/node_modules/pi-lens/docs/lsp-capability-matrix.md +23 -10
  139. package/node_modules/pi-lens/docs/lsp-idle-eviction.md +8 -3
  140. package/node_modules/pi-lens/docs/release-qa-baseline.md +22 -17
  141. package/node_modules/pi-lens/docs/servercapabilities.md +1 -1
  142. package/node_modules/pi-lens/docs/settings.md +9 -2
  143. package/node_modules/pi-lens/docs/tools.md +1 -1
  144. package/node_modules/pi-lens/package.json +3 -3
  145. package/node_modules/pi-typesafe/README.md +1 -1
  146. package/node_modules/pi-typesafe/dist/ask.js +6 -3
  147. package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
  148. package/node_modules/pi-typesafe/dist/auth.js +159 -55
  149. package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
  150. package/node_modules/pi-typesafe/dist/batch.js +62 -22
  151. package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
  152. package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
  153. package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
  154. package/node_modules/pi-typesafe/dist/client.js +67 -27
  155. package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
  156. package/node_modules/pi-typesafe/dist/errors.js +105 -2
  157. package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
  158. package/node_modules/pi-typesafe/dist/extension.js +206 -106
  159. package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
  160. package/node_modules/pi-typesafe/dist/index.js +3 -3
  161. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
  162. package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
  163. package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
  164. package/node_modules/pi-typesafe/dist/login.js +167 -13
  165. package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
  166. package/node_modules/pi-typesafe/dist/schema.js +47 -13
  167. package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
  168. package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
  169. package/node_modules/pi-typesafe/dist/usage.js +79 -40
  170. package/node_modules/pi-typesafe/package.json +3 -3
  171. package/package.json +8 -8
  172. package/node_modules/@narumitw/pi-btw/dist/chunks/main-tree-picker-3PXJARQW.ts.map +0 -7
  173. package/node_modules/pi-lens/dist/chunk-3UTDLQWO.js +0 -88
  174. package/node_modules/pi-lens/dist/chunk-3Z7Z3B7V.js +0 -27
  175. package/node_modules/pi-lens/dist/chunk-4E4OCW3L.js +0 -38
  176. package/node_modules/pi-lens/dist/chunk-5HVDD7IA.js +0 -17
  177. package/node_modules/pi-lens/dist/chunk-BKJ6WZKP.js +0 -255
  178. package/node_modules/pi-lens/dist/chunk-D3UQWOCB.js +0 -46
  179. package/node_modules/pi-lens/dist/chunk-EH6EHFW2.js +0 -73
  180. package/node_modules/pi-lens/dist/chunk-J7VNGHLN.js +0 -69
  181. package/node_modules/pi-lens/dist/chunk-L3Q72QGQ.js +0 -25
  182. package/node_modules/pi-lens/dist/chunk-TFSBHRL2.js +0 -25
  183. package/node_modules/pi-lens/dist/chunk-UWBD3JMH.js +0 -56
  184. package/node_modules/pi-lens/dist/chunk-XWWFESYZ.js +0 -27
  185. package/node_modules/pi-lens/dist/chunk-XZSXSM4K.js +0 -27
@@ -3,6 +3,28 @@ import { resolveBackend } from "./backends.js";
3
3
  import { DEFAULT_BACKEND_LIMITS, prepareEvaluationRequest } from "./schema.js";
4
4
  /** Default number of requests in flight. TypeSafe answers in isolation, so a small pool is enough. */
5
5
  export const DEFAULT_CONCURRENCY = 4;
6
+ // First stop transition wins so a late signal abort during drain cannot overwrite a prior stop cause.
7
+ function transitionPool(state, reason, cause) {
8
+ if (state.status === "stopping")
9
+ return state;
10
+ return cause === undefined ? { status: "stopping", reason } : { status: "stopping", reason, cause };
11
+ }
12
+ function skippedItem(index, reason, cause) {
13
+ if (reason === "aborted") {
14
+ return {
15
+ status: "skipped",
16
+ ok: false,
17
+ skipped: true,
18
+ skipReason: "aborted",
19
+ index,
20
+ error: new TypeSafeIntegrationError("aborted", "TypeSafe batch cancelled before this request was submitted."),
21
+ };
22
+ }
23
+ const error = cause instanceof TypeSafeIntegrationError && cause.code === "budget"
24
+ ? new TypeSafeIntegrationError("budget", "TypeSafe batch stopped after a budget limit was reached; this request was not submitted.")
25
+ : new TypeSafeIntegrationError("aborted", "TypeSafe batch stopped after a failed request; this request was not submitted.");
26
+ return { status: "skipped", ok: false, skipped: true, skipReason: "stopped", index, error };
27
+ }
6
28
  /**
7
29
  * Run `worker` over `items` with bounded concurrency, preserving input order. Never throws: every item comes back as a
8
30
  * settled result. This is the pool the client's batching methods use, exported so script authors stop hand-rolling one.
@@ -11,31 +33,45 @@ export async function fanOut(items, worker, options = {}) {
11
33
  const concurrency = Math.max(1, Math.floor(options.concurrency ?? DEFAULT_CONCURRENCY));
12
34
  const results = new Array(items.length);
13
35
  let next = 0;
14
- let stopped = false;
36
+ const pool = { state: { status: "running" } };
37
+ const stopPool = (reason, cause) => {
38
+ pool.state = transitionPool(pool.state, reason, cause);
39
+ };
40
+ const onAbort = () => { stopPool("aborted"); };
41
+ if (options.signal?.aborted)
42
+ stopPool("aborted");
43
+ else
44
+ options.signal?.addEventListener?.("abort", onAbort, { once: true });
15
45
  const run = async () => {
16
- while (!stopped) {
17
- const index = next++;
18
- if (index >= items.length)
19
- return;
46
+ while (pool.state.status === "running") {
20
47
  if (options.signal?.aborted) {
21
- stopped = true;
48
+ stopPool("aborted");
22
49
  return;
23
50
  }
51
+ const index = next++;
52
+ if (index >= items.length)
53
+ return;
24
54
  try {
25
- results[index] = { ok: true, index, value: await worker(items[index], index) };
55
+ results[index] = { status: "succeeded", ok: true, index, value: await worker(items[index], index) };
26
56
  }
27
57
  catch (error) {
28
- results[index] = { ok: false, index, error, skipped: false };
58
+ results[index] = { status: "failed", ok: false, skipped: false, index, error };
29
59
  if (options.stopOn?.(error))
30
- stopped = true;
60
+ stopPool("stopped", error);
31
61
  }
32
62
  }
33
63
  };
34
- await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, run));
35
- const reason = options.signal?.aborted ? "TypeSafe batch cancelled before this request was submitted." : "TypeSafe batch stopped after a failed request; this request was not submitted.";
36
- for (let index = 0; index < items.length; index++) {
37
- if (!results[index])
38
- results[index] = { ok: false, index, error: new TypeSafeIntegrationError("aborted", reason), skipped: true };
64
+ try {
65
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, run));
66
+ }
67
+ finally {
68
+ options.signal?.removeEventListener?.("abort", onAbort);
69
+ }
70
+ if (pool.state.status === "stopping") {
71
+ for (let index = 0; index < items.length; index++) {
72
+ if (!results[index])
73
+ results[index] = skippedItem(index, pool.state.reason, pool.state.cause);
74
+ }
39
75
  }
40
76
  return results;
41
77
  }
@@ -47,16 +83,20 @@ function summarize(results, elapsedMs) {
47
83
  let skipped = 0;
48
84
  let model;
49
85
  for (const result of results) {
50
- if (!result.ok) {
51
- if (result.skipped)
86
+ switch (result.status) {
87
+ case "succeeded":
88
+ succeeded++;
89
+ Object.assign(answers, result.value.answers);
90
+ inputTokens += result.value.usage.input_tokens ?? 0;
91
+ outputTokens += result.value.usage.output_tokens ?? 0;
92
+ model ??= result.value.model;
93
+ break;
94
+ case "skipped":
52
95
  skipped++;
53
- continue;
96
+ break;
97
+ case "failed":
98
+ break;
54
99
  }
55
- succeeded++;
56
- Object.assign(answers, result.value.answers);
57
- inputTokens += result.value.usage.input_tokens ?? 0;
58
- outputTokens += result.value.usage.output_tokens ?? 0;
59
- model ??= result.value.model;
60
100
  }
61
101
  return {
62
102
  ok: succeeded === results.length,
@@ -55,13 +55,21 @@ export declare function metricsAt(samples: readonly ScoredSample[], threshold: n
55
55
  export declare function sweep(samples: readonly ScoredSample[], thresholds: readonly number[]): ThresholdRow[];
56
56
  /** The distinct scores, ascending, as a threshold grid: every point where the counts can change. */
57
57
  export declare function defaultThresholds(samples: readonly ScoredSample[], limit?: number): number[];
58
+ /** Mode for selecting a threshold: best F1 when no floors are given, or the lowest threshold clearing requested floors. */
59
+ export type ThresholdSelection = {
60
+ readonly mode: "best_f1";
61
+ } | {
62
+ readonly mode: "floors";
63
+ readonly minPrecision?: number;
64
+ readonly minRecall?: number;
65
+ };
58
66
  /**
59
67
  * The lowest threshold that clears the precision and recall floors. With no floors, the best F1 among the rows;
60
68
  * undefined when nothing clears them.
61
69
  */
62
- export declare function pickThreshold(rows: readonly ThresholdRow[], options?: {
63
- minPrecision?: number;
64
- minRecall?: number;
70
+ export declare function pickThreshold(rows: readonly ThresholdRow[], options?: ThresholdSelection | {
71
+ readonly minPrecision?: number;
72
+ readonly minRecall?: number;
65
73
  }): ThresholdRow | undefined;
66
74
  /** Label, score, and read the numbers: AUC, the threshold sweep, and one recommendation. */
67
75
  export declare function calibrate(name: string, samples: readonly ScoredSample[], options?: CalibrateOptions): Calibration;
@@ -73,17 +81,36 @@ export interface ReplayCase<T> {
73
81
  readonly label: boolean;
74
82
  readonly data: T;
75
83
  }
76
- export interface ReplayResult<T> {
84
+ /** Terminal state of one replayed calibration case. */
85
+ export type ReplayStatus = "scored" | "failed" | "skipped";
86
+ export type ReplayResult<T> = {
87
+ readonly status: "scored";
77
88
  readonly id: string;
78
89
  readonly label: boolean;
79
90
  readonly data: T;
80
- /** The judge's number, absent when the case could not be scored. */
81
- readonly score?: number;
82
- /** The failure message, absent on success. Carries no upstream body. */
83
- readonly error?: string;
84
- /** True when the case was never submitted (abort or a stopped batch). */
85
- readonly skipped: boolean;
86
- }
91
+ /** The judge's finite number. */
92
+ readonly score: number;
93
+ readonly skipped: false;
94
+ readonly error?: undefined;
95
+ } | {
96
+ readonly status: "failed";
97
+ readonly id: string;
98
+ readonly label: boolean;
99
+ readonly data: T;
100
+ /** The failure message. Carries no upstream body. */
101
+ readonly error: string;
102
+ readonly skipped: false;
103
+ readonly score?: undefined;
104
+ } | {
105
+ readonly status: "skipped";
106
+ readonly id: string;
107
+ readonly label: boolean;
108
+ readonly data: T;
109
+ /** The skip message. Carries no upstream body. */
110
+ readonly error: string;
111
+ readonly skipped: true;
112
+ readonly score?: undefined;
113
+ };
87
114
  export interface ReplayOptions {
88
115
  /** Cases in flight at once. Default: DEFAULT_CONCURRENCY (4). */
89
116
  concurrency?: number;
@@ -54,30 +54,46 @@ export function defaultThresholds(samples, limit = 64) {
54
54
  const step = (distinct.length - 1) / (limit - 1);
55
55
  return Array.from({ length: limit }, (_, index) => distinct[Math.round(index * step)]);
56
56
  }
57
+ function resolveThresholdSelection(options) {
58
+ if ("mode" in options)
59
+ return options;
60
+ if (options.minPrecision === undefined && options.minRecall === undefined)
61
+ return { mode: "best_f1" };
62
+ return {
63
+ mode: "floors",
64
+ ...(options.minPrecision === undefined ? {} : { minPrecision: options.minPrecision }),
65
+ ...(options.minRecall === undefined ? {} : { minRecall: options.minRecall }),
66
+ };
67
+ }
57
68
  /**
58
69
  * The lowest threshold that clears the precision and recall floors. With no floors, the best F1 among the rows;
59
70
  * undefined when nothing clears them.
60
71
  */
61
72
  export function pickThreshold(rows, options = {}) {
62
- const { minPrecision, minRecall } = options;
63
- if (minPrecision === undefined && minRecall === undefined) {
64
- let best;
65
- let bestF1 = -1;
66
- for (const row of rows) {
67
- if (row.precision === undefined || row.recall === undefined)
68
- continue;
69
- const f1 = row.precision + row.recall === 0 ? 0 : 2 * row.precision * row.recall / (row.precision + row.recall);
70
- if (f1 > bestF1) {
71
- bestF1 = f1;
72
- best = row;
73
+ const selection = resolveThresholdSelection(options);
74
+ switch (selection.mode) {
75
+ case "best_f1": {
76
+ let best;
77
+ let bestF1 = -1;
78
+ for (const row of rows) {
79
+ if (row.precision === undefined || row.recall === undefined)
80
+ continue;
81
+ const f1 = row.precision + row.recall === 0 ? 0 : 2 * row.precision * row.recall / (row.precision + row.recall);
82
+ if (f1 > bestF1) {
83
+ bestF1 = f1;
84
+ best = row;
85
+ }
73
86
  }
87
+ return best;
88
+ }
89
+ case "floors": {
90
+ const { minPrecision, minRecall } = selection;
91
+ const candidates = rows
92
+ .filter(row => (minPrecision === undefined || (row.precision ?? 0) >= minPrecision) && (minRecall === undefined || (row.recall ?? 0) >= minRecall))
93
+ .sort((a, b) => a.threshold - b.threshold);
94
+ return candidates[0];
74
95
  }
75
- return best;
76
96
  }
77
- const candidates = rows
78
- .filter(row => (minPrecision === undefined || (row.precision ?? 0) >= minPrecision) && (minRecall === undefined || (row.recall ?? 0) >= minRecall))
79
- .sort((a, b) => a.threshold - b.threshold);
80
- return candidates[0];
81
97
  }
82
98
  /** Label, score, and read the numbers: AUC, the threshold sweep, and one recommendation. */
83
99
  export function calibrate(name, samples, options = {}) {
@@ -123,6 +139,28 @@ export function formatCalibration(calibration) {
123
139
  lines.push(`flagged negatives (${calibration.flagged.length}): ${calibration.flagged.map(sample => sample.id ?? sample.score.toFixed(2)).join(", ").slice(0, 300)}`);
124
140
  return lines.join("\n");
125
141
  }
142
+ const NON_FINITE_SCORE_MESSAGE = "The scorer returned a non-finite score.";
143
+ function describeReplayError(error, describeError) {
144
+ if (describeError)
145
+ return describeError(error);
146
+ return error instanceof Error ? error.message : "The scorer failed.";
147
+ }
148
+ function settleReplayCase(item, result, describeError) {
149
+ switch (result.status) {
150
+ case "succeeded": {
151
+ if (Number.isFinite(result.value)) {
152
+ return { status: "scored", id: item.id, label: item.label, data: item.data, score: result.value, skipped: false };
153
+ }
154
+ // Reject NaN/Infinity at the replay boundary instead of carrying an invalid score downstream.
155
+ const error = describeReplayError(new RangeError(NON_FINITE_SCORE_MESSAGE), describeError);
156
+ return { status: "failed", id: item.id, label: item.label, data: item.data, error, skipped: false };
157
+ }
158
+ case "failed":
159
+ return { status: "failed", id: item.id, label: item.label, data: item.data, error: describeReplayError(result.error, describeError), skipped: false };
160
+ case "skipped":
161
+ return { status: "skipped", id: item.id, label: item.label, data: item.data, error: describeReplayError(result.error, describeError), skipped: true };
162
+ }
163
+ }
126
164
  /**
127
165
  * Replay labelled cases through a scorer with bounded concurrency, keeping order and capturing per-case failures.
128
166
  * The scorer is usually one Jev question; a thrown error is recorded rather than aborting the run, so one bad case
@@ -134,20 +172,14 @@ export async function replay(cases, score, options = {}) {
134
172
  ...(options.signal === undefined ? {} : { signal: options.signal }),
135
173
  ...(options.stopOn === undefined ? {} : { stopOn: options.stopOn }),
136
174
  });
137
- return settled.map((result, index) => {
138
- const item = cases[index];
139
- if (result.ok)
140
- return { id: item.id, label: item.label, data: item.data, score: result.value, skipped: false };
141
- const error = options.describeError ? options.describeError(result.error) : result.error instanceof Error ? result.error.message : "The scorer failed.";
142
- return { id: item.id, label: item.label, data: item.data, error, skipped: result.skipped };
143
- });
175
+ return settled.map((result, index) => settleReplayCase(cases[index], result, options.describeError));
144
176
  }
145
177
  /** The scored cases of a replay, in replay order. Unscored cases are excluded and counted as errors. */
146
178
  export function samplesOf(results) {
147
179
  const samples = [];
148
180
  let errors = 0;
149
181
  for (const result of results) {
150
- if (result.score === undefined || !Number.isFinite(result.score)) {
182
+ if (result.status === "failed" || result.status === "skipped" || result.score === undefined || !Number.isFinite(result.score)) {
151
183
  errors++;
152
184
  continue;
153
185
  }
@@ -46,6 +46,18 @@ export interface UsageSnapshot {
46
46
  readonly outputTokens: number;
47
47
  readonly estimatedUsd: number;
48
48
  }
49
+ /** Explicit budget machine: daily cap takes precedence over session cap because it persists across client instances. */
50
+ export type BudgetState = {
51
+ readonly status: "within_budget";
52
+ readonly remainingRequests: number;
53
+ } | {
54
+ readonly status: "session_cap_reached";
55
+ readonly used: number;
56
+ readonly limit: number;
57
+ } | {
58
+ readonly status: "daily_cap_reached";
59
+ readonly blocked: BlockedCap;
60
+ };
49
61
  /** Session counters, today's persisted counters, the caps in force, and the cap that is currently reached. */
50
62
  export interface SpendReport {
51
63
  readonly session: UsageSnapshot;
@@ -54,6 +66,7 @@ export interface SpendReport {
54
66
  /** The price of this client's default model. A request that names another model may be priced differently. */
55
67
  readonly usdPerMTok: number;
56
68
  readonly blocked?: BlockedCap;
69
+ readonly budget: BudgetState;
57
70
  }
58
71
  export interface TypeSafe {
59
72
  /** What one request may ask on this client's backend; known without a request. Absent only on a hand-built TypeSafe, which gets the schema's bounds. */
@@ -168,6 +168,13 @@ function capsDescription(caps) {
168
168
  ].filter((part) => part !== undefined);
169
169
  return parts.length ? `Caps: ${parts.join(", ")}.` : "No request or spend caps are set.";
170
170
  }
171
+ function evaluateBudget(requestsStarted, maxRequests, dailyBlocked) {
172
+ if (dailyBlocked !== undefined)
173
+ return { status: "daily_cap_reached", blocked: dailyBlocked };
174
+ if (requestsStarted >= maxRequests)
175
+ return { status: "session_cap_reached", used: requestsStarted, limit: maxRequests };
176
+ return { status: "within_budget", remainingRequests: maxRequests - requestsStarted };
177
+ }
171
178
  /** A bounded, server-side TypeSafe client independent of Pi's runtime. */
172
179
  export function createTypeSafe(options = {}) {
173
180
  const backend = resolveBackend(options.backend);
@@ -229,21 +236,64 @@ export function createTypeSafe(options = {}) {
229
236
  const ledger = options.ledger ?? openUsageLedger(callerRate === undefined ? {} : { usdPerMTok: callerRate });
230
237
  let sessionUsd = 0;
231
238
  const usage = { requestsStarted: 0, requestsSucceeded: 0, requestsFailed: 0, inputTokens: 0, outputTokens: 0 };
232
- // One verification record per process; every failure is written, because its time is the rejection window's anchor.
233
- let verificationRecorded = false;
239
+ const authTarget = options.backend === undefined ? {} : { backend: options.backend };
240
+ let authSync = "unsynced";
241
+ const syncAuth = (event) => {
242
+ switch (event.type) {
243
+ case "verified":
244
+ // Skip redundant disk writes while already verified; degraded transitions back to verified to clear lastFailure.
245
+ if (authSync === "verified")
246
+ return;
247
+ authSync = "verified";
248
+ recordAuthVerified(undefined, authTarget);
249
+ return;
250
+ case "failed":
251
+ // Every failure writes because its timestamp anchors the rejection window.
252
+ authSync = "degraded";
253
+ recordAuthFailure(event.error, undefined, authTarget);
254
+ return;
255
+ }
256
+ };
257
+ // Single-settlement attempt machine keeps requestsStarted === requestsSucceeded + requestsFailed by construction.
258
+ const startAttempt = () => {
259
+ let state = "in_flight";
260
+ usage.requestsStarted += 1;
261
+ ledger.recordStart();
262
+ return {
263
+ succeed(inputTokens, outputTokens, costUsd) {
264
+ if (state !== "in_flight")
265
+ return false;
266
+ state = "succeeded";
267
+ usage.requestsSucceeded += 1;
268
+ usage.inputTokens += inputTokens;
269
+ usage.outputTokens += outputTokens;
270
+ sessionUsd += costUsd;
271
+ ledger.recordSuccess(inputTokens, outputTokens, costUsd);
272
+ return true;
273
+ },
274
+ fail() {
275
+ if (state !== "in_flight")
276
+ return false;
277
+ state = "failed";
278
+ usage.requestsFailed += 1;
279
+ ledger.recordFailure();
280
+ return true;
281
+ },
282
+ };
283
+ };
234
284
  const snapshot = () => ({ ...usage, estimatedUsd: Math.round(sessionUsd * 1e6) / 1e6 });
235
- const blocked = () => (usage.requestsStarted >= maxRequests ? undefined : ledger.blocked(caps));
236
285
  const typesafe = {
237
286
  limits: backend.limits,
238
287
  getUsage: snapshot,
239
288
  getSpend: () => {
240
- const reached = blocked();
289
+ const reached = ledger.blocked(caps);
241
290
  return {
242
291
  session: snapshot(),
243
292
  today: ledger.today(),
244
293
  caps,
245
294
  usdPerMTok,
246
295
  ...(reached === undefined ? {} : { blocked: reached }),
296
+ budget: evaluateBudget(usage.requestsStarted, maxRequests, reached),
247
297
  };
248
298
  },
249
299
  async listModels(callOptions = {}) {
@@ -252,10 +302,8 @@ export function createTypeSafe(options = {}) {
252
302
  if (!Array.isArray(models))
253
303
  throw new TypeSafeIntegrationError("response", `${backend.label} returned an unexpected model list.`);
254
304
  // A backend that serves its list publicly accepts any key, so a success there proves nothing about one.
255
- if (backend.modelsVerifyKey && !verificationRecorded) {
256
- verificationRecorded = true;
257
- recordAuthVerified();
258
- }
305
+ if (backend.modelsVerifyKey)
306
+ syncAuth({ type: "verified" });
259
307
  return models.map(card => card?.name).filter((name) => typeof name === "string" && name.length > 0 && name.length <= 100);
260
308
  }
261
309
  catch (error) {
@@ -270,45 +318,37 @@ export function createTypeSafe(options = {}) {
270
318
  assertWithinByteLimit(body, maxInputBytes);
271
319
  if (callOptions.signal?.aborted)
272
320
  throw new TypeSafeIntegrationError("aborted", `${backend.label} request cancelled before submission.`);
273
- if (usage.requestsStarted >= maxRequests) {
274
- throw new TypeSafeIntegrationError("budget", `${backend.label} request limit reached (${maxRequests} attempts per client instance). ${capsDescription(caps)}`);
275
- }
276
- const reached = ledger.blocked(caps);
277
- if (reached) {
321
+ const budget = evaluateBudget(usage.requestsStarted, maxRequests, ledger.blocked(caps));
322
+ if (budget.status === "daily_cap_reached") {
278
323
  // Name the cap, the used amount, and the day, so a long run stops loudly instead of burning tokens unnoticed.
324
+ const reached = budget.blocked;
279
325
  throw new TypeSafeIntegrationError("budget", `${backend.label} ${CAP_LABELS[reached.cap]} reached (${reached.used} of ${reached.limit} on ${reached.day}); no request was submitted. Requests resume after the local day rolls over, or raise the cap deliberately.`);
280
326
  }
327
+ if (budget.status === "session_cap_reached") {
328
+ throw new TypeSafeIntegrationError("budget", `${backend.label} request limit reached (${budget.limit} attempts per client instance). ${capsDescription(caps)}`);
329
+ }
281
330
  // Snapshot before awaiting so later mutations cannot change the request or validation.
282
331
  const request = JSON.parse(body);
283
- usage.requestsStarted += 1;
284
- ledger.recordStart();
332
+ const attempt = startAttempt();
285
333
  const start = performance.now();
286
334
  try {
287
335
  const result = await client.systemOne(request, callOptions);
288
336
  if (!validResult(result, request.questions))
289
337
  throw new TypeSafeIntegrationError("response", `${backend.label} returned an unexpected answer or usage format.`);
290
- usage.requestsSucceeded += 1;
291
338
  // An unreported count is not a count this package can add, price, or charge against a token cap.
292
339
  const inputTokens = result.usage.input_tokens ?? 0;
293
340
  const outputTokens = result.usage.output_tokens ?? 0;
294
- usage.inputTokens += inputTokens;
295
- usage.outputTokens += outputTokens;
296
341
  // Unrounded: a small request must still count toward the cap.
297
342
  const cost = (inputTokens * rateFor(sentModel)) / 1e6;
298
- sessionUsd += cost;
299
- ledger.recordSuccess(inputTokens, outputTokens, cost);
300
- if (!verificationRecorded) {
301
- verificationRecorded = true;
302
- recordAuthVerified();
303
- }
343
+ attempt.succeed(inputTokens, outputTokens, cost);
344
+ syncAuth({ type: "verified" });
304
345
  return { ...result, elapsedMs: Math.round(performance.now() - start) };
305
346
  }
306
347
  catch (error) {
307
348
  const safe = safeError(error, backend);
308
349
  // The request was submitted, so it counts even when it fails; the reason stays visible in `authState()`.
309
- usage.requestsFailed += 1;
310
- ledger.recordFailure();
311
- recordAuthFailure(safe);
350
+ attempt.fail();
351
+ syncAuth({ type: "failed", error: safe });
312
352
  throw safe;
313
353
  }
314
354
  },
@@ -1,5 +1,16 @@
1
1
  import type { BackendConfig, BackendSpec } from "./backends.js";
2
2
  export type IntegrationErrorCode = "configuration" | "validation" | "budget" | "aborted" | "timeout" | "http" | "connection" | "response";
3
+ export type ErrorTarget = "configuration" | "validation" | "credentials" | "billing" | "permission" | "budget" | "cancelled" | "response";
4
+ /** Machine-readable retryability and remediation target so callers and agents never parse error prose. */
5
+ export type ErrorDisposition = {
6
+ readonly status: "transient";
7
+ readonly retryable: true;
8
+ readonly retryAfterSeconds?: number;
9
+ } | {
10
+ readonly status: "permanent";
11
+ readonly retryable: false;
12
+ readonly target: ErrorTarget;
13
+ };
3
14
  /**
4
15
  * Safe to display: never contains upstream bodies, keys, or submitted state. The only header value a message can
5
16
  * quote is a numeric Retry-After count in seconds, which cannot carry a secret.
@@ -9,7 +20,16 @@ export declare class TypeSafeIntegrationError extends Error {
9
20
  readonly status?: number | undefined;
10
21
  readonly name = "TypeSafeIntegrationError";
11
22
  constructor(code: IntegrationErrorCode, message: string, status?: number | undefined);
23
+ get disposition(): ErrorDisposition;
24
+ get retryable(): boolean;
12
25
  }
26
+ /** Attach a known disposition to a non-throwing envelope (such as a failed AskAnswer) without adding properties to it. */
27
+ export declare function attachErrorDisposition(envelope: object, disposition: ErrorDisposition): void;
28
+ /**
29
+ * Pure retryability classifier for `TypeSafeIntegrationError`, SDK errors, failed `AskAnswer` envelopes, or unknown
30
+ * throwables. Advises callers whether their own workflow may retry (`transient`) or must address a fixed target (`permanent`).
31
+ */
32
+ export declare function classifyError(error: unknown): ErrorDisposition;
13
33
  /**
14
34
  * Classify an error into a message safe to display. The subject of every message is the backend that answered — its
15
35
  * `label`, or the caller's endpoint label — falling back to TypeSafe when no backend is passed. `backend` also names
@@ -1,5 +1,11 @@
1
1
  import { APIError, APIConnectionError, APITimeoutError, APIUserAbortError } from "@typesafe-ai/sdk";
2
2
  import { DECISIONS_BACKENDS, TYPESAFE_KEY_ENV, backendConfig } from "./backends.js";
3
+ const INTEGRATION_ERROR_CODES = new Set([
4
+ "configuration", "validation", "budget", "aborted", "timeout", "http", "connection", "response",
5
+ ]);
6
+ // Side tables keep extra metadata off error and AskAnswer instances so JSON.stringify and deep-equality shapes stay frozen.
7
+ const RETRY_AFTER = new WeakMap();
8
+ const ASSOCIATED_DISPOSITION = new WeakMap();
3
9
  /**
4
10
  * Safe to display: never contains upstream bodies, keys, or submitted state. The only header value a message can
5
11
  * quote is a numeric Retry-After count in seconds, which cannot carry a secret.
@@ -13,6 +19,16 @@ export class TypeSafeIntegrationError extends Error {
13
19
  this.code = code;
14
20
  this.status = status;
15
21
  }
22
+ get disposition() {
23
+ return classifyError(this);
24
+ }
25
+ get retryable() {
26
+ return this.disposition.retryable;
27
+ }
28
+ }
29
+ /** Attach a known disposition to a non-throwing envelope (such as a failed AskAnswer) without adding properties to it. */
30
+ export function attachErrorDisposition(envelope, disposition) {
31
+ ASSOCIATED_DISPOSITION.set(envelope, disposition);
16
32
  }
17
33
  /** A numeric Retry-After delay in seconds; dates, blanks, and anything else stay out of the message. */
18
34
  function retryAfterSeconds(error) {
@@ -22,6 +38,89 @@ function retryAfterSeconds(error) {
22
38
  const seconds = Number(raw);
23
39
  return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : undefined;
24
40
  }
41
+ function parseRetryAfterFromMessage(message) {
42
+ const match = /\bRetry after (\d+) seconds\./.exec(message);
43
+ if (!match?.[1])
44
+ return undefined;
45
+ const seconds = Number(match[1]);
46
+ return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : undefined;
47
+ }
48
+ function parseHttpStatusFromMessage(message) {
49
+ const match = /\bHTTP (\d{3})\b/.exec(message);
50
+ if (!match?.[1])
51
+ return undefined;
52
+ const status = Number(match[1]);
53
+ return Number.isSafeInteger(status) ? status : undefined;
54
+ }
55
+ function classifyCode(code, status, retryAfter) {
56
+ switch (code) {
57
+ case "timeout":
58
+ case "connection":
59
+ return { status: "transient", retryable: true };
60
+ case "configuration":
61
+ return { status: "permanent", retryable: false, target: "configuration" };
62
+ case "validation":
63
+ return { status: "permanent", retryable: false, target: "validation" };
64
+ case "budget":
65
+ return { status: "permanent", retryable: false, target: "budget" };
66
+ case "aborted":
67
+ return { status: "permanent", retryable: false, target: "cancelled" };
68
+ case "response":
69
+ return { status: "permanent", retryable: false, target: "response" };
70
+ case "http": {
71
+ if (status === 408 || status === 429 || (status !== undefined && status >= 500 && status <= 599)) {
72
+ return {
73
+ status: "transient",
74
+ retryable: true,
75
+ ...(retryAfter === undefined ? {} : { retryAfterSeconds: retryAfter }),
76
+ };
77
+ }
78
+ if (status === 401)
79
+ return { status: "permanent", retryable: false, target: "credentials" };
80
+ if (status === 402)
81
+ return { status: "permanent", retryable: false, target: "billing" };
82
+ if (status === 403)
83
+ return { status: "permanent", retryable: false, target: "permission" };
84
+ if (status === 400 || status === 404 || status === 422)
85
+ return { status: "permanent", retryable: false, target: "validation" };
86
+ return { status: "permanent", retryable: false, target: "response" };
87
+ }
88
+ }
89
+ }
90
+ /**
91
+ * Pure retryability classifier for `TypeSafeIntegrationError`, SDK errors, failed `AskAnswer` envelopes, or unknown
92
+ * throwables. Advises callers whether their own workflow may retry (`transient`) or must address a fixed target (`permanent`).
93
+ */
94
+ export function classifyError(error) {
95
+ if (error instanceof TypeSafeIntegrationError) {
96
+ const retry = RETRY_AFTER.get(error) ?? parseRetryAfterFromMessage(error.message);
97
+ return classifyCode(error.code, error.status, retry);
98
+ }
99
+ if (error instanceof APIUserAbortError)
100
+ return classifyCode("aborted");
101
+ if (error instanceof APITimeoutError)
102
+ return classifyCode("timeout");
103
+ if (error instanceof APIConnectionError)
104
+ return classifyCode("connection");
105
+ if (error instanceof APIError)
106
+ return classifyCode("http", error.status, retryAfterSeconds(error));
107
+ if (error !== null && typeof error === "object") {
108
+ const associated = ASSOCIATED_DISPOSITION.get(error);
109
+ if (associated !== undefined)
110
+ return associated;
111
+ const raw = error;
112
+ if (raw.ok === false && typeof raw.error === "string") {
113
+ if (typeof raw.errorCode === "string" && INTEGRATION_ERROR_CODES.has(raw.errorCode)) {
114
+ const code = raw.errorCode;
115
+ const status = code === "http" ? parseHttpStatusFromMessage(raw.error) : undefined;
116
+ const retry = code === "http" ? parseRetryAfterFromMessage(raw.error) : undefined;
117
+ return classifyCode(code, status, retry);
118
+ }
119
+ return { status: "permanent", retryable: false, target: "response" };
120
+ }
121
+ }
122
+ return { status: "permanent", retryable: false, target: "response" };
123
+ }
25
124
  /**
26
125
  * Classify an error into a message safe to display. The subject of every message is the backend that answered — its
27
126
  * `label`, or the caller's endpoint label — falling back to TypeSafe when no backend is passed. `backend` also names
@@ -39,14 +138,18 @@ export function safeError(error, backend) {
39
138
  if (error instanceof APITimeoutError)
40
139
  return new TypeSafeIntegrationError("timeout", `${subject} request timed out; it was not retried and may still be billed.`);
41
140
  if (error instanceof APIError) {
42
- const retry = error.status === 429 ? retryAfterSeconds(error) : undefined;
141
+ const headerRetry = retryAfterSeconds(error);
142
+ const retry = error.status === 429 ? headerRetry : undefined;
43
143
  const advice = error.status === 401 ? `Check ${keyEnv}.`
44
144
  : error.status === 402 ? (openrouter ? "Insufficient credits. Add credits at https://openrouter.ai/credits." : "Check your account balance.")
45
145
  : error.status === 403 ? "Check your account access and model permissions."
46
146
  : error.status === 429 ? `Check your account quota and try again later.${retry === undefined ? "" : ` Retry after ${retry} seconds.`}`
47
147
  : error.status === 400 || error.status === 422 ? "Check the question format and model limits."
48
148
  : "Try again later or check the service status.";
49
- return new TypeSafeIntegrationError("http", `${subject} returned HTTP ${error.status}. ${advice} No automatic retry was made.`, error.status);
149
+ const safe = new TypeSafeIntegrationError("http", `${subject} returned HTTP ${error.status}. ${advice} No automatic retry was made.`, error.status);
150
+ if (headerRetry !== undefined)
151
+ RETRY_AFTER.set(safe, headerRetry);
152
+ return safe;
50
153
  }
51
154
  if (error instanceof APIConnectionError)
52
155
  return new TypeSafeIntegrationError("connection", `Could not complete the ${subject} connection. No automatic retry was made.`);