opencode-devin 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +107 -0
- package/dist/auth/exchange.d.ts +15 -0
- package/dist/auth/exchange.js +43 -0
- package/dist/auth/loopback.d.ts +15 -0
- package/dist/auth/loopback.js +57 -0
- package/dist/auth/pkce.d.ts +11 -0
- package/dist/auth/pkce.js +27 -0
- package/dist/auth/url.d.ts +12 -0
- package/dist/auth/url.js +17 -0
- package/dist/catalog.d.ts +11 -0
- package/dist/catalog.js +47 -0
- package/dist/constants.d.ts +19 -0
- package/dist/constants.js +19 -0
- package/dist/credentials.d.ts +23 -0
- package/dist/credentials.js +53 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +121 -0
- package/dist/protocol/auth.d.ts +20 -0
- package/dist/protocol/auth.js +97 -0
- package/dist/protocol/catalog.d.ts +49 -0
- package/dist/protocol/catalog.js +182 -0
- package/dist/protocol/chat.d.ts +92 -0
- package/dist/protocol/chat.js +465 -0
- package/dist/protocol/metadata.d.ts +17 -0
- package/dist/protocol/metadata.js +42 -0
- package/dist/protocol/model.d.ts +32 -0
- package/dist/protocol/model.js +412 -0
- package/dist/protocol/wire.d.ts +30 -0
- package/dist/protocol/wire.js +114 -0
- package/dist/provider.d.ts +18 -0
- package/dist/provider.js +20 -0
- package/package.json +53 -0
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `GetChatMessage` — chat streaming over Cognition's Connect-RPC endpoint.
|
|
3
|
+
*
|
|
4
|
+
* Field layouts come from mitm captures of the Windsurf language_server.
|
|
5
|
+
* Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
|
|
6
|
+
*/
|
|
7
|
+
import * as zlib from "node:zlib";
|
|
8
|
+
import { encodeMessage, encodeString, encodeVarintField, frameConnectStream, iterFields, } from "./wire.js";
|
|
9
|
+
import { buildMetadata } from "./metadata.js";
|
|
10
|
+
import { getCachedUserJwt } from "./auth.js";
|
|
11
|
+
import { DEFAULT_API_SERVER } from "../constants.js";
|
|
12
|
+
const STREAM_IDLE_MS = 120_000;
|
|
13
|
+
const STREAM_TTFB_MS = 60_000;
|
|
14
|
+
const MAX_TOOL_DESC_LEN = 6998;
|
|
15
|
+
export class CloudChatError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
traceId;
|
|
18
|
+
constructor(message, code, traceId) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "CloudChatError";
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.traceId = traceId;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// --- Request encoding ---
|
|
26
|
+
/** Cognition rejects source=3 for system; system content is inlined into user turns. */
|
|
27
|
+
const SOURCE_BY_ROLE = { user: 1, assistant: 2, system: 1, tool: 4 };
|
|
28
|
+
function encodeImageData(image) {
|
|
29
|
+
const parts = [encodeString(1, image.base64Data), encodeString(2, image.mimeType)];
|
|
30
|
+
if (image.caption)
|
|
31
|
+
parts.push(encodeString(3, image.caption));
|
|
32
|
+
return Buffer.concat(parts);
|
|
33
|
+
}
|
|
34
|
+
function encodeToolCall(call) {
|
|
35
|
+
return Buffer.concat([encodeString(1, call.id), encodeString(2, call.name), encodeString(3, call.arguments)]);
|
|
36
|
+
}
|
|
37
|
+
function encodePrompt(content, source, opts) {
|
|
38
|
+
const text = content
|
|
39
|
+
.filter((part) => part.type === "text")
|
|
40
|
+
.map((part) => part.text)
|
|
41
|
+
.join("\n");
|
|
42
|
+
const images = content.filter((part) => part.type === "image");
|
|
43
|
+
const parts = [
|
|
44
|
+
encodeVarintField(2, source),
|
|
45
|
+
encodeString(3, text),
|
|
46
|
+
encodeVarintField(4, Math.max(1, Math.floor(text.length / 4))),
|
|
47
|
+
encodeVarintField(5, 1),
|
|
48
|
+
];
|
|
49
|
+
if (opts?.toolCallId)
|
|
50
|
+
parts.push(encodeString(7, opts.toolCallId));
|
|
51
|
+
if (opts?.toolCalls)
|
|
52
|
+
for (const call of opts.toolCalls)
|
|
53
|
+
parts.push(encodeMessage(6, encodeToolCall(call)));
|
|
54
|
+
for (const image of images)
|
|
55
|
+
parts.push(encodeMessage(10, encodeImageData(image)));
|
|
56
|
+
return Buffer.concat(parts);
|
|
57
|
+
}
|
|
58
|
+
function textOf(content) {
|
|
59
|
+
if (typeof content === "string")
|
|
60
|
+
return content;
|
|
61
|
+
return content
|
|
62
|
+
.filter((part) => part.type === "text")
|
|
63
|
+
.map((part) => part.text)
|
|
64
|
+
.join("\n");
|
|
65
|
+
}
|
|
66
|
+
/** Cascade has no system role: fold system content into the next user turn. */
|
|
67
|
+
function collapseSystemIntoUser(messages) {
|
|
68
|
+
if (!messages.some((message) => message.role === "system"))
|
|
69
|
+
return messages;
|
|
70
|
+
const out = [];
|
|
71
|
+
let pendingSystem = [];
|
|
72
|
+
for (const message of messages) {
|
|
73
|
+
if (message.role === "system") {
|
|
74
|
+
const text = textOf(message.content);
|
|
75
|
+
if (text)
|
|
76
|
+
pendingSystem.push(text);
|
|
77
|
+
}
|
|
78
|
+
else if (message.role === "user" && pendingSystem.length > 0) {
|
|
79
|
+
const content = normalizeContent(message.content);
|
|
80
|
+
const images = content.filter((part) => part.type === "image");
|
|
81
|
+
const wrapped = `<system>\n${pendingSystem.join("\n\n")}\n</system>\n${textOf(content)}`;
|
|
82
|
+
out.push({ role: "user", content: [{ type: "text", text: wrapped }, ...images] });
|
|
83
|
+
pendingSystem = [];
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
out.push(message);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (pendingSystem.length > 0) {
|
|
90
|
+
out.push({ role: "user", content: [{ type: "text", text: `<system>\n${pendingSystem.join("\n\n")}\n</system>` }] });
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
function normalizeContent(content) {
|
|
95
|
+
if (typeof content === "string")
|
|
96
|
+
return [{ type: "text", text: content }];
|
|
97
|
+
const out = [];
|
|
98
|
+
for (const part of content) {
|
|
99
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
100
|
+
out.push({ type: "text", text: part.text });
|
|
101
|
+
}
|
|
102
|
+
else if (part.type === "image" && typeof part.base64Data === "string") {
|
|
103
|
+
out.push({ type: "image", mimeType: part.mimeType ?? "image/png", base64Data: part.base64Data, caption: part.caption });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
function encodeToolDef(tool) {
|
|
109
|
+
const raw = tool.description ?? "";
|
|
110
|
+
const description = raw.length > MAX_TOOL_DESC_LEN ? `${raw.slice(0, MAX_TOOL_DESC_LEN - 24)}\n…(truncated for cloud)` : raw;
|
|
111
|
+
return Buffer.concat([
|
|
112
|
+
encodeString(1, tool.name),
|
|
113
|
+
encodeString(2, description),
|
|
114
|
+
encodeString(3, JSON.stringify(tool.parameters ?? {})),
|
|
115
|
+
]);
|
|
116
|
+
}
|
|
117
|
+
function encodeCompletionConfiguration(opts) {
|
|
118
|
+
const float64 = (fieldNum, value) => {
|
|
119
|
+
const buf = Buffer.alloc(8);
|
|
120
|
+
buf.writeDoubleLE(value, 0);
|
|
121
|
+
return Buffer.concat([Buffer.from([(fieldNum << 3) | 1]), buf]);
|
|
122
|
+
};
|
|
123
|
+
return Buffer.concat([
|
|
124
|
+
encodeVarintField(1, 1),
|
|
125
|
+
encodeVarintField(2, opts.maxInputTokens ?? 64_000),
|
|
126
|
+
encodeVarintField(3, opts.maxOutputTokens ?? 128_000),
|
|
127
|
+
float64(5, opts.temperature ?? 0.7),
|
|
128
|
+
float64(6, opts.topP ?? 0.95),
|
|
129
|
+
encodeVarintField(7, opts.topK ?? 50),
|
|
130
|
+
float64(8, 1.0),
|
|
131
|
+
float64(11, 1.0),
|
|
132
|
+
]);
|
|
133
|
+
}
|
|
134
|
+
const sessionCache = new Map();
|
|
135
|
+
function getOrAllocateSessionIds(apiKey, host, cascadeIdOverride) {
|
|
136
|
+
const key = `${host}${apiKey}`;
|
|
137
|
+
let ids = sessionCache.get(key);
|
|
138
|
+
if (!ids) {
|
|
139
|
+
ids = { sessionId: crypto.randomUUID(), cascadeId: cascadeIdOverride ?? crypto.randomUUID() };
|
|
140
|
+
sessionCache.set(key, ids);
|
|
141
|
+
}
|
|
142
|
+
else if (cascadeIdOverride && ids.cascadeId !== cascadeIdOverride) {
|
|
143
|
+
ids = { sessionId: ids.sessionId, cascadeId: cascadeIdOverride };
|
|
144
|
+
sessionCache.set(key, ids);
|
|
145
|
+
}
|
|
146
|
+
return ids;
|
|
147
|
+
}
|
|
148
|
+
function buildGetChatMessageRequest(args) {
|
|
149
|
+
const metadata = buildMetadata({
|
|
150
|
+
apiKey: args.apiKey,
|
|
151
|
+
userJwt: args.userJwt,
|
|
152
|
+
sessionId: args.sessionId,
|
|
153
|
+
requestId: args.requestId,
|
|
154
|
+
triggerId: args.triggerId,
|
|
155
|
+
});
|
|
156
|
+
const collapsed = collapseSystemIntoUser(args.messages);
|
|
157
|
+
const promptParts = collapsed.map((message) => encodeMessage(3, encodePrompt(normalizeContent(message.content), SOURCE_BY_ROLE[message.role] ?? 1, {
|
|
158
|
+
toolCallId: message.tool_call_id,
|
|
159
|
+
toolCalls: message.tool_calls,
|
|
160
|
+
})));
|
|
161
|
+
// Field layout from mitm capture of the Windsurf language_server:
|
|
162
|
+
// #1 metadata (message)
|
|
163
|
+
// #3 chat_message_prompts (repeated — one element per history turn)
|
|
164
|
+
// #7 request_type (varint enum, 5 = CASCADE)
|
|
165
|
+
// #8 completion_configuration (message)
|
|
166
|
+
// #10 tools (repeated ChatToolDefinition)
|
|
167
|
+
// #16 cascade_id (string)
|
|
168
|
+
// #21 chat_model_uid (string)
|
|
169
|
+
// #22 prompt_id (string)
|
|
170
|
+
const toolParts = (args.tools ?? []).map((tool) => encodeMessage(10, encodeToolDef(tool)));
|
|
171
|
+
return Buffer.concat([
|
|
172
|
+
encodeMessage(1, metadata),
|
|
173
|
+
...promptParts,
|
|
174
|
+
encodeVarintField(7, 5),
|
|
175
|
+
encodeMessage(8, encodeCompletionConfiguration(args.completionOpts ?? {})),
|
|
176
|
+
...toolParts,
|
|
177
|
+
encodeString(16, args.cascadeId),
|
|
178
|
+
encodeString(21, args.modelUid),
|
|
179
|
+
encodeString(22, args.promptId),
|
|
180
|
+
]);
|
|
181
|
+
}
|
|
182
|
+
function* decodeChatFrame(buf) {
|
|
183
|
+
for (const field of iterFields(buf)) {
|
|
184
|
+
if (field.num === 5 && field.wire === 0) {
|
|
185
|
+
// Finish reason (varint) — StopReason enum:
|
|
186
|
+
// 0 UNSPECIFIED → stop, 1 INCOMPLETE → length, 2 STOP_PATTERN → stop,
|
|
187
|
+
// 3 MAX_TOKENS → length, 10 FUNCTION_CALL → tool_calls, 11 CONTENT_FILTER → content_filter
|
|
188
|
+
const value = Number(field.value);
|
|
189
|
+
let reason = "stop";
|
|
190
|
+
if (value === 10)
|
|
191
|
+
reason = "tool_calls";
|
|
192
|
+
else if (value === 11)
|
|
193
|
+
reason = "content_filter";
|
|
194
|
+
else if (value === 1 || value === 3)
|
|
195
|
+
reason = "length";
|
|
196
|
+
yield { kind: "finish", reason };
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (field.wire !== 2 || !Buffer.isBuffer(field.value))
|
|
200
|
+
continue;
|
|
201
|
+
if (field.num === 3) {
|
|
202
|
+
// delta_text — visible text content
|
|
203
|
+
const text = field.value.toString("utf8");
|
|
204
|
+
if (text)
|
|
205
|
+
yield { kind: "text", text };
|
|
206
|
+
}
|
|
207
|
+
else if (field.num === 6) {
|
|
208
|
+
// ToolCallDelta { #1 id, #2 name, #3 arguments_delta }
|
|
209
|
+
let id;
|
|
210
|
+
let name;
|
|
211
|
+
let argsDelta;
|
|
212
|
+
for (const part of iterFields(field.value)) {
|
|
213
|
+
if (part.wire !== 2 || !Buffer.isBuffer(part.value))
|
|
214
|
+
continue;
|
|
215
|
+
const text = part.value.toString("utf8");
|
|
216
|
+
if (part.num === 1)
|
|
217
|
+
id = text;
|
|
218
|
+
else if (part.num === 2)
|
|
219
|
+
name = text;
|
|
220
|
+
else if (part.num === 3)
|
|
221
|
+
argsDelta = text;
|
|
222
|
+
}
|
|
223
|
+
if (id !== undefined && name !== undefined)
|
|
224
|
+
yield { kind: "tool_call_start", id, name };
|
|
225
|
+
if (argsDelta !== undefined)
|
|
226
|
+
yield { kind: "tool_call_args", argsDelta, ...(id !== undefined ? { id } : {}) };
|
|
227
|
+
}
|
|
228
|
+
else if (field.num === 9) {
|
|
229
|
+
// Internal thinking / chain-of-thought
|
|
230
|
+
const text = field.value.toString("utf8");
|
|
231
|
+
if (text)
|
|
232
|
+
yield { kind: "reasoning", text };
|
|
233
|
+
}
|
|
234
|
+
else if (field.num === 28) {
|
|
235
|
+
const usage = decodeUsageBlock(field.value);
|
|
236
|
+
if (usage)
|
|
237
|
+
yield usage;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function decodeUsageBlock(buf) {
|
|
242
|
+
let promptTokens;
|
|
243
|
+
let completionTokens;
|
|
244
|
+
let cachedInputTokens;
|
|
245
|
+
let cacheCreationInputTokens;
|
|
246
|
+
let reasoningTokens;
|
|
247
|
+
for (const field of iterFields(buf)) {
|
|
248
|
+
if (field.num !== 2 || field.wire !== 2 || !Buffer.isBuffer(field.value))
|
|
249
|
+
continue;
|
|
250
|
+
let metric;
|
|
251
|
+
let value;
|
|
252
|
+
for (const entry of iterFields(field.value)) {
|
|
253
|
+
if (entry.num === 5 && entry.wire === 2 && Buffer.isBuffer(entry.value)) {
|
|
254
|
+
metric = entry.value.toString("utf8");
|
|
255
|
+
}
|
|
256
|
+
else if (entry.num === 4 && entry.wire === 2 && Buffer.isBuffer(entry.value)) {
|
|
257
|
+
for (const inner of iterFields(entry.value)) {
|
|
258
|
+
if (inner.num === 2 && inner.wire === 5 && Buffer.isBuffer(inner.value)) {
|
|
259
|
+
value = inner.value.readFloatLE(0);
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (metric && value !== undefined && Number.isFinite(value)) {
|
|
266
|
+
const tokens = Math.round(value);
|
|
267
|
+
if (metric === "input_tokens")
|
|
268
|
+
promptTokens = tokens;
|
|
269
|
+
else if (metric === "output_tokens")
|
|
270
|
+
completionTokens = tokens;
|
|
271
|
+
else if (metric === "cached_input_tokens" || metric === "cache_read_input_tokens")
|
|
272
|
+
cachedInputTokens = (cachedInputTokens ?? 0) + tokens;
|
|
273
|
+
else if (metric === "cache_creation_input_tokens")
|
|
274
|
+
cacheCreationInputTokens = (cacheCreationInputTokens ?? 0) + tokens;
|
|
275
|
+
else if (metric === "reasoning_tokens" || metric === "output_reasoning_tokens")
|
|
276
|
+
reasoningTokens = tokens;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (promptTokens === undefined && completionTokens === undefined)
|
|
280
|
+
return null;
|
|
281
|
+
const total = (promptTokens ?? 0) + (completionTokens ?? 0);
|
|
282
|
+
return {
|
|
283
|
+
kind: "usage",
|
|
284
|
+
promptTokens,
|
|
285
|
+
completionTokens,
|
|
286
|
+
totalTokens: total > 0 ? total : undefined,
|
|
287
|
+
cachedInputTokens,
|
|
288
|
+
cacheCreationInputTokens,
|
|
289
|
+
reasoningTokens,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
const TRACE_ID_RE = /\(trace ID: ([0-9a-f]+)\)/i;
|
|
293
|
+
/** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
|
|
294
|
+
export async function* streamChatEvents(request) {
|
|
295
|
+
const host = (request.apiServerUrl ?? DEFAULT_API_SERVER).replace(/\/$/, "");
|
|
296
|
+
const userJwt = await getCachedUserJwt(request.apiKey, host, request.signal);
|
|
297
|
+
const sessionIds = getOrAllocateSessionIds(request.apiKey, host, request.cascadeId);
|
|
298
|
+
const proto = buildGetChatMessageRequest({
|
|
299
|
+
apiKey: request.apiKey,
|
|
300
|
+
userJwt,
|
|
301
|
+
modelUid: request.modelUid,
|
|
302
|
+
messages: request.messages,
|
|
303
|
+
tools: request.tools,
|
|
304
|
+
cascadeId: sessionIds.cascadeId,
|
|
305
|
+
promptId: crypto.randomUUID(),
|
|
306
|
+
sessionId: sessionIds.sessionId,
|
|
307
|
+
requestId: BigInt(Date.now()),
|
|
308
|
+
triggerId: crypto.randomUUID(),
|
|
309
|
+
completionOpts: request.completionOpts,
|
|
310
|
+
});
|
|
311
|
+
const body = frameConnectStream(proto, true);
|
|
312
|
+
const ttfbTimeout = AbortSignal.timeout(STREAM_TTFB_MS);
|
|
313
|
+
const response = await fetch(`${host}/exa.api_server_pb.ApiServerService/GetChatMessage`, {
|
|
314
|
+
method: "POST",
|
|
315
|
+
headers: {
|
|
316
|
+
"Content-Type": "application/connect+proto",
|
|
317
|
+
"Connect-Protocol-Version": "1",
|
|
318
|
+
"Connect-Content-Encoding": "gzip",
|
|
319
|
+
"Connect-Accept-Encoding": "gzip",
|
|
320
|
+
},
|
|
321
|
+
body: new Uint8Array(body),
|
|
322
|
+
signal: request.signal ? AbortSignal.any([request.signal, ttfbTimeout]) : ttfbTimeout,
|
|
323
|
+
});
|
|
324
|
+
if (!response.ok) {
|
|
325
|
+
const text = await response.text();
|
|
326
|
+
throw new CloudChatError(`GetChatMessage HTTP ${response.status}: ${text.slice(0, 300)}`);
|
|
327
|
+
}
|
|
328
|
+
if (!response.body)
|
|
329
|
+
throw new CloudChatError("GetChatMessage response had no body stream");
|
|
330
|
+
const reader = response.body.getReader();
|
|
331
|
+
const chunks = [];
|
|
332
|
+
let queuedBytes = 0;
|
|
333
|
+
let trailerError = null;
|
|
334
|
+
let sawEos = false;
|
|
335
|
+
let idleTimer = null;
|
|
336
|
+
const cancelBody = (reason) => {
|
|
337
|
+
try {
|
|
338
|
+
void response.body?.cancel(reason);
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
// already cancelled
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
const peek = (n) => {
|
|
345
|
+
if (queuedBytes < n)
|
|
346
|
+
return null;
|
|
347
|
+
if (chunks.length === 1 && chunks[0].length >= n)
|
|
348
|
+
return chunks[0].slice(0, n);
|
|
349
|
+
const parts = [];
|
|
350
|
+
let remaining = n;
|
|
351
|
+
for (const chunk of chunks) {
|
|
352
|
+
if (remaining <= 0)
|
|
353
|
+
break;
|
|
354
|
+
if (chunk.length <= remaining) {
|
|
355
|
+
parts.push(chunk);
|
|
356
|
+
remaining -= chunk.length;
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
parts.push(chunk.slice(0, remaining));
|
|
360
|
+
remaining = 0;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return Buffer.concat(parts, n);
|
|
364
|
+
};
|
|
365
|
+
const drop = (n) => {
|
|
366
|
+
queuedBytes -= n;
|
|
367
|
+
let remaining = n;
|
|
368
|
+
while (remaining > 0 && chunks.length > 0) {
|
|
369
|
+
const head = chunks[0];
|
|
370
|
+
if (head.length <= remaining) {
|
|
371
|
+
chunks.shift();
|
|
372
|
+
remaining -= head.length;
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
chunks[0] = head.slice(remaining);
|
|
376
|
+
remaining = 0;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
try {
|
|
381
|
+
if (request.signal?.aborted)
|
|
382
|
+
throw request.signal.reason;
|
|
383
|
+
request.signal?.addEventListener("abort", () => cancelBody(request.signal?.reason), { once: true });
|
|
384
|
+
while (true) {
|
|
385
|
+
if (idleTimer)
|
|
386
|
+
clearTimeout(idleTimer);
|
|
387
|
+
idleTimer = setTimeout(() => cancelBody(new Error(`idle timeout (${STREAM_IDLE_MS}ms)`)), STREAM_IDLE_MS);
|
|
388
|
+
const { value, done } = await reader.read();
|
|
389
|
+
if (idleTimer) {
|
|
390
|
+
clearTimeout(idleTimer);
|
|
391
|
+
idleTimer = null;
|
|
392
|
+
}
|
|
393
|
+
if (done)
|
|
394
|
+
break;
|
|
395
|
+
if (value) {
|
|
396
|
+
chunks.push(Buffer.from(value));
|
|
397
|
+
queuedBytes += value.length;
|
|
398
|
+
}
|
|
399
|
+
while (queuedBytes >= 5) {
|
|
400
|
+
const header = peek(5);
|
|
401
|
+
if (!header)
|
|
402
|
+
break;
|
|
403
|
+
const flags = header[0];
|
|
404
|
+
const length = header.readUInt32BE(1);
|
|
405
|
+
if (queuedBytes < 5 + length)
|
|
406
|
+
break;
|
|
407
|
+
drop(5);
|
|
408
|
+
const raw = peek(length) ?? Buffer.alloc(0);
|
|
409
|
+
drop(length);
|
|
410
|
+
let payload = raw;
|
|
411
|
+
if (flags & 0x01) {
|
|
412
|
+
try {
|
|
413
|
+
payload = zlib.gunzipSync(raw);
|
|
414
|
+
}
|
|
415
|
+
catch (cause) {
|
|
416
|
+
throw new CloudChatError(`Connect frame gunzip failed: ${cause.message}`);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
if ((flags & 0x02) !== 0) {
|
|
420
|
+
// End-of-stream trailer: JSON {error} on failure, empty on success.
|
|
421
|
+
sawEos = true;
|
|
422
|
+
const text = payload.toString("utf8");
|
|
423
|
+
if (text && text.includes('"error"')) {
|
|
424
|
+
let code;
|
|
425
|
+
let message = text;
|
|
426
|
+
try {
|
|
427
|
+
const parsed = JSON.parse(text);
|
|
428
|
+
code = parsed.error?.code;
|
|
429
|
+
if (parsed.error?.message)
|
|
430
|
+
message = parsed.error.message;
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
// non-JSON trailer — keep the raw text
|
|
434
|
+
}
|
|
435
|
+
const traceId = message.match(TRACE_ID_RE)?.[1];
|
|
436
|
+
trailerError = { code, message, traceId };
|
|
437
|
+
}
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
yield* decodeChatFrame(payload);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
finally {
|
|
445
|
+
if (idleTimer)
|
|
446
|
+
clearTimeout(idleTimer);
|
|
447
|
+
try {
|
|
448
|
+
reader.releaseLock();
|
|
449
|
+
}
|
|
450
|
+
catch {
|
|
451
|
+
// lock already released
|
|
452
|
+
}
|
|
453
|
+
cancelBody();
|
|
454
|
+
}
|
|
455
|
+
if (trailerError) {
|
|
456
|
+
const isOpaque = trailerError.code === "permission_denied" && /an internal error occurred/i.test(trailerError.message);
|
|
457
|
+
if (isOpaque) {
|
|
458
|
+
throw new CloudChatError(`Cognition denied model access for "${request.modelUid}". Check your account tier. (trace: ${trailerError.traceId ?? "n/a"})`, trailerError.code, trailerError.traceId);
|
|
459
|
+
}
|
|
460
|
+
throw new CloudChatError(trailerError.message, trailerError.code, trailerError.traceId);
|
|
461
|
+
}
|
|
462
|
+
if (!sawEos) {
|
|
463
|
+
throw new CloudChatError("Cloud stream ended without EOS trailer. Connection likely dropped.", "truncated_stream");
|
|
464
|
+
}
|
|
465
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Metadata` proto builder sent with every Codeium/Cognition RPC.
|
|
3
|
+
*
|
|
4
|
+
* Field layout reverse-engineered from the Windsurf language_server; originally
|
|
5
|
+
* ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
|
|
6
|
+
*/
|
|
7
|
+
export interface MetadataInput {
|
|
8
|
+
apiKey: string;
|
|
9
|
+
sessionId: string;
|
|
10
|
+
requestId: bigint;
|
|
11
|
+
triggerId: string;
|
|
12
|
+
/** Short-lived JWT from GetUserJwt, required for catalog and chat RPCs. */
|
|
13
|
+
userJwt?: string;
|
|
14
|
+
osName?: string;
|
|
15
|
+
version?: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function buildMetadata(input: MetadataInput): Buffer;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Metadata` proto builder sent with every Codeium/Cognition RPC.
|
|
3
|
+
*
|
|
4
|
+
* Field layout reverse-engineered from the Windsurf language_server; originally
|
|
5
|
+
* ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
|
|
6
|
+
*/
|
|
7
|
+
import { encodeMessage, encodeString, encodeTimestampBody, encodeVarintField } from "./wire.js";
|
|
8
|
+
const VERSION_STRING = "2.0.0";
|
|
9
|
+
function osName() {
|
|
10
|
+
switch (process.platform) {
|
|
11
|
+
case "darwin":
|
|
12
|
+
return "darwin";
|
|
13
|
+
case "linux":
|
|
14
|
+
return "linux";
|
|
15
|
+
case "win32":
|
|
16
|
+
return "windows";
|
|
17
|
+
default:
|
|
18
|
+
return process.platform;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function buildMetadata(input) {
|
|
22
|
+
const version = input.version ?? VERSION_STRING;
|
|
23
|
+
const os = input.osName ?? osName();
|
|
24
|
+
const parts = [
|
|
25
|
+
encodeString(1, "windsurf"),
|
|
26
|
+
encodeString(2, version),
|
|
27
|
+
encodeString(3, input.apiKey),
|
|
28
|
+
encodeString(4, "en"),
|
|
29
|
+
encodeString(5, os),
|
|
30
|
+
encodeString(7, version),
|
|
31
|
+
encodeVarintField(9, input.requestId),
|
|
32
|
+
encodeString(10, input.sessionId),
|
|
33
|
+
encodeString(12, "windsurf"),
|
|
34
|
+
encodeMessage(16, encodeTimestampBody()),
|
|
35
|
+
encodeString(25, input.triggerId),
|
|
36
|
+
encodeString(26, "Unset"),
|
|
37
|
+
encodeString(28, "windsurf"),
|
|
38
|
+
];
|
|
39
|
+
if (input.userJwt)
|
|
40
|
+
parts.push(encodeString(21, input.userJwt));
|
|
41
|
+
return Buffer.concat(parts);
|
|
42
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI SDK `LanguageModelV3` facade over the Cascade chat stream.
|
|
3
|
+
*
|
|
4
|
+
* Models are discovered dynamically from the per-account catalog
|
|
5
|
+
* (GetCascadeModelConfigs). Auth: the long-lived session token
|
|
6
|
+
* (`devin-session-token$<JWT>`) as `apiKey`; a short-lived `user_jwt` is
|
|
7
|
+
* minted automatically per session.
|
|
8
|
+
*
|
|
9
|
+
* Originally ported from ai-sdk-devin / pi-devin-auth (MIT).
|
|
10
|
+
*/
|
|
11
|
+
import type { LanguageModelV3 } from "@ai-sdk/provider";
|
|
12
|
+
import { type ModelCatalogEntry } from "./catalog.ts";
|
|
13
|
+
/** Valid reasoning effort levels (encoded as UID suffixes in the catalog). */
|
|
14
|
+
declare const EFFORT_LEVELS: readonly ["none", "low", "medium", "high", "xhigh", "max"];
|
|
15
|
+
export type EffortLevel = (typeof EFFORT_LEVELS)[number];
|
|
16
|
+
/** Calculate the dollar cost of a request from token usage and model pricing. */
|
|
17
|
+
export declare function calculateCost(usage: {
|
|
18
|
+
inputTokens?: number;
|
|
19
|
+
cachedInputTokens?: number;
|
|
20
|
+
outputTokens?: number;
|
|
21
|
+
}, pricing?: ModelCatalogEntry["pricing"]): number | undefined;
|
|
22
|
+
export interface DevinProviderOptions {
|
|
23
|
+
apiKey: string;
|
|
24
|
+
baseURL?: string;
|
|
25
|
+
}
|
|
26
|
+
export interface DevinProvider {
|
|
27
|
+
languageModel(modelId: string): LanguageModelV3;
|
|
28
|
+
/** Fetch the live model catalog for this account. Returns all enabled models. */
|
|
29
|
+
models(): Promise<ModelCatalogEntry[]>;
|
|
30
|
+
}
|
|
31
|
+
export declare function createDevin(options: DevinProviderOptions): DevinProvider;
|
|
32
|
+
export {};
|