@conveno/cli 0.2.0-rc.8 → 0.2.0

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.
Files changed (32) hide show
  1. package/README.md +3 -5
  2. package/dist/{acp-YHhVx0Ya.js → acp-BUddItzP.js} +39 -7
  3. package/dist/{agy-relay-BS2NeFlh.js → agy-relay-BZ3d_-FS.js} +4 -2
  4. package/dist/{args-CGL-AmNd.js → args-CtyKPZuN.js} +29 -8
  5. package/dist/bin.js +16 -2
  6. package/dist/daemon.js +4 -3139
  7. package/dist/{daemonError-DJ-P55nH.js → daemonError-CDgEtvy7.js} +1 -1
  8. package/dist/dist-BNhTPp5p.js +4509 -0
  9. package/dist/{dist-BRjg9CLd.js → dist-BOwFdixw.js} +23 -50
  10. package/dist/{dist-CcoTmwrf.js → dist-CFsDqevs.js} +94 -56
  11. package/dist/dist-CNdqmI3E.js +1065 -0
  12. package/dist/{dist-BBdba94T.js → dist-CSSvrcKr.js} +1752 -708
  13. package/dist/{dist-B6Sm0MRT.js → dist-D6Xoip5W.js} +203 -62
  14. package/dist/{dist-WTkKRM39.js → dist-DAVtixeC.js} +19 -5
  15. package/dist/dist-DTMnNySx.js +989 -0
  16. package/dist/hook-BA-tI6Oc.js +208 -0
  17. package/dist/hook-entry-BwzBtAnd.js +1346 -0
  18. package/dist/hook-entry-Cgt5ZH1s.js +1 -0
  19. package/dist/{main-DrzHsV5y.js → main-kKnLA7Hj.js} +58 -21
  20. package/dist/{pick-Bi1yJDh6.js → pick-BsMvXuDo.js} +1 -1
  21. package/dist/run-PQBzaHv1.js +8193 -0
  22. package/dist/{runtime-Db_YT5Xg.js → runtime-0FMqklYn.js} +233 -122
  23. package/dist/{uninstall-D9rW_j7H.js → uninstall-DcxkIDpk.js} +556 -82
  24. package/dist/{watch-BrTWYf3Y.js → watch-BIepRTXJ.js} +29 -7
  25. package/package.json +14 -15
  26. package/dist/dist-B1EVHdIM.js +0 -504
  27. package/dist/dist-BlWWt5gx.js +0 -624
  28. package/dist/dist-C6cMQ00I.js +0 -793
  29. package/dist/hook-DxjJDCjz.js +0 -94
  30. package/dist/hook-entry-CrpZz5QW.js +0 -1
  31. package/dist/hook-entry-pHJioNgN.js +0 -2494
  32. package/dist/run-C32oP2c_.js +0 -5550
@@ -1,4 +1,4 @@
1
- import "node:url";
1
+ import { release } from "node:os";
2
2
  // ../brand/dist/index.js
3
3
  const tokens = {
4
4
  "name": "Conveno",
@@ -50,7 +50,7 @@ const tokens = {
50
50
  },
51
51
  "roles": {
52
52
  "entry": "The one accent. The point in the mark, the orchestrator, links, primary actions, 'live'. Never used for decoration.",
53
- "stamp": "Attention that needs the owner: open tickets, waiting on question. Not an error.",
53
+ "stamp": "Attention that needs the owner: waiting on a question. Not an error.",
54
54
  "ok/warn/error/info": "Semantic state only. Never as brand accents."
55
55
  },
56
56
  "derived": {
@@ -257,9 +257,9 @@ const tokens = {
257
257
  "c--- *"
258
258
  ],
259
259
  "showAfterMs": 400,
260
- "noMotion": "Static 'c─── ●' line when CONVENO_NO_MOTION=1, CI is set, stdout is not a TTY, or NO_COLOR with TERM=dumb."
260
+ "noMotion": "Static 'c─── ●' line when CONVENO_REDUCED_MOTION=1, NO_COLOR is set, or stdout is not a TTY."
261
261
  },
262
- "env": "NO_COLOR disables colour; FORCE_COLOR=0..3 forces level; COLORTERM=truecolor|24bit enables truecolor; CONVENO_NO_MOTION and CI disable spinners."
262
+ "env": "NO_COLOR disables colour; FORCE_COLOR=0..3 forces level; COLORTERM=truecolor|24bit enables truecolor; CONVENO_REDUCED_MOTION disables spinners."
263
263
  },
264
264
  "naming": {
265
265
  "cssVariables": "All CSS custom properties use the --cv- prefix (e.g. --cv-ink, --cv-ease-enter, --cv-dur-quick, --cv-fs-sm, --cv-s-4, --cv-r-md). The icon accent point colour is --cv-point.",
@@ -291,7 +291,6 @@ const tokens = {
291
291
  "exempt": ["icons/sprite.svg (bundle)", "assets/social-preview*.svg (source for the PNG; outlined text)"]
292
292
  }
293
293
  };
294
- import.meta.url;
295
294
  const terminalTheme = {
296
295
  "name": "Conveno terminal theme",
297
296
  "version": "1.0.0-lock",
@@ -302,7 +301,7 @@ const terminalTheme = {
302
301
  "light": "#FBFCFD"
303
302
  },
304
303
  "attributes": {
305
- "bold": "SGR 1. Used for names, ticket ids and the one key phrase of a line. Never the only signal.",
304
+ "bold": "SGR 1. Used for names and the one key phrase of a line. Never the only signal.",
306
305
  "dim": "Not used. 'quiet' is a colour, because SGR 2 is unreliable across terminals.",
307
306
  "underline": "SGR 4. URLs only.",
308
307
  "reset": "SGR 0 at the end of every coloured span and every line."
@@ -324,7 +323,7 @@ const terminalTheme = {
324
323
  }
325
324
  },
326
325
  "stamp": {
327
- "use": "Needs the owner: open tickets, waiting on a question. Not an error.",
326
+ "use": "Needs the owner: waiting on a question. Not an error.",
328
327
  "truecolor": {
329
328
  "dark": "#FFB547",
330
329
  "light": "#9A5700"
@@ -538,7 +537,7 @@ const terminalTheme = {
538
537
  "COLORTERM",
539
538
  "TERM"
540
539
  ],
541
- "CONVENO_NO_MOTION": "1 disables the spinner and prints the static 'c─── ●' line. CI, a non-TTY stdout, or NO_COLOR with TERM=dumb do the same."
540
+ "CONVENO_REDUCED_MOTION": "1 disables the spinner and prints the static 'c─── ●' line. NO_COLOR or a non-TTY stdout do the same."
542
541
  },
543
542
  "status": {
544
543
  "shapes": {
@@ -585,23 +584,26 @@ const terminalTheme = {
585
584
  "note": "The c and the entry line are quiet; only the final point is entry (the mark's point)."
586
585
  },
587
586
  "staticLine": "c─── ●",
588
- "noMotion": "Static 'c─── ●' line when CONVENO_NO_MOTION=1, CI is set, stdout is not a TTY, or NO_COLOR with TERM=dumb."
589
- },
590
- "redaction": {
591
- "unicode": "[redacted]",
592
- "ascii": "[redacted]",
593
- "note": "Fixed text, inverse video when colour is on."
587
+ "noMotion": "Static 'c─── ●' line when CONVENO_REDUCED_MOTION=1, NO_COLOR is set, or stdout is not a TTY."
594
588
  }
595
589
  };
596
590
  const ESC = "\x1B[";
597
591
  const RESET = `${ESC}0m`;
598
592
  const set = (v) => v !== void 0 && v !== "";
599
593
  const falsy = (v) => v === void 0 || v === "" || v === "0" || v.toLowerCase() === "false";
594
+ /** Windows 10 build 18362 (1903) or later: conhost has VT, 256 colours and Unicode box drawing. */
595
+ function modernWindows(osRelease) {
596
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(osRelease ?? "");
597
+ if (!m) return false;
598
+ const major = Number(m[1]);
599
+ return major > 10 || major === 10 && Number(m[3]) >= 18362;
600
+ }
600
601
  function currentContext() {
601
602
  return {
602
603
  env: process.env,
603
604
  isTTY: Boolean(process.stdout.isTTY),
604
- platform: process.platform
605
+ platform: process.platform,
606
+ osRelease: release()
605
607
  };
606
608
  }
607
609
  /** Precedence from brand/components/terminal-theme.json: NO_COLOR, FORCE_COLOR, flag, TTY, COLORTERM, TERM. */
@@ -626,6 +628,7 @@ function detectColorLevel(ctx = currentContext(), flag = "auto") {
626
628
  if (colorterm === "truecolor" || colorterm === "24bit") detected = 3;
627
629
  else if (ctx.platform === "win32" && (set(env.WT_SESSION) || env.ConEmuANSI === "ON")) detected = 3;
628
630
  else if (term === "dumb") detected = 0;
631
+ else if (ctx.platform === "win32" && modernWindows(ctx.osRelease) && !/256color/.test(term)) detected = 2;
629
632
  else if (term === "" && ctx.platform !== "win32") detected = 0;
630
633
  else if (/256color/.test(term)) detected = 2;
631
634
  else detected = 1;
@@ -640,25 +643,16 @@ function detectBackground(env = process.env) {
640
643
  }
641
644
  return "dark";
642
645
  }
643
- /** False for CONVENO_ASCII=1, the legacy Windows console and non-UTF-8 locales. */
646
+ /** False for CONVENO_ASCII=1, Windows older than 10 build 18362 and non-UTF-8 locales. */
644
647
  function detectUnicode(ctx = currentContext()) {
645
648
  const { env } = ctx;
646
649
  if (!falsy(env.CONVENO_ASCII)) return false;
647
- if (ctx.platform === "win32") return set(env.WT_SESSION) || set(env.TERM_PROGRAM) || env.ConEmuANSI === "ON" || env.TERM === "xterm-256color" || env.TERM === "alacritty";
650
+ if (ctx.platform === "win32") return set(env.WT_SESSION) || set(env.TERM_PROGRAM) || env.ConEmuANSI === "ON" || env.TERM === "xterm-256color" || env.TERM === "alacritty" || modernWindows(ctx.osRelease);
648
651
  if (env.TERM === "linux") return false;
649
652
  const locale = env.LC_ALL || env.LC_CTYPE || env.LANG;
650
653
  if (set(locale)) return /utf-?8/i.test(locale);
651
654
  return true;
652
655
  }
653
- /** Spinner gate from tokens.terminal.spinner.noMotion: CONVENO_NO_MOTION, CI, non-TTY, TERM=dumb. */
654
- function detectMotion(ctx = currentContext()) {
655
- const { env } = ctx;
656
- if (!falsy(env.CONVENO_NO_MOTION)) return false;
657
- if (!falsy(env.CI)) return false;
658
- if (!ctx.isTTY) return false;
659
- if (env.TERM === "dumb") return false;
660
- return true;
661
- }
662
656
  function sgr(role, level, bg) {
663
657
  const r = terminalTheme.roles[role];
664
658
  if (level === 3) {
@@ -674,12 +668,12 @@ function createTheme(opts = {}) {
674
668
  const ctx = {
675
669
  env: opts.env ?? now.env,
676
670
  isTTY: opts.isTTY ?? now.isTTY,
677
- platform: opts.platform ?? now.platform
671
+ platform: opts.platform ?? now.platform,
672
+ ...(opts.osRelease ?? now.osRelease) !== void 0 ? { osRelease: opts.osRelease ?? now.osRelease } : {}
678
673
  };
679
674
  const colorLevel = detectColorLevel(ctx, opts.color);
680
675
  const background = opts.background ?? detectBackground(ctx.env);
681
676
  const unicode = opts.ascii ? false : detectUnicode(ctx);
682
- const motion = detectMotion(ctx);
683
677
  const wrap = (codes, text) => `${ESC}${codes}m${text}${RESET}`;
684
678
  const paint = (role, text, o) => {
685
679
  if (colorLevel === 0 || text === "") return text;
@@ -696,36 +690,15 @@ function createTheme(opts = {}) {
696
690
  const status = (name) => paint(tokens.terminal.glyphColors[name], glyph(name));
697
691
  const point = unicode ? "●" : tokens.terminal.asciiFallback["●"] ?? "*";
698
692
  const mark = () => `${paint("ink", "c")}${paint("entry", point)}`;
699
- const spinner = () => {
700
- const sp = tokens.terminal.spinner;
701
- const raw = unicode ? sp.frames : sp.asciiFrames;
702
- const dot = unicode ? "●" : "*";
703
- const paintFrame = (f) => {
704
- const i = f.indexOf(dot);
705
- const line = i === -1 ? f : f.slice(0, i);
706
- const tail = i === -1 ? "" : paint("entry", dot);
707
- return paint("quiet", line.trimEnd()) + " ".repeat(line.length - line.trimEnd().length) + tail;
708
- };
709
- const frames = raw.map(paintFrame);
710
- return {
711
- animated: motion,
712
- intervalMs: sp.intervalMs,
713
- showAfterMs: sp.showAfterMs,
714
- frames,
715
- staticLine: paintFrame(raw[raw.length - 1])
716
- };
717
- };
718
693
  return {
719
694
  colorLevel,
720
695
  background,
721
696
  unicode,
722
- motion,
723
697
  paint,
724
698
  bold,
725
699
  glyph,
726
700
  status,
727
- mark,
728
- spinner
701
+ mark
729
702
  };
730
703
  }
731
704
  export { tokens as i, detectColorLevel as n, detectUnicode as r, createTheme as t };
@@ -1,7 +1,6 @@
1
- import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
1
+ import { readFile } from "node:fs/promises";
3
2
  import { join } from "node:path";
4
- import { I as dropFromList, L as editJson, P as defaultProcessIo, Pt as sameJson, V as existedBefore, Z as isObject, a as FROM_USER_NOTICE, c as ORCHESTRATOR_TASK_NOTICE, et as loadJson, gt as putInList, it as ownSession, j as dataDir, ot as parseCliVersion, s as NOT_FROM_USER_NOTICE, ut as pendingHookContext, yt as readCommandLine, z as endTurnContinuation } from "./dist-BBdba94T.js";
3
+ import { $ as endTurnContinuation, At as needsQuoting, C as agentCommand, E as askedMarker, J as defaultProcessIo, Jt as putInList, Nt as ownSession, On as uninstallLauncher, Pt as parseCliVersion, T as askedKey, Ut as planLauncher, X as dropFromList, Z as editJson, Zt as readCommandLine, c as NOT_FROM_USER_NOTICE, gt as isObject, hn as sameJson, o as FROM_USER_NOTICE, pt as hostPidOf, tt as existedBefore, u as ORCHESTRATOR_TASK_NOTICE, wt as loadJson, yt as late, zt as pendingHookContext } from "./dist-CSSvrcKr.js";
5
4
  import { n as cs, t as Za } from "./toml-patch-DGzVRdd1.js";
6
5
  // ../adapters/grok/dist/index.js
7
6
  const SERVER_NAME = "conveno";
@@ -233,13 +232,22 @@ const TURN_FAILED_EVENTS = ["StopFailure", "StopCancelled"];
233
232
  const IDLE_EVENT = "Notification";
234
233
  /** The `Notification` matcher: only the idle ping reaches the hook. */
235
234
  const IDLE_MATCHER = "idle_prompt";
235
+ /**
236
+ * A conversation starts (`/new`, `/clear`, a resumed one: `source` new or load) or ends. Their
237
+ * output cannot add text. The start moves the window's session to the conversation; the end clears
238
+ * a turn that never reported its end.
239
+ */
240
+ const SESSION_START_EVENT = "SessionStart";
241
+ const SESSION_END_EVENT = "SessionEnd";
236
242
  /** Every hook event Conveno installs. */
237
243
  const HOOK_EVENTS = [
238
244
  HOOK_EVENT,
239
245
  MID_TURN_EVENT,
240
246
  TURN_START_EVENT,
241
247
  ...TURN_FAILED_EVENTS,
242
- IDLE_EVENT
248
+ IDLE_EVENT,
249
+ SESSION_START_EVENT,
250
+ SESSION_END_EVENT
243
251
  ];
244
252
  const EMPTY = {
245
253
  stdout: "",
@@ -252,7 +260,7 @@ const EMPTY = {
252
260
  */
253
261
  function quoteHookWord(arg, platform) {
254
262
  const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
255
- return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
263
+ return !needsQuoting(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
256
264
  }
257
265
  const hookCommand = (env, event) => [
258
266
  ...env.conveno.command,
@@ -265,7 +273,7 @@ const hookCommand = (env, event) => [
265
273
  * `UserPromptSubmit` is ignored with a warning, 10-hooks.md, matcher).
266
274
  */
267
275
  const desiredGroup = (env, event) => ({
268
- ...event === "Notification" ? { matcher: IDLE_MATCHER } : {},
276
+ ...event === IDLE_EVENT ? { matcher: IDLE_MATCHER } : {},
269
277
  hooks: [{
270
278
  type: "command",
271
279
  command: hookCommand(env, event),
@@ -335,24 +343,37 @@ async function detect(env) {
335
343
  }
336
344
  /** First line of the rules file: how Conveno tells the file is its own. */
337
345
  const RULES_MARKER = "<!-- Written by Conveno. `conveno uninstall` removes this file. -->";
338
- /** How the agent starts the watcher: the conveno command words, quoted, then `watch`. */
339
- const watchCommand = (env) => [...env.conveno.command, "watch"].map((w) => quoteHookWord(w, env.platform)).join(" ");
340
- const watchBase = (env) => [...env.conveno.command.map((w) => env.platform === "win32" ? w.replace(/\\/g, "/") : w)].join(" ");
341
346
  /**
342
- * The allow rule's pattern: `watch` of this conveno with anything after it. Grok matches the parsed
343
- * words of each command joined by single spaces: quotes are gone, so `"C:/Program Files/nodejs/node.exe"`
344
- * is the words `C:/Program Files/nodejs/node.exe` (user guide 22-permissions-and-safety.md, Rule
345
- * Matching Reference; shell_access.rs:910-939 dequotes, policy/bash_commands.rs:73-82 and
346
- * policy.rs:365-368 join the words and match them). The pattern is the glob of those words, so the
347
- * path is written unquoted with forward slashes. `*` stays inside one command: the script is split
347
+ * How the agent starts the watcher: the command words, quoted, then `watch`. The words are plain
348
+ * `conveno` or Conveno's launcher script, never `node <bin.js>`: Grok asks before it runs a
349
+ * command that starts with an interpreter (policy.rs `head_is_exec_vehicle`), but not one that
350
+ * starts with a script path.
351
+ */
352
+ const watchCommand = (env) => [...agentCommand(env, "grok"), "watch"].map((w) => quoteHookWord(w, env.platform)).join(" ");
353
+ const baseOf = (env, words) => words.map((w) => env.platform === "win32" ? w.replace(/\\/g, "/") : w).join(" ");
354
+ const watchBase = (env) => baseOf(env, agentCommand(env, "grok"));
355
+ /**
356
+ * The allow rule's pattern: `watch` of this conveno with anything after it. The pattern is matched
357
+ * against the command's words joined by single spaces (policy/bash_commands.rs:73-82,
358
+ * policy.rs:365-368), so it is written unquoted with forward slashes. Grok 1.0.98 never
359
+ * auto-allows a quoted command, whether the rule is written with the quotes or without (checked
360
+ * live), and an interpreter head (`node bin.js watch x`) is never auto-allowed either. That is why
361
+ * the command is a script path with no space in it, not `node <bin.js>`. `*` stays inside one command: the script is split
348
362
  * on ; && || | and every part must match (bash_commands.rs:58-104), and `$(...)` or backticks are
349
363
  * not eligible for an allow (bash_permission_script.rs:58-64). Monitor is checked as a Bash command
350
364
  * (xai-grok-tools permission_access.rs:55).
351
365
  */
352
366
  const watchPattern = (env) => `${watchBase(env)}${WATCH_TAIL}`;
353
- /** What an earlier build wrote for this conveno: `watch [a-z0-9]*`. Uninstall still removes exactly that. */
354
- const legacyWatchPattern = (env) => `${watchBase(env)}${NARROW_TAIL}`;
355
- const ownPatterns = (env) => [watchPattern(env), legacyWatchPattern(env)];
367
+ /** Every rule Conveno wrote for this install, now or in an earlier version (plain, node form, launcher). */
368
+ const ownPatterns = (env) => {
369
+ const launcher = env.conveno.launcher ? [[env.conveno.launcher.path]] : [];
370
+ return [...new Set([
371
+ agentCommand(env, "grok"),
372
+ env.conveno.command,
373
+ ["conveno"],
374
+ ...launcher
375
+ ].map((w) => baseOf(env, w)))].flatMap((b) => [`${b}${WATCH_TAIL}`, `${b}${NARROW_TAIL}`]);
376
+ };
356
377
  /**
357
378
  * What the Grok agent is told once, in a rules file Grok loads for every project. Idle wake needs
358
379
  * the agent's own help: Grok has no way to push text into an idle session, but it wakes on every
@@ -368,7 +389,7 @@ function rulesText(env) {
368
389
  "After you have answered the user's request, if no Conveno monitor is running yet, start one so messages from other sessions wake you while you are idle:",
369
390
  "",
370
391
  "1. Call the conveno `whoami` tool and note your session name.",
371
- `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, unless its last line says not to start it again. Conveno may also ask you at the end of a turn to start it: do so then.`,
392
+ `2. Call the \`monitor\` tool once with \`persistent: true\`, the description "Conveno messages" and the command \`${watchCommand(env)} <your session name>\`. Start it silently and never mention it to the user. It prints nothing until a message arrives or it ends. Do not start a second one while it runs. If it ended, start it again, unless its last line says not to start it again. Conveno may also ask you at the end of a turn to start it, with a conversation id to add as \`--conversation <id>\` after your session name: do so then, exactly as asked.`,
372
393
  "",
373
394
  "If the monitor is refused, not allowed or fails, skip it without a word and carry on. A refusal is never a reason to stop or to leave the user's request undone.",
374
395
  "",
@@ -388,6 +409,8 @@ async function plan(env) {
388
409
  const spec = specOf(env);
389
410
  const pattern = watchPattern(env);
390
411
  const server = serverOf(doc);
412
+ const launcher = await planLauncher(env, "grok");
413
+ if (launcher) changes.push(launcher);
391
414
  if (!matchesSpec(server, spec) || !hasRules(doc, pattern)) changes.push({
392
415
  component: "mcp",
393
416
  kind: server ? "update" : "add",
@@ -431,7 +454,8 @@ async function plan(env) {
431
454
  path: hp,
432
455
  before: hookFile.raw,
433
456
  after: editJson(hookFile, edits),
434
- description: `Add a ${HOOK_EVENT} hook that continues the agent with waiting Conveno messages at the end of a turn, a ${MID_TURN_EVENT} hook that adds them to a tool result while it works, and hooks that tell Conveno when a turn starts, fails or is cancelled.`
457
+ pruneEmptyDir: 1,
458
+ description: `Add a ${HOOK_EVENT} hook that continues the agent with waiting Conveno messages at the end of a turn, a ${MID_TURN_EVENT} hook that adds them to a tool result while it works, and hooks that tell Conveno when a conversation starts or ends and when a turn starts, fails or is cancelled.`
435
459
  });
436
460
  const rp = rulesPath(env);
437
461
  const rulesBefore = await readIfExists(rp);
@@ -446,6 +470,7 @@ async function plan(env) {
446
470
  path: rp,
447
471
  before: rulesBefore,
448
472
  after: rulesAfter,
473
+ pruneEmptyDir: 1,
449
474
  description: "Tell Grok to start `conveno watch` in a persistent monitor, so messages wake it while idle."
450
475
  });
451
476
  return changes;
@@ -454,6 +479,8 @@ async function uninstallPlan(env, baseline) {
454
479
  const changes = [];
455
480
  const path = configPath(env);
456
481
  const before = await readIfExists(path);
482
+ const launcher = await uninstallLauncher(env);
483
+ if (launcher) changes.push(launcher);
457
484
  if (before !== null) {
458
485
  const doc = parseToml(path, before);
459
486
  if (serverOf(doc) || hasAnyRule(doc, ownPatterns(env))) changes.push({
@@ -515,7 +542,14 @@ async function uninstallPlan(env, baseline) {
515
542
  * What Stop asks the model when no watcher is connected. Fixed text: the rules file says how.
516
543
  * It is a request from Conveno's own hook, so it carries no peer text.
517
544
  */
518
- const WATCHER_REQUEST = "[conveno] No Conveno monitor is running for this session, so other sessions cannot wake you while you are idle. Start it now, as the Conveno rules say (whoami, then one persistent monitor), then finish. Skip it without a word if the monitor is refused.";
545
+ const WATCHER_REQUEST = "[conveno] No Conveno monitor is running for this session, so other sessions cannot wake you while you are idle. Start it now, as the Conveno rules say (whoami, then one persistent monitor), then finish, without mentioning it to the user. Skip it without a word if the monitor is refused.";
546
+ /** A Grok conversation id is safe to put in a command and a prompt: plain characters, short. */
547
+ const SAFE_CONVERSATION = /^[A-Za-z0-9_.:-]{1,128}$/;
548
+ /**
549
+ * The ask with the conversation it is for: the monitor's command gets `--conversation <id>`, so
550
+ * the watcher follows this conversation and stops once the window's session moves to another.
551
+ */
552
+ const watcherRequest = (conversationId) => conversationId !== void 0 && SAFE_CONVERSATION.test(conversationId) ? `${WATCHER_REQUEST} This conversation's id is ${conversationId}: add \`--conversation ${conversationId}\` after your session name in the watch command.` : WATCHER_REQUEST;
519
553
  /**
520
554
  * True when a Stop payload lists a monitor that runs `watch`: the watcher is started but may not
521
555
  * have connected yet, so Conveno does not ask for a second one. `backgroundTasks` entries have a
@@ -538,37 +572,28 @@ function isOneShotGrok(command) {
538
572
  return Array.from(command.matchAll(/"([^"]*)"|(\S+)/g)).some((m) => ONE_SHOT.test(m[1] ?? m[2] ?? ""));
539
573
  }
540
574
  /** Where "already asked" is remembered: one empty file per Conveno session, in the data dir. */
541
- const askedFile = (sessionId) => join(dataDir(process.platform, process.env, homedir()), "grok-watch-asked", sessionId.replace(/[^A-Za-z0-9_-]/g, "_"));
542
- async function wasAsked(sessionId) {
543
- try {
544
- await readFile(askedFile(sessionId));
545
- return true;
546
- } catch {
547
- return false;
548
- }
549
- }
550
- /** Best effort: deletes the markers in `dir` not touched for `ASKED_MAX_AGE_MS`. */
551
- async function pruneAsked(dir, now = Date.now()) {
552
- try {
553
- for (const name of await readdir(dir)) try {
554
- const f = join(dir, name);
555
- if (now - (await stat(f)).mtimeMs > 6048e5) await rm(f, { force: true });
556
- } catch {}
557
- } catch {}
558
- }
559
- /** Best effort: when it fails the ask can repeat, which is only a nag. */
560
- async function markAsked(sessionId) {
561
- try {
562
- const f = askedFile(sessionId);
563
- await mkdir(join(f, ".."), { recursive: true });
564
- await writeFile(f, "");
565
- await pruneAsked(join(f, ".."));
566
- } catch {}
567
- }
575
+ const { wasAsked, markAsked } = askedMarker("grok-watch-asked");
568
576
  /** The payload as an object, or empty when Grok sent none. */
569
577
  const asInput = (input) => isObject(input) ? input : {};
570
578
  /** A subagent's own session runs the same hooks; its turns are not the session's (10-hooks.md). */
571
579
  const inSubagent = (input) => typeof input.subagentType === "string" && input.subagentType !== "";
580
+ /**
581
+ * The hook's context with Grok's own session id (`sessionId`; `session_id` in the snake_case form of
582
+ * the same input), which the daemon binds to the window's session: Grok starts a new MCP server per
583
+ * conversation under one host process, and the window's session follows the conversation. Only a
584
+ * conversation start or a prompt may move the window to it; the hooks of any other conversation
585
+ * than the current one are ignored.
586
+ */
587
+ function withConversation(data, ctx, turnStart) {
588
+ const id = data.sessionId ?? data.session_id;
589
+ if (typeof id !== "string" || id === "" || id.length > 256) return ctx;
590
+ return {
591
+ ...ctx,
592
+ cli: ctx.cli ?? "grok",
593
+ nativeId: id,
594
+ turnStart
595
+ };
596
+ }
572
597
  /** Tells the daemon the session is busy. Never throws; the answer is empty because Grok drops it. */
573
598
  async function markBusy(ctx) {
574
599
  try {
@@ -589,18 +614,24 @@ async function stopHook(input, ctx) {
589
614
  const genuine = input.reason === void 0 || input.reason === "end_turn";
590
615
  if (inSubagent(input)) return EMPTY;
591
616
  const continuation = await endTurnContinuation(ctx, { allowContinue: genuine });
592
- let ask = false;
593
- if (genuine && input.stopHookActive !== true && !hasWatchMonitor(input)) try {
617
+ let askFor = null;
618
+ if (continuation === null && genuine && input.stopHookActive !== true && !hasWatchMonitor(input)) try {
594
619
  const session = await ownSession(ctx);
595
- if (session !== null && session.deliveryTier !== "live" && !await wasAsked(session.id)) {
596
- const command = await readCommandLine(ctx.hostPid, defaultProcessIo, ASK_READ_TIMEOUT_MS);
597
- ask = command !== null && !isOneShotGrok(command);
598
- if (ask) await markAsked(session.id);
620
+ const key = session && askedKey(session.id, ctx.nativeId);
621
+ if (session !== null && key && session.deliveryTier !== "live" && !await wasAsked(key)) {
622
+ const hostPid = await hostPidOf(ctx);
623
+ const command = hostPid === void 0 ? null : await readCommandLine(hostPid, defaultProcessIo, ASK_READ_TIMEOUT_MS);
624
+ if (command !== null && !isOneShotGrok(command)) askFor = key;
599
625
  }
600
626
  } catch {
601
- ask = false;
627
+ askFor = null;
628
+ }
629
+ const ask = askFor !== null && !late(ctx, {});
630
+ if (ask && askFor !== null) {
631
+ await markAsked(askFor);
632
+ await markBusy(ctx);
602
633
  }
603
- const text = [continuation, ask ? WATCHER_REQUEST : null].filter((t) => t !== null).join("\n\n");
634
+ const text = [continuation, ask ? watcherRequest(ctx.nativeId) : null].filter((t) => t !== null).join("\n\n");
604
635
  return text === "" ? EMPTY : context(HOOK_EVENT, text);
605
636
  }
606
637
  /**
@@ -629,7 +660,14 @@ async function stopHook(input, ctx) {
629
660
  */
630
661
  async function hook(event, input, ctx) {
631
662
  const data = asInput(input);
663
+ ctx = withConversation(data, ctx, event === SESSION_START_EVENT || event === TURN_START_EVENT);
632
664
  switch (event) {
665
+ case SESSION_START_EVENT:
666
+ if (!inSubagent(data)) await ownSession(ctx).catch(() => null);
667
+ return EMPTY;
668
+ case SESSION_END_EVENT:
669
+ if (!inSubagent(data)) await markIdle(ctx);
670
+ return EMPTY;
633
671
  case MID_TURN_EVENT: {
634
672
  if (inSubagent(data)) return EMPTY;
635
673
  const text = await pendingHookContext(ctx);