opencode-devin 0.1.0 → 0.2.0

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 opencode-devin contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 opencode-devin contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,107 +1,177 @@
1
- # opencode-devin
2
-
3
- [OpenCode v2](https://opencode.ai) plugin that connects your [Devin](https://devin.ai) subscription to OpenCode:
4
-
5
- - **Native `/connect` integration** — log in with Devin straight from the OpenCode TUI using the same browser PKCE flow as the Devin CLI. The credential is stored in OpenCode's own auth store; no config files or API keys to copy.
6
- - **`devin/*` models in `/models`** — the live, per-account catalog (SWE, Claude Opus, GPT, Gemini, Grok, Kimi and more, with reasoning-effort and speed variants), streamed from Cognition's Cascade inference API.
7
-
8
- > **Requires OpenCode v2.** This plugin targets the v2 plugin API (`Plugin.define`). The official [`@cognitionai/opencode-devin`](https://www.npmjs.com/package/@cognitionai/opencode-devin) plugin is v1-only at the time of writing and does not load on v2.
9
-
10
- ## Install
11
-
12
- Add the plugin to `opencode.json` (project or `~/.config/opencode/opencode.json`):
13
-
14
- ```jsonc
15
- {
16
- "$schema": "https://opencode.ai/config.json",
17
- "plugins": ["opencode-devin"]
18
- }
19
- ```
20
-
21
- OpenCode installs it automatically on the next start.
22
-
23
- ## Connect
24
-
25
- Start OpenCode, run `/connect`, pick **Devin**, then choose a method:
26
-
27
- | Method | How it works | Best for |
28
- | --- | --- | --- |
29
- | **Log in with Devin (browser)** | Opens the Devin sign-in page (PKCE + S256) and captures the authorization code through a local loopback callback. | Interactive terminals |
30
- | **Paste code (headless)** | Opens the same login page without a redirect; the page shows a code to copy and paste back into the TUI. | Headless machines, SSH |
31
- | **`DEVIN_LLM_API_KEY`** | Reads a `devin-session-token$...` token from the environment. | CI, scripting |
32
-
33
- After connecting, the model list refreshes automatically and `devin/<model>` entries appear in `/models`.
34
-
35
- ### Environment variable alternative
36
-
37
- Skip `/connect` entirely:
38
-
39
- ```sh
40
- export DEVIN_LLM_API_KEY=devin-session-token$your_token_here
41
- ```
42
-
43
- ## Use
44
-
45
- Pick any `devin/` model in the `/models` picker, or set a default:
46
-
47
- ```jsonc
48
- // opencode.json
49
- {
50
- "model": "devin/swe-2-max"
51
- }
52
- ```
53
-
54
- From the CLI:
55
-
56
- ```sh
57
- opencode run --model devin/swe-2-max "Refactor the auth module"
58
- ```
59
-
60
- ## How it works
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)
73
- ```
74
-
75
- 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`.
76
- 2. **Catalog** — model families come from Cognition's Cascade API for the logged-in account (the same source the Devin CLI uses). The OpenAI-compatible REST gateway (`/api/v1`) is not provisioned for most accounts, so chat streams through Cascade gRPC instead.
77
- 3. **Provider** — the plugin publishes a `devin` provider whose package specifier self-references the plugin's own installed location (`aisdk:<this-package>`), so OpenCode's dynamic AI-SDK loader imports it directly with no registry round-trip — both from a repo checkout during development and from the npm cache once installed. Its `LanguageModelV3` implementation lives in `src/protocol/`: a short-lived `user_jwt` is minted per session (`GetUserJwt`) and chat streams through `GetChatMessage`.
78
- 4. **Reactivity** — the inventory re-publishes whenever a credential is connected, switched, or removed, so connecting mid-session updates `/models` without a restart.
79
-
80
- ## Troubleshooting
81
-
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`.
84
-
85
- ## Development
86
-
87
- ```sh
88
- bun install
89
- npm run typecheck
90
- npm run build # emits dist/
91
- ```
92
-
93
- To test a local checkout without publishing, create a bridge file that re-exports the build:
94
-
95
- ```ts
96
- // ~/.config/opencode/plugins/devin.ts
97
- export { default } from "file:///absolute/path/to/opencode-devin/dist/index.js"
98
- ```
99
-
100
- ## Credits
101
-
102
- - 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.
103
- - [`@cognitionai/opencode-devin`](https://www.npmjs.com/package/@cognitionai/opencode-devin) — reference for the Devin CLI PKCE login flow.
104
-
105
- ## License
106
-
107
- [MIT](LICENSE)
1
+ # opencode-devin
2
+
3
+ [OpenCode v2](https://opencode.ai) plugin that connects your [Devin](https://devin.ai) subscription to OpenCode:
4
+
5
+ - **Native `/connect` integration** — log in with Devin straight from the OpenCode TUI using the same browser PKCE flow as the Devin CLI. The credential is stored in OpenCode's own auth store; no config files or API keys to copy.
6
+ - **`devin/*` models in `/models`** — the live, per-account catalog (SWE, Claude Opus, GPT, Gemini, Grok, Kimi and more, with reasoning-effort and speed variants), streamed from Cognition's Cascade inference API.
7
+
8
+ > **Requires OpenCode v2.** This plugin targets the v2 plugin API (`Plugin.define`). The official [`@cognitionai/opencode-devin`](https://www.npmjs.com/package/@cognitionai/opencode-devin) plugin is v1-only at the time of writing and does not load on v2.
9
+
10
+ ## Install
11
+
12
+ Add the plugin to `opencode.json` (project or `~/.config/opencode/opencode.json`):
13
+
14
+ ```jsonc
15
+ {
16
+ "$schema": "https://opencode.ai/config.json",
17
+ "plugins": ["opencode-devin"]
18
+ }
19
+ ```
20
+
21
+ OpenCode installs it automatically on the next start.
22
+
23
+ ## Connect
24
+
25
+ Start OpenCode, run `/connect`, pick **Devin**, then choose a method:
26
+
27
+ | Method | How it works | Best for |
28
+ | --- | --- | --- |
29
+ | **Log in with Devin (browser)** | Opens the Devin sign-in page (PKCE + S256) and captures the authorization code through a local loopback callback. | Interactive terminals |
30
+ | **Paste code (headless)** | Opens the same login page without a redirect; the page shows a code to copy and paste back into the TUI. | Headless machines, SSH |
31
+ | **`DEVIN_LLM_API_KEY`** | Reads a `devin-session-token$...` token from the environment. | CI, scripting |
32
+
33
+ After connecting, the model list refreshes automatically and `devin/<model>` entries appear in `/models`.
34
+
35
+ ### Environment variable alternative
36
+
37
+ Skip `/connect` entirely:
38
+
39
+ ```sh
40
+ export DEVIN_LLM_API_KEY=devin-session-token$your_token_here
41
+ ```
42
+
43
+ ## Use
44
+
45
+ Pick any `devin/` model in the `/models` picker, or set a default:
46
+
47
+ ```jsonc
48
+ // opencode.json
49
+ {
50
+ "model": "devin/swe-2-max"
51
+ }
52
+ ```
53
+
54
+ From the CLI:
55
+
56
+ ```sh
57
+ opencode run --model devin/swe-2-max "Refactor the auth module"
58
+ ```
59
+
60
+ ## How it works
61
+
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
81
+ ```
82
+
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`.
84
+ 2. **Catalog** — model families come from Cognition's Cascade API for the logged-in account (the same source the Devin CLI uses). The OpenAI-compatible REST gateway (`/api/v1`) is not provisioned for most accounts, so chat streams through Cascade gRPC instead.
85
+ 3. **Provider** — the plugin publishes a `devin` provider whose package specifier self-references the plugin's own installed location (`aisdk:<this-package>`), so OpenCode's dynamic AI-SDK loader imports it directly with no registry round-trip — both from a repo checkout during development and from the npm cache once installed. Its `LanguageModelV3` implementation lives in `src/protocol/`: a short-lived `user_jwt` is minted per session (`GetUserJwt`) and chat streams through `GetChatMessage`.
86
+ 4. **Reactivity** — the inventory re-publishes whenever a credential is connected, switched, or removed, so connecting mid-session updates `/models` without a restart.
87
+
88
+ ## Troubleshooting
89
+
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.
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.
96
+
97
+ ## Development
98
+
99
+ ```sh
100
+ bun install
101
+ npm run typecheck
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
+ ### Developing against a local build
110
+
111
+ Edit `plugins` in `~/.config/opencode/opencode.json` to one of these, then run
112
+ `npm run build && opencode reload`:
113
+
114
+ ```jsonc
115
+ // this repository
116
+ { "plugins": ["opencode-devin@file:C:/path/to/opencode-devin"] }
117
+
118
+ // the published package
119
+ { "plugins": ["opencode-devin"] }
120
+ ```
121
+
122
+ The path must be absolute, and the `name@file:` form is required: a bare path
123
+ or a `file://` URL is ignored without an error.
124
+
125
+ To confirm which copy the server loaded:
126
+
127
+ ```sh
128
+ opencode api provider.list # the devin provider's "package" field
129
+ ```
130
+
131
+ ### Testing against the real API
132
+
133
+ `bun test` runs everything except the live suite, which skips itself without a
134
+ credential:
135
+
136
+ ```sh
137
+ DEVIN_LLM_API_KEY='devin-session-token$...' bun test test/live.test.ts
138
+ ```
139
+
140
+ ## FAQ
141
+
142
+ **Why is `build` atomic?** OpenCode reloads a linked plugin the moment its
143
+ entrypoint changes, and a failed load is not retried. Writing `dist/` in place
144
+ lets a reload land mid-write and fail, which shows up as `ENOENT reading
145
+ dist/index.js` or `Cannot find module '.../constants.js'`. `build` compiles to a
146
+ staging directory and swaps it in.
147
+
148
+ **Why a second protobuf implementation in the tests?** The suite encodes and
149
+ decodes with the same module, which only proves the two halves agree — they
150
+ could both be wrong. `wire-conformance.test.ts` checks the framing against
151
+ `protobufjs`, which shares no code with this repository. It is a dev-only
152
+ dependency.
153
+
154
+ **What the tests cannot check.** The Cascade field numbers were recovered by
155
+ reverse-engineering the Devin CLI. Only `test/live.test.ts`, which talks to
156
+ Cognition, can notice them changing. All three RPCs have been exercised against
157
+ the live API, but nothing guards a future upstream change; a committed capture of
158
+ real responses would, and there is not one yet.
159
+
160
+ **Why doesn't a missing model fail immediately?** Because the catalog is not
161
+ guaranteed to list every uid Cascade accepts, and refusing one that works would
162
+ be worse than a vague error. Disabled models are refused outright; unknown ones
163
+ are warned about, and the likely reason is appended if the request fails.
164
+
165
+ **Why is the session token in the provider registry?** It is passed as
166
+ `settings.apiKey`, which is how the provider receives it. `opencode api
167
+ provider.list` therefore returns it in clear text. Treat that output as a
168
+ secret.
169
+
170
+ ## Credits
171
+
172
+ - 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.
173
+ - [`@cognitionai/opencode-devin`](https://www.npmjs.com/package/@cognitionai/opencode-devin) — reference for the Devin CLI PKCE login flow.
174
+
175
+ ## License
176
+
177
+ [MIT](LICENSE)
@@ -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
@@ -21,11 +21,17 @@ import { exchangeCode } from "./auth/exchange.js";
21
21
  import { fetchModels } from "./catalog.js";
22
22
  export { createDevinProvider } from "./provider.js";
23
23
  function openBrowser(url) {
24
- const cmd = process.platform === "win32"
25
- ? ["cmd", "/c", "start", "", url]
26
- : process.platform === "darwin"
27
- ? ["open", url]
28
- : ["xdg-open", 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];
29
35
  Bun.spawn(cmd, { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
30
36
  }
31
37
  export default Plugin.define({
@@ -112,7 +118,11 @@ export default Plugin.define({
112
118
  void (async () => {
113
119
  for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
114
120
  if (event.type === "credential.updated" || event.type === "credential.switched") {
115
- await publish().catch(() => { });
121
+ // Not swallowed: a re-publish that fails leaves `/models` stale or
122
+ // empty, and that is otherwise indistinguishable from "no models".
123
+ await publish().catch((error) => {
124
+ console.error(`[opencode-devin] republish after ${event.type} failed:`, error);
125
+ });
116
126
  }
117
127
  }
118
128
  })();
@@ -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>;