worktrust 0.11.3 → 0.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * THE OPENCODE ADAPTER (owner, 2026-11-09: steer OpenCode, and through it Qwen on Ollama, from Remote Agent). OpenCode runs as
3
+ * `opencode run --format json`, ONE PROCESS PER RUN, no shell between us and it; read from OpenCode's source
4
+ * (anomalyco/opencode packages/cli/src/commands/commands.ts, run/run.ts, run/noninteractive.ts, session-target.ts; the
5
+ * permission docs; read 2026-11-09). NOT VERIFIED on a real install: OpenCode is not on the build machine; the tests run a
6
+ * fake of that shape, and the inventory offers OpenCode only when its own `run --help` names every flag used here.
7
+ *
8
+ * --session <id> "Session ID to continue, or to create if it does not exist": the id is minted HERE, in OpenCode's
9
+ * own shape (`ses_` + 26), so the steered ledger names the session before OpenCode writes a line
10
+ * --format json one JSON line per event (remote-opencode-events.mjs maps them)
11
+ * --model <p/m> the model, exactly as `opencode models` listed it (Qwen through Ollama is `ollama/qwen3:…`, OpenCode's
12
+ * own provider configuration; nothing here knows Ollama)
13
+ * --agent plan the plan mode: OpenCode's read-only agent, and edits denied by the run's own config besides
14
+ * the prompt on stdin, never in argv: a prompt that begins with "-" is never read as a flag
15
+ *
16
+ * APPROVALS. A non-interactive run cannot ask: OpenCode REJECTS every permission request (unless --auto, which is never
17
+ * passed, nor --yolo or --dangerously-skip-permissions) and tells the model so. The run's own config, inline through
18
+ * OPENCODE_CONFIG_CONTENT (above the project's opencode.json in OpenCode's order, beside the agents' own), asks for every
19
+ * command, edit, fetch, search and subagent, denies paths outside the project and the secret files Claude Code's deny rules
20
+ * name. So anything outside the computer's policy is refused BY OPENCODE first; the adapter then hands each refused call
21
+ * to `approve` (the computer's policy, then the phone, remote-approvals.mjs), and when one is approved runs ONE follow-up
22
+ * in the same session and the same turn, with exactly that command or that file allowed, and says so to the agent. Never
23
+ * an auto-approval, never a wildcard: a command or path that holds `*` or `?` is not carried (it would allow more).
24
+ * Steering is queued (the next run takes it); interrupt is SIGINT, on which OpenCode cancels its session and exits.
25
+ */
26
+ import { spawn } from "node:child_process";
27
+ import { randomBytes } from "node:crypto";
28
+ import { realpathSync } from "node:fs";
29
+ import { isAbsolute, relative } from "node:path";
30
+
31
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/@+#-]{0,127}$/;
32
+ const SESSION = /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/;
33
+ export const isOpenCodeSessionId = (value) => typeof value === "string" && SESSION.test(value);
34
+ /** The flags that make OpenCode approve by itself: never on our command line (check-remote-cli, rule D). */
35
+ export const OPENCODE_NEVER = Object.freeze(["--auto", "--yolo", "--dangerously-skip-permissions"]);
36
+ const BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
37
+
38
+ /** A new session id as OpenCode mints one (packages/schema identifier.ts `descending`): newest sorts first, 14 random characters. */
39
+ export function mintOpenCodeSessionId(now = Date.now(), random = randomBytes) {
40
+ const value = ~(BigInt(now) * 0x1000n + 1n);
41
+ const time = Array.from({ length: 6 }, (_, i) => Number((value >> BigInt(40 - 8 * i)) & 0xffn).toString(16).padStart(2, "0")).join("");
42
+ return `ses_${time}${Array.from(random(14), (byte) => BASE62[byte % 62]).join("")}`;
43
+ }
44
+
45
+ /** The fixed command line: no free argument reaches OpenCode, and the prompt goes on stdin. */
46
+ export function openCodeArgs({ sessionRef, model, mode }) {
47
+ if (!isOpenCodeSessionId(sessionRef)) throw new Error("an OpenCode session id is ses_ and 26 characters");
48
+ if (model !== null && !MODEL.test(model)) throw new Error("not a model name");
49
+ if (mode !== "ask" && mode !== "plan") throw new Error("the protocol offers the ask and plan modes only");
50
+ return ["run", "--format", "json", "--session", sessionRef, ...(model ? ["--model", model] : []), ...(mode === "plan" ? ["--agent", "plan"] : [])];
51
+ }
52
+
53
+ const SECRET_READS = ["*.env", "*.env.*", "*.envrc", "*.netrc", "*.npmrc", "*.pypirc", "*.git-credentials", "*.pem", "*.key", "*.p12", "*.pfx", "*id_rsa*", "*id_ed25519*", "*id_ecdsa*", "*credentials*", "*secret*"];
54
+ const noWildcard = (text) => typeof text === "string" && text.length > 0 && !/[*?]/.test(text);
55
+ /**
56
+ * The run's own permission config. `allow`: the actions approved for this one run, each `{ tool: "Bash", command }` or
57
+ * `{ tool: "Edit", path }` (relative to the project), allowed by their exact text on top of "ask". String values replace
58
+ * whatever a person's or a repository's config set for the same key (OpenCode merges configs key by key).
59
+ */
60
+ export function permissionConfig(mode, allow = []) {
61
+ const read = Object.fromEntries([["*", "allow"], ...SECRET_READS.map((p) => [p, "deny"])]);
62
+ const bash = allow.filter((a) => a.tool === "Bash" && noWildcard(a.command)), edit = allow.filter((a) => a.tool === "Edit" && noWildcard(a.path));
63
+ const permission = { "*": "ask", read, glob: "allow", grep: "allow", list: "allow", todowrite: "allow", external_directory: "deny", question: "deny", doom_loop: "deny",
64
+ bash: bash.length ? Object.fromEntries([["*", "ask"], ...bash.map((a) => [a.command, "allow"])]) : "ask",
65
+ edit: mode === "plan" ? "deny" : edit.length ? Object.fromEntries([["*", "ask"], ...edit.map((a) => [a.path, "allow"])]) : "ask" };
66
+ return { permission, agent: { build: { permission }, plan: { permission: { ...permission, edit: "deny" } } } };
67
+ }
68
+
69
+ const REFUSED = /cannot ask the user for permission/i; // OpenCode's own words to the model for a request this run rejected
70
+ const EDITS = new Set(["edit", "write", "patch", "multiedit"]);
71
+ /**
72
+ * A tool call OpenCode refused because nobody could answer → the call as the computer's policy classifies it, or null.
73
+ * Only a refusal is asked about; a call OpenCode's config denied outright (outside the project, a secret file) is not.
74
+ */
75
+ export function openCodeRefusal(line, projectPath) {
76
+ const part = line?.type === "tool_use" ? line.part : null;
77
+ if (!part || part.state?.status !== "error" || !REFUSED.test(String(part.state?.error ?? ""))) return null;
78
+ const input = part.state?.input && typeof part.state.input === "object" ? part.state.input : {};
79
+ if (part.tool === "bash") return noWildcard(input.command) ? { tool: "Bash", input: { command: input.command }, carry: { tool: "Bash", command: input.command } } : null;
80
+ if (EDITS.has(part.tool)) {
81
+ const file = input.filePath ?? input.file_path ?? input.path;
82
+ if (typeof file !== "string" || !file) return null;
83
+ const absolute = isAbsolute(file) ? file : `${projectPath}/${file}`;
84
+ let real = projectPath; try { real = realpathSync(projectPath); } catch { /* as given */ }
85
+ const rel = [projectPath, real].map((root) => relative(root, absolute).split("\\").join("/")).find((r) => !r.startsWith("..") && !isAbsolute(r));
86
+ if (rel === undefined || !noWildcard(rel)) return null;
87
+ return { tool: part.tool === "write" ? "Write" : "Edit", input: { file_path: absolute }, carry: { tool: "Edit", path: rel } };
88
+ }
89
+ if (part.tool === "webfetch") return { tool: "WebFetch", input: { url: String(input.url ?? "") }, carry: null }; // never approvable: the phone hears why
90
+ return null;
91
+ }
92
+ const followUp = (carried) => `The person approved on their phone what was refused a moment ago: ${carried.map((a) => (a.tool === "Bash" ? `run \`${a.command}\`` : `edit ${a.path}`)).join("; ")}. Do exactly that now, then continue the task.`;
93
+ const MAX_FOLLOW_UPS = 3;
94
+
95
+ /**
96
+ * o: { file, cwd, env, model, mode, sessionRef, onMessage(line), onExit(how), approve(tool, input) → Promise<boolean> }.
97
+ * → { pid, alive, write(text), interrupt() → Promise<boolean>, stop(), close() }. A turn is one run and its follow-ups;
98
+ * onMessage hears each JSON line and `wt.turn_started` / `wt.turn_ended` around them.
99
+ */
100
+ export function startOpenCode(o) {
101
+ const args = openCodeArgs({ sessionRef: o.sessionRef, model: o.model, mode: o.mode });
102
+ let child = null, closed = false, interrupted = false, busy = false, exited = false;
103
+ const queue = [];
104
+ const runOnce = (text, allow) => new Promise((resolve) => {
105
+ const env = { ...o.env, OPENCODE_CONFIG_CONTENT: JSON.stringify(permissionConfig(o.mode, allow)) };
106
+ const run = child = spawn(o.file, args, { cwd: o.cwd, env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
107
+ const asks = [];
108
+ let buffer = "";
109
+ run.stdout.setEncoding("utf8");
110
+ run.stdout.on("data", (chunk) => {
111
+ buffer += chunk;
112
+ if (buffer.length > 16 * 1024 * 1024) { buffer = ""; return; }
113
+ let end;
114
+ while ((end = buffer.indexOf("\n")) >= 0) {
115
+ const raw = buffer.slice(0, end); buffer = buffer.slice(end + 1);
116
+ let line; try { line = JSON.parse(raw); } catch { continue; }
117
+ o.onMessage(line);
118
+ const refused = openCodeRefusal(line, o.cwd);
119
+ if (refused) asks.push(Promise.resolve(o.approve(refused.tool, refused.input)).then((ok) => (ok && refused.carry ? refused.carry : null), () => null));
120
+ }
121
+ });
122
+ run.stderr.on("data", () => {}); // never logged: it may hold the agent's words
123
+ run.stdin.on("error", () => {});
124
+ run.stdin.end(text);
125
+ let done = false;
126
+ const finish = (how) => { if (!done) { done = true; if (child === run) child = null; resolve({ ...how, asks }); } };
127
+ run.on("exit", (code, signal) => finish({ code, signal }));
128
+ run.on("error", () => finish({ code: null, signal: null, error: true }));
129
+ });
130
+ async function turn(text) {
131
+ busy = true; interrupted = false;
132
+ o.onMessage({ type: "wt.turn_started" });
133
+ let prompt = text, allow = [], last = { code: null };
134
+ for (let round = 0; round <= MAX_FOLLOW_UPS; round += 1) {
135
+ last = await runOnce(prompt, allow);
136
+ if (interrupted || closed || last.code !== 0) break;
137
+ const carried = (await Promise.all(last.asks)).filter(Boolean); // an approval still open holds the turn, as it holds Claude Code's
138
+ if (carried.length === 0 || interrupted || closed) break;
139
+ allow = carried; prompt = followUp(carried);
140
+ }
141
+ busy = false;
142
+ o.onMessage({ type: "wt.turn_ended", outcome: interrupted || closed ? "interrupted" : last.code === 0 ? "completed" : "failed" });
143
+ if (!closed && queue.length > 0) turn(queue.shift());
144
+ }
145
+ const signal = (run, sig) => { try { if (process.platform === "win32") run.kill(sig); else process.kill(-run.pid, sig); } catch { /* gone */ } };
146
+ const waitExit = (run, ms) => new Promise((resolve) => { if (run.exitCode !== null || run.signalCode !== null) { resolve(true); return; } const t = setTimeout(() => resolve(false), ms); run.once("exit", () => { clearTimeout(t); resolve(true); }); });
147
+ async function halt(graceMs) {
148
+ const run = child;
149
+ if (!run) return;
150
+ for (const sig of ["SIGINT", "SIGTERM", "SIGKILL"]) { signal(run, sig); if (await waitExit(run, graceMs)) return; }
151
+ }
152
+ return {
153
+ get pid() { return child?.pid ?? null; },
154
+ alive: () => !closed,
155
+ sessionRef: () => o.sessionRef,
156
+ write: (t) => { if (closed) return; if (busy) queue.push(t); else turn(t); },
157
+ /** End the running turn: OpenCode cancels its session's work on SIGINT and exits; the session stays for the next prompt. */
158
+ async interrupt() { if (!child) return false; interrupted = true; await halt(3000); return true; },
159
+ async stop(graceMs = 3000) {
160
+ if (exited) return;
161
+ closed = true; interrupted = true; queue.length = 0;
162
+ await halt(graceMs);
163
+ exited = true;
164
+ o.onExit({ code: null, signal: null });
165
+ },
166
+ close() { return this.stop(); },
167
+ };
168
+ }
169
+
170
+ /** What `opencode --version` and `opencode run --help` say this OpenCode can do: every flag above, read from its help, never assumed. */
171
+ export function openCodeReport(version, runHelp) {
172
+ const h = runHelp ?? "";
173
+ const usable = Boolean(String(version ?? "").trim()) && /--format\b[\s\S]{0,200}?\bjson\b/.test(h) && /--session\b[\s\S]{0,200}?create if it does not exist/i.test(h) && /--model\b/.test(h) && /--agent\b/.test(h);
174
+ return { usable, capabilities: usable ? { start: true, prompt: true, steer: true, steer_mode: "queued", interrupt: true, stop: true, structured_events: true, resume_by_id: true, permission_modes: ["ask", "plan"], approvals: "structured" } : null };
175
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `npx worktrust remote codex on | off` and `npx worktrust remote opencode on | off` (2026-11-07; OpenCode 2026-11-09, owner:
3
+ * "the same on/off switch as Codex"). An agent that reads without asking is offered to a phone only after the person turned it
4
+ * on at this keyboard, the gap stated and a typed yes; until then the inventory lists it as installed and offers it nothing
5
+ * (remote-inventory.mjs `offered`, settings.codex / settings.opencode, off by default in remote-store.mjs).
6
+ *
7
+ * agentSwitch(io, agent, rest, askTyped) agent: "codex" | "opencode"
8
+ */
9
+ import { loadSettings, saveSettings } from "./remote-store.mjs";
10
+
11
+ const AGENTS = {
12
+ codex: { name: "Codex", gap: [
13
+ " Codex from a phone: it asks before every command it does not trust and every edit, and the computer classifies those.",
14
+ " But it runs the reads it deems safe (cat, rg, head, sed -n) WITHOUT asking. This computer ends a turn as soon as a",
15
+ " command reads a secret path (keys, .env, credentials), but by then the read has started. MCP servers a Codex plugin",
16
+ " brings still start. Claude Code has deny rules for those reads; Codex has none on this version."] },
17
+ opencode: { name: "OpenCode", gap: [
18
+ " OpenCode from a phone: every command, edit, fetch and subagent is refused by OpenCode and comes to the computer, which",
19
+ " classifies it; secret files and paths outside the project are denied. But it reads the project's other files WITHOUT",
20
+ " asking, and OpenCode merges its configuration key by key, so an agent file the repository brings can loosen a rule.",
21
+ " MCP servers in your OpenCode configuration still start."] },
22
+ };
23
+
24
+ export async function agentSwitch(io, agent, rest, askTyped) {
25
+ const { name, gap } = AGENTS[agent];
26
+ const s = loadSettings();
27
+ if (rest[0] === "off") { saveSettings({ ...s, [agent]: false }); io.say(` ${name} is no longer offered to a phone.`); return; }
28
+ if (rest[0] !== "on") { io.say(` ${name} is ${s[agent] ? "on" : "off"} for remote. npx worktrust remote ${agent} on | off`); return; }
29
+ for (const line of gap) io.say(line);
30
+ if (!(await askTyped(` Offer ${name} to your phones anyway? Type yes: `))) io.fail(`${name} stays off`);
31
+ saveSettings({ ...s, [agent]: true });
32
+ io.say(` ✓ ${name} is offered to your phones. npx worktrust remote ${agent} off takes it back.`);
33
+ }
package/remote-cli.mjs CHANGED
@@ -20,6 +20,7 @@
20
20
  * built HTML file, per granted folder (rendered with your Chrome)
21
21
  * remote codex on | off offer Codex to a phone (off by default): Codex runs the reads it
22
22
  * deems safe without asking, which the person accepts here
23
+ * remote opencode on | off the same for OpenCode (off by default; remote-agent-switch.mjs)
23
24
  * remote releases [released <number>] the releases on this computer; mark a ready one released (the
24
25
  * phone never can: publishing stays at the desk)
25
26
  * remote terminal on | off | list | start [<folder>] and remote attach <id> terminal sessions (release 19): Claude Code
@@ -157,7 +158,7 @@ async function phones(io, rest) {
157
158
  const all = [...list.confirmed, ...list.pending], at = Date.now(); if (all.length === 0) return io.say(" No phone or browser is connected to this computer.");
158
159
  if (process.stdin.isTTY && !(await askTyped(` Disconnect all ${all.length} phones and browsers from this computer now?`))) return io.say(" Nothing changed.");
159
160
  savePhones({ ...list, pending: [], confirmed: [], removed: [...list.removed.filter((p) => !all.some((x) => x.device_id === p.device_id)), ...all.map((p) => ({ device_id: p.device_id, fingerprint: p.fingerprint, how: "keyboard", removed_at: at }))].slice(-20) });
160
- return io.say(` ✓ Disconnected ${all.length}: none of them can steer this computer any more. Live sessions they started keep running here; stop them with npx worktrust remote disable, or pause everything with npx worktrust remote pause.\n End their keys for your whole account too: app.worktrust.io › Settings › MOCHI, or MOCHI settings on your phone.`);
161
+ return io.say(` ✓ Disconnected ${all.length}: none of them can steer this computer any more. Live sessions they started keep running here; stop them with npx worktrust remote disable, or pause everything with npx worktrust remote pause.\n End their keys for your whole account too: app.worktrust.io › Settings › Remote Agent, or Remote Agent settings on your phone.`);
161
162
  }
162
163
  if (rest[0] === "remove") {
163
164
  const phone = find(rest[1]);
@@ -281,7 +282,7 @@ function status(io) {
281
282
  const agents = inventory({ env: { ...process.env, PATH: settings.agent_path ?? process.env.PATH } }).reports.filter((r) => r.installed);
282
283
  const summary = { enabled: settings.enabled, paused: settings.paused, paired: Boolean(identity), device_id: identity?.device_id ?? null, fingerprint: keys ? fingerprintOf(keys) : null,
283
284
  gateway: settings.gateway, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length, browsers_added: phonesList.confirmed.filter((p) => p.how === "endorsed").length, allow_endorse: settings.allow_endorse === true }, projects: loadProjects().length,
284
- agents: agents.map((a) => ({ adapter: a.adapter, version: a.version, adapter_ready: a.capabilities.start, models: a.models === null ? "not listed" : a.models.length })), invite_open: Boolean(readJson("invite.json")?.used === false) };
285
+ agents: agents.map((a) => ({ adapter: a.adapter, version: a.version, adapter_ready: a.capabilities.start, switched_off: a.capabilities.start && (a.adapter === "codex" || a.adapter === "opencode") && settings[a.adapter] !== true, models: a.models === null ? "not listed" : a.models.length })), invite_open: Boolean(readJson("invite.json")?.used === false) };
285
286
  if (io.has("json")) { io.say(JSON.stringify(summary, null, 2)); return; }
286
287
  io.say(` Remote: ${settings.enabled ? (settings.paused ? `paused (${settings.paused === "desk" ? "here" : "from a phone"})` : "on") : "off"}`);
287
288
  io.say(` Paired: ${identity ? `${identity.device_id} · key ${summary.fingerprint}` : "no"}`);
@@ -289,7 +290,7 @@ function status(io) {
289
290
  io.say(` Service: ${service.kind === "foreground" ? "none on this system: run `npx worktrust remote run`" : `${service.installed ? "installed" : "not installed"}, ${service.running ? "running" : "not running"}`}`);
290
291
  io.say(` Phones: ${summary.phones.confirmed} confirmed (${summary.phones.browsers_added} browsers added by a phone), ${summary.phones.pending} pending · Folders granted: ${summary.projects}`);
291
292
  io.say(` Phones may add a browser: ${summary.phones.allow_endorse ? "yes" : "no"}`);
292
- for (const a of summary.agents) io.say(` Agent: ${a.adapter} ${a.version ?? ""} · ${a.adapter_ready ? "remote adapter ready" : "installed, no adapter yet"} · models: ${a.models}`);
293
+ for (const a of summary.agents) io.say(` Agent: ${a.adapter} ${a.version ?? ""} · ${a.switched_off ? `installed, switched off: npx worktrust remote ${a.adapter} on` : a.adapter_ready ? "remote adapter ready" : "installed, no adapter yet"} · models: ${a.models}`);
293
294
  }
294
295
 
295
296
  export async function remoteCommand(args, io) {
@@ -330,21 +331,9 @@ export async function remoteCommand(args, io) {
330
331
  for (const p of loadProjects()) { const g = grants[p.project_id]; if (g) io.say(` ${p.path}: ports ${g.ports.join(", ") || "none"} · files ${g.files.join(", ") || "none"}`); }
331
332
  return;
332
333
  }
333
- if (sub === "codex") {
334
- const s = loadSettings();
335
- if (rest[0] === "off") { saveSettings({ ...s, codex: false }); io.say(" Codex is no longer offered to a phone."); return; }
336
- if (rest[0] !== "on") { io.say(` Codex is ${s.codex ? "on" : "off"} for remote. npx worktrust remote codex on | off`); return; }
337
- io.say(" Codex from a phone: it asks before every command it does not trust and every edit, and the computer classifies those.");
338
- io.say(" But it runs the reads it deems safe (cat, rg, head, sed -n) WITHOUT asking. This computer ends a turn as soon as a");
339
- io.say(" command reads a secret path (keys, .env, credentials), but by then the read has started. MCP servers a Codex plugin");
340
- io.say(" brings still start. Claude Code has deny rules for those reads; Codex has none on this version.");
341
- if (!(await askTyped(" Offer Codex to your phones anyway? Type yes: "))) io.fail("Codex stays off");
342
- saveSettings({ ...s, codex: true });
343
- io.say(" ✓ Codex is offered to your phones. npx worktrust remote codex off takes it back.");
344
- return;
345
- }
334
+ if (sub === "codex" || sub === "opencode") return (await import("./remote-agent-switch.mjs")).agentSwitch(io, sub, rest, askTyped);
346
335
  if (sub === "releases") return releasesCommand(io, rest);
347
336
  if (sub === "terminal") return (await import("./remote-terminal-cli.mjs")).terminalCommand(io, rest, askTyped);
348
337
  if (sub === "attach") return (await import("./remote-terminal-cli.mjs")).attachCommand(io, rest);
349
- io.say(" npx worktrust remote enable | pair | status | pause | resume | disable [--forget] | phones [confirm|remove <id>|remove --all|allow-endorse on|off] | projects add|remove|list | run | pipeline review <folder>|status | roots add|remove|list | preview allow|deny|list | codex on|off | terminal on|off|list|start | attach <id> | releases [released <n>]");
338
+ io.say(" npx worktrust remote enable | pair | status | pause | resume | disable [--forget] | phones [confirm|remove <id>|remove --all|allow-endorse on|off] | projects add|remove|list | run | pipeline review <folder>|status | roots add|remove|list | preview allow|deny|list | codex on|off | opencode on|off | terminal on|off|list|start | attach <id> | releases [released <n>]");
350
339
  }
@@ -5,8 +5,9 @@
5
5
  * `cursor-agent models`). Claude Code has no lister: since 2026-11-08 (owner: the phone chooses Claude's models as it
6
6
  * does Codex's) its models are the ALIASES its own --model help names ("an alias for the latest model (e.g. 'fable',
7
7
  * 'opus', or 'sonnet')"), read from this computer's version, each a value `claude --model` takes; a help without that
8
- * line lists nothing ("not listed"), never a guess. Claude Code and Codex have adapters; the others report "installed, no
9
- * adapter yet" (every capability false).
8
+ * line lists nothing ("not listed"), never a guess. Claude Code, Codex and (2026-11-09) OpenCode have adapters; OpenCode is
9
+ * reported capable only when its own `run --help` names every flag the adapter uses (remote-adapter-opencode.mjs). The
10
+ * others report "installed, no adapter yet" (every capability false).
10
11
  *
11
12
  * No shell: each probe is execFile with fixed arguments, a timeout and no input. Nothing here leaves the computer except
12
13
  * inside a sealed device.inventory.
@@ -16,6 +17,7 @@ import { existsSync, statSync } from "node:fs";
16
17
  import { delimiter, join } from "node:path";
17
18
  import * as P from "./remote-protocol.mjs";
18
19
  import { codexReport } from "./remote-adapter-codex.mjs";
20
+ import { openCodeReport } from "./remote-adapter-opencode.mjs";
19
21
  import { terminalReport, tmuxVersion } from "./remote-adapter-terminal.mjs";
20
22
  import { typingTrusted } from "./remote-screen-states.mjs";
21
23
 
@@ -110,7 +112,7 @@ export function inventory({ env = process.env, refresh = false, now = Date.now()
110
112
  const version = probe(file, ["--version"], env);
111
113
  if (adapter === "claude-code") { const help = probe(file, ["--help"], env); features["claude-code"] = claudeFeatures(help); reports.push(claudeReport(version, help, now)); continue; }
112
114
  // Codex (2026-11-07): its app-server, when this version has one (remote-adapter-codex.mjs); models from `codex debug models`.
113
- const codex = adapter === "codex" ? codexReport(version, probe(file, ["app-server", "--help"], env)) : null;
115
+ const codex = adapter === "codex" ? codexReport(version, probe(file, ["app-server", "--help"], env)) : adapter === "opencode" ? openCodeReport(version, probe(file, ["run", "--help"], env)) : null;
114
116
  reports.push({ adapter, mode: "structured", installed: true, version: version ? version.trim().slice(0, 200) : null, signed_in: null, capabilities: codex?.usable ? { ...NO, ...codex.capabilities } : NO, ...listModels(adapter, file, env, now), default_model: null });
115
117
  }
116
118
  for (const report of reports) {
@@ -134,7 +136,9 @@ export const adapterOf = (inv, id) => inv.reports.find((r) => r.adapter === id);
134
136
  * listed as installed and offered nothing.
135
137
  */
136
138
  export function offered(inv, settings) {
137
- const reports = settings?.codex === true ? inv.reports : inv.reports.map((r) => (r.adapter === "codex" && r.capabilities.start ? { ...r, capabilities: NO } : r));
139
+ // OpenCode the same (owner, 2026-11-09): it reads the project's files without asking; `worktrust remote opencode on`.
140
+ const off = (r) => (r.adapter === "codex" || r.adapter === "opencode") && settings?.[r.adapter] !== true && r.capabilities.start;
141
+ const reports = inv.reports.map((r) => (off(r) ? { ...r, capabilities: NO } : r));
138
142
  // Terminal sessions (release 19) only after `worktrust remote terminal on`: an older phone refuses a second report of one adapter.
139
143
  // Typing from a phone only on a screen detector whose fixtures were recorded from the real agent (remote-screen-states.mjs).
140
144
  // Answering its dialogs from a phone (screen-hash approvals) needs the same: approvals "screen" only then.
@@ -0,0 +1,90 @@
1
+ /**
2
+ * OPENCODE'S `run --format json` STREAM, MAPPED TO THE PROTOCOL (owner, 2026-11-09: steer OpenCode, and through it Qwen on
3
+ * Ollama, from Remote Agent). Pure: one line in, the protocol's events out. Read from OpenCode's source (anomalyco/opencode,
4
+ * packages/cli/src/run/noninteractive.ts, the `renderer`'s `emit`, read 2026-11-09): every line is
5
+ * `{ type, timestamp, sessionID, ... }`, and these are the ones it writes:
6
+ *
7
+ * text part.text, the NEW words of an answer since the last line agent.output_delta { assistant }; kept as the answer
8
+ * tool_use one per finished tool call: part.tool, part.state.status agent.step_started and agent.step_completed together
9
+ * (completed | error), state.input, state.time { start, end } (OpenCode writes a call only when it is done)
10
+ * step_finish part.tokens { input, output, reasoning, cache { read, write } } per model step: agent.usage, the turn's sum
11
+ * error error.message kept: the failed turn's reason
12
+ * reasoning, step_start, retry, background_wait counted, nothing sent
13
+ *
14
+ * The adapter (remote-adapter-opencode.mjs) adds two lines of its own around the runs of one turn: `wt.turn_started`
15
+ * and `wt.turn_ended { outcome: completed | interrupted | failed }`. Words are cut to the protocol's sizes.
16
+ */
17
+ import * as P from "./remote-protocol.mjs";
18
+
19
+ const cut = (text, max) => (typeof text === "string" ? (text.length > max ? text.slice(0, max) : text) : "");
20
+ const TEST = /(^|\s)(pnpm|npm|yarn|bun)\s+(run\s+)?test\b|(^|\s)(pytest|vitest|jest|go\s+test|cargo\s+test|node\s+--test)\b/;
21
+ const STEP_KIND = { bash: "command", edit: "edit", write: "edit", patch: "edit", multiedit: "edit", read: "read", list: "read", glob: "search", grep: "search", webfetch: "search", websearch: "search", task: "tool", todowrite: "think", todoread: "think" };
22
+ const n = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
23
+ const steps = (s) => ({ kind: "steps", started: s.started, completed: s.completed });
24
+
25
+ export const emptyOpenCodeState = () => ({ turnStartedAt: null, started: 0, completed: 0, offset: 0, answer: "", turnTokens: null, session: null, error: null, ignored: 0 });
26
+
27
+ /** One step's counts in the protocol's fields: OpenCode's input is new input (the cache read apart), output holds the reasoning. */
28
+ export function openCodeTokens(t) {
29
+ if (!t || typeof t !== "object") return null;
30
+ const input = n(t.input), output = n(t.output), reasoning = n(t.reasoning) ?? 0;
31
+ return { input, output: output === null ? null : output + reasoning, cache_read: n(t.cache?.read), cache_creation: n(t.cache?.write) };
32
+ }
33
+ /** What a tool call is about, as the phone's step label: the command, the file, or the tool's name. */
34
+ function labelOf(tool, input) {
35
+ const i = input && typeof input === "object" ? input : {};
36
+ if (tool === "bash") return cut(String(i.command ?? ""), 500) || "command";
37
+ const file = i.filePath ?? i.file_path ?? i.path;
38
+ if (typeof file === "string" && file) return cut(file, 500);
39
+ if (tool === "grep" || tool === "glob") return cut(`${tool} ${String(i.pattern ?? "")}`.trim(), 500);
40
+ return cut(String(tool || "tool"), 500);
41
+ }
42
+
43
+ /** One line → { state, events, turn: "started" | "ended" | null }. `mint(prefix)` makes ids; `model` is the session's chosen model. */
44
+ export function mapOpenCodeLine(state, line, mint, now, model = null) {
45
+ const s = { ...state };
46
+ const events = [];
47
+ const type = line?.type, part = line?.part ?? {};
48
+ if (type === "wt.turn_started") {
49
+ Object.assign(s, { turnStartedAt: now, started: 0, completed: 0, offset: 0, answer: "", turnTokens: null, error: null });
50
+ return { state: s, events, turn: "started" };
51
+ }
52
+ if (type === "text" && typeof part.text === "string" && part.text.length > 0) {
53
+ const text = cut(part.text, 65_536);
54
+ events.push({ type: "agent.output_delta", body: { stream: "assistant", offset: s.offset, text } });
55
+ s.offset += text.length;
56
+ s.answer = cut(s.answer + text, P.MAX_ANSWER_CHARS + 1);
57
+ return { state: s, events, turn: null };
58
+ }
59
+ if (type === "tool_use" && typeof part.tool === "string") {
60
+ const label = labelOf(part.tool, part.state?.input), kind = STEP_KIND[part.tool] ?? "tool";
61
+ const step_id = mint("stp");
62
+ s.started += 1;
63
+ events.push({ type: "agent.step_started", body: { step_id, label, kind: kind === "command" && TEST.test(label) ? "test" : kind, progress: steps(s) } });
64
+ s.completed += 1;
65
+ const start = Number(part.state?.time?.start), end = Number(part.state?.time?.end);
66
+ events.push({ type: "agent.step_completed", body: { step_id, outcome: part.state?.status === "completed" ? "ok" : "failed", progress: steps(s), duration_ms: Number.isFinite(start) && Number.isFinite(end) && end >= start ? Math.round(end - start) : 0 } });
67
+ return { state: s, events, turn: null };
68
+ }
69
+ if (type === "step_finish") {
70
+ const t = openCodeTokens(part.tokens);
71
+ if (!t) { s.ignored += 1; return { state: s, events, turn: null }; }
72
+ s.turnTokens = s.turnTokens ? P.addTokens(s.turnTokens, t) : t;
73
+ s.session = s.session ? P.addTokens(s.session, t) : t;
74
+ events.push({ type: "agent.usage", body: { model, turn: s.turnTokens, turn_final: false, session: s.session } });
75
+ return { state: s, events, turn: null };
76
+ }
77
+ if (type === "error") { s.error = typeof line.error?.message === "string" ? cut(line.error.message, 4000) : "OpenCode reported an error"; return { state: s, events, turn: null }; }
78
+ if (type === "wt.turn_ended") {
79
+ const time = s.turnStartedAt !== null ? { started_at: s.turnStartedAt, duration_ms: Math.max(0, now - s.turnStartedAt) } : {};
80
+ if (s.turnTokens) events.push({ type: "agent.usage", body: { model, turn: s.turnTokens, turn_final: true, session: s.session } });
81
+ const answer = s.answer || null;
82
+ if (line.outcome === "completed") events.push({ type: "agent.completed", body: { summary: answer ? cut(answer, 4000) : null, progress: steps(s), result: { answer: answer ? cut(answer, P.MAX_ANSWER_CHARS) : null, answer_cut: (answer?.length ?? 0) > P.MAX_ANSWER_CHARS, source: "none", files: [], files_cut: false, tests: [] }, ...time } });
83
+ else if (line.outcome === "interrupted") events.push({ type: "agent.stopped", body: {} });
84
+ else events.push({ type: "agent.failed", body: { reason: "adapter_error", message: s.error, ...time } });
85
+ Object.assign(s, { turnStartedAt: null });
86
+ return { state: s, events, turn: "ended" };
87
+ }
88
+ s.ignored += 1;
89
+ return { state: s, events, turn: null };
90
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * AN OPENCODE SESSION ON THIS COMPUTER (owner, 2026-11-09), the glue between remote-sessions.mjs and the adapter
3
+ * (remote-adapter-opencode.mjs): the same order as Claude Code's start, held by check-remote-cli rule D. OpenCode creates a
4
+ * session under an id it is given, so the id was minted at the start and the steered ledger names it BEFORE the first run;
5
+ * each line goes through the protocol mapping (remote-opencode-events.mjs) into the session's one turn handling, and every
6
+ * call OpenCode refused reaches the computer's approvals (policy first, then the phone).
7
+ *
8
+ * spawnOpenCode(ctx, s, { mark, onExit, afterMapped, everyMs })
9
+ */
10
+ import * as P from "./remote-protocol.mjs";
11
+ import { startOpenCode } from "./remote-adapter-opencode.mjs";
12
+ import { mapOpenCodeLine } from "./remote-opencode-events.mjs";
13
+
14
+ export function spawnOpenCode(ctx, s, { mark, onExit, afterMapped, everyMs }) {
15
+ s.token = ctx.approvals.register(s); // so its open approvals are denied when it ends
16
+ mark(s); // the ledger names the session before OpenCode writes a line
17
+ s.run = startOpenCode({ file: ctx.inventory().files.opencode, cwd: s.projectPath, env: ctx.agentEnv(), model: s.model, mode: s.mode, sessionRef: s.agent_ref,
18
+ onMessage: (line) => { const mapped = mapOpenCodeLine(s.state, line, (prefix = "stp") => P.mintId(prefix, ctx.random), ctx.now(), s.model); s.state = mapped.state; afterMapped(s, mapped); },
19
+ onExit: (how) => onExit(s, how),
20
+ approve: async (tool, input) => (await ctx.approvals.request(s, tool, input))?.behavior === "allow" });
21
+ ctx.journal.recordSession({ session_id: s.session_id, pid: null, agent_session_ref: s.agent_ref }); // one process per run: no pid for a later daemon to end
22
+ s.ledgerTimer = setInterval(() => { if (s.turnOpen) mark(s); }, everyMs);
23
+ s.ledgerTimer.unref?.();
24
+ }
@@ -18,6 +18,9 @@ import { backgroundJobs, emptyClaudeState, endClaudeRun, mapClaudeLine } from ".
18
18
  import { collectChanges, snapshotChanges } from "./remote-changes.mjs";
19
19
  import { isCodexThreadId, startCodex, writeBridgeSession } from "./remote-adapter-codex.mjs";
20
20
  import { emptyCodexState, mapCodexMessage, unwrapShell } from "./remote-codex-events.mjs";
21
+ import { isOpenCodeSessionId, mintOpenCodeSessionId } from "./remote-adapter-opencode.mjs";
22
+ import { emptyOpenCodeState } from "./remote-opencode-events.mjs";
23
+ import { spawnOpenCode } from "./remote-opencode-session.mjs";
21
24
  import { createCoalescer } from "./remote-coalesce.mjs";
22
25
  import { accept, announceQueue, claudeReplay, codexLanded, dropWaiting, interruptedEnd, interruptOf, steerLive, steerModeOf } from "./remote-steering.mjs";
23
26
  import { classifyAction } from "./remote-policy.mjs";
@@ -25,6 +28,9 @@ import { activeRows, listSessions, statusReport } from "./remote-session-list.mj
25
28
 
26
29
  export const DEFAULT_MAX_SESSIONS = 4;
27
30
  const LEDGER_EVERY_MS = 10 * 60_000;
31
+ /** Per agent: the shape of its own session id (a resume names one), and a fresh stream state. */
32
+ const AGENT_ID = { "claude-code": isClaudeSessionId, codex: isCodexThreadId, opencode: isOpenCodeSessionId };
33
+ const FRESH_STATE = { "claude-code": emptyClaudeState, codex: emptyCodexState, opencode: emptyOpenCodeState };
28
34
 
29
35
  export { createCoalescer } from "./remote-coalesce.mjs"; // kept here for the modules that import it from sessions
30
36
 
@@ -98,7 +104,7 @@ export function createSessions(ctx) {
98
104
  /** What still waits goes out, then every subagent still open is stopped: the map never shows one working forever. */
99
105
  function endRun(s) {
100
106
  s.coalesce.flush();
101
- if (s.adapter === "codex") return; // Codex reports no subagents to close
107
+ if (s.adapter !== "claude-code") return; // Codex and OpenCode report no subagents to close
102
108
  const end = endClaudeRun(s.state, ctx.now());
103
109
  s.state = end.state;
104
110
  for (const e of end.events) deliver(s, e);
@@ -188,6 +194,7 @@ export function createSessions(ctx) {
188
194
 
189
195
  function spawnAgent(s, resume) {
190
196
  if (s.adapter === "codex") return spawnCodex(s, resume);
197
+ if (s.adapter === "opencode") return spawnOpenCode(ctx, s, { mark, onExit, afterMapped, everyMs: LEDGER_EVERY_MS }); // remote-opencode-session.mjs
191
198
  const features = ctx.inventory().features["claude-code"];
192
199
  s.token = ctx.approvals.register(s);
193
200
  s.mcpFile = writeMcpConfig(join(ctx.runDir, `${s.session_id}.mcp.json`), { node: ctx.node, bridge: ctx.bridgePath, socket: ctx.socket(), token: s.token });
@@ -206,10 +213,10 @@ export function createSessions(ctx) {
206
213
  if (!project) return "not_found";
207
214
  const refused = P.checkStart(payload, adapterOf(ctx.inventory(), payload.adapter));
208
215
  if (refused) return refused;
209
- if (payload.adapter !== "claude-code" && payload.adapter !== "codex") return "unsupported";
210
- if (payload.resume !== null && !(payload.adapter === "codex" ? isCodexThreadId : isClaudeSessionId)(payload.resume)) return "unsupported";
216
+ if (!AGENT_ID[payload.adapter]) return "unsupported";
217
+ if (payload.resume !== null && !AGENT_ID[payload.adapter](payload.resume)) return "unsupported";
211
218
  const s = { session_id: env.session_id, project_id: project.project_id, projectPath: project.path, adapter: payload.adapter, model: payload.model, mode: payload.permission_mode,
212
- agent_ref: payload.resume ?? (payload.adapter === "codex" ? null : randomUUID()), how: "started", first: ctx.now(), queue: [], state: payload.adapter === "codex" ? emptyCodexState() : emptyClaudeState(),
219
+ agent_ref: payload.resume ?? (payload.adapter === "codex" ? null : payload.adapter === "opencode" ? mintOpenCodeSessionId(ctx.now(), ctx.random) : randomUUID()), how: "started", first: ctx.now(), queue: [], state: FRESH_STATE[payload.adapter](),
213
220
  coalesce: createCoalescer({ now: ctx.now }), attention: null, command_id: null, waiting: null, turnOpen: false, run: null, steers: [], interrupting: false, ownTurn: null, task: env.task === true, tokens: P.NO_TOKENS, subagents: new Map(), turnStartedAt: null, name: payload.name ?? null, active: 0, countedTurn: null };
214
221
  live.set(s.session_id, s);
215
222
  ctx.journal.recordSession({ session_id: s.session_id, adapter: s.adapter, project_id: s.project_id, agent_session_ref: s.agent_ref, model: s.model, mode: s.mode, at: ctx.now(), name: s.name, active_ms: 0 });
@@ -229,9 +236,9 @@ export function createSessions(ctx) {
229
236
  if (!saved || saved.closed) return null;
230
237
  const project = ctx.projects().find((p) => p.project_id === saved.project_id);
231
238
  const ref = s?.agent_ref ?? saved.agent_session_ref;
232
- if (!project || !(saved.adapter === "codex" ? isCodexThreadId : isClaudeSessionId)(ref)) return null;
239
+ if (!project || !AGENT_ID[saved.adapter]?.(ref)) return null;
233
240
  if ([...live.values()].filter((x) => x.run).length >= (ctx.settings().max_sessions ?? DEFAULT_MAX_SESSIONS)) return null;
234
- s = s ?? { session_id: sessionId, project_id: saved.project_id, projectPath: project.path, adapter: saved.adapter, model: saved.model ?? null, mode: saved.mode ?? "ask", agent_ref: ref, how: "started", first: ctx.now(), queue: [], state: saved.adapter === "codex" ? emptyCodexState() : emptyClaudeState(),
241
+ s = s ?? { session_id: sessionId, project_id: saved.project_id, projectPath: project.path, adapter: saved.adapter, model: saved.model ?? null, mode: saved.mode ?? "ask", agent_ref: ref, how: "started", first: ctx.now(), queue: [], state: FRESH_STATE[saved.adapter](),
235
242
  coalesce: createCoalescer({ now: ctx.now }), attention: null, command_id: null, waiting: null, turnOpen: false, run: null, steers: [], interrupting: false, ownTurn: null, task: false, tokens: P.NO_TOKENS, subagents: new Map(), turnStartedAt: null, name: saved.name ?? null, active: saved.active_ms ?? null, countedTurn: null };
236
243
  live.set(sessionId, s);
237
244
  spawnAgent(s, s.agent_ref);
@@ -88,10 +88,16 @@ export function appendPipelineMark(record, file = steeredFile()) {
88
88
  try { writeSync(fd, `${canonical(record)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
89
89
  }
90
90
 
91
- /** The agent's own session id a reader file names: Claude Code's <uuid>.jsonl, a Codex rollout's trailing uuid, a database session's id. */
91
+ /**
92
+ * The agent's own session id a reader file names: Claude Code's <uuid>.jsonl, a Codex rollout's trailing uuid, a database
93
+ * session's id (`<client>:<database>#<session id>`, session-databases.mjs: the part after the last `#`; 2026-11-09, before
94
+ * which an OpenCode session steered from a phone named no ref and was measured as the person's).
95
+ */
92
96
  export function sessionRefsOf(file) {
93
97
  const name = String(file).split(/[\\/]/).at(-1).replace(/\.jsonl$/, "");
94
98
  const refs = new Set([name]);
99
+ const hash = name.lastIndexOf("#");
100
+ if (hash >= 0) refs.add(name.slice(hash + 1));
95
101
  const uuid = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.exec(name)?.[1];
96
102
  if (uuid) refs.add(uuid);
97
103
  const colon = name.lastIndexOf(":");
package/remote-store.mjs CHANGED
@@ -69,7 +69,7 @@ export const saveIdentity = (identity) => writeJson("identity.json", identity);
69
69
 
70
70
  // allow_endorse (2026-11-09): may a confirmed phone add a browser it scanned (remote-endorse.mjs)? Off until the person says so
71
71
  // here, at the keyboard (`worktrust remote phones allow-endorse on`).
72
- export const DEFAULT_SETTINGS = Object.freeze({ v: 1, enabled: false, paused: null, gateway: null, default_adapter: "claude-code", default_model: null, agent_path: null, codex: false, terminal: false, allow_endorse: false });
72
+ export const DEFAULT_SETTINGS = Object.freeze({ v: 1, enabled: false, paused: null, gateway: null, default_adapter: "claude-code", default_model: null, agent_path: null, codex: false, opencode: false, terminal: false, allow_endorse: false });
73
73
  export const loadSettings = () => ({ ...DEFAULT_SETTINGS, ...(readJson("settings.json") ?? {}) });
74
74
  export const saveSettings = (settings) => writeJson("settings.json", { ...DEFAULT_SETTINGS, ...settings });
75
75
 
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * THE SESSION DATABASES — the clients that keep their sessions in SQLite, read into Claude Code's shape (2026-10-05).
3
3
  *
4
- * Hermes Agent, Goose, OpenCode and OpenClaw keep no transcript file: each writes its sessions to its own SQLite
4
+ * Hermes Agent, Goose, OpenCode and OpenClaw (and, through session-local-models.mjs, the Ollama app and Open WebUI) keep no transcript file: each writes its sessions to its own SQLite
5
5
  * database. This reads them through node:sqlite (Node 22.5+), read-only, into the same lines transcript-readers.mjs
6
6
  * makes of the files, so the session hook's one clock reads them all. Each query takes roles, clocks, models and token
7
7
  * counts and no text column (scripts/test-database-clients.mjs holds every query to that). It ships beside the hook,
@@ -147,8 +147,7 @@ export function gooseLines(pseudo) {
147
147
  const messages = db.prepare(`select role, created_timestamp as at,
148
148
  case when json_valid(content_json) then (select group_concat(json_extract(value, '$.type')) from json_each(content_json)) end as kinds
149
149
  from messages where session_id = ? order by created_timestamp, id`).all(id);
150
- const ledger = db.prepare("select 1 from sqlite_master where type = 'table' and name = 'usage_ledger'").get() ? db.prepare("select created_timestamp as at, model, input_tokens as input, output_tokens as output, cache_read_tokens as cache_read, cache_write_tokens as cache_write from usage_ledger where session_id = ? order by created_timestamp, id").all(id)
151
- : null;
150
+ const ledger = db.prepare("select 1 from sqlite_master where type = 'table' and name = 'usage_ledger'").get() ? db.prepare("select created_timestamp as at, model, input_tokens as input, output_tokens as output, cache_read_tokens as cache_read, cache_write_tokens as cache_write from usage_ledger where session_id = ? order by created_timestamp, id").all(id) : null;
152
151
  const fallbackModel = cleanModel(session.model);
153
152
  const lines = messages.map((message) => {
154
153
  const kinds = new Set(String(message.kinds ?? "").split(","));
@@ -181,10 +180,7 @@ export function gooseLines(pseudo) {
181
180
  * leaves the database (text lives in the `part` table, which is never read). A subagent's session (`parent_id`) is not
182
181
  * read. How it was steered is not said: the terminal, the desktop app and a phone on `opencode serve` look alike here.
183
182
  */
184
- export function opencodeHomes(given) {
185
- if (given) return [given.replace(/^~(?=\/|$)/, homedir())];
186
- return [join(process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"), "opencode")];
187
- }
183
+ export function opencodeHomes(given) { return given ? [given.replace(/^~(?=\/|$)/, homedir())] : [join(process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"), "opencode")]; }
188
184
  const opencodeDatabases = (home) => { try { return readdirSync(home).filter((name) => /^opencode(-[A-Za-z0-9_.-]+)?\.db$/.test(name)).sort().map((name) => join(home, name)); } catch { return []; } };
189
185
  export function* opencodeSessions(homes) {
190
186
  for (const home of homes) for (const file of opencodeDatabases(home)) {
@@ -548,6 +544,7 @@ const DATABASE_CLIENTS = {
548
544
  cursor: { homes: cursorHomes, sessions: cursorSessions, lines: cursorLines },
549
545
  copilot: { homes: copilotHomes, sessions: copilotSessions, lines: copilotLines },
550
546
  "gemini-cli": { homes: geminiHomes, sessions: geminiSessions, lines: geminiLines },
547
+ ...((await import("./session-local-models.mjs").catch(() => null))?.LOCAL_MODEL_CLIENTS ?? {}), // 2026-11-09: the Ollama app and Open WebUI; without the module, not read
551
548
  };
552
549
  export const DATABASE_SESSION = new RegExp(`^(${Object.keys(DATABASE_CLIENTS).join("|")}):.+#[A-Za-z0-9_.:-]{1,120}$`);
553
550
  /** Every attended session of every database client; `given` names a client's own home (a test), `onlyGiven` reads no other. */
@@ -558,4 +555,6 @@ export function* databaseSessions(given = {}, onlyGiven = false) {
558
555
  }
559
556
  }
560
557
  export const databaseLines = (pseudo) => DATABASE_CLIENTS[pseudo.slice(0, pseudo.indexOf(":"))]?.lines(pseudo) ?? null;
558
+ /** What each client with a store report found (the local models): read with its count of chats, or present and not read with why. */
559
+ export const databaseStores = (given = {}, onlyGiven = false) => Object.entries(DATABASE_CLIENTS).flatMap(([client, r]) => (r.stores ? r.stores(given[client] ? r.homes(given[client]) : onlyGiven ? [] : r.homes()) : []));
561
560
  // ── end database clients ──