@herbertgao/pi-extensions 2026.11.18 → 2026.11.20

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 (177) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -5
  3. package/THIRD_PARTY_NOTICES.md +3 -24
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  64. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
  65. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  66. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
  67. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  68. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  69. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  70. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  71. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  72. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  73. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
  74. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  75. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  76. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
  77. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  78. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
  80. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  82. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  84. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  85. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  86. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  87. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  88. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  89. package/node_modules/pi-commandcode-provider/README.md +3 -2
  90. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  91. package/node_modules/pi-commandcode-provider/package.json +4 -3
  92. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  93. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  94. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  95. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  96. package/node_modules/pi-typesafe/README.md +1 -1
  97. package/node_modules/pi-typesafe/dist/ask.js +6 -3
  98. package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
  99. package/node_modules/pi-typesafe/dist/auth.js +159 -55
  100. package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
  101. package/node_modules/pi-typesafe/dist/batch.js +62 -22
  102. package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
  103. package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
  104. package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
  105. package/node_modules/pi-typesafe/dist/client.js +67 -27
  106. package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
  107. package/node_modules/pi-typesafe/dist/errors.js +105 -2
  108. package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
  109. package/node_modules/pi-typesafe/dist/extension.js +206 -106
  110. package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
  111. package/node_modules/pi-typesafe/dist/index.js +3 -3
  112. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
  113. package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
  114. package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
  115. package/node_modules/pi-typesafe/dist/login.js +167 -13
  116. package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
  117. package/node_modules/pi-typesafe/dist/schema.js +47 -13
  118. package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
  119. package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
  120. package/node_modules/pi-typesafe/dist/usage.js +79 -40
  121. package/node_modules/pi-typesafe/package.json +3 -3
  122. package/package.json +12 -15
  123. package/node_modules/pi-antigravity/README.md +0 -298
  124. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  125. package/node_modules/pi-antigravity/package.json +0 -87
  126. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  127. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  128. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  129. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  130. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  131. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  132. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  133. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  134. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  135. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  136. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  137. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  138. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  139. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  140. package/node_modules/pi-antigravity/src/index.ts +0 -547
  141. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  142. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  143. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  144. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  145. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  146. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  147. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  148. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  149. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  150. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  151. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  152. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  153. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  154. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  155. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  156. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  157. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  158. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  159. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  160. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  161. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  162. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  163. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  164. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  165. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  166. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  167. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  168. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  169. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  170. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  171. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  172. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  173. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  174. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  175. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  176. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  177. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -1,18 +1,32 @@
1
1
  import type { Questions, SystemOneRequest, Usage } from "@typesafe-ai/sdk";
2
2
  import type { Evaluation, TypeSafe } from "./client.js";
3
+ import { TypeSafeIntegrationError } from "./errors.js";
3
4
  import type { BackendSpec } from "./backends.js";
4
5
  /** Default number of requests in flight. TypeSafe answers in isolation, so a small pool is enough. */
5
6
  export declare const DEFAULT_CONCURRENCY = 4;
6
- /** One item's outcome. `skipped` marks work that was never started because of an abort or a stop rule. */
7
+ /** Terminal state of one item in a batch. */
8
+ export type SettledStatus = "succeeded" | "failed" | "skipped";
9
+ /** Why an unstarted batch item was skipped. */
10
+ export type SkipReason = "aborted" | "stopped";
11
+ /** One item's outcome. `status` discriminates every terminal state while keeping `ok` and `skipped` narrowable. */
7
12
  export type Settled<T> = {
13
+ readonly status: "succeeded";
8
14
  readonly ok: true;
9
15
  readonly index: number;
10
16
  readonly value: T;
11
17
  } | {
18
+ readonly status: "failed";
12
19
  readonly ok: false;
20
+ readonly skipped: false;
13
21
  readonly index: number;
14
22
  readonly error: unknown;
15
- readonly skipped: boolean;
23
+ } | {
24
+ readonly status: "skipped";
25
+ readonly ok: false;
26
+ readonly skipped: true;
27
+ readonly skipReason: SkipReason;
28
+ readonly index: number;
29
+ readonly error: TypeSafeIntegrationError;
16
30
  };
17
31
  export interface FanOutOptions {
18
32
  /** Requests in flight at once. Default: DEFAULT_CONCURRENCY. */
@@ -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