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,469 @@
1
+ /**
2
+ * Cascade wire client — clean-room Connect-RPC/protobuf implementation.
3
+ *
4
+ * GetChatMessage: server-streaming Connect-RPC
5
+ * request → unary frame: flags(1B) | len(4B BE) | proto body
6
+ * response → repeated frames: flags(1B) | len(4B BE) | payload
7
+ * flag 0x01 = gzip, 0x02 = EOS trailer (JSON {error})
8
+ *
9
+ * GetCascadeModelConfigs: unary RPC returning the account's model catalog.
10
+ *
11
+ * Field numbers verified against live traffic of the devin CLI (chisel).
12
+ */
13
+ import { gunzipSync, gzipSync } from "node:zlib";
14
+ import {
15
+ decodeMessage, fMessage, fString, fVarint, getBytes, getString,
16
+ getSubMessage, getSubMessages, type Message,
17
+ } from "./proto.js";
18
+ import { randomUUID } from "node:crypto";
19
+ import { DevinCredentials, concatProto, encodeMetadata } from "./auth.js";
20
+ import { log, redact, scrubSecrets } from "./log.js";
21
+
22
+ const RPC_BASE = "/exa.api_server_pb.ApiServerService";
23
+
24
+ /** Build the full Metadata proto for catalog/chat RPCs (includes userJwt). */
25
+ function buildMeta(sessionToken: string, userJwt: string): Uint8Array {
26
+ return encodeMetadata({
27
+ apiKey: sessionToken,
28
+ sessionId: randomUUID(),
29
+ requestId: BigInt(Date.now()),
30
+ triggerId: randomUUID(),
31
+ userJwt,
32
+ });
33
+ }
34
+
35
+ // ---------- connect frames ----------
36
+
37
+ function frame(body: Uint8Array, compress = false): Uint8Array {
38
+ let payload = body;
39
+ let flags = 0;
40
+ if (compress) {
41
+ payload = gzipSync(body);
42
+ flags |= 0x01;
43
+ }
44
+ const head = new Uint8Array(5);
45
+ head[0] = flags;
46
+ new DataView(head.buffer).setUint32(1, payload.length);
47
+ const out = new Uint8Array(5 + payload.length);
48
+ out.set(head); out.set(payload, 5);
49
+ return out;
50
+ }
51
+
52
+ interface RawFrame { flags: number; payload: Uint8Array }
53
+
54
+ async function* readFrames(stream: ReadableStream<Uint8Array>): AsyncGenerator<RawFrame> {
55
+ const reader = stream.getReader();
56
+ let buf = new Uint8Array(0);
57
+ const take = (n: number) => { const r = buf.subarray(0, n); buf = buf.subarray(n); return r };
58
+ try {
59
+ for (;;) {
60
+ while (buf.length < 5) {
61
+ const { done, value } = await reader.read();
62
+ if (done) return;
63
+ const nb = new Uint8Array(buf.length + value.length);
64
+ nb.set(buf); nb.set(value, buf.length); buf = nb;
65
+ }
66
+ const flags = buf[0];
67
+ const len = new DataView(buf.buffer, buf.byteOffset).getUint32(1);
68
+ while (buf.length < 5 + len) {
69
+ const { done, value } = await reader.read();
70
+ if (done) throw new Error("stream truncated mid-frame");
71
+ const nb = new Uint8Array(buf.length + value.length);
72
+ nb.set(buf); nb.set(value, buf.length); buf = nb;
73
+ }
74
+ take(5);
75
+ let payload = take(len);
76
+ if (flags & 0x01) payload = gunzipSync(payload);
77
+ yield { flags, payload };
78
+ }
79
+ } finally { reader.releaseLock(); }
80
+ }
81
+
82
+ async function post(host: string, path: string, body: Uint8Array, jwt: string, stream: boolean) {
83
+ // user_jwt travels inside proto Metadata field 21 — no Authorization header.
84
+ const res = await fetch(`${host}${RPC_BASE}/${path}`, {
85
+ method: "POST",
86
+ headers: stream
87
+ ? {
88
+ "content-type": "application/connect+proto",
89
+ "connect-protocol-version": "1",
90
+ "connect-content-encoding": "gzip",
91
+ "connect-accept-encoding": "gzip",
92
+ }
93
+ : {
94
+ "content-type": "application/proto",
95
+ "connect-protocol-version": "1",
96
+ authorization: `Bearer ${jwt}`,
97
+ },
98
+ body: stream ? frame(body, true) : body,
99
+ });
100
+ if (!res.ok) {
101
+ const text = await res.text().catch(() => "");
102
+ const err = new Error(`${path}: ${res.status} ${text}`) as Error & { status: number };
103
+ err.status = res.status;
104
+ throw err;
105
+ }
106
+ return res;
107
+ }
108
+
109
+ // ---------- model catalog ----------
110
+
111
+ export interface CatalogPricing {
112
+ input: number;
113
+ cachedInput: number;
114
+ output: number;
115
+ }
116
+
117
+ export interface CatalogEntry {
118
+ modelUid: string;
119
+ label: string;
120
+ disabled: boolean;
121
+ contextWindow: number;
122
+ /** Effort from uid suffix, or the capability "Effort" state rank. */
123
+ effortLevel?: string;
124
+ /** Family uid without effort/speed suffix — the modelID opencode shows. */
125
+ baseModelUid: string;
126
+ pricing?: CatalogPricing;
127
+ }
128
+
129
+ export async function fetchCatalog(creds: DevinCredentials): Promise<CatalogEntry[]> {
130
+ const t0 = Date.now();
131
+ const { jwt, cascadeHost } = await creds.jwt();
132
+ const body = fMessage(1, buildMeta(credsSessionToken(creds), jwt));
133
+ const res = await post(cascadeHost, "GetCascadeModelConfigs", body, jwt, false);
134
+ const raw = new Uint8Array(await res.arrayBuffer());
135
+ const msg = decodeMessage(raw); // unary response = raw proto body
136
+ const entries = getSubMessages(msg, 1)
137
+ .map(toCatalogEntry)
138
+ .filter((e): e is CatalogEntry => e !== undefined && e.modelUid.length > 0);
139
+ log.info("catalog.fetch", {
140
+ host: cascadeHost, entries: entries.length,
141
+ enabled: entries.filter((e) => !e.disabled).length, ms: Date.now() - t0,
142
+ });
143
+ return entries;
144
+ }
145
+
146
+ // sessionToken stays private inside DevinCredentials — expose via jwt mint side-channel
147
+ function credsSessionToken(creds: DevinCredentials): string {
148
+ return (creds as any).sessionToken as string;
149
+ }
150
+
151
+ const EFFORT_NAMES = ["none","minimal","low","medium","high","xhigh","max"];
152
+
153
+ function effortIndex(segs: string[]): number {
154
+ for (let i = segs.length - 1; i > 0; i--) {
155
+ if (EFFORT_NAMES.includes(segs[i])) return i;
156
+ }
157
+ return -1;
158
+ }
159
+
160
+ function splitEffortSuffix(uid: string): { base: string; effort?: string } {
161
+ const segs = uid.split("-");
162
+ const i = effortIndex(segs);
163
+ if (i === -1) return { base: uid };
164
+ return { base: [...segs.slice(0, i), ...segs.slice(i + 1)].join("-"), effort: segs[i] };
165
+ }
166
+
167
+ // field-32 pricing message: #1 type label, #2 price float32, #4 factor float32
168
+ function decodePricing(field32s: Uint8Array[]): CatalogPricing | undefined {
169
+ let p: CatalogPricing | undefined;
170
+ for (const buf of field32s) {
171
+ const m = decodeMessage(buf);
172
+ const type = (getString(m, 1) ?? "").trim().toLowerCase().replace(/[\s-]+/g, "_");
173
+ const raw = m.get(2)?.[0];
174
+ // decodeMessage keeps wire-5 as raw uint32 — read as float32
175
+ let price = 0;
176
+ if (typeof raw === "number") price = new Float32Array(new Uint32Array([raw]).buffer)[0];
177
+ if (!p) p = { input: 0, cachedInput: 0, output: 0 };
178
+ if (type === "input") p.input = price;
179
+ else if (type === "cached_input" || type === "cache_read") p.cachedInput = price;
180
+ else if (type === "output") p.output = price;
181
+ }
182
+ return p;
183
+ }
184
+
185
+ // field-30 capabilities → feature "Effort" → state rank (1 = enabled/effort label)
186
+ function decodeEffortCapability(capBody: Uint8Array | undefined): string | undefined {
187
+ if (!capBody) return undefined;
188
+ const cap = decodeMessage(capBody);
189
+ for (const featureBody of (cap.get(2) ?? []).filter((v): v is Uint8Array => v instanceof Uint8Array)) {
190
+ const feat = decodeMessage(featureBody);
191
+ const name = getString(feat, 1);
192
+ if (!name || !/^(reasoning )?effort$/i.test(name)) continue;
193
+ const stateBody = feat.get(2)?.[0];
194
+ if (!(stateBody instanceof Uint8Array)) continue;
195
+ const state = decodeMessage(stateBody);
196
+ const value = getString(state, 2);
197
+ if (value) return effortFromLabel(value);
198
+ }
199
+ return undefined;
200
+ }
201
+
202
+ function effortFromLabel(label?: string): string | undefined {
203
+ if (!label) return undefined;
204
+ const l = label.trim().toLowerCase();
205
+ if (l === "no thinking") return "none";
206
+ return EFFORT_NAMES.includes(l) ? l : undefined;
207
+ }
208
+
209
+ function toCatalogEntry(m: Message): CatalogEntry {
210
+ const modelUid = getString(m, 22) ?? "";
211
+ const label = getString(m, 1) ?? "";
212
+ const { base, effort: suffixEffort } = splitEffortSuffix(modelUid);
213
+ const capEffort = decodeEffortCapability(getBytes(m, 30));
214
+ return {
215
+ modelUid,
216
+ label,
217
+ disabled: getScalarNum(m, 4) === 1,
218
+ contextWindow: getScalarNum(m, 18) ?? 0,
219
+ effortLevel: suffixEffort ?? capEffort,
220
+ baseModelUid: base,
221
+ pricing: decodePricing(
222
+ (m.get(32) ?? []).filter((v): v is Uint8Array => v instanceof Uint8Array),
223
+ ),
224
+ };
225
+ }
226
+
227
+ function getScalarNum(m: Message, f: number): number | undefined {
228
+ const v = m.get(f)?.[0];
229
+ return typeof v === "number" ? v : typeof v === "bigint" ? Number(v) : undefined;
230
+ }
231
+
232
+ // ---------- chat streaming ----------
233
+
234
+ export type ChatRole = "user" | "assistant" | "tool";
235
+ // Cascade has NO system role — callers fold system into the first user turn.
236
+
237
+ export interface ChatMessage {
238
+ role: ChatRole;
239
+ content: string;
240
+ toolCallId?: string;
241
+ toolCalls?: { id: string; name: string; args: string }[];
242
+ }
243
+
244
+ export interface ChatRequest {
245
+ modelUid: string;
246
+ messages: ChatMessage[];
247
+ system?: string;
248
+ tools?: { name: string; description: string; parameters: string }[]; // JSON schema as string
249
+ maxTokens?: number;
250
+ temperature?: number;
251
+ cascadeId?: string;
252
+ }
253
+
254
+ export type ChatDelta =
255
+ | { type: "text"; text: string }
256
+ | { type: "thinking"; text: string }
257
+ | { type: "tool_call"; id: string; name?: string; argsDelta?: string }
258
+ | { type: "finish"; reason: string }
259
+ | { type: "usage"; usage: UsageBlock }
260
+ | { type: "error"; message: string };
261
+
262
+ /** Token metrics the API may report. All optional: the local-agent path
263
+ * usually sends only non-token stats (agent_messages, model), so callers
264
+ * fall back to an estimate for context accounting. */
265
+ export interface UsageBlock {
266
+ input?: number;
267
+ output?: number;
268
+ cachedInput?: number;
269
+ cacheCreation?: number;
270
+ reasoning?: number;
271
+ }
272
+
273
+ // ChatMessage field 28 = "Response Statistics": a list of Metric messages,
274
+ // Metric { #5 name ("input_tokens"…), #4 { #2 value (float32) } }
275
+ // Names outside the token set (agent_messages, model) are display-only.
276
+ function decodeUsage(buf: Uint8Array): UsageBlock | undefined {
277
+ const u: UsageBlock = {};
278
+ for (const metric of getSubMessages(decodeMessage(buf), 2)) {
279
+ const name = (getString(metric, 5) ?? "").trim().toLowerCase();
280
+ const raw = getSubMessage(metric, 4)?.get(2)?.[0];
281
+ if (!name || typeof raw !== "number") continue;
282
+ // decodeMessage keeps wire-5 as raw uint32 — read it back as float32
283
+ const value = new Float32Array(new Uint32Array([raw]).buffer)[0];
284
+ if (!Number.isFinite(value)) continue;
285
+ const tokens = Math.round(value);
286
+ switch (name) {
287
+ case "input_tokens":
288
+ u.input = tokens;
289
+ break;
290
+ case "output_tokens":
291
+ u.output = tokens;
292
+ break;
293
+ case "cached_input_tokens":
294
+ case "cache_read_input_tokens":
295
+ u.cachedInput = (u.cachedInput ?? 0) + tokens;
296
+ break;
297
+ case "cache_creation_input_tokens":
298
+ u.cacheCreation = (u.cacheCreation ?? 0) + tokens;
299
+ break;
300
+ case "reasoning_tokens":
301
+ case "output_reasoning_tokens":
302
+ u.reasoning = tokens;
303
+ break;
304
+ }
305
+ }
306
+ return u.input === undefined && u.output === undefined ? undefined : u;
307
+ }
308
+
309
+ const ROLE_SOURCE: Record<ChatRole, number> = { user: 1, assistant: 2, tool: 4 };
310
+
311
+ function encodeToolCallProto(tc: { id: string; name: string; args: string }): Uint8Array {
312
+ return concatProto([fString(1, tc.id), fString(2, tc.name), fString(3, tc.args)]);
313
+ }
314
+
315
+ // Prompt message layout (from live capture):
316
+ // 2 source | 3 text | 4 token-est | 5 =1 | 6 tool_calls(repeated msg) |
317
+ // 7 tool_call_id | 9 is_error | 10 images
318
+ function encodeChatPrompt(msg: ChatMessage, system?: string): Uint8Array {
319
+ const content = msg.role === "user" && system ? `${system}\n\n${msg.content}` : msg.content;
320
+ const parts: Uint8Array[] = [
321
+ fVarint(2, ROLE_SOURCE[msg.role]),
322
+ fString(3, content),
323
+ fVarint(4, Math.max(1, Math.floor(content.length / 4))),
324
+ fVarint(5, 1),
325
+ ];
326
+ if (msg.toolCallId) parts.push(fString(7, msg.toolCallId));
327
+ for (const tc of msg.toolCalls ?? []) parts.push(fMessage(6, encodeToolCallProto(tc)));
328
+ return concatProto(parts);
329
+ }
330
+
331
+ // CompletionConfiguration (field 8):
332
+ // 1 num_completions | 2 max_tokens | 3 max_newlines | 5 temperature(float64)
333
+ // 6 first_temperature | 7 top_k | 8 top_p(float64) | 11 fim_eot_prob_threshold
334
+ function encodeCompletionConfiguration(opts: { maxTokens?: number; temperature?: number }): Uint8Array {
335
+ const f64 = (field: number, v: number): Uint8Array => {
336
+ const b = new Uint8Array(8);
337
+ new DataView(b.buffer).setFloat64(0, v, true);
338
+ return concatProto([new Uint8Array([(field << 3) | 1]), b]);
339
+ };
340
+ return concatProto([
341
+ fVarint(1, 1),
342
+ fVarint(2, opts.maxTokens ?? 64_000),
343
+ fVarint(3, 128_000),
344
+ f64(5, opts.temperature ?? 0.7),
345
+ f64(6, 0.95),
346
+ fVarint(7, 50),
347
+ f64(8, 1.0),
348
+ f64(11, 1.0),
349
+ ]);
350
+ }
351
+
352
+ function encodeChatRequest(req: ChatRequest, creds: DevinCredentials, jwt: string): Uint8Array {
353
+ const meta = buildMeta(credsSessionToken(creds), jwt);
354
+ // fold system into first user turn
355
+ let sysFolded = false;
356
+ const promptParts: Uint8Array[] = [];
357
+ for (const m of req.messages) {
358
+ const sys = !sysFolded && m.role === "user" ? req.system : undefined;
359
+ if (sys) sysFolded = true;
360
+ promptParts.push(fMessage(3, encodeChatPrompt(m, sys)));
361
+ }
362
+ if (req.system && !sysFolded) {
363
+ promptParts.push(fMessage(3, encodeChatPrompt({ role: "user", content: "" }, req.system)));
364
+ sysFolded = true;
365
+ }
366
+ const toolParts = (req.tools ?? []).map((t) =>
367
+ fMessage(10, concatProto([
368
+ fString(1, t.name),
369
+ fString(2, t.description),
370
+ fString(3, t.parameters), // already a JSON schema string
371
+ ])),
372
+ );
373
+ return concatProto([
374
+ fMessage(1, meta),
375
+ ...promptParts,
376
+ fVarint(7, 5), // request_type = CASCADE
377
+ fMessage(8, encodeCompletionConfiguration(req)),
378
+ ...toolParts,
379
+ fString(16, req.cascadeId ?? randomUUID()), // cascade_id — always present
380
+ fString(21, req.modelUid),
381
+ fString(22, crypto.randomUUID()), // prompt_id
382
+ ]);
383
+ }
384
+
385
+ // StopReason enum: 0 UNSPECIFIED→stop, 1 INCOMPLETE→length, 2 STOP_PATTERN→stop,
386
+ // 3 MAX_TOKENS→length, 10 FUNCTION_CALL→tool_calls, 11 CONTENT_FILTER→content_filter
387
+ function stopReason(v: number): string {
388
+ if (v === 10) return "tool_calls";
389
+ if (v === 11) return "content_filter";
390
+ if (v === 1 || v === 3) return "length";
391
+ return "stop";
392
+ }
393
+
394
+ export async function* streamChat(
395
+ req: ChatRequest,
396
+ creds: DevinCredentials,
397
+ ): AsyncGenerator<ChatDelta> {
398
+ const t0 = Date.now();
399
+ let { jwt, cascadeHost } = await creds.jwt();
400
+ let body = encodeChatRequest(req, creds, jwt);
401
+ log.info("chat.request", {
402
+ modelUid: req.modelUid, messages: req.messages.length,
403
+ tools: req.tools?.length ?? 0, host: cascadeHost, cascadeId: req.cascadeId,
404
+ });
405
+
406
+ let res = await post(cascadeHost, "GetChatMessage", body, jwt, true).catch(async (e) => {
407
+ if (e.status === 401) { // expired jwt — re-mint and retry once
408
+ log.warn("chat.401_remint", { modelUid: req.modelUid });
409
+ creds.invalidate();
410
+ ({ jwt, cascadeHost } = await creds.jwt());
411
+ body = encodeChatRequest(req, creds, jwt);
412
+ return post(cascadeHost, "GetChatMessage", body, jwt, true);
413
+ }
414
+ log.error("chat.post_fail", { modelUid: req.modelUid, err: scrubSecrets(String(e)) });
415
+ throw e;
416
+ });
417
+
418
+ let textLen = 0, toolCalls = 0;
419
+ for await (const { flags, payload } of readFrames(res.body!)) {
420
+ if (flags & 0x02) { // EOS trailer — JSON error object when present
421
+ const text = new TextDecoder().decode(payload);
422
+ if (text.trim() && text !== "{}") {
423
+ try {
424
+ const j = JSON.parse(text);
425
+ if (j.error) {
426
+ log.error("chat.eos_error", { modelUid: req.modelUid, err: scrubSecrets(text.slice(0, 300)) });
427
+ yield { type: "error", message: String(j.error.message ?? j.error) };
428
+ }
429
+ } catch {
430
+ log.error("chat.eos_error", { modelUid: req.modelUid, err: scrubSecrets(text.slice(0, 300)) });
431
+ yield { type: "error", message: text };
432
+ }
433
+ }
434
+ continue;
435
+ }
436
+ const msg = decodeMessage(payload);
437
+ // field 3 = delta_text string (not a submessage)
438
+ const delta = getString(msg, 3);
439
+ if (delta) { textLen += delta.length; yield { type: "text", text: delta }; }
440
+ const think = getString(msg, 9);
441
+ if (think) yield { type: "thinking", text: think };
442
+ for (const tc of getSubMessages(msg, 6)) {
443
+ toolCalls++;
444
+ const call = {
445
+ id: getString(tc, 1) ?? crypto.randomUUID(),
446
+ name: getString(tc, 2),
447
+ argsDelta: getString(tc, 3),
448
+ };
449
+ log.info("chat.tool_call", { modelUid: req.modelUid, id: call.id, name: call.name });
450
+ yield { type: "tool_call", ...call };
451
+ }
452
+ const stop = getScalarNum(msg, 5);
453
+ if (stop !== undefined) {
454
+ log.info("chat.finish", {
455
+ modelUid: req.modelUid, reason: stopReason(stop),
456
+ textLen, toolCalls, ms: Date.now() - t0,
457
+ });
458
+ yield { type: "finish", reason: stopReason(stop) };
459
+ }
460
+ const usageBytes = getBytes(msg, 28);
461
+ if (usageBytes) {
462
+ const usage = decodeUsage(usageBytes);
463
+ if (usage) {
464
+ log.debug("chat.usage", { modelUid: req.modelUid, ...usage });
465
+ yield { type: "usage", usage };
466
+ }
467
+ }
468
+ }
469
+ }