@tea-agent/loop-agent 0.52.0-next.8 → 0.52.0

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 (83) hide show
  1. package/CHANGELOG.md +5 -71
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/shared/pi-context-pressure/compaction-policy.js +156 -150
  4. package/dist/shared/pi-context-pressure/extension.js +21 -14
  5. package/dist/shared/pi-context-pressure/index.js +1 -1
  6. package/dist/shared/pi-context-pressure/telemetry.js +10 -0
  7. package/dist/worker/console/chat/assistant-content.js +21 -3
  8. package/dist/worker/console/chat/compaction-errors.js +28 -2
  9. package/dist/worker/console/chat/context-insights.js +4 -4
  10. package/dist/worker/console/chat/context-usage.js +4 -1
  11. package/dist/worker/console/chat/contract-apply-receipt-store.js +37 -25
  12. package/dist/worker/console/chat/pi-runtime/extension-bindings.js +39 -0
  13. package/dist/worker/console/chat/pi-runtime.js +55 -119
  14. package/dist/worker/console/chat/routes.js +20 -0
  15. package/dist/worker/console/chat/turn-process.js +2 -0
  16. package/dist/worker/console/mutation-gate-receipt-store.js +38 -29
  17. package/dist/worker/console/pi-compaction-settings.js +72 -34
  18. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BeB0jyn_.js → abnfDiagram-N423BO3Z-CR1jj_rz.js} +1 -1
  19. package/dist/worker/console/static/assets/{arc-B4E8rogW.js → arc-CjxcQfEu.js} +1 -1
  20. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CuD5BPrV.js → architectureDiagram-T3A2C74G-D-3u2qFL.js} +1 -1
  21. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DOR4BrbY.js → blockDiagram-VBNYF7ZC-Bdr7gWVo.js} +1 -1
  22. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-GuWkFUBT.js → c4Diagram-5PPSVZJV-hQHNe5T3.js} +1 -1
  23. package/dist/worker/console/static/assets/channel-CBlJfald.js +1 -0
  24. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Bvp_6a1j.js → chunk-2GRJ4B5K-BEg_su6q.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-zgyCBGFw.js → chunk-2Q5K7J3B-DZnV6VTC.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bd7_XVhV.js → chunk-5RXB4S5H-Dg0LzAqO.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-CO5JbujI.js → chunk-5VM5RSS4-D2vqr52W.js} +1 -1
  28. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DPb24xsc.js → chunk-6Q2QTUOP-D8We_g6R.js} +1 -1
  29. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D4OKjlIA.js → chunk-GF5L2VYU-DbEU8drD.js} +1 -1
  30. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BdtF1gRX.js → chunk-JWPE2WC7-Boi8TJYN.js} +1 -1
  31. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-cSxCzmVA.js → chunk-KBJHAD2P-CjJmKa9f.js} +1 -1
  32. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-De4Oormb.js → chunk-RYQCIY6F-C-KV-ag7.js} +1 -1
  33. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CMIvrR5C.js → chunk-XXDRQBXY-DZlTonsZ.js} +1 -1
  34. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-mNUYCdDo.js +1 -0
  35. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-mNUYCdDo.js +1 -0
  36. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-9SmHPXIr.js → cose-bilkent-JH36ORCC-BIvFe3yn.js} +1 -1
  37. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-wl-77tI0.js → cynefinDiagram-MW4NZA55-BOBPfv8u.js} +1 -1
  38. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-yqj9yJJQ.js → dagre-VZM6K2ZE-BF54orLO.js} +1 -1
  39. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-D-rMYS98.js → diagram-7IWD3JNH-CxjAP2AP.js} +1 -1
  40. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CQFAofzl.js → diagram-B4RE2ZJO-BXYkuNGt.js} +1 -1
  41. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-CfUQmVKd.js → diagram-LBJQPF4R-DQTu-2Iy.js} +1 -1
  42. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BkK1xnZN.js → diagram-Q27KOJAE-DNURuIYc.js} +1 -1
  43. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BQQRT4QA.js → diagram-UB23O5K3-D69uANY8.js} +1 -1
  44. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR--rItMGHc.js → ebnfDiagram-BXEA7PRR-C658EcrV.js} +1 -1
  45. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-YO3gwIVo.js → erDiagram-JOGREHBK-BRccYtAl.js} +1 -1
  46. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-sVlorROr.js → flowDiagram-UKHOOZJN-DnIR4sLs.js} +1 -1
  47. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DRBbNi-x.js → ganttDiagram-PKOTCBZU-Bo3eWFVC.js} +1 -1
  48. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-D0VaAfPP.js → gitGraphDiagram-DS77QQ5N-EyWDCNU_.js} +1 -1
  49. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DtHpfgsg.js → infoDiagram-6WML65LV-B0Eld9u0.js} +1 -1
  50. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Ea8r9FLd.js → ishikawaDiagram-WSZJBQD7-DsJQiJ27.js} +1 -1
  51. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CVJVcKLc.js → journeyDiagram-NVQOT4AX-fpE0yqjC.js} +1 -1
  52. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CUdymoGj.js → kanban-definition-27J2QSJJ-Dq9IrDdT.js} +1 -1
  53. package/dist/worker/console/static/assets/{linear-D5880Sph.js → linear-CFV4BDyf.js} +1 -1
  54. package/dist/worker/console/static/assets/main-D-ZQ4gLb.css +1 -0
  55. package/dist/worker/console/static/assets/{main-2IXI34Fw.js → main-Dwhb3ZRq.js} +126 -126
  56. package/dist/worker/console/static/assets/{mermaid.core-D6dkYx5V.js → mermaid.core-BMMXqtrB.js} +4 -4
  57. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-DhZljSlQ.js → mindmap-definition-FAOFIHXS-DurrK_Gi.js} +1 -1
  58. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-2S30TPom.js → pegDiagram-VL7TDLO6-CzZayNy2.js} +1 -1
  59. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-B9y_krb1.js → pieDiagram-7S7Q4E2Y-B1W7Y0cE.js} +1 -1
  60. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-C-XgJLT_.js → quadrantDiagram-CIZ2JOQS-BdbL83CU.js} +1 -1
  61. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CTeVrhCo.js → railroadDiagram-AXF67PYL-W-bQpd18.js} +1 -1
  62. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-B7K6JWmy.js → requirementDiagram-LRYGKXZP-C9bi4tQJ.js} +1 -1
  63. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-QAlLfn7A.js → sankeyDiagram-W5VNT64P-D4kO56Wd.js} +1 -1
  64. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BdWZWKdx.js → sequenceDiagram-SI44F4Z6-CIbesK1e.js} +1 -1
  65. package/dist/worker/console/static/assets/{sheet-workbook-BoC0pAy2.js → sheet-workbook-kFN3yUBr.js} +1 -1
  66. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-D6ASD67I.js → sizeCapture-X5ZJPWSS-Dk4XAK7C.js} +1 -1
  67. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-C3MgmUi2.js → stateDiagram-OKZ733FA-Bz9B6UZ7.js} +1 -1
  68. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BBRlxIq8.js +1 -0
  69. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-Dqrd-WNB.js → swimlanes-SLNWSIFB-qLEds93n.js} +2 -2
  70. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CRBvOMCQ.js +8 -0
  71. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-lQftYLJh.js → timeline-definition-Z64GVDOM-C9rVFC0h.js} +1 -1
  72. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-WA2DaCGk.js → vennDiagram-T6HMQDX7-CoKJ9hU0.js} +1 -1
  73. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-CFpLw8Jh.js → wardleyDiagram-T6FBY63Y-tHz_S7-L.js} +1 -1
  74. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-zgM9I8sM.js → xychartDiagram-ELKLHX3M-DKzKYnvG.js} +1 -1
  75. package/dist/worker/console/static/index.html +2 -2
  76. package/dist/worker/console/static-src/operator-chat/format-file-size.js +26 -0
  77. package/package.json +3 -3
  78. package/dist/worker/console/static/assets/channel-DFwPpXxz.js +0 -1
  79. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9pWfL1L.js +0 -1
  80. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9pWfL1L.js +0 -1
  81. package/dist/worker/console/static/assets/main-Ckf7id9T.css +0 -1
  82. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BEwsMVdO.js +0 -1
  83. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-D9l9u9WV.js +0 -8
@@ -12,6 +12,20 @@ export function classifyChatCompactionFailure(error) {
12
12
  raw,
13
13
  };
14
14
  }
15
+ if (raw === "COMPACTION_IN_PROGRESS") {
16
+ /*
17
+ * Distinct from a busy turn: a compaction is already running, and
18
+ * starting another would abort the one in flight (Pi's `compact()`
19
+ * begins with `await abort()`), which surfaces as 「上下文压缩已取消」
20
+ * for a compaction the reader never cancelled.
21
+ */
22
+ return {
23
+ status: 409,
24
+ code: "COMPACTION_IN_PROGRESS",
25
+ message: "上下文正在压缩中,请等待本次压缩完成。",
26
+ raw,
27
+ };
28
+ }
15
29
  if (raw === "COMPACTION_UNSUPPORTED") {
16
30
  return {
17
31
  status: 501,
@@ -53,12 +67,24 @@ export function classifyChatCompactionFailure(error) {
53
67
  };
54
68
  }
55
69
  if (/chat session not found/i.test(raw)) {
56
- return { status: 404, code: "NOT_FOUND", message: raw, raw };
70
+ return {
71
+ status: 404,
72
+ code: "NOT_FOUND",
73
+ message: "对话不存在或已被移除。",
74
+ raw,
75
+ };
57
76
  }
77
+ /*
78
+ * Never pass the raw provider text through as the user-facing message.
79
+ *
80
+ * `raw` is kept for local diagnosis, but it can contain API keys, bearer
81
+ * tokens and absolute paths from provider errors. The default branch used to
82
+ * return `raw` verbatim, which surfaced all of that in the UI.
83
+ */
58
84
  return {
59
85
  status: 409,
60
86
  code: "COMPACTION_FAILED",
61
- message: raw.trim() || "上下文压缩失败",
87
+ message: "上下文压缩失败",
62
88
  raw,
63
89
  };
64
90
  }
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import { conservativeTokenEstimate } from "../../../shared/pi-context-pressure/compaction-policy.js";
21
21
  import { readPruneAccounting, reclaimedAmount, } from "./context-accounting.js";
22
+ import { formatCacheHitPercent } from "./session-stats.js";
22
23
  /** Fixed-density token estimate for preview text (chars → tokens). */
23
24
  export function estimateTokensFromText(text) {
24
25
  if (!text)
@@ -747,10 +748,9 @@ export function deriveContextInsights(events, options = {}) {
747
748
  composition.headroom = Math.max(0, contextWindow - composition.totalTokens);
748
749
  }
749
750
  const billed = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
750
- usage.cacheHitPercent =
751
- billed > 0
752
- ? Math.round((usage.cacheReadTokens / billed) * 1000) / 10
753
- : null;
751
+ // Same formatter as the turn pills: a partial hit must not round up to 100%.
752
+ const cacheHitText = billed > 0 ? formatCacheHitPercent(usage.cacheReadTokens, billed) : null;
753
+ usage.cacheHitPercent = cacheHitText === null ? null : Number(cacheHitText);
754
754
  usage.turns = turnIds.length;
755
755
  if (usage.totalTokens === 0 && billed + usage.outputTokens > 0) {
756
756
  usage.totalTokens = billed + usage.outputTokens;
@@ -47,7 +47,10 @@ export function deriveChatContextUsage(events) {
47
47
  beforeAssistant.set(event.turnId, surface);
48
48
  const blocks = parseAssistantContent(data.content);
49
49
  const price = blocks?.length
50
- ? 4 + blocks.reduce((total, block) => total + 4 + tokensForText(block.type === "text" ? block.text : block.type === "thinking" ? block.thinking : block.toolName), 0)
50
+ ? 4 + blocks.reduce((total, block) => total + 4 + tokensForText(block.type === "text" ? block.text
51
+ : block.type === "thinking" ? block.thinking
52
+ : block.type === "toolCall" ? block.toolName
53
+ : ""), 0)
51
54
  : 8 + tokensForText(data.text);
52
55
  append(event.seq, price);
53
56
  }
@@ -5,6 +5,8 @@
5
5
  */
6
6
  import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
7
7
  import path from "node:path";
8
+ /** 并发 CAS 争用预算:等持锁方完成 read→rename,而不是把「仍在写」判成非法状态。 */
9
+ const CAS_CONTENTION_BUDGET_MS = 2_000;
8
10
  export class ContractApplyReceiptStore {
9
11
  dir;
10
12
  constructor(appData) {
@@ -140,35 +142,45 @@ export class ContractApplyReceiptStore {
140
142
  await mkdir(this.dir, { recursive: true, mode: 0o700 });
141
143
  const target = this.file(id);
142
144
  const lockPath = `${target}.lock`;
143
- try {
144
- await writeFile(lockPath, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
145
- }
146
- catch (error) {
147
- if (error.code === "EEXIST") {
148
- await new Promise((r) => setTimeout(r, 25));
149
- return { ok: false, current: await this.get(id) };
145
+ // 争用方必须等持锁方的写入落地后再判定;单次旁路读在慢 I/O(CI、并发 console)
146
+ // 下可能仍看到 prepared,把一次正常的并发输掉误判成 INVALID_STATE。
147
+ const deadline = Date.now() + CAS_CONTENTION_BUDGET_MS;
148
+ for (;;) {
149
+ let locked = true;
150
+ try {
151
+ await writeFile(lockPath, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
150
152
  }
151
- throw error;
152
- }
153
- try {
154
- const current = await this.get(id);
155
- if (!current || current.state !== expectedState) {
156
- return { ok: false, current };
153
+ catch (error) {
154
+ if (error.code !== "EEXIST")
155
+ throw error;
156
+ locked = false;
157
157
  }
158
- const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
159
- await writeFile(tmp, `${JSON.stringify(next, null, 2)}\n`, {
160
- mode: 0o600,
161
- });
162
- await rename(tmp, target);
163
- return { ok: true };
164
- }
165
- finally {
166
- try {
167
- await unlink(lockPath);
158
+ if (locked) {
159
+ try {
160
+ const current = await this.get(id);
161
+ if (!current || current.state !== expectedState) {
162
+ return { ok: false, current };
163
+ }
164
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
165
+ await writeFile(tmp, `${JSON.stringify(next, null, 2)}\n`, {
166
+ mode: 0o600,
167
+ });
168
+ await rename(tmp, target);
169
+ return { ok: true };
170
+ }
171
+ finally {
172
+ try {
173
+ await unlink(lockPath);
174
+ }
175
+ catch {
176
+ // lock cleanup is best-effort
177
+ }
178
+ }
168
179
  }
169
- catch {
170
- // lock cleanup is best-effort
180
+ if (Date.now() >= deadline) {
181
+ return { ok: false, current: await this.get(id) };
171
182
  }
183
+ await new Promise((r) => setTimeout(r, 10));
172
184
  }
173
185
  }
174
186
  }
@@ -1,3 +1,32 @@
1
+ /**
2
+ * Headless stand-in for the terminal theme singleton.
3
+ *
4
+ * The Console has no TUI, so extensions cannot receive real ANSI styling. Returning the text
5
+ * unchanged keeps extension status/widget strings readable instead of failing: the SDK contract
6
+ * declares `ctx.ui.theme` as required, and any extension reading `ctx.ui.theme.fg(...)` would
7
+ * otherwise throw on every lifecycle event. The real singleton is deliberately not used — it is
8
+ * not exported from the package root, and the internal one throws "Theme not initialized."
9
+ * until `initTheme()` runs, which only happens in the top-level CLI entry (`main.js`).
10
+ */
11
+ function createHeadlessExtensionTheme() {
12
+ const passthrough = (text) => text;
13
+ return {
14
+ appearance: "dark",
15
+ colors: {},
16
+ style: (text, _options) => text,
17
+ fg: (_color, text) => text,
18
+ bg: (_color, text) => text,
19
+ bold: passthrough,
20
+ italic: passthrough,
21
+ underline: passthrough,
22
+ inverse: passthrough,
23
+ strikethrough: passthrough,
24
+ getFgAnsi: (_color) => "",
25
+ getBgAnsi: (_color) => "",
26
+ getColorMode: () => "truecolor",
27
+ getThinkingBorderColor: () => passthrough,
28
+ };
29
+ }
1
30
  const toolPolicies = new WeakMap();
2
31
  /** Selection controls declarations; this policy also gates deferred/nested calls. */
3
32
  export function setSessionToolPolicy(session, allowed) {
@@ -57,6 +86,8 @@ export function disposeSessionExtensions(session) {
57
86
  return close;
58
87
  }
59
88
  function createConsoleExtensionBindings(session) {
89
+ // The headless theme is stateless, so one per bindings object is enough.
90
+ const headlessTheme = createHeadlessExtensionTheme();
60
91
  return {
61
92
  mode: "rpc",
62
93
  onError: (error) => {
@@ -96,6 +127,14 @@ function createConsoleExtensionBindings(session) {
96
127
  addAutocompleteProvider: () => undefined,
97
128
  setEditorComponent: () => undefined,
98
129
  getEditorComponent: () => undefined,
130
+ // Required by the SDK contract; absent members make extensions crash on
131
+ // `ctx.ui.theme.fg(...)` instead of degrading to unstyled output.
132
+ theme: headlessTheme,
133
+ getAllThemes: () => [],
134
+ getTheme: () => undefined,
135
+ setTheme: () => ({ success: false, error: "Theme switching not supported in Console mode" }),
136
+ getToolsExpanded: () => false,
137
+ setToolsExpanded: () => undefined,
99
138
  },
100
139
  };
101
140
  }
@@ -51,12 +51,11 @@ import { applySkillAutoInvocationPreferences, loadResourcePreferences, } from ".
51
51
  import { buildPiModeLoopIsolationOptions } from "./pi-mode-loop-isolation.js";
52
52
  import { applyWorkflowIntakeSkillAuthority, resolveWorkflowIntakeCapability, verifyWorkflowIntakeSkillInventory, workflowIntakeMaterializationFailure, } from "./workflow-intake-skills.js";
53
53
  import { applyProcessRetryOverride, } from "../../../shared/pi-retry-settings.js";
54
- import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parsePiToolResultPruneConfig, parseSiftBridgeConfig, projectPromptPressure, deriveEffectiveWindow, projectSafeTelemetry, isContextOverflow, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
54
+ import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parsePiToolResultPruneConfig, parseSiftBridgeConfig, projectSafeTelemetry, isContextOverflow, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
55
55
  import { incrementCounter as incrementPressureCounter } from "../../../shared/pi-context-pressure/telemetry.js";
56
56
  import { resolveDefaultChatModel, resolveLowChatModel, } from "./model-resolver.js";
57
57
  import { filterActiveInterviewTools } from "../interview/tools.js";
58
58
  import { redactRuntimeText } from "./runtime-context.js";
59
- import { classifyChatCompactionFailure } from "./compaction-errors.js";
60
59
  import { BrowserAutomationService } from "./browser-automation.js";
61
60
  import { buildTodoContinuationContext, } from "./todos.js";
62
61
  import { buildPersistentTerminalTools } from "./terminal-tools.js";
@@ -482,7 +481,7 @@ export class PiSessionInitFailedError extends Error {
482
481
  /**
483
482
  * Merge saved user preferences into a parsed policy.
484
483
  *
485
- * Only the two deployment-shaped knobs are overridable here; everything else
484
+ * Only the three policy-shaped knobs are overridable here; everything else
486
485
  * stays with the environment parser so there is a single source for each
487
486
  * decision. The environment still wins inside `resolveCompactionSettings`.
488
487
  */
@@ -492,12 +491,15 @@ function withUserCompactionSettings(policy, settings) {
492
491
  const resolved = resolveCompactionSettings({ saved: settings });
493
492
  return {
494
493
  ...policy,
495
- ...(resolved.gatewayInputLimitTokens === undefined
494
+ ...(resolved.thresholdRatio === undefined
496
495
  ? {}
497
- : { gatewayInputLimitTokens: resolved.gatewayInputLimitTokens }),
498
- ...(resolved.keepRecentTokens === undefined
496
+ : { thresholdRatio: resolved.thresholdRatio }),
497
+ ...(resolved.headroomTokens === undefined
499
498
  ? {}
500
- : { keepRecentTokens: resolved.keepRecentTokens }),
499
+ : { headroomTokens: resolved.headroomTokens }),
500
+ ...(resolved.retainRatio === undefined
501
+ ? {}
502
+ : { retainRatio: resolved.retainRatio }),
501
503
  };
502
504
  }
503
505
  async function readModelConfigFileVersion(filePath) {
@@ -914,22 +916,13 @@ export class ConsolePiRuntime {
914
916
  const reportedWindow = session?.getSessionStats?.()?.contextUsage?.contextWindow;
915
917
  const declaredWindow = this.piDeclaredWindow(session, reportedWindow);
916
918
  applyProcessCompactionOverride(manager, {
917
- // User-scoped gateway limit / retained tail, when the operator saved
918
- // one in 模型与认证. Environment variables still win inside
919
+ // User-scoped ratio / headroom / retain, when the operator saved them
920
+ // in 设置 → 模型. Environment variables still win inside
919
921
  // resolveCompactionSettings.
920
922
  policy: withUserCompactionSettings(parseCompactionPolicy(), userSettings),
921
923
  ...(typeof declaredWindow === "number"
922
- ? {
923
- contextWindow: declaredWindow,
924
- declaredContextWindow: declaredWindow,
925
- }
924
+ ? { contextWindow: declaredWindow }
926
925
  : {}),
927
- // NOTE: no explicit keepRecentTokens here on purpose. Forcing 0 made
928
- // `messagesToSummarize` span the whole branch, so the summary request
929
- // re-sent the history the gateway had just rejected and failed too.
930
- // The policy derives a bounded tail from the trigger line (see
931
- // resolveKeepRecentTokens); saved settings or
932
- // HARNESS_COMPACTION_KEEP_RECENT_TOKENS override that split.
933
926
  });
934
927
  void sessionId;
935
928
  }
@@ -976,105 +969,6 @@ export class ConsolePiRuntime {
976
969
  }
977
970
  return DEFAULT_CONTEXT_WINDOW;
978
971
  }
979
- async runPrePromptCompaction(sessionId, session, promptText, imageCount, onEvent, signal) {
980
- if (signal?.aborted)
981
- return;
982
- const parsed = parseCompactionPolicy();
983
- if (parsed.mode === "off")
984
- return;
985
- // The saved preferences must reach this check too: the operator sets the
986
- // gateway limit here, and evaluating it only when writing Pi's settings
987
- // left the pre-prompt gate on the declared window.
988
- const policy = withUserCompactionSettings(parsed, await this.loadUserCompactionSettings());
989
- const controller = this.getCompactionController(sessionId);
990
- const stats = session.getSessionStats?.();
991
- const reportedWindow = stats?.contextUsage?.contextWindow;
992
- const tokens = stats?.contextUsage?.tokens;
993
- const window = this.resolveContextWindow(session, reportedWindow);
994
- // Keep Pi's own threshold on the same line as this gate. The settings
995
- // write is idempotent, so repeating it here costs nothing and guarantees
996
- // the two thresholds agree even when the window changed mid-session.
997
- if (typeof window === "number" && window > 0) {
998
- this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session, await this.loadUserCompactionSettings());
999
- }
1000
- const projection = projectPromptPressure({
1001
- currentContextTokens: tokens,
1002
- promptText,
1003
- imageCount,
1004
- });
1005
- if (projection.usageUnavailable) {
1006
- incrementPressureCounter(controller.counters, "usage-unavailable");
1007
- return;
1008
- }
1009
- const effective = deriveEffectiveWindow(window, policy);
1010
- if (projection.projected < effective.triggerTokens) {
1011
- controller.pruneArmed = false;
1012
- return;
1013
- }
1014
- controller.pruneArmed = true;
1015
- if (typeof session.compact !== "function")
1016
- return;
1017
- const compactionId = newCompactionId(sessionId);
1018
- onEvent({
1019
- type: "compaction_start",
1020
- sessionId,
1021
- compactionId,
1022
- reason: "threshold",
1023
- });
1024
- controller.proactiveCompaction = true;
1025
- try {
1026
- signal?.throwIfAborted();
1027
- incrementPressureCounter(controller.counters, "pre-prompt-threshold");
1028
- const result = await this.compactWithOverflowFallback(sessionId, session, undefined, signal);
1029
- const snapshot = projectCompactSnapshot(result ?? {});
1030
- onEvent({
1031
- type: "compaction_end",
1032
- sessionId,
1033
- compactionId,
1034
- reason: "threshold",
1035
- status: signal?.aborted ? "aborted" : "completed",
1036
- willRetry: false,
1037
- summary: snapshot.summary,
1038
- ...(snapshot.firstKeptEntryId
1039
- ? { firstKeptEntryId: snapshot.firstKeptEntryId }
1040
- : {}),
1041
- ...(snapshot.tokensBefore === undefined
1042
- ? {}
1043
- : { tokensBefore: snapshot.tokensBefore }),
1044
- ...(snapshot.accounting ? {
1045
- shadowedTokenCount: snapshot.accounting.shadowedTokenCount,
1046
- replacementTokenCount: snapshot.accounting.replacementTokenCount,
1047
- netTokensFreed: snapshot.accounting.netTokensFreed,
1048
- accounting: snapshot.accounting.accounting,
1049
- shrinkProof: snapshot.accounting.shrinkProof,
1050
- } : {}),
1051
- });
1052
- }
1053
- catch (error) {
1054
- if (!signal?.aborted)
1055
- incrementPressureCounter(controller.counters, "l0-compact-failed");
1056
- const classified = classifyChatCompactionFailure(error);
1057
- onEvent({
1058
- type: "compaction_end",
1059
- sessionId,
1060
- compactionId,
1061
- reason: "threshold",
1062
- status: signal?.aborted ? "aborted" : "failed",
1063
- willRetry: false,
1064
- ...(signal?.aborted
1065
- ? {}
1066
- : {
1067
- code: classified.code,
1068
- errorMessage: classified.code === "COMPACTION_FAILED"
1069
- ? "上下文压缩失败"
1070
- : redactRuntimeText(classified.message, 600),
1071
- }),
1072
- });
1073
- }
1074
- finally {
1075
- controller.proactiveCompaction = false;
1076
- }
1077
- }
1078
972
  /**
1079
973
  * Resolve a skill in the current session inventory by server-issued resourceId.
1080
974
  * Returns undefined when the id is unknown (caller maps to PI_SKILL_NOT_FOUND).
@@ -3166,6 +3060,16 @@ export class ConsolePiRuntime {
3166
3060
  if (options?.signal?.aborted) {
3167
3061
  return;
3168
3062
  }
3063
+ /*
3064
+ * Re-read the compaction preferences before every turn.
3065
+ *
3066
+ * The saved file is the source of truth and reading it is cheap, so a
3067
+ * change made in 设置 → 模型 applies to the NEXT turn instead of only to
3068
+ * sessions created afterwards. Without this, saving a corrected headroom
3069
+ * did nothing until the user happened to open a new session — the
3070
+ * setting looked ignored.
3071
+ */
3072
+ this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session, await this.loadUserCompactionSettings());
3169
3073
  let promptImages = options?.images;
3170
3074
  if ((options?.referenceImageCount ?? 0) > 0 && !session.model?.input?.includes("image")) {
3171
3075
  promptImages = promptImages?.slice(0, Math.max(0, promptImages.length - options.referenceImageCount));
@@ -3203,7 +3107,17 @@ export class ConsolePiRuntime {
3203
3107
  return;
3204
3108
  }
3205
3109
  emitContextUsage();
3206
- await this.runPrePromptCompaction(sessionId, session, text, promptImages?.length ?? 0, onEvent, options?.signal);
3110
+ /*
3111
+ * No pre-prompt compaction here.
3112
+ *
3113
+ * Pi checks the threshold before EVERY provider request
3114
+ * (`_compactBeforeNextAssistantResponse`, driven by
3115
+ * `prepareNextTurnWithContext`), and its `reserveTokens` is set from
3116
+ * the resolved spec in `applySessionRecoveryOverrides`. A second gate
3117
+ * here would have to agree with Pi's forever, and it only ever ran on
3118
+ * user input — so it could never cover an agentic loop. One threshold,
3119
+ * owned by Pi, is the whole point of the DSH-aligned policy.
3120
+ */
3207
3121
  if (options?.signal?.aborted)
3208
3122
  return;
3209
3123
  let step = 0;
@@ -3705,11 +3619,33 @@ export class ConsolePiRuntime {
3705
3619
  const session = this.sessions.get(sessionId);
3706
3620
  if (!session)
3707
3621
  throw new Error(`chat session not found: ${sessionId}`);
3622
+ /*
3623
+ * `isIdle` is false while compaction is running too, so this already
3624
+ * refuses a manual request that would collide with one.
3625
+ *
3626
+ * The reason it matters: Pi's `compact()` begins with `await abort()`,
3627
+ * which calls `abortCompaction()` and kills any automatic compaction
3628
+ * already in flight. The victim then throws "Compaction cancelled", and
3629
+ * the reader sees 「上下文压缩已取消」 for a compaction they never
3630
+ * started or cancelled. Refusing up front keeps the running one alive.
3631
+ */
3632
+ if (session.isCompacting === true) {
3633
+ throw new Error("COMPACTION_IN_PROGRESS");
3634
+ }
3708
3635
  if (session.isStreaming === true || session.isIdle === false)
3709
3636
  throw new Error("CHAT_TURN_ACTIVE");
3710
3637
  if (typeof session.compact !== "function")
3711
3638
  throw new Error("COMPACTION_UNSUPPORTED");
3712
3639
  incrementPressureCounter(this.getCompactionController(sessionId).counters, "manual");
3640
+ /*
3641
+ * Manual compaction runs exactly once.
3642
+ *
3643
+ * DSH's `compactionRetries` exists to keep an automatic turn under the
3644
+ * pressure threshold. Pi runs its own automatic compaction inside the SDK
3645
+ * and exposes no post-pass hook, so that retry is NOT implemented here —
3646
+ * see the design doc's "未实现" section. A user who asked for one
3647
+ * compaction gets one.
3648
+ */
3713
3649
  const result = await this.compactWithOverflowFallback(sessionId, session, customInstructions);
3714
3650
  return projectCompactSnapshot(result ?? {});
3715
3651
  }
@@ -3882,6 +3882,26 @@ async function handleChatFiles(res, deps, sessionId, query) {
3882
3882
  sendJson(res, 200, { ok: true, files });
3883
3883
  }
3884
3884
  export async function handleChatCommands(res, deps, sessionId) {
3885
+ /*
3886
+ * A durable session is not necessarily resident: after a Console restart,
3887
+ * or for a conversation reopened from history, the Pi runtime holds no live
3888
+ * session for it until something reopens it. `listSlashCommands` needs the
3889
+ * live session, so it used to fail with "chat session not found" while the
3890
+ * transcript and the session list looked perfectly healthy — the reader had
3891
+ * to run /reload to see their commands again.
3892
+ *
3893
+ * Reopen silently here, before listing: the durable record is the source of
3894
+ * truth for how to reopen, and the caller only asked for the command list.
3895
+ */
3896
+ if (typeof deps.runtime.hasSession === "function" &&
3897
+ !deps.runtime.hasSession(sessionId)) {
3898
+ const record = await deps.store.get(sessionId).catch(() => undefined);
3899
+ if (record) {
3900
+ await deps.runtime
3901
+ .reopenSession(reopenInitFromRecord(record))
3902
+ .catch(() => ({ ok: false }));
3903
+ }
3904
+ }
3885
3905
  try {
3886
3906
  const listed = typeof deps.runtime.listSlashCommands === "function"
3887
3907
  ? await deps.runtime.listSlashCommands(sessionId)
@@ -398,6 +398,8 @@ function fillProcessDetails(group) {
398
398
  }
399
399
  continue;
400
400
  }
401
+ if (block.type !== "toolCall")
402
+ continue;
401
403
  const tool = group.tools.find((entry) => entry.id === block.toolCallId);
402
404
  if (!tool || usedToolIds.has(tool.id))
403
405
  continue;
@@ -4,8 +4,10 @@
4
4
  * semantics with an atomic prepared → dispatching → dispatched state machine
5
5
  * so concurrent confirm POSTs cannot create duplicate operations.
6
6
  */
7
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
7
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
8
8
  import path from "node:path";
9
+ /** 并发 CAS 争用预算:等持锁方完成 read→rename,而不是把「仍在写」判成非法状态。 */
10
+ const CAS_CONTENTION_BUDGET_MS = 2_000;
9
11
  export class MutationGateReceiptStore {
10
12
  dir;
11
13
  constructor(appData) {
@@ -147,38 +149,45 @@ export class MutationGateReceiptStore {
147
149
  await mkdir(this.dir, { recursive: true, mode: 0o700 });
148
150
  const target = this.file(id);
149
151
  const lockPath = `${target}.lock`;
150
- try {
151
- await writeFile(lockPath, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
152
- }
153
- catch (error) {
154
- if (error.code === "EEXIST") {
155
- // Brief spin for the other writer; then re-read.
156
- await new Promise((r) => setTimeout(r, 25));
157
- return { ok: false, current: await this.get(id) };
152
+ // 与 contract-apply 同源:争用方要等持锁方的写入落地,单次旁路读会在慢 I/O
153
+ // 下仍看到 prepared,把并发输掉误判成 INVALID_STATE。
154
+ const deadline = Date.now() + CAS_CONTENTION_BUDGET_MS;
155
+ for (;;) {
156
+ let locked = true;
157
+ try {
158
+ await writeFile(lockPath, `${process.pid}\n`, { flag: "wx", mode: 0o600 });
158
159
  }
159
- throw error;
160
- }
161
- try {
162
- const current = await this.get(id);
163
- if (!current || current.state !== expectedState) {
164
- return { ok: false, current };
160
+ catch (error) {
161
+ if (error.code !== "EEXIST")
162
+ throw error;
163
+ locked = false;
165
164
  }
166
- const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
167
- await writeFile(tmp, `${JSON.stringify(next, null, 2)}\n`, {
168
- mode: 0o600,
169
- });
170
- await rename(tmp, target);
171
- return { ok: true };
172
- }
173
- finally {
174
- try {
175
- await writeFile(lockPath, "", { flag: "w" });
176
- const { unlink } = await import("node:fs/promises");
177
- await unlink(lockPath);
165
+ if (locked) {
166
+ try {
167
+ const current = await this.get(id);
168
+ if (!current || current.state !== expectedState) {
169
+ return { ok: false, current };
170
+ }
171
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
172
+ await writeFile(tmp, `${JSON.stringify(next, null, 2)}\n`, {
173
+ mode: 0o600,
174
+ });
175
+ await rename(tmp, target);
176
+ return { ok: true };
177
+ }
178
+ finally {
179
+ try {
180
+ await unlink(lockPath);
181
+ }
182
+ catch {
183
+ // lock cleanup is best-effort
184
+ }
185
+ }
178
186
  }
179
- catch {
180
- // lock cleanup is best-effort
187
+ if (Date.now() >= deadline) {
188
+ return { ok: false, current: await this.get(id) };
181
189
  }
190
+ await new Promise((r) => setTimeout(r, 10));
182
191
  }
183
192
  }
184
193
  }