opencode-devin 0.2.0 → 0.2.2

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.
@@ -4,10 +4,33 @@
4
4
  * Field layouts come from mitm captures of the Windsurf language_server.
5
5
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
6
6
  */
7
- export declare class CloudChatError extends Error {
7
+ import { APICallError } from "@ai-sdk/provider";
8
+ /** Exported for tests. */
9
+ export declare function statusForCode(code: string | undefined, message: string): number;
10
+ export interface CloudChatErrorOptions {
11
+ code?: string;
12
+ traceId?: string;
13
+ /** HTTP status when the server sent one; otherwise derived from `code`. */
14
+ status?: number;
15
+ url?: string;
16
+ responseBody?: string;
17
+ /**
18
+ * The failure was a rejected `user_jwt` that has since been dropped, so the
19
+ * same request will succeed with a fresh one. Without this an auth status
20
+ * reads as final and the host gives up.
21
+ */
22
+ retryWithFreshToken?: boolean;
23
+ }
24
+ /**
25
+ * A failed chat request.
26
+ *
27
+ * It is an `APICallError` so hosts can read `statusCode` and `isRetryable`
28
+ * instead of guessing from the message.
29
+ */
30
+ export declare class CloudChatError extends APICallError {
8
31
  readonly code?: string;
9
32
  readonly traceId?: string;
10
- constructor(message: string, code?: string, traceId?: string);
33
+ constructor(message: string, options?: CloudChatErrorOptions);
11
34
  }
12
35
  /** Cognition rejects source=3 for system; system content is inlined into user turns. */
13
36
  declare const SOURCE_BY_ROLE: {
@@ -38,14 +61,21 @@ export interface ChatHistoryItem {
38
61
  content: ChatContent;
39
62
  tool_call_id?: string;
40
63
  tool_calls?: ChatToolCall[];
64
+ /** For a tool message: the tool reported a failure. */
65
+ is_error?: boolean;
41
66
  }
67
+ export type ChatToolChoice = {
68
+ type: "auto" | "none" | "required";
69
+ } | {
70
+ type: "tool";
71
+ toolName: string;
72
+ };
42
73
  export interface ChatToolDefinition {
43
74
  name: string;
44
75
  description?: string;
45
76
  parameters?: unknown;
46
77
  }
47
78
  export interface CompletionOptions {
48
- maxInputTokens?: number;
49
79
  maxOutputTokens?: number;
50
80
  temperature?: number;
51
81
  topP?: number;
@@ -83,9 +113,15 @@ export interface StreamChatRequest {
83
113
  modelUid: string;
84
114
  messages: ChatHistoryItem[];
85
115
  tools?: ChatToolDefinition[];
116
+ toolChoice?: ChatToolChoice;
86
117
  cascadeId?: string;
87
118
  completionOpts?: CompletionOptions;
88
119
  signal?: AbortSignal;
120
+ /** Override the default timeouts. Exists so tests need not wait out the real ones. */
121
+ timeouts?: {
122
+ ttfbMs?: number;
123
+ idleMs?: number;
124
+ };
89
125
  }
90
126
  /** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
91
127
  export declare function streamChatEvents(request: StreamChatRequest): AsyncGenerator<ChatEvent>;
@@ -5,21 +5,75 @@
5
5
  * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
6
6
  */
7
7
  import * as zlib from "node:zlib";
8
+ import { APICallError } from "@ai-sdk/provider";
8
9
  import { encodeMessage, encodeString, encodeVarintField, frameConnectStream, iterFields, } from "./wire.js";
9
10
  import { buildMetadata } from "./metadata.js";
10
11
  import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
11
12
  import { DEFAULT_API_SERVER } from "../constants.js";
12
13
  const STREAM_IDLE_MS = 120_000;
13
14
  const STREAM_TTFB_MS = 60_000;
15
+ const DEFAULT_MAX_OUTPUT_TOKENS = 64_000;
14
16
  const MAX_TOOL_DESC_LEN = 6998;
15
- export class CloudChatError extends Error {
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 {
16
63
  code;
17
64
  traceId;
18
- constructor(message, code, traceId) {
19
- super(message);
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
+ });
20
74
  this.name = "CloudChatError";
21
- this.code = code;
22
- this.traceId = traceId;
75
+ this.code = options.code;
76
+ this.traceId = options.traceId;
23
77
  }
24
78
  }
25
79
  // --- Request encoding ---
@@ -51,6 +105,8 @@ function encodePrompt(content, source, opts) {
51
105
  if (opts?.toolCalls)
52
106
  for (const call of opts.toolCalls)
53
107
  parts.push(encodeMessage(6, encodeToolCall(call)));
108
+ if (opts?.isError)
109
+ parts.push(encodeVarintField(9, 1));
54
110
  for (const image of images)
55
111
  parts.push(encodeMessage(10, encodeImageData(image)));
56
112
  return Buffer.concat(parts);
@@ -120,17 +176,38 @@ function encodeCompletionConfiguration(opts) {
120
176
  buf.writeDoubleLE(value, 0);
121
177
  return Buffer.concat([Buffer.from([(fieldNum << 3) | 1]), buf]);
122
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
123
187
  return Buffer.concat([
124
188
  encodeVarintField(1, 1),
125
- encodeVarintField(2, opts.maxInputTokens ?? 64_000),
126
- encodeVarintField(3, opts.maxOutputTokens ?? 128_000),
189
+ encodeVarintField(2, opts.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS),
190
+ encodeVarintField(3, 128_000),
127
191
  float64(5, opts.temperature ?? 0.7),
128
- float64(6, opts.topP ?? 0.95),
192
+ float64(6, 0.95),
129
193
  encodeVarintField(7, opts.topK ?? 50),
130
- float64(8, 1.0),
194
+ float64(8, opts.topP ?? 1.0),
131
195
  float64(11, 1.0),
132
196
  ]);
133
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
+ }
134
211
  /**
135
212
  * Per-credential Cascade session ids.
136
213
  *
@@ -171,6 +248,7 @@ function buildGetChatMessageRequest(args) {
171
248
  const promptParts = collapsed.map((message) => encodeMessage(3, encodePrompt(normalizeContent(message.content), SOURCE_BY_ROLE[message.role] ?? 1, {
172
249
  toolCallId: message.tool_call_id,
173
250
  toolCalls: message.tool_calls,
251
+ isError: message.is_error,
174
252
  })));
175
253
  // Field layout from mitm capture of the Windsurf language_server:
176
254
  // #1 metadata (message)
@@ -178,16 +256,19 @@ function buildGetChatMessageRequest(args) {
178
256
  // #7 request_type (varint enum, 5 = CASCADE)
179
257
  // #8 completion_configuration (message)
180
258
  // #10 tools (repeated ChatToolDefinition)
259
+ // #12 tool_choice (message, omitted for "auto")
181
260
  // #16 cascade_id (string)
182
261
  // #21 chat_model_uid (string)
183
262
  // #22 prompt_id (string)
184
263
  const toolParts = (args.tools ?? []).map((tool) => encodeMessage(10, encodeToolDef(tool)));
264
+ const toolChoice = args.tools?.length && args.toolChoice ? encodeToolChoice(args.toolChoice) : undefined;
185
265
  return Buffer.concat([
186
266
  encodeMessage(1, metadata),
187
267
  ...promptParts,
188
268
  encodeVarintField(7, 5),
189
269
  encodeMessage(8, encodeCompletionConfiguration(args.completionOpts ?? {})),
190
270
  ...toolParts,
271
+ ...(toolChoice ? [toolChoice] : []),
191
272
  encodeString(16, args.cascadeId),
192
273
  encodeString(21, args.modelUid),
193
274
  encodeString(22, args.promptId),
@@ -320,6 +401,7 @@ export async function* streamChatEvents(request) {
320
401
  modelUid: request.modelUid,
321
402
  messages: request.messages,
322
403
  tools: request.tools,
404
+ toolChoice: request.toolChoice,
323
405
  cascadeId: sessionIds.cascadeId,
324
406
  promptId: crypto.randomUUID(),
325
407
  sessionId: sessionIds.sessionId,
@@ -328,34 +410,61 @@ export async function* streamChatEvents(request) {
328
410
  completionOpts: request.completionOpts,
329
411
  });
330
412
  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
- });
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
+ }
343
445
  if (!response.ok) {
344
446
  const text = await response.text();
345
447
  // A 401 means the cached user_jwt was rejected. Drop it so the next attempt
346
448
  // mints a fresh one instead of replaying a token already known to be bad.
347
449
  if (response.status === 401)
348
450
  clearCachedUserJwt();
349
- throw new CloudChatError(`GetChatMessage HTTP ${response.status}: ${text.slice(0, 300)}`);
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
+ });
350
457
  }
351
458
  if (!response.body)
352
- throw new CloudChatError("GetChatMessage response had no body stream");
459
+ throw new CloudChatError("GetChatMessage response had no body stream", { status: 502, url });
353
460
  const reader = response.body.getReader();
354
461
  const chunks = [];
355
462
  let queuedBytes = 0;
356
463
  let trailerError = null;
357
464
  let sawEos = false;
358
465
  let idleTimer = null;
466
+ let idleTimedOut = false;
467
+ const onAbort = () => cancelBody(request.signal?.reason);
359
468
  /**
360
469
  * Release the response body.
361
470
  *
@@ -405,16 +514,26 @@ export async function* streamChatEvents(request) {
405
514
  try {
406
515
  if (request.signal?.aborted)
407
516
  throw request.signal.reason;
408
- request.signal?.addEventListener("abort", () => cancelBody(request.signal?.reason), { once: true });
517
+ request.signal?.addEventListener("abort", onAbort, { once: true });
409
518
  while (true) {
410
519
  if (idleTimer)
411
520
  clearTimeout(idleTimer);
412
- idleTimer = setTimeout(() => cancelBody(new Error(`idle timeout (${STREAM_IDLE_MS}ms)`)), STREAM_IDLE_MS);
521
+ idleTimer = setTimeout(() => {
522
+ idleTimedOut = true;
523
+ cancelBody(new Error(`idle timeout (${idleMs}ms)`));
524
+ }, idleMs);
413
525
  const { value, done } = await reader.read();
414
526
  if (idleTimer) {
415
527
  clearTimeout(idleTimer);
416
528
  idleTimer = null;
417
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
+ }
418
537
  if (done)
419
538
  break;
420
539
  if (value) {
@@ -438,7 +557,10 @@ export async function* streamChatEvents(request) {
438
557
  payload = zlib.gunzipSync(raw);
439
558
  }
440
559
  catch (cause) {
441
- throw new CloudChatError(`Connect frame gunzip failed: ${cause.message}`);
560
+ throw new CloudChatError(`Connect frame gunzip failed: ${cause.message}`, {
561
+ code: "invalid_frame",
562
+ url,
563
+ });
442
564
  }
443
565
  }
444
566
  if ((flags & 0x02) !== 0) {
@@ -469,6 +591,7 @@ export async function* streamChatEvents(request) {
469
591
  finally {
470
592
  if (idleTimer)
471
593
  clearTimeout(idleTimer);
594
+ request.signal?.removeEventListener("abort", onAbort);
472
595
  // Cancel before releasing: releasing first would detach the reader, after
473
596
  // which the body can no longer be cancelled at all.
474
597
  await cancelBody("stream finished");
@@ -482,15 +605,25 @@ export async function* streamChatEvents(request) {
482
605
  if (trailerError) {
483
606
  const isOpaque = trailerError.code === "permission_denied" && /an internal error occurred/i.test(trailerError.message);
484
607
  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);
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 });
486
609
  }
487
610
  // A token the server rejected mid-stream is just as stale as a 401: the
488
611
  // account may have been reconnected between minting and streaming.
489
- if (isAuthFailure(trailerError.code))
612
+ const staleToken = isAuthFailure(trailerError.code);
613
+ if (staleToken)
490
614
  clearCachedUserJwt();
491
- throw new CloudChatError(trailerError.message, trailerError.code, trailerError.traceId);
615
+ throw new CloudChatError(trailerError.message, {
616
+ code: trailerError.code,
617
+ traceId: trailerError.traceId,
618
+ url,
619
+ retryWithFreshToken: staleToken,
620
+ ...(staleToken ? { status: 401 } : {}),
621
+ });
492
622
  }
493
623
  if (!sawEos) {
494
- throw new CloudChatError("Cloud stream ended without EOS trailer. Connection likely dropped.", "truncated_stream");
624
+ throw new CloudChatError("Cloud stream ended without EOS trailer. Connection likely dropped.", {
625
+ code: "truncated_stream",
626
+ url,
627
+ });
495
628
  }
496
629
  }
@@ -6,15 +6,31 @@
6
6
  * carry their own copy of the same alternation, which is exactly the kind of
7
7
  * duplication that drifts when Cognition adds an effort level.
8
8
  */
9
- /** Valid reasoning effort levels. */
10
- export declare const EFFORT_LEVELS: readonly ["none", "low", "medium", "high", "xhigh", "max"];
9
+ /** Valid reasoning effort levels, weakest first. */
10
+ export declare const EFFORT_LEVELS: readonly ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
11
11
  export type EffortLevel = (typeof EFFORT_LEVELS)[number];
12
12
  /** Narrow an arbitrary value to a known effort level, or `undefined`. */
13
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`. */
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
+ */
15
20
  export declare function splitEffortSuffix(modelUid: string): {
16
21
  baseModelUid: string;
17
22
  effortLevel?: EffortLevel;
18
23
  };
19
- /** Append an effort suffix to a base UID. */
24
+ /** Replace the effort in a UID that has one, or append it to one that does not. */
20
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;
@@ -6,10 +6,8 @@
6
6
  * carry their own copy of the same alternation, which is exactly the kind of
7
7
  * duplication that drifts when Cognition adds an effort level.
8
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("|")})$`);
9
+ /** Valid reasoning effort levels, weakest first. */
10
+ export const EFFORT_LEVELS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
13
11
  /** Narrow an arbitrary value to a known effort level, or `undefined`. */
14
12
  export function toEffortLevel(value) {
15
13
  if (typeof value !== "string")
@@ -17,15 +15,57 @@ export function toEffortLevel(value) {
17
15
  const effort = value.toLowerCase();
18
16
  return EFFORT_LEVELS.includes(effort) ? effort : undefined;
19
17
  }
20
- /** Split a UID into its base UID and effort suffix, e.g. `opus-4-8-high`. */
18
+ /** Effort named by a catalog capability value, e.g. "XHigh" or "No Thinking". */
19
+ export function effortFromLabel(label) {
20
+ if (!label)
21
+ return undefined;
22
+ return /^no thinking$/i.test(label.trim()) ? "none" : toEffortLevel(label.trim());
23
+ }
24
+ /**
25
+ * Index of the effort segment in a UID split on "-".
26
+ *
27
+ * The effort is not always last: speed and context modifiers follow it, as in
28
+ * `claude-opus-5-5-high-fast`, `gpt-5-6-sol-none-priority` and
29
+ * `glm-5-2-max-1m`. The last effort word wins, and the first segment is never
30
+ * one, so a bare effort word is not a suffix.
31
+ */
32
+ function effortIndex(segments) {
33
+ for (let i = segments.length - 1; i > 0; i--) {
34
+ if (toEffortLevel(segments[i]) === segments[i])
35
+ return i;
36
+ }
37
+ return -1;
38
+ }
39
+ /**
40
+ * Split a UID into its base UID and effort, e.g. `opus-4-8-high` into
41
+ * `opus-4-8` and `high`, or `opus-4-8-high-fast` into `opus-4-8-fast` and `high`.
42
+ */
21
43
  export function splitEffortSuffix(modelUid) {
22
- const match = modelUid.match(EFFORT_SUFFIX);
23
- const effortLevel = match?.[1];
24
- if (!effortLevel)
44
+ const segments = modelUid.split("-");
45
+ const index = effortIndex(segments);
46
+ if (index === -1)
25
47
  return { baseModelUid: modelUid };
26
- return { baseModelUid: modelUid.slice(0, -(effortLevel.length + 1)), effortLevel: effortLevel };
48
+ return {
49
+ baseModelUid: [...segments.slice(0, index), ...segments.slice(index + 1)].join("-"),
50
+ effortLevel: segments[index],
51
+ };
27
52
  }
28
- /** Append an effort suffix to a base UID. */
53
+ /** Replace the effort in a UID that has one, or append it to one that does not. */
29
54
  export function withEffortSuffix(modelUid, effort) {
30
- return `${modelUid}-${effort}`;
55
+ const segments = modelUid.split("-");
56
+ const index = effortIndex(segments);
57
+ if (index === -1)
58
+ return `${modelUid}-${effort}`;
59
+ segments[index] = effort;
60
+ return segments.join("-");
61
+ }
62
+ /**
63
+ * The member to use when no effort is asked for: the UID that carries no
64
+ * effort if the family has one, otherwise medium, then high, then the first.
65
+ */
66
+ export function defaultMember(family) {
67
+ return (family.find((member) => member.modelUid === (member.baseModelUid ?? member.modelUid)) ??
68
+ family.find((member) => member.effortLevel === "medium") ??
69
+ family.find((member) => member.effortLevel === "high") ??
70
+ family[0]);
31
71
  }
@@ -8,23 +8,31 @@
8
8
  *
9
9
  * Originally ported from ai-sdk-devin / pi-devin-auth (MIT).
10
10
  */
11
- import type { LanguageModelV3, LanguageModelV3StreamPart, LanguageModelV3Usage } from "@ai-sdk/provider";
12
- import { type ChatEvent } from "./chat.ts";
11
+ import type { LanguageModelV3, LanguageModelV3Prompt, LanguageModelV3StreamPart, LanguageModelV3Usage, SharedV3Warning } from "@ai-sdk/provider";
12
+ import { type ChatEvent, type ChatHistoryItem } from "./chat.ts";
13
13
  import { type ModelCatalogEntry } from "./catalog.ts";
14
14
  /**
15
- * Resolve the actual model UID to send upstream, applying an optional
16
- * reasoning-effort override from providerOptions: swap an existing effort
17
- * suffix, or append one when the catalog lists that variant.
15
+ * Resolve the model UID to send upstream.
16
+ *
17
+ * A model is published once per family, under its UID without the effort, and
18
+ * the effort arrives as `providerOptions.devin.reasoningEffort` from the
19
+ * variant the user picked. Upstream has no effort parameter: each effort is a
20
+ * separate UID, so the choice is made here.
18
21
  *
19
22
  * Exported for tests: this is what the catalog lookup exists for, so it needs
20
23
  * to stay covered independently of the network.
21
24
  */
22
25
  export declare function resolveEffortUid(modelId: string, catalog: readonly ModelCatalogEntry[] | undefined, requestedEffort: unknown): string;
26
+ /** Exported for tests. */
27
+ export declare function convertPrompt(prompt: LanguageModelV3Prompt): {
28
+ messages: ChatHistoryItem[];
29
+ warnings: SharedV3Warning[];
30
+ };
23
31
  /**
24
32
  * Exported for tests: the Cascade event -> AI SDK stream translation is pure,
25
33
  * and interleaved parallel tool calls are the case most likely to regress.
26
34
  */
27
- export declare function convertStreamEvents(events: AsyncGenerator<ChatEvent>, generateId: () => string): AsyncGenerator<LanguageModelV3StreamPart>;
35
+ export declare function convertStreamEvents(events: AsyncGenerator<ChatEvent>, generateId: () => string, warnings?: SharedV3Warning[]): AsyncGenerator<LanguageModelV3StreamPart>;
28
36
  interface CollectedResult {
29
37
  text: string;
30
38
  reasoning: string;