opencode-devin 0.2.11 → 2.0.0-beta.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.
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Provider package entrypoint loaded via the `aisdk:` specifier.
3
+ * opencode imports this module, calls the first `create*` export with the
4
+ * provider settings, and uses `sdk.languageModel(modelID)` as LanguageModelV3.
5
+ *
6
+ * Clean-room Cascade implementation — no third-party devin libs.
7
+ */
8
+ import { DevinCredentials } from "./auth.js";
9
+ import { streamChat, fetchCatalog, type ChatMessage, type UsageBlock } from "./cascade.js";
10
+ import { log } from "./log.js";
11
+
12
+ export { fetchCatalog };
13
+
14
+ /** Usage reported to opencode; missing metrics are estimated locally. */
15
+ type Usage = UsageBlock;
16
+
17
+ /** chars/4 heuristic — same one we put in the prompt's token-est field. */
18
+ function estimateTokens(chars: number): number {
19
+ return Math.max(1, Math.round(chars / 4));
20
+ }
21
+
22
+ interface ProviderSettings {
23
+ apiKey?: string;
24
+ sessionToken?: string; // devin-session-token$<jwt> — full credential
25
+ }
26
+
27
+ export function createDevinProvider(options: ProviderSettings = {}) {
28
+ const token = options.sessionToken ?? options.apiKey ?? process.env.DEVIN_API_KEY ?? "";
29
+ const creds = new DevinCredentials(token);
30
+ return {
31
+ languageModel: (modelID: string) => new CascadeLanguageModel(modelID, creds),
32
+ };
33
+ }
34
+
35
+ // Loader takes the module (or default export) as the SDK object itself —
36
+ // it must carry .languageModel(modelID) directly.
37
+ const sdk = createDevinProvider();
38
+ export const languageModel = sdk.languageModel;
39
+ export default sdk;
40
+
41
+ // Native package contract: model(modelID, settings) → LanguageModelV4.
42
+ export function model(modelID: string, settings: ProviderSettings = {}) {
43
+ return createDevinProvider(settings).languageModel(modelID);
44
+ }
45
+
46
+ /**
47
+ * LanguageModelV3 over the Cascade Connect-RPC stream.
48
+ * AI-SDK V3 contract: { specificationVersion, provider, modelId,
49
+ * doGenerate(), doStream() } — returns stream of model parts.
50
+ */
51
+ const EFFORT_LEVELS = ["none","minimal","low","medium","high","xhigh","max"] as const;
52
+
53
+ function effortIndex(segs: string[]): number {
54
+ for (let i = segs.length - 1; i > 0; i--) {
55
+ if ((EFFORT_LEVELS as readonly string[]).includes(segs[i])) return i;
56
+ }
57
+ return -1;
58
+ }
59
+
60
+ /** Replace the effort segment in a model uid (or append it if absent). */
61
+ export function withEffortSuffix(modelUid: string, effort: string): string {
62
+ const segs = modelUid.split("-");
63
+ const i = effortIndex(segs);
64
+ if (i === -1) return `${modelUid}-${effort}`;
65
+ segs[i] = effort;
66
+ return segs.join("-");
67
+ }
68
+
69
+ /** Catalog cache keyed by credential — one fetch per process per account. */
70
+ const catalogCache = new Map<string, Awaited<ReturnType<typeof fetchCatalog>>>();
71
+
72
+ async function catalogFor(creds: DevinCredentials) {
73
+ const hit = catalogCache.get(creds.key);
74
+ if (hit) return hit;
75
+ const entries = await fetchCatalog(creds);
76
+ catalogCache.set(creds.key, entries);
77
+ return entries;
78
+ }
79
+
80
+ /**
81
+ * Default catalog uid for a family when no effort was selected (e.g. the TUI
82
+ * picker sends `swe-2` with no variant). Mirrors the reference `defaultMember`:
83
+ * bare uid if the family has one, else medium, else high, else first.
84
+ */
85
+ async function defaultUidFor(family: string, creds: DevinCredentials): Promise<string> {
86
+ const entries = await catalogFor(creds);
87
+ const members = entries.filter((e) => !e.disabled && e.baseModelUid === family);
88
+ if (!members.length) return family;
89
+ return (
90
+ members.find((e) => e.modelUid === family) ??
91
+ members.find((e) => e.effortLevel === "medium") ??
92
+ members.find((e) => e.effortLevel === "high") ??
93
+ members[0]
94
+ ).modelUid;
95
+ }
96
+
97
+ export class CascadeLanguageModel {
98
+ readonly specificationVersion = "v3";
99
+ readonly provider = "devin";
100
+ readonly supportedUrls = {};
101
+
102
+ constructor(
103
+ readonly modelId: string,
104
+ private creds: DevinCredentials,
105
+ private effort?: string,
106
+ ) {}
107
+
108
+ private toCascadeMessages(prompt: unknown[]): { system?: string; messages: ChatMessage[] } {
109
+ let system: string | undefined;
110
+ const messages: ChatMessage[] = [];
111
+ for (const m of prompt as any[]) {
112
+ if (m.role === "system") {
113
+ const text =
114
+ typeof m.content === "string"
115
+ ? m.content
116
+ : (m.content ?? []).map((p: any) => p.text ?? "").join("");
117
+ system = (system ? system + "\n\n" : "") + text;
118
+ continue;
119
+ }
120
+ const role = m.role === "assistant" ? "assistant"
121
+ : m.role === "tool" ? "tool" : "user";
122
+ const parts: string[] = [];
123
+ const toolCalls: { id: string; name: string; args: string }[] = [];
124
+ if (typeof m.content === "string") parts.push(m.content);
125
+ const contentArr = Array.isArray(m.content) ? m.content : [];
126
+ for (const p of contentArr) {
127
+ if (p.type === "text") parts.push(p.text);
128
+ else if (p.type === "tool-call") {
129
+ toolCalls.push({ id: p.toolCallId, name: p.toolName, args: JSON.stringify(p.input) });
130
+ } else if (p.type === "tool-result") {
131
+ // tool result message — role tool with toolCallId
132
+ messages.push({
133
+ role: "tool",
134
+ toolCallId: p.toolCallId,
135
+ content: typeof p.output === "string" ? p.output : JSON.stringify(p.output?.value ?? p.output),
136
+ });
137
+ continue;
138
+ }
139
+ }
140
+ messages.push({ role, content: parts.join(""), toolCalls: toolCalls.length ? toolCalls : undefined });
141
+ }
142
+ return { system, messages };
143
+ }
144
+
145
+ async doGenerate(options: any) {
146
+ let text = "";
147
+ let finishReason = "stop";
148
+ let usage: Usage = {};
149
+ for await (const part of this.streamParts(options)) {
150
+ if (part.type === "text-delta") text += part.delta;
151
+ else if (part.type === "finish") {
152
+ finishReason = part.finishReason?.unified ?? finishReason;
153
+ usage = {
154
+ input: part.usage?.inputTokens?.total,
155
+ output: part.usage?.outputTokens?.total,
156
+ };
157
+ }
158
+ }
159
+ return {
160
+ content: [{ type: "text", text }],
161
+ finishReason,
162
+ usage: {
163
+ inputTokens: { total: usage.input ?? 0, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
164
+ outputTokens: { total: usage.output ?? 0, reasoning: undefined },
165
+ },
166
+ warnings: [],
167
+ };
168
+ }
169
+
170
+ private async *streamParts(options: any): AsyncGenerator<any> {
171
+ log.debug("model.doStream", {
172
+ modelId: this.modelId, optKeys: Object.keys(options),
173
+ providerOptionKeys: Object.keys(options.providerOptions ?? {}),
174
+ ctorEffort: this.effort ?? null,
175
+ });
176
+ const { system, messages } = this.toCascadeMessages(options.prompt ?? []);
177
+ const tools = (options.tools ?? [])
178
+ .filter((t: any) => t.type === "function")
179
+ .map((t: any) => ({
180
+ name: t.name,
181
+ description: t.description ?? "",
182
+ parameters: JSON.stringify(t.inputSchema ?? {}),
183
+ }));
184
+
185
+ // Effort resolution order: providerOptions (opencode sets
186
+ // devin.reasoningEffort from the #variant) then constructor effort.
187
+ // Variant effort travels in providerOptions.<provider>.reasoningEffort
188
+ // (opencode injects it from the model's #variant). Try provider ids.
189
+ const effort =
190
+ options.reasoningEffort ??
191
+ options.providerOptions?.devin?.reasoningEffort ??
192
+ options.providerOptions?.devin?.providerOptions?.devin?.reasoningEffort ??
193
+ // legacy provider-id namespace (harmless if opencode keys it differently)
194
+ options.providerOptions?.poc?.reasoningEffort ??
195
+ this.effort;
196
+ let modelUid: string;
197
+ if (effort) {
198
+ modelUid = withEffortSuffix(this.modelId, effort);
199
+ } else if (effortIndex(this.modelId.split("-")) !== -1) {
200
+ // Already an exact catalog uid (e.g. swe-2-high via -m).
201
+ modelUid = this.modelId;
202
+ } else {
203
+ // Bare family from the picker — resolve its default member.
204
+ try {
205
+ modelUid = await defaultUidFor(this.modelId, this.creds);
206
+ } catch (e) {
207
+ log.warn("model.default_uid_fail", { family: this.modelId, err: String(e) });
208
+ modelUid = this.modelId;
209
+ }
210
+ }
211
+ log.info("model.call", { modelId: this.modelId, effort: effort ?? null, modelUid });
212
+ // Prompt size for the usage estimate when the API reports no token metrics.
213
+ const promptChars =
214
+ (system?.length ?? 0) +
215
+ messages.reduce((n: number, m: ChatMessage) => n + m.content.length, 0) +
216
+ tools.reduce(
217
+ (n: number, t: { name: string; description: string; parameters: string }) =>
218
+ n + t.name.length + t.description.length + t.parameters.length,
219
+ 0,
220
+ );
221
+ const stream = streamChat(
222
+ {
223
+ modelUid,
224
+ messages,
225
+ system,
226
+ tools: tools.length ? tools : undefined,
227
+ temperature: options.temperature,
228
+ maxTokens: options.maxOutputTokens,
229
+ },
230
+ this.creds,
231
+ );
232
+
233
+ yield { type: "stream-start", warnings: [] };
234
+ yield { type: "response-metadata", id: crypto.randomUUID(), modelId: this.modelId };
235
+
236
+ // v3 finish part shape: {finishReason:{unified,raw}, usage:{inputTokens:{total,noCache,cacheRead,cacheWrite},outputTokens:{total,reasoning}}}
237
+ // v3 finish part shape: {finishReason:{unified,raw}, usage:{inputTokens:{total,noCache,cacheRead,cacheWrite},outputTokens:{total,reasoning}}}
238
+ // Cascade's local-agent path reports no token metrics (only display stats
239
+ // like agent_messages/model), so fall back to a chars/4 estimate — the same
240
+ // heuristic we send in the prompt's token-est field — to keep opencode's
241
+ // context accounting and auto-compaction working.
242
+ const mkUsage = (u: Usage) => ({
243
+ inputTokens: {
244
+ total: u.input ?? 0,
245
+ noCache: u.input !== undefined ? Math.max(0, u.input - (u.cachedInput ?? 0) - (u.cacheCreation ?? 0)) : undefined,
246
+ cacheRead: u.cachedInput,
247
+ cacheWrite: u.cacheCreation,
248
+ },
249
+ outputTokens: { total: u.output ?? 0, reasoning: u.reasoning },
250
+ });
251
+ const mkFinish = (reason: string, u: Usage) => ({
252
+ type: "finish",
253
+ finishReason: { unified: reason, raw: reason },
254
+ usage: mkUsage(u),
255
+ });
256
+
257
+ let textId: string | undefined;
258
+ let finishReason = "stop";
259
+ let reported: Usage = {};
260
+ let producedChars = 0;
261
+ for await (const d of stream) {
262
+ switch (d.type) {
263
+ case "thinking":
264
+ producedChars += d.text.length;
265
+ yield { type: "reasoning-start", id: "r1" };
266
+ yield { type: "reasoning-delta", id: "r1", delta: d.text };
267
+ break;
268
+ case "text":
269
+ producedChars += d.text.length;
270
+ if (!textId) { textId = "t1"; yield { type: "text-start", id: textId }; }
271
+ yield { type: "text-delta", id: textId, delta: d.text };
272
+ break;
273
+ case "tool_call":
274
+ producedChars += (d.argsDelta ?? "").length;
275
+ yield {
276
+ type: "tool-input-delta",
277
+ id: d.id,
278
+ delta: d.argsDelta ?? "",
279
+ };
280
+ break;
281
+ case "finish":
282
+ finishReason = d.reason;
283
+ break;
284
+ case "usage":
285
+ reported = { ...reported, ...d.usage };
286
+ break;
287
+ case "error":
288
+ yield { type: "error", error: new Error(d.message) };
289
+ break;
290
+ }
291
+ }
292
+ if (textId) yield { type: "text-end", id: textId };
293
+ const usage: Usage = {
294
+ ...reported,
295
+ input: reported.input ?? estimateTokens(promptChars),
296
+ output: reported.output ?? estimateTokens(producedChars),
297
+ };
298
+ log.debug("model.usage", {
299
+ modelUid, reported: reported.input !== undefined || reported.output !== undefined,
300
+ input: usage.input, output: usage.output,
301
+ });
302
+ yield mkFinish(finishReason, usage);
303
+ }
304
+
305
+ async doStream(options: any) {
306
+ const parts = this.streamParts(options);
307
+ return {
308
+ stream: new ReadableStream({
309
+ async start(ctrl) {
310
+ try {
311
+ for await (const p of parts) ctrl.enqueue(p);
312
+ ctrl.close();
313
+ } catch (e) {
314
+ ctrl.enqueue({ type: "error", error: e });
315
+ ctrl.close();
316
+ }
317
+ },
318
+ }),
319
+ };
320
+ }
321
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Lightweight structured logger — file-backed, no deps.
3
+ *
4
+ * Every model action (auth mint, catalog fetch, chat request, each streamed
5
+ * delta, tool call) gets one JSON line on disk so a user can hand us
6
+ * `opencode-devin.log` when something fails. A capped ring buffer keeps the most
7
+ * recent lines in memory for `recentLines()` — what a bug-report dumps.
8
+ *
9
+ * Destinations: OPENCODE_DEVIN_LOG → <dataDir>/opencode-devin.log
10
+ * (dataDir = OPENCODE_DEVIN_DIR → %APPDATA%/opencode-devin or ~/.config/opencode-devin)
11
+ */
12
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
13
+ import { dirname } from "node:path";
14
+ import { logFile } from "./paths.js";
15
+
16
+ export type LogLevel = "debug" | "info" | "warn" | "error";
17
+
18
+ const MAX_RING = 2000; // lines kept for recentLines()
19
+ const FILE_MAX = 5 * 1024 * 1024; // rotate above ~5MB
20
+ // logs can contain scrubbed-but-still-sensitive context; owner-only (0600).
21
+ const LOG_MODE = 0o600;
22
+
23
+ function resolvePath(): string {
24
+ // Fixed per-user location — cwd varies per project, which would scatter
25
+ // logs across every repo the user touches. paths.logFile() honours
26
+ // OPENCODE_DEVIN_LOG → dataDir().
27
+ return logFile();
28
+ }
29
+
30
+ const LOG_PATH = resolvePath();
31
+ const ring: string[] = [];
32
+ let fileSize = 0;
33
+
34
+ function ensureDir(p: string) {
35
+ try { mkdirSync(dirname(p), { recursive: true }); } catch {}
36
+ }
37
+ ensureDir(LOG_PATH);
38
+
39
+ function line(level: LogLevel, event: string, data?: Record<string, unknown>): string {
40
+ return JSON.stringify({
41
+ t: new Date().toISOString(),
42
+ lvl: level,
43
+ ev: event,
44
+ ...(data ? { d: data } : {}),
45
+ });
46
+ }
47
+
48
+ export function write(level: LogLevel, event: string, data?: Record<string, unknown>): void {
49
+ const l = line(level, event, data);
50
+ ring.push(l);
51
+ if (ring.length > MAX_RING) ring.splice(0, ring.length - MAX_RING);
52
+ try {
53
+ // rotate before appending when the cap is exceeded (keep one .1 backup)
54
+ if (fileSize === 0) {
55
+ try { fileSize = statSync(LOG_PATH).size; } catch { fileSize = 0; }
56
+ }
57
+ if (fileSize + l.length + 1 > FILE_MAX) {
58
+ try { renameSync(LOG_PATH, `${LOG_PATH}.1`); } catch {}
59
+ fileSize = 0;
60
+ }
61
+ appendFileSync(LOG_PATH, l + "\n", { mode: LOG_MODE });
62
+ fileSize += l.length + 1;
63
+ } catch { /* never let logging break a request */ }
64
+ }
65
+
66
+ export const log = {
67
+ debug: (ev: string, d?: Record<string, unknown>) => write("debug", ev, d),
68
+ info: (ev: string, d?: Record<string, unknown>) => write("info", ev, d),
69
+ warn: (ev: string, d?: Record<string, unknown>) => write("warn", ev, d),
70
+ error: (ev: string, d?: Record<string, unknown>) => write("error", ev, d),
71
+ };
72
+
73
+ /** Last N log lines — what a user pastes into a bug report. */
74
+ export function recentLines(n = 100): string[] {
75
+ return ring.slice(-n);
76
+ }
77
+
78
+ export function logPath(): string {
79
+ return LOG_PATH;
80
+ }
81
+
82
+ /**
83
+ * Scrub secret-looking substrings out of free-form text (server error bodies,
84
+ * tool output we forward) before it reaches the log. The log is meant to be
85
+ * safe to share; defense in depth on top of explicit `redact()`.
86
+ */
87
+ export function scrubSecrets(s: string): string {
88
+ return s
89
+ .replace(/devin-session-token\$[A-Za-z0-9._~+\/-]+=*/g, "devin-session-token$<redacted>")
90
+ .replace(/eyJ[A-Za-z0-9._~+\/-]{10,}=*/g, "<jwt-redacted>") // JWTs
91
+ .replace(/(Bearer|Authorization)\s+[A-Za-z0-9._~+\/-]+=*/gi, "$1 <redacted>")
92
+ .replace(/("(?:api_?key|access|refresh|token|secret|password)"\s*:\s*)"[^"]*"/gi, '$1"<redacted>"');
93
+ }
94
+
95
+ /** Redact a session/JWT for logs — keep enough to correlate, not enough to use. */
96
+ export function redact(token?: string): string | undefined {
97
+ if (!token) return token;
98
+ return token.length > 18 ? `${token.slice(0, 14)}…${token.slice(-6)}` : "***";
99
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "opencode-devin-provider",
3
+ "private": true,
4
+ "type": "module",
5
+ "main": "./index.ts"
6
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Fixed per-user data dir for the opencode-devin plugin.
3
+ *
4
+ * Namespaced `opencode-devin` on purpose: the reference/official Devin tooling
5
+ * may own anything called `devin`, so we never write there. Dev phase, no
6
+ * migration — only this dir is read.
7
+ *
8
+ * Resolution: OPENCODE_DEVIN_DIR → %APPDATA%/opencode-devin → ~/.config/opencode-devin
9
+ * Individual files: OPENCODE_DEVIN_LOG, OPENCODE_DEVIN_SESSION.
10
+ */
11
+ import { homedir } from "node:os";
12
+ import { mkdirSync } from "node:fs";
13
+ import { join } from "node:path";
14
+
15
+ const DIR_NAME = "opencode-devin";
16
+
17
+ export function dataDir(): string {
18
+ const dir =
19
+ process.env.OPENCODE_DEVIN_DIR ??
20
+ (process.env.APPDATA
21
+ ? join(process.env.APPDATA, DIR_NAME) // Windows
22
+ : join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), DIR_NAME));
23
+ try { mkdirSync(dir, { recursive: true }); } catch {}
24
+ return dir;
25
+ }
26
+
27
+ export function logFile(): string {
28
+ return process.env.OPENCODE_DEVIN_LOG ?? join(dataDir(), "opencode-devin.log");
29
+ }
30
+
31
+ export function sessionFile(): string {
32
+ return process.env.OPENCODE_DEVIN_SESSION ?? join(dataDir(), "session");
33
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Minimal protobuf wire encoder/decoder — no dependencies.
3
+ * Covers the Cascade protocol subset: varint, fixed32/64, length-delimited
4
+ * (strings, bytes, embedded messages), repeated fields via repeated tags.
5
+ */
6
+
7
+ export type Scalar = bigint | number | boolean
8
+ export type Bytes = Uint8Array
9
+ export type Message = Map<number, Array<Scalar | Bytes | Message>>
10
+
11
+ // ---------- encoding ----------
12
+
13
+ export function varint(v: number | bigint): Uint8Array {
14
+ let n = BigInt(v)
15
+ const out: number[] = []
16
+ do {
17
+ let b = Number(n & 0x7fn)
18
+ n >>= 7n
19
+ if (n !== 0n) b |= 0x80
20
+ out.push(b)
21
+ } while (n !== 0n)
22
+ return new Uint8Array(out)
23
+ }
24
+
25
+ export function zigzag(v: number | bigint): bigint {
26
+ const n = BigInt(v)
27
+ return (n << 1n) ^ (n >> 63n)
28
+ }
29
+
30
+ export function tag(field: number, wire: number): Uint8Array {
31
+ return varint((field << 3) | wire)
32
+ }
33
+
34
+ export function concat(...parts: Uint8Array[]): Uint8Array {
35
+ const len = parts.reduce((a, p) => a + p.length, 0)
36
+ const out = new Uint8Array(len)
37
+ let off = 0
38
+ for (const p of parts) { out.set(p, off); off += p.length }
39
+ return out
40
+ }
41
+
42
+ /** wire 0 — varint field */
43
+ export function fVarint(field: number, v: number | bigint): Uint8Array {
44
+ return concat(tag(field, 0), varint(v))
45
+ }
46
+
47
+ /** wire 2 — length-delimited: string */
48
+ export function fString(field: number, s: string): Uint8Array {
49
+ const b = new TextEncoder().encode(s)
50
+ return concat(tag(field, 2), varint(b.length), b)
51
+ }
52
+
53
+ /** wire 2 — length-delimited: raw bytes */
54
+ export function fBytes(field: number, b: Uint8Array): Uint8Array {
55
+ return concat(tag(field, 2), varint(b.length), b)
56
+ }
57
+
58
+ /** wire 2 — embedded message (takes an already-encoded body) */
59
+ export function fMessage(field: number, body: Uint8Array): Uint8Array {
60
+ return fBytes(field, body)
61
+ }
62
+
63
+ /** wire 5 — 32-bit */
64
+ export function fFixed32(field: number, v: number): Uint8Array {
65
+ const b = new Uint8Array(4)
66
+ new DataView(b.buffer).setUint32(0, v, true)
67
+ return concat(tag(field, 5), b)
68
+ }
69
+
70
+ /** wire 5 — float32 (Cascade pricing fields) */
71
+ export function fFloat32(field: number, v: number): Uint8Array {
72
+ const b = new Uint8Array(4)
73
+ new DataView(b.buffer).setFloat32(0, v, true)
74
+ return concat(tag(field, 5), b)
75
+ }
76
+
77
+ /** wire 1 — 64-bit / float64 */
78
+ export function fFixed64(field: number, v: number | bigint): Uint8Array {
79
+ const b = new Uint8Array(8)
80
+ new DataView(b.buffer).setBigUint64(0, BigInt(v), true)
81
+ return concat(tag(field, 1), b)
82
+ }
83
+
84
+ // ---------- decoding ----------
85
+
86
+ export class Reader {
87
+ pos = 0
88
+ constructor(public buf: Uint8Array, public end = buf.length) {}
89
+
90
+ varint(): bigint {
91
+ let result = 0n, shift = 0n
92
+ for (;;) {
93
+ const b = this.buf[this.pos++]
94
+ result |= BigInt(b & 0x7f) << shift
95
+ if (!(b & 0x80)) return result
96
+ shift += 7n
97
+ }
98
+ }
99
+
100
+ /** tag → {field, wire} */
101
+ readTag(): { field: number; wire: number } {
102
+ const t = Number(this.varint())
103
+ return { field: t >>> 3, wire: t & 7 }
104
+ }
105
+
106
+ bytes(): Uint8Array {
107
+ const len = Number(this.varint())
108
+ const out = this.buf.subarray(this.pos, this.pos + len)
109
+ this.pos += len
110
+ return out
111
+ }
112
+
113
+ string(): string {
114
+ return new TextDecoder().decode(this.bytes())
115
+ }
116
+
117
+ fixed32(): number {
118
+ const v = new DataView(this.buf.buffer, this.buf.byteOffset + this.pos).getUint32(0, true)
119
+ this.pos += 4
120
+ return v
121
+ }
122
+
123
+ float32(): number {
124
+ const v = new DataView(this.buf.buffer, this.buf.byteOffset + this.pos).getFloat32(0, true)
125
+ this.pos += 4
126
+ return v
127
+ }
128
+
129
+ fixed64(): bigint {
130
+ const v = new DataView(this.buf.buffer, this.buf.byteOffset + this.pos).getBigUint64(0, true)
131
+ this.pos += 8
132
+ return v
133
+ }
134
+
135
+ skip(wire: number): void {
136
+ switch (wire) {
137
+ case 0: this.varint(); break
138
+ case 1: this.pos += 8; break
139
+ case 2: this.pos += Number(this.varint()); break
140
+ case 5: this.pos += 4; break
141
+ default: throw new Error(`unknown wire type ${wire}`)
142
+ }
143
+ }
144
+
145
+ get done(): boolean { return this.pos >= this.end }
146
+ }
147
+
148
+ /** Decode a whole message into field → values map. wire-2 stays raw bytes. */
149
+ export function decodeMessage(buf: Uint8Array): Message {
150
+ const r = new Reader(buf)
151
+ const msg: Message = new Map()
152
+ while (!r.done) {
153
+ const { field, wire } = r.readTag()
154
+ let v: Scalar | Bytes
155
+ switch (wire) {
156
+ case 0: {
157
+ const n = r.varint()
158
+ v = n <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(n) : n
159
+ break
160
+ }
161
+ case 1: v = r.fixed64(); break
162
+ case 2: v = r.bytes(); break
163
+ case 5: v = r.fixed32(); break
164
+ default: throw new Error(`unknown wire type ${wire} at field ${field}`)
165
+ }
166
+ const arr = msg.get(field) ?? []
167
+ arr.push(v)
168
+ msg.set(field, arr)
169
+ }
170
+ return msg
171
+ }
172
+
173
+ // ---------- convenience getters ----------
174
+
175
+ export function getScalar(msg: Message, field: number): Scalar | undefined {
176
+ return msg.get(field)?.[0] as Scalar | undefined
177
+ }
178
+ export function getString(msg: Message, field: number): string | undefined {
179
+ const v = msg.get(field)?.[0]
180
+ return v instanceof Uint8Array ? new TextDecoder().decode(v) : undefined
181
+ }
182
+ export function getStrings(msg: Message, field: number): string[] {
183
+ return (msg.get(field) ?? []).filter((v): v is Uint8Array => v instanceof Uint8Array)
184
+ .map((b) => new TextDecoder().decode(b))
185
+ }
186
+ export function getBytes(msg: Message, field: number): Uint8Array | undefined {
187
+ const v = msg.get(field)?.[0]
188
+ return v instanceof Uint8Array ? v : undefined
189
+ }
190
+ export function getSubMessage(msg: Message, field: number): Message | undefined {
191
+ const b = getBytes(msg, field)
192
+ return b ? decodeMessage(b) : undefined
193
+ }
194
+ export function getSubMessages(msg: Message, field: number): Message[] {
195
+ return (msg.get(field) ?? []).filter((v): v is Uint8Array => v instanceof Uint8Array)
196
+ .map(decodeMessage)
197
+ }
package/dist/catalog.d.ts DELETED
@@ -1,22 +0,0 @@
1
- /**
2
- * Model catalog from Cognition's Cascade gRPC API.
3
- *
4
- * The live catalog comes from the per-account `GetCascadeModelConfigs` RPC
5
- * (via ai-sdk-devin) — every model UID the subscription can use, with pricing
6
- * and context windows. This is the same source the Devin CLI uses
7
- * (`GetCliModelConfigs`); the REST gateway (`/api/v1/models`) is not
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.
17
- */
18
- import { type ModelCatalogEntry } from "devin-core";
19
- import { Model } from "@opencode/plugin";
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[];