opencode-devin 0.1.1 → 0.2.1

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.
@@ -7,10 +7,31 @@
7
7
  */
8
8
  import { encodeMessage, iterFields } from "./wire.js";
9
9
  import { buildMetadata } from "./metadata.js";
10
- import { getCachedUserJwt } from "./auth.js";
10
+ import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
11
+ import { splitEffortSuffix } from "./effort.js";
11
12
  import { DEFAULT_API_SERVER } from "../constants.js";
12
13
  const CATALOG_TTL_MS = 10 * 60 * 1000;
13
14
  const CATALOG_FETCH_TIMEOUT_MS = 10_000;
15
+ /**
16
+ * Raised when the account's catalog lists the model but marks it disabled.
17
+ *
18
+ * Only this case is safe to fail on: the catalog states it explicitly, so the
19
+ * upstream request would be rejected regardless. A model that is simply absent
20
+ * is *not* asserted on, because the catalog is not guaranteed to enumerate every
21
+ * uid Cascade accepts and a false rejection would break a working model.
22
+ */
23
+ export class ModelNotAvailableError extends Error {
24
+ modelUid;
25
+ label;
26
+ constructor(modelUid, label) {
27
+ super(label && label !== modelUid
28
+ ? `Model "${label}" (uid=${modelUid}) is not enabled for your Cognition account tier.`
29
+ : `Model uid "${modelUid}" is not enabled for your Cognition account tier.`);
30
+ this.name = "ModelNotAvailableError";
31
+ this.modelUid = modelUid;
32
+ this.label = label;
33
+ }
34
+ }
14
35
  async function fetchCatalog(apiKey, host, signal) {
15
36
  const userJwt = await getCachedUserJwt(apiKey, host, signal);
16
37
  const metadata = buildMetadata({
@@ -30,6 +51,10 @@ async function fetchCatalog(apiKey, host, signal) {
30
51
  });
31
52
  if (!response.ok) {
32
53
  const text = await response.text();
54
+ // A 401 means the cached user_jwt was rejected. Drop it so the next attempt
55
+ // mints a fresh one instead of replaying a token already known to be bad.
56
+ if (response.status === 401)
57
+ clearCachedUserJwt();
33
58
  throw new Error(`GetCascadeModelConfigs HTTP ${response.status}: ${text.slice(0, 200)}`);
34
59
  }
35
60
  const buf = Buffer.from(await response.arrayBuffer());
@@ -88,7 +113,18 @@ function decodeModelConfig(buf) {
88
113
  }
89
114
  }
90
115
  else if (field.num === 32 && field.wire === 2 && Buffer.isBuffer(field.value)) {
91
- // Pricing message (repeated): #1 type, #4 price (float32 LE)
116
+ // Pricing message (repeated), verified against a live
117
+ // GetCascadeModelConfigs dump and the prices shown in the Devin app
118
+ // (e.g. claude-opus-5-5 = $4/$20, claude-sonnet-5-5 = $2/$10):
119
+ // #1 type string "Input" | "Cached input" | "Output"
120
+ // #2 price float32 USD per unit (#3 = "1M tokens") ← real price
121
+ // #3 unit string "1M tokens"
122
+ // #4 factor float32 per-type constant (0.1/0.007/0.28) —
123
+ // internal credit coefficient, NOT the price.
124
+ // This is what the old code read by mistake.
125
+ // #5 credits float32 same price expressed in Cognition credits
126
+ // #6 flag varint 1
127
+ // #7 note string e.g. "Higher effort consumes more tokens"
92
128
  pricing ??= { input: 0, cachedInput: 0, output: 0 };
93
129
  let type = "";
94
130
  let price = 0;
@@ -96,24 +132,30 @@ function decodeModelConfig(buf) {
96
132
  if (part.num === 1 && part.wire === 2 && Buffer.isBuffer(part.value)) {
97
133
  type = part.value.toString("utf8").toLowerCase();
98
134
  }
99
- else if (part.num === 4 && Buffer.isBuffer(part.value) && part.value.length === 4) {
135
+ else if (part.num === 2 &&
136
+ part.wire === 5 &&
137
+ Buffer.isBuffer(part.value) &&
138
+ part.value.length === 4) {
100
139
  price = part.value.readFloatLE(0);
101
140
  }
102
141
  }
103
- if (type.includes("input") && !type.includes("cached"))
142
+ // Match the pricing dimension by exact label, not substring: the REST
143
+ // API documents extra labels like "sidekick_input" (Fusion models) and
144
+ // "cache_read"/"cache_write" that would corrupt a substring match.
145
+ // Normalise case/spacing defensively — the wire strings are the same
146
+ // labels the REST API exposes in snake_case.
147
+ const normalized = type.trim().toLowerCase().replace(/[\s-]+/g, "_");
148
+ if (normalized === "input")
104
149
  pricing.input = price;
105
- else if (type.includes("cached"))
150
+ else if (normalized === "cached_input" || normalized === "cache_read")
106
151
  pricing.cachedInput = price;
107
- else if (type.includes("output"))
152
+ else if (normalized === "output")
108
153
  pricing.output = price;
109
154
  }
110
155
  }
111
156
  if (modelUid.length === 0)
112
157
  return undefined;
113
- // Extract the effort level from the UID suffix
114
- const effortMatch = modelUid.match(/-(none|low|medium|high|xhigh|max)$/);
115
- const effortLevel = effortMatch?.[1];
116
- const baseModelUid = effortLevel ? modelUid.slice(0, -effortLevel.length - 1) : undefined;
158
+ const { baseModelUid, effortLevel } = splitEffortSuffix(modelUid);
117
159
  return {
118
160
  modelUid,
119
161
  label: label || modelUid,
@@ -128,7 +170,7 @@ function decodeModelConfig(buf) {
128
170
  let cached = null;
129
171
  let inFlight = null;
130
172
  let inFlightKey = null;
131
- const flightKey = (apiKey, host) => `${host}${apiKey}`;
173
+ const flightKey = (apiKey, host) => credentialKey(host, apiKey);
132
174
  /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
133
175
  export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal) {
134
176
  if (cached && cached.apiKey === apiKey && cached.host === host && Date.now() - cached.fetchedAt < CATALOG_TTL_MS) {
@@ -161,22 +203,3 @@ export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal
161
203
  }
162
204
  }
163
205
  }
164
- export function clearCachedCatalog() {
165
- cached = null;
166
- inFlight = null;
167
- inFlightKey = null;
168
- }
169
- export class ModelNotAvailableError extends Error {
170
- modelUid;
171
- label;
172
- reason;
173
- constructor(modelUid, label, reason) {
174
- super(reason === "disabled"
175
- ? `Model "${label}" (uid=${modelUid}) is not enabled for your Cognition account tier.`
176
- : `Model uid "${modelUid}" is not listed in the Cognition catalog for your account.`);
177
- this.name = "ModelNotAvailableError";
178
- this.modelUid = modelUid;
179
- this.label = label;
180
- this.reason = reason;
181
- }
182
- }
@@ -7,7 +7,7 @@
7
7
  import * as zlib from "node:zlib";
8
8
  import { encodeMessage, encodeString, encodeVarintField, frameConnectStream, iterFields, } from "./wire.js";
9
9
  import { buildMetadata } from "./metadata.js";
10
- import { getCachedUserJwt } from "./auth.js";
10
+ import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
11
11
  import { DEFAULT_API_SERVER } from "../constants.js";
12
12
  const STREAM_IDLE_MS = 120_000;
13
13
  const STREAM_TTFB_MS = 60_000;
@@ -131,12 +131,26 @@ function encodeCompletionConfiguration(opts) {
131
131
  float64(11, 1.0),
132
132
  ]);
133
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;
134
143
  const sessionCache = new Map();
135
144
  function getOrAllocateSessionIds(apiKey, host, cascadeIdOverride) {
136
- const key = `${host}${apiKey}`;
145
+ const key = credentialKey(host, apiKey);
137
146
  let ids = sessionCache.get(key);
138
147
  if (!ids) {
139
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
+ }
140
154
  sessionCache.set(key, ids);
141
155
  }
142
156
  else if (cascadeIdOverride && ids.cascadeId !== cascadeIdOverride) {
@@ -290,6 +304,11 @@ function decodeUsageBlock(buf) {
290
304
  };
291
305
  }
292
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";
293
312
  /** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
294
313
  export async function* streamChatEvents(request) {
295
314
  const host = (request.apiServerUrl ?? DEFAULT_API_SERVER).replace(/\/$/, "");
@@ -323,6 +342,10 @@ export async function* streamChatEvents(request) {
323
342
  });
324
343
  if (!response.ok) {
325
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();
326
349
  throw new CloudChatError(`GetChatMessage HTTP ${response.status}: ${text.slice(0, 300)}`);
327
350
  }
328
351
  if (!response.body)
@@ -333,14 +356,16 @@ export async function* streamChatEvents(request) {
333
356
  let trailerError = null;
334
357
  let sawEos = false;
335
358
  let idleTimer = null;
336
- const cancelBody = (reason) => {
337
- try {
338
- void response.body?.cancel(reason);
339
- }
340
- catch {
341
- // already cancelled
342
- }
343
- };
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(() => { });
344
369
  const peek = (n) => {
345
370
  if (queuedBytes < n)
346
371
  return null;
@@ -444,19 +469,25 @@ export async function* streamChatEvents(request) {
444
469
  finally {
445
470
  if (idleTimer)
446
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");
447
475
  try {
448
476
  reader.releaseLock();
449
477
  }
450
478
  catch {
451
479
  // lock already released
452
480
  }
453
- cancelBody();
454
481
  }
455
482
  if (trailerError) {
456
483
  const isOpaque = trailerError.code === "permission_denied" && /an internal error occurred/i.test(trailerError.message);
457
484
  if (isOpaque) {
458
485
  throw new CloudChatError(`Cognition denied model access for "${request.modelUid}". Check your account tier. (trace: ${trailerError.traceId ?? "n/a"})`, trailerError.code, trailerError.traceId);
459
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();
460
491
  throw new CloudChatError(trailerError.message, trailerError.code, trailerError.traceId);
461
492
  }
462
493
  if (!sawEos) {
@@ -0,0 +1,20 @@
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;
@@ -0,0 +1,31 @@
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
+ }
@@ -8,25 +8,42 @@
8
8
  *
9
9
  * Originally ported from ai-sdk-devin / pi-devin-auth (MIT).
10
10
  */
11
- import type { LanguageModelV3 } from "@ai-sdk/provider";
11
+ import type { LanguageModelV3, LanguageModelV3StreamPart, LanguageModelV3Usage } from "@ai-sdk/provider";
12
+ import { type ChatEvent } from "./chat.ts";
12
13
  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;
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.
18
+ *
19
+ * Exported for tests: this is what the catalog lookup exists for, so it needs
20
+ * to stay covered independently of the network.
21
+ */
22
+ export declare function resolveEffortUid(modelId: string, catalog: readonly ModelCatalogEntry[] | undefined, requestedEffort: unknown): string;
23
+ /**
24
+ * Exported for tests: the Cascade event -> AI SDK stream translation is pure,
25
+ * and interleaved parallel tool calls are the case most likely to regress.
26
+ */
27
+ export declare function convertStreamEvents(events: AsyncGenerator<ChatEvent>, generateId: () => string): AsyncGenerator<LanguageModelV3StreamPart>;
28
+ interface CollectedResult {
29
+ text: string;
30
+ reasoning: string;
31
+ toolCalls: {
32
+ id: string;
33
+ name: string;
34
+ args: string;
35
+ }[];
36
+ finishReason: string;
37
+ usage?: LanguageModelV3Usage;
38
+ }
39
+ /** Exported for tests; mirrors `convertStreamEvents` for the non-streaming path. */
40
+ export declare function collectEvents(events: AsyncGenerator<ChatEvent>): Promise<CollectedResult>;
22
41
  export interface DevinProviderOptions {
23
42
  apiKey: string;
24
43
  baseURL?: string;
25
44
  }
26
45
  export interface DevinProvider {
27
46
  languageModel(modelId: string): LanguageModelV3;
28
- /** Fetch the live model catalog for this account. Returns all enabled models. */
29
- models(): Promise<ModelCatalogEntry[]>;
30
47
  }
31
48
  export declare function createDevin(options: DevinProviderOptions): DevinProvider;
32
49
  export {};