@songsid/agend 2.3.5-beta.5 → 2.3.6-beta.1

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 (214) hide show
  1. package/README.md +11 -1
  2. package/README.zh-TW.md +11 -1
  3. package/dist/agent-cli-instructions.md +15 -9
  4. package/dist/agent-cli.js +47 -20
  5. package/dist/agent-cli.js.map +1 -1
  6. package/dist/agent-endpoint.js +23 -8
  7. package/dist/agent-endpoint.js.map +1 -1
  8. package/dist/agent-list-output.d.ts +23 -0
  9. package/dist/agent-list-output.js +53 -0
  10. package/dist/agent-list-output.js.map +1 -0
  11. package/dist/agent-whats-new.js +10 -7
  12. package/dist/agent-whats-new.js.map +1 -1
  13. package/dist/auth-api.js +3 -1
  14. package/dist/auth-api.js.map +1 -1
  15. package/dist/backend/agy-onboarding.d.ts +14 -0
  16. package/dist/backend/agy-onboarding.js +114 -0
  17. package/dist/backend/agy-onboarding.js.map +1 -0
  18. package/dist/backend/antigravity.js +3 -0
  19. package/dist/backend/antigravity.js.map +1 -1
  20. package/dist/backend/claude-code.d.ts +8 -0
  21. package/dist/backend/claude-code.js +11 -4
  22. package/dist/backend/claude-code.js.map +1 -1
  23. package/dist/backend/codex.d.ts +7 -14
  24. package/dist/backend/codex.js +32 -32
  25. package/dist/backend/codex.js.map +1 -1
  26. package/dist/backend/grok-mcp.d.ts +5 -0
  27. package/dist/backend/grok-mcp.js +221 -0
  28. package/dist/backend/grok-mcp.js.map +1 -0
  29. package/dist/backend/grok.d.ts +19 -10
  30. package/dist/backend/grok.js +117 -83
  31. package/dist/backend/grok.js.map +1 -1
  32. package/dist/backend/types.d.ts +16 -1
  33. package/dist/backend/types.js.map +1 -1
  34. package/dist/channel/mcp-tools.js +10 -10
  35. package/dist/channel/mcp-tools.js.map +1 -1
  36. package/dist/claude-model-observation.d.ts +71 -0
  37. package/dist/claude-model-observation.js +169 -0
  38. package/dist/claude-model-observation.js.map +1 -0
  39. package/dist/cli.js +62 -12
  40. package/dist/cli.js.map +1 -1
  41. package/dist/codex-pane-ownership.d.ts +13 -0
  42. package/dist/codex-pane-ownership.js +192 -0
  43. package/dist/codex-pane-ownership.js.map +1 -0
  44. package/dist/config-validator.js +19 -0
  45. package/dist/config-validator.js.map +1 -1
  46. package/dist/cross-instance-envelope.d.ts +4 -1
  47. package/dist/cross-instance-envelope.js +12 -7
  48. package/dist/cross-instance-envelope.js.map +1 -1
  49. package/dist/daemon.d.ts +26 -2
  50. package/dist/daemon.js +344 -49
  51. package/dist/daemon.js.map +1 -1
  52. package/dist/decision-list.d.ts +5 -4
  53. package/dist/decision-list.js +22 -8
  54. package/dist/decision-list.js.map +1 -1
  55. package/dist/delivery-consumed-watch.d.ts +24 -0
  56. package/dist/delivery-consumed-watch.js +21 -10
  57. package/dist/delivery-consumed-watch.js.map +1 -1
  58. package/dist/delivery-outbox.d.ts +9 -1
  59. package/dist/delivery-outbox.js +16 -0
  60. package/dist/delivery-outbox.js.map +1 -1
  61. package/dist/delivery-reconciliation.d.ts +1 -1
  62. package/dist/delivery-reconciliation.js +1 -1
  63. package/dist/dispatcher-liveness.d.ts +172 -0
  64. package/dist/dispatcher-liveness.js +238 -0
  65. package/dist/dispatcher-liveness.js.map +1 -0
  66. package/dist/fleet-manager.d.ts +30 -2
  67. package/dist/fleet-manager.js +195 -22
  68. package/dist/fleet-manager.js.map +1 -1
  69. package/dist/general-knowledge/skills/concepts/SKILL.md +43 -4
  70. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +17 -2
  71. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +18 -8
  72. package/dist/general-knowledge/skills/fleet-health/SKILL.md +15 -0
  73. package/dist/general-knowledge/skills/multi-channel/SKILL.md +1 -1
  74. package/dist/general-knowledge/skills/scheduling/SKILL.md +1 -1
  75. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +63 -17
  76. package/dist/general-knowledge/skills/worker-collaboration/SKILL.md +5 -1
  77. package/dist/grok-delivery-proof.d.ts +24 -0
  78. package/dist/grok-delivery-proof.js +124 -0
  79. package/dist/grok-delivery-proof.js.map +1 -0
  80. package/dist/human-delivery-receipts.d.ts +4 -2
  81. package/dist/human-delivery-receipts.js +20 -13
  82. package/dist/human-delivery-receipts.js.map +1 -1
  83. package/dist/inbound-presentation.d.ts +28 -0
  84. package/dist/inbound-presentation.js +48 -0
  85. package/dist/inbound-presentation.js.map +1 -0
  86. package/dist/install-user-systemd.d.ts +20 -0
  87. package/dist/install-user-systemd.js +55 -0
  88. package/dist/install-user-systemd.js.map +1 -0
  89. package/dist/instance-config-impact.js +2 -0
  90. package/dist/instance-config-impact.js.map +1 -1
  91. package/dist/instance-lifecycle.d.ts +2 -0
  92. package/dist/instance-lifecycle.js +3 -0
  93. package/dist/instance-lifecycle.js.map +1 -1
  94. package/dist/instructions.d.ts +10 -2
  95. package/dist/instructions.js +32 -7
  96. package/dist/instructions.js.map +1 -1
  97. package/dist/linux-launchers.d.ts +88 -0
  98. package/dist/linux-launchers.js +296 -0
  99. package/dist/linux-launchers.js.map +1 -0
  100. package/dist/locale.js +174 -8
  101. package/dist/locale.js.map +1 -1
  102. package/dist/log-steps.d.ts +13 -0
  103. package/dist/log-steps.js +85 -40
  104. package/dist/log-steps.js.map +1 -1
  105. package/dist/needs-you-hub.js +8 -4
  106. package/dist/needs-you-hub.js.map +1 -1
  107. package/dist/needs-you.d.ts +7 -2
  108. package/dist/needs-you.js +5 -9
  109. package/dist/needs-you.js.map +1 -1
  110. package/dist/office-share-page.js +1 -1
  111. package/dist/office-share-page.js.map +1 -1
  112. package/dist/outbound-handlers.d.ts +1 -0
  113. package/dist/outbound-handlers.js +25 -19
  114. package/dist/outbound-handlers.js.map +1 -1
  115. package/dist/outbound-schemas.d.ts +20 -0
  116. package/dist/outbound-schemas.js +24 -4
  117. package/dist/outbound-schemas.js.map +1 -1
  118. package/dist/queued-handoffs.d.ts +3 -1
  119. package/dist/queued-handoffs.js +1 -1
  120. package/dist/queued-handoffs.js.map +1 -1
  121. package/dist/scheduler/db.d.ts +3 -0
  122. package/dist/scheduler/db.js +4 -0
  123. package/dist/scheduler/db.js.map +1 -1
  124. package/dist/scheduler/task-board.d.ts +1 -0
  125. package/dist/scheduler/task-board.js +10 -1
  126. package/dist/scheduler/task-board.js.map +1 -1
  127. package/dist/scheduler/task-liveness.d.ts +34 -0
  128. package/dist/scheduler/task-liveness.js +49 -0
  129. package/dist/scheduler/task-liveness.js.map +1 -0
  130. package/dist/selection-card.d.ts +4 -3
  131. package/dist/selection-card.js +2 -1
  132. package/dist/selection-card.js.map +1 -1
  133. package/dist/service-installer.js +11 -2
  134. package/dist/service-installer.js.map +1 -1
  135. package/dist/settings-change.d.ts +2 -0
  136. package/dist/settings-change.js +43 -29
  137. package/dist/settings-change.js.map +1 -1
  138. package/dist/settings-confirmation.d.ts +4 -0
  139. package/dist/settings-confirmation.js +5 -1
  140. package/dist/settings-confirmation.js.map +1 -1
  141. package/dist/settings-http-confirmation.js +2 -1
  142. package/dist/settings-http-confirmation.js.map +1 -1
  143. package/dist/settings-summary.d.ts +24 -0
  144. package/dist/settings-summary.js +42 -0
  145. package/dist/settings-summary.js.map +1 -0
  146. package/dist/task-board-tool.d.ts +0 -12
  147. package/dist/task-board-tool.js +52 -4
  148. package/dist/task-board-tool.js.map +1 -1
  149. package/dist/tool-receipt-output.d.ts +151 -0
  150. package/dist/tool-receipt-output.js +50 -0
  151. package/dist/tool-receipt-output.js.map +1 -0
  152. package/dist/topic-commands.js +2 -1
  153. package/dist/topic-commands.js.map +1 -1
  154. package/dist/transcript-delta-reader.d.ts +9 -1
  155. package/dist/transcript-delta-reader.js +37 -8
  156. package/dist/transcript-delta-reader.js.map +1 -1
  157. package/dist/transcript-monitor.d.ts +5 -1
  158. package/dist/transcript-monitor.js +66 -4
  159. package/dist/transcript-monitor.js.map +1 -1
  160. package/dist/transcript-sources.d.ts +2 -0
  161. package/dist/transcript-sources.js +2 -0
  162. package/dist/transcript-sources.js.map +1 -1
  163. package/dist/types.d.ts +10 -0
  164. package/dist/ui/chat-quote.js +12 -17
  165. package/dist/ui/chat-render.js +11 -2
  166. package/dist/ui/chat-strings.js +4 -4
  167. package/dist/ui/fleet-canvas.js +5 -2
  168. package/dist/ui/fleet-office-card.js +4 -2
  169. package/dist/ui/fleet-org.js +2 -0
  170. package/dist/ui/panel-chat.js +28 -6
  171. package/dist/ui/panel-details.js +6 -1
  172. package/dist/ui/panel-log.js +4 -2
  173. package/dist/ui/panel-needs.js +2 -0
  174. package/dist/ui/panel-settings.js +29 -1
  175. package/dist/ui/settings-registry.js +4 -0
  176. package/dist/ui/settings-strings.js +14 -0
  177. package/dist/ui/shared/app-i18n.js +2 -2
  178. package/dist/ui/shared/app-needs.js +3 -0
  179. package/dist/ui/shared/app-shell.js +48 -3
  180. package/dist/ui/shared/app.css +2 -0
  181. package/dist/ui/shared/chat-work-bar.css +12 -0
  182. package/dist/ui/shared/model-observation.js +16 -0
  183. package/dist/ui/shared/usage-dialog.js +2 -1
  184. package/dist/ui/shared/view-strings.js +2 -0
  185. package/dist/update-dispatch.d.ts +62 -0
  186. package/dist/update-dispatch.js +69 -2
  187. package/dist/update-dispatch.js.map +1 -1
  188. package/dist/usage/agent-output.d.ts +144 -0
  189. package/dist/usage/agent-output.js +76 -0
  190. package/dist/usage/agent-output.js.map +1 -0
  191. package/dist/usage/i18n-keys.d.ts +1 -1
  192. package/dist/usage/i18n-keys.js +1 -1
  193. package/dist/usage/i18n-keys.js.map +1 -1
  194. package/dist/usage/i18n.d.ts +1 -1
  195. package/dist/usage/i18n.js +2 -1
  196. package/dist/usage/i18n.js.map +1 -1
  197. package/dist/usage/providers.d.ts +4 -1
  198. package/dist/usage/providers.js +22 -11
  199. package/dist/usage/providers.js.map +1 -1
  200. package/dist/usage/usage-api.d.ts +1 -1
  201. package/dist/usage/usage-api.js +4 -4
  202. package/dist/usage/usage-api.js.map +1 -1
  203. package/dist/web-api.d.ts +1 -0
  204. package/dist/web-api.js +2 -1
  205. package/dist/web-api.js.map +1 -1
  206. package/dist/windows-shortcuts.d.ts +29 -5
  207. package/dist/windows-shortcuts.js +52 -9
  208. package/dist/windows-shortcuts.js.map +1 -1
  209. package/dist/workflow-templates/default.md +2 -2
  210. package/launcher/agend-install.cjs +7 -1
  211. package/package.json +1 -1
  212. package/templates/icons/agend-restart.ico +0 -0
  213. package/templates/icons/agend.ico +0 -0
  214. package/templates/windows-shortcuts.ps1 +45 -12
@@ -0,0 +1,221 @@
1
+ /** #1411: Grok has additive MCP discovery, not an exclusive config flag. The project holds only an identity-free
2
+ * shell shim; this launch's directory and binding select a private, guarded wrapper. No Grok auth/home relocation. */
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { existsSync, lstatSync, readFileSync, realpathSync, unlinkSync } from "node:fs";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import { ensureInstanceDir } from "../private-dir.js";
7
+ import { atomicWriteFileSync } from "../atomic-write.js";
8
+ import { shellQuote } from "./types.js";
9
+ const PRIVATE = "grok-mcp.json";
10
+ const HEADER = "#!/bin/bash\n# AgEnD Grok MCP launch binding v1\n";
11
+ const WAIT = '# Wait for IPC socket to be ready (up to 10s)\nfor i in $(seq 1 20); do [ -S "$AGEND_SOCKET_PATH" ] && break; sleep 0.5; done\n';
12
+ const FAIL = 'printf "%s\\n" "AgEnD MCP: missing or conflicting Grok launch binding; no tools loaded." >&2; exit 78';
13
+ const record = (v) => !!v && typeof v === "object" && !Array.isArray(v);
14
+ const read = (p) => { try {
15
+ return readFileSync(p, "utf8");
16
+ }
17
+ catch (e) {
18
+ if (e.code === "ENOENT")
19
+ return null;
20
+ throw e;
21
+ } };
22
+ const fingerprint = (c) => createHash("sha256").update(JSON.stringify([c.instanceName, c.workingDirectory, c.mcpServers])).digest("hex");
23
+ export function legacyGrokMcpKey(server, instance) {
24
+ const ascii = instance.replace(/[^\x20-\x7E]/g, "");
25
+ if (ascii === instance)
26
+ return `${server}-${instance}`;
27
+ const slug = ascii.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
28
+ const hash = createHash("md5").update(instance).digest("hex").slice(0, 8);
29
+ return slug ? `${server}-${slug}-${hash}` : `${server}-${hash}`;
30
+ }
31
+ function shim(name) {
32
+ return { command: "/bin/bash", args: ["-c", `if [ -z "\${AGEND_GROK_MCP_DIR:-}" ] || [ -z "\${AGEND_GROK_MCP_BINDING:-}" ]; then ${FAIL}; fi\nexec "\${AGEND_GROK_MCP_DIR}/mcp-wrapper-${name}.sh"`] };
33
+ }
34
+ function members(text, at = 0) {
35
+ const ws = (i) => { while (/\s/.test(text[i] ?? "") && i < text.length)
36
+ i++; return i; };
37
+ const stringEnd = (i) => { for (let j = i + 1; j < text.length; j++) {
38
+ if (text[j] === "\\")
39
+ j++;
40
+ else if (text[j] === '"')
41
+ return j + 1;
42
+ } throw Error("Grok MCP: invalid JSON string"); };
43
+ const valueEnd = (i) => {
44
+ if (text[i] === '"')
45
+ return stringEnd(i);
46
+ if (text[i] === "{" || text[i] === "[") {
47
+ const stack = [text[i]];
48
+ for (let j = i + 1; j < text.length; j++) {
49
+ if (text[j] === '"')
50
+ j = stringEnd(j) - 1;
51
+ else if (text[j] === "{" || text[j] === "[")
52
+ stack.push(text[j]);
53
+ else if (text[j] === "}" || text[j] === "]") {
54
+ stack.pop();
55
+ if (!stack.length)
56
+ return j + 1;
57
+ }
58
+ }
59
+ throw Error("Grok MCP: incomplete JSON");
60
+ }
61
+ let j = i;
62
+ while (j < text.length && !/[\s,}\]]/.test(text[j]))
63
+ j++;
64
+ return j;
65
+ };
66
+ let i = ws(at);
67
+ if (text[i] !== "{")
68
+ throw Error("Grok MCP: expected a JSON object");
69
+ i++;
70
+ const items = [], seen = new Set();
71
+ while (true) {
72
+ const begin = i;
73
+ i = ws(i);
74
+ if (text[i] === "}")
75
+ return { items, close: i };
76
+ if (text[i] !== '"')
77
+ throw Error("Grok MCP: expected a JSON member");
78
+ const kEnd = stringEnd(i), key = JSON.parse(text.slice(i, kEnd));
79
+ if (seen.has(key))
80
+ throw Error("Grok MCP: duplicate JSON member");
81
+ seen.add(key);
82
+ i = ws(kEnd);
83
+ if (text[i++] !== ":")
84
+ throw Error("Grok MCP: expected a JSON colon");
85
+ const start = ws(i), end = valueEnd(start);
86
+ i = ws(end);
87
+ items.push({ key, raw: text.slice(begin, i), start, end });
88
+ if (text[i] === ",") {
89
+ i++;
90
+ continue;
91
+ }
92
+ if (text[i] !== "}")
93
+ throw Error("Grok MCP: invalid JSON separator");
94
+ }
95
+ }
96
+ /** A path/key alone is not provenance: require the old exact generated wrapper contour at its canonical path. */
97
+ function legacyOwner(key, value, instanceDir, cwd) {
98
+ if (!record(value) || typeof value.command !== "string")
99
+ return null;
100
+ const cmd = value.command, match = /^mcp-wrapper-([A-Za-z0-9_-]+)\.sh$/.exec(basename(cmd));
101
+ if (!match)
102
+ return null;
103
+ const absolute = resolve(cwd, cmd), name = basename(dirname(absolute)), server = match[1];
104
+ let body;
105
+ try {
106
+ body = readFileSync(absolute, "utf8");
107
+ }
108
+ catch (e) {
109
+ if (e.code === "ENOENT")
110
+ return null;
111
+ throw Error("Grok MCP: legacy wrapper cannot be verified; project kept unchanged");
112
+ }
113
+ // An unproven path/key to an old identity-bearing wrapper must not be left discoverable either: refuse it.
114
+ if (!body.startsWith("#!/bin/bash\nexport ") || !body.includes("export AGEND_INSTANCE_NAME='") || !body.includes("export AGEND_SOCKET_PATH='") || !body.includes(WAIT) || !body.endsWith("\n"))
115
+ return null;
116
+ // Prove the whole generated grammar, not just a convenient path and a few matching substrings.
117
+ const quoted = String.raw `'[^']*(?:'\\''[^']*)*'`;
118
+ const generated = new RegExp("^#!/bin/bash\\n(?:export [A-Za-z_][A-Za-z0-9_]*=" + quoted + "\\n)+" + WAIT.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "exec " + quoted + "(?: " + quoted + ")*\\n$");
119
+ if (!generated.test(body))
120
+ return "foreign";
121
+ if (!Array.isArray(value.args) || value.args.length || Object.keys(value).some(k => k !== "command" && k !== "args")
122
+ || cmd !== absolute || !lstatSync(absolute).isFile() || realpathSync(absolute) !== absolute
123
+ || key !== legacyGrokMcpKey(server, name) && key !== server || !body.includes(`export AGEND_INSTANCE_NAME=${shellQuote(name)}\n`))
124
+ return "foreign";
125
+ return dirname(dirname(absolute)) === resolve(dirname(instanceDir)) ? "ours" : "foreign";
126
+ }
127
+ function projectText(config, instanceDir, old) {
128
+ const text = old ?? "{}\n", root = JSON.parse(text);
129
+ if (!record(root))
130
+ throw Error("Grok MCP: project config is not an object");
131
+ const top = members(text), field = top.items.find(x => x.key === "mcpServers");
132
+ if (field && !record(root.mcpServers))
133
+ throw Error("Grok MCP: project mcpServers is not an object");
134
+ const map = field ? members(text, field.start) : null, keep = [], remaining = new Map();
135
+ let changed = false;
136
+ for (const item of map?.items ?? []) {
137
+ const value = root.mcpServers[item.key];
138
+ const owner = legacyOwner(item.key, value, instanceDir, config.workingDirectory);
139
+ if (owner === "foreign")
140
+ throw Error("Grok MCP: legacy AgEnD binding belongs to another fleet; project config kept unchanged");
141
+ if (owner !== "ours") {
142
+ keep.push(item);
143
+ remaining.set(item.key, value);
144
+ }
145
+ else
146
+ changed = true;
147
+ }
148
+ for (const name of Object.keys(config.mcpServers)) {
149
+ if (!/^[A-Za-z0-9_-]+$/.test(name))
150
+ throw Error("Grok MCP: invalid managed server name");
151
+ const expected = shim(name);
152
+ if (remaining.has(name)) {
153
+ if (JSON.stringify(remaining.get(name)) !== JSON.stringify(expected))
154
+ throw Error(`Grok MCP: project server ${name} conflicts; user config kept unchanged`);
155
+ }
156
+ else {
157
+ changed = true;
158
+ keep.push({ key: name, raw: `\n ${JSON.stringify(name)}: ${JSON.stringify(expected)}`, start: 0, end: 0 });
159
+ remaining.set(name, expected);
160
+ }
161
+ }
162
+ if (!changed)
163
+ return text;
164
+ const replacement = "{" + keep.map(x => x.raw).join(",") + "\n }";
165
+ if (field)
166
+ return text.slice(0, field.start) + replacement + text.slice(field.end);
167
+ if (!Object.keys(config.mcpServers).length)
168
+ return text;
169
+ return text.slice(0, top.close) + (top.items.length ? "," : "") + `\n "mcpServers": ${replacement}\n` + text.slice(top.close);
170
+ }
171
+ export function writeGrokMcp(config, instanceDir) {
172
+ const path = join(config.workingDirectory, ".mcp.json"), old = read(path);
173
+ if (existsSync(path) && !lstatSync(path).isFile())
174
+ throw Error("Grok MCP: project config must be a regular file");
175
+ const next = projectText(config, instanceDir, old); // Validate conflicts/provenance before writing any private launch state.
176
+ ensureInstanceDir(instanceDir);
177
+ const binding = randomBytes(32).toString("hex");
178
+ for (const [name, entry] of Object.entries(config.mcpServers)) {
179
+ const env = { ...entry.env, AGEND_INSTANCE_NAME: config.instanceName };
180
+ if (Object.keys(env).some(k => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || k.startsWith("AGEND_GROK_MCP_")))
181
+ throw Error("Grok MCP: invalid or reserved server environment");
182
+ const guard = `if [ "\${AGEND_GROK_MCP_DIR:-}" != ${shellQuote(instanceDir)} ] || [ "\${AGEND_GROK_MCP_BINDING:-}" != ${shellQuote(binding)} ]; then ${FAIL}; fi\n`;
183
+ const exports = Object.entries(env).map(([k, v]) => `export ${k}=${shellQuote(String(v))}`).join("\n");
184
+ atomicWriteFileSync(join(instanceDir, `mcp-wrapper-${name}.sh`), HEADER + guard + exports + "\n" + WAIT + `exec ${[entry.command, ...entry.args].map(shellQuote).join(" ")}\n`, { mode: 0o700 });
185
+ }
186
+ if (next !== old)
187
+ atomicWriteFileSync(path, next, { mode: old === null ? 0o600 : lstatSync(path).mode & 0o777, beforeRename: () => { if (read(path) !== old || existsSync(path) && !lstatSync(path).isFile())
188
+ throw Error("Grok MCP: project config changed during preparation; launch refused"); } });
189
+ // Publish the binding only after the project transition commits; failed preparation must stay unbound.
190
+ atomicWriteFileSync(join(instanceDir, PRIVATE), JSON.stringify({ v: 1, instance: config.instanceName, fingerprint: fingerprint(config), binding, servers: Object.keys(config.mcpServers) }) + "\n", { mode: 0o600 });
191
+ }
192
+ export function grokMcpLaunchEnv(config, instanceDir) {
193
+ let binding = "";
194
+ try {
195
+ const v = JSON.parse(read(join(instanceDir, PRIVATE)) ?? "null");
196
+ if (v?.v === 1 && v.instance === config.instanceName && v.fingerprint === fingerprint(config) && /^[a-f0-9]{64}$/.test(v.binding))
197
+ binding = v.binding;
198
+ }
199
+ catch { /* missing/unbound: shim refuses, never use another instance's environment */ }
200
+ return `AGEND_GROK_MCP_DIR=${shellQuote(instanceDir)} AGEND_GROK_MCP_BINDING=${shellQuote(binding)}`;
201
+ }
202
+ export function cleanupGrokMcp(config, instanceDir) {
203
+ // The identity-free discovery shim is shared. Never take it away from a peer when this instance stops.
204
+ for (const name of Object.keys(config.mcpServers))
205
+ if (/^[A-Za-z0-9_-]+$/.test(name)) {
206
+ const path = join(instanceDir, `mcp-wrapper-${name}.sh`);
207
+ try {
208
+ if (read(path)?.startsWith(HEADER))
209
+ unlinkSync(path);
210
+ }
211
+ catch { /* private cleanup is best effort */ }
212
+ }
213
+ const path = join(instanceDir, PRIVATE);
214
+ try {
215
+ const v = JSON.parse(read(path) ?? "null");
216
+ if (v?.v === 1 && v.instance === config.instanceName)
217
+ unlinkSync(path);
218
+ }
219
+ catch { /* keep unknown private files */ }
220
+ }
221
+ //# sourceMappingURL=grok-mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grok-mcp.js","sourceRoot":"","sources":["../../src/backend/grok-mcp.ts"],"names":[],"mappings":"AAAA;sHACsH;AACtH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,m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I,GAAC,IAAI,CAAC,WAAW,EAAC,eAAe,IAAI,KAAK,CAAC,CAAC;YAAA,IAAI,CAAC;gBAAA,IAAG,IAAI,CAAC,IAAI,CAAC,EAAE,UAAU,CAAC,MAAM,CAAC;oBAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAAA,CAAC;YAAA,MAAK,CAAC,CAAC,oCAAoC,CAAC,CAAC;QAC9J,CAAC;IACD,MAAM,IAAI,GAAC,IAAI,CAAC,WAAW,EAAC,OAAO,CAAC,CAAC;IAAA,IAAI,CAAC;QAAA,MAAM,CAAC,GAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAE,MAAM,CAAC,CAAC;QAAA,IAAG,CAAC,EAAE,CAAC,KAAG,CAAC,IAAE,CAAC,CAAC,QAAQ,KAAG,MAAM,CAAC,YAAY;YAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAAA,CAAC;IAAA,MAAK,CAAC,CAAC,gCAAgC,CAAC,CAAC;AAC5L,CAAC"}
@@ -20,6 +20,15 @@ export declare function parseGrokModelsOutput(output: string): import("./types.j
20
20
  * UTF-16 offset while the real closer (and an unsent id) sit further right.
21
21
  */
22
22
  export declare function readGrokInputBox(pane: string): InputBox | null;
23
+ /**
24
+ * M-3098: the AgEnD lead markers (`[agend-delivery-id:…]`, `[hid:…]`, legacy `[agend-human-id:…]`) Grok shows as
25
+ * TAKEN, above the live box: the first row of a transcript echo (` ❯ <marker> <time>`) or a queued message
26
+ * (` #1 <marker> (+19 lines)`, a paste sent while a turn runs). Grok cuts an echo to three rows and a `…`, so an
27
+ * envelope's trailing `(message_id: …)` footer is never on screen after Enter; its lead marker always is (live 1.0.70
28
+ * and 1.0.77, tests/fixtures/grok-receipt-m3098). Box rows (`│ ❯ …`) and the preview card (`│[…`) never match.
29
+ * Empty when there is no readable box: then nothing above it can be placed.
30
+ */
31
+ export declare function readGrokTakenMarkers(pane: string): string[];
23
32
  /**
24
33
  * Grok Build (xAI) — https://docs.x.ai/build/cli
25
34
  *
@@ -49,19 +58,17 @@ export declare class GrokBackend implements CliBackend {
49
58
  /** #1811: what the last launch left out and why — the Log tab and daemon.log, never a channel. */
50
59
  private quietLaunchNotes;
51
60
  consumeQuietLaunchNotes(): string[];
61
+ private uuidPreparation;
62
+ private uuidBinarySignature;
63
+ private uuidSignature;
64
+ /** #3810/G1: no new flag on an old or unknown CLI. Version reads are disk-first, otherwise netless (#2078). */
65
+ prepareLaunch(): Promise<void>;
66
+ private canSelectSessionUuid;
67
+ private deliverySessionId;
68
+ getDeliverySessionId(): string | null;
52
69
  private launchResumes;
53
70
  resumesPreservedQuotaHistory(): boolean;
54
71
  buildCommand(config: CliBackendConfig): string;
55
- /**
56
- * Build an ASCII-only, per-instance MCP server key. Grok Build's MCP client has
57
- * a bug where a non-ASCII (e.g. CJK) server name connects but drops ALL tools
58
- * (tool_count=0, misreported as "connection failed"). Instance names can be CJK
59
- * (persona ClassicBot channels), so sanitize: pure-ASCII names pass through
60
- * unchanged (readable + already unique); names with non-ASCII are stripped to an
61
- * ASCII slug plus a short hash of the ORIGINAL name, so two distinct CJK names
62
- * sharing a working directory can't collide to the same key.
63
- */
64
- private mcpKey;
65
72
  /** The daemon's persisted session id (written from getSessionId()), for --resume. */
66
73
  private storedSessionId;
67
74
  writeConfig(config: CliBackendConfig): void;
@@ -95,6 +102,8 @@ export declare class GrokBackend implements CliBackend {
95
102
  * proof when this reader can still see the boxed `❯`. Dialogs have no box.
96
103
  */
97
104
  readInputRow(pane: string): InputBox | null;
105
+ /** M-3098: the lead markers Grok shows as taken (echoed or queued) above the live box. */
106
+ readTakenMarkers(pane: string): string[];
98
107
  getErrorPatterns(): ErrorPattern[];
99
108
  getStartupDialogs(): StartupDialog[];
100
109
  getContextUsage(): number | null;
@@ -1,10 +1,13 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { probeBackendVersion, versionBelow } from "../backend-availability.js";
3
+ import { randomUUID } from "node:crypto";
1
4
  import { EFFORT_CAPABILITIES } from "./effort-metadata.js";
2
5
  import { flagEffort } from "./launch-effort.js";
3
6
  import { join } from "node:path";
4
7
  import { execFileSync } from "node:child_process";
5
- import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, chmodSync } from "node:fs";
8
+ import { readFileSync, readdirSync, statSync } from "node:fs";
6
9
  import { homedir } from "node:os";
7
- import { createHash } from "node:crypto";
10
+ import { cleanupGrokMcp, grokMcpLaunchEnv, writeGrokMcp } from "./grok-mcp.js";
8
11
  import { resolveBinary, shellQuote, validateModel, warnIfModelMismatch } from "./types.js";
9
12
  import { appendWithMarker, removeMarker } from "./marker-utils.js";
10
13
  import { displayWidth } from "../ls-rows.js";
@@ -254,6 +257,70 @@ const GROK_BOX_MAX_ROWS = 40;
254
257
  * UTF-16 offset while the real closer (and an unsent id) sit further right.
255
258
  */
256
259
  export function readGrokInputBox(pane) {
260
+ const found = locateGrokInputBox(pane);
261
+ if (!found)
262
+ return null;
263
+ const { box, rows, top } = found;
264
+ // M-3098: a multi-line paste shows collapsed (`❯ [Pasted: 20 lines]`), its text in a preview card drawn just above
265
+ // the box (`╭…╮` / `│<line>│` / `╰─ paste again or double-click to expand ─╯`). That card is the draft, not the
266
+ // transcript: its rows (the envelope footer with the message_id among them) count as input, so an unsent paste can
267
+ // never be read as an echo of a sent one. Live captures: tests/fixtures/grok-receipt-m3098/<ver>/20-long-draft.
268
+ const collapsed = box.text.match(GROK_COLLAPSED_PASTE)?.length ?? 0;
269
+ if (!collapsed)
270
+ return box;
271
+ const card = grokPastePreviewCard(rows, top);
272
+ return { text: card ? `${box.text}\n${card}` : box.text, collapsedPastes: collapsed };
273
+ }
274
+ /** `[Pasted: 20 lines]`: Grok's collapsed paste in the box (1.0.70, 1.0.77). */
275
+ const GROK_COLLAPSED_PASTE = /\[Pasted: \d+ lines?\]/g;
276
+ /** Rows between a collapsed paste's preview card and the box (a busy status row, a blank). The card's rows may carry
277
+ * the transcript's scrollbar (`█`) at the pane's right edge. */
278
+ const GROK_PREVIEW_GAP_ROWS = 3;
279
+ /** The preview card's inner rows, joined; null when no framed card sits right above the box. */
280
+ function grokPastePreviewCard(rows, boxTop) {
281
+ let bottom = -1;
282
+ for (let i = boxTop - 1; i >= 0 && boxTop - i <= GROK_PREVIEW_GAP_ROWS + 1; i--) {
283
+ if (/^\s*╰─.*╯(?:\s+█)?\s*$/.test(rows[i])) {
284
+ bottom = i;
285
+ break;
286
+ }
287
+ }
288
+ if (bottom < 0)
289
+ return null;
290
+ const lines = [];
291
+ for (let i = bottom - 1; i >= 0 && bottom - i <= GROK_BOX_MAX_ROWS + 1; i--) {
292
+ const row = rows[i];
293
+ if (/^\s*╭─+╮(?:\s+█)?\s*$/.test(row))
294
+ return lines.reverse().join("\n");
295
+ const inner = /^\s*│(.*)│(?:\s+█)?\s*$/.exec(row);
296
+ if (!inner)
297
+ return null;
298
+ lines.push(inner[1].trimEnd());
299
+ }
300
+ return null;
301
+ }
302
+ /**
303
+ * M-3098: the AgEnD lead markers (`[agend-delivery-id:…]`, `[hid:…]`, legacy `[agend-human-id:…]`) Grok shows as
304
+ * TAKEN, above the live box: the first row of a transcript echo (` ❯ <marker> <time>`) or a queued message
305
+ * (` #1 <marker> (+19 lines)`, a paste sent while a turn runs). Grok cuts an echo to three rows and a `…`, so an
306
+ * envelope's trailing `(message_id: …)` footer is never on screen after Enter; its lead marker always is (live 1.0.70
307
+ * and 1.0.77, tests/fixtures/grok-receipt-m3098). Box rows (`│ ❯ …`) and the preview card (`│[…`) never match.
308
+ * Empty when there is no readable box: then nothing above it can be placed.
309
+ */
310
+ export function readGrokTakenMarkers(pane) {
311
+ const found = locateGrokInputBox(pane);
312
+ if (!found)
313
+ return [];
314
+ const markers = [];
315
+ for (const row of found.rows.slice(0, found.top)) {
316
+ const m = GROK_TAKEN_ROW.exec(row);
317
+ if (m)
318
+ markers.push(m[1]);
319
+ }
320
+ return markers;
321
+ }
322
+ const GROK_TAKEN_ROW = /^ {2,}(?:❯|#\d+) (\[(?:agend-(?:delivery|human)-id|hid):[^\]\s]+\])(?: |$)/;
323
+ function locateGrokInputBox(pane) {
257
324
  const rows = pane.replace(/\r/g, "").split("\n").map(row => row.trimEnd());
258
325
  let bottom = -1;
259
326
  for (let i = rows.length - 1, footer = 0; i >= 0; i--) {
@@ -316,7 +383,7 @@ export function readGrokInputBox(pane) {
316
383
  }
317
384
  if (lines.length === 0)
318
385
  return null;
319
- return { text: lines.join("\n").trimEnd(), collapsedPastes: 0 };
386
+ return { box: { text: lines.join("\n").trimEnd(), collapsedPastes: 0 }, rows, top };
320
387
  }
321
388
  /** UTF-16 index of the first positive-width character whose display column starts at `col`. */
322
389
  function indexAtDisplayCol(s, col) {
@@ -381,14 +448,48 @@ export class GrokBackend {
381
448
  /** #1811: what the last launch left out and why — the Log tab and daemon.log, never a channel. */
382
449
  quietLaunchNotes = [];
383
450
  consumeQuietLaunchNotes() { const notes = this.quietLaunchNotes; this.quietLaunchNotes = []; return notes; }
451
+ uuidPreparation = 0;
452
+ uuidBinarySignature = null;
453
+ uuidSignature(s) {
454
+ return `${this.binaryPath}:${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}`;
455
+ }
456
+ /** #3810/G1: no new flag on an old or unknown CLI. Version reads are disk-first, otherwise netless (#2078). */
457
+ async prepareLaunch() {
458
+ const preparation = ++this.uuidPreparation;
459
+ this.uuidBinarySignature = null;
460
+ try {
461
+ const before = await stat(this.binaryPath);
462
+ const version = await probeBackendVersion("grok", this.binaryPath);
463
+ const after = await stat(this.binaryPath);
464
+ if (preparation === this.uuidPreparation && before.isFile() && after.isFile()
465
+ && this.uuidSignature(before) === this.uuidSignature(after) && version && /^\d+\.\d+\.\d+$/.test(version)
466
+ && !versionBelow(version, "1.0.62")) {
467
+ this.uuidBinarySignature = this.uuidSignature(after);
468
+ }
469
+ }
470
+ catch { /* unknown: keep the previous launch syntax, without a fresh-session receipt lease */ }
471
+ }
472
+ canSelectSessionUuid() {
473
+ if (!this.uuidBinarySignature)
474
+ return false;
475
+ try {
476
+ return this.uuidSignature(statSync(this.binaryPath)) === this.uuidBinarySignature;
477
+ }
478
+ catch {
479
+ return false;
480
+ }
481
+ }
482
+ deliverySessionId = null;
483
+ getDeliverySessionId() { return this.deliverySessionId; }
384
484
  launchResumes = false;
385
485
  resumesPreservedQuotaHistory() { return this.launchResumes; }
386
486
  buildCommand(config) {
387
487
  this.launchResumes = false;
488
+ this.deliverySessionId = null;
388
489
  this.workingDirectory = config.workingDirectory;
389
490
  // Flags: -m/--model, --always-approve, -r/--resume <ID>, -p/--single, --no-auto-update.
390
491
  // --no-auto-update: an auto-update prompt on launch would corrupt ready detection.
391
- let cmd = `${this.binaryPath} --no-auto-update`;
492
+ let cmd = `${grokMcpLaunchEnv(config, this.instanceDir)} ${this.binaryPath} --no-auto-update --no-leader`;
392
493
  // --always-approve auto-approves tool executions (documented flag). If a grok
393
494
  // build ignores it, getRuntimeDialogs() auto-approves the prompt as a net.
394
495
  if (config.skipPermissions !== false)
@@ -402,8 +503,14 @@ export class GrokBackend {
402
503
  if (sid) {
403
504
  cmd += ` --resume ${sid}`;
404
505
  this.launchResumes = true;
506
+ this.deliverySessionId = sid;
405
507
  }
406
508
  }
509
+ // #3810: select a UUID before launch; newest-cwd discovery cannot authorize a receipt.
510
+ if (!this.deliverySessionId && this.canSelectSessionUuid()) {
511
+ this.deliverySessionId = randomUUID();
512
+ cmd += ` --session-id ${this.deliverySessionId}`;
513
+ }
407
514
  if (config.model) {
408
515
  const model = validateModel(config.model);
409
516
  warnIfModelMismatch("grok", model);
@@ -416,23 +523,6 @@ export class GrokBackend {
416
523
  this.quietLaunchNotes = effort.note ? [effort.note] : [];
417
524
  return cmd;
418
525
  }
419
- /**
420
- * Build an ASCII-only, per-instance MCP server key. Grok Build's MCP client has
421
- * a bug where a non-ASCII (e.g. CJK) server name connects but drops ALL tools
422
- * (tool_count=0, misreported as "connection failed"). Instance names can be CJK
423
- * (persona ClassicBot channels), so sanitize: pure-ASCII names pass through
424
- * unchanged (readable + already unique); names with non-ASCII are stripped to an
425
- * ASCII slug plus a short hash of the ORIGINAL name, so two distinct CJK names
426
- * sharing a working directory can't collide to the same key.
427
- */
428
- mcpKey(mcpName, instanceName) {
429
- const ascii = instanceName.replace(/[^\x20-\x7E]/g, "");
430
- if (ascii === instanceName)
431
- return `${mcpName}-${instanceName}`;
432
- const slug = ascii.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
433
- const hash = createHash("md5").update(instanceName).digest("hex").slice(0, 8);
434
- return slug ? `${mcpName}-${slug}-${hash}` : `${mcpName}-${hash}`;
435
- }
436
526
  /** The daemon's persisted session id (written from getSessionId()), for --resume. */
437
527
  storedSessionId() {
438
528
  try {
@@ -445,51 +535,7 @@ export class GrokBackend {
445
535
  }
446
536
  writeConfig(config) {
447
537
  this.workingDirectory = config.workingDirectory;
448
- // Grok Build merges MCP servers from a project-level .mcp.json (loaded below
449
- // ~/.grok/config.toml in priority). Using the project file means we never
450
- // clobber the user's global config. Standard mcpServers format: { command, args, env }.
451
- const mcpPath = join(config.workingDirectory, ".mcp.json");
452
- let root = {};
453
- try {
454
- root = JSON.parse(readFileSync(mcpPath, "utf-8"));
455
- }
456
- catch { /* new file */ }
457
- const servers = (root.mcpServers ?? {});
458
- // Drop stale agend entries whose wrapper script no longer exists, plus any
459
- // legacy non-ASCII key (grok drops all tools on a CJK key — we now always
460
- // write ASCII keys, so a lingering CJK entry is dead weight to remove).
461
- for (const [key, val] of Object.entries(servers)) {
462
- if (key.startsWith("agend-")) {
463
- const cmd = val?.command;
464
- if ((typeof cmd === "string" && !existsSync(cmd)) || /[^\x20-\x7E]/.test(key)) {
465
- delete servers[key];
466
- }
467
- }
468
- }
469
- // Namespace each server by instance so multiple instances can share a working
470
- // dir. Key is ASCII-sanitized (grok's MCP client drops tools on a CJK key).
471
- for (const [name, entry] of Object.entries(config.mcpServers)) {
472
- const instanceKey = this.mcpKey(name, config.instanceName);
473
- const allEnv = { ...entry.env, AGEND_INSTANCE_NAME: config.instanceName };
474
- // WORKAROUND (same as kiro-cli): grok does not reliably pass the mcp.json
475
- // "env" block to the MCP server subprocess — the process would inherit grok's
476
- // env, which has NO AGEND_SOCKET_PATH (the daemon keeps it out of process.env),
477
- // so the server can't connect and every MCP tool (reply/react/…) fails. Emit a
478
- // wrapper that exports the env explicitly, waits for the IPC socket, then execs
479
- // the real server. This is env-delivery-independent and works either way.
480
- const wrapperPath = join(this.instanceDir, `mcp-wrapper-${name}.sh`);
481
- const envExports = Object.entries(allEnv)
482
- .map(([k, v]) => `export ${k}='${String(v).replace(/'/g, "'\\''")}'`)
483
- .join("\n");
484
- // 0o700: wrapper inlines sensitive env (tokens, socket paths) — owner-only.
485
- writeFileSync(wrapperPath, `#!/bin/bash\n${envExports}\n# Wait for IPC socket to be ready (up to 10s)\nfor i in $(seq 1 20); do [ -S "$AGEND_SOCKET_PATH" ] && break; sleep 0.5; done\nexec ${[entry.command, ...entry.args].map(shellQuote).join(" ")}\n`, { mode: 0o700 });
486
- chmodSync(wrapperPath, 0o700);
487
- servers[instanceKey] = { command: wrapperPath, args: [] };
488
- }
489
- // Clean up any legacy non-namespaced key.
490
- delete servers["agend"];
491
- root.mcpServers = servers;
492
- writeFileSync(mcpPath, JSON.stringify(root, null, 2));
538
+ writeGrokMcp(config, this.instanceDir);
493
539
  // Fleet instructions → AGENTS.md marker block (Grok reads AGENTS.md project docs,
494
540
  // same convention as Codex). Additive + idempotent via the AGEND marker.
495
541
  if (config.instructions) {
@@ -554,6 +600,10 @@ export class GrokBackend {
554
600
  readInputRow(pane) {
555
601
  return readGrokInputBox(pane);
556
602
  }
603
+ /** M-3098: the lead markers Grok shows as taken (echoed or queued) above the live box. */
604
+ readTakenMarkers(pane) {
605
+ return readGrokTakenMarkers(pane);
606
+ }
557
607
  getErrorPatterns() {
558
608
  // NOTE: "Turn cancelled by user" is NORMAL behaviour (user interrupt), not an
559
609
  // error — none of the patterns below match it, and none should be added that do.
@@ -791,23 +841,7 @@ export class GrokBackend {
791
841
  return { version: probeCliVersion(this.binaryPath), models: await this.listModels(), currentModel };
792
842
  }
793
843
  cleanup(config) {
794
- // Remove only this instance's namespaced MCP entries — a non-namespaced key
795
- // may belong to another instance sharing the working directory.
796
- try {
797
- const mcpPath = join(config.workingDirectory, ".mcp.json");
798
- if (existsSync(mcpPath)) {
799
- const root = JSON.parse(readFileSync(mcpPath, "utf-8"));
800
- if (root.mcpServers) {
801
- for (const name of Object.keys(config.mcpServers)) {
802
- delete root.mcpServers[this.mcpKey(name, config.instanceName)];
803
- // Also drop any legacy raw (pre-sanitize) key for this instance.
804
- delete root.mcpServers[`${name}-${config.instanceName}`];
805
- }
806
- writeFileSync(mcpPath, JSON.stringify(root, null, 2));
807
- }
808
- }
809
- }
810
- catch { /* best effort */ }
844
+ cleanupGrokMcp(config, this.instanceDir);
811
845
  // Remove fleet instructions marker block from AGENTS.md.
812
846
  try {
813
847
  removeMarker(join(config.workingDirectory, "AGENTS.md"), config.instanceName);