pi-tuck 1.2.0 → 1.3.2
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 +30 -59
- package/dist/src/bash-command.d.ts +8 -0
- package/dist/src/bash-command.js +116 -0
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.js +67 -21
- package/dist/src/diagnostic-replay.js +1 -1
- package/dist/src/diagnostics.d.ts +1 -1
- package/dist/src/kept-reads.js +5 -114
- package/dist/src/kept-searches.d.ts +11 -0
- package/dist/src/kept-searches.js +202 -0
- package/dist/src/run.d.ts +2 -0
- package/dist/src/run.js +3 -0
- package/dist/src/tuck/core/content.d.ts +0 -11
- package/dist/src/tuck/core/content.js +0 -47
- package/dist/src/tuck/core/search-entries.d.ts +5 -28
- package/dist/src/tuck/core/search-entries.js +13 -155
- package/dist/src/tuck.d.ts +7 -15
- package/dist/src/tuck.js +32 -28
- package/package.json +3 -2
- package/src/bash-command.ts +59 -0
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +61 -22
- package/src/diagnostic-replay.ts +1 -1
- package/src/kept-reads.ts +5 -56
- package/src/kept-searches.ts +163 -0
- package/src/run.ts +3 -1
- package/src/tuck/core/content.ts +0 -43
- package/src/tuck/core/search-entries.ts +14 -201
- package/src/tuck.ts +33 -34
|
@@ -1,17 +1,3 @@
|
|
|
1
|
-
export const clip = (text, max = 200) => {
|
|
2
|
-
if (text.length <= max)
|
|
3
|
-
return text;
|
|
4
|
-
// Try to cut at a word boundary
|
|
5
|
-
const cut = text.lastIndexOf(" ", max);
|
|
6
|
-
let end = cut > max * 0.6 ? cut : max;
|
|
7
|
-
// Avoid splitting a surrogate pair
|
|
8
|
-
if (end > 0 && end < text.length) {
|
|
9
|
-
const code = text.charCodeAt(end - 1);
|
|
10
|
-
if (code >= 0xd800 && code <= 0xdbff)
|
|
11
|
-
end--;
|
|
12
|
-
}
|
|
13
|
-
return text.slice(0, end);
|
|
14
|
-
};
|
|
15
1
|
/** Content that is a string or only text blocks: what quoting can deliver whole. */
|
|
16
2
|
export const isTextOnly = (content) => typeof content === "string" || (Array.isArray(content) && content.every((part) => part.type === "text"));
|
|
17
3
|
export const textOf = (content) => {
|
|
@@ -21,36 +7,3 @@ export const textOf = (content) => {
|
|
|
21
7
|
return content;
|
|
22
8
|
return content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
|
|
23
9
|
};
|
|
24
|
-
/**
|
|
25
|
-
* Extract every scalar string argument from a tool call for search indexing
|
|
26
|
-
* — command, query, content, oldText/newText, etc. Generic value walk (no
|
|
27
|
-
* tool-name allowlist): top-level strings plus strings one level into
|
|
28
|
-
* array-of-object fields (e.g. `edits`). Unbounded by design — a single
|
|
29
|
-
* toolCall's raw argument text — so a message with several toolCalls doesn't
|
|
30
|
-
* silently multiply an internal cap. The caller (search-entries.ts) applies
|
|
31
|
-
* one shared budget across all toolCalls in a message.
|
|
32
|
-
*/
|
|
33
|
-
export const extractToolCallArgsText = (args) => {
|
|
34
|
-
if (!args || typeof args !== "object")
|
|
35
|
-
return "";
|
|
36
|
-
const parts = [];
|
|
37
|
-
for (const value of Object.values(args)) {
|
|
38
|
-
if (typeof value === "string") {
|
|
39
|
-
parts.push(value);
|
|
40
|
-
}
|
|
41
|
-
else if (Array.isArray(value)) {
|
|
42
|
-
for (const item of value) {
|
|
43
|
-
if (typeof item === "string") {
|
|
44
|
-
parts.push(item);
|
|
45
|
-
}
|
|
46
|
-
else if (item && typeof item === "object") {
|
|
47
|
-
for (const v of Object.values(item)) {
|
|
48
|
-
if (typeof v === "string")
|
|
49
|
-
parts.push(v);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return parts.join("\n");
|
|
56
|
-
};
|
|
@@ -1,28 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
7
|
-
/**
|
|
8
|
-
* Result of a search, with enough metadata for a caller to report truncation
|
|
9
|
-
* honestly (see `searchEntriesDetailed`).
|
|
10
|
-
*/
|
|
11
|
-
export interface SearchResult {
|
|
12
|
-
hits: SearchHit[];
|
|
13
|
-
/** Genuine matches found before the hard cap was applied (after any
|
|
14
|
-
* relative-floor noise filtering). May exceed `hits.length`. */
|
|
15
|
-
totalBeforeCap: number;
|
|
16
|
-
/** True when the hard cap discarded matches (`totalBeforeCap > hits.length`). */
|
|
17
|
-
truncated: boolean;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Tuning overrides for `searchEntriesDetailed`; without them a search uses `BM25_RELATIVE_FLOOR` and
|
|
21
|
-
* `SEARCH_RESULT_CAP`. `tuckRecall` passes a floor of 0 and a cap of every row, because it pages its own responses.
|
|
22
|
-
*/
|
|
23
|
-
export interface SearchTuning {
|
|
24
|
-
relativeFloor?: number;
|
|
25
|
-
cap?: number;
|
|
26
|
-
}
|
|
27
|
-
/** BM25 keyword search with truncation metadata. */
|
|
28
|
-
export declare const searchEntriesDetailed: (entries: RenderedEntry[], messages: Message[], query?: string, tuning?: SearchTuning) => SearchResult;
|
|
1
|
+
/** Rank already-eligible recall rows; filtering and paging belong to the caller. */
|
|
2
|
+
export declare const rankRecallRows: (rows: readonly {
|
|
3
|
+
role: string;
|
|
4
|
+
text: string;
|
|
5
|
+
}[], query: string) => number[];
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { isLookupTool } from "./recall-operation.js";
|
|
2
|
-
import { textOf, extractToolCallArgsText, clip } from "./content.js";
|
|
3
1
|
import { prepareKeywordQuery } from "./keyword-query.js";
|
|
4
2
|
/**
|
|
5
3
|
* Wall-clock budget for one search. A normal query over 400 entries takes ~10ms.
|
|
@@ -70,168 +68,28 @@ const bm25Score = (doc, terms, ctx) => {
|
|
|
70
68
|
}
|
|
71
69
|
return score;
|
|
72
70
|
};
|
|
73
|
-
/**
|
|
74
|
-
|
|
75
|
-
* message's searchable text — a single shared budget across every toolCall
|
|
76
|
-
* in the message, not per call, so N toolCalls can't multiply the bound and
|
|
77
|
-
* make one message's contribution to the BM25 doc corpus unbounded.
|
|
78
|
-
*
|
|
79
|
-
* Head-only cap: content past this budget is not indexed via toolCall
|
|
80
|
-
* arguments at all. This is an honest tradeoff, not a proxy for full
|
|
81
|
-
* coverage — a Write/Edit tool result commonly only acknowledges success
|
|
82
|
-
* (e.g. "wrote 400 lines"), so a fact buried past the cap in a giant
|
|
83
|
-
* argument is not guaranteed to be searchable elsewhere either.
|
|
84
|
-
*/
|
|
85
|
-
const TOOL_ARGS_BUDGET = 2000;
|
|
86
|
-
/**
|
|
87
|
-
* Tool name of the recall tool itself (src/tools/recall.ts). A search
|
|
88
|
-
* operation must not match its own query or its own prior output: the
|
|
89
|
-
* lookup invocation is persisted as an ordinary assistant toolCall (its
|
|
90
|
-
* `{ query }` argument, excluded below in `toolCallArgsText`) followed by an
|
|
91
|
-
* ordinary toolResult message (its `N matches for "<query>"` text, excluded
|
|
92
|
-
* in `fullText`) — without both exclusions a repeated query keeps matching
|
|
93
|
-
* its own prior invocation/output and the hit count grows on every search.
|
|
94
|
-
* This is a targeted introspection invariant for recognized history lookup tools, not a
|
|
95
|
-
* general allowlist/blocklist over tool names or tool results.
|
|
96
|
-
*/
|
|
97
|
-
/** Text of every toolCall's arguments in a message's content, for search —
|
|
98
|
-
* bounded once, in aggregate, by TOOL_ARGS_BUDGET. Excludes the recall
|
|
99
|
-
* tool's own arguments (see isLookupTool). */
|
|
100
|
-
const toolCallArgsText = (content) => {
|
|
101
|
-
if (!content || typeof content === "string")
|
|
102
|
-
return "";
|
|
103
|
-
const raw = content
|
|
104
|
-
.filter((part) => part.type === "toolCall")
|
|
105
|
-
.filter((part) => !isLookupTool(part.name ?? ""))
|
|
106
|
-
.map((part) => extractToolCallArgsText(part.arguments))
|
|
107
|
-
.filter(Boolean)
|
|
108
|
-
.join("\n");
|
|
109
|
-
return clip(raw, TOOL_ARGS_BUDGET);
|
|
110
|
-
};
|
|
111
|
-
/**
|
|
112
|
-
* Build full searchable text for a message: text parts plus toolCall
|
|
113
|
-
* arguments (bash command, Write/Edit content, etc.) so a match that only
|
|
114
|
-
* exists in a tool call's arguments is still findable.
|
|
115
|
-
*
|
|
116
|
-
* The recall tool's own toolResult is excluded (searchable text ""): it
|
|
117
|
-
* echoes back `N matches for "<query>"` from the *previous* recall call, so
|
|
118
|
-
* indexing it would make a repeated query self-match and grow with every
|
|
119
|
-
* search. This only affects search indexing — browse/no-query returns
|
|
120
|
-
* entries before fullText runs (see `searchEntriesDetailed`), and #N expand reads
|
|
121
|
-
* the message/entry directly, not through this function, so the toolResult
|
|
122
|
-
* is still fully visible there.
|
|
123
|
-
*/
|
|
124
|
-
const fullText = (msg) => {
|
|
125
|
-
if (msg.role === "bashExecution") {
|
|
126
|
-
return `${msg.command ?? ""} ${msg.output ?? ""}`;
|
|
127
|
-
}
|
|
128
|
-
if (msg.role === "toolResult" && isLookupTool(msg.toolName ?? "")) {
|
|
129
|
-
return "";
|
|
130
|
-
}
|
|
131
|
-
const text = textOf(msg.content);
|
|
132
|
-
const argsText = toolCallArgsText(msg.content);
|
|
133
|
-
return argsText ? `${text}\n${argsText}` : text;
|
|
134
|
-
};
|
|
135
|
-
/**
|
|
136
|
-
* Relative BM25 noise floor for MULTI-TERM natural-language queries only:
|
|
137
|
-
* after sorting by score, drop hits scoring below this fraction of the top
|
|
138
|
-
* score. Relative (not absolute) because BM25 magnitudes vary with corpus
|
|
139
|
-
* size and document length, so a fixed score threshold would behave
|
|
140
|
-
* inconsistently across short vs. long sessions.
|
|
141
|
-
*
|
|
142
|
-
* Applied only when the query has >=2 DISTINCT effective terms after
|
|
143
|
-
* stopword filtering and case/duplicate normalization (see the
|
|
144
|
-
* `effectiveTermCount >= 2` gate below `searchEntriesDetailed` uses before
|
|
145
|
-
* calling `applyRelativeFloor`). Distinct, not raw count: "auth auth" or
|
|
146
|
-
* "Auth AUTH" is a single-term query after normalization and must bypass the floor
|
|
147
|
-
* like any other single term — repeating or casing a word doesn't turn it
|
|
148
|
-
* into the multi-term OR-tail noise this floor targets. The normalization is
|
|
149
|
-
* gate-only; it doesn't change `terms` or the BM25 scoring itself, which
|
|
150
|
-
* already matches case-insensitively. For a genuine single term, every hit's
|
|
151
|
-
* occurrence already satisfies the whole query — its BM25 score differences
|
|
152
|
-
* reflect term frequency and document length, not multi-term OR-tail noise,
|
|
153
|
-
* so filtering by it there risks real matches for no corresponding noise
|
|
154
|
-
* reduction. The inherited floor is retained unchanged; private-corpus
|
|
155
|
-
* observations and their unavailable harness are not public quality evidence.
|
|
156
|
-
*
|
|
157
|
-
* The top-scoring hit always survives by construction: its own score
|
|
158
|
-
* always satisfies `score >= topScore * floor`
|
|
159
|
-
* for any floor <= 1, so a non-empty scored[] can never be filtered to zero.
|
|
160
|
-
*/
|
|
161
|
-
const BM25_RELATIVE_FLOOR = 0.2;
|
|
162
|
-
/**
|
|
163
|
-
* Hard cap on total SEARCH results, applied after the relative floor so pagination stays bounded regardless
|
|
164
|
-
* of how noisy or broad a query is.
|
|
165
|
-
*
|
|
166
|
-
* The inherited cap is retained unchanged. This is a resource bound, not
|
|
167
|
-
* a claim about retrieval quality on an undistributed corpus.
|
|
168
|
-
*/
|
|
169
|
-
const SEARCH_RESULT_CAP = 50;
|
|
170
|
-
/** Drop scored hits below `floor` of the top score. The top hit's own score
|
|
171
|
-
* always passes (score >= score * floor for floor <= 1), so this can never
|
|
172
|
-
* turn a non-empty `scored` into an empty result. */
|
|
173
|
-
const applyRelativeFloor = (scored, floor) => {
|
|
174
|
-
if (scored.length === 0)
|
|
175
|
-
return scored;
|
|
176
|
-
const topScore = scored[0].score;
|
|
177
|
-
if (topScore <= 0)
|
|
178
|
-
return scored;
|
|
179
|
-
return scored.filter((s) => s.score >= topScore * floor);
|
|
180
|
-
};
|
|
181
|
-
/**
|
|
182
|
-
* Bound `hits` to `cap` entries, reporting the pre-cap count so callers can
|
|
183
|
-
* signal truncation honestly instead of understating "total matches".
|
|
184
|
-
*
|
|
185
|
-
* Order preserved, never re-sorted: hits are already highest-score-first, so
|
|
186
|
-
* `slice(0, cap)` keeps the top `cap` hits.
|
|
187
|
-
*/
|
|
188
|
-
const capHits = (hits, cap) => {
|
|
189
|
-
const totalBeforeCap = hits.length;
|
|
190
|
-
const capped = totalBeforeCap > cap ? hits.slice(0, cap) : hits;
|
|
191
|
-
return { hits: capped, totalBeforeCap, truncated: capped.length < totalBeforeCap };
|
|
192
|
-
};
|
|
193
|
-
/** BM25 keyword search with truncation metadata. */
|
|
194
|
-
export const searchEntriesDetailed = (entries, messages, query, tuning) => {
|
|
195
|
-
if (!query?.trim())
|
|
196
|
-
return { hits: entries, totalBeforeCap: entries.length, truncated: false };
|
|
197
|
-
const relativeFloor = tuning?.relativeFloor ?? BM25_RELATIVE_FLOOR;
|
|
198
|
-
const cap = tuning?.cap ?? SEARCH_RESULT_CAP;
|
|
71
|
+
/** Rank already-eligible recall rows; filtering and paging belong to the caller. */
|
|
72
|
+
export const rankRecallRows = (rows, query) => {
|
|
199
73
|
const rawQuery = query.trim();
|
|
200
74
|
const checkBudget = startBudget();
|
|
201
|
-
// Natural language / multi-word query: BM25 scoring
|
|
202
75
|
const prepared = prepareKeywordQuery(rawQuery);
|
|
203
76
|
const terms = prepared.terms;
|
|
204
|
-
//
|
|
205
|
-
const docs =
|
|
206
|
-
for (let i = 0; i < entries.length; i++) {
|
|
207
|
-
const e = entries[i];
|
|
208
|
-
const msg = messages[i];
|
|
209
|
-
const text = msg ? fullText(msg) : e.summary;
|
|
210
|
-
const filePart = e.files?.join(" ") ?? "";
|
|
211
|
-
docs.push(`${e.role} ${text} ${filePart}`);
|
|
212
|
-
}
|
|
77
|
+
// Preserve the role prefix and trailing space of the original BM25 documents.
|
|
78
|
+
const docs = rows.map((row) => `${row.role} ${row.text} `);
|
|
213
79
|
const ctx = buildBM25Context(docs, terms, checkBudget);
|
|
214
80
|
const scored = [];
|
|
215
|
-
for (let i = 0; i <
|
|
81
|
+
for (let i = 0; i < rows.length; i++) {
|
|
216
82
|
checkBudget();
|
|
217
|
-
const e = entries[i];
|
|
218
83
|
const hay = docs[i];
|
|
219
|
-
|
|
220
|
-
if (mc === 0)
|
|
84
|
+
if (countMatches(hay, terms) === 0)
|
|
221
85
|
continue;
|
|
222
|
-
scored.push({
|
|
86
|
+
scored.push({ index: i, score: bm25Score(hay, terms, ctx) });
|
|
223
87
|
}
|
|
224
|
-
//
|
|
225
|
-
// top score (multi-term queries only — see BM25_RELATIVE_FLOOR), then
|
|
226
|
-
// apply the hard cap.
|
|
88
|
+
// Stable sort keeps source order for tied scores, including duplicate terms.
|
|
227
89
|
scored.sort((a, b) => b.score - a.score);
|
|
228
|
-
//
|
|
229
|
-
//
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
// scoring above, which already matches case-insensitively.
|
|
234
|
-
const effectiveTermCount = prepared.coverageTerms.length;
|
|
235
|
-
const floored = effectiveTermCount >= 2 ? applyRelativeFloor(scored, relativeFloor) : scored;
|
|
236
|
-
return capHits(floored.map((s) => s.hit), cap);
|
|
90
|
+
// Duplicate terms can make IDF negative. Preserve the original zero-floor
|
|
91
|
+
// selection when a multi-term query also has a positive top score.
|
|
92
|
+
const ranked = prepared.coverageTerms.length >= 2 && (scored[0]?.score ?? 0) > 0
|
|
93
|
+
? scored.filter((s) => s.score >= 0) : scored;
|
|
94
|
+
return ranked.map((s) => s.index);
|
|
237
95
|
};
|
package/dist/src/tuck.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { type SourceTime } from "./tuck/core/source-time.js";
|
|
2
|
-
import type { Message } from "@earendil-works/pi-ai";
|
|
3
2
|
import { convertToLlm, type ExtensionContext, type SessionBeforeCompactEvent, type SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
4
3
|
import { type RecallPolicy, type PreparedKeywordQuery, type RecordedAttempt, type RecallOptions } from "./recall.js";
|
|
5
4
|
type AgentMessage = Parameters<typeof convertToLlm>[0][number];
|
|
@@ -26,11 +25,6 @@ type Draft = {
|
|
|
26
25
|
capacityRejected?: boolean;
|
|
27
26
|
floorMessages?: AgentMessage[];
|
|
28
27
|
};
|
|
29
|
-
interface SearchHit {
|
|
30
|
-
index: number;
|
|
31
|
-
role: string;
|
|
32
|
-
summary: string;
|
|
33
|
-
}
|
|
34
28
|
export interface RecallContinuation {
|
|
35
29
|
query: string;
|
|
36
30
|
throughEntryId: string;
|
|
@@ -64,17 +58,16 @@ export interface Tuck {
|
|
|
64
58
|
};
|
|
65
59
|
}): ReturnType<typeof compileDialogue>;
|
|
66
60
|
prepareKeywordQuery(query: string): PreparedKeywordQuery;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}):
|
|
71
|
-
hits: SearchHit[];
|
|
72
|
-
};
|
|
61
|
+
rankRecallRows(rows: readonly {
|
|
62
|
+
role: string;
|
|
63
|
+
text: string;
|
|
64
|
+
}[], query: string): number[];
|
|
73
65
|
}
|
|
74
66
|
import { compileDialogue } from "./tuck/core/summarize.js";
|
|
75
67
|
export declare const tuck: Tuck;
|
|
76
|
-
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
77
|
-
|
|
68
|
+
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
69
|
+
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
70
|
+
export declare function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy?: RecallPolicy, retainCurrentInput?: boolean, _operatorManual?: boolean, newPrompt?: boolean, protectedPromptEntryId?: string): Draft;
|
|
78
71
|
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
|
|
79
72
|
/** `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
|
|
80
73
|
* a run a custom message starts); the session has moved on from an ended run.
|
|
@@ -83,7 +76,6 @@ export declare function tuckObservedDraft(tuck: Tuck, input: {
|
|
|
83
76
|
branchEntries: SessionEntry[];
|
|
84
77
|
tokensBefore: number;
|
|
85
78
|
previousSummary?: string;
|
|
86
|
-
operatorManual?: boolean;
|
|
87
79
|
newPrompt?: boolean;
|
|
88
80
|
reRenderSummary?: boolean;
|
|
89
81
|
protectedPromptEntryId?: string;
|
package/dist/src/tuck.js
CHANGED
|
@@ -8,6 +8,7 @@ import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
|
|
|
8
8
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
9
9
|
import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
|
|
10
10
|
import { keptReadCandidates } from "./kept-reads.js";
|
|
11
|
+
import { keptSearchCandidates } from "./kept-searches.js";
|
|
11
12
|
import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
12
13
|
import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
|
|
13
14
|
/** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
|
|
@@ -17,11 +18,12 @@ import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/
|
|
|
17
18
|
import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
|
|
18
19
|
import { compileDialogue } from "./tuck/core/summarize.js";
|
|
19
20
|
import { prepareKeywordQuery } from "./tuck/core/keyword-query.js";
|
|
20
|
-
import {
|
|
21
|
-
export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery,
|
|
22
|
-
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
import { rankRecallRows } from "./tuck/core/search-entries.js";
|
|
22
|
+
export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
|
|
23
|
+
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
24
|
+
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
25
|
+
export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId) {
|
|
26
|
+
return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId }, ctx, reserveTokens, measure, policy, retainCurrentInput);
|
|
25
27
|
}
|
|
26
28
|
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
|
|
27
29
|
/** `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
|
|
@@ -377,22 +379,26 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
377
379
|
const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
|
|
378
380
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
379
381
|
let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
+
const keptResults = [], counts = new Map();
|
|
383
|
+
const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry) => readable(entry) !== undefined;
|
|
384
|
+
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
385
|
+
.sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
386
|
+
for (const record of candidates) {
|
|
387
|
+
if ((counts.get(record.title) ?? 0) === 4)
|
|
388
|
+
continue;
|
|
382
389
|
const cost = lineCost([record]);
|
|
383
390
|
if (cost > allowance)
|
|
384
391
|
continue;
|
|
385
|
-
|
|
392
|
+
keptResults.push(record);
|
|
386
393
|
allowance -= cost;
|
|
387
|
-
|
|
388
|
-
break;
|
|
394
|
+
counts.set(record.title, (counts.get(record.title) ?? 0) + 1);
|
|
389
395
|
}
|
|
390
|
-
let ledger = [...lists.records, ...
|
|
396
|
+
let ledger = [...lists.records, ...keptResults];
|
|
391
397
|
// List caps are existing ranking policy; only the carried target is a
|
|
392
398
|
// spending limit. Candidate list sizes have fixed, cached line prices.
|
|
393
|
-
while (
|
|
394
|
-
|
|
395
|
-
ledger = [...lists.records, ...
|
|
399
|
+
while (keptResults.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
400
|
+
keptResults.pop();
|
|
401
|
+
ledger = [...lists.records, ...keptResults];
|
|
396
402
|
}
|
|
397
403
|
if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
398
404
|
ledger = [];
|
|
@@ -516,11 +522,11 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
516
522
|
return [{ role, missing, ends, counts, cost: lineCost([record]) }];
|
|
517
523
|
});
|
|
518
524
|
const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
|
|
519
|
-
const
|
|
520
|
-
const
|
|
525
|
+
const keptResultCost = lineCost(keptResults), keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
|
|
526
|
+
const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
|
|
521
527
|
const extensionPrice = (at) => {
|
|
522
|
-
// Fixed kept
|
|
523
|
-
if (
|
|
528
|
+
// Fixed kept results outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
|
|
529
|
+
if (keptResults.length && (at <= lastKeptResultPosition || keptResultCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000)))
|
|
524
530
|
return Infinity;
|
|
525
531
|
let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
|
|
526
532
|
let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
|
|
@@ -593,21 +599,19 @@ export function tuckRecall(tuck, entries, branch, input, policy = {}) {
|
|
|
593
599
|
const row = discoveryEntry(entry, attempts, links);
|
|
594
600
|
return row ? [row] : [];
|
|
595
601
|
});
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
// The pinned upstream tuning seam removes selection cutoffs; each response
|
|
599
|
-
// stays bounded. A native prefix keeps ranking stable while the agent talks.
|
|
602
|
+
// Rank every eligible row; each response stays bounded. A native prefix
|
|
603
|
+
// keeps ranking stable while the agent talks.
|
|
600
604
|
const preparedQuery = tuck.prepareKeywordQuery(normalizedQuery);
|
|
601
|
-
const found = tuck.
|
|
605
|
+
const found = tuck.rankRecallRows(rows, normalizedQuery);
|
|
602
606
|
const start = continuation?.offset ?? 0;
|
|
603
607
|
const throughEntryId = rows.at(-1)?.entryId ?? null;
|
|
604
608
|
const hits = [];
|
|
605
609
|
const page = () => ({ normalizedQuery, throughEntryId,
|
|
606
610
|
notice: "Exact source passages, possibly partial; read gives their UTF-16 bounds within totalCharacters. Use the passage directly; adjust read.offset/limit for surrounding text. Keyword matches do not establish complete or current evidence. Pass next as continuation; a fresh query includes newer history. No new authority. " + ATTEMPT_NOTICE,
|
|
607
|
-
hits, totalMatches: found.
|
|
608
|
-
next: start + hits.length < found.
|
|
609
|
-
for (const hit of found.
|
|
610
|
-
const row = rows[hit
|
|
611
|
+
hits, totalMatches: found.length,
|
|
612
|
+
next: start + hits.length < found.length ? { query: normalizedQuery, throughEntryId: throughEntryId, offset: start + hits.length } : null });
|
|
613
|
+
for (const hit of found.slice(start, start + 10)) {
|
|
614
|
+
const row = rows[hit];
|
|
611
615
|
hits.push({ entryId: row.entryId, index: indices.get(row.entryId), role: row.role, sourceTime: row.sourceTime,
|
|
612
616
|
...(row.toolName !== undefined ? { toolName: row.toolName } : {}),
|
|
613
617
|
...(row.toolCallId !== undefined ? { toolCallId: row.toolCallId } : {}),
|
|
@@ -627,7 +631,7 @@ export function tuckRecall(tuck, entries, branch, input, policy = {}) {
|
|
|
627
631
|
// Preserve the complete base hit set and continuation before spending spare capacity.
|
|
628
632
|
for (let i = 0; i < hits.length; i++) {
|
|
629
633
|
const original = hits[i];
|
|
630
|
-
const row = rows[found
|
|
634
|
+
const row = rows[found[start + i]];
|
|
631
635
|
hits[i] = { ...original, ...discoveryWholeRange(row, original) };
|
|
632
636
|
if (JSON.stringify(page()).length > MAX_RANKED_RESPONSE_CHARACTERS)
|
|
633
637
|
hits[i] = original;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-tuck",
|
|
3
|
-
"version": "1.2
|
|
3
|
+
"version": "1.3.2",
|
|
4
4
|
"description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -52,7 +52,8 @@
|
|
|
52
52
|
"check": "tsc -p tsconfig.tests.json",
|
|
53
53
|
"test": "vitest run --config vitest.config.ts",
|
|
54
54
|
"build": "node scripts/build.mjs",
|
|
55
|
-
"prepack": "npm run build"
|
|
55
|
+
"prepack": "npm run build",
|
|
56
|
+
"timing": "PI_TUCK_TIMING=1 STRESS=1 vitest run --config vitest.config.ts --maxWorkers=1 test/regression-bench.test.ts test/stress/large-session.test.ts"
|
|
56
57
|
},
|
|
57
58
|
"peerDependencies": {
|
|
58
59
|
"@earendil-works/pi-ai": ">=1.2.0",
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
|
|
3
|
+
// A deliberately bounded shell recognizer: substitutions, redirections and
|
|
4
|
+
// unrecognized composition never certify a command as read-only.
|
|
5
|
+
function shellWords(command: string, windows: boolean): { words: string[]; simple: boolean } {
|
|
6
|
+
const words: string[] = []; let word = "", quote = "", started = false, simple = true;
|
|
7
|
+
const flush = () => { if (started) words.push(word); word = ""; started = false; };
|
|
8
|
+
for (let i = 0; i < command.length; i++) {
|
|
9
|
+
const c = command[i]!;
|
|
10
|
+
if (quote === "'") { if (c === quote) quote = ""; else word += c; continue; }
|
|
11
|
+
if (c === "\\" && !windows) { if (command[i + 1] === "\n") { i++; continue; } started = true; if (i + 1 < command.length) word += command[++i]; else simple = false; continue; }
|
|
12
|
+
if (c === "$" || c === "`") simple = false;
|
|
13
|
+
if (windows && (c === "%" || c === "^")) simple = false;
|
|
14
|
+
if (quote) { if (c === quote) quote = ""; else word += c; continue; }
|
|
15
|
+
if (c === "'" || c === '"') { quote = c; started = true; }
|
|
16
|
+
else if (/\s/u.test(c)) { flush(); if (c === "\n") { words.push(";"); simple = false; } }
|
|
17
|
+
else if (/[|&;<>]/u.test(c)) { flush(); const op = command[i + 1] === c ? c + command[++i] : c; words.push(op); }
|
|
18
|
+
else { word += c; started = true; if (/[(){}]/u.test(c)) simple = false; }
|
|
19
|
+
}
|
|
20
|
+
flush(); return { words, simple: simple && !quote };
|
|
21
|
+
}
|
|
22
|
+
const readers = new Set(["ls", "cat", "head", "tail", "wc", "pwd", "echo", "tree", "file", "stat", "grep", "rg"]);
|
|
23
|
+
const windowsReaders = new Set(["type", "dir", "get-content", "get-childitem", "select-string", "findstr"]);
|
|
24
|
+
const windowsMutators = new Set(["set-content", "add-content", "out-file", "remove-item", "move-item", "copy-item", "new-item", "del", "move", "copy", "ren"]);
|
|
25
|
+
const gitMutations = new Set(["checkout", "restore", "stash", "apply", "reset", "pull", "merge", "rebase", "am"]);
|
|
26
|
+
function mutatingGit(words: string[]): boolean {
|
|
27
|
+
return words.some((word, at) => {
|
|
28
|
+
if (posix.basename(word.replace(/\\/gu, "/")).replace(/\.exe$/iu, "").toLowerCase() !== "git") return false;
|
|
29
|
+
for (let i = at + 1; i < words.length; i++) {
|
|
30
|
+
const arg = words[i]!;
|
|
31
|
+
if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(arg)) { i++; continue; }
|
|
32
|
+
if (arg.startsWith("-")) continue;
|
|
33
|
+
return gitMutations.has(arg);
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
function readOnly(words: string[], simple: boolean): boolean {
|
|
39
|
+
if (!simple) return false;
|
|
40
|
+
if (words[0] === "cd" && words[2] === "&&") words = words.slice(3);
|
|
41
|
+
if (!words.length || words.some(word => ["&&", "||", "&", ";", ">", ">>", "<", "<<"].includes(word))) return false;
|
|
42
|
+
const commands: string[][] = [[]];
|
|
43
|
+
for (const word of words) { if (word === "|") commands.push([]); else commands.at(-1)!.push(word); }
|
|
44
|
+
return commands.every(([name, ...args]) => readers.has(name!) || windowsReaders.has(name?.toLowerCase() ?? "") ||
|
|
45
|
+
name === "find" && !args.some(arg => /^-(exec|ok|delete|fprint)/u.test(arg)) ||
|
|
46
|
+
name === "sed" && args.includes("-n") && !args.some(arg => /^-[^-]*i|^--in-place/u.test(arg)) ||
|
|
47
|
+
name === "git" && ["status", "log", "diff", "show"].includes(args[0]!));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Classify the recorded shell independently of the host OS. Both kept-result lanes use this decision. */
|
|
51
|
+
export function classifyBash(command: string, cwd?: string) {
|
|
52
|
+
const commandName = command.trim().split(/\s/u)[0]!.toLowerCase();
|
|
53
|
+
const windows = /^[a-z]:[\\/]|\\/iu.test(cwd ?? "") || /[a-z]:\\/iu.test(command) ||
|
|
54
|
+
windowsReaders.has(commandName) || windowsMutators.has(commandName);
|
|
55
|
+
const { words, simple } = shellWords(command, windows);
|
|
56
|
+
return { words, windows, readOnly: readOnly(words, simple),
|
|
57
|
+
mutatesAll: mutatingGit(words) || !simple && mutatingGit(command.split(/[\s'"`();|&]+/u)),
|
|
58
|
+
directory: words[0] === "cd" && words[2] === "&&" ? words[1] : undefined };
|
|
59
|
+
}
|
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "b6a612ac60abaf5564c6020053627662851d7c7162337cf023ed686c1d598466";
|