Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tests/fixtures/** -text
61 changes: 61 additions & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,67 @@ The `prompts` object overrides acp-kernel's **load-bearing** compression prompt
- **Status:** 🟢 ACTIVE
- **Description:** The safety gate for `prompts` overrides. Set to `true` to acknowledge that replacing the kernel's tuned compression rules may reduce summary quality, and to make your `prompts` overrides take effect. When `false` (or omitted), all `prompts` overrides are ignored and the kernel defaults are used. If `resolvePrompts` rejects your override (for example a malformed value that still passes the type check), the extension falls back to the defaults and logs a `prompts-resolve-failed` warning rather than failing to start.

### `promptSections`

- **Type:** `object` (partial — per-section tri-state)
- **Default:** *(built-in defaults)*
- **Status:** 🟢 ACTIVE
- **Description:** Override the **structural documentation sections** of the ACP system prompt — not the compression rules. Nine keys: `acpTags`, `summariesInContext`, `tools`, `whenToCompress`, `whenNotToCompress`, `multiTierIntro`, `decompressPhilosophy`, `contextBreakdown`, `throttleRetry`. Tri-state per key: a string **replaces** the section, `null` **removes** it entirely, omitting it keeps the default. Not risk-gated — these are docs, not tuned rules. The four load-bearing rule blocks (`compressPhilosophy` etc.) stay under the gated `prompts` key and cannot be set here. Example:

```json
{
"promptSections": {
"acpTags": "(custom explanation of the acp tags)",
"contextBreakdown": null
}
}
```

### `nudgeSections`

- **Type:** `object` (partial — per-key tri-state)
- **Default:** *(built-in defaults)*
- **Status:** 🟢 ACTIVE
- **Description:** Override the **guidance-class texts** of compression nudges. Four keys: `efficiencyNote` (gentle nudge preamble), `emergencyHeader` (emergency nudge preamble), `t2Guidance` (tier-2 distillation guidance), `t3Guidance` (tier-3 condensation guidance). Same tri-state semantics as `promptSections`. Not risk-gated. Trigger lines, renderer labels, and tool feedback text are contract-locked and cannot be overridden. Example:

```json
{
"nudgeSections": {
"efficiencyNote": "Keep the working set lean — fold consumed output early.",
"emergencyHeader": null
}
}
```

### `toolPrompts`

- **Type:** `object` (per-tool partial)
- **Default:** *(built-in defaults)*
- **Status:** 🟢 ACTIVE
- **Description:** Override the LLM-facing text of the four ACP tools. Keys: `compress`, `decompress`, `search_context`, `acp_status`. Each accepts `description` (string), `paramDescriptions` (object mapping parameter names to strings — rewrites the schema field descriptions), `promptSnippet` (string, shown in the "Available tools" system prompt section), and `promptGuidelines` (string or string[] — appended to the system prompt Guidelines section). Read **synchronously at extension load** (tool definitions are frozen at registration), so changes require restarting pi. Example:

```json
{
"toolPrompts": {
"compress": {
"promptSnippet": "compress({ content: [{ startId, endId, summary }] })",
"paramDescriptions": { "summary": "Short dense summary; paths + decisions verbatim." }
}
}
}
```

### `delegatePrompt`

- **Type:** `string | null`
- **Default:** *(built-in `ACP_DELEGATE_NOTIFICATIONS` appendix)*
- **Status:** 🟢 ACTIVE
- **Description:** Replace (`string`) or remove (`null`) the `ACP_DELEGATE_NOTIFICATIONS` appendix appended to the system prompt when the delegate tool is enabled. Useful for hosts that run their own delegate scheme with different semantics. Only applies when `delegate` is enabled. Example:

```json
{ "delegatePrompt": "Background task results arrive as system notifications — read the result file if relevant." }
```

---

## Environment Variables
Expand Down
65 changes: 65 additions & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@
|----|------|--------|------|------|
| `prompts` | object | *(内核默认)* | 🟢 ACTIVE | 覆盖 acp-kernel 的 4 条承重压缩提示词规则。每个设置的字段逐字替换默认值。 |
| `acknowledgePromptsRisk` | boolean | `false` | 🟢 ACTIVE | 必须为 `true`,`prompts` 覆盖才会生效;否则覆盖被丢弃、使用默认值。 |
| `promptSections` | object | *(内置默认)* | 🟢 ACTIVE | 覆盖 ACP 系统提示词的 9 个结构性文档段(三态:字符串=替换 / null=删除 / 省略=默认)。不经风险门禁。 |
| `nudgeSections` | object | *(内置默认)* | 🟢 ACTIVE | 覆盖压缩提示的 4 段引导类文本(efficiencyNote / emergencyHeader / t2Guidance / t3Guidance),同样三态。不经风险门禁。 |
| `toolPrompts` | object | *(内置默认)* | 🟢 ACTIVE | 覆盖四个 ACP 工具的 LLM 文案(description / paramDescriptions / promptSnippet / promptGuidelines)。扩展加载时同步读取,改后需重启 pi。 |
| `delegatePrompt` | string \| null | *(内置附录)* | 🟢 ACTIVE | 替换(string)或删除(null)delegate 启用时的 ACP_DELEGATE_NOTIFICATIONS 系统提示词附录。 |

**环境变量**

Expand Down Expand Up @@ -629,6 +633,67 @@ provider 的 key 是 **Pi provider 名**(如 `"anthropic"`、`"openai"`、`"zhip
}
```

### `promptSections`

- **类型:** `object`(部分覆盖——逐段三态)
- **默认值:** *(内置默认)*
- **状态:** 🟢 ACTIVE
- **说明:** 覆盖 ACP 系统提示词的**结构性文档段**,而非压缩规则。九个键:`acpTags`、`summariesInContext`、`tools`、`whenToCompress`、`whenNotToCompress`、`multiTierIntro`、`decompressPhilosophy`、`contextBreakdown`、`throttleRetry`。三态语义:字符串**替换**该段,`null` **删除**该段,省略则保持默认。不经风险门禁——这些是文档说明,不是调优规则。四条承重规则(`compressPhilosophy` 等)仍在门禁的 `prompts` 键下,不能在此设置。示例:

```json
{
"promptSections": {
"acpTags": "(自定义 acp 标签说明)",
"contextBreakdown": null
}
}
```

### `nudgeSections`

- **类型:** `object`(部分覆盖——逐键三态)
- **默认值:** *(内置默认)*
- **状态:** 🟢 ACTIVE
- **说明:** 覆盖压缩提示的**引导类文本**。四个键:`efficiencyNote`(温和提示开场)、`emergencyHeader`(紧急提示开场)、`t2Guidance`(T2 蒸馏引导)、`t3Guidance`(T3 凝缩引导)。与 `promptSections` 相同的三态语义。不经风险门禁。触发行、渲染器标签和工具反馈文本属于契约锁定,不可覆盖。示例:

```json
{
"nudgeSections": {
"efficiencyNote": "保持工作集精简——尽早折叠已消耗的输出。",
"emergencyHeader": null
}
}
```

### `toolPrompts`

- **类型:** `object`(逐工具部分覆盖)
- **默认值:** *(内置默认)*
- **状态:** 🟢 ACTIVE
- **说明:** 覆盖四个 ACP 工具面向 LLM 的文案。键:`compress`、`decompress`、`search_context`、`acp_status`。每项可设 `description`(字符串)、`paramDescriptions`(参数名→字符串的对象——重写 schema 字段描述)、`promptSnippet`(字符串,显示在系统提示词的“可用工具”段)、`promptGuidelines`(字符串或字符串数组——追加到系统提示词 Guidelines 段)。在**扩展加载时同步读取**(工具定义在注册时固化),修改后需重启 pi。示例:

```json
{
"toolPrompts": {
"compress": {
"promptSnippet": "compress({ content: [{ startId, endId, summary }] })",
"paramDescriptions": { "summary": "简短稠密摘要;路径+决策逐字保留。" }
}
}
}
```

### `delegatePrompt`

- **类型:** `string | null`
- **默认值:** *(内置 `ACP_DELEGATE_NOTIFICATIONS` 附录)*
- **状态:** 🟢 ACTIVE
- **说明:** 替换(`string`)或删除(`null`)delegate 工具启用时追加到系统提示词的 `ACP_DELEGATE_NOTIFICATIONS` 附录。适用于用自己的后台任务机制、语义不同的宿主。仅在 `delegate` 启用时生效。示例:

```json
{ "delegatePrompt": "后台任务结果以系统通知到达——如相关则读取结果文件。" }
```

### `acknowledgePromptsRisk`

- **类型:** `boolean`
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"@earendil-works/pi-coding-agent": "0.83.0",
"@earendil-works/pi-tui": "0.83.0",
"@types/node": "^26.1.2",
"acp-kernel": "0.0.64",
"acp-kernel": "0.0.65",
"tsup": "^8.5.1",
"tsx": "^4.23.1",
"typescript": "^7.0.2"
Expand Down
7 changes: 4 additions & 3 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { AcpRuntime } from "./runtime.js";
import { MAX_COMPRESS_ATTEMPTS } from "./runtime.js";
import { debug, logError, logInfo, logThrow, logWarn } from "./log.js";
import { estimateTokens, collectCoveredMessageIds, collectImageTokens, modelSupportsImages, adjustedTokenCount } from "./tokens.js";
import { applyToolPromptOverrides, type ToolPromptOverrides } from "./surface.js";
import { lastTurnBoundaryId } from "./turn-boundary.js";
import { resolveHostSession } from "./config.js";
import { defaultCountTokens, parseCompressArgs, viableRanges, formatRanges, type CompressionBlock, type CompressionState, type CompressParseDiagnostics, type NudgeDecision } from "acp-kernel";
Expand Down Expand Up @@ -43,8 +44,8 @@ const CompressParams = Type.Object({

type CompressArgs = Static<typeof CompressParams>;

export function makeCompressTool(runtime: AcpRuntime): ToolDefinition<typeof CompressParams> {
return {
export function makeCompressTool(runtime: AcpRuntime, overrides?: ToolPromptOverrides): ToolDefinition<typeof CompressParams> {
return applyToolPromptOverrides({
name: "compress",
label: "Compress",
description:
Expand All @@ -68,7 +69,7 @@ export function makeCompressTool(runtime: AcpRuntime): ToolDefinition<typeof Com
}
return { details: undefined, content: [{ type: "text", text: result }] };
},
};
}, overrides);
}

type RangeEntry = Static<typeof RangeSpec>;
Expand Down
17 changes: 17 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { defaultConfig, type Config, type Prompts } from "acp-kernel";
import type { CompressReasoningConfig } from "./reasoning-drop.js";
import type { DegenerationGuardConfig } from "./degeneration.js";
import type { ThrottleRetryConfig } from "./throttle-retry.js";
import type { PiPromptSections } from "./system-prompt.js";
import type { NudgeSectionsConfig, ToolPromptsConfig } from "./surface.js";
import { logWarn } from "./log.js";

/** Per-role delegate defaults. Lets long-lived automation pin a cheaper or
Expand Down Expand Up @@ -271,6 +273,21 @@ export interface AdapterConfig {
* replacing the kernel's tuned compression rules may reduce summary quality
* (lost paths/signatures/decisions → worse retrieval). */
acknowledgePromptsRisk?: boolean;
/** Override structural sections of the ACP system prompt (ACP TAGS, TOOLS,
* WHEN TO COMPRESS, ...). Tri-state per section: string = replace, null =
* remove, omitted = default. Not risk-gated — these are documentation
* sections, not compression rules. Set via acp.json. */
promptSections?: Partial<PiPromptSections>;
/** Override guidance-class nudge texts (efficiencyNote, emergencyHeader,
* t2Guidance, t3Guidance). Same tri-state semantics. Not risk-gated. */
nudgeSections?: NudgeSectionsConfig;
/** Override the four ACP tool definitions' LLM-facing text (description,
* paramDescriptions, promptSnippet, promptGuidelines). Read synchronously
* at extension load — tool defs are frozen at registration time. */
toolPrompts?: ToolPromptsConfig;
/** Replace (string) or remove (null) the ACP_DELEGATE_NOTIFICATIONS appendix
* injected when the delegate tool is enabled. */
delegatePrompt?: string | null;
coreOverrides?: Partial<Config>;
}

Expand Down
7 changes: 4 additions & 3 deletions src/decompress-tool.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Type, type Static } from "typebox";
import type { AgentToolResult, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
import type { AcpRuntime } from "./runtime.js";
import { applyToolPromptOverrides, type ToolPromptOverrides } from "./surface.js";
import { debug, logError, logInfo, logThrow } from "./log.js";
import { parseBlockIdArg, collectBlockContent, type CompressionBlock } from "acp-kernel";
import { entriesToCoreMessages } from "./messages.js";
Expand Down Expand Up @@ -31,8 +32,8 @@ const DecompressParams = Type.Object({

type DecompressArgs = Static<typeof DecompressParams>;

export function makeDecompressTool(runtime: AcpRuntime): ToolDefinition<typeof DecompressParams> {
return {
export function makeDecompressTool(runtime: AcpRuntime, overrides?: ToolPromptOverrides): ToolDefinition<typeof DecompressParams> {
return applyToolPromptOverrides({
name: "decompress",
label: "Decompress",
description:
Expand All @@ -56,7 +57,7 @@ export function makeDecompressTool(runtime: AcpRuntime): ToolDefinition<typeof D
}
return { details: undefined, content: [{ type: "text", text: result }] };
},
};
}, overrides);
}

/** Allowed roots for toFile paths. Keeps user-supplied paths from escaping to
Expand Down
26 changes: 15 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { makeSearchTool } from "./search-tool.js";
import { makeStatusTool } from "./status-tool.js";
import { makeDelegateTool, makeDelegateWaitTool, makeDelegateCancelTool, runningRunsSnapshot, resetDelegateUsage, setDelegateDisplayUsage, setDelegatePolicy, setDelegateDefaults, setDelegateNotifyIfRead, markDelegateResultRead, markDelegateRunReadByCommand } from "./delegate-tool.js";
import { makeCommands } from "./commands.js";
import { readToolSurfaceSync, type NudgeSectionsConfig } from "./surface.js";
import { coreOutToAgentMessages, extractText } from "./messages.js";
import { countThinkingChars, dropCompressReasoning } from "./reasoning-drop.js";
import { collapseAssistantDegeneration, degenerationNotice, lastAssistantRuns, resolveDegenerationGuard } from "./degeneration.js";
Expand Down Expand Up @@ -98,10 +99,11 @@ export function createAcpExtension(adapter: AdapterConfig = {}): ExtensionFactor
wireToolGuardrails(pi, runtime);
wireOverflowSelfHeal(pi, runtime);
wireThrottleRetry(pi, runtime);
pi.registerTool(makeCompressTool(runtime));
pi.registerTool(makeDecompressTool(runtime));
pi.registerTool(makeSearchTool(runtime));
pi.registerTool(makeStatusTool(runtime));
const toolSurface = readToolSurfaceSync(process.cwd());
pi.registerTool(makeCompressTool(runtime, toolSurface.compress));
pi.registerTool(makeDecompressTool(runtime, toolSurface.decompress));
pi.registerTool(makeSearchTool(runtime, toolSurface.search_context));
pi.registerTool(makeStatusTool(runtime, toolSurface.acp_status));
for (const { name, options } of makeCommands(runtime, pi)) {
pi.registerCommand(name, options);
}
Expand Down Expand Up @@ -414,7 +416,7 @@ function wireContextTransform(pi: ExtensionAPI, runtime: AcpRuntime, standDownIf
prunedMsgs: coreMessages.length - turn.messages.length + turn.messages.filter((m) => m.id.startsWith("acp_summary")).length,
nudgeShouldInject: turn.nudge?.shouldInject ?? false,
nudgeReason: turn.nudge?.reason ?? null,
nudgeVoice: turn.nudge ? renderNudgeText(turn.nudge, runtime.prompts).voice : null,
nudgeVoice: turn.nudge ? renderNudgeText(turn.nudge, runtime.prompts, runtime.adapter.nudgeSections).voice : null,
nudgePct: turn.nudge ? Math.round(turn.nudge.contextUsage * 100) : null,
nudgeTier: turn.nudge?.tier ?? null,
nudgeCompressibleCount: turn.nudge?.compressibleRanges.length ?? 0,
Expand Down Expand Up @@ -561,8 +563,8 @@ function wireContextTransform(pi: ExtensionAPI, runtime: AcpRuntime, standDownIf
const reInjectReady = shownAt === undefined || tokenCount - shownAt >= reInjectFloor;
const alreadyShown = retryCapped || (!emergency && runtime.nudgeShownFor(sid, turnKey) && !reInjectReady);
if (!alreadyShown) {
rebuilt.push(nudgeMessage(turn.nudge, turn.state.blocks.filter((b) => b.active), runtime.prompts));
const rendered = renderNudgeText(turn.nudge, runtime.prompts);
rebuilt.push(nudgeMessage(turn.nudge, turn.state.blocks.filter((b) => b.active), runtime.prompts, runtime.adapter.nudgeSections));
const rendered = renderNudgeText(turn.nudge, runtime.prompts, runtime.adapter.nudgeSections);
const top = [...turn.nudge.compressibleRanges].sort((a, b) => b.tokens - a.tokens)[0];
const example = top ? `\n\nExample: compress({ content: [{ startId: "${top.startRef}", endId: "${top.endRef}", summary: "..." }] })` : "";
if (emergency) {
Expand Down Expand Up @@ -615,8 +617,10 @@ function wireSystemPrompt(pi: ExtensionAPI, runtime: AcpRuntime): void {
// not learn about compress/decompress on a host where they can't work.
if (runtime.refused) return;
const delegate = resolveDelegate(runtime.adapter).enabled;
const acp = buildAcpSystemPrompt(runtime.prompts);
const prompt = delegate ? `${acp}\n${ACP_DELEGATE_PROMPT}` : acp;
const acp = buildAcpSystemPrompt(runtime.prompts, runtime.adapter.promptSections);
const delegateOverride = runtime.adapter.delegatePrompt;
const delegateText = delegateOverride !== undefined ? delegateOverride : ACP_DELEGATE_PROMPT;
const prompt = delegate && delegateText !== null ? `${acp}\n${delegateText}` : acp;
return { systemPrompt: formatSystemPromptForEvent(event.systemPrompt, prompt) };
});
}
Expand Down Expand Up @@ -767,8 +771,8 @@ function collectCompressOutcomes(entries: Array<{ type: string; id: string; mess
return out;
}

function nudgeMessage(nudge: NudgeDecision, blocks: CompressionBlock[], prompts: Prompts): AgentMessage {
const rendered = renderNudgeText(nudge, prompts);
function nudgeMessage(nudge: NudgeDecision, blocks: CompressionBlock[], prompts: Prompts, sections?: NudgeSectionsConfig): AgentMessage {
const rendered = renderNudgeText(nudge, prompts, sections);
const lines = [rendered.text];

if (blocks.length > 0) {
Expand Down
3 changes: 2 additions & 1 deletion src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { entriesToCoreMessages, extractText, matchesStoredText, messageIdentity,
import { SessionStateStore, deriveChildState, type LiveRefOrigin } from "./state.js";
import { hasCompressHistory, rebuildStateFromLog } from "./state-rebuild.js";
import { loadUserConfig, applyUserConfig } from "./user-config.js";
import { sanitizeSurfaceConfig } from "./surface.js";
import { ThrottleEpisode } from "./throttle-retry.js";
import { logInfo, logWarn, setDebugEnabled } from "./log.js";
import { findUniqueLongestRun, type MatchRange } from "./sequence-match.js";
Expand Down Expand Up @@ -471,7 +472,7 @@ export function createRuntime(adapter: AdapterConfig): AcpRuntime {
lastUserConfigKey = key;
// Re-derive from the factory config (not adapterRef) so a key REMOVED from
// acp.json actually reverts, instead of lingering from a prior apply.
adapterRef = applyUserConfig(factoryAdapter, user);
adapterRef = sanitizeSurfaceConfig(applyUserConfig(factoryAdapter, user));
if (adapterRef.debug !== undefined) setDebugEnabled(adapterRef.debug);
logInfo("runtime", { event: "config-reloaded", limit: adapterRef.modelContextLimit ?? null });
} catch (e) {
Expand Down
Loading
Loading