@openclaw/tokenjuice 2026.9.3 → 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.
- package/assets/activity.svg +3 -0
- package/assets/icon.png +0 -0
- package/node_modules/tokenjuice/README.md +6 -1
- package/node_modules/tokenjuice/dist/cli/install-output.d.ts +7 -0
- package/node_modules/tokenjuice/dist/cli/install-output.js +19 -0
- package/node_modules/tokenjuice/dist/cli/main.d.ts +4 -0
- package/node_modules/tokenjuice/dist/cli/main.js +143 -26
- package/node_modules/tokenjuice/dist/core/artifacts.d.ts +1 -0
- package/node_modules/tokenjuice/dist/core/artifacts.js +29 -0
- package/node_modules/tokenjuice/dist/core/compaction-metadata.d.ts +1 -1
- package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.d.ts +1 -0
- package/node_modules/tokenjuice/dist/core/integrations/compact-bash-result.js +1 -1
- package/node_modules/tokenjuice/dist/core/reduce.js +18 -10
- package/node_modules/tokenjuice/dist/core/text.d.ts +4 -0
- package/node_modules/tokenjuice/dist/core/text.js +32 -0
- package/node_modules/tokenjuice/dist/hosts/codex/index.d.ts +25 -1
- package/node_modules/tokenjuice/dist/hosts/codex/index.js +211 -163
- package/node_modules/tokenjuice/dist/hosts/grok-bot/index.d.ts +25 -0
- package/node_modules/tokenjuice/dist/hosts/grok-bot/index.js +644 -0
- package/node_modules/tokenjuice/dist/hosts/opencode/extension/runtime.js +79 -10
- package/node_modules/tokenjuice/dist/hosts/pi/extension/runtime.js +79 -10
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.d.ts +24 -0
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command-doctor.js +80 -1
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command.d.ts +19 -0
- package/node_modules/tokenjuice/dist/hosts/shared/hook-command.js +61 -6
- package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.d.ts +3 -1
- package/node_modules/tokenjuice/dist/hosts/shared/hook-doctor.js +2 -0
- package/node_modules/tokenjuice/dist/hosts/shared/host-command.d.ts +10 -1
- package/node_modules/tokenjuice/dist/hosts/shared/host-command.js +43 -4
- package/node_modules/tokenjuice/dist/hosts/shared/pre-tool-wrap.js +9 -7
- package/node_modules/tokenjuice/dist/index.d.ts +2 -0
- package/node_modules/tokenjuice/dist/index.js +1 -0
- package/node_modules/tokenjuice/package.json +1 -1
- package/openclaw.plugin.json +1 -0
- package/package.json +8 -6
|
@@ -8,6 +8,9 @@ const TRUNCATION_SUFFIX = "\n... truncated ...";
|
|
|
8
8
|
const MIDDLE_TRUNCATION_MARKER = "\n... omitted ...\n";
|
|
9
9
|
const COMBINING_MARK_PATTERN = /\p{Mark}/u;
|
|
10
10
|
const EMOJI_PATTERN = /\p{Extended_Pictographic}/u;
|
|
11
|
+
const FLAG_EMOJI_PATTERN = /^\p{Regional_Indicator}{2}$/u;
|
|
12
|
+
const KEYCAP_EMOJI_PATTERN = /^[#*0-9]\uFE0F?\u20E3$/u;
|
|
13
|
+
const REPEATED_EMOJI_BANNER_MIN_REPETITIONS = 24;
|
|
11
14
|
const graphemeSegmenter = typeof Intl !== "undefined" && "Segmenter" in Intl
|
|
12
15
|
? new Intl.Segmenter(undefined, { granularity: "grapheme" })
|
|
13
16
|
: null;
|
|
@@ -115,6 +118,35 @@ export function dedupeAdjacent(lines) {
|
|
|
115
118
|
}
|
|
116
119
|
return next;
|
|
117
120
|
}
|
|
121
|
+
function formatCodePoints(text) {
|
|
122
|
+
return Array.from(text, (character) => `U+${character.codePointAt(0)?.toString(16).toUpperCase().padStart(4, "0")}`).join("+");
|
|
123
|
+
}
|
|
124
|
+
function isEmojiGrapheme(text) {
|
|
125
|
+
return EMOJI_PATTERN.test(text)
|
|
126
|
+
|| FLAG_EMOJI_PATTERN.test(text)
|
|
127
|
+
|| KEYCAP_EMOJI_PATTERN.test(text);
|
|
128
|
+
}
|
|
129
|
+
export function collapseRepeatedEmojiBanner(lines) {
|
|
130
|
+
let collapsed = false;
|
|
131
|
+
const nextLines = lines.map((line) => {
|
|
132
|
+
const visibleSegments = graphemes(line).filter((segment) => !/^\s+$/u.test(segment));
|
|
133
|
+
const repeatedEmoji = visibleSegments[0];
|
|
134
|
+
if (visibleSegments.length < REPEATED_EMOJI_BANNER_MIN_REPETITIONS
|
|
135
|
+
|| !repeatedEmoji
|
|
136
|
+
|| !isEmojiGrapheme(repeatedEmoji)
|
|
137
|
+
|| visibleSegments.some((segment) => segment !== repeatedEmoji)) {
|
|
138
|
+
return line;
|
|
139
|
+
}
|
|
140
|
+
collapsed = true;
|
|
141
|
+
return `[repeated emoji banner omitted: ${formatCodePoints(repeatedEmoji)} x${visibleSegments.length}]`;
|
|
142
|
+
});
|
|
143
|
+
return collapsed
|
|
144
|
+
? {
|
|
145
|
+
lines: nextLines,
|
|
146
|
+
compaction: createCompactionMetadata("repeated-emoji-banner-omission"),
|
|
147
|
+
}
|
|
148
|
+
: { lines: nextLines };
|
|
149
|
+
}
|
|
118
150
|
export function headTail(lines, head, tail, noOmit = false) {
|
|
119
151
|
const safeHead = Math.max(0, head);
|
|
120
152
|
const safeTail = Math.max(0, tail);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { HookCommandPackageVersionMismatch, HookCommandRuntimeMismatch } from "../shared/hook-command-doctor.js";
|
|
1
2
|
export type InstallCodexHookResult = {
|
|
2
3
|
hooksPath: string;
|
|
3
4
|
backupPath?: string;
|
|
@@ -40,6 +41,7 @@ export type CodexHookCommandOptions = {
|
|
|
40
41
|
local?: boolean;
|
|
41
42
|
binaryPath?: string;
|
|
42
43
|
nodePath?: string;
|
|
44
|
+
noOmit?: boolean;
|
|
43
45
|
/**
|
|
44
46
|
* Override for the config.toml consulted when reporting the
|
|
45
47
|
* `codex_hooks` feature-flag state. Defaults to `~/.codex/config.toml`.
|
|
@@ -48,6 +50,16 @@ export type CodexHookCommandOptions = {
|
|
|
48
50
|
*/
|
|
49
51
|
featureFlagConfigPath?: string;
|
|
50
52
|
};
|
|
53
|
+
export type CodexHookCommandDiagnostic = {
|
|
54
|
+
location: string;
|
|
55
|
+
command: string;
|
|
56
|
+
checkedPaths: string[];
|
|
57
|
+
missingPaths: string[];
|
|
58
|
+
nonExecutablePaths: string[];
|
|
59
|
+
runtimePath?: string;
|
|
60
|
+
runtimeMismatch?: HookCommandRuntimeMismatch;
|
|
61
|
+
packageVersionMismatch?: HookCommandPackageVersionMismatch;
|
|
62
|
+
};
|
|
51
63
|
export type CodexDoctorReport = {
|
|
52
64
|
hooksPath: string;
|
|
53
65
|
status: "ok" | "warn" | "broken" | "disabled";
|
|
@@ -55,8 +67,17 @@ export type CodexDoctorReport = {
|
|
|
55
67
|
fixCommand: string;
|
|
56
68
|
expectedCommand: string;
|
|
57
69
|
detectedCommand?: string;
|
|
70
|
+
detectedCommands: CodexHookCommandDiagnostic[];
|
|
71
|
+
duplicateHookCount: number;
|
|
58
72
|
checkedPaths: string[];
|
|
59
73
|
missingPaths: string[];
|
|
74
|
+
nonExecutablePaths: string[];
|
|
75
|
+
runtimeMismatches: Array<HookCommandRuntimeMismatch & {
|
|
76
|
+
location: string;
|
|
77
|
+
}>;
|
|
78
|
+
packageVersionMismatches: Array<HookCommandPackageVersionMismatch & {
|
|
79
|
+
location: string;
|
|
80
|
+
}>;
|
|
60
81
|
featureFlag: CodexFeatureFlagStatus;
|
|
61
82
|
runtimeConfig: CodexRuntimeConfigStatus;
|
|
62
83
|
};
|
|
@@ -90,4 +111,7 @@ export declare function inspectCodexRuntimeConfig(configPath?: string): Promise<
|
|
|
90
111
|
export declare function installCodexHook(hooksPath?: string, options?: CodexHookCommandOptions): Promise<InstallCodexHookResult>;
|
|
91
112
|
export declare function uninstallCodexHook(hooksPath?: string): Promise<UninstallCodexHookResult>;
|
|
92
113
|
export declare function doctorCodexHook(hooksPath?: string, options?: CodexHookCommandOptions): Promise<CodexDoctorReport>;
|
|
93
|
-
export declare function runCodexPostToolUseHook(rawText: string
|
|
114
|
+
export declare function runCodexPostToolUseHook(rawText: string, options?: {
|
|
115
|
+
noOmit?: boolean;
|
|
116
|
+
allowOmit?: boolean;
|
|
117
|
+
}): Promise<number>;
|
|
@@ -1,18 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
1
|
+
import { appendFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
4
3
|
import { homedir } from "node:os";
|
|
5
4
|
import packageJson from "../../../package.json" with { type: "json" };
|
|
6
5
|
import { stripLeadingCdPrefix } from "../../core/command.js";
|
|
7
|
-
import {
|
|
6
|
+
import { tryStoreArtifactMetadata } from "../../core/artifacts.js";
|
|
7
|
+
import { readNoOmissionFromEnv } from "../../core/env.js";
|
|
8
8
|
import { compactBashResult, getOutputAwareInspectionSkipReason } from "../../core/integrations/compact-bash-result.js";
|
|
9
9
|
import { classifyOnly } from "../../core/reduce.js";
|
|
10
|
-
import { countTextChars, stripAnsi } from "../../core/text.js";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
10
|
+
import { countTextChars, sliceTextChars, stripAnsi } from "../../core/text.js";
|
|
11
|
+
import { isNodeExecutablePath, parseShellWords } from "../shared/hook-command.js";
|
|
12
|
+
import { buildTokenjuiceHookCommand } from "../shared/host-command.js";
|
|
13
|
+
import { inspectTokenjuiceHookCommand } from "../shared/hook-command-doctor.js";
|
|
13
14
|
const GENERIC_FALLBACK_MIN_SAVED_CHARS = 120;
|
|
14
15
|
const GENERIC_FALLBACK_MAX_RATIO = 0.75;
|
|
15
16
|
const HOOK_REWRITE_MIN_SAVED_CHARS = 8;
|
|
17
|
+
const CODEX_HOOK_MAX_COMPACTION_BYTES = 1 * 1024 * 1024;
|
|
16
18
|
const CODEX_HOOK_LAST_LOG = "tokenjuice-hook.last.json";
|
|
17
19
|
const CODEX_HOOK_HISTORY_LOG = "tokenjuice-hook.history.jsonl";
|
|
18
20
|
const CODEX_HOOK_HISTORY_LIMIT = 200;
|
|
@@ -21,7 +23,12 @@ const CODEX_HOOK_HISTORY_LOCK_RETRY_MS = 25;
|
|
|
21
23
|
const CODEX_HOOK_HISTORY_LOCK_RETRIES = 8;
|
|
22
24
|
const LOW_NON_TOKENJUICE_TIMEOUT_SECONDS = 2;
|
|
23
25
|
const RECOMMENDED_NON_TOKENJUICE_TIMEOUT_SECONDS = 6;
|
|
24
|
-
const TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS =
|
|
26
|
+
const TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS = 30;
|
|
27
|
+
function validateCodexOmissionPolicy(options) {
|
|
28
|
+
if (options.noOmit && options.allowOmit) {
|
|
29
|
+
throw new Error("Codex noOmit and allowOmit policies cannot be enabled together");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
25
32
|
const TOKENJUICE_CODEX_STATUS = "compacting bash output with tokenjuice";
|
|
26
33
|
const TOKENJUICE_CODEX_FIX_COMMAND = "tokenjuice install codex";
|
|
27
34
|
function getCodexHome() {
|
|
@@ -196,65 +203,18 @@ function parseCodexRuntimeConfig(source) {
|
|
|
196
203
|
}
|
|
197
204
|
return values;
|
|
198
205
|
}
|
|
199
|
-
async function isExecutableFile(path) {
|
|
200
|
-
try {
|
|
201
|
-
await access(path, fsConstants.X_OK);
|
|
202
|
-
return true;
|
|
203
|
-
}
|
|
204
|
-
catch {
|
|
205
|
-
return false;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
async function resolveInstalledTokenjuicePath() {
|
|
209
|
-
const pathValue = process.env.PATH;
|
|
210
|
-
if (!pathValue) {
|
|
211
|
-
return undefined;
|
|
212
|
-
}
|
|
213
|
-
const candidateNames = process.platform === "win32"
|
|
214
|
-
? ["tokenjuice.exe", "tokenjuice.cmd", "tokenjuice.bat", "tokenjuice"]
|
|
215
|
-
: ["tokenjuice"];
|
|
216
|
-
for (const segment of pathValue.split(delimiter)) {
|
|
217
|
-
if (!segment) {
|
|
218
|
-
continue;
|
|
219
|
-
}
|
|
220
|
-
for (const candidateName of candidateNames) {
|
|
221
|
-
const candidatePath = join(segment, candidateName);
|
|
222
|
-
if (await isExecutableFile(candidatePath)) {
|
|
223
|
-
return candidatePath;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
return undefined;
|
|
228
|
-
}
|
|
229
206
|
async function buildCodexHookCommand(options = {}) {
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
}
|
|
236
|
-
if (!options.local) {
|
|
237
|
-
const installedBinaryPath = await resolveInstalledTokenjuicePath();
|
|
238
|
-
if (installedBinaryPath) {
|
|
239
|
-
return `${shellQuote(installedBinaryPath)} codex-post-tool-use`;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
if (binaryPath.endsWith(".js")) {
|
|
243
|
-
return `${shellQuote(nodePath)} ${shellQuote(binaryPath)} codex-post-tool-use`;
|
|
244
|
-
}
|
|
245
|
-
return `${shellQuote(binaryPath)} codex-post-tool-use`;
|
|
207
|
+
const command = await buildTokenjuiceHookCommand("codex-post-tool-use", "codex", {
|
|
208
|
+
...options,
|
|
209
|
+
pinNodeForJavaScriptLauncher: true,
|
|
210
|
+
});
|
|
211
|
+
return options.noOmit ? `${command} --no-omit` : command;
|
|
246
212
|
}
|
|
247
|
-
function getCodexFixCommand(local = false) {
|
|
248
|
-
return
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
await access(path);
|
|
253
|
-
return true;
|
|
254
|
-
}
|
|
255
|
-
catch {
|
|
256
|
-
return false;
|
|
257
|
-
}
|
|
213
|
+
function getCodexFixCommand(local = false, noOmit = false) {
|
|
214
|
+
return [
|
|
215
|
+
local ? "tokenjuice install codex --local" : TOKENJUICE_CODEX_FIX_COMMAND,
|
|
216
|
+
...(noOmit ? ["--no-omit"] : []),
|
|
217
|
+
].join(" ");
|
|
258
218
|
}
|
|
259
219
|
async function newestMtimeMs(path) {
|
|
260
220
|
try {
|
|
@@ -330,33 +290,32 @@ function createTokenjuiceCodexHook(command) {
|
|
|
330
290
|
],
|
|
331
291
|
};
|
|
332
292
|
}
|
|
333
|
-
function
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|| command.includes("post_tool_use_tokenjuice.py");
|
|
339
|
-
});
|
|
293
|
+
function isTokenjuiceCodexHookCommand(hook) {
|
|
294
|
+
const command = typeof hook.command === "string" ? hook.command : "";
|
|
295
|
+
return hook.statusMessage === TOKENJUICE_CODEX_STATUS
|
|
296
|
+
|| command.includes("codex-post-tool-use")
|
|
297
|
+
|| command.includes("post_tool_use_tokenjuice.py");
|
|
340
298
|
}
|
|
341
|
-
function
|
|
342
|
-
return
|
|
299
|
+
function isTokenjuiceCodexHook(group) {
|
|
300
|
+
return group.hooks.some((hook) => isTokenjuiceCodexHookCommand(hook));
|
|
343
301
|
}
|
|
344
|
-
function
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
302
|
+
function collectTokenjuiceCodexHookCommands(config) {
|
|
303
|
+
const commands = [];
|
|
304
|
+
for (const [eventName, groups] of Object.entries(config.hooks)) {
|
|
305
|
+
groups.forEach((group, groupIndex) => {
|
|
306
|
+
group.hooks.forEach((hook, hookIndex) => {
|
|
307
|
+
if (!isTokenjuiceCodexHookCommand(hook) || typeof hook.command !== "string") {
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
commands.push({
|
|
311
|
+
location: `${eventName}[${groupIndex}].hooks[${hookIndex}]`,
|
|
312
|
+
hook,
|
|
313
|
+
command: hook.command,
|
|
314
|
+
});
|
|
315
|
+
});
|
|
354
316
|
});
|
|
355
|
-
if (hook) {
|
|
356
|
-
return hook;
|
|
357
|
-
}
|
|
358
317
|
}
|
|
359
|
-
return
|
|
318
|
+
return commands;
|
|
360
319
|
}
|
|
361
320
|
function truncateHookCommand(command, maxLength = 80) {
|
|
362
321
|
const trimmed = command.trim();
|
|
@@ -365,35 +324,6 @@ function truncateHookCommand(command, maxLength = 80) {
|
|
|
365
324
|
}
|
|
366
325
|
return `${trimmed.slice(0, maxLength - 3)}...`;
|
|
367
326
|
}
|
|
368
|
-
function extractHomebrewCellarVersion(path) {
|
|
369
|
-
const normalized = path.replace(/\\/gu, "/");
|
|
370
|
-
const match = normalized.match(/\/Cellar\/tokenjuice\/([^/]+)\//u);
|
|
371
|
-
return match?.[1];
|
|
372
|
-
}
|
|
373
|
-
async function detectResolvedHomebrewVersionMismatch(commandPaths) {
|
|
374
|
-
for (const path of commandPaths) {
|
|
375
|
-
if (!path.endsWith("/tokenjuice") && !path.endsWith("\\tokenjuice") && !path.endsWith("\\tokenjuice.exe")) {
|
|
376
|
-
continue;
|
|
377
|
-
}
|
|
378
|
-
let resolvedPath;
|
|
379
|
-
try {
|
|
380
|
-
resolvedPath = await realpath(path);
|
|
381
|
-
}
|
|
382
|
-
catch {
|
|
383
|
-
continue;
|
|
384
|
-
}
|
|
385
|
-
const resolvedVersion = extractHomebrewCellarVersion(resolvedPath);
|
|
386
|
-
if (!resolvedVersion || resolvedVersion === packageJson.version) {
|
|
387
|
-
continue;
|
|
388
|
-
}
|
|
389
|
-
return {
|
|
390
|
-
launcherPath: path,
|
|
391
|
-
resolvedPath,
|
|
392
|
-
resolvedVersion,
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
return undefined;
|
|
396
|
-
}
|
|
397
327
|
function collectLowTimeoutWarnings(config) {
|
|
398
328
|
const issues = [];
|
|
399
329
|
for (const [eventName, groups] of Object.entries(config.hooks)) {
|
|
@@ -420,16 +350,14 @@ function collectLowTimeoutWarnings(config) {
|
|
|
420
350
|
return issues;
|
|
421
351
|
}
|
|
422
352
|
function collectTokenjuiceHookTimeoutWarnings(config, fixCommand) {
|
|
423
|
-
const
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
}
|
|
427
|
-
if (hook.timeout !== TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS) {
|
|
353
|
+
const staleCommands = collectTokenjuiceCodexHookCommands(config)
|
|
354
|
+
.filter(({ hook }) => hook.timeout !== TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS);
|
|
355
|
+
if (staleCommands.length === 1) {
|
|
428
356
|
return [
|
|
429
357
|
`configured Codex tokenjuice hook timeout is missing or stale; run ${fixCommand} to add the ${TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS}s safety cap`,
|
|
430
358
|
];
|
|
431
359
|
}
|
|
432
|
-
return
|
|
360
|
+
return staleCommands.map(({ location }) => `configured Codex tokenjuice hook ${location} timeout is missing or stale; run ${fixCommand} to add the ${TOKENJUICE_CODEX_HOOK_TIMEOUT_SECONDS}s safety cap`);
|
|
433
361
|
}
|
|
434
362
|
function sanitizeHooksConfig(raw) {
|
|
435
363
|
if (!isRecord(raw) || !isRecord(raw.hooks)) {
|
|
@@ -539,16 +467,58 @@ function commandRequestsTokenjuiceRawBypass(command) {
|
|
|
539
467
|
const optionArgs = argv.slice(wrapIndex + 1, optionEndIndex === -1 ? undefined : optionEndIndex);
|
|
540
468
|
return optionArgs.includes("--raw") || optionArgs.includes("--full");
|
|
541
469
|
}
|
|
542
|
-
function buildCodexFeedback(inlineText, rawRefId) {
|
|
543
|
-
|
|
470
|
+
function buildCodexFeedback(inlineText, rawRefId, compaction, exitCode, maxChars = 1200, noOmit = false) {
|
|
471
|
+
const recoveryReference = rawRefId
|
|
472
|
+
? `tokenjuice cat ${rawRefId}`
|
|
473
|
+
: "tokenjuice wrap --raw -- <command>";
|
|
474
|
+
const serialize = (compactedOutput, authoritative) => [
|
|
475
|
+
"<tokenjuice_compacted_tool_observation>",
|
|
476
|
+
JSON.stringify({
|
|
477
|
+
source: "codex-post-tool-use",
|
|
478
|
+
exitCode: exitCode ?? null,
|
|
479
|
+
authority: authoritative ? "authoritative-omission" : "non-authoritative-rewrite",
|
|
480
|
+
compactedOutput,
|
|
481
|
+
...(authoritative ? { recoveryReference } : {}),
|
|
482
|
+
}, null, 2),
|
|
483
|
+
"</tokenjuice_compacted_tool_observation>",
|
|
484
|
+
].join("\n");
|
|
485
|
+
const feedback = serialize(inlineText, compaction?.authoritative === true);
|
|
486
|
+
if (countTextChars(feedback) <= maxChars) {
|
|
487
|
+
return { text: feedback, truncated: false };
|
|
488
|
+
}
|
|
489
|
+
if (noOmit) {
|
|
490
|
+
return undefined;
|
|
491
|
+
}
|
|
492
|
+
const truncationMarker = "\n... compacted observation truncated ...";
|
|
493
|
+
let low = 0;
|
|
494
|
+
let high = countTextChars(inlineText);
|
|
495
|
+
let best;
|
|
496
|
+
while (low <= high) {
|
|
497
|
+
const midpoint = Math.floor((low + high) / 2);
|
|
498
|
+
const candidate = serialize(`${sliceTextChars(inlineText, 0, midpoint)}${truncationMarker}`, true);
|
|
499
|
+
if (countTextChars(candidate) <= maxChars) {
|
|
500
|
+
best = candidate;
|
|
501
|
+
low = midpoint + 1;
|
|
502
|
+
}
|
|
503
|
+
else {
|
|
504
|
+
high = midpoint - 1;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return best ? { text: best, truncated: true } : undefined;
|
|
544
508
|
}
|
|
545
|
-
function buildCodexReplacementOutput(inlineText, rawRefId) {
|
|
546
|
-
const feedback = buildCodexFeedback(inlineText, rawRefId);
|
|
509
|
+
function buildCodexReplacementOutput(inlineText, rawRefId, compaction, exitCode, maxChars, noOmit) {
|
|
510
|
+
const feedback = buildCodexFeedback(inlineText, rawRefId, compaction, exitCode, maxChars, noOmit);
|
|
511
|
+
if (!feedback) {
|
|
512
|
+
return undefined;
|
|
513
|
+
}
|
|
547
514
|
return {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
515
|
+
payload: {
|
|
516
|
+
hookSpecificOutput: {
|
|
517
|
+
hookEventName: "PostToolUse",
|
|
518
|
+
additionalContext: feedback.text,
|
|
519
|
+
},
|
|
551
520
|
},
|
|
521
|
+
truncated: feedback.truncated,
|
|
552
522
|
};
|
|
553
523
|
}
|
|
554
524
|
function parseExitCodeValue(value) {
|
|
@@ -618,11 +588,31 @@ export async function uninstallCodexHook(hooksPath = getDefaultHooksPath()) {
|
|
|
618
588
|
};
|
|
619
589
|
}
|
|
620
590
|
export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options = {}) {
|
|
591
|
+
const noOmit = options.noOmit === true;
|
|
621
592
|
const expectedCommand = await buildCodexHookCommand(options);
|
|
622
|
-
const
|
|
593
|
+
const expectedNodePath = options.nodePath ?? process.execPath;
|
|
594
|
+
const installFixCommand = getCodexFixCommand(options.local, noOmit);
|
|
623
595
|
let fixCommand = installFixCommand;
|
|
624
596
|
const { config, exists } = await readHooksConfig(hooksPath);
|
|
625
|
-
const
|
|
597
|
+
const locatedCommands = collectTokenjuiceCodexHookCommands(config);
|
|
598
|
+
const detectedCommands = await Promise.all(locatedCommands.map(async ({ location, command }) => ({
|
|
599
|
+
location,
|
|
600
|
+
command,
|
|
601
|
+
...(await inspectTokenjuiceHookCommand({
|
|
602
|
+
command,
|
|
603
|
+
expectedNodePath,
|
|
604
|
+
expectedPackageVersion: packageJson.version,
|
|
605
|
+
})),
|
|
606
|
+
})));
|
|
607
|
+
const detectedCommand = detectedCommands[0]?.command;
|
|
608
|
+
const duplicateHookCount = Math.max(0, detectedCommands.length - 1);
|
|
609
|
+
const checkedPaths = [...new Set(detectedCommands.flatMap((entry) => entry.checkedPaths))];
|
|
610
|
+
const missingPaths = [...new Set(detectedCommands.flatMap((entry) => entry.missingPaths))];
|
|
611
|
+
const nonExecutablePaths = [...new Set(detectedCommands.flatMap((entry) => entry.nonExecutablePaths))];
|
|
612
|
+
const runtimeMismatches = detectedCommands.flatMap((entry) => entry.runtimeMismatch ? [{ location: entry.location, ...entry.runtimeMismatch }] : []);
|
|
613
|
+
const packageVersionMismatches = detectedCommands.flatMap((entry) => entry.packageVersionMismatch
|
|
614
|
+
? [{ location: entry.location, ...entry.packageVersionMismatch }]
|
|
615
|
+
: []);
|
|
626
616
|
const featureFlag = await inspectCodexHooksFeatureFlag(options.featureFlagConfigPath);
|
|
627
617
|
const runtimeConfig = await inspectCodexRuntimeConfig(options.featureFlagConfigPath);
|
|
628
618
|
if (!exists) {
|
|
@@ -632,8 +622,13 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
632
622
|
issues: [],
|
|
633
623
|
fixCommand,
|
|
634
624
|
expectedCommand,
|
|
625
|
+
detectedCommands,
|
|
626
|
+
duplicateHookCount,
|
|
635
627
|
checkedPaths: [],
|
|
636
628
|
missingPaths: [],
|
|
629
|
+
nonExecutablePaths: [],
|
|
630
|
+
runtimeMismatches: [],
|
|
631
|
+
packageVersionMismatches: [],
|
|
637
632
|
featureFlag,
|
|
638
633
|
runtimeConfig,
|
|
639
634
|
};
|
|
@@ -645,22 +640,24 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
645
640
|
issues: [],
|
|
646
641
|
fixCommand,
|
|
647
642
|
expectedCommand,
|
|
643
|
+
detectedCommands,
|
|
644
|
+
duplicateHookCount,
|
|
648
645
|
checkedPaths: [],
|
|
649
646
|
missingPaths: [],
|
|
647
|
+
nonExecutablePaths: [],
|
|
648
|
+
runtimeMismatches: [],
|
|
649
|
+
packageVersionMismatches: [],
|
|
650
650
|
featureFlag,
|
|
651
651
|
runtimeConfig,
|
|
652
652
|
};
|
|
653
653
|
}
|
|
654
|
-
const checkedPaths = extractHookCommandPaths(detectedCommand);
|
|
655
|
-
const missingPaths = [];
|
|
656
|
-
for (const path of checkedPaths) {
|
|
657
|
-
if (!(await isExecutableFile(path)) && !(path.endsWith(".js") && await pathExists(path))) {
|
|
658
|
-
missingPaths.push(path);
|
|
659
|
-
}
|
|
660
|
-
}
|
|
661
654
|
const issues = [];
|
|
662
|
-
|
|
663
|
-
|
|
655
|
+
const commandMismatch = detectedCommands.some((entry) => entry.command !== expectedCommand);
|
|
656
|
+
if (duplicateHookCount > 0) {
|
|
657
|
+
issues.push(`configured Codex hooks contain ${detectedCommands.length} tokenjuice commands; expected exactly one managed hook`);
|
|
658
|
+
}
|
|
659
|
+
if (commandMismatch) {
|
|
660
|
+
if (detectedCommands.some((entry) => entry.command.includes("/Cellar/"))) {
|
|
664
661
|
issues.push("configured Codex hook is pinned to a versioned Homebrew Cellar path");
|
|
665
662
|
}
|
|
666
663
|
else {
|
|
@@ -670,14 +667,21 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
670
667
|
if (missingPaths.length > 0) {
|
|
671
668
|
issues.push(`configured Codex hook points at missing path${missingPaths.length === 1 ? "" : "s"}`);
|
|
672
669
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
670
|
+
if (nonExecutablePaths.length > 0) {
|
|
671
|
+
issues.push(`configured Codex hook points at non-executable path${nonExecutablePaths.length === 1 ? "" : "s"}`);
|
|
672
|
+
}
|
|
673
|
+
for (const mismatch of runtimeMismatches) {
|
|
674
|
+
issues.push(`configured Codex hook ${mismatch.location} uses Node runtime ${mismatch.configuredPath}, but this tokenjuice uses ${mismatch.expectedPath}`);
|
|
675
|
+
}
|
|
676
|
+
for (const mismatch of packageVersionMismatches) {
|
|
677
|
+
issues.push(`configured Codex hook launcher resolves to Homebrew tokenjuice ${mismatch.resolvedVersion}, but this tokenjuice is ${mismatch.expectedVersion}`);
|
|
678
|
+
fixCommand = commandMismatch
|
|
679
|
+
? `brew upgrade tokenjuice && ${installFixCommand}`
|
|
680
|
+
: "brew upgrade tokenjuice";
|
|
677
681
|
}
|
|
678
682
|
if (options.local && await detectStaleLocalBuild(checkedPaths)) {
|
|
679
683
|
issues.push("local Codex hook target is older than the source tree");
|
|
680
|
-
fixCommand =
|
|
684
|
+
fixCommand = `pnpm build && ${getCodexFixCommand(true, noOmit)}`;
|
|
681
685
|
}
|
|
682
686
|
if (!featureFlag.enabled) {
|
|
683
687
|
issues.push("Codex feature flag `hooks` is disabled — the configured hook will not fire");
|
|
@@ -686,13 +690,22 @@ export async function doctorCodexHook(hooksPath = getDefaultHooksPath(), options
|
|
|
686
690
|
issues.push(...collectLowTimeoutWarnings(config));
|
|
687
691
|
return {
|
|
688
692
|
hooksPath,
|
|
689
|
-
status: missingPaths.length > 0
|
|
693
|
+
status: missingPaths.length > 0 || nonExecutablePaths.length > 0
|
|
694
|
+
? "broken"
|
|
695
|
+
: issues.length > 0
|
|
696
|
+
? "warn"
|
|
697
|
+
: "ok",
|
|
690
698
|
issues,
|
|
691
699
|
fixCommand,
|
|
692
700
|
expectedCommand,
|
|
693
701
|
detectedCommand,
|
|
702
|
+
detectedCommands,
|
|
703
|
+
duplicateHookCount,
|
|
694
704
|
checkedPaths,
|
|
695
705
|
missingPaths,
|
|
706
|
+
nonExecutablePaths,
|
|
707
|
+
runtimeMismatches,
|
|
708
|
+
packageVersionMismatches,
|
|
696
709
|
featureFlag,
|
|
697
710
|
runtimeConfig,
|
|
698
711
|
};
|
|
@@ -710,18 +723,23 @@ function shouldStoreFromEnv() {
|
|
|
710
723
|
return value === "1" || value === "true" || value === "TRUE" || value === "yes" || value === "YES";
|
|
711
724
|
}
|
|
712
725
|
async function writeHookDebug(record) {
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
726
|
+
try {
|
|
727
|
+
const codexHome = getCodexHome();
|
|
728
|
+
const debugPath = join(codexHome, CODEX_HOOK_LAST_LOG);
|
|
729
|
+
const historyPath = join(codexHome, CODEX_HOOK_HISTORY_LOG);
|
|
730
|
+
const enrichedRecord = {
|
|
731
|
+
timestamp: new Date().toISOString(),
|
|
732
|
+
tokenjuiceVersion: packageJson.version,
|
|
733
|
+
hookCommandPath: process.argv[1],
|
|
734
|
+
...record,
|
|
735
|
+
};
|
|
736
|
+
await mkdir(dirname(debugPath), { recursive: true });
|
|
737
|
+
await writeFile(debugPath, `${JSON.stringify(enrichedRecord, null, 2)}\n`, "utf8");
|
|
738
|
+
await writeHookHistoryEntry(historyPath, JSON.stringify(enrichedRecord));
|
|
739
|
+
}
|
|
740
|
+
catch {
|
|
741
|
+
// A diagnostic side effect must never turn an otherwise optional hook into a failed tool call.
|
|
742
|
+
}
|
|
725
743
|
}
|
|
726
744
|
function sanitizeHookHistoryLines(text) {
|
|
727
745
|
return text
|
|
@@ -821,7 +839,7 @@ async function recordImmediateHookStats(input, rawText, storeRaw) {
|
|
|
821
839
|
}
|
|
822
840
|
const stats = buildImmediateSkipStats(rawText);
|
|
823
841
|
const classification = await classifyOnly(input);
|
|
824
|
-
await
|
|
842
|
+
await tryStoreArtifactMetadata({
|
|
825
843
|
input,
|
|
826
844
|
rawText,
|
|
827
845
|
classification,
|
|
@@ -832,7 +850,8 @@ async function recordImmediateHookStats(input, rawText, storeRaw) {
|
|
|
832
850
|
},
|
|
833
851
|
});
|
|
834
852
|
}
|
|
835
|
-
export async function runCodexPostToolUseHook(rawText) {
|
|
853
|
+
export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
854
|
+
validateCodexOmissionPolicy(options);
|
|
836
855
|
let payload;
|
|
837
856
|
try {
|
|
838
857
|
payload = JSON.parse(rawText);
|
|
@@ -841,10 +860,12 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
841
860
|
return 0;
|
|
842
861
|
}
|
|
843
862
|
const command = payload.tool_input?.command;
|
|
863
|
+
const noOmit = !options.allowOmit && (options.noOmit || readNoOmissionFromEnv());
|
|
844
864
|
const debug = {
|
|
845
865
|
hookEvent: payload.hook_event_name,
|
|
846
866
|
toolName: payload.tool_name,
|
|
847
867
|
command,
|
|
868
|
+
noOmit,
|
|
848
869
|
rewrote: false,
|
|
849
870
|
};
|
|
850
871
|
if (payload.hook_event_name !== "PostToolUse") {
|
|
@@ -864,6 +885,21 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
864
885
|
await writeHookDebug({ ...debug, skipped: "empty-tool-response" });
|
|
865
886
|
return 0;
|
|
866
887
|
}
|
|
888
|
+
const rawBytes = Buffer.byteLength(combinedText, "utf8");
|
|
889
|
+
if (rawBytes > CODEX_HOOK_MAX_COMPACTION_BYTES) {
|
|
890
|
+
const plainText = stripAnsi(combinedText);
|
|
891
|
+
const rawChars = countTextChars(plainText);
|
|
892
|
+
await writeHookDebug({
|
|
893
|
+
...debug,
|
|
894
|
+
rawChars,
|
|
895
|
+
rawBytes,
|
|
896
|
+
reducedChars: rawChars,
|
|
897
|
+
savedChars: 0,
|
|
898
|
+
ratio: 1,
|
|
899
|
+
skipped: "response-too-large",
|
|
900
|
+
});
|
|
901
|
+
return 0;
|
|
902
|
+
}
|
|
867
903
|
const exitCode = extractCodexExitCode(payload);
|
|
868
904
|
const executionInput = {
|
|
869
905
|
toolName: "exec",
|
|
@@ -905,7 +941,9 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
905
941
|
visibleText: combinedText,
|
|
906
942
|
...(typeof payload.cwd === "string" && payload.cwd.trim() ? { cwd: payload.cwd } : {}),
|
|
907
943
|
...(typeof exitCode === "number" ? { exitCode } : {}),
|
|
944
|
+
...(options.allowOmit ? { allowOmit: true } : {}),
|
|
908
945
|
...(typeof maxInlineChars === "number" ? { maxInlineChars } : {}),
|
|
946
|
+
...(noOmit ? { noOmit: true } : {}),
|
|
909
947
|
storeRaw,
|
|
910
948
|
metadata: {
|
|
911
949
|
source: "codex-post-tool-use",
|
|
@@ -925,13 +963,23 @@ export async function runCodexPostToolUseHook(rawText) {
|
|
|
925
963
|
debug.savedChars = savedChars;
|
|
926
964
|
debug.ratio = result.stats.ratio;
|
|
927
965
|
debug.matchedReducer = result.classification.matchedReducer;
|
|
966
|
+
debug.compaction = result.compaction;
|
|
928
967
|
}
|
|
929
968
|
if (outcome.action === "keep") {
|
|
930
969
|
await writeHookDebug({ ...debug, skipped: outcome.reason });
|
|
931
970
|
return 0;
|
|
932
971
|
}
|
|
933
|
-
|
|
934
|
-
|
|
972
|
+
const replacement = buildCodexReplacementOutput(outcome.result.inlineText, outcome.result.rawRef?.id, outcome.result.compaction, exitCode, maxInlineChars, noOmit);
|
|
973
|
+
if (!replacement) {
|
|
974
|
+
await writeHookDebug({ ...debug, skipped: "observation-inline-limit" });
|
|
975
|
+
return 0;
|
|
976
|
+
}
|
|
977
|
+
process.stdout.write(`${JSON.stringify(replacement.payload)}\n`);
|
|
978
|
+
await writeHookDebug({
|
|
979
|
+
...debug,
|
|
980
|
+
rewrote: true,
|
|
981
|
+
feedbackTruncated: replacement.truncated,
|
|
982
|
+
});
|
|
935
983
|
return 0;
|
|
936
984
|
}
|
|
937
985
|
catch (error) {
|