@herbertgao/pi-extensions 2026.11.19 → 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 (30) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +2 -2
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/node_modules/pi-typesafe/README.md +1 -1
  5. package/node_modules/pi-typesafe/dist/ask.js +6 -3
  6. package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
  7. package/node_modules/pi-typesafe/dist/auth.js +159 -55
  8. package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
  9. package/node_modules/pi-typesafe/dist/batch.js +62 -22
  10. package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
  11. package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
  12. package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
  13. package/node_modules/pi-typesafe/dist/client.js +67 -27
  14. package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
  15. package/node_modules/pi-typesafe/dist/errors.js +105 -2
  16. package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
  17. package/node_modules/pi-typesafe/dist/extension.js +206 -106
  18. package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
  19. package/node_modules/pi-typesafe/dist/index.js +3 -3
  20. package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
  21. package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
  22. package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
  23. package/node_modules/pi-typesafe/dist/login.js +167 -13
  24. package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
  25. package/node_modules/pi-typesafe/dist/schema.js +47 -13
  26. package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
  27. package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
  28. package/node_modules/pi-typesafe/dist/usage.js +79 -40
  29. package/node_modules/pi-typesafe/package.json +3 -3
  30. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @herbertgao/pi-extensions
2
2
 
3
+ ## 2026.11.20
4
+
5
+ ### Patch Changes
6
+
7
+ - [#413](https://github.com/HerbertGao/pi-extensions/pull/413) [`e703338`](https://github.com/HerbertGao/pi-extensions/commit/e703338631d4174a4fdf9485284b1e50a8e62df8) Thanks [@HerbertGao](https://github.com/HerbertGao)! - Pin Graphify PyPI `0.9.115` and bundle `pi-typesafe@0.15.1` so TypeSafe accepts Pi 1.x peers and per-backend auth matches the published companion releases.
8
+
3
9
  ## 2026.11.19
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -34,7 +34,7 @@ The package bundles 7 active `@herbertgao/*` child packages—`pi-agency`, `pi-b
34
34
  - `@tifan/pi-recap@0.4.8`
35
35
  - `@tifan/pi-rename@0.6.0`
36
36
  - `@tintinweb/pi-tasks@0.9.1`
37
- - `pi-typesafe@0.14.0`
37
+ - `pi-typesafe@0.15.1`
38
38
  - `pi-next-cue@1.0.8`
39
39
  - `pi-lens@4.5.1`
40
40
  - `pi-web-access@0.48.0`
@@ -63,7 +63,7 @@ Impeccable `4.10.0` is vendored as `@herbertgao/pi-impeccable` and loaded with `
63
63
 
64
64
  `@narumitw/pi-btw@0.63.8` opens its side workspace through the `@narumitw/pi-tui-kit@^0.70.0` fullscreen handoff. Published `src` and `dist` are unchanged from 0.63.7 aside from the manifest and changelog. Fullscreen, menu, and transcript modules load on first use. An already ended session does not open that UI. The loaded flow still stops when the dedicated UI is disposed or the parent terminal cannot be restored. Only one BTW flow can be open per session; a second `/btw` warns and stays closed. In split layout, mounting the first split releases Pi's idle wait so the main input stays usable. Importing new main-thread context stays manual. The main-thread tree picker walks an arbitrarily deep session on the heap, keeps raw copy text as fragments until a copy, and stores a saved label only when the entry has one. Settings rows keep a clipped label or value in full under the list, and a searchable model choice shows how many results match. A searchable choice keeps page scrolling; the host still owns search activation. The promoted kit can name an editor-status widget and collapse it to that divider; BTW does not mount that widget.
65
65
 
66
- `clef` asks Cloudflare Clef-flash an on-demand yes/no, choice, or score and prints the questions and answers in the transcript, plus a one-line notice. It is not a permission gate. `pi-typesafe@0.14.0` provides `/typesafe` and `typesafe_evaluate` for explicit structured decisions; `/typesafe enable` or `PI_TYPESAFE_ENABLED=1` is still required for agent tool calls. The default backend remains `https://api.typesafe.ai`. `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` select the session backend and model, and `/typesafe login` stores a key for the named backend. Only HTTP 401 refuses that key, and only for 15 minutes; a 403 refuses one request and leaves the key usable. Nace.AI (`https://console.nace.ai`, `NACE_API_KEY`, default model `drex-v2.0`) is a judgment backend. Daily request, token, and USD caps are opt-in. OpenRouter, Command Code, Liquid, SubQ, Nace.AI, and a named endpoint stay explicit and use that backend's own key. The promoted SDK is `@typesafe-ai/sdk@0.7.0`. Under Bun, the judge transport reads each response body once and replays it, so the SDK can still read the result after Bun marks the original body used.
66
+ `clef` asks Cloudflare Clef-flash an on-demand yes/no, choice, or score and prints the questions and answers in the transcript, plus a one-line notice. It is not a permission gate. `pi-typesafe@0.15.1` provides `/typesafe` and `typesafe_evaluate` for explicit structured decisions; `/typesafe enable` or `PI_TYPESAFE_ENABLED=1` is still required for agent tool calls. The default backend remains `https://api.typesafe.ai`. `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` select the session backend and model, and `/typesafe login` stores a key for the named backend; an unknown backend name is a configuration error at session start, so `/typesafe login`, `logout`, `setup`, `enable`, `test`, and `playground` decline until `PI_TYPESAFE_BACKEND` is fixed or unset. Login proves a candidate key in isolation on backends whose public model lists do not verify keys, so a rejected candidate does not write `usage.json` or mark that backend rejected. Only HTTP 401 refuses that key, and only for 15 minutes; a 403 refuses one request and leaves the key usable. Nace.AI (`https://console.nace.ai`, `NACE_API_KEY`, default model `drex-v2.0`) is a judgment backend. Daily request, token, and USD caps are opt-in. OpenRouter, Command Code, Liquid, SubQ, Nace.AI, and a named endpoint stay explicit and use that backend's own key. The promoted SDK is `@typesafe-ai/sdk@0.7.0`. Under Bun, the judge transport reads each response body once and replays it, so the SDK can still read the result after Bun marks the original body used.
67
67
 
68
68
  `@herbertgao/sol-pi` adds opt-in Action Fusion, ObservationPack, Evidence-Preserving Reducer, and Online Context Compact; see its [configuration guide](../sol-pi/docs/configuration.md). `pi-lens@4.5.1` publishes a public LSP config schema, reads user-level custom rule directories (project before user before built-in), normalizes argv-style server entries, downgrades `throw-new-error` to a warning, and counts Docker, JSON, and Jedi servers in idle eviction; language routing and the retained multi-root diagnostic facts are unchanged. `.mts` and `.cts` use the TypeScript rules. Groovy files still classify as Groovy, and the vendored Groovy grammar lists classes and methods. `--no-read-expansion` turns off read widening without disabling the read-before-edit guard. It promotes `@ast-grep/cli` to `0.51.1` and `@ast-grep/napi` to `^0.51.0`. A blank `PI_LENS_*` number falls back to the default, and an explicit `0` is a value. An edit that raises a named function past the high-complexity threshold and past the default branch names that function on one line; a function the edit improved, or that is still no worse than the default branch, is not named. `ast_grep_replace` no longer requests strict JSON-schema sampling; `lens_diagnostic_mark` still does. A language server for a project outside the session folder starts only when Pi would trust that project. Four MCP tools advertise only `path`. A session rooted at `/` keeps `lsp.disabledServers`. Concatenated SQL passed to `.execute()` is an advisory full-analysis finding; a parameterized `execute(sql, values)` call stays quiet. Keeping injected findings in later requests is opt-in. A workspace edit through a dangling symlink is refused, and a symlink that resolves outside the workspace is refused; the fallback Biome config no longer names a nursery rule. An identity `filter(x => x).map(...)` stays a warning, and a non-identity `filter(fn).map(...)` is no longer flagged. An async array callback with a block body is not flagged for a missing return. A sync block callback that does not return still is. `--lens-issues-status` can show diagnostic counts in the footer and stays off unless set. Esc cancels a hung language-server request instead of leaving that server busy. A reduce that copies its accumulator with `Object.assign` is a warning. A directory whose name starts with `..` stays inside its project. `.groovy`, `.gvy`, `.gy`, `.gsh`, `Jenkinsfile`, `build.gradle`, and `settings.gradle` classify as Groovy; `build.gradle.kts` does not. `minimatch` is `^11.0.4` and `vscode-jsonrpc` is `^10.0.0`. `pi-web-access@0.48.0` provides configurable web search and fetch tools; its `toolActivation` defaults to `auto`, choosing eager or dynamic tool activation per model. `toolActivation: "none"` stays opt-in and still requires deferred exposure. Field extraction, 9router, empty or off-topic search fallback, and plain HTTP gateway URLs stay off unless configured. An unknown tool-call provider name fails instead of selecting a provider automatically, and DuckDuckGo searches stay spaced apart after a bot check. It adds structured search/fetch data for codemode and an optional, manually started `pi-web-access-mcp` stdio CLI; installing the aggregate does not start that server. Degoog, Keenable, Ceramic, Linkup, DeepSeek fetch, Cloudflare search, SearchApi, Outcrawl, Sofya, cloro, Autom, SpecStream, and Tabstack are explicit-only, excluded from automatic and `all` selection. DuckDuckGo searches in one process start at least 10 seconds apart and at most 10 in any 10 minutes. `lockProxy: true` rejects a tool-call proxy other than the configured one. A GitHub repository README is returned up to 100K characters, and a clone with no `githubClone.clonePath` goes under the OS temp directory. Optional `fetchContent.curl` and Exa/Tabstack fetch routing stay off unless configured. Provider gateway base URLs are opt-in and are not configured by the aggregate. OpenAI search now defaults to `gpt-6-luna`, results and clone cleanup are scoped per extension instance, and the promoted `@modelcontextprotocol/sdk@^1.32.1` moves the bundle off GHSA-6qxp-vccf-f47h. Perplexity search now uses the Search API's ranked pages and snippets rather than a Sonar-generated answer; requests requiring prose still use Sonar. `@estebanforge/pi-antigravity-bridge@1.13.1` keeps provider id `antigravity` and requires the host `agy` CLI (`agy acp` by default). It does not register `google_search`, `read_url_content`, or `generate_image`; use `pi-web-access` or the bridge's opt-in web tools instead. Pi peers supply `typebox`; promoted `undici@^8.11.2` remains for web access. `pi-provider-qoder@0.6.13` registers the `qoder` and `qoder-cn` model providers. A plan-disabled catalog model stays listed so a configured model still resolves, and auto stays hidden unless the server enables it. After login the provider refreshes that catalog, waiting at most 15 seconds, instead of keeping the static fallback until restart. A tool-call argument stream that is cut off before a usable call is reported as a retryable server error. Startup logs one line when the npm registry has a newer release; `PI_PROVIDER_QODER_SKIP_UPDATE_CHECK=1` skips that lookup. A queued model-busy response reports its wait instead of being ignored; a ready busy response stays retryable. A queued wait that does not fit in a safe millisecond count uses `retryAfterSeconds` instead. Agent chat prefers the account's remote-agent node and, on daily chat limit code 110, tries the next node. The chosen node is cached for one hour. Sign in with `/login qoder` (browser or a personal access token from [qoder.com/account/integrations](https://qoder.com/account/integrations)) or `/login qoder-cn` (token from [qoder.com.cn/account/integrations](https://qoder.com.cn/account/integrations)). `QODER_PERSONAL_ACCESS_TOKEN` and `QODERCN_PERSONAL_ACCESS_TOKEN` log those providers in at startup. `/qoder-usage footer on` replaces the status-bar footer for that session, so leave it off while the pi-cc footer is in use. `pi-commandcode-provider@0.8.6` registers `commandcode` beside `qoder`, `qoder-cn`, and `antigravity`. Inference uses the Provider API only. `/login` lists those subscription providers and runs only the one you select. `@tifan/pi-preferred-thinking` is no longer bundled. Per-model thinking levels come from Pi. Deprecated `@tifan/pi-titlebar-spinner` is no longer bundled; Rename remains the single owner of Herdr tab naming. `@tifan/pi-handoff` imports `@tifan/pi-rename/naming` when it generates a session name, so Rename stays installed and its `/rename` command stays registered.
69
69
 
@@ -88,7 +88,7 @@ The aggregate bundles [`@estebanforge/pi-antigravity-bridge`](https://github.com
88
88
 
89
89
  ## `pi-typesafe`
90
90
 
91
- The aggregate bundles [`pi-typesafe`](https://github.com/DevMortimer/pi-typesafe) version 0.14.0 under its original MIT license:
91
+ The aggregate bundles [`pi-typesafe`](https://github.com/DevMortimer/pi-typesafe) version 0.15.1 under its original MIT license:
92
92
 
93
93
  MIT License
94
94
 
@@ -142,7 +142,7 @@ if (!answer.ok) return { skipped: answer.errorCode === "budget" }; // never thr
142
142
 
143
143
  Your extension owns its own user consent and budget; `/typesafe enable` applies only to this package's tool. Check `authState()` rather than your own consent flag before you report that judgments are on.
144
144
 
145
- Judgments can also go through OpenRouter: `createTypeSafe({ backend: "openrouter" })` sends them to `openrouter.ai` with the key from `OPENROUTER_API_KEY`. Command Code serves the same protocol: `createTypeSafe({ backend: "commandcode" })` sends them to `api.commandcode.ai` with the key from `COMMANDCODE_API_KEY` and the model `typesafe/jev`. So does Liquid AI: `createTypeSafe({ backend: "liquid" })` sends them to `api.liquid.ai` with the key from `LIQUID_API_KEY` and the model `d1:free`, which is free; pass `model: "d1"` for the paid model, priced at $0.040 per million input tokens. Liquid counts the state once per question, where TypeSafe counts it once per request, so a request with N questions costs about N times the state on Liquid. Speed, measured on 2026-10-03 with one request at a time: `d1:free` took a median of about 14 seconds and sometimes failed with HTTP 504 after about 46 seconds, while `d1` took about 0.5 seconds. With `d1:free`, raise `timeoutMs` above its 15-second default, or pass `model: "d1"`. SubQ too: `createTypeSafe({ backend: "subq" })` sends them to `api.subq.ai` with the key from `SUBQ_API_KEY` and the model `subq-snap-preview`, priced at $0.05 per million input tokens. SubQ takes at most 16 questions in one request, a Choice of at least 2 options, and a Score of at most 10 levels: `evaluate` refuses a larger request before it sends it, `evaluateAll` splits to 16, and `client.limits` tells you the limit without a request. Nace.AI serves Drex the same way: `createTypeSafe({ backend: "nace" })` sends judgments to `console.nace.ai` with the key from `NACE_API_KEY` and the model `drex-v2.0`, priced at $0.060 per million input tokens; `drex-v1.5` is $0.050, and `drex-max` and `drex-max-v1.1` are $0.030. Nace accepted every request shape the schema allows, so it declares no narrower limits. Drex holds a request for up to 55 seconds upstream, so raise `timeoutMs` above its 15-second default for a heavy request. Or pass a `BackendEndpoint` object as `backend` to name any host that serves the protocol: it brings its own key variable, never reads `TYPESAFE_API_KEY`, and `backendHost()` reports its destination host for your consent text. Each backend's key can also be stored with `/typesafe login <backend>`: it prompts once, proves the key with the backend's model list where that list checks the key and otherwise with one judge request, and saves it under that backend's name, so a key stored for one backend is never sent to another. A backend's own environment variable still wins over its stored key. Pass the same `backend` to `authState`, `keySituation`, and `ensureApiKey`, or the status you report describes the TypeSafe key while the requests use another one. The `/typesafe` commands and the `typesafe_evaluate` tool follow `PI_TYPESAFE_BACKEND` (`typesafe` by default) and name that backend's host, key variable, and model in their consent and status text — so the extension sends judgments where it says it sends them. A name the registry does not know is a `configuration` error at session start, not a silent fallback. `PI_TYPESAFE_MODEL` overrides the backend's default model, written as that backend's own id is written (`jev-1.14`; it is mapped to the backend's id form, so OpenRouter sends `typesafe/jev-1.14`). `/typesafe login [backend]` and `/typesafe logout [backend]` act on the backend they name, or on the session's own backend when they name none, and on a backend whose environment variable is set they say that the variable wins. Every export — the client, `ask`, batching, the usage ledger, auth state, the `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` readers, and the `pi-typesafe/calibrate` and `pi-typesafe/ui` entry points — is in [docs/api.md](docs/api.md).
145
+ Judgments can also go through OpenRouter: `createTypeSafe({ backend: "openrouter" })` sends them to `openrouter.ai` with the key from `OPENROUTER_API_KEY`. Command Code serves the same protocol: `createTypeSafe({ backend: "commandcode" })` sends them to `api.commandcode.ai` with the key from `COMMANDCODE_API_KEY` and the model `typesafe/jev`. So does Liquid AI: `createTypeSafe({ backend: "liquid" })` sends them to `api.liquid.ai` with the key from `LIQUID_API_KEY` and the model `d1:free`, which is free; pass `model: "d1"` for the paid model, priced at $0.040 per million input tokens. Liquid counts the state once per question, where TypeSafe counts it once per request, so a request with N questions costs about N times the state on Liquid. Speed, measured on 2026-10-03 with one request at a time: `d1:free` took a median of about 14 seconds and sometimes failed with HTTP 504 after about 46 seconds, while `d1` took about 0.5 seconds. With `d1:free`, raise `timeoutMs` above its 15-second default, or pass `model: "d1"`. SubQ too: `createTypeSafe({ backend: "subq" })` sends them to `api.subq.ai` with the key from `SUBQ_API_KEY` and the model `subq-snap-preview`, priced at $0.05 per million input tokens. SubQ takes at most 16 questions in one request, a Choice of at least 2 options, and a Score of at most 10 levels: `evaluate` refuses a larger request before it sends it, `evaluateAll` splits to 16, and `client.limits` tells you the limit without a request. Nace.AI serves Drex the same way: `createTypeSafe({ backend: "nace" })` sends judgments to `console.nace.ai` with the key from `NACE_API_KEY` and the model `drex-v2.0`, priced at $0.060 per million input tokens; `drex-v1.5` is $0.050, and `drex-max` and `drex-max-v1.1` are $0.030. Nace accepted every request shape the schema allows, so it declares no narrower limits. Drex holds a request for up to 55 seconds upstream, so raise `timeoutMs` above its 15-second default for a heavy request. Or pass a `BackendEndpoint` object as `backend` to name any host that serves the protocol: it brings its own key variable, never reads `TYPESAFE_API_KEY`, and `backendHost()` reports its destination host for your consent text. Each backend's key can also be stored with `/typesafe login <backend>`: it prompts once, proves the key with the backend's model list where that list checks the key and otherwise with one isolated judge request (without writing `usage.json`, hitting daily caps, or overwriting `auth-state.json` on a rejected candidate key), and saves it under that backend's name, so a key stored for one backend is never sent to another. A backend's own environment variable still wins over its stored key. Pass the same `backend` to `authState`, `keySituation`, and `ensureApiKey`, or the status you report describes the TypeSafe key while the requests use another one. The `/typesafe` commands and the `typesafe_evaluate` tool follow `PI_TYPESAFE_BACKEND` (`typesafe` by default) and name that backend's host, key variable, and model in their consent and status text — so the extension sends judgments where it says it sends them. A name the registry does not know is a `configuration` error at session start, not a silent fallback: `/typesafe login`, `logout`, `setup`, `enable`, `test`, and `playground` all decline until `PI_TYPESAFE_BACKEND` is fixed or unset. `PI_TYPESAFE_MODEL` overrides the backend's default model, written as that backend's own id is written (`jev-1.14`; it is mapped to the backend's id form, so OpenRouter sends `typesafe/jev-1.14`). `/typesafe login [backend]` and `/typesafe logout [backend]` act on the backend they name, or on the session's own backend when they name none, and on a backend whose environment variable is set they say that the variable wins. Every export — the client, `ask`, batching, the usage ledger, auth state, the `PI_TYPESAFE_BACKEND` and `PI_TYPESAFE_MODEL` readers, and the `pi-typesafe/calibrate` and `pi-typesafe/ui` entry points — is in [docs/api.md](docs/api.md).
146
146
 
147
147
  ## Development
148
148
 
@@ -1,4 +1,4 @@
1
- import { TypeSafeIntegrationError } from "./errors.js";
1
+ import { TypeSafeIntegrationError, attachErrorDisposition } from "./errors.js";
2
2
  /** Default per-ask deadline; matches the client's own request timeout. */
3
3
  export const DEFAULT_ASK_TIMEOUT_MS = 15_000;
4
4
  const FALLBACK_MESSAGE = "TypeSafe request failed.";
@@ -22,8 +22,11 @@ export async function ask(judge, request, options = {}) {
22
22
  return { ok: true, answers: result.answers, model: result.model, usage: result.usage, elapsedMs: result.elapsedMs };
23
23
  }
24
24
  catch (error) {
25
- if (error instanceof TypeSafeIntegrationError)
26
- return { ok: false, error: error.message, errorCode: error.code };
25
+ if (error instanceof TypeSafeIntegrationError) {
26
+ const failed = { ok: false, error: error.message, errorCode: error.code };
27
+ attachErrorDisposition(failed, error.disposition);
28
+ return failed;
29
+ }
27
30
  return { ok: false, error: FALLBACK_MESSAGE };
28
31
  }
29
32
  finally {
@@ -20,6 +20,28 @@ export interface AuthFailure {
20
20
  readonly message: string;
21
21
  readonly at: string;
22
22
  }
23
+ /** Explicit auth breaker state for one backend. */
24
+ export type AuthStatus = "missing" | "unusable" | "rejected" | "rejection_expired" | "unverified" | "verified";
25
+ /** Persisted per-backend auth record written through `transitionAuthRecord`. */
26
+ export interface AuthRecord {
27
+ readonly verifiedAt?: string;
28
+ readonly lastFailure?: AuthFailure;
29
+ }
30
+ export type AuthEvent = {
31
+ readonly type: "verified";
32
+ readonly at: string;
33
+ } | {
34
+ readonly type: "failed";
35
+ readonly failure: AuthFailure;
36
+ } | {
37
+ readonly type: "cleared";
38
+ };
39
+ export interface AuthWriteOptions {
40
+ readonly backend?: BackendSpec;
41
+ readonly path?: string;
42
+ }
43
+ /** Single-writer pure transition reducer for one backend's persisted auth record. */
44
+ export declare function transitionAuthRecord(record: AuthRecord, event: AuthEvent): AuthRecord;
23
45
  /**
24
46
  * The whole answer to "is Jev actually available right now": which key is in effect, whether it has been accepted, and
25
47
  * the last failure that degraded it. Consumers must consult this instead of treating their own consent flag as proof
@@ -28,6 +50,8 @@ export interface AuthFailure {
28
50
  export interface AuthState {
29
51
  /** The judgment backend this state describes; each backend has its own key. Holds the value the caller passed. */
30
52
  readonly backend: BackendSpec;
53
+ /** Explicit auth breaker state derived from key presence, persisted record, and the rejection window. */
54
+ readonly status: AuthStatus;
31
55
  /** Same kinds as KeySituation: where the key in effect comes from. */
32
56
  readonly kind: "environment" | "stored" | "missing" | "unusable";
33
57
  readonly source?: KeySource;
@@ -39,8 +63,8 @@ export interface AuthState {
39
63
  readonly keyName: string;
40
64
  /**
41
65
  * True when the key in effect was accepted by the backend (a login proves the backend it was asked for; a successful
42
- * request proves any key). A 401 rejection younger than `AUTH_REJECTION_TTL_MS` clears it; a 403 never does. The
43
- * record is shared across backends: switching backends keeps the last outcome until the next request.
66
+ * request proves any key). A 401 rejection younger than `AUTH_REJECTION_TTL_MS` clears it; a 403 never does. Each
67
+ * backend keeps its own record in `auth-state.json`.
44
68
  */
45
69
  readonly verified: boolean;
46
70
  readonly verifiedAt?: string;
@@ -64,11 +88,11 @@ export declare function authState(options?: {
64
88
  backend?: BackendSpec;
65
89
  }): AuthState;
66
90
  /** Record that the key was accepted: login verification, or any successful request. Clears the last failure. */
67
- export declare function recordAuthVerified(at?: Date): void;
68
- /** Record the failure that degraded TypeSafe. The verification timestamp is kept so a recovered key stays known. */
69
- export declare function recordAuthFailure(error: TypeSafeIntegrationError, at?: Date): void;
70
- /** Forget verification and degradation: used when the key itself changes (login or logout). */
71
- export declare function clearAuthState(): void;
91
+ export declare function recordAuthVerified(at?: Date, options?: AuthWriteOptions): void;
92
+ /** Record the failure that degraded a backend. The verification timestamp is kept so a recovered key stays known. */
93
+ export declare function recordAuthFailure(error: TypeSafeIntegrationError, at?: Date, options?: AuthWriteOptions): void;
94
+ /** Forget verification and degradation: removes the whole file with no backend, or clears only that backend's entry. */
95
+ export declare function clearAuthState(options?: BackendSpec | AuthWriteOptions): void;
72
96
  export interface AuthReport {
73
97
  /**
74
98
  * `error` when judgments will fail or the key was rejected, `warning` when the key is unverified or its rejection has
@@ -1,12 +1,15 @@
1
1
  import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { DEFAULT_BACKEND, TYPESAFE_KEY_ENV, resolveBackend } from "./backends.js";
4
- import { credentialsPath, keySituation, keySourceLabel, piTypesafeDir } from "./credentials.js";
2
+ import { dirname, join } from "node:path";
3
+ import { DEFAULT_BACKEND, resolveBackend } from "./backends.js";
4
+ import { credentialId, credentialsPath, keySituation, keySourceLabel, piTypesafeDir } from "./credentials.js";
5
5
  import { TypeSafeIntegrationError } from "./errors.js";
6
6
  const AUTH_VERSION = 1;
7
7
  const CODES = new Set([
8
8
  "configuration", "validation", "budget", "aborted", "timeout", "http", "connection", "response",
9
9
  ]);
10
+ function assertNever(value) {
11
+ throw new Error(`Unexpected auth state: ${String(value)}`);
12
+ }
10
13
  /**
11
14
  * How long a stored 401 vetoes the key. The next request proves the key again once the window passes, so one refusal
12
15
  * cannot disable judgments for good. Fifteen minutes is a policy choice, not a measured provider constant.
@@ -20,47 +23,101 @@ export const AUTH_REJECTION_TTL_MS = 15 * 60 * 1000;
20
23
  export function isKeyRejection(status) {
21
24
  return status === 401;
22
25
  }
26
+ /** Single-writer pure transition reducer for one backend's persisted auth record. */
27
+ export function transitionAuthRecord(record, event) {
28
+ switch (event.type) {
29
+ case "verified":
30
+ return { verifiedAt: event.at };
31
+ case "failed":
32
+ return {
33
+ ...(record.verifiedAt === undefined ? {} : { verifiedAt: record.verifiedAt }),
34
+ lastFailure: event.failure,
35
+ };
36
+ case "cleared":
37
+ return {};
38
+ default:
39
+ return assertNever(event);
40
+ }
41
+ }
23
42
  /** `fresh` still vetoes the key, `expired` is only a record of what was refused when: no schema change, no manual reset. */
24
- function rejectionOf(failure) {
43
+ function rejectionOf(failure, nowMs) {
25
44
  if (failure === undefined || failure.code !== "http" || !isKeyRejection(failure.status))
26
45
  return "none";
27
46
  const at = Date.parse(failure.at);
28
47
  // A timestamp this code cannot read cannot prove the rejection is current, so it counts as spent.
29
48
  if (!Number.isFinite(at))
30
49
  return "expired";
31
- return Date.now() - at < AUTH_REJECTION_TTL_MS ? "fresh" : "expired";
50
+ return nowMs - at < AUTH_REJECTION_TTL_MS ? "fresh" : "expired";
51
+ }
52
+ function evaluateAuth(situation, record, nowMs) {
53
+ const rejection = rejectionOf(record.lastFailure, nowMs);
54
+ const status = situation.kind === "missing" ? "missing"
55
+ : situation.kind === "unusable" ? "unusable"
56
+ : rejection === "fresh" ? "rejected"
57
+ : rejection === "expired" ? "rejection_expired"
58
+ : record.verifiedAt === undefined ? "unverified"
59
+ : "verified";
60
+ const usable = status !== "missing" && status !== "unusable" && status !== "rejected";
61
+ // Keeps `verified` aligned with `verifiedAt` whenever no fresh 401 stands against it (including expired 401s).
62
+ const verified = record.verifiedAt !== undefined && rejection !== "fresh";
63
+ return { status, usable, verified };
32
64
  }
33
65
  /** The auth-state file: one small, owner-only record that outlives the process that wrote it. */
34
66
  export function authStatePath() {
35
67
  return join(piTypesafeDir(), "auth-state.json");
36
68
  }
37
- function readState(path) {
69
+ function parseRecord(raw) {
70
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
71
+ return {};
72
+ const obj = raw;
73
+ const verifiedAt = typeof obj.verifiedAt === "string" && obj.verifiedAt.length <= 40 ? obj.verifiedAt : undefined;
74
+ const failure = obj.lastFailure && typeof obj.lastFailure === "object" && !Array.isArray(obj.lastFailure)
75
+ ? obj.lastFailure
76
+ : undefined;
77
+ const code = typeof failure?.code === "string" && CODES.has(failure.code) ? failure.code : undefined;
78
+ const message = typeof failure?.message === "string" ? failure.message.slice(0, 300) : undefined;
79
+ const at = typeof failure?.at === "string" && failure.at.length <= 40 ? failure.at : undefined;
80
+ const status = typeof failure?.status === "number" && Number.isSafeInteger(failure.status) ? failure.status : undefined;
81
+ const lastFailure = code && message && at
82
+ ? { code, message, at, ...(status === undefined ? {} : { status }) }
83
+ : undefined;
84
+ return { ...(verifiedAt === undefined ? {} : { verifiedAt }), ...(lastFailure === undefined ? {} : { lastFailure }) };
85
+ }
86
+ function isNonEmptyRecord(record) {
87
+ return record.verifiedAt !== undefined || record.lastFailure !== undefined;
88
+ }
89
+ function readStateMap(path) {
90
+ const map = Object.create(null);
38
91
  try {
39
92
  const parsed = JSON.parse(readFileSync(path, "utf8"));
40
- if (!parsed || typeof parsed !== "object")
41
- return {};
93
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
94
+ return map;
42
95
  const raw = parsed;
43
- const verifiedAt = typeof raw.verifiedAt === "string" && raw.verifiedAt.length <= 40 ? raw.verifiedAt : undefined;
44
- const failure = raw.lastFailure && typeof raw.lastFailure === "object" ? raw.lastFailure : undefined;
45
- const code = typeof failure?.code === "string" && CODES.has(failure.code) ? failure.code : undefined;
46
- const message = typeof failure?.message === "string" ? failure.message.slice(0, 300) : undefined;
47
- const at = typeof failure?.at === "string" && failure.at.length <= 40 ? failure.at : undefined;
48
- const status = typeof failure?.status === "number" && Number.isSafeInteger(failure.status) ? failure.status : undefined;
49
- const lastFailure = code && message && at
50
- ? { code, message, at, ...(status === undefined ? {} : { status }) }
51
- : undefined;
52
- return { ...(verifiedAt === undefined ? {} : { verifiedAt }), ...(lastFailure === undefined ? {} : { lastFailure }) };
96
+ if (raw.backends && typeof raw.backends === "object" && !Array.isArray(raw.backends)) {
97
+ for (const [id, entry] of Object.entries(raw.backends)) {
98
+ const record = parseRecord(entry);
99
+ if (isNonEmptyRecord(record))
100
+ map[id] = record;
101
+ }
102
+ }
103
+ // Pre-per-backend files hold top-level verifiedAt/lastFailure; heal them into DEFAULT_BACKEND on read.
104
+ if (!(DEFAULT_BACKEND in map)) {
105
+ const legacy = parseRecord(raw);
106
+ if (isNonEmptyRecord(legacy))
107
+ map[DEFAULT_BACKEND] = legacy;
108
+ }
109
+ return map;
53
110
  }
54
111
  catch {
55
- return {};
112
+ return map;
56
113
  }
57
114
  }
58
115
  /** Owner-only, atomic, and best-effort: an unwritable auth record never changes how a request behaves. */
59
- function writeState(path, state) {
116
+ function writeStateMap(path, backends) {
60
117
  const temporary = `${path}.${process.pid}.tmp`;
61
118
  try {
62
- mkdirSync(piTypesafeDir(), { recursive: true, mode: 0o700 });
63
- writeFileSync(temporary, `${JSON.stringify({ version: AUTH_VERSION, ...state }, null, 2)}\n`, { mode: 0o600, flag: "w" });
119
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
120
+ writeFileSync(temporary, `${JSON.stringify({ version: AUTH_VERSION, backends: { ...backends } }, null, 2)}\n`, { mode: 0o600, flag: "w" });
64
121
  chmodSync(temporary, 0o600);
65
122
  renameSync(temporary, path);
66
123
  }
@@ -71,6 +128,9 @@ function writeState(path, state) {
71
128
  catch { /* best-effort cleanup only */ }
72
129
  }
73
130
  }
131
+ function isBackendEndpoint(value) {
132
+ return "host" in value || "label" in value || "keyEnv" in value;
133
+ }
74
134
  /**
75
135
  * What the key situation, the last outcome, and the clock add up to for a valid backend; it never throws for one. An
76
136
  * invalid backend throws the same `configuration` error as resolveBackend(), so validate a user-supplied endpoint
@@ -80,44 +140,87 @@ export function authState(options = {}) {
80
140
  const path = options.path ?? authStatePath();
81
141
  const backend = options.backend ?? DEFAULT_BACKEND;
82
142
  const situation = keySituation(backend);
83
- const stored = readState(path);
143
+ const stored = readStateMap(path)[credentialId(backend)] ?? {};
84
144
  const source = situation.kind === "environment" ? "environment" : situation.kind === "stored" ? "stored" : undefined;
85
- const rejected = rejectionOf(stored.lastFailure) === "fresh";
86
- const usable = source !== undefined && !rejected;
145
+ const { status, usable, verified } = evaluateAuth(situation, stored, Date.now());
87
146
  return {
88
147
  backend,
148
+ status,
89
149
  kind: situation.kind,
90
150
  ...(source === undefined ? {} : { source }),
91
151
  path: situation.kind === "unusable" ? situation.path : credentialsPath(),
92
152
  ...(situation.kind === "unusable" ? { reason: situation.reason } : {}),
93
153
  keyName: keySourceLabel(situation),
94
- verified: stored.verifiedAt !== undefined && !rejected,
154
+ verified,
95
155
  ...(stored.verifiedAt === undefined ? {} : { verifiedAt: stored.verifiedAt }),
96
156
  ...(stored.lastFailure === undefined ? {} : { lastFailure: stored.lastFailure }),
97
157
  usable,
98
158
  };
99
159
  }
100
160
  /** Record that the key was accepted: login verification, or any successful request. Clears the last failure. */
101
- export function recordAuthVerified(at = new Date()) {
102
- writeState(authStatePath(), { verifiedAt: at.toISOString() });
161
+ export function recordAuthVerified(at = new Date(), options = {}) {
162
+ const path = options.path ?? authStatePath();
163
+ const id = credentialId(options.backend);
164
+ const map = readStateMap(path);
165
+ map[id] = transitionAuthRecord(map[id] ?? {}, { type: "verified", at: at.toISOString() });
166
+ writeStateMap(path, map);
103
167
  }
104
- /** Record the failure that degraded TypeSafe. The verification timestamp is kept so a recovered key stays known. */
105
- export function recordAuthFailure(error, at = new Date()) {
106
- const current = readState(authStatePath());
168
+ /** Record the failure that degraded a backend. The verification timestamp is kept so a recovered key stays known. */
169
+ export function recordAuthFailure(error, at = new Date(), options = {}) {
170
+ const path = options.path ?? authStatePath();
171
+ const id = credentialId(options.backend);
172
+ const map = readStateMap(path);
107
173
  const failure = {
108
174
  code: error.code,
109
175
  message: error.message,
110
176
  at: at.toISOString(),
111
177
  ...(error.status === undefined ? {} : { status: error.status }),
112
178
  };
113
- writeState(authStatePath(), { ...(current.verifiedAt === undefined ? {} : { verifiedAt: current.verifiedAt }), lastFailure: failure });
179
+ map[id] = transitionAuthRecord(map[id] ?? {}, { type: "failed", failure });
180
+ writeStateMap(path, map);
114
181
  }
115
- /** Forget verification and degradation: used when the key itself changes (login or logout). */
116
- export function clearAuthState() {
117
- try {
118
- rmSync(authStatePath(), { force: true });
182
+ /** Forget verification and degradation: removes the whole file with no backend, or clears only that backend's entry. */
183
+ export function clearAuthState(options) {
184
+ let backend;
185
+ let path = authStatePath();
186
+ if (typeof options === "string") {
187
+ backend = options;
188
+ }
189
+ else if (options !== undefined) {
190
+ if (isBackendEndpoint(options)) {
191
+ backend = options;
192
+ }
193
+ else {
194
+ backend = options.backend;
195
+ if (options.path !== undefined)
196
+ path = options.path;
197
+ }
198
+ }
199
+ if (backend === undefined) {
200
+ try {
201
+ rmSync(path, { force: true });
202
+ }
203
+ catch { /* nothing to clear */ }
204
+ return;
205
+ }
206
+ const id = credentialId(backend);
207
+ const map = readStateMap(path);
208
+ if (!(id in map))
209
+ return;
210
+ const next = transitionAuthRecord(map[id] ?? {}, { type: "cleared" });
211
+ if (!isNonEmptyRecord(next))
212
+ delete map[id];
213
+ else
214
+ map[id] = next;
215
+ if (Object.keys(map).length === 0) {
216
+ try {
217
+ rmSync(path, { force: true });
218
+ }
219
+ catch { /* nothing to clear */ }
220
+ }
221
+ else {
222
+ writeStateMap(path, map);
119
223
  }
120
- catch { /* nothing to clear */ }
121
224
  }
122
225
  /**
123
226
  * One line plus a level, so a status command, a headless log, or a consumer's own status line can call out a degraded
@@ -127,23 +230,24 @@ export function describeAuth(state = authState()) {
127
230
  const config = resolveBackend(state.backend);
128
231
  const label = `${config.label} key`;
129
232
  const since = state.lastFailure ? ` Last failure: ${state.lastFailure.message}${state.lastFailure.at ? ` (${state.lastFailure.at})` : ""}` : "";
130
- if (state.kind === "missing") {
131
- const how = `a key is configured (/typesafe login${config.name && config.name !== DEFAULT_BACKEND ? ` ${config.name}` : ""} or ${config.keyEnv})`;
132
- return { level: "error", text: `${label}: missing — every Jev judgment will fail until ${how}.${since}` };
133
- }
134
- if (state.kind === "unusable") {
135
- return { level: "error", text: `${label}: unusable (${state.reason ?? "unknown reason"}) — judgments will fail until the key is fixed.${since}` };
136
- }
137
- const rejection = rejectionOf(state.lastFailure);
138
- if (rejection === "fresh") {
139
- return { level: "error", text: `${label}: ${state.keyName} was rejected.${since}` };
140
- }
141
- if (rejection === "expired") {
142
- const at = state.lastFailure?.at;
143
- return { level: "warning", text: `${label}: ${state.keyName} was rejected${at === undefined ? "" : ` at ${at}`}; that rejection expired, so the next request proves the key.` };
144
- }
145
- if (!state.verified) {
146
- return { level: "warning", text: `${label}: ${state.keyName} (not verified yet — the first request proves it).${since}` };
233
+ switch (state.status) {
234
+ case "missing": {
235
+ const how = `a key is configured (/typesafe login${config.name && config.name !== DEFAULT_BACKEND ? ` ${config.name}` : ""} or ${config.keyEnv})`;
236
+ return { level: "error", text: `${label}: missing — every Jev judgment will fail until ${how}.${since}` };
237
+ }
238
+ case "unusable":
239
+ return { level: "error", text: `${label}: unusable (${state.reason ?? "unknown reason"}) — judgments will fail until the key is fixed.${since}` };
240
+ case "rejected":
241
+ return { level: "error", text: `${label}: ${state.keyName} was rejected.${since}` };
242
+ case "rejection_expired": {
243
+ const at = state.lastFailure?.at;
244
+ return { level: "warning", text: `${label}: ${state.keyName} was rejected${at === undefined ? "" : ` at ${at}`}; that rejection expired, so the next request proves the key.` };
245
+ }
246
+ case "unverified":
247
+ return { level: "warning", text: `${label}: ${state.keyName} (not verified yet — the first request proves it).${since}` };
248
+ case "verified":
249
+ return { level: "ok", text: `${label}: ${state.keyName} (verified${state.verifiedAt ? ` ${state.verifiedAt}` : ""}).${since}` };
250
+ default:
251
+ return assertNever(state.status);
147
252
  }
148
- return { level: "ok", text: `${label}: ${state.keyName} (verified${state.verifiedAt ? ` ${state.verifiedAt}` : ""}).${since}` };
149
253
  }
@@ -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,