pi-tuck 1.3.3 → 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.
Files changed (50) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +0 -59
  3. package/NOTICE +63 -0
  4. package/README.md +59 -189
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +49 -10
  7. package/dist/src/budget.d.ts +6 -15
  8. package/dist/src/budget.js +6 -11
  9. package/dist/src/build-id.d.ts +1 -1
  10. package/dist/src/build-id.js +1 -1
  11. package/dist/src/compaction.d.ts +12 -20
  12. package/dist/src/compaction.js +220 -202
  13. package/dist/src/content-observations.d.ts +24 -0
  14. package/dist/src/content-observations.js +122 -0
  15. package/dist/src/diagnostics.d.ts +1 -3
  16. package/dist/src/ledger.d.ts +6 -3
  17. package/dist/src/ledger.js +14 -7
  18. package/dist/src/llama-continuation.d.ts +8 -0
  19. package/dist/src/llama-continuation.js +179 -0
  20. package/dist/src/omissions.d.ts +1 -5
  21. package/dist/src/omissions.js +8 -10
  22. package/dist/src/recall.js +8 -25
  23. package/dist/src/request-capacity.d.ts +11 -26
  24. package/dist/src/request-capacity.js +20 -57
  25. package/dist/src/run.d.ts +16 -7
  26. package/dist/src/run.js +53 -25
  27. package/dist/src/status.d.ts +2 -0
  28. package/dist/src/status.js +6 -5
  29. package/dist/src/tuck/core/format.js +1 -1
  30. package/dist/src/tuck/core/readable-content.d.ts +14 -0
  31. package/dist/src/tuck/core/readable-content.js +43 -0
  32. package/dist/src/tuck.d.ts +2 -1
  33. package/dist/src/tuck.js +92 -30
  34. package/index.ts +42 -10
  35. package/package.json +3 -2
  36. package/src/budget.ts +7 -12
  37. package/src/build-id.ts +1 -1
  38. package/src/compaction.ts +220 -193
  39. package/src/content-observations.ts +115 -0
  40. package/src/diagnostics.ts +1 -1
  41. package/src/ledger.ts +17 -10
  42. package/src/llama-continuation.ts +176 -0
  43. package/src/omissions.ts +8 -10
  44. package/src/recall.ts +8 -20
  45. package/src/request-capacity.ts +18 -57
  46. package/src/run.ts +48 -22
  47. package/src/status.ts +8 -5
  48. package/src/tuck/core/format.ts +1 -1
  49. package/src/tuck/core/readable-content.ts +44 -0
  50. package/src/tuck.ts +79 -28
package/dist/index.js CHANGED
@@ -7,10 +7,7 @@ import { notify } from "./src/notify.js";
7
7
  import { cleanupLegacyFiles } from "./src/legacy-cleanup.js";
8
8
  export { installCompaction } from "./src/compaction.js";
9
9
  export { inspectIncident, readableIncident } from "./src/diagnostic-replay.js";
10
- /** pi-tuck as a Pi extension: compaction and history recall. `"cutAt"` in `pi-tuck.json` in Pi's agent folder (a number above 0 and at most
11
- * 1) fixes the cut point as a fraction of the input room; without it, the cut point adapts. */
12
- /** The oldest Pi with every hook and API pi-tuck uses, and the oldest its tests pass on (Pi 1.2 added the custom message that starts a
13
- * run to before_agent_start, which the prompt's cut counts). */
10
+ /** Pi 1.2 added the run's custom message to before_agent_start so preflight can count it. */
14
11
  export const PI_FLOOR = "1.2.0";
15
12
  /** Whether a Pi version is at or above the floor. A version that does not parse is taken as supported. */
16
13
  export function piSupported(version) {
@@ -38,17 +35,39 @@ export default async function (pi) {
38
35
  return;
39
36
  }
40
37
  const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
41
- const handle = await installCompaction(pi, { cutAt: settings.cutAt });
38
+ const handle = await installCompaction(pi, { cutAt: settings.cutAt, cacheSensitiveModels: settings.cacheSensitiveModels, continuationModel: settings.llamaContinuation?.model });
39
+ const continuation = settings.llamaContinuation;
40
+ let continuationError;
41
+ if (continuation) {
42
+ try {
43
+ const [{ getApiProvider }, { llamaContinuationStream }] = await Promise.all([
44
+ import("@earendil-works/pi-ai/compat"), import("./src/llama-continuation.js"),
45
+ ]);
46
+ const native = getApiProvider("openai-completions")?.streamSimple;
47
+ if (!native)
48
+ throw new Error("Pi's Chat Completions provider is unavailable");
49
+ pi.registerProvider(continuation.model.split("/")[0], {
50
+ api: "openai-completions",
51
+ streamSimple: llamaContinuationStream(continuation, native),
52
+ });
53
+ }
54
+ catch (error) {
55
+ continuationError = `pi-tuck: native continuation unavailable: ${String(error)}`;
56
+ }
57
+ }
42
58
  let said = false;
43
59
  pi.on("session_start", async (_event, ctx) => {
44
60
  await cleanupLegacyFiles(ctx);
45
61
  if (handle.state?.(ctx).kind === "standingDown")
46
62
  return;
63
+ if (continuationError)
64
+ notify(ctx, continuationError, "warning");
47
65
  if (settings.error && !said) {
48
- said = notify(ctx, `pi-tuck: ${settings.error}; using the defaults.`, "warning");
66
+ said = notify(ctx, `pi-tuck: ${settings.error}`, "warning");
49
67
  }
50
68
  });
51
69
  }
70
+ const modelRef = (value) => typeof value === "string" && /^[^/]+\/.+/.test(value);
52
71
  function readSettings(path) {
53
72
  let text;
54
73
  try {
@@ -57,12 +76,32 @@ function readSettings(path) {
57
76
  catch {
58
77
  return {};
59
78
  }
79
+ const cutAtHint = `${path} should be a JSON object like {"cutAt": 0.8}, with cutAt a number above 0 and at most 1`;
60
80
  try {
61
81
  const value = JSON.parse(text);
62
- if (value && typeof value === "object" &&
63
- (value.cutAt === undefined || validCutAt(value.cutAt)))
64
- return { cutAt: value.cutAt };
82
+ if (value && typeof value === "object" && !Array.isArray(value)) {
83
+ const settings = {};
84
+ const warnings = [];
85
+ if (value.cutAt === undefined || validCutAt(value.cutAt))
86
+ settings.cutAt = value.cutAt;
87
+ else
88
+ warnings.push(`${cutAtHint}; using the default cut point.`);
89
+ const models = value.cacheSensitiveModels;
90
+ if (Array.isArray(models) && models.every(modelRef))
91
+ settings.cacheSensitiveModels = models;
92
+ else if (models !== undefined)
93
+ warnings.push(`${path} cacheSensitiveModels must be an array of provider/model identifiers; ignoring that setting.`);
94
+ const c = value.llamaContinuation;
95
+ if (c && modelRef(c.model) && Number.isSafeInteger(c.extraTokens) && c.extraTokens > 0 &&
96
+ Number.isSafeInteger(c.deadlineMs) && c.deadlineMs > 0 && c.deadlineMs <= 2_147_483_647)
97
+ settings.llamaContinuation = c;
98
+ else if (c !== undefined)
99
+ warnings.push(`${path} llamaContinuation requires a provider/model identifier in model, a positive safe integer extraTokens, and an integer deadlineMs from 1 to 2147483647; native continuation is off.`);
100
+ if (warnings.length)
101
+ settings.error = warnings.join(" ");
102
+ return settings;
103
+ }
65
104
  }
66
105
  catch { /* reported below */ }
67
- return { error: `${path} should be a JSON object like {"cutAt": 0.8}, with cutAt a number above 0 and at most 1` };
106
+ return { error: `${cutAtHint}; using the defaults.` };
68
107
  }
@@ -18,21 +18,12 @@ export interface ToolShape {
18
18
  export declare const TRIGGER_MARGIN_FRACTION = 0.02;
19
19
  /** Whether `value` is a cut point: a fraction of the room above 0 and at most 1. */
20
20
  export declare const validCutAt: (value: unknown) => value is number;
21
- /**
22
- * The one owner of the band: the limit a cut is triggered at and preferably planned to. An adaptive default may raise the cut point above
23
- * 60% using the last cut's conversation size and current system size, both estimates, so they are converted to the room's units by the factor. Explicit cut points use the fraction alone. The margin caps both.
24
- */
25
- /** The initial default cut point: 60% of the room before a usable previous cut. Measured against 1 with paired replays (no answer loss) and billed
26
- * input under automatic and explicit prompt caching (about 17% less at 128k, 10-14% at 32k). */
27
- export declare const DEFAULT_CUT_AT = 0.6;
28
- /** Preferred native carry, in the planner's estimate: never more than the
29
- * keep-recent cut offers or the tail amount the adaptive band assumes. */
21
+ /** Trigger at the room for native parity of post-cut headroom. */
22
+ export declare const DEFAULT_CUT_AT = 1;
23
+ /** Preferred native carry, in the planner's estimate, bounded by the keep-recent offer and the existing tail limit. */
30
24
  export declare const carriedTailTokens: (offeredTokens: number) => number;
31
- export declare const bandOf: (room: number, cutAt?: number, adaptive?: {
32
- system: number;
33
- tokensAfter: number;
34
- factor: number;
35
- }) => number;
25
+ /** The one owner of the band: the trigger and preferred planning limit, capped by the margin. */
26
+ export declare const bandOf: (room: number, cutAt?: number) => number;
36
27
  /** The cut's one carried-context grant, in the planner's estimate. Combines
37
28
  * the existing native/fixed base with the quarter-free historical amount;
38
29
  * neither component remains an independent spending limit in the fill.
@@ -99,7 +90,7 @@ export type Decision<D extends object = {}> =
99
90
  message: string;
100
91
  };
101
92
  export interface CutInput<D extends object = {}> {
102
- /** The band adapts by itself (no explicit cut point), so a cut that isn't due must also free a tenth of the room. */
93
+ /** With no explicit cut point, a cut that isn't due must also free a tenth of the room. */
103
94
  usefulOnly?: boolean;
104
95
  /** Saved conversation, measured by the planner's own function. */
105
96
  before: number;
@@ -7,20 +7,15 @@ import { MAX_TAIL_TOKENS } from "./tuck/cut.js";
7
7
  export const TRIGGER_MARGIN_FRACTION = 0.02;
8
8
  /** Whether `value` is a cut point: a fraction of the room above 0 and at most 1. */
9
9
  export const validCutAt = (value) => typeof value === "number" && value > 0 && value <= 1;
10
- /**
11
- * The one owner of the band: the limit a cut is triggered at and preferably planned to. An adaptive default may raise the cut point above
12
- * 60% using the last cut's conversation size and current system size, both estimates, so they are converted to the room's units by the factor. Explicit cut points use the fraction alone. The margin caps both.
13
- */
14
- /** The initial default cut point: 60% of the room before a usable previous cut. Measured against 1 with paired replays (no answer loss) and billed
15
- * input under automatic and explicit prompt caching (about 17% less at 128k, 10-14% at 32k). */
16
- export const DEFAULT_CUT_AT = 0.6;
17
- /** Preferred native carry, in the planner's estimate: never more than the
18
- * keep-recent cut offers or the tail amount the adaptive band assumes. */
10
+ /** Trigger at the room for native parity of post-cut headroom. */
11
+ export const DEFAULT_CUT_AT = 1;
12
+ /** Preferred native carry, in the planner's estimate, bounded by the keep-recent offer and the existing tail limit. */
19
13
  export const carriedTailTokens = (offeredTokens) => Math.min(offeredTokens, MAX_TAIL_TOKENS / 2);
20
- export const bandOf = (room, cutAt = 1, adaptive) => {
14
+ /** The one owner of the band: the trigger and preferred planning limit, capped by the margin. */
15
+ export const bandOf = (room, cutAt = DEFAULT_CUT_AT) => {
21
16
  const positive = Math.max(0, room);
22
17
  const base = Math.floor(positive * cutAt);
23
- return Math.min(room - Math.ceil(positive * TRIGGER_MARGIN_FRACTION), adaptive ? Math.max(base, Math.ceil((adaptive.system + adaptive.tokensAfter + carriedTailTokens(MAX_TAIL_TOKENS)) * adaptive.factor)) : base);
18
+ return Math.min(room - Math.ceil(positive * TRIGGER_MARGIN_FRACTION), base);
24
19
  };
25
20
  /** The cut's one carried-context grant, in the planner's estimate. Combines
26
21
  * the existing native/fixed base with the quarter-free historical amount;
@@ -1 +1 @@
1
- export declare const BUILD_ID = "1c07ecfee4b1f37efd4aacb4daef591585a9fafe75814b51ea6ae2a26d86f168";
1
+ export declare const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
@@ -1 +1 @@
1
- export const BUILD_ID = "1c07ecfee4b1f37efd4aacb4daef591585a9fafe75814b51ea6ae2a26d86f168";
1
+ export const BUILD_ID = "8493bab7ad20ff2063558de74a92bcfeeb11f48536bb513d9dd442b03fdaf3ad";
@@ -3,27 +3,19 @@ import { type RecorderOptions } from "./diagnostics.js";
3
3
  import { type AgentMessage } from "./budget.js";
4
4
  import { SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
5
5
  import type { RecallPolicy } from "./recall.js";
6
- /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
7
- * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
6
+ /** Explain a high planning factor, which can come from reported usage or an overflow estimate. */
8
7
  export declare const refusalNotice: (message: string, factor: number) => string;
9
- /** What the operator hears when the provider refuses a request pi-tuck admitted as over its window: the bound that reply puts on the counting, and
10
- * what pi-tuck did with it. A bound pi-tuck cannot carry (above the ceiling) says so rather than implying the next request is planned at it. */
8
+ /** Keep the provider rejection distinct from the assumption used to estimate a planning factor. */
11
9
  export declare const overflowNotice: (contextWindow: number, bound: number, learned: boolean) => string;
12
10
  /** The most a seed or an overflow raise may set the calibration factor to. A paired reply's own ratio is not bounded by it. */
13
11
  export declare const CALIBRATION_CEILING = 1.5;
14
12
  /** How many recent paired replies (and overflow bounds, and the seed while it is among them) the calibration factor is the maximum of. */
15
13
  export declare const CALIBRATION_WINDOW = 32;
16
- /** Measured provider-input undercount by model, as "provider/id". An identity with no usable receipt of its own starts its window with this entry, which
17
- * ages out after CALIBRATION_WINDOW later entries; every other model starts at 1. Empty: an undercount of 1.18 once measured for openai/gpt-6.1-sol
18
- * was replayed reasoning, which the estimate now counts; with it counted, the first 32 requests of a real session measured at most 0.97. */
19
- export declare const MEASURED_CALIBRATION: Readonly<Record<string, number>>;
20
14
  export declare const CALIBRATION_RECEIPT = "pi-tuck-calibration";
21
- /** The calibration window a session starts with under accounting identity `key`: the newest calibration entry or compaction on the branch that carries this package's
22
- * receipt decides, and no older receipt is consulted. A receipt without the identity field (written before it existed) or from another identity gives `initialWindow`.
23
- * Otherwise its `calibrationWindow` (an array of 1..CALIBRATION_WINDOW finite numbers, oldest first) is the window, each entry clamped to
24
- * [0, CALIBRATION_CEILING]; without a valid one, the window is its `calibrationFactor` clamped to [1, CALIBRATION_CEILING] as one entry, else
25
- * `initialWindow`. A usable receipt of the identity's own wins over the measured seed, as a learned window replaces it: a Resume from a receipt
26
- * written before the seed existed, or after it aged out, starts at that receipt's window (as low as 1). Reads only; a malformed receipt never throws. */
15
+ /** Read the newest applicable calibration receipt on the branch for `key` ([provider, api, id]). A custom
16
+ * observation for another identity is skipped. A compaction receipt for another or missing identity resets
17
+ * the seed to [1]. A matching receipt supplies its recent ratios clamped to [0, CALIBRATION_CEILING],
18
+ * or its legacy factor clamped to [1, CALIBRATION_CEILING]. Without a usable seed, start at [1]. */
27
19
  export declare function seedWindow(branch: readonly SessionEntry[], key: string): number[];
28
20
  export type CompactionState = {
29
21
  kind: "active";
@@ -55,12 +47,12 @@ export interface CompactionOptions {
55
47
  * which is the room less 2% of it, or this fraction of the room when that is lower; a lower value cuts earlier and leaves less. The room
56
48
  * owns cut targets; standalone final capacity admission uses the branch reply floor. If omitted, the band adapts to the last cut. */
57
49
  cutAt?: number;
58
- /** A host's response reserve: without `responseExact: true`, the catalogue maximum output stays its floor; with it, `response` is exact.
59
- * Standalone cuts against Pi's reserveTokens, then admits up to the window less Pi's safety margin and max(3,584, largest branch output), capped at that reserve.
60
- * After a genuine length stop with text/tool output or context overflow it holds the full reserve, also raised to the catalogue maximum.
61
- * Server clipping below the sent reply cap instead learns the smaller window and preserves the normal reply floor.
62
- * Thinking-only exhaustion keeps Pi's reserve and requires the branch's largest observed reply instead.
63
- * Resume, fork and /tree follow that branch's history; a new session has no inherited fallback. */
50
+ /** Models where a usable cached prefix is more valuable than an early cut. */
51
+ cacheSensitiveModels?: readonly string[];
52
+ /** provider/model with provider-native continuation; it keeps one length recovery per run, and only where a cut adds reply room. */
53
+ continuationModel?: string;
54
+ /** Host response reserve. `responseExact: true` uses it as declared. Otherwise the SDK
55
+ * keeps the catalogue maximum as a floor for existing callers. Standalone uses Pi’s soft reserve. */
64
56
  requestReserve?: (ctx: ExtensionContext) => {
65
57
  response: number;
66
58
  responseExact?: true;