@ouro.bot/cli 0.1.0-alpha.1455 → 0.1.0-alpha.1457

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/changelog.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1457",
6
+ "changes": [
7
+ "`coding_spawn` is now the one way an agent starts a coding agent, and it opens it in Orca by default: a repo checkout gets its own Orca worktree, an existing Orca worktree gets a new agent tab, and either way the agent shows in Orca's sidebar with its terminal. `coding_status`, `coding_tail`, `coding_send_input` and `coding_kill` work on it like any other session: status comes from Orca's agent state, tail from the terminal's screen, input is typed into the terminal, and kill closes the tab but keeps the worktree.",
8
+ "`coding_spawn` takes `backend` (`orca`, `local` or `workbench`) to choose somewhere else for one job. An agent's default is `coding.backend` in agent.json, `orca` when unset; an unknown value is refused, not replaced with another. `local` is the old headless claude or codex child process. Workbench now gets picked as a backend this way instead of through the `features.workbenchCoding` runtime flag, which is gone.",
9
+ "An Orca session is not marked finished on one missed check: its terminal has to be missing from three refreshes in a row, and it counts as completed only if Orca last saw the agent done (Orca's `done` alone means the agent finished a turn and waits for more). After Orca restarts, a session finds its terminal again by its tab and pane, never by taking another session's terminal. A checkout Orca doesn't know yet is registered with Orca before the worktree is made. If Orca opens the agent but cannot deliver its prompt, the tab is closed and the spawn fails with the worktree's path."
10
+ ]
11
+ },
12
+ {
13
+ "version": "0.1.0-alpha.1456",
14
+ "changes": [
15
+ "Update the Ouro UI files to Ouro UI v1.3.479."
16
+ ]
17
+ },
4
18
  {
5
19
  "version": "0.1.0-alpha.1455",
6
20
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1455",
2
+ "runtimeVersion": "0.1.0-alpha.1457",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1455</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1457</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -112,9 +112,6 @@ const DEFAULT_LOCAL_RUNTIME_CONFIG = {
112
112
  perplexityApiKey: "",
113
113
  openaiEmbeddingsApiKey: "",
114
114
  },
115
- features: {
116
- workbenchCoding: false,
117
- },
118
115
  };
119
116
  function defaultRuntimeConfig() {
120
117
  return {
@@ -127,7 +124,6 @@ function defaultRuntimeConfig() {
127
124
  bluebubblesChannel: { ...DEFAULT_LOCAL_RUNTIME_CONFIG.bluebubblesChannel },
128
125
  vault: { ...DEFAULT_LOCAL_RUNTIME_CONFIG.vault },
129
126
  integrations: { ...DEFAULT_LOCAL_RUNTIME_CONFIG.integrations },
130
- features: { ...DEFAULT_LOCAL_RUNTIME_CONFIG.features },
131
127
  };
132
128
  }
133
129
  let _runtimeConfigOverride = null;
@@ -1,27 +1,56 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatCodingTail = exports.attachCodingSessionFeedback = exports.formatCodingMonitorReport = exports.CodingSessionMonitor = exports.WorkbenchMcpClient = exports.WorkbenchCodingSessionManager = exports.CodingSessionManager = void 0;
3
+ exports.formatCodingTail = exports.attachCodingSessionFeedback = exports.formatCodingMonitorReport = exports.CodingSessionMonitor = exports.CodingSessionRouter = exports.OrcaCli = exports.OrcaCodingSessionManager = exports.WorkbenchMcpClient = exports.WorkbenchCodingSessionManager = exports.CodingSessionManager = exports.DEFAULT_CODING_BACKEND = void 0;
4
+ exports.preferredCodingBackend = preferredCodingBackend;
5
+ exports.createBackendManager = createBackendManager;
4
6
  exports.getCodingSessionManager = getCodingSessionManager;
5
7
  exports.resetCodingSessionManager = resetCodingSessionManager;
6
8
  const runtime_1 = require("../../nerves/runtime");
7
- const config_1 = require("../../heart/config");
8
9
  const identity_1 = require("../../heart/identity");
9
10
  const manager_1 = require("./manager");
11
+ const orca_manager_1 = require("./orca-manager");
10
12
  const workbench_manager_1 = require("./workbench-manager");
11
13
  const workbench_client_1 = require("./workbench-client");
14
+ const router_1 = require("./router");
15
+ /** Ouro's current choice for where coding agents run when agent.json names none. */
16
+ exports.DEFAULT_CODING_BACKEND = "orca";
12
17
  let manager = null;
18
+ /** The agent's preferred coding backend: agent.json `coding.backend`, else orca. An unknown value is an error, never a quiet default. */
19
+ function preferredCodingBackend() {
20
+ const configured = (0, identity_1.loadAgentConfig)().coding?.backend;
21
+ if (configured === undefined)
22
+ return exports.DEFAULT_CODING_BACKEND;
23
+ if (router_1.CODING_BACKENDS.includes(configured))
24
+ return configured;
25
+ throw new Error(`agent.json coding.backend is ${JSON.stringify(configured)}; use one of ${router_1.CODING_BACKENDS.join(", ")} (or remove it for ${exports.DEFAULT_CODING_BACKEND})`);
26
+ }
27
+ function createBackendManager(backend, agentName) {
28
+ switch (backend) {
29
+ case "orca":
30
+ return new orca_manager_1.OrcaCodingSessionManager({ agentName });
31
+ case "workbench":
32
+ return new workbench_manager_1.WorkbenchCodingSessionManager({ agentName, client: new workbench_client_1.WorkbenchMcpClient() });
33
+ case "local":
34
+ return new manager_1.CodingSessionManager({ agentName });
35
+ }
36
+ }
13
37
  function getCodingSessionManager() {
14
38
  if (!manager) {
15
- const config = (0, config_1.loadConfig)();
16
- const backend = config.features.workbenchCoding ? "workbench" : "process";
17
- manager = config.features.workbenchCoding
18
- ? new workbench_manager_1.WorkbenchCodingSessionManager({ agentName: (0, identity_1.getAgentName)(), client: new workbench_client_1.WorkbenchMcpClient() })
19
- : new manager_1.CodingSessionManager({});
39
+ const agentName = (0, identity_1.getAgentName)();
40
+ const preferredBackend = preferredCodingBackend();
41
+ // Local and Orca sessions restore from files under the bundle, so they are read at start;
42
+ // Workbench is only reached when it is preferred or a spawn names it.
43
+ const eagerBackends = [...new Set(["local", "orca", preferredBackend])];
44
+ manager = new router_1.CodingSessionRouter({
45
+ preferredBackend,
46
+ eagerBackends,
47
+ createManager: (backend) => createBackendManager(backend, agentName),
48
+ });
20
49
  (0, runtime_1.emitNervesEvent)({
21
50
  component: "repertoire",
22
51
  event: "repertoire.coding_manager_init",
23
52
  message: "initialized coding session manager singleton",
24
- meta: { backend },
53
+ meta: { preferredBackend },
25
54
  });
26
55
  }
27
56
  return manager;
@@ -42,6 +71,12 @@ var workbench_manager_2 = require("./workbench-manager");
42
71
  Object.defineProperty(exports, "WorkbenchCodingSessionManager", { enumerable: true, get: function () { return workbench_manager_2.WorkbenchCodingSessionManager; } });
43
72
  var workbench_client_2 = require("./workbench-client");
44
73
  Object.defineProperty(exports, "WorkbenchMcpClient", { enumerable: true, get: function () { return workbench_client_2.WorkbenchMcpClient; } });
74
+ var orca_manager_2 = require("./orca-manager");
75
+ Object.defineProperty(exports, "OrcaCodingSessionManager", { enumerable: true, get: function () { return orca_manager_2.OrcaCodingSessionManager; } });
76
+ var orca_client_1 = require("./orca-client");
77
+ Object.defineProperty(exports, "OrcaCli", { enumerable: true, get: function () { return orca_client_1.OrcaCli; } });
78
+ var router_2 = require("./router");
79
+ Object.defineProperty(exports, "CodingSessionRouter", { enumerable: true, get: function () { return router_2.CodingSessionRouter; } });
45
80
  var monitor_1 = require("./monitor");
46
81
  Object.defineProperty(exports, "CodingSessionMonitor", { enumerable: true, get: function () { return monitor_1.CodingSessionMonitor; } });
47
82
  var reporter_1 = require("./reporter");
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.OrcaCli = exports.OrcaCliError = void 0;
37
+ exports.resolveOrcaExecutable = resolveOrcaExecutable;
38
+ const child_process_1 = require("child_process");
39
+ const fs = __importStar(require("fs"));
40
+ const os = __importStar(require("os"));
41
+ const path = __importStar(require("path"));
42
+ const runtime_1 = require("../../nerves/runtime");
43
+ class OrcaCliError extends Error {
44
+ code;
45
+ constructor(message, code) {
46
+ super(message);
47
+ this.code = code;
48
+ this.name = "OrcaCliError";
49
+ }
50
+ }
51
+ exports.OrcaCliError = OrcaCliError;
52
+ const APP_BINARY = path.join("Orca.app", "Contents", "Resources", "bin", "orca");
53
+ /** The orca binary: the app bundle's copy when installed (a daemon's PATH often lacks it), else `orca` on PATH. */
54
+ function resolveOrcaExecutable(options = {}) {
55
+ const existsSync = options.existsSync ?? fs.existsSync;
56
+ const homeDir = options.homeDir ?? os.homedir();
57
+ const candidates = [path.join("/Applications", APP_BINARY), path.join(homeDir, "Applications", APP_BINARY)];
58
+ return candidates.find((candidate) => existsSync(candidate)) ?? "orca";
59
+ }
60
+ function asRecord(value) {
61
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
62
+ }
63
+ function asString(value) {
64
+ return typeof value === "string" && value.length > 0 ? value : undefined;
65
+ }
66
+ function parseReply(command, stdout, execError, stderr) {
67
+ let reply = null;
68
+ try {
69
+ reply = asRecord(JSON.parse(stdout));
70
+ }
71
+ catch {
72
+ reply = null;
73
+ }
74
+ if (reply && reply.ok === true)
75
+ return asRecord(reply.result);
76
+ const error = asRecord(reply?.error);
77
+ const code = asString(error.code) ?? (execError ? "orca-cli-failed" : "orca-bad-reply");
78
+ const message = asString(error.message) ?? (stderr.trim() || execError?.message || `orca ${command} printed no JSON reply`);
79
+ throw new OrcaCliError(`orca ${command}: ${message}`, code);
80
+ }
81
+ function worktreeFrom(value) {
82
+ const record = asRecord(value);
83
+ const id = asString(record.id);
84
+ const worktreePath = asString(record.path);
85
+ if (!id || !worktreePath)
86
+ throw new OrcaCliError("orca reply carried no worktree id and path", "orca-bad-reply");
87
+ return {
88
+ id,
89
+ path: worktreePath,
90
+ branch: asString(record.branch)?.replace(/^refs\/heads\//, ""),
91
+ isMainWorktree: record.isMainWorktree === true,
92
+ };
93
+ }
94
+ function launchFrom(result, worktree) {
95
+ const launch = asRecord(result.launch ?? result);
96
+ const outcome = asRecord(launch.outcome);
97
+ const handle = asString(outcome.handle) ?? asString(result.agentTerminalHandle);
98
+ if (!handle)
99
+ throw new OrcaCliError("orca started no terminal agent (no launch.outcome.handle in its reply)", "orca-no-terminal");
100
+ const promptOutcome = asString(asRecord(launch.prompt).outcome);
101
+ return {
102
+ worktree,
103
+ terminalHandle: handle,
104
+ // Orca's AgentLaunchPromptReceipt: journaled | handed-to-terminal | not-delivered | unconfirmed.
105
+ promptDelivered: promptOutcome === "not-delivered"
106
+ ? false
107
+ : promptOutcome === "journaled" || promptOutcome === "handed-to-terminal" ? true : null,
108
+ detail: asString(asRecord(launch.receipt).detail) ?? null,
109
+ };
110
+ }
111
+ class OrcaCli {
112
+ executablePath;
113
+ execFileFn;
114
+ timeoutMs;
115
+ launchTimeoutMs;
116
+ constructor(options = {}) {
117
+ this.executablePath = options.executablePath ?? resolveOrcaExecutable(options);
118
+ this.execFileFn = options.execFileFn ?? child_process_1.execFile;
119
+ this.timeoutMs = options.timeoutMs ?? 30_000;
120
+ this.launchTimeoutMs = options.launchTimeoutMs ?? 180_000;
121
+ }
122
+ run(args, options = {}) {
123
+ const command = args.slice(0, 2).join(" ");
124
+ (0, runtime_1.emitNervesEvent)({
125
+ component: "repertoire",
126
+ event: "repertoire.orca_cli_call",
127
+ message: "running orca CLI command",
128
+ meta: { command },
129
+ });
130
+ return new Promise((resolve, reject) => {
131
+ this.execFileFn(this.executablePath, [...args, "--json"], { cwd: options.cwd, timeout: options.timeoutMs ?? this.timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {
132
+ try {
133
+ resolve(parseReply(command, String(stdout ?? ""), error, String(stderr ?? "")));
134
+ }
135
+ catch (parseError) {
136
+ reject(parseError);
137
+ }
138
+ });
139
+ });
140
+ }
141
+ /** The Orca worktree at `dir`, or null when Orca manages none there. */
142
+ async showWorktree(dir) {
143
+ try {
144
+ return worktreeFrom((await this.run(["worktree", "show", "--worktree", `path:${dir}`])).worktree);
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ }
150
+ /** The id of the Orca repo checked out at `dir`, registering it with Orca first when Orca doesn't know it yet. */
151
+ async ensureRepo(dir) {
152
+ const listed = await this.run(["repo", "list"]);
153
+ const known = (Array.isArray(listed.repos) ? listed.repos : []).map(asRecord).find((repo) => repo.path === dir);
154
+ const knownId = asString(known?.id);
155
+ if (knownId)
156
+ return knownId;
157
+ const added = await this.run(["repo", "add", "--path", dir]);
158
+ const addedId = asString(asRecord(added.repo).id) ?? asString(added.id);
159
+ if (!addedId)
160
+ throw new OrcaCliError(`orca repo add --path ${dir} named no repo id`, "orca-bad-reply");
161
+ return addedId;
162
+ }
163
+ /** A new Orca worktree off the repo at `repoDir`, with a terminal agent already given the prompt. */
164
+ async createWorktreeWithAgent(input) {
165
+ const result = await this.run(["worktree", "create", "--repo", `id:${input.repoId}`, "--name", input.name, "--no-parent", "--agent", input.agent, "--surface", "terminal", "--prompt", input.prompt], { cwd: input.repoDir, timeoutMs: this.launchTimeoutMs });
166
+ return launchFrom(result, worktreeFrom(result.worktree));
167
+ }
168
+ /** A terminal agent in an existing Orca worktree, already given the prompt. */
169
+ async launchAgent(input) {
170
+ const result = await this.run(["agent", "launch", "--worktree", `id:${input.worktree.id}`, "--agent", input.agent, "--surface", "terminal", "--prompt", input.prompt], { cwd: input.worktree.path, timeoutMs: this.launchTimeoutMs });
171
+ return launchFrom(result, input.worktree);
172
+ }
173
+ async listTerminals(worktreeId) {
174
+ const result = await this.run(["terminal", "list", "--worktree", `id:${worktreeId}`]);
175
+ return (Array.isArray(result.terminals) ? result.terminals : []).map((item) => asRecord(item));
176
+ }
177
+ async listAgents(worktreeId) {
178
+ const result = await this.run(["agent", "list", "--worktree", `id:${worktreeId}`]);
179
+ return (Array.isArray(result.agents) ? result.agents : []).map((item) => asRecord(item));
180
+ }
181
+ async readTerminal(handle, limit = 120) {
182
+ const terminal = asRecord((await this.run(["terminal", "read", "--terminal", handle, "--screen", "--limit", String(limit)])).terminal);
183
+ const status = terminal.status === "running" || terminal.status === "exited" ? terminal.status : "unknown";
184
+ const tail = Array.isArray(terminal.tail) ? terminal.tail.map(String).join("\n") : "";
185
+ return { status, tail };
186
+ }
187
+ async sendText(handle, text) {
188
+ await this.run(["terminal", "send", "--terminal", handle, "--text", text, "--enter"]);
189
+ }
190
+ async closeTerminal(handle) {
191
+ await this.run(["terminal", "close", "--terminal", handle, "--tab"]);
192
+ }
193
+ }
194
+ exports.OrcaCli = OrcaCli;
@@ -0,0 +1,436 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.OrcaCodingSessionManager = exports.ORCA_MISSES_BEFORE_GONE = void 0;
37
+ exports.orcaWorktreeName = orcaWorktreeName;
38
+ exports.statusFromOrcaAgent = statusFromOrcaAgent;
39
+ const crypto_1 = require("crypto");
40
+ const fs = __importStar(require("fs"));
41
+ const path = __importStar(require("path"));
42
+ const identity_1 = require("../../heart/identity");
43
+ const runtime_1 = require("../../nerves/runtime");
44
+ const orca_client_1 = require("./orca-client");
45
+ const spawner_1 = require("./spawner");
46
+ /** Refreshes in a row that must miss a session's terminal before it counts as gone; one miss may be Orca restarting or asleep. */
47
+ exports.ORCA_MISSES_BEFORE_GONE = 3;
48
+ /** A session is closed once its Orca terminal is gone (killed, failed, or closed after it finished). */
49
+ function isClosed(session) {
50
+ return session.endedAt !== null;
51
+ }
52
+ function cloneSession(session) {
53
+ return {
54
+ ...session,
55
+ originSession: session.originSession ? { ...session.originSession } : undefined,
56
+ orca: { ...session.orca },
57
+ failure: session.failure ? { ...session.failure, args: [...session.failure.args] } : null,
58
+ };
59
+ }
60
+ /** A worktree name Orca accepts, from the task: lowercase words joined by dashes. */
61
+ function orcaWorktreeName(taskRef, id) {
62
+ const slug = (taskRef ?? "")
63
+ .toLowerCase()
64
+ .replace(/[^a-z0-9]+/g, "-")
65
+ .replace(/^-+|-+$/g, "")
66
+ .slice(0, 48)
67
+ .replace(/-+$/g, "");
68
+ return slug.length > 0 ? slug : id;
69
+ }
70
+ /**
71
+ * Orca's agent state, as a coding session status. Orca's `done` ends a turn, not the job (an interactive
72
+ * agent waits in its tab for more), so it reads as waiting for input; a session completes only when its
73
+ * terminal closes after `done`. An agent that has not reported yet is running.
74
+ */
75
+ function statusFromOrcaAgent(state) {
76
+ return state === "blocked" || state === "waiting" || state === "done" ? "waiting_input" : "running";
77
+ }
78
+ function updateKindFor(status) {
79
+ return status === "running" ? "progress" : status;
80
+ }
81
+ function clip(text, max = 280) {
82
+ const trimmed = text.trim();
83
+ return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max - 3)}...`;
84
+ }
85
+ class OrcaCodingSessionManager {
86
+ records = new Map();
87
+ listeners = new Map();
88
+ cli;
89
+ agentName;
90
+ stateFilePath;
91
+ nowIso;
92
+ newId;
93
+ existsSync;
94
+ readFileSync;
95
+ writeFileSync;
96
+ mkdirSync;
97
+ pollIntervalMs;
98
+ pollTimer = null;
99
+ polling = false;
100
+ constructor(options) {
101
+ this.agentName = options.agentName;
102
+ this.cli = options.cli ?? new orca_client_1.OrcaCli();
103
+ this.stateFilePath = options.stateFilePath ?? path.join((0, identity_1.getAgentRoot)(options.agentName), "state", "coding", "orca-sessions.json");
104
+ this.nowIso = options.nowIso ?? (() => new Date().toISOString());
105
+ this.newId = options.newId ?? (() => `orca-${(0, crypto_1.randomUUID)().slice(0, 8)}`);
106
+ this.existsSync = options.existsSync ?? fs.existsSync;
107
+ this.readFileSync = options.readFileSync ?? fs.readFileSync;
108
+ this.writeFileSync = options.writeFileSync ?? fs.writeFileSync;
109
+ this.mkdirSync = options.mkdirSync ?? fs.mkdirSync;
110
+ this.pollIntervalMs = options.pollIntervalMs ?? 30_000;
111
+ this.loadState();
112
+ }
113
+ async spawnSession(request) {
114
+ const id = this.newId();
115
+ const now = this.nowIso();
116
+ const normalized = {
117
+ ...request,
118
+ backend: "orca",
119
+ sessionId: id,
120
+ parentAgent: request.parentAgent ?? this.agentName,
121
+ };
122
+ const prompt = (0, spawner_1.buildCodingPrompt)(normalized, { existsSync: this.existsSync, readFileSync: this.readFileSync });
123
+ // An Orca worktree already at workdir gets a new agent tab; anything else (a repo's main checkout, or
124
+ // a checkout Orca doesn't know yet, which is registered with Orca first) gets its own new Orca worktree,
125
+ // so parallel jobs never collide.
126
+ const existing = await this.cli.showWorktree(normalized.workdir);
127
+ const inExisting = existing !== null && !existing.isMainWorktree;
128
+ const launch = inExisting
129
+ ? await this.cli.launchAgent({ worktree: existing, agent: normalized.runner, prompt })
130
+ : await this.cli.createWorktreeWithAgent({
131
+ repoDir: normalized.workdir,
132
+ repoId: await this.cli.ensureRepo(normalized.workdir),
133
+ name: orcaWorktreeName(normalized.taskRef, id),
134
+ agent: normalized.runner,
135
+ prompt,
136
+ });
137
+ if (launch.promptDelivered === false) {
138
+ await this.cli.closeTerminal(launch.terminalHandle).catch(() => undefined);
139
+ throw new Error(`Orca opened ${normalized.runner} in ${launch.worktree.path} but did not deliver its task prompt, so its tab was closed; the worktree stays. Spawn again with workdir ${launch.worktree.path}`);
140
+ }
141
+ let paneKey;
142
+ try {
143
+ const terminal = (await this.cli.listTerminals(launch.worktree.id)).find((item) => item.handle === launch.terminalHandle);
144
+ paneKey = terminal?.tabId && terminal.leafId ? `${terminal.tabId}:${terminal.leafId}` : undefined;
145
+ }
146
+ catch (error) {
147
+ this.reportOrcaUnreachable(id, error);
148
+ }
149
+ const session = {
150
+ id,
151
+ runner: normalized.runner,
152
+ backend: "orca",
153
+ orca: {
154
+ requestedWorkdir: normalized.workdir,
155
+ worktreeId: launch.worktree.id,
156
+ worktreePath: launch.worktree.path,
157
+ branch: launch.worktree.branch,
158
+ terminalHandle: launch.terminalHandle,
159
+ paneKey,
160
+ },
161
+ workdir: launch.worktree.path,
162
+ taskRef: normalized.taskRef,
163
+ originSession: normalized.originSession ? { ...normalized.originSession } : undefined,
164
+ obligationId: normalized.obligationId,
165
+ evolutionCaseId: normalized.evolutionCaseId,
166
+ scopeFile: normalized.scopeFile,
167
+ stateFile: normalized.stateFile,
168
+ checkpoint: launch.promptDelivered === null
169
+ ? "Orca did not confirm the task prompt arrived; read coding_tail to check"
170
+ : launch.detail,
171
+ status: "running",
172
+ stdoutTail: "",
173
+ stderrTail: "",
174
+ pid: null,
175
+ startedAt: now,
176
+ lastActivityAt: now,
177
+ endedAt: null,
178
+ restartCount: 0,
179
+ lastExitCode: null,
180
+ lastSignal: null,
181
+ failure: null,
182
+ };
183
+ this.records.set(id, { request: normalized, session });
184
+ this.persistState();
185
+ (0, runtime_1.emitNervesEvent)({
186
+ component: "repertoire",
187
+ event: "repertoire.orca_coding_session_spawned",
188
+ message: "Orca coding session spawned",
189
+ meta: { id, runner: session.runner, worktreePath: launch.worktree.path, created: !inExisting },
190
+ });
191
+ this.notify(id, { kind: "spawned", session: cloneSession(session) });
192
+ return cloneSession(session);
193
+ }
194
+ listSessions() {
195
+ return [...this.records.values()].map((record) => cloneSession(record.session)).sort((a, b) => a.id.localeCompare(b.id));
196
+ }
197
+ getSession(sessionId) {
198
+ const record = this.records.get(sessionId);
199
+ return record ? cloneSession(record.session) : null;
200
+ }
201
+ async refreshSessions() {
202
+ const byWorktree = new Map();
203
+ for (const record of this.records.values()) {
204
+ if (isClosed(record.session))
205
+ continue;
206
+ const worktreeId = record.session.orca.worktreeId;
207
+ byWorktree.set(worktreeId, [...(byWorktree.get(worktreeId) ?? []), record]);
208
+ }
209
+ for (const [worktreeId, records] of byWorktree) {
210
+ await this.refreshWorktree(worktreeId, records);
211
+ }
212
+ return this.listSessions();
213
+ }
214
+ async refreshSession(sessionId) {
215
+ const record = this.records.get(sessionId);
216
+ if (!record)
217
+ return null;
218
+ if (!isClosed(record.session)) {
219
+ await this.refreshWorktree(record.session.orca.worktreeId, [record]);
220
+ }
221
+ if (!isClosed(record.session)) {
222
+ try {
223
+ const read = await this.cli.readTerminal(record.session.orca.terminalHandle);
224
+ record.session.stdoutTail = read.tail;
225
+ }
226
+ catch (error) {
227
+ this.reportOrcaUnreachable(sessionId, error);
228
+ }
229
+ }
230
+ return cloneSession(record.session);
231
+ }
232
+ subscribe(sessionId, listener) {
233
+ const set = this.listeners.get(sessionId) ?? new Set();
234
+ set.add(listener);
235
+ this.listeners.set(sessionId, set);
236
+ this.startPolling();
237
+ return () => {
238
+ const current = this.listeners.get(sessionId);
239
+ if (!current)
240
+ return;
241
+ current.delete(listener);
242
+ if (current.size === 0)
243
+ this.listeners.delete(sessionId);
244
+ if (this.listeners.size === 0)
245
+ this.stopPolling();
246
+ };
247
+ }
248
+ async sendInput(sessionId, input) {
249
+ const record = this.records.get(sessionId);
250
+ if (!record)
251
+ return { ok: false, message: `session not found: ${sessionId}` };
252
+ if (isClosed(record.session)) {
253
+ return { ok: false, message: `session ${sessionId} has ended (${record.session.status}); its Orca terminal is closed` };
254
+ }
255
+ try {
256
+ await this.cli.sendText(record.session.orca.terminalHandle, input);
257
+ }
258
+ catch (error) {
259
+ return { ok: false, message: `Orca refused input for ${sessionId}: ${error instanceof Error ? error.message : String(error)}` };
260
+ }
261
+ record.session.status = "running";
262
+ record.session.lastActivityAt = this.nowIso();
263
+ this.persistState();
264
+ this.notify(sessionId, { kind: "progress", session: cloneSession(record.session) });
265
+ return { ok: true, message: `input sent to ${sessionId}` };
266
+ }
267
+ async killSession(sessionId) {
268
+ const record = this.records.get(sessionId);
269
+ if (!record)
270
+ return { ok: false, message: `session not found: ${sessionId}` };
271
+ if (isClosed(record.session))
272
+ return { ok: true, message: `session ${sessionId} has already ended (${record.session.status})` };
273
+ try {
274
+ await this.cli.closeTerminal(record.session.orca.terminalHandle);
275
+ }
276
+ catch (error) {
277
+ const reason = error instanceof Error ? error.message : String(error);
278
+ // The tab may already be gone; ask Orca before calling the kill failed.
279
+ record.misses = exports.ORCA_MISSES_BEFORE_GONE - 1;
280
+ await this.refreshWorktree(record.session.orca.worktreeId, [record]);
281
+ if (isClosed(record.session))
282
+ return { ok: true, message: `session ${sessionId} had already ended (${record.session.status})` };
283
+ return { ok: false, message: `Orca could not close ${sessionId}: ${reason}` };
284
+ }
285
+ record.session.status = "killed";
286
+ record.session.endedAt = this.nowIso();
287
+ record.session.checkpoint = `terminated by parent agent; worktree kept at ${record.session.orca.worktreePath}`;
288
+ this.persistState();
289
+ this.notify(sessionId, { kind: "killed", session: cloneSession(record.session) });
290
+ return { ok: true, message: `killed ${sessionId}; its worktree stays at ${record.session.orca.worktreePath}` };
291
+ }
292
+ checkStalls() {
293
+ return 0;
294
+ }
295
+ shutdown() {
296
+ this.stopPolling();
297
+ this.listeners.clear();
298
+ }
299
+ async refreshWorktree(worktreeId, records) {
300
+ let terminals;
301
+ let agents;
302
+ try {
303
+ terminals = await this.cli.listTerminals(worktreeId);
304
+ agents = await this.cli.listAgents(worktreeId);
305
+ }
306
+ catch (error) {
307
+ for (const record of records)
308
+ this.reportOrcaUnreachable(record.session.id, error);
309
+ return;
310
+ }
311
+ for (const record of records)
312
+ this.applyOrcaState(record, terminals, agents);
313
+ }
314
+ applyOrcaState(record, terminals, agents) {
315
+ const session = record.session;
316
+ const placement = session.orca;
317
+ let terminal = terminals.find((item) => item.handle === placement.terminalHandle);
318
+ if (!terminal && placement.paneKey) {
319
+ // Orca hands out new terminal handles when it restarts; the pane it sits in keeps its key.
320
+ const heldByOthers = new Set([...this.records.values()].filter((other) => other !== record).map((other) => other.session.orca.terminalHandle));
321
+ terminal = terminals.find((item) => `${item.tabId}:${item.leafId}` === placement.paneKey && !heldByOthers.has(item.handle));
322
+ if (terminal)
323
+ placement.terminalHandle = terminal.handle;
324
+ }
325
+ const previous = session.status;
326
+ if (!terminal) {
327
+ record.misses = (record.misses ?? 0) + 1;
328
+ if (record.misses < exports.ORCA_MISSES_BEFORE_GONE)
329
+ return;
330
+ session.endedAt = this.nowIso();
331
+ if (record.agentState === "done") {
332
+ session.status = "completed";
333
+ session.checkpoint = "finished; its Orca terminal has closed";
334
+ }
335
+ else {
336
+ session.status = "failed";
337
+ session.checkpoint = "its Orca terminal closed before the agent reported done";
338
+ session.failure = {
339
+ command: `orca ${session.runner}`,
340
+ args: [],
341
+ code: null,
342
+ signal: null,
343
+ stdoutTail: session.stdoutTail,
344
+ stderrTail: session.checkpoint,
345
+ };
346
+ }
347
+ this.persistState();
348
+ }
349
+ else {
350
+ record.misses = 0;
351
+ placement.paneKey = `${terminal.tabId}:${terminal.leafId}`;
352
+ const agent = agents.find((item) => item.paneKey === placement.paneKey);
353
+ record.agentState = agent?.state ?? record.agentState;
354
+ session.status = statusFromOrcaAgent(agent?.state);
355
+ if (agent?.lastAssistantMessage)
356
+ session.checkpoint = clip(agent.lastAssistantMessage);
357
+ if (terminal.lastOutputAt)
358
+ session.lastActivityAt = new Date(terminal.lastOutputAt).toISOString();
359
+ }
360
+ if (session.status !== previous) {
361
+ this.persistState();
362
+ this.notify(session.id, { kind: updateKindFor(session.status), session: cloneSession(session) });
363
+ }
364
+ }
365
+ reportOrcaUnreachable(sessionId, error) {
366
+ (0, runtime_1.emitNervesEvent)({
367
+ level: "warn",
368
+ component: "repertoire",
369
+ event: "repertoire.orca_coding_refresh_error",
370
+ message: "could not read an Orca coding session; showing its last known state",
371
+ meta: { sessionId, reason: error instanceof Error ? error.message : String(error) },
372
+ });
373
+ }
374
+ startPolling() {
375
+ if (this.pollTimer)
376
+ return;
377
+ this.pollTimer = setInterval(() => {
378
+ if (this.polling)
379
+ return;
380
+ this.polling = true;
381
+ void this.refreshSessions().finally(() => {
382
+ this.polling = false;
383
+ });
384
+ }, this.pollIntervalMs);
385
+ this.pollTimer.unref?.();
386
+ }
387
+ stopPolling() {
388
+ if (!this.pollTimer)
389
+ return;
390
+ clearInterval(this.pollTimer);
391
+ this.pollTimer = null;
392
+ }
393
+ notify(sessionId, update) {
394
+ for (const listener of this.listeners.get(sessionId) ?? []) {
395
+ void Promise.resolve(listener(update));
396
+ }
397
+ }
398
+ loadState() {
399
+ if (!this.existsSync(this.stateFilePath))
400
+ return;
401
+ try {
402
+ const parsed = JSON.parse(this.readFileSync(this.stateFilePath, "utf-8"));
403
+ for (const record of parsed.records ?? []) {
404
+ if (typeof record?.session?.id !== "string" || !record.session.orca?.terminalHandle)
405
+ continue;
406
+ this.records.set(record.session.id, { request: record.request, session: { ...record.session, backend: "orca" } });
407
+ }
408
+ }
409
+ catch (error) {
410
+ (0, runtime_1.emitNervesEvent)({
411
+ level: "warn",
412
+ component: "repertoire",
413
+ event: "repertoire.orca_coding_state_unreadable",
414
+ message: "Orca coding session state was unreadable; starting with none",
415
+ meta: { path: this.stateFilePath, reason: error instanceof Error ? error.message : String(error) },
416
+ });
417
+ }
418
+ }
419
+ persistState() {
420
+ try {
421
+ this.mkdirSync(path.dirname(this.stateFilePath), { recursive: true });
422
+ const records = [...this.records.values()].map((record) => ({ request: record.request, session: record.session }));
423
+ this.writeFileSync(this.stateFilePath, `${JSON.stringify({ records }, null, 2)}\n`, "utf-8");
424
+ }
425
+ catch (error) {
426
+ (0, runtime_1.emitNervesEvent)({
427
+ level: "warn",
428
+ component: "repertoire",
429
+ event: "repertoire.orca_coding_state_write_error",
430
+ message: "could not save Orca coding sessions; they are kept in memory",
431
+ meta: { path: this.stateFilePath, reason: error instanceof Error ? error.message : String(error) },
432
+ });
433
+ }
434
+ }
435
+ }
436
+ exports.OrcaCodingSessionManager = OrcaCodingSessionManager;
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CodingSessionRouter = exports.CODING_BACKENDS = void 0;
4
+ const runtime_1 = require("../../nerves/runtime");
5
+ /** Every coding backend, in the order sessions are listed. */
6
+ exports.CODING_BACKENDS = ["orca", "local", "workbench"];
7
+ function isRefreshable(manager) {
8
+ return typeof manager.refreshSessions === "function";
9
+ }
10
+ function stamp(session, backend) {
11
+ return { ...session, backend };
12
+ }
13
+ /**
14
+ * The one way Ouro starts and drives a coding agent. Each spawn goes to one backend (the request's,
15
+ * else the preferred one); status, tail, input and kill find the session wherever it runs.
16
+ */
17
+ class CodingSessionRouter {
18
+ preferredBackend;
19
+ createManager;
20
+ managers = new Map();
21
+ constructor(options) {
22
+ this.preferredBackend = options.preferredBackend;
23
+ this.createManager = options.createManager;
24
+ for (const backend of options.eagerBackends ?? [])
25
+ this.managerFor(backend);
26
+ }
27
+ async spawnSession(request) {
28
+ const backend = request.backend ?? this.preferredBackend;
29
+ (0, runtime_1.emitNervesEvent)({
30
+ component: "repertoire",
31
+ event: "repertoire.coding_backend_selected",
32
+ message: "routing coding spawn to a backend",
33
+ meta: { backend, preferred: this.preferredBackend, runner: request.runner },
34
+ });
35
+ const session = await this.managerFor(backend).spawnSession({ ...request, backend });
36
+ return stamp(session, backend);
37
+ }
38
+ listSessions() {
39
+ return this.entries().flatMap(([backend, manager]) => manager.listSessions().map((session) => stamp(session, backend)));
40
+ }
41
+ async refreshSessions() {
42
+ const all = [];
43
+ for (const [backend, manager] of this.entries()) {
44
+ let sessions;
45
+ try {
46
+ sessions = isRefreshable(manager) ? await manager.refreshSessions() : manager.listSessions();
47
+ }
48
+ catch (error) {
49
+ // One unreachable backend must not hide the sessions running on the others.
50
+ (0, runtime_1.emitNervesEvent)({
51
+ level: "warn",
52
+ component: "repertoire",
53
+ event: "repertoire.coding_backend_refresh_error",
54
+ message: "a coding backend could not refresh; showing its last known sessions",
55
+ meta: { backend, reason: error instanceof Error ? error.message : String(error) },
56
+ });
57
+ sessions = manager.listSessions();
58
+ }
59
+ all.push(...sessions.map((session) => stamp(session, backend)));
60
+ }
61
+ return all;
62
+ }
63
+ getSession(sessionId) {
64
+ const owner = this.ownerOf(sessionId);
65
+ return owner ? stamp(owner[1].getSession(sessionId), owner[0]) : null;
66
+ }
67
+ async refreshSession(sessionId) {
68
+ const owner = await this.findOwner(sessionId);
69
+ if (!owner)
70
+ return null;
71
+ const [backend, manager] = owner;
72
+ const session = isRefreshable(manager) ? await manager.refreshSession(sessionId) : manager.getSession(sessionId);
73
+ return session ? stamp(session, backend) : null;
74
+ }
75
+ subscribe(sessionId, listener) {
76
+ const owner = this.ownerOf(sessionId);
77
+ if (!owner)
78
+ return () => { };
79
+ const [backend, manager] = owner;
80
+ return manager.subscribe(sessionId, (update) => listener({ ...update, session: stamp(update.session, backend) }));
81
+ }
82
+ async sendInput(sessionId, input) {
83
+ const owner = await this.findOwner(sessionId);
84
+ return owner ? owner[1].sendInput(sessionId, input) : { ok: false, message: `session not found: ${sessionId}` };
85
+ }
86
+ async killSession(sessionId) {
87
+ const owner = await this.findOwner(sessionId);
88
+ return owner ? owner[1].killSession(sessionId) : { ok: false, message: `session not found: ${sessionId}` };
89
+ }
90
+ async checkStalls(nowMs) {
91
+ let total = 0;
92
+ for (const [, manager] of this.entries())
93
+ total += await manager.checkStalls(nowMs);
94
+ return total;
95
+ }
96
+ shutdown() {
97
+ for (const [, manager] of this.entries())
98
+ void manager.shutdown();
99
+ this.managers.clear();
100
+ }
101
+ managerFor(backend) {
102
+ let manager = this.managers.get(backend);
103
+ if (!manager) {
104
+ manager = this.createManager(backend);
105
+ this.managers.set(backend, manager);
106
+ }
107
+ return manager;
108
+ }
109
+ entries() {
110
+ return exports.CODING_BACKENDS.filter((backend) => this.managers.has(backend)).map((backend) => [backend, this.managers.get(backend)]);
111
+ }
112
+ /** The session's backend, refreshing once first when no manager knows it yet (Workbench learns its sessions on refresh). */
113
+ async findOwner(sessionId) {
114
+ const known = this.ownerOf(sessionId);
115
+ if (known)
116
+ return known;
117
+ await this.refreshSessions();
118
+ return this.ownerOf(sessionId);
119
+ }
120
+ ownerOf(sessionId) {
121
+ return this.entries().find(([, manager]) => manager.getSession(sessionId) !== null) ?? null;
122
+ }
123
+ }
124
+ exports.CodingSessionRouter = CodingSessionRouter;
@@ -10,6 +10,7 @@ const obligations_1 = require("../../arc/obligations");
10
10
  const evolution_1 = require("../../arc/evolution");
11
11
  const runtime_1 = require("../../nerves/runtime");
12
12
  const scrutiny_1 = require("../../mind/scrutiny");
13
+ const router_1 = require("./router");
13
14
  const RUNNERS = ["claude", "codex"];
14
15
  function requireArg(args, key) {
15
16
  const value = args[key];
@@ -21,6 +22,9 @@ function requireArg(args, key) {
21
22
  function parseRunner(value) {
22
23
  return RUNNERS.includes(value) ? value : null;
23
24
  }
25
+ function parseBackend(value) {
26
+ return router_1.CODING_BACKENDS.includes(value) ? value : null;
27
+ }
24
28
  function optionalArg(args, key) {
25
29
  const raw = args[key];
26
30
  if (!raw)
@@ -98,8 +102,12 @@ function matchesReusableCodingSession(session, request) {
98
102
  const scopeMatches = request.scopeFile ? session.scopeFile === request.scopeFile : true;
99
103
  const stateMatches = request.stateFile ? session.stateFile === request.stateFile : true;
100
104
  const evolutionCaseMatches = request.evolutionCaseId ? session.evolutionCaseId === request.evolutionCaseId : true;
101
- return (session.runner === request.runner &&
102
- session.workdir === request.workdir &&
105
+ const backendMatches = request.backend ? session.backend === request.backend : true;
106
+ // An Orca session runs in a worktree it made from the requested checkout; match on what was asked for.
107
+ const workdirMatches = session.workdir === request.workdir || session.orca?.requestedWorkdir === request.workdir;
108
+ return (backendMatches &&
109
+ session.runner === request.runner &&
110
+ workdirMatches &&
103
111
  session.taskRef === request.taskRef &&
104
112
  scopeMatches &&
105
113
  stateMatches &&
@@ -185,12 +193,13 @@ const codingSpawnTool = {
185
193
  type: "function",
186
194
  function: {
187
195
  name: "coding_spawn",
188
- description: "Spawn a claude or codex coding session in a separate process with its own context. Give it a COMPLETE, SELF-CONTAINED task description -- it cannot see this conversation or what you've tried. Include what to do, why, which files are involved, what 'done' looks like, and any required verification steps or tests so it can prove the work is done. Never delegate understanding -- don't write 'based on the conversation, fix the bug'; write the specific file paths, line numbers, and what to change.",
196
+ description: "Start a claude or codex coding agent with its own context. This is the one way to start a coding agent: by default it opens in Orca (its own worktree and terminal tab that a person can watch; a workdir that is already an Orca worktree gets a new tab there), and coding_status, coding_tail, coding_send_input and coding_kill drive it wherever it runs. Set backend only to override the agent's preferred one (agent.json coding.backend, default orca): local runs it headless as a child process, workbench hands it to Ouro Workbench. Give it a COMPLETE, SELF-CONTAINED task description -- it cannot see this conversation or what you've tried. Include what to do, why, which files are involved, what 'done' looks like, and any required verification steps or tests so it can prove the work is done. Never delegate understanding -- don't write 'based on the conversation, fix the bug'; write the specific file paths, line numbers, and what to change.",
189
197
  parameters: {
190
198
  type: "object",
191
199
  properties: {
192
200
  runner: { type: "string", enum: ["claude", "codex"] },
193
- workdir: { type: "string" },
201
+ backend: { type: "string", enum: [...router_1.CODING_BACKENDS], description: "Where it runs; omit for the agent's preferred backend (orca unless agent.json coding.backend says otherwise)." },
202
+ workdir: { type: "string", description: "A repo checkout (Orca makes a new worktree from it) or an existing Orca worktree (the agent opens there)." },
194
203
  prompt: { type: "string" },
195
204
  taskRef: { type: "string" },
196
205
  scopeFile: { type: "string" },
@@ -232,7 +241,7 @@ const codingSendInputTool = {
232
241
  type: "function",
233
242
  function: {
234
243
  name: "coding_send_input",
235
- description: "send stdin text to an existing coding session",
244
+ description: "Send text to an existing coding session, as if typed and submitted (its Orca terminal, or its process's stdin).",
236
245
  parameters: {
237
246
  type: "object",
238
247
  properties: {
@@ -247,7 +256,7 @@ const codingKillTool = {
247
256
  type: "function",
248
257
  function: {
249
258
  name: "coding_kill",
250
- description: "terminate an existing coding session",
259
+ description: "Stop an existing coding session. For an Orca session this closes its terminal tab; its worktree and commits stay.",
251
260
  parameters: {
252
261
  type: "object",
253
262
  properties: {
@@ -283,6 +292,13 @@ exports.codingToolDefinitions = [
283
292
  prompt,
284
293
  taskRef,
285
294
  };
295
+ const rawBackend = optionalArg(args, "backend");
296
+ if (rawBackend) {
297
+ const backend = parseBackend(rawBackend);
298
+ if (!backend)
299
+ return (0, tool_error_code_1.withCode)(`invalid backend: ${rawBackend}; use one of ${router_1.CODING_BACKENDS.join(", ")}`, "invalid-backend");
300
+ request.backend = backend;
301
+ }
286
302
  const evolutionCaseId = optionalArg(args, "evolutionCaseId");
287
303
  if (evolutionCaseId)
288
304
  request.evolutionCaseId = evolutionCaseId;
@@ -304,8 +320,11 @@ exports.codingToolDefinitions = [
304
320
  if (stateFile)
305
321
  request.stateFile = stateFile;
306
322
  const manager = (0, index_1.getCodingSessionManager)();
323
+ // Reuse only a session on the backend this spawn would use.
324
+ const preferredBackend = manager.preferredBackend;
325
+ const reuseRequest = { ...request, backend: request.backend ?? preferredBackend };
307
326
  const existingSessions = await listCodingSessions(manager);
308
- const existingSession = findReusableCodingSession(existingSessions, request);
327
+ const existingSession = findReusableCodingSession(existingSessions, reuseRequest);
309
328
  if (existingSession) {
310
329
  (0, runtime_1.emitNervesEvent)({
311
330
  component: "repertoire",
@@ -372,15 +391,16 @@ exports.codingToolDefinitions = [
372
391
  }
373
392
  return JSON.stringify(session);
374
393
  },
375
- summaryKeys: ["runner", "workdir", "taskRef"],
394
+ summaryKeys: ["runner", "backend", "workdir", "taskRef"],
376
395
  riskProfile: {
377
396
  mutates: ["durable_state_write", "external_side_effect"],
378
397
  risk: "high",
379
- reason: "spawns a separate coding process and may create obligations",
398
+ reason: "starts a separate coding agent (an Orca worktree and terminal by default) and may create obligations",
380
399
  },
381
- ax: { id: "tool:coding_spawn", group: "turn-coding", when: "Pick this to hand a whole coding job to a separate claude or codex worker; for one quick command, shell is enough.", effect: "write", errors: [
400
+ ax: { id: "tool:coding_spawn", group: "turn-coding", when: "Pick this to hand a whole coding job to a separate claude or codex worker (in Orca by default); never start one with the orca CLI through shell. For one quick command, shell is enough.", effect: "write", errors: [
382
401
  { code: "missing-argument", means: "runner, workdir, prompt or taskRef is missing or blank; the message names which.", fix: "Call coding_spawn again with all four filled in, the prompt complete enough to work from alone." },
383
402
  { code: "invalid-runner", means: "runner is something other than claude or codex.", fix: "Set runner to claude or codex and spawn again." },
403
+ { code: "invalid-backend", means: "backend is something other than orca, local or workbench.", fix: "Omit backend to use the preferred one, or set it to orca, local or workbench." },
384
404
  { code: "orientation-hold", means: "This turn is on a correction hold, so new coding work waits.", fix: "Call orientation_get, settle what the person meant, then spawn if the job is still right." },
385
405
  ] },
386
406
  },
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1455",
3
+ "version": "0.1.0-alpha.1457",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1455",
9
+ "version": "0.1.0-alpha.1457",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1455",
3
+ "version": "0.1.0-alpha.1457",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {