@bastani/atomic 0.9.11 → 0.9.12-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 +13 -0
- package/dist/builtin/intercom/CHANGELOG.md +6 -0
- package/dist/builtin/intercom/closed-workflow-stage-message.ts +1 -1
- package/dist/builtin/intercom/contact-supervisor-tool.ts +1 -1
- package/dist/builtin/intercom/index-heavy.ts +2 -2
- package/dist/builtin/intercom/intercom-tool.ts +2 -2
- package/dist/builtin/intercom/intercom-utils.ts +1 -1
- package/dist/builtin/intercom/lifecycle.ts +2 -2
- package/dist/builtin/intercom/overlay.ts +2 -2
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/reply-tracker.ts +1 -1
- package/dist/builtin/intercom/subagent-relay.ts +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +6 -0
- package/dist/builtin/mcp/apps-cancellation.ts +1 -1
- package/dist/builtin/mcp/commands.ts +7 -7
- package/dist/builtin/mcp/direct-tool-executor.ts +1 -1
- package/dist/builtin/mcp/direct-tools.ts +3 -3
- package/dist/builtin/mcp/host-html-template.ts +1 -1
- package/dist/builtin/mcp/index.ts +3 -3
- package/dist/builtin/mcp/init.ts +6 -6
- package/dist/builtin/mcp/mcp-auth-flow.ts +1 -1
- package/dist/builtin/mcp/mcp-callback-server.ts +1 -1
- package/dist/builtin/mcp/mcp-panel-state.ts +1 -1
- package/dist/builtin/mcp/mcp-panel.ts +1 -1
- package/dist/builtin/mcp/metadata-cache.ts +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/mcp/proxy-call.ts +2 -2
- package/dist/builtin/mcp/proxy-info-modes.ts +2 -2
- package/dist/builtin/mcp/sampling-handler.ts +1 -1
- package/dist/builtin/mcp/server-manager.ts +3 -3
- package/dist/builtin/mcp/startup-warmup.ts +5 -5
- package/dist/builtin/mcp/state.ts +1 -1
- package/dist/builtin/mcp/tool-call-timeout.ts +1 -1
- package/dist/builtin/mcp/tool-metadata.ts +2 -2
- package/dist/builtin/mcp/types.ts +1 -1
- package/dist/builtin/mcp/ui-server.ts +4 -4
- package/dist/builtin/mcp/ui-session.ts +3 -3
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/runs/background/result-delivery-processor.ts +5 -5
- package/dist/builtin/subagents/src/runs/background/result-file-claims.ts +1 -1
- package/dist/builtin/subagents/src/runs/background/result-status.ts +2 -2
- package/dist/builtin/subagents/src/runs/background/result-watcher-data.ts +2 -2
- package/dist/builtin/subagents/src/runs/background/result-watcher.ts +1 -1
- package/dist/builtin/subagents/src/runs/foreground/execution-detach-reservations.ts +1 -1
- package/dist/builtin/subagents/src/shared/artifacts.ts +1 -1
- package/dist/builtin/web-access/CHANGELOG.md +6 -0
- package/dist/builtin/web-access/index-heavy.ts +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +11 -0
- package/dist/builtin/workflows/README.md +1 -1
- package/dist/builtin/workflows/builtin/goal-prompts.ts +4 -1
- package/dist/builtin/workflows/builtin/ralph-core.ts +7 -4
- package/dist/builtin/workflows/builtin/ralph-forked-prompts.ts +5 -2
- package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +2 -1
- package/dist/builtin/workflows/builtin/ralph-runner.ts +2 -1
- package/dist/builtin/workflows/builtin/shared-prompts.ts +34 -7
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/authoring/keep-context.ts +46 -0
- package/dist/builtin/workflows/src/authoring.d.ts +11 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +35 -17
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +4 -0
- package/dist/builtin/workflows/src/sdk-surface.ts +1 -0
- package/dist/core/agent-session-methods.d.ts +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/async/session-manager.d.ts +1 -1
- package/dist/core/async/session-manager.js.map +1 -1
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts +2 -2
- package/dist/core/compaction/compaction-boundary.js.map +1 -1
- package/dist/core/compaction/compaction-parameters.d.ts +5 -0
- package/dist/core/compaction/compaction-parameters.d.ts.map +1 -1
- package/dist/core/compaction/compaction-parameters.js +6 -5
- package/dist/core/compaction/compaction-parameters.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts +4 -0
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js +5 -1
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +7 -1
- package/dist/core/compaction/compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
- package/dist/core/compaction/deleted-ranges.js +2 -0
- package/dist/core/compaction/deleted-ranges.js.map +1 -1
- package/dist/core/compaction/fallback-planner.d.ts +1 -1
- package/dist/core/compaction/fallback-planner.js.map +1 -1
- package/dist/core/compaction/range-planner.d.ts +3 -3
- package/dist/core/compaction/range-planner.d.ts.map +1 -1
- package/dist/core/compaction/range-planner.js +12 -14
- package/dist/core/compaction/range-planner.js.map +1 -1
- package/dist/core/compaction/transcript-serialization.d.ts +12 -0
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
- package/dist/core/compaction/transcript-serialization.js +99 -1
- package/dist/core/compaction/transcript-serialization.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +3 -0
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +16 -0
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/tools/bash-async-execution.d.ts +1 -1
- package/dist/core/tools/bash-async-execution.js.map +1 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/oversized-tool-result.js.map +1 -1
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/llama/huggingface-ui.d.ts +2 -2
- package/dist/extensions/llama/huggingface-ui.js.map +1 -1
- package/dist/extensions/llama/index.d.ts +1 -1
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts +1 -1
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/modes/interactive-engine/remote-queue-pause.d.ts +1 -1
- package/dist/modes/interactive-engine/remote-queue-pause.js.map +1 -1
- package/docs/compaction.md +24 -0
- package/docs/workflows.md +56 -0
- package/npm-shrinkwrap.json +39 -39
- package/package.json +3 -3
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
export const FILTERED_MARKER_RE = /^\(filtered (\d+) lines\)$/;
|
|
2
2
|
export const LINE_NUMBER_SEPARATOR = "→";
|
|
3
3
|
export const ROLE_HEADER_RE = /^\[(User|Assistant|Assistant thinking|Assistant tool calls|Tool result)\]: /;
|
|
4
|
+
/**
|
|
5
|
+
* Callers wrap never-compressible content in `<keepContext>` / `</keepContext>`. Every line of
|
|
6
|
+
* such a span, tag lines included, becomes a protected line, so the span survives verbatim
|
|
7
|
+
* regardless of the compression ratio. Protecting the tags themselves is what makes the span
|
|
8
|
+
* re-detectable on the next boundary, since each compaction re-ranks the previous output.
|
|
9
|
+
*
|
|
10
|
+
* The region is untrusted: it is serialized user, assistant, and tool-result payload, and a
|
|
11
|
+
* message may quote or document the tag text. Detection is therefore deliberately narrow — a
|
|
12
|
+
* marker must be the entire line once an optional role header is stripped, and only a matched
|
|
13
|
+
* open/close pair protects anything. Prose that merely mentions a tag matches nothing, and an
|
|
14
|
+
* unmatched opener protects nothing rather than swallowing the rest of the region.
|
|
15
|
+
*/
|
|
16
|
+
const KEEP_CONTEXT_OPEN_LINE_RE = /^<keepContext>$/i;
|
|
17
|
+
const KEEP_CONTEXT_CLOSE_LINE_RE = /^<\/keepContext>$/i;
|
|
4
18
|
const TOOL_RESULT_MAX_CHARS = 16_000;
|
|
5
19
|
export function filteredMarker(lineCount) {
|
|
6
20
|
return `(filtered ${lineCount} lines)`;
|
|
@@ -121,6 +135,88 @@ export function serializeConversationForCompaction(messages) {
|
|
|
121
135
|
export function serializeRetainedTranscript(messages) {
|
|
122
136
|
return serializeTranscriptChunks(messages, "retained");
|
|
123
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Classify a line as a `keepContext` marker.
|
|
140
|
+
*
|
|
141
|
+
* The serializer prefixes the first line of a message with its role header, so a span opened at
|
|
142
|
+
* the start of a stage prompt arrives as `[User]: <keepContext>`. The header is stripped before
|
|
143
|
+
* matching, and the remainder must be the whole line — prose that mentions a tag mid-sentence is
|
|
144
|
+
* payload, not syntax.
|
|
145
|
+
*/
|
|
146
|
+
function keepContextMarker(line) {
|
|
147
|
+
const body = line.replace(ROLE_HEADER_RE, "").trim();
|
|
148
|
+
if (KEEP_CONTEXT_OPEN_LINE_RE.test(body))
|
|
149
|
+
return "open";
|
|
150
|
+
if (KEEP_CONTEXT_CLOSE_LINE_RE.test(body))
|
|
151
|
+
return "close";
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
/** Message roles whose payload is external, so its tag text is data rather than syntax. */
|
|
155
|
+
const UNTRUSTED_MARKER_ROLE = "Tool result";
|
|
156
|
+
/**
|
|
157
|
+
* Whether a message role may declare protection.
|
|
158
|
+
*
|
|
159
|
+
* User and assistant messages both may. Prompt construction — stage prompts, run inputs, and
|
|
160
|
+
* steering — arrives as user messages, and agents need protection in their own output too, to
|
|
161
|
+
* restate a contract amendment in a handoff report or pin a decision that changes later
|
|
162
|
+
* behavior. A user-only rule would make those inert while still looking correct at the call site.
|
|
163
|
+
*
|
|
164
|
+
* Tool results may not. Their payload is file contents, fetched pages, and command output —
|
|
165
|
+
* bytes an attacker can choose — and honoring tags there would let read material mark itself
|
|
166
|
+
* unreclaimable and persist through compaction ahead of real transcript content. An agent that
|
|
167
|
+
* wants to keep something it read can restate it in its own message, which is also the more
|
|
168
|
+
* selective habit.
|
|
169
|
+
*
|
|
170
|
+
* An undefined role is the prior compaction summary prepended ahead of the first role header.
|
|
171
|
+
* That is compaction's own output, and honoring it is what lets a span re-arm on later
|
|
172
|
+
* boundaries after its header line has itself been compacted away.
|
|
173
|
+
*/
|
|
174
|
+
function roleMayProtect(role) {
|
|
175
|
+
return role !== UNTRUSTED_MARKER_ROLE;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* One-based line numbers covered by `<keepContext>` spans, inclusive of the tag lines.
|
|
179
|
+
*
|
|
180
|
+
* Spans are scoped to a single message: a role header ends any span still open, and an unclosed
|
|
181
|
+
* span protects through the end of its own message rather than the end of the region. Together
|
|
182
|
+
* with the whole-line marker rule and the tool-result exclusion, that keeps the permissive
|
|
183
|
+
* unclosed case safe — quoted or injected tag text costs at most its own message instead of
|
|
184
|
+
* everything after it. Compaction that cannot reclaim is an overflow, not a safe failure.
|
|
185
|
+
*
|
|
186
|
+
* Nested openers flatten into the outermost span, and a closing tag with no opener is inert.
|
|
187
|
+
*/
|
|
188
|
+
export function keepContextLineNumbers(lines) {
|
|
189
|
+
const protectedLines = new Set();
|
|
190
|
+
let openIndex;
|
|
191
|
+
let role;
|
|
192
|
+
const protectThrough = (endIndex) => {
|
|
193
|
+
if (openIndex === undefined)
|
|
194
|
+
return;
|
|
195
|
+
for (let line = openIndex; line <= endIndex; line++)
|
|
196
|
+
protectedLines.add(line + 1);
|
|
197
|
+
openIndex = undefined;
|
|
198
|
+
};
|
|
199
|
+
for (let index = 0; index < lines.length; index++) {
|
|
200
|
+
const line = lines[index];
|
|
201
|
+
const header = ROLE_HEADER_RE.exec(line);
|
|
202
|
+
if (header) {
|
|
203
|
+
protectThrough(index - 1);
|
|
204
|
+
role = header[1];
|
|
205
|
+
}
|
|
206
|
+
if (!roleMayProtect(role))
|
|
207
|
+
continue;
|
|
208
|
+
const marker = keepContextMarker(line);
|
|
209
|
+
if (marker === "open") {
|
|
210
|
+
if (openIndex === undefined)
|
|
211
|
+
openIndex = index;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (marker === "close")
|
|
215
|
+
protectThrough(index);
|
|
216
|
+
}
|
|
217
|
+
protectThrough(lines.length - 1);
|
|
218
|
+
return protectedLines;
|
|
219
|
+
}
|
|
124
220
|
export function createNumberedRegion(text, protectedLineNumbers) {
|
|
125
221
|
const lines = text.split("\n");
|
|
126
222
|
const headerLineNumbers = new Set();
|
|
@@ -133,12 +229,14 @@ export function createNumberedRegion(text, protectedLineNumbers) {
|
|
|
133
229
|
if (markerMatch)
|
|
134
230
|
priorMarkerNs.set(lineNumber, Number(markerMatch[1]));
|
|
135
231
|
}
|
|
232
|
+
const detected = keepContextLineNumbers(lines);
|
|
233
|
+
const merged = protectedLineNumbers === undefined ? detected : new Set([...protectedLineNumbers, ...detected]);
|
|
136
234
|
return {
|
|
137
235
|
__brand: "NumberedRegion",
|
|
138
236
|
lines,
|
|
139
237
|
headerLineNumbers,
|
|
140
238
|
priorMarkerNs,
|
|
141
|
-
protectedLineNumbers,
|
|
239
|
+
protectedLineNumbers: merged.size > 0 ? merged : undefined,
|
|
142
240
|
tokenEstimate: Math.ceil(text.length / 4),
|
|
143
241
|
};
|
|
144
242
|
}
|
|
@@ -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,6EAA6E,CAAC;AAE5G,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAYrC,MAAM,UAAU,cAAc,CAAC,SAAiB;IAC/C,OAAO,aAAa,SAAS,SAAS,CAAC;AACxC,CAAC;AAED,S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AAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACxE,CAAC;IACD,OAAO;QACN,OAAO,EAAE,gBAAgB;QACzB,KAAK;QACL,iBAAiB;QACjB,aAAa;QACb,oBAAoB;QACpB,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;KACzC,CAAC;AACH,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 \"@earendil-works/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 thinking|Assistant tool calls|Tool result)\\]: /;\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.\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/** Serialize provider messages into transcript chunks using the durable section grammar. */\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 thinking: 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 === \"thinking\") thinking.push(block.thinking);\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 (thinking.length > 0) pushSection(\"[Assistant thinking]: \", [{ type: \"text\", text: thinking.join(\"\\n\") }]);\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.\n */\nexport function serializeRetainedTranscript(messages: Message[]): TranscriptChunk[] {\n\treturn serializeTranscriptChunks(messages, \"retained\");\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\treturn {\n\t\t__brand: \"NumberedRegion\",\n\t\tlines,\n\t\theaderLineNumbers,\n\t\tpriorMarkerNs,\n\t\tprotectedLineNumbers,\n\t\ttokenEstimate: Math.ceil(text.length / 4),\n\t};\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,6EAA6E,CAAC;AAE5G;;;;;;;;;;;GAWG;AACH,MAAM,yBAAyB,GAAG,kBAAkB,CAAC;AACrD,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAExD,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAYrC,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,CAAC,MAAM,GAAG,qBAAqB,6BAA6B,CAAC;AAC5H,CAAC;AAED,SAAS,SAAS,CAAC,MAAyB;IAC3C,OAAO,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClE,CAAC;AAED,SAAS,UAAU,CAAC,MAAyB,EAAE,IAAY;IAC1D,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAC9B,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;IAC/B,IAAI,IAAI,KAAK,SAAS,IA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,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,MAAM,GACX,oBAAoB,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAS,CAAC,GAAG,oBAAoB,EAAE,GAAG,QAAQ,CAAC,CAAC,CAAC;IACzG,OAAO;QACN,OAAO,EAAE,gBAAgB;QACzB,KAAK;QACL,iBAAiB;QACjB,aAAa;QACb,oBAAoB,EAAE,MAAM,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;QAC1D,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;KACzC,CAAC;AACH,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 \"@earendil-works/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 thinking|Assistant tool calls|Tool result)\\]: /;\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.\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/** Serialize provider messages into transcript chunks using the durable section grammar. */\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 thinking: 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 === \"thinking\") thinking.push(block.thinking);\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 (thinking.length > 0) pushSection(\"[Assistant thinking]: \", [{ type: \"text\", text: thinking.join(\"\\n\") }]);\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.\n */\nexport function serializeRetainedTranscript(messages: Message[]): TranscriptChunk[] {\n\treturn serializeTranscriptChunks(messages, \"retained\");\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 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"]}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
5
5
|
import type { Message } from "@earendil-works/pi-ai/compat";
|
|
6
|
+
import type { LineRange } from "./compaction-types.js";
|
|
6
7
|
export interface FileOperations {
|
|
7
8
|
read: Set<string>;
|
|
8
9
|
written: Set<string>;
|
|
@@ -35,4 +36,6 @@ export declare function formatFileOperations(readFiles: string[], modifiedFiles:
|
|
|
35
36
|
*/
|
|
36
37
|
export declare function serializeConversation(messages: Message[]): string;
|
|
37
38
|
export declare const SUMMARIZATION_SYSTEM_PROMPT = "You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.";
|
|
39
|
+
/** Collapse a sparse set of line numbers into ascending contiguous inclusive ranges. */
|
|
40
|
+
export declare function contiguousRanges(lines: ReadonlySet<number>): LineRange[];
|
|
38
41
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAMvD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpB;AAED,wBAAgB,aAAa,IAAI,cAAc,CAM9C;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CA2B9F;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG;IAAE,SAAS,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAA;CAAE,CAK1G;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,CAUzF;AAmBD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAqDjE;AAMD,eAAO,MAAM,2BAA2B,6TAEmF,CAAC;AAM5H,wFAAwF;AACxF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,EAAE,CASxE"}
|
|
@@ -150,4 +150,20 @@ export function serializeConversation(messages) {
|
|
|
150
150
|
export const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
|
|
151
151
|
|
|
152
152
|
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
|
|
153
|
+
// ============================================================================
|
|
154
|
+
// Line Range Helpers
|
|
155
|
+
// ============================================================================
|
|
156
|
+
/** Collapse a sparse set of line numbers into ascending contiguous inclusive ranges. */
|
|
157
|
+
export function contiguousRanges(lines) {
|
|
158
|
+
const sorted = [...lines].sort((left, right) => left - right);
|
|
159
|
+
const ranges = [];
|
|
160
|
+
for (const line of sorted) {
|
|
161
|
+
const last = ranges[ranges.length - 1];
|
|
162
|
+
if (last && line === last.end + 1)
|
|
163
|
+
last.end = line;
|
|
164
|
+
else
|
|
165
|
+
ranges.push({ start: line, end: line });
|
|
166
|
+
}
|
|
167
|
+
return ranges;
|
|
168
|
+
}
|
|
153
169
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAeH,MAAM,UAAU,aAAa;IAC5B,OAAO;QACN,IAAI,EAAE,IAAI,GAAG,EAAE;QACf,OAAO,EAAE,IAAI,GAAG,EAAE;QAClB,MAAM,EAAE,IAAI,GAAG,EAAE;KACjB,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB,EAAE,OAAuB;IACvF,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO;IACzC,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO;IAEvE,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QACrC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;YAAE,SAAS;QAC1D,IAAI,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;YAAE,SAAS;QAC9D,IAAI,CAAC,CAAC,WAAW,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,IAAI,K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AG,CAAC,EAAE,CAAC;gBAC9B,KAAK,CAAC,IAAI,CAAC,yBAAyB,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACjE,CAAC;YACD,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC1B,KAAK,CAAC,IAAI,CAAC,gBAAgB,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACpD,CAAC;YACD,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC1B,KAAK,CAAC,IAAI,CAAC,2BAA2B,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YAC/D,CAAC;QACF,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YACtC,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO;iBACzB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;iBACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBAClB,IAAI,CAAC,EAAE,CAAC,CAAC;YACX,IAAI,OAAO,EAAE,CAAC;gBACb,KAAK,CAAC,IAAI,CAAC,kBAAkB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,CAAC;YACpF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E,MAAM,CAAC,MAAM,2BAA2B,GAAG;;2HAEgF,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Message } from \"@earendil-works/pi-ai/compat\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from tool calls in an assistant message.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\tconst args = block.arguments as Record<string, unknown> | undefined;\n\t\tif (!args) continue;\n\n\t\tconst path = typeof args.path === \"string\" ? args.path : undefined;\n\t\tif (!path) continue;\n\n\t\tswitch (block.name) {\n\t\t\tcase \"read\":\n\t\t\t\tfileOps.read.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"write\":\n\t\t\t\tfileOps.written.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"edit\":\n\t\t\t\tfileOps.edited.add(path);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst thinkingParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tthinkingParts.push(block.thinking);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (thinkingParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant thinking]: ${thinkingParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAgBH,MAAM,UAAU,aAAa;IAC5B,OAAO;QACN,IAAI,EAAE,IAAI,GAAG,EAAE;QACf,OAAO,EAAE,IAAI,GAAG,EAAE;QAClB,MAAM,EAAE,IAAI,GAAG,EAAE;KACjB,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB,EA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C,EAAE,CAAC,CAAC;YACX,IAAI,OAAO,EAAE,CAAC;gBACb,KAAK,CAAC,IAAI,CAAC,kBAAkB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,CAAC;YACpF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E,MAAM,CAAC,MAAM,2BAA2B,GAAG;;2HAEgF,CAAC;AAE5H,+EAA+E;AAC/E,qBAAqB;AACrB,+EAA+E;AAE/E,wFAAwF;AACxF,MAAM,UAAU,gBAAgB,CAAC,KAA0B;IAC1D,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC;IAC9D,MAAM,MAAM,GAAgB,EAAE,CAAC;IAC/B,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACvC,IAAI,IAAI,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC;YAAE,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC;;YAC9C,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Message } from \"@earendil-works/pi-ai/compat\";\nimport type { LineRange } from \"./compaction-types.js\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from tool calls in an assistant message.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\tconst args = block.arguments as Record<string, unknown> | undefined;\n\t\tif (!args) continue;\n\n\t\tconst path = typeof args.path === \"string\" ? args.path : undefined;\n\t\tif (!path) continue;\n\n\t\tswitch (block.name) {\n\t\t\tcase \"read\":\n\t\t\t\tfileOps.read.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"write\":\n\t\t\t\tfileOps.written.add(path);\n\t\t\t\tbreak;\n\t\t\tcase \"edit\":\n\t\t\t\tfileOps.edited.add(path);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst thinkingParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tthinkingParts.push(block.thinking);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (thinkingParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant thinking]: ${thinkingParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n\n// ============================================================================\n// Line Range Helpers\n// ============================================================================\n\n/** Collapse a sparse set of line numbers into ascending contiguous inclusive ranges. */\nexport function contiguousRanges(lines: ReadonlySet<number>): LineRange[] {\n\tconst sorted = [...lines].sort((left, right) => left - right);\n\tconst ranges: LineRange[] = [];\n\tfor (const line of sorted) {\n\t\tconst last = ranges[ranges.length - 1];\n\t\tif (last && line === last.end + 1) last.end = line;\n\t\telse ranges.push({ start: line, end: line });\n\t}\n\treturn ranges;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-manager-history.js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C,IAAI,CAAC,IAAI,CAAC,CAAC;YAC5B,CAAC;iBAAM,CAAC;gBACP,yBAAyB;gBACzB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAClB,CAAC;QACF,CAAC;IACF,CAAC;IAED,8DAA8D;IAC9D,+DAA+D;IAC/D,MAAM,KAAK,GAAsB,CAAC,GAAG,KAAK,CAAC,CAAC;IAC5C,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,EAAG,CAAC;QAC1B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5G,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { VerbatimCompactionDetails } from \"./compaction/compaction-types.js\";\nimport { serializeRetainedTranscript, type TranscriptChunk } from \"./compaction/transcript-serialization.ts\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tcreateVerbatimCompactionMessage,\n\tnormalizeMessageContent,\n} from \"./messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"./session-entry-normalization.ts\";\nimport type {\n\tCompactionEntry,\n\tFileEntry,\n\tSessionContext,\n\tSessionEntry,\n\tSessionTreeNode,\n} from \"./session-manager-types.ts\";\n\n/** Build the single context message a durable entry contributes, if any. */\nfunction contextMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return normalizeMessageContent(entry.message);\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t\tentry.stageAdmissionKey,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\" && entry.summary.length > 0) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\n/**\n * Serialize the kept tail into the compaction boundary's transcript grammar.\n *\n * The tail is concatenated onto the end of the boundary string instead of being\n * replayed as structured messages. A tail that starts mid-turn (a tool result whose\n * tool call was compacted away, or a trailing unanswered tool call) would otherwise\n * emit ill-ordered provider blocks and fail the request. Serialization is lossless:\n * tool results keep their full text and images stay as image blocks, because the tail\n * is exactly the span `preserve_recent` promised to keep.\n */\nfunction serializeKeptTail(entries: SessionEntry[]): TranscriptChunk[] {\n\tconst messages: AgentMessage[] = [];\n\tfor (const entry of entries) {\n\t\tconst message = contextMessageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\tif (messages.length === 0) return [];\n\treturn serializeRetainedTranscript(convertToLlm(messages));\n}\n\nexport function getLatestCompactionBoundaryEntry(\n\tentries: SessionEntry[],\n): CompactionEntry<VerbatimCompactionDetails> | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"compaction\") continue;\n\t\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\t\tif (details?.strategy === \"verbatim-lines\") return entry as CompactionEntry<VerbatimCompactionDetails>;\n\t}\n\treturn null;\n}\n\n/** Convert one durable session entry into the messages it contributes to model context. */\nexport function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[] {\n\tif (entry.type === \"message\") return [normalizeMessageContent(entry.message)];\n\tif (entry.type === \"custom_message\") {\n\t\treturn [\n\t\t\tcreateCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t\tentry.stageAdmissionKey,\n\t\t\t),\n\t\t];\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary.length > 0) {\n\t\treturn [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n\t}\n\tif (entry.type === \"compaction\") {\n\t\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\t\tif (details?.strategy === \"verbatim-lines\") {\n\t\t\treturn [\n\t\t\t\tcreateVerbatimCompactionMessage(\n\t\t\t\t\tentry.summary,\n\t\t\t\t\tentry.tokensBefore,\n\t\t\t\t\tentry.timestamp,\n\t\t\t\t\tentry.details as VerbatimCompactionDetails,\n\t\t\t\t),\n\t\t\t];\n\t\t}\n\t}\n\treturn [];\n}\n\n/** Return the active branch entries after applying the latest compaction boundary. */\nexport function buildContextEntries(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId = new Map(entries.map((entry) => [entry.id, entry])),\n): SessionEntry[] {\n\tif (leafId === null) return [];\n\tconst leaf = leafId ? byId.get(leafId) : entries[entries.length - 1];\n\tif (!leaf) return [];\n\tconst path = normalizeDerivedSessionEntries(getBranchPath(leaf.id, byId));\n\tconst boundary = getLatestCompactionBoundaryEntry(path);\n\tif (!boundary) return path;\n\tconst boundaryIndex = path.findIndex((entry) => entry.id === boundary.id);\n\tconst firstKeptIndex = path.findIndex(\n\t\t(entry, index) => index < boundaryIndex && entry.id === boundary.firstKeptEntryId,\n\t);\n\treturn [\n\t\tboundary,\n\t\t...(firstKeptIndex >= 0 ? path.slice(firstKeptIndex, boundaryIndex) : []),\n\t\t...path.slice(boundaryIndex + 1),\n\t];\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Emits the latest verbatim compaction boundary as one custom-role text message: the\n * compacted string with the kept tail serialized and appended to its end, rather than\n * the tail being replayed as separate structured messages.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionContext {\n\t// Build uuid index if not available\n\tif (!byId) {\n\t\tbyId = new Map<string, SessionEntry>();\n\t\tfor (const entry of entries) {\n\t\t\tbyId.set(entry.id, entry);\n\t\t}\n\t}\n\n\t// Find leaf\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\t// Explicitly null - return no messages (navigated to before first entry)\n\t\treturn { messages: [], thinkingLevel: \"off\", model: null };\n\t}\n\tif (leafId) {\n\t\tleaf = byId.get(leafId);\n\t}\n\tif (!leaf) {\n\t\t// Fallback to last entry (when leafId is undefined)\n\t\tleaf = entries[entries.length - 1];\n\t}\n\n\tif (!leaf) {\n\t\treturn { messages: [], thinkingLevel: \"off\", model: null };\n\t}\n\n\t// Walk from leaf to root, collecting path\n\tconst path = normalizeDerivedSessionEntries(getBranchPath(leaf.id, byId));\n\n\t// Extract settings\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\tconst messages: AgentMessage[] = [];\n\tconst appendMessage = (entry: SessionEntry): void => {\n\t\tconst message = contextMessageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t};\n\n\tconst boundary = getLatestCompactionBoundaryEntry(path);\n\tif (!boundary) {\n\t\tfor (const entry of path) appendMessage(entry);\n\t\treturn { messages, thinkingLevel, model };\n\t}\n\n\tconst boundaryIndex = path.findIndex((entry) => entry.id === boundary.id);\n\tconst firstKeptIndex = path.findIndex(\n\t\t(entry, index) => index < boundaryIndex && entry.id === boundary.firstKeptEntryId,\n\t);\n\tconst keptTail = firstKeptIndex >= 0 ? serializeKeptTail(path.slice(firstKeptIndex, boundaryIndex)) : [];\n\tconst separator: TranscriptChunk[] =\n\t\tkeptTail.length > 0 && boundary.summary.length > 0 ? [{ type: \"text\", text: \"\\n\\n\" }] : [];\n\tmessages.push(\n\t\tcreateVerbatimCompactionMessage(boundary.summary, boundary.tokensBefore, boundary.timestamp, boundary.details, [\n\t\t\t...separator,\n\t\t\t...keptTail,\n\t\t]),\n\t);\n\tfor (let i = boundaryIndex + 1; i < path.length; i++) appendMessage(path[i]);\n\n\treturn { messages, thinkingLevel, model };\n}\n\nexport interface SessionIndex {\n\tbyId: Map<string, SessionEntry>;\n\tlabelsById: Map<string, string>;\n\tlabelTimestampsById: Map<string, string>;\n\tleafId: string | null;\n}\n\nexport function buildSessionIndex(fileEntries: FileEntry[]): SessionIndex {\n\tconst byId = new Map<string, SessionEntry>();\n\tconst labelsById = new Map<string, string>();\n\tconst labelTimestampsById = new Map<string, string>();\n\tlet leafId: string | null = null;\n\n\tfor (const entry of fileEntries) {\n\t\tif (entry.type === \"session\") continue;\n\t\tbyId.set(entry.id, entry);\n\t\tleafId = entry.id;\n\t\tif (entry.type === \"label\") {\n\t\t\tif (entry.label) {\n\t\t\t\tlabelsById.set(entry.targetId, entry.label);\n\t\t\t\tlabelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t} else {\n\t\t\t\tlabelsById.delete(entry.targetId);\n\t\t\t\tlabelTimestampsById.delete(entry.targetId);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { byId, labelsById, labelTimestampsById, leafId };\n}\n\nexport function getBranchPath(fromId: string | null | undefined, byId: Map<string, SessionEntry>): SessionEntry[] {\n\tconst path: SessionEntry[] = [];\n\tlet current = fromId ? byId.get(fromId) : undefined;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? byId.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nexport function buildSessionTree(\n\tentries: SessionEntry[],\n\tlabelsById: ReadonlyMap<string, string>,\n\tlabelTimestampsById: ReadonlyMap<string, string>,\n): SessionTreeNode[] {\n\tconst nodeMap = new Map<string, SessionTreeNode>();\n\tconst roots: SessionTreeNode[] = [];\n\n\t// Create nodes with resolved labels\n\tfor (const entry of entries) {\n\t\tconst label = labelsById.get(entry.id);\n\t\tconst labelTimestamp = labelTimestampsById.get(entry.id);\n\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t}\n\n\t// Build tree\n\tfor (const entry of entries) {\n\t\tconst node = nodeMap.get(entry.id)!;\n\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\troots.push(node);\n\t\t} else {\n\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\tif (parent) {\n\t\t\t\tparent.children.push(node);\n\t\t\t} else {\n\t\t\t\t// Orphan - treat as root\n\t\t\t\troots.push(node);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort children by timestamp (oldest first, newest at bottom)\n\t// Use iterative approach to avoid stack overflow on deep trees\n\tconst stack: SessionTreeNode[] = [...roots];\n\twhile (stack.length > 0) {\n\t\tconst node = stack.pop()!;\n\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\tstack.push(...node.children);\n\t}\n\n\treturn roots;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session-manager-history.js","sourceRoot":"","sources":["../../src/core/session-manager-history.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAwB,MAAM,0CAA0C,CAAC;AAC7G,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,+BAA+B,EAC/B,uBAAuB,GACvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AASlF,4EAA4E;AAC5E,SAAS,uBAAuB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B,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,EAAG,CAAC;QAC1B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QAC5G,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { VerbatimCompactionDetails } from \"./compaction/compaction-types.js\";\nimport { serializeRetainedTranscript, type TranscriptChunk } from \"./compaction/transcript-serialization.js\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tcreateVerbatimCompactionMessage,\n\tnormalizeMessageContent,\n} from \"./messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"./session-entry-normalization.ts\";\nimport type {\n\tCompactionEntry,\n\tFileEntry,\n\tSessionContext,\n\tSessionEntry,\n\tSessionTreeNode,\n} from \"./session-manager-types.ts\";\n\n/** Build the single context message a durable entry contributes, if any. */\nfunction contextMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return normalizeMessageContent(entry.message);\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t\tentry.stageAdmissionKey,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\" && entry.summary.length > 0) {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\n/**\n * Serialize the kept tail into the compaction boundary's transcript grammar.\n *\n * The tail is concatenated onto the end of the boundary string instead of being\n * replayed as structured messages. A tail that starts mid-turn (a tool result whose\n * tool call was compacted away, or a trailing unanswered tool call) would otherwise\n * emit ill-ordered provider blocks and fail the request. Serialization is lossless:\n * tool results keep their full text and images stay as image blocks, because the tail\n * is exactly the span `preserve_recent` promised to keep.\n */\nfunction serializeKeptTail(entries: SessionEntry[]): TranscriptChunk[] {\n\tconst messages: AgentMessage[] = [];\n\tfor (const entry of entries) {\n\t\tconst message = contextMessageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t}\n\tif (messages.length === 0) return [];\n\treturn serializeRetainedTranscript(convertToLlm(messages));\n}\n\nexport function getLatestCompactionBoundaryEntry(\n\tentries: SessionEntry[],\n): CompactionEntry<VerbatimCompactionDetails> | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tif (entry.type !== \"compaction\") continue;\n\t\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\t\tif (details?.strategy === \"verbatim-lines\") return entry as CompactionEntry<VerbatimCompactionDetails>;\n\t}\n\treturn null;\n}\n\n/** Convert one durable session entry into the messages it contributes to model context. */\nexport function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[] {\n\tif (entry.type === \"message\") return [normalizeMessageContent(entry.message)];\n\tif (entry.type === \"custom_message\") {\n\t\treturn [\n\t\t\tcreateCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t\tentry.stageAdmissionKey,\n\t\t\t),\n\t\t];\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary.length > 0) {\n\t\treturn [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n\t}\n\tif (entry.type === \"compaction\") {\n\t\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\t\tif (details?.strategy === \"verbatim-lines\") {\n\t\t\treturn [\n\t\t\t\tcreateVerbatimCompactionMessage(\n\t\t\t\t\tentry.summary,\n\t\t\t\t\tentry.tokensBefore,\n\t\t\t\t\tentry.timestamp,\n\t\t\t\t\tentry.details as VerbatimCompactionDetails,\n\t\t\t\t),\n\t\t\t];\n\t\t}\n\t}\n\treturn [];\n}\n\n/** Return the active branch entries after applying the latest compaction boundary. */\nexport function buildContextEntries(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId = new Map(entries.map((entry) => [entry.id, entry])),\n): SessionEntry[] {\n\tif (leafId === null) return [];\n\tconst leaf = leafId ? byId.get(leafId) : entries[entries.length - 1];\n\tif (!leaf) return [];\n\tconst path = normalizeDerivedSessionEntries(getBranchPath(leaf.id, byId));\n\tconst boundary = getLatestCompactionBoundaryEntry(path);\n\tif (!boundary) return path;\n\tconst boundaryIndex = path.findIndex((entry) => entry.id === boundary.id);\n\tconst firstKeptIndex = path.findIndex(\n\t\t(entry, index) => index < boundaryIndex && entry.id === boundary.firstKeptEntryId,\n\t);\n\treturn [\n\t\tboundary,\n\t\t...(firstKeptIndex >= 0 ? path.slice(firstKeptIndex, boundaryIndex) : []),\n\t\t...path.slice(boundaryIndex + 1),\n\t];\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Emits the latest verbatim compaction boundary as one custom-role text message: the\n * compacted string with the kept tail serialized and appended to its end, rather than\n * the tail being replayed as separate structured messages.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map<string, SessionEntry>,\n): SessionContext {\n\t// Build uuid index if not available\n\tif (!byId) {\n\t\tbyId = new Map<string, SessionEntry>();\n\t\tfor (const entry of entries) {\n\t\t\tbyId.set(entry.id, entry);\n\t\t}\n\t}\n\n\t// Find leaf\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\t// Explicitly null - return no messages (navigated to before first entry)\n\t\treturn { messages: [], thinkingLevel: \"off\", model: null };\n\t}\n\tif (leafId) {\n\t\tleaf = byId.get(leafId);\n\t}\n\tif (!leaf) {\n\t\t// Fallback to last entry (when leafId is undefined)\n\t\tleaf = entries[entries.length - 1];\n\t}\n\n\tif (!leaf) {\n\t\treturn { messages: [], thinkingLevel: \"off\", model: null };\n\t}\n\n\t// Walk from leaf to root, collecting path\n\tconst path = normalizeDerivedSessionEntries(getBranchPath(leaf.id, byId));\n\n\t// Extract settings\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\tconst messages: AgentMessage[] = [];\n\tconst appendMessage = (entry: SessionEntry): void => {\n\t\tconst message = contextMessageFromEntry(entry);\n\t\tif (message) messages.push(message);\n\t};\n\n\tconst boundary = getLatestCompactionBoundaryEntry(path);\n\tif (!boundary) {\n\t\tfor (const entry of path) appendMessage(entry);\n\t\treturn { messages, thinkingLevel, model };\n\t}\n\n\tconst boundaryIndex = path.findIndex((entry) => entry.id === boundary.id);\n\tconst firstKeptIndex = path.findIndex(\n\t\t(entry, index) => index < boundaryIndex && entry.id === boundary.firstKeptEntryId,\n\t);\n\tconst keptTail = firstKeptIndex >= 0 ? serializeKeptTail(path.slice(firstKeptIndex, boundaryIndex)) : [];\n\tconst separator: TranscriptChunk[] =\n\t\tkeptTail.length > 0 && boundary.summary.length > 0 ? [{ type: \"text\", text: \"\\n\\n\" }] : [];\n\tmessages.push(\n\t\tcreateVerbatimCompactionMessage(boundary.summary, boundary.tokensBefore, boundary.timestamp, boundary.details, [\n\t\t\t...separator,\n\t\t\t...keptTail,\n\t\t]),\n\t);\n\tfor (let i = boundaryIndex + 1; i < path.length; i++) appendMessage(path[i]);\n\n\treturn { messages, thinkingLevel, model };\n}\n\nexport interface SessionIndex {\n\tbyId: Map<string, SessionEntry>;\n\tlabelsById: Map<string, string>;\n\tlabelTimestampsById: Map<string, string>;\n\tleafId: string | null;\n}\n\nexport function buildSessionIndex(fileEntries: FileEntry[]): SessionIndex {\n\tconst byId = new Map<string, SessionEntry>();\n\tconst labelsById = new Map<string, string>();\n\tconst labelTimestampsById = new Map<string, string>();\n\tlet leafId: string | null = null;\n\n\tfor (const entry of fileEntries) {\n\t\tif (entry.type === \"session\") continue;\n\t\tbyId.set(entry.id, entry);\n\t\tleafId = entry.id;\n\t\tif (entry.type === \"label\") {\n\t\t\tif (entry.label) {\n\t\t\t\tlabelsById.set(entry.targetId, entry.label);\n\t\t\t\tlabelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t} else {\n\t\t\t\tlabelsById.delete(entry.targetId);\n\t\t\t\tlabelTimestampsById.delete(entry.targetId);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { byId, labelsById, labelTimestampsById, leafId };\n}\n\nexport function getBranchPath(fromId: string | null | undefined, byId: Map<string, SessionEntry>): SessionEntry[] {\n\tconst path: SessionEntry[] = [];\n\tlet current = fromId ? byId.get(fromId) : undefined;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? byId.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nexport function buildSessionTree(\n\tentries: SessionEntry[],\n\tlabelsById: ReadonlyMap<string, string>,\n\tlabelTimestampsById: ReadonlyMap<string, string>,\n): SessionTreeNode[] {\n\tconst nodeMap = new Map<string, SessionTreeNode>();\n\tconst roots: SessionTreeNode[] = [];\n\n\t// Create nodes with resolved labels\n\tfor (const entry of entries) {\n\t\tconst label = labelsById.get(entry.id);\n\t\tconst labelTimestamp = labelTimestampsById.get(entry.id);\n\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t}\n\n\t// Build tree\n\tfor (const entry of entries) {\n\t\tconst node = nodeMap.get(entry.id)!;\n\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\troots.push(node);\n\t\t} else {\n\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\tif (parent) {\n\t\t\t\tparent.children.push(node);\n\t\t\t} else {\n\t\t\t\t// Orphan - treat as root\n\t\t\t\troots.push(node);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort children by timestamp (oldest first, newest at bottom)\n\t// Use iterative approach to avoid stack overflow on deep trees\n\tconst stack: SessionTreeNode[] = [...roots];\n\twhile (stack.length > 0) {\n\t\tconst node = stack.pop()!;\n\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\tstack.push(...node.children);\n\t}\n\n\treturn roots;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { AsyncJobManager } from "../async/job-manager.js";
|
|
2
2
|
import type { AsyncJobDeliveryHandler } from "../async/types.js";
|
|
3
|
-
import type { BashOperations, BashToolDetails } from "./bash.
|
|
3
|
+
import type { BashOperations, BashToolDetails } from "./bash.ts";
|
|
4
4
|
interface StartAsyncBashCommandOptions {
|
|
5
5
|
command: string;
|
|
6
6
|
cwd: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-async-execution.js","sourceRoot":"","sources":["../../../src/core/tools/bash-async-execution.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACxG,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAgBjE,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,OAAqC;IAIhF,IA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AmB,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;IAC7D,CAAC,CAAC,EAAE,CAAC;IACL,OAAO;QACN,OAAO,EAAE;YACR;gBACC,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,8BAA8B,GAAG,CAAC,KAAK,KAAK,OAAO,CAAC,OAAO,kDAAkD,GAAG,CAAC,KAAK,+DAA+D,GAAG,CAAC,KAAK,MAAM;aAC1M;SACD;QACD,OAAO,EAAE;YACR,KAAK,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE;YACxG,cAAc,EAAE,OAAO,CAAC,cAAc;YACtC,GAAG,CAAC,OAAO,CAAC,uBAAuB,KAAK,SAAS;gBAChD,CAAC,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,uBAAuB,EAAE;gBAC9D,CAAC,CAAC,EAAE,CAAC;SACN;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AsyncJobManager } from \"../async/job-manager.js\";\nimport type { AsyncJobDeliveryHandler } from \"../async/types.js\";\nimport type { BashOperations, BashToolDetails } from \"./bash.
|
|
1
|
+
{"version":3,"file":"bash-async-execution.js","sourceRoot":"","sources":["../../../src/core/tools/bash-async-execution.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACxG,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAgBjE,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,OAAqC;IAIhF,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU;QAC9B,MAAM,IAAI,KAAK,CAAC,8EAA8E,CAAC,CAAC;IACjG,MAAM,GAAG,GAAG,o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IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,8BAA8B,GAAG,CAAC,KAAK,KAAK,OAAO,CAAC,OAAO,kDAAkD,GAAG,CAAC,KAAK,+DAA+D,GAAG,CAAC,KAAK,MAAM;aAC1M;SACD;QACD,OAAO,EAAE;YACR,KAAK,EAAE,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE;YACxG,cAAc,EAAE,OAAO,CAAC,cAAc;YACtC,GAAG,CAAC,OAAO,CAAC,uBAAuB,KAAK,SAAS;gBAChD,CAAC,CAAC,EAAE,uBAAuB,EAAE,OAAO,CAAC,uBAAuB,EAAE;gBAC9D,CAAC,CAAC,EAAE,CAAC;SACN;KACD,CAAC;AACH,CAAC","sourcesContent":["import type { AsyncJobManager } from \"../async/job-manager.js\";\nimport type { AsyncJobDeliveryHandler } from \"../async/types.js\";\nimport type { BashOperations, BashToolDetails } from \"./bash.ts\";\nimport { createManagedBashJob, discardManagedBashJob, formatAsyncJobError } from \"./bash-async-jobs.js\";\nimport { createAsyncOutputAppender } from \"./bash-async-output.js\";\nimport { invalidateNativeSearchCache } from \"./search-native.ts\";\n\ninterface StartAsyncBashCommandOptions {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n\tpty?: boolean;\n\ttimeoutSeconds: number;\n\trequestedTimeoutSeconds?: number;\n\tsignal?: AbortSignal;\n\toperations: BashOperations;\n\tmanager?: AsyncJobManager;\n\tdeliveryHandler?: AsyncJobDeliveryHandler;\n\tsessionId?: symbol;\n}\n\nexport async function startAsyncBashCommand(options: StartAsyncBashCommandOptions): Promise<{\n\tcontent: Array<{ type: \"text\"; text: string }>;\n\tdetails: BashToolDetails;\n}> {\n\tif (options.manager?.atCapacity)\n\t\tthrow new Error(\"Background job limit reached. Wait for running jobs to finish or cancel one.\");\n\tconst job = createManagedBashJob(\n\t\toptions.command,\n\t\toptions.cwd,\n\t\toptions.timeoutSeconds,\n\t\toptions.requestedTimeoutSeconds,\n\t);\n\ttry {\n\t\toptions.manager?.registerBashJob(job, options.deliveryHandler, options.sessionId);\n\t} catch (registerError) {\n\t\t// The job was inserted into the managed map but never started; drop it so\n\t\t// it cannot linger as a permanently-\"running\" zombie entry (see\n\t\t// discardManagedBashJob). Registration failures (disposed manager/session,\n\t\t// capacity race) still surface to the caller as tool errors.\n\t\tdiscardManagedBashJob(job.jobId);\n\t\tthrow registerError;\n\t}\n\tconst appendAsyncOutput = createAsyncOutputAppender(job, { persistAfterBytes: 12_000 });\n\tconst onParentAbort = () => {\n\t\toptions.manager?.acknowledgeDeliveries([job.jobId]);\n\t\tjob.abortController?.abort();\n\t};\n\tif (options.signal?.aborted) onParentAbort();\n\telse options.signal?.addEventListener(\"abort\", onParentAbort, { once: true });\n\tvoid (async () => {\n\t\tlet error: Error | string | undefined;\n\t\tlet exitCode: number | null | undefined;\n\t\ttry {\n\t\t\texitCode = (\n\t\t\t\tawait options.operations.exec(options.command, options.cwd, {\n\t\t\t\t\tonData: appendAsyncOutput.append,\n\t\t\t\t\ttimeout: options.timeoutSeconds,\n\t\t\t\t\tenv: options.env,\n\t\t\t\t\tpty: options.pty,\n\t\t\t\t\tsignal: job.abortController?.signal,\n\t\t\t\t})\n\t\t\t).exitCode;\n\t\t} catch (execError) {\n\t\t\terror = execError instanceof Error ? execError : String(execError);\n\t\t}\n\t\ttry {\n\t\t\tawait appendAsyncOutput.close();\n\t\t} catch (closeError) {\n\t\t\terror ??= closeError instanceof Error ? closeError : String(closeError);\n\t\t}\n\t\tif (error !== undefined) {\n\t\t\tjob.status = \"failed\";\n\t\t\tjob.error = job.abortController?.signal.aborted ? \"aborted\" : formatAsyncJobError(error);\n\t\t} else {\n\t\t\tjob.exitCode = exitCode;\n\t\t\tjob.status = exitCode && exitCode !== 0 ? \"failed\" : \"completed\";\n\t\t}\n\t\tjob.endedAt = Date.now();\n\t\tinvalidateNativeSearchCache();\n\t\toptions.manager?.completeBashJob(job);\n\t\toptions.signal?.removeEventListener(\"abort\", onParentAbort);\n\t})();\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: `Started async bash command ${job.jobId}: ${options.command}\\nPoll with bash({ command: \"__atomic_bash_job ${job.jobId}\" }); cancel with bash({ command: \"__atomic_bash_job_cancel ${job.jobId}\" })`,\n\t\t\t},\n\t\t],\n\t\tdetails: {\n\t\t\tasync: { jobId: job.jobId, type: \"bash\", state: \"running\", command: options.command, status: \"running\" },\n\t\t\ttimeoutSeconds: options.timeoutSeconds,\n\t\t\t...(options.requestedTimeoutSeconds !== undefined\n\t\t\t\t? { requestedTimeoutSeconds: options.requestedTimeoutSeconds }\n\t\t\t\t: {}),\n\t\t},\n\t};\n}\n"]}
|