@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.
@@ -6158,12 +6158,19 @@ const RepoInfo = object({
6158
6158
  /** SHA-256 of the normalised `origin` URL; lets sessions on different machines match repos without exposing the URL. */
6159
6159
  remoteUrlHash: Sha256Hex.optional()
6160
6160
  });
6161
+ /**
6162
+ * A client of a CLI that is not the CLI itself: `app` is the Antigravity desktop app, which shares
6163
+ * agy's settings and so loads Conveno the same way.
6164
+ */
6165
+ const SessionVariant = literal("app");
6161
6166
  const Session = object({
6162
6167
  id: SessionId,
6163
6168
  /** `<device>:<name>` for a session on another device (`remote`). */
6164
6169
  name: union([SessionName, RemoteSessionName]),
6165
6170
  cli: CliKind,
6166
6171
  cliVersion: string().min(1).max(64).optional(),
6172
+ /** Set when the session is a desktop app of `cli` rather than the CLI. Screens say "Antigravity app". */
6173
+ variant: SessionVariant.optional(),
6167
6174
  deviceId: DeviceId,
6168
6175
  cwd: string().min(1),
6169
6176
  repo: RepoInfo.optional(),
@@ -6232,11 +6239,15 @@ const AuthParams = object({
6232
6239
  proof: Sha256Hex });
6233
6240
  const sid = { sessionId: SessionId };
6234
6241
  const SessionResult = object({ session: Session });
6242
+ /** An absolute path (POSIX, drive or UNC) without control characters. */
6243
+ const AbsolutePath = string().min(1).max(1024).regex(/^(?:[A-Za-z]:[\\/]|\\\\|\/)/, "must be an absolute path").regex(/^[^\u0000-\u001f\u007f]*$/, "must not contain control characters");
6235
6244
  const RegisterParams = object({
6236
6245
  /** Requested name. If omitted the daemon assigns one such as `claude@repo-1`. */
6237
6246
  name: SessionNameInput.optional(),
6238
6247
  cli: CliKind,
6239
6248
  cliVersion: string().min(1).max(64).optional(),
6249
+ /** The session runs in a desktop app of `cli`. See `Session.variant`. */
6250
+ variant: SessionVariant.optional(),
6240
6251
  cwd: string().min(1),
6241
6252
  repo: RepoInfo.optional(),
6242
6253
  pid: number().int().positive().optional(),
@@ -6348,6 +6359,8 @@ function makeEventNotification(payload) {
6348
6359
  params: payload
6349
6360
  };
6350
6361
  }
6362
+ /** In the NotFound message for a heartbeat of a retired session. The MCP server exits on it. */
6363
+ const SESSION_ENDED_TEXT = "has ended and will not come back";
6351
6364
  const ipcMethods = {
6352
6365
  hello: {
6353
6366
  params: HelloParams,
@@ -6375,6 +6388,10 @@ const ipcMethods = {
6375
6388
  }),
6376
6389
  result: object({ ok: literal(true) })
6377
6390
  },
6391
+ "session.remove": {
6392
+ params: object({ ...sid }),
6393
+ result: object({ ok: literal(true) })
6394
+ },
6378
6395
  "session.rename": {
6379
6396
  params: object({
6380
6397
  ...sid,
@@ -6414,10 +6431,27 @@ const ipcMethods = {
6414
6431
  /** The calling MCP process, attached to the surviving session on a merge. */
6415
6432
  pid: number().int().positive().optional(),
6416
6433
  hostPid: number().int().positive().optional(),
6434
+ /**
6435
+ * A hook's direct parent pid, in place of `hostPid`, so the hook skips the process walk
6436
+ * when the daemon can tell without it. The answer is a session, none, or `needsHost`: the
6437
+ * hook then walks and asks again with `hostPid`.
6438
+ */
6439
+ ppid: number().int().positive().optional(),
6417
6440
  cwd: string().min(1).optional(),
6418
6441
  turnStart: boolean().default(false)
6419
- }).refine((p) => p.sessionId !== void 0 || p.hostPid !== void 0, { message: "provide sessionId or hostPid" }),
6420
- result: object({ session: Session.nullable() })
6442
+ }).refine((p) => p.sessionId !== void 0 || p.hostPid !== void 0 || p.ppid !== void 0, { message: "provide sessionId, hostPid or ppid" }),
6443
+ result: object({
6444
+ session: Session.nullable(),
6445
+ needsHost: boolean().optional()
6446
+ })
6447
+ },
6448
+ "session.setCwd": {
6449
+ params: object({
6450
+ ...sid,
6451
+ cwd: AbsolutePath,
6452
+ variant: SessionVariant.optional()
6453
+ }),
6454
+ result: SessionResult
6421
6455
  },
6422
6456
  "session.hostOf": {
6423
6457
  params: object({
@@ -6467,12 +6501,51 @@ const ipcMethods = {
6467
6501
  result: object({ sessions: array(Session) })
6468
6502
  },
6469
6503
  "orchestrator.claim": {
6470
- params: object(sid),
6504
+ params: object({
6505
+ ...sid,
6506
+ via: _enum([
6507
+ "tool",
6508
+ "cli",
6509
+ "home"
6510
+ ]).optional()
6511
+ }),
6471
6512
  result: object({
6472
6513
  orchestrator: SessionId,
6473
6514
  previous: SessionId.nullable()
6474
6515
  })
6475
6516
  },
6517
+ "permission.ask": {
6518
+ params: object({
6519
+ ...sid,
6520
+ title: string().max(500).optional(),
6521
+ kind: string().max(100).optional(),
6522
+ timeoutMs: number().int().min(1).max(3e5),
6523
+ /** What happens when nobody answers, for the notice to the spawner. Default deny. */
6524
+ unanswered: _enum(["deny", "allow"]).optional()
6525
+ }),
6526
+ result: object({
6527
+ answer: _enum([
6528
+ "allow_once",
6529
+ "allow_always",
6530
+ "deny",
6531
+ "unanswered",
6532
+ "no_spawner"
6533
+ ]),
6534
+ by: SessionId.optional()
6535
+ })
6536
+ },
6537
+ "permission.answer": {
6538
+ params: object({
6539
+ ...sid,
6540
+ requestId: string().min(1).max(64),
6541
+ answer: _enum([
6542
+ "allow_once",
6543
+ "allow_always",
6544
+ "deny"
6545
+ ])
6546
+ }),
6547
+ result: object({ ok: literal(true) })
6548
+ },
6476
6549
  "orchestrator.clear": {
6477
6550
  params: object({}),
6478
6551
  result: object({ previous: SessionId.nullable() })
@@ -7744,25 +7817,63 @@ async function runWaker(o) {
7744
7817
  /** Longest wait between two tries to reach the daemon again (`reconnectMs`). */
7745
7818
  const MAX_RECONNECT_MS = 6e4;
7746
7819
  /**
7820
+ * The pid of the CLI above the hook: the one the context already knows, else the walk up the
7821
+ * process tree (`resolveHostPid`, which runs once). Undefined when no session of the CLI is online.
7822
+ */
7823
+ async function hostPidOf(ctx) {
7824
+ if (ctx.hostPid !== void 0) return ctx.hostPid;
7825
+ return ctx.resolveHostPid ? await ctx.resolveHostPid() : void 0;
7826
+ }
7827
+ /** Is the host CLI still running. True when there is no check or the host is not known. */
7828
+ async function hostAlive(ctx) {
7829
+ if (!ctx.isAlive) return true;
7830
+ const pid = await hostPidOf(ctx);
7831
+ return pid === void 0 || ctx.isAlive(pid);
7832
+ }
7833
+ /** The daemon cannot take `ppid` (an older one): fall back to the walk. */
7834
+ const noPpidSupport = (e) => {
7835
+ const code = e?.code;
7836
+ return code === RpcErrorCode.MethodNotFound || code === RpcErrorCode.InvalidParams;
7837
+ };
7838
+ /**
7747
7839
  * The session that owns the hook's host process, when it is a session of the hook's own CLI. Every
7748
7840
  * helper below goes through here before taking messages, so a hook running inside another CLI
7749
7841
  * (which would print a format that CLI discards) never marks anything delivered.
7750
7842
  */
7751
7843
  async function ownSession(ctx) {
7752
7844
  if (ctx.nativeId !== void 0 && ctx.cli !== void 0) try {
7753
- const { session } = await ctx.client["session.bind"]({
7845
+ const base = {
7754
7846
  cli: ctx.cli,
7755
7847
  nativeId: ctx.nativeId,
7756
- hostPid: ctx.hostPid,
7757
7848
  ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7758
7849
  turnStart: ctx.turnStart === true
7759
- });
7760
- return session && ctx.cli !== void 0 && session.cli !== ctx.cli ? null : session;
7850
+ };
7851
+ let r;
7852
+ if (ctx.hostPid === void 0 && ctx.ppid !== void 0) try {
7853
+ r = await ctx.client["session.bind"]({
7854
+ ...base,
7855
+ ppid: ctx.ppid
7856
+ });
7857
+ } catch (e) {
7858
+ if (!noPpidSupport(e)) throw e;
7859
+ }
7860
+ if (!r || r.needsHost) {
7861
+ const hostPid = await hostPidOf(ctx);
7862
+ if (hostPid === void 0) return null;
7863
+ r = await ctx.client["session.bind"]({
7864
+ ...base,
7865
+ hostPid
7866
+ });
7867
+ }
7868
+ const { session } = r;
7869
+ return session && session.cli !== ctx.cli ? null : session;
7761
7870
  } catch (e) {
7762
7871
  if (e?.code !== RpcErrorCode.MethodNotFound) throw e;
7763
7872
  }
7873
+ const pid = await hostPidOf(ctx);
7874
+ if (pid === void 0) return null;
7764
7875
  const { session } = await ctx.client["session.byHost"]({
7765
- pid: ctx.hostPid,
7876
+ pid,
7766
7877
  ...ctx.cwd === void 0 ? {} : { cwd: ctx.cwd },
7767
7878
  ...ctx.nativeId === void 0 ? {} : { nativeId: ctx.nativeId }
7768
7879
  });
@@ -7881,7 +7992,7 @@ async function awaitOwnSession(ctx, waitMs, pollMs, signal) {
7881
7992
  return "disconnected";
7882
7993
  }
7883
7994
  if (Date.now() + pollMs > until || signal?.aborted) return null;
7884
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return null;
7995
+ if (!await hostAlive(ctx)) return null;
7885
7996
  if (own.turnStart) own = {
7886
7997
  ...own,
7887
7998
  turnStart: false
@@ -7897,7 +8008,7 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7897
8008
  const until = Math.min(Date.now() + ms, deadline);
7898
8009
  for (;;) {
7899
8010
  if (signal?.aborted || Date.now() >= deadline) return false;
7900
- if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return false;
8011
+ if (!await hostAlive(ctx)) return false;
7901
8012
  const left = until - Date.now();
7902
8013
  if (left <= 0) return true;
7903
8014
  await new Promise((r) => setTimeout(r, Math.min(left, stepMs)));
@@ -7906,7 +8017,8 @@ async function pauseWhileAlive(ctx, ms, stepMs, deadline, signal) {
7906
8017
  /** `waitForWork`, returning the whole batch and its session (for a requeue). */
7907
8018
  async function waitForWorkBatch(ctx, opts = {}) {
7908
8019
  const deadline = opts.maxMs === void 0 ? 1e400 : Date.now() + opts.maxMs;
7909
- const { isAlive, hostPid } = ctx;
8020
+ const { isAlive } = ctx;
8021
+ const hostPid = isAlive ? await hostPidOf(ctx) : void 0;
7910
8022
  const listenerId = opts.listenerId ?? randomBytes(12).toString("base64url");
7911
8023
  let delay = opts.reconnectMs;
7912
8024
  /** After a lost connection: wait, then go round again. False when the listener must stop. */
@@ -7939,7 +8051,7 @@ async function waitForWorkBatch(ctx, opts = {}) {
7939
8051
  ...deadline !== 1e400 ? { maxMs: Math.max(0, deadline - Date.now()) } : {},
7940
8052
  ...opts.signal !== void 0 ? { signal: opts.signal } : {},
7941
8053
  ...opts.maxChars !== void 0 ? { maxChars: opts.maxChars } : {},
7942
- ...isAlive ? { isHostAlive: () => isAlive(hostPid) } : {}
8054
+ ...isAlive && hostPid !== void 0 ? { isHostAlive: () => isAlive(hostPid) } : {}
7943
8055
  });
7944
8056
  if (r.ok) return {
7945
8057
  sessionId: session.id,
@@ -7953,16 +8065,25 @@ async function waitForWorkBatch(ctx, opts = {}) {
7953
8065
  const HOOK_LOG_MAX_BYTES = 1e6;
7954
8066
  /** `<data dir>/logs/hooks.log`. */
7955
8067
  const hookLogPath = (dataDir) => join(dataDir, "logs", "hooks.log");
8068
+ /** `<data dir>/logs/lead.log`: one line per change of the lead (see `leadLogLine`). */
8069
+ const leadLogPath = (dataDir) => join(dataDir, "logs", "lead.log");
7956
8070
  /** Keep a logged word to plain characters, so one entry is one line and nothing is injected. */
7957
8071
  const plain = (v, max, extra = "") => v.replace(new RegExp(`[^A-Za-z0-9_.@:${extra}-]`, "g"), "_").slice(0, max);
8072
+ /** A duration in whole ms, or `-` when there is none. */
8073
+ const num = (v) => v === void 0 || !Number.isFinite(v) ? "-" : String(Math.max(0, Math.round(v)));
7958
8074
  /**
7959
- * One line: `<iso time> cli=<cli> event=<event> conv=<first 8 of the conversation id> session=<name
7960
- * or none> result=<result>`. No message text and no tokens: only ids the CLI hands to hooks and the
8075
+ * One line: `<iso time> cli=<cli> event=<event> conv=<the conversation id> session=<name
8076
+ * or none> result=<result> host_ms=<n or -> ms=<n or ->`. No message text and no tokens: only ids the CLI hands to hooks and the
7961
8077
  * session's name.
7962
8078
  */
7963
8079
  function hookLogLine(e) {
7964
- const conv = e.conversationId ? plain(e.conversationId, 8) : "-";
7965
- return `${(e.at ?? /* @__PURE__ */ new Date()).toISOString()} cli=${plain(e.cli, 16)} event=${plain(e.event, 32)} conv=${conv} session=${e.session ? plain(e.session, 64) : "none"} result=${plain(e.result, 40, " ")}\n`;
8080
+ const conv = e.conversationId ? plain(e.conversationId, 64) : "-";
8081
+ return `${(e.at ?? /* @__PURE__ */ new Date()).toISOString()} cli=${plain(e.cli, 16)} event=${plain(e.event, 32)} conv=${conv} session=${e.session ? plain(e.session, 64) : "none"} result=${plain(e.result, 40, " ")} host_ms=${num(e.hostMs)} ms=${num(e.ms)}\n`;
8082
+ }
8083
+ /** One line: `<iso time> lead=<name or none> previous=<name or none> via=<how>`. */
8084
+ function leadLogLine(e) {
8085
+ const name = (v) => v ? plain(v, 64) : "none";
8086
+ return `${(e.at ?? /* @__PURE__ */ new Date()).toISOString()} lead=${name(e.lead)} previous=${name(e.previous)} via=${plain(e.via, 16)}\n`;
7966
8087
  }
7967
8088
  /**
7968
8089
  * Append one line to the hook log, rotating at `HOOK_LOG_MAX_BYTES`. Synchronous and tiny so a hook
@@ -8657,6 +8778,12 @@ function parseProcStat(stat) {
8657
8778
  const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
8658
8779
  return Number.isInteger(ppid) && ppid >= 0 ? ppid : void 0;
8659
8780
  }
8781
+ const ANTIGRAVITY_APP_EXE = /(?:^|[\\/"])antigravity(?:\.exe)?"?(?:\s|$)/i;
8782
+ const ANTIGRAVITY_APP_HUB = /--subclient_type[=\s]+hub\b/;
8783
+ /** Does the process chain run through the Antigravity desktop app? Needs command lines; false without them. */
8784
+ function isAntigravityApp(entries) {
8785
+ return entries.some((e) => e.command !== void 0 && (ANTIGRAVITY_APP_HUB.test(e.command) || ANTIGRAVITY_APP_EXE.test(e.command)));
8786
+ }
8660
8787
  const norm = (text) => text.replaceAll("\\", "/").toLowerCase();
8661
8788
  /** Split a command line into tokens, keeping quoted parts together and dropping the quotes. */
8662
8789
  function tokens(command) {
@@ -8809,6 +8936,22 @@ async function readTable(io, timeoutMs) {
8809
8936
  return out === null ? null : parseProcessTable(out);
8810
8937
  }
8811
8938
  /**
8939
+ * Every process with its command line, from the same one query the ancestry walk uses (the
8940
+ * Windows Script Host or CIM on Windows, `ps` elsewhere). Null when the table cannot be read.
8941
+ */
8942
+ async function readProcessList(io = defaultProcessIo, timeoutMs = 5e3) {
8943
+ try {
8944
+ const table = await readTable(io, timeoutMs);
8945
+ if (!table || table.size === 0) return null;
8946
+ return [...table].map(([pid, row]) => row.command === void 0 ? { pid } : {
8947
+ pid,
8948
+ command: row.command
8949
+ });
8950
+ } catch {
8951
+ return null;
8952
+ }
8953
+ }
8954
+ /**
8812
8955
  * The command line of a process as one string, or null when the OS does not say (the process is
8813
8956
  * gone, or the query was denied). A null answer means "unknown", never "not the daemon".
8814
8957
  */
@@ -8998,6 +9141,103 @@ async function detectRepo(cwd, fs) {
8998
9141
  basename: baseName(cwd)
8999
9142
  };
9000
9143
  }
9144
+ function globMatch(glob, text) {
9145
+ return new RegExp(`^${glob.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "s").test(text);
9146
+ }
9147
+ /** Does any rule allow a tool call of this kind and title? A call with no kind is `other`. */
9148
+ function isAllowed(rules, call) {
9149
+ const kind = call.kind ?? "other";
9150
+ const title = call.title ?? "";
9151
+ return rules.some((r) => (r.kind === "*" || r.kind === kind) && (r.title === void 0 || globMatch(r.title, title)));
9152
+ }
9153
+ const WORKER_ACCESS = [
9154
+ "read",
9155
+ "edit",
9156
+ "full"
9157
+ ];
9158
+ function parseWorkerAccess(s) {
9159
+ const v = s.trim().toLowerCase();
9160
+ return WORKER_ACCESS.includes(v) ? v : void 0;
9161
+ }
9162
+ const READ_KINDS = [
9163
+ "read",
9164
+ "search",
9165
+ "think"
9166
+ ];
9167
+ const EDIT_KINDS = [
9168
+ ...READ_KINDS,
9169
+ "edit",
9170
+ "move",
9171
+ "fetch"
9172
+ ];
9173
+ /** The allow rules a preset stands for. */
9174
+ function accessRules(access) {
9175
+ if (access === "full") return [{ kind: "*" }];
9176
+ return (access === "read" ? READ_KINDS : EDIT_KINDS).map((kind) => ({ kind }));
9177
+ }
9178
+ const SAFE_READ_COMMANDS = new Set([
9179
+ "ls",
9180
+ "dir",
9181
+ "pwd",
9182
+ "cat",
9183
+ "type",
9184
+ "head",
9185
+ "tail",
9186
+ "wc",
9187
+ "tree",
9188
+ "stat",
9189
+ "Get-ChildItem",
9190
+ "gci",
9191
+ "Get-Content",
9192
+ "Get-Item",
9193
+ "Get-Location",
9194
+ "Test-Path",
9195
+ "Resolve-Path"
9196
+ ].map((c) => c.toLowerCase()));
9197
+ const MAX_COMMAND_CHARS = 500;
9198
+ const TITLE_VERB = /^(?:execute|executing|run|running|command|shell)\b:?\s+/i;
9199
+ const SHELL_WRAPPER = /^(?:cmd\s+\/c|powershell\s+-command|pwsh\s+-c|bash\s+-lc|sh\s+-c)\s+/i;
9200
+ /**
9201
+ * Is the whole title one simple read-only command, such as `ls -la` or `bash -lc "cat a.txt"`?
9202
+ * Anything that chains, redirects, pipes or substitutes is not.
9203
+ */
9204
+ function isSafeReadCommand(title) {
9205
+ if (title.length > MAX_COMMAND_CHARS) return false;
9206
+ let inner = title.trim();
9207
+ inner = inner.replace(TITLE_VERB, "");
9208
+ if (/^`[^`]+`$/.test(inner)) inner = inner.slice(1, -1).trim();
9209
+ if (/[;&|><`()\n\r]/.test(inner) || inner.includes("${")) return false;
9210
+ if (/-exec/i.test(inner)) return false;
9211
+ const wrapper = SHELL_WRAPPER.exec(inner);
9212
+ if (wrapper) {
9213
+ inner = inner.slice(wrapper[0].length).trim();
9214
+ const q = inner[0];
9215
+ if ((q === "\"" || q === "'") && inner.length >= 2 && inner.endsWith(q)) inner = inner.slice(1, -1).trim();
9216
+ }
9217
+ const first = inner.split(/\s+/)[0] ?? "";
9218
+ return SAFE_READ_COMMANDS.has(first.toLowerCase());
9219
+ }
9220
+ /** May a worker with this access, make this tool call without asking? */
9221
+ function accessAllows(access, call) {
9222
+ if (access === "full") return true;
9223
+ return isAllowed(accessRules(access), call) || call.kind === "execute" && isSafeReadCommand(call.title ?? "");
9224
+ }
9225
+ const WORKER_UNANSWERED = ["deny", "allow"];
9226
+ /** What workers may do, with the default when it was never chosen. */
9227
+ function workerAccessOf(s) {
9228
+ return s.workerAccess ?? "edit";
9229
+ }
9230
+ /** What happens to an unanswered request, with the default when it was never chosen. */
9231
+ function workerUnansweredOf(s) {
9232
+ return s.workerUnanswered ?? "deny";
9233
+ }
9234
+ const WORKER_ASK_TIMEOUT_CHOICES = [
9235
+ 60,
9236
+ 120,
9237
+ 300
9238
+ ];
9239
+ /** Seconds a worker waits for its spawner's answer. */
9240
+ const workerAskTimeoutOf = (s) => s.workerAskTimeoutSec ?? 120;
9001
9241
  /** Read the settings. A missing, unreadable or malformed file gives no settings. */
9002
9242
  function readSettings(path) {
9003
9243
  try {
@@ -9008,7 +9248,10 @@ function readSettings(path) {
9008
9248
  ...typeof o.acpAdapterNpx === "boolean" ? { acpAdapterNpx: o.acpAdapterNpx } : {},
9009
9249
  ...typeof o.leadCli === "string" && CLI_KINDS.includes(o.leadCli) ? { leadCli: o.leadCli } : {},
9010
9250
  ...Array.isArray(o.tools) ? { tools: [...new Set(o.tools.filter((t) => typeof t === "string" && CLI_KINDS.includes(t)))] } : {},
9011
- ...typeof o.wakeBeforeFirstPrompt === "boolean" ? { wakeBeforeFirstPrompt: o.wakeBeforeFirstPrompt } : {}
9251
+ ...typeof o.wakeBeforeFirstPrompt === "boolean" ? { wakeBeforeFirstPrompt: o.wakeBeforeFirstPrompt } : {},
9252
+ ...typeof o.workerAccess === "string" && parseWorkerAccess(o.workerAccess) ? { workerAccess: parseWorkerAccess(o.workerAccess) } : {},
9253
+ ...WORKER_ASK_TIMEOUT_CHOICES.includes(o.workerAskTimeoutSec) ? { workerAskTimeoutSec: o.workerAskTimeoutSec } : {},
9254
+ ...WORKER_UNANSWERED.includes(o.workerUnanswered) ? { workerUnanswered: o.workerUnanswered } : {}
9012
9255
  };
9013
9256
  } catch {
9014
9257
  return {};
@@ -9224,7 +9467,6 @@ function decodeAcpLaunchSpec(text) {
9224
9467
  return x;
9225
9468
  };
9226
9469
  if (!strings(o.args)) throw new Error("The ACP launch file has no \"args\".");
9227
- if (!strings(o.allow)) throw new Error("The ACP launch file has no \"allow\".");
9228
9470
  const mcp = o.mcp;
9229
9471
  return {
9230
9472
  file: str("file"),
@@ -9237,12 +9479,14 @@ function decodeAcpLaunchSpec(text) {
9237
9479
  ...typeof o.task === "string" && o.task !== "" ? { task: o.task } : {},
9238
9480
  ...typeof o.spawnedBy === "string" ? { spawnedBy: o.spawnedBy } : {},
9239
9481
  from: str("from"),
9240
- allow: o.allow,
9241
- ...typeof o.fullAccessMode === "string" && o.fullAccessMode !== "" ? { fullAccessMode: o.fullAccessMode } : {},
9482
+ access: (typeof o.access === "string" ? parseWorkerAccess(o.access) : void 0) ?? "edit",
9483
+ ...typeof o.mode === "string" && o.mode !== "" ? { mode: o.mode } : {},
9242
9484
  ...mcp && typeof mcp.command === "string" && strings(mcp.args) ? { mcp: {
9243
9485
  command: mcp.command,
9244
9486
  args: mcp.args
9245
9487
  } } : {},
9488
+ askTimeoutMs: typeof o.askTimeoutMs === "number" && o.askTimeoutMs > 0 ? o.askTimeoutMs : 12e4,
9489
+ ...o.unanswered === "allow" || o.unanswered === "deny" ? { unanswered: o.unanswered } : {},
9246
9490
  ...typeof o.setupTimeoutMs === "number" && o.setupTimeoutMs > 0 ? { setupTimeoutMs: o.setupTimeoutMs } : {}
9247
9491
  };
9248
9492
  }
@@ -9256,65 +9500,6 @@ function takeAcpLaunchFile(path) {
9256
9500
  rmSync(path, { force: true });
9257
9501
  return spec;
9258
9502
  }
9259
- const ACP_TOOL_KINDS = [
9260
- "read",
9261
- "edit",
9262
- "delete",
9263
- "move",
9264
- "search",
9265
- "execute",
9266
- "think",
9267
- "fetch",
9268
- "switch_mode",
9269
- "other"
9270
- ];
9271
- const MAX_RULES = 32;
9272
- /**
9273
- * Parse `--allow` patterns: comma separated, each `<kind>` or `<kind>:<title glob>`, where kind is
9274
- * an ACP tool kind or `*`. Examples: `read,search`, `execute:npm test*`, `*`.
9275
- */
9276
- function parseAllowPatterns(input) {
9277
- const rules = [];
9278
- for (const raw of input.flatMap((s) => s.split(","))) {
9279
- const item = raw.trim();
9280
- if (item === "") continue;
9281
- const colon = item.indexOf(":");
9282
- const kind = (colon === -1 ? item : item.slice(0, colon)).trim();
9283
- const title = colon === -1 ? void 0 : item.slice(colon + 1).trim();
9284
- if (kind !== "*" && !ACP_TOOL_KINDS.includes(kind)) return {
9285
- ok: false,
9286
- message: `"${kind}" is not a tool kind. Use one of: ${ACP_TOOL_KINDS.join(", ")}, or *.`
9287
- };
9288
- if (title === "") return {
9289
- ok: false,
9290
- message: `"${item}" has an empty title pattern.`
9291
- };
9292
- rules.push({
9293
- kind,
9294
- ...title !== void 0 ? { title } : {}
9295
- });
9296
- }
9297
- if (rules.length > MAX_RULES) return {
9298
- ok: false,
9299
- message: `At most ${MAX_RULES} allow patterns.`
9300
- };
9301
- return {
9302
- ok: true,
9303
- rules
9304
- };
9305
- }
9306
- const formatAllowRule = (r) => r.title === void 0 ? r.kind : `${r.kind}:${r.title}`;
9307
- function globMatch(glob, text) {
9308
- return new RegExp(`^${glob.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "s").test(text);
9309
- }
9310
- /** Does any rule allow a tool call of this kind and title? A call with no kind is `other`. */
9311
- function isAllowed(rules, call) {
9312
- const kind = call.kind ?? "other";
9313
- const title = call.title ?? "";
9314
- return rules.some((r) => (r.kind === "*" || r.kind === kind) && (r.title === void 0 || globMatch(r.title, title)));
9315
- }
9316
- /** The allow rules a worker gets when none were given: every kind of tool call. */
9317
- const DEFAULT_ALLOW_RULES = [{ kind: "*" }];
9318
9503
  /** Why a CLI cannot be started the way the caller asked. The message is shown to the user. */
9319
9504
  var SpawnError = class extends Error {
9320
9505
  fix;
@@ -9459,6 +9644,7 @@ async function runLaunchFile(path) {
9459
9644
  const child = spawn(spec.file, spec.args, {
9460
9645
  cwd: spec.cwd,
9461
9646
  stdio: "inherit",
9647
+ env: Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "CONVENO_ACP_WORKER")),
9462
9648
  ...spec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9463
9649
  });
9464
9650
  child.once("error", (e) => {
@@ -9577,6 +9763,9 @@ function realSpawnDeps(opts) {
9577
9763
  isDir: isDirectory,
9578
9764
  which: (name) => findOnPath(name, env, platform, platform === "win32" ? entryExists : void 0),
9579
9765
  acpNpxConsent: () => readSettings(dataPaths(platform, opts.dataDir).settings).acpAdapterNpx === true,
9766
+ workerAccess: () => readSettings(dataPaths(platform, opts.dataDir).settings).workerAccess,
9767
+ workerUnanswered: () => readSettings(dataPaths(platform, opts.dataDir).settings).workerUnanswered ?? "deny",
9768
+ workerAskTimeoutSec: () => workerAskTimeoutOf(readSettings(dataPaths(platform, opts.dataDir).settings)),
9580
9769
  repoExists: existsSync,
9581
9770
  killProcess: (pid) => killProcessTree(pid, platform),
9582
9771
  prepareFiles: (dataDir) => {
@@ -9663,7 +9852,11 @@ const SPAWN_TABLE = {
9663
9852
  binaries: ["claude-agent-acp"],
9664
9853
  args: [],
9665
9854
  adapterPackage: "@agentclientprotocol/claude-agent-acp",
9666
- fullAccessMode: "bypassPermissions",
9855
+ modes: {
9856
+ read: "plan",
9857
+ edit: "acceptEdits",
9858
+ full: "bypassPermissions"
9859
+ },
9667
9860
  note: "Claude Code has no ACP server of its own. The ACP project's npm package @agentclientprotocol/claude-agent-acp provides one and uses the Claude Code sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9668
9861
  docs: ["https://github.com/agentclientprotocol/claude-agent-acp (Apache-2.0, maintained by the ACP project)", "https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp (bin claude-agent-acp)"]
9669
9862
  }
@@ -9677,7 +9870,11 @@ const SPAWN_TABLE = {
9677
9870
  binaries: ["codex-acp"],
9678
9871
  args: [],
9679
9872
  adapterPackage: "@agentclientprotocol/codex-acp",
9680
- fullAccessMode: "agent-full-access",
9873
+ modes: {
9874
+ read: "read-only",
9875
+ edit: "workspace-write",
9876
+ full: "agent-full-access"
9877
+ },
9681
9878
  note: "Codex has no ACP server of its own. The ACP project's npm package @agentclientprotocol/codex-acp provides one and uses the Codex sign-in. Run conveno init to let Conveno fetch it with npx, or install it yourself.",
9682
9879
  docs: [
9683
9880
  "https://github.com/agentclientprotocol/codex-acp (Apache-2.0, built on the Codex app server)",
@@ -9694,6 +9891,11 @@ const SPAWN_TABLE = {
9694
9891
  acp: {
9695
9892
  binaries: ["opencode"],
9696
9893
  args: ["acp"],
9894
+ modes: {
9895
+ read: "plan",
9896
+ edit: "build",
9897
+ full: "build"
9898
+ },
9697
9899
  note: "",
9698
9900
  docs: ["https://opencode.ai/docs/cli/acp/ (opencode acp, stdio, protocol version 1)", "reference/src/opencode/packages/opencode/src/cli/cmd/acp.ts"]
9699
9901
  }
@@ -9706,6 +9908,11 @@ const SPAWN_TABLE = {
9706
9908
  acp: {
9707
9909
  binaries: ["agy"],
9708
9910
  args: ["acp"],
9911
+ modes: {
9912
+ read: "plan",
9913
+ edit: "accept-edits",
9914
+ full: "default"
9915
+ },
9709
9916
  note: "Uses the sign-in cached by an interactive `agy`.",
9710
9917
  docs: ["https://antigravity.google/docs/cli/acp (agy acp, stdio)"]
9711
9918
  }
@@ -9963,10 +10170,8 @@ async function spawnSession(deps, req) {
9963
10170
  isDir: deps.isDir,
9964
10171
  confineToHome: req.confineToHome
9965
10172
  });
9966
- const allow = parseAllowPatterns(req.allow ?? []);
9967
- if (!allow.ok) throw new SpawnError(allow.message, "Fix the --allow patterns.");
9968
10173
  const window = req.window === true;
9969
- if (window && allow.rules.length > 0) throw new SpawnError("--allow only applies to a background worker.", "Drop --window, or drop --allow.");
10174
+ const access = req.access ?? deps.workerAccess?.() ?? "edit";
9970
10175
  const acpResolved = spec.acp ? resolveAcpProgram(cli, spec.acp, {
9971
10176
  env: deps.env,
9972
10177
  which: deps.which,
@@ -10036,8 +10241,8 @@ async function spawnSession(deps, req) {
10036
10241
  ...task !== void 0 ? { task } : {},
10037
10242
  ...req.requester ? { spawnedBy: req.requester.id } : {},
10038
10243
  from: req.requester?.name ?? "the user",
10039
- allow: allow.rules.map(formatAllowRule),
10040
- ...allow.rules.length === 0 && spec.acp?.fullAccessMode ? { fullAccessMode: spec.acp.fullAccessMode } : {},
10244
+ access,
10245
+ ...spec.acp?.modes?.[access] ? { mode: spec.acp.modes[access] } : {},
10041
10246
  mcp: {
10042
10247
  command: node,
10043
10248
  args: [
@@ -10047,6 +10252,8 @@ async function spawnSession(deps, req) {
10047
10252
  cli
10048
10253
  ]
10049
10254
  },
10255
+ unanswered: deps.workerUnanswered?.() === "allow" ? "allow" : "deny",
10256
+ askTimeoutMs: (deps.workerAskTimeoutSec?.() ?? 120) * 1e3,
10050
10257
  ...acpRun?.source.startsWith("npx:") ? { setupTimeoutMs: NPX_SETUP_TIMEOUT_MS } : {}
10051
10258
  });
10052
10259
  run = await deps.launchBackground({
@@ -10093,7 +10300,7 @@ async function spawnSession(deps, req) {
10093
10300
  }
10094
10301
  req.onProgress?.(window ? `Opened ${terminal}. Waiting for ${cli} to register.` : `Started ${cli} over ACP in the background (host pid ${run?.pid}). Waiting for it to register.`);
10095
10302
  const viaNpx = !window && acpRun?.source.startsWith("npx:") === true;
10096
- if (viaNpx) req.onProgress?.(`Fetching the ${cli} adapter with npx (first run downloads it and can take a few minutes).`);
10303
+ if (viaNpx) req.onProgress?.(`Starting the ${cli} adapter with npx (only the first run downloads it).`);
10097
10304
  const session = await waitForRegistration(deps, {
10098
10305
  name,
10099
10306
  cli,
@@ -10174,4 +10381,4 @@ async function waitForRegistration(deps, w) {
10174
10381
  await deps.sleep(250);
10175
10382
  }
10176
10383
  }
10177
- export { generateSessionName as $, statusAfterLiveness as $t, clientProof as A, isSocketPathTooLong as An, proofsMatch as At, defaultProcessIo as B, sanitizeLine as Bn, requestDeviceCode as Bt, autoCandidates as C, RpcResponse as Cn, pendingHookContext as Ct, claimOrchestrator as D, defaultSocketPath as Dn, planProgram as Dt, bindAccountDevice as E, createLineDecoder as En, planLauncher as Et, currentAccessToken as F, newMessageId as Fn, readInbox as Ft, endTurnContinuation as G, discriminatedUnion as Gn, resolveWindowsCommand as Gt, dropFromList as H, _enum as Hn, requeueMessages as Ht, daemonProof as I, newSessionId as In, readSettings as It, fetchAccountStatus as J, object as Jn, sameJson as Jt, evaluateLiveness as K, literal as Kn, runLaunchFile as Kt, dataDir as L, parseIpcRequest as Ln, readSpawnRecord as Lt, compatStatus as M, makeEventNotification as Mn, readAccountTokens as Mt, completeLogin as N, makeResult as Nn, readAncestry as Nt, claimSpawnRecord as O, encodeFrame as On, planSpawn as Ot, createWmiWalker as P, newDeviceId as Pn, readCommandLine as Pt, formatInbox as Q, startTurnContext as Qt, dataPaths as R, parseRelayFrame as Rn, realSpawnDeps as Rt, attachAcpSession as S, RpcErrorCode as Sn, pendingForInjection as St, baseName as T, SessionId as Tn, pinnedAdapter as Tt, editJson as U, array as Un, resolveAcpProgram as Ut, detectRepo as V, socketPathTooLongMessage as Vn, requeueEntries as Vt, effectiveHolder as W, boolean as Wn, resolveRecipient as Wt, formatContinuation as X, spawnRecordPath as Xt, findOnPath as Y, string as Yn, senderOf as Yt, formatHookContext as Z, spawnSession as Zt, adapterNpxCommand as _, Message as _n, ownSession as _t, DEFAULT_ALLOW_RULES as a, uninstallLauncher as an, isObject as at, askedKey as b, PROTOCOL_VERSION as bn, parseCmdShimTarget as bt, NOT_FROM_USER_NOTICE as c, waitForWork as cn, late as ct, SPAWN_CLIS as d, CLI_KINDS as dn, loadJson as dt, takeAcpLaunchFile as en, holderAfterDeparture as et, SPAWN_TABLE as f, CliKind as fn, logoutAccount as ft, adapterInstallCommand as g, EventPayload as gn, oneWindowPerHost as gt, acpOverrideVar as h, EVENT_NOTIFICATION_METHOD as hn, newAuthNonce as ht, ConvenoError as i, turnHops as in, isFromOwner as it, compareVersions as j, makeError as jn, putInList as jt, clearOrchestrator as k, ipcMethods as kn, pollDeviceCode as kt, ORCHESTRATOR_TASK_NOTICE as l, waitForWorkBatch as ln, launcherPath as lt, ackEntries as m, EVENT_NAMES as mn, needsQuoting as mt, AccountError as n, takeWithinChars as nn, hookLogPath as nt, FROM_USER_NOTICE as o, updateSpawnRecord as on, isOnline as ot, SpawnError as p, DeviceId as pn, markDelivered as pt, existedBefore as q, number as qn, runWaker as qt, CLAUDE_PENDING_TURN_FOLDER as r, tooManyUnreadMessage as rn, isAllowed as rt, HEARTBEAT_INTERVAL_MS as s, validateRename as sn, jwtClaim as st, ACCOUNT_API as t, takeWithinBytes as tn, hookLogLine as tt, RESPONSE_BUDGET_BYTES as u, writeSettings as un, launcherText as ut, agentCommand as v, MessageId as vn, parseAllowPatterns as vt, autoLimitsFromEnv as w, SESSION_NAME_PATTERN as wn, pendingTurn as wt, askedMarker as x, RelayPayload as xn, parsePs1ShimTarget as xt, appendHookLog as y, OWNER_SESSION_ID as yn, parseCliVersion as yt, decideAutoContinue as z, safeParse as zn, renderBody as zt };
10384
+ export { formatContinuation as $, sanitizeLine as $n, resolveRecipient as $t, claimOrchestrator as A, MessageId as An, pendingHookContext as At, dataDir as B, defaultSocketPath as Bn, readAccountTokens as Bt, askedKey as C, CLI_KINDS as Cn, oneWindowPerHost as Ct, autoLimitsFromEnv as D, EVENT_NOTIFICATION_METHOD as Dn, parsePs1ShimTarget as Dt, autoCandidates as E, EVENT_NAMES as En, parseCmdShimTarget as Et, compatStatus as F, RpcResponse as Fn, planProgram as Ft, dropFromList as G, makeEventNotification as Gn, readSettings as Gt, decideAutoContinue as H, ipcMethods as Hn, readCommandLine as Ht, completeLogin as I, SESSION_ENDED_TEXT as In, planSpawn as It, endTurnContinuation as J, newMessageId as Jn, renderBody as Jt, editJson as K, makeResult as Kn, readSpawnRecord as Kt, createWmiWalker as L, SESSION_NAME_PATTERN as Ln, pollDeviceCode as Lt, clearOrchestrator as M, PROTOCOL_VERSION as Mn, pidAlive as Mt, clientProof as N, RelayPayload as Nn, pinnedAdapter as Nt, baseName as O, EventPayload as On, parseWorkerAccess as Ot, compareVersions as P, RpcErrorCode as Pn, planLauncher as Pt, findOnPath as Q, safeParse as Qn, resolveAcpProgram as Qt, currentAccessToken as R, SessionId as Rn, proofsMatch as Rt, appendHookLog as S, writeSettings as Sn, newAuthNonce as St, attachAcpSession as T, DeviceId as Tn, parseCliVersion as Tt, defaultProcessIo as U, isSocketPathTooLong as Un, readInbox as Ut, dataPaths as V, encodeFrame as Vn, readAncestry as Vt, detectRepo as W, makeError as Wn, readProcessList as Wt, existedBefore as X, parseIpcRequest as Xn, requeueEntries as Xt, evaluateLiveness as Y, newSessionId as Yn, requestDeviceCode as Yt, fetchAccountStatus as Z, parseRelayFrame as Zn, requeueMessages as Zt, ackEntries as _, waitForWork as _n, leadLogPath as _t, FROM_USER_NOTICE as a, spawnRecordPath as an, literal as ar, hookLogPath as at, adapterNpxCommand as b, workerAskTimeoutOf as bn, markDelivered as bt, ORCHESTRATOR_TASK_NOTICE as c, statusAfterLiveness as cn, string as cr, isAntigravityApp as ct, SPAWN_TABLE as d, takeWithinChars as dn, isOnline as dt, resolveWindowsCommand as en, socketPathTooLongMessage as er, formatHookContext as et, SpawnError as f, tooManyUnreadMessage as fn, jwtClaim as ft, accessAllows as g, validateRename as gn, leadLogLine as gt, WORKER_UNANSWERED as h, updateSpawnRecord as hn, launcherText as ht, ConvenoError as i, senderOf as in, discriminatedUnion as ir, hookLogLine as it, claimSpawnRecord as j, OWNER_SESSION_ID as jn, pendingTurn as jt, bindAccountDevice as k, Message as kn, pendingForInjection as kt, RESPONSE_BUDGET_BYTES as l, takeAcpLaunchFile as ln, isFromOwner as lt, WORKER_ASK_TIMEOUT_CHOICES as m, uninstallLauncher as mn, launcherPath as mt, AccountError as n, runWaker as nn, array as nr, generateSessionName as nt, HEARTBEAT_INTERVAL_MS as o, spawnSession as on, number as or, hostAlive as ot, WORKER_ACCESS as p, turnHops as pn, late as pt, effectiveHolder as q, newDeviceId as qn, realSpawnDeps as qt, CLAUDE_PENDING_TURN_FOLDER as r, sameJson as rn, boolean as rr, holderAfterDeparture as rt, NOT_FROM_USER_NOTICE as s, startTurnContext as sn, object as sr, hostPidOf as st, ACCOUNT_API as t, runLaunchFile as tn, _enum as tr, formatInbox as tt, SPAWN_CLIS as u, takeWithinBytes as un, isObject as ut, acpOverrideVar as v, waitForWorkBatch as vn, loadJson as vt, askedMarker as w, CliKind as wn, ownSession as wt, agentCommand as x, workerUnansweredOf as xn, needsQuoting as xt, adapterInstallCommand as y, workerAccessOf as yn, logoutAccount as yt, daemonProof as z, createLineDecoder as zn, putInList as zt };