pi-tuck 1.3.4 → 1.5.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +67 -122
  3. package/dist/index.d.ts +1 -4
  4. package/dist/index.js +56 -10
  5. package/dist/src/budget.d.ts +6 -15
  6. package/dist/src/budget.js +6 -11
  7. package/dist/src/build-id.d.ts +1 -1
  8. package/dist/src/build-id.js +1 -1
  9. package/dist/src/compaction.d.ts +15 -20
  10. package/dist/src/compaction.js +236 -204
  11. package/dist/src/content-observations.d.ts +24 -0
  12. package/dist/src/content-observations.js +122 -0
  13. package/dist/src/diagnostics.d.ts +1 -3
  14. package/dist/src/footer.d.ts +37 -0
  15. package/dist/src/footer.js +91 -0
  16. package/dist/src/ledger.d.ts +6 -3
  17. package/dist/src/ledger.js +14 -7
  18. package/dist/src/llama-continuation.d.ts +8 -0
  19. package/dist/src/llama-continuation.js +179 -0
  20. package/dist/src/recall.js +8 -25
  21. package/dist/src/request-capacity.d.ts +11 -26
  22. package/dist/src/request-capacity.js +20 -57
  23. package/dist/src/run.d.ts +16 -7
  24. package/dist/src/run.js +53 -25
  25. package/dist/src/status.d.ts +9 -0
  26. package/dist/src/status.js +14 -9
  27. package/dist/src/tuck/core/format.js +1 -1
  28. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  29. package/dist/src/tuck/core/readable-content.js +43 -0
  30. package/dist/src/tuck.d.ts +2 -1
  31. package/dist/src/tuck.js +92 -30
  32. package/index.ts +46 -10
  33. package/package.json +3 -1
  34. package/src/budget.ts +7 -12
  35. package/src/build-id.ts +1 -1
  36. package/src/compaction.ts +228 -194
  37. package/src/content-observations.ts +115 -0
  38. package/src/diagnostics.ts +1 -1
  39. package/src/footer.ts +111 -0
  40. package/src/ledger.ts +17 -10
  41. package/src/llama-continuation.ts +176 -0
  42. package/src/recall.ts +8 -20
  43. package/src/request-capacity.ts +18 -57
  44. package/src/run.ts +48 -22
  45. package/src/status.ts +20 -9
  46. package/src/tuck/core/format.ts +1 -1
  47. package/src/tuck/core/readable-content.ts +44 -0
  48. package/src/tuck.ts +79 -28
@@ -0,0 +1,24 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
+ export declare const MAX_OUTPUT_TAIL_LINES = 3;
4
+ export declare const MAX_OUTPUT_TAIL_CHARACTERS = 200;
5
+ export declare const MAX_DEFINITION_LINES = 40;
6
+ export declare const MAX_DEFINITION_CHARACTERS = 800;
7
+ /** Mechanical line matches only; no language detection or inferred symbols. */
8
+ export declare const DEFINITION_PATTERNS: readonly RegExp[];
9
+ /** The last nonempty physical lines, with a leading marker whenever earlier text was cut.
10
+ * The marker and embedded newlines spend the same 200-character allowance. */
11
+ export declare function outputTail(output: string): string | undefined;
12
+ /** Whole matching source lines, numbered in the file. Both caps include numbers and newlines. */
13
+ export declare function definitionLines(content: string, firstLine?: number): string | undefined;
14
+ export interface FileObservation {
15
+ text: string;
16
+ sourceIndex: number;
17
+ }
18
+ /** The newest available content for each requested path, including operations in the kept tail.
19
+ * An edit or a write without content invalidates older content. A read result can supply only
20
+ * its recorded lines, and never survive a mutation after its call, even if its result arrives later. */
21
+ export declare function fileObservations(paths: ReadonlySet<string>, entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, failedCalls: ReadonlySet<string>): Map<string, FileObservation>;
22
+ /** Plain-thinking openings before the final kept tail, newest block first.
23
+ * Each pointer addresses the exact block in the message's readable text. */
24
+ export declare function thinkingRecords(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, openingLength: number): Generator<TranscriptRecord>;
@@ -0,0 +1,122 @@
1
+ import { isDiscardedResponse } from "./protocol.js";
2
+ import { isTextOnly, textOf } from "./tuck/core/content.js";
3
+ import { extractPath } from "./tuck/core/tool-args.js";
4
+ import { readableContentParts } from "./tuck/core/readable-content.js";
5
+ import { MAX_RECALL_CHARACTERS } from "./recall.js";
6
+ export const MAX_OUTPUT_TAIL_LINES = 3;
7
+ export const MAX_OUTPUT_TAIL_CHARACTERS = 200;
8
+ export const MAX_DEFINITION_LINES = 40;
9
+ export const MAX_DEFINITION_CHARACTERS = 800;
10
+ /** Mechanical line matches only; no language detection or inferred symbols. */
11
+ export const DEFINITION_PATTERNS = [
12
+ /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:func|def|function)\b/u,
13
+ /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:type|struct|interface|class)\b/u,
14
+ /^\s*export\s+(?:const|let)\b/u,
15
+ /^\s*var\s*\(/u,
16
+ ];
17
+ /** The last nonempty physical lines, with a leading marker whenever earlier text was cut.
18
+ * The marker and embedded newlines spend the same 200-character allowance. */
19
+ export function outputTail(output) {
20
+ const lines = output.split(/\r\n|\n|\r/u).filter(line => line.trim());
21
+ if (!lines.length)
22
+ return undefined;
23
+ let text = lines.slice(-MAX_OUTPUT_TAIL_LINES).join("\n");
24
+ const cut = lines.length > MAX_OUTPUT_TAIL_LINES || text.length > MAX_OUTPUT_TAIL_CHARACTERS;
25
+ if (text.length > MAX_OUTPUT_TAIL_CHARACTERS - Number(cut)) {
26
+ let start = text.length - (MAX_OUTPUT_TAIL_CHARACTERS - 1);
27
+ if (/[\uDC00-\uDFFF]/u.test(text[start]))
28
+ start++;
29
+ text = text.slice(start);
30
+ }
31
+ return (cut ? "…" : "") + text;
32
+ }
33
+ /** Whole matching source lines, numbered in the file. Both caps include numbers and newlines. */
34
+ export function definitionLines(content, firstLine = 1) {
35
+ const selected = [];
36
+ let characters = 0;
37
+ for (const [at, line] of content.split(/\r\n|\n|\r/u).entries()) {
38
+ if (!DEFINITION_PATTERNS.some(pattern => pattern.test(line)))
39
+ continue;
40
+ const numbered = `${firstLine + at}: ${line}`;
41
+ const cost = numbered.length + Number(selected.length > 0);
42
+ if (selected.length === MAX_DEFINITION_LINES || characters + cost > MAX_DEFINITION_CHARACTERS)
43
+ break;
44
+ selected.push(numbered);
45
+ characters += cost;
46
+ }
47
+ return selected.length ? selected.join("\n") : undefined;
48
+ }
49
+ /** The newest available content for each requested path, including operations in the kept tail.
50
+ * An edit or a write without content invalidates older content. A read result can supply only
51
+ * its recorded lines, and never survive a mutation after its call, even if its result arrives later. */
52
+ export function fileObservations(paths, entries, indices, failedCalls) {
53
+ const known = new Map(), generations = new Map();
54
+ if (!paths.size)
55
+ return known;
56
+ const reads = new Map();
57
+ const remember = (path, content, sourceIndex, firstLine = 1) => {
58
+ known.delete(path);
59
+ const text = sourceIndex === undefined ? undefined : definitionLines(content, firstLine);
60
+ if (text && sourceIndex !== undefined)
61
+ known.set(path, { text, sourceIndex });
62
+ };
63
+ for (const entry of entries) {
64
+ if (entry.type !== "message")
65
+ continue;
66
+ const message = entry.message;
67
+ if (message.role === "assistant" && !isDiscardedResponse(message))
68
+ for (const block of message.content) {
69
+ if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) || failedCalls.has(block.id))
70
+ continue;
71
+ const args = block.arguments;
72
+ const path = args && extractPath(args);
73
+ if (!path || !paths.has(path))
74
+ continue;
75
+ if (block.name === "read") {
76
+ const offset = args.offset;
77
+ // Unknown coordinate conventions cannot produce file line numbers.
78
+ if (offset !== undefined && (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 1))
79
+ continue;
80
+ reads.set(block.id, { path, generation: generations.get(path) ?? 0, firstLine: typeof offset === "number" ? offset : 1 });
81
+ }
82
+ else {
83
+ generations.set(path, (generations.get(path) ?? 0) + 1);
84
+ known.delete(path);
85
+ if (block.name === "write" && typeof args.content === "string")
86
+ remember(path, args.content, indices.get(entry.id));
87
+ }
88
+ }
89
+ if (message.role === "toolResult") {
90
+ const read = reads.get(message.toolCallId);
91
+ if (read && !message.isError && read.generation === (generations.get(read.path) ?? 0)) {
92
+ // Image/unknown content supplies no textual file snapshot.
93
+ remember(read.path, isTextOnly(message.content) ? textOf(message.content) : "", indices.get(entry.id), read.firstLine);
94
+ }
95
+ }
96
+ }
97
+ return known;
98
+ }
99
+ /** Plain-thinking openings before the final kept tail, newest block first.
100
+ * Each pointer addresses the exact block in the message's readable text. */
101
+ export function* thinkingRecords(entries, indices, openingLength) {
102
+ for (let at = entries.length - 1; at >= 0; at--) {
103
+ const entry = entries[at];
104
+ if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message))
105
+ continue;
106
+ const sourceIndex = indices.get(entry.id);
107
+ if (sourceIndex === undefined)
108
+ continue;
109
+ const parts = readableContentParts(entry.message.content, true);
110
+ for (let block = parts.length - 1; block >= 0; block--) {
111
+ const part = parts[block];
112
+ if (part.kind !== "thinking" || !part.text.trim())
113
+ continue;
114
+ let end = Math.min(part.text.length, openingLength);
115
+ if (end < part.text.length && /[\uD800-\uDBFF]/u.test(part.text[end - 1]))
116
+ end++;
117
+ const locator = { index: sourceIndex, offset: part.offset, limit: Math.min(MAX_RECALL_CHARACTERS, part.text.length) };
118
+ yield { kind: "section", title: "Thinking", sourceIndex,
119
+ text: `Plain thinking opening (tuck_recall ${JSON.stringify(locator)}):\n${part.text.slice(0, end)}` };
120
+ }
121
+ }
122
+ }
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "6a84733ab75ecf863fe77c6dd6d0a91602a8a0d353a785c3fdb34585f42637a2";
3
+ export declare const DIAGNOSTIC_BUILD = "afdb81c50c0608b05013bc64aee8a7ff9f4100d7f7e3da9784a7ac789f92aff3";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -19,8 +19,6 @@ export interface Receipt {
19
19
  calibrationFactor?: number;
20
20
  calibrationWindow?: number[];
21
21
  calibrationIdentity?: string;
22
- learnedContextWindow?: number;
23
- catalogueContextWindow?: number;
24
22
  activeInputCeilingTokens?: number | null;
25
23
  };
26
24
  before: {
@@ -0,0 +1,37 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ /**
3
+ * pi-tuck's footer in place of Pi's: the folder and branch line, then how full the context is against pi-tuck's trim point (a full bar
4
+ * means pi-tuck trims), the trim count once there is one, the cost when there is one, and the model; other extensions' statuses below. The figures are computed only after
5
+ * a reply, a trim, or a model or thinking change, and cached; a render reads the cache and Pi's own cached branch and statuses. It reads;
6
+ * it changes nothing the model sees.
7
+ */
8
+ export interface FooterFigures {
9
+ /** Context tokens as Pi reports them, or the last trim's size (estimated) right after a trim, before the next reply. */
10
+ tokens: number | null;
11
+ estimated: boolean;
12
+ /** pi-tuck's trim point in tokens (the band), when pi-tuck is active for this model. */
13
+ cut: number | undefined;
14
+ /** pi-tuck trims on this branch so far. */
15
+ cuts: number;
16
+ window: number;
17
+ cost: number;
18
+ model: string;
19
+ pwd: string;
20
+ session: string | undefined;
21
+ }
22
+ /** The part of Pi's theme the footer uses. */
23
+ export interface FooterTheme {
24
+ fg(color: "dim" | "warning", text: string): string;
25
+ }
26
+ /** Context at or above this share of the trim point shows in the warning color. */
27
+ export declare const NEAR_CUT = 0.85;
28
+ /** Pi's compact token format (its footer's formatTokens). */
29
+ export declare const formatTokens: (n: number) => string;
30
+ /** Everything a render needs, from the session as it is now. The one place the footer reads the session. */
31
+ export declare function footerFigures(ctx: ExtensionContext, cutPoint: number | undefined, thinking: string | undefined): FooterFigures;
32
+ /** A bar of `cells` cells that fills toward the trim point: full means pi-tuck trims. */
33
+ export declare function gauge(f: Pick<FooterFigures, "tokens" | "cut">, cells: number): string;
34
+ /** The footer's lines at this width, from the cached figures. Dim when healthy; the bar and size turn yellow near the trim point. */
35
+ export declare function footerLines(f: FooterFigures, width: number, theme: FooterTheme, branch: string | null, statuses: ReadonlyMap<string, string>): string[];
36
+ /** Replace Pi's footer while a UI is present. `cutPoint` is the compactor's own trim point (the number `/tuck` shows). */
37
+ export declare function installFooter(pi: ExtensionAPI, cutPoint: (ctx: ExtensionContext) => number | undefined): void;
@@ -0,0 +1,91 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { tuckCuts } from "./status.js";
3
+ /** Context at or above this share of the trim point shows in the warning color. */
4
+ export const NEAR_CUT = 0.85;
5
+ const BAR = 10;
6
+ /** Pi's compact token format (its footer's formatTokens). */
7
+ export const formatTokens = (n) => n < 1000 ? `${n}` : n < 10_000 ? `${(n / 1000).toFixed(1)}k` : n < 1_000_000 ? `${Math.round(n / 1000)}k`
8
+ : n < 10_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1_000_000)}M`;
9
+ const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
10
+ /** Everything a render needs, from the session as it is now. The one place the footer reads the session. */
11
+ export function footerFigures(ctx, cutPoint, thinking) {
12
+ let cost = 0;
13
+ // As Pi's footer: cost from all entries (every branch), including usage carried by summaries and tool results.
14
+ for (const entry of ctx.sessionManager.getEntries())
15
+ cost += num((entry.type === "message" ? entry.message?.usage : entry.usage)?.cost?.total);
16
+ const ours = tuckCuts(ctx.sessionManager.getBranch()), usage = ctx.getContextUsage();
17
+ let tokens = usage?.tokens ?? null, estimated = false;
18
+ // Pi does not know the context size between a trim and the next reply; pi-tuck's trim recorded what it left.
19
+ const after = ours.at(-1)?.details?.tokensAfter;
20
+ if (tokens === null && typeof after === "number") {
21
+ tokens = after;
22
+ estimated = true;
23
+ }
24
+ const home = process.env.HOME || process.env.USERPROFILE;
25
+ const pwd = home && (ctx.cwd === home || ctx.cwd.startsWith(home + "/") || ctx.cwd.startsWith(home + "\\")) ? "~" + ctx.cwd.slice(home.length) : ctx.cwd;
26
+ const model = ctx.model ? ctx.model.reasoning ? `${ctx.model.id} · ${thinking && thinking !== "off" ? thinking : "thinking off"}` : ctx.model.id : "no-model";
27
+ return { tokens, estimated, cut: cutPoint, cuts: ours.length, window: usage?.contextWindow ?? ctx.model?.contextWindow ?? 0, cost, model, pwd, session: ctx.sessionManager.getSessionName?.() };
28
+ }
29
+ /** A bar of `cells` cells that fills toward the trim point: full means pi-tuck trims. */
30
+ export function gauge(f, cells) {
31
+ const filled = f.cut && f.cut > 0 ? Math.min(cells, Math.max(0, Math.round((f.tokens ?? 0) / f.cut * cells))) : 0;
32
+ return "█".repeat(filled) + "░".repeat(cells - filled);
33
+ }
34
+ /** The footer's lines at this width, from the cached figures. Dim when healthy; the bar and size turn yellow near the trim point. */
35
+ export function footerLines(f, width, theme, branch, statuses) {
36
+ const dim = (s) => theme.fg("dim", s);
37
+ const near = f.tokens !== null && f.cut !== undefined && f.tokens >= f.cut * NEAR_CUT;
38
+ const hot = (s) => theme.fg(near ? "warning" : "dim", s);
39
+ const size = f.tokens === null ? "?" : (f.estimated ? "~" : "") + formatTokens(f.tokens);
40
+ // Against the trim point; with no trim point (pi-tuck off, or no window), against the window when Pi knows it.
41
+ const of = f.cut ?? (f.window > 0 ? f.window : undefined);
42
+ const amount = (f.cut === undefined ? "" : `${gauge(f, BAR)} `) + size + (of === undefined ? "" : ` of ${formatTokens(of)}`);
43
+ const cost = f.cost > 0 ? ` · $${f.cost.toFixed(f.cost < 0.01 ? 3 : 2)}` : "";
44
+ const trims = f.cuts > 0 ? ` · ${f.cuts} trim${f.cuts === 1 ? "" : "s"}` : "";
45
+ const wide = dim("context ") + hot(amount) + dim(trims + cost);
46
+ const room = width - visibleWidth(wide) - visibleWidth(f.model);
47
+ // The whole line when it fits, else only the bar and the sizes.
48
+ const stats = room >= 2 ? wide + dim(" ".repeat(room) + f.model) : truncateToWidth(hot(amount), width, dim("..."));
49
+ const pwd = f.pwd + (branch ? ` (${branch})` : "") + (f.session ? ` • ${f.session}` : "");
50
+ const lines = [truncateToWidth(dim(pwd), width, dim("...")), stats];
51
+ if (statuses.size > 0)
52
+ lines.push(truncateToWidth([...statuses.entries()].sort(([a], [b]) => a.localeCompare(b))
53
+ .map(([, text]) => text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim()).join(" "), width, dim("...")));
54
+ return lines;
55
+ }
56
+ /** Replace Pi's footer while a UI is present. `cutPoint` is the compactor's own trim point (the number `/tuck` shows). */
57
+ export function installFooter(pi, cutPoint) {
58
+ let figures;
59
+ let redraw;
60
+ const refresh = (ctx) => {
61
+ if (!ctx.hasUI)
62
+ return;
63
+ try {
64
+ figures = footerFigures(ctx, cutPoint(ctx), pi.getThinkingLevel?.());
65
+ redraw?.();
66
+ }
67
+ catch { /* an ended session keeps the last figures */ }
68
+ };
69
+ const show = (ctx) => {
70
+ if (!ctx.hasUI)
71
+ return;
72
+ refresh(ctx);
73
+ try {
74
+ ctx.ui.setFooter((tui, theme, data) => {
75
+ redraw = () => tui.requestRender();
76
+ const unsubscribe = data.onBranchChange(() => tui.requestRender());
77
+ return {
78
+ render: (width) => figures ? footerLines(figures, width, theme, data.getGitBranch(), data.getExtensionStatuses()) : [],
79
+ invalidate: () => { },
80
+ dispose: () => { unsubscribe(); redraw = undefined; },
81
+ };
82
+ });
83
+ }
84
+ catch { /* a host without a footer keeps its own */ }
85
+ };
86
+ pi.on("session_start", (_event, ctx) => show(ctx));
87
+ // After a reply, a trim, a tree move, or a model or thinking change. pi-tuck saves its trims as turn_end and agent_before_settle entries,
88
+ // which Pi appends after every handler has run; the next turn_start and agent_settled come after both the reply and the trim are saved.
89
+ for (const event of ["turn_start", "agent_settled", "session_compact", "session_tree", "model_select", "thinking_level_select"])
90
+ pi.on(event, (_event, ctx) => refresh(ctx));
91
+ }
@@ -1,5 +1,6 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
+ import { type FileObservation } from "./content-observations.js";
3
4
  /** Owner default; older distinct paths are counted, not listed. */
4
5
  export declare const MAX_LEDGER_LINES = 60;
5
6
  export declare const LEDGER_HEADING = "Files touched by read, write and edit before this summary, newest first, with the last operation:";
@@ -15,17 +16,18 @@ export interface LedgerItem {
15
16
  sourceIndex?: number;
16
17
  locatorIndex?: number;
17
18
  resolvable: boolean;
19
+ definitions?: FileObservation;
18
20
  }
19
21
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
20
22
  * 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. */
21
23
  export declare function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, failedCalls: ReadonlySet<string>, cwd?: string): LedgerItem[];
22
24
  /** The ledger: a heading, one record per listed path (at most `keep` and the line cap, newest first), then a count of the older ones.
23
25
  * Each line carries its own source index, so a later native omission of that entry removes that line only. */
24
- export declare function ledgerRecords(items: readonly LedgerItem[], keep?: number): TranscriptRecord[];
26
+ export declare function ledgerRecords(items: readonly LedgerItem[], keep?: number, observations?: ReadonlySet<LedgerItem>): TranscriptRecord[];
25
27
  /** Owner defaults: the newest calls are listed, each on one line of at most this many characters; older ones are counted. */
26
28
  export declare const MAX_ACTION_LINES = 30;
27
29
  export declare const MAX_ACTION_CHARACTERS = 200;
28
- export declare const ACTIONS_HEADING = "Tool calls other than read, write, edit and history lookups before this summary, newest first, without their output:";
30
+ export declare const ACTIONS_HEADING = "Tool calls other than read, write, edit and history lookups before this summary, newest first; command output tails when room permits:";
29
31
  /** One tool call other than a read, write, edit or history lookup: the file ledger and the dialogue cover those. `sourceIndex` is
30
32
  * the entry holding its result, shown as a locator only where tuck_recall {index} reads it. */
31
33
  export interface ActionItem {
@@ -33,10 +35,11 @@ export interface ActionItem {
33
35
  failed: boolean;
34
36
  sourceIndex?: number;
35
37
  resolvable: boolean;
38
+ outputTail?: string;
36
39
  }
37
40
  /** The calls exactly as recorded, newest first, with the command (or else the arguments) flattened to one line. A call from a failed or
38
41
  * aborted response is not listed; a call whose result is an error is marked. */
39
42
  export declare function actionItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, failedCalls: ReadonlySet<string>): ActionItem[];
40
43
  /** The action trail: a heading, one record per listed call (at most `keep` and the line cap), then a count of the older ones; nothing
41
44
  * when there were no such calls. Each line carries its own source index, as the file ledger's do. */
42
- export declare function actionRecords(items: readonly ActionItem[], keep?: number): TranscriptRecord[];
45
+ export declare function actionRecords(items: readonly ActionItem[], keep?: number, observations?: ReadonlySet<ActionItem>): TranscriptRecord[];
@@ -2,6 +2,8 @@ import { isLookupTool } from "./tuck/core/recall-operation.js";
2
2
  import { isDiscardedResponse } from "./protocol.js";
3
3
  import { extractPath } from "./tuck/core/tool-args.js";
4
4
  import { pathKey } from "./path-key.js";
5
+ import { outputTail } from "./content-observations.js";
6
+ import { textOf } from "./tuck/core/content.js";
5
7
  /** Owner default; older distinct paths are counted, not listed. */
6
8
  export const MAX_LEDGER_LINES = 60;
7
9
  const LEDGER_TITLE = "Files";
@@ -47,11 +49,12 @@ export function ledgerItems(entries, indices, resolvable, failedCalls, cwd) {
47
49
  }
48
50
  /** The ledger: a heading, one record per listed path (at most `keep` and the line cap, newest first), then a count of the older ones.
49
51
  * Each line carries its own source index, so a later native omission of that entry removes that line only. */
50
- export function ledgerRecords(items, keep = items.length) {
52
+ export function ledgerRecords(items, keep = items.length, observations = new Set()) {
51
53
  const listed = items.slice(0, Math.max(0, Math.min(keep, MAX_LEDGER_LINES)));
52
54
  const line = (text, sourceIndex) => ({ kind: "section", title: LEDGER_TITLE, text, ...(sourceIndex !== undefined ? { sourceIndex } : {}) });
53
55
  return [line(LEDGER_HEADING),
54
- ...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.locatorIndex}})` : ""), item.sourceIndex)),
56
+ ...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.locatorIndex}})` : "") +
57
+ (observations.has(item) && item.definitions ? ` (definitions as of #${item.definitions.sourceIndex}):\n${item.definitions.text}` : ""), item.sourceIndex)),
55
58
  ...(items.length ? [] : [line("(none)")]),
56
59
  ...(listed.length < items.length ? [line(`+${items.length - listed.length} older files: use tuck_recall`)] : [])];
57
60
  }
@@ -59,7 +62,7 @@ export function ledgerRecords(items, keep = items.length) {
59
62
  export const MAX_ACTION_LINES = 30;
60
63
  export const MAX_ACTION_CHARACTERS = 200;
61
64
  const ACTIONS_TITLE = "Actions";
62
- export const ACTIONS_HEADING = "Tool calls other than read, write, edit and history lookups before this summary, newest first, without their output:";
65
+ export const ACTIONS_HEADING = "Tool calls other than read, write, edit and history lookups before this summary, newest first; command output tails when room permits:";
63
66
  /** The calls exactly as recorded, newest first, with the command (or else the arguments) flattened to one line. A call from a failed or
64
67
  * aborted response is not listed; a call whose result is an error is marked. */
65
68
  export function actionItems(entries, indices, resolvable, failedCalls) {
@@ -80,24 +83,28 @@ export function actionItems(entries, indices, resolvable, failedCalls) {
80
83
  const what = typeof args?.command === "string" ? args.command : JSON.stringify(args ?? {});
81
84
  const line = `${block.name}: ${what}`.replace(/\s+/gu, " ").trim();
82
85
  calls.push({ text: line.length > MAX_ACTION_CHARACTERS ? head(line, MAX_ACTION_CHARACTERS - 1) + "…" : line,
83
- failed: failedCalls.has(block.id), result: results.get(block.id) });
86
+ failed: failedCalls.has(block.id), result: results.get(block.id), command: typeof args?.command === "string" });
84
87
  }
85
88
  }
86
- return calls.reverse().map(({ text, failed, result }, rank) => {
89
+ return calls.reverse().map(({ text, failed, result, command }, rank) => {
87
90
  const sourceIndex = result && indices.get(result.id);
91
+ const tail = rank < MAX_ACTION_LINES && command && result?.type === "message" && result.message.role === "toolResult"
92
+ ? outputTail(textOf(result.message.content)) : undefined;
88
93
  return { text, failed, ...(sourceIndex !== undefined ? { sourceIndex } : {}),
94
+ ...(tail ? { outputTail: tail } : {}),
89
95
  resolvable: rank < MAX_ACTION_LINES && sourceIndex !== undefined && resolvable(result) };
90
96
  });
91
97
  }
92
98
  /** The action trail: a heading, one record per listed call (at most `keep` and the line cap), then a count of the older ones; nothing
93
99
  * when there were no such calls. Each line carries its own source index, as the file ledger's do. */
94
- export function actionRecords(items, keep = items.length) {
100
+ export function actionRecords(items, keep = items.length, observations = new Set()) {
95
101
  if (!items.length)
96
102
  return [];
97
103
  const listed = items.slice(0, Math.max(0, Math.min(keep, MAX_ACTION_LINES)));
98
104
  const line = (text, sourceIndex) => ({ kind: "section", title: ACTIONS_TITLE, text, ...(sourceIndex !== undefined ? { sourceIndex } : {}) });
99
105
  return [line(ACTIONS_HEADING),
100
106
  ...listed.map(item => line(`- ${item.text}` + (item.failed ? " (failed)" : "") +
101
- (item.resolvable ? ` (output: tuck_recall {"index":${item.sourceIndex}})` : ""), item.sourceIndex)),
107
+ (item.resolvable ? ` (output: tuck_recall {"index":${item.sourceIndex}})` : "") +
108
+ (observations.has(item) && item.outputTail ? ` (output tail):\n${item.outputTail}` : ""), item.sourceIndex)),
102
109
  ...(listed.length < items.length ? [line(`+${items.length - listed.length} older calls: use tuck_recall`)] : [])];
103
110
  }
@@ -0,0 +1,8 @@
1
+ import { type Api, type Model, type SimpleStreamOptions, type TranscriptContext } from "@earendil-works/pi-ai";
2
+ import type { ApiStreamSimpleFunction } from "@earendil-works/pi-ai/compat";
3
+ export interface LlamaContinuation {
4
+ model: string;
5
+ extraTokens: number;
6
+ deadlineMs: number;
7
+ }
8
+ export declare function llamaContinuationStream(profile: LlamaContinuation, native: ApiStreamSimpleFunction): (model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) => import("@earendil-works/pi-ai").AssistantMessageEventStream;
@@ -0,0 +1,179 @@
1
+ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
2
+ import { CONTINUATION_CACHE_MISS } from "./status.js";
3
+ const wire = (value) => {
4
+ if (!value || typeof value !== "object" || Array.isArray(value))
5
+ throw new Error("Expected a Chat Completions request");
6
+ return value;
7
+ };
8
+ const promptTokens = (message) => message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
9
+ export function llamaContinuationStream(profile, native) {
10
+ return (model, context, options) => {
11
+ if (`${model.provider}/${model.id}` !== profile.model || (options && "disableContinuation" in options && options.disableContinuation) || !model.reasoning)
12
+ return native(model, context, options);
13
+ const output = createAssistantMessageEventStream();
14
+ const deadline = AbortSignal.timeout(profile.deadlineMs);
15
+ const signal = options?.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
16
+ void (async () => {
17
+ let first;
18
+ let firstRequest;
19
+ let thinkingEnd;
20
+ try {
21
+ const stream = native(model, context, {
22
+ ...options, signal,
23
+ onPayload: async (value, actualModel) => {
24
+ // The gateway notices a disconnected client on its next write,
25
+ // including during a silent prompt prefill.
26
+ const withPing = { sse_ping_interval: 5, ...wire(value) };
27
+ const payload = (await options?.onPayload?.(withPing, actualModel)) ?? withPing;
28
+ firstRequest = structuredClone(wire(payload));
29
+ return payload;
30
+ },
31
+ });
32
+ for await (const event of stream) {
33
+ if (event.type === "done" || event.type === "error")
34
+ continue;
35
+ if (event.type === "thinking_end" && event.partial.stopReason === "length" &&
36
+ event.contentIndex === 0 && event.partial.content.length === 1) {
37
+ thinkingEnd = event;
38
+ }
39
+ else {
40
+ output.push(event);
41
+ }
42
+ }
43
+ first = await stream.result();
44
+ const thought = first.content.length === 1 ? first.content[0] : undefined;
45
+ const initialPrompt = promptTokens(first);
46
+ const expectedPrompt = initialPrompt + first.usage.output;
47
+ const request = firstRequest;
48
+ const originalCap = request?.max_completion_tokens ?? request?.max_tokens;
49
+ // Only exhaustions at the full configured cap qualify. An input-clamped or
50
+ // server-clipped reply is Pi's capacity recovery case.
51
+ const remainder = Math.min(profile.extraTokens, model.contextWindow - expectedPrompt - 4096);
52
+ if (!signal.aborted && first.stopReason === "length" && thought?.type === "thinking" && thought.thinking &&
53
+ thinkingEnd && request && Array.isArray(request.messages) &&
54
+ originalCap === model.maxTokens && first.usage.output === model.maxTokens &&
55
+ Number.isSafeInteger(remainder) && remainder > 0 && initialPrompt > 0 &&
56
+ request.n_predict === undefined && request.continue_final_message === undefined) {
57
+ const messages = [...request.messages, { role: "assistant", content: "", reasoning_content: thought.thinking }];
58
+ const payload = { ...request, messages, max_completion_tokens: remainder, add_generation_prompt: false,
59
+ continue_final_message: "reasoning_content", return_progress: true };
60
+ delete payload.max_tokens;
61
+ const admission = new AbortController();
62
+ const continuationSignal = AbortSignal.any([signal, admission.signal]);
63
+ let cacheVerified = false;
64
+ // Expect an initial report, before prompt evaluation. A server that cannot
65
+ // show reuse must not silently spend the deadline rebuilding the prompt.
66
+ const admissionTimer = setTimeout(() => admission.abort(), 15_000);
67
+ admissionTimer.unref();
68
+ // The native parser keeps streaming, handles cancellation and validates tool
69
+ // arguments. Only the completed combined response is returned to the agent loop.
70
+ let second;
71
+ try {
72
+ const continuation = native(model, context, {
73
+ ...options, signal: continuationSignal, maxTokens: remainder, maxRetries: 0,
74
+ onPayload: async (_value, actualModel) => {
75
+ const expected = JSON.stringify(payload);
76
+ const next = (await options?.onPayload?.(payload, actualModel)) ?? payload;
77
+ if (JSON.stringify(next) !== expected)
78
+ throw new Error("Continuation request changed by a provider hook");
79
+ return next;
80
+ },
81
+ onProviderStreamEvent: async (event, actualModel) => {
82
+ if (!cacheVerified && !admission.signal.aborted && event && typeof event === "object" && "prompt_progress" in event) {
83
+ const progress = wire(event.prompt_progress);
84
+ cacheVerified = progress.total === expectedPrompt &&
85
+ (progress.cache === expectedPrompt - 1 || progress.cache === expectedPrompt);
86
+ if (!cacheVerified)
87
+ admission.abort();
88
+ clearTimeout(admissionTimer);
89
+ }
90
+ await options?.onProviderStreamEvent?.(event, actualModel);
91
+ },
92
+ });
93
+ // Release no tool actions until the terminal response confirms the prefix
94
+ // length and that the shared allowance still holds.
95
+ second = await continuation.result();
96
+ }
97
+ finally {
98
+ clearTimeout(admissionTimer);
99
+ }
100
+ if (signal.aborted) {
101
+ first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
102
+ }
103
+ else if (!cacheVerified) {
104
+ first = { ...first, errorMessage: CONTINUATION_CACHE_MISS };
105
+ }
106
+ else if (second.stopReason !== "error" && second.stopReason !== "aborted" &&
107
+ promptTokens(second) === expectedPrompt &&
108
+ Number.isSafeInteger(second.usage.output) && second.usage.output > 0 && second.usage.output <= remainder) {
109
+ // A length stop cannot certify complete arguments. Keep the
110
+ // reasoning and any text, but do not offer a tool call to Pi.
111
+ const leading = second.content[0];
112
+ const suffix = leading?.type === "thinking" ? leading : undefined;
113
+ const rest = suffix ? second.content.slice(1) : second.content;
114
+ const blocks = second.stopReason === "length" ? rest.filter(block => block.type !== "toolCall") : rest;
115
+ const combined = { ...thought, thinking: thought.thinking + (suffix?.thinking ?? "") };
116
+ const outputTokens = first.usage.output + second.usage.output;
117
+ // Pi uses this as the size of one logical transcript prefix.
118
+ // The native stream hooks observe actual usage for each HTTP request.
119
+ const usage = { ...first.usage, output: outputTokens, totalTokens: initialPrompt + outputTokens };
120
+ first = { ...second, timestamp: first.timestamp, content: [combined, ...blocks], usage };
121
+ if (first.stopReason === "stop" && !blocks.some(block => block.type === "toolCall" || block.type === "text" && block.text.trim()))
122
+ first.stopReason = "length";
123
+ const partial = { ...first, content: [combined] };
124
+ if (suffix)
125
+ output.push({ type: "thinking_delta", contentIndex: 0, delta: suffix.thinking, partial });
126
+ output.push({ type: "thinking_end", contentIndex: 0, content: combined.thinking, partial });
127
+ thinkingEnd = undefined;
128
+ for (const [index, block] of blocks.entries()) {
129
+ const contentIndex = index + 1;
130
+ const partial = { ...first, content: first.content.slice(0, contentIndex + 1) };
131
+ if (block.type === "toolCall") {
132
+ output.push({ type: "toolcall_start", contentIndex, partial });
133
+ output.push({ type: "toolcall_end", contentIndex, partial, toolCall: block });
134
+ }
135
+ else if (block.type === "text") {
136
+ output.push({ type: "text_start", contentIndex, partial });
137
+ output.push({ type: "text_delta", contentIndex, partial, delta: block.text });
138
+ output.push({ type: "text_end", contentIndex, partial, content: block.text });
139
+ }
140
+ else {
141
+ output.push({ type: "thinking_start", contentIndex, partial });
142
+ output.push({ type: "thinking_delta", contentIndex, partial, delta: block.thinking });
143
+ output.push({ type: "thinking_end", contentIndex, partial, content: block.thinking });
144
+ }
145
+ }
146
+ }
147
+ }
148
+ }
149
+ catch (error) {
150
+ if (!first)
151
+ throw error;
152
+ if (signal.aborted)
153
+ first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
154
+ }
155
+ finally {
156
+ if (thinkingEnd)
157
+ output.push(thinkingEnd);
158
+ }
159
+ if (!first)
160
+ throw new Error("Provider returned no response");
161
+ if (first.stopReason === "error" || first.stopReason === "aborted")
162
+ output.push({ type: "error", reason: first.stopReason, error: first });
163
+ else if (first.stopReason !== "pending")
164
+ output.push({ type: "done", reason: first.stopReason, message: first });
165
+ else
166
+ throw new Error("Provider returned an unfinished stream");
167
+ output.end();
168
+ })().catch(error => {
169
+ const reason = signal.aborted ? "aborted" : "error";
170
+ output.push({ type: "error", reason, error: {
171
+ role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(),
172
+ content: [], stopReason: reason, errorMessage: String(error),
173
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
174
+ } });
175
+ output.end();
176
+ });
177
+ return output;
178
+ };
179
+ }