@openclaw/tokenjuice 2026.11.10 → 2026.12.1-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.
- package/node_modules/tokenjuice/README.md +133 -6
- package/node_modules/tokenjuice/dist/cli/main.d.ts +1 -2
- package/node_modules/tokenjuice/dist/cli/main.js +3 -18
- package/node_modules/tokenjuice/dist/core/analysis.js +7 -10
- package/node_modules/tokenjuice/dist/core/artifacts.d.ts +1 -1
- package/node_modules/tokenjuice/dist/core/artifacts.js +4 -3
- package/node_modules/tokenjuice/dist/core/command-identity.js +7 -6
- package/node_modules/tokenjuice/dist/core/compaction-metadata.d.ts +3 -2
- package/node_modules/tokenjuice/dist/core/compaction-metadata.js +2 -1
- package/node_modules/tokenjuice/dist/core/failure-summary.d.ts +7 -0
- package/node_modules/tokenjuice/dist/core/failure-summary.js +76 -0
- package/node_modules/tokenjuice/dist/core/inventory-safety.js +14 -6
- package/node_modules/tokenjuice/dist/core/reduce-utils.js +9 -7
- package/node_modules/tokenjuice/dist/core/reduce.js +32 -21
- package/node_modules/tokenjuice/dist/core/streamed-text-counter.d.ts +8 -0
- package/node_modules/tokenjuice/dist/core/streamed-text-counter.js +56 -0
- package/node_modules/tokenjuice/dist/core/text.d.ts +1 -0
- package/node_modules/tokenjuice/dist/core/text.js +22 -11
- package/node_modules/tokenjuice/dist/core/wrap-format.d.ts +3 -0
- package/node_modules/tokenjuice/dist/core/wrap-format.js +34 -0
- package/node_modules/tokenjuice/dist/core/wrap.js +55 -6
- package/node_modules/tokenjuice/dist/hosts/codex/index.js +37 -10
- package/node_modules/tokenjuice/dist/hosts/deepseek-harness/bundle/index.js +221 -79
- package/node_modules/tokenjuice/dist/hosts/deepseek-harness/bundle/package.json +1 -1
- package/node_modules/tokenjuice/dist/hosts/hermes/bundle/plugin.yaml +1 -1
- package/node_modules/tokenjuice/dist/hosts/hermes/bundle/tokenjuice_integrations/README.md +4 -2
- package/node_modules/tokenjuice/dist/hosts/hermes/bundle/tokenjuice_integrations/bridge.py +62 -5
- package/node_modules/tokenjuice/dist/hosts/openclaw/extension.js +7 -2
- package/node_modules/tokenjuice/dist/hosts/opencode/extension/runtime.js +221 -79
- package/node_modules/tokenjuice/dist/hosts/opencode/v2/bundle/index.js +221 -79
- package/node_modules/tokenjuice/dist/hosts/pi/extension/runtime.js +221 -79
- package/node_modules/tokenjuice/dist/python/README.md +1 -1
- package/node_modules/tokenjuice/dist/python/pyproject.toml +1 -1
- package/node_modules/tokenjuice/dist/python/tokenjuice_integrations/README.md +4 -2
- package/node_modules/tokenjuice/dist/python/tokenjuice_integrations/bridge.py +62 -5
- package/node_modules/tokenjuice/dist/rules/build/tsc.json +8 -3
- package/node_modules/tokenjuice/dist/rules/fixtures/build/tsc.fixture.json +6 -2
- package/node_modules/tokenjuice/dist/rules/install/bun-install.json +12 -4
- package/node_modules/tokenjuice/dist/rules/install/npm-ci.json +12 -4
- package/node_modules/tokenjuice/dist/rules/install/npm-install.json +12 -4
- package/node_modules/tokenjuice/dist/rules/install/pnpm-install.json +12 -4
- package/node_modules/tokenjuice/dist/rules/install/yarn-install.json +12 -4
- package/node_modules/tokenjuice/dist/rules/tests/pytest.json +8 -3
- package/node_modules/tokenjuice/dist/types.d.ts +3 -0
- package/node_modules/tokenjuice/package.json +5 -15
- package/package.json +5 -5
|
@@ -5,7 +5,8 @@ import { isFileContentInspectionCommand, isVerbatimConfigInspectionCommand } fro
|
|
|
5
5
|
import { normalizeExecutionInput } from "./execution-input.js";
|
|
6
6
|
import { clampTextMiddleWithMetadata, clampTextWithMetadata, collapseRepeatedEmojiBanner, countTextChars, dedupeAdjacent, headTail, normalizeLines, pluralize, stripAnsi, trimEmptyEdges } from "./text.js";
|
|
7
7
|
import { storeArtifact, tryStoreArtifactMetadata } from "./artifacts.js";
|
|
8
|
-
import { NO_COMPACTION_METADATA, mergeCompactionMetadata } from "./compaction-metadata.js";
|
|
8
|
+
import { NO_COMPACTION_METADATA, createCompactionMetadata, mergeCompactionMetadata } from "./compaction-metadata.js";
|
|
9
|
+
import { buildFailureSummary } from "./failure-summary.js";
|
|
9
10
|
import { buildGithubActionsFailureSummary } from "./github-actions-summary.js";
|
|
10
11
|
import { rewriteGhLines, rewriteGitDiffLines, rewriteGitStatusLines, rewriteSearchLines } from "./reduce-formatters.js";
|
|
11
12
|
import { buildInspectionSummary } from "./reduce-inspection-summary.js";
|
|
@@ -44,7 +45,7 @@ function prettyPrintJsonIfPossible(text) {
|
|
|
44
45
|
}
|
|
45
46
|
return text;
|
|
46
47
|
}
|
|
47
|
-
function applyRule(compiledRule, input, rawText, noOmit = false) {
|
|
48
|
+
function applyRule(compiledRule, input, rawText, noOmit = false, maxInlineChars = 1200) {
|
|
48
49
|
const rule = compiledRule.rule;
|
|
49
50
|
if (rule.transforms?.prettyPrintJson) {
|
|
50
51
|
rawText = prettyPrintJsonIfPossible(rawText);
|
|
@@ -62,13 +63,16 @@ function applyRule(compiledRule, input, rawText, noOmit = false) {
|
|
|
62
63
|
}
|
|
63
64
|
const outputMatchText = trimEmptyEdges(lines).join("\n");
|
|
64
65
|
const matchedOutput = compiledRule.compiled.outputMatches.find((entry) => entry.pattern.test(outputMatchText));
|
|
65
|
-
if (!noOmit && matchedOutput) {
|
|
66
|
+
if (!noOmit && input.exitCode === 0 && matchedOutput) {
|
|
66
67
|
return {
|
|
67
68
|
summary: matchedOutput.message,
|
|
68
69
|
facts,
|
|
69
|
-
compaction:
|
|
70
|
+
compaction: matchedOutput.message === outputMatchText
|
|
71
|
+
? NO_COMPACTION_METADATA
|
|
72
|
+
: createCompactionMetadata("rule-output-replacement"),
|
|
70
73
|
};
|
|
71
74
|
}
|
|
75
|
+
const unfilteredLineCount = lines.length;
|
|
72
76
|
if (!noOmit && rule.filters?.skipPatterns?.length) {
|
|
73
77
|
lines = lines.filter((line) => !compiledRule.compiled.skipPatterns.some((pattern) => pattern.test(line)));
|
|
74
78
|
}
|
|
@@ -79,6 +83,9 @@ function applyRule(compiledRule, input, rawText, noOmit = false) {
|
|
|
79
83
|
lines = kept;
|
|
80
84
|
}
|
|
81
85
|
}
|
|
86
|
+
if (lines.length < unfilteredLineCount) {
|
|
87
|
+
rewriteCompaction = mergeCompactionMetadata(rewriteCompaction, createCompactionMetadata("rule-line-filter"));
|
|
88
|
+
}
|
|
82
89
|
if (rule.transforms?.trimEmptyEdges) {
|
|
83
90
|
counterLines = trimEmptyEdges(counterLines);
|
|
84
91
|
lines = trimEmptyEdges(lines);
|
|
@@ -98,11 +105,6 @@ function applyRule(compiledRule, input, rawText, noOmit = false) {
|
|
|
98
105
|
lines = rewritten.lines;
|
|
99
106
|
rewriteCompaction = mergeCompactionMetadata(rewriteCompaction, rewritten.compaction);
|
|
100
107
|
}
|
|
101
|
-
if (rule.id === "search/rg") {
|
|
102
|
-
const rewritten = rewriteSearchLines(lines, noOmit);
|
|
103
|
-
lines = rewritten.lines;
|
|
104
|
-
rewriteCompaction = mergeCompactionMetadata(rewriteCompaction, rewritten.compaction);
|
|
105
|
-
}
|
|
106
108
|
if (rule.id === "git/diff") {
|
|
107
109
|
const rewritten = rewriteGitDiffLines(lines, noOmit);
|
|
108
110
|
lines = rewritten.lines;
|
|
@@ -116,6 +118,12 @@ function applyRule(compiledRule, input, rawText, noOmit = false) {
|
|
|
116
118
|
}
|
|
117
119
|
facts[counter.name] = factLines.filter((line) => pattern.test(line)).length;
|
|
118
120
|
}
|
|
121
|
+
const searchFits = rule.family === "search" && countTextChars(formatInline({ family: rule.family, matchedReducer: rule.id }, input, lines.join("\n"), facts, noOmit)) <= maxInlineChars;
|
|
122
|
+
if (rule.id === "search/rg" && !searchFits) {
|
|
123
|
+
const rewritten = rewriteSearchLines(lines, noOmit);
|
|
124
|
+
lines = rewritten.lines;
|
|
125
|
+
rewriteCompaction = mergeCompactionMetadata(rewriteCompaction, rewritten.compaction);
|
|
126
|
+
}
|
|
119
127
|
if (lines.length === 0 && rule.onEmpty) {
|
|
120
128
|
return {
|
|
121
129
|
summary: rule.onEmpty,
|
|
@@ -132,7 +140,9 @@ function applyRule(compiledRule, input, rawText, noOmit = false) {
|
|
|
132
140
|
head: rule.summarize?.head ?? 6,
|
|
133
141
|
tail: rule.summarize?.tail ?? 6,
|
|
134
142
|
};
|
|
135
|
-
const compacted =
|
|
143
|
+
const compacted = searchFits
|
|
144
|
+
? { lines, compaction: NO_COMPACTION_METADATA }
|
|
145
|
+
: headTail(lines, summarize.head, summarize.tail, noOmit);
|
|
136
146
|
return {
|
|
137
147
|
summary: compacted.lines.join("\n").trim(),
|
|
138
148
|
facts,
|
|
@@ -205,9 +215,8 @@ function formatInline(classification, input, summary, facts, noOmit = false) {
|
|
|
205
215
|
lines.push(summary);
|
|
206
216
|
return lines.join("\n").trim();
|
|
207
217
|
}
|
|
208
|
-
function selectInlineText(classification, input, rawText, compactText, maxInlineChars, compactCompaction, noOmit = false) {
|
|
218
|
+
function selectInlineText(classification, input, rawText, rawChars, compactText, maxInlineChars, compactCompaction, noOmit = false) {
|
|
209
219
|
const passthroughText = buildPassthroughText(input, rawText);
|
|
210
|
-
const rawChars = countTextChars(stripAnsi(rawText));
|
|
211
220
|
const compactChars = countTextChars(compactText);
|
|
212
221
|
if (noOmit) {
|
|
213
222
|
return {
|
|
@@ -234,13 +243,14 @@ function selectInlineText(classification, input, rawText, compactText, maxInline
|
|
|
234
243
|
};
|
|
235
244
|
}
|
|
236
245
|
const passthroughLimit = classification.family === "help" ? maxInlineChars : TINY_OUTPUT_MAX_CHARS;
|
|
237
|
-
|
|
246
|
+
const passthroughChars = countTextChars(passthroughText);
|
|
247
|
+
if (passthroughChars > passthroughLimit) {
|
|
238
248
|
return {
|
|
239
249
|
text: compactText,
|
|
240
250
|
compaction: compactCompaction,
|
|
241
251
|
};
|
|
242
252
|
}
|
|
243
|
-
if (
|
|
253
|
+
if (passthroughChars <= compactChars) {
|
|
244
254
|
return {
|
|
245
255
|
text: passthroughText,
|
|
246
256
|
compaction: NO_COMPACTION_METADATA,
|
|
@@ -409,11 +419,12 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
|
|
|
409
419
|
if (!matchedRule) {
|
|
410
420
|
throw new Error("missing generic fallback rule");
|
|
411
421
|
}
|
|
412
|
-
const
|
|
422
|
+
const failureSummary = classification.matchedReducer === "generic/fallback"
|
|
413
423
|
? buildGithubActionsFailureSummary(reducerInput, rawText, opts.noOmit)
|
|
424
|
+
?? buildFailureSummary(reducerInput, rawText, maxInlineChars, opts.noOmit)
|
|
414
425
|
: null;
|
|
415
|
-
if (
|
|
416
|
-
const inlineText = clampTextMiddleWithMetadata(
|
|
426
|
+
if (failureSummary) {
|
|
427
|
+
const inlineText = clampTextMiddleWithMetadata(failureSummary.text, maxInlineChars, opts.noOmit);
|
|
417
428
|
const reducedChars = countTextChars(inlineText.text);
|
|
418
429
|
const stats = {
|
|
419
430
|
rawChars: measuredRawChars,
|
|
@@ -439,8 +450,8 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
|
|
|
439
450
|
}
|
|
440
451
|
return {
|
|
441
452
|
inlineText: inlineText.text,
|
|
442
|
-
previewText:
|
|
443
|
-
compaction: mergeCompactionMetadata(
|
|
453
|
+
previewText: failureSummary.text,
|
|
454
|
+
compaction: mergeCompactionMetadata(failureSummary.compaction, inlineText.compaction),
|
|
444
455
|
...(trace ? { trace } : {}),
|
|
445
456
|
...(rawRef ? { rawRef } : {}),
|
|
446
457
|
stats,
|
|
@@ -489,9 +500,9 @@ export async function reduceExecutionWithRules(input, rules, opts = {}) {
|
|
|
489
500
|
};
|
|
490
501
|
}
|
|
491
502
|
}
|
|
492
|
-
const { summary, facts, compaction } = applyRule(matchedRule, reducerInput, rawText, opts.noOmit);
|
|
503
|
+
const { summary, facts, compaction } = applyRule(matchedRule, reducerInput, rawText, opts.noOmit, maxInlineChars);
|
|
493
504
|
const compactText = formatInline(classification, reducerInput, summary || "(no output)", facts, opts.noOmit);
|
|
494
|
-
const selectedText = selectInlineText(classification, reducerInput, rawText, compactText, maxInlineChars, compaction, opts.noOmit);
|
|
505
|
+
const selectedText = selectInlineText(classification, reducerInput, rawText, measuredRawChars, compactText, maxInlineChars, compaction, opts.noOmit);
|
|
495
506
|
const clamp = classification.family === "help" || selectedText.text.includes("\n") ? clampTextMiddleWithMetadata : clampTextWithMetadata;
|
|
496
507
|
const inlineText = clamp(selectedText.text, maxInlineChars, opts.noOmit);
|
|
497
508
|
const reducedChars = countTextChars(inlineText.text);
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
2
|
+
/** Count visible text without retaining the streamed output or splitting ANSI sequences. */
|
|
3
|
+
export class StreamedTextCounter {
|
|
4
|
+
state = "text";
|
|
5
|
+
completed = 0;
|
|
6
|
+
tail = "";
|
|
7
|
+
write(text) {
|
|
8
|
+
let visible = "";
|
|
9
|
+
for (const char of text) {
|
|
10
|
+
if (this.state === "csi") {
|
|
11
|
+
if (char >= "@" && char <= "~")
|
|
12
|
+
this.state = "text";
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
if (this.state === "osc" || this.state === "osc-escape") {
|
|
16
|
+
if (char === "\u0007" || (this.state === "osc-escape" && char === "\\")) {
|
|
17
|
+
this.state = "text";
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
this.state = char === "\u001b" ? "osc-escape" : "osc";
|
|
21
|
+
}
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (this.state === "escape") {
|
|
25
|
+
if (char === "[") {
|
|
26
|
+
this.state = "csi";
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (char === "]") {
|
|
30
|
+
this.state = "osc";
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
this.state = "text";
|
|
34
|
+
if (char >= "@" && char <= "_")
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (char === "\u001b")
|
|
38
|
+
this.state = "escape";
|
|
39
|
+
else
|
|
40
|
+
visible += char;
|
|
41
|
+
}
|
|
42
|
+
if (!visible)
|
|
43
|
+
return;
|
|
44
|
+
let previous = "";
|
|
45
|
+
for (const { segment } of segmenter.segment(this.tail + visible)) {
|
|
46
|
+
if (previous)
|
|
47
|
+
this.completed += 1;
|
|
48
|
+
previous = segment;
|
|
49
|
+
}
|
|
50
|
+
// A following chunk can extend the last grapheme (combining marks or ZWJ).
|
|
51
|
+
this.tail = previous;
|
|
52
|
+
}
|
|
53
|
+
get count() {
|
|
54
|
+
return this.completed + (this.tail ? 1 : 0);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type CompactionMetadata } from "./compaction-metadata.js";
|
|
2
|
+
export declare function segmentTextChars(text: string): string[];
|
|
2
3
|
export declare function stripAnsi(text: string): string;
|
|
3
4
|
export declare function countTextChars(text: string): number;
|
|
4
5
|
export declare function sliceTextChars(text: string, start: number, end?: number): string;
|
|
@@ -14,7 +14,7 @@ const REPEATED_EMOJI_BANNER_MIN_REPETITIONS = 24;
|
|
|
14
14
|
const graphemeSegmenter = typeof Intl !== "undefined" && "Segmenter" in Intl
|
|
15
15
|
? new Intl.Segmenter(undefined, { granularity: "grapheme" })
|
|
16
16
|
: null;
|
|
17
|
-
function
|
|
17
|
+
export function segmentTextChars(text) {
|
|
18
18
|
if (!graphemeSegmenter) {
|
|
19
19
|
return Array.from(text);
|
|
20
20
|
}
|
|
@@ -44,10 +44,16 @@ export function stripAnsi(text) {
|
|
|
44
44
|
.replaceAll("\u001b", "");
|
|
45
45
|
}
|
|
46
46
|
export function countTextChars(text) {
|
|
47
|
-
|
|
47
|
+
const iterator = graphemeSegmenter
|
|
48
|
+
? graphemeSegmenter.segment(text)[Symbol.iterator]()
|
|
49
|
+
: text[Symbol.iterator]();
|
|
50
|
+
let count = 0;
|
|
51
|
+
while (!iterator.next().done)
|
|
52
|
+
count += 1;
|
|
53
|
+
return count;
|
|
48
54
|
}
|
|
49
55
|
export function sliceTextChars(text, start, end) {
|
|
50
|
-
return
|
|
56
|
+
return segmentTextChars(text).slice(start, end).join("");
|
|
51
57
|
}
|
|
52
58
|
function codePointWidth(codePoint) {
|
|
53
59
|
if (codePoint === 0
|
|
@@ -90,7 +96,7 @@ function graphemeWidth(segment) {
|
|
|
90
96
|
return hasVisibleCodePoint ? width : 0;
|
|
91
97
|
}
|
|
92
98
|
export function countTerminalCells(text) {
|
|
93
|
-
return
|
|
99
|
+
return segmentTextChars(text).reduce((sum, segment) => sum + graphemeWidth(segment), 0);
|
|
94
100
|
}
|
|
95
101
|
export function normalizeLines(text) {
|
|
96
102
|
return text
|
|
@@ -129,7 +135,7 @@ function isEmojiGrapheme(text) {
|
|
|
129
135
|
export function collapseRepeatedEmojiBanner(lines) {
|
|
130
136
|
let collapsed = false;
|
|
131
137
|
const nextLines = lines.map((line) => {
|
|
132
|
-
const visibleSegments =
|
|
138
|
+
const visibleSegments = segmentTextChars(line).filter((segment) => !/^\s+$/u.test(segment));
|
|
133
139
|
const repeatedEmoji = visibleSegments[0];
|
|
134
140
|
if (visibleSegments.length < REPEATED_EMOJI_BANNER_MIN_REPETITIONS
|
|
135
141
|
|| !repeatedEmoji
|
|
@@ -172,15 +178,20 @@ export function headTail(lines, head, tail, noOmit = false) {
|
|
|
172
178
|
};
|
|
173
179
|
}
|
|
174
180
|
export function clampText(text, maxChars) {
|
|
175
|
-
|
|
181
|
+
const segments = segmentTextChars(text);
|
|
182
|
+
if (segments.length <= maxChars) {
|
|
176
183
|
return text;
|
|
177
184
|
}
|
|
185
|
+
return clampSegments(segments, maxChars);
|
|
186
|
+
}
|
|
187
|
+
function clampSegments(segments, maxChars) {
|
|
178
188
|
const bodyChars = Math.max(0, maxChars - countTextChars(TRUNCATION_SUFFIX));
|
|
179
|
-
const head = trimHeadToLineBoundary(
|
|
189
|
+
const head = trimHeadToLineBoundary(segments.slice(0, bodyChars).join(""));
|
|
180
190
|
return `${head}${TRUNCATION_SUFFIX}`;
|
|
181
191
|
}
|
|
182
192
|
export function clampTextWithMetadata(text, maxChars, noOmit = false) {
|
|
183
|
-
|
|
193
|
+
const segments = segmentTextChars(text);
|
|
194
|
+
if (segments.length <= maxChars) {
|
|
184
195
|
return { text };
|
|
185
196
|
}
|
|
186
197
|
if (noOmit) {
|
|
@@ -190,12 +201,13 @@ export function clampTextWithMetadata(text, maxChars, noOmit = false) {
|
|
|
190
201
|
};
|
|
191
202
|
}
|
|
192
203
|
return {
|
|
193
|
-
text:
|
|
204
|
+
text: clampSegments(segments, maxChars),
|
|
194
205
|
compaction: createCompactionMetadata("tail-truncation"),
|
|
195
206
|
};
|
|
196
207
|
}
|
|
197
208
|
export function clampTextMiddleWithMetadata(text, maxChars, noOmit = false) {
|
|
198
|
-
|
|
209
|
+
const segments = segmentTextChars(text);
|
|
210
|
+
if (segments.length <= maxChars) {
|
|
199
211
|
return { text };
|
|
200
212
|
}
|
|
201
213
|
if (noOmit) {
|
|
@@ -208,7 +220,6 @@ export function clampTextMiddleWithMetadata(text, maxChars, noOmit = false) {
|
|
|
208
220
|
const bodyChars = Math.max(0, maxChars - markerChars);
|
|
209
221
|
const headChars = Math.ceil(bodyChars * 0.7);
|
|
210
222
|
const tailChars = Math.max(0, bodyChars - headChars);
|
|
211
|
-
const segments = graphemes(text);
|
|
212
223
|
const head = trimHeadToLineBoundary(segments.slice(0, headChars).join(""));
|
|
213
224
|
const tail = trimTailToLineBoundary(segments.slice(-tailChars).join(""));
|
|
214
225
|
return {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { dirname, resolve } from "node:path";
|
|
2
|
+
import { resolveArtifactBaseDir } from "./artifacts.js";
|
|
3
|
+
import { WRAP_AUTHORITATIVE_FOOTER, WRAP_RECOVERY_HINT } from "./compaction-metadata.js";
|
|
4
|
+
export function quoteRecoveryDirectory(directory, platform = process.platform) {
|
|
5
|
+
return platform === "win32"
|
|
6
|
+
? `'${directory.replaceAll("'", "''")}'`
|
|
7
|
+
: `'${directory.replaceAll("'", "'\\''")}'`;
|
|
8
|
+
}
|
|
9
|
+
function recoveryCommand(result) {
|
|
10
|
+
if (!result.rawRef)
|
|
11
|
+
return undefined;
|
|
12
|
+
const directory = resolve(dirname(result.rawRef.path));
|
|
13
|
+
const defaultDirectory = resolve(resolveArtifactBaseDir());
|
|
14
|
+
const quotedDirectory = quoteRecoveryDirectory(directory);
|
|
15
|
+
return `tokenjuice cat ${result.rawRef.id}${directory === defaultDirectory ? "" : ` --store-dir ${quotedDirectory}`}`;
|
|
16
|
+
}
|
|
17
|
+
export function decorateWrapInlineText(result, raw) {
|
|
18
|
+
const { rawChars, reducedChars } = result.stats;
|
|
19
|
+
if (raw || !result.compaction?.authoritative || reducedChars === 0 || reducedChars >= rawChars) {
|
|
20
|
+
return result.inlineText;
|
|
21
|
+
}
|
|
22
|
+
const recovery = recoveryCommand(result);
|
|
23
|
+
const footer = [
|
|
24
|
+
"",
|
|
25
|
+
"---",
|
|
26
|
+
result.captureTruncated
|
|
27
|
+
? "[tokenjuice] Capture limit reached. This summary and any stored output are incomplete."
|
|
28
|
+
: recovery
|
|
29
|
+
? `${WRAP_AUTHORITATIVE_FOOTER} ${WRAP_RECOVERY_HINT}`
|
|
30
|
+
: WRAP_AUTHORITATIVE_FOOTER,
|
|
31
|
+
...(recovery ? [`Captured output is available locally${process.platform === "win32" ? " (PowerShell)" : ""}: ${recovery}`] : []),
|
|
32
|
+
].join("\n");
|
|
33
|
+
return `${result.inlineText}${footer}`;
|
|
34
|
+
}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { reduceExecution } from "./reduce.js";
|
|
3
|
+
import { storeArtifact, tryStoreArtifactMetadata } from "./artifacts.js";
|
|
4
|
+
import { NO_COMPACTION_METADATA } from "./compaction-metadata.js";
|
|
5
|
+
import { countTextChars, stripAnsi } from "./text.js";
|
|
6
|
+
import { decorateWrapInlineText } from "./wrap-format.js";
|
|
7
|
+
import { StreamedTextCounter } from "./streamed-text-counter.js";
|
|
3
8
|
const DEFAULT_MAX_CAPTURE_BYTES = 4 * 1024 * 1024;
|
|
4
9
|
const CAPTURE_TRUNCATED_SUFFIX = "\n[tokenjuice: output truncated]\n";
|
|
5
10
|
function appendCapturedChunk(current, chunk, limitBytes) {
|
|
@@ -49,11 +54,14 @@ export async function runWrappedCommand(argv, opts = {}) {
|
|
|
49
54
|
let stdout = { text: "", bytes: 0, truncated: false };
|
|
50
55
|
let stderr = { text: "", bytes: 0, truncated: false };
|
|
51
56
|
let combined = { text: "", bytes: 0, truncated: false };
|
|
57
|
+
const streamedStdout = new StreamedTextCounter();
|
|
58
|
+
const streamedStderr = new StreamedTextCounter();
|
|
52
59
|
child.stdout.on("data", (chunk) => {
|
|
53
60
|
const text = chunk.toString("utf8");
|
|
54
61
|
stdout = appendCapturedChunk(stdout, chunk, maxCaptureBytes);
|
|
55
62
|
combined = appendCapturedChunk(combined, chunk, maxCaptureBytes);
|
|
56
63
|
if (opts.tee) {
|
|
64
|
+
streamedStdout.write(text);
|
|
57
65
|
process.stdout.write(text);
|
|
58
66
|
}
|
|
59
67
|
});
|
|
@@ -62,13 +70,14 @@ export async function runWrappedCommand(argv, opts = {}) {
|
|
|
62
70
|
stderr = appendCapturedChunk(stderr, chunk, maxCaptureBytes);
|
|
63
71
|
combined = appendCapturedChunk(combined, chunk, maxCaptureBytes);
|
|
64
72
|
if (opts.tee) {
|
|
73
|
+
streamedStderr.write(text);
|
|
65
74
|
process.stderr.write(text);
|
|
66
75
|
}
|
|
67
76
|
});
|
|
68
77
|
child.on("error", reject);
|
|
69
78
|
child.on("close", async (code) => {
|
|
70
79
|
try {
|
|
71
|
-
const
|
|
80
|
+
const input = {
|
|
72
81
|
toolName: "exec",
|
|
73
82
|
command: argv.join(" "),
|
|
74
83
|
argv,
|
|
@@ -80,15 +89,55 @@ export async function runWrappedCommand(argv, opts = {}) {
|
|
|
80
89
|
...(opts.source ? { source: opts.source } : {}),
|
|
81
90
|
tokenjuiceCaptureTruncated: combined.truncated,
|
|
82
91
|
},
|
|
83
|
-
}
|
|
84
|
-
|
|
92
|
+
};
|
|
93
|
+
const raw = opts.raw === true || (opts.keepFailures === true && code !== 0);
|
|
94
|
+
const reduced = await reduceExecution(input, {
|
|
95
|
+
raw,
|
|
85
96
|
noOmit: opts.noOmit ?? false,
|
|
86
97
|
trace: opts.trace ?? false,
|
|
87
|
-
|
|
88
|
-
store: opts.store ?? false,
|
|
89
|
-
...(opts.storeDir ? { storeDir: opts.storeDir } : {}),
|
|
98
|
+
recordStats: false,
|
|
90
99
|
...(typeof opts.maxInlineChars === "number" ? { maxInlineChars: opts.maxInlineChars } : {}),
|
|
91
100
|
});
|
|
101
|
+
const finalize = (ref) => {
|
|
102
|
+
const result = { ...reduced, ...(combined.truncated ? { captureTruncated: true } : {}), ...(ref ? { rawRef: ref } : {}) };
|
|
103
|
+
if (!opts.includeCompactionNotice)
|
|
104
|
+
return result;
|
|
105
|
+
const decorated = decorateWrapInlineText(result, raw);
|
|
106
|
+
const candidate = raw || (stderr.text.length === 0 && decorated === stdout.text)
|
|
107
|
+
? decorated
|
|
108
|
+
: `${decorated}\n`;
|
|
109
|
+
const keepRaw = result.compaction?.authoritative
|
|
110
|
+
&& countTextChars(stripAnsi(candidate)) >= result.stats.rawChars;
|
|
111
|
+
const inlineText = keepRaw ? combined.text : candidate;
|
|
112
|
+
const failurePassthrough = opts.keepFailures && code !== 0;
|
|
113
|
+
const inlineChars = failurePassthrough
|
|
114
|
+
? opts.tee ? 0 : countTextChars(stripAnsi(stdout.text)) + countTextChars(stripAnsi(stderr.text))
|
|
115
|
+
: countTextChars(stripAnsi(inlineText));
|
|
116
|
+
const reducedChars = inlineChars + streamedStdout.count + streamedStderr.count;
|
|
117
|
+
return {
|
|
118
|
+
...result,
|
|
119
|
+
inlineText,
|
|
120
|
+
...(keepRaw ? { compaction: NO_COMPACTION_METADATA } : {}),
|
|
121
|
+
stats: {
|
|
122
|
+
rawChars: result.stats.rawChars,
|
|
123
|
+
reducedChars,
|
|
124
|
+
ratio: result.stats.rawChars === 0 ? 1 : reducedChars / result.stats.rawChars,
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
let result = finalize();
|
|
129
|
+
if (opts.store) {
|
|
130
|
+
// Allocate the recovery ID before measuring the emitted payload, but
|
|
131
|
+
// persist only its final statistics in both the sidecar and ledger.
|
|
132
|
+
const ref = await storeArtifact({ input, rawText: combined.text, classification: reduced.classification, ...(opts.recordStats !== undefined ? { recordStats: opts.recordStats } : {}) }, opts.storeDir, (rawRef) => {
|
|
133
|
+
result = finalize(rawRef);
|
|
134
|
+
return result.stats;
|
|
135
|
+
});
|
|
136
|
+
result = { ...result, rawRef: ref };
|
|
137
|
+
}
|
|
138
|
+
else if (opts.recordStats) {
|
|
139
|
+
await tryStoreArtifactMetadata({ input, rawText: combined.text, classification: result.classification, stats: result.stats }, opts.storeDir);
|
|
140
|
+
}
|
|
92
141
|
resolve({
|
|
93
142
|
result,
|
|
94
143
|
exitCode: code ?? 1,
|
|
@@ -1126,8 +1126,8 @@ export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
|
1126
1126
|
...(options.allowOmit ? { allowOmit: true } : {}),
|
|
1127
1127
|
...(typeof maxInlineChars === "number" ? { maxInlineChars } : {}),
|
|
1128
1128
|
...(noOmit ? { noOmit: true } : {}),
|
|
1129
|
-
storeRaw,
|
|
1130
|
-
recordStats:
|
|
1129
|
+
storeRaw: false,
|
|
1130
|
+
recordStats: false,
|
|
1131
1131
|
metadata: {
|
|
1132
1132
|
source: "codex-post-tool-use",
|
|
1133
1133
|
},
|
|
@@ -1149,21 +1149,48 @@ export async function runCodexPostToolUseHook(rawText, options = {}) {
|
|
|
1149
1149
|
debug.compaction = result.compaction;
|
|
1150
1150
|
}
|
|
1151
1151
|
if (outcome.action === "keep") {
|
|
1152
|
-
await
|
|
1152
|
+
await recordImmediateHookStats(executionInput, combinedText, false);
|
|
1153
|
+
await writeDebug({ ...debug, ...buildImmediateSkipStats(combinedText), deliveryMode: "original-only", skipped: outcome.reason });
|
|
1153
1154
|
return 0;
|
|
1154
1155
|
}
|
|
1155
|
-
const
|
|
1156
|
-
|
|
1157
|
-
|
|
1156
|
+
const rawChars = countTextChars(stripAnsi(combinedText));
|
|
1157
|
+
const finalize = (rawRefId) => {
|
|
1158
|
+
const replacement = buildCodexReplacementOutput(outcome.result.inlineText, rawRefId, outcome.result.compaction, exitCode, maxInlineChars, noOmit);
|
|
1159
|
+
const feedbackChars = replacement
|
|
1160
|
+
? countTextChars(replacement.payload.stopReason)
|
|
1161
|
+
: rawChars;
|
|
1162
|
+
const worthwhile = replacement && feedbackChars < rawChars;
|
|
1163
|
+
const reducedChars = worthwhile ? feedbackChars : rawChars;
|
|
1164
|
+
return {
|
|
1165
|
+
replacement: worthwhile ? replacement : undefined,
|
|
1166
|
+
reason: replacement ? "observation-no-savings" : "observation-inline-limit",
|
|
1167
|
+
stats: { rawChars, reducedChars, ratio: rawChars === 0 ? 1 : reducedChars / rawChars },
|
|
1168
|
+
};
|
|
1169
|
+
};
|
|
1170
|
+
let finalized = finalize();
|
|
1171
|
+
const recordStats = shouldRecordStats();
|
|
1172
|
+
const artifact = { input: executionInput, rawText: combinedText, classification: outcome.result.classification };
|
|
1173
|
+
if (storeRaw && finalized.replacement) {
|
|
1174
|
+
await storeArtifact({ ...artifact, recordStats }, undefined, (ref) => {
|
|
1175
|
+
finalized = finalize(ref.id);
|
|
1176
|
+
return finalized.stats;
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
else if (recordStats) {
|
|
1180
|
+
await tryStoreArtifactMetadata({ ...artifact, stats: finalized.stats });
|
|
1181
|
+
}
|
|
1182
|
+
const finalDebug = { ...debug, ...finalized.stats, savedChars: rawChars - finalized.stats.reducedChars };
|
|
1183
|
+
if (!finalized.replacement) {
|
|
1184
|
+
await writeDebug({ ...finalDebug, deliveryMode: "original-only", skipped: finalized.reason });
|
|
1158
1185
|
return 0;
|
|
1159
1186
|
}
|
|
1160
|
-
process.stdout.write(`${JSON.stringify(replacement.payload)}\n`);
|
|
1187
|
+
process.stdout.write(`${JSON.stringify(finalized.replacement.payload)}\n`);
|
|
1161
1188
|
await writeDebug({
|
|
1162
|
-
...
|
|
1189
|
+
...finalDebug,
|
|
1163
1190
|
rewrote: true,
|
|
1164
1191
|
deliveryMode: "replacement-feedback",
|
|
1165
|
-
measurement: "
|
|
1166
|
-
feedbackTruncated: replacement.truncated,
|
|
1192
|
+
measurement: "model-visible-feedback-characters",
|
|
1193
|
+
feedbackTruncated: finalized.replacement.truncated,
|
|
1167
1194
|
});
|
|
1168
1195
|
return 0;
|
|
1169
1196
|
}
|