@openclaw/tokenjuice 2026.9.4 → 2026.9.5

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 (35) hide show
  1. package/assets/activity.svg +3 -0
  2. package/assets/icon.png +0 -0
  3. package/node_modules/tokenjuice/README.md +6 -1
  4. package/node_modules/tokenjuice/dist/cli/install-output.d.ts +7 -0
  5. package/node_modules/tokenjuice/dist/cli/install-output.js +19 -0
  6. package/node_modules/tokenjuice/dist/cli/main.d.ts +4 -0
  7. package/node_modules/tokenjuice/dist/cli/main.js +143 -26
  8. package/node_modules/tokenjuice/dist/core/artifacts.d.ts +1 -0
  9. package/node_modules/tokenjuice/dist/core/artifacts.js +29 -0
  10. package/node_modules/tokenjuice/dist/core/compaction-metadata.d.ts +1 -1
  11. package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.d.ts +1 -0
  12. package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.js +1 -1
  13. package/node_modules/tokenjuice/dist/core/reduce.js +18 -10
  14. package/node_modules/tokenjuice/dist/core/text.d.ts +4 -0
  15. package/node_modules/tokenjuice/dist/core/text.js +32 -0
  16. package/node_modules/tokenjuice/dist/hosts/codex/index.d.ts +25 -1
  17. package/node_modules/tokenjuice/dist/hosts/codex/index.js +211 -163
  18. package/node_modules/tokenjuice/dist/hosts/grok-bot/index.d.ts +25 -0
  19. package/node_modules/tokenjuice/dist/hosts/grok-bot/index.js +644 -0
  20. package/node_modules/tokenjuice/dist/hosts/opencode/extension/runtime.js +79 -10
  21. package/node_modules/tokenjuice/dist/hosts/pi/extension/runtime.js +79 -10
  22. package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.d.ts +24 -0
  23. package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.js +80 -1
  24. package/node_modules/tokenjuice/dist/hosts/shared/hook-command.d.ts +19 -0
  25. package/node_modules/tokenjuice/dist/hosts/shared/hook-command.js +61 -6
  26. package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.d.ts +3 -1
  27. package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.js +2 -0
  28. package/node_modules/tokenjuice/dist/hosts/shared/host-command.d.ts +10 -1
  29. package/node_modules/tokenjuice/dist/hosts/shared/host-command.js +43 -4
  30. package/node_modules/tokenjuice/dist/hosts/shared/pre-tool-wrap.js +9 -7
  31. package/node_modules/tokenjuice/dist/index.d.ts +2 -0
  32. package/node_modules/tokenjuice/dist/index.js +1 -0
  33. package/node_modules/tokenjuice/package.json +1 -1
  34. package/openclaw.plugin.json +1 -1
  35. package/package.json +8 -6
@@ -0,0 +1,25 @@
1
+ export type GrokBotRuleOptions = {
2
+ projectDir?: string;
3
+ };
4
+ export type InstallGrokBotRuleResult = {
5
+ rulePath: string;
6
+ backupPath?: string;
7
+ };
8
+ export type UninstallGrokBotRuleResult = {
9
+ rulePath: string;
10
+ removed: boolean;
11
+ restoredBackup: boolean;
12
+ };
13
+ export type GrokBotDoctorReport = {
14
+ rulePath: string;
15
+ hasTokenjuiceMarker: boolean;
16
+ status: "ok" | "warn" | "broken" | "disabled";
17
+ issues: string[];
18
+ advisories: string[];
19
+ fixCommand: string;
20
+ checkedPaths: string[];
21
+ missingPaths: string[];
22
+ };
23
+ export declare function installGrokBotRule(rulePath?: string, options?: GrokBotRuleOptions): Promise<InstallGrokBotRuleResult>;
24
+ export declare function uninstallGrokBotRule(rulePath?: string, options?: GrokBotRuleOptions): Promise<UninstallGrokBotRuleResult>;
25
+ export declare function doctorGrokBotRule(rulePath?: string, options?: GrokBotRuleOptions): Promise<GrokBotDoctorReport>;
@@ -0,0 +1,644 @@
1
+ import { constants } from "node:fs";
2
+ import { link, lstat, mkdir, mkdtemp, open, realpath, rename, rm, stat } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { buildTokenjuiceGuidanceBullets, TOKENJUICE_FULL_COMMAND, TOKENJUICE_RAW_COMMAND, TOKENJUICE_WRAP_COMMAND, } from "../shared/instruction-guidance.js";
5
+ import { buildInstructionDoctorReportFields, instructionDoctorStatusFromIssues, } from "../shared/instruction-doctor.js";
6
+ import { collectGuidanceIssues } from "../shared/instruction-file.js";
7
+ const TOKENJUICE_GROK_BOT_FIX_COMMAND = "tokenjuice install grok-bot";
8
+ const TOKENJUICE_GROK_BOT_OWNERSHIP_MARKER = "<!-- tokenjuice:grok-bot-rule -->";
9
+ const TOKENJUICE_GROK_BOT_RESTORE_MARKER_PREFIX = "<!-- tokenjuice:grok-bot-restore-backup=";
10
+ const TOKENJUICE_GROK_BOT_RULE_MARKER = "tokenjuice terminal output compaction";
11
+ const TOKENJUICE_GROK_BOT_ADVISORY = "Grok Bot support is beta and rule-based; it uses the shipped .cursor/rules workspace surface to guide command usage but does not intercept or rewrite tool output.";
12
+ function getLeadingFrontmatterLines(text) {
13
+ const frontmatterStart = text.match(/^---\r?\n/u);
14
+ if (!frontmatterStart) {
15
+ return [];
16
+ }
17
+ const endIndex = text.search(/\r?\n---(?:\r?\n|$)/u);
18
+ if (endIndex === -1) {
19
+ return [];
20
+ }
21
+ return text.slice(frontmatterStart[0].length, endIndex).split(/\r?\n/u);
22
+ }
23
+ function inspectFrontmatter(text) {
24
+ const lines = getLeadingFrontmatterLines(text);
25
+ const values = new Map();
26
+ let isValid = lines.length > 0;
27
+ for (const line of lines) {
28
+ const match = line.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(\S.*)$/u);
29
+ const key = match?.[1];
30
+ const value = match?.[2];
31
+ if (!key || !value || values.has(key)) {
32
+ isValid = false;
33
+ continue;
34
+ }
35
+ values.set(key, value);
36
+ }
37
+ return {
38
+ hasAlwaysApply: isValid && values.get("alwaysApply") === "true",
39
+ hasDescription: isValid
40
+ && values.get("description") === '"Use tokenjuice for noisy terminal output in Grok Bot workspaces."',
41
+ isValid,
42
+ };
43
+ }
44
+ function getExplicitProjectDir(options = {}) {
45
+ return options.projectDir || process.env.GROK_BOT_PROJECT_DIR;
46
+ }
47
+ async function hasGitMetadata(dir) {
48
+ try {
49
+ await stat(join(dir, ".git"));
50
+ return true;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ async function findGitRoot(startDir) {
57
+ let current = resolve(startDir);
58
+ while (true) {
59
+ if (await hasGitMetadata(current)) {
60
+ return current;
61
+ }
62
+ const parent = dirname(current);
63
+ if (parent === current) {
64
+ return undefined;
65
+ }
66
+ current = parent;
67
+ }
68
+ }
69
+ async function resolveProjectDir(options = {}) {
70
+ const explicitProjectDir = getExplicitProjectDir(options);
71
+ if (explicitProjectDir) {
72
+ return resolve(explicitProjectDir);
73
+ }
74
+ return (await findGitRoot(process.cwd())) ?? process.cwd();
75
+ }
76
+ function isInsideOrEqual(parentDir, childPath) {
77
+ const relativePath = relative(parentDir, childPath);
78
+ return relativePath === "" || (!relativePath.startsWith("..") && !isAbsolute(relativePath));
79
+ }
80
+ async function realpathExistingAncestor(path) {
81
+ let current = path;
82
+ while (true) {
83
+ try {
84
+ return await realpath(current);
85
+ }
86
+ catch (error) {
87
+ if (error.code !== "ENOENT") {
88
+ throw error;
89
+ }
90
+ const parent = dirname(current);
91
+ if (parent === current) {
92
+ throw error;
93
+ }
94
+ current = parent;
95
+ }
96
+ }
97
+ }
98
+ async function rejectSymlink(filePath) {
99
+ try {
100
+ if ((await lstat(filePath)).isSymbolicLink()) {
101
+ throw new Error(`cannot use Grok Bot rule ${filePath}; tokenjuice will not read or write through symlinks`);
102
+ }
103
+ }
104
+ catch (error) {
105
+ if (error.code === "ENOENT") {
106
+ return;
107
+ }
108
+ throw error;
109
+ }
110
+ }
111
+ async function rejectHardlink(filePath) {
112
+ try {
113
+ const stats = await lstat(filePath);
114
+ if (stats.isFile() && stats.nlink !== 1) {
115
+ throw new Error(`cannot use Grok Bot rule ${filePath}; tokenjuice will not read or write hard-linked files`);
116
+ }
117
+ }
118
+ catch (error) {
119
+ if (error.code === "ENOENT") {
120
+ return;
121
+ }
122
+ throw error;
123
+ }
124
+ }
125
+ async function rejectSymlinkPathComponents(filePath, projectDir) {
126
+ const segments = relative(projectDir, filePath).split(sep).filter(Boolean);
127
+ let currentPath = projectDir;
128
+ for (const segment of segments.slice(0, -1)) {
129
+ currentPath = join(currentPath, segment);
130
+ try {
131
+ if ((await lstat(currentPath)).isSymbolicLink()) {
132
+ throw new Error(`cannot use Grok Bot rule ${filePath}; tokenjuice will not read or write through symlinks`);
133
+ }
134
+ }
135
+ catch (error) {
136
+ if (error.code === "ENOENT") {
137
+ return;
138
+ }
139
+ throw error;
140
+ }
141
+ }
142
+ }
143
+ async function resolveSafeRulePath(filePath, projectDir, realProjectDir = projectDir) {
144
+ const resolvedPath = resolve(filePath);
145
+ if (projectDir !== realProjectDir) {
146
+ throw new Error(`cannot use Grok Bot rule ${resolvedPath}; tokenjuice will not read or write through symlinks`);
147
+ }
148
+ const realParentDir = await realpathExistingAncestor(dirname(resolvedPath));
149
+ if (!isInsideOrEqual(realProjectDir, realParentDir)) {
150
+ throw new Error(`cannot use Grok Bot rule ${resolvedPath}; tokenjuice will not write outside ${realProjectDir}`);
151
+ }
152
+ await rejectSymlink(projectDir);
153
+ await rejectSymlinkPathComponents(resolvedPath, projectDir);
154
+ await rejectSymlink(resolvedPath);
155
+ await rejectHardlink(resolvedPath);
156
+ try {
157
+ return join(await realpath(dirname(resolvedPath)), basename(resolvedPath));
158
+ }
159
+ catch (error) {
160
+ if (error.code === "ENOENT") {
161
+ return resolvedPath;
162
+ }
163
+ throw error;
164
+ }
165
+ }
166
+ async function getRulePathContext(rulePath, options) {
167
+ const projectDir = await resolveProjectDir(options);
168
+ const realProjectDir = await realpath(projectDir).catch(() => projectDir);
169
+ return {
170
+ projectDir,
171
+ realProjectDir,
172
+ rulePath: rulePath ?? join(projectDir, ".cursor", "rules", "tokenjuice.mdc"),
173
+ };
174
+ }
175
+ async function getDefaultAliasPath(options = {}) {
176
+ return join(await resolveProjectDir(options), ".cursor", "rules", "tokenjuice.mdc");
177
+ }
178
+ async function resolveRulePath(rulePath, options = {}) {
179
+ const context = await getRulePathContext(rulePath, options);
180
+ return resolveSafeRulePath(context.rulePath, context.projectDir, context.realProjectDir);
181
+ }
182
+ async function prepareRulePathForInstall(rulePath, options = {}) {
183
+ const context = await getRulePathContext(rulePath, options);
184
+ const initiallyResolved = await resolveSafeRulePath(context.rulePath, context.projectDir, context.realProjectDir);
185
+ const relativeParent = relative(context.projectDir, dirname(initiallyResolved));
186
+ if (relativeParent.startsWith("..") || isAbsolute(relativeParent)) {
187
+ throw new Error(`cannot use Grok Bot rule ${initiallyResolved}; tokenjuice will not write outside ${context.realProjectDir}`);
188
+ }
189
+ let current = context.projectDir;
190
+ for (const segment of relativeParent.split(sep).filter(Boolean)) {
191
+ current = join(current, segment);
192
+ try {
193
+ await mkdir(current);
194
+ }
195
+ catch (error) {
196
+ if (error.code !== "EEXIST") {
197
+ throw error;
198
+ }
199
+ }
200
+ const stats = await lstat(current);
201
+ const realCurrent = await realpath(current);
202
+ if (!stats.isDirectory() || stats.isSymbolicLink() || !isInsideOrEqual(context.realProjectDir, realCurrent)) {
203
+ throw new Error(`cannot use Grok Bot rule ${initiallyResolved}; tokenjuice will not read or write through unsafe parent paths`);
204
+ }
205
+ }
206
+ return resolveSafeRulePath(initiallyResolved, context.projectDir, context.realProjectDir);
207
+ }
208
+ function buildGrokBotRule(restoreBackupSuffix) {
209
+ return [
210
+ "---",
211
+ 'description: "Use tokenjuice for noisy terminal output in Grok Bot workspaces."',
212
+ "alwaysApply: true",
213
+ "---",
214
+ "",
215
+ TOKENJUICE_GROK_BOT_OWNERSHIP_MARKER,
216
+ ...(restoreBackupSuffix ? [`${TOKENJUICE_GROK_BOT_RESTORE_MARKER_PREFIX}${restoreBackupSuffix} -->`] : []),
217
+ "",
218
+ `# ${TOKENJUICE_GROK_BOT_RULE_MARKER}`,
219
+ "",
220
+ ...buildTokenjuiceGuidanceBullets({
221
+ wrapBullet: "- When running terminal commands through Grok Bot, prefer `tokenjuice wrap -- <command>` for commands likely to produce long output.",
222
+ }),
223
+ "- Grok Bot owns command execution and output delivery.",
224
+ "- Tokenjuice does not install an interception hook or rewrite Grok Bot tool results.",
225
+ "",
226
+ ].join("\n");
227
+ }
228
+ function isTokenjuiceRule(text) {
229
+ return /^---\r?\n(?:[^\r\n]*\r?\n)*---\r?\n\r?\n<!-- tokenjuice:grok-bot-rule -->(?:\r?\n|$)/u.test(text);
230
+ }
231
+ function inspectRestoreBackupReference(text) {
232
+ const markerLines = text.split(/\r?\n/u).filter((line) => line.includes(TOKENJUICE_GROK_BOT_RESTORE_MARKER_PREFIX));
233
+ if (markerLines.length === 0) {
234
+ return { kind: "none" };
235
+ }
236
+ if (markerLines.length !== 1) {
237
+ return { kind: "invalid" };
238
+ }
239
+ const match = markerLines[0]?.trim().match(/^<!-- tokenjuice:grok-bot-restore-backup=(\.bak(?:\.\d+)?) -->$/u);
240
+ return match?.[1] ? { kind: "valid", suffix: match[1] } : { kind: "invalid" };
241
+ }
242
+ async function readVerifiedRule(filePath) {
243
+ let file;
244
+ try {
245
+ const noFollowFlag = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
246
+ file = await open(filePath, constants.O_RDONLY | noFollowFlag);
247
+ }
248
+ catch (error) {
249
+ const code = error.code;
250
+ if (code === "ENOENT") {
251
+ return { exists: false, text: "", mode: 0o644 };
252
+ }
253
+ if (code === "ELOOP") {
254
+ throw new Error(`cannot use Grok Bot rule ${filePath}; tokenjuice will not read or write through symlinks`);
255
+ }
256
+ throw error;
257
+ }
258
+ try {
259
+ const fileStats = await file.stat();
260
+ const pathStats = await lstat(filePath);
261
+ if (!fileStats.isFile()
262
+ || !pathStats.isFile()
263
+ || pathStats.isSymbolicLink()
264
+ || fileStats.dev !== pathStats.dev
265
+ || fileStats.ino !== pathStats.ino
266
+ || fileStats.nlink !== 1
267
+ || pathStats.nlink !== 1) {
268
+ throw new Error(`cannot use Grok Bot rule ${filePath}; expected one regular, non-linked project file`);
269
+ }
270
+ return { exists: true, text: await file.readFile("utf8"), mode: fileStats.mode & 0o777 };
271
+ }
272
+ finally {
273
+ await file.close();
274
+ }
275
+ }
276
+ function snapshotsMatch(actual, expected) {
277
+ return actual.exists === expected.exists
278
+ && actual.text === expected.text
279
+ && (!actual.exists || actual.mode === expected.mode);
280
+ }
281
+ async function chooseBackupPath(filePath) {
282
+ for (let suffix = 0;; suffix += 1) {
283
+ const candidate = suffix === 0 ? `${filePath}.bak` : `${filePath}.bak.${suffix}`;
284
+ try {
285
+ const stats = await lstat(candidate);
286
+ if (stats.isSymbolicLink()) {
287
+ throw new Error(`cannot write Grok Bot rule backup ${candidate}; tokenjuice will not write through symlinks`);
288
+ }
289
+ }
290
+ catch (error) {
291
+ if (error.code === "ENOENT") {
292
+ return candidate;
293
+ }
294
+ throw error;
295
+ }
296
+ }
297
+ }
298
+ async function writeExclusiveFile(filePath, text, mode) {
299
+ const noFollowFlag = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
300
+ const file = await open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag, mode);
301
+ try {
302
+ await file.writeFile(text, "utf8");
303
+ await file.chmod(mode);
304
+ const fileStats = await file.stat();
305
+ const pathStats = await lstat(filePath);
306
+ if (!fileStats.isFile()
307
+ || !pathStats.isFile()
308
+ || pathStats.isSymbolicLink()
309
+ || fileStats.dev !== pathStats.dev
310
+ || fileStats.ino !== pathStats.ino
311
+ || fileStats.nlink !== 1
312
+ || pathStats.nlink !== 1) {
313
+ throw new Error(`cannot safely write Grok Bot rule file ${filePath}; the path changed during the operation`);
314
+ }
315
+ }
316
+ finally {
317
+ await file.close();
318
+ }
319
+ }
320
+ async function writeBackup(backupPath, snapshot) {
321
+ await writeExclusiveFile(backupPath, snapshot.text, snapshot.mode);
322
+ }
323
+ async function publishClaimedRule(claimedPath, destinationPath, mode) {
324
+ try {
325
+ await link(claimedPath, destinationPath);
326
+ }
327
+ catch (error) {
328
+ if (error.code === "EEXIST") {
329
+ return false;
330
+ }
331
+ try {
332
+ const claimed = await readVerifiedRule(claimedPath);
333
+ if (!claimed.exists) {
334
+ throw new Error(`cannot recover Grok Bot rule from missing claimed file ${claimedPath}`);
335
+ }
336
+ await writeExclusiveFile(destinationPath, claimed.text, mode);
337
+ }
338
+ catch (copyError) {
339
+ if (copyError.code === "EEXIST") {
340
+ return false;
341
+ }
342
+ throw copyError;
343
+ }
344
+ }
345
+ await rm(claimedPath, { force: true });
346
+ return true;
347
+ }
348
+ async function preserveClaimedRule(claimedPath, filePath, mode) {
349
+ for (let suffix = 0;; suffix += 1) {
350
+ const recoveryPath = suffix === 0
351
+ ? `${filePath}.tokenjuice-recovery`
352
+ : `${filePath}.tokenjuice-recovery.${suffix}`;
353
+ if (await publishClaimedRule(claimedPath, recoveryPath, mode)) {
354
+ return;
355
+ }
356
+ }
357
+ }
358
+ async function replaceRuleIfUnchanged(filePath, expected, nextText, nextMode = expected.mode) {
359
+ await mkdir(dirname(filePath), { recursive: true });
360
+ const tempDir = await mkdtemp(join(dirname(filePath), ".tokenjuice-grok-bot-"));
361
+ const nextPath = join(tempDir, "next");
362
+ const claimedPath = join(tempDir, "claimed");
363
+ let claimed = false;
364
+ try {
365
+ await writeExclusiveFile(nextPath, nextText, nextMode);
366
+ if (!expected.exists) {
367
+ try {
368
+ await link(nextPath, filePath);
369
+ }
370
+ catch (error) {
371
+ if (error.code === "EEXIST") {
372
+ throw new Error(`cannot safely install Grok Bot rule at ${filePath}; the file appeared during install`);
373
+ }
374
+ throw error;
375
+ }
376
+ return;
377
+ }
378
+ await rename(filePath, claimedPath);
379
+ claimed = true;
380
+ if (!snapshotsMatch(await readVerifiedRule(claimedPath), expected)) {
381
+ throw new Error(`cannot safely update Grok Bot rule at ${filePath}; the file changed during the operation`);
382
+ }
383
+ try {
384
+ await link(nextPath, filePath);
385
+ }
386
+ catch (error) {
387
+ if (error.code === "EEXIST") {
388
+ throw new Error(`cannot safely update Grok Bot rule at ${filePath}; another writer created the file`);
389
+ }
390
+ throw error;
391
+ }
392
+ await rm(claimedPath, { force: true });
393
+ claimed = false;
394
+ }
395
+ finally {
396
+ if (claimed) {
397
+ if (!(await publishClaimedRule(claimedPath, filePath, expected.mode))) {
398
+ await preserveClaimedRule(claimedPath, filePath, expected.mode);
399
+ }
400
+ claimed = false;
401
+ }
402
+ if (!claimed) {
403
+ await rm(tempDir, { recursive: true, force: true });
404
+ }
405
+ }
406
+ }
407
+ async function removeRuleIfUnchanged(filePath, expected) {
408
+ const tempDir = await mkdtemp(join(dirname(filePath), ".tokenjuice-grok-bot-remove-"));
409
+ const claimedPath = join(tempDir, "claimed");
410
+ let claimed = false;
411
+ try {
412
+ await rename(filePath, claimedPath);
413
+ claimed = true;
414
+ if (!snapshotsMatch(await readVerifiedRule(claimedPath), expected)) {
415
+ throw new Error(`cannot safely remove Grok Bot rule at ${filePath}; the file changed during the operation`);
416
+ }
417
+ await rm(claimedPath, { force: true });
418
+ claimed = false;
419
+ }
420
+ catch (error) {
421
+ if (claimed) {
422
+ if (!(await publishClaimedRule(claimedPath, filePath, expected.mode))) {
423
+ await preserveClaimedRule(claimedPath, filePath, expected.mode);
424
+ }
425
+ claimed = false;
426
+ }
427
+ throw error;
428
+ }
429
+ finally {
430
+ if (!claimed) {
431
+ await rm(tempDir, { recursive: true, force: true });
432
+ }
433
+ }
434
+ }
435
+ async function restoreBackupIfUnchanged(filePath, expectedRule, backupPath, expectedBackup) {
436
+ const tempDir = await mkdtemp(join(dirname(filePath), ".tokenjuice-grok-bot-restore-"));
437
+ const claimedBackupPath = join(tempDir, "backup");
438
+ let backupClaimed = false;
439
+ try {
440
+ await rename(backupPath, claimedBackupPath);
441
+ backupClaimed = true;
442
+ if (!snapshotsMatch(await readVerifiedRule(claimedBackupPath), expectedBackup)) {
443
+ throw new Error(`cannot safely restore the original Grok Bot rule from ${backupPath}; the backup changed`);
444
+ }
445
+ await replaceRuleIfUnchanged(filePath, expectedRule, expectedBackup.text, expectedBackup.mode);
446
+ await rm(claimedBackupPath, { force: true });
447
+ backupClaimed = false;
448
+ }
449
+ catch (error) {
450
+ if (backupClaimed) {
451
+ if (!(await publishClaimedRule(claimedBackupPath, backupPath, expectedBackup.mode))) {
452
+ await preserveClaimedRule(claimedBackupPath, backupPath, expectedBackup.mode);
453
+ }
454
+ backupClaimed = false;
455
+ }
456
+ throw error;
457
+ }
458
+ finally {
459
+ if (!backupClaimed) {
460
+ await rm(tempDir, { recursive: true, force: true });
461
+ }
462
+ }
463
+ }
464
+ export async function installGrokBotRule(rulePath, options = {}) {
465
+ const resolvedRulePath = await prepareRulePathForInstall(rulePath, options);
466
+ const existing = await readVerifiedRule(resolvedRulePath);
467
+ const restoreBackupReference = isTokenjuiceRule(existing.text)
468
+ ? inspectRestoreBackupReference(existing.text)
469
+ : { kind: "none" };
470
+ if (restoreBackupReference.kind === "invalid") {
471
+ throw new Error(`cannot safely repair ${resolvedRulePath}; its restore backup marker is malformed or duplicated`);
472
+ }
473
+ const restoreBackupSuffix = restoreBackupReference.kind === "valid"
474
+ ? restoreBackupReference.suffix
475
+ : undefined;
476
+ const expectedRule = buildGrokBotRule(restoreBackupSuffix);
477
+ if (existing.exists && existing.text === expectedRule) {
478
+ return { rulePath: resolvedRulePath };
479
+ }
480
+ let backupPath;
481
+ let nextRule = expectedRule;
482
+ if (existing.exists && !isTokenjuiceRule(existing.text)) {
483
+ backupPath = await chooseBackupPath(resolvedRulePath);
484
+ await writeBackup(backupPath, existing);
485
+ nextRule = buildGrokBotRule(backupPath.slice(resolvedRulePath.length));
486
+ }
487
+ try {
488
+ await replaceRuleIfUnchanged(resolvedRulePath, existing, nextRule);
489
+ }
490
+ catch (error) {
491
+ if (backupPath) {
492
+ await removeRuleIfUnchanged(backupPath, {
493
+ exists: true,
494
+ text: existing.text,
495
+ mode: existing.mode,
496
+ }).catch(() => undefined);
497
+ }
498
+ throw error;
499
+ }
500
+ return { rulePath: resolvedRulePath, ...(backupPath ? { backupPath } : {}) };
501
+ }
502
+ export async function uninstallGrokBotRule(rulePath, options = {}) {
503
+ const resolvedRulePath = await resolveRulePath(rulePath, options);
504
+ const existing = await readVerifiedRule(resolvedRulePath);
505
+ if (!existing.exists) {
506
+ return { rulePath: resolvedRulePath, removed: false, restoredBackup: false };
507
+ }
508
+ if (!isTokenjuiceRule(existing.text)) {
509
+ throw new Error(`refusing to remove ${resolvedRulePath}; it is not the tokenjuice Grok Bot rule`);
510
+ }
511
+ const restoreBackupReference = inspectRestoreBackupReference(existing.text);
512
+ if (restoreBackupReference.kind === "invalid") {
513
+ throw new Error(`cannot safely uninstall ${resolvedRulePath}; its restore backup marker is malformed or duplicated`);
514
+ }
515
+ if (restoreBackupReference.kind === "valid") {
516
+ const backupPath = `${resolvedRulePath}${restoreBackupReference.suffix}`;
517
+ const backup = await readVerifiedRule(backupPath);
518
+ if (!backup.exists || isTokenjuiceRule(backup.text)) {
519
+ throw new Error(`cannot restore the original Grok Bot rule from ${backupPath}; review the backup manually`);
520
+ }
521
+ await restoreBackupIfUnchanged(resolvedRulePath, existing, backupPath, backup);
522
+ return { rulePath: resolvedRulePath, removed: true, restoredBackup: true };
523
+ }
524
+ await removeRuleIfUnchanged(resolvedRulePath, existing);
525
+ return { rulePath: resolvedRulePath, removed: true, restoredBackup: false };
526
+ }
527
+ export async function doctorGrokBotRule(rulePath, options = {}) {
528
+ let resolvedRulePath;
529
+ try {
530
+ resolvedRulePath = await resolveRulePath(rulePath, options);
531
+ }
532
+ catch (error) {
533
+ return {
534
+ rulePath: rulePath ?? (await getDefaultAliasPath(options)),
535
+ hasTokenjuiceMarker: false,
536
+ ...buildInstructionDoctorReportFields({
537
+ status: "broken",
538
+ issues: [error.message],
539
+ advisory: TOKENJUICE_GROK_BOT_ADVISORY,
540
+ fixCommand: TOKENJUICE_GROK_BOT_FIX_COMMAND,
541
+ }),
542
+ };
543
+ }
544
+ let existing;
545
+ try {
546
+ existing = await readVerifiedRule(resolvedRulePath);
547
+ }
548
+ catch (error) {
549
+ return {
550
+ rulePath: resolvedRulePath,
551
+ hasTokenjuiceMarker: false,
552
+ ...buildInstructionDoctorReportFields({
553
+ status: "broken",
554
+ issues: [error.message],
555
+ advisory: TOKENJUICE_GROK_BOT_ADVISORY,
556
+ fixCommand: TOKENJUICE_GROK_BOT_FIX_COMMAND,
557
+ }),
558
+ };
559
+ }
560
+ const hasTokenjuiceMarker = isTokenjuiceRule(existing.text);
561
+ if (!existing.exists || !hasTokenjuiceMarker) {
562
+ return {
563
+ rulePath: resolvedRulePath,
564
+ hasTokenjuiceMarker,
565
+ ...buildInstructionDoctorReportFields({
566
+ status: "disabled",
567
+ issues: existing.exists
568
+ ? ["tokenjuice Grok Bot rule is not installed; existing rule file is not tokenjuice-managed"]
569
+ : ["tokenjuice Grok Bot rule is not installed"],
570
+ advisory: TOKENJUICE_GROK_BOT_ADVISORY,
571
+ fixCommand: TOKENJUICE_GROK_BOT_FIX_COMMAND,
572
+ }),
573
+ };
574
+ }
575
+ const issues = collectGuidanceIssues(existing.text, {
576
+ required: [
577
+ {
578
+ requiredText: TOKENJUICE_GROK_BOT_OWNERSHIP_MARKER,
579
+ missingIssue: "configured Grok Bot rule is missing the tokenjuice ownership marker",
580
+ },
581
+ {
582
+ requiredText: TOKENJUICE_GROK_BOT_RULE_MARKER,
583
+ missingIssue: "configured Grok Bot rule does not look like the tokenjuice rule",
584
+ },
585
+ {
586
+ requiredText: TOKENJUICE_WRAP_COMMAND,
587
+ missingIssue: "configured Grok Bot rule is missing tokenjuice wrap guidance",
588
+ },
589
+ {
590
+ requiredText: TOKENJUICE_RAW_COMMAND,
591
+ missingIssue: "configured Grok Bot rule is missing the raw escape hatch",
592
+ },
593
+ {
594
+ requiredText: "does not install an interception hook or rewrite Grok Bot tool results",
595
+ missingIssue: "configured Grok Bot rule is missing the guidance-only boundary",
596
+ },
597
+ ],
598
+ forbidden: [
599
+ {
600
+ forbiddenText: TOKENJUICE_FULL_COMMAND,
601
+ presentIssue: "configured Grok Bot rule still suggests the full escape hatch",
602
+ },
603
+ ],
604
+ });
605
+ const frontmatter = inspectFrontmatter(existing.text);
606
+ if (!frontmatter.isValid) {
607
+ issues.unshift("configured Grok Bot rule has invalid or duplicate frontmatter");
608
+ }
609
+ if (!frontmatter.hasDescription) {
610
+ issues.unshift("configured Grok Bot rule is missing description frontmatter");
611
+ }
612
+ if (!frontmatter.hasAlwaysApply) {
613
+ issues.unshift("configured Grok Bot rule is missing alwaysApply frontmatter");
614
+ }
615
+ const restoreBackupReference = inspectRestoreBackupReference(existing.text);
616
+ if (restoreBackupReference.kind === "invalid") {
617
+ issues.push("configured Grok Bot rule has a malformed or duplicated restore backup marker");
618
+ }
619
+ else if (restoreBackupReference.kind === "valid") {
620
+ const backupPath = `${resolvedRulePath}${restoreBackupReference.suffix}`;
621
+ try {
622
+ const backup = await readVerifiedRule(backupPath);
623
+ if (!backup.exists) {
624
+ issues.push(`configured Grok Bot rule references missing restore backup ${backupPath}`);
625
+ }
626
+ else if (isTokenjuiceRule(backup.text)) {
627
+ issues.push(`configured Grok Bot rule restore backup ${backupPath} is tokenjuice-managed`);
628
+ }
629
+ }
630
+ catch (error) {
631
+ issues.push(error.message);
632
+ }
633
+ }
634
+ return {
635
+ rulePath: resolvedRulePath,
636
+ hasTokenjuiceMarker,
637
+ ...buildInstructionDoctorReportFields({
638
+ status: instructionDoctorStatusFromIssues(issues),
639
+ issues,
640
+ advisory: TOKENJUICE_GROK_BOT_ADVISORY,
641
+ fixCommand: TOKENJUICE_GROK_BOT_FIX_COMMAND,
642
+ }),
643
+ };
644
+ }