opencode-devin 0.2.1 → 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
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,
@@ -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)
@@ -155,7 +171,9 @@ function decodeModelConfig(buf) {
155
171
  }
156
172
  if (modelUid.length === 0)
157
173
  return undefined;
158
- 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);
159
177
  return {
160
178
  modelUid,
161
179
  label: label || modelUid,
@@ -186,6 +204,13 @@ export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal
186
204
  }
187
205
  }
188
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
+ });
189
214
  inFlight = promise;
190
215
  inFlightKey = key;
191
216
  try {
@@ -4,10 +4,33 @@
4
4
  * Field layouts come from mitm captures of the Windsurf language_server.
5
5
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
6
6
  */
7
- export declare class CloudChatError extends Error {
7
+ import { APICallError } from "@ai-sdk/provider";
8
+ /** Exported for tests. */
9
+ export declare function statusForCode(code: string | undefined, message: string): number;
10
+ export interface CloudChatErrorOptions {
11
+ code?: string;
12
+ traceId?: string;
13
+ /** HTTP status when the server sent one; otherwise derived from `code`. */
14
+ status?: number;
15
+ url?: string;
16
+ responseBody?: string;
17
+ /**
18
+ * The failure was a rejected `user_jwt` that has since been dropped, so the
19
+ * same request will succeed with a fresh one. Without this an auth status
20
+ * reads as final and the host gives up.
21
+ */
22
+ retryWithFreshToken?: boolean;
23
+ }
24
+ /**
25
+ * A failed chat request.
26
+ *
27
+ * It is an `APICallError` so hosts can read `statusCode` and `isRetryable`
28
+ * instead of guessing from the message.
29
+ */
30
+ export declare class CloudChatError extends APICallError {
8
31
  readonly code?: string;
9
32
  readonly traceId?: string;
10
- constructor(message: string, code?: string, traceId?: string);
33
+ constructor(message: string, options?: CloudChatErrorOptions);
11
34
  }
12
35
  /** Cognition rejects source=3 for system; system content is inlined into user turns. */
13
36
  declare const SOURCE_BY_ROLE: {
@@ -38,14 +61,21 @@ export interface ChatHistoryItem {
38
61
  content: ChatContent;
39
62
  tool_call_id?: string;
40
63
  tool_calls?: ChatToolCall[];
64
+ /** For a tool message: the tool reported a failure. */
65
+ is_error?: boolean;
41
66
  }
67
+ export type ChatToolChoice = {
68
+ type: "auto" | "none" | "required";
69
+ } | {
70
+ type: "tool";
71
+ toolName: string;
72
+ };
42
73
  export interface ChatToolDefinition {
43
74
  name: string;
44
75
  description?: string;
45
76
  parameters?: unknown;
46
77
  }
47
78
  export interface CompletionOptions {
48
- maxInputTokens?: number;
49
79
  maxOutputTokens?: number;
50
80
  temperature?: number;
51
81
  topP?: number;
@@ -83,9 +113,15 @@ export interface StreamChatRequest {
83
113
  modelUid: string;
84
114
  messages: ChatHistoryItem[];
85
115
  tools?: ChatToolDefinition[];
116
+ toolChoice?: ChatToolChoice;
86
117
  cascadeId?: string;
87
118
  completionOpts?: CompletionOptions;
88
119
  signal?: AbortSignal;
120
+ /** Override the default timeouts. Exists so tests need not wait out the real ones. */
121
+ timeouts?: {
122
+ ttfbMs?: number;
123
+ idleMs?: number;
124
+ };
89
125
  }
90
126
  /** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
91
127
  export declare function streamChatEvents(request: StreamChatRequest): AsyncGenerator<ChatEvent>;