opencode-devin 0.2.2 → 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.
@@ -1,629 +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 { APICallError } from "@ai-sdk/provider";
9
- import { encodeMessage, encodeString, encodeVarintField, frameConnectStream, iterFields, } from "./wire.js";
10
- import { buildMetadata } from "./metadata.js";
11
- import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
12
- import { DEFAULT_API_SERVER } from "../constants.js";
13
- const STREAM_IDLE_MS = 120_000;
14
- const STREAM_TTFB_MS = 60_000;
15
- const DEFAULT_MAX_OUTPUT_TOKENS = 64_000;
16
- const MAX_TOOL_DESC_LEN = 6998;
17
- /**
18
- * HTTP status equivalents of the Connect error codes, per the Connect protocol.
19
- *
20
- * A streaming RPC always answers 200 and reports failure in the trailer, so the
21
- * trailer code is the only signal of what went wrong. Hosts decide whether to
22
- * retry from the status: without one every failure looks unknown, and opencode
23
- * retries unknown errors ten times, including ones that cannot succeed.
24
- */
25
- const CONNECT_CODE_STATUS = {
26
- canceled: 499,
27
- unknown: 500,
28
- invalid_argument: 400,
29
- deadline_exceeded: 504,
30
- not_found: 404,
31
- already_exists: 409,
32
- permission_denied: 403,
33
- resource_exhausted: 429,
34
- failed_precondition: 400,
35
- aborted: 409,
36
- out_of_range: 400,
37
- unimplemented: 501,
38
- internal: 500,
39
- unavailable: 503,
40
- data_loss: 500,
41
- unauthenticated: 401,
42
- // Raised by this client rather than by the server.
43
- ttfb_timeout: 504,
44
- idle_timeout: 504,
45
- truncated_stream: 502,
46
- invalid_frame: 502,
47
- };
48
- /** Exported for tests. */
49
- export function statusForCode(code, message) {
50
- // An exhausted quota is not worth retrying, whichever code it arrives under,
51
- // and under `resource_exhausted` it would otherwise look like a rate limit.
52
- if (/\bquota\b|out of credits/i.test(message))
53
- return 402;
54
- return (code && CONNECT_CODE_STATUS[code]) || 500;
55
- }
56
- /**
57
- * A failed chat request.
58
- *
59
- * It is an `APICallError` so hosts can read `statusCode` and `isRetryable`
60
- * instead of guessing from the message.
61
- */
62
- export class CloudChatError extends APICallError {
63
- code;
64
- traceId;
65
- constructor(message, options = {}) {
66
- super({
67
- message,
68
- url: options.url ?? "",
69
- requestBodyValues: undefined,
70
- statusCode: options.status ?? statusForCode(options.code, message),
71
- responseBody: options.responseBody,
72
- ...(options.retryWithFreshToken ? { isRetryable: true, responseHeaders: { "x-should-retry": "true" } } : {}),
73
- });
74
- this.name = "CloudChatError";
75
- this.code = options.code;
76
- this.traceId = options.traceId;
77
- }
78
- }
79
- // --- Request encoding ---
80
- /** Cognition rejects source=3 for system; system content is inlined into user turns. */
81
- const SOURCE_BY_ROLE = { user: 1, assistant: 2, system: 1, tool: 4 };
82
- function encodeImageData(image) {
83
- const parts = [encodeString(1, image.base64Data), encodeString(2, image.mimeType)];
84
- if (image.caption)
85
- parts.push(encodeString(3, image.caption));
86
- return Buffer.concat(parts);
87
- }
88
- function encodeToolCall(call) {
89
- return Buffer.concat([encodeString(1, call.id), encodeString(2, call.name), encodeString(3, call.arguments)]);
90
- }
91
- function encodePrompt(content, source, opts) {
92
- const text = content
93
- .filter((part) => part.type === "text")
94
- .map((part) => part.text)
95
- .join("\n");
96
- const images = content.filter((part) => part.type === "image");
97
- const parts = [
98
- encodeVarintField(2, source),
99
- encodeString(3, text),
100
- encodeVarintField(4, Math.max(1, Math.floor(text.length / 4))),
101
- encodeVarintField(5, 1),
102
- ];
103
- if (opts?.toolCallId)
104
- parts.push(encodeString(7, opts.toolCallId));
105
- if (opts?.toolCalls)
106
- for (const call of opts.toolCalls)
107
- parts.push(encodeMessage(6, encodeToolCall(call)));
108
- if (opts?.isError)
109
- parts.push(encodeVarintField(9, 1));
110
- for (const image of images)
111
- parts.push(encodeMessage(10, encodeImageData(image)));
112
- return Buffer.concat(parts);
113
- }
114
- function textOf(content) {
115
- if (typeof content === "string")
116
- return content;
117
- return content
118
- .filter((part) => part.type === "text")
119
- .map((part) => part.text)
120
- .join("\n");
121
- }
122
- /** Cascade has no system role: fold system content into the next user turn. */
123
- function collapseSystemIntoUser(messages) {
124
- if (!messages.some((message) => message.role === "system"))
125
- return messages;
126
- const out = [];
127
- let pendingSystem = [];
128
- for (const message of messages) {
129
- if (message.role === "system") {
130
- const text = textOf(message.content);
131
- if (text)
132
- pendingSystem.push(text);
133
- }
134
- else if (message.role === "user" && pendingSystem.length > 0) {
135
- const content = normalizeContent(message.content);
136
- const images = content.filter((part) => part.type === "image");
137
- const wrapped = `<system>\n${pendingSystem.join("\n\n")}\n</system>\n${textOf(content)}`;
138
- out.push({ role: "user", content: [{ type: "text", text: wrapped }, ...images] });
139
- pendingSystem = [];
140
- }
141
- else {
142
- out.push(message);
143
- }
144
- }
145
- if (pendingSystem.length > 0) {
146
- out.push({ role: "user", content: [{ type: "text", text: `<system>\n${pendingSystem.join("\n\n")}\n</system>` }] });
147
- }
148
- return out;
149
- }
150
- function normalizeContent(content) {
151
- if (typeof content === "string")
152
- return [{ type: "text", text: content }];
153
- const out = [];
154
- for (const part of content) {
155
- if (part.type === "text" && typeof part.text === "string") {
156
- out.push({ type: "text", text: part.text });
157
- }
158
- else if (part.type === "image" && typeof part.base64Data === "string") {
159
- out.push({ type: "image", mimeType: part.mimeType ?? "image/png", base64Data: part.base64Data, caption: part.caption });
160
- }
161
- }
162
- return out;
163
- }
164
- function encodeToolDef(tool) {
165
- const raw = tool.description ?? "";
166
- const description = raw.length > MAX_TOOL_DESC_LEN ? `${raw.slice(0, MAX_TOOL_DESC_LEN - 24)}\n…(truncated for cloud)` : raw;
167
- return Buffer.concat([
168
- encodeString(1, tool.name),
169
- encodeString(2, description),
170
- encodeString(3, JSON.stringify(tool.parameters ?? {})),
171
- ]);
172
- }
173
- function encodeCompletionConfiguration(opts) {
174
- const float64 = (fieldNum, value) => {
175
- const buf = Buffer.alloc(8);
176
- buf.writeDoubleLE(value, 0);
177
- return Buffer.concat([Buffer.from([(fieldNum << 3) | 1]), buf]);
178
- };
179
- // Field names are from the `CompletionConfiguration` descriptor in a build
180
- // of the same codebase. #2 was checked against the live API: it caps the
181
- // output (2 = 25 stops at 25 output tokens with reason MAX_TOKENS) and does
182
- // not truncate the input (a 164k-token prompt passes with 2 = 64000). #3 is
183
- // sent as before but had no observable effect (3 = 3 did not stop a
184
- // 200-line reply).
185
- // #1 num_completions #2 max_tokens #3 max_newlines #5 temperature
186
- // #6 first_temperature #7 top_k #8 top_p #11 fim_eot_prob_threshold
187
- return Buffer.concat([
188
- encodeVarintField(1, 1),
189
- encodeVarintField(2, opts.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS),
190
- encodeVarintField(3, 128_000),
191
- float64(5, opts.temperature ?? 0.7),
192
- float64(6, 0.95),
193
- encodeVarintField(7, opts.topK ?? 50),
194
- float64(8, opts.topP ?? 1.0),
195
- float64(11, 1.0),
196
- ]);
197
- }
198
- /**
199
- * `ChatToolChoice`: #1 option_name | #2 tool_name (oneof).
200
- *
201
- * Field #12 of the request. Checked against the live API on Claude, GPT,
202
- * Gemini and Kimi models: "required" forces a tool call, "none" suppresses
203
- * them, and a tool name forces that tool. "auto" is the default, so it is not
204
- * sent at all.
205
- */
206
- function encodeToolChoice(choice) {
207
- if (choice.type === "auto")
208
- return undefined;
209
- return encodeMessage(12, choice.type === "tool" ? encodeString(2, choice.toolName) : encodeString(1, choice.type));
210
- }
211
- /**
212
- * Per-credential Cascade session ids.
213
- *
214
- * Keys embed the session token, so the map is capped and evicted in insertion
215
- * order: a user who connects and switches credentials repeatedly would
216
- * otherwise accumulate tokens in memory for the life of the process. In
217
- * practice only one or two credentials are ever live at a time.
218
- */
219
- const SESSION_CACHE_LIMIT = 4;
220
- const sessionCache = new Map();
221
- function getOrAllocateSessionIds(apiKey, host, cascadeIdOverride) {
222
- const key = credentialKey(host, apiKey);
223
- let ids = sessionCache.get(key);
224
- if (!ids) {
225
- ids = { sessionId: crypto.randomUUID(), cascadeId: cascadeIdOverride ?? crypto.randomUUID() };
226
- if (sessionCache.size >= SESSION_CACHE_LIMIT) {
227
- const oldest = sessionCache.keys().next();
228
- if (!oldest.done)
229
- sessionCache.delete(oldest.value);
230
- }
231
- sessionCache.set(key, ids);
232
- }
233
- else if (cascadeIdOverride && ids.cascadeId !== cascadeIdOverride) {
234
- ids = { sessionId: ids.sessionId, cascadeId: cascadeIdOverride };
235
- sessionCache.set(key, ids);
236
- }
237
- return ids;
238
- }
239
- function buildGetChatMessageRequest(args) {
240
- const metadata = buildMetadata({
241
- apiKey: args.apiKey,
242
- userJwt: args.userJwt,
243
- sessionId: args.sessionId,
244
- requestId: args.requestId,
245
- triggerId: args.triggerId,
246
- });
247
- const collapsed = collapseSystemIntoUser(args.messages);
248
- const promptParts = collapsed.map((message) => encodeMessage(3, encodePrompt(normalizeContent(message.content), SOURCE_BY_ROLE[message.role] ?? 1, {
249
- toolCallId: message.tool_call_id,
250
- toolCalls: message.tool_calls,
251
- isError: message.is_error,
252
- })));
253
- // Field layout from mitm capture of the Windsurf language_server:
254
- // #1 metadata (message)
255
- // #3 chat_message_prompts (repeated — one element per history turn)
256
- // #7 request_type (varint enum, 5 = CASCADE)
257
- // #8 completion_configuration (message)
258
- // #10 tools (repeated ChatToolDefinition)
259
- // #12 tool_choice (message, omitted for "auto")
260
- // #16 cascade_id (string)
261
- // #21 chat_model_uid (string)
262
- // #22 prompt_id (string)
263
- const toolParts = (args.tools ?? []).map((tool) => encodeMessage(10, encodeToolDef(tool)));
264
- const toolChoice = args.tools?.length && args.toolChoice ? encodeToolChoice(args.toolChoice) : undefined;
265
- return Buffer.concat([
266
- encodeMessage(1, metadata),
267
- ...promptParts,
268
- encodeVarintField(7, 5),
269
- encodeMessage(8, encodeCompletionConfiguration(args.completionOpts ?? {})),
270
- ...toolParts,
271
- ...(toolChoice ? [toolChoice] : []),
272
- encodeString(16, args.cascadeId),
273
- encodeString(21, args.modelUid),
274
- encodeString(22, args.promptId),
275
- ]);
276
- }
277
- function* decodeChatFrame(buf) {
278
- for (const field of iterFields(buf)) {
279
- if (field.num === 5 && field.wire === 0) {
280
- // Finish reason (varint) — StopReason enum:
281
- // 0 UNSPECIFIED → stop, 1 INCOMPLETE → length, 2 STOP_PATTERN → stop,
282
- // 3 MAX_TOKENS → length, 10 FUNCTION_CALL → tool_calls, 11 CONTENT_FILTER → content_filter
283
- const value = Number(field.value);
284
- let reason = "stop";
285
- if (value === 10)
286
- reason = "tool_calls";
287
- else if (value === 11)
288
- reason = "content_filter";
289
- else if (value === 1 || value === 3)
290
- reason = "length";
291
- yield { kind: "finish", reason };
292
- continue;
293
- }
294
- if (field.wire !== 2 || !Buffer.isBuffer(field.value))
295
- continue;
296
- if (field.num === 3) {
297
- // delta_text — visible text content
298
- const text = field.value.toString("utf8");
299
- if (text)
300
- yield { kind: "text", text };
301
- }
302
- else if (field.num === 6) {
303
- // ToolCallDelta { #1 id, #2 name, #3 arguments_delta }
304
- let id;
305
- let name;
306
- let argsDelta;
307
- for (const part of iterFields(field.value)) {
308
- if (part.wire !== 2 || !Buffer.isBuffer(part.value))
309
- continue;
310
- const text = part.value.toString("utf8");
311
- if (part.num === 1)
312
- id = text;
313
- else if (part.num === 2)
314
- name = text;
315
- else if (part.num === 3)
316
- argsDelta = text;
317
- }
318
- if (id !== undefined && name !== undefined)
319
- yield { kind: "tool_call_start", id, name };
320
- if (argsDelta !== undefined)
321
- yield { kind: "tool_call_args", argsDelta, ...(id !== undefined ? { id } : {}) };
322
- }
323
- else if (field.num === 9) {
324
- // Internal thinking / chain-of-thought
325
- const text = field.value.toString("utf8");
326
- if (text)
327
- yield { kind: "reasoning", text };
328
- }
329
- else if (field.num === 28) {
330
- const usage = decodeUsageBlock(field.value);
331
- if (usage)
332
- yield usage;
333
- }
334
- }
335
- }
336
- function decodeUsageBlock(buf) {
337
- let promptTokens;
338
- let completionTokens;
339
- let cachedInputTokens;
340
- let cacheCreationInputTokens;
341
- let reasoningTokens;
342
- for (const field of iterFields(buf)) {
343
- if (field.num !== 2 || field.wire !== 2 || !Buffer.isBuffer(field.value))
344
- continue;
345
- let metric;
346
- let value;
347
- for (const entry of iterFields(field.value)) {
348
- if (entry.num === 5 && entry.wire === 2 && Buffer.isBuffer(entry.value)) {
349
- metric = entry.value.toString("utf8");
350
- }
351
- else if (entry.num === 4 && entry.wire === 2 && Buffer.isBuffer(entry.value)) {
352
- for (const inner of iterFields(entry.value)) {
353
- if (inner.num === 2 && inner.wire === 5 && Buffer.isBuffer(inner.value)) {
354
- value = inner.value.readFloatLE(0);
355
- break;
356
- }
357
- }
358
- }
359
- }
360
- if (metric && value !== undefined && Number.isFinite(value)) {
361
- const tokens = Math.round(value);
362
- if (metric === "input_tokens")
363
- promptTokens = tokens;
364
- else if (metric === "output_tokens")
365
- completionTokens = tokens;
366
- else if (metric === "cached_input_tokens" || metric === "cache_read_input_tokens")
367
- cachedInputTokens = (cachedInputTokens ?? 0) + tokens;
368
- else if (metric === "cache_creation_input_tokens")
369
- cacheCreationInputTokens = (cacheCreationInputTokens ?? 0) + tokens;
370
- else if (metric === "reasoning_tokens" || metric === "output_reasoning_tokens")
371
- reasoningTokens = tokens;
372
- }
373
- }
374
- if (promptTokens === undefined && completionTokens === undefined)
375
- return null;
376
- const total = (promptTokens ?? 0) + (completionTokens ?? 0);
377
- return {
378
- kind: "usage",
379
- promptTokens,
380
- completionTokens,
381
- totalTokens: total > 0 ? total : undefined,
382
- cachedInputTokens,
383
- cacheCreationInputTokens,
384
- reasoningTokens,
385
- };
386
- }
387
- const TRACE_ID_RE = /\(trace ID: ([0-9a-f]+)\)/i;
388
- /**
389
- * Trailer codes that mean "your credential was rejected", as opposed to a
390
- * permission or tier problem, which a fresh token would not fix.
391
- */
392
- const isAuthFailure = (code) => code === "unauthenticated" || code === "unauthorized" || code === "invalid_token";
393
- /** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
394
- export async function* streamChatEvents(request) {
395
- const host = (request.apiServerUrl ?? DEFAULT_API_SERVER).replace(/\/$/, "");
396
- const userJwt = await getCachedUserJwt(request.apiKey, host, request.signal);
397
- const sessionIds = getOrAllocateSessionIds(request.apiKey, host, request.cascadeId);
398
- const proto = buildGetChatMessageRequest({
399
- apiKey: request.apiKey,
400
- userJwt,
401
- modelUid: request.modelUid,
402
- messages: request.messages,
403
- tools: request.tools,
404
- toolChoice: request.toolChoice,
405
- cascadeId: sessionIds.cascadeId,
406
- promptId: crypto.randomUUID(),
407
- sessionId: sessionIds.sessionId,
408
- requestId: BigInt(Date.now()),
409
- triggerId: crypto.randomUUID(),
410
- completionOpts: request.completionOpts,
411
- });
412
- const body = frameConnectStream(proto, true);
413
- const ttfbMs = request.timeouts?.ttfbMs ?? STREAM_TTFB_MS;
414
- const idleMs = request.timeouts?.idleMs ?? STREAM_IDLE_MS;
415
- // The fetch signal also governs the response body, so the TTFB timer must be
416
- // cleared once headers arrive. `AbortSignal.timeout()` cannot be cleared and
417
- // would abort a healthy stream `ttfbMs` after the request started.
418
- const ttfb = new AbortController();
419
- const url = `${host}/exa.api_server_pb.ApiServerService/GetChatMessage`;
420
- const ttfbError = new CloudChatError(`GetChatMessage got no response within ${ttfbMs}ms`, { code: "ttfb_timeout", url });
421
- const ttfbTimer = setTimeout(() => ttfb.abort(ttfbError), ttfbMs);
422
- let response;
423
- try {
424
- response = await fetch(url, {
425
- method: "POST",
426
- headers: {
427
- "Content-Type": "application/connect+proto",
428
- "Connect-Protocol-Version": "1",
429
- "Connect-Content-Encoding": "gzip",
430
- "Connect-Accept-Encoding": "gzip",
431
- },
432
- body: new Uint8Array(body),
433
- signal: request.signal ? AbortSignal.any([request.signal, ttfb.signal]) : ttfb.signal,
434
- });
435
- }
436
- catch (cause) {
437
- // Runtimes differ on whether fetch rejects with the abort reason itself.
438
- if (ttfb.signal.aborted && !request.signal?.aborted)
439
- throw ttfbError;
440
- throw cause;
441
- }
442
- finally {
443
- clearTimeout(ttfbTimer);
444
- }
445
- if (!response.ok) {
446
- const text = await response.text();
447
- // A 401 means the cached user_jwt was rejected. Drop it so the next attempt
448
- // mints a fresh one instead of replaying a token already known to be bad.
449
- if (response.status === 401)
450
- clearCachedUserJwt();
451
- throw new CloudChatError(`GetChatMessage HTTP ${response.status}: ${text.slice(0, 300)}`, {
452
- status: response.status,
453
- url,
454
- responseBody: text,
455
- retryWithFreshToken: response.status === 401,
456
- });
457
- }
458
- if (!response.body)
459
- throw new CloudChatError("GetChatMessage response had no body stream", { status: 502, url });
460
- const reader = response.body.getReader();
461
- const chunks = [];
462
- let queuedBytes = 0;
463
- let trailerError = null;
464
- let sawEos = false;
465
- let idleTimer = null;
466
- let idleTimedOut = false;
467
- const onAbort = () => cancelBody(request.signal?.reason);
468
- /**
469
- * Release the response body.
470
- *
471
- * Must go through `reader`, not `response.body`: the body is locked by that
472
- * reader, so `body.cancel()` rejects with "Cannot cancel a locked
473
- * ReadableStream". Since it rejects rather than throws, a surrounding
474
- * try/catch never saw it and the connection was silently left open on every
475
- * abort and idle timeout.
476
- */
477
- const cancelBody = (reason) => reader.cancel(reason).catch(() => { });
478
- const peek = (n) => {
479
- if (queuedBytes < n)
480
- return null;
481
- if (chunks.length === 1 && chunks[0].length >= n)
482
- return chunks[0].slice(0, n);
483
- const parts = [];
484
- let remaining = n;
485
- for (const chunk of chunks) {
486
- if (remaining <= 0)
487
- break;
488
- if (chunk.length <= remaining) {
489
- parts.push(chunk);
490
- remaining -= chunk.length;
491
- }
492
- else {
493
- parts.push(chunk.slice(0, remaining));
494
- remaining = 0;
495
- }
496
- }
497
- return Buffer.concat(parts, n);
498
- };
499
- const drop = (n) => {
500
- queuedBytes -= n;
501
- let remaining = n;
502
- while (remaining > 0 && chunks.length > 0) {
503
- const head = chunks[0];
504
- if (head.length <= remaining) {
505
- chunks.shift();
506
- remaining -= head.length;
507
- }
508
- else {
509
- chunks[0] = head.slice(remaining);
510
- remaining = 0;
511
- }
512
- }
513
- };
514
- try {
515
- if (request.signal?.aborted)
516
- throw request.signal.reason;
517
- request.signal?.addEventListener("abort", onAbort, { once: true });
518
- while (true) {
519
- if (idleTimer)
520
- clearTimeout(idleTimer);
521
- idleTimer = setTimeout(() => {
522
- idleTimedOut = true;
523
- cancelBody(new Error(`idle timeout (${idleMs}ms)`));
524
- }, idleMs);
525
- const { value, done } = await reader.read();
526
- if (idleTimer) {
527
- clearTimeout(idleTimer);
528
- idleTimer = null;
529
- }
530
- // Cancelling the reader resolves the pending read as `done`, so the cause
531
- // has to be reported here or it surfaces as a misleading truncated stream.
532
- if (request.signal?.aborted)
533
- throw request.signal.reason;
534
- if (idleTimedOut) {
535
- throw new CloudChatError(`GetChatMessage stream was idle for ${idleMs}ms`, { code: "idle_timeout", url });
536
- }
537
- if (done)
538
- break;
539
- if (value) {
540
- chunks.push(Buffer.from(value));
541
- queuedBytes += value.length;
542
- }
543
- while (queuedBytes >= 5) {
544
- const header = peek(5);
545
- if (!header)
546
- break;
547
- const flags = header[0];
548
- const length = header.readUInt32BE(1);
549
- if (queuedBytes < 5 + length)
550
- break;
551
- drop(5);
552
- const raw = peek(length) ?? Buffer.alloc(0);
553
- drop(length);
554
- let payload = raw;
555
- if (flags & 0x01) {
556
- try {
557
- payload = zlib.gunzipSync(raw);
558
- }
559
- catch (cause) {
560
- throw new CloudChatError(`Connect frame gunzip failed: ${cause.message}`, {
561
- code: "invalid_frame",
562
- url,
563
- });
564
- }
565
- }
566
- if ((flags & 0x02) !== 0) {
567
- // End-of-stream trailer: JSON {error} on failure, empty on success.
568
- sawEos = true;
569
- const text = payload.toString("utf8");
570
- if (text && text.includes('"error"')) {
571
- let code;
572
- let message = text;
573
- try {
574
- const parsed = JSON.parse(text);
575
- code = parsed.error?.code;
576
- if (parsed.error?.message)
577
- message = parsed.error.message;
578
- }
579
- catch {
580
- // non-JSON trailer — keep the raw text
581
- }
582
- const traceId = message.match(TRACE_ID_RE)?.[1];
583
- trailerError = { code, message, traceId };
584
- }
585
- continue;
586
- }
587
- yield* decodeChatFrame(payload);
588
- }
589
- }
590
- }
591
- finally {
592
- if (idleTimer)
593
- clearTimeout(idleTimer);
594
- request.signal?.removeEventListener("abort", onAbort);
595
- // Cancel before releasing: releasing first would detach the reader, after
596
- // which the body can no longer be cancelled at all.
597
- await cancelBody("stream finished");
598
- try {
599
- reader.releaseLock();
600
- }
601
- catch {
602
- // lock already released
603
- }
604
- }
605
- if (trailerError) {
606
- const isOpaque = trailerError.code === "permission_denied" && /an internal error occurred/i.test(trailerError.message);
607
- if (isOpaque) {
608
- throw new CloudChatError(`Cognition denied model access for "${request.modelUid}". Check your account tier. (trace: ${trailerError.traceId ?? "n/a"})`, { code: trailerError.code, traceId: trailerError.traceId, url });
609
- }
610
- // A token the server rejected mid-stream is just as stale as a 401: the
611
- // account may have been reconnected between minting and streaming.
612
- const staleToken = isAuthFailure(trailerError.code);
613
- if (staleToken)
614
- clearCachedUserJwt();
615
- throw new CloudChatError(trailerError.message, {
616
- code: trailerError.code,
617
- traceId: trailerError.traceId,
618
- url,
619
- retryWithFreshToken: staleToken,
620
- ...(staleToken ? { status: 401 } : {}),
621
- });
622
- }
623
- if (!sawEos) {
624
- throw new CloudChatError("Cloud stream ended without EOS trailer. Connection likely dropped.", {
625
- code: "truncated_stream",
626
- url,
627
- });
628
- }
629
- }
@@ -1,36 +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, weakest first. */
10
- export declare const EFFORT_LEVELS: readonly ["none", "minimal", "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
- /** Effort named by a catalog capability value, e.g. "XHigh" or "No Thinking". */
15
- export declare function effortFromLabel(label: string | undefined): EffortLevel | undefined;
16
- /**
17
- * Split a UID into its base UID and effort, e.g. `opus-4-8-high` into
18
- * `opus-4-8` and `high`, or `opus-4-8-high-fast` into `opus-4-8-fast` and `high`.
19
- */
20
- export declare function splitEffortSuffix(modelUid: string): {
21
- baseModelUid: string;
22
- effortLevel?: EffortLevel;
23
- };
24
- /** Replace the effort in a UID that has one, or append it to one that does not. */
25
- export declare function withEffortSuffix(modelUid: string, effort: EffortLevel): string;
26
- /** A model as far as effort selection is concerned. */
27
- export interface EffortMember {
28
- modelUid: string;
29
- baseModelUid?: string;
30
- effortLevel?: string;
31
- }
32
- /**
33
- * The member to use when no effort is asked for: the UID that carries no
34
- * effort if the family has one, otherwise medium, then high, then the first.
35
- */
36
- export declare function defaultMember<T extends EffortMember>(family: readonly T[]): T | undefined;