opencode-devin 0.2.11 → 2.0.0-beta.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.
package/package.json CHANGED
@@ -1,29 +1,24 @@
1
1
  {
2
- "$schema": "https://json.schemastore.org/package.json",
3
2
  "name": "opencode-devin",
4
- "version": "0.2.11",
5
- "description": "OpenCode v2 plugin: connect your Devin subscription to opencode with native /connect login and devin/* models",
3
+ "version": "2.0.0-beta.1",
4
+ "description": "Devin (Cognition) provider for opencode — clean-room Cascade client, PKCE login, full model catalog",
6
5
  "type": "module",
7
- "main": "./dist/index.js",
6
+ "main": "./src/index.ts",
8
7
  "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "default": "./dist/index.js"
12
- },
13
- "./provider": {
14
- "types": "./dist/provider.d.ts",
15
- "default": "./dist/provider.js"
16
- }
8
+ ".": "./src/index.ts"
17
9
  },
18
10
  "files": [
19
- "dist"
11
+ "CHANGELOG.md",
12
+ "LICENSE",
13
+ "README.md",
14
+ "SECURITY.md",
15
+ "scripts",
16
+ "src"
20
17
  ],
21
18
  "scripts": {
22
- "build": "node scripts/build.mjs",
23
- "build:clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true})\" && tsc",
24
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
25
- "test": "bun test",
26
- "prepublishOnly": "npm run build:clean"
19
+ "typecheck": "tsc --noEmit -p tsconfig.json",
20
+ "login": "bun run scripts/login.ts",
21
+ "log": "bun run scripts/dump-log.ts"
27
22
  },
28
23
  "keywords": [
29
24
  "opencode",
@@ -31,6 +26,7 @@
31
26
  "opencode-v2",
32
27
  "devin",
33
28
  "cognition",
29
+ "cascade",
34
30
  "windsurf"
35
31
  ],
36
32
  "license": "MIT",
@@ -43,16 +39,14 @@
43
39
  "url": "git+https://github.com/JoShMiQueL/opencode-devin.git"
44
40
  },
45
41
  "homepage": "https://github.com/JoShMiQueL/opencode-devin#readme",
46
- "bugs": "https://github.com/JoShMiQueL/opencode-devin/issues",
42
+ "bugs": {
43
+ "url": "https://github.com/JoShMiQueL/opencode-devin/issues"
44
+ },
47
45
  "dependencies": {
48
- "@ai-sdk/provider": "3.0.8",
49
- "@opencode/plugin": "2.4.1",
50
- "devin-core": "0.0.7",
51
- "devin-engine": "0.0.12"
46
+ "@opencode/plugin": "2.4.2"
52
47
  },
53
48
  "devDependencies": {
54
- "@types/bun": "1.4.4",
55
- "protobufjs": "8.8.1",
49
+ "@types/bun": "1.4.5",
56
50
  "typescript": "7.0.2"
57
51
  }
58
52
  }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * dump-log — print the tail of devin.log for bug reports.
3
+ *
4
+ * Usage: bun run scripts/dump-log.ts [lines]
5
+ * A user runs this, copies the output, and hands it to us. Tokens are already
6
+ * redacted at write time — the dump is safe to paste anywhere.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+
10
+ import { logFile } from "../src/provider/paths.js";
11
+
12
+ const N = Number(process.argv[2] ?? 120);
13
+ const path = logFile();
14
+
15
+ try {
16
+ const lines = readFileSync(path, "utf8").trimEnd().split("\n");
17
+ console.log(lines.slice(-N).join("\n"));
18
+ console.error(`\n[dump-log] ${Math.min(N, lines.length)} of ${lines.length} lines from ${path}`);
19
+ } catch {
20
+ console.error(`[dump-log] no log file at ${path}`);
21
+ process.exit(1);
22
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Standalone Devin PKCE login.
3
+ * bun run scripts/login.ts
4
+ *
5
+ * Opens the browser on app.devin.ai/auth/cli/continue, catches the loopback
6
+ * callback, exchanges the code, verifies the token by minting a user_jwt,
7
+ * then persists the session token to the per-user data dir (gitignored by
8
+ * location — never inside a repo).
9
+ */
10
+ import { writeFileSync } from "node:fs";
11
+ import { loginAuto, mintUserJwt, SESSION_PREFIX } from "../src/provider/auth.js";
12
+ import { sessionFile } from "../src/provider/paths.js";
13
+
14
+ // Fixed per-user location (%APPDATA%/opencode-devin/session or
15
+ // ~/.config/opencode-devin/session) — the plugin reads it from anywhere.
16
+ const TOKEN_FILE = sessionFile();
17
+
18
+ const flow = await loginAuto();
19
+ console.log("\nOpening Devin login in your browser…");
20
+ console.log("If it doesn't open, paste this URL manually:\n\n " + flow.url + "\n");
21
+
22
+ // cmd `start` splits on & — use rundll32 url.dll,FileProtocolHandler instead
23
+ const openCmd =
24
+ process.platform === "win32"
25
+ ? ["rundll32", "url.dll,FileProtocolHandler", flow.url]
26
+ : process.platform === "darwin"
27
+ ? ["open", flow.url]
28
+ : ["xdg-open", flow.url];
29
+ Bun.spawn(openCmd, { stdout: "ignore", stderr: "ignore" });
30
+
31
+ console.log("Waiting for the login callback on 127.0.0.1…");
32
+ const cred = await flow.finish();
33
+ console.log("Got session token (redacted).");
34
+
35
+ if (!cred.sessionToken.startsWith(SESSION_PREFIX))
36
+ throw new Error("unexpected token format");
37
+
38
+ // verify it end-to-end: mint a user_jwt against the cascade host
39
+ console.log("Verifying: minting user_jwt via GetUserJwt…");
40
+ const uj = await mintUserJwt(cred.sessionToken);
41
+ console.log("user_jwt OK — cascade host:", uj.cascadeHost);
42
+
43
+ writeFileSync(TOKEN_FILE, cred.sessionToken + "\n", { mode: 0o600 });
44
+ console.log(`\nSaved to ${TOKEN_FILE}\n`);
45
+ console.log("Run a test:");
46
+ console.log(' opencode run --standalone -m devin/swe-2 "say OK"');
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Package entry point — opencode loads this when the plugin is installed from
3
+ * npm (`"plugin": ["opencode-devin"]`).
4
+ */
5
+ export { default } from "./plugin.js";
package/src/plugin.ts ADDED
@@ -0,0 +1,364 @@
1
+ /**
2
+ * opencode-devin — clean-room Devin provider plugin for opencode v2.4.
3
+ *
4
+ * Publishes the `devin` provider backed
5
+ * by our own Cascade client (src/provider/*). Credential =
6
+ * devin-session-token$<jwt> from /connect, OPENCODE_DEVIN session file, or
7
+ * DEVIN_API_KEY env var.
8
+ *
9
+ * This module is the package entry point (`src/index.ts` re-exports it); the
10
+ * local `.opencode/plugin/opencode-devin.ts` is a thin re-export for dev
11
+ * auto-loading.
12
+ */
13
+ import { Plugin, Provider, Model, Credential } from "@opencode/plugin";
14
+ import { Effect } from "effect";
15
+ import { readFileSync } from "node:fs";
16
+ import * as cascadeModule from "./provider/index.js";
17
+ import * as authModule from "./provider/auth.js";
18
+ import { log, redact, logPath } from "./provider/log.js";
19
+ import * as pathsModule from "./provider/paths.js";
20
+
21
+ // Provider id + display name — everything downstream (provider info, integration
22
+ // id, methods, settings key, /connect labels) derives from these.
23
+ const PROVIDER_ID = "devin" as const;
24
+ const PROVIDER_NAME = "Devin" as const;
25
+
26
+ // Plugin id = npm package name. Replaces the previous opencode-devin@0.x.
27
+ const PLUGIN_ID = "opencode-devin" as const;
28
+
29
+ // Token sources, in priority order:
30
+ // 1. hook options / explicit sessionToken
31
+ // 2. DEVIN_API_KEY env var
32
+ // 3. the /connect stored credential (via resolveStoredToken, needs ctx)
33
+ // 4. the session file in the per-user data dir (paths.ts)
34
+ function resolveSessionToken(opts?: any): string {
35
+ if (opts?.sessionToken) return opts.sessionToken;
36
+ if (process.env.DEVIN_API_KEY) return process.env.DEVIN_API_KEY;
37
+ try {
38
+ const t = readFileSync(pathsModule.sessionFile(), "utf8").trim();
39
+ if (t) return t;
40
+ } catch {}
41
+ return "";
42
+ }
43
+
44
+ const CREDENTIAL_TTL_MS = 30 * 24 * 3600 * 1000; // ~30 days, mirrors devin session
45
+
46
+ /** Credential shape opencode stores after /connect finishes. */
47
+ function toStoredCredential(apiKey: string, name = "opencode"): Credential.OAuth {
48
+ return {
49
+ type: "oauth",
50
+ methodID: "devin",
51
+ refresh: "",
52
+ access: apiKey,
53
+ expires: Date.now() + CREDENTIAL_TTL_MS,
54
+ metadata: { name },
55
+ } as unknown as Credential.OAuth;
56
+ }
57
+
58
+ /** Read the session token stored by /connect. */
59
+ async function resolveStoredToken(ctx: any): Promise<string | undefined> {
60
+ try {
61
+ const connection = await ctx.integration.connection.active(PROVIDER_ID);
62
+ if (!connection) return undefined;
63
+ const value = await ctx.integration.connection.resolve(connection);
64
+ const access =
65
+ value?.type === "oauth" ? value.access : value?.type === "key" ? value.key : undefined;
66
+ return access?.startsWith("devin-session-token$") ? access : undefined;
67
+ } catch (e) {
68
+ log.warn("credential.resolve_fail", { err: String(e) });
69
+ return undefined;
70
+ }
71
+ }
72
+
73
+ function openBrowser(url: string): void {
74
+ const cmd =
75
+ process.platform === "win32"
76
+ ? ["rundll32", "url.dll,FileProtocolHandler", url]
77
+ : process.platform === "darwin"
78
+ ? ["open", url]
79
+ : ["xdg-open", url];
80
+ Bun.spawn(cmd, { stdout: "ignore", stderr: "ignore" });
81
+ }
82
+
83
+ /** "Free" = no per-token pricing block — the model rides on the plan quota
84
+ * (swe-2 family, claude, gemini… all carry pricing:undefined). The paid
85
+ * promo tiers (-lightning ultrafast, muse-wonder) report real $/M rates. */
86
+ function isFree(e: { pricing?: { input: number; cachedInput: number; output: number } }): boolean {
87
+ return e.pricing === undefined;
88
+ }
89
+
90
+ /** Group catalog entries into one Model.Info per family (baseModelUid), with
91
+ * effort variants from the present suffixes. Speed modifiers like
92
+ * `-fast`/`-lightning`/`ultrafast` live in the family name, not the effort —
93
+ * `swe-2-flash-high` joins family `swe-2-flash` with variant `high`. */
94
+ /** Which variants are listed per model. Two orthogonal axes:
95
+ * - LISTING mode "censored" | "both" | "uncensored" (default "censored":
96
+ * stock picker; opt in to reveal uncensored rows)
97
+ * - ACTIVATION per-variant #X-uncensored / providerOptions.uncensored /
98
+ * env OPENCODE_DEVIN_UNCENSORED / plugin mode "uncensored" force the
99
+ * uncensored preamble on every call, independent of listing. */
100
+ type VariantListing = "censored" | "both" | "uncensored";
101
+
102
+ function catalogModels(
103
+ entries: {
104
+ modelUid: string; label: string; disabled: boolean; contextWindow: number;
105
+ effortLevel?: string; baseModelUid: string;
106
+ pricing?: { input: number; cachedInput: number; output: number };
107
+ }[],
108
+ listing: VariantListing = "censored",
109
+ ): Model.Info[] {
110
+ const pid = Provider.ID.make(PROVIDER_ID);
111
+ const families = new Map<string, {
112
+ name: string; ctx: number; free: boolean; variants: Map<string, string>;
113
+ pricing?: { input: number; cachedInput: number; output: number };
114
+ }>();
115
+ for (const e of entries) {
116
+ if (e.disabled || !e.modelUid) continue;
117
+ const fam = families.get(e.baseModelUid) ?? {
118
+ // Strip ONLY the trailing effort word — keep speed modifiers in the
119
+ // family name ("SWE-2 Flash Medium Ultrafast" → effort medium →
120
+ // "SWE-2 Flash Ultrafast"; "SWE-2 Flash Medium" → "SWE-2 Flash").
121
+ name: e.label
122
+ .replace(/\s+(Minimal|Low|Medium|High|XHigh|Max|No Thinking)$/g, "")
123
+ .trim() || e.label,
124
+ ctx: e.contextWindow,
125
+ free: isFree(e),
126
+ variants: new Map(),
127
+ pricing: e.pricing,
128
+ };
129
+ // A member without a pricing block rides the plan quota; keep biggest ctx.
130
+ fam.free = fam.free || isFree(e);
131
+ fam.pricing ??= e.pricing;
132
+ fam.ctx = Math.max(fam.ctx, e.contextWindow);
133
+ if (e.effortLevel) fam.variants.set(e.effortLevel, e.modelUid);
134
+ families.set(e.baseModelUid, fam);
135
+ }
136
+ // float32 wire values carry noise (0.10000000149011612) — round to 4 decimals
137
+ const usd = (n: number) => Math.round(n * 10_000) / 10_000;
138
+ return [...families].map(([base, f]) => ({
139
+ ...Model.Info.default(pid, Model.ID.make(base)),
140
+ name: f.name + (f.free ? " · Free" : ""),
141
+ limit: { context: f.ctx, output: 32000 },
142
+ // Plan-quota models report no pricing → no cost entries (opencode shows
143
+ // nothing to pay). Paid families get their real $/1M rates so spend adds up.
144
+ cost: !f.free && f.pricing
145
+ ? [{
146
+ input: usd(f.pricing.input),
147
+ output: usd(f.pricing.output),
148
+ cache: { read: usd(f.pricing.cachedInput), write: 0 },
149
+ }]
150
+ : [],
151
+ // Variant id IS the effort word (low/medium/high/…). settings merge into
152
+ // the call options — providerOptions.devin.reasoningEffort reaches doStream.
153
+ variants: (() => {
154
+ const efforts = [...f.variants].map(([effort]) => effort);
155
+ const out: { id: string; name: string; settings: Record<string, unknown> }[] = [];
156
+ if (listing !== "uncensored") {
157
+ for (const effort of efforts) {
158
+ out.push({ id: effort, name: effort, settings: { reasoningEffort: effort } });
159
+ }
160
+ }
161
+ if (listing !== "censored") {
162
+ for (const effort of efforts) {
163
+ // Mirror per effort in uncensored mode: swe-2#medium-uncensored →
164
+ // same uid member + providerOptions.devin.uncensored=true.
165
+ out.push({
166
+ id: `${effort}-uncensored`,
167
+ name: `${effort} · uncensored`,
168
+ settings: { reasoningEffort: effort, uncensored: true },
169
+ });
170
+ }
171
+ }
172
+ return out;
173
+ })(),
174
+ } as unknown as Model.Info));
175
+ }
176
+
177
+ export default Plugin.define({
178
+ id: PLUGIN_ID,
179
+ async setup(ctx) {
180
+ // Plugin-level options from opencode.json — ONE tri-state switch:
181
+ // options.mode = "censored" (DEFAULT) | "both" | "uncensored"
182
+ // censored → stock picker only; no uncensored rows; no forcing.
183
+ // both → list stock + uncensored rows; no forcing.
184
+ // uncensored → list uncensored rows only; FORCE preamble on every
185
+ // call (same as OPENCODE_DEVIN_UNCENSORED=1).
186
+ // Nothing needs to be set for default. Per-call providerOptions.uncensored
187
+ // and the #X-uncensored variant remain available independently.
188
+ const pluginOptions = (ctx as any).options ?? {};
189
+ const mode = pluginOptions?.mode;
190
+ if (mode === "uncensored") {
191
+ process.env.OPENCODE_DEVIN_UNCENSORED = "1";
192
+ }
193
+ const variantListing: VariantListing =
194
+ mode === "both" ? "both"
195
+ : mode === "uncensored" ? "uncensored"
196
+ : "censored";
197
+ log.info("plugin.setup", {
198
+ aisdkHook: typeof (ctx as any).aisdk?.hook, logPath: logPath(),
199
+ uncensored: process.env.OPENCODE_DEVIN_UNCENSORED === "1" || undefined,
200
+ variantListing,
201
+ });
202
+
203
+ // Shared token cache — resolved async at publish, read sync by hooks.
204
+ let activeToken = "";
205
+
206
+ if (ctx.aisdk?.hook) {
207
+ // The runtime wants an Effect here (the hook runs it); the published
208
+ // d.ts only declares void | Promise<void>, hence the casts.
209
+ const onSdk = ((evt: any) =>
210
+ Effect.sync(() => {
211
+ if (evt.model?.providerID !== PROVIDER_ID) return;
212
+ log.debug("aisdk.sdk", { modelID: evt.model?.modelID });
213
+ evt.sdk = cascadeModule.createDevinProvider(evt.options ?? {});
214
+ })) as any;
215
+ const onLanguage = ((evt: any) =>
216
+ Effect.sync(() => {
217
+ if (evt.model?.providerID !== PROVIDER_ID) return;
218
+ const token = resolveSessionToken(evt.options) || activeToken;
219
+ // Variant id is the effort word; the language model resolves the
220
+ // exact catalog uid (default member when no variant is selected).
221
+ const variant =
222
+ evt.model?.variant ?? evt.model?.selectedVariant ?? evt.variant;
223
+ const rawId = typeof variant === "string" ? variant : variant?.id;
224
+ // Uncensored markers: bare "uncensored" or "<effort>-uncensored".
225
+ // The marker is a MODE flag, not an effort — strip it before
226
+ // resolving the catalog uid; flag travels onward.
227
+ const UNCENSORED_SUFFIXES = ["uncensored"];
228
+ let effortId = rawId;
229
+ let uncensored = false;
230
+ if (effortId === "uncensored") {
231
+ effortId = undefined;
232
+ uncensored = true;
233
+ } else if (effortId) {
234
+ for (const s of UNCENSORED_SUFFIXES) {
235
+ if (effortId.endsWith(`-${s}`)) {
236
+ effortId = effortId.slice(0, -(s.length + 1));
237
+ uncensored = true;
238
+ break;
239
+ }
240
+ }
241
+ }
242
+ // Variant-level settings may also carry uncensored=true.
243
+ if (variant && typeof variant === "object" && (variant as any).uncensored === true) {
244
+ uncensored = true;
245
+ }
246
+ const base = evt.model.modelID ?? evt.model.id;
247
+ const modelUid = effortId
248
+ ? cascadeModule.withEffortSuffix(base, effortId)
249
+ : base;
250
+ log.info("model.resolve", {
251
+ base, effort: effortId ?? null, uncensored: uncensored || undefined,
252
+ modelUid, token: redact(token),
253
+ });
254
+ evt.language = new cascadeModule.CascadeLanguageModel(
255
+ modelUid,
256
+ new authModule.DevinCredentials(token),
257
+ undefined,
258
+ uncensored,
259
+ );
260
+ })) as any;
261
+ await ctx.aisdk.hook("sdk", onSdk);
262
+ await ctx.aisdk.hook("language", onLanguage);
263
+ }
264
+
265
+ // /connect integration — three ways to store a session token:
266
+ // auto → browser PKCE flow (loopback callback, no paste)
267
+ // code → headless: open URL, paste the shown code back
268
+ // env → DEVIN_API_KEY env var
269
+ await ctx.integration.transform((editor) => {
270
+ editor.update(PROVIDER_ID, (int: any) => { int.name = PROVIDER_NAME; });
271
+ editor.method.update({
272
+ integrationID: PROVIDER_ID,
273
+ method: { id: "devin", type: "oauth", label: "Log in with Devin (browser)" },
274
+ authorize: async () => {
275
+ const flow = await authModule.loginAuto();
276
+ openBrowser(flow.url);
277
+ return {
278
+ url: flow.url,
279
+ instructions: `Log in to Devin in the opened browser tab. If it did not open, go to: ${flow.url}`,
280
+ mode: "auto",
281
+ callback: flow.finish().then((c: any) => toStoredCredential(c.sessionToken)),
282
+ };
283
+ },
284
+ });
285
+ editor.method.update({
286
+ integrationID: PROVIDER_ID,
287
+ method: { id: "code", type: "oauth", label: "Paste code (headless)" },
288
+ authorize: async () => {
289
+ const flow = await authModule.loginManual();
290
+ return {
291
+ url: flow.url,
292
+ instructions: "Open the URL, sign in to Devin, copy the code shown, and paste it here.",
293
+ mode: "code",
294
+ callback: async (code: string) =>
295
+ toStoredCredential((await flow.finish(code)).sessionToken),
296
+ };
297
+ },
298
+ });
299
+ editor.method.update({
300
+ integrationID: PROVIDER_ID,
301
+ method: { type: "env", names: ["DEVIN_API_KEY"] },
302
+ });
303
+ });
304
+
305
+ const publish = async () => {
306
+ // /connect credential first, then env / session file.
307
+ const sessionToken =
308
+ (await resolveStoredToken(ctx)) ?? resolveSessionToken();
309
+ if (!sessionToken) {
310
+ log.warn("publish.no_token");
311
+ return;
312
+ }
313
+ activeToken = sessionToken; // shared with the sync aisdk language hook
314
+ log.info("publish.start", { token: redact(sessionToken) });
315
+ let models: Model.Info[] = [];
316
+ try {
317
+ const catalog = await cascadeModule.fetchCatalog(
318
+ new authModule.DevinCredentials(sessionToken),
319
+ );
320
+ models = catalogModels(catalog, variantListing);
321
+ log.info("provider.catalog", { entries: catalog.length, families: models.length });
322
+ } catch (e) {
323
+ log.error("provider.catalog_fail", { err: String(e) });
324
+ }
325
+ if (!models.length) {
326
+ log.warn("provider.fallback_models");
327
+ models = [{
328
+ ...Model.Info.default(Provider.ID.make(PROVIDER_ID), Model.ID.make("swe-2")),
329
+ name: "SWE-2",
330
+ } as Model.Info];
331
+ }
332
+ await ctx.provider.transform((editor) => {
333
+ editor.add({
334
+ info: {
335
+ ...Provider.Info.empty(Provider.ID.make(PROVIDER_ID)),
336
+ name: PROVIDER_NAME,
337
+ activation: "enabled",
338
+ package: `aisdk:${new URL("./provider/", import.meta.url).href}`,
339
+ settings: { sessionToken },
340
+ },
341
+ models,
342
+ });
343
+ });
344
+ };
345
+
346
+ await publish().catch((error) => {
347
+ log.error("publish.failed", { err: String(error) });
348
+ });
349
+
350
+ const controller = new AbortController();
351
+ void (async () => {
352
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
353
+ if (event.type === "credential.updated" || event.type === "credential.switched") {
354
+ log.info("credential.event", { type: event.type });
355
+ await publish().catch((error) => {
356
+ log.error("republish.fail", { type: event.type, err: String(error) });
357
+ });
358
+ }
359
+ }
360
+ })();
361
+
362
+ return () => controller.abort();
363
+ },
364
+ });