opencode-devin 0.1.1 → 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/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,86 @@ 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.
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
+ ### 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"] }
91
120
  ```
92
121
 
93
- To test a local checkout without publishing, create a bridge file that re-exports the build:
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.
94
124
 
95
- ```ts
96
- // ~/.config/opencode/plugins/devin.ts
97
- export { default } from "file:///absolute/path/to/opencode-devin/dist/index.js"
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
98
138
  ```
99
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
+
100
170
  ## Credits
101
171
 
102
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.
@@ -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
@@ -118,7 +118,11 @@ export default Plugin.define({
118
118
  void (async () => {
119
119
  for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
120
120
  if (event.type === "credential.updated" || event.type === "credential.switched") {
121
- 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
+ });
122
126
  }
123
127
  }
124
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>;
@@ -7,10 +7,31 @@
7
7
  */
8
8
  import { encodeMessage, iterFields } from "./wire.js";
9
9
  import { buildMetadata } from "./metadata.js";
10
- import { getCachedUserJwt } from "./auth.js";
10
+ import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
11
+ import { splitEffortSuffix } from "./effort.js";
11
12
  import { DEFAULT_API_SERVER } from "../constants.js";
12
13
  const CATALOG_TTL_MS = 10 * 60 * 1000;
13
14
  const CATALOG_FETCH_TIMEOUT_MS = 10_000;
15
+ /**
16
+ * Raised when the account's catalog lists the model but marks it disabled.
17
+ *
18
+ * Only this case is safe to fail on: the catalog states it explicitly, so the
19
+ * upstream request would be rejected regardless. A model that is simply absent
20
+ * is *not* asserted on, because the catalog is not guaranteed to enumerate every
21
+ * uid Cascade accepts and a false rejection would break a working model.
22
+ */
23
+ export class ModelNotAvailableError extends Error {
24
+ modelUid;
25
+ label;
26
+ constructor(modelUid, label) {
27
+ super(label && label !== modelUid
28
+ ? `Model "${label}" (uid=${modelUid}) is not enabled for your Cognition account tier.`
29
+ : `Model uid "${modelUid}" is not enabled for your Cognition account tier.`);
30
+ this.name = "ModelNotAvailableError";
31
+ this.modelUid = modelUid;
32
+ this.label = label;
33
+ }
34
+ }
14
35
  async function fetchCatalog(apiKey, host, signal) {
15
36
  const userJwt = await getCachedUserJwt(apiKey, host, signal);
16
37
  const metadata = buildMetadata({
@@ -30,6 +51,10 @@ async function fetchCatalog(apiKey, host, signal) {
30
51
  });
31
52
  if (!response.ok) {
32
53
  const text = await response.text();
54
+ // A 401 means the cached user_jwt was rejected. Drop it so the next attempt
55
+ // mints a fresh one instead of replaying a token already known to be bad.
56
+ if (response.status === 401)
57
+ clearCachedUserJwt();
33
58
  throw new Error(`GetCascadeModelConfigs HTTP ${response.status}: ${text.slice(0, 200)}`);
34
59
  }
35
60
  const buf = Buffer.from(await response.arrayBuffer());
@@ -110,10 +135,7 @@ function decodeModelConfig(buf) {
110
135
  }
111
136
  if (modelUid.length === 0)
112
137
  return undefined;
113
- // Extract the effort level from the UID suffix
114
- const effortMatch = modelUid.match(/-(none|low|medium|high|xhigh|max)$/);
115
- const effortLevel = effortMatch?.[1];
116
- const baseModelUid = effortLevel ? modelUid.slice(0, -effortLevel.length - 1) : undefined;
138
+ const { baseModelUid, effortLevel } = splitEffortSuffix(modelUid);
117
139
  return {
118
140
  modelUid,
119
141
  label: label || modelUid,
@@ -128,7 +150,7 @@ function decodeModelConfig(buf) {
128
150
  let cached = null;
129
151
  let inFlight = null;
130
152
  let inFlightKey = null;
131
- const flightKey = (apiKey, host) => `${host}${apiKey}`;
153
+ const flightKey = (apiKey, host) => credentialKey(host, apiKey);
132
154
  /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
133
155
  export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal) {
134
156
  if (cached && cached.apiKey === apiKey && cached.host === host && Date.now() - cached.fetchedAt < CATALOG_TTL_MS) {
@@ -161,22 +183,3 @@ export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal
161
183
  }
162
184
  }
163
185
  }
164
- export function clearCachedCatalog() {
165
- cached = null;
166
- inFlight = null;
167
- inFlightKey = null;
168
- }
169
- export class ModelNotAvailableError extends Error {
170
- modelUid;
171
- label;
172
- reason;
173
- constructor(modelUid, label, reason) {
174
- super(reason === "disabled"
175
- ? `Model "${label}" (uid=${modelUid}) is not enabled for your Cognition account tier.`
176
- : `Model uid "${modelUid}" is not listed in the Cognition catalog for your account.`);
177
- this.name = "ModelNotAvailableError";
178
- this.modelUid = modelUid;
179
- this.label = label;
180
- this.reason = reason;
181
- }
182
- }
@@ -7,7 +7,7 @@
7
7
  import * as zlib from "node:zlib";
8
8
  import { encodeMessage, encodeString, encodeVarintField, frameConnectStream, iterFields, } from "./wire.js";
9
9
  import { buildMetadata } from "./metadata.js";
10
- import { getCachedUserJwt } from "./auth.js";
10
+ import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
11
11
  import { DEFAULT_API_SERVER } from "../constants.js";
12
12
  const STREAM_IDLE_MS = 120_000;
13
13
  const STREAM_TTFB_MS = 60_000;
@@ -131,12 +131,26 @@ function encodeCompletionConfiguration(opts) {
131
131
  float64(11, 1.0),
132
132
  ]);
133
133
  }
134
+ /**
135
+ * Per-credential Cascade session ids.
136
+ *
137
+ * Keys embed the session token, so the map is capped and evicted in insertion
138
+ * order: a user who connects and switches credentials repeatedly would
139
+ * otherwise accumulate tokens in memory for the life of the process. In
140
+ * practice only one or two credentials are ever live at a time.
141
+ */
142
+ const SESSION_CACHE_LIMIT = 4;
134
143
  const sessionCache = new Map();
135
144
  function getOrAllocateSessionIds(apiKey, host, cascadeIdOverride) {
136
- const key = `${host}${apiKey}`;
145
+ const key = credentialKey(host, apiKey);
137
146
  let ids = sessionCache.get(key);
138
147
  if (!ids) {
139
148
  ids = { sessionId: crypto.randomUUID(), cascadeId: cascadeIdOverride ?? crypto.randomUUID() };
149
+ if (sessionCache.size >= SESSION_CACHE_LIMIT) {
150
+ const oldest = sessionCache.keys().next();
151
+ if (!oldest.done)
152
+ sessionCache.delete(oldest.value);
153
+ }
140
154
  sessionCache.set(key, ids);
141
155
  }
142
156
  else if (cascadeIdOverride && ids.cascadeId !== cascadeIdOverride) {
@@ -290,6 +304,11 @@ function decodeUsageBlock(buf) {
290
304
  };
291
305
  }
292
306
  const TRACE_ID_RE = /\(trace ID: ([0-9a-f]+)\)/i;
307
+ /**
308
+ * Trailer codes that mean "your credential was rejected", as opposed to a
309
+ * permission or tier problem, which a fresh token would not fix.
310
+ */
311
+ const isAuthFailure = (code) => code === "unauthenticated" || code === "unauthorized" || code === "invalid_token";
293
312
  /** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
294
313
  export async function* streamChatEvents(request) {
295
314
  const host = (request.apiServerUrl ?? DEFAULT_API_SERVER).replace(/\/$/, "");
@@ -323,6 +342,10 @@ export async function* streamChatEvents(request) {
323
342
  });
324
343
  if (!response.ok) {
325
344
  const text = await response.text();
345
+ // A 401 means the cached user_jwt was rejected. Drop it so the next attempt
346
+ // mints a fresh one instead of replaying a token already known to be bad.
347
+ if (response.status === 401)
348
+ clearCachedUserJwt();
326
349
  throw new CloudChatError(`GetChatMessage HTTP ${response.status}: ${text.slice(0, 300)}`);
327
350
  }
328
351
  if (!response.body)
@@ -333,14 +356,16 @@ export async function* streamChatEvents(request) {
333
356
  let trailerError = null;
334
357
  let sawEos = false;
335
358
  let idleTimer = null;
336
- const cancelBody = (reason) => {
337
- try {
338
- void response.body?.cancel(reason);
339
- }
340
- catch {
341
- // already cancelled
342
- }
343
- };
359
+ /**
360
+ * Release the response body.
361
+ *
362
+ * Must go through `reader`, not `response.body`: the body is locked by that
363
+ * reader, so `body.cancel()` rejects with "Cannot cancel a locked
364
+ * ReadableStream". Since it rejects rather than throws, a surrounding
365
+ * try/catch never saw it and the connection was silently left open on every
366
+ * abort and idle timeout.
367
+ */
368
+ const cancelBody = (reason) => reader.cancel(reason).catch(() => { });
344
369
  const peek = (n) => {
345
370
  if (queuedBytes < n)
346
371
  return null;
@@ -444,19 +469,25 @@ export async function* streamChatEvents(request) {
444
469
  finally {
445
470
  if (idleTimer)
446
471
  clearTimeout(idleTimer);
472
+ // Cancel before releasing: releasing first would detach the reader, after
473
+ // which the body can no longer be cancelled at all.
474
+ await cancelBody("stream finished");
447
475
  try {
448
476
  reader.releaseLock();
449
477
  }
450
478
  catch {
451
479
  // lock already released
452
480
  }
453
- cancelBody();
454
481
  }
455
482
  if (trailerError) {
456
483
  const isOpaque = trailerError.code === "permission_denied" && /an internal error occurred/i.test(trailerError.message);
457
484
  if (isOpaque) {
458
485
  throw new CloudChatError(`Cognition denied model access for "${request.modelUid}". Check your account tier. (trace: ${trailerError.traceId ?? "n/a"})`, trailerError.code, trailerError.traceId);
459
486
  }
487
+ // A token the server rejected mid-stream is just as stale as a 401: the
488
+ // account may have been reconnected between minting and streaming.
489
+ if (isAuthFailure(trailerError.code))
490
+ clearCachedUserJwt();
460
491
  throw new CloudChatError(trailerError.message, trailerError.code, trailerError.traceId);
461
492
  }
462
493
  if (!sawEos) {
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Reasoning-effort handling, in one place.
3
+ *
4
+ * The catalog encodes effort as a suffix on the model UID, and both the
5
+ * catalog decoder and the request path have to read that suffix. They used to
6
+ * carry their own copy of the same alternation, which is exactly the kind of
7
+ * duplication that drifts when Cognition adds an effort level.
8
+ */
9
+ /** Valid reasoning effort levels. */
10
+ export declare const EFFORT_LEVELS: readonly ["none", "low", "medium", "high", "xhigh", "max"];
11
+ export type EffortLevel = (typeof EFFORT_LEVELS)[number];
12
+ /** Narrow an arbitrary value to a known effort level, or `undefined`. */
13
+ export declare function toEffortLevel(value: unknown): EffortLevel | undefined;
14
+ /** Split a UID into its base UID and effort suffix, e.g. `opus-4-8-high`. */
15
+ export declare function splitEffortSuffix(modelUid: string): {
16
+ baseModelUid: string;
17
+ effortLevel?: EffortLevel;
18
+ };
19
+ /** Append an effort suffix to a base UID. */
20
+ export declare function withEffortSuffix(modelUid: string, effort: EffortLevel): string;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Reasoning-effort handling, in one place.
3
+ *
4
+ * The catalog encodes effort as a suffix on the model UID, and both the
5
+ * catalog decoder and the request path have to read that suffix. They used to
6
+ * carry their own copy of the same alternation, which is exactly the kind of
7
+ * duplication that drifts when Cognition adds an effort level.
8
+ */
9
+ /** Valid reasoning effort levels. */
10
+ export const EFFORT_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"];
11
+ /** Derived from EFFORT_LEVELS so the two can never disagree. */
12
+ const EFFORT_SUFFIX = new RegExp(`-(${EFFORT_LEVELS.join("|")})$`);
13
+ /** Narrow an arbitrary value to a known effort level, or `undefined`. */
14
+ export function toEffortLevel(value) {
15
+ if (typeof value !== "string")
16
+ return undefined;
17
+ const effort = value.toLowerCase();
18
+ return EFFORT_LEVELS.includes(effort) ? effort : undefined;
19
+ }
20
+ /** Split a UID into its base UID and effort suffix, e.g. `opus-4-8-high`. */
21
+ export function splitEffortSuffix(modelUid) {
22
+ const match = modelUid.match(EFFORT_SUFFIX);
23
+ const effortLevel = match?.[1];
24
+ if (!effortLevel)
25
+ return { baseModelUid: modelUid };
26
+ return { baseModelUid: modelUid.slice(0, -(effortLevel.length + 1)), effortLevel: effortLevel };
27
+ }
28
+ /** Append an effort suffix to a base UID. */
29
+ export function withEffortSuffix(modelUid, effort) {
30
+ return `${modelUid}-${effort}`;
31
+ }
@@ -8,25 +8,42 @@
8
8
  *
9
9
  * Originally ported from ai-sdk-devin / pi-devin-auth (MIT).
10
10
  */
11
- import type { LanguageModelV3 } from "@ai-sdk/provider";
11
+ import type { LanguageModelV3, LanguageModelV3StreamPart, LanguageModelV3Usage } from "@ai-sdk/provider";
12
+ import { type ChatEvent } from "./chat.ts";
12
13
  import { type ModelCatalogEntry } from "./catalog.ts";
13
- /** Valid reasoning effort levels (encoded as UID suffixes in the catalog). */
14
- declare const EFFORT_LEVELS: readonly ["none", "low", "medium", "high", "xhigh", "max"];
15
- export type EffortLevel = (typeof EFFORT_LEVELS)[number];
16
- /** Calculate the dollar cost of a request from token usage and model pricing. */
17
- export declare function calculateCost(usage: {
18
- inputTokens?: number;
19
- cachedInputTokens?: number;
20
- outputTokens?: number;
21
- }, pricing?: ModelCatalogEntry["pricing"]): number | undefined;
14
+ /**
15
+ * Resolve the actual model UID to send upstream, applying an optional
16
+ * reasoning-effort override from providerOptions: swap an existing effort
17
+ * suffix, or append one when the catalog lists that variant.
18
+ *
19
+ * Exported for tests: this is what the catalog lookup exists for, so it needs
20
+ * to stay covered independently of the network.
21
+ */
22
+ export declare function resolveEffortUid(modelId: string, catalog: readonly ModelCatalogEntry[] | undefined, requestedEffort: unknown): string;
23
+ /**
24
+ * Exported for tests: the Cascade event -> AI SDK stream translation is pure,
25
+ * and interleaved parallel tool calls are the case most likely to regress.
26
+ */
27
+ export declare function convertStreamEvents(events: AsyncGenerator<ChatEvent>, generateId: () => string): AsyncGenerator<LanguageModelV3StreamPart>;
28
+ interface CollectedResult {
29
+ text: string;
30
+ reasoning: string;
31
+ toolCalls: {
32
+ id: string;
33
+ name: string;
34
+ args: string;
35
+ }[];
36
+ finishReason: string;
37
+ usage?: LanguageModelV3Usage;
38
+ }
39
+ /** Exported for tests; mirrors `convertStreamEvents` for the non-streaming path. */
40
+ export declare function collectEvents(events: AsyncGenerator<ChatEvent>): Promise<CollectedResult>;
22
41
  export interface DevinProviderOptions {
23
42
  apiKey: string;
24
43
  baseURL?: string;
25
44
  }
26
45
  export interface DevinProvider {
27
46
  languageModel(modelId: string): LanguageModelV3;
28
- /** Fetch the live model catalog for this account. Returns all enabled models. */
29
- models(): Promise<ModelCatalogEntry[]>;
30
47
  }
31
48
  export declare function createDevin(options: DevinProviderOptions): DevinProvider;
32
49
  export {};
@@ -9,37 +9,29 @@
9
9
  * Originally ported from ai-sdk-devin / pi-devin-auth (MIT).
10
10
  */
11
11
  import { streamChatEvents } from "./chat.js";
12
- import { getCachedCatalog } from "./catalog.js";
12
+ import { getCachedCatalog, ModelNotAvailableError, } from "./catalog.js";
13
+ import { splitEffortSuffix, toEffortLevel, withEffortSuffix } from "./effort.js";
13
14
  import { DEFAULT_API_SERVER } from "../constants.js";
14
- /** Valid reasoning effort levels (encoded as UID suffixes in the catalog). */
15
- const EFFORT_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"];
16
15
  /**
17
16
  * Resolve the actual model UID to send upstream, applying an optional
18
17
  * reasoning-effort override from providerOptions: swap an existing effort
19
18
  * suffix, or append one when the catalog lists that variant.
19
+ *
20
+ * Exported for tests: this is what the catalog lookup exists for, so it needs
21
+ * to stay covered independently of the network.
20
22
  */
21
- function resolveEffortUid(modelId, catalog, requestedEffort) {
22
- const effort = typeof requestedEffort === "string" ? requestedEffort.toLowerCase() : "";
23
- if (!EFFORT_LEVELS.includes(effort))
23
+ export function resolveEffortUid(modelId, catalog, requestedEffort) {
24
+ const effort = toEffortLevel(requestedEffort);
25
+ if (!effort)
24
26
  return modelId;
25
- const effortMatch = modelId.match(/-(none|low|medium|high|xhigh|max)$/);
26
- if (effortMatch?.[1])
27
- return modelId.slice(0, -effortMatch[1].length - 1) + "-" + effort;
27
+ const split = splitEffortSuffix(modelId);
28
+ if (split.effortLevel)
29
+ return withEffortSuffix(split.baseModelUid, effort);
28
30
  if (catalog?.some((entry) => entry.baseModelUid === modelId && entry.effortLevel === effort)) {
29
- return modelId + "-" + effort;
31
+ return withEffortSuffix(modelId, effort);
30
32
  }
31
33
  return modelId;
32
34
  }
33
- /** Calculate the dollar cost of a request from token usage and model pricing. */
34
- export function calculateCost(usage, pricing) {
35
- if (!pricing)
36
- return undefined;
37
- const input = ((usage.inputTokens ?? 0) / 1_000_000) * pricing.input;
38
- const cached = ((usage.cachedInputTokens ?? 0) / 1_000_000) * pricing.cachedInput;
39
- const output = ((usage.outputTokens ?? 0) / 1_000_000) * pricing.output;
40
- const total = input + cached + output;
41
- return total > 0 ? Math.round(total * 1_000_000) / 1_000_000 : 0;
42
- }
43
35
  // --- Prompt conversion: LanguageModelV3Prompt → ChatHistoryItem[] ---
44
36
  function convertPrompt(prompt) {
45
37
  const items = [];
@@ -114,105 +106,149 @@ const DEFAULT_USAGE = {
114
106
  inputTokens: { total: 0, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
115
107
  outputTokens: { total: 0, text: undefined, reasoning: undefined },
116
108
  };
117
- async function* convertStreamEvents(events, generateId, pricing) {
109
+ /** Sentinel distinguishing a timer wake-up from an upstream event. */
110
+ const TICK = Symbol("coalesce-tick");
111
+ /**
112
+ * Exported for tests: the Cascade event -> AI SDK stream translation is pure,
113
+ * and interleaved parallel tool calls are the case most likely to regress.
114
+ */
115
+ export async function* convertStreamEvents(events, generateId) {
118
116
  let textId = "";
119
117
  let reasoningId = "";
120
118
  let textOpen = false;
121
119
  let reasoningOpen = false;
122
- let currentToolId = "";
123
- let currentToolName = "";
124
- let toolInputOpen = false;
125
- let pendingToolArgs = "";
126
120
  let finishReason = "stop";
127
121
  let usage;
128
122
  let textBuf = "";
129
123
  let textLastFlush = 0;
130
124
  let reasoningBuf = "";
131
125
  let reasoningLastFlush = 0;
132
- yield { type: "stream-start", warnings: [] };
133
- for await (const event of events) {
126
+ // Cascade interleaves argument deltas across parallel tool calls, so pending
127
+ // arguments are buffered per call id. A single shared buffer would splice two
128
+ // calls' JSON into one unparsable string.
129
+ const openTools = new Map();
130
+ // Deltas that carry no id belong to the most recently opened call.
131
+ let lastToolId = "";
132
+ const pendingDeltas = () => {
133
+ const parts = [];
134
+ if (textBuf) {
135
+ parts.push({ type: "text-delta", id: textId, delta: textBuf });
136
+ textBuf = "";
137
+ }
138
+ if (reasoningBuf) {
139
+ parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
140
+ reasoningBuf = "";
141
+ }
142
+ return parts;
143
+ };
144
+ const closeBlocks = () => {
145
+ const parts = [];
146
+ if (textOpen) {
147
+ parts.push({ type: "text-end", id: textId });
148
+ textOpen = false;
149
+ }
150
+ if (reasoningOpen) {
151
+ parts.push({ type: "reasoning-end", id: reasoningId });
152
+ reasoningOpen = false;
153
+ }
154
+ return parts;
155
+ };
156
+ // The protocol has no end-of-tool-call marker, so a call cannot be completed
157
+ // until the stream ends. They are emitted in the order they were started.
158
+ const completedToolCalls = () => {
159
+ const parts = [];
160
+ for (const [id, tool] of openTools) {
161
+ parts.push({ type: "tool-call", toolCallId: id, toolName: tool.name, input: tool.args });
162
+ }
163
+ openTools.clear();
164
+ return parts;
165
+ };
166
+ /** Flush only the buffers that have been waiting longer than the interval. */
167
+ const staleDeltas = () => {
168
+ const now = Date.now();
169
+ const parts = [];
170
+ if (textBuf && now - textLastFlush >= COALESCE_INTERVAL_MS) {
171
+ parts.push({ type: "text-delta", id: textId, delta: textBuf });
172
+ textBuf = "";
173
+ textLastFlush = now;
174
+ }
175
+ if (reasoningBuf && now - reasoningLastFlush >= COALESCE_INTERVAL_MS) {
176
+ parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
177
+ reasoningBuf = "";
178
+ reasoningLastFlush = now;
179
+ }
180
+ return parts;
181
+ };
182
+ const handleEvent = (event) => {
183
+ const parts = [];
134
184
  switch (event.kind) {
135
185
  case "text": {
186
+ // Flush the other block before opening this one, so the parts stay in
187
+ // causal order. Without this, text buffered right before the model
188
+ // starts thinking would stay invisible until more text, a tool call, or
189
+ // the end of the stream.
190
+ if (reasoningOpen && reasoningBuf) {
191
+ parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
192
+ reasoningBuf = "";
193
+ reasoningLastFlush = Date.now();
194
+ }
136
195
  if (!textOpen) {
137
196
  textId = generateId();
138
197
  textOpen = true;
139
198
  textLastFlush = Date.now();
140
- yield { type: "text-start", id: textId };
199
+ parts.push({ type: "text-start", id: textId });
141
200
  }
142
201
  textBuf += event.text;
143
202
  if (textBuf.length >= COALESCE_MAX_BYTES || Date.now() - textLastFlush >= COALESCE_INTERVAL_MS) {
144
- yield { type: "text-delta", id: textId, delta: textBuf };
203
+ parts.push({ type: "text-delta", id: textId, delta: textBuf });
145
204
  textBuf = "";
146
205
  textLastFlush = Date.now();
147
206
  }
148
207
  break;
149
208
  }
150
209
  case "reasoning": {
210
+ if (textOpen && textBuf) {
211
+ parts.push({ type: "text-delta", id: textId, delta: textBuf });
212
+ textBuf = "";
213
+ textLastFlush = Date.now();
214
+ }
151
215
  if (!reasoningOpen) {
152
216
  reasoningId = generateId();
153
217
  reasoningOpen = true;
154
218
  reasoningLastFlush = Date.now();
155
- yield { type: "reasoning-start", id: reasoningId };
219
+ parts.push({ type: "reasoning-start", id: reasoningId });
156
220
  }
157
221
  reasoningBuf += event.text;
158
222
  if (reasoningBuf.length >= COALESCE_MAX_BYTES || Date.now() - reasoningLastFlush >= COALESCE_INTERVAL_MS) {
159
- yield { type: "reasoning-delta", id: reasoningId, delta: reasoningBuf };
223
+ parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
160
224
  reasoningBuf = "";
161
225
  reasoningLastFlush = Date.now();
162
226
  }
163
227
  break;
164
228
  }
165
229
  case "tool_call_start": {
166
- if (textBuf) {
167
- yield { type: "text-delta", id: textId, delta: textBuf };
168
- textBuf = "";
169
- }
170
- if (reasoningBuf) {
171
- yield { type: "reasoning-delta", id: reasoningId, delta: reasoningBuf };
172
- reasoningBuf = "";
173
- }
174
- if (textOpen) {
175
- yield { type: "text-end", id: textId };
176
- textOpen = false;
177
- }
178
- if (reasoningOpen) {
179
- yield { type: "reasoning-end", id: reasoningId };
180
- reasoningOpen = false;
181
- }
182
- if (toolInputOpen) {
183
- yield { type: "tool-call", toolCallId: currentToolId, toolName: currentToolName, input: pendingToolArgs };
184
- }
185
- currentToolId = event.id || generateId();
186
- currentToolName = event.name;
187
- toolInputOpen = true;
188
- pendingToolArgs = "";
230
+ parts.push(...pendingDeltas());
231
+ parts.push(...closeBlocks());
232
+ const id = event.id || generateId();
233
+ const open = openTools.get(id);
234
+ if (open)
235
+ open.name = event.name;
236
+ else
237
+ openTools.set(id, { name: event.name, args: "" });
238
+ lastToolId = id;
189
239
  break;
190
240
  }
191
241
  case "tool_call_args": {
192
- pendingToolArgs += event.argsDelta;
242
+ const open = openTools.get(event.id ?? lastToolId);
243
+ // An orphan delta has no call to attach to; dropping it beats inventing
244
+ // a nameless tool call.
245
+ if (open)
246
+ open.args += event.argsDelta;
193
247
  break;
194
248
  }
195
249
  case "finish": {
196
- if (textBuf) {
197
- yield { type: "text-delta", id: textId, delta: textBuf };
198
- textBuf = "";
199
- }
200
- if (reasoningBuf) {
201
- yield { type: "reasoning-delta", id: reasoningId, delta: reasoningBuf };
202
- reasoningBuf = "";
203
- }
204
- if (textOpen) {
205
- yield { type: "text-end", id: textId };
206
- textOpen = false;
207
- }
208
- if (reasoningOpen) {
209
- yield { type: "reasoning-end", id: reasoningId };
210
- reasoningOpen = false;
211
- }
212
- if (toolInputOpen) {
213
- yield { type: "tool-call", toolCallId: currentToolId, toolName: currentToolName, input: pendingToolArgs };
214
- toolInputOpen = false;
215
- }
250
+ parts.push(...pendingDeltas());
251
+ parts.push(...closeBlocks());
216
252
  finishReason = event.reason;
217
253
  break;
218
254
  }
@@ -237,34 +273,77 @@ async function* convertStreamEvents(events, generateId, pricing) {
237
273
  break;
238
274
  }
239
275
  }
276
+ return parts;
277
+ };
278
+ // The loop is woken by a timer as well as by upstream events, so text that
279
+ // arrives and is then followed by silence is still delivered promptly instead
280
+ // of waiting for the next event or the end of the stream.
281
+ //
282
+ // A single `next()` is kept in flight across iterations: when the timer wins
283
+ // the race the pending read is handed to the next iteration rather than
284
+ // dropped, which is what keeps this from losing events.
285
+ const upstream = events[Symbol.asyncIterator]();
286
+ let inFlight = null;
287
+ const nextEvent = () => (inFlight ??= upstream.next());
288
+ let wake;
289
+ const ticker = setInterval(() => wake?.(), COALESCE_INTERVAL_MS);
290
+ const tick = () => new Promise((resolve) => {
291
+ wake = () => {
292
+ wake = undefined;
293
+ resolve(TICK);
294
+ };
295
+ });
296
+ // With nothing buffered there is nothing to flush, so the timer race — and its
297
+ // allocation — is skipped entirely for the common fast-streaming path.
298
+ const nextStep = () => textBuf || reasoningBuf ? Promise.race([nextEvent(), tick()]) : nextEvent();
299
+ yield { type: "stream-start", warnings: [] };
300
+ try {
301
+ for (;;) {
302
+ const step = await nextStep();
303
+ if (step === TICK) {
304
+ // The upstream read is still in flight; keep it for the next iteration.
305
+ yield* staleDeltas();
306
+ continue;
307
+ }
308
+ // Consume the read. Without clearing it here, the same settled promise
309
+ // would be handed back on the next iteration and the same event replayed
310
+ // forever.
311
+ inFlight = null;
312
+ if (step.done)
313
+ break;
314
+ yield* handleEvent(step.value);
315
+ }
240
316
  }
241
- // Final flush
242
- if (textBuf)
243
- yield { type: "text-delta", id: textId, delta: textBuf };
244
- if (reasoningBuf)
245
- yield { type: "reasoning-delta", id: reasoningId, delta: reasoningBuf };
246
- if (textOpen)
247
- yield { type: "text-end", id: textId };
248
- if (reasoningOpen)
249
- yield { type: "reasoning-end", id: reasoningId };
250
- if (toolInputOpen) {
251
- yield { type: "tool-call", toolCallId: currentToolId, toolName: currentToolName, input: pendingToolArgs };
317
+ finally {
318
+ clearInterval(ticker);
319
+ inFlight = null;
320
+ // Let the upstream generator finish so its own cleanup runs.
321
+ void upstream.return?.(undefined);
252
322
  }
253
- const inputTotal = usage?.inputTokens?.total;
254
- const cachedRead = usage?.inputTokens?.cacheRead;
255
- const outputTotal = usage?.outputTokens?.total;
256
- const cost = calculateCost({ inputTokens: inputTotal, cachedInputTokens: cachedRead, outputTokens: outputTotal }, pricing);
323
+ // Final flush
324
+ yield* pendingDeltas();
325
+ yield* closeBlocks();
326
+ yield* completedToolCalls();
257
327
  const rawReason = FINISH_REASON_MAP[finishReason] ?? "stop";
258
328
  yield {
259
329
  type: "finish",
260
330
  finishReason: { unified: rawReason, raw: finishReason },
261
331
  usage: usage ?? DEFAULT_USAGE,
262
- ...(cost !== undefined ? { providerMetadata: { devin: { cost } } } : {}),
263
332
  };
264
333
  }
265
- async function collectEvents(events) {
334
+ /** Exported for tests; mirrors `convertStreamEvents` for the non-streaming path. */
335
+ export async function collectEvents(events) {
266
336
  const result = { text: "", reasoning: "", toolCalls: [], finishReason: "stop" };
267
- let currentTool = null;
337
+ // Keyed by call id for the same reason as the streaming path: parallel tool
338
+ // calls interleave their argument deltas.
339
+ const openTools = new Map();
340
+ let lastToolId = "";
341
+ let anonymous = 0;
342
+ const commit = () => {
343
+ for (const tool of openTools.values())
344
+ result.toolCalls.push(tool);
345
+ openTools.clear();
346
+ };
268
347
  for await (const event of events) {
269
348
  switch (event.kind) {
270
349
  case "text":
@@ -273,20 +352,25 @@ async function collectEvents(events) {
273
352
  case "reasoning":
274
353
  result.reasoning += event.text;
275
354
  break;
276
- case "tool_call_start":
277
- if (currentTool)
278
- result.toolCalls.push(currentTool);
279
- currentTool = { id: event.id, name: event.name, args: "" };
355
+ case "tool_call_start": {
356
+ // A start without an id still needs its own buffer, otherwise two
357
+ // anonymous calls would share one.
358
+ const id = event.id ?? `__anonymous_${anonymous++}`;
359
+ const open = openTools.get(id);
360
+ if (open)
361
+ open.name = event.name;
362
+ else
363
+ openTools.set(id, { id: event.id ?? id, name: event.name, args: "" });
364
+ lastToolId = id;
280
365
  break;
281
- case "tool_call_args":
282
- if (currentTool)
283
- currentTool.args += event.argsDelta;
366
+ }
367
+ case "tool_call_args": {
368
+ const open = openTools.get(event.id ?? lastToolId);
369
+ if (open)
370
+ open.args += event.argsDelta;
284
371
  break;
372
+ }
285
373
  case "finish":
286
- if (currentTool) {
287
- result.toolCalls.push(currentTool);
288
- currentTool = null;
289
- }
290
374
  result.finishReason = event.reason;
291
375
  break;
292
376
  case "usage":
@@ -302,18 +386,65 @@ async function collectEvents(events) {
302
386
  break;
303
387
  }
304
388
  }
305
- if (currentTool)
306
- result.toolCalls.push(currentTool);
389
+ commit();
307
390
  return result;
308
391
  }
392
+ /**
393
+ * Refuse a request the catalog says cannot succeed, and warn about one it cannot
394
+ * vouch for.
395
+ *
396
+ * Disabled is a hard stop because the account cannot use it. Absent is only a
397
+ * warning: the catalog is not a contract that it enumerates every uid Cascade
398
+ * accepts, so the upstream response stays the authority.
399
+ */
400
+ function checkModelUsable(modelId, catalog) {
401
+ if (!catalog)
402
+ return;
403
+ const entry = catalog.entries.find((candidate) => candidate.modelUid === modelId);
404
+ if (!entry) {
405
+ console.warn(`[opencode-devin] model "${modelId}" is not in the Cascade catalog for this account; sending the request anyway`);
406
+ return;
407
+ }
408
+ if (entry.disabled)
409
+ throw new ModelNotAvailableError(modelId, entry.label);
410
+ }
411
+ /**
412
+ * Whether the catalog vouches for this model.
413
+ *
414
+ * `true` when the account's catalog lists it, `false` when the catalog loaded
415
+ * and does not mention it, `undefined` when no catalog was available at all.
416
+ */
417
+ function isKnownToCatalog(modelId, catalog) {
418
+ if (!catalog)
419
+ return undefined;
420
+ return catalog.entries.some((entry) => entry.modelUid === modelId);
421
+ }
422
+ /**
423
+ * Add the likely cause to a failure for a model the catalog never listed.
424
+ *
425
+ * Refusing such a model up front would be wrong: the catalog is not a contract
426
+ * that it enumerates every uid Cascade accepts, so a false rejection would break
427
+ * a model that does work. Instead the request is allowed to fail the way
428
+ * upstream makes it fail, and the probable reason is attached to that error —
429
+ * otherwise the user has to correlate a log warning with an HTTP failure.
430
+ */
431
+ function hintUnlistedModel(cause, modelId, known) {
432
+ if (known !== false || !(cause instanceof Error))
433
+ return cause;
434
+ cause.message +=
435
+ ` — model "${modelId}" is not listed in your Cognition catalog, which is the most likely reason.` +
436
+ ` If it should be available, run /connect to refresh the catalog, or pick a model from /models.`;
437
+ return cause;
438
+ }
309
439
  function createLanguageModel(options) {
310
- const run = (callOptions) => {
440
+ const run = async (callOptions, signal) => {
441
+ const catalog = await options.loadCatalog();
442
+ checkModelUsable(options.modelId, catalog);
311
443
  const effortOverride = callOptions.providerOptions?.devin?.reasoningEffort;
312
- const resolvedModelId = resolveEffortUid(options.modelId, options.catalog, effortOverride);
313
- const pricing = options.catalogMap?.get(resolvedModelId)?.pricing;
444
+ const resolvedModelId = resolveEffortUid(options.modelId, catalog?.enabled, effortOverride);
314
445
  return {
315
446
  resolvedModelId,
316
- pricing,
447
+ knownToCatalog: isKnownToCatalog(options.modelId, catalog),
317
448
  events: streamChatEvents({
318
449
  apiKey: options.apiKey,
319
450
  apiServerUrl: options.apiServerUrl,
@@ -326,7 +457,7 @@ function createLanguageModel(options) {
326
457
  topP: callOptions.topP,
327
458
  topK: callOptions.topK,
328
459
  },
329
- signal: callOptions.abortSignal,
460
+ signal,
330
461
  }),
331
462
  };
332
463
  };
@@ -336,8 +467,10 @@ function createLanguageModel(options) {
336
467
  modelId: options.modelId,
337
468
  supportedUrls: {},
338
469
  async doGenerate(callOptions) {
339
- const { pricing, events } = run(callOptions);
340
- const collected = await collectEvents(events);
470
+ const { events, knownToCatalog } = await run(callOptions, callOptions.abortSignal);
471
+ const collected = await collectEvents(events).catch((cause) => {
472
+ throw hintUnlistedModel(cause, options.modelId, knownToCatalog);
473
+ });
341
474
  const content = [];
342
475
  if (collected.reasoning)
343
476
  content.push({ type: "reasoning", text: collected.reasoning });
@@ -346,11 +479,6 @@ function createLanguageModel(options) {
346
479
  for (const call of collected.toolCalls) {
347
480
  content.push({ type: "tool-call", toolCallId: call.id, toolName: call.name, input: call.args });
348
481
  }
349
- const cost = calculateCost({
350
- inputTokens: collected.usage?.inputTokens?.total,
351
- cachedInputTokens: collected.usage?.inputTokens?.cacheRead,
352
- outputTokens: collected.usage?.outputTokens?.total,
353
- }, pricing);
354
482
  return {
355
483
  content,
356
484
  finishReason: {
@@ -359,25 +487,44 @@ function createLanguageModel(options) {
359
487
  },
360
488
  usage: collected.usage ?? DEFAULT_USAGE,
361
489
  warnings: [],
362
- ...(cost !== undefined ? { providerMetadata: { devin: { cost } } } : {}),
363
490
  };
364
491
  },
365
492
  async doStream(callOptions) {
366
- const { pricing, events } = run(callOptions);
493
+ // Owned so that cancelling the stream can tear the request down; the
494
+ // caller's signal is honoured alongside it.
495
+ const abort = new AbortController();
496
+ const signal = callOptions.abortSignal
497
+ ? AbortSignal.any([callOptions.abortSignal, abort.signal])
498
+ : abort.signal;
499
+ const { events, knownToCatalog } = await run(callOptions, signal);
367
500
  const generateId = () => crypto.randomUUID();
368
- const generator = convertStreamEvents(events, generateId, pricing);
501
+ const generator = convertStreamEvents(events, generateId);
502
+ const modelId = options.modelId;
503
+ let cancelled = false;
369
504
  const stream = new ReadableStream({
370
505
  async start(controller) {
371
506
  try {
372
507
  for await (const chunk of generator) {
508
+ if (cancelled)
509
+ break;
373
510
  controller.enqueue(chunk);
374
511
  }
375
- controller.close();
512
+ if (!cancelled)
513
+ controller.close();
376
514
  }
377
515
  catch (cause) {
378
- controller.error(cause);
516
+ if (!cancelled)
517
+ controller.error(hintUnlistedModel(cause, modelId, knownToCatalog));
379
518
  }
380
519
  },
520
+ async cancel() {
521
+ cancelled = true;
522
+ // Aborting is what actually releases the connection. `generator.return()`
523
+ // alone is not enough: it is queued behind the in-flight read, so the
524
+ // request would stay open until the idle timeout fired.
525
+ abort.abort(new Error("Stream cancelled by the consumer"));
526
+ await generator.return(undefined).catch(() => { });
527
+ },
381
528
  });
382
529
  return { stream };
383
530
  },
@@ -385,28 +532,43 @@ function createLanguageModel(options) {
385
532
  }
386
533
  export function createDevin(options) {
387
534
  const apiKey = options.apiKey ?? "";
388
- let cachedModels;
389
- let catalogMap;
535
+ let catalog;
536
+ let pending;
537
+ /**
538
+ * Per-account catalog, memoized for the life of the provider.
539
+ *
540
+ * `getCachedCatalog` already dedupes concurrent fetches and caches the result
541
+ * for 10 minutes, so this is normally a cache hit — the plugin's `publish()`
542
+ * warms the same module-level cache before any chat happens. On failure it
543
+ * resolves `undefined`, and the request proceeds uncatalogued rather than being
544
+ * rejected on a guess.
545
+ */
546
+ const loadCatalog = () => {
547
+ if (!apiKey)
548
+ return Promise.resolve(undefined);
549
+ if (catalog)
550
+ return Promise.resolve(catalog);
551
+ pending ??= getCachedCatalog(apiKey, options.baseURL)
552
+ .then((result) => {
553
+ if (result) {
554
+ const entries = Array.from(result.byUid.values());
555
+ catalog = { entries, enabled: entries.filter((entry) => !entry.disabled) };
556
+ }
557
+ return catalog;
558
+ })
559
+ .finally(() => {
560
+ pending = undefined;
561
+ });
562
+ return pending;
563
+ };
390
564
  return {
391
565
  languageModel(modelId) {
392
566
  return createLanguageModel({
393
567
  modelId,
394
568
  apiKey,
395
569
  apiServerUrl: options.baseURL,
396
- catalog: cachedModels,
397
- catalogMap,
570
+ loadCatalog,
398
571
  });
399
572
  },
400
- async models() {
401
- if (!apiKey)
402
- return [];
403
- const catalog = await getCachedCatalog(apiKey, options.baseURL);
404
- if (!catalog)
405
- return [];
406
- const models = Array.from(catalog.byUid.values()).filter((entry) => !entry.disabled);
407
- cachedModels = models;
408
- catalogMap = new Map(models.map((entry) => [entry.modelUid, entry]));
409
- return models;
410
- },
411
573
  };
412
574
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "opencode-devin",
4
- "version": "0.1.1",
4
+ "version": "0.2.0",
5
5
  "description": "OpenCode v2 plugin: connect your Devin subscription to opencode with native /connect login and devin/* models",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -19,9 +19,11 @@
19
19
  "dist"
20
20
  ],
21
21
  "scripts": {
22
- "build": "node -e \"fs.rmSync('dist',{recursive:true,force:true})\" && tsc",
23
- "typecheck": "tsc --noEmit",
24
- "prepublishOnly": "npm run build"
22
+ "build": "node scripts/build.mjs",
23
+ "build:clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true})\" && tsc",
24
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
25
+ "test": "bun test",
26
+ "prepublishOnly": "npm run build:clean"
25
27
  },
26
28
  "keywords": [
27
29
  "opencode",
@@ -48,6 +50,7 @@
48
50
  },
49
51
  "devDependencies": {
50
52
  "@types/bun": "1.4.2",
51
- "typescript": "5.9.3"
53
+ "protobufjs": "^8.8.0",
54
+ "typescript": "7.0.2"
52
55
  }
53
56
  }