devin-proxy 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # devin-proxy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An **OpenAI-compatible local proxy** that serves the Devin/Cascade backend's SWE-2 / SWE-2.1 lanes through the [`devin-engine`](../devin-engine) guarded-retry pipeline — a drop-in `OPENAI_BASE_URL` for any client that speaks `/v1/chat/completions`.
4
+
5
+ TypeScript port of the Python `devin-proxy`. Sits on [`devin-core`](../devin-core) (wire + auth + catalog) and [`devin-engine`](../devin-engine) (guard, override, retry, sanitize, resolve).
6
+
7
+ ## Run
8
+
9
+ ```bash
10
+ bun install
11
+ bun src/cli.ts serve # 127.0.0.1:8390
12
+ # or, after build:
13
+ node dist/cli.js serve --port 8390
14
+ ```
15
+
16
+ Credentials come from `DEVIN_PROXY_API_KEY` or the Devin CLI's `credentials.toml` (`windsurf_api_key`). `devin-proxy login` runs the PKCE browser flow and writes it.
17
+
18
+ ## Client
19
+
20
+ ```python
21
+ from openai import OpenAI
22
+ c = OpenAI(base_url="http://127.0.0.1:8391/v1", api_key="unused")
23
+ c.chat.completions.create(model="swe-2", messages=[...])
24
+ ```
25
+
26
+ Point `ANTHROPIC_BASE_URL`/`OPENAI_BASE_URL`, Cursor, aider, continue.dev, Cline — anything OpenAI-shaped — at it.
27
+
28
+ ## Endpoints
29
+
30
+ | Route | What |
31
+ | --- | --- |
32
+ | `POST /v1/chat/completions` | OpenAI chat, `stream: true`→SSE, `stream:false`→unary |
33
+ | `GET /v1/models`, `/models` | allowed lanes + `swe-2`/`swe-2-flash`/`swe-2.1` aliases; `free_until`, `credits_per_run`, `free_tier` when `--allow-paid` |
34
+ | `GET /health` | backend, override file, catalog count, promo windows |
35
+
36
+ ## Models
37
+
38
+ `model` resolves by family + `reasoning_effort`:
39
+
40
+ - `swe-2` → `swe-2-{medium,high,max}` (default `high`)
41
+ - `swe-2-flash` → `swe-2-flash-{medium,high,max}`
42
+ - `swe-2.1` → `swe-2-1-{low,medium,high,xhigh,max}` — free promo until **2026-12-09**
43
+ - `reasoning_effort` picks the tier inside whichever family the id selected, clamping to the nearest defined level.
44
+
45
+ `*-lightning` lanes are never routed — they bill fast-mode credits. `allow_paid` opens the full live catalog; every non-SWE uid bills credits.
46
+
47
+ ## Settings
48
+
49
+ Env `DEVIN_PROXY_*`, `~/.devin-proxy/settings.toml` `[devin_proxy]`, or flags. Notables: `ALLOW_PAID`, `ALLOWED_MODELS` (CSV), `GUARD_CHARS`, `GUARD_FULL`, `MAX_RETRIES`, `EMIT_REASONING`, `MAX_INPUT_TOKENS`, `SYSTEM_FILE` (`es`/`english`/`spanish` picks a bundled override).
50
+
51
+ ## What the engine does per request
52
+
53
+ Sanitize history → inject the system override → resolve model → stream upstream → hold the first N chars behind a multilingual refusal guard → on a refusal, resample inside the same downstream stream with an escalated frame (invisible to the client) → translate tool calls back to OpenAI shape. See [devin-engine](../devin-engine).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Credential loading and JWT minting for the Devin gateway.
3
+ *
4
+ * Resolves the session token (env > credentials.toml) and caches the
5
+ * short-lived JWT (10 min) via devin-core's getCachedUserJwt.
6
+ *
7
+ * Ported from devin_proxy/transport/auth.py.
8
+ */
9
+ export declare function defaultCredentialsPath(): string;
10
+ /** windsurf_api_key out of a credentials.toml (Devin CLI format). */
11
+ export declare function readKey(path: string): string;
12
+ /** Persist a session token in the Devin CLI's own credentials.toml format. */
13
+ export declare function writeCredentials(path: string, apiKey: string, apiServer?: string): string;
14
+ /** Session token + cached JWT. */
15
+ export declare class Auth {
16
+ readonly base: string;
17
+ readonly credentials: string;
18
+ constructor(base: string, credentials?: string);
19
+ apiKey(): string;
20
+ jwt(): Promise<string>;
21
+ }
package/dist/auth.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Credential loading and JWT minting for the Devin gateway.
3
+ *
4
+ * Resolves the session token (env > credentials.toml) and caches the
5
+ * short-lived JWT (10 min) via devin-core's getCachedUserJwt.
6
+ *
7
+ * Ported from devin_proxy/transport/auth.py.
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { dirname, join } from "node:path";
12
+ import { getCachedUserJwt } from "devin-core";
13
+ export function defaultCredentialsPath() {
14
+ const envPath = process.env.DEVIN_PROXY_CRED;
15
+ if (envPath)
16
+ return envPath;
17
+ const home = homedir();
18
+ const appdata = process.env.APPDATA;
19
+ const candidates = [
20
+ join(home, ".devin", "credentials.toml"),
21
+ ...(appdata ? [join(appdata, "devin", "credentials.toml")] : []),
22
+ join(home, ".config", "devin", "credentials.toml"),
23
+ ];
24
+ for (const p of candidates)
25
+ if (existsSync(p))
26
+ return p;
27
+ return candidates[0];
28
+ }
29
+ /** windsurf_api_key out of a credentials.toml (Devin CLI format). */
30
+ export function readKey(path) {
31
+ const s = readFileSync(path, "utf-8");
32
+ const m = /windsurf_api_key\s*=\s*"([^"]+)"/.exec(s);
33
+ if (!m)
34
+ throw new Error(`no windsurf_api_key in ${path}`);
35
+ return m[1];
36
+ }
37
+ /** Persist a session token in the Devin CLI's own credentials.toml format. */
38
+ export function writeCredentials(path, apiKey, apiServer = "https://server.codeium.com") {
39
+ mkdirSync(dirname(path), { recursive: true });
40
+ writeFileSync(path, `windsurf_api_key = "${apiKey}"\napi_server_url = "${apiServer}"\ndevin_webapp_host = "app.devin.ai"\ndevin_api_url = "https://api.devin.ai"\n`, "utf-8");
41
+ return path;
42
+ }
43
+ /** Session token + cached JWT. */
44
+ export class Auth {
45
+ base;
46
+ credentials;
47
+ constructor(base, credentials) {
48
+ this.base = base;
49
+ this.base = base.replace(/\/+$/, "");
50
+ this.credentials = credentials ?? defaultCredentialsPath();
51
+ }
52
+ apiKey() {
53
+ const k = process.env.DEVIN_PROXY_API_KEY;
54
+ if (k)
55
+ return k.trim();
56
+ return readKey(this.credentials);
57
+ }
58
+ jwt() {
59
+ return getCachedUserJwt(this.apiKey(), this.base);
60
+ }
61
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Fetch the live model catalog from GetCliModelConfigs.
3
+ *
4
+ * This is the *other* catalog RPC — the one that exposes per-model credit
5
+ * cost, promo/free windows and aliases. devin-core's `getCachedCatalog`
6
+ * reads GetCascadeModelConfigs for enabled/pricing; this reads the CLI
7
+ * surface the Python proxy uses for billing tags.
8
+ *
9
+ * Ported from devin_proxy/models/fetch.py + the ModelCatalog half of
10
+ * devin_proxy/models/catalog.py.
11
+ */
12
+ export interface CliModelConfig {
13
+ uid: string;
14
+ name: string;
15
+ context: number;
16
+ /** Relative credit cost per run (field 3, float32). 0 = free lane. */
17
+ credits: number;
18
+ /** Promo/free window end, epoch seconds (field 19.2.1). */
19
+ expiresAt: number;
20
+ /** Promo label, e.g. "83% off" (field 19.3). */
21
+ promo: string;
22
+ aliases: string[];
23
+ expiryIso(): string;
24
+ }
25
+ /** GetImageCaption: base64 image -> caption text. Ported from transport/caption.py. */
26
+ export declare function imageCaption(base: string, apiKey: string, jwt: string, imageB64: string, mime?: string, clientVersion?: string, timeoutMs?: number): Promise<string>;
27
+ /** GetWebSearchResults: query -> [{id,url,title,content}]. Ported from transport/websearch.py. */
28
+ export declare function webSearch(base: string, apiKey: string, jwt: string, query: string, clientVersion?: string, timeoutMs?: number): Promise<Array<Record<string, string>>>;
29
+ /** GetCliModelConfigs -> Map<uid, config>, or null on failure. */
30
+ export declare function fetchCliCatalog(base: string, apiKey: string, jwt: string, clientVersion: string, timeoutMs?: number): Promise<Map<string, CliModelConfig> | null>;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Fetch the live model catalog from GetCliModelConfigs.
3
+ *
4
+ * This is the *other* catalog RPC — the one that exposes per-model credit
5
+ * cost, promo/free windows and aliases. devin-core's `getCachedCatalog`
6
+ * reads GetCascadeModelConfigs for enabled/pricing; this reads the CLI
7
+ * surface the Python proxy uses for billing tags.
8
+ *
9
+ * Ported from devin_proxy/models/fetch.py + the ModelCatalog half of
10
+ * devin_proxy/models/catalog.py.
11
+ */
12
+ import { encodeMessage, encodeString, iterFields } from "devin-core";
13
+ import { randomUUID } from "node:crypto";
14
+ import { CHANNEL, FALLBACK_VERSION } from "./config.js";
15
+ const CFG_PATH = "/exa.api_server_pb.ApiServerService/GetCliModelConfigs";
16
+ function metadata(apiKey, jwt, version, channel = CHANNEL) {
17
+ const v = version || FALLBACK_VERSION;
18
+ const parts = [
19
+ encodeString(1, "devin-cli"),
20
+ encodeString(7, v),
21
+ encodeString(28, channel),
22
+ encodeString(12, channel),
23
+ encodeString(2, v),
24
+ encodeString(3, apiKey),
25
+ encodeString(4, "en"),
26
+ encodeString(5, "windows"),
27
+ encodeString(10, randomUUID()),
28
+ ];
29
+ if (jwt)
30
+ parts.push(encodeString(21, jwt));
31
+ return Buffer.concat(parts);
32
+ }
33
+ function parseCfg(b) {
34
+ let name = "";
35
+ let uid = "";
36
+ let context = 0;
37
+ let credits = 0;
38
+ let expiresAt = 0;
39
+ let promo = "";
40
+ const aliases = [];
41
+ for (const f of iterFields(b)) {
42
+ if (f.num === 1 && f.wire === 2 && Buffer.isBuffer(f.value))
43
+ name = f.value.toString("utf8");
44
+ else if (f.num === 3 && f.wire === 5 && Buffer.isBuffer(f.value) && f.value.length === 4) {
45
+ credits = f.value.readFloatLE(0);
46
+ }
47
+ else if (f.num === 18 && f.wire === 0)
48
+ context = Number(f.value);
49
+ else if (f.num === 19 && f.wire === 2 && Buffer.isBuffer(f.value)) {
50
+ for (const p of iterFields(f.value)) {
51
+ if (p.num === 2 && p.wire === 2 && Buffer.isBuffer(p.value)) {
52
+ for (const w of iterFields(p.value)) {
53
+ if (w.num === 1 && w.wire === 0)
54
+ expiresAt = Number(w.value);
55
+ }
56
+ }
57
+ else if (p.num === 3 && p.wire === 2 && Buffer.isBuffer(p.value)) {
58
+ promo = p.value.toString("utf8");
59
+ }
60
+ }
61
+ }
62
+ else if (f.num === 22 && f.wire === 2 && Buffer.isBuffer(f.value)) {
63
+ uid = f.value.toString("utf8");
64
+ }
65
+ else if (f.num === 23 && f.wire === 2 && Buffer.isBuffer(f.value)) {
66
+ for (const i of iterFields(f.value)) {
67
+ if (i.num === 27 && i.wire === 2 && Buffer.isBuffer(i.value)) {
68
+ aliases.push(i.value.toString("utf8"));
69
+ }
70
+ }
71
+ }
72
+ }
73
+ if (!uid)
74
+ return null;
75
+ return {
76
+ uid, name, context, credits, expiresAt, promo, aliases,
77
+ expiryIso: () => (expiresAt ? new Date(expiresAt * 1000).toISOString().slice(0, 10) : ""),
78
+ };
79
+ }
80
+ const CAPTION_PATH = "/exa.api_server_pb.ApiServerService/GetImageCaption";
81
+ const WS_PATH = "/exa.api_server_pb.ApiServerService/GetWebSearchResults";
82
+ async function unary(base, path, body, timeoutMs) {
83
+ const res = await fetch(`${base}${path}`, {
84
+ method: "POST",
85
+ headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
86
+ body: new Uint8Array(body),
87
+ signal: AbortSignal.timeout(timeoutMs),
88
+ });
89
+ if (!res.ok)
90
+ throw new Error(`${path} HTTP ${res.status}`);
91
+ return Buffer.from(await res.arrayBuffer());
92
+ }
93
+ /** GetImageCaption: base64 image -> caption text. Ported from transport/caption.py. */
94
+ export async function imageCaption(base, apiKey, jwt, imageB64, mime = "image/png", clientVersion = "", timeoutMs = 30_000) {
95
+ const img = Buffer.concat([encodeString(1, imageB64), encodeString(2, mime)]);
96
+ const body = Buffer.concat([encodeMessage(1, metadata(apiKey, jwt, clientVersion)), encodeMessage(2, img)]);
97
+ const raw = await unary(base, CAPTION_PATH, body, timeoutMs);
98
+ for (const f of iterFields(raw)) {
99
+ if (f.num === 1 && f.wire === 2 && Buffer.isBuffer(f.value))
100
+ return f.value.toString("utf8");
101
+ }
102
+ return "";
103
+ }
104
+ /** GetWebSearchResults: query -> [{id,url,title,content}]. Ported from transport/websearch.py. */
105
+ export async function webSearch(base, apiKey, jwt, query, clientVersion = "", timeoutMs = 30_000) {
106
+ const body = Buffer.concat([encodeMessage(1, metadata(apiKey, jwt, clientVersion)), encodeString(2, query)]);
107
+ const raw = await unary(base, WS_PATH, body, timeoutMs);
108
+ const results = [];
109
+ for (const f of iterFields(raw)) {
110
+ if (f.num !== 1 || f.wire !== 2 || !Buffer.isBuffer(f.value))
111
+ continue;
112
+ const item = {};
113
+ for (const p of iterFields(f.value)) {
114
+ if (p.wire !== 2 || !Buffer.isBuffer(p.value))
115
+ continue;
116
+ const s = p.value.toString("utf8");
117
+ if (p.num === 1)
118
+ item.id = s;
119
+ else if (p.num === 3)
120
+ item.url = s;
121
+ else if (p.num === 4)
122
+ item.title = s;
123
+ else if (p.num === 7)
124
+ item.content = s;
125
+ }
126
+ if (Object.keys(item).length)
127
+ results.push(item);
128
+ }
129
+ return results;
130
+ }
131
+ /** GetCliModelConfigs -> Map<uid, config>, or null on failure. */
132
+ export async function fetchCliCatalog(base, apiKey, jwt, clientVersion, timeoutMs = 30_000) {
133
+ const body = encodeMessage(1, metadata(apiKey, jwt, clientVersion));
134
+ try {
135
+ const res = await fetch(`${base}${CFG_PATH}`, {
136
+ method: "POST",
137
+ headers: { "Content-Type": "application/proto", "Connect-Protocol-Version": "1" },
138
+ body: new Uint8Array(body),
139
+ signal: AbortSignal.timeout(timeoutMs),
140
+ });
141
+ if (!res.ok)
142
+ return null;
143
+ const buf = Buffer.from(await res.arrayBuffer());
144
+ const out = new Map();
145
+ for (const f of iterFields(buf)) {
146
+ if (f.num !== 1 || f.wire !== 2 || !Buffer.isBuffer(f.value))
147
+ continue;
148
+ const cfg = parseCfg(f.value);
149
+ if (cfg)
150
+ out.set(cfg.uid, cfg);
151
+ }
152
+ return out;
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `devin-proxy` CLI — serve | login | version.
4
+ *
5
+ * Ported from devin_proxy/cli.py (the serve path; login reuses devin-core's
6
+ * PKCE flow).
7
+ */
8
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `devin-proxy` CLI — serve | login | version.
4
+ *
5
+ * Ported from devin_proxy/cli.py (the serve path; login reuses devin-core's
6
+ * PKCE flow).
7
+ */
8
+ import { loadSettings } from "./config.js";
9
+ import { serve } from "./server.js";
10
+ const PKG_VERSION = "0.1.1";
11
+ const USAGE = `devin-proxy — OpenAI-compatible proxy over the Devin backend
12
+
13
+ Usage:
14
+ devin-proxy serve [--host H] [--port P] [--backend URL]
15
+ devin-proxy login [--api-key TOKEN] # PKCE browser flow, or write token
16
+ devin-proxy version
17
+ `;
18
+ async function main(argv) {
19
+ const args = argv.slice(2);
20
+ const cmd = args[0] ?? "serve";
21
+ const flag = (name) => {
22
+ const i = args.indexOf(`--${name}`);
23
+ return i >= 0 ? args[i + 1] : undefined;
24
+ };
25
+ if (cmd === "version" || cmd === "--version" || cmd === "-V") {
26
+ console.log(PKG_VERSION);
27
+ return 0;
28
+ }
29
+ if (cmd === "help" || cmd === "--help" || cmd === "-h") {
30
+ process.stdout.write(USAGE);
31
+ return 0;
32
+ }
33
+ if (cmd === "login") {
34
+ const apiKey = flag("api-key");
35
+ const { Auth, writeCredentials, defaultCredentialsPath } = await import("./auth.js");
36
+ if (apiKey) {
37
+ writeCredentials(defaultCredentialsPath(), apiKey);
38
+ console.log(`credentials written to ${defaultCredentialsPath()}`);
39
+ return 0;
40
+ }
41
+ // PKCE browser flow via devin-core
42
+ const { loginAuto, openBrowser } = await import("devin-core");
43
+ const flow = await loginAuto();
44
+ openBrowser(flow.url);
45
+ console.log(`opened ${flow.url} — finish the login in the browser`);
46
+ const token = await flow.finish();
47
+ if (token) {
48
+ writeCredentials(defaultCredentialsPath(), token);
49
+ console.log(`credentials written to ${defaultCredentialsPath()}`);
50
+ return 0;
51
+ }
52
+ console.error("login produced no token");
53
+ return 1;
54
+ }
55
+ if (cmd === "serve" || cmd === undefined) {
56
+ const settings = loadSettings({
57
+ ...(flag("host") ? { host: flag("host") } : {}),
58
+ ...(flag("port") ? { port: parseInt(flag("port"), 10) } : {}),
59
+ ...(flag("backend") ? { backend: flag("backend") } : {}),
60
+ });
61
+ await serve(settings);
62
+ // Block forever — the server keeps the event loop alive; exiting main
63
+ // would process.exit() and kill it. Signal handlers let Ctrl+C through.
64
+ await new Promise(() => { });
65
+ return 0;
66
+ }
67
+ process.stderr.write(USAGE);
68
+ return 1;
69
+ }
70
+ main(process.argv).then((code) => process.exit(code), (e) => {
71
+ console.error("[devin-proxy]", e);
72
+ process.exit(1);
73
+ });
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Runtime configuration: env var > ~/.devin-proxy/settings.toml > default.
3
+ *
4
+ * Ported from devin_proxy/config.py.
5
+ */
6
+ export declare const SETTINGS_TOML: string;
7
+ export declare const FALLBACK_VERSION = "3000.11.234";
8
+ export declare const CHANNEL = "chisel";
9
+ /** Version of the `devin` binary on PATH ("" when absent). */
10
+ export declare function cliVersion(): string;
11
+ export interface Settings {
12
+ host: string;
13
+ port: number;
14
+ backend: string;
15
+ clientVersion: string;
16
+ emitReasoning: boolean;
17
+ stripIncomingReasoning: boolean;
18
+ guardChars: number;
19
+ guardFull: boolean;
20
+ planPreamble: boolean;
21
+ maxRetries: number;
22
+ retryTemps: string;
23
+ toolDesc: "full" | "compact" | "none";
24
+ nativeTools: boolean;
25
+ imgMaxBytes: number;
26
+ keepClientSystem: boolean;
27
+ maxInputTokens: number;
28
+ pruneKeepTurns: number;
29
+ allowedModels: string[];
30
+ allowPaid: boolean;
31
+ defaultModel: string;
32
+ clientModelId: string;
33
+ systemFile?: string;
34
+ }
35
+ export declare function loadSettings(overrides?: Partial<Settings>): Settings;
package/dist/config.js ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Runtime configuration: env var > ~/.devin-proxy/settings.toml > default.
3
+ *
4
+ * Ported from devin_proxy/config.py.
5
+ */
6
+ import { execFileSync } from "node:child_process";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+ export const SETTINGS_TOML = join(homedir(), ".devin-proxy", "settings.toml");
11
+ /** Minimal TOML reader: only [devin_proxy] KEY = VALUE scalars/arrays matter. */
12
+ function fileOverrides() {
13
+ try {
14
+ if (!existsSync(SETTINGS_TOML))
15
+ return {};
16
+ const text = readFileSync(SETTINGS_TOML, "utf-8");
17
+ const out = {};
18
+ let inSection = false;
19
+ for (const raw of text.split(/\r?\n/)) {
20
+ const line = raw.trim();
21
+ if (!line || line.startsWith("#"))
22
+ continue;
23
+ if (line.startsWith("[")) {
24
+ inSection = line.replace(/[\[\]\s]/g, "").toLowerCase() === "devin_proxy";
25
+ continue;
26
+ }
27
+ if (!inSection)
28
+ continue;
29
+ const eq = line.indexOf("=");
30
+ if (eq < 0)
31
+ continue;
32
+ const key = line.slice(0, eq).trim().toLowerCase().replace(/^devin_proxy_/, "");
33
+ let val = line.slice(eq + 1).trim();
34
+ if (typeof val === "string" && val.startsWith('"') && val.endsWith('"'))
35
+ val = val.slice(1, -1);
36
+ else if (typeof val === "string" && val.startsWith("[") && val.endsWith("]")) {
37
+ val = val.slice(1, -1).split(",").map((s) => s.trim().replace(/^"|"$/g, "")).filter(Boolean);
38
+ }
39
+ else if (val === "true" || val === "false")
40
+ val = val === "true";
41
+ else if (typeof val === "string" && /^-?\d+$/.test(val))
42
+ val = parseInt(val, 10);
43
+ else if (typeof val === "string" && /^-?\d*\.\d+$/.test(val))
44
+ val = parseFloat(val);
45
+ out[key] = val;
46
+ }
47
+ return out;
48
+ }
49
+ catch {
50
+ return {};
51
+ }
52
+ }
53
+ export const FALLBACK_VERSION = "3000.11.234";
54
+ export const CHANNEL = "chisel";
55
+ /** Version of the `devin` binary on PATH ("" when absent). */
56
+ export function cliVersion() {
57
+ try {
58
+ const exe = process.platform === "win32" ? "devin.exe" : "devin";
59
+ const out = execFileSync(exe, ["version"], { timeout: 10000, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
60
+ const m = /(\d+\.\d+\.\d+)/.exec(out);
61
+ return m ? m[1] : "";
62
+ }
63
+ catch {
64
+ return "";
65
+ }
66
+ }
67
+ const DEFAULTS = {
68
+ host: "127.0.0.1",
69
+ port: 8390,
70
+ backend: "https://server.codeium.com",
71
+ clientVersion: "auto",
72
+ emitReasoning: false,
73
+ stripIncomingReasoning: true,
74
+ guardChars: 300,
75
+ guardFull: false,
76
+ planPreamble: false,
77
+ maxRetries: 3,
78
+ retryTemps: "0.85,1.0,1.1",
79
+ toolDesc: "compact",
80
+ nativeTools: true,
81
+ imgMaxBytes: 12 * 1024 * 1024,
82
+ keepClientSystem: false,
83
+ maxInputTokens: 240000,
84
+ pruneKeepTurns: 12,
85
+ allowedModels: [
86
+ "swe-2-medium", "swe-2-high", "swe-2-max",
87
+ "swe-2-flash-medium", "swe-2-flash-high", "swe-2-flash-max",
88
+ "swe-2-1-low", "swe-2-1-medium", "swe-2-1-high", "swe-2-1-xhigh", "swe-2-1-max",
89
+ ],
90
+ allowPaid: false,
91
+ defaultModel: "swe-2-high",
92
+ clientModelId: "swe-2",
93
+ };
94
+ const env = (k) => process.env["DEVIN_PROXY_" + k];
95
+ export function loadSettings(overrides = {}) {
96
+ const merged = { ...fileOverrides(), ...overrides };
97
+ const s = { ...DEFAULTS };
98
+ const pick = (key, envName, parse) => {
99
+ const e = env(envName);
100
+ const sAny = s;
101
+ if (e !== undefined)
102
+ sAny[key] = parse(e);
103
+ else if (merged[key] !== undefined)
104
+ sAny[key] = merged[key];
105
+ };
106
+ pick("host", "HOST", (v) => v);
107
+ pick("port", "PORT", (v) => parseInt(v, 10));
108
+ pick("backend", "BACKEND", (v) => v.replace(/\/+$/, ""));
109
+ pick("clientVersion", "CLIENT_VERSION", (v) => v);
110
+ pick("emitReasoning", "EMIT_REASONING", (v) => v === "true" || v === "1");
111
+ pick("stripIncomingReasoning", "STRIP_INCOMING_REASONING", (v) => v !== "false" && v !== "0");
112
+ pick("guardChars", "GUARD_CHARS", (v) => parseInt(v, 10));
113
+ pick("guardFull", "GUARD_FULL", (v) => v === "true" || v === "1");
114
+ pick("planPreamble", "PLAN_PREAMBLE", (v) => v === "true" || v === "1");
115
+ pick("maxRetries", "MAX_RETRIES", (v) => parseInt(v, 10));
116
+ pick("retryTemps", "RETRY_TEMPS", (v) => v);
117
+ pick("toolDesc", "TOOL_DESC", (v) => v.toLowerCase());
118
+ pick("nativeTools", "NATIVE_TOOLS", (v) => v !== "false" && v !== "0");
119
+ pick("imgMaxBytes", "IMG_MAX_BYTES", (v) => parseInt(v, 10));
120
+ pick("keepClientSystem", "KEEP_CLIENT_SYSTEM", (v) => v === "true" || v === "1");
121
+ pick("maxInputTokens", "MAX_INPUT_TOKENS", (v) => parseInt(v, 10));
122
+ pick("pruneKeepTurns", "PRUNE_KEEP_TURNS", (v) => parseInt(v, 10));
123
+ pick("allowedModels", "ALLOWED_MODELS", (v) => v.split(",").map((x) => x.trim()).filter(Boolean));
124
+ pick("allowPaid", "ALLOW_PAID", (v) => v === "true" || v === "1");
125
+ pick("defaultModel", "DEFAULT_MODEL", (v) => v);
126
+ pick("clientModelId", "CLIENT_MODEL_ID", (v) => v);
127
+ pick("systemFile", "SYSTEM_FILE", (v) => v);
128
+ if (s.clientVersion === "auto")
129
+ s.clientVersion = cliVersion() || FALLBACK_VERSION;
130
+ else if (!s.clientVersion)
131
+ s.clientVersion = FALLBACK_VERSION;
132
+ return s;
133
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * devin-proxy — the standalone OpenAI-compatible proxy over devin-engine.
3
+ *
4
+ * Library exports; the `devin-proxy` bin runs `cli.ts`.
5
+ */
6
+ export { loadSettings, SETTINGS_TOML, FALLBACK_VERSION, CHANNEL, cliVersion, type Settings } from "./config.js";
7
+ export { Auth, defaultCredentialsPath, readKey, writeCredentials } from "./auth.js";
8
+ export { fetchCliCatalog, type CliModelConfig } from "./catalog.js";
9
+ export { buildApp, serve, type App, type ServeHandle } from "./server.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * devin-proxy — the standalone OpenAI-compatible proxy over devin-engine.
3
+ *
4
+ * Library exports; the `devin-proxy` bin runs `cli.ts`.
5
+ */
6
+ export { loadSettings, SETTINGS_TOML, FALLBACK_VERSION, CHANNEL, cliVersion } from "./config.js";
7
+ export { Auth, defaultCredentialsPath, readKey, writeCredentials } from "./auth.js";
8
+ export { fetchCliCatalog } from "./catalog.js";
9
+ export { buildApp, serve } from "./server.js";
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The OpenAI-compatible HTTP surface: /v1/chat/completions (SSE + unary),
3
+ * /v1/models, /health, /v1/image_caption, /v1/web_search.
4
+ *
5
+ * node:http server — no framework. The Engine drives the upstream; this
6
+ * layer only frames deltas as chat.completion.chunk SSE events.
7
+ *
8
+ * Ported from devin_proxy/api/routes.py + server.py.
9
+ */
10
+ import { type Server } from "node:http";
11
+ import { Engine, OverridePrompt } from "devin-engine";
12
+ import type { Auth } from "./auth.js";
13
+ import type { CliModelConfig } from "./catalog.js";
14
+ import type { Settings } from "./config.js";
15
+ export interface App {
16
+ server: Server;
17
+ /** Catalog lands after boot — routes degrade until it does. */
18
+ setCatalog(cat: Map<string, CliModelConfig>): void;
19
+ }
20
+ export declare function buildApp(settings: Settings, auth: Auth, engine: Engine, override: OverridePrompt): App;
21
+ export interface ServeHandle {
22
+ server: Server;
23
+ engine: Engine;
24
+ close(): void;
25
+ }
26
+ /** settings -> auth -> engine -> http server. Ported from server.py::serve. */
27
+ export declare function serve(settings: Settings): Promise<ServeHandle>;
package/dist/server.js ADDED
@@ -0,0 +1,322 @@
1
+ /**
2
+ * The OpenAI-compatible HTTP surface: /v1/chat/completions (SSE + unary),
3
+ * /v1/models, /health, /v1/image_caption, /v1/web_search.
4
+ *
5
+ * node:http server — no framework. The Engine drives the upstream; this
6
+ * layer only frames deltas as chat.completion.chunk SSE events.
7
+ *
8
+ * Ported from devin_proxy/api/routes.py + server.py.
9
+ */
10
+ import { createServer } from "node:http";
11
+ import { randomUUID } from "node:crypto";
12
+ import { Engine, OverridePrompt } from "devin-engine";
13
+ const log = (...args) => console.log(`[devin-proxy]`, ...args);
14
+ const logWarn = (...args) => console.warn(`[devin-proxy]`, ...args);
15
+ const REASONING_OFF = new Set(["none", "off", "disabled", "false", "no", "0"]);
16
+ function clientReasoningOff(data) {
17
+ if (REASONING_OFF.has(String(data.reasoning_effort ?? "").trim().toLowerCase()))
18
+ return true;
19
+ const r = data.reasoning;
20
+ if (r && (r.enabled === false || REASONING_OFF.has(String(r.effort ?? "").trim().toLowerCase())))
21
+ return true;
22
+ const t = data.thinking;
23
+ if (t && (t.enabled === false || t.thinking === false || REASONING_OFF.has(String(t.type ?? "").trim().toLowerCase())))
24
+ return true;
25
+ return data.enable_thinking === false;
26
+ }
27
+ const REASONING_BLOCK = {
28
+ supported_efforts: ["none", "minimal", "low", "medium", "high", "xhigh", "max"],
29
+ default_effort: "high",
30
+ default_enabled: true,
31
+ mandatory: false,
32
+ };
33
+ const REASONING_EFFORTS = REASONING_BLOCK.supported_efforts;
34
+ function json(res, status, body) {
35
+ const payload = JSON.stringify(body);
36
+ res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) });
37
+ res.end(payload);
38
+ }
39
+ function sseHeaders(res) {
40
+ res.writeHead(200, {
41
+ "Content-Type": "text/event-stream",
42
+ "Cache-Control": "no-cache",
43
+ Connection: "keep-alive",
44
+ "X-Accel-Buffering": "no",
45
+ });
46
+ }
47
+ function sse(res, data) {
48
+ res.write(`data: ${data}\n\n`);
49
+ }
50
+ async function readBody(req) {
51
+ const chunks = [];
52
+ for await (const c of req)
53
+ chunks.push(c);
54
+ return Buffer.concat(chunks).toString("utf8");
55
+ }
56
+ export function buildApp(settings, auth, engine, override) {
57
+ let catalog = null;
58
+ const modelEntry = (uid, cfg) => ({
59
+ id: uid,
60
+ object: "model",
61
+ created: Math.floor(Date.now() / 1000),
62
+ name: cfg?.name ?? uid.replace("swe-2-1-", "SWE-2.1 ").replace("swe-2-", "SWE-2 ").replace(/\b\w/g, (c) => c.toUpperCase()),
63
+ owned_by: "devin",
64
+ context_window: cfg?.context ?? 262144,
65
+ max_tokens: 16384,
66
+ reasoning: REASONING_BLOCK,
67
+ supported_reasoning_efforts: REASONING_EFFORTS,
68
+ ...(cfg?.aliases?.length ? { aliases: cfg.aliases } : {}),
69
+ });
70
+ const modelsHandler = () => {
71
+ const data = [];
72
+ if (settings.allowPaid && catalog) {
73
+ const allowed = new Set(settings.allowedModels);
74
+ for (const cfg of [...catalog.values()].sort((a, b) => a.uid.localeCompare(b.uid))) {
75
+ data.push({
76
+ id: cfg.uid, object: "model", created: Math.floor(Date.now() / 1000),
77
+ name: cfg.name || cfg.uid, owned_by: "devin",
78
+ context_window: cfg.context || 262144, max_tokens: 16384,
79
+ credits_per_run: cfg.credits || undefined,
80
+ free_tier: allowed.has(cfg.uid),
81
+ free_until: cfg.expiryIso() || undefined,
82
+ aliases: cfg.aliases.length ? cfg.aliases : undefined,
83
+ });
84
+ }
85
+ return { object: "list", data };
86
+ }
87
+ for (const uid of settings.allowedModels)
88
+ data.push(modelEntry(uid, catalog?.get(uid)));
89
+ data.unshift({
90
+ ...modelEntry(settings.clientModelId, catalog?.get(settings.defaultModel)),
91
+ wire_model: settings.defaultModel,
92
+ });
93
+ const flash = catalog?.get("swe-2-flash-high");
94
+ if (flash || settings.allowedModels.includes("swe-2-flash-high")) {
95
+ data.splice(1, 0, { ...modelEntry("swe-2-flash", flash), wire_model: "swe-2-flash-high" });
96
+ }
97
+ const s21 = catalog?.get("swe-2-1-high");
98
+ if (s21 || settings.allowedModels.includes("swe-2-1-high")) {
99
+ data.splice(2, 0, { ...modelEntry("swe-2.1", s21), wire_model: "swe-2-1-high" });
100
+ }
101
+ return { object: "list", data };
102
+ };
103
+ const healthHandler = () => ({
104
+ status: "ok",
105
+ backend: settings.backend,
106
+ override_file: override.path,
107
+ override_chars: override.load().length,
108
+ models: [settings.clientModelId],
109
+ wire_models: settings.allowedModels,
110
+ catalog_models: catalog?.size ?? 0,
111
+ free_until: catalog
112
+ ? Object.fromEntries([...catalog.values()].filter((c) => c.expiresAt).map((c) => [c.uid, c.expiryIso()]))
113
+ : {},
114
+ });
115
+ const chatHandler = async (req, res) => {
116
+ let data;
117
+ try {
118
+ data = JSON.parse(await readBody(req));
119
+ }
120
+ catch {
121
+ return json(res, 400, { error: { message: "invalid JSON body", type: "invalid_request" } });
122
+ }
123
+ const respId = "chatcmpl-" + randomUUID().replace(/-/g, "").slice(0, 24);
124
+ const created = Math.floor(Date.now() / 1000);
125
+ const fingerprint = "fp_devin";
126
+ const clientOff = clientReasoningOff(data);
127
+ const isStream = data.stream === true;
128
+ const dropReasoning = (delta) => (clientOff || !settings.emitReasoning) && "reasoning_content" in delta;
129
+ if (isStream) {
130
+ sseHeaders(res);
131
+ const send = (payload) => {
132
+ if ("data" in payload && payload.data === "[DONE]")
133
+ sse(res, "[DONE]");
134
+ else
135
+ sse(res, JSON.stringify(payload));
136
+ };
137
+ const chunk = (delta, finishReason = null) => ({
138
+ id: respId, object: "chat.completion.chunk", created,
139
+ model: settings.clientModelId, system_fingerprint: fingerprint,
140
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
141
+ });
142
+ const emit = (delta) => {
143
+ if (dropReasoning(delta)) {
144
+ const { reasoning_content: _r, ...rest } = delta;
145
+ if (!Object.keys(rest).length)
146
+ return;
147
+ delta = rest;
148
+ }
149
+ send(chunk(delta));
150
+ };
151
+ const finish = (final) => {
152
+ send(chunk({}, String(final?.finish_reason ?? "stop")));
153
+ send({ data: "[DONE]" });
154
+ };
155
+ const includeUsage = data.stream_options?.include_usage === true;
156
+ const usageEmit = (usage) => {
157
+ if (!includeUsage)
158
+ return;
159
+ send({ ...chunk({}), choices: [], usage });
160
+ };
161
+ send(chunk({ role: "assistant" }));
162
+ try {
163
+ await engine.run(data, emit, finish, usageEmit);
164
+ }
165
+ catch (e) {
166
+ logWarn("engine error:", e);
167
+ send({
168
+ id: respId, object: "chat.completion.chunk", created,
169
+ model: settings.clientModelId, system_fingerprint: fingerprint,
170
+ choices: [{ index: 0, delta: { content: `[devin-proxy] error: ${e.message}` }, finish_reason: "stop" }],
171
+ });
172
+ send({ data: "[DONE]" });
173
+ }
174
+ res.end();
175
+ return;
176
+ }
177
+ // non-stream
178
+ const chunks = [];
179
+ const finishMeta = {};
180
+ const usage = {};
181
+ const emit = (delta) => {
182
+ if (dropReasoning(delta))
183
+ return;
184
+ chunks.push(delta);
185
+ };
186
+ try {
187
+ await engine.run(data, emit, (f) => Object.assign(finishMeta, f ?? {}), (u) => Object.assign(usage, u));
188
+ }
189
+ catch (e) {
190
+ logWarn("engine error:", e);
191
+ return json(res, 502, { error: { message: e.message, type: "server_error" } });
192
+ }
193
+ const text = chunks.map((c) => String(c.content ?? "")).join("");
194
+ const think = chunks.map((c) => String(c.reasoning_content ?? "")).join("");
195
+ const calls = chunks.find((c) => c.tool_calls)?.tool_calls;
196
+ const msg = { role: "assistant", content: text || null };
197
+ if (calls?.length)
198
+ msg.tool_calls = calls;
199
+ if (think && !clientOff) {
200
+ msg.reasoning_content = think;
201
+ msg.reasoning = think;
202
+ }
203
+ json(res, 200, {
204
+ id: respId, object: "chat.completion", created,
205
+ model: settings.clientModelId, system_fingerprint: fingerprint,
206
+ choices: [{ index: 0, message: msg, finish_reason: finishMeta.finish_reason ?? (calls?.length ? "tool_calls" : "stop") }],
207
+ usage: Object.keys(usage).length ? usage : { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
208
+ });
209
+ };
210
+ const server = createServer(async (req, res) => {
211
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
212
+ const path = url.pathname;
213
+ try {
214
+ if (req.method === "GET" && path === "/health")
215
+ return json(res, 200, healthHandler());
216
+ if (req.method === "GET" && (path === "/v1/models" || path === "/models"))
217
+ return json(res, 200, modelsHandler());
218
+ if (req.method === "POST" && path === "/v1/chat/completions")
219
+ return await chatHandler(req, res);
220
+ if (req.method === "POST" && path === "/v1/image_caption") {
221
+ const body = JSON.parse(await readBody(req));
222
+ const b64 = String(body.image ?? body.data ?? "");
223
+ const mime = String(body.mime ?? "image/png");
224
+ if (!b64)
225
+ return json(res, 400, { error: { message: "missing image", type: "invalid_request" } });
226
+ try {
227
+ const { imageCaption } = await import("./catalog.js");
228
+ const caption = await imageCaption(settings.backend, auth.apiKey(), await auth.jwt(), b64, mime, settings.clientVersion);
229
+ return json(res, 200, { caption });
230
+ }
231
+ catch (e) {
232
+ logWarn("image caption failed:", e);
233
+ return json(res, 502, { error: { message: e.message, type: "server_error" } });
234
+ }
235
+ }
236
+ if (req.method === "POST" && path === "/v1/web_search") {
237
+ const body = JSON.parse(await readBody(req));
238
+ const query = String(body.query ?? body.q ?? "").trim();
239
+ if (!query)
240
+ return json(res, 400, { error: { message: "missing query", type: "invalid_request" } });
241
+ try {
242
+ const { webSearch } = await import("./catalog.js");
243
+ const results = await webSearch(settings.backend, auth.apiKey(), await auth.jwt(), query, settings.clientVersion);
244
+ return json(res, 200, { object: "list", data: results });
245
+ }
246
+ catch (e) {
247
+ logWarn("web search failed:", e);
248
+ return json(res, 502, { error: { message: e.message, type: "server_error" } });
249
+ }
250
+ }
251
+ return json(res, 404, { error: { message: "not found", type: "invalid_request" } });
252
+ }
253
+ catch (e) {
254
+ logWarn("unhandled:", e);
255
+ return json(res, 500, { error: { message: e.message, type: "server_error" } });
256
+ }
257
+ });
258
+ return {
259
+ server,
260
+ setCatalog(cat) {
261
+ catalog = cat;
262
+ },
263
+ };
264
+ }
265
+ /** settings -> auth -> engine -> http server. Ported from server.py::serve. */
266
+ export async function serve(settings) {
267
+ const { fetchCliCatalog } = await import("./catalog.js");
268
+ const { Auth } = await import("./auth.js");
269
+ const { resolveSystemFile } = await import("devin-engine");
270
+ const auth = new Auth(settings.backend);
271
+ const override = new OverridePrompt(resolveSystemFile(settings.systemFile));
272
+ const engineSettings = {
273
+ backend: settings.backend,
274
+ guardChars: settings.guardChars,
275
+ guardFull: settings.guardFull,
276
+ maxRetries: settings.maxRetries,
277
+ retryTemps: settings.retryTemps,
278
+ toolDesc: settings.toolDesc,
279
+ nativeTools: settings.nativeTools,
280
+ imgMaxBytes: settings.imgMaxBytes,
281
+ keepClientSystem: settings.keepClientSystem,
282
+ maxInputTokens: settings.maxInputTokens,
283
+ pruneKeepTurns: settings.pruneKeepTurns,
284
+ allowedModels: settings.allowedModels,
285
+ allowPaid: settings.allowPaid,
286
+ defaultModel: settings.defaultModel,
287
+ emitReasoning: settings.emitReasoning,
288
+ stripIncomingReasoning: settings.stripIncomingReasoning,
289
+ planPreamble: settings.planPreamble,
290
+ };
291
+ const engine = new Engine(engineSettings, auth.apiKey(), override, undefined);
292
+ const app = buildApp(settings, auth, engine, override);
293
+ // Prefetch the CLI catalog in the background — /v1/models and allowPaid
294
+ // routing degrade gracefully until it lands. The engine's catalog list is
295
+ // refreshed in place so allowPaid starts routing once it lands.
296
+ void fetchCliCatalog(settings.backend, auth.apiKey(), await auth.jwt().catch(() => ""), settings.clientVersion)
297
+ .then((cat) => {
298
+ if (cat?.size) {
299
+ app.setCatalog(cat);
300
+ engine.catalog = [...cat.values()].map((c) => ({ uid: c.uid }));
301
+ log(`model catalog: ${cat.size} configs`);
302
+ }
303
+ })
304
+ .catch((e) => logWarn("catalog prefetch skipped:", e));
305
+ await new Promise((resolve) => {
306
+ app.server.listen(settings.port, settings.host, resolve);
307
+ });
308
+ log(`listening on ${settings.host}:${settings.port} -> ${settings.backend} ` +
309
+ `(allowed=${settings.allowedModels.join(",")}${settings.allowPaid ? "+paid" : ""}) override=${override.load().length}c`);
310
+ try {
311
+ auth.apiKey();
312
+ log(`devin credentials ok (${auth.credentials})`);
313
+ }
314
+ catch (e) {
315
+ logWarn("credentials unavailable:", e.message);
316
+ }
317
+ return {
318
+ server: app.server,
319
+ engine,
320
+ close: () => app.server.close(),
321
+ };
322
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
- {
2
- "name": "devin-proxy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "devin-proxy",
3
+ "version": "0.1.1",
4
+ "description": "OpenAI-compatible local proxy over the Devin/Cascade backend — SWE-2/SWE-2.1 lanes through the guarded-retry devin-engine",
5
+ "type": "module",
6
+ "bin": {
7
+ "devin-proxy": "./dist/cli.js"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.build.json",
23
+ "prepare": "bun run build",
24
+ "test": "bun test",
25
+ "typecheck": "tsc --noEmit",
26
+ "start": "bun src/cli.ts"
27
+ },
28
+ "keywords": [
29
+ "devin",
30
+ "cognition",
31
+ "swe",
32
+ "openai-compatible",
33
+ "proxy"
34
+ ],
35
+ "license": "MIT",
36
+ "author": {
37
+ "name": "JoShMiQueL",
38
+ "email": "joshmiquel.cs@gmail.com"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/JoShMiQueL/devin-proxy.git"
43
+ },
44
+ "dependencies": {
45
+ "devin-core": "^0.0.3",
46
+ "devin-engine": "^0.0.3"
47
+ },
48
+ "devDependencies": {
49
+ "@types/bun": "^1.4.4",
50
+ "@types/node": "^26.6.7",
51
+ "typescript": "^7.0.2"
52
+ }
6
53
  }