opencode-devin 0.2.2 → 0.2.4

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,142 +0,0 @@
1
- /**
2
- * `GetUserJwt` — mints the short-lived `user_jwt` required by catalog and chat
3
- * RPCs. The long-lived session token alone is not accepted.
4
- *
5
- * The real lifetime comes from the token's own `exp` claim; the cache only
6
- * trusts it, and falls back to {@link FALLBACK_JWT_TTL_SECONDS} when `exp` is
7
- * missing or unparseable. Observed tokens run roughly 24 minutes.
8
- *
9
- * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
10
- */
11
- import { APICallError } from "@ai-sdk/provider";
12
- import { encodeMessage, iterFields } from "./wire.js";
13
- import { buildMetadata } from "./metadata.js";
14
- import { DEFAULT_API_SERVER } from "../constants.js";
15
- const MINT_TIMEOUT_MS = 30_000;
16
- /**
17
- * Assumed lifetime when the token carries no readable `exp`. Deliberately
18
- * shorter than the observed ~24 minutes: a too-short assumption costs one extra
19
- * mint, a too-long one keeps sending a token the server will reject.
20
- */
21
- const FALLBACK_JWT_TTL_SECONDS = 600;
22
- /**
23
- * An `APICallError`, so the host sees the status: a rejected session token is
24
- * then reported as an auth failure instead of being retried as unknown.
25
- */
26
- export class CloudAuthError extends APICallError {
27
- status;
28
- constructor(message, status, url = "") {
29
- // A 200 that carries no token is a server-side fault, not a success.
30
- super({ message, url, requestBodyValues: undefined, statusCode: status >= 400 ? status : 502 });
31
- this.name = "CloudAuthError";
32
- this.status = status;
33
- }
34
- }
35
- /** Mint a fresh user_jwt for the given session token. */
36
- export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
37
- const metadata = buildMetadata({
38
- apiKey,
39
- sessionId: crypto.randomUUID(),
40
- requestId: BigInt(Date.now()),
41
- triggerId: crypto.randomUUID(),
42
- });
43
- const request = encodeMessage(1, metadata);
44
- const timeout = AbortSignal.timeout(MINT_TIMEOUT_MS);
45
- const url = `${host.replace(/\/$/, "")}/exa.auth_pb.AuthService/GetUserJwt`;
46
- const response = await fetch(url, {
47
- method: "POST",
48
- headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
49
- body: new Uint8Array(request),
50
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
51
- });
52
- const buf = Buffer.from(await response.arrayBuffer());
53
- if (!response.ok) {
54
- throw new CloudAuthError(`GetUserJwt HTTP ${response.status}: ${buf.toString("utf8").slice(0, 400)}`, response.status, url);
55
- }
56
- let jwt = null;
57
- for (const field of iterFields(buf)) {
58
- if (field.num === 1 && field.wire === 2 && Buffer.isBuffer(field.value)) {
59
- const candidate = field.value.toString("utf8");
60
- if (/^eyJ[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}$/.test(candidate)) {
61
- jwt = candidate;
62
- break;
63
- }
64
- }
65
- }
66
- if (!jwt) {
67
- throw new CloudAuthError(`GetUserJwt 200 but no field-1 JWT found (${buf.length} bytes)`, response.status, url);
68
- }
69
- let expiresAt = Math.floor(Date.now() / 1000) + FALLBACK_JWT_TTL_SECONDS;
70
- try {
71
- const parts = jwt.split(".");
72
- const pad = (s) => s + "=".repeat((4 - (s.length % 4)) % 4);
73
- const payload = JSON.parse(Buffer.from(pad(parts[1]).replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
74
- if (typeof payload.exp === "number")
75
- expiresAt = payload.exp;
76
- }
77
- catch {
78
- // non-JWT payload — keep the conservative fallback
79
- }
80
- return { jwt, expiresAt };
81
- }
82
- /**
83
- * Separator for composite cache keys.
84
- *
85
- * 0x1F (unit separator) cannot appear in a host or a token, so keys built from
86
- * them are unambiguous. It is spelled as an escape rather than a literal control
87
- * byte so it stays visible in diffs and review: silently dropped by a re-encode,
88
- * `host="a" key="bc"` would collide with `host="ab" key="c"` and two different
89
- * credentials would share a cached session.
90
- */
91
- const KEY_SEPARATOR = "\x1f";
92
- /** Cache key for one credential against one host. */
93
- export const credentialKey = (host, apiKey) => `${host}${KEY_SEPARATOR}${apiKey}`;
94
- let cache = null;
95
- const inFlight = new Map();
96
- let cacheEpoch = 0;
97
- /** Settle with `promise`, or reject as soon as `signal` aborts. */
98
- function untilAborted(promise, signal) {
99
- if (!signal)
100
- return promise;
101
- if (signal.aborted)
102
- return Promise.reject(signal.reason);
103
- return new Promise((resolve, reject) => {
104
- const onAbort = () => reject(signal.reason);
105
- signal.addEventListener("abort", onAbort, { once: true });
106
- promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
107
- });
108
- }
109
- /** Mint a user_jwt, reusing a cached one until shortly before expiry. */
110
- export async function getCachedUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
111
- const now = Math.floor(Date.now() / 1000);
112
- if (cache && cache.apiKey === apiKey && cache.host === host && cache.expiresAt > now + 60) {
113
- return cache.jwt;
114
- }
115
- const key = credentialKey(host, apiKey);
116
- let pending = inFlight.get(key);
117
- if (!pending) {
118
- const epochAtStart = cacheEpoch;
119
- // The mint is shared by every caller waiting on this credential, so it must
120
- // not be tied to one caller's signal: cancelling that request would fail
121
- // the others. It is bounded by its own timeout instead.
122
- const shared = mintUserJwt(apiKey, host)
123
- .then((minted) => {
124
- if (cacheEpoch === epochAtStart)
125
- cache = { ...minted, apiKey, host };
126
- return minted;
127
- })
128
- .finally(() => {
129
- if (inFlight.get(key) === shared)
130
- inFlight.delete(key);
131
- });
132
- inFlight.set(key, shared);
133
- pending = shared;
134
- }
135
- return (await untilAborted(pending, signal)).jwt;
136
- }
137
- /** Drop the cached user_jwt (e.g. after an auth failure). */
138
- export function clearCachedUserJwt() {
139
- cache = null;
140
- inFlight.clear();
141
- cacheEpoch++;
142
- }
@@ -1,69 +0,0 @@
1
- /**
2
- * `GetCascadeModelConfigs` — per-account model catalog from Cognition.
3
- *
4
- * Returns every model UID the subscription can use, with pricing and context
5
- * windows. This is the same source the Devin CLI uses (`GetCliModelConfigs`).
6
- * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
7
- */
8
- import { APICallError } from "@ai-sdk/provider";
9
- export interface ModelPricing {
10
- /** Price per 1M input tokens (USD), or 0 if free. */
11
- input: number;
12
- /** Price per 1M cached input tokens (USD), or 0 if N/A. */
13
- cachedInput: number;
14
- /** Price per 1M output tokens (USD), or 0 if free. */
15
- output: number;
16
- }
17
- export interface ModelCapability {
18
- /** Feature name, e.g. "Effort", "Thinking", "Fast Mode", "1M Context". */
19
- name: string;
20
- enabled: boolean;
21
- /** Optional value, e.g. "Medium" for Effort. */
22
- value?: string;
23
- }
24
- export interface ModelCatalogEntry {
25
- modelUid: string;
26
- label: string;
27
- disabled: boolean;
28
- contextWindow: number;
29
- pricing?: ModelPricing;
30
- capabilities?: ModelCapability[];
31
- /** Model UID without its effort (e.g. "claude-opus-4-8" for "claude-opus-4-8-medium"). */
32
- baseModelUid?: string;
33
- /**
34
- * Reasoning effort this UID runs at: read from the UID, or from the "Effort"
35
- * capability when the UID names none (`glm-5-2` is GLM-5.2 at high).
36
- */
37
- effortLevel?: string;
38
- }
39
- export interface Catalog {
40
- byUid: Map<string, ModelCatalogEntry>;
41
- fetchedAt: number;
42
- apiKey: string;
43
- host: string;
44
- }
45
- /**
46
- * Raised when the account's catalog lists the model but marks it disabled.
47
- *
48
- * Only this case is safe to fail on: the catalog states it explicitly, so the
49
- * upstream request would be rejected regardless. A model that is simply absent
50
- * is *not* asserted on, because the catalog is not guaranteed to enumerate every
51
- * uid Cascade accepts and a false rejection would break a working model.
52
- *
53
- * Reported as a 403 so the host does not retry it: nothing changes between
54
- * attempts.
55
- */
56
- export declare class ModelNotAvailableError extends APICallError {
57
- readonly modelUid: string;
58
- readonly label: string;
59
- constructor(modelUid: string, label: string);
60
- }
61
- /** The catalog as the request path needs it: everything, and the usable subset. */
62
- export interface CatalogSnapshot {
63
- /** Every model the account can see, including ones disabled for its tier. */
64
- readonly entries: readonly ModelCatalogEntry[];
65
- /** The subset currently usable; what the effort-variant lookup resolves against. */
66
- readonly enabled: readonly ModelCatalogEntry[];
67
- }
68
- /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
69
- export declare function getCachedCatalog(apiKey: string, host?: string, signal?: AbortSignal): Promise<Catalog | null>;
@@ -1,230 +0,0 @@
1
- /**
2
- * `GetCascadeModelConfigs` — per-account model catalog from Cognition.
3
- *
4
- * Returns every model UID the subscription can use, with pricing and context
5
- * windows. This is the same source the Devin CLI uses (`GetCliModelConfigs`).
6
- * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
7
- */
8
- import { APICallError } from "@ai-sdk/provider";
9
- import { encodeMessage, iterFields } from "./wire.js";
10
- import { buildMetadata } from "./metadata.js";
11
- import { clearCachedUserJwt, credentialKey, getCachedUserJwt } from "./auth.js";
12
- import { effortFromLabel, splitEffortSuffix } from "./effort.js";
13
- import { DEFAULT_API_SERVER } from "../constants.js";
14
- const CATALOG_TTL_MS = 10 * 60 * 1000;
15
- const CATALOG_FETCH_TIMEOUT_MS = 10_000;
16
- /**
17
- * Raised when the account's catalog lists the model but marks it disabled.
18
- *
19
- * Only this case is safe to fail on: the catalog states it explicitly, so the
20
- * upstream request would be rejected regardless. A model that is simply absent
21
- * is *not* asserted on, because the catalog is not guaranteed to enumerate every
22
- * uid Cascade accepts and a false rejection would break a working model.
23
- *
24
- * Reported as a 403 so the host does not retry it: nothing changes between
25
- * attempts.
26
- */
27
- export class ModelNotAvailableError extends APICallError {
28
- modelUid;
29
- label;
30
- constructor(modelUid, label) {
31
- super({
32
- message: label && label !== modelUid
33
- ? `Model "${label}" (uid=${modelUid}) is not enabled for your Cognition account tier.`
34
- : `Model uid "${modelUid}" is not enabled for your Cognition account tier.`,
35
- url: "",
36
- requestBodyValues: undefined,
37
- statusCode: 403,
38
- });
39
- this.name = "ModelNotAvailableError";
40
- this.modelUid = modelUid;
41
- this.label = label;
42
- }
43
- }
44
- async function fetchCatalog(apiKey, host, signal) {
45
- const userJwt = await getCachedUserJwt(apiKey, host, signal);
46
- const metadata = buildMetadata({
47
- apiKey,
48
- userJwt,
49
- sessionId: crypto.randomUUID(),
50
- requestId: BigInt(Date.now()),
51
- triggerId: crypto.randomUUID(),
52
- });
53
- const request = encodeMessage(1, metadata);
54
- const timeout = AbortSignal.timeout(CATALOG_FETCH_TIMEOUT_MS);
55
- const response = await fetch(`${host}/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs`, {
56
- method: "POST",
57
- headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
58
- body: new Uint8Array(request),
59
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
60
- });
61
- if (!response.ok) {
62
- const text = await response.text();
63
- // A 401 means the cached user_jwt was rejected. Drop it so the next attempt
64
- // mints a fresh one instead of replaying a token already known to be bad.
65
- if (response.status === 401)
66
- clearCachedUserJwt();
67
- throw new Error(`GetCascadeModelConfigs HTTP ${response.status}: ${text.slice(0, 200)}`);
68
- }
69
- const buf = Buffer.from(await response.arrayBuffer());
70
- const byUid = new Map();
71
- for (const field of iterFields(buf)) {
72
- if (field.num !== 1 || field.wire !== 2 || !Buffer.isBuffer(field.value))
73
- continue;
74
- const entry = decodeModelConfig(field.value);
75
- if (entry)
76
- byUid.set(entry.modelUid, entry);
77
- }
78
- return { byUid, fetchedAt: Date.now(), apiKey, host };
79
- }
80
- function decodeModelConfig(buf) {
81
- let label = "";
82
- let modelUid = "";
83
- let disabled = false;
84
- let contextWindow = 0;
85
- let pricing;
86
- let capabilities;
87
- for (const field of iterFields(buf)) {
88
- if (field.num === 1 && field.wire === 2 && Buffer.isBuffer(field.value)) {
89
- label = field.value.toString("utf8");
90
- }
91
- else if (field.num === 4 && field.wire === 0) {
92
- disabled = field.value === 1n;
93
- }
94
- else if (field.num === 18 && field.wire === 0) {
95
- contextWindow = Number(field.value);
96
- }
97
- else if (field.num === 22 && field.wire === 2 && Buffer.isBuffer(field.value)) {
98
- modelUid = field.value.toString("utf8");
99
- }
100
- else if (field.num === 30 && field.wire === 2 && Buffer.isBuffer(field.value)) {
101
- // Capabilities message: #1 display name, #2 (repeated) feature
102
- // { #1 name, #2 state { #1 level, #2 value } }. The level is 1 for an
103
- // on/off feature that is on, and the rank of the effort for "Effort".
104
- capabilities = [];
105
- for (const feature of iterFields(field.value)) {
106
- if (feature.num !== 2 || feature.wire !== 2 || !Buffer.isBuffer(feature.value))
107
- continue;
108
- let name = "";
109
- let enabled = false;
110
- let value;
111
- for (const part of iterFields(feature.value)) {
112
- if (part.num === 1 && part.wire === 2 && Buffer.isBuffer(part.value)) {
113
- name = part.value.toString("utf8");
114
- }
115
- else if (part.num === 2 && part.wire === 2 && Buffer.isBuffer(part.value)) {
116
- // The state is a nested message. Reading it as a string, as this
117
- // used to, yielded its raw bytes and never set `enabled`.
118
- for (const state of iterFields(part.value)) {
119
- if (state.num === 1 && state.wire === 0)
120
- enabled = state.value !== 0n;
121
- else if (state.num === 2 && state.wire === 2 && Buffer.isBuffer(state.value)) {
122
- value = state.value.toString("utf8");
123
- }
124
- }
125
- }
126
- }
127
- if (name)
128
- capabilities.push({ name, enabled, value });
129
- }
130
- }
131
- else if (field.num === 32 && field.wire === 2 && Buffer.isBuffer(field.value)) {
132
- // Pricing message (repeated), verified against a live
133
- // GetCascadeModelConfigs dump and the prices shown in the Devin app
134
- // (e.g. claude-opus-5-5 = $4/$20, claude-sonnet-5-5 = $2/$10):
135
- // #1 type string "Input" | "Cached input" | "Output"
136
- // #2 price float32 USD per unit (#3 = "1M tokens") ← real price
137
- // #3 unit string "1M tokens"
138
- // #4 factor float32 per-type constant (0.1/0.007/0.28) —
139
- // internal credit coefficient, NOT the price.
140
- // This is what the old code read by mistake.
141
- // #5 credits float32 same price expressed in Cognition credits
142
- // #6 flag varint 1
143
- // #7 note string e.g. "Higher effort consumes more tokens"
144
- pricing ??= { input: 0, cachedInput: 0, output: 0 };
145
- let type = "";
146
- let price = 0;
147
- for (const part of iterFields(field.value)) {
148
- if (part.num === 1 && part.wire === 2 && Buffer.isBuffer(part.value)) {
149
- type = part.value.toString("utf8").toLowerCase();
150
- }
151
- else if (part.num === 2 &&
152
- part.wire === 5 &&
153
- Buffer.isBuffer(part.value) &&
154
- part.value.length === 4) {
155
- price = part.value.readFloatLE(0);
156
- }
157
- }
158
- // Match the pricing dimension by exact label, not substring: the REST
159
- // API documents extra labels like "sidekick_input" (Fusion models) and
160
- // "cache_read"/"cache_write" that would corrupt a substring match.
161
- // Normalise case/spacing defensively — the wire strings are the same
162
- // labels the REST API exposes in snake_case.
163
- const normalized = type.trim().toLowerCase().replace(/[\s-]+/g, "_");
164
- if (normalized === "input")
165
- pricing.input = price;
166
- else if (normalized === "cached_input" || normalized === "cache_read")
167
- pricing.cachedInput = price;
168
- else if (normalized === "output")
169
- pricing.output = price;
170
- }
171
- }
172
- if (modelUid.length === 0)
173
- return undefined;
174
- const split = splitEffortSuffix(modelUid);
175
- const baseModelUid = split.baseModelUid;
176
- const effortLevel = split.effortLevel ?? effortFromLabel(capabilities?.find((capability) => /^(reasoning )?effort$/i.test(capability.name))?.value);
177
- return {
178
- modelUid,
179
- label: label || modelUid,
180
- disabled,
181
- contextWindow,
182
- pricing,
183
- capabilities,
184
- baseModelUid,
185
- effortLevel,
186
- };
187
- }
188
- let cached = null;
189
- let inFlight = null;
190
- let inFlightKey = null;
191
- const flightKey = (apiKey, host) => credentialKey(host, apiKey);
192
- /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
193
- export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal) {
194
- if (cached && cached.apiKey === apiKey && cached.host === host && Date.now() - cached.fetchedAt < CATALOG_TTL_MS) {
195
- return cached;
196
- }
197
- const key = flightKey(apiKey, host);
198
- if (inFlight && inFlightKey === key) {
199
- try {
200
- return await inFlight;
201
- }
202
- catch {
203
- return null;
204
- }
205
- }
206
- const promise = fetchCatalog(apiKey, host, signal);
207
- // Logged once, where the fetch is owned. The visible symptom is an empty
208
- // `/models` list, and without this nothing says why. A caller cancelling its
209
- // own request is not a failure worth reporting.
210
- promise.catch((error) => {
211
- if (!signal?.aborted)
212
- console.warn("[opencode-devin] could not load the model catalog:", error);
213
- });
214
- inFlight = promise;
215
- inFlightKey = key;
216
- try {
217
- const result = await promise;
218
- cached = result;
219
- return result;
220
- }
221
- catch {
222
- return null;
223
- }
224
- finally {
225
- if (inFlight === promise) {
226
- inFlight = null;
227
- inFlightKey = null;
228
- }
229
- }
230
- }
@@ -1,128 +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 { 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 {
31
- readonly code?: string;
32
- readonly traceId?: string;
33
- constructor(message: string, options?: CloudChatErrorOptions);
34
- }
35
- /** Cognition rejects source=3 for system; system content is inlined into user turns. */
36
- declare const SOURCE_BY_ROLE: {
37
- readonly user: 1;
38
- readonly assistant: 2;
39
- readonly system: 1;
40
- readonly tool: 4;
41
- };
42
- export type ChatRole = keyof typeof SOURCE_BY_ROLE;
43
- export interface ChatImage {
44
- mimeType: string;
45
- base64Data: string;
46
- caption?: string;
47
- }
48
- export type ChatContent = string | Array<{
49
- type: "text";
50
- text: string;
51
- } | ({
52
- type: "image";
53
- } & ChatImage)>;
54
- export interface ChatToolCall {
55
- id: string;
56
- name: string;
57
- arguments: string;
58
- }
59
- export interface ChatHistoryItem {
60
- role: ChatRole;
61
- content: ChatContent;
62
- tool_call_id?: string;
63
- tool_calls?: ChatToolCall[];
64
- /** For a tool message: the tool reported a failure. */
65
- is_error?: boolean;
66
- }
67
- export type ChatToolChoice = {
68
- type: "auto" | "none" | "required";
69
- } | {
70
- type: "tool";
71
- toolName: string;
72
- };
73
- export interface ChatToolDefinition {
74
- name: string;
75
- description?: string;
76
- parameters?: unknown;
77
- }
78
- export interface CompletionOptions {
79
- maxOutputTokens?: number;
80
- temperature?: number;
81
- topP?: number;
82
- topK?: number;
83
- }
84
- export type ChatEvent = {
85
- kind: "text";
86
- text: string;
87
- } | {
88
- kind: "reasoning";
89
- text: string;
90
- } | {
91
- kind: "tool_call_start";
92
- id: string;
93
- name: string;
94
- } | {
95
- kind: "tool_call_args";
96
- argsDelta: string;
97
- id?: string;
98
- } | {
99
- kind: "finish";
100
- reason: string;
101
- } | {
102
- kind: "usage";
103
- promptTokens?: number;
104
- completionTokens?: number;
105
- totalTokens?: number;
106
- cachedInputTokens?: number;
107
- cacheCreationInputTokens?: number;
108
- reasoningTokens?: number;
109
- };
110
- export interface StreamChatRequest {
111
- apiKey: string;
112
- apiServerUrl?: string;
113
- modelUid: string;
114
- messages: ChatHistoryItem[];
115
- tools?: ChatToolDefinition[];
116
- toolChoice?: ChatToolChoice;
117
- cascadeId?: string;
118
- completionOpts?: CompletionOptions;
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
- };
125
- }
126
- /** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
127
- export declare function streamChatEvents(request: StreamChatRequest): AsyncGenerator<ChatEvent>;
128
- export {};