@conveno/cli 0.2.0-rc.12 → 0.2.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,7 +39,7 @@ Or run `conveno` with no arguments. It opens a full-screen app (Sessions, New, D
39
39
  | `conveno send <to> <text...> [--urgent]` | Send a message as you to a session name or id, `lead`, or `device:name`. `-` reads the text from standard input. |
40
40
  | `conveno rename <session> <new-name>` | Rename an online session. |
41
41
  | `conveno lead <session>` | Make a session the lead. `conveno lead --clear` leaves no lead. |
42
- | `conveno spawn <cli> [--cwd <dir>] [--name <name>] [--task <text> \| --task-file <path>] [--window] [--allow <kinds>] [--yes]` | Start a worker session of `claude`, `codex`, `opencode`, `antigravity` or `grok`, and print its name once it registers. The CLI must be installed. By default the worker runs in the background through the CLI's Agent Client Protocol server, with `conveno acp-host` driving it. It keeps running: each message sent to it becomes its next prompt at once when it is idle, or when its current turn ends. `--window` opens the real CLI in a new terminal instead, so you can watch it and take over: Windows Terminal (`wt -w 0 new-tab`, else a new console window) on Windows, Terminal.app (iTerm2 when it is your terminal) on macOS, and on Linux a new tmux window when you are inside tmux, else the first of `x-terminal-emulator`, `gnome-terminal`, `konsole`, `kitty`, `wezterm`, `alacritty` and `xterm`. The ACP commands are `claude-agent-acp` (install `@agentclientprotocol/claude-agent-acp`), `codex-acp` (install `@agentclientprotocol/codex-acp`), `opencode acp`, `agy acp` and `grok agent stdio`; a missing one is an error that says what to install. For Claude Code and Codex, `conveno init` can allow running the adapter with `npx -y <package>@<pinned version>`, and `CONVENO_ACP_CODEX_CMD` / `CONVENO_ACP_CLAUDE_CMD` replace the command. In the background a tool call that needs approval is denied unless `--allow` covers it: comma-separated ACP tool kinds (`read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `switch_mode`, `other`, or `*`), each optionally with `:` and a title glob (`execute:npm test*`). Allowed calls are answered "allow once", never "always". The first task is optional. `--name` sets the session name (a taken or reserved one is refused); otherwise the usual `<cli>@<repo>-<n>` name is used. `--cwd` defaults to the current folder, which must be inside your home folder; an explicit `--cwd` can be anywhere. It asks first and `--yes` skips the question; without a terminal it exits 2 unless `--yes` is given. At most 8 spawned sessions run at once (`CONVENO_SPAWN_MAX` changes that), and a spawned session cannot spawn more than 3 levels deep. A task is at most 16000 characters. See `packages/protocol/PROTOCOL.md`. |
42
+ | `conveno spawn <cli> [--cwd <dir>] [--name <name>] [--task <text> \| --task-file <path>] [--window] [--access <read\|edit\|full>] [--yes]` | Start a worker session of `claude`, `codex`, `opencode`, `antigravity` or `grok`, and print its name once it registers. The CLI must be installed. By default the worker runs in the background through the CLI's Agent Client Protocol server, with `conveno acp-host` driving it. It keeps running: each message sent to it becomes its next prompt at once when it is idle, or when its current turn ends. `--window` opens the real CLI in a new terminal instead, so you can watch it and take over: Windows Terminal (`wt -w 0 new-tab`, else a new console window) on Windows, Terminal.app (iTerm2 when it is your terminal) on macOS, and on Linux a new tmux window when you are inside tmux, else the first of `x-terminal-emulator`, `gnome-terminal`, `konsole`, `kitty`, `wezterm`, `alacritty` and `xterm`. The ACP commands are `claude-agent-acp` (install `@agentclientprotocol/claude-agent-acp`), `codex-acp` (install `@agentclientprotocol/codex-acp`), `opencode acp`, `agy acp` and `grok agent stdio`; a missing one is an error that says what to install. For Claude Code and Codex, `conveno init` can allow running the adapter with `npx -y <package>@<pinned version>`, and `CONVENO_ACP_CODEX_CMD` / `CONVENO_ACP_CLAUDE_CMD` replace the command. In the background a tool call the `--access` preset (`read`, `edit` or `full`; default `edit`) does not cover is asked of the session that spawned the worker. The first task is optional. `--name` sets the session name (a taken or reserved one is refused); otherwise the usual `<cli>@<repo>-<n>` name is used. `--cwd` defaults to the current folder, which must be inside your home folder; an explicit `--cwd` can be anywhere. It asks first and `--yes` skips the question; without a terminal it exits 2 unless `--yes` is given. At most 8 spawned sessions run at once (`CONVENO_SPAWN_MAX` changes that), and a spawned session cannot spawn more than 3 levels deep. A task is at most 16000 characters. See `packages/protocol/PROTOCOL.md`. |
43
43
  | `conveno stop <worker>` | Stop a background worker. It cancels a running turn, ends its CLI and the processes it started, tells the spawning session why, and goes offline. A worker in a window is yours to close. |
44
44
  | `conveno doctor [--cli <list>]` | Check each CLI and the daemon, and say how to fix what is wrong. `--cli claude,codex` checks only those CLIs, so problems in the others do not count. |
45
45
  | `conveno devices [pair\|join\|revoke\|rename\|accept\|reset]` | Pro. List your devices, or pair a new machine: `pair` on one device and `join` on the new one at the same time, then type the 8-digit code each screen shows. `revoke` removes a device for good. Needs a Pro login on both. |
@@ -1,7 +1,7 @@
1
1
  import { writeFileSync } from "node:fs";
2
- import { n as runAcpHostFromFile, r as stopRequestPath, t as killProcessTree } from "./dist-4iJnF07i.js";
3
- import { Lt as readSpawnRecord, Xt as spawnRecordPath } from "./dist-CRj_cuHc.js";
4
- import { a as parseFlags, n as COMMANDS } from "./args-C1eX8Ixk.js";
2
+ import { n as runAcpHostFromFile, r as stopRequestPath, t as killProcessTree } from "./dist-BiV6HopA.js";
3
+ import { Kt as readSpawnRecord, an as spawnRecordPath } from "./dist-1k5b8UGF.js";
4
+ import { a as parseFlags, n as COMMANDS } from "./args-DmUsbNu9.js";
5
5
  import { a as fail, n as cmd } from "./fmt-C2SsP5Y0.js";
6
6
  // src/acp.ts
7
7
  /** How long `conveno stop` waits for a worker to end by itself before it ends the process tree. */
@@ -1,6 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
- import { t as RELAY_SUBCOMMAND } from "./dist-Du1hwaux.js";
3
- import { qt as runWaker } from "./dist-CRj_cuHc.js";
2
+ import { t as RELAY_SUBCOMMAND } from "./dist-vefQHFb-.js";
3
+ import { nn as runWaker } from "./dist-1k5b8UGF.js";
4
4
  import { n as connectOpts } from "./ctx-tYftvhz_.js";
5
5
  // src/agy-relay.ts
6
6
  /**
@@ -33,7 +33,7 @@ const SETUP_FLAGS = {
33
33
  const COMMANDS = [
34
34
  {
35
35
  name: "setup",
36
- usage: "conveno setup [--yes] [--dry-run] [--cli <list>] [--lead <cli>]",
36
+ usage: "conveno setup [--yes] [--dry-run] [--cli <list>] [--lead <cli>] [--worker-access <level>]",
37
37
  summary: "Connect Conveno to your AI tools",
38
38
  flags: {
39
39
  ...SETUP_FLAGS,
@@ -41,6 +41,11 @@ const COMMANDS = [
41
41
  type: "string",
42
42
  value: "<cli>",
43
43
  help: "The AI tool that should lead when it starts, such as claude"
44
+ },
45
+ "worker-access": {
46
+ type: "string",
47
+ value: "<read|edit|full>",
48
+ help: "What background workers may do: read, edit (the default) or full"
44
49
  }
45
50
  },
46
51
  notes: [
@@ -153,10 +158,10 @@ const COMMANDS = [
153
158
  type: "boolean",
154
159
  help: "Open the CLI in a terminal window you can watch, instead of the background"
155
160
  },
156
- allow: {
161
+ access: {
157
162
  type: "string",
158
- value: "<kinds>",
159
- help: "Background: tool calls to approve, such as read,search or execute:npm test*"
163
+ value: "<read|edit|full>",
164
+ help: "Background: what the worker may do without asking (default: edit)"
160
165
  },
161
166
  yes: {
162
167
  type: "boolean",
@@ -165,10 +170,13 @@ const COMMANDS = [
165
170
  }
166
171
  },
167
172
  notes: [
173
+ "--access sets what a background worker may do without asking: read (look only), edit (also",
174
+ "change files and fetch pages; the default) or full (everything).",
168
175
  "By default the worker runs in the background over ACP and stays alive. Each message sent to",
169
176
  "it becomes its next prompt: right away when it is idle, else when its turn ends.",
170
177
  "--window opens the real CLI in a new terminal instead, so you can watch it and take over.",
171
- "In the background, tool calls that need approval are denied unless --allow covers them.",
178
+ "In the background, tool calls the preset does not cover are denied.",
179
+ "Conveno's own tools, such as send, are always allowed.",
172
180
  "claude and codex need an ACP adapter installed. End a worker with conveno stop.",
173
181
  "Waits until the session registers, then prints its name.",
174
182
  "Without a terminal of your own it needs --yes, and exits 2 without it.",
package/dist/bin.js CHANGED
@@ -2,6 +2,19 @@
2
2
  import { enableCompileCache } from "node:module";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
+ // src/hook-skip.ts
6
+ /**
7
+ * Whether `conveno <argv>` is a hook that must exit 0 at once, with no output:
8
+ * - an ACP worker's agent (`CONVENO_ACP_WORKER`, set by the ACP host): the host drives its turns
9
+ * and delivery itself, and a hook's process walk could reach the lead's session instead;
10
+ * - Claude hooks run by Grok, which imports `~/.claude/settings.json` and sets `GROK_HOOK_EVENT`
11
+ * on every hook process. Claude Code never sets it. Grok's own hooks (`hook grok ...`) still run.
12
+ */
13
+ function hookSkipped(argv, env) {
14
+ if (argv[0] !== "hook") return false;
15
+ if (env.CONVENO_ACP_WORKER) return true;
16
+ return argv[1] === "claude" && Boolean(env.GROK_HOOK_EVENT);
17
+ }
5
18
  // src/bin.ts
6
19
  /**
7
20
  * Cache V8's compiled code for Conveno's files and its dependencies, in the user's own data
@@ -20,15 +33,16 @@ function startCompileCache() {
20
33
  startCompileCache();
21
34
  const argv = process.argv.slice(2);
22
35
  const isHook = argv[0] === "hook";
36
+ if (hookSkipped(argv, process.env)) process.exit(0);
23
37
  for (const stream of [process.stdout, process.stderr]) stream.on("error", (err) => {
24
38
  if (err.code === "EPIPE") process.exit(0);
25
39
  throw err;
26
40
  });
27
41
  try {
28
42
  let code;
29
- if (isHook) code = await (await import("./hook-entry-ajdMBSpY.js")).runHookEntry(argv.slice(1));
43
+ if (isHook) code = await (await import("./hook-entry-De06GWme.js")).runHookEntry(argv.slice(1));
30
44
  else {
31
- const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-WIfawg60.js"), import("./runtime-BKPod_ZQ.js")]);
45
+ const [{ main }, { createRuntimeCtx }] = await Promise.all([import("./main-BY7Kcf9S.js"), import("./runtime-PeEPWwix.js")]);
32
46
  code = await main(argv, createRuntimeCtx());
33
47
  }
34
48
  if (isHook) process.exit(code);
package/dist/daemon.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, userInfo } from "node:os";
3
- import { t as codexAdapter } from "./dist-BjATai4T.js";
4
- import { $ as generateSessionName, $t as statusAfterLiveness, A as clientProof, An as isSocketPathTooLong, At as proofsMatch, B as defaultProcessIo, Bn as sanitizeLine, C as autoCandidates, D as claimOrchestrator, Dn as defaultSocketPath, E as bindAccountDevice, En as createLineDecoder, F as currentAccessToken, Fn as newMessageId, Ft as readInbox, I as daemonProof, In as newSessionId, It as readSettings, K as evaluateLiveness, L as dataDir, Ln as parseIpcRequest, Mn as makeEventNotification, Mt as readAccountTokens, Nn as makeResult, Nt as readAncestry, On as encodeFrame, Ot as planSpawn, P as createWmiWalker, Pn as newDeviceId, R as dataPaths, Rn as parseRelayFrame, Sn as RpcErrorCode, St as pendingForInjection, T as baseName, Tn as SessionId, V as detectRepo, Vn as socketPathTooLongMessage, Vt as requeueEntries, W as effectiveHolder, Wt as resolveRecipient, X as formatContinuation, Z as formatHookContext, _n as Message, bn as PROTOCOL_VERSION, et as holderAfterDeparture, gt as oneWindowPerHost, ht as newAuthNonce, i as ConvenoError, in as turnHops, jn as makeError, k as clearOrchestrator, m as ackEntries, mn as EVENT_NAMES, n as AccountError, nn as takeWithinChars, ot as isOnline, pn as DeviceId, pt as markDelivered, rn as tooManyUnreadMessage, sn as validateRename, st as jwtClaim, tn as takeWithinBytes, u as RESPONSE_BUDGET_BYTES, w as autoLimitsFromEnv, xn as RelayPayload, yn as OWNER_SESSION_ID, z as decideAutoContinue, zn as safeParse } from "./dist-CRj_cuHc.js";
3
+ import { t as codexAdapter } from "./dist-Cv5et1iE.js";
4
+ import { $ as formatContinuation, $n as sanitizeLine, $t as resolveRecipient, A as claimOrchestrator, B as dataDir, Bn as defaultSocketPath, Bt as readAccountTokens, Ct as oneWindowPerHost, D as autoLimitsFromEnv, E as autoCandidates, En as EVENT_NAMES, Gn as makeEventNotification, Gt as readSettings, H as decideAutoContinue, In as SESSION_ENDED_TEXT, It as planSpawn, Jn as newMessageId, Kn as makeResult, L as createWmiWalker, M as clearOrchestrator, Mn as PROTOCOL_VERSION, N as clientProof, Nn as RelayPayload, O as baseName, Pn as RpcErrorCode, Qn as safeParse, R as currentAccessToken, Rn as SessionId, Rt as proofsMatch, S as appendHookLog, St as newAuthNonce, Tn as DeviceId, U as defaultProcessIo, Un as isSocketPathTooLong, Ut as readInbox, V as dataPaths, Vn as encodeFrame, Vt as readAncestry, W as detectRepo, Wn as makeError, Xn as parseIpcRequest, Xt as requeueEntries, Y as evaluateLiveness, Yn as newSessionId, Zn as parseRelayFrame, _ as ackEntries, _t as leadLogPath, bt as markDelivered, cn as statusAfterLiveness, dn as takeWithinChars, dt as isOnline, er as socketPathTooLongMessage, et as formatHookContext, fn as tooManyUnreadMessage, ft as jwtClaim, gn as validateRename, gt as leadLogLine, i as ConvenoError, jn as OWNER_SESSION_ID, k as bindAccountDevice, kn as Message, kt as pendingForInjection, l as RESPONSE_BUDGET_BYTES, n as AccountError, nt as generateSessionName, pn as turnHops, q as effectiveHolder, qn as newDeviceId, rt as holderAfterDeparture, un as takeWithinBytes, z as daemonProof, zn as createLineDecoder } from "./dist-1k5b8UGF.js";
5
5
  import { randomBytes } from "node:crypto";
6
6
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { connect, createServer } from "node:net";
8
8
  import { dirname, join, posix, win32 } from "node:path";
9
- import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-DeN0jR3I.js";
9
+ import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-C4Ey9THP.js";
10
10
  import { execFileSync } from "node:child_process";
11
11
  import { DatabaseSync } from "node:sqlite";
12
12
  // ../daemon/src/lifecycle.ts
@@ -1691,6 +1691,10 @@ const MIGRATIONS = [
1691
1691
  ALTER TABLE sessions ADD COLUMN native_id TEXT;
1692
1692
  CREATE INDEX sessions_native_id ON sessions (native_id);
1693
1693
  `
1694
+ },
1695
+ {
1696
+ name: "008_variant",
1697
+ sql: "ALTER TABLE sessions ADD COLUMN variant TEXT;"
1694
1698
  }
1695
1699
  ];
1696
1700
  const str = (v) => typeof v === "string" ? v : void 0;
@@ -1749,6 +1753,7 @@ function toSessionRow(r) {
1749
1753
  if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
1750
1754
  const nativeId = str(r.native_id);
1751
1755
  if (nativeId !== void 0) row.nativeId = nativeId;
1756
+ if (r.variant === "app") row.variant = "app";
1752
1757
  return row;
1753
1758
  }
1754
1759
  /** Wire-format session for a stored row. */
@@ -1779,6 +1784,7 @@ function toSession(row, isOrchestrator, unreadCount) {
1779
1784
  if (row.statusText !== void 0) s.statusText = row.statusText;
1780
1785
  if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
1781
1786
  if (row.nativeId !== void 0) s.nativeId = row.nativeId;
1787
+ if (row.variant !== void 0) s.variant = row.variant;
1782
1788
  return s;
1783
1789
  }
1784
1790
  function toEntry(r) {
@@ -1852,8 +1858,8 @@ var Store = class {
1852
1858
  insertSession(s) {
1853
1859
  this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
1854
1860
  pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawned, spawn_depth,
1855
- auto_runs, turn_hops, started_at, last_seen_at)
1856
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.id, s.name, s.cli, s.cliVersion ?? null, s.deviceId, s.cwd, s.repoRoot ?? null, s.repoRemoteUrlHash ?? null, s.pid ?? null, s.hostPid ?? null, s.hostPids ? JSON.stringify(s.hostPids) : null, s.status, s.statusText ?? null, s.deliveryTier, s.spawnedBy ?? null, s.spawned ? 1 : 0, s.spawnDepth, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt);
1861
+ auto_runs, turn_hops, started_at, last_seen_at, variant)
1862
+ VALUES (?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.id, s.name, s.cli, s.cliVersion ?? null, s.deviceId, s.cwd, s.repoRoot ?? null, s.repoRemoteUrlHash ?? null, s.pid ?? null, s.hostPid ?? null, s.hostPids ? JSON.stringify(s.hostPids) : null, s.status, s.statusText ?? null, s.deliveryTier, s.spawnedBy ?? null, s.spawned ? 1 : 0, s.spawnDepth, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt, s.variant ?? null);
1857
1863
  }
1858
1864
  getSession(id) {
1859
1865
  const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
@@ -1866,6 +1872,18 @@ var Store = class {
1866
1872
  updateSession(id, fields) {
1867
1873
  const sets = [];
1868
1874
  const vals = [];
1875
+ if (fields.cwd !== void 0) {
1876
+ sets.push("cwd = ?");
1877
+ vals.push(fields.cwd);
1878
+ }
1879
+ if (fields.repoRoot !== void 0) {
1880
+ sets.push("repo_root = ?", "repo_remote_hash = NULL");
1881
+ vals.push(fields.repoRoot);
1882
+ }
1883
+ if (fields.variant !== void 0) {
1884
+ sets.push("variant = ?");
1885
+ vals.push(fields.variant);
1886
+ }
1869
1887
  if (fields.pid !== void 0) {
1870
1888
  sets.push("pid = ?");
1871
1889
  vals.push(fields.pid);
@@ -1952,7 +1970,7 @@ var Store = class {
1952
1970
  }
1953
1971
  };
1954
1972
  // ../daemon/src/server.ts
1955
- const DAEMON_VERSION = "0.2.0-rc.12";
1973
+ const DAEMON_VERSION = "0.2.0-rc.14";
1956
1974
  /** A connection that has not finished the handshake by then is closed. */
1957
1975
  const AUTH_TIMEOUT_MS = 5e3;
1958
1976
  /** Unread messages one session may hold. */
@@ -1973,6 +1991,8 @@ const WAKE_RETRY_MS = 15e3;
1973
1991
  const WOKEN_STALL_MS = 3e4;
1974
1992
  const WAKE_RETRY_MAX_MS = 3e5;
1975
1993
  /** Sender id on `system` messages made by the daemon itself (no session sent them). */
1994
+ /** Permission requests one worker may have waiting at once. */
1995
+ const MAX_ASKS_PER_WORKER = 5;
1976
1996
  const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
1977
1997
  const CLI_TIER = {
1978
1998
  claude: "next_turn",
@@ -1994,6 +2014,7 @@ var Daemon = class {
1994
2014
  platform;
1995
2015
  wakers;
1996
2016
  settingsPath;
2017
+ leadLog;
1997
2018
  conns = /* @__PURE__ */ new Set();
1998
2019
  /** Reaches the owner's other devices; set by startDaemon unless disabled. */
1999
2020
  relay;
@@ -2024,6 +2045,8 @@ var Daemon = class {
2024
2045
  wokenAt = /* @__PURE__ */ new Map();
2025
2046
  idleSince;
2026
2047
  startedMs;
2048
+ /** Permission requests of workers that wait for their spawner, by request id. In memory only. */
2049
+ asks = /* @__PURE__ */ new Map();
2027
2050
  /** When each session went offline, for the removal grace. In memory only. */
2028
2051
  offlineSince = /* @__PURE__ */ new Map();
2029
2052
  /**
@@ -2034,7 +2057,12 @@ var Daemon = class {
2034
2057
  attached = /* @__PURE__ */ new Map();
2035
2058
  /** When a hook last touched each session (a turn start or end, a delivery, a bind). In memory only. */
2036
2059
  hookAt = /* @__PURE__ */ new Map();
2037
- constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath) {
2060
+ /**
2061
+ * Sessions retired by an unregister without a pid (a Codex SessionEnd hook, an ACP host exiting).
2062
+ * Their heartbeats are refused, so a leftover MCP process cannot bring them back online.
2063
+ */
2064
+ retired = /* @__PURE__ */ new Set();
2065
+ constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath, leadLog) {
2038
2066
  this.store = store;
2039
2067
  this.token = token;
2040
2068
  this.now = now;
@@ -2049,6 +2077,7 @@ var Daemon = class {
2049
2077
  this.platform = platform;
2050
2078
  this.wakers = wakers;
2051
2079
  this.settingsPath = settingsPath;
2080
+ this.leadLog = leadLog;
2052
2081
  this.deviceId = store.deviceId();
2053
2082
  this.startedMs = now().getTime();
2054
2083
  this.idleSince = this.startedMs;
@@ -2131,6 +2160,7 @@ var Daemon = class {
2131
2160
  case "session.register": return this.registerAsync(req.params);
2132
2161
  case "session.heartbeat": return this.heartbeat(req.params.sessionId, req.params.pid);
2133
2162
  case "session.unregister": return this.unregister(req.params.sessionId, req.params.pid);
2163
+ case "session.remove": return this.remove(req.params.sessionId);
2134
2164
  case "session.rename": return this.rename(req.params);
2135
2165
  case "session.setStatus": return this.setStatus(req.params);
2136
2166
  case "session.list": return this.list(req.params);
@@ -2138,12 +2168,15 @@ var Daemon = class {
2138
2168
  case "session.hostOf": return this.hostOf(req.params);
2139
2169
  case "session.setNative": return this.setNative(req.params);
2140
2170
  case "session.bind": return this.bind(req.params);
2171
+ case "session.setCwd": return this.setCwd(req.params);
2141
2172
  case "turn.start": return this.turnStart(req.params.sessionId);
2142
2173
  case "turn.end": return this.turnEnd(req.params);
2143
2174
  case "turn.wake": return this.turnWake(conn, req.params);
2144
2175
  case "daemon.shutdown": return { ok: true };
2145
- case "orchestrator.claim": return this.claim(req.params.sessionId);
2176
+ case "orchestrator.claim": return this.claim(req.params.sessionId, req.params.via ?? "unknown");
2146
2177
  case "orchestrator.clear": return this.clearLead(conn);
2178
+ case "permission.ask": return this.permissionAsk(req.params);
2179
+ case "permission.answer": return this.permissionAnswer(req.params);
2147
2180
  case "message.send": return this.sendMessage(req.params);
2148
2181
  case "owner.send": return this.ownerSend(conn, req.params);
2149
2182
  case "message.inbox": return this.inbox(req.params);
@@ -2299,6 +2332,7 @@ var Daemon = class {
2299
2332
  lastSeenAt: at
2300
2333
  };
2301
2334
  if (p.cliVersion !== void 0) r.cliVersion = p.cliVersion;
2335
+ if (p.variant !== void 0) r.variant = p.variant;
2302
2336
  if (repo) {
2303
2337
  r.repoRoot = repo.root;
2304
2338
  if (repo.remoteUrlHash !== void 0) r.repoRemoteUrlHash = repo.remoteUrlHash;
@@ -2325,13 +2359,14 @@ var Daemon = class {
2325
2359
  if (settings.leadCli !== row.cli) return;
2326
2360
  if (settings.tools && !settings.tools.includes(row.cli)) return;
2327
2361
  if (this.orchestratorNow() !== null) return;
2328
- this.claim(row.id);
2362
+ this.claim(row.id, "preferred");
2329
2363
  }
2330
2364
  async registerAsync(p) {
2331
2365
  return this.register(p, await this.detect(p));
2332
2366
  }
2333
2367
  heartbeat(sessionId, pid) {
2334
2368
  const row = this.requireSession(sessionId);
2369
+ if (this.retired.has(sessionId)) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" ${SESSION_ENDED_TEXT}.`);
2335
2370
  const at = this.iso();
2336
2371
  if (row.status !== "offline") {
2337
2372
  if (pid !== void 0) this.attachedOf(row).add(pid);
@@ -2352,14 +2387,17 @@ var Daemon = class {
2352
2387
  depart(sessionId, change) {
2353
2388
  const before = this.store.holder();
2354
2389
  const after = holderAfterDeparture(before, sessionId);
2390
+ const prevName = this.leadName(before);
2355
2391
  this.store.tx(() => {
2356
2392
  this.store.updateSession(sessionId, { status: "offline" });
2357
2393
  if (after !== before) this.store.setHolder(after);
2358
2394
  });
2395
+ this.logLead(prevName, before, after, "departed");
2359
2396
  this.listeners.delete(sessionId);
2360
2397
  this.woken.delete(sessionId);
2361
2398
  this.attached.delete(sessionId);
2362
2399
  this.hookAt.delete(sessionId);
2400
+ this.settleAsksOf(sessionId);
2363
2401
  this.offlineSince.set(sessionId, this.now().getTime());
2364
2402
  this.emitSession(sessionId, change);
2365
2403
  if (after !== before) this.emit({
@@ -2385,9 +2423,53 @@ var Daemon = class {
2385
2423
  return { ok: true };
2386
2424
  }
2387
2425
  }
2426
+ if (pid === void 0) this.retired.add(sessionId);
2388
2427
  this.depart(sessionId, "unregistered");
2389
2428
  return { ok: true };
2390
2429
  }
2430
+ /**
2431
+ * Delete a session and its mail (the app's "Remove this session"). The lead role goes with it.
2432
+ * A window that is still open registers again on its next heartbeat or tool call.
2433
+ */
2434
+ remove(sessionId) {
2435
+ const row = this.requireSession(sessionId);
2436
+ const shown = {
2437
+ ...this.view(row),
2438
+ status: "offline"
2439
+ };
2440
+ const before = this.store.holder();
2441
+ const after = holderAfterDeparture(before, sessionId);
2442
+ const prevName = this.leadName(before);
2443
+ this.store.tx(() => {
2444
+ if (after !== before) this.store.setHolder(after);
2445
+ this.store.deleteSession(sessionId);
2446
+ });
2447
+ this.logLead(prevName, before, after, "removed");
2448
+ this.listeners.delete(sessionId);
2449
+ this.woken.delete(sessionId);
2450
+ this.wokenAt.delete(sessionId);
2451
+ this.wakersOff.delete(sessionId);
2452
+ this.offlineSince.delete(sessionId);
2453
+ this.attached.delete(sessionId);
2454
+ this.hookAt.delete(sessionId);
2455
+ this.settleAsksOf(sessionId);
2456
+ this.emit({
2457
+ event: "session.updated",
2458
+ data: {
2459
+ session: shown,
2460
+ change: "unregistered"
2461
+ }
2462
+ });
2463
+ this.relay?.sessionsChanged();
2464
+ if (after !== before) this.emit({
2465
+ event: "orchestrator.changed",
2466
+ data: {
2467
+ orchestrator: after,
2468
+ previous: before
2469
+ }
2470
+ });
2471
+ return { ok: true };
2472
+ }
2391
2473
  rename(p) {
2392
2474
  const row = this.requireSession(p.sessionId);
2393
2475
  const name = validateRename(p.sessionId, p.name, this.named(this.store.allSessions()));
@@ -2499,6 +2581,36 @@ var Daemon = class {
2499
2581
  return { session: this.view(this.requireSession(row.id)) };
2500
2582
  }
2501
2583
  /**
2584
+ * A desktop app session learns its workspace from a hook: the app starts Conveno in its install
2585
+ * folder, so the row moves to the folder the user has open. A name made from the old folder
2586
+ * follows it; a name the user chose stays. Only an app session moves (`variant` on the call may
2587
+ * mark one); a CLI row keeps the folder it registered with.
2588
+ */
2589
+ async setCwd(p) {
2590
+ const row = this.requireOnline(p.sessionId);
2591
+ if (!(row.variant === "app" || p.variant === "app")) return { session: this.view(row) };
2592
+ const found = samePath(row.cwd, p.cwd, this.platform) ? void 0 : await detectRepo(p.cwd, { exists: (path) => existsSync(path) });
2593
+ const cur = this.requireOnline(p.sessionId);
2594
+ const fields = {};
2595
+ if (cur.variant !== "app") fields.variant = "app";
2596
+ if (found && !samePath(cur.cwd, p.cwd, this.platform)) {
2597
+ const oldBase = baseName(cur.repoRoot ?? cur.cwd);
2598
+ const prefix = generateSessionName(cur.cli, oldBase, []).replace(/1$/, "");
2599
+ const auto = cur.name.startsWith(prefix) && /^\d+$/.test(cur.name.slice(prefix.length));
2600
+ fields.cwd = p.cwd;
2601
+ fields.repoRoot = found.root ?? null;
2602
+ if (auto) {
2603
+ const others = this.named(this.store.allSessions().filter((r) => r.id !== cur.id));
2604
+ fields.name = generateSessionName(cur.cli, baseName(found.root ?? p.cwd), others);
2605
+ }
2606
+ }
2607
+ if (Object.keys(fields).length > 0) {
2608
+ this.store.updateSession(cur.id, fields);
2609
+ this.emitSession(cur.id, "updated");
2610
+ }
2611
+ return { session: this.view(this.requireSession(cur.id)) };
2612
+ }
2613
+ /**
2502
2614
  * The session of the window a hook runs in, among the online sessions of its CLI: the one under
2503
2615
  * its host process (and in its folder, when the hook says which). Codex shares one host process
2504
2616
  * between windows, so there it prefers a session that has no conversation yet, and takes a bound
@@ -2514,6 +2626,31 @@ var Daemon = class {
2514
2626
  return cands.length === 1 ? cands[0] : void 0;
2515
2627
  }
2516
2628
  /**
2629
+ * `session.bind` from a hook that has only its parent pid. Answers without the hook walking the
2630
+ * process tree when the conversation settles it: exactly one online session of the CLI holds the
2631
+ * id, and the hook's parent is that session's host, or the hook starts no turn (a Stop or an
2632
+ * idle never moves a window), or that session is already busy. A conversation no window could
2633
+ * take (no session online, or a hook that is no turn start and every session has a
2634
+ * conversation) answers none. Anything else needs the host pid: `needsHost`. So only the turn
2635
+ * start of an idle conversation walks.
2636
+ */
2637
+ bindWithoutHost(rows, p) {
2638
+ if (rows.length === 0) return { session: null };
2639
+ const holders = rows.filter((r) => r.nativeId === p.nativeId);
2640
+ const [holder] = holders;
2641
+ if (holders.length === 1 && holder) {
2642
+ const pids = [...holder.hostPid === void 0 ? [] : [holder.hostPid], ...holder.hostPids ?? []];
2643
+ if (p.ppid !== void 0 && pids.includes(p.ppid) || !p.turnStart || holder.status === "busy") {
2644
+ this.touchHook(holder.id);
2645
+ return { session: this.view(holder) };
2646
+ }
2647
+ } else if (holders.length === 0 && !p.turnStart && rows.every((r) => r.nativeId !== void 0)) return { session: null };
2648
+ return {
2649
+ session: null,
2650
+ needsHost: true
2651
+ };
2652
+ }
2653
+ /**
2517
2654
  * Bind a conversation to the window's session (see `session.bind` in the protocol). The session
2518
2655
  * that holds the id wins; a caller with a session of its own is merged into it. Otherwise only a
2519
2656
  * turn start moves the window to the conversation, and a conversation that is not the window's
@@ -2523,6 +2660,7 @@ var Daemon = class {
2523
2660
  const caller = p.sessionId === void 0 ? void 0 : this.requireOnline(p.sessionId);
2524
2661
  if (caller && caller.cli !== p.cli) return { session: null };
2525
2662
  const rows = this.store.allSessions().filter((r) => r.status !== "offline" && r.cli === p.cli);
2663
+ if (!caller && p.hostPid === void 0) return this.bindWithoutHost(rows, p);
2526
2664
  let holder = rows.find((r) => r.nativeId === p.nativeId);
2527
2665
  if (holder && !caller && p.hostPid !== void 0) {
2528
2666
  const pids = [...holder.hostPid === void 0 ? [] : [holder.hostPid], ...holder.hostPids ?? []];
@@ -2570,13 +2708,16 @@ var Daemon = class {
2570
2708
  const pids = this.attachedOf(into);
2571
2709
  for (const q of this.attachedOf(from)) pids.add(q);
2572
2710
  if (pid !== void 0) pids.add(pid);
2573
- const lead = this.store.holder() === from.id;
2711
+ const before = this.store.holder();
2712
+ const lead = before === from.id;
2713
+ const prevName = this.leadName(before);
2574
2714
  this.store.tx(() => {
2575
2715
  this.store.moveMailbox(from.id, into.id);
2576
2716
  if (lead) this.store.setHolder(into.id);
2577
2717
  this.store.updateSession(into.id, { lastSeenAt: this.iso() });
2578
2718
  this.store.deleteSession(from.id);
2579
2719
  });
2720
+ if (lead) this.logLead(prevName, before, into.id, "merged");
2580
2721
  this.listeners.delete(from.id);
2581
2722
  this.woken.delete(from.id);
2582
2723
  this.attached.delete(from.id);
@@ -2616,11 +2757,27 @@ var Daemon = class {
2616
2757
  this.hookAt.delete(r.id);
2617
2758
  }
2618
2759
  }
2619
- claim(sessionId) {
2760
+ leadName(id) {
2761
+ return id ? this.store.getSession(id)?.name ?? null : null;
2762
+ }
2763
+ /** One line in `<dataDir>/logs/lead.log` when the holder changed. Never throws. */
2764
+ logLead(previous, before, after, via) {
2765
+ if (before === after || !this.leadLog) return;
2766
+ try {
2767
+ appendHookLog(this.leadLog, leadLogLine({
2768
+ at: this.now(),
2769
+ lead: this.leadName(after),
2770
+ previous,
2771
+ via
2772
+ }));
2773
+ } catch {}
2774
+ }
2775
+ claim(sessionId, via) {
2620
2776
  this.requireSession(sessionId);
2621
2777
  const rows = this.store.allSessions();
2622
2778
  const holder = this.store.holder();
2623
2779
  const res = claimOrchestrator(holder, sessionId, this.named(rows));
2780
+ const prevName = this.leadName(holder);
2624
2781
  const at = this.iso();
2625
2782
  const sent = [];
2626
2783
  this.store.tx(() => {
@@ -2642,6 +2799,7 @@ var Daemon = class {
2642
2799
  sent.push(m);
2643
2800
  }
2644
2801
  });
2802
+ this.logLead(prevName, holder, res.orchestrator, via);
2645
2803
  if (res.notices.length > 0) {
2646
2804
  this.emit({
2647
2805
  event: "orchestrator.changed",
@@ -2659,10 +2817,74 @@ var Daemon = class {
2659
2817
  previous: res.previous
2660
2818
  };
2661
2819
  }
2820
+ /**
2821
+ * A worker asks its spawner to allow a tool call. Resolves when the spawner answers, when
2822
+ * `timeoutMs` passes, or when the worker goes away. The request lives in memory only.
2823
+ */
2824
+ permissionAsk(p) {
2825
+ const worker = this.requireOnline(p.sessionId);
2826
+ const spawner = worker.spawnedBy ? this.store.getSession(worker.spawnedBy) : void 0;
2827
+ if (!spawner || spawner.status === "offline") return Promise.resolve({ answer: "no_spawner" });
2828
+ let mine = 0;
2829
+ for (const a of this.asks.values()) if (a.worker === worker.id) mine++;
2830
+ if (mine >= MAX_ASKS_PER_WORKER) throw new ConvenoError(RpcErrorCode.LimitExceeded, `Session "${worker.name}" already has ${mine} permission requests waiting. Wait for an answer.`);
2831
+ let id = randomBytes(4).toString("base64url").slice(0, 6);
2832
+ while (this.asks.has(id)) id = randomBytes(4).toString("base64url").slice(0, 6);
2833
+ const what = `${p.title ?? "a tool call"} (${p.kind ?? "other"})`;
2834
+ const fallback = p.unanswered === "allow" ? "allow" : "deny";
2835
+ const at = this.iso();
2836
+ const m = {
2837
+ id: newMessageId(),
2838
+ from: DAEMON_SENDER_ID,
2839
+ to: spawner.id,
2840
+ kind: "system",
2841
+ body: {
2842
+ event: "permission.asked",
2843
+ detail: `${worker.name} wants to run: ${what}. Answer with the answer_permission tool: request ${id}, answer allow, always or deny. No answer in ${p.timeoutMs >= 6e4 && p.timeoutMs % 6e4 === 0 ? `${p.timeoutMs / 6e4} min` : `${Math.round(p.timeoutMs / 1e3)} s`}: ${fallback}.`
2844
+ },
2845
+ urgent: false,
2846
+ createdAt: at
2847
+ };
2848
+ this.store.insertMessage(m, spawner.id, at);
2849
+ this.emitMessage(m, spawner.id);
2850
+ return new Promise((resolve) => {
2851
+ const timer = setTimeout(() => this.settleAsk(id, { answer: "unanswered" }), p.timeoutMs);
2852
+ timer.unref();
2853
+ this.asks.set(id, {
2854
+ worker: worker.id,
2855
+ spawner: spawner.id,
2856
+ resolve,
2857
+ timer
2858
+ });
2859
+ });
2860
+ }
2861
+ permissionAnswer(p) {
2862
+ this.requireOnline(p.sessionId);
2863
+ const ask = this.asks.get(p.requestId);
2864
+ if (!ask) throw new ConvenoError(RpcErrorCode.NotFound, `No permission request "${p.requestId}". It was already answered, or it expired.`);
2865
+ if (ask.spawner !== p.sessionId) throw new ConvenoError(RpcErrorCode.PermissionRequired, `Only the session that spawned the worker can answer request "${p.requestId}".`);
2866
+ this.settleAsk(p.requestId, {
2867
+ answer: p.answer,
2868
+ by: p.sessionId
2869
+ });
2870
+ return { ok: true };
2871
+ }
2872
+ settleAsk(id, result) {
2873
+ const ask = this.asks.get(id);
2874
+ if (!ask) return;
2875
+ this.asks.delete(id);
2876
+ clearTimeout(ask.timer);
2877
+ ask.resolve(result);
2878
+ }
2879
+ /** The worker left: its waiting requests end as unanswered. */
2880
+ settleAsksOf(worker) {
2881
+ for (const [id, a] of this.asks) if (a.worker === worker) this.settleAsk(id, { answer: "unanswered" });
2882
+ }
2662
2883
  clearLead(conn) {
2663
2884
  this.requireCli(conn, "clear the lead");
2664
2885
  const holder = this.store.holder();
2665
2886
  const res = clearOrchestrator(holder, this.named(this.store.allSessions()));
2887
+ const prevName = this.leadName(holder);
2666
2888
  const at = this.iso();
2667
2889
  const sent = [];
2668
2890
  this.store.tx(() => {
@@ -2684,6 +2906,7 @@ var Daemon = class {
2684
2906
  sent.push(m);
2685
2907
  }
2686
2908
  });
2909
+ this.logLead(prevName, holder, null, "clear");
2687
2910
  if (holder !== null) {
2688
2911
  this.emit({
2689
2912
  event: "orchestrator.changed",
@@ -3255,7 +3478,7 @@ async function startDaemon(opts) {
3255
3478
  close().then(() => opts.onIdleExit?.());
3256
3479
  }, () => {
3257
3480
  close().then(() => opts.onShutdown?.());
3258
- }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings);
3481
+ }, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings, leadLogPath(opts.dataDir));
3259
3482
  daemon.removeAllOffline();
3260
3483
  const srv = createServer((socket) => daemon.attach(socket));
3261
3484
  server = srv;
@@ -1,4 +1,4 @@
1
- import { t as ClientError } from "./dist-B3YYLzKS.js";
1
+ import { t as ClientError } from "./dist-BYkDv29h.js";
2
2
  import { n as cmd, s as plainError } from "./fmt-C2SsP5Y0.js";
3
3
  // src/daemonError.ts
4
4
  /**