opencode-devin 0.1.1 → 0.2.1

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.
package/README.md CHANGED
@@ -59,17 +59,25 @@ opencode run --model devin/swe-2-max "Refactor the auth module"
59
59
 
60
60
  ## How it works
61
61
 
62
- ```
63
- /connect ──▶ app.devin.ai PKCE login ──▶ devin-session-token$<JWT>
64
- │ │
65
- ▼ ▼
66
- stored as an OpenCode credential GetCascadeModelConfigs (gRPC)
67
- │
68
- ▼
69
- provider `devin`
70
- │
71
- ▼
72
- ai-sdk-devin ──▶ Cascade gRPC (GetUserJwt + GetChatMessage)
62
+ ```mermaid
63
+ flowchart TD
64
+ subgraph Login["Login — /connect"]
65
+ A["/connect → Log in with Devin"] --> B["app.devin.ai/auth/cli/continue<br/>PKCE + S256, loopback callback on 127.0.0.1"]
66
+ B --> C["api.devin.ai/auth/cli/token"]
67
+ C --> D[("devin-session-token$JWT<br/>stored as an OpenCode credential")]
68
+ end
69
+
70
+ subgraph Catalog["Catalog — /models"]
71
+ D --> E["GetCascadeModelConfigs (gRPC)<br/>live per-account model list"]
72
+ E --> F["devin/* models"]
73
+ end
74
+
75
+ subgraph Chat["Chat — agent loop"]
76
+ D --> G["GetUserJwt → short-lived user_jwt"]
77
+ G --> H["GetChatMessage<br/>Cascade gRPC streaming"]
78
+ end
79
+
80
+ D -. "credential events → re-publish" .-> Catalog
73
81
  ```
74
82
 
75
83
  1. **Integration** — the plugin registers a `devin` integration with the Devin CLI login flow: PKCE (S256) against `app.devin.ai/auth/cli/continue`, a loopback callback on `127.0.0.1` (or manual code paste), and a token exchange at `api.devin.ai/auth/cli/token`.
@@ -79,24 +87,103 @@ opencode run --model devin/swe-2-max "Refactor the auth module"
79
87
 
80
88
  ## Troubleshooting
81
89
 
82
- - **No `devin/` models** — the credential is missing or the catalog fetch failed. Run `/connect` again.
83
- - **401 during chat** — the session token was revoked. Re-run `/connect`.
90
+ - **No `devin/` models**: run `/connect` again. Failures are logged as `[opencode-devin] ...`; the log is at `~/.local/share/opencode/log/opencode.log`.
91
+ - **A model is rejected even though `/models` lists it**: the account can see a uid it is not entitled to. The error names the tier.
92
+ - **Costs look wrong or absent**: OpenCode reads cost from the pricing published to `/models`, not from the stream. Check the model has a non-zero price there — `bun scripts/devin.ts verify` dumps what the catalog actually reports.
93
+ - **A 401 during chat**: the short-lived token is refreshed automatically. Reconnect only if the session token itself was revoked.
94
+ - **`Plugin failed to load`**: rebuild and `opencode reload`. See the FAQ on atomic builds.
95
+ - **A path in `plugins` is ignored**: only `name@file:<absolute-path>` links a local build.
84
96
 
85
97
  ## Development
86
98
 
87
99
  ```sh
88
100
  bun install
89
101
  npm run typecheck
90
- npm run build # emits dist/
102
+ bun test
103
+ npm run build
104
+ ```
105
+
106
+ `build` is atomic, so the plugin can be reloaded while it runs. Publishing uses
107
+ `build:clean`, which wipes `dist/` first.
108
+
109
+ Shared fixtures for the synthetic-catalog tests live in `test/helpers.ts`
110
+ (fake JWTs, protobuf `modelConfig`/`catalogReply` encoders, `stubFetch`).
111
+
112
+ ### Developing against a local build
113
+
114
+ Edit `plugins` in `~/.config/opencode/opencode.json` to one of these, then run
115
+ `npm run build && opencode reload`:
116
+
117
+ ```jsonc
118
+ // this repository
119
+ { "plugins": ["opencode-devin@file:C:/path/to/opencode-devin"] }
120
+
121
+ // the published package
122
+ { "plugins": ["opencode-devin"] }
123
+ ```
124
+
125
+ The path must be absolute, and the `name@file:` form is required: a bare path
126
+ or a `file://` URL is ignored without an error.
127
+
128
+ To confirm which copy the server loaded:
129
+
130
+ ```sh
131
+ opencode api provider.list # the devin provider's "package" field
91
132
  ```
92
133
 
93
- To test a local checkout without publishing, create a bridge file that re-exports the build:
134
+ ### Testing against the real API
94
135
 
95
- ```ts
96
- // ~/.config/opencode/plugins/devin.ts
97
- export { default } from "file:///absolute/path/to/opencode-devin/dist/index.js"
136
+ `bun test` runs everything except the live suite, which skips itself without a
137
+ credential. The dev CLI gets you one and runs the whole check end to end:
138
+
139
+ ```sh
140
+ bun scripts/devin.ts all # login (if needed) → catalog dump → live tests
141
+ bun scripts/devin.ts login # just the PKCE login → .devin-token.env
142
+ bun scripts/devin.ts verify # dump live catalog pricing
143
+ bun scripts/devin.ts test # run test/live.test.ts
98
144
  ```
99
145
 
146
+ The login is the same browser PKCE flow as `/connect` (loopback callback, or
147
+ `--manual` for paste-code on headless machines). The token lands in
148
+ `.devin-token.env`, which `verify`/`test`/`all` pick up automatically, so a
149
+ second `all` run skips the browser entirely.
150
+
151
+ Or with a token you already have:
152
+
153
+ ```sh
154
+ DEVIN_LLM_API_KEY='devin-session-token$...' bun test test/live.test.ts
155
+ ```
156
+
157
+ ## FAQ
158
+
159
+ **Why is `build` atomic?** OpenCode reloads a linked plugin the moment its
160
+ entrypoint changes, and a failed load is not retried. Writing `dist/` in place
161
+ lets a reload land mid-write and fail, which shows up as `ENOENT reading
162
+ dist/index.js` or `Cannot find module '.../constants.js'`. `build` compiles to a
163
+ staging directory and swaps it in.
164
+
165
+ **Why a second protobuf implementation in the tests?** The suite encodes and
166
+ decodes with the same module, which only proves the two halves agree — they
167
+ could both be wrong. `wire-conformance.test.ts` checks the framing against
168
+ `protobufjs`, which shares no code with this repository. It is a dev-only
169
+ dependency.
170
+
171
+ **What the tests cannot check.** The Cascade field numbers were recovered by
172
+ reverse-engineering the Devin CLI. Only `test/live.test.ts`, which talks to
173
+ Cognition, can notice them changing. All three RPCs have been exercised against
174
+ the live API, but nothing guards a future upstream change; a committed capture of
175
+ real responses would, and there is not one yet.
176
+
177
+ **Why doesn't a missing model fail immediately?** Because the catalog is not
178
+ guaranteed to list every uid Cascade accepts, and refusing one that works would
179
+ be worse than a vague error. Disabled models are refused outright; unknown ones
180
+ are warned about, and the likely reason is appended if the request fails.
181
+
182
+ **Why is the session token in the provider registry?** It is passed as
183
+ `settings.apiKey`, which is how the provider receives it. `opencode api
184
+ provider.list` therefore returns it in clear text. Treat that output as a
185
+ secret.
186
+
100
187
  ## Credits
101
188
 
102
189
  - The Cascade protocol client is a **typed TypeScript port**, owned in `src/protocol/` (see `ATTRIBUTION.md`) — originally from [`ai-sdk-devin`](https://www.npmjs.com/package/ai-sdk-devin) by [karthiknish](https://github.com/karthiknish) and `pi-devin-auth` by nmzpy, both MIT. Owning the port keeps the credential path free of third-party runtime dependencies.
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Open a URL in the system browser.
3
+ *
4
+ * Windows: `cmd /c start` truncates URLs at "&" (cmd metacharacter) when
5
+ * spawned from Bun — rundll32 hands the URL to the default browser verbatim.
6
+ */
7
+ export declare function openBrowser(url: string): void;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Open a URL in the system browser.
3
+ *
4
+ * Windows: `cmd /c start` truncates URLs at "&" (cmd metacharacter) when
5
+ * spawned from Bun — rundll32 hands the URL to the default browser verbatim.
6
+ */
7
+ export function openBrowser(url) {
8
+ if (process.platform === "win32") {
9
+ Bun.spawn(["rundll32", "url.dll,FileProtocolHandler", url], {
10
+ stdin: "ignore",
11
+ stdout: "ignore",
12
+ stderr: "ignore",
13
+ });
14
+ return;
15
+ }
16
+ const cmd = process.platform === "darwin" ? ["open", url] : ["xdg-open", url];
17
+ Bun.spawn(cmd, { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
18
+ }
@@ -0,0 +1,15 @@
1
+ import { type CallbackServer } from "./loopback.ts";
2
+ export interface LoginFlow {
3
+ /** URL to open in the browser. */
4
+ url: string;
5
+ /** Resolve with the authorization code (auto: wait for redirect; code: pass the pasted code). */
6
+ finish: (code?: string) => Promise<string>;
7
+ /** Abort the flow and release resources. */
8
+ close: () => void;
9
+ }
10
+ /** Start an automatic login: binds the loopback server and returns the URL to open. */
11
+ export declare function loginAuto(): Promise<LoginFlow & {
12
+ server: CallbackServer;
13
+ }>;
14
+ /** Start a manual login: no loopback; the webapp displays the code for pasting. */
15
+ export declare function loginManual(): Promise<LoginFlow>;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Devin CLI login flow (PKCE), shared by the plugin's `/connect` methods and
3
+ * the standalone `scripts/devin.ts login` command.
4
+ *
5
+ * Two modes, matching what the webapp supports:
6
+ * - "auto": loopback callback — browser redirects to 127.0.0.1, we capture
7
+ * the code. Hands-free once the user finishes the web login.
8
+ * - "code": no redirect_uri — the webapp shows a code the user pastes back.
9
+ * Fallback for headless machines and environments where loopback
10
+ * redirects can't reach the browser.
11
+ */
12
+ import { authorizeUrl } from "./url.js";
13
+ import { exchangeCode } from "./exchange.js";
14
+ import { startCallbackServer } from "./loopback.js";
15
+ import { challengeFor, generateState, generateVerifier } from "./pkce.js";
16
+ /** Start an automatic login: binds the loopback server and returns the URL to open. */
17
+ export async function loginAuto() {
18
+ const verifier = generateVerifier();
19
+ const state = generateState();
20
+ const server = await startCallbackServer(state);
21
+ const url = authorizeUrl({ state, challenge: await challengeFor(verifier), redirectUri: server.redirectUri });
22
+ return {
23
+ url,
24
+ server,
25
+ finish: async () => {
26
+ try {
27
+ const code = await server.code;
28
+ return await exchangeCode({ code, verifier });
29
+ }
30
+ finally {
31
+ server.close();
32
+ }
33
+ },
34
+ close: () => server.close(),
35
+ };
36
+ }
37
+ /** Start a manual login: no loopback; the webapp displays the code for pasting. */
38
+ export async function loginManual() {
39
+ const verifier = generateVerifier();
40
+ const state = generateState();
41
+ const url = authorizeUrl({ state, challenge: await challengeFor(verifier) });
42
+ return {
43
+ url,
44
+ finish: async (code) => {
45
+ if (!code?.trim())
46
+ throw new Error("Manual login requires the pasted authorization code");
47
+ return exchangeCode({ code: code.trim(), verifier });
48
+ },
49
+ close: () => { },
50
+ };
51
+ }
@@ -12,4 +12,4 @@ export interface CallbackServer {
12
12
  close: () => void;
13
13
  }
14
14
  /** Bind a one-shot HTTP server and wait for the authorization code. */
15
- export declare function startCallbackServer(state: string): Promise<CallbackServer>;
15
+ export declare function startCallbackServer(state: string, timeoutMs?: number): Promise<CallbackServer>;
@@ -7,8 +7,19 @@
7
7
  * the caller awaits the promise.
8
8
  */
9
9
  import { CALLBACK_PATH } from "../constants.js";
10
+ /**
11
+ * How long the loopback listener stays armed waiting for the browser redirect.
12
+ *
13
+ * The integration method registration has no cancellation hook, so an
14
+ * abandoned sign-in (tab closed, user picked the paste-code method instead)
15
+ * would otherwise leave the port bound and the HTTP server running for the
16
+ * life of the process. This timer is the only place that can be cleaned up
17
+ * from, so it is the backstop. Long enough for a real interactive login
18
+ * including any second factor.
19
+ */
20
+ const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
10
21
  /** Bind a one-shot HTTP server and wait for the authorization code. */
11
- export function startCallbackServer(state) {
22
+ export function startCallbackServer(state, timeoutMs = CALLBACK_TIMEOUT_MS) {
12
23
  return new Promise((resolve, reject) => {
13
24
  let settle;
14
25
  let fail;
@@ -16,6 +27,20 @@ export function startCallbackServer(state) {
16
27
  settle = res;
17
28
  fail = rej;
18
29
  });
30
+ let timer;
31
+ let stopped = false;
32
+ const clearTimer = () => {
33
+ if (timer)
34
+ clearTimeout(timer);
35
+ timer = undefined;
36
+ };
37
+ const stop = () => {
38
+ if (stopped)
39
+ return;
40
+ stopped = true;
41
+ clearTimer();
42
+ server.stop(true);
43
+ };
19
44
  let server;
20
45
  try {
21
46
  server = Bun.serve({
@@ -36,6 +61,10 @@ export function startCallbackServer(state) {
36
61
  return page("No authorization code received", "Please return to the terminal and try again.", 400);
37
62
  }
38
63
  settle?.(received);
64
+ // Stopping here would kill the listener before this response is
65
+ // delivered, so the success page would never reach the browser.
66
+ // The caller closes the server once the code is exchanged.
67
+ clearTimer();
39
68
  return page("Signed in to Devin", "You can close this tab and return to opencode.");
40
69
  },
41
70
  });
@@ -44,13 +73,20 @@ export function startCallbackServer(state) {
44
73
  reject(cause instanceof Error ? cause : new Error("Failed to bind loopback callback server"));
45
74
  return;
46
75
  }
76
+ // Armed before the caller can learn the redirect URI, so there is no
77
+ // window in which a completed redirect would leave the timer running.
78
+ timer = setTimeout(() => {
79
+ const label = timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)}s` : `${timeoutMs}ms`;
80
+ fail?.(new Error(`Login timed out after ${label}`));
81
+ stop();
82
+ }, timeoutMs);
47
83
  resolve({
48
84
  // The server is listening at this point, so the port is always set.
49
85
  redirectUri: `http://127.0.0.1:${server.port}${CALLBACK_PATH}`,
50
86
  code,
51
87
  close: () => {
52
88
  fail?.(new Error("Login cancelled"));
53
- server.stop(true);
89
+ stop();
54
90
  },
55
91
  });
56
92
  });
@@ -32,7 +32,11 @@ async function fromStoredConnection(ctx) {
32
32
  apiServerUrl: typeof metadata?.apiServerUrl === "string" ? metadata.apiServerUrl : undefined,
33
33
  };
34
34
  }
35
- catch {
35
+ catch (error) {
36
+ // An absent connection is normal and returns above without logging. An
37
+ // exception here is not: the visible symptom is "no devin models", so the
38
+ // reason has to reach the log somewhere.
39
+ console.warn("[opencode-devin] could not resolve the stored credential:", error);
36
40
  return undefined;
37
41
  }
38
42
  }
package/dist/index.js CHANGED
@@ -14,26 +14,10 @@
14
14
  import { Plugin, Provider } from "@opencode/plugin";
15
15
  import { DEFAULT_API_SERVER, LLM_ENV_VAR, PROVIDER_ID } from "./constants.js";
16
16
  import { resolveCredentials, toStoredCredential } from "./credentials.js";
17
- import { startCallbackServer } from "./auth/loopback.js";
18
- import { authorizeUrl } from "./auth/url.js";
19
- import { challengeFor, generateState, generateVerifier } from "./auth/pkce.js";
20
- import { exchangeCode } from "./auth/exchange.js";
17
+ import { openBrowser } from "./auth/browser.js";
18
+ import { loginAuto, loginManual } from "./auth/login.js";
21
19
  import { fetchModels } from "./catalog.js";
22
20
  export { createDevinProvider } from "./provider.js";
23
- function openBrowser(url) {
24
- if (process.platform === "win32") {
25
- // `cmd /c start` truncates URLs at "&" (cmd metacharacter) when spawned
26
- // from Bun — rundll32 hands the URL to the default browser verbatim.
27
- Bun.spawn(["rundll32", "url.dll,FileProtocolHandler", url], {
28
- stdin: "ignore",
29
- stdout: "ignore",
30
- stderr: "ignore",
31
- });
32
- return;
33
- }
34
- const cmd = process.platform === "darwin" ? ["open", url] : ["xdg-open", url];
35
- Bun.spawn(cmd, { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
36
- }
37
21
  export default Plugin.define({
38
22
  id: PROVIDER_ID,
39
23
  async setup(ctx) {
@@ -71,24 +55,13 @@ export default Plugin.define({
71
55
  integrationID: PROVIDER_ID,
72
56
  method: { id: "devin", type: "oauth", label: "Log in with Devin (browser)" },
73
57
  authorize: async () => {
74
- const verifier = generateVerifier();
75
- const state = generateState();
76
- const server = await startCallbackServer(state);
77
- const url = authorizeUrl({ state, challenge: await challengeFor(verifier), redirectUri: server.redirectUri });
78
- openBrowser(url);
58
+ const flow = await loginAuto();
59
+ openBrowser(flow.url);
79
60
  return {
80
- url,
81
- instructions: `Log in to Devin in the opened browser tab. If it did not open, go to: ${url}`,
61
+ url: flow.url,
62
+ instructions: `Log in to Devin in the opened browser tab. If it did not open, go to: ${flow.url}`,
82
63
  mode: "auto",
83
- callback: (async () => {
84
- try {
85
- const code = await server.code;
86
- return toStoredCredential(await exchangeCode({ code, verifier }));
87
- }
88
- finally {
89
- server.close();
90
- }
91
- })(),
64
+ callback: flow.finish().then(toStoredCredential),
92
65
  };
93
66
  },
94
67
  });
@@ -96,13 +69,12 @@ export default Plugin.define({
96
69
  integrationID: PROVIDER_ID,
97
70
  method: { id: "code", type: "oauth", label: "Paste code (headless)" },
98
71
  authorize: async () => {
99
- const verifier = generateVerifier();
100
- const state = generateState();
72
+ const flow = await loginManual();
101
73
  return {
102
- url: authorizeUrl({ state, challenge: await challengeFor(verifier) }),
74
+ url: flow.url,
103
75
  instructions: "Open the URL, sign in to Devin, and copy the code shown on the page, then paste it here.",
104
76
  mode: "code",
105
- callback: async (code) => toStoredCredential(await exchangeCode({ code: code.trim(), verifier })),
77
+ callback: async (code) => toStoredCredential(await flow.finish(code)),
106
78
  };
107
79
  },
108
80
  });
@@ -118,7 +90,11 @@ export default Plugin.define({
118
90
  void (async () => {
119
91
  for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
120
92
  if (event.type === "credential.updated" || event.type === "credential.switched") {
121
- await publish().catch(() => { });
93
+ // Not swallowed: a re-publish that fails leaves `/models` stale or
94
+ // empty, and that is otherwise indistinguishable from "no models".
95
+ await publish().catch((error) => {
96
+ console.error(`[opencode-devin] republish after ${event.type} failed:`, error);
97
+ });
122
98
  }
123
99
  }
124
100
  })();
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * `GetUserJwt` — mints the short-lived `user_jwt` required by catalog and chat
3
- * RPCs (~24 min TTL). The long-lived session token alone is not accepted.
3
+ * RPCs. The long-lived session token alone is not accepted.
4
+ *
5
+ * The real lifetime comes from the token's own `exp` claim; the cache only
6
+ * trusts it, and falls back to {@link FALLBACK_JWT_TTL_SECONDS} when `exp` is
7
+ * missing or unparseable. Observed tokens run roughly 24 minutes.
4
8
  *
5
9
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
6
10
  */
@@ -14,6 +18,8 @@ export interface UserJwt {
14
18
  }
15
19
  /** Mint a fresh user_jwt for the given session token. */
16
20
  export declare function mintUserJwt(apiKey: string, host?: string, signal?: AbortSignal): Promise<UserJwt>;
21
+ /** Cache key for one credential against one host. */
22
+ export declare const credentialKey: (host: string, apiKey: string) => string;
17
23
  /** Mint a user_jwt, reusing a cached one until shortly before expiry. */
18
24
  export declare function getCachedUserJwt(apiKey: string, host?: string, signal?: AbortSignal): Promise<string>;
19
25
  /** Drop the cached user_jwt (e.g. after an auth failure). */
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * `GetUserJwt` — mints the short-lived `user_jwt` required by catalog and chat
3
- * RPCs (~24 min TTL). The long-lived session token alone is not accepted.
3
+ * RPCs. The long-lived session token alone is not accepted.
4
+ *
5
+ * The real lifetime comes from the token's own `exp` claim; the cache only
6
+ * trusts it, and falls back to {@link FALLBACK_JWT_TTL_SECONDS} when `exp` is
7
+ * missing or unparseable. Observed tokens run roughly 24 minutes.
4
8
  *
5
9
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
6
10
  */
@@ -8,6 +12,12 @@ import { encodeMessage, iterFields } from "./wire.js";
8
12
  import { buildMetadata } from "./metadata.js";
9
13
  import { DEFAULT_API_SERVER } from "../constants.js";
10
14
  const MINT_TIMEOUT_MS = 30_000;
15
+ /**
16
+ * Assumed lifetime when the token carries no readable `exp`. Deliberately
17
+ * shorter than the observed ~24 minutes: a too-short assumption costs one extra
18
+ * mint, a too-long one keeps sending a token the server will reject.
19
+ */
20
+ const FALLBACK_JWT_TTL_SECONDS = 600;
11
21
  export class CloudAuthError extends Error {
12
22
  status;
13
23
  constructor(message, status) {
@@ -49,7 +59,7 @@ export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
49
59
  if (!jwt) {
50
60
  throw new CloudAuthError(`GetUserJwt 200 but no field-1 JWT found (${buf.length} bytes)`, response.status);
51
61
  }
52
- let expiresAt = Math.floor(Date.now() / 1000) + 600;
62
+ let expiresAt = Math.floor(Date.now() / 1000) + FALLBACK_JWT_TTL_SECONDS;
53
63
  try {
54
64
  const parts = jwt.split(".");
55
65
  const pad = (s) => s + "=".repeat((4 - (s.length % 4)) % 4);
@@ -58,10 +68,22 @@ export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
58
68
  expiresAt = payload.exp;
59
69
  }
60
70
  catch {
61
- // non-JWT payload — keep the 10-minute fallback
71
+ // non-JWT payload — keep the conservative fallback
62
72
  }
63
73
  return { jwt, expiresAt };
64
74
  }
75
+ /**
76
+ * Separator for composite cache keys.
77
+ *
78
+ * 0x1F (unit separator) cannot appear in a host or a token, so keys built from
79
+ * them are unambiguous. It is spelled as an escape rather than a literal control
80
+ * byte so it stays visible in diffs and review: silently dropped by a re-encode,
81
+ * `host="a" key="bc"` would collide with `host="ab" key="c"` and two different
82
+ * credentials would share a cached session.
83
+ */
84
+ const KEY_SEPARATOR = "\x1f";
85
+ /** Cache key for one credential against one host. */
86
+ export const credentialKey = (host, apiKey) => `${host}${KEY_SEPARATOR}${apiKey}`;
65
87
  let cache = null;
66
88
  const inFlight = new Map();
67
89
  let cacheEpoch = 0;
@@ -71,7 +93,7 @@ export async function getCachedUserJwt(apiKey, host = DEFAULT_API_SERVER, signal
71
93
  if (cache && cache.apiKey === apiKey && cache.host === host && cache.expiresAt > now + 60) {
72
94
  return cache.jwt;
73
95
  }
74
- const key = `${host}${apiKey}`;
96
+ const key = credentialKey(host, apiKey);
75
97
  const pending = inFlight.get(key);
76
98
  if (pending)
77
99
  return (await pending).jwt;
@@ -38,12 +38,25 @@ export interface Catalog {
38
38
  apiKey: string;
39
39
  host: string;
40
40
  }
41
- /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
42
- export declare function getCachedCatalog(apiKey: string, host?: string, signal?: AbortSignal): Promise<Catalog | null>;
43
- export declare function clearCachedCatalog(): void;
41
+ /**
42
+ * Raised when the account's catalog lists the model but marks it disabled.
43
+ *
44
+ * Only this case is safe to fail on: the catalog states it explicitly, so the
45
+ * upstream request would be rejected regardless. A model that is simply absent
46
+ * is *not* asserted on, because the catalog is not guaranteed to enumerate every
47
+ * uid Cascade accepts and a false rejection would break a working model.
48
+ */
44
49
  export declare class ModelNotAvailableError extends Error {
45
50
  readonly modelUid: string;
46
51
  readonly label: string;
47
- readonly reason: "disabled" | "not_listed";
48
- constructor(modelUid: string, label: string, reason: "disabled" | "not_listed");
52
+ constructor(modelUid: string, label: string);
53
+ }
54
+ /** The catalog as the request path needs it: everything, and the usable subset. */
55
+ export interface CatalogSnapshot {
56
+ /** Every model the account can see, including ones disabled for its tier. */
57
+ readonly entries: readonly ModelCatalogEntry[];
58
+ /** The subset currently usable; what the effort-variant lookup resolves against. */
59
+ readonly enabled: readonly ModelCatalogEntry[];
49
60
  }
61
+ /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
62
+ export declare function getCachedCatalog(apiKey: string, host?: string, signal?: AbortSignal): Promise<Catalog | null>;