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,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 = "
|
|
3
|
+
export declare const DIAGNOSTIC_BUILD = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
|
|
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: {
|
package/dist/src/ledger.d.ts
CHANGED
|
@@ -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
|
|
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[];
|
package/dist/src/ledger.js
CHANGED
|
@@ -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}})` : "")
|
|
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
|
|
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}})` : "")
|
|
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
|
+
}
|
package/dist/src/recall.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { resolveSourceTime } from "./tuck/core/source-time.js";
|
|
2
2
|
import { isSourceExport, isLookupTool, isRecallTool } from "./tuck/core/recall-operation.js";
|
|
3
3
|
import { escapeRegex } from "./tuck/core/keyword-query.js";
|
|
4
|
+
import { readableContentParts } from "./tuck/core/readable-content.js";
|
|
4
5
|
export const MAX_RECALL_CHARACTERS = 16000;
|
|
5
6
|
export const MAX_RECALL_QUERY_CHARACTERS = 256;
|
|
6
7
|
export const MAX_RECALL_ENTRY_ID_CHARACTERS = 100;
|
|
@@ -56,22 +57,8 @@ export function createRecall(policy = {}) {
|
|
|
56
57
|
(entry.message.role === "assistant" && entry.message.content.some((b) => b.type === "toolCall")) ||
|
|
57
58
|
entry.message.role === "bashExecution");
|
|
58
59
|
}
|
|
59
|
-
function textContent(content,
|
|
60
|
-
|
|
61
|
-
return content;
|
|
62
|
-
if (!Array.isArray(content))
|
|
63
|
-
return "";
|
|
64
|
-
const blocks = content;
|
|
65
|
-
return blocks.flatMap((block) => {
|
|
66
|
-
if (block === null || typeof block !== "object" || !("type" in block))
|
|
67
|
-
return [];
|
|
68
|
-
if (block.type === "text" && "text" in block && typeof block.text === "string")
|
|
69
|
-
return [block.text];
|
|
70
|
-
if (includeToolCalls && block.type === "toolCall" && "name" in block && typeof block.name === "string"
|
|
71
|
-
&& "id" in block && typeof block.id === "string" && "arguments" in block)
|
|
72
|
-
return [JSON.stringify({ toolCall: { name: block.name, id: block.id, arguments: block.arguments } })];
|
|
73
|
-
return [];
|
|
74
|
-
}).join("\n");
|
|
60
|
+
function textContent(content, assistant = false) {
|
|
61
|
+
return readableContentParts(content, assistant).map(part => part.text).join("\n");
|
|
75
62
|
}
|
|
76
63
|
function readable(entry, attempts, links) {
|
|
77
64
|
if (!isHistorySource(entry))
|
|
@@ -142,7 +129,8 @@ export function createRecall(policy = {}) {
|
|
|
142
129
|
calls.set(block.id, group);
|
|
143
130
|
local.push(call);
|
|
144
131
|
}
|
|
145
|
-
// Exactly the
|
|
132
|
+
// Exactly the public prefix admitted by textContent, including empty
|
|
133
|
+
// text/newlines. Plain thinking is appended after this prefix.
|
|
146
134
|
if (!(block.type === "text" && typeof block.text === "string" || block.type === "toolCall" &&
|
|
147
135
|
typeof block.name === "string" && typeof block.id === "string" && "arguments" in block))
|
|
148
136
|
continue;
|
|
@@ -186,20 +174,15 @@ export function createRecall(policy = {}) {
|
|
|
186
174
|
if (message.role !== "assistant")
|
|
187
175
|
return [{ start: 0, end: text.length }];
|
|
188
176
|
const ranges = [];
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
if (
|
|
192
|
-
continue;
|
|
193
|
-
const part = textContent([block], true);
|
|
194
|
-
const end = position + part.length;
|
|
195
|
-
if (block.type !== "toolCall" || !isLookupTool(block.name) || isRecallTool(block.name) && isSourceExport(block.arguments)) {
|
|
177
|
+
for (const part of readableContentParts(message.content, true)) {
|
|
178
|
+
const position = part.offset, end = position + part.text.length;
|
|
179
|
+
if (part.kind !== "toolCall" || !isLookupTool(part.toolName) || isRecallTool(part.toolName) && isSourceExport(part.arguments)) {
|
|
196
180
|
const previous = ranges.at(-1);
|
|
197
181
|
if (previous && previous.end + 1 === position)
|
|
198
182
|
previous.end = end;
|
|
199
183
|
else
|
|
200
184
|
ranges.push({ start: position, end });
|
|
201
185
|
}
|
|
202
|
-
position = end + 1;
|
|
203
186
|
}
|
|
204
187
|
return ranges.filter(({ start, end }) => end > start);
|
|
205
188
|
}
|
|
@@ -16,34 +16,19 @@ export declare function loadPiRequestMath(): Promise<PiRequestMath | undefined>;
|
|
|
16
16
|
* Without Pi's request arithmetic, fall back to Pi 1.2–1.5's documented 4,096-token allowance.
|
|
17
17
|
*/
|
|
18
18
|
export declare function piContextSafetyMargin(math?: PiRequestMath): Promise<number>;
|
|
19
|
-
/**
|
|
20
|
-
export declare const REPLY_FLOOR_MIN = 3584;
|
|
21
|
-
/** A spent thinking budget that produced neither a visible answer nor work. Empty/text/tool replies keep the existing length recovery. */
|
|
19
|
+
/** A length stop with visible reasoning but no visible answer or work. */
|
|
22
20
|
export declare const thinkingOnlyLength: (message: AgentMessage) => boolean;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
export interface WindowReceipt {
|
|
29
|
-
calibrationIdentity: string;
|
|
30
|
-
learnedContextWindow: number;
|
|
31
|
-
catalogueContextWindow: number;
|
|
32
|
-
serverClippedReplyId: string;
|
|
33
|
-
}
|
|
34
|
-
export declare const WINDOW_RECEIPT = "pi-tuck-window";
|
|
35
|
-
/** The newest learned window for `identity`, if it was learned under the model's current configured window. One recorded before 1.3.3
|
|
36
|
-
* carries no configured window and is not trusted: if the server still clips, the next clipped reply learns it again. */
|
|
37
|
-
export declare function seedContextWindow(branch: readonly SessionEntry[], identity: string, catalogue: number | undefined): number | undefined;
|
|
38
|
-
/** One branch reader for the reserve override and reply floor, including history before cuts. A server-clipping receipt follows its reply. */
|
|
39
|
-
export declare function replyFit(branch: readonly SessionEntry[]): {
|
|
40
|
-
failed: boolean;
|
|
41
|
-
largestOutput: number;
|
|
42
|
-
thinkingStop: boolean;
|
|
21
|
+
type ReplyModel = {
|
|
22
|
+
provider: string;
|
|
23
|
+
api: string;
|
|
24
|
+
id: string;
|
|
25
|
+
maxTokens: number;
|
|
43
26
|
};
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
27
|
+
/** Reply room a cut above the room aims for before any long reply is seen. Cuts only: admission keeps the observed floor. */
|
|
28
|
+
export declare const CUT_REPLY_FLOOR = 3584;
|
|
29
|
+
/** Ordinary reply demand is bounded by the reserve and model output limit.
|
|
30
|
+
* Recovery compares its candidate against the interrupted attempt separately. */
|
|
31
|
+
export declare function requestReplyFloor(branch: readonly SessionEntry[], reserve: number, model: ReplyModel, minimum?: number): number;
|
|
47
32
|
/** Check decoded starting text, native or quoted whole with its original role; never JSON-escaped substring matching. */
|
|
48
33
|
export declare function carriesPrompt(messages: Messages, prompt: string, role?: 'user' | 'custom'): boolean;
|
|
49
34
|
export {};
|