opencode-devin 0.2.0 → 0.2.2

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
@@ -57,6 +57,21 @@ From the CLI:
57
57
  opencode run --model devin/swe-2-max "Refactor the auth module"
58
58
  ```
59
59
 
60
+ ### Reasoning effort
61
+
62
+ Cognition lists one model UID per reasoning effort (`claude-opus-5-5-low`,
63
+ `claude-opus-5-5-high`, ...). The plugin publishes each family once, as
64
+ `devin/claude-opus-5-5`, with the efforts as variants:
65
+
66
+ - In the TUI, cycle the effort with `ctrl+t` (`variant.cycle`).
67
+ - From the CLI or config, append it: `devin/claude-opus-5-5#high`.
68
+ - With no variant selected, the family runs at medium, or at high when it has
69
+ no medium.
70
+
71
+ Speed and context modifiers are separate families (`devin/claude-opus-5-5-fast`,
72
+ `devin/glm-5-2-1m`). The per-effort UIDs are still accepted, so an existing
73
+ `devin/claude-opus-5-5-high` keeps working; they are only hidden from the picker.
74
+
60
75
  ## How it works
61
76
 
62
77
  ```mermaid
@@ -89,7 +104,7 @@ flowchart TD
89
104
 
90
105
  - **No `devin/` models**: run `/connect` again. Failures are logged as `[opencode-devin] ...`; the log is at `~/.local/share/opencode/log/opencode.log`.
91
106
  - **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.
107
+ - **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
108
  - **A 401 during chat**: the short-lived token is refreshed automatically. Reconnect only if the session token itself was revoked.
94
109
  - **`Plugin failed to load`**: rebuild and `opencode reload`. See the FAQ on atomic builds.
95
110
  - **A path in `plugins` is ignored**: only `name@file:<absolute-path>` links a local build.
@@ -106,6 +121,9 @@ npm run build
106
121
  `build` is atomic, so the plugin can be reloaded while it runs. Publishing uses
107
122
  `build:clean`, which wipes `dist/` first.
108
123
 
124
+ Shared fixtures for the synthetic-catalog tests live in `test/helpers.ts`
125
+ (fake JWTs, protobuf `modelConfig`/`catalogReply` encoders, `stubFetch`).
126
+
109
127
  ### Developing against a local build
110
128
 
111
129
  Edit `plugins` in `~/.config/opencode/opencode.json` to one of these, then run
@@ -131,7 +149,21 @@ opencode api provider.list # the devin provider's "package" field
131
149
  ### Testing against the real API
132
150
 
133
151
  `bun test` runs everything except the live suite, which skips itself without a
134
- credential:
152
+ credential. The dev CLI gets you one and runs the whole check end to end:
153
+
154
+ ```sh
155
+ bun scripts/devin.ts all # login (if needed) → catalog dump → live tests
156
+ bun scripts/devin.ts login # just the PKCE login → .devin-token.env
157
+ bun scripts/devin.ts verify # dump live catalog pricing
158
+ bun scripts/devin.ts test # run test/live.test.ts
159
+ ```
160
+
161
+ The login is the same browser PKCE flow as `/connect` (loopback callback, or
162
+ `--manual` for paste-code on headless machines). The token lands in
163
+ `.devin-token.env`, which `verify`/`test`/`all` pick up automatically, so a
164
+ second `all` run skips the browser entirely.
165
+
166
+ Or with a token you already have:
135
167
 
136
168
  ```sh
137
169
  DEVIN_LLM_API_KEY='devin-session-token$...' bun test test/live.test.ts
@@ -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
+ }
package/dist/catalog.d.ts CHANGED
@@ -6,6 +6,17 @@
6
6
  * and context windows. This is the same source the Devin CLI uses
7
7
  * (`GetCliModelConfigs`); the REST gateway (`/api/v1/models`) is not
8
8
  * provisioned for most accounts.
9
+ *
10
+ * Upstream lists one UID per reasoning effort. They are published as one model
11
+ * per family with the efforts as variants, so the effort is picked with the
12
+ * variant switcher instead of by choosing a different model.
13
+ *
14
+ * The per-effort UIDs stay published as deprecated models. opencode leaves
15
+ * those out of the model picker but still resolves them, so a config, a
16
+ * favourite or a session that names `devin/claude-opus-5-5-high` keeps working.
9
17
  */
18
+ import { type ModelCatalogEntry } from "./protocol/catalog.ts";
10
19
  import { Model } from "@opencode/plugin";
11
20
  export declare function fetchModels(apiKey: string, apiServerUrl?: string): Promise<Model.Info[]>;
21
+ /** Exported for tests. */
22
+ export declare function toModelInfos(entries: readonly ModelCatalogEntry[]): Model.Info[];
package/dist/catalog.js CHANGED
@@ -6,31 +6,84 @@
6
6
  * and context windows. This is the same source the Devin CLI uses
7
7
  * (`GetCliModelConfigs`); the REST gateway (`/api/v1/models`) is not
8
8
  * provisioned for most accounts.
9
+ *
10
+ * Upstream lists one UID per reasoning effort. They are published as one model
11
+ * per family with the efforts as variants, so the effort is picked with the
12
+ * variant switcher instead of by choosing a different model.
13
+ *
14
+ * The per-effort UIDs stay published as deprecated models. opencode leaves
15
+ * those out of the model picker but still resolves them, so a config, a
16
+ * favourite or a session that names `devin/claude-opus-5-5-high` keeps working.
9
17
  */
10
18
  import { getCachedCatalog } from "./protocol/catalog.js";
19
+ import { defaultMember, EFFORT_LEVELS, toEffortLevel } from "./protocol/effort.js";
11
20
  import { Model, Provider } from "@opencode/plugin";
12
21
  import { DEFAULT_RELEASED_MS, PROVIDER_ID } from "./constants.js";
13
22
  export async function fetchModels(apiKey, apiServerUrl) {
14
23
  const catalog = await getCachedCatalog(apiKey, apiServerUrl || undefined);
15
24
  if (!catalog)
16
25
  return [];
17
- return Array.from(catalog.byUid.values())
18
- .filter((entry) => !entry.disabled)
19
- .map(toModelInfo);
26
+ return toModelInfos(Array.from(catalog.byUid.values()));
27
+ }
28
+ /** Exported for tests. */
29
+ export function toModelInfos(entries) {
30
+ const families = new Map();
31
+ for (const entry of entries) {
32
+ if (entry.disabled)
33
+ continue;
34
+ const key = entry.baseModelUid ?? entry.modelUid;
35
+ const family = families.get(key);
36
+ if (family)
37
+ family.push(entry);
38
+ else
39
+ families.set(key, [entry]);
40
+ }
41
+ const models = [];
42
+ for (const [baseModelUid, family] of families) {
43
+ const efforts = new Set(family.map((entry) => toEffortLevel(entry.effortLevel)));
44
+ // Only a family whose members are told apart by effort alone is merged.
45
+ // Anything else keeps one model per UID, so no UID becomes unreachable.
46
+ if (family.length > 1 && efforts.size === family.length && !efforts.has(undefined)) {
47
+ models.push(toModelInfo(defaultMember(family), baseModelUid, family));
48
+ for (const entry of family) {
49
+ if (entry.modelUid !== baseModelUid)
50
+ models.push(toModelInfo(entry, entry.modelUid, [], "deprecated"));
51
+ }
52
+ }
53
+ else {
54
+ for (const entry of family)
55
+ models.push(toModelInfo(entry, entry.modelUid, []));
56
+ }
57
+ }
58
+ return models;
59
+ }
60
+ /** "Claude Opus 5.5 High Fast" and "GPT-6 Sol No Thinking" without the effort. */
61
+ function familyName(label) {
62
+ const efforts = EFFORT_LEVELS.join("|");
63
+ const stripped = label
64
+ .replace(/\s+No Thinking\b/i, "")
65
+ .replace(new RegExp(`\\s+(?:${efforts})(?:\\s+Thinking)?(?=\\s|$)(?!.*\\s(?:${efforts})(?:\\s|$))`, "i"), "")
66
+ .trim();
67
+ return stripped || label;
20
68
  }
21
- function toModelInfo(entry) {
69
+ function toModelInfo(entry, id, family, status = "active") {
22
70
  const { pricing } = entry;
23
- const base = Model.Info.default(Provider.ID.make(PROVIDER_ID), Model.ID.make(entry.modelUid));
71
+ const base = Model.Info.default(Provider.ID.make(PROVIDER_ID), Model.ID.make(id));
72
+ const rank = (candidate) => EFFORT_LEVELS.indexOf(toEffortLevel(candidate.effortLevel));
24
73
  return {
25
74
  ...base,
26
- name: entry.label || entry.modelUid,
75
+ name: family.length > 0 ? familyName(entry.label || id) : entry.label || id,
27
76
  enabled: !entry.disabled,
28
- status: "active",
77
+ status,
29
78
  capabilities: {
30
79
  tools: true,
31
80
  input: ["text", "image"],
32
81
  output: ["text"],
33
82
  },
83
+ // Read by the provider as `providerOptions.devin.reasoningEffort`.
84
+ variants: [...family]
85
+ .sort((a, b) => rank(a) - rank(b))
86
+ .map((member) => ({ id: member.effortLevel, settings: { reasoningEffort: member.effortLevel } })),
34
87
  cost: [
35
88
  {
36
89
  input: pricing?.input ?? 0,
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
  });
@@ -8,9 +8,14 @@
8
8
  *
9
9
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
10
10
  */
11
- export declare class CloudAuthError extends Error {
11
+ import { APICallError } from "@ai-sdk/provider";
12
+ /**
13
+ * An `APICallError`, so the host sees the status: a rejected session token is
14
+ * then reported as an auth failure instead of being retried as unknown.
15
+ */
16
+ export declare class CloudAuthError extends APICallError {
12
17
  readonly status: number;
13
- constructor(message: string, status: number);
18
+ constructor(message: string, status: number, url?: string);
14
19
  }
15
20
  export interface UserJwt {
16
21
  jwt: string;
@@ -8,6 +8,7 @@
8
8
  *
9
9
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
10
10
  */
11
+ import { APICallError } from "@ai-sdk/provider";
11
12
  import { encodeMessage, iterFields } from "./wire.js";
12
13
  import { buildMetadata } from "./metadata.js";
13
14
  import { DEFAULT_API_SERVER } from "../constants.js";
@@ -18,10 +19,15 @@ const MINT_TIMEOUT_MS = 30_000;
18
19
  * mint, a too-long one keeps sending a token the server will reject.
19
20
  */
20
21
  const FALLBACK_JWT_TTL_SECONDS = 600;
21
- export class CloudAuthError extends Error {
22
+ /**
23
+ * An `APICallError`, so the host sees the status: a rejected session token is
24
+ * then reported as an auth failure instead of being retried as unknown.
25
+ */
26
+ export class CloudAuthError extends APICallError {
22
27
  status;
23
- constructor(message, status) {
24
- super(message);
28
+ constructor(message, status, url = "") {
29
+ // A 200 that carries no token is a server-side fault, not a success.
30
+ super({ message, url, requestBodyValues: undefined, statusCode: status >= 400 ? status : 502 });
25
31
  this.name = "CloudAuthError";
26
32
  this.status = status;
27
33
  }
@@ -36,7 +42,8 @@ export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
36
42
  });
37
43
  const request = encodeMessage(1, metadata);
38
44
  const timeout = AbortSignal.timeout(MINT_TIMEOUT_MS);
39
- const response = await fetch(`${host.replace(/\/$/, "")}/exa.auth_pb.AuthService/GetUserJwt`, {
45
+ const url = `${host.replace(/\/$/, "")}/exa.auth_pb.AuthService/GetUserJwt`;
46
+ const response = await fetch(url, {
40
47
  method: "POST",
41
48
  headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
42
49
  body: new Uint8Array(request),
@@ -44,7 +51,7 @@ export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
44
51
  });
45
52
  const buf = Buffer.from(await response.arrayBuffer());
46
53
  if (!response.ok) {
47
- throw new CloudAuthError(`GetUserJwt HTTP ${response.status}: ${buf.toString("utf8").slice(0, 400)}`, response.status);
54
+ throw new CloudAuthError(`GetUserJwt HTTP ${response.status}: ${buf.toString("utf8").slice(0, 400)}`, response.status, url);
48
55
  }
49
56
  let jwt = null;
50
57
  for (const field of iterFields(buf)) {
@@ -57,7 +64,7 @@ export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
57
64
  }
58
65
  }
59
66
  if (!jwt) {
60
- throw new CloudAuthError(`GetUserJwt 200 but no field-1 JWT found (${buf.length} bytes)`, response.status);
67
+ throw new CloudAuthError(`GetUserJwt 200 but no field-1 JWT found (${buf.length} bytes)`, response.status, url);
61
68
  }
62
69
  let expiresAt = Math.floor(Date.now() / 1000) + FALLBACK_JWT_TTL_SECONDS;
63
70
  try {
@@ -87,6 +94,18 @@ export const credentialKey = (host, apiKey) => `${host}${KEY_SEPARATOR}${apiKey}
87
94
  let cache = null;
88
95
  const inFlight = new Map();
89
96
  let cacheEpoch = 0;
97
+ /** Settle with `promise`, or reject as soon as `signal` aborts. */
98
+ function untilAborted(promise, signal) {
99
+ if (!signal)
100
+ return promise;
101
+ if (signal.aborted)
102
+ return Promise.reject(signal.reason);
103
+ return new Promise((resolve, reject) => {
104
+ const onAbort = () => reject(signal.reason);
105
+ signal.addEventListener("abort", onAbort, { once: true });
106
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
107
+ });
108
+ }
90
109
  /** Mint a user_jwt, reusing a cached one until shortly before expiry. */
91
110
  export async function getCachedUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
92
111
  const now = Math.floor(Date.now() / 1000);
@@ -94,22 +113,26 @@ export async function getCachedUserJwt(apiKey, host = DEFAULT_API_SERVER, signal
94
113
  return cache.jwt;
95
114
  }
96
115
  const key = credentialKey(host, apiKey);
97
- const pending = inFlight.get(key);
98
- if (pending)
99
- return (await pending).jwt;
100
- const promise = mintUserJwt(apiKey, host, signal);
101
- inFlight.set(key, promise);
102
- const epochAtStart = cacheEpoch;
103
- try {
104
- const minted = await promise;
105
- if (cacheEpoch === epochAtStart) {
106
- cache = { ...minted, apiKey, host };
107
- }
108
- return minted.jwt;
109
- }
110
- finally {
111
- inFlight.delete(key);
116
+ let pending = inFlight.get(key);
117
+ if (!pending) {
118
+ const epochAtStart = cacheEpoch;
119
+ // The mint is shared by every caller waiting on this credential, so it must
120
+ // not be tied to one caller's signal: cancelling that request would fail
121
+ // the others. It is bounded by its own timeout instead.
122
+ const shared = mintUserJwt(apiKey, host)
123
+ .then((minted) => {
124
+ if (cacheEpoch === epochAtStart)
125
+ cache = { ...minted, apiKey, host };
126
+ return minted;
127
+ })
128
+ .finally(() => {
129
+ if (inFlight.get(key) === shared)
130
+ inFlight.delete(key);
131
+ });
132
+ inFlight.set(key, shared);
133
+ pending = shared;
112
134
  }
135
+ return (await untilAborted(pending, signal)).jwt;
113
136
  }
114
137
  /** Drop the cached user_jwt (e.g. after an auth failure). */
115
138
  export function clearCachedUserJwt() {
@@ -5,6 +5,7 @@
5
5
  * windows. This is the same source the Devin CLI uses (`GetCliModelConfigs`).
6
6
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
7
7
  */
8
+ import { APICallError } from "@ai-sdk/provider";
8
9
  export interface ModelPricing {
9
10
  /** Price per 1M input tokens (USD), or 0 if free. */
10
11
  input: number;
@@ -27,9 +28,12 @@ export interface ModelCatalogEntry {
27
28
  contextWindow: number;
28
29
  pricing?: ModelPricing;
29
30
  capabilities?: ModelCapability[];
30
- /** Base model UID without the effort suffix (e.g. "claude-opus-4-8" for "claude-opus-4-8-medium"). */
31
+ /** Model UID without its effort (e.g. "claude-opus-4-8" for "claude-opus-4-8-medium"). */
31
32
  baseModelUid?: string;
32
- /** Reasoning effort level if encoded in the UID (none/low/medium/high/xhigh/max). */
33
+ /**
34
+ * Reasoning effort this UID runs at: read from the UID, or from the "Effort"
35
+ * capability when the UID names none (`glm-5-2` is GLM-5.2 at high).
36
+ */
33
37
  effortLevel?: string;
34
38
  }
35
39
  export interface Catalog {
@@ -45,8 +49,11 @@ export interface Catalog {
45
49
  * upstream request would be rejected regardless. A model that is simply absent
46
50
  * is *not* asserted on, because the catalog is not guaranteed to enumerate every
47
51
  * uid Cascade accepts and a false rejection would break a working model.
52
+ *
53
+ * Reported as a 403 so the host does not retry it: nothing changes between
54
+ * attempts.
48
55
  */
49
- export declare class ModelNotAvailableError extends Error {
56
+ export declare class ModelNotAvailableError extends APICallError {
50
57
  readonly modelUid: string;
51
58
  readonly label: string;
52
59
  constructor(modelUid: string, label: string);
@@ -5,10 +5,11 @@
5
5
  * windows. This is the same source the Devin CLI uses (`GetCliModelConfigs`).
6
6
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
7
7
  */
8
+ import { APICallError } from "@ai-sdk/provider";
8
9
  import { encodeMessage, iterFields } from "./wire.js";
9
10
  import { buildMetadata } from "./metadata.js";
10
11
  import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
11
- import { splitEffortSuffix } from "./effort.js";
12
+ import { effortFromLabel, splitEffortSuffix } from "./effort.js";
12
13
  import { DEFAULT_API_SERVER } from "../constants.js";
13
14
  const CATALOG_TTL_MS = 10 * 60 * 1000;
14
15
  const CATALOG_FETCH_TIMEOUT_MS = 10_000;
@@ -19,14 +20,22 @@ const CATALOG_FETCH_TIMEOUT_MS = 10_000;
19
20
  * upstream request would be rejected regardless. A model that is simply absent
20
21
  * is *not* asserted on, because the catalog is not guaranteed to enumerate every
21
22
  * uid Cascade accepts and a false rejection would break a working model.
23
+ *
24
+ * Reported as a 403 so the host does not retry it: nothing changes between
25
+ * attempts.
22
26
  */
23
- export class ModelNotAvailableError extends Error {
27
+ export class ModelNotAvailableError extends APICallError {
24
28
  modelUid;
25
29
  label;
26
30
  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.`);
31
+ super({
32
+ message: label && label !== modelUid
33
+ ? `Model "${label}" (uid=${modelUid}) is not enabled for your Cognition account tier.`
34
+ : `Model uid "${modelUid}" is not enabled for your Cognition account tier.`,
35
+ url: "",
36
+ requestBodyValues: undefined,
37
+ statusCode: 403,
38
+ });
30
39
  this.name = "ModelNotAvailableError";
31
40
  this.modelUid = modelUid;
32
41
  this.label = label;
@@ -89,7 +98,9 @@ function decodeModelConfig(buf) {
89
98
  modelUid = field.value.toString("utf8");
90
99
  }
91
100
  else if (field.num === 30 && field.wire === 2 && Buffer.isBuffer(field.value)) {
92
- // Capabilities message: #1 display name, #2 (repeated) feature { #1 name, #2 { #1 enabled, #2 value } }
101
+ // Capabilities message: #1 display name, #2 (repeated) feature
102
+ // { #1 name, #2 state { #1 level, #2 value } }. The level is 1 for an
103
+ // on/off feature that is on, and the rank of the effort for "Effort".
93
104
  capabilities = [];
94
105
  for (const feature of iterFields(field.value)) {
95
106
  if (feature.num !== 2 || feature.wire !== 2 || !Buffer.isBuffer(feature.value))
@@ -101,11 +112,16 @@ function decodeModelConfig(buf) {
101
112
  if (part.num === 1 && part.wire === 2 && Buffer.isBuffer(part.value)) {
102
113
  name = part.value.toString("utf8");
103
114
  }
104
- else if (part.num === 1 && part.wire === 0) {
105
- enabled = part.value === 1n;
106
- }
107
115
  else if (part.num === 2 && part.wire === 2 && Buffer.isBuffer(part.value)) {
108
- value = part.value.toString("utf8");
116
+ // The state is a nested message. Reading it as a string, as this
117
+ // used to, yielded its raw bytes and never set `enabled`.
118
+ for (const state of iterFields(part.value)) {
119
+ if (state.num === 1 && state.wire === 0)
120
+ enabled = state.value !== 0n;
121
+ else if (state.num === 2 && state.wire === 2 && Buffer.isBuffer(state.value)) {
122
+ value = state.value.toString("utf8");
123
+ }
124
+ }
109
125
  }
110
126
  }
111
127
  if (name)
@@ -113,7 +129,18 @@ function decodeModelConfig(buf) {
113
129
  }
114
130
  }
115
131
  else if (field.num === 32 && field.wire === 2 && Buffer.isBuffer(field.value)) {
116
- // Pricing message (repeated): #1 type, #4 price (float32 LE)
132
+ // Pricing message (repeated), verified against a live
133
+ // GetCascadeModelConfigs dump and the prices shown in the Devin app
134
+ // (e.g. claude-opus-5-5 = $4/$20, claude-sonnet-5-5 = $2/$10):
135
+ // #1 type string "Input" | "Cached input" | "Output"
136
+ // #2 price float32 USD per unit (#3 = "1M tokens") ← real price
137
+ // #3 unit string "1M tokens"
138
+ // #4 factor float32 per-type constant (0.1/0.007/0.28) —
139
+ // internal credit coefficient, NOT the price.
140
+ // This is what the old code read by mistake.
141
+ // #5 credits float32 same price expressed in Cognition credits
142
+ // #6 flag varint 1
143
+ // #7 note string e.g. "Higher effort consumes more tokens"
117
144
  pricing ??= { input: 0, cachedInput: 0, output: 0 };
118
145
  let type = "";
119
146
  let price = 0;
@@ -121,21 +148,32 @@ function decodeModelConfig(buf) {
121
148
  if (part.num === 1 && part.wire === 2 && Buffer.isBuffer(part.value)) {
122
149
  type = part.value.toString("utf8").toLowerCase();
123
150
  }
124
- else if (part.num === 4 && Buffer.isBuffer(part.value) && part.value.length === 4) {
151
+ else if (part.num === 2 &&
152
+ part.wire === 5 &&
153
+ Buffer.isBuffer(part.value) &&
154
+ part.value.length === 4) {
125
155
  price = part.value.readFloatLE(0);
126
156
  }
127
157
  }
128
- if (type.includes("input") && !type.includes("cached"))
158
+ // Match the pricing dimension by exact label, not substring: the REST
159
+ // API documents extra labels like "sidekick_input" (Fusion models) and
160
+ // "cache_read"/"cache_write" that would corrupt a substring match.
161
+ // Normalise case/spacing defensively — the wire strings are the same
162
+ // labels the REST API exposes in snake_case.
163
+ const normalized = type.trim().toLowerCase().replace(/[\s-]+/g, "_");
164
+ if (normalized === "input")
129
165
  pricing.input = price;
130
- else if (type.includes("cached"))
166
+ else if (normalized === "cached_input" || normalized === "cache_read")
131
167
  pricing.cachedInput = price;
132
- else if (type.includes("output"))
168
+ else if (normalized === "output")
133
169
  pricing.output = price;
134
170
  }
135
171
  }
136
172
  if (modelUid.length === 0)
137
173
  return undefined;
138
- const { baseModelUid, effortLevel } = splitEffortSuffix(modelUid);
174
+ const split = splitEffortSuffix(modelUid);
175
+ const baseModelUid = split.baseModelUid;
176
+ const effortLevel = split.effortLevel ?? effortFromLabel(capabilities?.find((capability) => /^(reasoning )?effort$/i.test(capability.name))?.value);
139
177
  return {
140
178
  modelUid,
141
179
  label: label || modelUid,
@@ -166,6 +204,13 @@ export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal
166
204
  }
167
205
  }
168
206
  const promise = fetchCatalog(apiKey, host, signal);
207
+ // Logged once, where the fetch is owned. The visible symptom is an empty
208
+ // `/models` list, and without this nothing says why. A caller cancelling its
209
+ // own request is not a failure worth reporting.
210
+ promise.catch((error) => {
211
+ if (!signal?.aborted)
212
+ console.warn("[opencode-devin] could not load the model catalog:", error);
213
+ });
169
214
  inFlight = promise;
170
215
  inFlightKey = key;
171
216
  try {