@conveno/cli 0.2.0-rc.6 → 0.2.0-rc.8

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.
@@ -1,12 +1,13 @@
1
1
  import { homedir } from "node:os";
2
- import { t as antigravityAdapter } from "./dist-LkcRvVjE.js";
2
+ import { n as antigravityAdapter } from "./dist-B6Sm0MRT.js";
3
3
  import { isAbsolute, join } from "node:path";
4
- import { $ as loadJson$1, Et as requeueMessages, Gt as waitForWorkBatch, I as dropFromList, It as startTurnContext, L as editJson$1, Mt as sameJson$1, V as existedBefore, Wt as waitForWork, X as isObject$1, _t as readAncestry, a as FROM_USER_NOTICE, at as parseCliVersion, c as ORCHESTRATOR_TASK_NOTICE, ht as putInList, j as dataDir, lt as pendingHookContext, rt as ownSession, s as NOT_FROM_USER_NOTICE, z as endTurnContinuation } from "./dist-BTLBO1Rp.js";
4
+ import { Dt as requeueMessages, I as dropFromList, Jt as waitForWorkBatch, L as editJson$1, Ot as requeueOwnMessages, Pt as sameJson$1, Rt as startTurnContext, V as existedBefore, Z as isObject$1, et as loadJson$1, gt as putInList, it as ownSession, j as dataDir, ot as parseCliVersion, qt as waitForWork, ut as pendingHookContext, vt as readAncestry, z as endTurnContinuation } from "./dist-BBdba94T.js";
5
5
  import { readFile } from "node:fs/promises";
6
6
  import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
7
- import { n as Za, r as cs, t as codexAdapter } from "./dist-CNyzLyZh.js";
8
- import { n as connect } from "./dist-BYVibI3a.js";
9
- import { t as runHook } from "./hook-BGJc4PHG.js";
7
+ import { t as codexAdapter } from "./dist-B1EVHdIM.js";
8
+ import { t as grokAdapter } from "./dist-CcoTmwrf.js";
9
+ import { n as connect } from "./dist-WTkKRM39.js";
10
+ import { t as runHook } from "./hook-DxjJDCjz.js";
10
11
  // ../adapters/claude/dist/index.js
11
12
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
12
13
  /** Read a JSON object file. Missing or blank files give `{}`; anything else that is not a JSON object throws. */
@@ -60,11 +61,12 @@ function editJson(file, edits) {
60
61
  for (const e of edits) text = applyEdits(text, modify(text, e.path, e.value, { formattingOptions }));
61
62
  return (bom ? "" : "") + text;
62
63
  }
63
- const SERVER_NAME$4 = "conveno";
64
+ const SERVER_NAME$3 = "conveno";
64
65
  /** Claude Code events Conveno installs hooks for. */
65
- const HOOK_EVENTS$3 = [
66
+ const HOOK_EVENTS$2 = [
66
67
  "SessionStart",
67
68
  "UserPromptSubmit",
69
+ "PostToolUse",
68
70
  "Stop"
69
71
  ];
70
72
  /** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
@@ -86,19 +88,50 @@ const LISTEN_MAX_MS$1 = 17277e5;
86
88
  * A listener armed on SessionStart can start before Claude Code's MCP server registered the
87
89
  * session. It looks for its session this long before it gives up.
88
90
  */
89
- const LISTEN_REGISTER_WAIT_MS = 12e4;
91
+ const LISTEN_REGISTER_WAIT_MS$1 = 12e4;
92
+ /**
93
+ * First wait before a listener that lost the daemon (it restarted or was stopped) tries again;
94
+ * doubles up to a minute. The listener keeps the session wakeable instead of exiting.
95
+ */
96
+ const LISTEN_RECONNECT_MS = 5e3;
97
+ /**
98
+ * `CLAUDE_CODE_ENTRYPOINT` values of a non-interactive run: `claude -p` sets `sdk-cli`, the Agent
99
+ * SDKs `sdk-ts` and `sdk-py`. Claude Code's own check for an SDK entrypoint is this set (2.1.332
100
+ * bundle: `e==="sdk-ts"||e==="sdk-py"||e==="sdk-cli"`; `claude -p` turns `cli` into `sdk-cli`).
101
+ */
102
+ const NON_INTERACTIVE_ENTRYPOINTS = /* @__PURE__ */ new Set([
103
+ "sdk-cli",
104
+ "sdk-ts",
105
+ "sdk-py"
106
+ ]);
90
107
  /**
91
108
  * Claude Code shows the stderr of a waking hook after its own "Stop hook blocking error from
92
109
  * command" prefix. This first line tells the model what the text is.
93
110
  */
94
111
  const WAKE_LEAD = "Conveno messages for this session follow. This is not an error and no hook failed: Claude Code labels every wake from a background hook this way.";
112
+ /**
113
+ * Characters a hook prints at most. Claude Code caps a hook's `additionalContext` and plain stdout
114
+ * at 10,000 characters; past that it saves the text to a file and shows Claude a 2,000-character
115
+ * preview without asking it to read the rest (docs, hooks: "capped at 10,000 characters"). Kept
116
+ * under the cap with room to spare; messages past it stay queued for the next delivery.
117
+ */
118
+ const OUTPUT_MAX_CHARS = 9e3;
119
+ /** The listener's framed batch, after `WAKE_LEAD` and a blank line, within `OUTPUT_MAX_CHARS`. */
120
+ const WAKE_MAX_CHARS = 8853;
121
+ /**
122
+ * Milliseconds from the start of a hook by which it must have its messages: `conveno hook` gives up
123
+ * after 2 s, counted from before it connected and found the host, and a hook that has given up
124
+ * prints nothing. Messages the daemon hands over later are put back to queued.
125
+ */
126
+ const DELIVER_DEADLINE_MS = 1200;
95
127
  /** The handlers Conveno wants on each event, in order: the hook itself, then a listener where one is armed. */
96
128
  const HANDLERS = {
97
129
  SessionStart: ["SessionStart", LISTEN_EVENT$1],
98
130
  UserPromptSubmit: ["UserPromptSubmit"],
131
+ PostToolUse: ["PostToolUse"],
99
132
  Stop: ["Stop", LISTEN_EVENT$1]
100
133
  };
101
- const EMPTY$4 = {
134
+ const EMPTY$3 = {
102
135
  stdout: "",
103
136
  exitCode: 0
104
137
  };
@@ -115,33 +148,42 @@ function paths$2(env) {
115
148
  };
116
149
  }
117
150
  /**
118
- * Quote one word of a hook command for the shell Claude Code runs it in. On Windows that is Git
119
- * Bash (PowerShell only when Git Bash is not installed), so the word is written for bash. Windows
120
- * paths use forward slashes there: bash would read `\P` inside double quotes as an escape, and
121
- * Windows accepts `/` in every API Node and Git Bash use, so `C:/Program Files/nodejs/node.exe`
122
- * means the same file and needs no escaping.
151
+ * The program and arguments of one hook, in exec form: Claude Code spawns `command` with `args` and
152
+ * no shell, so nothing is quoted and Git Bash, PowerShell and `sh` read it alike
153
+ * (https://code.claude.com/docs/en/hooks, "Exec form and shell form"; `args` since Claude Code
154
+ * 2.1.139, older than the 2.1.332 minimum). On Windows `command` must be a real executable, not an
155
+ * npm `.cmd` shim, so a bare `conveno` there becomes `node <conveno's script>`, the pattern the
156
+ * docs give for npm tools.
123
157
  */
124
- function quoteHookWord$1(arg, platform) {
125
- const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
126
- return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
158
+ function hookProgram(env, event) {
159
+ let [command = "conveno", ...rest] = env.conveno.command;
160
+ if (env.platform === "win32" && rest.length === 0 && env.conveno.bin) {
161
+ command = "node";
162
+ rest = [env.conveno.bin];
163
+ }
164
+ return {
165
+ command,
166
+ args: [
167
+ ...rest,
168
+ "hook",
169
+ "claude",
170
+ event
171
+ ]
172
+ };
127
173
  }
128
- const hookCommand$2 = (env, event) => [
129
- ...env.conveno.command,
130
- "hook",
131
- "claude",
132
- event
133
- ].map((w) => quoteHookWord$1(w, env.platform)).join(" ");
134
174
  /** One hook handler as written to settings.json. The listener runs in the background (`asyncRewake`). */
135
175
  function handlerFor(env, arg) {
136
- const command = hookCommand$2(env, arg);
176
+ const { command, args } = hookProgram(env, arg);
137
177
  return arg === "Listen" ? {
138
178
  type: "command",
139
179
  command,
180
+ args,
140
181
  asyncRewake: true,
141
182
  timeout: LISTEN_TIMEOUT_SECONDS
142
183
  } : {
143
184
  type: "command",
144
185
  command,
186
+ args,
145
187
  timeout: 5
146
188
  };
147
189
  }
@@ -160,8 +202,20 @@ const desiredServer$2 = (env) => {
160
202
  env: {}
161
203
  };
162
204
  };
163
- /** Recognizes our hook command even if the conveno path changed since install. */
164
- const isOurHookCommand$2 = (cmd) => typeof cmd === "string" && /(^|\s)hook claude (SessionStart|UserPromptSubmit|Stop|Listen|PermissionRequest)$/.test(cmd.trim());
205
+ const OUR_EVENTS = /^(SessionStart|UserPromptSubmit|PostToolUse|Stop|Listen|PermissionRequest)$/;
206
+ /**
207
+ * Recognizes our hook handler even if the conveno path changed since install: exec form (`args`
208
+ * ending in `hook claude <event>`) or the shell form older versions wrote.
209
+ */
210
+ function isOurHook(h) {
211
+ if (!isObject(h)) return false;
212
+ if (Array.isArray(h.args)) {
213
+ const [a, b, c] = h.args.slice(-3);
214
+ return a === "hook" && b === "claude" && typeof c === "string" && OUR_EVENTS.test(c);
215
+ }
216
+ const m = typeof h.command === "string" && /(?:^|\s)hook claude (\S+)$/.exec(h.command.trim());
217
+ return m ? OUR_EVENTS.test(m[1] ?? "") : false;
218
+ }
165
219
  const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
166
220
  function groupsOf(hooks, event) {
167
221
  const g = hooks[event];
@@ -174,7 +228,7 @@ function hasExactHook$2(hooks, event, handler) {
174
228
  const eventComplete = (env, hooks, event) => HANDLERS[event].every((arg) => hasExactHook$2(hooks, event, handlerFor(env, arg)));
175
229
  /** The name `conveno doctor --verbose` shows for one event. Start and Stop also arm the listener. */
176
230
  const hookPartName = (e) => HANDLERS[e].includes("Listen") ? `${e} hook and listener` : `${e} hook`;
177
- const hasOurHandler = (g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand$2(h.command));
231
+ const hasOurHandler = (g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook);
178
232
  /** Drop our hook handlers (and groups left empty by that). */
179
233
  function stripOurHooks(groups) {
180
234
  const out = [];
@@ -183,7 +237,7 @@ function stripOurHooks(groups) {
183
237
  out.push(g);
184
238
  continue;
185
239
  }
186
- const kept = g.hooks.filter((h) => !(isObject(h) && isOurHookCommand$2(h.command)));
240
+ const kept = g.hooks.filter((h) => !isOurHook(h));
187
241
  if (kept.length === g.hooks.length) out.push(g);
188
242
  else if (kept.length > 0) out.push({
189
243
  ...g,
@@ -204,7 +258,7 @@ function mcpObject$2(config, path) {
204
258
  if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
205
259
  return s;
206
260
  }
207
- async function detect$4(env) {
261
+ async function detect$3(env) {
208
262
  const p = paths$2(env);
209
263
  const configPaths = [p.mcp, p.settings];
210
264
  try {
@@ -229,7 +283,7 @@ async function detect$4(env) {
229
283
  }
230
284
  /** `A`, `A and B`, `A, B and C`. */
231
285
  const listed = (words) => words.length < 2 ? words[0] ?? "" : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
232
- async function plan$4(env) {
286
+ async function plan$3(env) {
233
287
  const p = paths$2(env);
234
288
  const changes = [];
235
289
  const mcpFile = await loadJson(p.mcp);
@@ -237,7 +291,7 @@ async function plan$4(env) {
237
291
  const want = desiredServer$2(env);
238
292
  if (!sameJson(servers["conveno"], want)) {
239
293
  const after = editJson(mcpFile, [{
240
- path: ["mcpServers", SERVER_NAME$4],
294
+ path: ["mcpServers", SERVER_NAME$3],
241
295
  value: want
242
296
  }]);
243
297
  changes.push({
@@ -250,14 +304,14 @@ async function plan$4(env) {
250
304
  name: "MCP server",
251
305
  kind: servers["conveno"] === void 0 ? "add" : "update"
252
306
  }],
253
- description: `Register the "${SERVER_NAME$4}" MCP server at user scope (conveno mcp --cli claude).`,
307
+ description: `Register the "${SERVER_NAME$3}" MCP server at user scope (conveno mcp --cli claude).`,
254
308
  viaCommand: [
255
309
  "claude",
256
310
  "mcp",
257
311
  "add",
258
312
  "--scope",
259
313
  "user",
260
- SERVER_NAME$4,
314
+ SERVER_NAME$3,
261
315
  "--",
262
316
  ...mcpArgs$2(env)
263
317
  ]
@@ -265,11 +319,11 @@ async function plan$4(env) {
265
319
  }
266
320
  const setFile = await loadJson(p.settings);
267
321
  const hooks = hooksObject$2(setFile.value, p.settings);
268
- const missing = HOOK_EVENTS$3.filter((e) => !eventComplete(env, hooks, e));
322
+ const missing = HOOK_EVENTS$2.filter((e) => !eventComplete(env, hooks, e));
269
323
  if (missing.length > 0) {
270
324
  const next = { ...hooks };
271
325
  for (const e of missing) next[e] = [...stripOurHooks(groupsOf(hooks, e)), ...HANDLERS[e].map((arg) => ({ hooks: [handlerFor(env, arg)] }))];
272
- const installed = [...HOOK_EVENTS$3, ...LEGACY_HOOK_EVENTS].some((e) => groupsOf(hooks, e).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand$2(h.command))));
326
+ const installed = [...HOOK_EVENTS$2, ...LEGACY_HOOK_EVENTS].some((e) => groupsOf(hooks, e).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook)));
273
327
  changes.push({
274
328
  component: "hooks",
275
329
  kind: installed ? "update" : "add",
@@ -283,12 +337,12 @@ async function plan$4(env) {
283
337
  path: ["hooks", e],
284
338
  value: next[e]
285
339
  }))),
286
- description: `Add Conveno's ${listed(missing)} hooks to Claude Code. They deliver messages at the next prompt and, at the end of a turn or by waking an idle session through a background listener.`
340
+ description: `Add Conveno's ${listed(missing)} hooks to Claude Code. They deliver messages at the next prompt, after a tool call, at the end of a turn, or by waking an idle session through a background listener.`
287
341
  });
288
342
  }
289
343
  return changes;
290
344
  }
291
- async function uninstallPlan$4(env) {
345
+ async function uninstallPlan$3(env) {
292
346
  const p = paths$2(env);
293
347
  const changes = [];
294
348
  const mcpFile = await loadJson(p.mcp);
@@ -298,24 +352,24 @@ async function uninstallPlan$4(env) {
298
352
  path: p.mcp,
299
353
  before: mcpFile.raw,
300
354
  after: editJson(mcpFile, [{
301
- path: ["mcpServers", SERVER_NAME$4],
355
+ path: ["mcpServers", SERVER_NAME$3],
302
356
  value: void 0
303
357
  }]),
304
- description: `Remove the "${SERVER_NAME$4}" MCP server from user scope.`,
358
+ description: `Remove the "${SERVER_NAME$3}" MCP server from user scope.`,
305
359
  viaCommand: [
306
360
  "claude",
307
361
  "mcp",
308
362
  "remove",
309
363
  "--scope",
310
364
  "user",
311
- SERVER_NAME$4
365
+ SERVER_NAME$3
312
366
  ]
313
367
  });
314
368
  const setFile = await loadJson(p.settings);
315
369
  const hooks = hooksObject$2(setFile.value, p.settings);
316
370
  const next = { ...hooks };
317
371
  const edits = [];
318
- for (const e of [...HOOK_EVENTS$3, ...LEGACY_HOOK_EVENTS]) {
372
+ for (const e of [...HOOK_EVENTS$2, ...LEGACY_HOOK_EVENTS]) {
319
373
  const groups = groupsOf(hooks, e);
320
374
  const stripped = stripOurHooks(groups);
321
375
  if (sameJson(groups, stripped)) continue;
@@ -337,63 +391,117 @@ async function uninstallPlan$4(env) {
337
391
  path: p.settings,
338
392
  before: setFile.raw,
339
393
  after: editJson(setFile, edits),
340
- description: "Remove the Conveno SessionStart, UserPromptSubmit, and Stop hooks and the listener."
394
+ description: "Remove the Conveno SessionStart, UserPromptSubmit, PostToolUse and Stop hooks and the listener."
341
395
  });
342
396
  }
343
397
  return changes;
344
398
  }
345
399
  /** `stop_hook_active` from the Stop input: Claude Code is already continuing because of a Stop hook. */
346
400
  const stopHookActive = (input) => isObject(input) && input.stop_hook_active === true;
401
+ /** `agent_id` is in a hook's input only when it fires inside a subagent (docs, "Common input fields"). */
402
+ const inSubagent = (input) => isObject(input) && typeof input.agent_id === "string" && input.agent_id !== "";
403
+ const contextOutput = (event, additionalContext) => additionalContext === null ? EMPTY$3 : {
404
+ stdout: JSON.stringify({ hookSpecificOutput: {
405
+ hookEventName: event,
406
+ additionalContext
407
+ } }),
408
+ exitCode: 0
409
+ };
410
+ /**
411
+ * Claude Code's id for this session: `CLAUDE_CODE_SESSION_ID`, which hook processes get and which
412
+ * matches the input's `session_id` (docs, env-vars); the input field when the variable is missing.
413
+ */
414
+ function claudeSessionId(input) {
415
+ const env = process.env.CLAUDE_CODE_SESSION_ID;
416
+ if (env) return env;
417
+ return isObject(input) && typeof input.session_id === "string" && input.session_id !== "" ? input.session_id : void 0;
418
+ }
419
+ /**
420
+ * Finds the session by Claude Code's own session id where the daemon knows it, with the host pid as
421
+ * the fallback. The MCP server records the id it was started with, but that id is not the hooks'
422
+ * after `/clear`, and after `--continue` or `--resume` without an id it can be the startup one
423
+ * (docs, `CLAUDE_CODE_SESSION_ID`). So on a miss the hook looks the session up by pid and, when that
424
+ * finds this host's Claude session, records the hooks' id on it, so later hooks match it directly.
425
+ * Never throws: on any failure the pid lookup of the helpers applies.
426
+ */
427
+ async function withSessionId(ctx, input) {
428
+ const nativeId = claudeSessionId(input);
429
+ if (nativeId === void 0 || ctx.nativeId !== void 0) return ctx;
430
+ try {
431
+ const { client, hostPid: pid } = ctx;
432
+ if ((await client["session.byHost"]({
433
+ pid,
434
+ nativeId
435
+ })).session) return {
436
+ ...ctx,
437
+ nativeId
438
+ };
439
+ const byPid = await client["session.byHost"]({ pid });
440
+ if (byPid.session?.cli !== "claude") return ctx;
441
+ await client["session.setNative"]({
442
+ sessionId: byPid.session.id,
443
+ nativeId
444
+ });
445
+ return {
446
+ ...ctx,
447
+ nativeId
448
+ };
449
+ } catch {
450
+ return ctx;
451
+ }
452
+ }
347
453
  /**
348
- * Never throws: any failure means "deliver nothing this time".
454
+ * Never throws: any failure means "deliver nothing this time". What a hook prints stays within
455
+ * `OUTPUT_MAX_CHARS`, and messages handed over after `DELIVER_DEADLINE_MS` go back to queued.
349
456
  *
350
457
  * - SessionStart: waiting messages as `additionalContext`.
351
458
  * - UserPromptSubmit: the turn starts (the session is busy), waiting messages as `additionalContext`.
352
- * - Stop: with messages waiting, `decision: "block"` with the framed messages as
353
- * `reason`, so Claude continues with them. When `stop_hook_active` is set (Claude is already
354
- * continuing because of a Stop hook) it never blocks; it only records that the turn ended, and the
355
- * listener armed on this Stop wakes the session with what waits, as a new turn.
459
+ * - PostToolUse: mid-turn, waiting messages as `additionalContext`, which Claude Code puts next to
460
+ * the tool result. Not inside a subagent, whose context the main conversation does not see.
461
+ * - Stop: with messages waiting, `hookSpecificOutput.additionalContext` with the framed messages,
462
+ * so Claude continues with them, shown as hook feedback rather than a hook error. When
463
+ * `stop_hook_active` is set (Claude is already continuing because of a Stop hook) it never
464
+ * continues; it only records that the turn ended, and the listener armed on this Stop wakes the
465
+ * session with what waits, as a new turn.
356
466
  * - Listen: the background listener (`asyncRewake`). Waits for its session to register, then for
357
467
  * work, and exits 2 with the framed messages on stderr (after `WAKE_LEAD`), which wakes Claude
358
- * even when the session is idle. Exit 0, silent, when it stops for any other reason, and at once
359
- * in `claude -p` (`CLAUDE_CODE_ENTRYPOINT=sdk-cli`). A batch taken just as Claude Code exited is
360
- * requeued.
468
+ * even when the session is idle. A lost daemon connection is retried, so a daemon restart does
469
+ * not leave the session unwakeable. Exit 0, silent, when it stops for any other reason, and at
470
+ * once in a non-interactive run (`NON_INTERACTIVE_ENTRYPOINTS`). A batch taken just as Claude
471
+ * Code exited is requeued.
361
472
  */
362
- async function hook$4(event, input, ctx) {
473
+ async function hook$3(event, input, ctx) {
474
+ const opts = {
475
+ maxChars: OUTPUT_MAX_CHARS,
476
+ deadline: Date.now() + DELIVER_DEADLINE_MS
477
+ };
363
478
  switch (event) {
364
- case "SessionStart":
365
- case "UserPromptSubmit": {
366
- const additionalContext = await (event === "SessionStart" ? pendingHookContext(ctx) : startTurnContext(ctx));
367
- if (additionalContext === null) return EMPTY$4;
368
- return {
369
- stdout: JSON.stringify({ hookSpecificOutput: {
370
- hookEventName: event,
371
- additionalContext
372
- } }),
373
- exitCode: 0
374
- };
375
- }
479
+ case "SessionStart": return contextOutput(event, await pendingHookContext(await withSessionId(ctx, input), opts));
480
+ case "UserPromptSubmit": return contextOutput(event, await startTurnContext(await withSessionId(ctx, input), opts));
481
+ case "PostToolUse":
482
+ if (inSubagent(input)) return EMPTY$3;
483
+ return contextOutput(event, await pendingHookContext(await withSessionId(ctx, input), opts));
376
484
  case "Stop": {
377
- const reason = await endTurnContinuation(ctx, { allowContinue: !stopHookActive(input) });
378
- if (reason === null) return EMPTY$4;
379
- return {
380
- stdout: JSON.stringify({
381
- decision: "block",
382
- reason
383
- }),
384
- exitCode: 0
385
- };
485
+ const reason = await endTurnContinuation(await withSessionId(ctx, input), {
486
+ ...opts,
487
+ allowContinue: !stopHookActive(input)
488
+ });
489
+ return contextOutput(event, reason);
386
490
  }
387
491
  case LISTEN_EVENT$1: {
388
- if (process.env.CLAUDE_CODE_ENTRYPOINT === "sdk-cli") return EMPTY$4;
389
- const r = await waitForWorkBatch(ctx, {
492
+ const entry = process.env.CLAUDE_CODE_ENTRYPOINT;
493
+ if (entry !== void 0 && NON_INTERACTIVE_ENTRYPOINTS.has(entry)) return EMPTY$3;
494
+ const own = await withSessionId(ctx, input);
495
+ const r = await waitForWorkBatch(own, {
390
496
  maxMs: LISTEN_MAX_MS$1,
391
- registerWaitMs: LISTEN_REGISTER_WAIT_MS
497
+ registerWaitMs: LISTEN_REGISTER_WAIT_MS$1,
498
+ reconnectMs: LISTEN_RECONNECT_MS,
499
+ maxChars: WAKE_MAX_CHARS
392
500
  });
393
- if (r === null) return EMPTY$4;
501
+ if (r === null) return EMPTY$3;
394
502
  if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) {
395
503
  await requeueMessages(ctx.client, r.sessionId, r.batch.messages);
396
- return EMPTY$4;
504
+ return EMPTY$3;
397
505
  }
398
506
  return {
399
507
  stdout: "",
@@ -401,7 +509,7 @@ async function hook$4(event, input, ctx) {
401
509
  exitCode: 2
402
510
  };
403
511
  }
404
- default: return EMPTY$4;
512
+ default: return EMPTY$3;
405
513
  }
406
514
  }
407
515
  const delivery$1 = () => ({
@@ -413,15 +521,37 @@ const claudeAdapter = {
413
521
  cli: "claude",
414
522
  displayName: "Claude Code",
415
523
  deliveryTier: "next_turn",
416
- detect: detect$4,
417
- plan: plan$4,
418
- uninstallPlan: uninstallPlan$4,
419
- hook: hook$4,
524
+ detect: detect$3,
525
+ plan: plan$3,
526
+ uninstallPlan: uninstallPlan$3,
527
+ hook: hook$3,
420
528
  listenEvents: [LISTEN_EVENT$1],
421
529
  delivery: delivery$1
422
530
  };
423
531
  // ../adapters/copilot/dist/index.js
424
- const EXTENSION_MARKER = `// conveno-extension: 1`;
532
+ /**
533
+ * The Copilot CLI extension Conveno installs as `<copilot home>/extensions/conveno/extension.mjs`.
534
+ * Copilot starts every extension in that folder as its own Node process next to an interactive
535
+ * session, once experimental mode is on (https://docs.github.com/en/copilot/tutorials/create-an-extension).
536
+ * The extension joins the session with `joinSession()` from `@github/copilot-sdk/extension`, which
537
+ * the CLI itself provides, so the file has no imports to install.
538
+ *
539
+ * It does no Conveno work itself. While the session is idle it runs `conveno hook copilot Listen`,
540
+ * the shared listener (it waits for the daemon to hand the session messages, like Claude's), and
541
+ * sends what that prints with `session.send({ prompt, mode: "enqueue" })`, which starts a turn
542
+ * with no keypress. Any turn starting stops the listener; `session.idle` starts it again.
543
+ *
544
+ * Listen's output starts with a line `#conveno-ids <id>,<id>`. The extension cuts that line off, so
545
+ * it never reaches the model, and if `session.send` fails it runs `hook copilot Requeue` with the
546
+ * ids so the messages are queued again. On SIGTERM it does the same for a listener it stops.
547
+ *
548
+ * Listen and Requeue run under this process, not under Copilot, so they name the session by
549
+ * Copilot's `sessionId`, and Listen also passes `process.ppid`: Copilot forks every extension
550
+ * (copilot-sdk docs/extensions.md), so that is the CLI that hosts the session.
551
+ */
552
+ /** Start of the first line of the extension file. Uninstall and re-install recognise it by this. */
553
+ const EXTENSION_MARKER_PREFIX = "// conveno-extension:";
554
+ const EXTENSION_MARKER = `${EXTENSION_MARKER_PREFIX} 1`;
425
555
  /** Plain JavaScript source with the conveno command baked in. No imports beyond Node built-ins and the SDK. */
426
556
  function extensionSource(command) {
427
557
  return `${EXTENSION_MARKER}
@@ -433,21 +563,38 @@ import { dirname, join } from "node:path";
433
563
  import { joinSession } from "@github/copilot-sdk/extension";
434
564
 
435
565
  const COMMAND = ${JSON.stringify(command)};
436
- // A listener that ends without a message (daemon not up yet, superseded) is retried after this long.
437
- const RETRY_MS = 30000;
566
+ // A listener that ends without a message (daemon not up yet, superseded) is retried, first soon,
567
+ // then less often, up to this long.
568
+ const RETRY_MIN_MS = 1000;
569
+ const RETRY_MAX_MS = 30000;
570
+ // On SIGTERM, wait at most this long for messages a listener already took to go back to the queue.
571
+ const QUIT_MS = 3000;
572
+
573
+ // The first PATH entry that holds this file.
574
+ const onPath = (name) => {
575
+ for (const dir of (process.env.PATH ?? "").split(";")) {
576
+ if (dir && existsSync(join(dir, name))) return join(dir, name);
577
+ }
578
+ return undefined;
579
+ };
438
580
 
439
581
  // A bare \`conveno\` on Windows is an npm .cmd shim. Run its node entry directly, so no shell is involved
440
- // and killing the child kills the listener. Only if the shim cannot be read is a shell used.
582
+ // and killing the child kills the listener. The node is the one the shim itself would run: node.exe
583
+ // next to the shim, else node.exe on PATH (npm cmd-shim). Not process.execPath: in a native Copilot
584
+ // build that is copilot.exe. Only if neither can be found is a shell used.
441
585
  const resolveCommand = () => {
442
586
  const [file, ...args] = COMMAND;
443
587
  if (process.platform !== "win32" || /\\.exe$/i.test(file)) return { file, args, shell: false };
444
588
  try {
445
- const dirs = /[\\/]/.test(file) ? [""] : (process.env.PATH ?? "").split(";");
589
+ const dirs = /[\\\\/]/.test(file) ? [""] : (process.env.PATH ?? "").split(";");
446
590
  for (const dir of dirs) {
447
591
  const shim = join(dir, /\\.cmd$/i.test(file) ? file : file + ".cmd");
448
592
  if (!existsSync(shim)) continue;
449
- const m = /"%(?:~dp0|dp0%)\\?([^"%]*\\.[cm]?js)"/i.exec(readFileSync(shim, "utf8"));
450
- if (m) return { file: process.execPath, args: [join(dirname(shim), m[1]), ...args], shell: false };
593
+ const m = /"%(?:~dp0|dp0%)\\\\?([^"%]*\\.[cm]?js)"/i.exec(readFileSync(shim, "utf8"));
594
+ if (!m) continue;
595
+ const local = join(dirname(shim), "node.exe");
596
+ const node = existsSync(local) ? local : onPath("node.exe");
597
+ if (node) return { file: node, args: [join(dirname(shim), m[1]), ...args], shell: false };
451
598
  }
452
599
  } catch {}
453
600
  return { file, args, shell: true };
@@ -487,8 +634,12 @@ const requeue = (ids) =>
487
634
  });
488
635
 
489
636
  let busy = false;
637
+ let quitting = false;
490
638
  let listener;
491
639
  let retry;
640
+ let retryMs = RETRY_MIN_MS;
641
+ // Listeners that have not finished putting back what they took. SIGTERM waits for them.
642
+ const endings = new Set();
492
643
 
493
644
  const stop = () => {
494
645
  clearTimeout(retry);
@@ -499,6 +650,12 @@ const stop = () => {
499
650
  kill(child);
500
651
  };
501
652
 
653
+ const later = () => {
654
+ if (quitting) return;
655
+ retry = setTimeout(arm, retryMs);
656
+ retryMs = Math.min(retryMs * 2, RETRY_MAX_MS);
657
+ };
658
+
502
659
  const send = async (text) => {
503
660
  for (let attempt = 0; attempt < 2; attempt++) {
504
661
  try {
@@ -512,7 +669,7 @@ const send = async (text) => {
512
669
  };
513
670
 
514
671
  const arm = () => {
515
- if (busy || listener) return;
672
+ if (busy || listener || quitting) return;
516
673
  const child = run(["hook", "copilot", "Listen"], ["pipe", "pipe", "ignore"]);
517
674
  listener = child;
518
675
  let out = "";
@@ -522,29 +679,40 @@ const arm = () => {
522
679
  out += chunk;
523
680
  });
524
681
  child.stdin.on("error", () => {});
525
- child.stdin.end(JSON.stringify({ hook_event_name: "Listen", sessionId: session.sessionId }));
682
+ // copilotPid: Copilot forks every extension, so the parent is the CLI that hosts the session.
683
+ child.stdin.end(
684
+ JSON.stringify({ hook_event_name: "Listen", sessionId: session.sessionId, copilotPid: process.ppid }),
685
+ );
526
686
  const finish = async (code) => {
527
687
  if (ended) return;
528
688
  ended = true;
529
689
  const current = listener === child;
530
690
  if (current) listener = undefined;
531
691
  const { ids, text } = split(out);
532
- // Whenever the output is not sent (stopped by a user turn, failed exit, busy), the daemon has
533
- // already handed these messages over, so put them back.
534
- if (!current || code !== 0 || !text || busy) {
692
+ // Whenever the output is not sent (stopped by a user turn, failed exit, busy, quitting), the
693
+ // daemon has already handed these messages over, so put them back.
694
+ if (!current || code !== 0 || !text || busy || quitting) {
535
695
  await requeue(ids);
536
- if (current && !busy && !listener) retry = setTimeout(arm, RETRY_MS);
696
+ if (current && !busy && !listener) later();
537
697
  return;
538
698
  }
539
699
  busy = true;
540
- if (!(await send(text))) {
541
- await requeue(ids);
542
- busy = false;
543
- retry = setTimeout(arm, RETRY_MS);
700
+ if (await send(text)) {
701
+ retryMs = RETRY_MIN_MS;
702
+ return;
544
703
  }
704
+ await requeue(ids);
705
+ busy = false;
706
+ later();
545
707
  };
546
- child.once("error", () => void finish(1));
547
- child.once("close", (code) => void finish(code));
708
+ let done;
709
+ const ending = new Promise((resolve) => {
710
+ done = resolve;
711
+ });
712
+ endings.add(ending);
713
+ void ending.then(() => endings.delete(ending));
714
+ child.once("error", () => done(finish(1)));
715
+ child.once("close", (code) => done(finish(code)));
548
716
  };
549
717
 
550
718
  session.on("user.message", () => {
@@ -560,8 +728,15 @@ session.on("session.idle", () => {
560
728
  arm();
561
729
  });
562
730
 
563
- const quit = () => {
731
+ // Stop the listener and let it put back what it took before exiting, within QUIT_MS.
732
+ const quit = async () => {
733
+ if (quitting) return;
734
+ quitting = true;
564
735
  stop();
736
+ await Promise.race([
737
+ Promise.all([...endings]),
738
+ new Promise((resolve) => setTimeout(resolve, QUIT_MS)),
739
+ ]);
565
740
  process.exit(0);
566
741
  };
567
742
  process.once("SIGTERM", quit);
@@ -571,28 +746,37 @@ process.once("disconnect", quit);
571
746
  arm();
572
747
  `;
573
748
  }
574
- const SERVER_NAME$3 = "conveno";
749
+ const SERVER_NAME$2 = "conveno";
575
750
  /**
576
- * `sessionStart` and `userPromptSubmitted` add context for the model; `postToolUse` adds waiting
577
- * messages in the middle of a turn; `preToolUse` allows Conveno's own MCP tools without a prompt;
578
- * `agentStop` ends a turn and continues with waiting messages.
751
+ * `sessionStart` adds context for the model; `userPromptSubmitted` marks the turn started (Copilot
752
+ * drops its output); `permissionRequest` allows Conveno's own MCP tools without a prompt;
753
+ * `postToolUse` adds waiting messages in the middle of a turn; `agentStop` ends a turn and
754
+ * continues with waiting messages.
579
755
  */
580
- const HOOK_EVENTS$2 = [
756
+ const HOOK_EVENTS$1 = [
581
757
  "sessionStart",
582
758
  "userPromptSubmitted",
583
- "preToolUse",
759
+ "permissionRequest",
584
760
  "postToolUse",
585
761
  "agentStop"
586
762
  ];
763
+ /** Events an older Conveno wrote and this one removes: `preToolUse` failed closed for every tool. */
764
+ const LEGACY_EVENTS = ["preToolUse"];
587
765
  /** The extension's listener: `conveno hook copilot Listen`. Not a Copilot hook event, so not in the hook file. */
588
766
  const LISTEN_EVENT = "Listen";
589
767
  /** First line of Listen's output: the ids of the handed-over messages. The extension strips it. */
590
768
  const IDS_LEAD = "#conveno-ids";
591
769
  /** The listener gives up on its own after this long; the extension starts a new one at the next idle. */
592
770
  const LISTEN_MAX_MS = 216e5;
771
+ /** How long Listen looks for its session: the extension can start before the MCP server registers it. */
772
+ const LISTEN_REGISTER_WAIT_MS = 6e4;
773
+ const LISTEN_REGISTER_POLL_MS = 1e3;
774
+ /** Asked by `conveno init` before the extension and `experimental` are set up. Default no. */
775
+ const IDLE_WAKE_OPTION = "copilot-idle-wake";
776
+ const IDLE_WAKE_QUESTION = "Copilot idle wake needs Copilot's experimental mode, which also turns on its other experimental features. Turn it on?";
593
777
  /** Our own hook file inside `~/.copilot/hooks/`, which Copilot reads as every `*.json` there. */
594
778
  const HOOK_FILE = "conveno.json";
595
- const EMPTY$3 = {
779
+ const EMPTY$2 = {
596
780
  stdout: "",
597
781
  exitCode: 0
598
782
  };
@@ -632,6 +816,7 @@ function powershellWord(arg) {
632
816
  * The hook entry. Copilot runs `bash` on macOS and Linux and `powershell` on Windows, and takes
633
817
  * the command as one string, so both are written whatever the platform of this install: the file
634
818
  * then stays right if the home directory is shared with a Windows machine through WSL.
819
+ * `permissionRequest` carries a matcher, so it runs only for Conveno's own tools.
635
820
  */
636
821
  function hookEntry$1(env, event) {
637
822
  const words = [
@@ -646,6 +831,7 @@ function hookEntry$1(env, event) {
646
831
  type: "command",
647
832
  bash: words.map(bashWord).join(" "),
648
833
  powershell: call + ps.join(" "),
834
+ ...event === "permissionRequest" ? { matcher: OWN_TOOL_MATCHER } : {},
649
835
  timeoutSec: 5
650
836
  };
651
837
  }
@@ -666,7 +852,7 @@ const desiredServer$1 = (env) => {
666
852
  };
667
853
  };
668
854
  /** Recognizes our hook command even if the conveno path changed since install. */
669
- const isOurCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook copilot (sessionStart|userPromptSubmitted|preToolUse|postToolUse|agentStop)$/.test(cmd.trim());
855
+ const isOurCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook copilot (sessionStart|userPromptSubmitted|permissionRequest|preToolUse|postToolUse|agentStop)$/.test(cmd.trim());
670
856
  const isOurEntry$1 = (e) => isObject$1(e) && [
671
857
  e.bash,
672
858
  e.powershell,
@@ -677,7 +863,7 @@ function entriesOf$1(hooks, event) {
677
863
  return Array.isArray(g) ? g : [];
678
864
  }
679
865
  function hasExactHook$1(hooks, event, want) {
680
- return entriesOf$1(hooks, event).some((e) => isObject$1(e) && e.bash === want.bash && e.powershell === want.powershell);
866
+ return entriesOf$1(hooks, event).some((e) => isObject$1(e) && e.bash === want.bash && e.powershell === want.powershell && e.matcher === want.matcher);
681
867
  }
682
868
  function hooksObject$1(file, path) {
683
869
  const h = file.hooks;
@@ -693,7 +879,7 @@ function mcpObject$1(config, path) {
693
879
  }
694
880
  /** `copilot --version` prints "GitHub Copilot CLI 1.0.117." with a full stop after the number. */
695
881
  const versionOf = (stdout) => parseCliVersion(stdout)?.replace(/\.+$/, "");
696
- async function detect$3(env) {
882
+ async function detect$2(env) {
697
883
  const p = paths$1(env);
698
884
  const configPaths = [
699
885
  p.mcp,
@@ -831,7 +1017,18 @@ async function uninstallExtension(env, baseline) {
831
1017
  }
832
1018
  return changes;
833
1019
  }
834
- async function plan$3(env) {
1020
+ /**
1021
+ * Is the idle-wake extension set up? Then `plan` keeps it up to date and `conveno init` does not
1022
+ * ask again.
1023
+ */
1024
+ async function idleWakeEnabled(env) {
1025
+ return (await readText$1(paths$1(env).extension))?.startsWith(EXTENSION_MARKER_PREFIX) === true;
1026
+ }
1027
+ /**
1028
+ * `accept` lists the optional parts the user said yes to (`IDLE_WAKE_OPTION`). Without it the
1029
+ * extension and `experimental` are left out, unless the extension is already there.
1030
+ */
1031
+ async function plan$2(env, opts = {}) {
835
1032
  const p = paths$1(env);
836
1033
  const changes = [];
837
1034
  const mcpFile = await loadJson$1(p.mcp);
@@ -847,46 +1044,49 @@ async function plan$3(env) {
847
1044
  path: p.mcp,
848
1045
  before: mcpFile.raw,
849
1046
  after: editJson$1(mcpFile, [{
850
- path: ["mcpServers", SERVER_NAME$3],
1047
+ path: ["mcpServers", SERVER_NAME$2],
851
1048
  value: want
852
1049
  }]),
853
- description: `Register the "${SERVER_NAME$3}" MCP server for Copilot CLI (conveno mcp --cli copilot).`,
1050
+ description: `Register the "${SERVER_NAME$2}" MCP server for Copilot CLI (conveno mcp --cli copilot).`,
854
1051
  viaCommand: [
855
1052
  "copilot",
856
1053
  "mcp",
857
1054
  "add",
858
- SERVER_NAME$3,
1055
+ SERVER_NAME$2,
859
1056
  "--",
860
1057
  ...mcpArgs$1(env)
861
1058
  ]
862
1059
  });
863
1060
  const hookFile = await loadJson$1(p.hooks);
864
1061
  const hooks = hooksObject$1(hookFile.value, p.hooks);
865
- const missing = HOOK_EVENTS$2.filter((e) => !hasExactHook$1(hooks, e, hookEntry$1(env, e)));
866
- if (missing.length > 0) {
1062
+ const missing = HOOK_EVENTS$1.filter((e) => !hasExactHook$1(hooks, e, hookEntry$1(env, e)));
1063
+ const legacy = LEGACY_EVENTS.filter((e) => entriesOf$1(hooks, e).some(isOurEntry$1));
1064
+ if (missing.length > 0 || legacy.length > 0) {
867
1065
  const edits = [];
868
1066
  if (hookFile.value.version === void 0) edits.push({
869
1067
  path: ["version"],
870
1068
  value: 1
871
1069
  });
872
1070
  for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry$1(env, e), isOurEntry$1));
873
- const installed = HOOK_EVENTS$2.some((e) => entriesOf$1(hooks, e).some(isOurEntry$1));
1071
+ for (const e of legacy) edits.push(...dropFromList(hooks[e], ["hooks", e], isOurEntry$1));
1072
+ const installed = [...HOOK_EVENTS$1, ...LEGACY_EVENTS].some((e) => entriesOf$1(hooks, e).some(isOurEntry$1));
874
1073
  changes.push({
875
1074
  component: "hooks",
876
1075
  kind: installed ? "update" : "add",
877
- parts: missing.map((e) => ({
1076
+ parts: [...missing, ...legacy].map((e) => ({
878
1077
  name: `${e} hook`,
879
- kind: entriesOf$1(hooks, e).some(isOurEntry$1) ? "update" : "add"
1078
+ kind: installed ? "update" : "add"
880
1079
  })),
881
1080
  path: p.hooks,
882
1081
  before: hookFile.raw,
883
1082
  after: editJson$1(hookFile, edits),
884
- description: `Add ${missing.join(", ")} hooks that deliver Conveno messages to Copilot CLI on the next turn and at the end of a turn.`
1083
+ description: missing.length > 0 ? `Add ${missing.join(", ")} hooks that deliver Conveno messages to Copilot CLI on the next turn and at the end of a turn.` : `Remove the old ${legacy.join(", ")} hook, which blocked every tool when conveno could not run.`
885
1084
  });
886
1085
  }
887
- return [...changes, ...await planExtension(env)];
1086
+ const extension = opts.accept?.includes("copilot-idle-wake") === true || await idleWakeEnabled(env);
1087
+ return [...changes, ...extension ? await planExtension(env) : []];
888
1088
  }
889
- async function uninstallPlan$3(env, baseline) {
1089
+ async function uninstallPlan$2(env, baseline) {
890
1090
  const p = paths$1(env);
891
1091
  const changes = [];
892
1092
  const mcpFile = await loadJson$1(p.mcp);
@@ -896,22 +1096,22 @@ async function uninstallPlan$3(env, baseline) {
896
1096
  path: p.mcp,
897
1097
  before: mcpFile.raw,
898
1098
  after: editJson$1(mcpFile, [{
899
- path: ["mcpServers", SERVER_NAME$3],
1099
+ path: ["mcpServers", SERVER_NAME$2],
900
1100
  value: void 0
901
1101
  }]),
902
- description: `Remove the "${SERVER_NAME$3}" MCP server.`,
1102
+ description: `Remove the "${SERVER_NAME$2}" MCP server.`,
903
1103
  viaCommand: [
904
1104
  "copilot",
905
1105
  "mcp",
906
1106
  "remove",
907
- SERVER_NAME$3
1107
+ SERVER_NAME$2
908
1108
  ]
909
1109
  });
910
1110
  const hookFile = await loadJson$1(p.hooks);
911
1111
  const hooks = hooksObject$1(hookFile.value, p.hooks);
912
1112
  const next = { ...hooks };
913
1113
  const edits = [];
914
- for (const e of HOOK_EVENTS$2) {
1114
+ for (const e of [...HOOK_EVENTS$1, ...LEGACY_EVENTS]) {
915
1115
  const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry$1, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
916
1116
  if (drops.length === 0) continue;
917
1117
  if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
@@ -928,14 +1128,19 @@ async function uninstallPlan$3(env, baseline) {
928
1128
  path: p.hooks,
929
1129
  before: hookFile.raw,
930
1130
  after: editJson$1(hookFile, edits),
931
- description: "Remove the Conveno sessionStart, userPromptSubmitted, preToolUse, postToolUse and agentStop hooks."
1131
+ description: "Remove the Conveno sessionStart, userPromptSubmitted, permissionRequest, postToolUse and agentStop hooks."
932
1132
  });
933
1133
  }
934
1134
  return [...changes, ...await uninstallExtension(env, baseline)];
935
1135
  }
936
- const isHookEvent$1 = (e) => HOOK_EVENTS$2.includes(e);
937
- /** The tools Conveno's MCP server offers (packages/mcp). */
938
- const OWN_TOOLS = /* @__PURE__ */ new Set([
1136
+ const isHookEvent$1 = (e) => HOOK_EVENTS$1.includes(e);
1137
+ /**
1138
+ * The `permissionRequest` matcher: Conveno's own MCP tools. Copilot names an MCP tool there
1139
+ * `<server>/<tool>` and anchors the matcher as `^(?:...)$`, so another server whose name starts
1140
+ * with "conveno" never matches (docs hooks-reference "permissionRequest decision control";
1141
+ * the 1.0.63 bundle builds the name as `${t.serverName}/${toolName}` for `kind: "mcp"`).
1142
+ */
1143
+ const OWN_TOOL_MATCHER = `${SERVER_NAME$2}/(${[
939
1144
  "whoami",
940
1145
  "list_sessions",
941
1146
  "send",
@@ -947,17 +1152,9 @@ const OWN_TOOLS = /* @__PURE__ */ new Set([
947
1152
  "orchestrate",
948
1153
  "handoff",
949
1154
  "spawn_session"
950
- ]);
951
- /**
952
- * Conveno's own MCP tools as Copilot names them: `conveno-send` for the model, `conveno/send`
953
- * inside Copilot (1.0.63 bundle). Only exact names match, so another server whose name starts
954
- * with "conveno" is never pre-approved.
955
- */
956
- const isOwnTool = (name) => {
957
- if (typeof name !== "string") return false;
958
- const m = /^conveno[-/]([a-z_]+)$/.exec(name);
959
- return m !== null && OWN_TOOLS.has(m[1] ?? "");
960
- };
1155
+ ].join("|")})`;
1156
+ const OWN_TOOL_RE = new RegExp(`^(?:${OWN_TOOL_MATCHER})$`);
1157
+ const isOwnTool = (name) => typeof name === "string" && OWN_TOOL_RE.test(name);
961
1158
  /**
962
1159
  * If Copilot sets `COPILOT_HOOK_DEPTH` on a run started from inside another hook or extension, that
963
1160
  * run's hooks deliver nothing: those messages belong to the outer session. Depth 1 is the session
@@ -965,12 +1162,71 @@ const isOwnTool = (name) => {
965
1162
  */
966
1163
  const nested = () => Number(process.env.COPILOT_HOOK_DEPTH ?? 0) > 1;
967
1164
  const field = (input, ...keys) => isObject$1(input) ? keys.map((k) => input[k]).find((v) => v !== void 0) : void 0;
1165
+ /** Copilot's own id for the session: `sessionId` in every hook input and in the extension's. */
1166
+ const copilotSessionId = (input) => {
1167
+ const id = field(input, "sessionId", "session_id");
1168
+ return typeof id === "string" && id !== "" ? id : void 0;
1169
+ };
1170
+ /**
1171
+ * A hook runs under the Copilot process that hosts the session, so its pid finds the session. Record
1172
+ * Copilot's session id on it, so the extension's Listen and Requeue, which run under the extension's
1173
+ * own process, find it by that id. Best effort.
1174
+ */
1175
+ async function recordSessionId(ctx, id) {
1176
+ if (id === void 0) return;
1177
+ try {
1178
+ const session = await ownSession(ctx);
1179
+ if (session && session.nativeId !== id) await ctx.client["session.setNative"]({
1180
+ sessionId: session.id,
1181
+ nativeId: id
1182
+ });
1183
+ } catch {}
1184
+ }
1185
+ /**
1186
+ * Listen's session: the one that holds Copilot's session id. Until a hook has recorded that id, the
1187
+ * session is found by `copilotPid`, the CLI the extension was forked from, and the id is recorded
1188
+ * then. Looks again until the MCP server has registered the session or `LISTEN_REGISTER_WAIT_MS`
1189
+ * passes. False when there is none.
1190
+ */
1191
+ async function claimSession(ctx, id, copilotPid) {
1192
+ const until = Date.now() + LISTEN_REGISTER_WAIT_MS;
1193
+ for (;;) {
1194
+ try {
1195
+ if (await ownSession({
1196
+ ...ctx,
1197
+ nativeId: id
1198
+ })) return true;
1199
+ if (typeof copilotPid === "number" && Number.isInteger(copilotPid) && copilotPid > 0) {
1200
+ const { nativeId: _, ...byPid } = ctx;
1201
+ const session = await ownSession({
1202
+ ...byPid,
1203
+ hostPid: copilotPid
1204
+ });
1205
+ if (session) {
1206
+ await ctx.client["session.setNative"]({
1207
+ sessionId: session.id,
1208
+ nativeId: id
1209
+ });
1210
+ return true;
1211
+ }
1212
+ }
1213
+ } catch {
1214
+ return false;
1215
+ }
1216
+ if (Date.now() + LISTEN_REGISTER_POLL_MS > until) return false;
1217
+ if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return false;
1218
+ await new Promise((r) => setTimeout(r, LISTEN_REGISTER_POLL_MS));
1219
+ }
1220
+ }
968
1221
  /**
969
- * - sessionStart, userPromptSubmitted: `{ "additionalContext": "<text>" }`. `sessionStart` adds it
970
- * as a first message of the session; `userPromptSubmitted` adds it to the prompt being submitted
971
- * and marks the turn started.
972
- * - preToolUse: `{ "permissionDecision": "allow" }` for Conveno's own MCP tools, so a session never
973
- * waits on a prompt to read or send a message. Nothing for any other tool.
1222
+ * - sessionStart: waiting messages as `{ "additionalContext": "<text>" }`, added as a first message
1223
+ * of the session.
1224
+ * - userPromptSubmitted: marks the turn started. Nothing is delivered: Copilot drops the output of
1225
+ * command `userPromptSubmitted` hooks (docs hooks-reference, `userPromptSubmitted` note), so a
1226
+ * message taken there would be lost.
1227
+ * - permissionRequest: `{ "behavior": "allow" }` for Conveno's own MCP tools, so a session never
1228
+ * waits on a prompt to read or send a message. Its matcher keeps it to those tools, and a failing
1229
+ * `permissionRequest` hook falls through to the normal prompt (only exit 2 denies).
974
1230
  * - postToolUse: waiting messages as `additionalContext`, which Copilot appends to the tool result
975
1231
  * so the model sees them on the same turn (10 KB cap).
976
1232
  * - agentStop: records the turn end. With messages waiting, `decision: "block"` with
@@ -981,13 +1237,27 @@ const field = (input, ...keys) => isObject$1(input) ? keys.map((k) => input[k]).
981
1237
  * and then the framed messages (plain text, exit 0); the extension strips the first line and sends
982
1238
  * the rest with `session.send`. Nothing when it stops for any other reason.
983
1239
  * - Requeue: the extension's `session.send` failed; puts the messages (`ids` in the input) back to queued.
1240
+ * The hooks record Copilot's `sessionId` on the session; Listen and Requeue run under the
1241
+ * extension's process, not Copilot's, so they find the session by that id.
984
1242
  * Never throws and never writes to stderr: any failure means "deliver nothing this time".
985
1243
  */
986
- async function hook$3(event, input, ctx) {
987
- if (nested()) return EMPTY$3;
1244
+ /**
1245
+ * Copilot caps a hook's `additionalContext` at 10 KB (docs hooks-reference, `postToolUse`). The
1246
+ * budget counts characters, so 4,500 keeps text of up to two UTF-8 bytes a character under it.
1247
+ * Messages past it stay queued for the next tool call or turn end.
1248
+ */
1249
+ const CONTEXT_MAX_CHARS = 4500;
1250
+ async function hook$2(event, input, ctx) {
1251
+ if (nested()) return EMPTY$2;
1252
+ const id = copilotSessionId(input);
988
1253
  if (event === "Listen") {
989
- const r = await waitForWorkBatch(ctx, { maxMs: LISTEN_MAX_MS });
990
- if (r === null) return EMPTY$3;
1254
+ if (id === void 0) return EMPTY$2;
1255
+ if (!await claimSession(ctx, id, field(input, "copilotPid"))) return EMPTY$2;
1256
+ const r = await waitForWorkBatch({
1257
+ ...ctx,
1258
+ nativeId: id
1259
+ }, { maxMs: LISTEN_MAX_MS });
1260
+ if (r === null) return EMPTY$2;
991
1261
  const ids = r.batch.messages.map((m) => m.id);
992
1262
  return {
993
1263
  stdout: (ids.length > 0 ? `${IDS_LEAD} ${ids.join(",")}\n` : "") + r.batch.text,
@@ -995,20 +1265,28 @@ async function hook$3(event, input, ctx) {
995
1265
  };
996
1266
  }
997
1267
  if (event === "Requeue") {
998
- await requeue$1(ctx, input);
999
- return EMPTY$3;
1268
+ if (id !== void 0) await requeue$1({
1269
+ ...ctx,
1270
+ nativeId: id
1271
+ }, input);
1272
+ return EMPTY$2;
1000
1273
  }
1001
- if (!isHookEvent$1(event)) return EMPTY$3;
1002
- if (event === "preToolUse") {
1003
- if (!isOwnTool(field(input, "toolName", "tool_name"))) return EMPTY$3;
1274
+ if (!isHookEvent$1(event)) return EMPTY$2;
1275
+ if (event === "permissionRequest") {
1276
+ if (!isOwnTool(field(input, "toolName", "tool_name"))) return EMPTY$2;
1004
1277
  return {
1005
- stdout: JSON.stringify({ permissionDecision: "allow" }),
1278
+ stdout: JSON.stringify({ behavior: "allow" }),
1006
1279
  exitCode: 0
1007
1280
  };
1008
1281
  }
1282
+ await recordSessionId(ctx, id);
1283
+ if (event === "userPromptSubmitted") {
1284
+ await startTurn(ctx);
1285
+ return EMPTY$2;
1286
+ }
1009
1287
  if (event === "agentStop") {
1010
1288
  const reason = await endTurnContinuation(ctx);
1011
- if (reason === null) return EMPTY$3;
1289
+ if (reason === null) return EMPTY$2;
1012
1290
  return {
1013
1291
  stdout: JSON.stringify({
1014
1292
  decision: "block",
@@ -1017,25 +1295,43 @@ async function hook$3(event, input, ctx) {
1017
1295
  exitCode: 0
1018
1296
  };
1019
1297
  }
1020
- const additionalContext = event === "userPromptSubmitted" ? await startTurnContext(ctx) : await pendingHookContext(ctx);
1021
- if (additionalContext === null) return EMPTY$3;
1298
+ const additionalContext = await pendingHookContext(ctx, { maxChars: CONTEXT_MAX_CHARS });
1299
+ if (additionalContext === null) return EMPTY$2;
1022
1300
  return {
1023
1301
  stdout: JSON.stringify({ additionalContext }),
1024
1302
  exitCode: 0
1025
1303
  };
1026
1304
  }
1027
- /** `Requeue`: sending failed, so the messages go back to queued for the next turn. */
1028
- async function requeue$1(ctx, input) {
1305
+ /** A typed prompt starts a turn: the session is busy, and what it sends starts a new chain. */
1306
+ async function startTurn(ctx) {
1029
1307
  try {
1030
- const ids = field(input, "ids");
1031
- if (!Array.isArray(ids) || ids.length === 0) return;
1032
1308
  const session = await ownSession(ctx);
1033
- if (!session) return;
1034
- await ctx.client["message.requeue"]({
1035
- sessionId: session.id,
1036
- ids
1037
- });
1309
+ if (session) await ctx.client["turn.start"]({ sessionId: session.id });
1310
+ } catch {}
1311
+ }
1312
+ /**
1313
+ * `Requeue`: sending failed, so the messages go back to queued for the next turn. Copilot may be
1314
+ * exiting and have unregistered the session already, so a session that just went offline counts.
1315
+ */
1316
+ async function requeue$1(ctx, input) {
1317
+ const ids = field(input, "ids");
1318
+ if (!Array.isArray(ids) || !ids.every((i) => typeof i === "string")) return;
1319
+ await requeueOwnMessages(ctx, ids);
1320
+ }
1321
+ /**
1322
+ * Things `conveno doctor` should tell the user about the idle-wake extension: Copilot asks once
1323
+ * before it starts an extension (docs cli-command-reference, extensions: "Each extension requires
1324
+ * approval before it launches"), and with `extensions.enabled` false in settings.json (docs
1325
+ * cli-config-dir-reference, `extensions/`) it never starts. Empty without the extension.
1326
+ */
1327
+ async function doctorNotes(env) {
1328
+ if (!await idleWakeEnabled(env)) return [];
1329
+ const notes = ["Copilot asks once to approve the Conveno extension. Approve it, or idle sessions do not wake."];
1330
+ try {
1331
+ const ext = (await loadJson$1(paths$1(env).settings)).value.extensions;
1332
+ if (isObject$1(ext) && ext.enabled === false) notes.push("Copilot extensions are off (\"extensions\": { \"enabled\": false } in settings.json), so idle sessions do not wake. Turn them on with /extensions in Copilot.");
1038
1333
  } catch {}
1334
+ return notes;
1039
1335
  }
1040
1336
  const copilotAdapter = {
1041
1337
  cli: "copilot",
@@ -1046,27 +1342,33 @@ const copilotAdapter = {
1046
1342
  endOfTurn: true,
1047
1343
  idleWake: true
1048
1344
  }),
1049
- detect: detect$3,
1050
- plan: plan$3,
1051
- uninstallPlan: uninstallPlan$3,
1052
- hook: hook$3,
1053
- listenEvents: [LISTEN_EVENT]
1345
+ detect: detect$2,
1346
+ plan: plan$2,
1347
+ uninstallPlan: uninstallPlan$2,
1348
+ hook: hook$2,
1349
+ listenEvents: [LISTEN_EVENT],
1350
+ optional: [{
1351
+ id: IDLE_WAKE_OPTION,
1352
+ question: IDLE_WAKE_QUESTION,
1353
+ enabled: idleWakeEnabled
1354
+ }],
1355
+ doctorNotes
1054
1356
  };
1055
1357
  // ../adapters/cursor/dist/index.js
1056
- const SERVER_NAME$2 = "conveno";
1358
+ const SERVER_NAME$1 = "conveno";
1057
1359
  /**
1058
1360
  * Hooks that can add context to the conversation: `sessionStart` for a new chat and `postToolUse`
1059
1361
  * after each tool call. `beforeSubmitPrompt` is not here because it can only allow or block a
1060
1362
  * prompt, never add to it. `stop` ends a turn and, continues with waiting messages.
1061
1363
  */
1062
- const HOOK_EVENTS$1 = [
1364
+ const HOOK_EVENTS = [
1063
1365
  "sessionStart",
1064
1366
  "postToolUse",
1065
1367
  "stop"
1066
1368
  ];
1067
1369
  /** The `permissions.allow` token that lets the agent call every tool of the conveno server. */
1068
- const MCP_PERMISSION = `Mcp(${SERVER_NAME$2}:*)`;
1069
- const EMPTY$2 = {
1370
+ const MCP_PERMISSION = `Mcp(${SERVER_NAME$1}:*)`;
1371
+ const EMPTY$1 = {
1070
1372
  stdout: "",
1071
1373
  exitCode: 0
1072
1374
  };
@@ -1087,33 +1389,30 @@ function paths(env) {
1087
1389
  };
1088
1390
  }
1089
1391
  /**
1090
- * Quote one word of a hook command. On Windows the desktop app runs hook commands through
1091
- * PowerShell, so words are written for PowerShell: single quotes, and forward slashes in paths
1092
- * (Windows accepts `/` everywhere, and it keeps `\` away from every quoting rule). Elsewhere the
1093
- * command runs in a POSIX shell.
1392
+ * Quote one word of a hook command. Cursor runs every hook command through a POSIX shell, on
1393
+ * Windows too (Git Bash): the bundle's `hookCommandsArePowerShell()` is `false` and the payload is
1394
+ * appended as `<command> <<'CURSOR_HOOK_EOF' ...` (cursor-agent 2026.11.22 4721.index.js,
1395
+ * `executeCommandScript`). So words get POSIX single quotes everywhere. On Windows, `\` becomes
1396
+ * `/` first: bash would read a backslash as an escape, and Windows accepts `/` in paths.
1094
1397
  */
1095
1398
  function quoteWord(arg, platform) {
1096
- if (platform === "win32") {
1097
- const word = arg.replace(/\\/g, "/");
1098
- return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "''")}'`;
1099
- }
1100
- return /^[A-Za-z0-9_@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
1399
+ const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
1400
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
1101
1401
  }
1102
- function hookCommand$1(env, event) {
1103
- const words = [
1402
+ function hookCommand(env, event) {
1403
+ return [
1104
1404
  ...env.conveno.command,
1105
1405
  "hook",
1106
1406
  "cursor",
1107
1407
  event
1108
- ].map((w) => quoteWord(w, env.platform));
1109
- return (env.platform === "win32" && /^'/.test(words[0] ?? "") ? "& " : "") + words.join(" ");
1408
+ ].map((w) => quoteWord(w, env.platform)).join(" ");
1110
1409
  }
1111
1410
  /**
1112
1411
  * `stop` sets `loop_limit: null`: Cursor's own cap (5 follow-ups by default) would end the loop
1113
1412
  * for the conversation, and Conveno's own auto-mode limit already bounds it.
1114
1413
  */
1115
1414
  const hookEntry = (env, event) => ({
1116
- command: hookCommand$1(env, event),
1415
+ command: hookCommand(env, event),
1117
1416
  timeout: 5,
1118
1417
  ...event === "stop" ? { loop_limit: null } : {}
1119
1418
  });
@@ -1132,8 +1431,8 @@ const desiredServer = (env) => {
1132
1431
  };
1133
1432
  };
1134
1433
  /** Recognizes our hook command even if the conveno path changed since install. */
1135
- const isOurHookCommand$1 = (cmd) => typeof cmd === "string" && /(^|\s)hook cursor (sessionStart|postToolUse|stop)$/.test(cmd.trim());
1136
- const isOurEntry = (e) => isObject$1(e) && isOurHookCommand$1(e.command);
1434
+ const isOurHookCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook cursor (sessionStart|postToolUse|stop)$/.test(cmd.trim());
1435
+ const isOurEntry = (e) => isObject$1(e) && isOurHookCommand(e.command);
1137
1436
  function entriesOf(hooks, event) {
1138
1437
  const g = hooks[event];
1139
1438
  return Array.isArray(g) ? g : [];
@@ -1161,7 +1460,7 @@ function allowList(config, path) {
1161
1460
  if (!Array.isArray(a)) throw new Error(`"permissions.allow" in ${path} must be an array. Fix the file, then run the install again. Nothing was changed.`);
1162
1461
  return a;
1163
1462
  }
1164
- async function detect$2(env) {
1463
+ async function detect$1(env) {
1165
1464
  const p = paths(env);
1166
1465
  const configPaths = [
1167
1466
  p.mcp,
@@ -1185,7 +1484,7 @@ async function detect$2(env) {
1185
1484
  configPaths
1186
1485
  };
1187
1486
  }
1188
- async function plan$2(env) {
1487
+ async function plan$1(env) {
1189
1488
  const p = paths(env);
1190
1489
  const changes = [];
1191
1490
  const mcpFile = await loadJson$1(p.mcp);
@@ -1201,10 +1500,10 @@ async function plan$2(env) {
1201
1500
  path: p.mcp,
1202
1501
  before: mcpFile.raw,
1203
1502
  after: editJson$1(mcpFile, [{
1204
- path: ["mcpServers", SERVER_NAME$2],
1503
+ path: ["mcpServers", SERVER_NAME$1],
1205
1504
  value: want
1206
1505
  }]),
1207
- description: `Register the "${SERVER_NAME$2}" MCP server for the Cursor CLI (conveno mcp --cli cursor).`
1506
+ description: `Register the "${SERVER_NAME$1}" MCP server for the Cursor CLI (conveno mcp --cli cursor).`
1208
1507
  });
1209
1508
  const cfgFile = await loadJson$1(p.cliConfig);
1210
1509
  const allow = allowList(cfgFile.value, p.cliConfig);
@@ -1253,12 +1552,12 @@ async function plan$2(env) {
1253
1552
  path: p.cliConfig,
1254
1553
  before: cfgFile.raw,
1255
1554
  after: editJson$1(cfgFile, edits),
1256
- description: `Allow the agent to call the "${SERVER_NAME$2}" server's tools without asking (${MCP_PERMISSION}). They only exchange messages between your own sessions.`
1555
+ description: `Allow the agent to call the "${SERVER_NAME$1}" server's tools without asking (${MCP_PERMISSION}). They only exchange messages between your own sessions.`
1257
1556
  });
1258
1557
  }
1259
1558
  const hookFile = await loadJson$1(p.hooks);
1260
1559
  const hooks = hooksObject(hookFile.value, p.hooks);
1261
- const missing = HOOK_EVENTS$1.filter((e) => !hasExactHook(hooks, e, hookEntry(env, e)));
1560
+ const missing = HOOK_EVENTS.filter((e) => !hasExactHook(hooks, e, hookEntry(env, e)));
1262
1561
  if (missing.length > 0) {
1263
1562
  const edits = [];
1264
1563
  if (hookFile.value.version === void 0) edits.push({
@@ -1266,7 +1565,7 @@ async function plan$2(env) {
1266
1565
  value: 1
1267
1566
  });
1268
1567
  for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry(env, e), isOurEntry));
1269
- const installed = HOOK_EVENTS$1.some((e) => entriesOf(hooks, e).some(isOurEntry));
1568
+ const installed = HOOK_EVENTS.some((e) => entriesOf(hooks, e).some(isOurEntry));
1270
1569
  changes.push({
1271
1570
  component: "hooks",
1272
1571
  kind: installed ? "update" : "add",
@@ -1282,7 +1581,7 @@ async function plan$2(env) {
1282
1581
  }
1283
1582
  return changes;
1284
1583
  }
1285
- async function uninstallPlan$2(env, baseline) {
1584
+ async function uninstallPlan$1(env, baseline) {
1286
1585
  const p = paths(env);
1287
1586
  const changes = [];
1288
1587
  const mcpFile = await loadJson$1(p.mcp);
@@ -1292,10 +1591,10 @@ async function uninstallPlan$2(env, baseline) {
1292
1591
  path: p.mcp,
1293
1592
  before: mcpFile.raw,
1294
1593
  after: editJson$1(mcpFile, [{
1295
- path: ["mcpServers", SERVER_NAME$2],
1594
+ path: ["mcpServers", SERVER_NAME$1],
1296
1595
  value: void 0
1297
1596
  }]),
1298
- description: `Remove the "${SERVER_NAME$2}" MCP server.`
1597
+ description: `Remove the "${SERVER_NAME$1}" MCP server.`
1299
1598
  });
1300
1599
  const cfgFile = await loadJson$1(p.cliConfig);
1301
1600
  const at = (allowList(cfgFile.value, p.cliConfig) ?? []).flatMap((x, i) => x === "Mcp(conveno:*)" ? [i] : []);
@@ -1318,7 +1617,7 @@ async function uninstallPlan$2(env, baseline) {
1318
1617
  const hooks = hooksObject(hookFile.value, p.hooks);
1319
1618
  const next = { ...hooks };
1320
1619
  const edits = [];
1321
- for (const e of HOOK_EVENTS$1) {
1620
+ for (const e of HOOK_EVENTS) {
1322
1621
  const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
1323
1622
  if (drops.length === 0) continue;
1324
1623
  if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
@@ -1340,7 +1639,7 @@ async function uninstallPlan$2(env, baseline) {
1340
1639
  }
1341
1640
  return changes;
1342
1641
  }
1343
- const isHookEvent = (e) => HOOK_EVENTS$1.includes(e);
1642
+ const isHookEvent = (e) => HOOK_EVENTS.includes(e);
1344
1643
  /**
1345
1644
  * - sessionStart, postToolUse: `{ "additional_context": "<text>" }`, added to the chat's initial
1346
1645
  * context or to the conversation after the tool result.
@@ -1348,26 +1647,49 @@ const isHookEvent = (e) => HOOK_EVENTS$1.includes(e);
1348
1647
  * `{ "followup_message": "<text>" }`, which Cursor submits as the next user message. An aborted
1349
1648
  * or failed turn never continues. Like Codex, Cursor has no idle wake, so this also runs on a
1350
1649
  * turn that was itself a follow-up; Conveno's auto-mode limit bounds the chain.
1650
+ * cursor-agent 2026.11.22 sends `completed` even after Esc and then does not submit the follow-up
1651
+ * (7000.index.js), so `status` cannot catch every abort; see the README.
1351
1652
  * Never throws and never writes to stderr: any failure means "deliver nothing this time".
1352
1653
  */
1353
- async function hook$2(event, input, ctx) {
1354
- if (!isHookEvent(event)) return EMPTY$2;
1654
+ async function hook$1(event, input, ctx) {
1655
+ if (!isHookEvent(event)) return EMPTY$1;
1656
+ await recordConversationId(input, ctx);
1355
1657
  if (event === "stop") {
1356
1658
  const status = isObject$1(input) ? input.status : void 0;
1357
1659
  const followup = await endTurnContinuation(ctx, { allowContinue: status === void 0 || status === "completed" });
1358
- if (followup === null) return EMPTY$2;
1660
+ if (followup === null) return EMPTY$1;
1359
1661
  return {
1360
1662
  stdout: JSON.stringify({ followup_message: followup }),
1361
1663
  exitCode: 0
1362
1664
  };
1363
1665
  }
1364
1666
  const additionalContext = await pendingHookContext(ctx);
1365
- if (additionalContext === null) return EMPTY$2;
1667
+ if (additionalContext === null) return EMPTY$1;
1366
1668
  return {
1367
1669
  stdout: JSON.stringify({ additional_context: additionalContext }),
1368
1670
  exitCode: 0
1369
1671
  };
1370
1672
  }
1673
+ /**
1674
+ * Every hook input carries `conversation_id`, stable across a chat's turns
1675
+ * (https://cursor.com/docs/hooks.md, "Input (all hooks)"). Tell the daemon, so it knows the CLI's
1676
+ * own id for the session. The lookup itself stays by process: the first hook of a new chat (`/new`
1677
+ * in the same process) holds an id the daemon has not seen, and a lookup by that id would miss.
1678
+ * Best effort; an older daemon without `session.setNative` keeps the pid lookup.
1679
+ */
1680
+ async function recordConversationId(input, ctx) {
1681
+ const id = isObject$1(input) ? input.conversation_id : void 0;
1682
+ if (typeof id !== "string" || id === "") return;
1683
+ try {
1684
+ const session = await ownSession(ctx);
1685
+ if (!session || session.nativeId === id) return;
1686
+ const call = ctx.client["session.setNative"];
1687
+ if (typeof call === "function") await call({
1688
+ sessionId: session.id,
1689
+ nativeId: id
1690
+ });
1691
+ } catch {}
1692
+ }
1371
1693
  const cursorAdapter = {
1372
1694
  cli: "cursor",
1373
1695
  displayName: "Cursor CLI",
@@ -1377,522 +1699,6 @@ const cursorAdapter = {
1377
1699
  endOfTurn: true,
1378
1700
  idleWake: false
1379
1701
  }),
1380
- detect: detect$2,
1381
- plan: plan$2,
1382
- uninstallPlan: uninstallPlan$2,
1383
- hook: hook$2
1384
- };
1385
- // ../adapters/grok/dist/index.js
1386
- const SERVER_NAME$1 = "conveno";
1387
- /** The pattern of the allow rule: every tool of our server, in Grok's `server__tool` spelling. */
1388
- const RULE_PATTERN = `${SERVER_NAME$1}__*`;
1389
- var ConfigParseError = class extends Error {};
1390
- function parseToml(path, text) {
1391
- try {
1392
- return cs(text);
1393
- } catch (err) {
1394
- throw new ConfigParseError(`Cannot parse ${path} as TOML (${err instanceof Error ? err.message : String(err)}). Fix or move the file, then run conveno again. Conveno did not change it.`);
1395
- }
1396
- }
1397
- const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1398
- function serverOf(doc) {
1399
- const ours = isTable(doc.mcp_servers) ? doc.mcp_servers[SERVER_NAME$1] : void 0;
1400
- return isTable(ours) ? ours : void 0;
1401
- }
1402
- const matchesSpec = (server, spec) => server !== void 0 && server.command === spec.command && JSON.stringify(server.args) === JSON.stringify(spec.args);
1403
- /** True for the MCP allow rule Conveno writes. Extra keys on the rule make it someone else's. */
1404
- const isMcpRule = (r) => isTable(r) && r.action === "allow" && r.tool === "mcp" && r.pattern === "conveno__*" && Object.keys(r).length === 3;
1405
- /** Tail of the watch rule Conveno writes: one session name starting with a letter or digit. */
1406
- const WATCH_TAIL = " watch [a-z0-9]*";
1407
- /**
1408
- * True for an allow rule that lets Conveno's `watch` command run without a prompt: a bash rule
1409
- * whose pattern is `<conveno command> watch [a-z0-9]*` (or, with `pattern`, any exact
1410
- * string, such as the older `... watch *`). Without `pattern`, any conveno path, which only install
1411
- * uses to replace a stale rule after a move; uninstall always passes exact patterns (`isOurRule`).
1412
- */
1413
- const isWatchRule = (r, pattern) => isTable(r) && r.action === "allow" && r.tool === "bash" && typeof r.pattern === "string" && Object.keys(r).length === 3 && (pattern === void 0 ? r.pattern.endsWith(" watch [a-z0-9]*") : r.pattern === pattern);
1414
- /** Either of the allow rules Conveno wrote, the watch one only if its pattern is one of `watchPatterns`. */
1415
- const isOurRule = (r, watchPatterns) => isMcpRule(r) || watchPatterns.some((p) => isWatchRule(r, p));
1416
- function rulesOf(doc) {
1417
- const rules = isTable(doc.permission) ? doc.permission.rules : void 0;
1418
- return Array.isArray(rules) ? rules : void 0;
1419
- }
1420
- /** True when the MCP rule and the exact watch rule are both there. */
1421
- const hasRules = (doc, watchPattern) => {
1422
- const rules = rulesOf(doc) ?? [];
1423
- return rules.some(isMcpRule) && rules.some((r) => isWatchRule(r, watchPattern));
1424
- };
1425
- /** True when any rule of ours is there (the watch rule only with one of `watchPatterns`). */
1426
- const hasAnyRule = (doc, watchPatterns) => rulesOf(doc)?.some((r) => isOurRule(r, watchPatterns)) ?? false;
1427
- const eolOf = (text) => text.includes("\r\n") ? "\r\n" : "\n";
1428
- /** TOML basic strings use the same escapes as JSON for everything we write. */
1429
- const q = (s) => JSON.stringify(s);
1430
- function serverText(spec, eol) {
1431
- return [
1432
- `[mcp_servers.${SERVER_NAME$1}]`,
1433
- `command = ${q(spec.command)}`,
1434
- `args = [${spec.args.map(q).join(", ")}]`,
1435
- ""
1436
- ].join(eol);
1437
- }
1438
- function ruleText(eol, tool, pattern) {
1439
- return [
1440
- "[[permission.rules]]",
1441
- "action = \"allow\"",
1442
- `tool = ${q(tool)}`,
1443
- `pattern = ${q(pattern)}`,
1444
- ""
1445
- ].join(eol);
1446
- }
1447
- const EMPTYABLE = /* @__PURE__ */ new Set([
1448
- "mcp_servers",
1449
- "permission",
1450
- "rules"
1451
- ]);
1452
- /** A copy of `v` in which an emptied `mcp_servers`, `permission` or `rules` is gone, children first. */
1453
- function prune(v) {
1454
- if (Array.isArray(v)) return v.map(prune);
1455
- if (!isTable(v)) return v;
1456
- const out = {};
1457
- for (const [k, child] of Object.entries(v)) {
1458
- const p = prune(child);
1459
- if (!((Array.isArray(p) && p.length === 0 || isTable(p) && Object.keys(p).length === 0) && EMPTYABLE.has(k))) out[k] = p;
1460
- }
1461
- return out;
1462
- }
1463
- /** Compare parsed data, treating an emptied `mcp_servers`, `permission` or `rules` as missing. */
1464
- const sameData = (a, b) => JSON.stringify(prune(a)) === JSON.stringify(prune(b));
1465
- /** `text` with a header line as the start of each section. The first one has no header. */
1466
- function sections(text) {
1467
- const out = [{
1468
- key: null,
1469
- text: ""
1470
- }];
1471
- for (const line of text.split(/(?<=\n)/)) {
1472
- const m = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/.exec(line.replace(/\r?\n$/, ""));
1473
- if (m) out.push({
1474
- key: m[1].replace(/["'\s]/g, ""),
1475
- text: line
1476
- });
1477
- else out.at(-1).text += line;
1478
- }
1479
- return out;
1480
- }
1481
- /**
1482
- * Drop the sections whose header is `key` (or a subtable of it) and for which `drop` returns true.
1483
- * The blank line that separated a dropped last section from the rest goes with it.
1484
- */
1485
- function dropSections(text, keys, drop) {
1486
- const all = sections(text);
1487
- let lastDropped = false;
1488
- let out = all.filter((s, i) => {
1489
- const hit = s.key !== null && keys.some((k) => s.key === k || s.key?.startsWith(`${k}.`)) && drop(s.text);
1490
- if (i === all.length - 1) lastDropped = hit;
1491
- return !hit;
1492
- }).map((s) => s.text).join("");
1493
- if (lastDropped) out = out.replace(/(\r?\n)+$/, "") + (out.trim() === "" ? "" : eolOf(text));
1494
- return out;
1495
- }
1496
- const parsesTo = (text, expected) => {
1497
- try {
1498
- return sameData(cs(text), expected);
1499
- } catch {
1500
- return false;
1501
- }
1502
- };
1503
- /** Drop the `[[permission.rules]]` sections that hold one of our watch rules, other than `keep`. */
1504
- function dropStaleWatchRules(text, keep) {
1505
- return dropSections(text, ["permission.rules"], (section) => {
1506
- try {
1507
- const rule = cs(section).permission?.rules;
1508
- return rule?.length === 1 && isWatchRule(rule[0]) && !isWatchRule(rule[0], keep);
1509
- } catch {
1510
- return false;
1511
- }
1512
- });
1513
- }
1514
- /**
1515
- * Add our server table and our two allow rules (the MCP tools, and the `watch` command at
1516
- * `watchPattern`) where they are missing, by appending text to the file. A watch rule for another
1517
- * conveno path is replaced. If the result does not parse to the expected data (for example the user
1518
- * already defines the rules as an inline `rules = [...]`), fall back to a comment-preserving patch.
1519
- */
1520
- function addConfig(path, before, spec, watchPattern) {
1521
- const doc = parseToml(path, before);
1522
- const expected = structuredClone(doc);
1523
- const servers = isTable(expected.mcp_servers) ? expected.mcp_servers : {};
1524
- servers[SERVER_NAME$1] = {
1525
- command: spec.command,
1526
- args: spec.args
1527
- };
1528
- expected.mcp_servers = servers;
1529
- const permission = isTable(expected.permission) ? expected.permission : {};
1530
- const rules = (Array.isArray(permission.rules) ? permission.rules : []).filter((r) => !isWatchRule(r) || isWatchRule(r, watchPattern));
1531
- if (!rules.some(isMcpRule)) rules.push({
1532
- action: "allow",
1533
- tool: "mcp",
1534
- pattern: RULE_PATTERN
1535
- });
1536
- if (!rules.some((r) => isWatchRule(r, watchPattern))) rules.push({
1537
- action: "allow",
1538
- tool: "bash",
1539
- pattern: watchPattern
1540
- });
1541
- permission.rules = rules;
1542
- expected.permission = permission;
1543
- const eol = eolOf(before);
1544
- const needServer = !matchesSpec(serverOf(doc), spec);
1545
- let text = needServer && serverOf(doc) ? removeServerText(before) : before;
1546
- text = dropStaleWatchRules(text, watchPattern);
1547
- const rulesBefore = rulesOf(doc) ?? [];
1548
- const append = (block) => {
1549
- const sep = text === "" ? "" : text.endsWith("\n") ? eol : eol + eol;
1550
- text = text + sep + block;
1551
- };
1552
- if (needServer) append(serverText(spec, eol));
1553
- if (!rulesBefore.some(isMcpRule)) append(ruleText(eol, "mcp", RULE_PATTERN));
1554
- if (!rulesBefore.some((r) => isWatchRule(r, watchPattern))) append(ruleText(eol, "bash", watchPattern));
1555
- if (parsesTo(text, expected)) return text;
1556
- return Za(before, expected);
1557
- }
1558
- function removeServerText(text) {
1559
- return dropSections(text, [`mcp_servers.${SERVER_NAME$1}`], () => true);
1560
- }
1561
- /** Remove our server table (and its subtables) and the allow rules Conveno wrote, matched exactly. Everything else stays byte for byte. */
1562
- function removeConfig(path, before, watchPatterns) {
1563
- const doc = parseToml(path, before);
1564
- const expected = structuredClone(doc);
1565
- if (isTable(expected.mcp_servers)) delete expected.mcp_servers[SERVER_NAME$1];
1566
- const rules = rulesOf(expected);
1567
- if (rules && isTable(expected.permission)) expected.permission.rules = rules.filter((r) => !isOurRule(r, watchPatterns));
1568
- const text = dropSections(removeServerText(before), ["permission.rules"], (section) => {
1569
- try {
1570
- const rule = cs(section).permission?.rules;
1571
- return rule?.length === 1 && isOurRule(rule[0], watchPatterns);
1572
- } catch {
1573
- return false;
1574
- }
1575
- });
1576
- if (parsesTo(text, expected)) return text;
1577
- return Za(before, expected);
1578
- }
1579
- /** `$GROK_HOME`, else `~/.grok` (`%USERPROFILE%\.grok` on Windows). */
1580
- const grokDir = (env) => env.env.GROK_HOME || join(env.home, ".grok");
1581
- const configPath = (env) => join(grokDir(env), "config.toml");
1582
- /**
1583
- * Grok loads every `*.json` file in `$GROK_HOME/hooks`, always trusted. Conveno's hook gets a file
1584
- * of its own: `config.toml` carries the MCP change, and one file cannot take two changes.
1585
- */
1586
- const hooksPath = (env) => join(grokDir(env), "hooks", "conveno.json");
1587
- /**
1588
- * Home rules: Grok reads every `*.md` in `$GROK_HOME/rules` for every project, whatever the folder
1589
- * trust (user guide 12-project-rules.md). Conveno's wake instructions get a file of their own.
1590
- */
1591
- const rulesPath = (env) => join(grokDir(env), "rules", "conveno.md");
1592
- /** The agent is about to end its turn. */
1593
- const HOOK_EVENT = "Stop";
1594
- /** A tool finished: the one point inside a turn where a hook can hand the model text. */
1595
- const MID_TURN_EVENT = "PostToolUse";
1596
- /** Every hook event Conveno installs. */
1597
- const HOOK_EVENTS = [HOOK_EVENT, MID_TURN_EVENT];
1598
- const EMPTY$1 = {
1599
- stdout: "",
1600
- exitCode: 0
1601
- };
1602
- /**
1603
- * Quote one word of a hook command. Grok runs the command in a POSIX shell, and on Windows in
1604
- * Git Bash, PowerShell or cmd.exe, whichever it finds, so the word is written to mean the same in
1605
- * all of them: double quotes only when it needs them, and on Windows forward slashes.
1606
- */
1607
- function quoteHookWord(arg, platform) {
1608
- const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
1609
- return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
1610
- }
1611
- const hookCommand = (env, event) => [
1612
- ...env.conveno.command,
1613
- "hook",
1614
- "grok",
1615
- event
1616
- ].map((w) => quoteHookWord(w, env.platform)).join(" ");
1617
- /** The matcher group in the hook file. Neither event is filtered, so there is no matcher. */
1618
- const desiredGroup = (env, event) => ({ hooks: [{
1619
- type: "command",
1620
- command: hookCommand(env, event),
1621
- timeout: 5
1622
- }] });
1623
- /** Recognizes our hook command for `event` even if the conveno path changed since install. */
1624
- const isOurHookCommand = (cmd, event) => typeof cmd === "string" && cmd.trim().endsWith(` hook grok ${event}`);
1625
- const isOurGroup = (event) => (g) => isObject$1(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject$1(h) && isOurHookCommand(h.command, event));
1626
- const isOurAnyGroup = (g) => HOOK_EVENTS.some((e) => isOurGroup(e)(g));
1627
- /** The `hooks` object of the hook file, and the list of each of our events when there is one. */
1628
- function eventsOf(file, path) {
1629
- const hooks = file.hooks;
1630
- if (hooks !== void 0 && !isObject$1(hooks)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
1631
- const lists = /* @__PURE__ */ new Map();
1632
- for (const event of HOOK_EVENTS) {
1633
- const list = hooks?.[event];
1634
- if (list !== void 0 && !Array.isArray(list)) throw new Error(`"hooks.${event}" in ${path} must be a list. Fix the file, then run the install again. Nothing was changed.`);
1635
- lists.set(event, list);
1636
- }
1637
- return {
1638
- hooks,
1639
- lists
1640
- };
1641
- }
1642
- async function readIfExists(path) {
1643
- try {
1644
- return await readFile(path, "utf8");
1645
- } catch (err) {
1646
- if (err.code === "ENOENT") return null;
1647
- throw err;
1648
- }
1649
- }
1650
- const specOf = (env) => {
1651
- const [command = "conveno", ...args] = [
1652
- ...env.conveno.command,
1653
- "mcp",
1654
- "--cli",
1655
- "grok"
1656
- ];
1657
- return {
1658
- command,
1659
- args
1660
- };
1661
- };
1662
- async function detect$1(env) {
1663
- const configPaths = [configPath(env)];
1664
- try {
1665
- const r = await env.exec("grok", ["--version"]);
1666
- if (r.code !== 0) return {
1667
- installed: false,
1668
- configPaths
1669
- };
1670
- const version = parseCliVersion(r.stdout);
1671
- return {
1672
- installed: true,
1673
- binary: "grok",
1674
- ...version ? { version } : {},
1675
- configPaths
1676
- };
1677
- } catch {
1678
- return {
1679
- installed: false,
1680
- configPaths
1681
- };
1682
- }
1683
- }
1684
- /** First line of the rules file: how Conveno tells the file is its own. */
1685
- const RULES_MARKER = "<!-- Written by Conveno. `conveno uninstall` removes this file. -->";
1686
- /** How the agent starts the watcher: the conveno command words, quoted, then `watch`. */
1687
- const watchCommand = (env) => [...env.conveno.command, "watch"].map((w) => quoteHookWord(w, env.platform)).join(" ");
1688
- const watchBase = (env) => [...env.conveno.command.map((w) => env.platform === "win32" ? w.replace(/\\/g, "/") : w)].join(" ");
1689
- /**
1690
- * The allow rule's pattern: `watch` of this conveno with one session name. Grok matches parsed words
1691
- * joined by single spaces, without quotes (user guide 22-permissions-and-safety.md, Rule Matching
1692
- * Reference). Allow is checked per command: the script is split on ; && || | and every part must
1693
- * match a rule (xai-grok-permission-rules policy/bash_commands.rs:58-104), and a script with `$(...)`
1694
- * or backticks is not eligible for an allow (bash_permission_script.rs:58-64). So the `*` only spans
1695
- * the rest of one command, and `[a-z0-9]` keeps the name from starting with `-`, `$` or a quote.
1696
- * Monitor is checked as a Bash command (xai-grok-tools permission_access.rs:55).
1697
- */
1698
- const watchPattern = (env) => `${watchBase(env)}${WATCH_TAIL}`;
1699
- /** What older Conveno wrote for this conveno: `watch *`. Uninstall still removes exactly that. */
1700
- const legacyWatchPattern = (env) => `${watchBase(env)} watch *`;
1701
- const ownPatterns = (env) => [watchPattern(env), legacyWatchPattern(env)];
1702
- /**
1703
- * What the Grok agent is told once, in a rules file Grok loads for every project. Idle wake needs
1704
- * the agent's own help: Grok has no way to push text into an idle session, but it wakes on every
1705
- * line a monitor prints, so the agent starts `conveno watch` in one persistent monitor.
1706
- */
1707
- function rulesText(env) {
1708
- return `${[
1709
- RULES_MARKER,
1710
- "# Conveno",
1711
- "",
1712
- "Conveno connects this session to your other AI coding sessions. Do this once so their messages wake you while you are idle:",
1713
- "",
1714
- "1. Call the conveno `whoami` tool and note your session name.",
1715
- `2. Call the \`monitor\` tool once with \`persistent: true\`, the description "Conveno messages" and the command \`${watchCommand(env)} <your session name>\`. Do not start a second one while it runs. If it ended, start it again.`,
1716
- "",
1717
- "Every line the monitor prints starts with `[conveno]` and is one message:",
1718
- `- "The user sent a message through Conveno": ${FROM_USER_NOTICE}`,
1719
- `- "Task from the lead": ${ORCHESTRATOR_TASK_NOTICE}`,
1720
- `- "sent a message (not from the user)": ${NOT_FROM_USER_NOTICE}`,
1721
- "",
1722
- "A line holds at most a short piece of the message. Call the `inbox` tool with `unread_only` false for the full text. While you work, Conveno also adds new messages to your tool results."
1723
- ].join("\n")}\n`;
1724
- }
1725
- async function plan$1(env) {
1726
- const changes = [];
1727
- const path = configPath(env);
1728
- const before = await readIfExists(path);
1729
- const doc = parseToml(path, before ?? "");
1730
- const spec = specOf(env);
1731
- const pattern = watchPattern(env);
1732
- const server = serverOf(doc);
1733
- if (!matchesSpec(server, spec) || !hasRules(doc, pattern)) changes.push({
1734
- component: "mcp",
1735
- kind: server ? "update" : "add",
1736
- parts: [{
1737
- name: "MCP server",
1738
- kind: server ? "update" : "add"
1739
- }],
1740
- path,
1741
- before,
1742
- after: addConfig(path, before ?? "", spec, pattern),
1743
- description: `Register the "${SERVER_NAME$1}" MCP server (conveno mcp --cli grok) and allow its tools (permission rule MCPTool(${RULE_PATTERN})) and the idle-wake watcher (permission rule Bash(${pattern})).`
1744
- });
1745
- const hp = hooksPath(env);
1746
- const hookFile = await loadJson$1(hp);
1747
- const { hooks, lists } = eventsOf(hookFile.value, hp);
1748
- const edits = [];
1749
- const parts = [];
1750
- let anyOurs = false;
1751
- for (const event of HOOK_EVENTS) {
1752
- const list = lists.get(event);
1753
- const want = desiredGroup(env, event);
1754
- if (list?.some((g) => sameJson$1(g, want))) continue;
1755
- const has = list?.some(isOurGroup(event)) ?? false;
1756
- anyOurs ||= has;
1757
- parts.push({
1758
- name: `${event} hook`,
1759
- kind: has ? "update" : "add"
1760
- });
1761
- edits.push(...hooks === void 0 && edits.length === 0 ? [{
1762
- path: ["hooks"],
1763
- value: { [event]: [want] }
1764
- }] : list === void 0 ? [{
1765
- path: ["hooks", event],
1766
- value: [want]
1767
- }] : putInList(list, ["hooks", event], want, isOurGroup(event)));
1768
- }
1769
- if (edits.length > 0) changes.push({
1770
- component: "hooks",
1771
- kind: anyOurs ? "update" : "add",
1772
- parts,
1773
- path: hp,
1774
- before: hookFile.raw,
1775
- after: editJson$1(hookFile, edits),
1776
- description: `Add a ${HOOK_EVENT} hook that continues the agent with waiting Conveno messages at the end of a turn, and a ${MID_TURN_EVENT} hook that adds them to a tool result while it works.`
1777
- });
1778
- const rp = rulesPath(env);
1779
- const rulesBefore = await readIfExists(rp);
1780
- const rulesAfter = rulesText(env);
1781
- if (rulesBefore !== rulesAfter) changes.push({
1782
- component: "hooks",
1783
- kind: rulesBefore === null ? "add" : "update",
1784
- parts: [{
1785
- name: "Wake instructions",
1786
- kind: rulesBefore === null ? "add" : "update"
1787
- }],
1788
- path: rp,
1789
- before: rulesBefore,
1790
- after: rulesAfter,
1791
- description: "Tell Grok to start `conveno watch` in a persistent monitor, so messages wake it while idle."
1792
- });
1793
- return changes;
1794
- }
1795
- async function uninstallPlan$1(env, baseline) {
1796
- const changes = [];
1797
- const path = configPath(env);
1798
- const before = await readIfExists(path);
1799
- if (before !== null) {
1800
- const doc = parseToml(path, before);
1801
- if (serverOf(doc) || hasAnyRule(doc, ownPatterns(env))) changes.push({
1802
- component: "mcp",
1803
- kind: "remove",
1804
- path,
1805
- before,
1806
- after: removeConfig(path, before, ownPatterns(env)),
1807
- description: `Remove the "${SERVER_NAME$1}" MCP server and its permission rules.`
1808
- });
1809
- }
1810
- const hp = hooksPath(env);
1811
- const hookFile = await loadJson$1(hp);
1812
- const { hooks, lists } = eventsOf(hookFile.value, hp);
1813
- if (hookFile.raw !== null && [...lists.values()].some((l) => l?.some(isOurAnyGroup))) {
1814
- const base = baseline?.get(hp);
1815
- const onlyOurs = [...lists.values()].every((l) => l === void 0 || l.every(isOurAnyGroup)) && Object.keys(hooks ?? {}).every((k) => HOOK_EVENTS.includes(k)) && Object.keys(hookFile.value).length === 1;
1816
- const description = "Remove the Conveno hooks.";
1817
- if (onlyOurs && typeof base !== "string") changes.push({
1818
- component: "hooks",
1819
- kind: "remove",
1820
- path: hp,
1821
- before: hookFile.raw,
1822
- after: "",
1823
- description,
1824
- deleteFile: true
1825
- });
1826
- else {
1827
- const edits = [];
1828
- for (const event of HOOK_EVENTS) {
1829
- const list = lists.get(event);
1830
- if (!list?.some(isOurGroup(event))) continue;
1831
- edits.push(...dropFromList(list, ["hooks", event], isOurGroup(event), { keepEmpty: existedBefore(base, ["hooks", event]) }));
1832
- }
1833
- changes.push({
1834
- component: "hooks",
1835
- kind: "remove",
1836
- path: hp,
1837
- before: hookFile.raw,
1838
- after: editJson$1(hookFile, edits),
1839
- description
1840
- });
1841
- }
1842
- }
1843
- const rp = rulesPath(env);
1844
- const rulesBefore = await readIfExists(rp);
1845
- if (rulesBefore?.startsWith(RULES_MARKER)) changes.push({
1846
- component: "hooks",
1847
- kind: "remove",
1848
- path: rp,
1849
- before: rulesBefore,
1850
- after: "",
1851
- description: "Remove the Conveno wake instructions.",
1852
- deleteFile: true
1853
- });
1854
- return changes;
1855
- }
1856
- /**
1857
- * Hooks. A hook can hand text to the model in two places:
1858
- * - PostToolUse: `hookSpecificOutput.additionalContext` lands next to the tool result, inside the
1859
- * turn (user guide 10-hooks.md, PostToolUse Output). Messages that arrive while Grok works
1860
- * reach it after its next tool call.
1861
- * - Stop: records the turn end. With messages waiting, after a genuine turn end (`reason`
1862
- * `end_turn`), `hookSpecificOutput.additionalContext` keeps the agent working and is shown as
1863
- * hook feedback, not as a hook error (10-hooks.md, Stop Decision Control). The session-end
1864
- * fire (`channel_closed`, `shutdown`) only records. Grok overrides the gate after 8
1865
- * continuations in a turn, and Conveno's auto-mode limit bounds the chain before that.
1866
- * `UserPromptSubmit` and `SessionStart` output cannot add text, so a message that arrives while
1867
- * the session is idle reaches it through `conveno watch` in a monitor, not through a hook.
1868
- * Never throws and never writes to stderr: any failure means "deliver nothing this time".
1869
- */
1870
- async function hook$1(event, input, ctx) {
1871
- if (event === "PostToolUse") {
1872
- const text = await pendingHookContext(ctx);
1873
- return text === null ? EMPTY$1 : context(MID_TURN_EVENT, text);
1874
- }
1875
- if (event !== "Stop") return EMPTY$1;
1876
- const reason = isObject$1(input) ? input.reason : void 0;
1877
- const text = await endTurnContinuation(ctx, { allowContinue: reason === void 0 || reason === "end_turn" });
1878
- return text === null ? EMPTY$1 : context(HOOK_EVENT, text);
1879
- }
1880
- const context = (hookEventName, additionalContext) => ({
1881
- stdout: JSON.stringify({ hookSpecificOutput: {
1882
- hookEventName,
1883
- additionalContext
1884
- } }),
1885
- exitCode: 0
1886
- });
1887
- const grokAdapter = {
1888
- cli: "grok",
1889
- displayName: "Grok",
1890
- deliveryTier: "inbox",
1891
- delivery: () => ({
1892
- nextTurn: false,
1893
- endOfTurn: true,
1894
- idleWake: true
1895
- }),
1896
1702
  detect: detect$1,
1897
1703
  plan: plan$1,
1898
1704
  uninstallPlan: uninstallPlan$1,
@@ -1911,6 +1717,10 @@ const grokAdapter = {
1911
1717
  * that prints the continuation prompt, and the plugin sends it with `client.session.promptAsync`.
1912
1718
  * - Otherwise it starts `Listen`, which waits in the background and prints a prompt when work
1913
1719
  * arrives while the session is idle; the plugin sends that the same way.
1720
+ * - `promptAsync` always answers 204, so a prompt that cannot run shows up later as a `session.error`
1721
+ * event. The plugin remembers the ids it just sent and hands them back with `Requeue` if that
1722
+ * event arrives before the session turns busy. (The event shape is `{ sessionID?, error }`,
1723
+ * `packages/schema/src/v1/session.ts` at v2.4.3; that it comes before `busy` is UNVERIFIED.)
1914
1724
  * - When the session turns busy, the plugin is disposed, or a newer listener starts, the listener
1915
1725
  * is stopped. It also stops by itself when OpenCode exits.
1916
1726
  */
@@ -1974,9 +1784,20 @@ export const ConvenoPlugin = async ({ client }) => {
1974
1784
  listener = undefined;
1975
1785
  };
1976
1786
 
1787
+ // Ids of the batch just sent to a session, until it turns busy, the next prompt replaces it, or
1788
+ // SENT_TTL_MS pass. A session.error before that means the prompt did not run. An idle event does
1789
+ // not clear it: a cancel with no runner can publish one before the error. The TTL stops a much
1790
+ // later error (of a turn that did run) from requeueing messages that were delivered.
1791
+ const SENT_TTL_MS = 30000;
1792
+ const sent = new Map();
1793
+ const requeue = (sessionID, ids) =>
1794
+ ids.length > 0 ? run("Requeue", sessionID, undefined, { ids }).done : undefined;
1795
+
1977
1796
  const prompt = async (sessionID, out) => {
1978
1797
  const { ids, text } = split(out);
1979
1798
  try {
1799
+ sent.delete(sessionID);
1800
+ if (ids.length > 0) sent.set(sessionID, { ids, at: Date.now() });
1980
1801
  const res = await client.session.promptAsync({
1981
1802
  path: { id: sessionID },
1982
1803
  body: { parts: [{ type: "text", text }] },
@@ -1984,7 +1805,8 @@ export const ConvenoPlugin = async ({ client }) => {
1984
1805
  if (res?.error) throw new Error("prompt failed");
1985
1806
  } catch {
1986
1807
  // The session is gone or busy again: hand the messages back so the next turn gets them.
1987
- if (ids.length > 0) await run("Requeue", sessionID, undefined, { ids }).done;
1808
+ sent.delete(sessionID);
1809
+ await requeue(sessionID, ids);
1988
1810
  }
1989
1811
  };
1990
1812
 
@@ -2025,12 +1847,16 @@ export const ConvenoPlugin = async ({ client }) => {
2025
1847
  return {
2026
1848
  event: async ({ event }) => {
2027
1849
  if (event.type === "session.idle") void onIdle(event.properties.sessionID);
2028
- else if (
2029
- event.type === "session.status" &&
2030
- event.properties.status?.type === "busy" &&
2031
- event.properties.sessionID === listener?.sessionID
2032
- ) {
2033
- stop();
1850
+ else if (event.type === "session.error") {
1851
+ const id = event.properties?.sessionID;
1852
+ const entry = id && sent.get(id);
1853
+ if (entry) {
1854
+ sent.delete(id);
1855
+ if (Date.now() - entry.at <= SENT_TTL_MS) await requeue(id, entry.ids);
1856
+ }
1857
+ } else if (event.type === "session.status" && event.properties.status?.type === "busy") {
1858
+ sent.delete(event.properties.sessionID);
1859
+ if (event.properties.sessionID === listener?.sessionID) stop();
2034
1860
  }
2035
1861
  },
2036
1862
  dispose: async () => stop(),
@@ -2066,7 +1892,14 @@ export const ConvenoPlugin = async ({ client }) => {
2066
1892
  * - When a session is deleted (`session.deleted`) it runs `Deleted`, which releases the Conveno
2067
1893
  * session so it goes offline at once instead of waiting for the MCP server to lapse it.
2068
1894
  *
2069
- * `session.status` and `session.idle` are not used: 2.4.3 does not deliver them to plugins.
1895
+ * A prompt sent while the session is busy (between `session.execution.started` and the end event)
1896
+ * uses `delivery: "steer"`, which reaches the agent before its next model call
1897
+ * (`packages/schema/src/session-inbox.ts` at v2.4.3); an idle session gets `"queue"`.
1898
+ *
1899
+ * `session.idle` (deprecated) and `session.status` are not used: 2.4.3 does not deliver them to
1900
+ * plugins (README, "Events"); the durable `session.execution.*` events replace them. Of the APIs
1901
+ * used here, `experimental.idle`, `delivery` and the execution events are feature-detected at run
1902
+ * time; the first 2.x release that has all three is UNVERIFIED.
2070
1903
  */
2071
1904
  /** First line of the 2.x plugin. */
2072
1905
  const PLUGIN_MARKER_V2 = `${PLUGIN_MARKER_PREFIX} 2`;
@@ -2082,6 +1915,8 @@ export default {
2082
1915
  setup(ctx) {
2083
1916
  const controller = new AbortController();
2084
1917
  let listener;
1918
+ // Sessions with a running execution, from the execution events.
1919
+ const busy = new Set();
2085
1920
 
2086
1921
  const stop = () => {
2087
1922
  if (!listener) return;
@@ -2089,11 +1924,19 @@ export default {
2089
1924
  listener = undefined;
2090
1925
  };
2091
1926
 
2092
- const prompt = async (sessionID, out) => {
1927
+ const prompt = async (sessionID, out, forceQueue) => {
2093
1928
  const { ids, text } = split(out);
1929
+ // "steer" reaches a busy agent before its next model call; "queue" waits for it to finish.
1930
+ // The idle hook runs while the execution is still open but about to end, so it queues.
1931
+ const delivery = !forceQueue && busy.has(sessionID) ? "steer" : "queue";
2094
1932
  try {
2095
- // "queue" waits for the agent's current work and never cuts into a running turn.
2096
- await ctx.session.prompt({ sessionID, text, delivery: "queue" });
1933
+ try {
1934
+ await ctx.session.prompt({ sessionID, text, delivery });
1935
+ } catch (err) {
1936
+ // A server that does not know \`delivery\` rejects it; send without it (the server's default).
1937
+ if (!/delivery/i.test(String(err?.message ?? err))) throw err;
1938
+ await ctx.session.prompt({ sessionID, text });
1939
+ }
2097
1940
  } catch {
2098
1941
  // The session is gone or busy again: hand the messages back so the next turn gets them.
2099
1942
  if (ids.length > 0) await run("Requeue", sessionID, ctx.location.directory, { ids }).done;
@@ -2131,7 +1974,7 @@ export default {
2131
1974
  .hook("experimental.idle", async ({ sessionID }) => {
2132
1975
  if (!(await ours(sessionID))) return;
2133
1976
  const now = await run("Idle", sessionID, ctx.location.directory).done;
2134
- if (now) await prompt(sessionID, now);
1977
+ if (now) await prompt(sessionID, now, true);
2135
1978
  })
2136
1979
  .catch(() => {});
2137
1980
  }
@@ -2151,6 +1994,7 @@ export default {
2151
1994
 
2152
1995
  void (async () => {
2153
1996
  try {
1997
+ if (typeof ctx.event?.subscribe !== "function") return;
2154
1998
  for await (const event of ctx.event.subscribe({
2155
1999
  types: [
2156
2000
  "session.execution.started",
@@ -2162,6 +2006,8 @@ export default {
2162
2006
  signal: controller.signal,
2163
2007
  })) {
2164
2008
  const { sessionID } = event.data;
2009
+ if (event.type === "session.execution.started") busy.add(sessionID);
2010
+ else busy.delete(sessionID);
2165
2011
  if (event.type === "session.deleted") {
2166
2012
  // The session is gone: release its Conveno session so it goes offline now.
2167
2013
  if (sessionID === listener?.sessionID) stop();
@@ -2197,12 +2043,24 @@ const FORMAT = {
2197
2043
  tabSize: 2,
2198
2044
  eol: "\n"
2199
2045
  };
2200
- /** First OpenCode release that reads `mcp.servers`. There were no 2.0.x or 2.1.x releases. */
2046
+ /**
2047
+ * First OpenCode release that reads `mcp.servers` and gets the 2.x plugin. There were no 2.0.x or
2048
+ * 2.1.x releases.
2049
+ */
2201
2050
  const V2_MIN = [
2202
2051
  2,
2203
2052
  2,
2204
2053
  0
2205
2054
  ];
2055
+ /**
2056
+ * The 2.x release Conveno is checked against (the 2.4.3 source). Older 2.x still gets the right
2057
+ * config, but waking is only supported from here; doctor says so.
2058
+ */
2059
+ const V2_SUPPORTED = [
2060
+ 2,
2061
+ 4,
2062
+ 0
2063
+ ];
2206
2064
  /** `$XDG_CONFIG_HOME/opencode` when XDG_CONFIG_HOME is an absolute path, else `~/.config/opencode`. */
2207
2065
  function configDir(env) {
2208
2066
  const xdg = env.env.XDG_CONFIG_HOME;
@@ -2279,10 +2137,19 @@ function parseVersion(text) {
2279
2137
  Number(m[3])
2280
2138
  ] : void 0;
2281
2139
  }
2282
- function isV2OrLater(v) {
2283
- for (let i = 0; i < 3; i++) if (v[i] !== V2_MIN[i]) return v[i] > V2_MIN[i];
2140
+ function atLeast(v, min) {
2141
+ for (let i = 0; i < 3; i++) if (v[i] !== min[i]) return v[i] > min[i];
2284
2142
  return true;
2285
2143
  }
2144
+ function isV2OrLater(v) {
2145
+ return atLeast(v, V2_MIN);
2146
+ }
2147
+ /** One line for `conveno doctor` when this OpenCode is a 2.x release older than the supported one. */
2148
+ async function opencodeDoctorNotes(env) {
2149
+ const v = await installedVersion(env);
2150
+ if (!v || !isV2OrLater(v) || atLeast(v, V2_SUPPORTED)) return [];
2151
+ return [`OpenCode ${v.join(".")} is older than 2.4, the oldest 2.x Conveno supports. Update OpenCode so waking works.`];
2152
+ }
2286
2153
  async function installedVersion(env) {
2287
2154
  try {
2288
2155
  const res = await env.exec("opencode", ["--version"]);
@@ -2545,9 +2412,13 @@ async function sessionName(ctx) {
2545
2412
  return null;
2546
2413
  }
2547
2414
  }
2548
- /** Only the plugin delivers, on 1.x and 2.x alike; it adds nothing to a prompt the user types. */
2415
+ /**
2416
+ * Only the plugin delivers, on 1.x and 2.4+ alike; it adds nothing to a prompt the user types.
2417
+ * 2.0 to 2.3 are not supported (`opencodeDoctorNotes`), so doctor claims no waking for them.
2418
+ */
2549
2419
  function delivery(detection) {
2550
- const supported = detection.version !== void 0 && parseVersion(detection.version) !== void 0;
2420
+ const v = detection.version === void 0 ? void 0 : parseVersion(detection.version);
2421
+ const supported = v !== void 0 && (!isV2OrLater(v) || atLeast(v, V2_SUPPORTED));
2551
2422
  return {
2552
2423
  nextTurn: false,
2553
2424
  endOfTurn: supported,
@@ -2555,6 +2426,7 @@ function delivery(detection) {
2555
2426
  };
2556
2427
  }
2557
2428
  const opencodeAdapter = {
2429
+ doctorNotes: opencodeDoctorNotes,
2558
2430
  cli: "opencode",
2559
2431
  displayName: "OpenCode",
2560
2432
  deliveryTier: "inbox",
@@ -2619,4 +2491,4 @@ function createHookCtx() {
2619
2491
  function runHookEntry(argv) {
2620
2492
  return runHook(createHookCtx(), argv);
2621
2493
  }
2622
- export { opencodeAdapter as a, copilotAdapter as c, runHookEntry as i, claudeAdapter as l, isProcessAlive as n, grokAdapter as o, readAllStdin as r, cursorAdapter as s, createHookCtx as t };
2494
+ export { opencodeAdapter as a, claudeAdapter as c, runHookEntry as i, isProcessAlive as n, cursorAdapter as o, readAllStdin as r, copilotAdapter as s, createHookCtx as t };