@tea-agent/loop-agent 0.52.0-next.9 → 0.53.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +36 -10
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/dag-pi/plan/finalize-tools.js +13 -0
  4. package/dist/executors/dag-pi/plan/record-tools.js +37 -11
  5. package/dist/executors/dag-pi/sessions/plan-batches.js +1 -1
  6. package/dist/executors/dag-pi/sessions/segmented-plan.js +28 -20
  7. package/dist/executors/dag-pi/tools/plan-decision-tools.js +2 -1
  8. package/dist/executors/dag-pi-executor.js +50 -5
  9. package/dist/executors/pi-executor.js +12 -0
  10. package/dist/executors/pi-sdk-executor.js +2 -2
  11. package/dist/shared/frontend-execution-policy.js +28 -2
  12. package/dist/shared/pi-context-pressure/compaction-policy.js +156 -150
  13. package/dist/shared/pi-context-pressure/extension.js +21 -14
  14. package/dist/shared/pi-context-pressure/index.js +1 -1
  15. package/dist/shared/pi-context-pressure/telemetry.js +10 -0
  16. package/dist/task/config-types.js +2 -2
  17. package/dist/task/source-prepare/prepare.js +1 -1
  18. package/dist/task/source-prepare/semantic-intake.js +2 -2
  19. package/dist/task/source-prepare/source-fidelity-pi.js +2 -1
  20. package/dist/worker/console/chat/assistant-content.js +21 -3
  21. package/dist/worker/console/chat/compaction-errors.js +28 -2
  22. package/dist/worker/console/chat/context-insights.js +4 -4
  23. package/dist/worker/console/chat/context-usage.js +4 -1
  24. package/dist/worker/console/chat/contract-apply-receipt-store.js +37 -25
  25. package/dist/worker/console/chat/pi-runtime.js +55 -119
  26. package/dist/worker/console/chat/routes.js +20 -0
  27. package/dist/worker/console/chat/turn-process.js +2 -0
  28. package/dist/worker/console/mutation-gate-receipt-store.js +38 -29
  29. package/dist/worker/console/pi-compaction-settings.js +72 -34
  30. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BeB0jyn_.js → abnfDiagram-N423BO3Z-CR1jj_rz.js} +1 -1
  31. package/dist/worker/console/static/assets/{arc-B4E8rogW.js → arc-CjxcQfEu.js} +1 -1
  32. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CuD5BPrV.js → architectureDiagram-T3A2C74G-D-3u2qFL.js} +1 -1
  33. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DOR4BrbY.js → blockDiagram-VBNYF7ZC-Bdr7gWVo.js} +1 -1
  34. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-GuWkFUBT.js → c4Diagram-5PPSVZJV-hQHNe5T3.js} +1 -1
  35. package/dist/worker/console/static/assets/channel-CBlJfald.js +1 -0
  36. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Bvp_6a1j.js → chunk-2GRJ4B5K-BEg_su6q.js} +1 -1
  37. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-zgyCBGFw.js → chunk-2Q5K7J3B-DZnV6VTC.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bd7_XVhV.js → chunk-5RXB4S5H-Dg0LzAqO.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-CO5JbujI.js → chunk-5VM5RSS4-D2vqr52W.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DPb24xsc.js → chunk-6Q2QTUOP-D8We_g6R.js} +1 -1
  41. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D4OKjlIA.js → chunk-GF5L2VYU-DbEU8drD.js} +1 -1
  42. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BdtF1gRX.js → chunk-JWPE2WC7-Boi8TJYN.js} +1 -1
  43. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-cSxCzmVA.js → chunk-KBJHAD2P-CjJmKa9f.js} +1 -1
  44. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-De4Oormb.js → chunk-RYQCIY6F-C-KV-ag7.js} +1 -1
  45. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CMIvrR5C.js → chunk-XXDRQBXY-DZlTonsZ.js} +1 -1
  46. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-mNUYCdDo.js +1 -0
  47. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-mNUYCdDo.js +1 -0
  48. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-9SmHPXIr.js → cose-bilkent-JH36ORCC-BIvFe3yn.js} +1 -1
  49. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-wl-77tI0.js → cynefinDiagram-MW4NZA55-BOBPfv8u.js} +1 -1
  50. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-yqj9yJJQ.js → dagre-VZM6K2ZE-BF54orLO.js} +1 -1
  51. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-D-rMYS98.js → diagram-7IWD3JNH-CxjAP2AP.js} +1 -1
  52. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CQFAofzl.js → diagram-B4RE2ZJO-BXYkuNGt.js} +1 -1
  53. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-CfUQmVKd.js → diagram-LBJQPF4R-DQTu-2Iy.js} +1 -1
  54. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BkK1xnZN.js → diagram-Q27KOJAE-DNURuIYc.js} +1 -1
  55. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BQQRT4QA.js → diagram-UB23O5K3-D69uANY8.js} +1 -1
  56. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR--rItMGHc.js → ebnfDiagram-BXEA7PRR-C658EcrV.js} +1 -1
  57. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-YO3gwIVo.js → erDiagram-JOGREHBK-BRccYtAl.js} +1 -1
  58. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-sVlorROr.js → flowDiagram-UKHOOZJN-DnIR4sLs.js} +1 -1
  59. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DRBbNi-x.js → ganttDiagram-PKOTCBZU-Bo3eWFVC.js} +1 -1
  60. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-D0VaAfPP.js → gitGraphDiagram-DS77QQ5N-EyWDCNU_.js} +1 -1
  61. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DtHpfgsg.js → infoDiagram-6WML65LV-B0Eld9u0.js} +1 -1
  62. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Ea8r9FLd.js → ishikawaDiagram-WSZJBQD7-DsJQiJ27.js} +1 -1
  63. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CVJVcKLc.js → journeyDiagram-NVQOT4AX-fpE0yqjC.js} +1 -1
  64. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CUdymoGj.js → kanban-definition-27J2QSJJ-Dq9IrDdT.js} +1 -1
  65. package/dist/worker/console/static/assets/{linear-D5880Sph.js → linear-CFV4BDyf.js} +1 -1
  66. package/dist/worker/console/static/assets/main-D-ZQ4gLb.css +1 -0
  67. package/dist/worker/console/static/assets/{main-2IXI34Fw.js → main-Dwhb3ZRq.js} +126 -126
  68. package/dist/worker/console/static/assets/{mermaid.core-D6dkYx5V.js → mermaid.core-BMMXqtrB.js} +4 -4
  69. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-DhZljSlQ.js → mindmap-definition-FAOFIHXS-DurrK_Gi.js} +1 -1
  70. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-2S30TPom.js → pegDiagram-VL7TDLO6-CzZayNy2.js} +1 -1
  71. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-B9y_krb1.js → pieDiagram-7S7Q4E2Y-B1W7Y0cE.js} +1 -1
  72. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-C-XgJLT_.js → quadrantDiagram-CIZ2JOQS-BdbL83CU.js} +1 -1
  73. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CTeVrhCo.js → railroadDiagram-AXF67PYL-W-bQpd18.js} +1 -1
  74. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-B7K6JWmy.js → requirementDiagram-LRYGKXZP-C9bi4tQJ.js} +1 -1
  75. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-QAlLfn7A.js → sankeyDiagram-W5VNT64P-D4kO56Wd.js} +1 -1
  76. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BdWZWKdx.js → sequenceDiagram-SI44F4Z6-CIbesK1e.js} +1 -1
  77. package/dist/worker/console/static/assets/{sheet-workbook-BoC0pAy2.js → sheet-workbook-kFN3yUBr.js} +1 -1
  78. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-D6ASD67I.js → sizeCapture-X5ZJPWSS-Dk4XAK7C.js} +1 -1
  79. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-C3MgmUi2.js → stateDiagram-OKZ733FA-Bz9B6UZ7.js} +1 -1
  80. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BBRlxIq8.js +1 -0
  81. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-Dqrd-WNB.js → swimlanes-SLNWSIFB-qLEds93n.js} +2 -2
  82. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CRBvOMCQ.js +8 -0
  83. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-lQftYLJh.js → timeline-definition-Z64GVDOM-C9rVFC0h.js} +1 -1
  84. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-WA2DaCGk.js → vennDiagram-T6HMQDX7-CoKJ9hU0.js} +1 -1
  85. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-CFpLw8Jh.js → wardleyDiagram-T6FBY63Y-tHz_S7-L.js} +1 -1
  86. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-zgM9I8sM.js → xychartDiagram-ELKLHX3M-DKzKYnvG.js} +1 -1
  87. package/dist/worker/console/static/index.html +2 -2
  88. package/dist/worker/console/static-src/operator-chat/format-file-size.js +26 -0
  89. package/dist/workflows/dag/checkpoint.js +6 -1
  90. package/dist/workflows/dag/frontend-committed-facts.js +38 -5
  91. package/dist/workflows/dag/frontend-design-policy.js +22 -0
  92. package/dist/workflows/dag/frontend-implementation-contract.js +39 -12
  93. package/dist/workflows/dag/frontend-imported-run-artifacts.js +126 -0
  94. package/dist/workflows/dag/frontend-recovery-run.js +7 -110
  95. package/dist/workflows/dag/frontend-test-framework-adapters.js +14 -0
  96. package/dist/workflows/dag/frontend-verification-trace.js +20 -8
  97. package/dist/workflows/dag/frontend-writer-reuse.js +104 -0
  98. package/dist/workflows/dag/frontend-writer-status.js +0 -4
  99. package/dist/workflows/dag/hybrid/templates/frontend.js +15 -8
  100. package/dist/workflows/dag/init-hybrid.js +1 -1
  101. package/dist/workflows/dag/reconcile-run.js +11 -1
  102. package/dist/workflows/dag/recovery-lease.js +23 -0
  103. package/dist/workflows/dag/rerun-feedback.js +4 -2
  104. package/dist/workflows/dag/rerun-run.js +40 -0
  105. package/dist/workflows/dag/runner.js +11 -0
  106. package/dist/workflows/dag/terminal-status.js +2 -1
  107. package/package.json +3 -3
  108. package/dist/worker/console/static/assets/channel-DFwPpXxz.js +0 -1
  109. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9pWfL1L.js +0 -1
  110. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9pWfL1L.js +0 -1
  111. package/dist/worker/console/static/assets/main-Ckf7id9T.css +0 -1
  112. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BEwsMVdO.js +0 -1
  113. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-D9l9u9WV.js +0 -8
@@ -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
  }
@@ -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
  }
@@ -5,12 +5,11 @@
5
5
  * `<appDataRoot>/settings/pi-compaction.json`.
6
6
  *
7
7
  * Why this exists: a self-hosted gateway can accept far less input than the
8
- * model's declared `contextWindow`. When compaction is triggered from the
9
- * declared window it never fires before the gateway rejects the request, so
10
- * every session lands on the deterministic local checkpoint instead of a
11
- * provider summary. The gateway limit is a property of the deployment, not of
12
- * the project or the model, so it is a user preference rather than a manifest
13
- * value or a hard-coded constant.
8
+ * model's declared `contextWindow`. The old model exposed that as an absolute
9
+ * "gateway limit", which silently stops working the moment the conversation
10
+ * moves to a model with a different window. The policy now follows DSH: a
11
+ * window fraction plus headroom, both relative to the window, so one setting
12
+ * stays correct across models.
14
13
  *
15
14
  * Environment variables remain supported and take precedence, so an operator
16
15
  * can override without touching saved settings (see `resolveCompactionSettings`).
@@ -18,6 +17,7 @@
18
17
  import { readFile, rename, writeFile } from "node:fs/promises";
19
18
  import path from "node:path";
20
19
  import { ensureSecureDir } from "../../infrastructure/console/app-data.js";
20
+ import { DEFAULT_HEADROOM_TOKENS, DEFAULT_RETAIN_RATIO, DEFAULT_THRESHOLD_RATIO, } from "../../shared/pi-context-pressure/compaction-policy.js";
21
21
  export const PI_COMPACTION_SETTINGS_SCHEMA_VERSION = 1;
22
22
  export class PiCompactionSettingsError extends Error {
23
23
  code;
@@ -30,23 +30,35 @@ export class PiCompactionSettingsError extends Error {
30
30
  }
31
31
  }
32
32
  /** Bounds mirror the environment parser so the two sources cannot disagree. */
33
- export const GATEWAY_LIMIT_MIN = 1_024;
34
- export const GATEWAY_LIMIT_MAX = 10_000_000;
35
- export const KEEP_RECENT_MIN = 0;
36
- export const KEEP_RECENT_MAX = 1_000_000;
33
+ export const THRESHOLD_RATIO_MIN = 0.05;
34
+ export const THRESHOLD_RATIO_MAX = 1;
35
+ export const HEADROOM_MIN = 0;
36
+ export const HEADROOM_MAX = 10_000_000;
37
+ export const RETAIN_RATIO_MIN = 0.01;
38
+ export const RETAIN_RATIO_MAX = 0.99;
39
+ /**
40
+ * Keys accepted from a saved file.
41
+ *
42
+ * The previous schema stored `gatewayInputLimitTokens` and `keepRecentTokens`.
43
+ * Those are dropped on read rather than migrated: an absolute gateway ceiling
44
+ * cannot be converted into a relative headroom, and a retained-token count is
45
+ * now derived from the window. Ignoring them means an upgraded install lands on
46
+ * the DSH defaults instead of on a silently wrong value.
47
+ */
48
+ const LEGACY_KEYS = new Set(["gatewayInputLimitTokens", "keepRecentTokens"]);
49
+ const CURRENT_KEYS = ["thresholdRatio", "headroomTokens", "retainRatio"];
37
50
  function isRecord(value) {
38
51
  return typeof value === "object" && value !== null && !Array.isArray(value);
39
52
  }
40
- function boundedInteger(value, field, label, min, max) {
53
+ function boundedNumber(value, label, min, max) {
41
54
  if (value === undefined || value === null)
42
55
  return undefined;
43
- if (typeof value !== "number" || !Number.isSafeInteger(value)) {
44
- throw new PiCompactionSettingsError("INVALID_INPUT", `${label}必须是整数`);
56
+ if (typeof value !== "number" || !Number.isFinite(value)) {
57
+ throw new PiCompactionSettingsError("INVALID_INPUT", `${label}必须是数字`);
45
58
  }
46
59
  if (value < min || value > max) {
47
60
  throw new PiCompactionSettingsError("INVALID_INPUT", `${label}必须在 ${min} 到 ${max} 之间(收到 ${value})`);
48
61
  }
49
- void field;
50
62
  return value;
51
63
  }
52
64
  export function parsePiCompactionSettings(value) {
@@ -55,15 +67,24 @@ export function parsePiCompactionSettings(value) {
55
67
  if (!isRecord(value)) {
56
68
  throw new PiCompactionSettingsError("INVALID_INPUT", "压缩设置格式无效");
57
69
  }
58
- const unknownKeys = Object.keys(value).filter((key) => key !== "gatewayInputLimitTokens" && key !== "keepRecentTokens");
70
+ const unknownKeys = Object.keys(value).filter((key) => !LEGACY_KEYS.has(key) && !CURRENT_KEYS.includes(key));
59
71
  if (unknownKeys.length > 0) {
60
72
  throw new PiCompactionSettingsError("INVALID_INPUT", `压缩设置包含无效字段:${unknownKeys.join(", ")}`);
61
73
  }
62
- const gateway = boundedInteger(value.gatewayInputLimitTokens, "gatewayInputLimitTokens", "网关输入上限", GATEWAY_LIMIT_MIN, GATEWAY_LIMIT_MAX);
63
- const keepRecent = boundedInteger(value.keepRecentTokens, "keepRecentTokens", "压缩保留的近期 token", KEEP_RECENT_MIN, KEEP_RECENT_MAX);
74
+ const thresholdRatio = boundedNumber(value.thresholdRatio, "窗口比例", THRESHOLD_RATIO_MIN, THRESHOLD_RATIO_MAX);
75
+ const headroomTokens = boundedNumber(value.headroomTokens, "额外余量", HEADROOM_MIN, HEADROOM_MAX);
76
+ const retainRatio = boundedNumber(value.retainRatio, "保留比例", RETAIN_RATIO_MIN, RETAIN_RATIO_MAX);
77
+ if (thresholdRatio !== undefined &&
78
+ retainRatio !== undefined &&
79
+ retainRatio >= thresholdRatio) {
80
+ // DSH rejects this outright: retaining as much as we compact leaves the
81
+ // summary covering nothing.
82
+ throw new PiCompactionSettingsError("INVALID_INPUT", "保留比例必须小于窗口比例");
83
+ }
64
84
  return {
65
- ...(gateway === undefined ? {} : { gatewayInputLimitTokens: gateway }),
66
- ...(keepRecent === undefined ? {} : { keepRecentTokens: keepRecent }),
85
+ ...(thresholdRatio === undefined ? {} : { thresholdRatio }),
86
+ ...(headroomTokens === undefined ? {} : { headroomTokens }),
87
+ ...(retainRatio === undefined ? {} : { retainRatio }),
67
88
  };
68
89
  }
69
90
  /**
@@ -74,17 +95,28 @@ export function parsePiCompactionSettings(value) {
74
95
  export function resolveCompactionSettings(input) {
75
96
  const env = input.env ?? process.env;
76
97
  const saved = input.saved ?? {};
77
- const gatewayFromEnv = Number(env.HARNESS_GATEWAY_INPUT_LIMIT_TOKENS?.trim());
78
- const keepRecentFromEnv = Number(env.HARNESS_COMPACTION_KEEP_RECENT_TOKENS?.trim());
79
- const hasGatewayEnv = Number.isSafeInteger(gatewayFromEnv) && gatewayFromEnv > 0;
80
- const hasKeepRecentEnv = Number.isSafeInteger(keepRecentFromEnv) && keepRecentFromEnv >= 0;
98
+ const readEnv = (name) => {
99
+ const raw = env[name]?.trim();
100
+ if (!raw)
101
+ return undefined;
102
+ const parsed = Number(raw);
103
+ return Number.isFinite(parsed) ? parsed : undefined;
104
+ };
105
+ const thresholdFromEnv = readEnv("HARNESS_COMPACTION_THRESHOLD_RATIO");
106
+ const headroomFromEnv = readEnv("HARNESS_COMPACTION_HEADROOM_TOKENS");
107
+ const retainFromEnv = readEnv("HARNESS_COMPACTION_RETAIN_RATIO");
81
108
  return {
82
- gatewayInputLimitTokens: hasGatewayEnv
83
- ? gatewayFromEnv
84
- : saved.gatewayInputLimitTokens,
85
- keepRecentTokens: hasKeepRecentEnv
86
- ? keepRecentFromEnv
87
- : saved.keepRecentTokens,
109
+ thresholdRatio: thresholdFromEnv ?? saved.thresholdRatio,
110
+ headroomTokens: headroomFromEnv ?? saved.headroomTokens,
111
+ retainRatio: retainFromEnv ?? saved.retainRatio,
112
+ };
113
+ }
114
+ /** Effective values with DSH defaults applied, for display. */
115
+ export function effectiveCompactionSettings(settings) {
116
+ return {
117
+ thresholdRatio: settings.thresholdRatio ?? DEFAULT_THRESHOLD_RATIO,
118
+ headroomTokens: settings.headroomTokens ?? DEFAULT_HEADROOM_TOKENS,
119
+ retainRatio: settings.retainRatio ?? DEFAULT_RETAIN_RATIO,
88
120
  };
89
121
  }
90
122
  function settingsFile(appDataRoot) {
@@ -120,7 +152,11 @@ async function readStored(file) {
120
152
  settings: parsePiCompactionSettings(parsed.settings),
121
153
  };
122
154
  }
123
- catch {
155
+ catch (error) {
156
+ // A file written by the previous schema is readable: its keys are parsed
157
+ // and dropped. Only a genuinely broken file is an error.
158
+ if (error instanceof PiCompactionSettingsError)
159
+ throw error;
124
160
  throw new PiCompactionSettingsError("SETTINGS_UNREADABLE", "无法读取压缩设置,请检查程序数据目录中的 settings/pi-compaction.json", 503);
125
161
  }
126
162
  }
@@ -134,20 +170,22 @@ async function writeAtomic(file, content) {
134
170
  * One persisted preference per Console data root.
135
171
  *
136
172
  * Reads are uncached on purpose: the runtime asks once per session start, and a
137
- * stale cache would silently keep a corrected gateway limit from applying.
173
+ * stale cache would silently keep a corrected setting from applying.
138
174
  */
139
175
  export async function createPiCompactionSettings(appDataRoot) {
140
176
  const file = settingsFile(appDataRoot);
141
177
  const view = (stored) => {
142
178
  const effective = resolveCompactionSettings({ saved: stored.settings });
179
+ const resolved = effectiveCompactionSettings(effective);
143
180
  return {
144
181
  ok: true,
145
182
  revision: stored.revision,
146
183
  settings: stored.settings,
147
- effective,
184
+ effective: resolved,
148
185
  envOverrides: {
149
- gatewayInputLimitTokens: effective.gatewayInputLimitTokens !== stored.settings.gatewayInputLimitTokens,
150
- keepRecentTokens: effective.keepRecentTokens !== stored.settings.keepRecentTokens,
186
+ thresholdRatio: effective.thresholdRatio !== stored.settings.thresholdRatio,
187
+ headroomTokens: effective.headroomTokens !== stored.settings.headroomTokens,
188
+ retainRatio: effective.retainRatio !== stored.settings.retainRatio,
151
189
  },
152
190
  };
153
191
  };