@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.
@@ -0,0 +1,671 @@
1
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ 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";
5
+ import { n as cs, t as Za } from "./toml-patch-DGzVRdd1.js";
6
+ // ../adapters/grok/dist/index.js
7
+ const SERVER_NAME = "conveno";
8
+ /** The pattern of the allow rule: every tool of our server, in Grok's `server__tool` spelling. */
9
+ const RULE_PATTERN = `${SERVER_NAME}__*`;
10
+ var ConfigParseError = class extends Error {};
11
+ function parseToml(path, text) {
12
+ try {
13
+ return cs(text);
14
+ } catch (err) {
15
+ 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.`);
16
+ }
17
+ }
18
+ const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19
+ function serverOf(doc) {
20
+ const ours = isTable(doc.mcp_servers) ? doc.mcp_servers[SERVER_NAME] : void 0;
21
+ return isTable(ours) ? ours : void 0;
22
+ }
23
+ const matchesSpec = (server, spec) => server !== void 0 && server.command === spec.command && JSON.stringify(server.args) === JSON.stringify(spec.args);
24
+ /** True for the MCP allow rule Conveno writes. Extra keys on the rule make it someone else's. */
25
+ const isMcpRule = (r) => isTable(r) && r.action === "allow" && r.tool === "mcp" && r.pattern === "conveno__*" && Object.keys(r).length === 3;
26
+ /** Tail of the watch rule Conveno writes. Grok splits chains and refuses `$(...)` before it matches. */
27
+ const WATCH_TAIL = " watch *";
28
+ /** Tail of the narrower rule an earlier build wrote; it never matched a quoted Windows command. */
29
+ const NARROW_TAIL = " watch [a-z0-9]*";
30
+ /** The last word of a conveno command: the `conveno` launcher or a script such as `.../bin.js`. */
31
+ const CONVENO_WORD = /(?:^|[/\\ ])(?:conveno(?:\.cmd|\.ps1|\.exe)?|bin\.[cm]?js)$/;
32
+ /**
33
+ * True for an allow rule that lets Conveno's `watch` command run without a prompt: a bash rule
34
+ * whose pattern is `<conveno command> watch *` (or, with `pattern`, any exact string, such as the
35
+ * narrower `... watch [a-z0-9]*` of an earlier build). Without `pattern`, any conveno path, which
36
+ * only install uses to replace a stale rule after a move: the word before `watch` must be a conveno
37
+ * launcher or script, so a user's own `/x/conveno-tools watch *` is never taken for ours.
38
+ * Uninstall always passes exact patterns (`isOurRule`).
39
+ */
40
+ const isWatchRule = (r, pattern) => {
41
+ if (!(isTable(r) && r.action === "allow" && r.tool === "bash") || typeof r.pattern !== "string" || Object.keys(r).length !== 3) return false;
42
+ if (pattern !== void 0) return r.pattern === pattern;
43
+ if (r.pattern.endsWith(" watch [a-z0-9]*")) return true;
44
+ return r.pattern.endsWith(" watch *") && CONVENO_WORD.test(r.pattern.slice(0, -8).replace(/"/g, ""));
45
+ };
46
+ /** Either of the allow rules Conveno wrote, the watch one only if its pattern is one of `watchPatterns`. */
47
+ const isOurRule = (r, watchPatterns) => isMcpRule(r) || watchPatterns.some((p) => isWatchRule(r, p));
48
+ function rulesOf(doc) {
49
+ const rules = isTable(doc.permission) ? doc.permission.rules : void 0;
50
+ return Array.isArray(rules) ? rules : void 0;
51
+ }
52
+ /** True when the MCP rule and the exact watch rule are both there. */
53
+ const hasRules = (doc, watchPattern) => {
54
+ const rules = rulesOf(doc) ?? [];
55
+ return rules.some(isMcpRule) && rules.some((r) => isWatchRule(r, watchPattern));
56
+ };
57
+ /** True when any rule of ours is there (the watch rule only with one of `watchPatterns`). */
58
+ const hasAnyRule = (doc, watchPatterns) => rulesOf(doc)?.some((r) => isOurRule(r, watchPatterns)) ?? false;
59
+ const eolOf = (text) => text.includes("\r\n") ? "\r\n" : "\n";
60
+ /** TOML basic strings use the same escapes as JSON for everything we write. */
61
+ const q = (s) => JSON.stringify(s);
62
+ function serverText(spec, eol) {
63
+ return [
64
+ `[mcp_servers.${SERVER_NAME}]`,
65
+ `command = ${q(spec.command)}`,
66
+ `args = [${spec.args.map(q).join(", ")}]`,
67
+ ""
68
+ ].join(eol);
69
+ }
70
+ function ruleText(eol, tool, pattern) {
71
+ return [
72
+ "[[permission.rules]]",
73
+ "action = \"allow\"",
74
+ `tool = ${q(tool)}`,
75
+ `pattern = ${q(pattern)}`,
76
+ ""
77
+ ].join(eol);
78
+ }
79
+ const EMPTYABLE = /* @__PURE__ */ new Set([
80
+ "mcp_servers",
81
+ "permission",
82
+ "rules"
83
+ ]);
84
+ /** A copy of `v` in which an emptied `mcp_servers`, `permission` or `rules` is gone, children first. */
85
+ function prune(v) {
86
+ if (Array.isArray(v)) return v.map(prune);
87
+ if (!isTable(v)) return v;
88
+ const out = {};
89
+ for (const [k, child] of Object.entries(v)) {
90
+ const p = prune(child);
91
+ if (!((Array.isArray(p) && p.length === 0 || isTable(p) && Object.keys(p).length === 0) && EMPTYABLE.has(k))) out[k] = p;
92
+ }
93
+ return out;
94
+ }
95
+ /** Compare parsed data, treating an emptied `mcp_servers`, `permission` or `rules` as missing. */
96
+ const sameData = (a, b) => JSON.stringify(prune(a)) === JSON.stringify(prune(b));
97
+ /** `text` with a header line as the start of each section. The first one has no header. */
98
+ function sections(text) {
99
+ const out = [{
100
+ key: null,
101
+ text: ""
102
+ }];
103
+ for (const line of text.split(/(?<=\n)/)) {
104
+ const m = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/.exec(line.replace(/\r?\n$/, ""));
105
+ if (m) out.push({
106
+ key: m[1].replace(/["'\s]/g, ""),
107
+ text: line
108
+ });
109
+ else out.at(-1).text += line;
110
+ }
111
+ return out;
112
+ }
113
+ /**
114
+ * Drop the sections whose header is `key` (or a subtable of it) and for which `drop` returns true.
115
+ * The blank line that separated a dropped last section from the rest goes with it.
116
+ */
117
+ function dropSections(text, keys, drop) {
118
+ const all = sections(text);
119
+ let lastDropped = false;
120
+ let out = all.filter((s, i) => {
121
+ const hit = s.key !== null && keys.some((k) => s.key === k || s.key?.startsWith(`${k}.`)) && drop(s.text);
122
+ if (i === all.length - 1) lastDropped = hit;
123
+ return !hit;
124
+ }).map((s) => s.text).join("");
125
+ if (lastDropped) out = out.replace(/(\r?\n)+$/, "") + (out.trim() === "" ? "" : eolOf(text));
126
+ return out;
127
+ }
128
+ const parsesTo = (text, expected) => {
129
+ try {
130
+ return sameData(cs(text), expected);
131
+ } catch {
132
+ return false;
133
+ }
134
+ };
135
+ /** Drop the `[[permission.rules]]` sections that hold one of our watch rules, other than `keep`. */
136
+ function dropStaleWatchRules(text, keep) {
137
+ return dropSections(text, ["permission.rules"], (section) => {
138
+ try {
139
+ const rule = cs(section).permission?.rules;
140
+ return rule?.length === 1 && isWatchRule(rule[0]) && !isWatchRule(rule[0], keep);
141
+ } catch {
142
+ return false;
143
+ }
144
+ });
145
+ }
146
+ /**
147
+ * Add our server table and our two allow rules (the MCP tools, and the `watch` command at
148
+ * `watchPattern`) where they are missing, by appending text to the file. A watch rule for another
149
+ * conveno path is replaced. If the result does not parse to the expected data (for example the user
150
+ * already defines the rules as an inline `rules = [...]`), fall back to a comment-preserving patch.
151
+ */
152
+ function addConfig(path, before, spec, watchPattern) {
153
+ const doc = parseToml(path, before);
154
+ const expected = structuredClone(doc);
155
+ const servers = isTable(expected.mcp_servers) ? expected.mcp_servers : {};
156
+ servers[SERVER_NAME] = {
157
+ command: spec.command,
158
+ args: spec.args
159
+ };
160
+ expected.mcp_servers = servers;
161
+ const permission = isTable(expected.permission) ? expected.permission : {};
162
+ const rules = (Array.isArray(permission.rules) ? permission.rules : []).filter((r) => !isWatchRule(r) || isWatchRule(r, watchPattern));
163
+ if (!rules.some(isMcpRule)) rules.push({
164
+ action: "allow",
165
+ tool: "mcp",
166
+ pattern: RULE_PATTERN
167
+ });
168
+ if (!rules.some((r) => isWatchRule(r, watchPattern))) rules.push({
169
+ action: "allow",
170
+ tool: "bash",
171
+ pattern: watchPattern
172
+ });
173
+ permission.rules = rules;
174
+ expected.permission = permission;
175
+ const eol = eolOf(before);
176
+ const needServer = !matchesSpec(serverOf(doc), spec);
177
+ let text = needServer && serverOf(doc) ? removeServerText(before) : before;
178
+ text = dropStaleWatchRules(text, watchPattern);
179
+ const rulesBefore = rulesOf(doc) ?? [];
180
+ const append = (block) => {
181
+ const sep = text === "" ? "" : text.endsWith("\n") ? eol : eol + eol;
182
+ text = text + sep + block;
183
+ };
184
+ if (needServer) append(serverText(spec, eol));
185
+ if (!rulesBefore.some(isMcpRule)) append(ruleText(eol, "mcp", RULE_PATTERN));
186
+ if (!rulesBefore.some((r) => isWatchRule(r, watchPattern))) append(ruleText(eol, "bash", watchPattern));
187
+ if (parsesTo(text, expected)) return text;
188
+ return Za(before, expected);
189
+ }
190
+ function removeServerText(text) {
191
+ return dropSections(text, [`mcp_servers.${SERVER_NAME}`], () => true);
192
+ }
193
+ /** Remove our server table (and its subtables) and the allow rules Conveno wrote, matched exactly. Everything else stays byte for byte. */
194
+ function removeConfig(path, before, watchPatterns) {
195
+ const doc = parseToml(path, before);
196
+ const expected = structuredClone(doc);
197
+ if (isTable(expected.mcp_servers)) delete expected.mcp_servers[SERVER_NAME];
198
+ const rules = rulesOf(expected);
199
+ if (rules && isTable(expected.permission)) expected.permission.rules = rules.filter((r) => !isOurRule(r, watchPatterns));
200
+ const text = dropSections(removeServerText(before), ["permission.rules"], (section) => {
201
+ try {
202
+ const rule = cs(section).permission?.rules;
203
+ return rule?.length === 1 && isOurRule(rule[0], watchPatterns);
204
+ } catch {
205
+ return false;
206
+ }
207
+ });
208
+ if (parsesTo(text, expected)) return text;
209
+ return Za(before, expected);
210
+ }
211
+ /** `$GROK_HOME`, else `~/.grok` (`%USERPROFILE%\.grok` on Windows). */
212
+ const grokDir = (env) => env.env.GROK_HOME || join(env.home, ".grok");
213
+ const configPath = (env) => join(grokDir(env), "config.toml");
214
+ /**
215
+ * Grok loads every `*.json` file in `$GROK_HOME/hooks`, always trusted. Conveno's hook gets a file
216
+ * of its own: `config.toml` carries the MCP change, and one file cannot take two changes.
217
+ */
218
+ const hooksPath = (env) => join(grokDir(env), "hooks", "conveno.json");
219
+ /**
220
+ * Home rules: Grok reads every `*.md` in `$GROK_HOME/rules` for every project, whatever the folder
221
+ * trust (user guide 12-project-rules.md). Conveno's wake instructions get a file of their own.
222
+ */
223
+ const rulesPath = (env) => join(grokDir(env), "rules", "conveno.md");
224
+ /** The agent is about to end its turn. */
225
+ const HOOK_EVENT = "Stop";
226
+ /** A tool finished: the one point inside a turn where a hook can hand the model text. */
227
+ const MID_TURN_EVENT = "PostToolUse";
228
+ /** A prompt the user typed, or an automatic wake: the turn starts. Its output cannot add text. */
229
+ const TURN_START_EVENT = "UserPromptSubmit";
230
+ /** A turn ended in an error or was cancelled. Both are observe-only (10-hooks.md, StopFailure). */
231
+ const TURN_FAILED_EVENTS = ["StopFailure", "StopCancelled"];
232
+ /** Fires after any turn end, and again once the session has settled (10-hooks.md, idle_prompt). */
233
+ const IDLE_EVENT = "Notification";
234
+ /** The `Notification` matcher: only the idle ping reaches the hook. */
235
+ const IDLE_MATCHER = "idle_prompt";
236
+ /** Every hook event Conveno installs. */
237
+ const HOOK_EVENTS = [
238
+ HOOK_EVENT,
239
+ MID_TURN_EVENT,
240
+ TURN_START_EVENT,
241
+ ...TURN_FAILED_EVENTS,
242
+ IDLE_EVENT
243
+ ];
244
+ const EMPTY = {
245
+ stdout: "",
246
+ exitCode: 0
247
+ };
248
+ /**
249
+ * Quote one word of a hook command. Grok runs the command in a POSIX shell, and on Windows in
250
+ * Git Bash, PowerShell or cmd.exe, whichever it finds, so the word is written to mean the same in
251
+ * all of them: double quotes only when it needs them, and on Windows forward slashes.
252
+ */
253
+ function quoteHookWord(arg, platform) {
254
+ const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
255
+ return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
256
+ }
257
+ const hookCommand = (env, event) => [
258
+ ...env.conveno.command,
259
+ "hook",
260
+ "grok",
261
+ event
262
+ ].map((w) => quoteHookWord(w, env.platform)).join(" ");
263
+ /**
264
+ * The matcher group in the hook file. Only `Notification` has a matcher (a matcher on `Stop` or
265
+ * `UserPromptSubmit` is ignored with a warning, 10-hooks.md, matcher).
266
+ */
267
+ const desiredGroup = (env, event) => ({
268
+ ...event === "Notification" ? { matcher: IDLE_MATCHER } : {},
269
+ hooks: [{
270
+ type: "command",
271
+ command: hookCommand(env, event),
272
+ timeout: 5
273
+ }]
274
+ });
275
+ /** Recognizes our hook command for `event` even if the conveno path changed since install. */
276
+ const isOurHookCommand = (cmd, event) => typeof cmd === "string" && cmd.trim().endsWith(` hook grok ${event}`);
277
+ const isOurGroup = (event) => (g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand(h.command, event));
278
+ const isOurAnyGroup = (g) => HOOK_EVENTS.some((e) => isOurGroup(e)(g));
279
+ /** The `hooks` object of the hook file, and the list of each of our events when there is one. */
280
+ function eventsOf(file, path) {
281
+ const hooks = file.hooks;
282
+ if (hooks !== void 0 && !isObject(hooks)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
283
+ const lists = /* @__PURE__ */ new Map();
284
+ for (const event of HOOK_EVENTS) {
285
+ const list = hooks?.[event];
286
+ 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.`);
287
+ lists.set(event, list);
288
+ }
289
+ return {
290
+ hooks,
291
+ lists
292
+ };
293
+ }
294
+ async function readIfExists(path) {
295
+ try {
296
+ return await readFile(path, "utf8");
297
+ } catch (err) {
298
+ if (err.code === "ENOENT") return null;
299
+ throw err;
300
+ }
301
+ }
302
+ const specOf = (env) => {
303
+ const [command = "conveno", ...args] = [
304
+ ...env.conveno.command,
305
+ "mcp",
306
+ "--cli",
307
+ "grok"
308
+ ];
309
+ return {
310
+ command,
311
+ args
312
+ };
313
+ };
314
+ async function detect(env) {
315
+ const configPaths = [configPath(env)];
316
+ try {
317
+ const r = await env.exec("grok", ["--version"]);
318
+ if (r.code !== 0) return {
319
+ installed: false,
320
+ configPaths
321
+ };
322
+ const version = parseCliVersion(r.stdout);
323
+ return {
324
+ installed: true,
325
+ binary: "grok",
326
+ ...version ? { version } : {},
327
+ configPaths
328
+ };
329
+ } catch {
330
+ return {
331
+ installed: false,
332
+ configPaths
333
+ };
334
+ }
335
+ }
336
+ /** First line of the rules file: how Conveno tells the file is its own. */
337
+ 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
+ /**
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
348
+ * on ; && || | and every part must match (bash_commands.rs:58-104), and `$(...)` or backticks are
349
+ * not eligible for an allow (bash_permission_script.rs:58-64). Monitor is checked as a Bash command
350
+ * (xai-grok-tools permission_access.rs:55).
351
+ */
352
+ 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)];
356
+ /**
357
+ * What the Grok agent is told once, in a rules file Grok loads for every project. Idle wake needs
358
+ * the agent's own help: Grok has no way to push text into an idle session, but it wakes on every
359
+ * line a monitor prints, so the agent starts `conveno watch` in one persistent monitor.
360
+ */
361
+ function rulesText(env) {
362
+ return `${[
363
+ RULES_MARKER,
364
+ "# Conveno",
365
+ "",
366
+ "Conveno connects this session to your other AI coding sessions. The user's request always comes first: do it before anything below. This is a quick side step that never blocks, delays or replaces the task.",
367
+ "",
368
+ "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
+ "",
370
+ "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.`,
372
+ "",
373
+ "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
+ "",
375
+ "Every line the monitor prints starts with `[conveno]` and is one message:",
376
+ `- "The user sent a message through Conveno": ${FROM_USER_NOTICE}`,
377
+ `- "Task from the lead": ${ORCHESTRATOR_TASK_NOTICE}`,
378
+ `- "sent a message (not from the user)": ${NOT_FROM_USER_NOTICE}`,
379
+ "",
380
+ "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."
381
+ ].join("\n")}\n`;
382
+ }
383
+ async function plan(env) {
384
+ const changes = [];
385
+ const path = configPath(env);
386
+ const before = await readIfExists(path);
387
+ const doc = parseToml(path, before ?? "");
388
+ const spec = specOf(env);
389
+ const pattern = watchPattern(env);
390
+ const server = serverOf(doc);
391
+ if (!matchesSpec(server, spec) || !hasRules(doc, pattern)) changes.push({
392
+ component: "mcp",
393
+ kind: server ? "update" : "add",
394
+ parts: [{
395
+ name: "MCP server",
396
+ kind: server ? "update" : "add"
397
+ }],
398
+ path,
399
+ before,
400
+ after: addConfig(path, before ?? "", spec, pattern),
401
+ description: `Register the "${SERVER_NAME}" MCP server (conveno mcp --cli grok) and allow its tools (permission rule MCPTool(${RULE_PATTERN})) and the idle-wake watcher (permission rule Bash(${pattern})).`
402
+ });
403
+ const hp = hooksPath(env);
404
+ const hookFile = await loadJson(hp);
405
+ const { hooks, lists } = eventsOf(hookFile.value, hp);
406
+ const edits = [];
407
+ const parts = [];
408
+ let anyOurs = false;
409
+ for (const event of HOOK_EVENTS) {
410
+ const list = lists.get(event);
411
+ const want = desiredGroup(env, event);
412
+ if (list?.some((g) => sameJson(g, want))) continue;
413
+ const has = list?.some(isOurGroup(event)) ?? false;
414
+ anyOurs ||= has;
415
+ parts.push({
416
+ name: `${event} hook`,
417
+ kind: has ? "update" : "add"
418
+ });
419
+ edits.push(...hooks === void 0 && edits.length === 0 ? [{
420
+ path: ["hooks"],
421
+ value: { [event]: [want] }
422
+ }] : list === void 0 ? [{
423
+ path: ["hooks", event],
424
+ value: [want]
425
+ }] : putInList(list, ["hooks", event], want, isOurGroup(event)));
426
+ }
427
+ if (edits.length > 0) changes.push({
428
+ component: "hooks",
429
+ kind: anyOurs ? "update" : "add",
430
+ parts,
431
+ path: hp,
432
+ before: hookFile.raw,
433
+ 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.`
435
+ });
436
+ const rp = rulesPath(env);
437
+ const rulesBefore = await readIfExists(rp);
438
+ const rulesAfter = rulesText(env);
439
+ if (rulesBefore !== rulesAfter) changes.push({
440
+ component: "hooks",
441
+ kind: rulesBefore === null ? "add" : "update",
442
+ parts: [{
443
+ name: "Wake instructions",
444
+ kind: rulesBefore === null ? "add" : "update"
445
+ }],
446
+ path: rp,
447
+ before: rulesBefore,
448
+ after: rulesAfter,
449
+ description: "Tell Grok to start `conveno watch` in a persistent monitor, so messages wake it while idle."
450
+ });
451
+ return changes;
452
+ }
453
+ async function uninstallPlan(env, baseline) {
454
+ const changes = [];
455
+ const path = configPath(env);
456
+ const before = await readIfExists(path);
457
+ if (before !== null) {
458
+ const doc = parseToml(path, before);
459
+ if (serverOf(doc) || hasAnyRule(doc, ownPatterns(env))) changes.push({
460
+ component: "mcp",
461
+ kind: "remove",
462
+ path,
463
+ before,
464
+ after: removeConfig(path, before, ownPatterns(env)),
465
+ description: `Remove the "${SERVER_NAME}" MCP server and its permission rules.`
466
+ });
467
+ }
468
+ const hp = hooksPath(env);
469
+ const hookFile = await loadJson(hp);
470
+ const { hooks, lists } = eventsOf(hookFile.value, hp);
471
+ if (hookFile.raw !== null && [...lists.values()].some((l) => l?.some(isOurAnyGroup))) {
472
+ const base = baseline?.get(hp);
473
+ 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;
474
+ const description = "Remove the Conveno hooks.";
475
+ if (onlyOurs && typeof base !== "string") changes.push({
476
+ component: "hooks",
477
+ kind: "remove",
478
+ path: hp,
479
+ before: hookFile.raw,
480
+ after: "",
481
+ description,
482
+ deleteFile: true
483
+ });
484
+ else {
485
+ const edits = [];
486
+ for (const event of HOOK_EVENTS) {
487
+ const list = lists.get(event);
488
+ if (!list?.some(isOurGroup(event))) continue;
489
+ edits.push(...dropFromList(list, ["hooks", event], isOurGroup(event), { keepEmpty: existedBefore(base, ["hooks", event]) }));
490
+ }
491
+ changes.push({
492
+ component: "hooks",
493
+ kind: "remove",
494
+ path: hp,
495
+ before: hookFile.raw,
496
+ after: editJson(hookFile, edits),
497
+ description
498
+ });
499
+ }
500
+ }
501
+ const rp = rulesPath(env);
502
+ const rulesBefore = await readIfExists(rp);
503
+ if (rulesBefore?.startsWith(RULES_MARKER)) changes.push({
504
+ component: "hooks",
505
+ kind: "remove",
506
+ path: rp,
507
+ before: rulesBefore,
508
+ after: "",
509
+ description: "Remove the Conveno wake instructions.",
510
+ deleteFile: true
511
+ });
512
+ return changes;
513
+ }
514
+ /**
515
+ * What Stop asks the model when no watcher is connected. Fixed text: the rules file says how.
516
+ * It is a request from Conveno's own hook, so it carries no peer text.
517
+ */
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.";
519
+ /**
520
+ * True when a Stop payload lists a monitor that runs `watch`: the watcher is started but may not
521
+ * have connected yet, so Conveno does not ask for a second one. `backgroundTasks` entries have a
522
+ * `type` and, for a monitor, the watched command line in `description` (10-hooks.md, Stop input).
523
+ */
524
+ function hasWatchMonitor(input) {
525
+ const tasks = input.backgroundTasks;
526
+ return Array.isArray(tasks) && tasks.some((t) => isObject(t) && t.type === "monitor" && typeof t.description === "string" && /(^|\s)watch(\s|$)/.test(t.description));
527
+ }
528
+ /**
529
+ * Grok's one-shot flags: `-p` (long `--single`, alias `--print`), `--prompt-json` and `--prompt-file`
530
+ * (grok-build xai-grok-pager app/cli.rs:462-496). They start the headless runner, which nobody wakes.
531
+ */
532
+ const ONE_SHOT = /^(?:-p|--single|--print|--prompt-json|--prompt-file)(?:=|$)/;
533
+ /** How long the Stop hook waits for the host's command line before skipping the ask. */
534
+ const ASK_READ_TIMEOUT_MS = 1500;
535
+ /** True when `command` (a Grok command line) is a one-shot run. */
536
+ function isOneShotGrok(command) {
537
+ if (!command) return false;
538
+ return Array.from(command.matchAll(/"([^"]*)"|(\S+)/g)).some((m) => ONE_SHOT.test(m[1] ?? m[2] ?? ""));
539
+ }
540
+ /** 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
+ }
568
+ /** The payload as an object, or empty when Grok sent none. */
569
+ const asInput = (input) => isObject(input) ? input : {};
570
+ /** A subagent's own session runs the same hooks; its turns are not the session's (10-hooks.md). */
571
+ const inSubagent = (input) => typeof input.subagentType === "string" && input.subagentType !== "";
572
+ /** Tells the daemon the session is busy. Never throws; the answer is empty because Grok drops it. */
573
+ async function markBusy(ctx) {
574
+ try {
575
+ const session = await ownSession(ctx);
576
+ if (session) await ctx.client["turn.start"]({ sessionId: session.id });
577
+ } catch {}
578
+ }
579
+ /** Tells the daemon the turn ended without handing anything over. */
580
+ async function markIdle(ctx) {
581
+ await endTurnContinuation(ctx, { allowContinue: false });
582
+ }
583
+ /**
584
+ * The Stop hook. Records the turn end and hands over waiting messages. Without a connected
585
+ * watcher it also asks the model, once per session, to start one: idle wake depends on it, and
586
+ * the rules file alone leaves it to the model's memory.
587
+ */
588
+ async function stopHook(input, ctx) {
589
+ const genuine = input.reason === void 0 || input.reason === "end_turn";
590
+ if (inSubagent(input)) return EMPTY;
591
+ const continuation = await endTurnContinuation(ctx, { allowContinue: genuine });
592
+ let ask = false;
593
+ if (genuine && input.stopHookActive !== true && !hasWatchMonitor(input)) try {
594
+ 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);
599
+ }
600
+ } catch {
601
+ ask = false;
602
+ }
603
+ const text = [continuation, ask ? WATCHER_REQUEST : null].filter((t) => t !== null).join("\n\n");
604
+ return text === "" ? EMPTY : context(HOOK_EVENT, text);
605
+ }
606
+ /**
607
+ * Hooks. A hook can hand text to the model in two places:
608
+ * - PostToolUse: `hookSpecificOutput.additionalContext` lands next to the tool result, inside the
609
+ * turn (user guide 10-hooks.md, PostToolUse Output). Messages that arrive while Grok works
610
+ * reach it after its next tool call.
611
+ * - Stop: records the turn end. With messages waiting, after a genuine turn end (`reason`
612
+ * `end_turn`), `hookSpecificOutput.additionalContext` keeps the agent working and is shown as
613
+ * hook feedback, not as a hook error (10-hooks.md, Stop Decision Control). The session-end
614
+ * fire (`channel_closed`, `shutdown`) only records. Grok overrides the gate after 8
615
+ * continuations in a turn, and Conveno's auto-mode limit bounds the chain before that. When
616
+ * the session has no connected watcher (the daemon's tier is not `live`) and the payload lists
617
+ * no `watch` monitor, the same output asks the model to start one, except while
618
+ * `stopHookActive`, in a one-shot run, or when the session was asked before (a marker file in
619
+ * the data dir): one ask per session.
620
+ * Busy and idle follow 10-hooks.md, "A complete busy and idle indicator": `UserPromptSubmit` marks
621
+ * the session busy (its output is discarded, so it never takes messages); `StopFailure`,
622
+ * `StopCancelled` and the `idle_prompt` `Notification` mark it idle, so a failed or cancelled turn
623
+ * does not leave it busy. A subagent's events are skipped. Reports of an older turn can arrive
624
+ * after the next prompt (the doc says to track `promptId`); Conveno does not, and the next tool
625
+ * result or turn end corrects the state.
626
+ * `SessionStart` output cannot add text, so a message that arrives while the session is idle
627
+ * reaches it through `conveno watch` in a monitor, not through a hook.
628
+ * Never throws and never writes to stderr: any failure means "deliver nothing this time".
629
+ */
630
+ async function hook(event, input, ctx) {
631
+ const data = asInput(input);
632
+ switch (event) {
633
+ case MID_TURN_EVENT: {
634
+ if (inSubagent(data)) return EMPTY;
635
+ const text = await pendingHookContext(ctx);
636
+ return text === null ? EMPTY : context(MID_TURN_EVENT, text);
637
+ }
638
+ case HOOK_EVENT: return stopHook(data, ctx);
639
+ case TURN_START_EVENT:
640
+ if (!inSubagent(data)) await markBusy(ctx);
641
+ return EMPTY;
642
+ case IDLE_EVENT:
643
+ case "StopFailure":
644
+ case "StopCancelled":
645
+ if (!inSubagent(data)) await markIdle(ctx);
646
+ return EMPTY;
647
+ default: return EMPTY;
648
+ }
649
+ }
650
+ const context = (hookEventName, additionalContext) => ({
651
+ stdout: JSON.stringify({ hookSpecificOutput: {
652
+ hookEventName,
653
+ additionalContext
654
+ } }),
655
+ exitCode: 0
656
+ });
657
+ const grokAdapter = {
658
+ cli: "grok",
659
+ displayName: "Grok",
660
+ deliveryTier: "inbox",
661
+ delivery: () => ({
662
+ nextTurn: false,
663
+ endOfTurn: true,
664
+ idleWake: true
665
+ }),
666
+ detect,
667
+ plan,
668
+ uninstallPlan,
669
+ hook
670
+ };
671
+ export { isOneShotGrok as n, grokAdapter as t };
@@ -3,7 +3,7 @@ import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
3
3
  import { createConnection } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
- import { A as daemonProof, M as dataPaths, Qt as EventPayload, Sn as socketPathTooLongMessage, T as clientProof, an as RpcResponse, cn as defaultSocketPath, dn as isSocketPathTooLong, in as RpcErrorCode, j as dataDir, ln as encodeFrame, mt as proofsMatch, nn as PROTOCOL_VERSION, nt as newAuthNonce, r as ConvenoError, sn as createLineDecoder, un as ipcMethods } from "./dist-BTLBO1Rp.js";
6
+ import { A as daemonProof, En as socketPathTooLongMessage, M as dataPaths, T as clientProof, an as PROTOCOL_VERSION, cn as RpcResponse, dn as createLineDecoder, fn as defaultSocketPath, hn as isSocketPathTooLong, ht as proofsMatch, j as dataDir, mn as ipcMethods, pn as encodeFrame, r as ConvenoError, rt as newAuthNonce, sn as RpcErrorCode, tn as EventPayload } from "./dist-BBdba94T.js";
7
7
  // ../client/dist/index.js
8
8
  const DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
9
9
  const DEFAULT_START_TIMEOUT_MS = 1e4;