opencode-devin 0.1.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.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `GetUserJwt` — mints the short-lived `user_jwt` required by catalog and chat
3
+ * RPCs (~24 min TTL). The long-lived session token alone is not accepted.
4
+ *
5
+ * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
6
+ */
7
+ export declare class CloudAuthError extends Error {
8
+ readonly status: number;
9
+ constructor(message: string, status: number);
10
+ }
11
+ export interface UserJwt {
12
+ jwt: string;
13
+ expiresAt: number;
14
+ }
15
+ /** Mint a fresh user_jwt for the given session token. */
16
+ export declare function mintUserJwt(apiKey: string, host?: string, signal?: AbortSignal): Promise<UserJwt>;
17
+ /** Mint a user_jwt, reusing a cached one until shortly before expiry. */
18
+ export declare function getCachedUserJwt(apiKey: string, host?: string, signal?: AbortSignal): Promise<string>;
19
+ /** Drop the cached user_jwt (e.g. after an auth failure). */
20
+ export declare function clearCachedUserJwt(): void;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `GetUserJwt` — mints the short-lived `user_jwt` required by catalog and chat
3
+ * RPCs (~24 min TTL). The long-lived session token alone is not accepted.
4
+ *
5
+ * Originally ported from pi-devin-auth (MIT, Copyright (c) 2026 nmzpy).
6
+ */
7
+ import { encodeMessage, iterFields } from "./wire.js";
8
+ import { buildMetadata } from "./metadata.js";
9
+ import { DEFAULT_API_SERVER } from "../constants.js";
10
+ const MINT_TIMEOUT_MS = 30_000;
11
+ export class CloudAuthError extends Error {
12
+ status;
13
+ constructor(message, status) {
14
+ super(message);
15
+ this.name = "CloudAuthError";
16
+ this.status = status;
17
+ }
18
+ }
19
+ /** Mint a fresh user_jwt for the given session token. */
20
+ export async function mintUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
21
+ const metadata = buildMetadata({
22
+ apiKey,
23
+ sessionId: crypto.randomUUID(),
24
+ requestId: BigInt(Date.now()),
25
+ triggerId: crypto.randomUUID(),
26
+ });
27
+ const request = encodeMessage(1, metadata);
28
+ const timeout = AbortSignal.timeout(MINT_TIMEOUT_MS);
29
+ const response = await fetch(`${host.replace(/\/$/, "")}/exa.auth_pb.AuthService/GetUserJwt`, {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
32
+ body: new Uint8Array(request),
33
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
34
+ });
35
+ const buf = Buffer.from(await response.arrayBuffer());
36
+ if (!response.ok) {
37
+ throw new CloudAuthError(`GetUserJwt HTTP ${response.status}: ${buf.toString("utf8").slice(0, 400)}`, response.status);
38
+ }
39
+ let jwt = null;
40
+ for (const field of iterFields(buf)) {
41
+ if (field.num === 1 && field.wire === 2 && Buffer.isBuffer(field.value)) {
42
+ const candidate = field.value.toString("utf8");
43
+ if (/^eyJ[A-Za-z0-9_-]{10,}={0,2}\.[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}$/.test(candidate)) {
44
+ jwt = candidate;
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ if (!jwt) {
50
+ throw new CloudAuthError(`GetUserJwt 200 but no field-1 JWT found (${buf.length} bytes)`, response.status);
51
+ }
52
+ let expiresAt = Math.floor(Date.now() / 1000) + 600;
53
+ try {
54
+ const parts = jwt.split(".");
55
+ const pad = (s) => s + "=".repeat((4 - (s.length % 4)) % 4);
56
+ const payload = JSON.parse(Buffer.from(pad(parts[1]).replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
57
+ if (typeof payload.exp === "number")
58
+ expiresAt = payload.exp;
59
+ }
60
+ catch {
61
+ // non-JWT payload — keep the 10-minute fallback
62
+ }
63
+ return { jwt, expiresAt };
64
+ }
65
+ let cache = null;
66
+ const inFlight = new Map();
67
+ let cacheEpoch = 0;
68
+ /** Mint a user_jwt, reusing a cached one until shortly before expiry. */
69
+ export async function getCachedUserJwt(apiKey, host = DEFAULT_API_SERVER, signal) {
70
+ const now = Math.floor(Date.now() / 1000);
71
+ if (cache && cache.apiKey === apiKey && cache.host === host && cache.expiresAt > now + 60) {
72
+ return cache.jwt;
73
+ }
74
+ const key = `${host}${apiKey}`;
75
+ const pending = inFlight.get(key);
76
+ if (pending)
77
+ return (await pending).jwt;
78
+ const promise = mintUserJwt(apiKey, host, signal);
79
+ inFlight.set(key, promise);
80
+ const epochAtStart = cacheEpoch;
81
+ try {
82
+ const minted = await promise;
83
+ if (cacheEpoch === epochAtStart) {
84
+ cache = { ...minted, apiKey, host };
85
+ }
86
+ return minted.jwt;
87
+ }
88
+ finally {
89
+ inFlight.delete(key);
90
+ }
91
+ }
92
+ /** Drop the cached user_jwt (e.g. after an auth failure). */
93
+ export function clearCachedUserJwt() {
94
+ cache = null;
95
+ inFlight.clear();
96
+ cacheEpoch++;
97
+ }
@@ -0,0 +1,49 @@
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
+ export interface ModelPricing {
9
+ /** Price per 1M input tokens (USD), or 0 if free. */
10
+ input: number;
11
+ /** Price per 1M cached input tokens (USD), or 0 if N/A. */
12
+ cachedInput: number;
13
+ /** Price per 1M output tokens (USD), or 0 if free. */
14
+ output: number;
15
+ }
16
+ export interface ModelCapability {
17
+ /** Feature name, e.g. "Effort", "Thinking", "Fast Mode", "1M Context". */
18
+ name: string;
19
+ enabled: boolean;
20
+ /** Optional value, e.g. "Medium" for Effort. */
21
+ value?: string;
22
+ }
23
+ export interface ModelCatalogEntry {
24
+ modelUid: string;
25
+ label: string;
26
+ disabled: boolean;
27
+ contextWindow: number;
28
+ pricing?: ModelPricing;
29
+ capabilities?: ModelCapability[];
30
+ /** Base model UID without the effort suffix (e.g. "claude-opus-4-8" for "claude-opus-4-8-medium"). */
31
+ baseModelUid?: string;
32
+ /** Reasoning effort level if encoded in the UID (none/low/medium/high/xhigh/max). */
33
+ effortLevel?: string;
34
+ }
35
+ export interface Catalog {
36
+ byUid: Map<string, ModelCatalogEntry>;
37
+ fetchedAt: number;
38
+ apiKey: string;
39
+ host: string;
40
+ }
41
+ /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
42
+ export declare function getCachedCatalog(apiKey: string, host?: string, signal?: AbortSignal): Promise<Catalog | null>;
43
+ export declare function clearCachedCatalog(): void;
44
+ export declare class ModelNotAvailableError extends Error {
45
+ readonly modelUid: string;
46
+ readonly label: string;
47
+ readonly reason: "disabled" | "not_listed";
48
+ constructor(modelUid: string, label: string, reason: "disabled" | "not_listed");
49
+ }
@@ -0,0 +1,182 @@
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 { encodeMessage, iterFields } from "./wire.js";
9
+ import { buildMetadata } from "./metadata.js";
10
+ import { getCachedUserJwt } from "./auth.js";
11
+ import { DEFAULT_API_SERVER } from "../constants.js";
12
+ const CATALOG_TTL_MS = 10 * 60 * 1000;
13
+ const CATALOG_FETCH_TIMEOUT_MS = 10_000;
14
+ async function fetchCatalog(apiKey, host, signal) {
15
+ const userJwt = await getCachedUserJwt(apiKey, host, signal);
16
+ const metadata = buildMetadata({
17
+ apiKey,
18
+ userJwt,
19
+ sessionId: crypto.randomUUID(),
20
+ requestId: BigInt(Date.now()),
21
+ triggerId: crypto.randomUUID(),
22
+ });
23
+ const request = encodeMessage(1, metadata);
24
+ const timeout = AbortSignal.timeout(CATALOG_FETCH_TIMEOUT_MS);
25
+ const response = await fetch(`${host}/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs`, {
26
+ method: "POST",
27
+ headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
28
+ body: new Uint8Array(request),
29
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
30
+ });
31
+ if (!response.ok) {
32
+ const text = await response.text();
33
+ throw new Error(`GetCascadeModelConfigs HTTP ${response.status}: ${text.slice(0, 200)}`);
34
+ }
35
+ const buf = Buffer.from(await response.arrayBuffer());
36
+ const byUid = new Map();
37
+ for (const field of iterFields(buf)) {
38
+ if (field.num !== 1 || field.wire !== 2 || !Buffer.isBuffer(field.value))
39
+ continue;
40
+ const entry = decodeModelConfig(field.value);
41
+ if (entry)
42
+ byUid.set(entry.modelUid, entry);
43
+ }
44
+ return { byUid, fetchedAt: Date.now(), apiKey, host };
45
+ }
46
+ function decodeModelConfig(buf) {
47
+ let label = "";
48
+ let modelUid = "";
49
+ let disabled = false;
50
+ let contextWindow = 0;
51
+ let pricing;
52
+ let capabilities;
53
+ for (const field of iterFields(buf)) {
54
+ if (field.num === 1 && field.wire === 2 && Buffer.isBuffer(field.value)) {
55
+ label = field.value.toString("utf8");
56
+ }
57
+ else if (field.num === 4 && field.wire === 0) {
58
+ disabled = field.value === 1n;
59
+ }
60
+ else if (field.num === 18 && field.wire === 0) {
61
+ contextWindow = Number(field.value);
62
+ }
63
+ else if (field.num === 22 && field.wire === 2 && Buffer.isBuffer(field.value)) {
64
+ modelUid = field.value.toString("utf8");
65
+ }
66
+ else if (field.num === 30 && field.wire === 2 && Buffer.isBuffer(field.value)) {
67
+ // Capabilities message: #1 display name, #2 (repeated) feature { #1 name, #2 { #1 enabled, #2 value } }
68
+ capabilities = [];
69
+ for (const feature of iterFields(field.value)) {
70
+ if (feature.num !== 2 || feature.wire !== 2 || !Buffer.isBuffer(feature.value))
71
+ continue;
72
+ let name = "";
73
+ let enabled = false;
74
+ let value;
75
+ for (const part of iterFields(feature.value)) {
76
+ if (part.num === 1 && part.wire === 2 && Buffer.isBuffer(part.value)) {
77
+ name = part.value.toString("utf8");
78
+ }
79
+ else if (part.num === 1 && part.wire === 0) {
80
+ enabled = part.value === 1n;
81
+ }
82
+ else if (part.num === 2 && part.wire === 2 && Buffer.isBuffer(part.value)) {
83
+ value = part.value.toString("utf8");
84
+ }
85
+ }
86
+ if (name)
87
+ capabilities.push({ name, enabled, value });
88
+ }
89
+ }
90
+ else if (field.num === 32 && field.wire === 2 && Buffer.isBuffer(field.value)) {
91
+ // Pricing message (repeated): #1 type, #4 price (float32 LE)
92
+ pricing ??= { input: 0, cachedInput: 0, output: 0 };
93
+ let type = "";
94
+ let price = 0;
95
+ for (const part of iterFields(field.value)) {
96
+ if (part.num === 1 && part.wire === 2 && Buffer.isBuffer(part.value)) {
97
+ type = part.value.toString("utf8").toLowerCase();
98
+ }
99
+ else if (part.num === 4 && Buffer.isBuffer(part.value) && part.value.length === 4) {
100
+ price = part.value.readFloatLE(0);
101
+ }
102
+ }
103
+ if (type.includes("input") && !type.includes("cached"))
104
+ pricing.input = price;
105
+ else if (type.includes("cached"))
106
+ pricing.cachedInput = price;
107
+ else if (type.includes("output"))
108
+ pricing.output = price;
109
+ }
110
+ }
111
+ if (modelUid.length === 0)
112
+ 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;
117
+ return {
118
+ modelUid,
119
+ label: label || modelUid,
120
+ disabled,
121
+ contextWindow,
122
+ pricing,
123
+ capabilities,
124
+ baseModelUid,
125
+ effortLevel,
126
+ };
127
+ }
128
+ let cached = null;
129
+ let inFlight = null;
130
+ let inFlightKey = null;
131
+ const flightKey = (apiKey, host) => `${host}${apiKey}`;
132
+ /** Fetch the per-account catalog, cached for 10 minutes. Returns null on failure. */
133
+ export async function getCachedCatalog(apiKey, host = DEFAULT_API_SERVER, signal) {
134
+ if (cached && cached.apiKey === apiKey && cached.host === host && Date.now() - cached.fetchedAt < CATALOG_TTL_MS) {
135
+ return cached;
136
+ }
137
+ const key = flightKey(apiKey, host);
138
+ if (inFlight && inFlightKey === key) {
139
+ try {
140
+ return await inFlight;
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ }
146
+ const promise = fetchCatalog(apiKey, host, signal);
147
+ inFlight = promise;
148
+ inFlightKey = key;
149
+ try {
150
+ const result = await promise;
151
+ cached = result;
152
+ return result;
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ finally {
158
+ if (inFlight === promise) {
159
+ inFlight = null;
160
+ inFlightKey = null;
161
+ }
162
+ }
163
+ }
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
+ }
@@ -0,0 +1,92 @@
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
+ export declare class CloudChatError extends Error {
8
+ readonly code?: string;
9
+ readonly traceId?: string;
10
+ constructor(message: string, code?: string, traceId?: string);
11
+ }
12
+ /** Cognition rejects source=3 for system; system content is inlined into user turns. */
13
+ declare const SOURCE_BY_ROLE: {
14
+ readonly user: 1;
15
+ readonly assistant: 2;
16
+ readonly system: 1;
17
+ readonly tool: 4;
18
+ };
19
+ export type ChatRole = keyof typeof SOURCE_BY_ROLE;
20
+ export interface ChatImage {
21
+ mimeType: string;
22
+ base64Data: string;
23
+ caption?: string;
24
+ }
25
+ export type ChatContent = string | Array<{
26
+ type: "text";
27
+ text: string;
28
+ } | ({
29
+ type: "image";
30
+ } & ChatImage)>;
31
+ export interface ChatToolCall {
32
+ id: string;
33
+ name: string;
34
+ arguments: string;
35
+ }
36
+ export interface ChatHistoryItem {
37
+ role: ChatRole;
38
+ content: ChatContent;
39
+ tool_call_id?: string;
40
+ tool_calls?: ChatToolCall[];
41
+ }
42
+ export interface ChatToolDefinition {
43
+ name: string;
44
+ description?: string;
45
+ parameters?: unknown;
46
+ }
47
+ export interface CompletionOptions {
48
+ maxInputTokens?: number;
49
+ maxOutputTokens?: number;
50
+ temperature?: number;
51
+ topP?: number;
52
+ topK?: number;
53
+ }
54
+ export type ChatEvent = {
55
+ kind: "text";
56
+ text: string;
57
+ } | {
58
+ kind: "reasoning";
59
+ text: string;
60
+ } | {
61
+ kind: "tool_call_start";
62
+ id: string;
63
+ name: string;
64
+ } | {
65
+ kind: "tool_call_args";
66
+ argsDelta: string;
67
+ id?: string;
68
+ } | {
69
+ kind: "finish";
70
+ reason: string;
71
+ } | {
72
+ kind: "usage";
73
+ promptTokens?: number;
74
+ completionTokens?: number;
75
+ totalTokens?: number;
76
+ cachedInputTokens?: number;
77
+ cacheCreationInputTokens?: number;
78
+ reasoningTokens?: number;
79
+ };
80
+ export interface StreamChatRequest {
81
+ apiKey: string;
82
+ apiServerUrl?: string;
83
+ modelUid: string;
84
+ messages: ChatHistoryItem[];
85
+ tools?: ChatToolDefinition[];
86
+ cascadeId?: string;
87
+ completionOpts?: CompletionOptions;
88
+ signal?: AbortSignal;
89
+ }
90
+ /** Stream decoded chat events from the GetChatMessage Connect-RPC endpoint. */
91
+ export declare function streamChatEvents(request: StreamChatRequest): AsyncGenerator<ChatEvent>;
92
+ export {};