billion-context-pi 0.1.34 → 0.1.36

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 CHANGED
@@ -148,7 +148,10 @@ Create `~/.pi/acp.json` (global) and/or `<project>/.pi/acp.json` (project-local,
148
148
  "modelContextLimit": 200000,
149
149
  "delegate": true,
150
150
  "toolBashDefaultTimeout": 60,
151
- "toolOutputMaxBytes": 200000
151
+ "toolOutputMaxBytes": 200000,
152
+ "maxContextLimit": "75%",
153
+ "emergencyThresholdPercent": "95%",
154
+ "nudgeGrowthTokens": 50000
152
155
  }
153
156
  ```
154
157
 
@@ -160,8 +163,11 @@ Create `~/.pi/acp.json` (global) and/or `<project>/.pi/acp.json` (project-local,
160
163
  | `delegate` | `true` | Enable the `acp_delegate` tools (delegate/wait/cancel) and their system-prompt section. Set `false` to skip registering them (e.g. you use a different sub-agent extension, or run headless where async injection adds no value). |
161
164
  | `toolBashDefaultTimeout` | `60` | Seconds injected into the `bash` tool when the model omits `timeout`. Pi has **no** default of its own, so without this a forgotten timeout can hang for thousands of seconds. On timeout the model is guided to re-run with a larger `timeout`. `0` restores Pi's unbounded behavior. |
162
165
  | `toolOutputMaxBytes` | `200000` | Hard byte cap on tool result text (~5000 lines at ~40 B/line; applied via the `tool_result` hook). Stops runaway output that Pi's own 50KB/2000-line cap can't catch (e.g. tools Pi doesn't cap). When it fires the model is told how to see the full output — for `bash` the full output is in its temp file (`BashToolDetails.fullOutputPath`); set lower (e.g. `8192`) for a tighter context budget, or `0` to disable. |
166
+ | `maxContextLimit` | `"75%"` | Context usage threshold that triggers **forced compression** nudges (bypasses growth-gate + cadence). Accepts a ratio (`0.75`) or percent string (`"75%"`). Lower = compress earlier / more aggressively. Maps to kernel `nudge.maxContextLimitPct`. |
167
+ | `emergencyThresholdPercent` | `"95%"` | Context usage threshold that triggers **emergency truncation** of large tool outputs to keep the session alive. Accepts a ratio (`0.95`) or percent string (`"95%"`). Must be ≥ `maxContextLimit`. Maps to kernel `nudge.emergencyThresholdPct` + `truncate.threshold`. |
168
+ | `nudgeGrowthTokens` | `50000` | Token growth step for soft compression nudges. A nudge fires roughly every time this many tokens become compressible. Lower = compress more often; higher = compress less often. Maps to kernel `nudge.growthFloor` + `nudge.growthCap`. |
163
169
 
164
- > **Only these six keys are read from `acp.json`.** Other tuning knobs (`preserveRecentMessages`, `protectedTools`, nudge thresholds) are code-level and not user-overridable.
170
+ > **Only these nine keys are read from `acp.json`.** Other tuning knobs (`preserveRecentMessages`, `protectedTools`) are code-level and not user-overridable. The three nudge thresholds (`maxContextLimit`, `emergencyThresholdPercent`, `nudgeGrowthTokens`) form a three-tier escalation: growth-driven soft nudges → forced nudges at `maxContextLimit` → emergency truncation at `emergencyThresholdPercent`.
165
171
 
166
172
  ### Environment variables
167
173
 
package/README.zh-CN.md CHANGED
@@ -147,7 +147,10 @@ billion-context-pi 开箱即用,无需任何配置。可以在 JSON 配置文件
147
147
  "modelContextLimit": 200000,
148
148
  "delegate": true,
149
149
  "toolBashDefaultTimeout": 60,
150
- "toolOutputMaxBytes": 200000
150
+ "toolOutputMaxBytes": 200000,
151
+ "maxContextLimit": "75%",
152
+ "emergencyThresholdPercent": "95%",
153
+ "nudgeGrowthTokens": 50000
151
154
  }
152
155
  ```
153
156
 
@@ -159,8 +162,11 @@ billion-context-pi 开箱即用,无需任何配置。可以在 JSON 配置文件
159
162
  | `delegate` | `true` | 启用 `acp_delegate` 工具(delegate/wait/cancel)及其系统提示词段落。设为 `false` 则不注册这些工具(例如你用了别的子代理扩展,或跑 headless 场景异步注入没有意义)。 |
160
163
  | `toolBashDefaultTimeout` | `60` | 当模型未指定 `timeout` 时注入 `bash` 工具的超时秒数。Pi **本身没有默认超时**,不加这个,一次遗漏的超时可能挂起几千秒。超时后会提示模型用更大的 `timeout` 重跑。设为 `0` 恢复 Pi 的无界行为。 |
161
164
  | `toolOutputMaxBytes` | `200000` | 工具结果文本硬上限(字节,约 5000 行 @ ~40 字节/行,通过 `tool_result` hook 应用)。用于兜住 Pi 自身 50KB/2000 行截断管不到的输出(例如 Pi 未加限制的工具)。触发截断时会告诉模型如何查看完整输出——对 `bash`,完整输出在其临时文件(`BashToolDetails.fullOutputPath`)中;设更小(如 `8192`)可更省上下文,设 `0` 关闭。 |
165
+ | `maxContextLimit` | `"75%"` | 上下文使用率达到此值时触发**强制压缩** nudge(绕过增长门控 + 频率限制)。支持比例(`0.75`)或百分比字符串(`"75%"`)。调小 → 更早/更激进压缩。映射到内核 `nudge.maxContextLimitPct`。 |
166
+ | `emergencyThresholdPercent` | `"95%"` | 上下文使用率达到此值时触发**紧急截断**,硬截断大块工具输出以保住会话。支持比例(`0.95`)或百分比字符串(`"95%"`)。必须 ≥ `maxContextLimit`。映射到内核 `nudge.emergencyThresholdPct` + `truncate.threshold`。 |
167
+ | `nudgeGrowthTokens` | `50000` | 软压缩 nudge 的增长步长(token)。大约每积累这么多可压缩 token 就触发一次 nudge。调小 → 压得更频繁;调大 → 压得更少。映射到内核 `nudge.growthFloor` + `nudge.growthCap`。 |
162
168
 
163
- > **只有这六个 key 会被 `acp.json` 读取。** 其他调优参数(`preserveRecentMessages`、`protectedTools`、nudge 阈值)是代码级的,不向用户开放。
169
+ > **只有这九个 key 会被 `acp.json` 读取。** 其他调优参数(`preserveRecentMessages`、`protectedTools`)是代码级的,不向用户开放。三个 nudge 阈值(`maxContextLimit`、`emergencyThresholdPercent`、`nudgeGrowthTokens`)构成三级触发:增长驱动的软 nudge → `maxContextLimit` 强制 nudge → `emergencyThresholdPercent` 紧急截断。
164
170
 
165
171
  ### 环境变量
166
172
 
package/dist/config.d.ts CHANGED
@@ -1,4 +1,33 @@
1
1
  import { type Config } from "acp-kernel";
2
+ /** Delegate sub-agent configuration. */
3
+ export interface DelegateConfig {
4
+ /** Enable acp_delegate tools (delegate/wait/cancel) and their system-prompt
5
+ * section. Default: true. Set `enabled: false` to skip registering them. */
6
+ enabled?: boolean;
7
+ /** How delegate usage is reported back to the main session.
8
+ * "separate" (default) — delegate tokens tracked in a separate accumulator;
9
+ * main session totals stay clean, delegate usage shows as its own block in
10
+ * acp_status (excluded from main totals).
11
+ * "merged" — delegate token usage folded into the tool-result usage field,
12
+ * counted as part of the main session totals. */
13
+ displayUsage?: "merged" | "separate";
14
+ }
15
+ /** Compression tuning. All fields accept a ratio (0.75) or percent string
16
+ * ("75%") where noted. */
17
+ export interface CompressConfig {
18
+ /** Context usage percentage that triggers forced compression nudges
19
+ * (bypasses growth-gate + cadence). Accepts a ratio (0.75) or percent
20
+ * string ("75%"). Default: 0.75. Maps to kernel nudge.maxContextLimitPct. */
21
+ maxContextLimit?: number | string;
22
+ /** Context usage percentage that triggers emergency truncation of large
23
+ * tool outputs. Accepts a ratio (0.95) or percent string ("95%").
24
+ * Default: 0.95. Must be >= maxContextLimit. Maps to kernel
25
+ * nudge.emergencyThresholdPct + truncate.threshold. */
26
+ emergencyThresholdPercent?: number | string;
27
+ /** Token growth threshold for soft compression nudges. Default: 50000.
28
+ * Maps to kernel nudge.growthFloor + nudge.growthCap. */
29
+ nudgeGrowthTokens?: number;
30
+ }
2
31
  /**
3
32
  * Adapter configuration. Maps onto acp-kernel's `Config` plus Pi-specific knobs
4
33
  * (live model context window, protected tools, state persistence).
@@ -18,10 +47,6 @@ export interface AdapterConfig {
18
47
  * warnings) are written regardless; `debug` only adds verbose diagnostics.
19
48
  * Default: false (or env ACP_DEBUG=1/true). */
20
49
  debug?: boolean;
21
- /** Enable acp_delegate tools (delegate/wait/cancel) and their system-prompt
22
- * section. Default: true. Set `delegate: false` (adapter config or
23
- * ~/.pi/acp.json) to skip registering them. */
24
- delegate?: boolean;
25
50
  /** Default timeout in seconds injected into the bash tool when the model
26
51
  * omits `timeout`. Pi has NO built-in default, so without this a command
27
52
  * that the model forgets to time out can hang for thousands of seconds.
@@ -38,8 +63,24 @@ export interface AdapterConfig {
38
63
  * head-truncated with a notice telling the model how to see the full output
39
64
  * (bash: read BashToolDetails.fullOutputPath). */
40
65
  toolOutputMaxBytes?: number;
66
+ /** Delegate sub-agent config. Accepts a boolean shorthand (`true` →
67
+ * `{ enabled: true }`, `false` → `{ enabled: false }`) or a DelegateConfig
68
+ * object. Default: enabled. */
69
+ delegate?: boolean | DelegateConfig;
70
+ /** Compression tuning. */
71
+ compress?: CompressConfig;
72
+ /** Legacy flat alias for `delegate.displayUsage`. Kept for backward
73
+ * compatibility with existing acp.json files. Prefer `delegate.displayUsage`. */
74
+ displayUsage?: "merged" | "separate";
41
75
  coreOverrides?: Partial<Config>;
42
76
  }
43
77
  export declare const DEFAULT_TOOL_BASH_TIMEOUT = 60;
44
78
  export declare const DEFAULT_TOOL_OUTPUT_MAX_BYTES = 200000;
79
+ /** Resolve delegate config from the adapter, handling the boolean shorthand
80
+ * and the legacy flat `displayUsage` alias. */
81
+ export declare function resolveDelegate(adapter: AdapterConfig): {
82
+ enabled: boolean;
83
+ displayUsage: "merged" | "separate";
84
+ };
45
85
  export declare function resolveConfig(adapter: AdapterConfig, liveContextLimit: number): Config;
86
+ export declare function parsePercent(v: number | string): number;
@@ -1,3 +1,27 @@
1
+ export interface Usage {
2
+ input: number;
3
+ output: number;
4
+ cacheRead: number;
5
+ cacheWrite: number;
6
+ cacheWrite1h?: number;
7
+ reasoning?: number;
8
+ totalTokens: number;
9
+ cost: {
10
+ input: number;
11
+ output: number;
12
+ cacheRead: number;
13
+ cacheWrite: number;
14
+ total: number;
15
+ };
16
+ }
17
+ export interface UsageUpdateEvent {
18
+ kind: "usage-update";
19
+ usage: Usage;
20
+ }
21
+ export interface AgentSettledEvent {
22
+ kind: "agent-settled";
23
+ }
24
+ export declare function handleMessageEnd(event: Record<string, unknown>): UsageUpdateEvent | null;
1
25
  export interface ToolStartEvent {
2
26
  kind: "tool-start";
3
27
  toolName: string;
@@ -25,7 +49,7 @@ export interface ThinkingDeltaEvent {
25
49
  kind: "thinking-delta";
26
50
  delta: string;
27
51
  }
28
- export type ParsedEvent = ToolStartEvent | ToolUpdateEvent | ToolEndEvent | ReplyDeltaEvent | ReplyCompleteEvent | ThinkingDeltaEvent | ThinkingEndEvent | RetryStartEvent | RetryEndEvent;
52
+ export type ParsedEvent = ToolStartEvent | ToolUpdateEvent | ToolEndEvent | ReplyDeltaEvent | ReplyCompleteEvent | ThinkingDeltaEvent | ThinkingEndEvent | RetryStartEvent | RetryEndEvent | UsageUpdateEvent | AgentSettledEvent;
29
53
  export interface ThinkingEndEvent {
30
54
  kind: "thinking-end";
31
55
  }
@@ -37,10 +61,12 @@ export interface ThinkingEndEvent {
37
61
  export declare class ThinkingCollector {
38
62
  private readonly showThinking;
39
63
  private buf;
64
+ private usage;
40
65
  constructor(showThinking: boolean);
41
66
  push(delta: string): void;
42
- /** Return the segment line to write ("" when empty or disabled), resetting. */
67
+ process(ev: ParsedEvent): void;
43
68
  flush(): string;
69
+ getUsage(): Usage | undefined;
44
70
  }
45
71
  export interface RetryStartEvent {
46
72
  kind: "retry-start";
@@ -1,7 +1,44 @@
1
- import { type SpawnOptions } from "node:child_process";
1
+ import { type ChildProcess, type SpawnOptions } from "node:child_process";
2
2
  import { Type, type Static } from "typebox";
3
- import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ import type { AgentToolResult, ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
4
+ import { type Usage } from "./delegate-events.js";
4
5
  export declare function delegateSpawnOptions(cwd: string, env: NodeJS.ProcessEnv): SpawnOptions;
6
+ type RunStatus = "running" | "completed" | "failed" | "cancelled";
7
+ interface DelegateRun {
8
+ runId: string;
9
+ agent: string;
10
+ task: string;
11
+ cwd: string;
12
+ startedAt: number;
13
+ finishedAt?: number;
14
+ status: RunStatus;
15
+ exitCode?: number | null;
16
+ child?: ChildProcess;
17
+ result?: {
18
+ code: number | null;
19
+ file: string;
20
+ body: string;
21
+ };
22
+ consumed?: boolean;
23
+ /** True once the close handler injected the result as a system
24
+ * notification (sendUserMessage succeeded). Lets a later wait() avoid
25
+ * re-delivering the same payload. */
26
+ injected?: boolean;
27
+ /** Watchdog reason string when the run was force-terminated ("no output for
28
+ * 5m", "30m limit"); surfaced in completion headers as "(timed out: ...)". */
29
+ timedOut?: string;
30
+ waiter?: () => void;
31
+ /** Accumulated LLM usage from the delegate (from message_end events). */
32
+ usage?: Usage;
33
+ /** True once a wait/cancel tool has returned usage — prevents double-count. */
34
+ usageReported?: boolean;
35
+ /** True once agent_settled fired; a watchdog kill after this is stuck teardown, not a timeout. */
36
+ agentSettled?: boolean;
37
+ }
38
+ export declare function addDelegateUsage(u: Usage): void;
39
+ export declare function getDelegateUsage(): Usage | undefined;
40
+ export declare function resetDelegateUsage(): void;
41
+ export declare function setDelegateDisplayUsage(mode: "merged" | "separate"): void;
5
42
  /** Snapshot of currently-running delegate runs, for the TUI status widget. */
6
43
  export declare function runningRunsSnapshot(): {
7
44
  runId: string;
@@ -36,6 +73,8 @@ export interface EventApplier {
36
73
  * never lost from the file. */
37
74
  export declare function makeEventApplier(opts: {
38
75
  showThinking: boolean;
76
+ onUsage?: (usage: Usage) => void;
77
+ onSettled?: () => void;
39
78
  }, writers: EventApplierWriters): EventApplier;
40
79
  declare const DelegateParams: Type.TObject<{
41
80
  agent: Type.TString;
@@ -53,6 +92,7 @@ declare const WaitParams: Type.TObject<{
53
92
  runId: Type.TString;
54
93
  timeout: Type.TOptional<Type.TInteger>;
55
94
  }>;
95
+ export declare function accumulateUsage(a: Usage | undefined, b: Usage): Usage;
56
96
  export declare function makeDelegateTool(pi: ExtensionAPI): ToolDefinition<typeof DelegateParams>;
57
97
  /** If the delegate already delivered its result via a system notification
58
98
  * (the close handler injected before this wait was called), return a short
@@ -66,6 +106,25 @@ export declare function injectedWaitMessage(run: {
66
106
  file: string;
67
107
  };
68
108
  }, runId: string, remainingLine: string): string | null;
109
+ /** Build usage-aware return payload. Sets usageReported=true so subsequent
110
+ * waits on the same run skip usage. */
111
+ export declare function buildWaitResult(run: DelegateRun, content: string, mode?: "merged" | "separate", contentType?: "text"): {
112
+ details: undefined;
113
+ content: {
114
+ type: "text";
115
+ text: string;
116
+ }[];
117
+ usage?: AgentToolResult<unknown>["usage"];
118
+ };
119
+ /** Build usage-aware result for cancel tool. */
120
+ export declare function buildCancelResult(run: DelegateRun, content: string, mode?: "merged" | "separate"): {
121
+ details: undefined;
122
+ content: {
123
+ type: "text";
124
+ text: string;
125
+ }[];
126
+ usage?: AgentToolResult<unknown>["usage"];
127
+ };
69
128
  export declare function makeDelegateWaitTool(_pi: ExtensionAPI): ToolDefinition<typeof WaitParams>;
70
129
  export declare function makeDelegateCancelTool(_pi: ExtensionAPI): ToolDefinition<typeof CancelParams>;
71
130
  export declare function buildChildArgs(args: DelegateArgs, rolePrompt: string, ctx: ExtensionContext): Promise<{
@@ -74,4 +133,5 @@ export declare function buildChildArgs(args: DelegateArgs, rolePrompt: string, c
74
133
  isAsync: boolean;
75
134
  useJsonStream: boolean;
76
135
  }>;
136
+ export declare function injectResult(pi: ExtensionAPI, agent: string, runId: string, task: string, code: number | null, file: string, timedOut?: string, usage?: Usage, mode?: "merged" | "separate", usageAlreadyReported?: boolean): boolean;
77
137
  export {};
@@ -18,6 +18,17 @@ export interface WatchdogHandle {
18
18
  poke(): void;
19
19
  /** Stop all timers (call on finalize). */
20
20
  dispose(): void;
21
+ /**
22
+ * agent_settled has been received: the agent's full flow (prompt + continue
23
+ * loop + retries) is over and pi emits this exactly once in the finally of
24
+ * _runAgentPrompt, after which the process should exit within milliseconds.
25
+ * If it is still alive after graceMs, the process is stuck in teardown
26
+ * (e.g. a provider call not returning) — kill it via killByWatchdog. graceMs
27
+ * is symmetric with EOF_GRACE_MS (10s): normal exits are millisecond-level,
28
+ * so 10s only hits genuinely hung processes. Idempotent (no-op when already
29
+ * settled or a grace timer is pending); dispose() clears the timer.
30
+ */
31
+ settledGrace(graceMs: number, _killGraceMs: number, reason: string): void;
21
32
  }
22
33
  /**
23
34
  * Guarantees a hung child process gets killed. A stuck child holds its stdout
@@ -0,0 +1,8 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ /** Mirrors pi's footer.js formatTokens: lowercase k/M, thresholds <1000/<10000/<1e6/<1e7. */
3
+ export declare function formatCompactTokens(count: number): string;
4
+ export declare function initFooterStatus(ctx: ExtensionContext): void;
5
+ /** Refresh the footer delegate-usage line. Cheap: reads the accumulated total
6
+ * and no-ops when the rendered text is unchanged (called on a 500ms tick). */
7
+ export declare function updateFooterStatus(): void;
8
+ export declare function disposeFooterStatus(): void;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionFactory } from "@earendil-works/pi-coding-agent";
2
- import type { AdapterConfig } from "./config.js";
2
+ import { type AdapterConfig } from "./config.js";
3
3
  export declare function createAcpExtension(adapter?: AdapterConfig): ExtensionFactory;
4
4
  declare const _default: ExtensionFactory;
5
5
  export default _default;