opencode-agent-orchestration-kit 1.0.37 → 1.0.38

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,8 +1,11 @@
1
1
  # OpenCode Agent Orchestration Kit
2
2
 
3
- [![Check](https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/actions/workflows/check.yml/badge.svg)](https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/actions/workflows/check.yml)
4
- [![License](https://img.shields.io/github/license/jcarlosrodicio/opencode-agent-orchestration-kit)](LICENSE)
5
- [![Latest release](https://img.shields.io/github/v/release/jcarlosrodicio/opencode-agent-orchestration-kit)](https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/releases)
3
+ <p align="center">
4
+ <a href="https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/actions/workflows/check.yml"><img src="https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/actions/workflows/check.yml/badge.svg" alt="Check"></a>
5
+ <a href="LICENSE"><img src="https://img.shields.io/github/license/jcarlosrodicio/opencode-agent-orchestration-kit" alt="License"></a>
6
+ <a href="https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/releases"><img src="https://img.shields.io/github/v/release/jcarlosrodicio/opencode-agent-orchestration-kit" alt="Latest release"></a>
7
+ <a href="https://github.com/sponsors/jcarlosrodicio"><img src="https://img.shields.io/badge/Sponsor-GitHub%20Sponsors-ea4aaa?logo=githubsponsors&logoColor=white" alt="Sponsor on GitHub"></a>
8
+ </p>
6
9
 
7
10
  A reproducible product-development workflow for OpenCode.
8
11
 
@@ -297,6 +300,58 @@ export OPENCODE_EVOLVER_MODEL="$OPENCODE_MODEL"
297
300
 
298
301
  You can use one model for every role or assign different models depending on cost, speed, and task complexity.
299
302
 
303
+ ### Interactive OpenCode model switching
304
+
305
+ The repository also includes `oc-switch`, a standalone TUI for changing the
306
+ OpenCode default model, small/title model, and per-agent overrides. It builds
307
+ its provider list from OpenCode itself and reads the local model catalog from
308
+ `opencode models --pure`, so it only shows providers configured in your
309
+ OpenCode installation. Startup is cache-first; press `r` when you want an
310
+ explicit remote catalog refresh through `--refresh`. It does not share a
311
+ catalog with Pi.
312
+
313
+ From this checkout, run:
314
+
315
+ ```bash
316
+ npm run oc-switch
317
+ ```
318
+
319
+ To install the command globally with npm from the cloned checkout:
320
+
321
+ ```bash
322
+ npm install --global .
323
+ oc-switch
324
+ ```
325
+
326
+ After a tagged release is published, you can install the same CLI directly
327
+ from GitHub without keeping a checkout:
328
+
329
+ ```bash
330
+ npm install --global "git+https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit.git#v1.0.38"
331
+ oc-switch
332
+ ```
333
+
334
+ The package exposes `oc-switch` through its npm `bin` entry; no separate
335
+ wrapper or shell alias is required. Keep `~/.npm-global/bin` (or your npm
336
+ global bin directory) on `PATH` if npm is configured with a user prefix.
337
+
338
+ #### `oc-switch` quick guide
339
+
340
+ - `↑`/`↓` moves through `Default`, `Small/title`, and the agent rows.
341
+ - `Enter` or `/` opens the model picker for the focused row.
342
+ - Type to filter the current OpenCode catalog; `q`, `r`, and `s` are search
343
+ characters while the picker is open. `Backspace` deletes one character.
344
+ - `Enter` applies the highlighted model. `Space` marks several agent rows so
345
+ one selection can be applied to all of them.
346
+ - `s` saves. `q` saves and exits. `Esc` returns to the assignment list, and
347
+ `r` explicitly refreshes OpenCode's catalog.
348
+
349
+ The selected values are persisted in the OpenCode model-switcher state and in
350
+ the managed model block of `.zshrc` or `.bashrc`.
351
+
352
+ Pi has its own independent `pi-switch`; its catalog comes only from Pi's
353
+ `pi --list-models` command.
354
+
300
355
  ### 3. Install local plugin dependencies
301
356
 
302
357
  ```bash
@@ -677,7 +732,7 @@ Validate only the canonical identity and current release note with:
677
732
 
678
733
  ```bash
679
734
  npm run check:version
680
- node scripts/version.mjs --check-tag v1.0.37
735
+ node scripts/version.mjs --check-tag v1.0.38
681
736
  ```
682
737
 
683
738
  Tag validation compares an explicitly supplied tag with the package identity.
@@ -880,6 +935,8 @@ definitions, exact pins, evidence, and scope.
880
935
 
881
936
  Contributions are welcome.
882
937
 
938
+ Found a bug or have an idea? [Open an issue](https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/issues/new/choose) · [Browse existing issues](https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit/issues)
939
+
883
940
  Good contributions include:
884
941
 
885
942
  - Clearer documentation.
package/docs/models.md CHANGED
@@ -14,4 +14,34 @@ export OPENCODE_RESEARCHER_MODEL="openai/gpt-5.5"
14
14
  export OPENCODE_REVIEWER_MODEL="openai/gpt-5.5"
15
15
  ```
16
16
 
17
+ ## Interactive switching
18
+
19
+ Run `npm run oc-switch` from a checkout, or install the CLI globally with npm:
20
+
21
+ ```bash
22
+ npm install --global .
23
+ oc-switch
24
+ ```
25
+
26
+ Once a release tag exists, a checkout is optional:
27
+
28
+ ```bash
29
+ npm install --global "git+https://github.com/jcarlosrodicio/opencode-agent-orchestration-kit.git#v1.0.38"
30
+ oc-switch
31
+ ```
32
+
33
+ The TUI reads available models from OpenCode's own local `opencode models --pure`
34
+ catalog and discovers configured providers through OpenCode; it does not use
35
+ Pi's catalog. Startup is cache-first. Press `r` to request an explicit remote
36
+ refresh with `opencode models --pure --refresh`.
37
+
38
+ `Default` changes `OPENCODE_MODEL`, `Small/title` changes
39
+ `OPENCODE_SMALL_MODEL`, and agent rows change their corresponding
40
+ `OPENCODE_<AGENT>_MODEL` override. Press `Enter` or `/` to open the picker;
41
+ while it is open, all printable letters—including `q`, `r`, and `s`—filter the
42
+ catalog. Use `Enter` to apply, `Esc` to go back, `s` to save, and `q` to save
43
+ and exit. `Space` marks several agents for one assignment. The state is kept
44
+ under the XDG state directory and the model variables are updated in the
45
+ managed block of `.zshrc` or `.bashrc`.
46
+
17
47
  Keep provider credentials in your shell, password manager, or OpenCode auth flow. Do not commit credentials.
@@ -0,0 +1,44 @@
1
+ # v1.0.38 - Safe lifecycle and canonical release identity
2
+
3
+ This release adds a standalone OpenCode model switcher for quickly assigning
4
+ configured models to the default, small/title, and individual agent routes.
5
+
6
+ ## Highlights
7
+
8
+ - `oc-switch` provides a bounded interactive TUI with search, refresh, multi-agent selection, and persistent model assignments.
9
+ - The catalog is read from the current OpenCode installation and is independent from Pi's model catalog.
10
+ - The public README and model-routing documentation describe installation and shell persistence behavior.
11
+
12
+ ## Installation or upgrade
13
+
14
+ Install or upgrade the public kit using the normal manifest-owned flow:
15
+
16
+ ```bash
17
+ ./install.sh --dry-run
18
+ ./install.sh
19
+ ./upgrade.sh --dry-run
20
+ ./upgrade.sh
21
+ ```
22
+
23
+ After installation, run `oc-switch` from the checkout or global package. The
24
+ README and [model guide](../models.md) include both the local `npm run
25
+ oc-switch` path and the global `npm install --global` path, plus the keyboard
26
+ guide.
27
+
28
+ ## Migration
29
+
30
+ No migration is required. Existing OpenCode model variables remain valid; the
31
+ switcher adds an interactive way to edit them.
32
+
33
+ ## Validation performed
34
+
35
+ The public contract checker, unit and script tests, type checks, dependency
36
+ audits, signature checks, installation smoke, package smoke, and canonical
37
+ version/tag checks pass for this release.
38
+
39
+ ## Public safety boundary
40
+
41
+ The public release excludes private OpenCode and Pi configuration, local
42
+ providers and MCP wiring, credentials, authentication files, raw transcripts,
43
+ private evidence, absolute machine paths, and runtime state. Pi uses its own
44
+ native model catalog and is not included in this OpenCode package.
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "opencode-agent-orchestration-kit",
3
- "version": "1.0.37",
3
+ "version": "1.0.38",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
7
7
  "bin": {
8
- "oak": "scripts/oak.mjs"
8
+ "oak": "scripts/oak.mjs",
9
+ "oc-switch": "scripts/oc-switch.mjs"
9
10
  },
10
11
  "files": [
11
12
  "CODE_OF_CONDUCT.md",
@@ -40,6 +41,7 @@
40
41
  "dependency-signature-audit": "npm --prefix opencode audit signatures",
41
42
  "installation-smoke": "bash scripts/install-smoke.sh",
42
43
  "package-smoke": "bash scripts/package-smoke.sh",
44
+ "oc-switch": "node scripts/oc-switch.mjs",
43
45
  "check:quick": "npm run contract-check",
44
46
  "check": "npm run contract-check && npm run unit-and-script-tests",
45
47
  "check:release": "npm --prefix opencode ci --ignore-scripts && npm run check && npm run typecheck && npm run dependency-audit && npm run dependency-signature-audit && npm run installation-smoke && npm run package-smoke",
@@ -191,10 +191,13 @@ function validatePackages(root, data, fsOps) {
191
191
  if (JSON.stringify(rootPackage.files) !== JSON.stringify(PACKAGE_FILES)) {
192
192
  throw invalid(`package.json files must be exactly: ${PACKAGE_FILES.join(", ")}`);
193
193
  }
194
- assertExactKeys(rootPackage.bin, ["oak"], "package.json bin");
194
+ assertExactKeys(rootPackage.bin, ["oak", "oc-switch"], "package.json bin");
195
195
  if (rootPackage.bin.oak !== "scripts/oak.mjs") {
196
196
  throw invalid("package.json bin.oak must be scripts/oak.mjs");
197
197
  }
198
+ if (rootPackage.bin["oc-switch"] !== "scripts/oc-switch.mjs") {
199
+ throw invalid("package.json bin.oc-switch must be scripts/oc-switch.mjs");
200
+ }
198
201
  for (const [script, command] of [
199
202
  ["dependency-audit", "npm --prefix opencode audit --omit=dev --audit-level=low"],
200
203
  ["dependency-signature-audit", "npm --prefix opencode audit signatures"],
@@ -161,7 +161,7 @@ function withSurfaceFixture(callback) {
161
161
  fs.writeFileSync(path.join(root, "supply-chain.json"), `${JSON.stringify(VALID)}\n`);
162
162
  fs.writeFileSync(path.join(root, "package.json"), `${JSON.stringify({
163
163
  files: PACKAGE_FILES,
164
- bin: { oak: "scripts/oak.mjs" },
164
+ bin: { oak: "scripts/oak.mjs", "oc-switch": "scripts/oc-switch.mjs" },
165
165
  scripts: {
166
166
  "dependency-audit": "npm --prefix opencode audit --omit=dev --audit-level=low",
167
167
  "dependency-signature-audit": "npm --prefix opencode audit signatures",
@@ -222,7 +222,7 @@ function withCliFixture(inventory, callback) {
222
222
  writeValidDocumentation(root);
223
223
  fs.writeFileSync(path.join(root, "package.json"), `${JSON.stringify({
224
224
  files: PACKAGE_FILES,
225
- bin: { oak: "scripts/oak.mjs" },
225
+ bin: { oak: "scripts/oak.mjs", "oc-switch": "scripts/oc-switch.mjs" },
226
226
  scripts: {
227
227
  "dependency-audit": "npm --prefix opencode audit --omit=dev --audit-level=low",
228
228
  "dependency-signature-audit": "npm --prefix opencode audit signatures",
@@ -341,11 +341,12 @@ test("surface validation accepts exact overrides, regenerated lock entries, and
341
341
  });
342
342
  });
343
343
 
344
- test("surface validation requires exactly the canonical oak bin", () => {
344
+ test("surface validation requires exactly the canonical oak and oc-switch bins", () => {
345
345
  for (const [bin, expected] of [
346
346
  [undefined, /package\.json bin/i],
347
- [{ oak: "scripts/other.mjs" }, /bin\.oak/i],
348
- [{ oak: "scripts/oak.mjs", other: "scripts/other.mjs" }, /keys must be exactly/i],
347
+ [{ oak: "scripts/other.mjs", "oc-switch": "scripts/oc-switch.mjs" }, /bin\.oak/i],
348
+ [{ oak: "scripts/oak.mjs", "oc-switch": "scripts/other.mjs" }, /bin\.oc-switch/i],
349
+ [{ oak: "scripts/oak.mjs", "oc-switch": "scripts/oc-switch.mjs", other: "scripts/other.mjs" }, /keys must be exactly/i],
349
350
  ]) {
350
351
  withSurfaceFixture((root) => {
351
352
  const packagePath = path.join(root, "package.json");
package/scripts/check.sh CHANGED
@@ -122,8 +122,8 @@ node scripts/check-use-cases.mjs
122
122
  node <<'NODE'
123
123
  const fs = require('fs')
124
124
  const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'))
125
- if (JSON.stringify(packageJson.bin) !== JSON.stringify({ oak: 'scripts/oak.mjs' })) {
126
- throw new Error('package.json must expose exactly bin.oak = scripts/oak.mjs')
125
+ if (JSON.stringify(packageJson.bin) !== JSON.stringify({ oak: 'scripts/oak.mjs', 'oc-switch': 'scripts/oc-switch.mjs' })) {
126
+ throw new Error('package.json must expose exactly bin.oak and bin.oc-switch')
127
127
  }
128
128
  NODE
129
129
 
@@ -317,13 +317,20 @@ test("[O011] symlinked oak executable runs its CLI", (t) => {
317
317
  assert.equal(result.stderr, "");
318
318
  });
319
319
 
320
- test("[O012] package exposes exactly one executable oak binary", () => {
320
+ test("[O012] package exposes the executable oak and oc-switch binaries", () => {
321
321
  const packageJson = JSON.parse(
322
322
  fs.readFileSync(path.join(REPOSITORY_ROOT, "package.json"), "utf8"),
323
323
  );
324
- assert.deepEqual(packageJson.bin, { oak: "scripts/oak.mjs" });
324
+ assert.deepEqual(packageJson.bin, {
325
+ oak: "scripts/oak.mjs",
326
+ "oc-switch": "scripts/oc-switch.mjs",
327
+ });
325
328
  const stat = fs.lstatSync(path.join(REPOSITORY_ROOT, packageJson.bin.oak));
326
329
  assert.equal(stat.isFile(), true);
327
330
  assert.equal(stat.isSymbolicLink(), false);
328
331
  assert.notEqual(stat.mode & 0o111, 0);
332
+ const switchStat = fs.lstatSync(path.join(REPOSITORY_ROOT, packageJson.bin["oc-switch"]));
333
+ assert.equal(switchStat.isFile(), true);
334
+ assert.equal(switchStat.isSymbolicLink(), false);
335
+ assert.notEqual(switchStat.mode & 0o111, 0);
329
336
  });
@@ -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
+ });
@@ -15,6 +15,7 @@ const REQUIRED_FILES = [
15
15
  "package/install.sh",
16
16
  "package/scripts/manage-installation.mjs",
17
17
  "package/scripts/oak.mjs",
18
+ "package/scripts/oc-switch.mjs",
18
19
  "package/scripts/package-smoke.sh",
19
20
  "package/scripts/package-smoke.mjs",
20
21
  "package/opencode/opencode.json",
@@ -123,10 +124,11 @@ export function validatePackedOak({ packed, packedRoot, fsOps = fs }) {
123
124
  !packed?.bin
124
125
  || typeof packed.bin !== "object"
125
126
  || Array.isArray(packed.bin)
126
- || JSON.stringify(Object.keys(packed.bin).sort()) !== JSON.stringify(["oak"])
127
+ || JSON.stringify(Object.keys(packed.bin).sort()) !== JSON.stringify(["oak", "oc-switch"])
127
128
  || packed.bin.oak !== "scripts/oak.mjs"
129
+ || packed.bin["oc-switch"] !== "scripts/oc-switch.mjs"
128
130
  ) {
129
- throw smokeError("packed package bin must expose exactly oak at scripts/oak.mjs");
131
+ throw smokeError("packed package bin must expose oak and oc-switch at their scripts entrypoints");
130
132
  }
131
133
  let stat;
132
134
  try {
@@ -140,6 +142,18 @@ export function validatePackedOak({ packed, packedRoot, fsOps = fs }) {
140
142
  if ((stat.mode & 0o111) === 0) {
141
143
  throw smokeError("packed oak entrypoint must be executable");
142
144
  }
145
+ let switchStat;
146
+ try {
147
+ switchStat = fsOps.lstatSync(path.join(packedRoot, packed.bin["oc-switch"]));
148
+ } catch {
149
+ throw smokeError("packed oc-switch entrypoint is missing");
150
+ }
151
+ if (switchStat.isSymbolicLink() || !switchStat.isFile()) {
152
+ throw smokeError("packed oc-switch entrypoint must be a regular non-symlink file");
153
+ }
154
+ if ((switchStat.mode & 0o111) === 0) {
155
+ throw smokeError("packed oc-switch entrypoint must be executable");
156
+ }
143
157
  }
144
158
 
145
159
  function inspectRegularFile(file) {
@@ -17,13 +17,14 @@ import {
17
17
 
18
18
  const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
19
19
  const HASH = "a".repeat(64);
20
- const BASENAME = "opencode-agent-orchestration-kit-1.0.37.tgz";
20
+ const BASENAME = "opencode-agent-orchestration-kit-1.0.38.tgz";
21
21
  const REQUIRED = [
22
22
  "package/package.json",
23
23
  "package/supply-chain.json",
24
24
  "package/install.sh",
25
25
  "package/scripts/manage-installation.mjs",
26
26
  "package/scripts/oak.mjs",
27
+ "package/scripts/oc-switch.mjs",
27
28
  "package/scripts/package-smoke.sh",
28
29
  "package/scripts/package-smoke.mjs",
29
30
  "package/opencode/opencode.json",
@@ -157,20 +158,21 @@ test("validatePackedOak requires exact metadata and executable regular file", (t
157
158
  t.after(() => fs.rmSync(root, { recursive: true, force: true }));
158
159
  fs.mkdirSync(path.join(root, "scripts"));
159
160
  fs.writeFileSync(path.join(root, "scripts/oak.mjs"), "#!/usr/bin/env node\n", { mode: 0o755 });
161
+ fs.writeFileSync(path.join(root, "scripts/oc-switch.mjs"), "#!/usr/bin/env node\n", { mode: 0o755 });
160
162
  assert.doesNotThrow(() => validatePackedOak({
161
- packed: { bin: { oak: "scripts/oak.mjs" } },
163
+ packed: { bin: { oak: "scripts/oak.mjs", "oc-switch": "scripts/oc-switch.mjs" } },
162
164
  packedRoot: root,
163
165
  }));
164
166
  for (const bin of [
165
167
  undefined,
166
168
  { oak: "scripts/other.mjs" },
167
- { oak: "scripts/oak.mjs", other: "scripts/other.mjs" },
169
+ { oak: "scripts/oak.mjs", "oc-switch": "scripts/oc-switch.mjs", other: "scripts/other.mjs" },
168
170
  ]) {
169
171
  assert.throws(() => validatePackedOak({ packed: { bin }, packedRoot: root }), /bin/i);
170
172
  }
171
173
  fs.chmodSync(path.join(root, "scripts/oak.mjs"), 0o644);
172
174
  assert.throws(() => validatePackedOak({
173
- packed: { bin: { oak: "scripts/oak.mjs" } },
175
+ packed: { bin: { oak: "scripts/oak.mjs", "oc-switch": "scripts/oc-switch.mjs" } },
174
176
  packedRoot: root,
175
177
  }), /executable/i);
176
178
  });
@@ -208,7 +210,7 @@ test("smokeTarball validates both archive listings before extraction", async ()
208
210
  await assert.rejects(
209
211
  smokeTarball({
210
212
  repositoryRoot: ROOT,
211
- tarball: "/public/opencode-agent-orchestration-kit-1.0.37.tgz",
213
+ tarball: "/public/opencode-agent-orchestration-kit-1.0.38.tgz",
212
214
  captureTarball(_source, destination) {
213
215
  fs.writeFileSync(destination, "fixture");
214
216
  return { size: 1 };
@@ -109,7 +109,7 @@ test("[V004] direct version entrypoints are exact and mutation-free", (t) => {
109
109
  for (const args of [["scripts/version.mjs"], ["scripts/manage-installation.mjs", "--version"]]) {
110
110
  const result = run(process.execPath, args, { HOME: home });
111
111
  assert.equal(result.status, 0, result.stderr);
112
- assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.37\n");
112
+ assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.38\n");
113
113
  assert.equal(fs.existsSync(target), false);
114
114
  }
115
115
  });
@@ -118,7 +118,7 @@ test("[V005] all lifecycle wrappers expose the canonical version", () => {
118
118
  for (const wrapper of ["install.sh", "upgrade.sh", "doctor.sh", "uninstall.sh", "rollback.sh"]) {
119
119
  const result = run(path.join(REPOSITORY_ROOT, wrapper), ["--version"]);
120
120
  assert.equal(result.status, 0, `${wrapper}: ${result.stderr}`);
121
- assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.37\n", wrapper);
121
+ assert.equal(result.stdout, "opencode-agent-orchestration-kit 1.0.38\n", wrapper);
122
122
  }
123
123
  });
124
124