opencode-devin 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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());
@@ -110,10 +135,7 @@ function decodeModelConfig(buf) {
110
135
  }
111
136
  if (modelUid.length === 0)
112
137
  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;
138
+ const { baseModelUid, effortLevel } = splitEffortSuffix(modelUid);
117
139
  return {
118
140
  modelUid,
119
141
  label: label || modelUid,
@@ -128,7 +150,7 @@ function decodeModelConfig(buf) {
128
150
  let cached = null;
129
151
  let inFlight = null;
130
152
  let inFlightKey = null;
131
- const flightKey = (apiKey, host) => `${host}${apiKey}`;
153
+ const flightKey = (apiKey, host) => credentialKey(host, apiKey);
132
154
  /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
133
155
  export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal) {
134
156
  if (cached && cached.apiKey === apiKey && cached.host === host && Date.now() - cached.fetchedAt < CATALOG_TTL_MS) {
@@ -161,22 +183,3 @@ export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal
161
183
  }
162
184
  }
163
185
  }
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 {};