pi-tuck 1.13.0 → 1.14.0

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 CHANGED
@@ -3,6 +3,25 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.14.0]
7
+
8
+ ### Changed
9
+
10
+ - Kept prompt outputs: once a user prompt gives a command after "Run:" (for example "New telex. Run: telex read NAME"), the summary carries
11
+ the output of every later run of that command, not only of the run that directly follows the prompt. An agent that polls its inbox by itself
12
+ reads its tasks this way. The newest output comes first and is never left out: one that does not fit is clipped to its head and tail with
13
+ a `tuck_recall` locator. An output equal to an earlier one is carried once. These outputs have one allowance, at most 16,000 characters or
14
+ a quarter of the summary room; the user's messages count against it too, the first one first at its own limit. Outputs past the allowance
15
+ are listed by recall index. The space is set aside before the dialogue is filled, in every form of the summary. On a recorded session with
16
+ 42 cuts, the newest such output that had left the kept turns was missing from 13 summaries; it is now whole in all 42, for 21 more tokens
17
+ per summary on average (374 at most). Sessions with no "Run:" prompt get the same summaries as before, byte for byte.
18
+
19
+ ## [1.13.1]
20
+
21
+ ### Changed
22
+
23
+ - Internal cleanup across the code, tests and benchmark scripts, with no change to any request.
24
+
6
25
  ## [1.13.0]
7
26
 
8
27
  ### Changed
package/README.md CHANGED
@@ -12,11 +12,11 @@ pi install npm:pi-tuck
12
12
 
13
13
  Start a new Pi process after installing or updating. pi-tuck handles automatic compaction and `/compact` by default. Run `/tuck` to see the loaded version, cut history, and active cut policy.
14
14
 
15
- This README describes pi-tuck 1.13.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.13.0` or `pi install git:github.com/galyavin/pi-tuck@v1.13.0`. To uninstall, run `pi remove` with the source you installed.
15
+ This README describes pi-tuck 1.14.0. To pin a published release, use a versioned source such as `pi install npm:pi-tuck@1.14.0` or `pi install git:github.com/galyavin/pi-tuck@v1.14.0`. To uninstall, run `pi remove` with the source you installed.
16
16
 
17
17
  ## Compaction and recall
18
18
 
19
- A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It carries the output of a command a prompt told the agent to run (such as "Run: telex read NAME"), the newest four and at most 8,000 characters in all, since an agent driven by messages gets its tasks that way. When the tool round just before the kept turns is too large to keep with them, the summary carries it, clipped where needed, with a `tuck_recall` locator for each clipped part. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
19
+ A cut replaces older turns in the model's context with a summary while keeping the original entries in the session. The summary prioritizes the current prompt, recent turns, excerpts from earlier prompts, and pointers to files and tool actions. It carries the output of a command a prompt told the agent to run, the newest four and at most 8,000 characters in all, since an agent driven by messages gets its tasks that way. When a prompt gives the command after "Run:" (such as "Run: telex read NAME"), every later run of that command counts too: the newest output always rides, clipped with a `tuck_recall` locator if it is too large, and older ones follow within one allowance (at most 16,000 characters or a quarter of the summary room) that the user's messages also count against. When the tool round just before the kept turns is too large to keep with them, the summary carries it, clipped where needed, with a `tuck_recall` locator for each clipped part. It can also carry recent reads and searches when the session records no action that could have changed their files. The recorded text is historical evidence about the session. Re-read a file before editing it.
20
20
 
21
21
  Files the agent has read more than once are carried whole after the summary, most-read first, as far as a share of the summary allows. A file is carried only when its last read covered the whole file and the file on disk still holds exactly that text; the agent can edit from a carried copy without re-reading it. When a session's cuts keep dropping files the agent then reads again unchanged, pi-tuck moves its trim point later, to native Pi's (the larger of the room and `keepRecentTokens`), while keeping room for the next reply. Cuts still trim to the usual size.
22
22
 
@@ -132,6 +132,8 @@ See [Contributing](CONTRIBUTING.md) for stress tests and [the changelog](CHANGEL
132
132
  - **128k recall replay.** Completed answer sets at cuts 1–4 supported the registered 3-point margin against Pi's summaries and kept messages. The scoring excluded 52 of 95 pi-tuck sets that aborted. [Retention results](benchmark/RESULTS-MAIN.md)
133
133
  - **32k live run.** pi-tuck 1.0.5 resolved 120 of 150 tasks versus Pi's 94 and observation masking's 117. The one-sided 95% lower bounds were +10.7 and −2.7 points, respectively. pi-tuck recorded one dead task against a target of zero. [32k results](benchmark/RESULTS-32K-ACCEPT.md)
134
134
 
135
+ Tested so far: Qwen3.8 Flash Next (local) at a 128k window, DeepSeek V4.1 Flash at a 32k window, and a local model at 272k and 230k windows in the [72-hour run](docs/case-study-long-run.md). Other models and windows have not been measured.
136
+
135
137
  The [benchmark index](benchmark/README.md) records the models, versions, plans, and scope of each result.
136
138
 
137
139
  ## Author
@@ -1 +1 @@
1
- export declare const BUILD_ID = "9a1d1acbec0fa4d9ce13c203156e107f843afb87bb3123d9b20b3a44236f366e";
1
+ export declare const BUILD_ID = "cd8c8431465b86de67dc1413b447074fa4412dedcb31688d7d88663622b73c96";
@@ -1 +1 @@
1
- export const BUILD_ID = "9a1d1acbec0fa4d9ce13c203156e107f843afb87bb3123d9b20b3a44236f366e";
1
+ export const BUILD_ID = "cd8c8431465b86de67dc1413b447074fa4412dedcb31688d7d88663622b73c96";
@@ -4,8 +4,8 @@ export interface Clip {
4
4
  toolCallId: string;
5
5
  content: ToolResultMessage["content"];
6
6
  }
7
- /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
8
- /** `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
7
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
8
+ * `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
9
9
  export declare const clipText: (text: string, keep: number, locator: {
10
10
  entryId: string;
11
11
  } | {
package/dist/src/clip.js CHANGED
@@ -3,8 +3,8 @@ import { MAX_RECALL_CHARACTERS } from "./recall.js";
3
3
  /** The text `tuck_recall {entryId, offset}` reads from a text-only result; any other result is not clipped. */
4
4
  const textOf = (message) => message.content.every(block => block.type === "text")
5
5
  ? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
6
- /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
7
- /** `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
6
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
7
+ * `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
8
8
  export const clipText = (text, keep, locator, base = 0) => {
9
9
  const head = Math.ceil(keep / 2), tail = keep - head;
10
10
  return text.slice(0, head) +
@@ -266,7 +266,7 @@ export async function installCompaction(pi, options = {}) {
266
266
  const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
267
267
  if (!validCutAt(cutAt))
268
268
  throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
269
- const view = (ctx, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
269
+ const view = (ctx) => (run?.cut ?? liveCut).view(ctx);
270
270
  const liveCut = new PendingCut();
271
271
  const recorder = new IncidentRecorder(options.diagnostics);
272
272
  let proposalId;
@@ -587,9 +587,8 @@ export async function installCompaction(pi, options = {}) {
587
587
  const fits = (tokens, limit, ctx) => corrected(tokens, ctx) < limit;
588
588
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
589
589
  const measureFor = (ctx) => (messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
590
- // The planner counts with the same function, except that it does not fail on a summary in another format: a cut can replace one
591
- // (an operator's /compact repairs a session whose saved summary is foreign). Identical to the strict one for this compactor's summaries.
592
- const plannerMeasureFor = (ctx) => Object.assign((messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy), { messageTokens: (message) => conversationTokens(applyClips([message], clips())) });
590
+ // The planner counts with the same function, and also prices a single message.
591
+ const plannerMeasureFor = (ctx) => Object.assign(measureFor(ctx), { messageTokens: (message) => conversationTokens(applyClips([message], clips())) });
593
592
  const hostMessages = (ctx) => options.hostMessages?.(ctx) ?? [];
594
593
  const toolShapes = (names) => {
595
594
  const selected = new Set(names);
@@ -10,10 +10,13 @@ export function historyToolNames(pi, names, enabled) {
10
10
  const registered = new Set(pi.getAllTools().map(tool => tool.name));
11
11
  return [...names, ...["tuck_recall"].filter(name => registered.has(name) && !names.includes(name))];
12
12
  }
13
- export function applyHistoryTools(pi, enabled) {
14
- const current = pi.getActiveTools(), next = historyToolNames(pi, current, enabled);
13
+ const setIfChanged = (pi, current, next) => {
15
14
  if (current.length !== next.length || current.some((name, index) => name !== next[index]))
16
15
  pi.setActiveTools(next);
16
+ };
17
+ export function applyHistoryTools(pi, enabled) {
18
+ const current = pi.getActiveTools(), next = historyToolNames(pi, current, enabled);
19
+ setIfChanged(pi, current, next);
17
20
  }
18
21
  /** Match only our part of Pi's saved declaration snapshot, so its loop records no activation/removal message. Legacy sessions can
19
22
  * already declare our tools; new sessions declare them only in the request projection. Executable tools are restored at turn_start. */
@@ -21,8 +24,7 @@ export function stageHistoryTools(pi, messages) {
21
24
  const declared = new Set(getCurrentTools(convertToLlm(messages)).map(tool => tool.name));
22
25
  const current = pi.getActiveTools();
23
26
  const next = historyToolNames(pi, current, true).filter(name => !own(name) || declared.has(name));
24
- if (current.length !== next.length || current.some((name, index) => name !== next[index]))
25
- pi.setActiveTools(next);
27
+ setIfChanged(pi, current, next);
26
28
  return next;
27
29
  }
28
30
  /** Pi has already declared the request's tools before queued user messages are appended. A prompt cut planned on such a message needs its declarations
@@ -2,9 +2,20 @@ import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agen
2
2
  import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
3
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
4
  export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, exclude?: ReadonlySet<string>): TranscriptRecord[];
5
+ /** The commands that user turns name on a "Run: COMMAND" line (to the end of the line, backticks removed), anywhere on the branch. A session with
6
+ * one has a channel: the agent's orders arrive as that command's output, from the call the turn asked for and from the agent's own later calls. */
7
+ export declare function promptChannels(entries: readonly (SessionEntry | SessionHeader)[]): string[];
5
8
  /** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
6
- * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
7
- export declare function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
9
+ * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go.
10
+ * With `orders` (a session with a channel): every output of a channel's command counts, a later one equal to an earlier one is skipped, and
11
+ * the outputs share `budget` characters with the user turns after the first (`firstUserId`), newest first. A user turn takes its length. An
12
+ * output that fits rides whole; the newest is never left out, and one that does not fit keeps the head and tail that do, with a recall
13
+ * locator (clip.ts); once nothing is left, older ones are listed by recall index. */
14
+ export declare function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, orders?: {
15
+ channels: readonly string[];
16
+ budget: number;
17
+ firstUserId?: string;
18
+ }): TranscriptRecord[];
8
19
  /** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
9
20
  * results fit `budget` tokens together: the smallest go whole, the rest share what is left and are clipped as a fresh result is (clip.ts), so that
10
21
  * tuck_recall reads the rest from the untouched entries by their summary index (the arguments of a call at their place in the assistant entry's readable text).
@@ -71,10 +71,22 @@ export function keptReadCandidates(entries, indices, resolvable, exclude = new S
71
71
  }
72
72
  /** At most this many outputs, newest first, holding at most this much output text in all; the rest is cut with a pointer. */
73
73
  const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
74
+ /** At most this many outputs past the shared cap are listed by their recall index. */
75
+ const MAX_ORDER_LOCATORS = 8;
74
76
  const words = (text) => text.replace(/\s+/gu, " ").trim();
77
+ /** The commands that user turns name on a "Run: COMMAND" line (to the end of the line, backticks removed), anywhere on the branch. A session with
78
+ * one has a channel: the agent's orders arrive as that command's output, from the call the turn asked for and from the agent's own later calls. */
79
+ export function promptChannels(entries) {
80
+ return entries.flatMap(entry => entry.type === "message" && entry.message.role === "user"
81
+ ? [...textOf(entry.message.content).matchAll(/Run:([^\n]*)/gu)].map(match => words(match[1].replace(/`/gu, ""))).filter(Boolean) : []);
82
+ }
75
83
  /** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
76
- * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
77
- export function promptOutputCandidates(entries, indices, resolvable) {
84
+ * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go.
85
+ * With `orders` (a session with a channel): every output of a channel's command counts, a later one equal to an earlier one is skipped, and
86
+ * the outputs share `budget` characters with the user turns after the first (`firstUserId`), newest first. A user turn takes its length. An
87
+ * output that fits rides whole; the newest is never left out, and one that does not fit keeps the head and tail that do, with a recall
88
+ * locator (clip.ts); once nothing is left, older ones are listed by recall index. */
89
+ export function promptOutputCandidates(entries, indices, resolvable, orders) {
78
90
  const results = new Map(), named = new Map();
79
91
  let prompt;
80
92
  for (const entry of entries) {
@@ -89,7 +101,7 @@ export function promptOutputCandidates(entries, indices, resolvable) {
89
101
  results.set(message.toolCallId, entry);
90
102
  continue;
91
103
  }
92
- if (message.role !== "assistant" || prompt === undefined || isDiscardedResponse(message))
104
+ if (message.role !== "assistant" || prompt === undefined && !orders || isDiscardedResponse(message))
93
105
  continue;
94
106
  for (const block of message.content) {
95
107
  if (block.type !== "toolCall" || block.name !== "bash" || typeof block.arguments?.command !== "string")
@@ -98,28 +110,70 @@ export function promptOutputCandidates(entries, indices, resolvable) {
98
110
  // A leading "cd DIR &&" is not what the prompt names; classifyBash already recognizes it.
99
111
  const rest = classifyBash(command).directory === undefined ? command : command.slice(command.indexOf("&&") + 2);
100
112
  const lead = words(rest.split(/[|;&<>]|\d>/u)[0]);
101
- if (lead.includes(" ") && prompt.includes(lead))
113
+ if (lead.includes(" ") && (prompt?.includes(lead) || orders?.channels.some(channel => channel.includes(lead))))
102
114
  named.set(block.id, command);
103
115
  }
104
116
  prompt = undefined;
105
117
  }
106
- const records = [];
107
- let room = MAX_PROMPT_OUTPUT_CHARACTERS;
108
- for (const [id, command] of [...named].reverse()) {
109
- const entry = results.get(id), sourceIndex = entry && indices.get(entry.id);
118
+ const output = (entry) => {
119
+ const sourceIndex = entry && indices.get(entry.id);
110
120
  if (entry?.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content) ||
111
121
  sourceIndex === undefined || !resolvable(entry))
112
- continue;
122
+ return undefined;
113
123
  const text = textOf(entry.message.content);
114
- if (!text.length)
124
+ return text.length ? { sourceIndex, text } : undefined;
125
+ };
126
+ const record = (command, sourceIndex, kept) => ({ kind: "section", title: "Kept-prompt-output", sourceIndex,
127
+ text: `bash ${words(command)} (run as a user prompt asked; output as recorded at #${sourceIndex}):\n${kept}` });
128
+ const records = [];
129
+ if (!orders) {
130
+ let room = MAX_PROMPT_OUTPUT_CHARACTERS;
131
+ for (const [id, command] of [...named].reverse()) {
132
+ const found = output(results.get(id));
133
+ if (!found)
134
+ continue;
135
+ const { sourceIndex, text } = found;
136
+ records.push(record(command, sourceIndex, text.length <= room ? text : `${text.slice(0, room)}\n… (truncated; whole output: tuck_recall {"index":${sourceIndex}})`));
137
+ room -= Math.min(room, text.length);
138
+ if (!room || records.length === MAX_PROMPT_OUTPUTS)
139
+ break;
140
+ }
141
+ return records;
142
+ }
143
+ const payloads = new Map(), seen = new Set();
144
+ for (const [id, command] of named) {
145
+ const entry = results.get(id), found = output(entry);
146
+ if (!found || seen.has(found.text))
115
147
  continue;
116
- const kept = text.length <= room ? text : `${text.slice(0, room)}\n… (truncated; whole output: tuck_recall {"index":${sourceIndex}})`;
117
- records.push({ kind: "section", title: "Kept-prompt-output", sourceIndex,
118
- text: `bash ${words(command)} (run as a user prompt asked; output as recorded at #${sourceIndex}):\n${kept}` });
119
- room -= Math.min(room, text.length);
120
- if (!room || records.length === MAX_PROMPT_OUTPUTS)
121
- break;
148
+ seen.add(found.text);
149
+ payloads.set(entry.id, { command, ...found });
150
+ }
151
+ const older = [];
152
+ let room = Math.max(0, orders.budget);
153
+ for (let at = entries.length - 1; at >= 0; at--) {
154
+ const entry = entries[at];
155
+ if (entry.type !== "message")
156
+ continue;
157
+ if (entry.message.role === "user") {
158
+ if (entry.id !== orders.firstUserId)
159
+ room -= Math.min(room, textOf(entry.message.content).length);
160
+ continue;
161
+ }
162
+ const payload = payloads.get(entry.id);
163
+ if (!payload)
164
+ continue;
165
+ const { command, sourceIndex, text } = payload, spare = room - clipText(text, 0, { index: sourceIndex }).length;
166
+ if (text.length > room && records.length && spare <= 0) {
167
+ older.push(sourceIndex);
168
+ continue;
169
+ }
170
+ const kept = text.length <= room ? text : clipText(text, Math.max(0, spare), { index: sourceIndex });
171
+ records.push(record(command, sourceIndex, kept));
172
+ room -= Math.min(room, kept.length);
122
173
  }
174
+ if (older.length)
175
+ records.push({ kind: "section", title: "Kept-prompt-output", sourceIndex: older[0],
176
+ text: `${older.length} older output${older.length === 1 ? "" : "s"} of these commands not shown; read one with tuck_recall {"index":N}, newest first: ${older.slice(0, MAX_ORDER_LOCATORS).join(", ")}${older.length > MAX_ORDER_LOCATORS ? ", …" : ""}` });
123
177
  return records;
124
178
  }
125
179
  /** The tool round just older than a tail boundary (the assistant's calls and their text results), as one closing-section record whose calls and
@@ -15,13 +15,17 @@ export const head = (text, max) => {
15
15
  return text;
16
16
  return text.slice(0, /[\uD800-\uDBFF]/u.test(text[max - 1]) ? max - 1 : max);
17
17
  };
18
- /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
19
- * A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
20
- export function ledgerItems(entries, indices, resolvable, failedCalls, cwd) {
18
+ const resultsByCall = (entries) => {
21
19
  const results = new Map();
22
20
  for (const entry of entries)
23
21
  if (entry.type === "message" && entry.message.role === "toolResult")
24
22
  results.set(entry.message.toolCallId, entry);
23
+ return results;
24
+ };
25
+ /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
26
+ * A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
27
+ export function ledgerItems(entries, indices, resolvable, failedCalls, cwd) {
28
+ const results = resultsByCall(entries);
25
29
  const last = new Map();
26
30
  for (const entry of entries) {
27
31
  if (entry.type !== "message" || entry.message.role !== "assistant")
@@ -66,10 +70,7 @@ export const ACTIONS_HEADING = "Tool calls other than read, write, edit and hist
66
70
  /** The calls exactly as recorded, newest first, with the command (or else the arguments) flattened to one line. A call from a failed or
67
71
  * aborted response is not listed; a call whose result is an error is marked. */
68
72
  export function actionItems(entries, indices, resolvable, failedCalls) {
69
- const results = new Map();
70
- for (const entry of entries)
71
- if (entry.type === "message" && entry.message.role === "toolResult")
72
- results.set(entry.message.toolCallId, entry);
73
+ const results = resultsByCall(entries);
73
74
  const calls = [];
74
75
  for (const entry of entries) {
75
76
  if (entry.type !== "message" || entry.message.role !== "assistant")
@@ -128,7 +128,7 @@ export function cleanupLegacyFiles(ctx) {
128
128
  }
129
129
  const children = await readdir(root);
130
130
  started = true;
131
- const names = [...directories, ...children.filter(name => temporaryDirectory.exec(name)?.[0] === name)];
131
+ const names = [...directories, ...children.filter(name => temporaryDirectory.test(name))];
132
132
  const candidates = [];
133
133
  for (const name of names) {
134
134
  const path = join(root, name);
@@ -5,6 +5,7 @@ const wire = (value) => {
5
5
  throw new Error("Expected a Chat Completions request");
6
6
  return value;
7
7
  };
8
+ const cancelled = (message) => ({ ...message, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" });
8
9
  const promptTokens = (message) => message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
9
10
  export function llamaContinuationStream(profile, native) {
10
11
  return (model, context, options) => {
@@ -98,7 +99,7 @@ export function llamaContinuationStream(profile, native) {
98
99
  clearTimeout(admissionTimer);
99
100
  }
100
101
  if (signal.aborted) {
101
- first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
102
+ first = cancelled(first);
102
103
  }
103
104
  else if (!cacheVerified) {
104
105
  first = { ...first, errorMessage: CONTINUATION_CACHE_MISS };
@@ -150,7 +151,7 @@ export function llamaContinuationStream(profile, native) {
150
151
  if (!first)
151
152
  throw error;
152
153
  if (signal.aborted)
153
- first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
154
+ first = cancelled(first);
154
155
  }
155
156
  finally {
156
157
  if (thinkingEnd)
@@ -76,6 +76,9 @@ export interface ReadableEntry {
76
76
  arguments: Record<string, unknown>;
77
77
  };
78
78
  }
79
+ type ProducerLink = NonNullable<ReadableEntry["producerRead"]> & {
80
+ sourceTime: SourceTime;
81
+ };
79
82
  interface DiscoveryEntry extends ReadableEntry {
80
83
  sourceText: string;
81
84
  ranges: {
@@ -85,20 +88,10 @@ interface DiscoveryEntry extends ReadableEntry {
85
88
  }
86
89
  export declare function createRecall(policy?: RecallPolicy): {
87
90
  isHistorySource: (entry: SessionEntry) => boolean;
88
- readable: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, NonNullable<ReadableEntry["producerRead"]> & {
89
- sourceTime: SourceTime;
90
- }>) => ReadableEntry | undefined;
91
+ readable: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>) => ReadableEntry | undefined;
91
92
  recallAttempts: (branch: readonly SessionEntry[]) => ReadonlyMap<string, RecordedAttempt | null>;
92
- producerReads: (branch: readonly SessionEntry[]) => Map<string, {
93
- entryId: string;
94
- offset: number;
95
- limit: number;
96
- } & {
97
- sourceTime: SourceTime;
98
- }>;
99
- discoveryEntry: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, NonNullable<ReadableEntry["producerRead"]> & {
100
- sourceTime: SourceTime;
101
- }>) => DiscoveryEntry | undefined;
93
+ producerReads: (branch: readonly SessionEntry[]) => Map<string, ProducerLink>;
94
+ discoveryEntry: (entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>) => DiscoveryEntry | undefined;
102
95
  discoveryExcerpt: (row: DiscoveryEntry, query: PreparedKeywordQuery) => {
103
96
  snippet: string;
104
97
  totalCharacters: number;
@@ -264,16 +264,6 @@ export function createRecall(policy = {}) {
264
264
  return { snippet: row.sourceText.slice(range.start, range.end), totalCharacters: row.sourceText.length,
265
265
  read: { entryId: row.entryId, offset: range.start, limit: range.end - range.start } };
266
266
  }
267
- /**
268
- * The host supplies this role's current branch; this function never opens a path.
269
- * Query is a case-insensitive literal over eligible source ranges. Offset/limit
270
- * page the concatenation of matching texts, with no added separators. Without an
271
- * explicit offset, a source-scoped query returns the whole matching readable
272
- * source when it fits, otherwise disjoint exact match windows;
273
- * unscoped browsing starts up to 120 characters before its first match.
274
- * Returned nextOffset uses the same filter and can page through any long entry.
275
- * At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
276
- */
277
267
  /** Add factual call context to a demanded complete receipt, never to discovery or partial pages. */
278
268
  function contextualReceipt(branch, entryId, fragment) {
279
269
  const read = fragment.producerRead;
@@ -301,6 +291,16 @@ export function createRecall(policy = {}) {
301
291
  return fragment;
302
292
  } // An incomplete or malformed prefix remains only a locator.
303
293
  }
294
+ /**
295
+ * The host supplies this role's current branch; this function never opens a path.
296
+ * Query is a case-insensitive literal over eligible source ranges. Offset/limit
297
+ * page the concatenation of matching texts, with no added separators. Without an
298
+ * explicit offset, a source-scoped query returns the whole matching readable
299
+ * source when it fits, otherwise disjoint exact match windows;
300
+ * unscoped browsing starts up to 120 characters before its first match.
301
+ * Returned nextOffset uses the same filter and can page through any long entry.
302
+ * At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
303
+ */
304
304
  function recallHistory(branch, options = {}) {
305
305
  const { query, entryId } = options;
306
306
  if (query !== undefined && (typeof query !== "string" || !query.length || query.length > MAX_RECALL_QUERY_CHARACTERS))
@@ -24,7 +24,6 @@ export function rereadsAfterCuts(branch) {
24
24
  current = epoch[i];
25
25
  replies = 0;
26
26
  }
27
- const cuts = current;
28
27
  replies++;
29
28
  for (const block of message.content) {
30
29
  if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object")
@@ -70,9 +70,8 @@ const bm25Score = (doc, terms, ctx) => {
70
70
  };
71
71
  /** Rank already-eligible recall rows; filtering and paging belong to the caller. */
72
72
  export const rankRecallRows = (rows, query) => {
73
- const rawQuery = query.trim();
74
73
  const checkBudget = startBudget();
75
- const prepared = prepareKeywordQuery(rawQuery);
74
+ const prepared = prepareKeywordQuery(query);
76
75
  const terms = prepared.terms;
77
76
  // Preserve the role prefix and trailing space of the original BM25 documents.
78
77
  const docs = rows.map((row) => `${row.role} ${row.text} `);
package/dist/src/tuck.js CHANGED
@@ -7,7 +7,7 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget.j
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content.js";
9
9
  import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
10
- import { crossingRoundRecord, keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
10
+ import { crossingRoundRecord, keptReadCandidates, promptChannels, promptOutputCandidates } from "./kept-reads.js";
11
11
  import { workingSetCandidates } from "./working-set.js";
12
12
  import { keptSearchCandidates } from "./kept-searches.js";
13
13
  import { clipText } from "./clip.js";
@@ -42,6 +42,7 @@ export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {},
42
42
  * `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
43
43
  export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true) {
44
44
  const { isHistorySource, readable } = createRecall(policy);
45
+ const resolvable = (entry) => readable(entry) !== undefined;
45
46
  const projected = ctx.sessionManager.buildSessionProjection();
46
47
  if (input.branchEntries.some(entry => entry.type === "context_edit" && entry.replacement !== null))
47
48
  return { unavailable: "pi-tuck does not support replacement context edits" };
@@ -164,9 +165,15 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
164
165
  if (!header)
165
166
  throw new Error("Missing native session header");
166
167
  const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
167
- const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
168
+ const minimumOpeningLength = 80, openingLength = Math.max(minimumOpeningLength, Math.floor(Math.sqrt(room * 4)));
168
169
  // At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
169
170
  const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
171
+ // A session whose user turns name a command ("Run: …") gets its orders as that command's output. There the first user turn, the later
172
+ // user turns and those outputs share twice the first turn's cap: the first turn takes what it shows, the rest go newest first. The
173
+ // outputs ride in every summary, reserved before the dialogue fills, and no more than `left` characters of the summary's own room.
174
+ const channels = promptChannels(entries);
175
+ const ordersAt = (boundary, left = Infinity) => channels.length ? promptOutputCandidates([header, ...entries.slice(0, boundary)], indices, resolvable, { channels, firstUserId: firstUser?.id, budget: Math.min(left, 2 * firstTurnCap - (firstUser?.type === "message" && firstUser.message.role === "user" && firstUserPosition >= 0 && firstUserPosition < boundary
176
+ ? Math.min(firstTurnCap, textOf(firstUser.message.content).length) : 0)) }) : undefined;
170
177
  const positions = new Map(entries.map((entry, at) => [entry.id, at]));
171
178
  const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
172
179
  if (!originals.ok)
@@ -335,8 +342,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
335
342
  // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
336
343
  // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
337
344
  if (input.deepest) {
338
- // The floor carries the outputs prompts asked for (capped at 8,000 characters) and closes without claiming lists it does not have.
339
- const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, entry => readable(entry) !== undefined);
345
+ // The floor carries the outputs prompts asked for (capped at 8,000 characters, or the shared cap of a session with a channel) and closes without claiming lists it does not have.
346
+ const outputs = ordersAt(floorBoundary) ?? promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, resolvable);
340
347
  const summary = (serializeTranscript([...calibrationHigh.rows, ...outputs]) || TRANSCRIPT_HEADER + "\n") + DEEPEST_SUFFIX;
341
348
  const projection = preview(summary, floorBoundary);
342
349
  assertNativeToolRounds(projection);
@@ -351,8 +358,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
351
358
  const cached = listCache.get(boundary);
352
359
  if (cached)
353
360
  return cached;
354
- const compacted = entries.slice(0, boundary), resolves = (entry) => readable(entry) !== undefined;
355
- const files = ledgerItems(compacted, indices, resolves, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolves, failedCalls);
361
+ const compacted = entries.slice(0, boundary);
362
+ const files = ledgerItems(compacted, indices, resolvable, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolvable, failedCalls);
356
363
  const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
357
364
  listCache.set(boundary, lists);
358
365
  return lists;
@@ -403,7 +410,6 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
403
410
  const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
404
411
  // The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
405
412
  // WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
406
- const resolvable = (entry) => readable(entry) !== undefined;
407
413
  const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
408
414
  if (workingSet.files.length) {
409
415
  const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
@@ -419,13 +425,14 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
419
425
  }
420
426
  const carriedKeys = new Set(carried.map(file => file.key));
421
427
  let ledger = lists.records;
422
- let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
428
+ const maxListLines = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
429
+ let listedKeep = maxListLines;
423
430
  // List caps are existing ranking policy; only the carried target is a
424
431
  // spending limit. Candidate list sizes have fixed, cached line prices.
425
432
  if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
426
433
  ledger = [];
427
434
  listedKeep = 0;
428
- for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
435
+ for (let keep = 0; keep <= Math.min(maxListLines, Math.max(lists.files.length, lists.actions.length)); keep++) {
429
436
  const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
430
437
  if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) {
431
438
  ledger = candidate;
@@ -441,17 +448,18 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
441
448
  // The tool round the tail boundary passed (the one crossing the tail size) rides in the closing section, so the tail is not left far
442
449
  // below its size. It is paid from the summary, up to what the native tail leaves of that size, and is reserved before the dialogue fills.
443
450
  let crossingRound;
444
- const briefRoom = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
451
+ const summaryRoom = maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length);
452
+ const orders = ordersAt(boundary, summaryRoom), ordersCost = orders ? lineCost(orders) : 0;
453
+ const maxBriefChars = Math.max(0, summaryRoom - ordersCost);
445
454
  if (boundary === preferredBoundary && (preferredBoundary > originalBoundary || budgetCut) && boundary < entries.length) {
446
455
  const crossing = entries.slice(0, boundary).findLastIndex(entry => !(entry.type === "message" && entry.message.role === "toolResult"));
447
456
  const tail = crossing < 0 ? 0 : carriedTailTokens(Math.max(nativeAt(originalBoundary), nativeAt(crossing))) - nativeAt(boundary);
448
457
  // Like the working set, at most WORKING_SET_SHARE of what the summary may spend beyond its protected rows: the dialogue keeps the rest.
449
- const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * briefRoom / 4));
458
+ const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * maxBriefChars / 4));
450
459
  if (size > 0)
451
460
  crossingRound = crossingRoundRecord(entries, boundary, indices, resolvable, size);
452
461
  }
453
462
  const crossingCost = crossingRound ? lineCost([crossingRound]) : 0;
454
- const maxBriefChars = briefRoom;
455
463
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
456
464
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position])),
457
465
  ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
@@ -462,7 +470,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
462
470
  const compiledBoundary = boundary;
463
471
  // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
464
472
  const sourceKey = (record) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
465
- const keptResults = [], thinking = [];
473
+ const keptResults = [...orders ?? []], thinking = [];
466
474
  const assemble = (compiled, at = compiledBoundary) => {
467
475
  const split = compiled ? splitSummary(compiled) : undefined;
468
476
  if (compiled && !split)
@@ -606,8 +614,8 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
606
614
  const counts = new Map();
607
615
  const prefix = [header, ...entries.slice(0, boundary)];
608
616
  // Outputs a user prompt asked for lead (a message-driven agent's tasks); reads and searches follow, newest result first. One
609
- // allowance; L2's independent four-item caps and whole-item skips.
610
- const candidates = [...promptOutputCandidates(prefix, indices, resolvable), ...[...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
617
+ // allowance; L2's independent four-item caps and whole-item skips. A channel's outputs are already in, on their own cap.
618
+ const candidates = [...orders ? [] : promptOutputCandidates(prefix, indices, resolvable), ...[...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
611
619
  .sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"))];
612
620
  for (const record of candidates) {
613
621
  if ((counts.get(record.title) ?? 0) === 4)
@@ -713,7 +721,7 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
713
721
  missing.forEach((unit, at) => counts[at + 1] = counts[at] + unit.count);
714
722
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
715
723
  });
716
- const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
724
+ const baseCost = lineCost(offer.records) + lineCost(ledger) + ordersCost + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
717
725
  const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
718
726
  const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
719
727
  const extensionPrice = (at) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.13.0",
3
+ "version": "1.14.0",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "9a1d1acbec0fa4d9ce13c203156e107f843afb87bb3123d9b20b3a44236f366e";
1
+ export const BUILD_ID = "cd8c8431465b86de67dc1413b447074fa4412dedcb31688d7d88663622b73c96";
package/src/clip.ts CHANGED
@@ -9,8 +9,8 @@ export interface Clip { toolCallId: string; content: ToolResultMessage["content"
9
9
  const textOf = (message: ToolResultMessage) => message.content.every(block => block.type === "text")
10
10
  ? message.content.map(block => block.type === "text" ? block.text : "").join("\n") : undefined;
11
11
 
12
- /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at. */
13
- /** `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
12
+ /** `keep` characters of the text, half head and half tail, with where the rest is: the `tuck_recall` locator plus the offset the gap starts at.
13
+ * `base`: where `text` starts in the readable text the locator names (the arguments of a call inside its assistant entry). */
14
14
  export const clipText = (text: string, keep: number, locator: { entryId: string } | { index: number }, base = 0): string => {
15
15
  const head = Math.ceil(keep / 2), tail = keep - head;
16
16
  return text.slice(0, head) +
package/src/compaction.ts CHANGED
@@ -271,7 +271,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
271
271
  };
272
272
  const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
273
273
  if (!validCutAt(cutAt)) throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
274
- const view = (ctx: ExtensionContext, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
274
+ const view = (ctx: ExtensionContext) => (run?.cut ?? liveCut).view(ctx);
275
275
  const liveCut = new PendingCut();
276
276
  const recorder = new IncidentRecorder(options.diagnostics);
277
277
  let proposalId: string | undefined;
@@ -527,10 +527,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
527
527
  const fits = (tokens: number, limit: number, ctx: ExtensionContext) => corrected(tokens, ctx) < limit;
528
528
  // The saved conversation and a cut's quantities are counted by the one function the guard counts with (strict, as the context hook is).
529
529
  const measureFor = (ctx: ExtensionContext) => (messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy);
530
- // The planner counts with the same function, except that it does not fail on a summary in another format: a cut can replace one
531
- // (an operator's /compact repairs a session whose saved summary is foreign). Identical to the strict one for this compactor's summaries.
532
- const plannerMeasureFor = (ctx: ExtensionContext) => Object.assign(
533
- (messages: Messages) => projectedConversationTokens(applyClips(messages, clips()), ctx, options.recallPolicy),
530
+ // The planner counts with the same function, and also prices a single message.
531
+ const plannerMeasureFor = (ctx: ExtensionContext) => Object.assign(measureFor(ctx),
534
532
  { messageTokens: (message: Messages[number]) => conversationTokens(applyClips([message], clips())) });
535
533
  const hostMessages = (ctx: ExtensionContext) => options.hostMessages?.(ctx) ?? [];
536
534
  const toolShapes = (names: Iterable<string>) => {
@@ -14,9 +14,13 @@ export function historyToolNames(pi: ExtensionAPI, names: readonly string[], ena
14
14
  return [...names, ...["tuck_recall"].filter(name => registered.has(name) && !names.includes(name))];
15
15
  }
16
16
 
17
+ const setIfChanged = (pi: ExtensionAPI, current: readonly string[], next: string[]): void => {
18
+ if (current.length !== next.length || current.some((name, index) => name !== next[index])) pi.setActiveTools(next);
19
+ };
20
+
17
21
  export function applyHistoryTools(pi: ExtensionAPI, enabled: boolean): void {
18
22
  const current = pi.getActiveTools(), next = historyToolNames(pi, current, enabled);
19
- if (current.length !== next.length || current.some((name, index) => name !== next[index])) pi.setActiveTools(next);
23
+ setIfChanged(pi, current, next);
20
24
  }
21
25
 
22
26
  /** Match only our part of Pi's saved declaration snapshot, so its loop records no activation/removal message. Legacy sessions can
@@ -25,7 +29,7 @@ export function stageHistoryTools(pi: ExtensionAPI, messages: Messages): string[
25
29
  const declared = new Set(getCurrentTools(convertToLlm(messages)).map(tool => tool.name));
26
30
  const current = pi.getActiveTools();
27
31
  const next = historyToolNames(pi, current, true).filter(name => !own(name) || declared.has(name));
28
- if (current.length !== next.length || current.some((name, index) => name !== next[index])) pi.setActiveTools(next);
32
+ setIfChanged(pi, current, next);
29
33
  return next;
30
34
  }
31
35
 
package/src/kept-reads.ts CHANGED
@@ -59,11 +59,23 @@ export function keptReadCandidates(entries: readonly (SessionEntry | SessionHead
59
59
 
60
60
  /** At most this many outputs, newest first, holding at most this much output text in all; the rest is cut with a pointer. */
61
61
  const MAX_PROMPT_OUTPUTS = 4, MAX_PROMPT_OUTPUT_CHARACTERS = 8000;
62
+ /** At most this many outputs past the shared cap are listed by their recall index. */
63
+ const MAX_ORDER_LOCATORS = 8;
62
64
  const words = (text: string) => text.replace(/\s+/gu, " ").trim();
65
+ /** The commands that user turns name on a "Run: COMMAND" line (to the end of the line, backticks removed), anywhere on the branch. A session with
66
+ * one has a channel: the agent's orders arrive as that command's output, from the call the turn asked for and from the agent's own later calls. */
67
+ export function promptChannels(entries: readonly (SessionEntry | SessionHeader)[]): string[] {
68
+ return entries.flatMap(entry => entry.type === "message" && entry.message.role === "user"
69
+ ? [...textOf(entry.message.content).matchAll(/Run:([^\n]*)/gu)].map(match => words(match[1]!.replace(/`/gu, ""))).filter(Boolean) : []);
70
+ }
63
71
  /** The output of a command a user prompt names ("New telex. Run: telex read NAME"), from the first response after that prompt, newest
64
- * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go. */
72
+ * first. A message-driven agent receives its tasks this way, as tool results, so these stay whole while older observations go.
73
+ * With `orders` (a session with a channel): every output of a channel's command counts, a later one equal to an earlier one is skipped, and
74
+ * the outputs share `budget` characters with the user turns after the first (`firstUserId`), newest first. A user turn takes its length. An
75
+ * output that fits rides whole; the newest is never left out, and one that does not fit keeps the head and tail that do, with a recall
76
+ * locator (clip.ts); once nothing is left, older ones are listed by recall index. */
65
77
  export function promptOutputCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
66
- resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
78
+ resolvable: (entry: SessionEntry) => boolean, orders?: { channels: readonly string[]; budget: number; firstUserId?: string }): TranscriptRecord[] {
67
79
  const results = new Map<string, SessionEntry>(), named = new Map<string, string>();
68
80
  let prompt: string | undefined;
69
81
  for (const entry of entries) {
@@ -71,31 +83,61 @@ export function promptOutputCandidates(entries: readonly (SessionEntry | Session
71
83
  const message = entry.message;
72
84
  if (message.role === "user") { prompt = words(textOf(message.content)); continue; }
73
85
  if (message.role === "toolResult") { results.set(message.toolCallId, entry); continue; }
74
- if (message.role !== "assistant" || prompt === undefined || isDiscardedResponse(message)) continue;
86
+ if (message.role !== "assistant" || prompt === undefined && !orders || isDiscardedResponse(message)) continue;
75
87
  for (const block of message.content) {
76
88
  if (block.type !== "toolCall" || block.name !== "bash" || typeof (block.arguments as { command?: unknown })?.command !== "string") continue;
77
89
  const command = (block.arguments as { command: string }).command;
78
90
  // A leading "cd DIR &&" is not what the prompt names; classifyBash already recognizes it.
79
91
  const rest = classifyBash(command).directory === undefined ? command : command.slice(command.indexOf("&&") + 2);
80
92
  const lead = words(rest.split(/[|;&<>]|\d>/u)[0]!);
81
- if (lead.includes(" ") && prompt.includes(lead)) named.set(block.id, command);
93
+ if (lead.includes(" ") && (prompt?.includes(lead) || orders?.channels.some(channel => channel.includes(lead)))) named.set(block.id, command);
82
94
  }
83
95
  prompt = undefined;
84
96
  }
85
- const records: TranscriptRecord[] = [];
86
- let room = MAX_PROMPT_OUTPUT_CHARACTERS;
87
- for (const [id, command] of [...named].reverse()) {
88
- const entry = results.get(id), sourceIndex = entry && indices.get(entry.id);
97
+ const output = (entry: SessionEntry | undefined) => {
98
+ const sourceIndex = entry && indices.get(entry.id);
89
99
  if (entry?.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content) ||
90
- sourceIndex === undefined || !resolvable(entry)) continue;
100
+ sourceIndex === undefined || !resolvable(entry)) return undefined;
91
101
  const text = textOf(entry.message.content);
92
- if (!text.length) continue;
93
- const kept = text.length <= room ? text : `${text.slice(0, room)}\n… (truncated; whole output: tuck_recall {"index":${sourceIndex}})`;
94
- records.push({ kind: "section", title: "Kept-prompt-output", sourceIndex,
95
- text: `bash ${words(command)} (run as a user prompt asked; output as recorded at #${sourceIndex}):\n${kept}` });
96
- room -= Math.min(room, text.length);
97
- if (!room || records.length === MAX_PROMPT_OUTPUTS) break;
102
+ return text.length ? { sourceIndex, text } : undefined;
103
+ };
104
+ const record = (command: string, sourceIndex: number, kept: string): TranscriptRecord => ({ kind: "section", title: "Kept-prompt-output", sourceIndex,
105
+ text: `bash ${words(command)} (run as a user prompt asked; output as recorded at #${sourceIndex}):\n${kept}` });
106
+ const records: TranscriptRecord[] = [];
107
+ if (!orders) {
108
+ let room = MAX_PROMPT_OUTPUT_CHARACTERS;
109
+ for (const [id, command] of [...named].reverse()) {
110
+ const found = output(results.get(id));
111
+ if (!found) continue;
112
+ const { sourceIndex, text } = found;
113
+ records.push(record(command, sourceIndex, text.length <= room ? text : `${text.slice(0, room)}\n… (truncated; whole output: tuck_recall {"index":${sourceIndex}})`));
114
+ room -= Math.min(room, text.length);
115
+ if (!room || records.length === MAX_PROMPT_OUTPUTS) break;
116
+ }
117
+ return records;
118
+ }
119
+ const payloads = new Map<string, { command: string; sourceIndex: number; text: string }>(), seen = new Set<string>();
120
+ for (const [id, command] of named) {
121
+ const entry = results.get(id), found = output(entry);
122
+ if (!found || seen.has(found.text)) continue;
123
+ seen.add(found.text); payloads.set(entry!.id, { command, ...found });
124
+ }
125
+ const older: number[] = [];
126
+ let room = Math.max(0, orders.budget);
127
+ for (let at = entries.length - 1; at >= 0; at--) {
128
+ const entry = entries[at]!;
129
+ if (entry.type !== "message") continue;
130
+ if (entry.message.role === "user") { if (entry.id !== orders.firstUserId) room -= Math.min(room, textOf(entry.message.content).length); continue; }
131
+ const payload = payloads.get(entry.id);
132
+ if (!payload) continue;
133
+ const { command, sourceIndex, text } = payload, spare = room - clipText(text, 0, { index: sourceIndex }).length;
134
+ if (text.length > room && records.length && spare <= 0) { older.push(sourceIndex); continue; }
135
+ const kept = text.length <= room ? text : clipText(text, Math.max(0, spare), { index: sourceIndex });
136
+ records.push(record(command, sourceIndex, kept));
137
+ room -= Math.min(room, kept.length);
98
138
  }
139
+ if (older.length) records.push({ kind: "section", title: "Kept-prompt-output", sourceIndex: older[0]!,
140
+ text: `${older.length} older output${older.length === 1 ? "" : "s"} of these commands not shown; read one with tuck_recall {"index":N}, newest first: ${older.slice(0, MAX_ORDER_LOCATORS).join(", ")}${older.length > MAX_ORDER_LOCATORS ? ", …" : ""}` });
99
141
  return records;
100
142
  }
101
143
 
package/src/ledger.ts CHANGED
@@ -25,12 +25,17 @@ export const head = (text: string, max: number): string => {
25
25
  * `resolvable` says tuck_recall {index} reads the locator, so only then is it shown. A read whose result is missing points at its call. */
26
26
  export interface LedgerItem { path: string; operation: "wrote/edited" | "read"; sourceIndex?: number; locatorIndex?: number; resolvable: boolean; definitions?: FileObservation }
27
27
 
28
+ const resultsByCall = (entries: readonly SessionEntry[]): Map<string, SessionEntry> => {
29
+ const results = new Map<string, SessionEntry>();
30
+ for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
31
+ return results;
32
+ };
33
+
28
34
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
29
35
  * A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
30
36
  export function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean,
31
37
  failedCalls: ReadonlySet<string>, cwd?: string): LedgerItem[] {
32
- const results = new Map<string, SessionEntry>();
33
- for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
38
+ const results = resultsByCall(entries);
34
39
  const last = new Map<string, { path: string; operation: LedgerItem["operation"]; entry: SessionEntry; target: SessionEntry }>();
35
40
  for (const entry of entries) {
36
41
  if (entry.type !== "message" || entry.message.role !== "assistant") continue;
@@ -79,8 +84,7 @@ export interface ActionItem { text: string; failed: boolean; sourceIndex?: numbe
79
84
  * aborted response is not listed; a call whose result is an error is marked. */
80
85
  export function actionItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean,
81
86
  failedCalls: ReadonlySet<string>): ActionItem[] {
82
- const results = new Map<string, SessionEntry>();
83
- for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
87
+ const results = resultsByCall(entries);
84
88
  const calls: { text: string; failed: boolean; result?: SessionEntry; command: boolean }[] = [];
85
89
  for (const entry of entries) {
86
90
  if (entry.type !== "message" || entry.message.role !== "assistant") continue;
@@ -97,7 +97,7 @@ export function cleanupLegacyFiles(ctx: ExtensionContext): Promise<void> {
97
97
  if (process.platform === "win32" || !await realDirectory(root)) { started = true; return; }
98
98
  const children = await readdir(root);
99
99
  started = true;
100
- const names = [...directories, ...children.filter(name => temporaryDirectory.exec(name)?.[0] === name)];
100
+ const names = [...directories, ...children.filter(name => temporaryDirectory.test(name))];
101
101
  const candidates: string[] = [];
102
102
  for (const name of names) {
103
103
  const path = join(root, name);
@@ -13,6 +13,7 @@ const wire = (value: unknown): Wire => {
13
13
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a Chat Completions request");
14
14
  return value as Wire;
15
15
  };
16
+ const cancelled = (message: AssistantMessage): AssistantMessage => ({ ...message, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" });
16
17
  const promptTokens = (message: AssistantMessage) => message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
17
18
 
18
19
  export function llamaContinuationStream(profile: LlamaContinuation, native: ApiStreamSimpleFunction) {
@@ -103,7 +104,7 @@ export function llamaContinuationStream(profile: LlamaContinuation, native: ApiS
103
104
  clearTimeout(admissionTimer);
104
105
  }
105
106
  if (signal.aborted) {
106
- first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
107
+ first = cancelled(first);
107
108
  } else if (!cacheVerified) {
108
109
  first = { ...first, errorMessage: CONTINUATION_CACHE_MISS };
109
110
  } else if (second.stopReason !== "error" && second.stopReason !== "aborted" &&
@@ -151,7 +152,7 @@ export function llamaContinuationStream(profile: LlamaContinuation, native: ApiS
151
152
  } catch (error) {
152
153
  if (!first) throw error;
153
154
  if (signal.aborted)
154
- first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
155
+ first = cancelled(first);
155
156
  } finally {
156
157
  if (thinkingEnd) output.push(thinkingEnd);
157
158
  }
package/src/recall.ts CHANGED
@@ -61,6 +61,7 @@ export interface ReadableEntry {
61
61
  producerCall?: { sourceTime: SourceTime; name: string; id: string; arguments: Record<string, unknown> };
62
62
  }
63
63
 
64
+ type ProducerLink = NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime };
64
65
  interface DiscoveryEntry extends ReadableEntry {
65
66
  sourceText: string;
66
67
  ranges: { start: number; end: number }[];
@@ -117,7 +118,7 @@ function textContent(content: unknown, assistant = false): string {
117
118
  return readableContentParts(content, assistant).map(part => part.text).join("\n");
118
119
  }
119
120
 
120
- function readable(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime } >): ReadableEntry | undefined {
121
+ function readable(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>): ReadableEntry | undefined {
121
122
  if (!isHistorySource(entry)) return;
122
123
  let value: Omit<ReadableEntry, "entryId" | "sourceTime"> | undefined;
123
124
  if (entry.type === "compaction") value = { role: "compaction", text: entry.summary };
@@ -154,7 +155,7 @@ function producerReads(branch: readonly SessionEntry[]) {
154
155
  for (const entry of branch) identities.set(entry.id, (identities.get(entry.id) ?? 0) + 1);
155
156
  const usable = (entry: SessionEntry) => typeof entry.id === "string" && entry.id.length > 0 &&
156
157
  entry.id.length <= MAX_RECALL_ENTRY_ID_CHARACTERS && identities.get(entry.id) === 1 && isHistorySource(entry);
157
- type Call = { order: number; name: string; export?: boolean; read?: NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime } };
158
+ type Call = { order: number; name: string; export?: boolean; read?: ProducerLink };
158
159
  const calls = new Map<string, Call[]>(), receipts = new Map<string, { entry: SessionEntry; order: number; name: string }[]>();
159
160
  for (const [order, entry] of branch.entries()) {
160
161
  if (entry.type !== "message") continue;
@@ -182,7 +183,7 @@ function producerReads(branch: readonly SessionEntry[]) {
182
183
  }
183
184
  if (!valid || !usable(entry)) for (const call of local) delete call.read;
184
185
  }
185
- const links = new Map<string, NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime }>();
186
+ const links = new Map<string, ProducerLink>();
186
187
  for (const [id, producers] of calls) {
187
188
  const results = receipts.get(id), call = producers[0], result = results?.[0];
188
189
  if (producers.length === 1 && results?.length === 1 && call?.read && result && usable(result.entry) &&
@@ -193,7 +194,7 @@ function producerReads(branch: readonly SessionEntry[]) {
193
194
  }
194
195
 
195
196
  /** Match ranges address the unmodified readable source, including mixed messages. */
196
- function discoveryRanges(entry: SessionEntry, text: string, links?: ReadonlyMap<string, NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime } >): { start: number; end: number }[] {
197
+ function discoveryRanges(entry: SessionEntry, text: string, links?: ReadonlyMap<string, ProducerLink>): { start: number; end: number }[] {
197
198
  // Saved views repeat selected originals; discovery must not rank that repetition.
198
199
  // Explicit ID reads still expose the saved view through readable().
199
200
  if (entry.type === "compaction") return [];
@@ -214,7 +215,7 @@ function discoveryRanges(entry: SessionEntry, text: string, links?: ReadonlyMap<
214
215
  }
215
216
 
216
217
  /** Ranking uses filtered text; excerpts retain the original readable coordinates. */
217
- function discoveryEntry(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime } >): DiscoveryEntry | undefined {
218
+ function discoveryEntry(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, ProducerLink>): DiscoveryEntry | undefined {
218
219
  const row = readable(entry, attempts, links);
219
220
  if (!row) return;
220
221
  const ranges = discoveryRanges(entry, row.text, links);
@@ -287,16 +288,6 @@ function discoveryWholeRange(row: DiscoveryEntry, passage: ReturnType<typeof dis
287
288
  read: { entryId: row.entryId, offset: range.start, limit: range.end - range.start } };
288
289
  }
289
290
 
290
- /**
291
- * The host supplies this role's current branch; this function never opens a path.
292
- * Query is a case-insensitive literal over eligible source ranges. Offset/limit
293
- * page the concatenation of matching texts, with no added separators. Without an
294
- * explicit offset, a source-scoped query returns the whole matching readable
295
- * source when it fits, otherwise disjoint exact match windows;
296
- * unscoped browsing starts up to 120 characters before its first match.
297
- * Returned nextOffset uses the same filter and can page through any long entry.
298
- * At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
299
- */
300
291
  /** Add factual call context to a demanded complete receipt, never to discovery or partial pages. */
301
292
  function contextualReceipt(branch: readonly SessionEntry[], entryId: string | undefined, fragment: RecallFragment): RecallFragment {
302
293
  const read = fragment.producerRead;
@@ -318,6 +309,16 @@ function contextualReceipt(branch: readonly SessionEntry[], entryId: string | un
318
309
  } catch { return fragment; } // An incomplete or malformed prefix remains only a locator.
319
310
  }
320
311
 
312
+ /**
313
+ * The host supplies this role's current branch; this function never opens a path.
314
+ * Query is a case-insensitive literal over eligible source ranges. Offset/limit
315
+ * page the concatenation of matching texts, with no added separators. Without an
316
+ * explicit offset, a source-scoped query returns the whole matching readable
317
+ * source when it fits, otherwise disjoint exact match windows;
318
+ * unscoped browsing starts up to 120 characters before its first match.
319
+ * Returned nextOffset uses the same filter and can page through any long entry.
320
+ * At most 20 fragments and 16,000 text characters are returned; metadata is bounded.
321
+ */
321
322
  function recallHistory(branch: readonly SessionEntry[], options: RecallOptions = {}): RecallPage {
322
323
  const { query, entryId } = options;
323
324
  if (query !== undefined && (typeof query !== "string" || !query.length || query.length > MAX_RECALL_QUERY_CHARACTERS))
package/src/thrash.ts CHANGED
@@ -23,7 +23,6 @@ export function rereadsAfterCuts(branch: readonly SessionEntry[]): Rereads {
23
23
  if (message.role === "assistant") {
24
24
  if (isDiscardedResponse(message)) continue;
25
25
  if (epoch[i] !== current) { current = epoch[i]; replies = 0; }
26
- const cuts = current;
27
26
  replies++;
28
27
  for (const block of message.content) {
29
28
  if (block.type !== "toolCall" || block.name !== "read" || !block.arguments || typeof block.arguments !== "object") continue;
@@ -90,9 +90,8 @@ const bm25Score = (doc: string, terms: readonly KeywordMatcher[], ctx: BM25Conte
90
90
 
91
91
  /** Rank already-eligible recall rows; filtering and paging belong to the caller. */
92
92
  export const rankRecallRows = (rows: readonly { role: string; text: string }[], query: string): number[] => {
93
- const rawQuery = query.trim();
94
93
  const checkBudget = startBudget();
95
- const prepared = prepareKeywordQuery(rawQuery);
94
+ const prepared = prepareKeywordQuery(query);
96
95
  const terms = prepared.terms;
97
96
  // Preserve the role prefix and trailing space of the original BM25 documents.
98
97
  const docs = rows.map((row) => `${row.role} ${row.text} `);
package/src/tuck.ts CHANGED
@@ -7,7 +7,7 @@ import { carriedTailTokens, carriedTarget, conversationTokens } from "./budget";
7
7
  import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
8
8
  import { isTextOnly, textOf } from "./tuck/core/content";
9
9
  import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
10
- import { crossingRoundRecord, keptReadCandidates, promptOutputCandidates } from "./kept-reads.js";
10
+ import { crossingRoundRecord, keptReadCandidates, promptChannels, promptOutputCandidates } from "./kept-reads.js";
11
11
  import { workingSetCandidates, type WorkingFile } from "./working-set.js";
12
12
  import { keptSearchCandidates } from "./kept-searches.js";
13
13
  import { clipText } from "./clip.js";
@@ -71,6 +71,7 @@ export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: Ext
71
71
  export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean; keepRecentTokens?: number }, ctx: ExtensionContext,
72
72
  reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true): Draft {
73
73
  const { isHistorySource, readable } = createRecall(policy);
74
+ const resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
74
75
  const projected = ctx.sessionManager.buildSessionProjection();
75
76
  if (input.branchEntries.some(entry => entry.type === "context_edit" && entry.replacement !== null))
76
77
  return { unavailable: "pi-tuck does not support replacement context edits" };
@@ -183,9 +184,16 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
183
184
  const header = ctx.sessionManager.getHeader();
184
185
  if (!header) throw new Error("Missing native session header");
185
186
  const before = measure(projected.messages), room = Math.max(0, model.contextWindow - reserveTokens - 1);
186
- const minimumOpeningLength = 80, openingLength = Math.max(80, Math.floor(Math.sqrt(room * 4)));
187
+ const minimumOpeningLength = 80, openingLength = Math.max(minimumOpeningLength, Math.floor(Math.sqrt(room * 4)));
187
188
  // At most about a thirty-second of the room in tokens, so a small window keeps its cut room (1.12.1).
188
189
  const firstTurnCap = Math.min(FIRST_TURN_CHARACTERS, Math.floor(room / 8));
190
+ // A session whose user turns name a command ("Run: …") gets its orders as that command's output. There the first user turn, the later
191
+ // user turns and those outputs share twice the first turn's cap: the first turn takes what it shows, the rest go newest first. The
192
+ // outputs ride in every summary, reserved before the dialogue fills, and no more than `left` characters of the summary's own room.
193
+ const channels = promptChannels(entries);
194
+ const ordersAt = (boundary: number, left = Infinity) => channels.length ? promptOutputCandidates([header, ...entries.slice(0, boundary)], indices, resolvable,
195
+ { channels, firstUserId: firstUser?.id, budget: Math.min(left, 2 * firstTurnCap - (firstUser?.type === "message" && firstUser.message.role === "user" && firstUserPosition >= 0 && firstUserPosition < boundary
196
+ ? Math.min(firstTurnCap, textOf(firstUser.message.content).length) : 0)) }) : undefined;
189
197
  const positions = new Map(entries.map((entry, at) => [entry.id, at]));
190
198
  const originals = tuck.buildOwnCut(entries.filter(entry => entry.type !== "compaction"), 0);
191
199
  if (!originals.ok) return { unavailable: "No eligible original prefix to compile" };
@@ -322,8 +330,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
322
330
  // The last admission attempt and thinking-only retry share this exact floor: whole protected prompts, the smallest
323
331
  // existing summary representation, and the required fresh/native suffix. No historical fill or room target spends reply space.
324
332
  if (input.deepest) {
325
- // The floor carries the outputs prompts asked for (capped at 8,000 characters) and closes without claiming lists it does not have.
326
- const outputs = promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, entry => readable(entry) !== undefined);
333
+ // The floor carries the outputs prompts asked for (capped at 8,000 characters, or the shared cap of a session with a channel) and closes without claiming lists it does not have.
334
+ const outputs = ordersAt(floorBoundary) ?? promptOutputCandidates([header, ...entries.slice(0, floorBoundary)], indices, resolvable);
327
335
  const summary = (serializeTranscript([...calibrationHigh.rows, ...outputs]) || TRANSCRIPT_HEADER + "\n") + DEEPEST_SUFFIX;
328
336
  const projection = preview(summary, floorBoundary);
329
337
  assertNativeToolRounds(projection);
@@ -337,8 +345,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
337
345
  const listsAt = (boundary: number) => {
338
346
  const cached = listCache.get(boundary);
339
347
  if (cached) return cached;
340
- const compacted = entries.slice(0, boundary), resolves = (entry: SessionEntry) => readable(entry) !== undefined;
341
- const files = ledgerItems(compacted, indices, resolves, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolves, failedCalls);
348
+ const compacted = entries.slice(0, boundary);
349
+ const files = ledgerItems(compacted, indices, resolvable, failedCalls, header.cwd), actions = actionItems(compacted, indices, resolvable, failedCalls);
342
350
  const lists = { files, actions, records: [...actionRecords(actions), ...ledgerRecords(files)] };
343
351
  listCache.set(boundary, lists);
344
352
  return lists;
@@ -383,7 +391,6 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
383
391
  const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
384
392
  // The working set ranks above every other summary item and is paid for from the summary, never from the native tail: up to
385
393
  // WORKING_SET_SHARE of what the summary may spend beyond its protected prompts. Whole files only; one that does not fit is skipped.
386
- const resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
387
394
  const workingSet = workingSetCandidates(entries, boundary, indices, header.cwd, resolvable);
388
395
  if (workingSet.files.length) {
389
396
  const allowance = Math.floor(WORKING_SET_SHARE * Math.max(0, maxSummaryCharacters - frameLength(protectedView.cost, protectedView.rows.length)));
@@ -397,13 +404,14 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
397
404
  }
398
405
  const carriedKeys = new Set(carried.map(file => file.key));
399
406
  let ledger: TranscriptRecord[] = lists.records;
400
- let listedKeep = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
407
+ const maxListLines = Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES);
408
+ let listedKeep = maxListLines;
401
409
  // List caps are existing ranking policy; only the carried target is a
402
410
  // spending limit. Candidate list sizes have fixed, cached line prices.
403
411
  if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
404
412
  ledger = [];
405
413
  listedKeep = 0;
406
- for (let keep = 0; keep <= Math.min(Math.max(MAX_LEDGER_LINES, MAX_ACTION_LINES), Math.max(lists.files.length, lists.actions.length)); keep++) {
414
+ for (let keep = 0; keep <= Math.min(maxListLines, Math.max(lists.files.length, lists.actions.length)); keep++) {
407
415
  const candidate = [...actionRecords(lists.actions, keep), ...ledgerRecords(lists.files, keep)];
408
416
  if (price(frameLength(protectedView.cost + lineCost(candidate), protectedView.rows.length + candidate.length), boundary) <= target) {
409
417
  ledger = candidate; listedKeep = keep;
@@ -418,16 +426,17 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
418
426
  // The tool round the tail boundary passed (the one crossing the tail size) rides in the closing section, so the tail is not left far
419
427
  // below its size. It is paid from the summary, up to what the native tail leaves of that size, and is reserved before the dialogue fills.
420
428
  let crossingRound: TranscriptRecord | undefined;
421
- const briefRoom = Math.max(0, maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length));
429
+ const summaryRoom = maxSummaryCharacters - fixedCost - (suffix.length - DIALOGUE_SUFFIX.length);
430
+ const orders = ordersAt(boundary, summaryRoom), ordersCost = orders ? lineCost(orders) : 0;
431
+ const maxBriefChars = Math.max(0, summaryRoom - ordersCost);
422
432
  if (boundary === preferredBoundary && (preferredBoundary > originalBoundary || budgetCut) && boundary < entries.length) {
423
433
  const crossing = entries.slice(0, boundary).findLastIndex(entry => !(entry.type === "message" && entry.message.role === "toolResult"));
424
434
  const tail = crossing < 0 ? 0 : carriedTailTokens(Math.max(nativeAt(originalBoundary), nativeAt(crossing))) - nativeAt(boundary);
425
435
  // Like the working set, at most WORKING_SET_SHARE of what the summary may spend beyond its protected rows: the dialogue keeps the rest.
426
- const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * briefRoom / 4));
436
+ const size = Math.min(tail, Math.floor(WORKING_SET_SHARE * maxBriefChars / 4));
427
437
  if (size > 0) crossingRound = crossingRoundRecord(entries, boundary, indices, resolvable, size);
428
438
  }
429
439
  const crossingCost = crossingRound ? lineCost([crossingRound]) : 0;
430
- const maxBriefChars = briefRoom;
431
440
  const compileInput = { messages: sourceRows.map(row => row.message), sourceIndices: sourceRows.map(row => row.index),
432
441
  sourceEntryIds: sourceRows.map(row => row.id), sourceTimes: sourceRows.map(row => resolveSourceTime(entries[row.position]!)),
433
442
  ranking: { maxBriefChars, mandatorySourceIndices: mandatory } };
@@ -437,7 +446,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
437
446
  const compiledBoundary = boundary;
438
447
  // A protected custom prompt uses its native entry ID in the same anchoring/movement path as indexed user prompts.
439
448
  const sourceKey = (record: TranscriptRecord) => current?.type === "custom_message" && record.sourceEntryId === current.id ? current.id : record.sourceIndex;
440
- const keptResults: TranscriptRecord[] = [], thinking: TranscriptRecord[] = [];
449
+ const keptResults: TranscriptRecord[] = [...orders ?? []], thinking: TranscriptRecord[] = [];
441
450
  const assemble = (compiled: string, at = compiledBoundary) => {
442
451
  const split = compiled ? splitSummary(compiled) : undefined;
443
452
  if (compiled && !split) throw new Error("pi-tuck returned an invalid summary");
@@ -562,8 +571,8 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
562
571
  const counts = new Map<string, number>();
563
572
  const prefix = [header, ...entries.slice(0, boundary)];
564
573
  // Outputs a user prompt asked for lead (a message-driven agent's tasks); reads and searches follow, newest result first. One
565
- // allowance; L2's independent four-item caps and whole-item skips.
566
- const candidates = [...promptOutputCandidates(prefix, indices, resolvable), ...[...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
574
+ // allowance; L2's independent four-item caps and whole-item skips. A channel's outputs are already in, on their own cap.
575
+ const candidates = [...orders ? [] : promptOutputCandidates(prefix, indices, resolvable), ...[...keptReadCandidates(prefix, indices, resolvable, carriedKeys), ...keptSearchCandidates(prefix, indices, resolvable)]
567
576
  .sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"))];
568
577
  for (const record of candidates) {
569
578
  if ((counts.get(record.title!) ?? 0) === 4) continue;
@@ -649,7 +658,7 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
649
658
  missing.forEach((unit, at) => counts[at + 1] = counts[at]! + unit.count);
650
659
  return [{ role, missing, ends, counts, cost: lineCost([record]) }];
651
660
  });
652
- const baseCost = lineCost(offer.records) + lineCost(ledger) + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
661
+ const baseCost = lineCost(offer.records) + lineCost(ledger) + ordersCost + keptResultCost, baseCount = offer.records.length + ledger.length + keptResults.length;
653
662
  const keptResultIndices = new Set([...keptResults.map(record => record.sourceIndex), ...carried.map(file => file.sourceIndex)]);
654
663
  const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
655
664
  const extensionPrice = (at: number) => {