opencode-devin 0.2.1 → 0.2.3
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 +28 -0
- package/dist/catalog.d.ts +11 -0
- package/dist/catalog.js +72 -8
- package/dist/index.js +2 -2
- package/dist/protocol/model.d.ts +15 -7
- package/dist/protocol/model.js +166 -65
- package/package.json +5 -4
- package/dist/auth/browser.d.ts +0 -7
- package/dist/auth/browser.js +0 -18
- package/dist/auth/exchange.d.ts +0 -15
- package/dist/auth/exchange.js +0 -43
- package/dist/auth/login.d.ts +0 -15
- package/dist/auth/login.js +0 -51
- package/dist/auth/loopback.d.ts +0 -15
- package/dist/auth/loopback.js +0 -93
- package/dist/auth/pkce.d.ts +0 -11
- package/dist/auth/pkce.js +0 -27
- package/dist/auth/url.d.ts +0 -12
- package/dist/auth/url.js +0 -17
- package/dist/protocol/auth.d.ts +0 -26
- package/dist/protocol/auth.js +0 -119
- package/dist/protocol/catalog.d.ts +0 -62
- package/dist/protocol/catalog.js +0 -205
- package/dist/protocol/chat.d.ts +0 -92
- package/dist/protocol/chat.js +0 -496
- package/dist/protocol/effort.d.ts +0 -20
- package/dist/protocol/effort.js +0 -31
- package/dist/protocol/metadata.d.ts +0 -17
- package/dist/protocol/metadata.js +0 -42
- package/dist/protocol/wire.d.ts +0 -30
- package/dist/protocol/wire.js +0 -114
package/dist/protocol/chat.js
DELETED
|
@@ -1,496 +0,0 @@
|
|
|
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 { clearCachedUserJwt, credentialKey, 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
|
-
/**
|
|
135
|
-
* Per-credential Cascade session ids.
|
|
136
|
-
*
|
|
137
|
-
* Keys embed the session token, so the map is capped and evicted in insertion
|
|
138
|
-
* order: a user who connects and switches credentials repeatedly would
|
|
139
|
-
* otherwise accumulate tokens in memory for the life of the process. In
|
|
140
|
-
* practice only one or two credentials are ever live at a time.
|
|
141
|
-
*/
|
|
142
|
-
const SESSION_CACHE_LIMIT = 4;
|
|
143
|
-
const sessionCache = new Map();
|
|
144
|
-
function getOrAllocateSessionIds(apiKey, host, cascadeIdOverride) {
|
|
145
|
-
const key = credentialKey(host, apiKey);
|
|
146
|
-
let ids = sessionCache.get(key);
|
|
147
|
-
if (!ids) {
|
|
148
|
-
ids = { sessionId: crypto.randomUUID(), cascadeId: cascadeIdOverride ?? crypto.randomUUID() };
|
|
149
|
-
if (sessionCache.size >= SESSION_CACHE_LIMIT) {
|
|
150
|
-
const oldest = sessionCache.keys().next();
|
|
151
|
-
if (!oldest.done)
|
|
152
|
-
sessionCache.delete(oldest.value);
|
|
153
|
-
}
|
|
154
|
-
sessionCache.set(key, ids);
|
|
155
|
-
}
|
|
156
|
-
else if (cascadeIdOverride && ids.cascadeId !== cascadeIdOverride) {
|
|
157
|
-
ids = { sessionId: ids.sessionId, cascadeId: cascadeIdOverride };
|
|
158
|
-
sessionCache.set(key, ids);
|
|
159
|
-
}
|
|
160
|
-
return ids;
|
|
161
|
-
}
|
|
162
|
-
function buildGetChatMessageRequest(args) {
|
|
163
|
-
const metadata = buildMetadata({
|
|
164
|
-
apiKey: args.apiKey,
|
|
165
|
-
userJwt: args.userJwt,
|
|
166
|
-
sessionId: args.sessionId,
|
|
167
|
-
requestId: args.requestId,
|
|
168
|
-
triggerId: args.triggerId,
|
|
169
|
-
});
|
|
170
|
-
const collapsed = collapseSystemIntoUser(args.messages);
|
|
171
|
-
const promptParts = collapsed.map((message) => encodeMessage(3, encodePrompt(normalizeContent(message.content), SOURCE_BY_ROLE[message.role] ?? 1, {
|
|
172
|
-
toolCallId: message.tool_call_id,
|
|
173
|
-
toolCalls: message.tool_calls,
|
|
174
|
-
})));
|
|
175
|
-
// Field layout from mitm capture of the Windsurf language_server:
|
|
176
|
-
// #1 metadata (message)
|
|
177
|
-
// #3 chat_message_prompts (repeated — one element per history turn)
|
|
178
|
-
// #7 request_type (varint enum, 5 = CASCADE)
|
|
179
|
-
// #8 completion_configuration (message)
|
|
180
|
-
// #10 tools (repeated ChatToolDefinition)
|
|
181
|
-
// #16 cascade_id (string)
|
|
182
|
-
// #21 chat_model_uid (string)
|
|
183
|
-
// #22 prompt_id (string)
|
|
184
|
-
const toolParts = (args.tools ?? []).map((tool) => encodeMessage(10, encodeToolDef(tool)));
|
|
185
|
-
return Buffer.concat([
|
|
186
|
-
encodeMessage(1, metadata),
|
|
187
|
-
...promptParts,
|
|
188
|
-
encodeVarintField(7, 5),
|
|
189
|
-
encodeMessage(8, encodeCompletionConfiguration(args.completionOpts ?? {})),
|
|
190
|
-
...toolParts,
|
|
191
|
-
encodeString(16, args.cascadeId),
|
|
192
|
-
encodeString(21, args.modelUid),
|
|
193
|
-
encodeString(22, args.promptId),
|
|
194
|
-
]);
|
|
195
|
-
}
|
|
196
|
-
function* decodeChatFrame(buf) {
|
|
197
|
-
for (const field of iterFields(buf)) {
|
|
198
|
-
if (field.num === 5 && field.wire === 0) {
|
|
199
|
-
// Finish reason (varint) — StopReason enum:
|
|
200
|
-
// 0 UNSPECIFIED → stop, 1 INCOMPLETE → length, 2 STOP_PATTERN → stop,
|
|
201
|
-
// 3 MAX_TOKENS → length, 10 FUNCTION_CALL → tool_calls, 11 CONTENT_FILTER → content_filter
|
|
202
|
-
const value = Number(field.value);
|
|
203
|
-
let reason = "stop";
|
|
204
|
-
if (value === 10)
|
|
205
|
-
reason = "tool_calls";
|
|
206
|
-
else if (value === 11)
|
|
207
|
-
reason = "content_filter";
|
|
208
|
-
else if (value === 1 || value === 3)
|
|
209
|
-
reason = "length";
|
|
210
|
-
yield { kind: "finish", reason };
|
|
211
|
-
continue;
|
|
212
|
-
}
|
|
213
|
-
if (field.wire !== 2 || !Buffer.isBuffer(field.value))
|
|
214
|
-
continue;
|
|
215
|
-
if (field.num === 3) {
|
|
216
|
-
// delta_text — visible text content
|
|
217
|
-
const text = field.value.toString("utf8");
|
|
218
|
-
if (text)
|
|
219
|
-
yield { kind: "text", text };
|
|
220
|
-
}
|
|
221
|
-
else if (field.num === 6) {
|
|
222
|
-
// ToolCallDelta { #1 id, #2 name, #3 arguments_delta }
|
|
223
|
-
let id;
|
|
224
|
-
let name;
|
|
225
|
-
let argsDelta;
|
|
226
|
-
for (const part of iterFields(field.value)) {
|
|
227
|
-
if (part.wire !== 2 || !Buffer.isBuffer(part.value))
|
|
228
|
-
continue;
|
|
229
|
-
const text = part.value.toString("utf8");
|
|
230
|
-
if (part.num === 1)
|
|
231
|
-
id = text;
|
|
232
|
-
else if (part.num === 2)
|
|
233
|
-
name = text;
|
|
234
|
-
else if (part.num === 3)
|
|
235
|
-
argsDelta = text;
|
|
236
|
-
}
|
|
237
|
-
if (id !== undefined && name !== undefined)
|
|
238
|
-
yield { kind: "tool_call_start", id, name };
|
|
239
|
-
if (argsDelta !== undefined)
|
|
240
|
-
yield { kind: "tool_call_args", argsDelta, ...(id !== undefined ? { id } : {}) };
|
|
241
|
-
}
|
|
242
|
-
else if (field.num === 9) {
|
|
243
|
-
// Internal thinking / chain-of-thought
|
|
244
|
-
const text = field.value.toString("utf8");
|
|
245
|
-
if (text)
|
|
246
|
-
yield { kind: "reasoning", text };
|
|
247
|
-
}
|
|
248
|
-
else if (field.num === 28) {
|
|
249
|
-
const usage = decodeUsageBlock(field.value);
|
|
250
|
-
if (usage)
|
|
251
|
-
yield usage;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
function decodeUsageBlock(buf) {
|
|
256
|
-
let promptTokens;
|
|
257
|
-
let completionTokens;
|
|
258
|
-
let cachedInputTokens;
|
|
259
|
-
let cacheCreationInputTokens;
|
|
260
|
-
let reasoningTokens;
|
|
261
|
-
for (const field of iterFields(buf)) {
|
|
262
|
-
if (field.num !== 2 || field.wire !== 2 || !Buffer.isBuffer(field.value))
|
|
263
|
-
continue;
|
|
264
|
-
let metric;
|
|
265
|
-
let value;
|
|
266
|
-
for (const entry of iterFields(field.value)) {
|
|
267
|
-
if (entry.num === 5 && entry.wire === 2 && Buffer.isBuffer(entry.value)) {
|
|
268
|
-
metric = entry.value.toString("utf8");
|
|
269
|
-
}
|
|
270
|
-
else if (entry.num === 4 && entry.wire === 2 && Buffer.isBuffer(entry.value)) {
|
|
271
|
-
for (const inner of iterFields(entry.value)) {
|
|
272
|
-
if (inner.num === 2 && inner.wire === 5 && Buffer.isBuffer(inner.value)) {
|
|
273
|
-
value = inner.value.readFloatLE(0);
|
|
274
|
-
break;
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
if (metric && value !== undefined && Number.isFinite(value)) {
|
|
280
|
-
const tokens = Math.round(value);
|
|
281
|
-
if (metric === "input_tokens")
|
|
282
|
-
promptTokens = tokens;
|
|
283
|
-
else if (metric === "output_tokens")
|
|
284
|
-
completionTokens = tokens;
|
|
285
|
-
else if (metric === "cached_input_tokens" || metric === "cache_read_input_tokens")
|
|
286
|
-
cachedInputTokens = (cachedInputTokens ?? 0) + tokens;
|
|
287
|
-
else if (metric === "cache_creation_input_tokens")
|
|
288
|
-
cacheCreationInputTokens = (cacheCreationInputTokens ?? 0) + tokens;
|
|
289
|
-
else if (metric === "reasoning_tokens" || metric === "output_reasoning_tokens")
|
|
290
|
-
reasoningTokens = tokens;
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
if (promptTokens === undefined && completionTokens === undefined)
|
|
294
|
-
return null;
|
|
295
|
-
const total = (promptTokens ?? 0) + (completionTokens ?? 0);
|
|
296
|
-
return {
|
|
297
|
-
kind: "usage",
|
|
298
|
-
promptTokens,
|
|
299
|
-
completionTokens,
|
|
300
|
-
totalTokens: total > 0 ? total : undefined,
|
|
301
|
-
cachedInputTokens,
|
|
302
|
-
cacheCreationInputTokens,
|
|
303
|
-
reasoningTokens,
|
|
304
|
-
};
|
|
305
|
-
}
|
|
306
|
-
const TRACE_ID_RE = /\(trace ID: ([0-9a-f]+)\)/i;
|
|
307
|
-
/**
|
|
308
|
-
* Trailer codes that mean "your credential was rejected", as opposed to a
|
|
309
|
-
* permission or tier problem, which a fresh token would not fix.
|
|
310
|
-
*/
|
|
311
|
-
const isAuthFailure = (code) => code === "unauthenticated" || code === "unauthorized" || code === "invalid_token";
|
|
312
|
-
/** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
|
|
313
|
-
export async function* streamChatEvents(request) {
|
|
314
|
-
const host = (request.apiServerUrl ?? DEFAULT_API_SERVER).replace(/\/$/, "");
|
|
315
|
-
const userJwt = await getCachedUserJwt(request.apiKey, host, request.signal);
|
|
316
|
-
const sessionIds = getOrAllocateSessionIds(request.apiKey, host, request.cascadeId);
|
|
317
|
-
const proto = buildGetChatMessageRequest({
|
|
318
|
-
apiKey: request.apiKey,
|
|
319
|
-
userJwt,
|
|
320
|
-
modelUid: request.modelUid,
|
|
321
|
-
messages: request.messages,
|
|
322
|
-
tools: request.tools,
|
|
323
|
-
cascadeId: sessionIds.cascadeId,
|
|
324
|
-
promptId: crypto.randomUUID(),
|
|
325
|
-
sessionId: sessionIds.sessionId,
|
|
326
|
-
requestId: BigInt(Date.now()),
|
|
327
|
-
triggerId: crypto.randomUUID(),
|
|
328
|
-
completionOpts: request.completionOpts,
|
|
329
|
-
});
|
|
330
|
-
const body = frameConnectStream(proto, true);
|
|
331
|
-
const ttfbTimeout = AbortSignal.timeout(STREAM_TTFB_MS);
|
|
332
|
-
const response = await fetch(`${host}/exa.api_server_pb.ApiServerService/GetChatMessage`, {
|
|
333
|
-
method: "POST",
|
|
334
|
-
headers: {
|
|
335
|
-
"Content-Type": "application/connect+proto",
|
|
336
|
-
"Connect-Protocol-Version": "1",
|
|
337
|
-
"Connect-Content-Encoding": "gzip",
|
|
338
|
-
"Connect-Accept-Encoding": "gzip",
|
|
339
|
-
},
|
|
340
|
-
body: new Uint8Array(body),
|
|
341
|
-
signal: request.signal ? AbortSignal.any([request.signal, ttfbTimeout]) : ttfbTimeout,
|
|
342
|
-
});
|
|
343
|
-
if (!response.ok) {
|
|
344
|
-
const text = await response.text();
|
|
345
|
-
// A 401 means the cached user_jwt was rejected. Drop it so the next attempt
|
|
346
|
-
// mints a fresh one instead of replaying a token already known to be bad.
|
|
347
|
-
if (response.status === 401)
|
|
348
|
-
clearCachedUserJwt();
|
|
349
|
-
throw new CloudChatError(`GetChatMessage HTTP ${response.status}: ${text.slice(0, 300)}`);
|
|
350
|
-
}
|
|
351
|
-
if (!response.body)
|
|
352
|
-
throw new CloudChatError("GetChatMessage response had no body stream");
|
|
353
|
-
const reader = response.body.getReader();
|
|
354
|
-
const chunks = [];
|
|
355
|
-
let queuedBytes = 0;
|
|
356
|
-
let trailerError = null;
|
|
357
|
-
let sawEos = false;
|
|
358
|
-
let idleTimer = null;
|
|
359
|
-
/**
|
|
360
|
-
* Release the response body.
|
|
361
|
-
*
|
|
362
|
-
* Must go through `reader`, not `response.body`: the body is locked by that
|
|
363
|
-
* reader, so `body.cancel()` rejects with "Cannot cancel a locked
|
|
364
|
-
* ReadableStream". Since it rejects rather than throws, a surrounding
|
|
365
|
-
* try/catch never saw it and the connection was silently left open on every
|
|
366
|
-
* abort and idle timeout.
|
|
367
|
-
*/
|
|
368
|
-
const cancelBody = (reason) => reader.cancel(reason).catch(() => { });
|
|
369
|
-
const peek = (n) => {
|
|
370
|
-
if (queuedBytes < n)
|
|
371
|
-
return null;
|
|
372
|
-
if (chunks.length === 1 && chunks[0].length >= n)
|
|
373
|
-
return chunks[0].slice(0, n);
|
|
374
|
-
const parts = [];
|
|
375
|
-
let remaining = n;
|
|
376
|
-
for (const chunk of chunks) {
|
|
377
|
-
if (remaining <= 0)
|
|
378
|
-
break;
|
|
379
|
-
if (chunk.length <= remaining) {
|
|
380
|
-
parts.push(chunk);
|
|
381
|
-
remaining -= chunk.length;
|
|
382
|
-
}
|
|
383
|
-
else {
|
|
384
|
-
parts.push(chunk.slice(0, remaining));
|
|
385
|
-
remaining = 0;
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
return Buffer.concat(parts, n);
|
|
389
|
-
};
|
|
390
|
-
const drop = (n) => {
|
|
391
|
-
queuedBytes -= n;
|
|
392
|
-
let remaining = n;
|
|
393
|
-
while (remaining > 0 && chunks.length > 0) {
|
|
394
|
-
const head = chunks[0];
|
|
395
|
-
if (head.length <= remaining) {
|
|
396
|
-
chunks.shift();
|
|
397
|
-
remaining -= head.length;
|
|
398
|
-
}
|
|
399
|
-
else {
|
|
400
|
-
chunks[0] = head.slice(remaining);
|
|
401
|
-
remaining = 0;
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
try {
|
|
406
|
-
if (request.signal?.aborted)
|
|
407
|
-
throw request.signal.reason;
|
|
408
|
-
request.signal?.addEventListener("abort", () => cancelBody(request.signal?.reason), { once: true });
|
|
409
|
-
while (true) {
|
|
410
|
-
if (idleTimer)
|
|
411
|
-
clearTimeout(idleTimer);
|
|
412
|
-
idleTimer = setTimeout(() => cancelBody(new Error(`idle timeout (${STREAM_IDLE_MS}ms)`)), STREAM_IDLE_MS);
|
|
413
|
-
const { value, done } = await reader.read();
|
|
414
|
-
if (idleTimer) {
|
|
415
|
-
clearTimeout(idleTimer);
|
|
416
|
-
idleTimer = null;
|
|
417
|
-
}
|
|
418
|
-
if (done)
|
|
419
|
-
break;
|
|
420
|
-
if (value) {
|
|
421
|
-
chunks.push(Buffer.from(value));
|
|
422
|
-
queuedBytes += value.length;
|
|
423
|
-
}
|
|
424
|
-
while (queuedBytes >= 5) {
|
|
425
|
-
const header = peek(5);
|
|
426
|
-
if (!header)
|
|
427
|
-
break;
|
|
428
|
-
const flags = header[0];
|
|
429
|
-
const length = header.readUInt32BE(1);
|
|
430
|
-
if (queuedBytes < 5 + length)
|
|
431
|
-
break;
|
|
432
|
-
drop(5);
|
|
433
|
-
const raw = peek(length) ?? Buffer.alloc(0);
|
|
434
|
-
drop(length);
|
|
435
|
-
let payload = raw;
|
|
436
|
-
if (flags & 0x01) {
|
|
437
|
-
try {
|
|
438
|
-
payload = zlib.gunzipSync(raw);
|
|
439
|
-
}
|
|
440
|
-
catch (cause) {
|
|
441
|
-
throw new CloudChatError(`Connect frame gunzip failed: ${cause.message}`);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
if ((flags & 0x02) !== 0) {
|
|
445
|
-
// End-of-stream trailer: JSON {error} on failure, empty on success.
|
|
446
|
-
sawEos = true;
|
|
447
|
-
const text = payload.toString("utf8");
|
|
448
|
-
if (text && text.includes('"error"')) {
|
|
449
|
-
let code;
|
|
450
|
-
let message = text;
|
|
451
|
-
try {
|
|
452
|
-
const parsed = JSON.parse(text);
|
|
453
|
-
code = parsed.error?.code;
|
|
454
|
-
if (parsed.error?.message)
|
|
455
|
-
message = parsed.error.message;
|
|
456
|
-
}
|
|
457
|
-
catch {
|
|
458
|
-
// non-JSON trailer — keep the raw text
|
|
459
|
-
}
|
|
460
|
-
const traceId = message.match(TRACE_ID_RE)?.[1];
|
|
461
|
-
trailerError = { code, message, traceId };
|
|
462
|
-
}
|
|
463
|
-
continue;
|
|
464
|
-
}
|
|
465
|
-
yield* decodeChatFrame(payload);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
finally {
|
|
470
|
-
if (idleTimer)
|
|
471
|
-
clearTimeout(idleTimer);
|
|
472
|
-
// Cancel before releasing: releasing first would detach the reader, after
|
|
473
|
-
// which the body can no longer be cancelled at all.
|
|
474
|
-
await cancelBody("stream finished");
|
|
475
|
-
try {
|
|
476
|
-
reader.releaseLock();
|
|
477
|
-
}
|
|
478
|
-
catch {
|
|
479
|
-
// lock already released
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
if (trailerError) {
|
|
483
|
-
const isOpaque = trailerError.code === "permission_denied" && /an internal error occurred/i.test(trailerError.message);
|
|
484
|
-
if (isOpaque) {
|
|
485
|
-
throw new CloudChatError(`Cognition denied model access for "${request.modelUid}". Check your account tier. (trace: ${trailerError.traceId ?? "n/a"})`, trailerError.code, trailerError.traceId);
|
|
486
|
-
}
|
|
487
|
-
// A token the server rejected mid-stream is just as stale as a 401: the
|
|
488
|
-
// account may have been reconnected between minting and streaming.
|
|
489
|
-
if (isAuthFailure(trailerError.code))
|
|
490
|
-
clearCachedUserJwt();
|
|
491
|
-
throw new CloudChatError(trailerError.message, trailerError.code, trailerError.traceId);
|
|
492
|
-
}
|
|
493
|
-
if (!sawEos) {
|
|
494
|
-
throw new CloudChatError("Cloud stream ended without EOS trailer. Connection likely dropped.", "truncated_stream");
|
|
495
|
-
}
|
|
496
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Reasoning-effort handling, in one place.
|
|
3
|
-
*
|
|
4
|
-
* The catalog encodes effort as a suffix on the model UID, and both the
|
|
5
|
-
* catalog decoder and the request path have to read that suffix. They used to
|
|
6
|
-
* carry their own copy of the same alternation, which is exactly the kind of
|
|
7
|
-
* duplication that drifts when Cognition adds an effort level.
|
|
8
|
-
*/
|
|
9
|
-
/** Valid reasoning effort levels. */
|
|
10
|
-
export declare const EFFORT_LEVELS: readonly ["none", "low", "medium", "high", "xhigh", "max"];
|
|
11
|
-
export type EffortLevel = (typeof EFFORT_LEVELS)[number];
|
|
12
|
-
/** Narrow an arbitrary value to a known effort level, or `undefined`. */
|
|
13
|
-
export declare function toEffortLevel(value: unknown): EffortLevel | undefined;
|
|
14
|
-
/** Split a UID into its base UID and effort suffix, e.g. `opus-4-8-high`. */
|
|
15
|
-
export declare function splitEffortSuffix(modelUid: string): {
|
|
16
|
-
baseModelUid: string;
|
|
17
|
-
effortLevel?: EffortLevel;
|
|
18
|
-
};
|
|
19
|
-
/** Append an effort suffix to a base UID. */
|
|
20
|
-
export declare function withEffortSuffix(modelUid: string, effort: EffortLevel): string;
|
package/dist/protocol/effort.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Reasoning-effort handling, in one place.
|
|
3
|
-
*
|
|
4
|
-
* The catalog encodes effort as a suffix on the model UID, and both the
|
|
5
|
-
* catalog decoder and the request path have to read that suffix. They used to
|
|
6
|
-
* carry their own copy of the same alternation, which is exactly the kind of
|
|
7
|
-
* duplication that drifts when Cognition adds an effort level.
|
|
8
|
-
*/
|
|
9
|
-
/** Valid reasoning effort levels. */
|
|
10
|
-
export const EFFORT_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"];
|
|
11
|
-
/** Derived from EFFORT_LEVELS so the two can never disagree. */
|
|
12
|
-
const EFFORT_SUFFIX = new RegExp(`-(${EFFORT_LEVELS.join("|")})$`);
|
|
13
|
-
/** Narrow an arbitrary value to a known effort level, or `undefined`. */
|
|
14
|
-
export function toEffortLevel(value) {
|
|
15
|
-
if (typeof value !== "string")
|
|
16
|
-
return undefined;
|
|
17
|
-
const effort = value.toLowerCase();
|
|
18
|
-
return EFFORT_LEVELS.includes(effort) ? effort : undefined;
|
|
19
|
-
}
|
|
20
|
-
/** Split a UID into its base UID and effort suffix, e.g. `opus-4-8-high`. */
|
|
21
|
-
export function splitEffortSuffix(modelUid) {
|
|
22
|
-
const match = modelUid.match(EFFORT_SUFFIX);
|
|
23
|
-
const effortLevel = match?.[1];
|
|
24
|
-
if (!effortLevel)
|
|
25
|
-
return { baseModelUid: modelUid };
|
|
26
|
-
return { baseModelUid: modelUid.slice(0, -(effortLevel.length + 1)), effortLevel: effortLevel };
|
|
27
|
-
}
|
|
28
|
-
/** Append an effort suffix to a base UID. */
|
|
29
|
-
export function withEffortSuffix(modelUid, effort) {
|
|
30
|
-
return `${modelUid}-${effort}`;
|
|
31
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
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;
|
|
@@ -1,42 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/protocol/wire.d.ts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Protobuf wire-format encoding and Connect-RPC streaming envelope.
|
|
3
|
-
*
|
|
4
|
-
* Connect-RPC streaming frame layout (HTTPS POST body):
|
|
5
|
-
*
|
|
6
|
-
* flags 1 byte | length 4 bytes BE | payload
|
|
7
|
-
*
|
|
8
|
-
* - flags bit 0x01: payload is gzip-compressed
|
|
9
|
-
* - flags bit 0x02: end-of-stream trailer frame (JSON `{error}` or empty)
|
|
10
|
-
*
|
|
11
|
-
* Protocol reverse-engineered from the Windsurf language_server and the Devin
|
|
12
|
-
* CLI; originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
|
|
13
|
-
*/
|
|
14
|
-
export type WireType = 0 | 1 | 2 | 5;
|
|
15
|
-
export interface ProtoField {
|
|
16
|
-
readonly num: number;
|
|
17
|
-
readonly wire: WireType;
|
|
18
|
-
readonly value: bigint | Buffer;
|
|
19
|
-
}
|
|
20
|
-
export declare function encodeVarint(value: bigint | number): Buffer;
|
|
21
|
-
export declare function encodeTag(fieldNum: number, wire: WireType): Buffer;
|
|
22
|
-
export declare function encodeString(fieldNum: number, value: string): Buffer;
|
|
23
|
-
export declare function encodeMessage(fieldNum: number, body: Buffer): Buffer;
|
|
24
|
-
export declare function encodeVarintField(fieldNum: number, value: bigint | number): Buffer;
|
|
25
|
-
export declare function encodeTimestampBody(): Buffer;
|
|
26
|
-
export declare function decodeVarint(buf: Buffer, offset: number): [bigint, number];
|
|
27
|
-
/** Iterate the protobuf fields of a message in wire order. */
|
|
28
|
-
export declare function iterFields(buf: Buffer): Generator<ProtoField>;
|
|
29
|
-
/** Wrap a protobuf message into a Connect-RPC streaming request frame. */
|
|
30
|
-
export declare function frameConnectStream(body: Buffer, compress?: boolean): Buffer;
|