@herbertgao/pi-extensions 2026.10.10 → 2026.10.11
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/README.md +10 -8
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +3 -0
- package/node_modules/@herbertgao/pi-cc-extensions/README.md +3 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +3 -3
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +126 -42
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +24 -6
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +69 -16
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/sticky-prompt.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
- package/node_modules/@herbertgao/sol-pi/README.md +7 -1
- package/node_modules/@herbertgao/sol-pi/docs/compatibility.md +28 -4
- package/node_modules/@herbertgao/sol-pi/docs/configuration.md +17 -4
- package/node_modules/@herbertgao/sol-pi/package.json +1 -1
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/index.ts +35 -25
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/then-run.ts +95 -26
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/candidate.ts +39 -2
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/index.ts +24 -0
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/observation-pack/index.ts +12 -7
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/extension.ts +138 -130
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/projection.ts +88 -14
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/tools.ts +9 -0
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/index.ts +14 -5
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/shell-options.ts +22 -0
- package/node_modules/@herbertgao/sol-pi/src/sol-pi/tui.ts +11 -0
- package/node_modules/@juicesharp/rpiv-ask-user-question/answer-channel.ts +109 -0
- package/node_modules/@juicesharp/rpiv-ask-user-question/ask-user-question.ts +117 -71
- package/node_modules/@juicesharp/rpiv-ask-user-question/docs/hosts.md +2 -0
- package/node_modules/@juicesharp/rpiv-ask-user-question/docs/keyboard.md +3 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/docs/startup-performance.md +83 -0
- package/node_modules/@juicesharp/rpiv-ask-user-question/docs/tool-schema.md +74 -5
- package/node_modules/@juicesharp/rpiv-ask-user-question/events.ts +84 -0
- package/node_modules/@juicesharp/rpiv-ask-user-question/index.ts +10 -4
- package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +4 -2
- package/node_modules/@juicesharp/rpiv-ask-user-question/presentation.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/reconcile.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/rpc-fallback.ts +5 -4
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/build-questionnaire.ts +19 -19
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/i18n-bridge.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/key-router.ts +7 -4
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/questionnaire-session.ts +10 -10
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/row-intent.ts +2 -2
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/contract.ts +6 -6
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/derivations.ts +2 -2
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/focus.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/projections.ts +9 -9
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/state-reducer.ts +5 -5
- package/node_modules/@juicesharp/rpiv-ask-user-question/state/state.ts +2 -2
- package/node_modules/@juicesharp/rpiv-ask-user-question/tool/external-answer.ts +125 -0
- package/node_modules/@juicesharp/rpiv-ask-user-question/tool/format-answer.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/tool/normalize-params.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/tool/response-envelope.ts +2 -2
- package/node_modules/@juicesharp/rpiv-ask-user-question/tool/types.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/tool/validate-questionnaire.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/component-binding.ts +4 -4
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/multi-select-view.ts +4 -4
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/option-list-view.ts +2 -2
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/markdown-content-cache.ts +3 -3
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-block-renderer.ts +5 -5
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-layout-decider.ts +3 -3
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-pane.ts +10 -10
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/submit-picker.ts +2 -2
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/tab-bar.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/wrapping-select.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-builder.ts +9 -9
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-copy.ts +1 -1
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/props-adapter.ts +8 -8
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-components.ts +4 -4
- package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-content-strategy.ts +10 -10
- package/node_modules/@narumitw/pi-btw/dist/index.ts +3 -0
- package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
- package/node_modules/@narumitw/pi-btw/package.json +4 -4
- package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +6 -0
- package/node_modules/@narumitw/pi-btw/src/keybindings.ts +1 -1
- package/node_modules/@narumitw/pi-caffeinate/dist/index.ts +1 -0
- package/node_modules/@narumitw/pi-caffeinate/dist/index.ts.map +2 -2
- package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
- package/node_modules/@narumitw/pi-caffeinate/src/inhibitor-process.ts +1 -0
- package/node_modules/pi-antigravity/README.md +6 -2
- package/node_modules/pi-antigravity/package.json +2 -2
- package/node_modules/pi-antigravity/src/client/client.ts +44 -52
- package/node_modules/pi-antigravity/src/index.ts +13 -0
- package/node_modules/pi-antigravity/src/models/discovery.ts +25 -2
- package/node_modules/pi-antigravity/src/models/grouping.ts +107 -68
- package/node_modules/pi-antigravity/src/models/models.ts +10 -0
- package/node_modules/pi-antigravity/src/search/search.ts +581 -43
- package/node_modules/pi-antigravity/src/stream/stream.ts +53 -13
- package/node_modules/pi-antigravity/src/types/types.ts +13 -0
- package/node_modules/pi-antigravity/src/usage/usage.ts +11 -3
- package/node_modules/pi-web-access/CHANGELOG.md +21 -0
- package/node_modules/pi-web-access/README.md +22 -7
- package/node_modules/pi-web-access/credential-source.ts +54 -4
- package/node_modules/pi-web-access/curator-page.ts +3 -1
- package/node_modules/pi-web-access/curator-server.ts +1 -0
- package/node_modules/pi-web-access/deepseek.ts +204 -0
- package/node_modules/pi-web-access/dist/index.js +927 -642
- package/node_modules/pi-web-access/dist/mcp-cli.js +877 -615
- package/node_modules/pi-web-access/gemini-adc.ts +48 -1
- package/node_modules/pi-web-access/gemini-search.ts +8 -4
- package/node_modules/pi-web-access/index.ts +16 -1
- package/node_modules/pi-web-access/package.json +1 -1
- package/node_modules/pi-web-access/page-query.ts +12 -6
- package/node_modules/pi-web-access/query-rewrite.ts +16 -13
- package/node_modules/pi-web-access/summary-review.ts +16 -6
- package/node_modules/pi-web-access/utils.ts +3 -0
- package/node_modules/pi-web-access/web-tool-core.ts +2 -0
- package/package.json +9 -9
|
@@ -11,10 +11,17 @@ import { recordValue } from "./config.ts";
|
|
|
11
11
|
/** Markers written by the action-fusion extension around a fused command's output. */
|
|
12
12
|
const THEN_RUN_SUCCEEDED = "[then_run:succeeded]";
|
|
13
13
|
const THEN_RUN_FAILED = "[then_run:failed]";
|
|
14
|
+
/** Status line pi's bash appends to the inline text of a command that exited non-zero. */
|
|
15
|
+
const EXIT_STATUS_LINE = /(?:^|\n)Command exited with code (-?\d+)\s*$/u;
|
|
14
16
|
|
|
15
17
|
export interface ReducibleToolResult {
|
|
16
18
|
readonly command: string;
|
|
17
19
|
readonly body: string;
|
|
20
|
+
/**
|
|
21
|
+
* Whether the result itself reports a failed command: a non-zero exit code or
|
|
22
|
+
* a `[then_run:failed]` marker. `undefined` when the result carries no signal.
|
|
23
|
+
*/
|
|
24
|
+
readonly exitFailed: boolean | undefined;
|
|
18
25
|
/** Put the receipt back where the raw output was, leaving the rest of the result alone. */
|
|
19
26
|
readonly projectReceipt: (receipt: string) => ToolResultEvent["content"];
|
|
20
27
|
}
|
|
@@ -41,6 +48,22 @@ async function safePiBashTempPath(path: string | undefined): Promise<boolean> {
|
|
|
41
48
|
}
|
|
42
49
|
}
|
|
43
50
|
|
|
51
|
+
/**
|
|
52
|
+
* Read the exit status from the inline text. This must run on the text pi put
|
|
53
|
+
* in the result, not on the full-output file: the file holds only the
|
|
54
|
+
* command's output, without the status line.
|
|
55
|
+
*/
|
|
56
|
+
function inlineExitFailed(inline: string): boolean | undefined {
|
|
57
|
+
const match = inline.match(EXIT_STATUS_LINE);
|
|
58
|
+
return match ? Number(match[1]) !== 0 : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** `structuredContent.exit_code` of a pi >= 0.99 bash result; absent on older pi. */
|
|
62
|
+
function structuredExitCode(event: ToolResultEvent): number | undefined {
|
|
63
|
+
const value = recordValue((event as { structuredContent?: unknown }).structuredContent, "exit_code");
|
|
64
|
+
return typeof value === "number" ? value : undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
44
67
|
/**
|
|
45
68
|
* Prefer the untruncated file pi wrote for a large bash result, so evidence is
|
|
46
69
|
* checked against the exact bytes the command produced rather than a preview.
|
|
@@ -57,6 +80,10 @@ async function exactBodyFromInline(inline: string, details: unknown): Promise<st
|
|
|
57
80
|
}
|
|
58
81
|
}
|
|
59
82
|
|
|
83
|
+
function firstIndex(left: number, right: number): number {
|
|
84
|
+
return left < 0 ? right : right < 0 ? left : Math.min(left, right);
|
|
85
|
+
}
|
|
86
|
+
|
|
60
87
|
/**
|
|
61
88
|
* Identify the log inside a tool result: either a plain bash result, or the
|
|
62
89
|
* command output appended by a fused `edit`/`write` call.
|
|
@@ -66,9 +93,11 @@ export async function reducibleToolResult(event: ToolResultEvent): Promise<Reduc
|
|
|
66
93
|
const command = typeof event.input.command === "string" ? event.input.command : "";
|
|
67
94
|
if (!command) return undefined;
|
|
68
95
|
const inline = textContent(event);
|
|
96
|
+
const exitCode = structuredExitCode(event);
|
|
69
97
|
return {
|
|
70
98
|
command,
|
|
71
99
|
body: await exactBodyFromInline(inline, event.details),
|
|
100
|
+
exitFailed: exitCode !== undefined ? exitCode !== 0 : inlineExitFailed(inline),
|
|
72
101
|
projectReceipt: (receipt) => [{ type: "text", text: receipt }],
|
|
73
102
|
};
|
|
74
103
|
}
|
|
@@ -76,12 +105,14 @@ export async function reducibleToolResult(event: ToolResultEvent): Promise<Reduc
|
|
|
76
105
|
const thenRun = recordValue(event.input, "then_run");
|
|
77
106
|
const commandValue = recordValue(thenRun, "command");
|
|
78
107
|
if (typeof commandValue !== "string" || !commandValue) return undefined;
|
|
79
|
-
const marker = event.isError ? THEN_RUN_FAILED : THEN_RUN_SUCCEEDED;
|
|
80
108
|
for (let index = 0; index < event.content.length; index++) {
|
|
81
109
|
const block = event.content[index];
|
|
82
110
|
if (!block || block.type !== "text") continue;
|
|
83
|
-
|
|
111
|
+
// The first marker in the block is the one action-fusion wrote; the
|
|
112
|
+
// command's own output may quote either marker later on.
|
|
113
|
+
const markerIndex = firstIndex(block.text.indexOf(THEN_RUN_SUCCEEDED), block.text.indexOf(THEN_RUN_FAILED));
|
|
84
114
|
if (markerIndex < 0) continue;
|
|
115
|
+
const marker = block.text.startsWith(THEN_RUN_FAILED, markerIndex) ? THEN_RUN_FAILED : THEN_RUN_SUCCEEDED;
|
|
85
116
|
const suffixStart = markerIndex + marker.length;
|
|
86
117
|
const suffix = block.text.slice(suffixStart);
|
|
87
118
|
const separator = suffix.match(/^(?:\r?\n)+/u)?.[0] ?? "\n";
|
|
@@ -89,6 +120,12 @@ export async function reducibleToolResult(event: ToolResultEvent): Promise<Reduc
|
|
|
89
120
|
return {
|
|
90
121
|
command: commandValue,
|
|
91
122
|
body: await exactBodyFromInline(inline, event.details),
|
|
123
|
+
// Fused results carry no structured exit code, so pi's status line is
|
|
124
|
+
// also trusted over a succeeded marker. This is deliberately conservative:
|
|
125
|
+
// a passing command whose own last line reads `Command exited with code N`
|
|
126
|
+
// is only left unreduced, while a misreported failure would otherwise get
|
|
127
|
+
// a success receipt.
|
|
128
|
+
exitFailed: marker === THEN_RUN_FAILED || inlineExitFailed(inline) === true,
|
|
92
129
|
projectReceipt: (receipt) =>
|
|
93
130
|
event.content.map((content, contentIndex) =>
|
|
94
131
|
contentIndex === index && content.type === "text"
|
package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/index.ts
CHANGED
|
@@ -55,16 +55,39 @@ function errorName(error: unknown): string | undefined {
|
|
|
55
55
|
return isRecord(error) && typeof error.name === "string" ? error.name : undefined;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/**
|
|
59
|
+
* A call another tool made through `executeTool` (a codemode script, for
|
|
60
|
+
* example) carries `parentToolCallId` on pi >= 0.99; older pi never sets it.
|
|
61
|
+
* Such a result never enters the transcript, so reducing it saves nothing, and
|
|
62
|
+
* replacing its content drops the `structuredContent` the calling script reads.
|
|
63
|
+
*/
|
|
64
|
+
function isNestedToolResult(event: ToolResultEvent): boolean {
|
|
65
|
+
return (event as { parentToolCallId?: string }).parentToolCallId !== undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
58
68
|
export async function reduceToolResult(
|
|
59
69
|
journal: Journal,
|
|
60
70
|
config: ReducerConfig,
|
|
61
71
|
event: ToolResultEvent,
|
|
62
72
|
context: ExtensionContext,
|
|
63
73
|
): Promise<ReducedToolResult | undefined> {
|
|
74
|
+
if (isNestedToolResult(event)) return undefined;
|
|
64
75
|
const reducible = await reducibleToolResult(event);
|
|
65
76
|
if (!reducible || !DIAGNOSTIC_COMMAND.test(reducible.command)) return undefined;
|
|
66
77
|
const { body, command } = reducible;
|
|
67
78
|
if (Buffer.byteLength(body, "utf8") < config.minBytes) return undefined;
|
|
79
|
+
// The receipt status follows `isError`. When the result's own text disagrees
|
|
80
|
+
// (a non-zero exit or a failed then_run reported as success, or the reverse),
|
|
81
|
+
// leave the original output in place rather than certify the wrong status.
|
|
82
|
+
if (reducible.exitFailed !== undefined && reducible.exitFailed !== event.isError) {
|
|
83
|
+
journal("fallback", {
|
|
84
|
+
toolCallId: event.toolCallId,
|
|
85
|
+
reason: "exit-state-mismatch",
|
|
86
|
+
isError: event.isError,
|
|
87
|
+
exitFailed: reducible.exitFailed,
|
|
88
|
+
});
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
68
91
|
if (body.length > config.maxChars) {
|
|
69
92
|
journal("fallback", { reason: "source-over-max-chars", sourceChars: body.length, maxChars: config.maxChars });
|
|
70
93
|
return undefined;
|
|
@@ -180,6 +203,7 @@ export function createEvidencePreservingReducerExtension(options: EvidencePreser
|
|
|
180
203
|
return (pi: ExtensionAPI) => {
|
|
181
204
|
const states = new Map<string, { config: ReducerConfig; journal: Journal }>();
|
|
182
205
|
pi.on("tool_result", (event, context) => {
|
|
206
|
+
if (isNestedToolResult(event)) return undefined;
|
|
183
207
|
let root: string;
|
|
184
208
|
try {
|
|
185
209
|
root = runtimeRoot(context);
|
|
@@ -10,9 +10,16 @@
|
|
|
10
10
|
* original bytes are archived by observation id outside the provider context,
|
|
11
11
|
* and the agent pulls exact pages back with the registered `obs_recall` tool.
|
|
12
12
|
*
|
|
13
|
-
* The mechanism never edits history
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* The mechanism never edits stored history. It rewrites only at the projection
|
|
14
|
+
* layer (`pi.on("context")`), so the stored session stays intact and recall
|
|
15
|
+
* keeps working after native compaction or a session resume. Pi hands context
|
|
16
|
+
* handlers a structured clone of the conversation, and the placeholder replaces
|
|
17
|
+
* the content of that clone's message objects in place: since Pi 0.87 a handler
|
|
18
|
+
* that returns different message objects makes Pi collapse every
|
|
19
|
+
* mid-conversation system message (prompt and tool-declaration deltas) into one
|
|
20
|
+
* leading system message, which breaks the provider's cached prefix on every
|
|
21
|
+
* later request. Pi 0.84 sends the edited clone too, so the handler returns
|
|
22
|
+
* nothing on every version.
|
|
16
23
|
*
|
|
17
24
|
* Storage lives under the active Pi session directory.
|
|
18
25
|
*/
|
|
@@ -135,7 +142,6 @@ export function createObservationPackExtension(): ExtensionFactory {
|
|
|
135
142
|
});
|
|
136
143
|
|
|
137
144
|
pi.on("context", async (event, ctx: ExtensionContext) => {
|
|
138
|
-
const projected = [...event.messages];
|
|
139
145
|
const root = runtimeRoot(ctx);
|
|
140
146
|
// How many provider requests each message has already been part of,
|
|
141
147
|
// counted by the assistant messages that follow it.
|
|
@@ -197,7 +203,8 @@ export function createObservationPackExtension(): ExtensionFactory {
|
|
|
197
203
|
formatSavingsCount(removedTokens, "context tokens avoided"),
|
|
198
204
|
);
|
|
199
205
|
}
|
|
200
|
-
|
|
206
|
+
// Same message object, new content: see the note at the top of this file.
|
|
207
|
+
message.content = [{ type: "text", text: placeholder }];
|
|
201
208
|
sentCounts.set(sendCountKey, previousSends + 1);
|
|
202
209
|
} catch (error) {
|
|
203
210
|
// Fail open: a packing failure must never cost the agent its observation.
|
|
@@ -205,8 +212,6 @@ export function createObservationPackExtension(): ExtensionFactory {
|
|
|
205
212
|
console.error(`[observationpack] fail-open for tool result: ${reason}`);
|
|
206
213
|
}
|
|
207
214
|
}
|
|
208
|
-
|
|
209
|
-
return { messages: projected };
|
|
210
215
|
});
|
|
211
216
|
};
|
|
212
217
|
}
|
package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/extension.ts
CHANGED
|
@@ -5,8 +5,6 @@
|
|
|
5
5
|
import type { AgentMessage, AgentToolResult, ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
6
6
|
import {
|
|
7
7
|
estimateTokens,
|
|
8
|
-
findCutPoint,
|
|
9
|
-
sessionEntryToContextMessages,
|
|
10
8
|
type ExtensionAPI,
|
|
11
9
|
type ExtensionContext,
|
|
12
10
|
type ExtensionFactory,
|
|
@@ -19,7 +17,7 @@ import {
|
|
|
19
17
|
type CompactionDecision,
|
|
20
18
|
} from "./economics.ts";
|
|
21
19
|
import { analyzePlanTransition, formatPlanSnapshot, parsePlanSteps } from "./plan.ts";
|
|
22
|
-
import {
|
|
20
|
+
import { estimateProjectedCompactionTokens } from "./projection.ts";
|
|
23
21
|
import {
|
|
24
22
|
appendOnlineState,
|
|
25
23
|
initialOnlineState,
|
|
@@ -51,6 +49,9 @@ const RECOVERABLE_COMPACTION_ERRORS = new Set([
|
|
|
51
49
|
"Already compacted",
|
|
52
50
|
"Summarization failed: generation hit the token cap and the summary is incomplete",
|
|
53
51
|
]);
|
|
52
|
+
export const COMPACTION_FAILED_RESUME_REMINDER =
|
|
53
|
+
"Online context compaction did not complete. The parent task is still active. " +
|
|
54
|
+
"Continue the remaining work from the current plan.";
|
|
54
55
|
|
|
55
56
|
export type OnlineContextCompactOptions = {
|
|
56
57
|
readonly cacheWriteReadRatio?: number | null;
|
|
@@ -61,10 +62,8 @@ type PendingBoundary = { readonly toolCallId: string };
|
|
|
61
62
|
type SelectedCompaction = { readonly decision: CompactionDecision };
|
|
62
63
|
type CacheDebt = { readonly debtTokens: number; readonly repaymentTokens: number };
|
|
63
64
|
type PendingContinuation = { readonly promise: Promise<void>; readonly resolve: () => void };
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (continuation) setTimeout(continuation.resolve, 0);
|
|
67
|
-
}
|
|
65
|
+
type CompactionTokenSettings = { readonly keepRecentTokens: number; readonly reserveTokens: number };
|
|
66
|
+
type SettingsSource = { readonly getSettings?: () => unknown };
|
|
68
67
|
|
|
69
68
|
const SUBAGENTS_MANAGER_KEY = Symbol.for("pi-subagents:manager");
|
|
70
69
|
|
|
@@ -116,84 +115,12 @@ function progressSummary(input: PlanUpdateInput, completedStepId: string): Progr
|
|
|
116
115
|
};
|
|
117
116
|
}
|
|
118
117
|
|
|
119
|
-
function compactionTokenEstimate(
|
|
120
|
-
entries: readonly SessionEntry[],
|
|
121
|
-
startIndex: number,
|
|
122
|
-
endIndex: number,
|
|
123
|
-
projected?: ReadonlyMap<string, number>,
|
|
124
|
-
): number {
|
|
125
|
-
let tokens = 0;
|
|
126
|
-
for (let index = startIndex; index < endIndex; index++) {
|
|
127
|
-
const entry = entries[index];
|
|
128
|
-
if (!entry || entry.type === "compaction") continue;
|
|
129
|
-
if (projected) {
|
|
130
|
-
tokens += projected.get(entry.id) ?? 0;
|
|
131
|
-
continue;
|
|
132
|
-
}
|
|
133
|
-
const message = sessionEntryToContextMessages(entry)[0];
|
|
134
|
-
if (message) tokens += estimateTokens(message);
|
|
135
|
-
}
|
|
136
|
-
return tokens;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function branchAfterAbort(entries: readonly SessionEntry[]): SessionEntry[] {
|
|
140
|
-
const last = entries.at(-1);
|
|
141
|
-
const markerProvider = ["sol", "pi"].join("-");
|
|
142
|
-
return [
|
|
143
|
-
...entries,
|
|
144
|
-
{
|
|
145
|
-
type: "message",
|
|
146
|
-
id: "sol-pi-online-context-compact-abort-marker",
|
|
147
|
-
parentId: last?.id ?? null,
|
|
148
|
-
timestamp: new Date(0).toISOString(),
|
|
149
|
-
message: {
|
|
150
|
-
role: "assistant",
|
|
151
|
-
content: [],
|
|
152
|
-
api: markerProvider,
|
|
153
|
-
provider: markerProvider,
|
|
154
|
-
model: "aborted",
|
|
155
|
-
usage: {
|
|
156
|
-
input: 0,
|
|
157
|
-
output: 0,
|
|
158
|
-
cacheRead: 0,
|
|
159
|
-
cacheWrite: 0,
|
|
160
|
-
totalTokens: 0,
|
|
161
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
162
|
-
},
|
|
163
|
-
stopReason: "aborted",
|
|
164
|
-
timestamp: 0,
|
|
165
|
-
},
|
|
166
|
-
} as SessionEntry,
|
|
167
|
-
];
|
|
168
|
-
}
|
|
169
|
-
|
|
170
118
|
export function estimateNativeCompactionTokens(
|
|
171
119
|
entries: readonly SessionEntry[],
|
|
172
120
|
keepRecentTokens: number,
|
|
173
121
|
projectedMessages?: readonly AgentMessage[],
|
|
174
122
|
): number {
|
|
175
|
-
|
|
176
|
-
const projected = projectedMessages === undefined ? undefined : projectedEntryTokens(entries, projectedMessages);
|
|
177
|
-
let startIndex = 0;
|
|
178
|
-
let previousSummaryTokens = 0;
|
|
179
|
-
for (let index = path.length - 1; index >= 0; index--) {
|
|
180
|
-
const entry = path[index];
|
|
181
|
-
if (entry?.type !== "compaction") continue;
|
|
182
|
-
const keptIndex = path.findIndex((item) => item.id === entry.firstKeptEntryId);
|
|
183
|
-
startIndex = keptIndex >= 0 ? keptIndex : index + 1;
|
|
184
|
-
const previousSummary = sessionEntryToContextMessages(entry)[0];
|
|
185
|
-
previousSummaryTokens = projected
|
|
186
|
-
? projected.get(entry.id) ?? 0
|
|
187
|
-
: previousSummary ? estimateTokens(previousSummary) : 0;
|
|
188
|
-
break;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// Keep Pi's native cut on session entries; price only the corresponding
|
|
192
|
-
// messages that the provider actually saw after context projection.
|
|
193
|
-
const cut = findCutPoint(path, startIndex, path.length, keepRecentTokens);
|
|
194
|
-
const firstKept = cut.firstKeptEntryIndex;
|
|
195
|
-
if (compactionTokenEstimate(path, startIndex, firstKept) === 0) return 0;
|
|
196
|
-
return previousSummaryTokens + compactionTokenEstimate(path, startIndex, firstKept, projected);
|
|
123
|
+
return estimateProjectedCompactionTokens(entries, keepRecentTokens, projectedMessages);
|
|
197
124
|
}
|
|
198
125
|
|
|
199
126
|
function validPositiveInteger(value: unknown): value is number {
|
|
@@ -231,8 +158,45 @@ function restoreCompactionThinking(pi: ExtensionAPI, override: CompactionThinkin
|
|
|
231
158
|
}
|
|
232
159
|
}
|
|
233
160
|
|
|
161
|
+
function tokenSetting(value: unknown): number | undefined {
|
|
162
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function record(value: unknown): Readonly<Record<string, unknown>> | undefined {
|
|
166
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
167
|
+
? (value as Readonly<Record<string, unknown>>)
|
|
168
|
+
: undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Pi's effective compaction token settings for `model`, resolved the way Pi resolves them:
|
|
173
|
+
* `compaction.modelOverrides["<provider>/<id>"]`, then `compaction`, then Pi's defaults.
|
|
174
|
+
*/
|
|
175
|
+
export function resolveCompactionTokenSettings(
|
|
176
|
+
settings: unknown,
|
|
177
|
+
model: { readonly provider: string; readonly id: string } | undefined,
|
|
178
|
+
): CompactionTokenSettings {
|
|
179
|
+
const compaction = record(record(settings)?.compaction);
|
|
180
|
+
const override = model ? record(record(compaction?.modelOverrides)?.[`${model.provider}/${model.id}`]) : undefined;
|
|
181
|
+
return {
|
|
182
|
+
keepRecentTokens:
|
|
183
|
+
tokenSetting(override?.keepRecentTokens) ??
|
|
184
|
+
tokenSetting(compaction?.keepRecentTokens) ??
|
|
185
|
+
DEFAULT_KEEP_RECENT_TOKENS,
|
|
186
|
+
reserveTokens:
|
|
187
|
+
tokenSetting(override?.reserveTokens) ??
|
|
188
|
+
tokenSetting(compaction?.reserveTokens) ??
|
|
189
|
+
DEFAULT_COMPACTION_ECONOMICS.windowReserveTokens,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function isUserAbort(error: Error): boolean {
|
|
194
|
+
return error.name === "AbortError" || error.message === "Compaction cancelled";
|
|
195
|
+
}
|
|
196
|
+
|
|
234
197
|
export function createOnlineContextCompactExtension(options: OnlineContextCompactOptions = {}): ExtensionFactory {
|
|
235
|
-
const
|
|
198
|
+
const configuredKeepRecentTokens =
|
|
199
|
+
options.keepRecentTokens === undefined ? undefined : resolveKeepRecentTokens(options.keepRecentTokens);
|
|
236
200
|
const cacheWriteReadRatio = resolveCacheWriteReadRatio(options.cacheWriteReadRatio);
|
|
237
201
|
|
|
238
202
|
return (pi) => {
|
|
@@ -242,9 +206,10 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
242
206
|
let pendingBoundary: PendingBoundary | undefined;
|
|
243
207
|
let selected: SelectedCompaction | undefined;
|
|
244
208
|
let activeDebt: CacheDebt | undefined;
|
|
209
|
+
let nextContinuation: PendingContinuation | undefined;
|
|
245
210
|
let compactionInFlight = false;
|
|
246
211
|
let compactionThinkingOverride: CompactionThinkingOverride | undefined;
|
|
247
|
-
let
|
|
212
|
+
let requestPending = false;
|
|
248
213
|
let compactionRefused = false;
|
|
249
214
|
|
|
250
215
|
const releaseContinuation = (): void => {
|
|
@@ -253,6 +218,10 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
253
218
|
continuation?.resolve();
|
|
254
219
|
};
|
|
255
220
|
|
|
221
|
+
const releaseParentContinuation = (continuation: PendingContinuation | undefined): void => {
|
|
222
|
+
if (continuation) setTimeout(continuation.resolve, 0);
|
|
223
|
+
};
|
|
224
|
+
|
|
256
225
|
const restore = (context: ExtensionContext): void => {
|
|
257
226
|
releaseContinuation();
|
|
258
227
|
state = restoreOnlineState(context.sessionManager.getBranch());
|
|
@@ -263,12 +232,27 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
263
232
|
selected = undefined;
|
|
264
233
|
activeDebt = undefined;
|
|
265
234
|
compactionInFlight = false;
|
|
235
|
+
requestPending = false;
|
|
266
236
|
compactionRefused = false;
|
|
267
237
|
};
|
|
268
238
|
const ensureRestored = (context: ExtensionContext): void => {
|
|
269
239
|
if (!restored) restore(context);
|
|
270
240
|
};
|
|
271
241
|
const save = (): void => appendOnlineState(pi, state);
|
|
242
|
+
// Pi 1.0 exposes its effective settings; Pi 0.84.2 does not, so it keeps the documented defaults.
|
|
243
|
+
const compactionSettings = (context: ExtensionContext): CompactionTokenSettings => {
|
|
244
|
+
const getSettings = (pi as SettingsSource).getSettings;
|
|
245
|
+
let settings: unknown;
|
|
246
|
+
try {
|
|
247
|
+
settings = typeof getSettings === "function" ? getSettings.call(pi) : undefined;
|
|
248
|
+
} catch {
|
|
249
|
+
settings = undefined;
|
|
250
|
+
}
|
|
251
|
+
const resolved = resolveCompactionTokenSettings(settings, context.model);
|
|
252
|
+
return configuredKeepRecentTokens === undefined
|
|
253
|
+
? resolved
|
|
254
|
+
: { ...resolved, keepRecentTokens: configuredKeepRecentTokens };
|
|
255
|
+
};
|
|
272
256
|
const contextTokens = (context: ExtensionContext): number => {
|
|
273
257
|
const visible = observedMessages.reduce((total, message) => total + estimateTokens(message), 0);
|
|
274
258
|
const estimated = visible + tokenEstimate(context.getSystemPrompt());
|
|
@@ -310,17 +294,31 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
310
294
|
pi.on("session_before_tree", () => (compactionInFlight ? { cancel: true } : undefined));
|
|
311
295
|
pi.on("session_tree", (_event, context) => restore(context));
|
|
312
296
|
|
|
297
|
+
// Count a provider request only when it carries an agent-loop context. Pi builds each agent
|
|
298
|
+
// request with one context event before the provider sends it. A build that never reaches the
|
|
299
|
+
// provider, such as the one Pi still starts after this extension aborts at a boundary, is not
|
|
300
|
+
// a request. Pi 1.0 cache warming replays the last request through before_provider_request
|
|
301
|
+
// without a context event; a replay is not a request either.
|
|
313
302
|
pi.on("context", (event, context) => {
|
|
314
303
|
ensureRestored(context);
|
|
315
304
|
observedMessages = [...event.messages];
|
|
305
|
+
requestPending = !context.signal?.aborted;
|
|
316
306
|
});
|
|
317
307
|
|
|
318
308
|
pi.on("before_provider_request", (_event, context) => {
|
|
309
|
+
if (!requestPending) return;
|
|
310
|
+
requestPending = false;
|
|
319
311
|
ensureRestored(context);
|
|
320
312
|
state = recordProviderRequest(state, contextTokens(context));
|
|
321
313
|
save();
|
|
322
314
|
});
|
|
323
315
|
|
|
316
|
+
// The assistant message ends the request a context event started, whether or not it reached
|
|
317
|
+
// the provider, so a later replay cannot take its place.
|
|
318
|
+
pi.on("message_end", (event) => {
|
|
319
|
+
if (event.message.role === "assistant") requestPending = false;
|
|
320
|
+
});
|
|
321
|
+
|
|
324
322
|
pi.on("input", (event, context) => {
|
|
325
323
|
compactionRefused = false;
|
|
326
324
|
ensureRestored(context);
|
|
@@ -359,6 +357,7 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
359
357
|
return;
|
|
360
358
|
}
|
|
361
359
|
|
|
360
|
+
const { keepRecentTokens, reserveTokens } = compactionSettings(context);
|
|
362
361
|
const usage = context.getContextUsage();
|
|
363
362
|
const writeTokens = contextTokens(context);
|
|
364
363
|
const archiveTokens = estimateNativeCompactionTokens(
|
|
@@ -392,7 +391,7 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
392
391
|
carriedDebtTokens: state.cacheDebtTokens,
|
|
393
392
|
cacheDebtRepaymentTokens: state.cacheDebtRepaymentTokens,
|
|
394
393
|
cacheWriteReadRatio,
|
|
395
|
-
economics: DEFAULT_COMPACTION_ECONOMICS,
|
|
394
|
+
economics: { ...DEFAULT_COMPACTION_ECONOMICS, windowReserveTokens: reserveTokens },
|
|
396
395
|
});
|
|
397
396
|
const decision: CompactionDecision =
|
|
398
397
|
priced.compact && archiveTokens === 0
|
|
@@ -404,9 +403,41 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
404
403
|
context.abort();
|
|
405
404
|
});
|
|
406
405
|
|
|
406
|
+
// Resume the parent task after a boundary compaction. Pi before 0.87 starts the requested turn
|
|
407
|
+
// synchronously, and this barrier keeps the settlement open until that turn settles. Pi 0.87+
|
|
408
|
+
// defers a turn requested from agent_settled until every settled handler has returned, keeps
|
|
409
|
+
// the session idle meanwhile, and awaits the turn before its own settlement completes, so
|
|
410
|
+
// waiting here would deadlock.
|
|
411
|
+
const continueParentTask = async (context: ExtensionContext, content: string): Promise<void> => {
|
|
412
|
+
let resolveContinuation!: () => void;
|
|
413
|
+
const continuation: PendingContinuation = {
|
|
414
|
+
promise: new Promise<void>((resolve) => {
|
|
415
|
+
resolveContinuation = resolve;
|
|
416
|
+
}),
|
|
417
|
+
resolve: () => resolveContinuation(),
|
|
418
|
+
};
|
|
419
|
+
nextContinuation = continuation;
|
|
420
|
+
try {
|
|
421
|
+
pi.sendMessage(
|
|
422
|
+
{ customType: "sol-pi-online-context-compact", content, display: false },
|
|
423
|
+
{ triggerTurn: true },
|
|
424
|
+
);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
if (nextContinuation === continuation) nextContinuation = undefined;
|
|
427
|
+
continuation.resolve();
|
|
428
|
+
throw error;
|
|
429
|
+
}
|
|
430
|
+
if (context.isIdle()) {
|
|
431
|
+
if (nextContinuation === continuation) nextContinuation = undefined;
|
|
432
|
+
continuation.resolve();
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
await continuation.promise;
|
|
436
|
+
};
|
|
437
|
+
|
|
407
438
|
pi.on("agent_settled", async (_event, context) => {
|
|
408
|
-
//
|
|
409
|
-
//
|
|
439
|
+
// sendMessage() starts a turn without returning its promise. Capture the
|
|
440
|
+
// child settlement so print/JSON mode cannot dispose while it is running.
|
|
410
441
|
const parentContinuation = nextContinuation;
|
|
411
442
|
nextContinuation = undefined;
|
|
412
443
|
const pending = selected;
|
|
@@ -467,54 +498,20 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
467
498
|
restoreCompactionThinking(pi, compactionThinkingOverride);
|
|
468
499
|
compactionThinkingOverride = undefined;
|
|
469
500
|
compactionInFlight = false;
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
compactionError &&
|
|
473
|
-
!recoverableError &&
|
|
474
|
-
compactionError.name !== "AbortError" &&
|
|
475
|
-
compactionError.message !== "Compaction cancelled"
|
|
476
|
-
) {
|
|
477
|
-
throw compactionError;
|
|
478
|
-
}
|
|
479
|
-
|
|
501
|
+
const failure = compactionError && !isUserAbort(compactionError) ? compactionError : undefined;
|
|
502
|
+
const recoverableError = failure !== undefined && RECOVERABLE_COMPACTION_ERRORS.has(failure.message);
|
|
480
503
|
if (recoverableError) {
|
|
481
504
|
compactionRefused = true;
|
|
482
|
-
pi.appendEntry("sol-pi-online-context-compact-skipped", { reason:
|
|
483
|
-
if (context.mode === "tui") context.ui.notify(`Online compaction skipped: ${
|
|
484
|
-
}
|
|
485
|
-
if (compacted || recoverableError) {
|
|
486
|
-
let resolveContinuation!: () => void;
|
|
487
|
-
const continuation: PendingContinuation = {
|
|
488
|
-
promise: new Promise<void>((resolve) => {
|
|
489
|
-
resolveContinuation = resolve;
|
|
490
|
-
}),
|
|
491
|
-
resolve: () => resolveContinuation(),
|
|
492
|
-
};
|
|
493
|
-
nextContinuation = continuation;
|
|
494
|
-
try {
|
|
495
|
-
pi.sendMessage(
|
|
496
|
-
{
|
|
497
|
-
customType: "sol-pi-online-context-compact",
|
|
498
|
-
content: compacted ? POST_COMPACTION_PLAN_REMINDER : SKIPPED_COMPACTION_REMINDER,
|
|
499
|
-
display: false,
|
|
500
|
-
},
|
|
501
|
-
{ triggerTurn: true },
|
|
502
|
-
);
|
|
503
|
-
} catch (error) {
|
|
504
|
-
if (nextContinuation === continuation) nextContinuation = undefined;
|
|
505
|
-
continuation.resolve();
|
|
506
|
-
throw error;
|
|
507
|
-
}
|
|
508
|
-
if (context.isIdle() && nextContinuation === continuation) {
|
|
509
|
-
// Newer Pi hosts defer runs until settled handlers return. Hand
|
|
510
|
-
// control back to that host instead of waiting on a deferred run.
|
|
511
|
-
nextContinuation = undefined;
|
|
512
|
-
continuation.resolve();
|
|
513
|
-
} else {
|
|
514
|
-
// Pi 0.85.1 starts synchronously; keep its print-mode barrier.
|
|
515
|
-
await continuation.promise;
|
|
516
|
-
}
|
|
505
|
+
pi.appendEntry("sol-pi-online-context-compact-skipped", { reason: failure!.message });
|
|
506
|
+
if (context.mode === "tui") context.ui.notify(`Online compaction skipped: ${failure!.message}`, "warning");
|
|
517
507
|
}
|
|
508
|
+
|
|
509
|
+
// The run was stopped for this compaction, so resume it unless the user cancelled.
|
|
510
|
+
// Known native refusals are recorded as skips; other failures still propagate after resuming.
|
|
511
|
+
if (compacted) await continueParentTask(context, POST_COMPACTION_PLAN_REMINDER);
|
|
512
|
+
else if (recoverableError) await continueParentTask(context, SKIPPED_COMPACTION_REMINDER);
|
|
513
|
+
else if (failure) await continueParentTask(context, COMPACTION_FAILED_RESUME_REMINDER);
|
|
514
|
+
if (failure && !recoverableError) throw failure;
|
|
518
515
|
} finally {
|
|
519
516
|
restoreCompactionThinking(pi, compactionThinkingOverride);
|
|
520
517
|
compactionThinkingOverride = undefined;
|
|
@@ -524,6 +521,15 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
524
521
|
}
|
|
525
522
|
});
|
|
526
523
|
|
|
524
|
+
// Pi may run its own threshold compaction for a run this extension has already stopped for a
|
|
525
|
+
// selected boundary compaction: Pi 0.84.4+ before the run's next request, older Pi after the
|
|
526
|
+
// run when the aborted request ends with an error. That compaction would consume the
|
|
527
|
+
// selection, so the boundary would get no continuation. Let the selected compaction run from
|
|
528
|
+
// agent_settled instead.
|
|
529
|
+
pi.on("session_before_compact", (event) =>
|
|
530
|
+
selected && event.reason === "threshold" ? { cancel: true } : undefined,
|
|
531
|
+
);
|
|
532
|
+
|
|
527
533
|
pi.on("session_compact", (event, context) => {
|
|
528
534
|
ensureRestored(context);
|
|
529
535
|
compactionRefused = false;
|
|
@@ -535,6 +541,7 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
535
541
|
pendingBoundary = undefined;
|
|
536
542
|
selected = undefined;
|
|
537
543
|
activeDebt = undefined;
|
|
544
|
+
requestPending = false;
|
|
538
545
|
observedMessages = [];
|
|
539
546
|
});
|
|
540
547
|
|
|
@@ -546,6 +553,7 @@ export function createOnlineContextCompactExtension(options: OnlineContextCompac
|
|
|
546
553
|
selected = undefined;
|
|
547
554
|
activeDebt = undefined;
|
|
548
555
|
compactionInFlight = false;
|
|
556
|
+
requestPending = false;
|
|
549
557
|
});
|
|
550
558
|
};
|
|
551
559
|
}
|