@bastani/atomic 0.9.73-alpha.1 → 0.9.74-alpha.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/CHANGELOG.md +36 -0
- package/dist/builtin/intercom/CHANGELOG.md +10 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +16 -0
- package/dist/builtin/workflows/README.md +2 -2
- package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
- package/dist/builtin/workflows/builtin/{chunk-2377r57g.js → chunk-8kdrnrpa.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-t8y25z1j.js → chunk-8ycbc76t.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-vbrmytm5.js → chunk-a4fdm2cw.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-9pjdp2td.js → chunk-d5cxskkp.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-tpsw128z.js → chunk-d9pz64yp.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-z0d03ktm.js → chunk-gp0s6m45.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-4kygv34g.js → chunk-m8eg152f.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-mswg7kc7.js → chunk-r39ypw6b.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-q7dry6km.js → chunk-va2h64a6.js} +3 -3
- package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
- package/dist/builtin/workflows/builtin/goal.js +4 -4
- package/dist/builtin/workflows/builtin/index.js +9 -9
- package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
- package/dist/builtin/workflows/builtin/ralph.js +4 -4
- package/dist/builtin/workflows/builtin/tournament.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/authoring.d.ts +2 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +403 -76
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +387 -60
- package/dist/builtin/workflows/src/index.js +393 -62
- package/dist/builtin/workflows/src/local-worker-entry.mjs +387 -60
- package/dist/builtin/workflows/src/shared/serializable-error-families.d.ts +1 -0
- package/dist/builtin/workflows/src/shared/structured-output-errors.d.ts +50 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-background-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-background-compaction.js +2 -1
- package/dist/core/agent-session-background-compaction.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +98 -4
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-detached-tools.d.ts +20 -5
- package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
- package/dist/core/agent-session-detached-tools.js +97 -21
- package/dist/core/agent-session-detached-tools.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +2 -1
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +3 -1
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.js +12 -4
- package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +33 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/compaction/background-compaction.d.ts +11 -5
- package/dist/core/compaction/background-compaction.d.ts.map +1 -1
- package/dist/core/compaction/background-compaction.js +19 -10
- package/dist/core/compaction/background-compaction.js.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts +10 -0
- package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
- package/dist/core/compaction/compaction-boundary.js +30 -2
- package/dist/core/compaction/compaction-boundary.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts +7 -0
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js +13 -5
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +1 -1
- package/dist/core/compaction/compaction-types.js +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/compaction/deleted-ranges.d.ts +17 -2
- package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
- package/dist/core/compaction/deleted-ranges.js +44 -5
- package/dist/core/compaction/deleted-ranges.js.map +1 -1
- package/dist/core/compaction/history-recall.d.ts +32 -0
- package/dist/core/compaction/history-recall.d.ts.map +1 -0
- package/dist/core/compaction/history-recall.js +275 -0
- package/dist/core/compaction/history-recall.js.map +1 -0
- package/dist/core/compaction/index.d.ts +2 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +2 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
- package/dist/core/compaction/pi-summary-fallback.js +1 -0
- package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
- package/dist/core/compaction/planner-outcome.d.ts +14 -0
- package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
- package/dist/core/compaction/planner-outcome.js +8 -0
- package/dist/core/compaction/planner-outcome.js.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.d.ts +35 -10
- package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
- package/dist/core/compaction/range-planner-diagnostics.js +67 -24
- package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
- package/dist/core/compaction/range-planner.d.ts +7 -4
- package/dist/core/compaction/range-planner.d.ts.map +1 -1
- package/dist/core/compaction/range-planner.js +43 -19
- package/dist/core/compaction/range-planner.js.map +1 -1
- package/dist/core/compaction/refusal-recovery.d.ts +27 -0
- package/dist/core/compaction/refusal-recovery.d.ts.map +1 -0
- package/dist/core/compaction/refusal-recovery.js +65 -0
- package/dist/core/compaction/refusal-recovery.js.map +1 -0
- package/dist/core/compaction/region-trimming.d.ts +23 -0
- package/dist/core/compaction/region-trimming.d.ts.map +1 -1
- package/dist/core/compaction/region-trimming.js +59 -15
- package/dist/core/compaction/region-trimming.js.map +1 -1
- package/dist/core/compaction/structured-compaction-input.d.ts +19 -1
- package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -1
- package/dist/core/compaction/structured-compaction-input.js +30 -17
- package/dist/core/compaction/structured-compaction-input.js.map +1 -1
- package/dist/core/compaction/transcript-serialization.d.ts +9 -3
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
- package/dist/core/compaction/transcript-serialization.js +18 -10
- package/dist/core/compaction/transcript-serialization.js.map +1 -1
- package/dist/core/messages.d.ts +5 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +21 -3
- package/dist/core/messages.js.map +1 -1
- package/dist/core/session-manager-core.js +1 -1
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-history.d.ts +1 -1
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-history.js +2 -5
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +2 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +2 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +3 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/settings-schema.d.ts +2 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +4 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/storage/session/conformance.d.ts.map +1 -1
- package/dist/core/storage/session/conformance.js +12 -0
- package/dist/core/storage/session/conformance.js.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/jsonl-session-store.js +3 -0
- package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
- package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/legacy-session-store.js +3 -0
- package/dist/core/storage/session/legacy-session-store.js.map +1 -1
- package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/memory-session-store.js +3 -0
- package/dist/core/storage/session/memory-session-store.js.map +1 -1
- package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/sql-session-store.js +12 -3
- package/dist/core/storage/session/sql-session-store.js.map +1 -1
- package/dist/core/storage/session/types.d.ts +3 -0
- package/dist/core/storage/session/types.d.ts.map +1 -1
- package/dist/core/storage/session/types.js +3 -0
- package/dist/core/storage/session/types.js.map +1 -1
- package/dist/core/tools/history-protocol.d.ts +3 -0
- package/dist/core/tools/history-protocol.d.ts.map +1 -1
- package/dist/core/tools/history-protocol.js +7 -87
- package/dist/core/tools/history-protocol.js.map +1 -1
- package/dist/core/tools/history-transcript.d.ts +24 -0
- package/dist/core/tools/history-transcript.d.ts.map +1 -0
- package/dist/core/tools/history-transcript.js +110 -0
- package/dist/core/tools/history-transcript.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +21 -5
- package/dist/main-session.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js +7 -3
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +2 -2
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/session-id-target.d.ts +1 -0
- package/dist/session-id-target.d.ts.map +1 -1
- package/dist/session-id-target.js +3 -0
- package/dist/session-id-target.js.map +1 -1
- package/docs/compaction/reference.md +3 -2
- package/docs/compaction.md +35 -7
- package/docs/development.md +1 -1
- package/docs/sdk/reference.md +6 -5
- package/docs/sessions.md +3 -3
- package/docs/settings.md +3 -0
- package/docs/storage.md +2 -0
- package/docs/workflows/api-reference.md +15 -3
- package/docs/workflows/authoring.md +2 -2
- package/docs/workflows/operations.md +1 -0
- package/docs/workflows/reliable-design.md +1 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
- package/schemas/settings.schema.json +5 -0
|
@@ -14,6 +14,24 @@ export interface StructuredCompactionInput {
|
|
|
14
14
|
protected: MessageLineRange[];
|
|
15
15
|
}
|
|
16
16
|
export declare function buildStructuredCompactionInput(region: NumberedRegion, parameters: VerbatimCompactionParameters): StructuredCompactionInput;
|
|
17
|
-
export declare function
|
|
17
|
+
export declare function inferMessageSpans(region: NumberedRegion): NonNullable<NumberedRegion["messageSpans"]>;
|
|
18
|
+
/**
|
|
19
|
+
* A planner answer is malformed when more than this fraction of its non-blank,
|
|
20
|
+
* non-fence lines are not records. Exactly this fraction is still accepted.
|
|
21
|
+
*/
|
|
22
|
+
export declare const MAX_SKIPPED_LINE_FRACTION = 0.5;
|
|
23
|
+
export interface ParsedMessageRangeRecords {
|
|
24
|
+
/** Valid records in the order the planner emitted them. */
|
|
25
|
+
ranges: MessageLineRange[];
|
|
26
|
+
/** Non-blank, non-fence lines that were not valid records. */
|
|
27
|
+
skippedLineCount: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Parse planner output into `id:start,end` records, skipping lines that are not records.
|
|
31
|
+
* Blank lines and Markdown fence lines are ignored without being counted. Returns
|
|
32
|
+
* undefined when no record remains or when skipped lines exceed `MAX_SKIPPED_LINE_FRACTION`.
|
|
33
|
+
* With `truncated`, the incomplete last line is dropped before parsing.
|
|
34
|
+
*/
|
|
35
|
+
export declare function parseMessageRangeRecords(text: string, truncated?: boolean): ParsedMessageRangeRecords | undefined;
|
|
18
36
|
export declare function mapMessageRanges(ranges: readonly MessageLineRange[], input: StructuredCompactionInput): LineRange[];
|
|
19
37
|
//# sourceMappingURL=structured-compaction-input.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured-compaction-input.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/structured-compaction-input.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAIrG,MAAM,WAAW,sBAAsB;IACtC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,MAAM,CAAC;IACpC,KAAK,EAAE,MAAM,EAAE,CAAC;CAChB;AAED,MAAM,WAAW,gBAAiB,SAAQ,SAAS;IAClD,EAAE,EAAE,MAAM,CAAC;CACX;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,EAAE,sBAAsB,EAAE,CAAC;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,gBAAgB,EAAE,CAAC;CAC9B;AAED,wBAAgB,8BAA8B,CAC7C,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,4BAA4B,GACtC,yBAAyB,CAsB3B;
|
|
1
|
+
{"version":3,"file":"structured-compaction-input.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/structured-compaction-input.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAIrG,MAAM,WAAW,sBAAsB;IACtC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,MAAM,CAAC;IACpC,KAAK,EAAE,MAAM,EAAE,CAAC;CAChB;AAED,MAAM,WAAW,gBAAiB,SAAQ,SAAS;IAClD,EAAE,EAAE,MAAM,CAAC;CACX;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,EAAE,sBAAsB,EAAE,CAAC;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,gBAAgB,EAAE,CAAC;CAC9B;AAED,wBAAgB,8BAA8B,CAC7C,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,4BAA4B,GACtC,yBAAyB,CAsB3B;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,GAAG,WAAW,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC,CAcrG;AAID;;;GAGG;AACH,eAAO,MAAM,yBAAyB,MAAM,CAAC;AAE7C,MAAM,WAAW,yBAAyB;IACzC,2DAA2D;IAC3D,MAAM,EAAE,gBAAgB,EAAE,CAAC;IAC3B,8DAA8D;IAC9D,gBAAgB,EAAE,MAAM,CAAC;CACzB;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,UAAQ,GAAG,yBAAyB,GAAG,SAAS,CAe/G;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,gBAAgB,EAAE,EAAE,KAAK,EAAE,yBAAyB,GAAG,SAAS,EAAE,CAYnH"}
|
|
@@ -17,7 +17,7 @@ export function buildStructuredCompactionInput(region, parameters) {
|
|
|
17
17
|
protected: protectedRanges,
|
|
18
18
|
};
|
|
19
19
|
}
|
|
20
|
-
function inferMessageSpans(region) {
|
|
20
|
+
export function inferMessageSpans(region) {
|
|
21
21
|
const spans = [];
|
|
22
22
|
for (let index = 0; index < region.lines.length; index++) {
|
|
23
23
|
const header = ROLE_HEADER_RE.exec(region.lines[index]);
|
|
@@ -33,25 +33,38 @@ function inferMessageSpans(region) {
|
|
|
33
33
|
}
|
|
34
34
|
return spans;
|
|
35
35
|
}
|
|
36
|
+
const MESSAGE_RANGE_RECORD_RE = /^(0|[1-9][0-9]*):(0|[1-9][0-9]*),(0|[1-9][0-9]*)$/;
|
|
37
|
+
/**
|
|
38
|
+
* A planner answer is malformed when more than this fraction of its non-blank,
|
|
39
|
+
* non-fence lines are not records. Exactly this fraction is still accepted.
|
|
40
|
+
*/
|
|
41
|
+
export const MAX_SKIPPED_LINE_FRACTION = 0.5;
|
|
42
|
+
/**
|
|
43
|
+
* Parse planner output into `id:start,end` records, skipping lines that are not records.
|
|
44
|
+
* Blank lines and Markdown fence lines are ignored without being counted. Returns
|
|
45
|
+
* undefined when no record remains or when skipped lines exceed `MAX_SKIPPED_LINE_FRACTION`.
|
|
46
|
+
* With `truncated`, the incomplete last line is dropped before parsing.
|
|
47
|
+
*/
|
|
36
48
|
export function parseMessageRangeRecords(text, truncated = false) {
|
|
37
|
-
const complete = truncated
|
|
38
|
-
? text.slice(0, Math.max(0, text.lastIndexOf("\n")))
|
|
39
|
-
: text.endsWith("\n")
|
|
40
|
-
? text.slice(0, -1)
|
|
41
|
-
: text;
|
|
42
|
-
if (!complete)
|
|
43
|
-
return undefined;
|
|
49
|
+
const complete = truncated ? text.slice(0, Math.max(0, text.lastIndexOf("\n"))) : text;
|
|
44
50
|
const ranges = [];
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
let skippedLineCount = 0;
|
|
52
|
+
for (const rawLine of complete.split("\n")) {
|
|
53
|
+
const line = rawLine.trim();
|
|
54
|
+
if (line === "" || line.startsWith("```"))
|
|
55
|
+
continue;
|
|
56
|
+
const match = MESSAGE_RANGE_RECORD_RE.exec(line);
|
|
57
|
+
const [id, start, end] = match ? match.slice(1).map(Number) : [];
|
|
58
|
+
if (match && [id, start, end].every(Number.isSafeInteger))
|
|
59
|
+
ranges.push({ id, start, end });
|
|
60
|
+
else
|
|
61
|
+
skippedLineCount++;
|
|
53
62
|
}
|
|
54
|
-
|
|
63
|
+
if (ranges.length === 0)
|
|
64
|
+
return undefined;
|
|
65
|
+
if (skippedLineCount > MAX_SKIPPED_LINE_FRACTION * (ranges.length + skippedLineCount))
|
|
66
|
+
return undefined;
|
|
67
|
+
return { ranges, skippedLineCount };
|
|
55
68
|
}
|
|
56
69
|
export function mapMessageRanges(ranges, input) {
|
|
57
70
|
const offsets = new Map();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured-compaction-input.js","sourceRoot":"","sources":["../../../src/core/compaction/structured-compaction-input.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAmB9C,MAAM,UAAU,8BAA8B,CAC7C,MAAsB,EACtB,UAAwC;IAExC,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAC;IAC/D,MAAM,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5C,EAAE,EAAE,KAAK,GAAG,CAAC;QACb,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC;KACnD,CAAC,CAAC,CAAC;IACJ,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACrD,gBAAgB,CACf,IAAI,GAAG,CACN,CAAC,GAAG,CAAC,MAAM,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;SACtC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC;SACxD,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,CACtC,CACD,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,GAAG,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC,CAC/C,CAAC;IACF,OAAO;QACN,QAAQ;QACR,KAAK,EAAE,UAAU,CAAC,KAAK;QACvB,iBAAiB,EAAE,UAAU,CAAC,iBAAiB;QAC/C,SAAS,EAAE,eAAe;KAC1B,CAAC;AACH,CAAC;AAED,
|
|
1
|
+
{"version":3,"file":"structured-compaction-input.js","sourceRoot":"","sources":["../../../src/core/compaction/structured-compaction-input.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAmB9C,MAAM,UAAU,8BAA8B,CAC7C,MAAsB,EACtB,UAAwC;IAExC,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAC;IAC/D,MAAM,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5C,EAAE,EAAE,KAAK,GAAG,CAAC;QACb,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC;KACnD,CAAC,CAAC,CAAC;IACJ,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACrD,gBAAgB,CACf,IAAI,GAAG,CACN,CAAC,GAAG,CAAC,MAAM,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;SACtC,MA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ineRange, NumberedRegion, VerbatimCompactionParameters } from \"./compaction-types.js\";\nimport { ROLE_HEADER_RE } from \"./transcript-serialization.js\";\nimport { contiguousRanges } from \"./utils.ts\";\n\nexport interface CompactionInputMessage {\n\tid: number;\n\trole: \"user\" | \"assistant\" | \"tool\";\n\tlines: string[];\n}\n\nexport interface MessageLineRange extends LineRange {\n\tid: number;\n}\n\nexport interface StructuredCompactionInput {\n\tmessages: CompactionInputMessage[];\n\tquery: string;\n\tcompression_ratio: number;\n\tprotected: MessageLineRange[];\n}\n\nexport function buildStructuredCompactionInput(\n\tregion: NumberedRegion,\n\tparameters: VerbatimCompactionParameters,\n): StructuredCompactionInput {\n\tconst spans = region.messageSpans ?? inferMessageSpans(region);\n\tconst messages = spans.map((span, index) => ({\n\t\tid: index + 1,\n\t\trole: span.role,\n\t\tlines: region.lines.slice(span.start - 1, span.end),\n\t}));\n\tconst protectedRanges = spans.flatMap((span, index) =>\n\t\tcontiguousRanges(\n\t\t\tnew Set(\n\t\t\t\t[...(region.protectedLineNumbers ?? [])]\n\t\t\t\t\t.filter((line) => line >= span.start && line <= span.end)\n\t\t\t\t\t.map((line) => line - span.start + 1),\n\t\t\t),\n\t\t).map((range) => ({ id: index + 1, ...range })),\n\t);\n\treturn {\n\t\tmessages,\n\t\tquery: parameters.query,\n\t\tcompression_ratio: parameters.compression_ratio,\n\t\tprotected: protectedRanges,\n\t};\n}\n\nexport function inferMessageSpans(region: NumberedRegion): NonNullable<NumberedRegion[\"messageSpans\"]> {\n\tconst spans: NonNullable<NumberedRegion[\"messageSpans\"]> = [];\n\tfor (let index = 0; index < region.lines.length; index++) {\n\t\tconst header = ROLE_HEADER_RE.exec(region.lines[index]);\n\t\tif (header || spans.length === 0) {\n\t\t\tif (spans.length > 0) spans[spans.length - 1].end = index;\n\t\t\tspans.push({\n\t\t\t\trole: header?.[1] === \"User\" ? \"user\" : header?.[1] === \"Tool result\" ? \"tool\" : \"assistant\",\n\t\t\t\tstart: index + 1,\n\t\t\t\tend: region.lines.length,\n\t\t\t});\n\t\t}\n\t}\n\treturn spans;\n}\n\nconst MESSAGE_RANGE_RECORD_RE = /^(0|[1-9][0-9]*):(0|[1-9][0-9]*),(0|[1-9][0-9]*)$/;\n\n/**\n * A planner answer is malformed when more than this fraction of its non-blank,\n * non-fence lines are not records. Exactly this fraction is still accepted.\n */\nexport const MAX_SKIPPED_LINE_FRACTION = 0.5;\n\nexport interface ParsedMessageRangeRecords {\n\t/** Valid records in the order the planner emitted them. */\n\tranges: MessageLineRange[];\n\t/** Non-blank, non-fence lines that were not valid records. */\n\tskippedLineCount: number;\n}\n\n/**\n * Parse planner output into `id:start,end` records, skipping lines that are not records.\n * Blank lines and Markdown fence lines are ignored without being counted. Returns\n * undefined when no record remains or when skipped lines exceed `MAX_SKIPPED_LINE_FRACTION`.\n * With `truncated`, the incomplete last line is dropped before parsing.\n */\nexport function parseMessageRangeRecords(text: string, truncated = false): ParsedMessageRangeRecords | undefined {\n\tconst complete = truncated ? text.slice(0, Math.max(0, text.lastIndexOf(\"\\n\"))) : text;\n\tconst ranges: MessageLineRange[] = [];\n\tlet skippedLineCount = 0;\n\tfor (const rawLine of complete.split(\"\\n\")) {\n\t\tconst line = rawLine.trim();\n\t\tif (line === \"\" || line.startsWith(\"```\")) continue;\n\t\tconst match = MESSAGE_RANGE_RECORD_RE.exec(line);\n\t\tconst [id, start, end] = match ? match.slice(1).map(Number) : [];\n\t\tif (match && [id, start, end].every(Number.isSafeInteger)) ranges.push({ id, start, end });\n\t\telse skippedLineCount++;\n\t}\n\tif (ranges.length === 0) return undefined;\n\tif (skippedLineCount > MAX_SKIPPED_LINE_FRACTION * (ranges.length + skippedLineCount)) return undefined;\n\treturn { ranges, skippedLineCount };\n}\n\nexport function mapMessageRanges(ranges: readonly MessageLineRange[], input: StructuredCompactionInput): LineRange[] {\n\tconst offsets = new Map<number, { offset: number; length: number }>();\n\tlet offset = 0;\n\tfor (const message of input.messages) {\n\t\toffsets.set(message.id, { offset, length: message.lines.length });\n\t\toffset += message.lines.length;\n\t}\n\treturn ranges.flatMap((range) => {\n\t\tconst message = offsets.get(range.id);\n\t\tif (!message || range.start < 1 || range.end < range.start || range.end > message.length) return [];\n\t\treturn [{ start: message.offset + range.start, end: message.offset + range.end }];\n\t});\n}\n"]}
|
|
@@ -6,8 +6,14 @@ export declare const ROLE_HEADER_RE: RegExp;
|
|
|
6
6
|
/** One piece of a serialized transcript: literal text, or an image kept at its position. */
|
|
7
7
|
export type TranscriptChunk = TextContent | ImageContent;
|
|
8
8
|
export declare function filteredMarker(lineCount: number): string;
|
|
9
|
-
/**
|
|
10
|
-
export
|
|
9
|
+
/** Where a tool result's full output can be read back: a `history://sessions/<id>:N-M` URL, keyed by the message. */
|
|
10
|
+
export type FullOutputLocators = ReadonlyMap<Message, string>;
|
|
11
|
+
/**
|
|
12
|
+
* Serialize provider messages using the durable verbatim-compaction section grammar.
|
|
13
|
+
* A truncated tool result names its location in `locators` when it has one, and otherwise says only that the
|
|
14
|
+
* full output is in the session's history.
|
|
15
|
+
*/
|
|
16
|
+
export declare function serializeConversationForCompaction(messages: Message[], locators?: FullOutputLocators): string;
|
|
11
17
|
/**
|
|
12
18
|
* Serialize retained messages without losing payloads: tool results keep their full text and
|
|
13
19
|
* images stay as image blocks at their position in the transcript. Thinking is omitted.
|
|
@@ -35,6 +41,6 @@ export declare function omitLegacyThinkingSections(text: string): string;
|
|
|
35
41
|
*/
|
|
36
42
|
export declare function keepContextLineNumbers(lines: readonly string[]): Set<number>;
|
|
37
43
|
export declare function createNumberedRegion(text: string, protectedLineNumbers?: ReadonlySet<number>): NumberedRegion;
|
|
38
|
-
export declare function createConversationRegion(messages: Message[], previousSummary?: string): NumberedRegion;
|
|
44
|
+
export declare function createConversationRegion(messages: Message[], previousSummary?: string, locators?: FullOutputLocators): NumberedRegion;
|
|
39
45
|
export declare function numberRegionLines(region: NumberedRegion, start?: number, end?: number): string;
|
|
40
46
|
//# sourceMappingURL=transcript-serialization.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript-serialization.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/transcript-serialization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D,eAAO,MAAM,kBAAkB,QAA+B,CAAC;AAC/D,eAAO,MAAM,qBAAqB,WAAM,CAAC;AACzC,eAAO,MAAM,cAAc,QAA6D,CAAC;AAyBzF,4FAA4F;AAC5F,MAAM,MAAM,eAAe,GAAG,WAAW,GAAG,YAAY,CAAC;AAUzD,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAExD;
|
|
1
|
+
{"version":3,"file":"transcript-serialization.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/transcript-serialization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D,eAAO,MAAM,kBAAkB,QAA+B,CAAC;AAC/D,eAAO,MAAM,qBAAqB,WAAM,CAAC;AACzC,eAAO,MAAM,cAAc,QAA6D,CAAC;AAyBzF,4FAA4F;AAC5F,MAAM,MAAM,eAAe,GAAG,WAAW,GAAG,YAAY,CAAC;AAUzD,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAExD;AAED,qHAAqH;AACrH,MAAM,MAAM,kBAAkB,GAAG,WAAW,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAmH9D;;;;GAIG;AACH,wBAAgB,kCAAkC,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,QAAQ,CAAC,EAAE,kBAAkB,GAAG,MAAM,CAI7G;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,eAAe,EAAE,CAElF;AAED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAU/D;AA0CD;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,CA0B5E;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,oBAAoB,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,cAAc,CAqB7G;AAED,wBAAgB,wBAAwB,CACvC,QAAQ,EAAE,OAAO,EAAE,EACnB,eAAe,CAAC,EAAE,MAAM,EACxB,QAAQ,CAAC,EAAE,kBAAkB,GAC3B,cAAc,CAuBhB;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,EAAE,KAAK,SAAI,EAAE,GAAG,SAAsB,GAAG,MAAM,CAQtG"}
|
|
@@ -20,14 +20,18 @@ const LEGACY_THINKING_HEADER = "[Assistant thinking]: ";
|
|
|
20
20
|
*/
|
|
21
21
|
const KEEP_CONTEXT_OPEN_LINE_RE = /^<keepContext>$/i;
|
|
22
22
|
const KEEP_CONTEXT_CLOSE_LINE_RE = /^<\/keepContext>$/i;
|
|
23
|
-
const TOOL_RESULT_MAX_CHARS =
|
|
23
|
+
const TOOL_RESULT_MAX_CHARS = 2_000;
|
|
24
24
|
export function filteredMarker(lineCount) {
|
|
25
25
|
return `(filtered ${lineCount} lines)`;
|
|
26
26
|
}
|
|
27
|
-
function truncateToolResult(text) {
|
|
27
|
+
function truncateToolResult(text, fullOutputUrl) {
|
|
28
28
|
if (text.length <= TOOL_RESULT_MAX_CHARS)
|
|
29
29
|
return text;
|
|
30
|
-
|
|
30
|
+
const removed = text.length - TOOL_RESULT_MAX_CHARS;
|
|
31
|
+
const where = fullOutputUrl === undefined
|
|
32
|
+
? "the full output is in this session's history"
|
|
33
|
+
: `full output: read ${fullOutputUrl}`;
|
|
34
|
+
return `${text.slice(0, TOOL_RESULT_MAX_CHARS)}\n\n[... ${removed} more characters truncated; ${where}]`;
|
|
31
35
|
}
|
|
32
36
|
function lastChunk(chunks) {
|
|
33
37
|
return chunks.length > 0 ? chunks[chunks.length - 1] : undefined;
|
|
@@ -78,7 +82,7 @@ function serializeContentBlocks(content, mode) {
|
|
|
78
82
|
* and tool results. Thinking is omitted. Providers return summaries of the real reasoning, and
|
|
79
83
|
* some refuse a compaction request that replays earlier thinking as transcript text (#4544).
|
|
80
84
|
*/
|
|
81
|
-
function serializeTranscriptChunks(messages, mode) {
|
|
85
|
+
function serializeTranscriptChunks(messages, mode, locators) {
|
|
82
86
|
const chunks = [];
|
|
83
87
|
const pushSection = (header, section) => {
|
|
84
88
|
if (!hasContent(section))
|
|
@@ -120,7 +124,7 @@ function serializeTranscriptChunks(messages, mode) {
|
|
|
120
124
|
if (mode === "compacted") {
|
|
121
125
|
for (const chunk of section) {
|
|
122
126
|
if (chunk.type === "text")
|
|
123
|
-
chunk.text = truncateToolResult(chunk.text);
|
|
127
|
+
chunk.text = truncateToolResult(chunk.text, locators?.get(message));
|
|
124
128
|
}
|
|
125
129
|
}
|
|
126
130
|
pushSection("[Tool result]: ", section);
|
|
@@ -128,9 +132,13 @@ function serializeTranscriptChunks(messages, mode) {
|
|
|
128
132
|
}
|
|
129
133
|
return chunks;
|
|
130
134
|
}
|
|
131
|
-
/**
|
|
132
|
-
|
|
133
|
-
|
|
135
|
+
/**
|
|
136
|
+
* Serialize provider messages using the durable verbatim-compaction section grammar.
|
|
137
|
+
* A truncated tool result names its location in `locators` when it has one, and otherwise says only that the
|
|
138
|
+
* full output is in the session's history.
|
|
139
|
+
*/
|
|
140
|
+
export function serializeConversationForCompaction(messages, locators) {
|
|
141
|
+
return serializeTranscriptChunks(messages, "compacted", locators)
|
|
134
142
|
.map((chunk) => (chunk.type === "text" ? chunk.text : ""))
|
|
135
143
|
.join("");
|
|
136
144
|
}
|
|
@@ -269,12 +277,12 @@ export function createNumberedRegion(text, protectedLineNumbers) {
|
|
|
269
277
|
tokenEstimate: Math.ceil(text.length / 4),
|
|
270
278
|
};
|
|
271
279
|
}
|
|
272
|
-
export function createConversationRegion(messages, previousSummary) {
|
|
280
|
+
export function createConversationRegion(messages, previousSummary, locators) {
|
|
273
281
|
const sections = [];
|
|
274
282
|
if (previousSummary)
|
|
275
283
|
sections.push({ role: "assistant", text: previousSummary });
|
|
276
284
|
for (const message of messages) {
|
|
277
|
-
const text = serializeConversationForCompaction([message]);
|
|
285
|
+
const text = serializeConversationForCompaction([message], locators);
|
|
278
286
|
if (text)
|
|
279
287
|
sections.push({
|
|
280
288
|
role: message.role === "toolResult" ? "tool" : message.role === "user" ? "user" : "assistant",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcript-serialization.js","sourceRoot":"","sources":["../../../src/core/compaction/transcript-serialization.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,kBAAkB,GAAG,4BAA4B,CAAC;AAC/D,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AACzC,MAAM,CAAC,MAAM,cAAc,GAAG,0DAA0D,CAAC;AAEzF;;;GAGG;AACH,MAAM,sBAAsB,GAAG,wBAAwB,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,yBAAyB,GAAG,kBAAkB,CAAC;AACrD,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAExD,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAarC,MAAM,UAAU,cAAc,CAAC,SAAiB;IAC/C,OAAO,aAAa,SAAS,SAAS,CAAC;AACxC,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAY;IACvC,IAAI,IAAI,CAAC,MAAM,IAAI,qBAAqB;QAAE,OAAO,IAAI,CAAC;IACtD,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,YAAY,IAAI,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AAE,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,MAAM,GAAG,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACtD,MAAM,CAAC,YAAY,GAAG,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;IACzG,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAsB,EAAE,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM;IAC7F,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAC5D,IAAI,KAAK,GAAG,IAAI;QAAE,OAAO,EAAE,CAAC;IAC5B,OAAO,MAAM,CAAC,KAAK;SACjB,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,CAAC;SACtB,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,GAAG,KAAK,GAAG,qBAAqB,GAAG,IAAI,EAAE,CAAC;SACvE,IAAI,CAAC,IAAI,CAAC,CAAC;AACd,CAAC","sourcesContent":["import type { ImageContent, Message, TextContent } from \"@bastani/pi-ai/compat\";\nimport type { NumberedRegion } from \"./compaction-types.js\";\n\nexport const FILTERED_MARKER_RE = /^\\(filtered (\\d+) lines\\)$/;\nexport const LINE_NUMBER_SEPARATOR = \"→\";\nexport const ROLE_HEADER_RE = /^\\[(User|Assistant|Assistant tool calls|Tool result)\\]: /;\n\n/**\n * Header of the thinking section that transcripts serialized before prompt version 5 carried.\n * Current transcripts never emit it; it is recognized only to drop those sections from older summaries.\n */\nconst LEGACY_THINKING_HEADER = \"[Assistant thinking]: \";\n\n/**\n * Callers wrap never-compressible content in `<keepContext>` / `</keepContext>`. Every line of\n * such a span, tag lines included, becomes a protected line, so the span survives verbatim\n * regardless of the compression ratio. Protecting the tags themselves is what makes the span\n * re-detectable on the next boundary, since each compaction re-ranks the previous output.\n *\n * The region is untrusted: it is serialized user, assistant, and tool-result payload, and a\n * message may quote or document the tag text. Detection is therefore deliberately narrow — a\n * marker must be the entire line once an optional role header is stripped, and only a matched\n * open/close pair protects anything. Prose that merely mentions a tag matches nothing, and an\n * unmatched opener protects nothing rather than swallowing the rest of the region.\n */\nconst KEEP_CONTEXT_OPEN_LINE_RE = /^<keepContext>$/i;\nconst KEEP_CONTEXT_CLOSE_LINE_RE = /^<\\/keepContext>$/i;\n\nconst TOOL_RESULT_MAX_CHARS = 16_000;\n\n/** One piece of a serialized transcript: literal text, or an image kept at its position. */\nexport type TranscriptChunk = TextContent | ImageContent;\n\n/**\n * `compacted` renders the durable transcript grammar: images become `[image]` markers and\n * oversized tool results are truncated. `retained` keeps every payload, for spans the\n * compaction promised to preserve verbatim. Both modes omit thinking, as `serializeConversation()`\n * does for summaries.\n */\ntype SerializeMode = \"compacted\" | \"retained\";\n\nexport function filteredMarker(lineCount: number): string {\n\treturn `(filtered ${lineCount} lines)`;\n}\n\nfunction truncateToolResult(text: string): string {\n\tif (text.length <= TOOL_RESULT_MAX_CHARS) return text;\n\treturn `${text.slice(0, TOOL_RESULT_MAX_CHARS)}\\n\\n[... ${text.length - TOOL_RESULT_MAX_CHARS} more characters truncated]`;\n}\n\nfunction lastChunk(chunks: TranscriptChunk[]): TranscriptChunk | undefined {\n\treturn chunks.length > 0 ? chunks[chunks.length - 1] : undefined;\n}\n\nfunction appendText(chunks: TranscriptChunk[], text: string): void {\n\tif (text.length === 0) return;\n\tconst last = lastChunk(chunks);\n\tif (last !== undefined && last.type === \"text\") last.text += text;\n\telse chunks.push({ type: \"text\", text });\n}\n\nfunction hasContent(chunks: TranscriptChunk[]): boolean {\n\treturn chunks.some((chunk) => chunk.type !== \"text\" || chunk.text.length > 0);\n}\n\nfunction serializeContentBlocks(\n\tcontent: Extract<Message, { role: \"user\" | \"toolResult\" }>[\"content\"],\n\tmode: SerializeMode,\n): TranscriptChunk[] {\n\tif (typeof content === \"string\") return content.length > 0 ? [{ type: \"text\", text: content }] : [];\n\tconst chunks: TranscriptChunk[] = [];\n\tfor (const block of content) {\n\t\tif (block.type === \"text\") {\n\t\t\tappendText(chunks, block.text);\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.type !== \"image\") continue;\n\t\tif (mode === \"retained\") {\n\t\t\tif (chunks.length > 0) appendText(chunks, \"\\n\");\n\t\t\tchunks.push({ ...block });\n\t\t\tcontinue;\n\t\t}\n\t\tconst last = lastChunk(chunks);\n\t\tconst needsBreak = last !== undefined && last.type === \"text\" && !last.text.endsWith(\"\\n\");\n\t\tappendText(chunks, `${needsBreak ? \"\\n\" : \"\"}[image]\\n`);\n\t}\n\tconst trailing = lastChunk(chunks);\n\tif (trailing !== undefined && trailing.type === \"text\" && trailing.text.endsWith(\"\\n\")) {\n\t\ttrailing.text = trailing.text.slice(0, -1);\n\t}\n\treturn chunks;\n}\n\n/**\n * Serialize provider messages into transcript chunks using the durable section grammar.\n *\n * The sections match `serializeConversation()`: user text, assistant text, assistant tool calls,\n * and tool results. Thinking is omitted. Providers return summaries of the real reasoning, and\n * some refuse a compaction request that replays earlier thinking as transcript text (#4544).\n */\nfunction serializeTranscriptChunks(messages: Message[], mode: SerializeMode): TranscriptChunk[] {\n\tconst chunks: TranscriptChunk[] = [];\n\tconst pushSection = (header: string, section: TranscriptChunk[]): void => {\n\t\tif (!hasContent(section)) return;\n\t\tappendText(chunks, `${chunks.length > 0 ? \"\\n\\n\" : \"\"}${header}`);\n\t\tfor (const chunk of section) {\n\t\t\tif (chunk.type === \"text\") appendText(chunks, chunk.text);\n\t\t\telse chunks.push(chunk);\n\t\t}\n\t};\n\n\tfor (const message of messages) {\n\t\tif (message.role === \"user\") {\n\t\t\tpushSection(\"[User]: \", serializeContentBlocks(message.content, mode));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\") {\n\t\t\tconst text: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"text\") text.push(block.text);\n\t\t\t\telse if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = Object.entries(block.arguments)\n\t\t\t\t\t\t.map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${args})`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (text.length > 0) pushSection(\"[Assistant]: \", [{ type: \"text\", text: text.join(\"\\n\") }]);\n\t\t\tif (toolCalls.length > 0)\n\t\t\t\tpushSection(\"[Assistant tool calls]: \", [{ type: \"text\", text: toolCalls.join(\"; \") }]);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst section = serializeContentBlocks(message.content, mode);\n\t\t\tif (mode === \"compacted\") {\n\t\t\t\tfor (const chunk of section) {\n\t\t\t\t\tif (chunk.type === \"text\") chunk.text = truncateToolResult(chunk.text);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpushSection(\"[Tool result]: \", section);\n\t\t}\n\t}\n\n\treturn chunks;\n}\n\n/** Serialize provider messages using the durable verbatim-compaction section grammar. */\nexport function serializeConversationForCompaction(messages: Message[]): string {\n\treturn serializeTranscriptChunks(messages, \"compacted\")\n\t\t.map((chunk) => (chunk.type === \"text\" ? chunk.text : \"\"))\n\t\t.join(\"\");\n}\n\n/**\n * Serialize retained messages without losing payloads: tool results keep their full text and\n * images stay as image blocks at their position in the transcript. Thinking is omitted.\n */\nexport function serializeRetainedTranscript(messages: Message[]): TranscriptChunk[] {\n\treturn serializeTranscriptChunks(messages, \"retained\");\n}\n\n/**\n * Drop the `[Assistant thinking]: ` sections from a transcript serialized before prompt version 5.\n *\n * A section runs from its header to the next role header or `(filtered N lines)` marker. Stopping\n * at a marker is deliberate: a prior compaction may have deleted the following header along with\n * part of the section, so the lines after the marker can belong to the next section. Thinking lines\n * whose header an earlier compaction deleted cannot be told apart from their neighbours and stay.\n */\nexport function omitLegacyThinkingSections(text: string): string {\n\tconst kept: string[] = [];\n\tlet omitting = false;\n\tfor (const line of text.split(\"\\n\")) {\n\t\tif (line.startsWith(LEGACY_THINKING_HEADER)) omitting = true;\n\t\telse if (omitting && (ROLE_HEADER_RE.test(line) || FILTERED_MARKER_RE.test(line))) omitting = false;\n\t\tif (!omitting) kept.push(line);\n\t}\n\tif (omitting && kept[kept.length - 1] === \"\") kept.pop();\n\treturn kept.join(\"\\n\");\n}\n\n/**\n * Classify a line as a `keepContext` marker.\n *\n * The serializer prefixes the first line of a message with its role header, so a span opened at\n * the start of a stage prompt arrives as `[User]: <keepContext>`. The header is stripped before\n * matching, and the remainder must be the whole line — prose that mentions a tag mid-sentence is\n * payload, not syntax.\n */\nfunction keepContextMarker(line: string): \"open\" | \"close\" | undefined {\n\tconst body = line.replace(ROLE_HEADER_RE, \"\").trim();\n\tif (KEEP_CONTEXT_OPEN_LINE_RE.test(body)) return \"open\";\n\tif (KEEP_CONTEXT_CLOSE_LINE_RE.test(body)) return \"close\";\n\treturn undefined;\n}\n\n/** Message roles whose payload is external, so its tag text is data rather than syntax. */\nconst UNTRUSTED_MARKER_ROLE = \"Tool result\";\n\n/**\n * Whether a message role may declare protection.\n *\n * User and assistant messages both may. Prompt construction — stage prompts, run inputs, and\n * steering — arrives as user messages, and agents need protection in their own output too, to\n * restate a contract amendment in a handoff report or pin a decision that changes later\n * behavior. A user-only rule would make those inert while still looking correct at the call site.\n *\n * Tool results may not. Their payload is file contents, fetched pages, and command output —\n * bytes an attacker can choose — and honoring tags there would let read material mark itself\n * unreclaimable and persist through compaction ahead of real transcript content. An agent that\n * wants to keep something it read can restate it in its own message, which is also the more\n * selective habit.\n *\n * An undefined role is the prior compaction summary prepended ahead of the first role header.\n * That is compaction's own output, and honoring it is what lets a span re-arm on later\n * boundaries after its header line has itself been compacted away.\n */\nfunction roleMayProtect(role: string | undefined): boolean {\n\treturn role !== UNTRUSTED_MARKER_ROLE;\n}\n\n/**\n * One-based line numbers covered by `<keepContext>` spans, inclusive of the tag lines.\n *\n * Spans are scoped to a single message: a role header ends any span still open, and an unclosed\n * span protects through the end of its own message rather than the end of the region. Together\n * with the whole-line marker rule and the tool-result exclusion, that keeps the permissive\n * unclosed case safe — quoted or injected tag text costs at most its own message instead of\n * everything after it. Compaction that cannot reclaim is an overflow, not a safe failure.\n *\n * Nested openers flatten into the outermost span, and a closing tag with no opener is inert.\n */\nexport function keepContextLineNumbers(lines: readonly string[]): Set<number> {\n\tconst protectedLines = new Set<number>();\n\tlet openIndex: number | undefined;\n\tlet role: string | undefined;\n\tconst protectThrough = (endIndex: number): void => {\n\t\tif (openIndex === undefined) return;\n\t\tfor (let line = openIndex; line <= endIndex; line++) protectedLines.add(line + 1);\n\t\topenIndex = undefined;\n\t};\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst line = lines[index];\n\t\tconst header = ROLE_HEADER_RE.exec(line);\n\t\tif (header) {\n\t\t\tprotectThrough(index - 1);\n\t\t\trole = header[1];\n\t\t}\n\t\tif (!roleMayProtect(role)) continue;\n\t\tconst marker = keepContextMarker(line);\n\t\tif (marker === \"open\") {\n\t\t\tif (openIndex === undefined) openIndex = index;\n\t\t\tcontinue;\n\t\t}\n\t\tif (marker === \"close\") protectThrough(index);\n\t}\n\tprotectThrough(lines.length - 1);\n\treturn protectedLines;\n}\n\nexport function createNumberedRegion(text: string, protectedLineNumbers?: ReadonlySet<number>): NumberedRegion {\n\tconst lines = text.split(\"\\n\");\n\tconst headerLineNumbers = new Set<number>();\n\tconst priorMarkerNs = new Map<number, number>();\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst lineNumber = index + 1;\n\t\tif (ROLE_HEADER_RE.test(lines[index])) headerLineNumbers.add(lineNumber);\n\t\tconst markerMatch = FILTERED_MARKER_RE.exec(lines[index]);\n\t\tif (markerMatch) priorMarkerNs.set(lineNumber, Number(markerMatch[1]));\n\t}\n\tconst detected = keepContextLineNumbers(lines);\n\tconst merged =\n\t\tprotectedLineNumbers === undefined ? detected : new Set<number>([...protectedLineNumbers, ...detected]);\n\treturn {\n\t\t__brand: \"NumberedRegion\",\n\t\tlines,\n\t\theaderLineNumbers,\n\t\tpriorMarkerNs,\n\t\tprotectedLineNumbers: merged.size > 0 ? merged : undefined,\n\t\ttokenEstimate: Math.ceil(text.length / 4),\n\t};\n}\n\nexport function createConversationRegion(messages: Message[], previousSummary?: string): NumberedRegion {\n\tconst sections: { role: \"user\" | \"assistant\" | \"tool\"; text: string }[] = [];\n\tif (previousSummary) sections.push({ role: \"assistant\", text: previousSummary });\n\tfor (const message of messages) {\n\t\tconst text = serializeConversationForCompaction([message]);\n\t\tif (text)\n\t\t\tsections.push({\n\t\t\t\trole: message.role === \"toolResult\" ? \"tool\" : message.role === \"user\" ? \"user\" : \"assistant\",\n\t\t\t\ttext,\n\t\t\t});\n\t}\n\tconst lines: string[] = [];\n\tconst messageSpans: NonNullable<NumberedRegion[\"messageSpans\"]> = [];\n\tfor (let index = 0; index < sections.length; index++) {\n\t\tconst section = sections[index];\n\t\tconst start = lines.length + 1;\n\t\tlines.push(...section.text.split(\"\\n\"));\n\t\tif (index < sections.length - 1 && !(index === 0 && previousSummary)) lines.push(\"\");\n\t\tmessageSpans.push({ role: section.role, start, end: lines.length });\n\t}\n\tconst region = createNumberedRegion(lines.join(\"\\n\"));\n\tregion.messageSpans = messageSpans.length > 0 ? messageSpans : [{ role: \"assistant\", start: 1, end: 1 }];\n\treturn region;\n}\n\nexport function numberRegionLines(region: NumberedRegion, start = 1, end = region.lines.length): string {\n\tconst first = Math.max(1, Math.trunc(start));\n\tconst last = Math.min(region.lines.length, Math.trunc(end));\n\tif (first > last) return \"\";\n\treturn region.lines\n\t\t.slice(first - 1, last)\n\t\t.map((line, index) => `${first + index}${LINE_NUMBER_SEPARATOR}${line}`)\n\t\t.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transcript-serialization.js","sourceRoot":"","sources":["../../../src/core/compaction/transcript-serialization.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,MAAM,kBAAkB,GAAG,4BAA4B,CAAC;AAC/D,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AACzC,MAAM,CAAC,MAAM,cAAc,GAAG,0DAA0D,CAAC;AAEzF;;;GAGG;AACH,MAAM,sBAAsB,GAAG,wBAAwB,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,yBAAyB,GAAG,kBAAkB,CAAC;AACrD,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAExD,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAapC,MAAM,UAAU,cAAc,CAAC,SAAiB;IAC/C,OAAO,aAAa,SAAS,SAAS,CAAC;AACxC,CAAC;AAKD,SAAS,kBAAkB,CAAC,IAAY,EAAE,aAAiC;IAC1E,IAAI,IAAI,CAAC,MAAM,IAAI,qBAAqB;QAAE,OAAO,IAAI,CAAC;IACtD,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,GAAG,qBAAqB,CAAC;IACpD,MAAM,KAAK,GACV,aAAa,KAAK,SAAS;QAC1B,CAAC,CAAC,8CAA8C;QAChD,CAAC,CAAC,qBAAqB,aAAa,EAAE,CAAC;IACzC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,qBAAqB,CAAC,YAAY,OAAO,+BAA+B,KAAK,GAAG,CAAC;AAC1G,CAAC;AAED,SAAS,SAAS,CAAC,MAAy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AI,EAAE,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,MAAM,GAAG,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACtD,MAAM,CAAC,YAAY,GAAG,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;IACzG,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAsB,EAAE,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM;IAC7F,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAC5D,IAAI,KAAK,GAAG,IAAI;QAAE,OAAO,EAAE,CAAC;IAC5B,OAAO,MAAM,CAAC,KAAK;SACjB,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,CAAC;SACtB,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,GAAG,KAAK,GAAG,qBAAqB,GAAG,IAAI,EAAE,CAAC;SACvE,IAAI,CAAC,IAAI,CAAC,CAAC;AACd,CAAC","sourcesContent":["import type { ImageContent, Message, TextContent } from \"@bastani/pi-ai/compat\";\nimport type { NumberedRegion } from \"./compaction-types.js\";\n\nexport const FILTERED_MARKER_RE = /^\\(filtered (\\d+) lines\\)$/;\nexport const LINE_NUMBER_SEPARATOR = \"→\";\nexport const ROLE_HEADER_RE = /^\\[(User|Assistant|Assistant tool calls|Tool result)\\]: /;\n\n/**\n * Header of the thinking section that transcripts serialized before prompt version 5 carried.\n * Current transcripts never emit it; it is recognized only to drop those sections from older summaries.\n */\nconst LEGACY_THINKING_HEADER = \"[Assistant thinking]: \";\n\n/**\n * Callers wrap never-compressible content in `<keepContext>` / `</keepContext>`. Every line of\n * such a span, tag lines included, becomes a protected line, so the span survives verbatim\n * regardless of the compression ratio. Protecting the tags themselves is what makes the span\n * re-detectable on the next boundary, since each compaction re-ranks the previous output.\n *\n * The region is untrusted: it is serialized user, assistant, and tool-result payload, and a\n * message may quote or document the tag text. Detection is therefore deliberately narrow — a\n * marker must be the entire line once an optional role header is stripped, and only a matched\n * open/close pair protects anything. Prose that merely mentions a tag matches nothing, and an\n * unmatched opener protects nothing rather than swallowing the rest of the region.\n */\nconst KEEP_CONTEXT_OPEN_LINE_RE = /^<keepContext>$/i;\nconst KEEP_CONTEXT_CLOSE_LINE_RE = /^<\\/keepContext>$/i;\n\nconst TOOL_RESULT_MAX_CHARS = 2_000;\n\n/** One piece of a serialized transcript: literal text, or an image kept at its position. */\nexport type TranscriptChunk = TextContent | ImageContent;\n\n/**\n * `compacted` renders the durable transcript grammar: images become `[image]` markers and\n * oversized tool results are truncated. `retained` keeps every payload, for spans the\n * compaction promised to preserve verbatim. Both modes omit thinking, as `serializeConversation()`\n * does for summaries.\n */\ntype SerializeMode = \"compacted\" | \"retained\";\n\nexport function filteredMarker(lineCount: number): string {\n\treturn `(filtered ${lineCount} lines)`;\n}\n\n/** Where a tool result's full output can be read back: a `history://sessions/<id>:N-M` URL, keyed by the message. */\nexport type FullOutputLocators = ReadonlyMap<Message, string>;\n\nfunction truncateToolResult(text: string, fullOutputUrl: string | undefined): string {\n\tif (text.length <= TOOL_RESULT_MAX_CHARS) return text;\n\tconst removed = text.length - TOOL_RESULT_MAX_CHARS;\n\tconst where =\n\t\tfullOutputUrl === undefined\n\t\t\t? \"the full output is in this session's history\"\n\t\t\t: `full output: read ${fullOutputUrl}`;\n\treturn `${text.slice(0, TOOL_RESULT_MAX_CHARS)}\\n\\n[... ${removed} more characters truncated; ${where}]`;\n}\n\nfunction lastChunk(chunks: TranscriptChunk[]): TranscriptChunk | undefined {\n\treturn chunks.length > 0 ? chunks[chunks.length - 1] : undefined;\n}\n\nfunction appendText(chunks: TranscriptChunk[], text: string): void {\n\tif (text.length === 0) return;\n\tconst last = lastChunk(chunks);\n\tif (last !== undefined && last.type === \"text\") last.text += text;\n\telse chunks.push({ type: \"text\", text });\n}\n\nfunction hasContent(chunks: TranscriptChunk[]): boolean {\n\treturn chunks.some((chunk) => chunk.type !== \"text\" || chunk.text.length > 0);\n}\n\nfunction serializeContentBlocks(\n\tcontent: Extract<Message, { role: \"user\" | \"toolResult\" }>[\"content\"],\n\tmode: SerializeMode,\n): TranscriptChunk[] {\n\tif (typeof content === \"string\") return content.length > 0 ? [{ type: \"text\", text: content }] : [];\n\tconst chunks: TranscriptChunk[] = [];\n\tfor (const block of content) {\n\t\tif (block.type === \"text\") {\n\t\t\tappendText(chunks, block.text);\n\t\t\tcontinue;\n\t\t}\n\t\tif (block.type !== \"image\") continue;\n\t\tif (mode === \"retained\") {\n\t\t\tif (chunks.length > 0) appendText(chunks, \"\\n\");\n\t\t\tchunks.push({ ...block });\n\t\t\tcontinue;\n\t\t}\n\t\tconst last = lastChunk(chunks);\n\t\tconst needsBreak = last !== undefined && last.type === \"text\" && !last.text.endsWith(\"\\n\");\n\t\tappendText(chunks, `${needsBreak ? \"\\n\" : \"\"}[image]\\n`);\n\t}\n\tconst trailing = lastChunk(chunks);\n\tif (trailing !== undefined && trailing.type === \"text\" && trailing.text.endsWith(\"\\n\")) {\n\t\ttrailing.text = trailing.text.slice(0, -1);\n\t}\n\treturn chunks;\n}\n\n/**\n * Serialize provider messages into transcript chunks using the durable section grammar.\n *\n * The sections match `serializeConversation()`: user text, assistant text, assistant tool calls,\n * and tool results. Thinking is omitted. Providers return summaries of the real reasoning, and\n * some refuse a compaction request that replays earlier thinking as transcript text (#4544).\n */\nfunction serializeTranscriptChunks(\n\tmessages: Message[],\n\tmode: SerializeMode,\n\tlocators?: FullOutputLocators,\n): TranscriptChunk[] {\n\tconst chunks: TranscriptChunk[] = [];\n\tconst pushSection = (header: string, section: TranscriptChunk[]): void => {\n\t\tif (!hasContent(section)) return;\n\t\tappendText(chunks, `${chunks.length > 0 ? \"\\n\\n\" : \"\"}${header}`);\n\t\tfor (const chunk of section) {\n\t\t\tif (chunk.type === \"text\") appendText(chunks, chunk.text);\n\t\t\telse chunks.push(chunk);\n\t\t}\n\t};\n\n\tfor (const message of messages) {\n\t\tif (message.role === \"user\") {\n\t\t\tpushSection(\"[User]: \", serializeContentBlocks(message.content, mode));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\") {\n\t\t\tconst text: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (block.type === \"text\") text.push(block.text);\n\t\t\t\telse if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = Object.entries(block.arguments)\n\t\t\t\t\t\t.map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${args})`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (text.length > 0) pushSection(\"[Assistant]: \", [{ type: \"text\", text: text.join(\"\\n\") }]);\n\t\t\tif (toolCalls.length > 0)\n\t\t\t\tpushSection(\"[Assistant tool calls]: \", [{ type: \"text\", text: toolCalls.join(\"; \") }]);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst section = serializeContentBlocks(message.content, mode);\n\t\t\tif (mode === \"compacted\") {\n\t\t\t\tfor (const chunk of section) {\n\t\t\t\t\tif (chunk.type === \"text\") chunk.text = truncateToolResult(chunk.text, locators?.get(message));\n\t\t\t\t}\n\t\t\t}\n\t\t\tpushSection(\"[Tool result]: \", section);\n\t\t}\n\t}\n\n\treturn chunks;\n}\n\n/**\n * Serialize provider messages using the durable verbatim-compaction section grammar.\n * A truncated tool result names its location in `locators` when it has one, and otherwise says only that the\n * full output is in the session's history.\n */\nexport function serializeConversationForCompaction(messages: Message[], locators?: FullOutputLocators): string {\n\treturn serializeTranscriptChunks(messages, \"compacted\", locators)\n\t\t.map((chunk) => (chunk.type === \"text\" ? chunk.text : \"\"))\n\t\t.join(\"\");\n}\n\n/**\n * Serialize retained messages without losing payloads: tool results keep their full text and\n * images stay as image blocks at their position in the transcript. Thinking is omitted.\n */\nexport function serializeRetainedTranscript(messages: Message[]): TranscriptChunk[] {\n\treturn serializeTranscriptChunks(messages, \"retained\");\n}\n\n/**\n * Drop the `[Assistant thinking]: ` sections from a transcript serialized before prompt version 5.\n *\n * A section runs from its header to the next role header or `(filtered N lines)` marker. Stopping\n * at a marker is deliberate: a prior compaction may have deleted the following header along with\n * part of the section, so the lines after the marker can belong to the next section. Thinking lines\n * whose header an earlier compaction deleted cannot be told apart from their neighbours and stay.\n */\nexport function omitLegacyThinkingSections(text: string): string {\n\tconst kept: string[] = [];\n\tlet omitting = false;\n\tfor (const line of text.split(\"\\n\")) {\n\t\tif (line.startsWith(LEGACY_THINKING_HEADER)) omitting = true;\n\t\telse if (omitting && (ROLE_HEADER_RE.test(line) || FILTERED_MARKER_RE.test(line))) omitting = false;\n\t\tif (!omitting) kept.push(line);\n\t}\n\tif (omitting && kept[kept.length - 1] === \"\") kept.pop();\n\treturn kept.join(\"\\n\");\n}\n\n/**\n * Classify a line as a `keepContext` marker.\n *\n * The serializer prefixes the first line of a message with its role header, so a span opened at\n * the start of a stage prompt arrives as `[User]: <keepContext>`. The header is stripped before\n * matching, and the remainder must be the whole line — prose that mentions a tag mid-sentence is\n * payload, not syntax.\n */\nfunction keepContextMarker(line: string): \"open\" | \"close\" | undefined {\n\tconst body = line.replace(ROLE_HEADER_RE, \"\").trim();\n\tif (KEEP_CONTEXT_OPEN_LINE_RE.test(body)) return \"open\";\n\tif (KEEP_CONTEXT_CLOSE_LINE_RE.test(body)) return \"close\";\n\treturn undefined;\n}\n\n/** Message roles whose payload is external, so its tag text is data rather than syntax. */\nconst UNTRUSTED_MARKER_ROLE = \"Tool result\";\n\n/**\n * Whether a message role may declare protection.\n *\n * User and assistant messages both may. Prompt construction — stage prompts, run inputs, and\n * steering — arrives as user messages, and agents need protection in their own output too, to\n * restate a contract amendment in a handoff report or pin a decision that changes later\n * behavior. A user-only rule would make those inert while still looking correct at the call site.\n *\n * Tool results may not. Their payload is file contents, fetched pages, and command output —\n * bytes an attacker can choose — and honoring tags there would let read material mark itself\n * unreclaimable and persist through compaction ahead of real transcript content. An agent that\n * wants to keep something it read can restate it in its own message, which is also the more\n * selective habit.\n *\n * An undefined role is the prior compaction summary prepended ahead of the first role header.\n * That is compaction's own output, and honoring it is what lets a span re-arm on later\n * boundaries after its header line has itself been compacted away.\n */\nfunction roleMayProtect(role: string | undefined): boolean {\n\treturn role !== UNTRUSTED_MARKER_ROLE;\n}\n\n/**\n * One-based line numbers covered by `<keepContext>` spans, inclusive of the tag lines.\n *\n * Spans are scoped to a single message: a role header ends any span still open, and an unclosed\n * span protects through the end of its own message rather than the end of the region. Together\n * with the whole-line marker rule and the tool-result exclusion, that keeps the permissive\n * unclosed case safe — quoted or injected tag text costs at most its own message instead of\n * everything after it. Compaction that cannot reclaim is an overflow, not a safe failure.\n *\n * Nested openers flatten into the outermost span, and a closing tag with no opener is inert.\n */\nexport function keepContextLineNumbers(lines: readonly string[]): Set<number> {\n\tconst protectedLines = new Set<number>();\n\tlet openIndex: number | undefined;\n\tlet role: string | undefined;\n\tconst protectThrough = (endIndex: number): void => {\n\t\tif (openIndex === undefined) return;\n\t\tfor (let line = openIndex; line <= endIndex; line++) protectedLines.add(line + 1);\n\t\topenIndex = undefined;\n\t};\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst line = lines[index];\n\t\tconst header = ROLE_HEADER_RE.exec(line);\n\t\tif (header) {\n\t\t\tprotectThrough(index - 1);\n\t\t\trole = header[1];\n\t\t}\n\t\tif (!roleMayProtect(role)) continue;\n\t\tconst marker = keepContextMarker(line);\n\t\tif (marker === \"open\") {\n\t\t\tif (openIndex === undefined) openIndex = index;\n\t\t\tcontinue;\n\t\t}\n\t\tif (marker === \"close\") protectThrough(index);\n\t}\n\tprotectThrough(lines.length - 1);\n\treturn protectedLines;\n}\n\nexport function createNumberedRegion(text: string, protectedLineNumbers?: ReadonlySet<number>): NumberedRegion {\n\tconst lines = text.split(\"\\n\");\n\tconst headerLineNumbers = new Set<number>();\n\tconst priorMarkerNs = new Map<number, number>();\n\tfor (let index = 0; index < lines.length; index++) {\n\t\tconst lineNumber = index + 1;\n\t\tif (ROLE_HEADER_RE.test(lines[index])) headerLineNumbers.add(lineNumber);\n\t\tconst markerMatch = FILTERED_MARKER_RE.exec(lines[index]);\n\t\tif (markerMatch) priorMarkerNs.set(lineNumber, Number(markerMatch[1]));\n\t}\n\tconst detected = keepContextLineNumbers(lines);\n\tconst merged =\n\t\tprotectedLineNumbers === undefined ? detected : new Set<number>([...protectedLineNumbers, ...detected]);\n\treturn {\n\t\t__brand: \"NumberedRegion\",\n\t\tlines,\n\t\theaderLineNumbers,\n\t\tpriorMarkerNs,\n\t\tprotectedLineNumbers: merged.size > 0 ? merged : undefined,\n\t\ttokenEstimate: Math.ceil(text.length / 4),\n\t};\n}\n\nexport function createConversationRegion(\n\tmessages: Message[],\n\tpreviousSummary?: string,\n\tlocators?: FullOutputLocators,\n): NumberedRegion {\n\tconst sections: { role: \"user\" | \"assistant\" | \"tool\"; text: string }[] = [];\n\tif (previousSummary) sections.push({ role: \"assistant\", text: previousSummary });\n\tfor (const message of messages) {\n\t\tconst text = serializeConversationForCompaction([message], locators);\n\t\tif (text)\n\t\t\tsections.push({\n\t\t\t\trole: message.role === \"toolResult\" ? \"tool\" : message.role === \"user\" ? \"user\" : \"assistant\",\n\t\t\t\ttext,\n\t\t\t});\n\t}\n\tconst lines: string[] = [];\n\tconst messageSpans: NonNullable<NumberedRegion[\"messageSpans\"]> = [];\n\tfor (let index = 0; index < sections.length; index++) {\n\t\tconst section = sections[index];\n\t\tconst start = lines.length + 1;\n\t\tlines.push(...section.text.split(\"\\n\"));\n\t\tif (index < sections.length - 1 && !(index === 0 && previousSummary)) lines.push(\"\");\n\t\tmessageSpans.push({ role: section.role, start, end: lines.length });\n\t}\n\tconst region = createNumberedRegion(lines.join(\"\\n\"));\n\tregion.messageSpans = messageSpans.length > 0 ? messageSpans : [{ role: \"assistant\", start: 1, end: 1 }];\n\treturn region;\n}\n\nexport function numberRegionLines(region: NumberedRegion, start = 1, end = region.lines.length): string {\n\tconst first = Math.max(1, Math.trunc(start));\n\tconst last = Math.min(region.lines.length, Math.trunc(end));\n\tif (first > last) return \"\";\n\treturn region.lines\n\t\t.slice(first - 1, last)\n\t\t.map((line, index) => `${first + index}${LINE_NUMBER_SEPARATOR}${line}`)\n\t\t.join(\"\\n\");\n}\n"]}
|
package/dist/core/messages.d.ts
CHANGED
|
@@ -67,14 +67,18 @@ export declare function messageIsLlmVisible(message: AgentMessage, deletedBlockI
|
|
|
67
67
|
export declare function bashExecutionToText(msg: BashExecutionMessage): string;
|
|
68
68
|
export declare const VERBATIM_COMPACTION_PREFIX = "The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked \"(filtered N lines)\".\n\n";
|
|
69
69
|
export declare const SUMMARY_COMPACTION_PREFIX = "The following is a summary of the earlier conversation:\n\n";
|
|
70
|
+
export declare function verbatimRecallHint(sessionId: string): string;
|
|
71
|
+
/** Drop the verbatim boundary prefix and, when present, the history recall hint that follows it. */
|
|
72
|
+
export declare function stripVerbatimCompactionPrefix(text: string): string;
|
|
70
73
|
export declare function isVerbatimCompactionMessage(message: CustomMessage): boolean;
|
|
71
74
|
/**
|
|
72
75
|
* Create the visible custom-role boundary used to replay a verbatim compaction.
|
|
73
76
|
*
|
|
74
77
|
* `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and
|
|
75
78
|
* its image blocks stay intact, so preserved content is not reduced to a placeholder.
|
|
79
|
+
* When `sessionId` is given, a verbatim boundary also tells the agent where removed lines can be recalled.
|
|
76
80
|
*/
|
|
77
|
-
export declare function createVerbatimCompactionMessage(compactedText: string, tokensBefore: number, timestamp: string, details?: unknown, retainedTail?: readonly (TextContent | ImageContent)[]): CustomMessage;
|
|
81
|
+
export declare function createVerbatimCompactionMessage(compactedText: string, tokensBefore: number, timestamp: string, details?: unknown, retainedTail?: readonly (TextContent | ImageContent)[], sessionId?: string): CustomMessage;
|
|
78
82
|
export declare function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage;
|
|
79
83
|
/** Convert CustomMessageEntry to AgentMessage format */
|
|
80
84
|
export declare function createCustomMessage(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details: unknown | undefined, timestamp: string, excludeFromContext?: boolean, stageAdmissionKey?: string): StageAdmittedCustomMessage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACnG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,eAAO,MAAM,qBAAqB,iGAGjC,CAAC;AAEF,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAA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C,CAAC;CAC1C;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,SAAS,YAAY,EACpE,QAAQ,EAAE,QAAQ,EAAE,EACpB,OAAO,GAAE,yBAA8B,GACrC,CAAC,QAAQ,GAAG,iBAAiB,CAAC,EAAE,CAsElC;AAID;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,EAAE,CAiDhE"}
|
package/dist/core/messages.js
CHANGED
|
@@ -113,8 +113,24 @@ export function bashExecutionToText(msg) {
|
|
|
113
113
|
return text;
|
|
114
114
|
}
|
|
115
115
|
export const VERBATIM_COMPACTION_PREFIX = 'The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked "(filtered N lines)".\n\n';
|
|
116
|
+
const VERBATIM_RECALL_HINT_PATTERN = /^Removed lines remain in this session's history at history:\/\/sessions\/\S+\. Use `search`[\s\S]*?\n\n/;
|
|
116
117
|
export const SUMMARY_COMPACTION_PREFIX = "The following is a summary of the earlier conversation:\n\n";
|
|
117
118
|
const verbatimCompactionMessages = new WeakSet();
|
|
119
|
+
export function verbatimRecallHint(sessionId) {
|
|
120
|
+
const url = `history://sessions/${sessionId}`;
|
|
121
|
+
const lines = [
|
|
122
|
+
`Removed lines remain in this session's history at ${url}. Use \`search\` on that URL to find removed text, including text removed in this session's earlier compaction cycles, then \`read\` with \`:N-M\` to open it.`,
|
|
123
|
+
"You can also recall relevant findings from the project's other sessions (`search history://sessions`) and from workflow runs (`search history://workflows`, or `search history://` for both). Do this before redoing an investigation, or when a removed decision, error message, file path or result matters.",
|
|
124
|
+
"A search over several records covers the newest ones by default; page on with `?offset=`.",
|
|
125
|
+
];
|
|
126
|
+
return `${lines.join("\n")}\n\n`;
|
|
127
|
+
}
|
|
128
|
+
/** Drop the verbatim boundary prefix and, when present, the history recall hint that follows it. */
|
|
129
|
+
export function stripVerbatimCompactionPrefix(text) {
|
|
130
|
+
if (!text.startsWith(VERBATIM_COMPACTION_PREFIX))
|
|
131
|
+
return text;
|
|
132
|
+
return text.slice(VERBATIM_COMPACTION_PREFIX.length).replace(VERBATIM_RECALL_HINT_PATTERN, "");
|
|
133
|
+
}
|
|
118
134
|
export function isVerbatimCompactionMessage(message) {
|
|
119
135
|
return verbatimCompactionMessages.has(message);
|
|
120
136
|
}
|
|
@@ -123,11 +139,13 @@ export function isVerbatimCompactionMessage(message) {
|
|
|
123
139
|
*
|
|
124
140
|
* `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and
|
|
125
141
|
* its image blocks stay intact, so preserved content is not reduced to a placeholder.
|
|
142
|
+
* When `sessionId` is given, a verbatim boundary also tells the agent where removed lines can be recalled.
|
|
126
143
|
*/
|
|
127
|
-
export function createVerbatimCompactionMessage(compactedText, tokensBefore, timestamp, details, retainedTail) {
|
|
128
|
-
const
|
|
144
|
+
export function createVerbatimCompactionMessage(compactedText, tokensBefore, timestamp, details, retainedTail, sessionId) {
|
|
145
|
+
const isSummary = typeof details === "object" && details !== null && "backend" in details && details.backend === "summary";
|
|
146
|
+
const prefix = isSummary
|
|
129
147
|
? SUMMARY_COMPACTION_PREFIX
|
|
130
|
-
: VERBATIM_COMPACTION_PREFIX;
|
|
148
|
+
: VERBATIM_COMPACTION_PREFIX + (sessionId === undefined ? "" : verbatimRecallHint(sessionId));
|
|
131
149
|
const content = [{ type: "text", text: prefix + compactedText }];
|
|
132
150
|
for (const block of retainedTail ?? []) {
|
|
133
151
|
const last = content[content.length - 1];
|