opencode-agent-orchestration-kit 1.0.37 → 1.0.39
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 +61 -4
- package/docker/open-design/Dockerfile +3 -1
- package/docker/open-design/entrypoint.mjs +61 -0
- package/docs/docker-open-design.md +5 -0
- package/docs/models.md +30 -0
- package/docs/open-design.md +8 -0
- package/docs/releases/v1.0.38.md +44 -0
- package/docs/releases/v1.0.39.md +44 -0
- package/opencode/tools/open-design-http.d.mts +45 -0
- package/opencode/tools/open-design-http.mjs +387 -0
- package/opencode/tools/open_design.ts +1 -102
- package/package.json +5 -3
- package/scripts/check-supply-chain.mjs +4 -1
- package/scripts/check-supply-chain.test.mjs +6 -5
- package/scripts/check.sh +4 -2
- package/scripts/oak.test.mjs +9 -2
- package/scripts/oc-switch.mjs +472 -0
- package/scripts/oc-switch.test.mjs +217 -0
- package/scripts/open-design-entrypoint.test.mjs +54 -0
- package/scripts/open-design-http.test.mjs +211 -0
- package/scripts/package-smoke.mjs +16 -2
- package/scripts/package-smoke.test.mjs +7 -5
- package/scripts/version.test.mjs +2 -2
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { emitKeypressEvents } from "node:readline";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
|
|
10
|
+
export const AGENT_IDS = [
|
|
11
|
+
"lead", "designer", "researcher", "specifier", "developer",
|
|
12
|
+
"reviewer", "evaluator", "debugger", "evolver",
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
const ANSI = Object.freeze({
|
|
16
|
+
eraseDown: "\u001b[0J",
|
|
17
|
+
hideCursor: "\u001b[?25l",
|
|
18
|
+
showCursor: "\u001b[?25h",
|
|
19
|
+
reverse: "\u001b[7m",
|
|
20
|
+
reset: "\u001b[0m",
|
|
21
|
+
dim: "\u001b[2m",
|
|
22
|
+
});
|
|
23
|
+
const STATE_VERSION = 1;
|
|
24
|
+
const STATE_PARTS = ["opencode", "model-switcher", "state.json"];
|
|
25
|
+
const SHELL_START = "# >>> oc-switch managed model routing >>>";
|
|
26
|
+
const SHELL_END = "# <<< oc-switch managed model routing <<<";
|
|
27
|
+
|
|
28
|
+
const agentEnvKey = (agent) => `OPENCODE_${agent.toUpperCase()}_MODEL`;
|
|
29
|
+
|
|
30
|
+
function validateModelReference(value) {
|
|
31
|
+
if (typeof value !== "string" || value.length === 0 || /\s/.test(value)) {
|
|
32
|
+
throw new Error("model must be a provider/model reference");
|
|
33
|
+
}
|
|
34
|
+
const slash = value.indexOf("/");
|
|
35
|
+
if (slash <= 0 || slash === value.length - 1) {
|
|
36
|
+
throw new Error("model must have the form provider/model");
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function providerFromModel(modelRef) {
|
|
42
|
+
return validateModelReference(modelRef).slice(0, validateModelReference(modelRef).indexOf("/"));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseConfigProviderIds(contents) {
|
|
46
|
+
try {
|
|
47
|
+
const parsed = JSON.parse(contents);
|
|
48
|
+
return parsed?.provider && typeof parsed.provider === "object"
|
|
49
|
+
? Object.keys(parsed.provider).filter((providerId) => /^[^\s/]+$/.test(providerId))
|
|
50
|
+
: [];
|
|
51
|
+
} catch {
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function parseOpenCodeModelList(stdout) {
|
|
57
|
+
if (typeof stdout !== "string") throw new Error("catalog stdout must be a string");
|
|
58
|
+
const grouped = {};
|
|
59
|
+
const seen = new Set();
|
|
60
|
+
for (const rawLine of stdout.split(/\r?\n/)) {
|
|
61
|
+
const modelRef = rawLine.trim();
|
|
62
|
+
if (!modelRef || /\s/.test(modelRef)) continue;
|
|
63
|
+
try { validateModelReference(modelRef); } catch { continue; }
|
|
64
|
+
if (seen.has(modelRef)) continue;
|
|
65
|
+
seen.add(modelRef);
|
|
66
|
+
const providerId = providerFromModel(modelRef);
|
|
67
|
+
(grouped[providerId] ??= []).push(modelRef);
|
|
68
|
+
}
|
|
69
|
+
return grouped;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function parseOpenCodeAuthProviders(stdout) {
|
|
73
|
+
if (typeof stdout !== "string") throw new Error("auth stdout must be a string");
|
|
74
|
+
const providers = [];
|
|
75
|
+
let credentials = false;
|
|
76
|
+
for (const rawLine of stdout.split(/\r?\n/)) {
|
|
77
|
+
const line = rawLine.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "").trim();
|
|
78
|
+
if (/\bEnvironment\b/i.test(line) && !line.startsWith("●")) break;
|
|
79
|
+
if (/\bCredentials\b/i.test(line)) {
|
|
80
|
+
credentials = true;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!credentials || !line.startsWith("●")) continue;
|
|
84
|
+
const label = line.slice(1).trim().replace(/\s+(?:oauth|api|token|key)$/i, "");
|
|
85
|
+
const providerId = label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
86
|
+
if (providerId && !providers.includes(providerId)) providers.push(providerId);
|
|
87
|
+
}
|
|
88
|
+
return providers;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function providerIdsFromEnvironment(env) {
|
|
92
|
+
const refs = Object.entries(env)
|
|
93
|
+
.filter(([key]) => /^OPENCODE_(?:MODEL|SMALL_MODEL|[A-Z0-9_]+_MODEL)$/.test(key))
|
|
94
|
+
.map(([, value]) => value);
|
|
95
|
+
return refs.flatMap((value) => {
|
|
96
|
+
try { return [providerFromModel(value)]; } catch { return []; }
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function configuredProviderIds({ homeDir, env = process.env, cwd = process.cwd() }) {
|
|
101
|
+
const providers = [];
|
|
102
|
+
const add = (values) => values.forEach((value) => {
|
|
103
|
+
if (!providers.includes(value)) providers.push(value);
|
|
104
|
+
});
|
|
105
|
+
add(providerIdsFromEnvironment(env));
|
|
106
|
+
if (typeof env.OPENCODE_CONFIG_CONTENT === "string") {
|
|
107
|
+
add(parseConfigProviderIds(env.OPENCODE_CONFIG_CONTENT));
|
|
108
|
+
}
|
|
109
|
+
const configPaths = [
|
|
110
|
+
env.OPENCODE_CONFIG,
|
|
111
|
+
path.join(cwd, "opencode.json"),
|
|
112
|
+
path.join(homeDir, ".config", "opencode", "opencode.json"),
|
|
113
|
+
].filter((value, index, values) => typeof value === "string" && value && values.indexOf(value) === index);
|
|
114
|
+
configPaths.forEach((configPath) => {
|
|
115
|
+
try { add(parseConfigProviderIds(fs.readFileSync(configPath, "utf8"))); } catch { /* optional config */ }
|
|
116
|
+
});
|
|
117
|
+
return providers;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function applyModelSelection(state, { target, agents = [], modelRef } = {}) {
|
|
121
|
+
validateModelReference(modelRef);
|
|
122
|
+
const next = JSON.parse(JSON.stringify(state));
|
|
123
|
+
if (target === "defaultModel" || target === "smallModel") {
|
|
124
|
+
next[target] = modelRef;
|
|
125
|
+
return next;
|
|
126
|
+
}
|
|
127
|
+
if (target !== "agents" || !Array.isArray(agents) || agents.length === 0) {
|
|
128
|
+
throw new Error("model selection target is invalid");
|
|
129
|
+
}
|
|
130
|
+
for (const agent of agents) {
|
|
131
|
+
if (!AGENT_IDS.includes(agent)) throw new Error("unknown agent");
|
|
132
|
+
next.agents[agent] = modelRef;
|
|
133
|
+
}
|
|
134
|
+
return next;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function rowsForState(state) {
|
|
138
|
+
return [
|
|
139
|
+
{ key: "defaultModel", label: "Default", modelRef: state.defaultModel, kind: "root" },
|
|
140
|
+
{ key: "smallModel", label: "Small/title", modelRef: state.smallModel, kind: "root" },
|
|
141
|
+
...AGENT_IDS.map((agent) => ({ key: agent, label: agent, modelRef: state.agents[agent], kind: "agent" })),
|
|
142
|
+
];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function renderMainScreen({ state, focusedIndex = 0, selectedAgents = new Set(), status = "", catalogFresh = false } = {}) {
|
|
146
|
+
const rows = rowsForState(state);
|
|
147
|
+
const lines = ["OpenCode Model Switcher", ""];
|
|
148
|
+
if (status) lines.push(`Status: ${status}`, "");
|
|
149
|
+
lines.push("Model assignments");
|
|
150
|
+
rows.forEach((row, index) => {
|
|
151
|
+
const selected = row.kind === "agent" && selectedAgents.has(row.key) ? "[x] " : " ";
|
|
152
|
+
const focus = index === focusedIndex ? "> " : " ";
|
|
153
|
+
lines.push(`${focus}${selected}${row.label.padEnd(12)} ${row.modelRef}`);
|
|
154
|
+
});
|
|
155
|
+
lines.push("", selectedAgents.size ? `Selected agents: ${[...selectedAgents].join(", ")}` : "Selected agents: none");
|
|
156
|
+
lines.push(`Catalog: ${catalogFresh ? "current" : "Loading models..."}`, "");
|
|
157
|
+
lines.push(`${ANSI.dim}↑↓ move Enter select Space mark / search r refresh${ANSI.reset}`);
|
|
158
|
+
lines.push(`${ANSI.dim}s save Esc back/clear q save and quit${ANSI.reset}`);
|
|
159
|
+
return lines.join("\n");
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function visibleWindow(models, focusedIndex, maxVisibleModels) {
|
|
163
|
+
const limit = Math.max(1, Number.isInteger(maxVisibleModels) ? maxVisibleModels : 14);
|
|
164
|
+
if (models.length <= limit) return { models, before: false, after: false };
|
|
165
|
+
const safeIndex = Math.max(0, Math.min(focusedIndex, models.length - 1));
|
|
166
|
+
const start = Math.min(Math.max(0, safeIndex - Math.floor(limit / 2)), models.length - limit);
|
|
167
|
+
return { models: models.slice(start, start + limit), before: start > 0, after: start + limit < models.length };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function renderModelPicker({ targetLabel = "model", models = [], query = "", focusedIndex = 0, maxVisibleModels = 14 } = {}) {
|
|
171
|
+
const filtered = models.filter((modelRef) => modelRef.toLowerCase().includes(String(query).trim().toLowerCase()));
|
|
172
|
+
const visible = visibleWindow(filtered, focusedIndex, maxVisibleModels);
|
|
173
|
+
const lines = [`Select model for ${targetLabel}`, `Search: ${query || "_"}`, ""];
|
|
174
|
+
if (visible.before) lines.push(`${ANSI.dim}↑ more models${ANSI.reset}`);
|
|
175
|
+
visible.models.forEach((modelRef) => {
|
|
176
|
+
const index = filtered.indexOf(modelRef);
|
|
177
|
+
lines.push(`${index === focusedIndex ? `${ANSI.reverse}> ` : " "}${modelRef}${index === focusedIndex ? ANSI.reset : ""}`);
|
|
178
|
+
});
|
|
179
|
+
if (visible.after) lines.push(`${ANSI.dim}↓ more models${ANSI.reset}`);
|
|
180
|
+
if (!filtered.length) lines.push("No configured models match the search.");
|
|
181
|
+
lines.push("", `${ANSI.dim}Enter select Esc back type to search Backspace delete${ANSI.reset}`);
|
|
182
|
+
return lines.join("\n");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function stateFromEnvironment(env, now) {
|
|
186
|
+
const defaultModel = validateModelReference(env.OPENCODE_MODEL);
|
|
187
|
+
const get = (key, fallback) => env[key] ? validateModelReference(env[key]) : fallback;
|
|
188
|
+
return {
|
|
189
|
+
schemaVersion: STATE_VERSION,
|
|
190
|
+
updatedAt: now(),
|
|
191
|
+
defaultModel,
|
|
192
|
+
smallModel: get("OPENCODE_SMALL_MODEL", defaultModel),
|
|
193
|
+
agents: Object.fromEntries(AGENT_IDS.map((agent) => [agent, get(agentEnvKey(agent), defaultModel)])),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function statePath({ homeDir = os.homedir(), env = process.env } = {}) {
|
|
198
|
+
const root = env.XDG_STATE_HOME || path.join(homeDir, ".local", "state");
|
|
199
|
+
return path.join(root, ...STATE_PARTS);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function readState(filePath, env, now) {
|
|
203
|
+
try {
|
|
204
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
205
|
+
if (!parsed || parsed.schemaVersion !== STATE_VERSION || !parsed.defaultModel || !parsed.smallModel) throw new Error("invalid state");
|
|
206
|
+
return parsed;
|
|
207
|
+
} catch (cause) {
|
|
208
|
+
if (cause?.code === "ENOENT") return stateFromEnvironment(env, now);
|
|
209
|
+
throw new Error("Saved OpenCode model state is invalid.", { cause });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function atomicWrite(filePath, contents) {
|
|
214
|
+
const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
215
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
216
|
+
try {
|
|
217
|
+
fs.writeFileSync(temporaryPath, contents, { mode: 0o600 });
|
|
218
|
+
fs.chmodSync(temporaryPath, 0o600);
|
|
219
|
+
fs.renameSync(temporaryPath, filePath);
|
|
220
|
+
} catch (cause) {
|
|
221
|
+
try { fs.rmSync(temporaryPath, { force: true }); } catch { /* best effort */ }
|
|
222
|
+
throw cause;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function shellQuote(value) { return `'${String(value).replaceAll("'", "'\\''")}'`; }
|
|
227
|
+
|
|
228
|
+
function shellRcPath({ homeDir, shell }) {
|
|
229
|
+
const name = path.basename(shell || "zsh");
|
|
230
|
+
if (name === "zsh") return path.join(homeDir, ".zshrc");
|
|
231
|
+
if (name === "bash") return path.join(homeDir, ".bashrc");
|
|
232
|
+
throw new Error("oc-switch supports zsh and bash startup files");
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function updateShellRc(contents, state) {
|
|
236
|
+
const managed = [SHELL_START, `export OPENCODE_MODEL=${shellQuote(state.defaultModel)}`, `export OPENCODE_SMALL_MODEL=${shellQuote(state.smallModel)}`,
|
|
237
|
+
...AGENT_IDS.map((agent) => `export ${agentEnvKey(agent)}=${shellQuote(state.agents[agent])}`), SHELL_END].join("\n");
|
|
238
|
+
const block = new RegExp(`${SHELL_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${SHELL_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\r?\\n?`, "g");
|
|
239
|
+
return `${contents.replace(block, "").trimEnd()}\n\n${managed}\n`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function findOpenCodeBinaryOnPath({ env = process.env } = {}) {
|
|
243
|
+
const candidates = [];
|
|
244
|
+
if (typeof env.OPENCODE_BIN === "string" && path.isAbsolute(env.OPENCODE_BIN)) {
|
|
245
|
+
candidates.push(env.OPENCODE_BIN);
|
|
246
|
+
}
|
|
247
|
+
for (const directory of String(env.PATH ?? "").split(path.delimiter)) {
|
|
248
|
+
if (directory.length > 0) candidates.push(path.resolve(directory, "opencode"));
|
|
249
|
+
}
|
|
250
|
+
for (const candidate of candidates) {
|
|
251
|
+
try {
|
|
252
|
+
if (fs.statSync(candidate).isFile()) {
|
|
253
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
254
|
+
return candidate;
|
|
255
|
+
}
|
|
256
|
+
} catch { /* Fall back to the login-shell resolver. */ }
|
|
257
|
+
}
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function resolveBinary({ signal } = {}) {
|
|
262
|
+
if (signal?.aborted) return Promise.reject(new Error("OpenCode binary unavailable"));
|
|
263
|
+
const directPath = findOpenCodeBinaryOnPath();
|
|
264
|
+
if (directPath) return Promise.resolve(directPath);
|
|
265
|
+
return new Promise((resolve, reject) => {
|
|
266
|
+
const child = spawn("zsh", ["-lic", "whence -p opencode"], { shell: false, stdio: ["ignore", "pipe", "ignore"] });
|
|
267
|
+
let stdout = "";
|
|
268
|
+
let stopped = false;
|
|
269
|
+
const abort = () => { stopped = true; child.kill("SIGTERM"); };
|
|
270
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
271
|
+
child.stdout.setEncoding("utf8");
|
|
272
|
+
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
273
|
+
child.on("error", () => reject(new Error("OpenCode binary unavailable")));
|
|
274
|
+
child.on("close", (code) => {
|
|
275
|
+
signal?.removeEventListener("abort", abort);
|
|
276
|
+
const candidate = stdout.split(/\r?\n/).map((line) => line.trim()).find((line) => path.isAbsolute(line));
|
|
277
|
+
if (stopped || code !== 0 || !candidate) reject(new Error("OpenCode binary unavailable"));
|
|
278
|
+
else resolve(candidate);
|
|
279
|
+
});
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function runCommand(args, { signal } = {}) {
|
|
284
|
+
return new Promise((resolve, reject) => {
|
|
285
|
+
const child = spawn(args[0], args.slice(1), { shell: false, stdio: ["ignore", "pipe", "pipe"] });
|
|
286
|
+
let stdout = "";
|
|
287
|
+
const abort = () => child.kill("SIGTERM");
|
|
288
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
289
|
+
child.stdout.setEncoding("utf8");
|
|
290
|
+
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
291
|
+
child.on("error", () => reject(new Error("OpenCode command unavailable")));
|
|
292
|
+
child.on("close", (code) => {
|
|
293
|
+
signal?.removeEventListener("abort", abort);
|
|
294
|
+
if (code !== 0) reject(new Error("OpenCode command unavailable"));
|
|
295
|
+
else resolve(stdout);
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function moveIndex(index, delta, length) { return length ? (index + delta + length) % length : 0; }
|
|
301
|
+
function frame(screen, first, previousLineCount) {
|
|
302
|
+
if (first) return `${ANSI.hideCursor}${screen}`;
|
|
303
|
+
return `${previousLineCount > 1 ? `\u001b[${previousLineCount - 1}A` : ""}\r${ANSI.eraseDown}${screen}`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function createOcSwitcher({ homeDir = os.homedir(), env = process.env, shell = env.SHELL, now = () => new Date().toISOString(), resolve = resolveBinary, command = runCommand } = {}) {
|
|
307
|
+
const filePath = statePath({ homeDir, env });
|
|
308
|
+
const read = () => readState(filePath, env, now);
|
|
309
|
+
const save = (state) => {
|
|
310
|
+
const normalized = { ...state, schemaVersion: STATE_VERSION, updatedAt: now() };
|
|
311
|
+
atomicWrite(filePath, `${JSON.stringify(normalized, null, 2)}\n`);
|
|
312
|
+
const rcPath = shellRcPath({ homeDir, shell });
|
|
313
|
+
let contents = "";
|
|
314
|
+
try { contents = fs.readFileSync(rcPath, "utf8"); } catch (cause) { if (cause?.code !== "ENOENT") throw cause; }
|
|
315
|
+
atomicWrite(rcPath, updateShellRc(contents, normalized));
|
|
316
|
+
return normalized;
|
|
317
|
+
};
|
|
318
|
+
const refresh = async ({ signal, forceRefresh = false } = {}) => {
|
|
319
|
+
const binary = await resolve({ signal });
|
|
320
|
+
const providers = configuredProviderIds({ homeDir, env });
|
|
321
|
+
try {
|
|
322
|
+
const auth = await command([binary, "auth", "list"], { signal });
|
|
323
|
+
parseOpenCodeAuthProviders(auth).forEach((providerId) => { if (!providers.includes(providerId)) providers.push(providerId); });
|
|
324
|
+
} catch { /* config/env discovery still applies */ }
|
|
325
|
+
const modelArgs = [binary, "models", "--pure"];
|
|
326
|
+
if (forceRefresh) modelArgs.push("--refresh");
|
|
327
|
+
const grouped = parseOpenCodeModelList(await command(modelArgs, { signal }));
|
|
328
|
+
return providers.flatMap((providerId) => grouped[providerId] ?? []);
|
|
329
|
+
};
|
|
330
|
+
return { getStatePath: () => filePath, loadState: read, saveState: save, refreshModels: refresh };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export async function runTerminalOcSwitcher({ input = process.stdin, output = process.stdout, initialState, initialModels = [], refreshModels, saveState, agentIds = AGENT_IDS } = {}) {
|
|
334
|
+
let state = JSON.parse(JSON.stringify(initialState));
|
|
335
|
+
let models = [...initialModels];
|
|
336
|
+
let screen = "main";
|
|
337
|
+
let focusedIndex = 0;
|
|
338
|
+
let pickerFocusedIndex = 0;
|
|
339
|
+
let pickerQuery = "";
|
|
340
|
+
let selectedAgents = new Set();
|
|
341
|
+
let status = "Loading models...";
|
|
342
|
+
let catalogFresh = false;
|
|
343
|
+
let dirty = false;
|
|
344
|
+
let finished = false;
|
|
345
|
+
let result;
|
|
346
|
+
let previousLineCount = 0;
|
|
347
|
+
let pickerTarget;
|
|
348
|
+
const controller = new AbortController();
|
|
349
|
+
const height = Number(output.rows ?? input.rows) || 24;
|
|
350
|
+
const maxVisibleModels = Math.max(4, height - 14);
|
|
351
|
+
const rows = () => rowsForState(state);
|
|
352
|
+
const filtered = () => models.filter((modelRef) => modelRef.toLowerCase().includes(pickerQuery.toLowerCase()));
|
|
353
|
+
const write = (chunk) => output.write(chunk);
|
|
354
|
+
const render = (first = false) => {
|
|
355
|
+
if (finished) return;
|
|
356
|
+
const screenText = screen === "main"
|
|
357
|
+
? renderMainScreen({ state, focusedIndex, selectedAgents, status, catalogFresh })
|
|
358
|
+
: renderModelPicker({ targetLabel: pickerTarget.label, models, query: pickerQuery, focusedIndex: pickerFocusedIndex, maxVisibleModels });
|
|
359
|
+
write(frame(screenText, first, previousLineCount));
|
|
360
|
+
previousLineCount = screenText.split("\n").length;
|
|
361
|
+
};
|
|
362
|
+
const finish = (nextResult) => { finished = true; result = nextResult; controller.abort(); };
|
|
363
|
+
const persist = async () => { state = await saveState(state); dirty = false; status = "Guardado."; };
|
|
364
|
+
const startRefresh = (first = false) => {
|
|
365
|
+
catalogFresh = false;
|
|
366
|
+
status = "Loading models...";
|
|
367
|
+
render();
|
|
368
|
+
Promise.resolve().then(() => refreshModels({
|
|
369
|
+
signal: controller.signal,
|
|
370
|
+
forceRefresh: !first,
|
|
371
|
+
})).then((nextModels) => {
|
|
372
|
+
if (finished) return;
|
|
373
|
+
models = [...nextModels]; catalogFresh = true; status = "Catalog ready."; render();
|
|
374
|
+
}).catch(() => { if (!finished) { status = "Unable to update catalog; saved values remain visible."; render(); } });
|
|
375
|
+
};
|
|
376
|
+
emitKeypressEvents(input);
|
|
377
|
+
input.setRawMode?.(true);
|
|
378
|
+
input.resume?.();
|
|
379
|
+
const onKeypress = (sequence, key = {}) => {
|
|
380
|
+
const name = key.ctrl && key.name === "c" ? "ctrl-c" : key.name === "return" ? "enter" : key.name ?? sequence;
|
|
381
|
+
const searchKey = sequence === "/" || name === "/" || name === "slash";
|
|
382
|
+
if (name === "ctrl-c") { finish({ status: "cancelled", state }); return; }
|
|
383
|
+
if (screen === "main") {
|
|
384
|
+
const currentRows = rows();
|
|
385
|
+
if (name === "up") focusedIndex = moveIndex(focusedIndex, -1, currentRows.length);
|
|
386
|
+
else if (name === "down") focusedIndex = moveIndex(focusedIndex, 1, currentRows.length);
|
|
387
|
+
else if (name === "space" && currentRows[focusedIndex]?.kind === "agent") {
|
|
388
|
+
const agent = currentRows[focusedIndex].key;
|
|
389
|
+
if (selectedAgents.has(agent)) selectedAgents.delete(agent); else selectedAgents.add(agent);
|
|
390
|
+
} else if (name === "enter" && currentRows[focusedIndex]) {
|
|
391
|
+
pickerTarget = currentRows[focusedIndex];
|
|
392
|
+
pickerFocusedIndex = Math.max(0, filtered().indexOf(pickerTarget.modelRef));
|
|
393
|
+
pickerQuery = "";
|
|
394
|
+
screen = "picker";
|
|
395
|
+
} else if (searchKey) {
|
|
396
|
+
pickerTarget = currentRows[focusedIndex];
|
|
397
|
+
if (pickerTarget) {
|
|
398
|
+
pickerFocusedIndex = Math.max(0, filtered().indexOf(pickerTarget.modelRef));
|
|
399
|
+
pickerQuery = "";
|
|
400
|
+
screen = "picker";
|
|
401
|
+
}
|
|
402
|
+
} else if (name === "r") startRefresh();
|
|
403
|
+
else if (name === "s") persist().catch(() => { status = "Save failed."; });
|
|
404
|
+
else if (name === "q") persist().then(() => finish({ status: "saved", state })).catch(() => finish({ status: "error", error: "Save failed." }));
|
|
405
|
+
else if (name === "escape") selectedAgents.clear();
|
|
406
|
+
} else {
|
|
407
|
+
const available = filtered();
|
|
408
|
+
if (name === "up") pickerFocusedIndex = moveIndex(pickerFocusedIndex, -1, available.length);
|
|
409
|
+
else if (name === "down") pickerFocusedIndex = moveIndex(pickerFocusedIndex, 1, available.length);
|
|
410
|
+
else if (name === "enter" && available[pickerFocusedIndex]) {
|
|
411
|
+
const targetAgents = pickerTarget.kind === "agent"
|
|
412
|
+
? [...(selectedAgents.size ? selectedAgents : new Set([pickerTarget.key]))]
|
|
413
|
+
: [];
|
|
414
|
+
state = applyModelSelection(state, { target: pickerTarget.key, agents: targetAgents, modelRef: available[pickerFocusedIndex] });
|
|
415
|
+
dirty = true; selectedAgents.clear(); screen = "main"; status = "Change pending save.";
|
|
416
|
+
} else if (name === "escape") { screen = "main"; pickerQuery = ""; }
|
|
417
|
+
else if (name === "backspace") { pickerQuery = pickerQuery.slice(0, -1); pickerFocusedIndex = 0; }
|
|
418
|
+
else if (typeof sequence === "string" && sequence.length === 1 && sequence >= " " && sequence <= "~") { pickerQuery += sequence; pickerFocusedIndex = 0; }
|
|
419
|
+
}
|
|
420
|
+
render();
|
|
421
|
+
};
|
|
422
|
+
input.on("keypress", onKeypress);
|
|
423
|
+
render(true);
|
|
424
|
+
startRefresh(true);
|
|
425
|
+
return new Promise((resolve) => {
|
|
426
|
+
const poll = () => {
|
|
427
|
+
if (finished) {
|
|
428
|
+
input.off?.("keypress", onKeypress);
|
|
429
|
+
input.setRawMode?.(false);
|
|
430
|
+
input.pause?.();
|
|
431
|
+
write(`\n${ANSI.showCursor}\n`);
|
|
432
|
+
resolve(result);
|
|
433
|
+
} else setImmediate(poll);
|
|
434
|
+
};
|
|
435
|
+
poll();
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export async function runInteractive(options = {}) {
|
|
440
|
+
const switcher = createOcSwitcher(options);
|
|
441
|
+
const input = options.input ?? process.stdin;
|
|
442
|
+
const output = options.output ?? process.stdout;
|
|
443
|
+
if (input.isTTY !== true || output.isTTY !== true) return { status: "error", error: "oc-switch requires an interactive terminal." };
|
|
444
|
+
try {
|
|
445
|
+
return await runTerminalOcSwitcher({
|
|
446
|
+
input, output,
|
|
447
|
+
initialState: options.initialState ?? switcher.loadState(),
|
|
448
|
+
initialModels: options.initialModels ?? [],
|
|
449
|
+
refreshModels: options.refreshModels ?? switcher.refreshModels,
|
|
450
|
+
saveState: options.saveState ?? switcher.saveState,
|
|
451
|
+
});
|
|
452
|
+
} catch {
|
|
453
|
+
return { status: "error", error: "Unable to start oc-switch. Check OPENCODE_MODEL and the OpenCode configuration." };
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
export function isDirectExecution({
|
|
458
|
+
argvPath = process.argv[1],
|
|
459
|
+
modulePath = fileURLToPath(import.meta.url),
|
|
460
|
+
} = {}) {
|
|
461
|
+
if (!argvPath) return false;
|
|
462
|
+
try {
|
|
463
|
+
return fs.realpathSync(argvPath) === fs.realpathSync(modulePath);
|
|
464
|
+
} catch {
|
|
465
|
+
return path.resolve(argvPath) === path.resolve(modulePath);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
if (isDirectExecution()) {
|
|
470
|
+
const result = await runInteractive();
|
|
471
|
+
if (result.status === "error") { process.stderr.write(`${result.error}\n`); process.exitCode = 1; }
|
|
472
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import test from "node:test";
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
AGENT_IDS,
|
|
10
|
+
applyModelSelection,
|
|
11
|
+
createOcSwitcher,
|
|
12
|
+
findOpenCodeBinaryOnPath,
|
|
13
|
+
isDirectExecution,
|
|
14
|
+
parseOpenCodeAuthProviders,
|
|
15
|
+
parseOpenCodeModelList,
|
|
16
|
+
renderModelPicker,
|
|
17
|
+
renderMainScreen,
|
|
18
|
+
runTerminalOcSwitcher,
|
|
19
|
+
} from "./oc-switch.mjs";
|
|
20
|
+
|
|
21
|
+
function createTuiInput() {
|
|
22
|
+
const input = new EventEmitter();
|
|
23
|
+
input.isTTY = true;
|
|
24
|
+
input.setRawMode = () => {};
|
|
25
|
+
input.resume = () => {};
|
|
26
|
+
input.pause = () => {};
|
|
27
|
+
return input;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function emitKey(input, name, sequence = name) {
|
|
31
|
+
input.emit("keypress", sequence, { name, sequence, ctrl: name === "c" });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function nextTick() {
|
|
35
|
+
return new Promise((resolve) => setImmediate(resolve));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test("parses OpenCode models without a fixed provider list", () => {
|
|
39
|
+
assert.deepEqual(parseOpenCodeModelList([
|
|
40
|
+
"openai/gpt-5",
|
|
41
|
+
"custom-provider/model-a",
|
|
42
|
+
"openrouter/anthropic/claude-sonnet-4.6",
|
|
43
|
+
"openai/gpt-5",
|
|
44
|
+
"informational text",
|
|
45
|
+
].join("\n")), {
|
|
46
|
+
openai: ["openai/gpt-5"],
|
|
47
|
+
"custom-provider": ["custom-provider/model-a"],
|
|
48
|
+
openrouter: ["openrouter/anthropic/claude-sonnet-4.6"],
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("extracts only credential providers from auth output", () => {
|
|
53
|
+
assert.deepEqual(parseOpenCodeAuthProviders([
|
|
54
|
+
"┌ Credentials",
|
|
55
|
+
"● OpenAI oauth",
|
|
56
|
+
"● OpenCode Go api",
|
|
57
|
+
"┌ Environment",
|
|
58
|
+
"● DeepSeek DEEPSEEK_API_KEY",
|
|
59
|
+
].join("\n")), ["openai", "opencode-go"]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("updates OpenCode default, small, and selected agent assignments", () => {
|
|
63
|
+
const state = {
|
|
64
|
+
schemaVersion: 1,
|
|
65
|
+
updatedAt: "2026-01-01T00:00:00.000Z",
|
|
66
|
+
defaultModel: "openai/old",
|
|
67
|
+
smallModel: "openai/old-small",
|
|
68
|
+
agents: Object.fromEntries(AGENT_IDS.map((agent) => [agent, "openai/old"])),
|
|
69
|
+
};
|
|
70
|
+
const next = applyModelSelection(state, {
|
|
71
|
+
target: "smallModel",
|
|
72
|
+
modelRef: "custom-provider/model-a",
|
|
73
|
+
});
|
|
74
|
+
const agents = applyModelSelection(next, {
|
|
75
|
+
target: "agents",
|
|
76
|
+
agents: ["lead", "developer"],
|
|
77
|
+
modelRef: "custom-provider/model-a",
|
|
78
|
+
});
|
|
79
|
+
assert.equal(agents.smallModel, "custom-provider/model-a");
|
|
80
|
+
assert.equal(agents.agents.lead, "custom-provider/model-a");
|
|
81
|
+
assert.equal(agents.agents.developer, "custom-provider/model-a");
|
|
82
|
+
assert.equal(agents.agents.reviewer, "openai/old");
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("renders a bounded provider-neutral picker", () => {
|
|
86
|
+
const screen = renderModelPicker({
|
|
87
|
+
targetLabel: "lead",
|
|
88
|
+
models: Array.from({ length: 12 }, (_, index) => `provider/model-${index}`),
|
|
89
|
+
focusedIndex: 8,
|
|
90
|
+
maxVisibleModels: 5,
|
|
91
|
+
});
|
|
92
|
+
assert.match(screen, /more models/);
|
|
93
|
+
assert.match(screen, /provider\/model-8/);
|
|
94
|
+
assert.doesNotMatch(screen, /provider\/model-0/);
|
|
95
|
+
assert.match(renderMainScreen({
|
|
96
|
+
state: {
|
|
97
|
+
defaultModel: "provider/model-0",
|
|
98
|
+
smallModel: "provider/model-1",
|
|
99
|
+
agents: Object.fromEntries(AGENT_IDS.map((agent) => [agent, "provider/model-0"])),
|
|
100
|
+
},
|
|
101
|
+
focusedIndex: 2,
|
|
102
|
+
}), />\s+lead/);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("OpenCode TUI changes the default model and persists on q", async () => {
|
|
106
|
+
const input = createTuiInput();
|
|
107
|
+
const output = { isTTY: true, rows: 30, writes: [], write(chunk) { this.writes.push(String(chunk)); } };
|
|
108
|
+
const saved = [];
|
|
109
|
+
const state = {
|
|
110
|
+
schemaVersion: 1,
|
|
111
|
+
defaultModel: "nan/model-a",
|
|
112
|
+
smallModel: "nan/model-a",
|
|
113
|
+
agents: Object.fromEntries(AGENT_IDS.map((agent) => [agent, "nan/model-a"])),
|
|
114
|
+
};
|
|
115
|
+
const running = runTerminalOcSwitcher({
|
|
116
|
+
input,
|
|
117
|
+
output,
|
|
118
|
+
initialState: state,
|
|
119
|
+
initialModels: ["nan/model-a", "openai/model-b"],
|
|
120
|
+
refreshModels: async () => ["nan/model-a", "openai/model-b"],
|
|
121
|
+
saveState: async (nextState) => {
|
|
122
|
+
saved.push(nextState);
|
|
123
|
+
return nextState;
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
await nextTick();
|
|
128
|
+
emitKey(input, "return", "\r");
|
|
129
|
+
await nextTick();
|
|
130
|
+
emitKey(input, "down");
|
|
131
|
+
emitKey(input, "return", "\r");
|
|
132
|
+
await nextTick();
|
|
133
|
+
emitKey(input, "q");
|
|
134
|
+
const result = await running;
|
|
135
|
+
|
|
136
|
+
assert.equal(result.status, "saved");
|
|
137
|
+
assert.equal(saved.length, 1);
|
|
138
|
+
assert.equal(saved[0].defaultModel, "openai/model-b");
|
|
139
|
+
assert.match(output.writes.join(""), /Loading models/);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("OpenCode search treats shortcut letters as query text", async () => {
|
|
143
|
+
const input = createTuiInput();
|
|
144
|
+
const output = { isTTY: true, rows: 30, writes: [], write(chunk) { this.writes.push(String(chunk)); } };
|
|
145
|
+
const running = runTerminalOcSwitcher({
|
|
146
|
+
input,
|
|
147
|
+
output,
|
|
148
|
+
initialState: {
|
|
149
|
+
schemaVersion: 1,
|
|
150
|
+
defaultModel: "nan/model-a",
|
|
151
|
+
smallModel: "nan/model-a",
|
|
152
|
+
agents: Object.fromEntries(AGENT_IDS.map((agent) => [agent, "nan/model-a"])),
|
|
153
|
+
},
|
|
154
|
+
initialModels: ["nan/model-a", "openai/model-b"],
|
|
155
|
+
refreshModels: async () => ["nan/model-a", "openai/model-b"],
|
|
156
|
+
saveState: async (state) => state,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
await nextTick();
|
|
160
|
+
emitKey(input, "/", "/");
|
|
161
|
+
emitKey(input, "q");
|
|
162
|
+
emitKey(input, "r");
|
|
163
|
+
emitKey(input, "s");
|
|
164
|
+
await nextTick();
|
|
165
|
+
assert.match(output.writes.join(""), /Search: qrs/);
|
|
166
|
+
emitKey(input, "escape");
|
|
167
|
+
await nextTick();
|
|
168
|
+
emitKey(input, "q");
|
|
169
|
+
const result = await running;
|
|
170
|
+
assert.equal(result.status, "saved");
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("uses the local OpenCode model cache until an explicit refresh", async () => {
|
|
174
|
+
const calls = [];
|
|
175
|
+
const switcher = createOcSwitcher({
|
|
176
|
+
homeDir: "/tmp/oc-switch-test-home",
|
|
177
|
+
env: { OPENCODE_MODEL: "openai/model-a" },
|
|
178
|
+
resolve: async () => "/opt/opencode/bin/opencode",
|
|
179
|
+
command: async (args) => {
|
|
180
|
+
calls.push(args);
|
|
181
|
+
return "openai/model-a\n";
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
await switcher.refreshModels();
|
|
186
|
+
await switcher.refreshModels({ forceRefresh: true });
|
|
187
|
+
|
|
188
|
+
assert.deepEqual(calls, [
|
|
189
|
+
["/opt/opencode/bin/opencode", "auth", "list"],
|
|
190
|
+
["/opt/opencode/bin/opencode", "models", "--pure"],
|
|
191
|
+
["/opt/opencode/bin/opencode", "auth", "list"],
|
|
192
|
+
["/opt/opencode/bin/opencode", "models", "--pure", "--refresh"],
|
|
193
|
+
]);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test("finds OpenCode directly on PATH without starting a login shell", () => {
|
|
197
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "oc-switch-path-"));
|
|
198
|
+
const binary = path.join(directory, "opencode");
|
|
199
|
+
try {
|
|
200
|
+
fs.writeFileSync(binary, "#!/bin/sh\n", { mode: 0o755 });
|
|
201
|
+
assert.equal(findOpenCodeBinaryOnPath({ env: { PATH: directory } }), binary);
|
|
202
|
+
} finally {
|
|
203
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
test("direct execution helper follows the installed oc-switch symlink", () => {
|
|
208
|
+
const root = new URL("./", import.meta.url).pathname;
|
|
209
|
+
const link = `${root}..test-oc-switch-link-${process.pid}`;
|
|
210
|
+
const source = new URL("./oc-switch.mjs", import.meta.url).pathname;
|
|
211
|
+
try {
|
|
212
|
+
fs.symlinkSync(source, link);
|
|
213
|
+
assert.equal(isDirectExecution({ argvPath: link, modulePath: source }), true);
|
|
214
|
+
} finally {
|
|
215
|
+
fs.rmSync(link, { force: true });
|
|
216
|
+
}
|
|
217
|
+
});
|