pi-tuck 1.3.4 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +58 -125
- package/dist/index.d.ts +1 -4
- package/dist/index.js +49 -10
- package/dist/src/budget.d.ts +6 -15
- package/dist/src/budget.js +6 -11
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +12 -20
- package/dist/src/compaction.js +220 -202
- package/dist/src/content-observations.d.ts +24 -0
- package/dist/src/content-observations.js +122 -0
- package/dist/src/diagnostics.d.ts +1 -3
- package/dist/src/ledger.d.ts +6 -3
- package/dist/src/ledger.js +14 -7
- package/dist/src/llama-continuation.d.ts +8 -0
- package/dist/src/llama-continuation.js +179 -0
- package/dist/src/recall.js +8 -25
- package/dist/src/request-capacity.d.ts +11 -26
- package/dist/src/request-capacity.js +20 -57
- package/dist/src/run.d.ts +16 -7
- package/dist/src/run.js +53 -25
- package/dist/src/status.d.ts +2 -0
- package/dist/src/status.js +6 -5
- package/dist/src/tuck/core/format.js +1 -1
- package/dist/src/tuck/core/readable-content.d.ts +14 -0
- package/dist/src/tuck/core/readable-content.js +43 -0
- package/dist/src/tuck.d.ts +2 -1
- package/dist/src/tuck.js +92 -30
- package/index.ts +42 -10
- package/package.json +1 -1
- package/src/budget.ts +7 -12
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +220 -193
- package/src/content-observations.ts +115 -0
- package/src/diagnostics.ts +1 -1
- package/src/ledger.ts +17 -10
- package/src/llama-continuation.ts +176 -0
- package/src/recall.ts +8 -20
- package/src/request-capacity.ts +18 -57
- package/src/run.ts +48 -22
- package/src/status.ts +8 -5
- package/src/tuck/core/format.ts +1 -1
- package/src/tuck/core/readable-content.ts +44 -0
- package/src/tuck.ts +79 -28
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { isDiscardedResponse } from "./protocol";
|
|
3
|
+
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
4
|
+
import { extractPath } from "./tuck/core/tool-args";
|
|
5
|
+
import { readableContentParts } from "./tuck/core/readable-content";
|
|
6
|
+
import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
7
|
+
import { MAX_RECALL_CHARACTERS } from "./recall";
|
|
8
|
+
|
|
9
|
+
export const MAX_OUTPUT_TAIL_LINES = 3;
|
|
10
|
+
export const MAX_OUTPUT_TAIL_CHARACTERS = 200;
|
|
11
|
+
export const MAX_DEFINITION_LINES = 40;
|
|
12
|
+
export const MAX_DEFINITION_CHARACTERS = 800;
|
|
13
|
+
|
|
14
|
+
/** Mechanical line matches only; no language detection or inferred symbols. */
|
|
15
|
+
export const DEFINITION_PATTERNS: readonly RegExp[] = [
|
|
16
|
+
/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:func|def|function)\b/u,
|
|
17
|
+
/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:type|struct|interface|class)\b/u,
|
|
18
|
+
/^\s*export\s+(?:const|let)\b/u,
|
|
19
|
+
/^\s*var\s*\(/u,
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
/** The last nonempty physical lines, with a leading marker whenever earlier text was cut.
|
|
23
|
+
* The marker and embedded newlines spend the same 200-character allowance. */
|
|
24
|
+
export function outputTail(output: string): string | undefined {
|
|
25
|
+
const lines = output.split(/\r\n|\n|\r/u).filter(line => line.trim());
|
|
26
|
+
if (!lines.length) return undefined;
|
|
27
|
+
let text = lines.slice(-MAX_OUTPUT_TAIL_LINES).join("\n");
|
|
28
|
+
const cut = lines.length > MAX_OUTPUT_TAIL_LINES || text.length > MAX_OUTPUT_TAIL_CHARACTERS;
|
|
29
|
+
if (text.length > MAX_OUTPUT_TAIL_CHARACTERS - Number(cut)) {
|
|
30
|
+
let start = text.length - (MAX_OUTPUT_TAIL_CHARACTERS - 1);
|
|
31
|
+
if (/[\uDC00-\uDFFF]/u.test(text[start]!)) start++;
|
|
32
|
+
text = text.slice(start);
|
|
33
|
+
}
|
|
34
|
+
return (cut ? "…" : "") + text;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Whole matching source lines, numbered in the file. Both caps include numbers and newlines. */
|
|
38
|
+
export function definitionLines(content: string, firstLine = 1): string | undefined {
|
|
39
|
+
const selected: string[] = [];
|
|
40
|
+
let characters = 0;
|
|
41
|
+
for (const [at, line] of content.split(/\r\n|\n|\r/u).entries()) {
|
|
42
|
+
if (!DEFINITION_PATTERNS.some(pattern => pattern.test(line))) continue;
|
|
43
|
+
const numbered = `${firstLine + at}: ${line}`;
|
|
44
|
+
const cost = numbered.length + Number(selected.length > 0);
|
|
45
|
+
if (selected.length === MAX_DEFINITION_LINES || characters + cost > MAX_DEFINITION_CHARACTERS) break;
|
|
46
|
+
selected.push(numbered); characters += cost;
|
|
47
|
+
}
|
|
48
|
+
return selected.length ? selected.join("\n") : undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface FileObservation { text: string; sourceIndex: number }
|
|
52
|
+
|
|
53
|
+
/** The newest available content for each requested path, including operations in the kept tail.
|
|
54
|
+
* An edit or a write without content invalidates older content. A read result can supply only
|
|
55
|
+
* its recorded lines, and never survive a mutation after its call, even if its result arrives later. */
|
|
56
|
+
export function fileObservations(paths: ReadonlySet<string>, entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>,
|
|
57
|
+
failedCalls: ReadonlySet<string>): Map<string, FileObservation> {
|
|
58
|
+
const known = new Map<string, FileObservation>(), generations = new Map<string, number>();
|
|
59
|
+
if (!paths.size) return known;
|
|
60
|
+
const reads = new Map<string, { path: string; generation: number; firstLine: number }>();
|
|
61
|
+
const remember = (path: string, content: string, sourceIndex: number | undefined, firstLine = 1) => {
|
|
62
|
+
known.delete(path);
|
|
63
|
+
const text = sourceIndex === undefined ? undefined : definitionLines(content, firstLine);
|
|
64
|
+
if (text && sourceIndex !== undefined) known.set(path, { text, sourceIndex });
|
|
65
|
+
};
|
|
66
|
+
for (const entry of entries) {
|
|
67
|
+
if (entry.type !== "message") continue;
|
|
68
|
+
const message = entry.message;
|
|
69
|
+
if (message.role === "assistant" && !isDiscardedResponse(message)) for (const block of message.content) {
|
|
70
|
+
if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) || failedCalls.has(block.id)) continue;
|
|
71
|
+
const args = block.arguments as Record<string, unknown> | undefined;
|
|
72
|
+
const path = args && extractPath(args);
|
|
73
|
+
if (!path || !paths.has(path)) continue;
|
|
74
|
+
if (block.name === "read") {
|
|
75
|
+
const offset = args!.offset;
|
|
76
|
+
// Unknown coordinate conventions cannot produce file line numbers.
|
|
77
|
+
if (offset !== undefined && (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 1)) continue;
|
|
78
|
+
reads.set(block.id, { path, generation: generations.get(path) ?? 0, firstLine: typeof offset === "number" ? offset : 1 });
|
|
79
|
+
} else {
|
|
80
|
+
generations.set(path, (generations.get(path) ?? 0) + 1);
|
|
81
|
+
known.delete(path);
|
|
82
|
+
if (block.name === "write" && typeof args!.content === "string") remember(path, args!.content, indices.get(entry.id));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (message.role === "toolResult") {
|
|
86
|
+
const read = reads.get(message.toolCallId);
|
|
87
|
+
if (read && !message.isError && read.generation === (generations.get(read.path) ?? 0)) {
|
|
88
|
+
// Image/unknown content supplies no textual file snapshot.
|
|
89
|
+
remember(read.path, isTextOnly(message.content) ? textOf(message.content) : "", indices.get(entry.id), read.firstLine);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return known;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Plain-thinking openings before the final kept tail, newest block first.
|
|
97
|
+
* Each pointer addresses the exact block in the message's readable text. */
|
|
98
|
+
export function* thinkingRecords(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, openingLength: number): Generator<TranscriptRecord> {
|
|
99
|
+
for (let at = entries.length - 1; at >= 0; at--) {
|
|
100
|
+
const entry = entries[at]!;
|
|
101
|
+
if (entry.type !== "message" || entry.message.role !== "assistant" || isDiscardedResponse(entry.message)) continue;
|
|
102
|
+
const sourceIndex = indices.get(entry.id);
|
|
103
|
+
if (sourceIndex === undefined) continue;
|
|
104
|
+
const parts = readableContentParts(entry.message.content, true);
|
|
105
|
+
for (let block = parts.length - 1; block >= 0; block--) {
|
|
106
|
+
const part = parts[block]!;
|
|
107
|
+
if (part.kind !== "thinking" || !part.text.trim()) continue;
|
|
108
|
+
let end = Math.min(part.text.length, openingLength);
|
|
109
|
+
if (end < part.text.length && /[\uD800-\uDBFF]/u.test(part.text[end - 1]!)) end++;
|
|
110
|
+
const locator = { index: sourceIndex, offset: part.offset, limit: Math.min(MAX_RECALL_CHARACTERS, part.text.length) };
|
|
111
|
+
yield { kind: "section", title: "Thinking", sourceIndex,
|
|
112
|
+
text: `Plain thinking opening (tuck_recall ${JSON.stringify(locator)}):\n${part.text.slice(0, end)}` };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
package/src/diagnostics.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { createRecall, type RecallPolicy } from './recall.js';
|
|
|
8
8
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
9
9
|
import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
|
|
10
10
|
export const DIAGNOSTIC_BUILD = BUILD_ID;
|
|
11
|
-
export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string;
|
|
11
|
+
export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string; activeInputCeilingTokens?: number | null }; before: { value: number; unit: 'estimated-input-tokens'; scope: 'native-preparation' | 'public-conversation' }; after: { value: number | null; unit: 'estimated-input-tokens'; scope: 'draft-preview' }; }
|
|
12
12
|
export function attachReceipt<T extends { details?: unknown; firstKeptEntryId: string; tokensBefore: number }>(draft: T, reason: string, reserveTokens: number, contextWindow: number, resolved: Partial<Receipt['settings']> = {}): T & { details: Record<string, unknown> & { diagnosticReceipt: Receipt } } {
|
|
13
13
|
const details = draft.details && typeof draft.details === 'object' ? draft.details as Record<string, unknown> : {};
|
|
14
14
|
const receipt: Receipt = { id: randomUUID(), build: DIAGNOSTIC_BUILD, reason, selectedView: typeof details.view === 'string' ? details.view : 'deterministic-selected-draft', boundary: draft.firstKeptEntryId, settings: { draftReservedTokens: reserveTokens, contextWindow, ...resolved }, before: { value: draft.tokensBefore, unit: 'estimated-input-tokens', scope: reason === 'tool-loop' || reason === 'run-end' || reason === 'prompt' ? 'public-conversation' : 'native-preparation' }, after: { value: typeof details.tokensAfter === 'number' ? details.tokensAfter : null, unit: 'estimated-input-tokens', scope: 'draft-preview' } };
|
package/src/ledger.ts
CHANGED
|
@@ -4,6 +4,8 @@ import { isDiscardedResponse } from "./protocol";
|
|
|
4
4
|
import { extractPath } from "./tuck/core/tool-args";
|
|
5
5
|
import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
6
6
|
import { pathKey } from "./path-key";
|
|
7
|
+
import { outputTail, type FileObservation } from "./content-observations";
|
|
8
|
+
import { textOf } from "./tuck/core/content";
|
|
7
9
|
|
|
8
10
|
/** Owner default; older distinct paths are counted, not listed. */
|
|
9
11
|
export const MAX_LEDGER_LINES = 60;
|
|
@@ -21,7 +23,7 @@ export const head = (text: string, max: number): string => {
|
|
|
21
23
|
* omission of the call removes the line). `locatorIndex` is the entry an agent wants back: for a read, the one holding its result (what
|
|
22
24
|
* the file showed; a live check, 2026-11-12: an agent asked for "#13" and got the call); for a write or edit, the call (what was written).
|
|
23
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. */
|
|
24
|
-
export interface LedgerItem { path: string; operation: "wrote/edited" | "read"; sourceIndex?: number; locatorIndex?: number; resolvable: boolean }
|
|
26
|
+
export interface LedgerItem { path: string; operation: "wrote/edited" | "read"; sourceIndex?: number; locatorIndex?: number; resolvable: boolean; definitions?: FileObservation }
|
|
25
27
|
|
|
26
28
|
/** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
|
|
27
29
|
* 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. */
|
|
@@ -53,11 +55,12 @@ export function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyM
|
|
|
53
55
|
|
|
54
56
|
/** 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.
|
|
55
57
|
* Each line carries its own source index, so a later native omission of that entry removes that line only. */
|
|
56
|
-
export function ledgerRecords(items: readonly LedgerItem[], keep = items.length): TranscriptRecord[] {
|
|
58
|
+
export function ledgerRecords(items: readonly LedgerItem[], keep = items.length, observations: ReadonlySet<LedgerItem> = new Set()): TranscriptRecord[] {
|
|
57
59
|
const listed = items.slice(0, Math.max(0, Math.min(keep, MAX_LEDGER_LINES)));
|
|
58
60
|
const line = (text: string, sourceIndex?: number): TranscriptRecord => ({ kind: "section", title: LEDGER_TITLE, text, ...(sourceIndex !== undefined ? { sourceIndex } : {}) });
|
|
59
61
|
return [line(LEDGER_HEADING),
|
|
60
|
-
...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.locatorIndex}})` : "")
|
|
62
|
+
...listed.map(item => line(`- ${item.operation} ${item.path}` + (item.resolvable ? ` (tuck_recall {"index":${item.locatorIndex}})` : "") +
|
|
63
|
+
(observations.has(item) && item.definitions ? ` (definitions as of #${item.definitions.sourceIndex}):\n${item.definitions.text}` : ""), item.sourceIndex)),
|
|
61
64
|
...(items.length ? [] : [line("(none)")]),
|
|
62
65
|
...(listed.length < items.length ? [line(`+${items.length - listed.length} older files: use tuck_recall`)] : [])];
|
|
63
66
|
}
|
|
@@ -66,11 +69,11 @@ export function ledgerRecords(items: readonly LedgerItem[], keep = items.length)
|
|
|
66
69
|
export const MAX_ACTION_LINES = 30;
|
|
67
70
|
export const MAX_ACTION_CHARACTERS = 200;
|
|
68
71
|
const ACTIONS_TITLE = "Actions";
|
|
69
|
-
export const ACTIONS_HEADING = "Tool calls other than read, write, edit and history lookups before this summary, newest first
|
|
72
|
+
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:";
|
|
70
73
|
|
|
71
74
|
/** One tool call other than a read, write, edit or history lookup: the file ledger and the dialogue cover those. `sourceIndex` is
|
|
72
75
|
* the entry holding its result, shown as a locator only where tuck_recall {index} reads it. */
|
|
73
|
-
export interface ActionItem { text: string; failed: boolean; sourceIndex?: number; resolvable: boolean }
|
|
76
|
+
export interface ActionItem { text: string; failed: boolean; sourceIndex?: number; resolvable: boolean; outputTail?: string }
|
|
74
77
|
|
|
75
78
|
/** The calls exactly as recorded, newest first, with the command (or else the arguments) flattened to one line. A call from a failed or
|
|
76
79
|
* aborted response is not listed; a call whose result is an error is marked. */
|
|
@@ -78,7 +81,7 @@ export function actionItems(entries: readonly SessionEntry[], indices: ReadonlyM
|
|
|
78
81
|
failedCalls: ReadonlySet<string>): ActionItem[] {
|
|
79
82
|
const results = new Map<string, SessionEntry>();
|
|
80
83
|
for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
|
|
81
|
-
const calls: { text: string; failed: boolean; result?: SessionEntry }[] = [];
|
|
84
|
+
const calls: { text: string; failed: boolean; result?: SessionEntry; command: boolean }[] = [];
|
|
82
85
|
for (const entry of entries) {
|
|
83
86
|
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
84
87
|
if (isDiscardedResponse(entry.message)) continue;
|
|
@@ -88,24 +91,28 @@ export function actionItems(entries: readonly SessionEntry[], indices: ReadonlyM
|
|
|
88
91
|
const what = typeof args?.command === "string" ? args.command : JSON.stringify(args ?? {});
|
|
89
92
|
const line = `${block.name}: ${what}`.replace(/\s+/gu, " ").trim();
|
|
90
93
|
calls.push({ text: line.length > MAX_ACTION_CHARACTERS ? head(line, MAX_ACTION_CHARACTERS - 1) + "…" : line,
|
|
91
|
-
failed: failedCalls.has(block.id), result: results.get(block.id) });
|
|
94
|
+
failed: failedCalls.has(block.id), result: results.get(block.id), command: typeof args?.command === "string" });
|
|
92
95
|
}
|
|
93
96
|
}
|
|
94
|
-
return calls.reverse().map(({ text, failed, result }, rank) => {
|
|
97
|
+
return calls.reverse().map(({ text, failed, result, command }, rank) => {
|
|
95
98
|
const sourceIndex = result && indices.get(result.id);
|
|
99
|
+
const tail = rank < MAX_ACTION_LINES && command && result?.type === "message" && result.message.role === "toolResult"
|
|
100
|
+
? outputTail(textOf(result.message.content)) : undefined;
|
|
96
101
|
return { text, failed, ...(sourceIndex !== undefined ? { sourceIndex } : {}),
|
|
102
|
+
...(tail ? { outputTail: tail } : {}),
|
|
97
103
|
resolvable: rank < MAX_ACTION_LINES && sourceIndex !== undefined && resolvable(result!) };
|
|
98
104
|
});
|
|
99
105
|
}
|
|
100
106
|
|
|
101
107
|
/** 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
|
|
102
108
|
* when there were no such calls. Each line carries its own source index, as the file ledger's do. */
|
|
103
|
-
export function actionRecords(items: readonly ActionItem[], keep = items.length): TranscriptRecord[] {
|
|
109
|
+
export function actionRecords(items: readonly ActionItem[], keep = items.length, observations: ReadonlySet<ActionItem> = new Set()): TranscriptRecord[] {
|
|
104
110
|
if (!items.length) return [];
|
|
105
111
|
const listed = items.slice(0, Math.max(0, Math.min(keep, MAX_ACTION_LINES)));
|
|
106
112
|
const line = (text: string, sourceIndex?: number): TranscriptRecord => ({ kind: "section", title: ACTIONS_TITLE, text, ...(sourceIndex !== undefined ? { sourceIndex } : {}) });
|
|
107
113
|
return [line(ACTIONS_HEADING),
|
|
108
114
|
...listed.map(item => line(`- ${item.text}` + (item.failed ? " (failed)" : "") +
|
|
109
|
-
(item.resolvable ? ` (output: tuck_recall {"index":${item.sourceIndex}})` : "")
|
|
115
|
+
(item.resolvable ? ` (output: tuck_recall {"index":${item.sourceIndex}})` : "") +
|
|
116
|
+
(observations.has(item) && item.outputTail ? ` (output tail):\n${item.outputTail}` : ""), item.sourceIndex)),
|
|
110
117
|
...(listed.length < items.length ? [line(`+${items.length - listed.length} older calls: use tuck_recall`)] : [])];
|
|
111
118
|
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { createAssistantMessageEventStream, type Api, type AssistantMessage, type AssistantMessageEvent, type Model, type SimpleStreamOptions, type TranscriptContext } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ApiStreamSimpleFunction } from "@earendil-works/pi-ai/compat";
|
|
3
|
+
import { CONTINUATION_CACHE_MISS } from "./status.js";
|
|
4
|
+
|
|
5
|
+
export interface LlamaContinuation {
|
|
6
|
+
model: string;
|
|
7
|
+
extraTokens: number;
|
|
8
|
+
deadlineMs: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
type Wire = Record<string, unknown>;
|
|
12
|
+
const wire = (value: unknown): Wire => {
|
|
13
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a Chat Completions request");
|
|
14
|
+
return value as Wire;
|
|
15
|
+
};
|
|
16
|
+
const promptTokens = (message: AssistantMessage) => message.usage.input + message.usage.cacheRead + message.usage.cacheWrite;
|
|
17
|
+
|
|
18
|
+
export function llamaContinuationStream(profile: LlamaContinuation, native: ApiStreamSimpleFunction) {
|
|
19
|
+
return (model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) => {
|
|
20
|
+
if (`${model.provider}/${model.id}` !== profile.model || (options && "disableContinuation" in options && options.disableContinuation) || !model.reasoning)
|
|
21
|
+
return native(model, context, options);
|
|
22
|
+
const output = createAssistantMessageEventStream();
|
|
23
|
+
const deadline = AbortSignal.timeout(profile.deadlineMs);
|
|
24
|
+
const signal = options?.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
|
|
25
|
+
|
|
26
|
+
void (async () => {
|
|
27
|
+
let first: AssistantMessage | undefined;
|
|
28
|
+
let firstRequest: Wire | undefined;
|
|
29
|
+
let thinkingEnd: Extract<AssistantMessageEvent, {type: "thinking_end"}> | undefined;
|
|
30
|
+
try {
|
|
31
|
+
const stream = native(model, context, {
|
|
32
|
+
...options, signal,
|
|
33
|
+
onPayload: async (value, actualModel) => {
|
|
34
|
+
// The gateway notices a disconnected client on its next write,
|
|
35
|
+
// including during a silent prompt prefill.
|
|
36
|
+
const withPing = { sse_ping_interval: 5, ...wire(value) };
|
|
37
|
+
const payload = (await options?.onPayload?.(withPing, actualModel)) ?? withPing;
|
|
38
|
+
firstRequest = structuredClone(wire(payload));
|
|
39
|
+
return payload;
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
for await (const event of stream) {
|
|
43
|
+
if (event.type === "done" || event.type === "error") continue;
|
|
44
|
+
if (event.type === "thinking_end" && event.partial.stopReason === "length" &&
|
|
45
|
+
event.contentIndex === 0 && event.partial.content.length === 1) {
|
|
46
|
+
thinkingEnd = event;
|
|
47
|
+
} else {
|
|
48
|
+
output.push(event);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
first = await stream.result();
|
|
52
|
+
const thought = first.content.length === 1 ? first.content[0] : undefined;
|
|
53
|
+
const initialPrompt = promptTokens(first);
|
|
54
|
+
const expectedPrompt = initialPrompt + first.usage.output;
|
|
55
|
+
const request = firstRequest;
|
|
56
|
+
const originalCap = request?.max_completion_tokens ?? request?.max_tokens;
|
|
57
|
+
// Only exhaustions at the full configured cap qualify. An input-clamped or
|
|
58
|
+
// server-clipped reply is Pi's capacity recovery case.
|
|
59
|
+
const remainder = Math.min(profile.extraTokens, model.contextWindow - expectedPrompt - 4096);
|
|
60
|
+
if (!signal.aborted && first.stopReason === "length" && thought?.type === "thinking" && thought.thinking &&
|
|
61
|
+
thinkingEnd && request && Array.isArray(request.messages) &&
|
|
62
|
+
originalCap === model.maxTokens && first.usage.output === model.maxTokens &&
|
|
63
|
+
Number.isSafeInteger(remainder) && remainder > 0 && initialPrompt > 0 &&
|
|
64
|
+
request.n_predict === undefined && request.continue_final_message === undefined) {
|
|
65
|
+
const messages = [...request.messages, { role: "assistant", content: "", reasoning_content: thought.thinking }];
|
|
66
|
+
const payload = { ...request, messages, max_completion_tokens: remainder, add_generation_prompt: false,
|
|
67
|
+
continue_final_message: "reasoning_content", return_progress: true } as Wire;
|
|
68
|
+
delete payload.max_tokens;
|
|
69
|
+
const admission = new AbortController();
|
|
70
|
+
const continuationSignal = AbortSignal.any([signal, admission.signal]);
|
|
71
|
+
let cacheVerified = false;
|
|
72
|
+
// Expect an initial report, before prompt evaluation. A server that cannot
|
|
73
|
+
// show reuse must not silently spend the deadline rebuilding the prompt.
|
|
74
|
+
const admissionTimer = setTimeout(() => admission.abort(), 15_000);
|
|
75
|
+
admissionTimer.unref();
|
|
76
|
+
// The native parser keeps streaming, handles cancellation and validates tool
|
|
77
|
+
// arguments. Only the completed combined response is returned to the agent loop.
|
|
78
|
+
let second: AssistantMessage;
|
|
79
|
+
try {
|
|
80
|
+
const continuation = native(model, context, {
|
|
81
|
+
...options, signal: continuationSignal, maxTokens: remainder, maxRetries: 0,
|
|
82
|
+
onPayload: async (_value, actualModel) => {
|
|
83
|
+
const expected = JSON.stringify(payload);
|
|
84
|
+
const next = (await options?.onPayload?.(payload, actualModel)) ?? payload;
|
|
85
|
+
if (JSON.stringify(next) !== expected) throw new Error("Continuation request changed by a provider hook");
|
|
86
|
+
return next;
|
|
87
|
+
},
|
|
88
|
+
onProviderStreamEvent: async (event, actualModel) => {
|
|
89
|
+
if (!cacheVerified && !admission.signal.aborted && event && typeof event === "object" && "prompt_progress" in event) {
|
|
90
|
+
const progress = wire(event.prompt_progress);
|
|
91
|
+
cacheVerified = progress.total === expectedPrompt &&
|
|
92
|
+
(progress.cache === expectedPrompt - 1 || progress.cache === expectedPrompt);
|
|
93
|
+
if (!cacheVerified) admission.abort();
|
|
94
|
+
clearTimeout(admissionTimer);
|
|
95
|
+
}
|
|
96
|
+
await options?.onProviderStreamEvent?.(event, actualModel);
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
// Release no tool actions until the terminal response confirms the prefix
|
|
100
|
+
// length and that the shared allowance still holds.
|
|
101
|
+
second = await continuation.result();
|
|
102
|
+
} finally {
|
|
103
|
+
clearTimeout(admissionTimer);
|
|
104
|
+
}
|
|
105
|
+
if (signal.aborted) {
|
|
106
|
+
first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
|
|
107
|
+
} else if (!cacheVerified) {
|
|
108
|
+
first = { ...first, errorMessage: CONTINUATION_CACHE_MISS };
|
|
109
|
+
} else if (second.stopReason !== "error" && second.stopReason !== "aborted" &&
|
|
110
|
+
promptTokens(second) === expectedPrompt &&
|
|
111
|
+
Number.isSafeInteger(second.usage.output) && second.usage.output > 0 && second.usage.output <= remainder) {
|
|
112
|
+
// A length stop cannot certify complete arguments. Keep the
|
|
113
|
+
// reasoning and any text, but do not offer a tool call to Pi.
|
|
114
|
+
const leading = second.content[0];
|
|
115
|
+
const suffix = leading?.type === "thinking" ? leading : undefined;
|
|
116
|
+
const rest = suffix ? second.content.slice(1) : second.content;
|
|
117
|
+
const blocks = second.stopReason === "length" ? rest.filter(block => block.type !== "toolCall") : rest;
|
|
118
|
+
const combined = { ...thought, thinking: thought.thinking + (suffix?.thinking ?? "") };
|
|
119
|
+
const outputTokens = first.usage.output + second.usage.output;
|
|
120
|
+
// Pi uses this as the size of one logical transcript prefix.
|
|
121
|
+
// The native stream hooks observe actual usage for each HTTP request.
|
|
122
|
+
const usage = { ...first.usage, output: outputTokens, totalTokens: initialPrompt + outputTokens };
|
|
123
|
+
first = { ...second, timestamp: first.timestamp, content: [combined, ...blocks], usage };
|
|
124
|
+
if (first.stopReason === "stop" && !blocks.some(block =>
|
|
125
|
+
block.type === "toolCall" || block.type === "text" && block.text.trim()))
|
|
126
|
+
first.stopReason = "length";
|
|
127
|
+
|
|
128
|
+
const partial = { ...first, content: [combined] };
|
|
129
|
+
if (suffix)
|
|
130
|
+
output.push({ type: "thinking_delta", contentIndex: 0, delta: suffix.thinking, partial });
|
|
131
|
+
output.push({ type: "thinking_end", contentIndex: 0, content: combined.thinking, partial });
|
|
132
|
+
thinkingEnd = undefined;
|
|
133
|
+
for (const [index, block] of blocks.entries()) {
|
|
134
|
+
const contentIndex = index + 1;
|
|
135
|
+
const partial = { ...first, content: first.content.slice(0, contentIndex + 1) };
|
|
136
|
+
if (block.type === "toolCall") {
|
|
137
|
+
output.push({ type: "toolcall_start", contentIndex, partial });
|
|
138
|
+
output.push({ type: "toolcall_end", contentIndex, partial, toolCall: block });
|
|
139
|
+
} else if (block.type === "text") {
|
|
140
|
+
output.push({ type: "text_start", contentIndex, partial });
|
|
141
|
+
output.push({ type: "text_delta", contentIndex, partial, delta: block.text });
|
|
142
|
+
output.push({ type: "text_end", contentIndex, partial, content: block.text });
|
|
143
|
+
} else {
|
|
144
|
+
output.push({ type: "thinking_start", contentIndex, partial });
|
|
145
|
+
output.push({ type: "thinking_delta", contentIndex, partial, delta: block.thinking });
|
|
146
|
+
output.push({ type: "thinking_end", contentIndex, partial, content: block.thinking });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (!first) throw error;
|
|
153
|
+
if (signal.aborted)
|
|
154
|
+
first = { ...first, stopReason: "aborted", errorMessage: "Continuation cancelled or deadline reached" };
|
|
155
|
+
} finally {
|
|
156
|
+
if (thinkingEnd) output.push(thinkingEnd);
|
|
157
|
+
}
|
|
158
|
+
if (!first) throw new Error("Provider returned no response");
|
|
159
|
+
if (first.stopReason === "error" || first.stopReason === "aborted")
|
|
160
|
+
output.push({ type: "error", reason: first.stopReason, error: first });
|
|
161
|
+
else if (first.stopReason !== "pending")
|
|
162
|
+
output.push({ type: "done", reason: first.stopReason, message: first });
|
|
163
|
+
else throw new Error("Provider returned an unfinished stream");
|
|
164
|
+
output.end();
|
|
165
|
+
})().catch(error => {
|
|
166
|
+
const reason = signal.aborted ? "aborted" : "error";
|
|
167
|
+
output.push({type: "error", reason, error: {
|
|
168
|
+
role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(),
|
|
169
|
+
content: [], stopReason: reason, errorMessage: String(error),
|
|
170
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
171
|
+
}});
|
|
172
|
+
output.end();
|
|
173
|
+
});
|
|
174
|
+
return output;
|
|
175
|
+
};
|
|
176
|
+
}
|
package/src/recall.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resolveSourceTime, type SourceTime } from "./tuck/core/source-time";
|
|
2
2
|
import { isSourceExport, isLookupTool, isRecallTool } from "./tuck/core/recall-operation";
|
|
3
3
|
import { escapeRegex } from "./tuck/core/keyword-query";
|
|
4
|
+
import { readableContentParts } from "./tuck/core/readable-content";
|
|
4
5
|
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
5
6
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
6
7
|
export interface RecallOptions {
|
|
@@ -112,18 +113,8 @@ function isToolSource(entry: SessionEntry): boolean {
|
|
|
112
113
|
|
|
113
114
|
|
|
114
115
|
|
|
115
|
-
function textContent(content: unknown,
|
|
116
|
-
|
|
117
|
-
if (!Array.isArray(content)) return "";
|
|
118
|
-
const blocks: unknown[] = content;
|
|
119
|
-
return blocks.flatMap((block) => {
|
|
120
|
-
if (block === null || typeof block !== "object" || !("type" in block)) return [];
|
|
121
|
-
if (block.type === "text" && "text" in block && typeof block.text === "string") return [block.text];
|
|
122
|
-
if (includeToolCalls && block.type === "toolCall" && "name" in block && typeof block.name === "string"
|
|
123
|
-
&& "id" in block && typeof block.id === "string" && "arguments" in block)
|
|
124
|
-
return [JSON.stringify({ toolCall: { name: block.name, id: block.id, arguments: block.arguments } })];
|
|
125
|
-
return [];
|
|
126
|
-
}).join("\n");
|
|
116
|
+
function textContent(content: unknown, assistant = false): string {
|
|
117
|
+
return readableContentParts(content, assistant).map(part => part.text).join("\n");
|
|
127
118
|
}
|
|
128
119
|
|
|
129
120
|
function readable(entry: SessionEntry, attempts?: ReadonlyMap<string, RecordedAttempt | null>, links?: ReadonlyMap<string, NonNullable<ReadableEntry["producerRead"]> & { sourceTime: SourceTime } >): ReadableEntry | undefined {
|
|
@@ -178,7 +169,8 @@ function producerReads(branch: readonly SessionEntry[]) {
|
|
|
178
169
|
const call = block.type === "toolCall" && typeof block.id === "string" && block.id ?
|
|
179
170
|
{ order, name: block.name } as Call : undefined;
|
|
180
171
|
if (call && block.type === "toolCall") { call.export = isSourceExport(block.arguments); const group = calls.get(block.id) ?? []; group.push(call); calls.set(block.id, group); local.push(call); }
|
|
181
|
-
// Exactly the
|
|
172
|
+
// Exactly the public prefix admitted by textContent, including empty
|
|
173
|
+
// text/newlines. Plain thinking is appended after this prefix.
|
|
182
174
|
if (!(block.type === "text" && typeof block.text === "string" || block.type === "toolCall" &&
|
|
183
175
|
typeof block.name === "string" && typeof block.id === "string" && "arguments" in block)) continue;
|
|
184
176
|
try {
|
|
@@ -210,17 +202,13 @@ function discoveryRanges(entry: SessionEntry, text: string, links?: ReadonlyMap<
|
|
|
210
202
|
if (message.role === "toolResult" && isLookupTool(message.toolName) && !links?.has(entry.id)) return [];
|
|
211
203
|
if (message.role !== "assistant") return [{ start: 0, end: text.length }];
|
|
212
204
|
const ranges: { start: number; end: number }[] = [];
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
if (
|
|
216
|
-
const part = textContent([block], true);
|
|
217
|
-
const end = position + part.length;
|
|
218
|
-
if (block.type !== "toolCall" || !isLookupTool(block.name) || isRecallTool(block.name) && isSourceExport(block.arguments)) {
|
|
205
|
+
for (const part of readableContentParts(message.content, true)) {
|
|
206
|
+
const position = part.offset, end = position + part.text.length;
|
|
207
|
+
if (part.kind !== "toolCall" || !isLookupTool(part.toolName!) || isRecallTool(part.toolName!) && isSourceExport(part.arguments)) {
|
|
219
208
|
const previous = ranges.at(-1);
|
|
220
209
|
if (previous && previous.end + 1 === position) previous.end = end;
|
|
221
210
|
else ranges.push({ start: position, end });
|
|
222
211
|
}
|
|
223
|
-
position = end + 1;
|
|
224
212
|
}
|
|
225
213
|
return ranges.filter(({ start, end }) => end > start);
|
|
226
214
|
}
|
package/src/request-capacity.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { normalizeContext } from '@earendil-works/pi-ai';
|
|
2
2
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
3
3
|
import type { AgentMessage, Messages } from './budget.js';
|
|
4
4
|
import { parseRecords, splitSummary } from './tuck/core/transcript.js';
|
|
@@ -51,71 +51,32 @@ export async function piContextSafetyMargin(math?: PiRequestMath): Promise<numbe
|
|
|
51
51
|
} catch { return 4_096; }
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
/**
|
|
55
|
-
export const REPLY_FLOOR_MIN = 3_584;
|
|
56
|
-
|
|
57
|
-
/** A spent thinking budget that produced neither a visible answer nor work. Empty/text/tool replies keep the existing length recovery. */
|
|
54
|
+
/** A length stop with visible reasoning but no visible answer or work. */
|
|
58
55
|
export const thinkingOnlyLength = (message: AgentMessage): boolean => message.role === 'assistant' && message.stopReason === 'length' &&
|
|
59
56
|
message.content.length > 0 && message.content.every(block => block.type === 'thinking');
|
|
60
57
|
|
|
61
|
-
|
|
62
|
-
export const needsFullReplyReserve = (message: AgentMessage): boolean => message.role === 'assistant' &&
|
|
63
|
-
(message.stopReason === 'length' && !thinkingOnlyLength(message) || message.stopReason === 'error' && isContextOverflow(message));
|
|
58
|
+
type ReplyModel = { provider: string; api: string; id: string; maxTokens: number };
|
|
64
59
|
|
|
65
|
-
/**
|
|
66
|
-
|
|
67
|
-
* configured window is unchanged: a server or catalogue that grew must not stay capped by an old clip (Nautilus, 2026-11-20). */
|
|
68
|
-
export interface WindowReceipt { calibrationIdentity: string; learnedContextWindow: number; catalogueContextWindow: number; serverClippedReplyId: string }
|
|
69
|
-
export const WINDOW_RECEIPT = 'pi-tuck-window';
|
|
70
|
-
function windowSettings(entry: SessionEntry): Partial<WindowReceipt> | undefined {
|
|
71
|
-
if (entry.type === 'custom' && entry.customType === WINDOW_RECEIPT) return entry.data as Partial<WindowReceipt> | undefined;
|
|
72
|
-
if (entry.type === 'compaction') return (entry.details as { diagnosticReceipt?: { settings?: Partial<WindowReceipt> } } | undefined)?.diagnosticReceipt?.settings;
|
|
73
|
-
return undefined;
|
|
74
|
-
}
|
|
75
|
-
/** The newest learned window for `identity`, if it was learned under the model's current configured window. One recorded before 1.3.3
|
|
76
|
-
* carries no configured window and is not trusted: if the server still clips, the next clipped reply learns it again. */
|
|
77
|
-
export function seedContextWindow(branch: readonly SessionEntry[], identity: string, catalogue: number | undefined): number | undefined {
|
|
78
|
-
for (let i = branch.length; i--;) {
|
|
79
|
-
const settings = windowSettings(branch[i]!);
|
|
80
|
-
if (settings?.calibrationIdentity !== identity) continue;
|
|
81
|
-
const window = settings.learnedContextWindow;
|
|
82
|
-
if (!(Number.isSafeInteger(window) && window! > 0)) return undefined;
|
|
83
|
-
return catalogue !== undefined && settings.catalogueContextWindow === catalogue ? window : undefined;
|
|
84
|
-
}
|
|
85
|
-
return undefined;
|
|
86
|
-
}
|
|
60
|
+
/** Reply room a cut above the room aims for before any long reply is seen. Cuts only: admission keeps the observed floor. */
|
|
61
|
+
export const CUT_REPLY_FLOOR = 3_584;
|
|
87
62
|
|
|
88
|
-
/**
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if (receipt && Number.isSafeInteger(receipt.learnedContextWindow) && receipt.learnedContextWindow! > 0 &&
|
|
96
|
-
typeof receipt.serverClippedReplyId === 'string') clipped.add(receipt.serverClippedReplyId);
|
|
63
|
+
/** Ordinary reply demand is bounded by the reserve and model output limit.
|
|
64
|
+
* Recovery compares its candidate against the interrupted attempt separately. */
|
|
65
|
+
export function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, model: ReplyModel, minimum = 1): number {
|
|
66
|
+
const reserved = Math.max(1, reserve);
|
|
67
|
+
const limit = model.maxTokens > 0 ? Math.min(reserved, model.maxTokens) : reserved;
|
|
68
|
+
let largest = minimum;
|
|
69
|
+
for (const entry of branch) {
|
|
97
70
|
if (entry.type !== 'message' || entry.message.role !== 'assistant') continue;
|
|
98
71
|
const message = entry.message;
|
|
99
|
-
|
|
100
|
-
|
|
72
|
+
if (message.model !== model.id || message.provider !== model.provider || message.api !== model.api ||
|
|
73
|
+
message.stopReason === 'error' || message.stopReason === 'aborted') continue;
|
|
101
74
|
const output = message.usage?.output;
|
|
102
|
-
if (typeof output
|
|
75
|
+
if (typeof output !== 'number' || !Number.isFinite(output) || output <= 0) continue;
|
|
76
|
+
largest = Math.max(largest, output);
|
|
77
|
+
if (largest >= limit) break;
|
|
103
78
|
}
|
|
104
|
-
return
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
export function branchReplyFloor(branch: readonly SessionEntry[], reserve: number): number {
|
|
108
|
-
const { failed, largestOutput, thinkingStop } = replyFit(branch);
|
|
109
|
-
if (failed) return reserve;
|
|
110
|
-
// Include exhausted thinking output across cuts/restarts; requestReplyFloor applies the model cap.
|
|
111
|
-
const largest = Math.ceil(Math.max(REPLY_FLOOR_MIN, largestOutput));
|
|
112
|
-
return thinkingStop ? largest : Math.min(reserve, largest);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/** Admission never promises more output than a model with a positive reply cap can produce. */
|
|
116
|
-
export function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, maxTokens?: number): number {
|
|
117
|
-
const floor = branchReplyFloor(branch, reserve);
|
|
118
|
-
return maxTokens !== undefined && maxTokens > 0 ? Math.min(floor, maxTokens) : floor;
|
|
79
|
+
return Math.min(limit, Math.ceil(largest));
|
|
119
80
|
}
|
|
120
81
|
|
|
121
82
|
/** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
|