@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.
- package/CHANGELOG.md +36 -10
- package/dist/build-stamp.json +3 -3
- package/dist/executors/dag-pi/plan/finalize-tools.js +13 -0
- package/dist/executors/dag-pi/plan/record-tools.js +37 -11
- package/dist/executors/dag-pi/sessions/plan-batches.js +1 -1
- package/dist/executors/dag-pi/sessions/segmented-plan.js +28 -20
- package/dist/executors/dag-pi/tools/plan-decision-tools.js +2 -1
- package/dist/executors/dag-pi-executor.js +50 -5
- package/dist/executors/pi-executor.js +12 -0
- package/dist/executors/pi-sdk-executor.js +2 -2
- package/dist/shared/frontend-execution-policy.js +28 -2
- package/dist/shared/pi-context-pressure/compaction-policy.js +156 -150
- package/dist/shared/pi-context-pressure/extension.js +21 -14
- package/dist/shared/pi-context-pressure/index.js +1 -1
- package/dist/shared/pi-context-pressure/telemetry.js +10 -0
- package/dist/task/config-types.js +2 -2
- package/dist/task/source-prepare/prepare.js +1 -1
- package/dist/task/source-prepare/semantic-intake.js +2 -2
- package/dist/task/source-prepare/source-fidelity-pi.js +2 -1
- package/dist/worker/console/chat/assistant-content.js +21 -3
- package/dist/worker/console/chat/compaction-errors.js +28 -2
- package/dist/worker/console/chat/context-insights.js +4 -4
- package/dist/worker/console/chat/context-usage.js +4 -1
- package/dist/worker/console/chat/contract-apply-receipt-store.js +37 -25
- package/dist/worker/console/chat/pi-runtime.js +55 -119
- package/dist/worker/console/chat/routes.js +20 -0
- package/dist/worker/console/chat/turn-process.js +2 -0
- package/dist/worker/console/mutation-gate-receipt-store.js +38 -29
- package/dist/worker/console/pi-compaction-settings.js +72 -34
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BeB0jyn_.js → abnfDiagram-N423BO3Z-CR1jj_rz.js} +1 -1
- package/dist/worker/console/static/assets/{arc-B4E8rogW.js → arc-CjxcQfEu.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CuD5BPrV.js → architectureDiagram-T3A2C74G-D-3u2qFL.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DOR4BrbY.js → blockDiagram-VBNYF7ZC-Bdr7gWVo.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-GuWkFUBT.js → c4Diagram-5PPSVZJV-hQHNe5T3.js} +1 -1
- package/dist/worker/console/static/assets/channel-CBlJfald.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Bvp_6a1j.js → chunk-2GRJ4B5K-BEg_su6q.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-zgyCBGFw.js → chunk-2Q5K7J3B-DZnV6VTC.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bd7_XVhV.js → chunk-5RXB4S5H-Dg0LzAqO.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-CO5JbujI.js → chunk-5VM5RSS4-D2vqr52W.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DPb24xsc.js → chunk-6Q2QTUOP-D8We_g6R.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D4OKjlIA.js → chunk-GF5L2VYU-DbEU8drD.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BdtF1gRX.js → chunk-JWPE2WC7-Boi8TJYN.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-cSxCzmVA.js → chunk-KBJHAD2P-CjJmKa9f.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-De4Oormb.js → chunk-RYQCIY6F-C-KV-ag7.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CMIvrR5C.js → chunk-XXDRQBXY-DZlTonsZ.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-mNUYCdDo.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-mNUYCdDo.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-9SmHPXIr.js → cose-bilkent-JH36ORCC-BIvFe3yn.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-wl-77tI0.js → cynefinDiagram-MW4NZA55-BOBPfv8u.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-yqj9yJJQ.js → dagre-VZM6K2ZE-BF54orLO.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-D-rMYS98.js → diagram-7IWD3JNH-CxjAP2AP.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CQFAofzl.js → diagram-B4RE2ZJO-BXYkuNGt.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-CfUQmVKd.js → diagram-LBJQPF4R-DQTu-2Iy.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BkK1xnZN.js → diagram-Q27KOJAE-DNURuIYc.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-BQQRT4QA.js → diagram-UB23O5K3-D69uANY8.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR--rItMGHc.js → ebnfDiagram-BXEA7PRR-C658EcrV.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-YO3gwIVo.js → erDiagram-JOGREHBK-BRccYtAl.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-sVlorROr.js → flowDiagram-UKHOOZJN-DnIR4sLs.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DRBbNi-x.js → ganttDiagram-PKOTCBZU-Bo3eWFVC.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-D0VaAfPP.js → gitGraphDiagram-DS77QQ5N-EyWDCNU_.js} +1 -1
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DtHpfgsg.js → infoDiagram-6WML65LV-B0Eld9u0.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Ea8r9FLd.js → ishikawaDiagram-WSZJBQD7-DsJQiJ27.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CVJVcKLc.js → journeyDiagram-NVQOT4AX-fpE0yqjC.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CUdymoGj.js → kanban-definition-27J2QSJJ-Dq9IrDdT.js} +1 -1
- package/dist/worker/console/static/assets/{linear-D5880Sph.js → linear-CFV4BDyf.js} +1 -1
- package/dist/worker/console/static/assets/main-D-ZQ4gLb.css +1 -0
- package/dist/worker/console/static/assets/{main-2IXI34Fw.js → main-Dwhb3ZRq.js} +126 -126
- package/dist/worker/console/static/assets/{mermaid.core-D6dkYx5V.js → mermaid.core-BMMXqtrB.js} +4 -4
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-DhZljSlQ.js → mindmap-definition-FAOFIHXS-DurrK_Gi.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-2S30TPom.js → pegDiagram-VL7TDLO6-CzZayNy2.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-B9y_krb1.js → pieDiagram-7S7Q4E2Y-B1W7Y0cE.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-C-XgJLT_.js → quadrantDiagram-CIZ2JOQS-BdbL83CU.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CTeVrhCo.js → railroadDiagram-AXF67PYL-W-bQpd18.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-B7K6JWmy.js → requirementDiagram-LRYGKXZP-C9bi4tQJ.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-QAlLfn7A.js → sankeyDiagram-W5VNT64P-D4kO56Wd.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BdWZWKdx.js → sequenceDiagram-SI44F4Z6-CIbesK1e.js} +1 -1
- package/dist/worker/console/static/assets/{sheet-workbook-BoC0pAy2.js → sheet-workbook-kFN3yUBr.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-D6ASD67I.js → sizeCapture-X5ZJPWSS-Dk4XAK7C.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-C3MgmUi2.js → stateDiagram-OKZ733FA-Bz9B6UZ7.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BBRlxIq8.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-Dqrd-WNB.js → swimlanes-SLNWSIFB-qLEds93n.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CRBvOMCQ.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-lQftYLJh.js → timeline-definition-Z64GVDOM-C9rVFC0h.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-WA2DaCGk.js → vennDiagram-T6HMQDX7-CoKJ9hU0.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-CFpLw8Jh.js → wardleyDiagram-T6FBY63Y-tHz_S7-L.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-zgM9I8sM.js → xychartDiagram-ELKLHX3M-DKzKYnvG.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/format-file-size.js +26 -0
- package/dist/workflows/dag/checkpoint.js +6 -1
- package/dist/workflows/dag/frontend-committed-facts.js +38 -5
- package/dist/workflows/dag/frontend-design-policy.js +22 -0
- package/dist/workflows/dag/frontend-implementation-contract.js +39 -12
- package/dist/workflows/dag/frontend-imported-run-artifacts.js +126 -0
- package/dist/workflows/dag/frontend-recovery-run.js +7 -110
- package/dist/workflows/dag/frontend-test-framework-adapters.js +14 -0
- package/dist/workflows/dag/frontend-verification-trace.js +20 -8
- package/dist/workflows/dag/frontend-writer-reuse.js +104 -0
- package/dist/workflows/dag/frontend-writer-status.js +0 -4
- package/dist/workflows/dag/hybrid/templates/frontend.js +15 -8
- package/dist/workflows/dag/init-hybrid.js +1 -1
- package/dist/workflows/dag/reconcile-run.js +11 -1
- package/dist/workflows/dag/recovery-lease.js +23 -0
- package/dist/workflows/dag/rerun-feedback.js +4 -2
- package/dist/workflows/dag/rerun-run.js +40 -0
- package/dist/workflows/dag/runner.js +11 -0
- package/dist/workflows/dag/terminal-status.js +2 -1
- package/package.json +3 -3
- package/dist/worker/console/static/assets/channel-DFwPpXxz.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9pWfL1L.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9pWfL1L.js +0 -1
- package/dist/worker/console/static/assets/main-Ckf7id9T.css +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BEwsMVdO.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-D9l9u9WV.js +0 -8
|
@@ -1,132 +1,161 @@
|
|
|
1
1
|
import { parseBoundedNumber, readContextPressureMode, } from "./env.js";
|
|
2
|
+
/**
|
|
3
|
+
* Pi's own fallback reserve. Only used when the window is unusable, so Pi keeps
|
|
4
|
+
* a finite threshold instead of compacting on every request.
|
|
5
|
+
*/
|
|
2
6
|
export const PI_DEFAULT_RESERVE_TOKENS = 16_384;
|
|
3
|
-
export const DEFAULT_TRAILING_BUDGET_TOKENS = 8_192;
|
|
4
|
-
export const DEFAULT_SAFETY_MARGIN_TOKENS = 4_096;
|
|
5
|
-
export const DEFAULT_MINIMUM_WORKING_SET = 32_768;
|
|
6
|
-
export const DEFAULT_KEEP_RECENT_TOKENS = 20_000;
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
8
|
+
* Output tokens reserved out of the window before pressure is computed.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* DSH derives this from the routed adapter's `defaultMaxTokens`. Pi only
|
|
11
|
+
* exposes the model's `maxTokens`, which is the model's *capability*, not the
|
|
12
|
+
* budget reserved for this request. Using it would drag the trigger far down on
|
|
13
|
+
* small-window models: a 150k window with `maxTokens = 32768` triggers at
|
|
14
|
+
* 51,696 tokens (34.5% of the window) instead of 76,272 (50.8%), which compacts
|
|
15
|
+
* far more often than intended. A fixed conservative reservation avoids that.
|
|
14
16
|
*/
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
export const DEFAULT_RESERVED_COMPLETION_TOKENS = 8_192;
|
|
18
|
+
/** DSH defaults, adopted verbatim. See `compaction-basic/src/config.ts`. */
|
|
19
|
+
export const DEFAULT_THRESHOLD_RATIO = 0.8;
|
|
20
|
+
/*
|
|
21
|
+
* 20,000 instead of DSH's 65,536.
|
|
22
|
+
*
|
|
23
|
+
* DSH's value is an absolute distance from the top, chosen for its large
|
|
24
|
+
* windows. On a 150k window it costs 43.7% of the budget, so the `min()` term
|
|
25
|
+
* that actually decides the trigger is the headroom, not `thresholdRatio`:
|
|
26
|
+
* the line landed on 50.8% and the configured 80% never applied. At 20,000 the
|
|
27
|
+
* ratio term wins again (trigger = 120,000 = 80.0%), which is what the ratio
|
|
28
|
+
* field promises.
|
|
29
|
+
*
|
|
30
|
+
* Still an absolute value on purpose: a deployment whose gateway rejects below
|
|
31
|
+
* the declared window raises this to pull the trigger under the real ceiling.
|
|
32
|
+
*/
|
|
33
|
+
export const DEFAULT_HEADROOM_TOKENS = 20_000;
|
|
34
|
+
export const DEFAULT_RETAIN_RATIO = 0.16;
|
|
20
35
|
export function parseCompactionPolicy(env = process.env) {
|
|
21
36
|
const diagnostics = [];
|
|
22
37
|
const modeResult = readContextPressureMode(env);
|
|
23
38
|
if (modeResult.diagnostic)
|
|
24
39
|
diagnostics.push(modeResult.diagnostic);
|
|
25
|
-
const
|
|
26
|
-
if (
|
|
27
|
-
diagnostics.push(
|
|
28
|
-
const
|
|
29
|
-
if (
|
|
30
|
-
diagnostics.push(
|
|
31
|
-
const
|
|
32
|
-
if (
|
|
33
|
-
diagnostics.push(
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
: parseBoundedNumber(explicit, PI_DEFAULT_RESERVE_TOKENS, 1_024, 1_000_000);
|
|
38
|
-
if (explicitReserve?.diagnostic)
|
|
39
|
-
diagnostics.push(explicitReserve.diagnostic);
|
|
40
|
-
// A gateway limit that is absent means "no separate cap", which is the
|
|
41
|
-
// common case for direct provider access; only a positive value constrains
|
|
42
|
-
// the trigger. Parsing happens only when the value can mean something, since
|
|
43
|
-
// `parseBoundedNumber` clamps 0 up to the minimum instead of rejecting it.
|
|
44
|
-
const gatewayLimitRaw = env.HARNESS_GATEWAY_INPUT_LIMIT_TOKENS?.trim();
|
|
45
|
-
const gatewayLimit = gatewayLimitRaw === undefined ||
|
|
46
|
-
gatewayLimitRaw === "" ||
|
|
47
|
-
!/^\d+$/.test(gatewayLimitRaw) ||
|
|
48
|
-
Number(gatewayLimitRaw) <= 0
|
|
49
|
-
? undefined
|
|
50
|
-
: parseBoundedNumber(gatewayLimitRaw, 0, 1_024, 10_000_000);
|
|
51
|
-
if (gatewayLimit?.diagnostic)
|
|
52
|
-
diagnostics.push(gatewayLimit.diagnostic);
|
|
53
|
-
const keepRecentRaw = env.HARNESS_COMPACTION_KEEP_RECENT_TOKENS;
|
|
54
|
-
const keepRecent = keepRecentRaw === undefined || keepRecentRaw.trim() === ""
|
|
55
|
-
? undefined
|
|
56
|
-
: parseBoundedNumber(keepRecentRaw, 0, 0, 1_000_000);
|
|
57
|
-
if (keepRecent?.diagnostic)
|
|
58
|
-
diagnostics.push(keepRecent.diagnostic);
|
|
40
|
+
const ratio = parseBoundedNumber(env.HARNESS_COMPACTION_THRESHOLD_RATIO, DEFAULT_THRESHOLD_RATIO, 0.05, 1);
|
|
41
|
+
if (ratio.diagnostic)
|
|
42
|
+
diagnostics.push(ratio.diagnostic);
|
|
43
|
+
const headroom = parseBoundedNumber(env.HARNESS_COMPACTION_HEADROOM_TOKENS, DEFAULT_HEADROOM_TOKENS, 0, 10_000_000);
|
|
44
|
+
if (headroom.diagnostic)
|
|
45
|
+
diagnostics.push(headroom.diagnostic);
|
|
46
|
+
const retain = parseBoundedNumber(env.HARNESS_COMPACTION_RETAIN_RATIO, DEFAULT_RETAIN_RATIO, 0.01, 0.99);
|
|
47
|
+
if (retain.diagnostic)
|
|
48
|
+
diagnostics.push(retain.diagnostic);
|
|
49
|
+
const reserved = parseBoundedNumber(env.HARNESS_COMPACTION_RESERVED_COMPLETION_TOKENS, DEFAULT_RESERVED_COMPLETION_TOKENS, 0, 1_000_000);
|
|
50
|
+
if (reserved.diagnostic)
|
|
51
|
+
diagnostics.push(reserved.diagnostic);
|
|
59
52
|
return {
|
|
60
53
|
mode: modeResult.mode,
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
...(explicitReserve ? { explicitReserveTokens: explicitReserve.value } : {}),
|
|
66
|
-
...(gatewayLimit && gatewayLimit.value > 0
|
|
67
|
-
? { gatewayInputLimitTokens: gatewayLimit.value }
|
|
68
|
-
: {}),
|
|
69
|
-
...(keepRecent ? { keepRecentTokens: keepRecent.value } : {}),
|
|
54
|
+
thresholdRatio: ratio.value,
|
|
55
|
+
headroomTokens: headroom.value,
|
|
56
|
+
retainRatio: retain.value,
|
|
57
|
+
reservedCompletionTokens: reserved.value,
|
|
70
58
|
diagnostics,
|
|
71
59
|
};
|
|
72
60
|
}
|
|
73
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Resolve the pressure threshold and the retained tail for one model window.
|
|
63
|
+
*
|
|
64
|
+
* Mirrors DSH's `resolveCompactSpec`:
|
|
65
|
+
*
|
|
66
|
+
* messageBudget = contextWindow - reservedCompletion
|
|
67
|
+
* pressureBudget = messageBudget - headroomTokens
|
|
68
|
+
* thresholdTokens = min(contextWindow × thresholdRatio, pressureBudget)
|
|
69
|
+
* retainTokens = messageBudget × retainRatio
|
|
70
|
+
*
|
|
71
|
+
* DSH throws when the window cannot support the policy, because it is a
|
|
72
|
+
* library and the host can fix its configuration. The Console must keep the
|
|
73
|
+
* session usable instead, so it falls back to Pi's default reserve and records
|
|
74
|
+
* a diagnostic.
|
|
75
|
+
*/
|
|
76
|
+
export function resolveCompactSpec(contextWindow, policy) {
|
|
77
|
+
const diagnostics = [];
|
|
74
78
|
const declared = Math.floor(contextWindow);
|
|
75
79
|
if (!Number.isFinite(declared) || declared <= 0) {
|
|
76
80
|
return {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
81
|
+
thresholdTokens: 0,
|
|
82
|
+
retainTokens: 0,
|
|
83
|
+
contextWindow: 0,
|
|
84
|
+
messageBudgetTokens: 0,
|
|
85
|
+
fallback: true,
|
|
86
|
+
diagnostics: ["invalid-context-window"],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const reserved = Math.max(0, Math.floor(policy.reservedCompletionTokens));
|
|
90
|
+
const messageBudget = declared - reserved;
|
|
91
|
+
if (messageBudget <= 0) {
|
|
92
|
+
const thresholdTokens = Math.max(0, declared - PI_DEFAULT_RESERVE_TOKENS);
|
|
93
|
+
return {
|
|
94
|
+
thresholdTokens,
|
|
95
|
+
retainTokens: Math.max(0, Math.floor(thresholdTokens * policy.retainRatio)),
|
|
96
|
+
contextWindow: declared,
|
|
97
|
+
messageBudgetTokens: 0,
|
|
80
98
|
fallback: true,
|
|
99
|
+
diagnostics: ["reserved-completion-exhausts-window"],
|
|
81
100
|
};
|
|
82
101
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
* accepts. Shrinking only the trigger keeps `contextWindow` itself truthful
|
|
87
|
-
* (it still describes the model) and leaves `maxTokens` accounting alone.
|
|
88
|
-
*/
|
|
89
|
-
const W = policy.gatewayInputLimitTokens !== undefined &&
|
|
90
|
-
policy.gatewayInputLimitTokens > 0 &&
|
|
91
|
-
policy.gatewayInputLimitTokens < declared
|
|
92
|
-
? Math.floor(policy.gatewayInputLimitTokens)
|
|
93
|
-
: declared;
|
|
94
|
-
if (policy.explicitReserveTokens !== undefined) {
|
|
95
|
-
const recommendedReserve = Math.min(Math.max(policy.explicitReserveTokens, 1), Math.max(1, W - 1));
|
|
96
|
-
const triggerTokens = Math.max(0, W - recommendedReserve);
|
|
102
|
+
const pressureBudget = messageBudget - policy.headroomTokens;
|
|
103
|
+
if (pressureBudget <= 0) {
|
|
104
|
+
const thresholdTokens = Math.max(0, declared - PI_DEFAULT_RESERVE_TOKENS);
|
|
97
105
|
return {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
106
|
+
thresholdTokens,
|
|
107
|
+
retainTokens: Math.max(0, Math.floor(thresholdTokens * policy.retainRatio)),
|
|
108
|
+
contextWindow: declared,
|
|
109
|
+
messageBudgetTokens: messageBudget,
|
|
110
|
+
fallback: true,
|
|
111
|
+
diagnostics: ["headroom-exhausts-message-budget"],
|
|
102
112
|
};
|
|
103
113
|
}
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
policy.safetyMarginTokens;
|
|
107
|
-
const rawReserve = W - rawTrigger;
|
|
108
|
-
const maxReserve = Math.max(1, W - policy.minimumWorkingSet);
|
|
109
|
-
if (!Number.isFinite(rawTrigger) ||
|
|
110
|
-
!Number.isFinite(rawReserve) ||
|
|
111
|
-
maxReserve < PI_DEFAULT_RESERVE_TOKENS) {
|
|
112
|
-
const recommendedReserve = Math.min(PI_DEFAULT_RESERVE_TOKENS, Math.max(1, W - 1));
|
|
113
|
-
const triggerTokens = Math.max(0, W - recommendedReserve);
|
|
114
|
+
const thresholdTokens = Math.floor(Math.min(declared * policy.thresholdRatio, pressureBudget));
|
|
115
|
+
if (thresholdTokens <= 0) {
|
|
114
116
|
return {
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
117
|
+
thresholdTokens: 0,
|
|
118
|
+
retainTokens: 0,
|
|
119
|
+
contextWindow: declared,
|
|
120
|
+
messageBudgetTokens: messageBudget,
|
|
118
121
|
fallback: true,
|
|
122
|
+
diagnostics: ["non-positive-threshold"],
|
|
119
123
|
};
|
|
120
124
|
}
|
|
121
|
-
|
|
122
|
-
|
|
125
|
+
let retainTokens = Math.floor(messageBudget * policy.retainRatio);
|
|
126
|
+
if (retainTokens >= thresholdTokens) {
|
|
127
|
+
// DSH rejects this configuration. Retaining as much as we compact would
|
|
128
|
+
// make the summary cover nothing, so clamp and say so.
|
|
129
|
+
retainTokens = Math.max(0, thresholdTokens - 1);
|
|
130
|
+
diagnostics.push("retain-clamped-below-threshold");
|
|
131
|
+
}
|
|
123
132
|
return {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
133
|
+
thresholdTokens,
|
|
134
|
+
retainTokens,
|
|
135
|
+
contextWindow: declared,
|
|
136
|
+
messageBudgetTokens: messageBudget,
|
|
127
137
|
fallback: false,
|
|
138
|
+
diagnostics,
|
|
128
139
|
};
|
|
129
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* The `reserveTokens` to hand Pi so that its own threshold lands exactly on
|
|
143
|
+
* `thresholdTokens`.
|
|
144
|
+
*
|
|
145
|
+
* Pi decides with `contextTokens > contextWindow - reserveTokens` and reads
|
|
146
|
+
* `contextWindow` from the model definition, so the reserve must be expressed
|
|
147
|
+
* against that same number.
|
|
148
|
+
*/
|
|
149
|
+
export function piReserveTokensFor(contextWindow, thresholdTokens) {
|
|
150
|
+
const declared = Math.floor(contextWindow);
|
|
151
|
+
if (!Number.isFinite(declared) || declared <= 0) {
|
|
152
|
+
return PI_DEFAULT_RESERVE_TOKENS;
|
|
153
|
+
}
|
|
154
|
+
if (!Number.isFinite(thresholdTokens) || thresholdTokens <= 0) {
|
|
155
|
+
return Math.min(PI_DEFAULT_RESERVE_TOKENS, Math.max(1, declared - 1));
|
|
156
|
+
}
|
|
157
|
+
return Math.min(Math.max(1, declared - Math.floor(thresholdTokens)), Math.max(1, declared - 1));
|
|
158
|
+
}
|
|
130
159
|
export function conservativeTokenEstimate(text, imageCount = 0) {
|
|
131
160
|
const chars = Array.from(text);
|
|
132
161
|
let cjk = 0;
|
|
@@ -163,60 +192,37 @@ function isExplicitlyDisabled(manager) {
|
|
|
163
192
|
return project === false || (project === undefined && global === false);
|
|
164
193
|
}
|
|
165
194
|
/**
|
|
166
|
-
*
|
|
195
|
+
* Apply the resolved spec to Pi's settings manager.
|
|
167
196
|
*
|
|
168
|
-
*
|
|
169
|
-
* puts the ENTIRE branch into `messagesToSummarize`. The summary request then
|
|
170
|
-
* carries the same oversized history the provider just rejected, so it fails
|
|
171
|
-
* too, and recovery falls through to the local checkpoint. That is exactly the
|
|
172
|
-
* regression that made provider summaries disappear in favour of the
|
|
173
|
-
* deterministic checkpoint.
|
|
197
|
+
* Writes both knobs Pi reads:
|
|
174
198
|
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
199
|
+
* - `reserveTokens` positions Pi's own threshold on `thresholdTokens`.
|
|
200
|
+
* - `keepRecentTokens` becomes the retained tail, so Pi's summary request
|
|
201
|
+
* carries the same amount of verbatim history the policy intends.
|
|
178
202
|
*/
|
|
179
|
-
export const KEEP_RECENT_TRIGGER_RATIO = 0.15;
|
|
180
|
-
export const KEEP_RECENT_MAX_TOKENS = 30_000;
|
|
181
|
-
export const KEEP_RECENT_MIN_TOKENS = 2_000;
|
|
182
|
-
export function resolveKeepRecentTokens(input) {
|
|
183
|
-
if (Number.isFinite(input.explicit)) {
|
|
184
|
-
return Math.max(0, Math.floor(input.explicit));
|
|
185
|
-
}
|
|
186
|
-
if (input.policy.keepRecentTokens !== undefined) {
|
|
187
|
-
return Math.max(0, Math.floor(input.policy.keepRecentTokens));
|
|
188
|
-
}
|
|
189
|
-
if (typeof input.triggerTokens === "number" &&
|
|
190
|
-
Number.isFinite(input.triggerTokens) &&
|
|
191
|
-
input.triggerTokens > 0) {
|
|
192
|
-
const scaled = Math.floor(input.triggerTokens * KEEP_RECENT_TRIGGER_RATIO);
|
|
193
|
-
return Math.min(Math.max(scaled, KEEP_RECENT_MIN_TOKENS), KEEP_RECENT_MAX_TOKENS);
|
|
194
|
-
}
|
|
195
|
-
return DEFAULT_KEEP_RECENT_TOKENS;
|
|
196
|
-
}
|
|
197
203
|
export function applyProcessCompactionOverride(manager, input) {
|
|
198
204
|
if (!manager?.applyOverrides || input.policy.mode === "off") {
|
|
199
205
|
return { applied: false };
|
|
200
206
|
}
|
|
201
207
|
const explicitOff = input.policy.mode === "safe" && isExplicitlyDisabled(manager);
|
|
202
208
|
const enabled = input.policy.mode === "strict" ? true : explicitOff ? false : true;
|
|
203
|
-
const
|
|
204
|
-
input.
|
|
205
|
-
? input.declaredContextWindow
|
|
206
|
-
: input.contextWindow;
|
|
207
|
-
const window = typeof declaredWindow === "number" && declaredWindow > 0
|
|
208
|
-
? deriveEffectiveWindow(declaredWindow, input.policy)
|
|
209
|
+
const contextWindow = typeof input.contextWindow === "number" && input.contextWindow > 0
|
|
210
|
+
? input.contextWindow
|
|
209
211
|
: undefined;
|
|
212
|
+
const spec = contextWindow === undefined ? undefined : resolveCompactSpec(contextWindow, input.policy);
|
|
210
213
|
const compaction = { enabled };
|
|
211
|
-
if (enabled) {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
214
|
+
if (enabled && spec !== undefined) {
|
|
215
|
+
/*
|
|
216
|
+
* Write the reserve even in the fallback case.
|
|
217
|
+
*
|
|
218
|
+
* `resolveCompactSpec` still returns a usable threshold there (the window
|
|
219
|
+
* minus Pi's default reserve), and Pi has to be told about it. Skipping
|
|
220
|
+
* the write left Pi on its own defaults while the Console reported a
|
|
221
|
+
* different threshold — two thresholds again, which is exactly the class
|
|
222
|
+
* of bug this change removes.
|
|
223
|
+
*/
|
|
224
|
+
compaction.reserveTokens = piReserveTokensFor(spec.contextWindow, spec.thresholdTokens);
|
|
225
|
+
compaction.keepRecentTokens = spec.retainTokens;
|
|
220
226
|
}
|
|
221
227
|
manager.applyOverrides({ compaction });
|
|
222
228
|
return {
|
|
@@ -225,24 +231,24 @@ export function applyProcessCompactionOverride(manager, input) {
|
|
|
225
231
|
...(typeof compaction.reserveTokens === "number"
|
|
226
232
|
? { reserveTokens: compaction.reserveTokens }
|
|
227
233
|
: {}),
|
|
228
|
-
...(window ? { triggerTokens: window.triggerTokens } : {}),
|
|
229
234
|
...(typeof compaction.keepRecentTokens === "number"
|
|
230
235
|
? { keepRecentTokens: compaction.keepRecentTokens }
|
|
231
236
|
: {}),
|
|
232
|
-
...(
|
|
233
|
-
|
|
237
|
+
...(spec ? { thresholdTokens: spec.thresholdTokens, retainTokens: spec.retainTokens, fallback: spec.fallback } : {}),
|
|
238
|
+
...(spec && spec.diagnostics.length > 0
|
|
239
|
+
? { diagnostic: spec.diagnostics.join(",") }
|
|
234
240
|
: {}),
|
|
235
241
|
};
|
|
236
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* Settings for harness runs that build a Pi session without a Console window.
|
|
245
|
+
*
|
|
246
|
+
* DSH's policy needs a context window, which a harness-owned session does not
|
|
247
|
+
* know up front, so this keeps Pi's defaults and only honours the mode switch.
|
|
248
|
+
*/
|
|
237
249
|
export function inMemoryCompactionSettings(policy) {
|
|
238
250
|
if (policy.mode === "off") {
|
|
239
251
|
return { enabled: true };
|
|
240
252
|
}
|
|
241
|
-
return {
|
|
242
|
-
enabled: true,
|
|
243
|
-
keepRecentTokens: DEFAULT_KEEP_RECENT_TOKENS,
|
|
244
|
-
...(policy.explicitReserveTokens
|
|
245
|
-
? { reserveTokens: policy.explicitReserveTokens }
|
|
246
|
-
: {}),
|
|
247
|
-
};
|
|
253
|
+
return { enabled: true };
|
|
248
254
|
}
|
|
@@ -96,25 +96,32 @@ export function createContextPressureExtension(options) {
|
|
|
96
96
|
incrementCounter(options.controller.counters, "manual");
|
|
97
97
|
}
|
|
98
98
|
/*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
99
|
+
* A THRESHOLD compaction asks the provider, because a real
|
|
100
|
+
* summary is better than the deterministic checkpoint and the
|
|
101
|
+
* request is expected to fit.
|
|
101
102
|
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
103
|
+
* An OVERFLOW compaction is different: the provider has just
|
|
104
|
+
* refused this exact context. Asking it for a summary re-sends
|
|
105
|
+
* the history it rejected, so the summary fails too. Pi's own
|
|
106
|
+
* recovery allows exactly ONE attempt (`_overflowRecoveryAttempted`)
|
|
107
|
+
* and then ends the session with "Context overflow recovery
|
|
108
|
+
* failed after one compact-and-retry attempt" — so the local
|
|
109
|
+
* checkpoint has to answer on that first call or the reader
|
|
110
|
+
* loses the conversation entirely. That is the whole point of
|
|
111
|
+
* having a fallback.
|
|
112
|
+
*
|
|
113
|
+
* `manualCheckpointFallbackArmed` still covers the case where a
|
|
114
|
+
* summary request was already attempted and rejected.
|
|
109
115
|
*/
|
|
110
|
-
const
|
|
116
|
+
const providerJustRejectedContext = reason === "overflow" && providerOverflow;
|
|
117
|
+
const useCheckpoint = options.controller.manualCheckpointFallbackArmed ||
|
|
118
|
+
providerJustRejectedContext;
|
|
111
119
|
if (!useCheckpoint) {
|
|
112
|
-
if (reason === "overflow" && providerOverflow) {
|
|
113
|
-
incrementCounter(options.controller.counters, "overflow-summary-retry");
|
|
114
|
-
options.controller.summaryRetryPending = true;
|
|
115
|
-
}
|
|
116
120
|
return undefined;
|
|
117
121
|
}
|
|
122
|
+
if (providerJustRejectedContext) {
|
|
123
|
+
incrementCounter(options.controller.counters, "overflow-local-fallback");
|
|
124
|
+
}
|
|
118
125
|
options.controller.manualCheckpointFallbackArmed = false;
|
|
119
126
|
const checkpoint = buildOverflowCheckpoint({
|
|
120
127
|
preparation: event.preparation,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { isContextOverflow, CONTEXT_OVERFLOW_PHRASES, OVERFLOW_FIXTURES, NORMALIZED_OVERFLOW_PREFIX, shouldRewriteAssistantOverflow, normalizeOverflowErrorMessage, buildGeneratedOverflowClassifierSource, } from "./overflow.js";
|
|
2
|
-
export { parseCompactionPolicy,
|
|
2
|
+
export { parseCompactionPolicy, resolveCompactSpec, piReserveTokensFor, conservativeTokenEstimate, projectPromptPressure, applyProcessCompactionOverride, inMemoryCompactionSettings, PI_DEFAULT_RESERVE_TOKENS, DEFAULT_THRESHOLD_RATIO, DEFAULT_HEADROOM_TOKENS, DEFAULT_RETAIN_RATIO, DEFAULT_RESERVED_COMPLETION_TOKENS, } from "./compaction-policy.js";
|
|
3
3
|
export { buildOverflowCheckpoint, normalizeCompactionPreparation, } from "./checkpoint.js";
|
|
4
4
|
export { deriveCompactionAccounting, readCompactionAccounting, } from "./compaction-accounting.js";
|
|
5
5
|
export { PI_TOOL_RESULT_PRUNE_MARKER, DEFAULT_PI_TOOL_RESULT_PRUNE_CONFIG, resolvePiToolResultPruneConfig, parsePiToolResultPruneConfig, piCodePointLength, prunePiToolResultMessages, } from "./tool-result-pruner.js";
|
|
@@ -3,7 +3,9 @@ export function emptyContextPressureCounters() {
|
|
|
3
3
|
prePromptThreshold: 0,
|
|
4
4
|
overflow: 0,
|
|
5
5
|
overflowSummaryRetry: 0,
|
|
6
|
+
overflowLocalFallback: 0,
|
|
6
7
|
manual: 0,
|
|
8
|
+
compactionRetry: 0,
|
|
7
9
|
wireCompression: 0,
|
|
8
10
|
failOpen: 0,
|
|
9
11
|
usageUnavailable: 0,
|
|
@@ -29,9 +31,15 @@ export function incrementCounter(counters, reason, amount = 1) {
|
|
|
29
31
|
case "overflow-summary-retry":
|
|
30
32
|
counters.overflowSummaryRetry += amount;
|
|
31
33
|
break;
|
|
34
|
+
case "overflow-local-fallback":
|
|
35
|
+
counters.overflowLocalFallback += amount;
|
|
36
|
+
break;
|
|
32
37
|
case "manual":
|
|
33
38
|
counters.manual += amount;
|
|
34
39
|
break;
|
|
40
|
+
case "compaction-retry":
|
|
41
|
+
counters.compactionRetry += amount;
|
|
42
|
+
break;
|
|
35
43
|
case "wire-compression":
|
|
36
44
|
counters.wireCompression += amount;
|
|
37
45
|
break;
|
|
@@ -53,7 +61,9 @@ export function projectSafeTelemetry(counters) {
|
|
|
53
61
|
prePromptThreshold: counters.prePromptThreshold,
|
|
54
62
|
overflow: counters.overflow,
|
|
55
63
|
overflowSummaryRetry: counters.overflowSummaryRetry,
|
|
64
|
+
overflowLocalFallback: counters.overflowLocalFallback,
|
|
56
65
|
manual: counters.manual,
|
|
66
|
+
compactionRetry: counters.compactionRetry,
|
|
57
67
|
wireCompression: counters.wireCompression,
|
|
58
68
|
failOpen: counters.failOpen,
|
|
59
69
|
tokensSavedEstimate: counters.tokensSavedEstimate,
|
|
@@ -404,8 +404,8 @@ const taskConfigObjectSchema = z.object({
|
|
|
404
404
|
* default; raise to 2-3 for more tolerance of transient verify failures). */
|
|
405
405
|
frontendRecovery: z
|
|
406
406
|
.object({
|
|
407
|
-
/**
|
|
408
|
-
maxProviderRequests: z.number().int().positive().optional(),
|
|
407
|
+
/** Task-lifetime request quota; null explicitly disables admission, omitted defaults to 1024. */
|
|
408
|
+
maxProviderRequests: z.number().int().positive().nullable().optional(),
|
|
409
409
|
maxContinuations: z
|
|
410
410
|
.number()
|
|
411
411
|
.int()
|
|
@@ -781,7 +781,7 @@ async function prepareTaskSourceInExecution(input) {
|
|
|
781
781
|
// A previously ordinary intake may only become frontend after deterministic
|
|
782
782
|
// source classification. Admit its observed requests before further work;
|
|
783
783
|
// dry-run must remain read-only.
|
|
784
|
-
if (input.mode === "apply") {
|
|
784
|
+
if (input.mode === "apply" && existingTaskConfig?.frontendRecovery?.maxProviderRequests !== null) {
|
|
785
785
|
await openTaskSourceProviderBudget({ repoRoot, taskId, maxProviderRequests: existingTaskConfig?.frontendRecovery?.maxProviderRequests ?? 1024 });
|
|
786
786
|
}
|
|
787
787
|
// An imported PRD is materialized under sourceIntegrity rather than copied
|
|
@@ -601,7 +601,7 @@ export async function runSemanticIntake(input) {
|
|
|
601
601
|
const result = await observeSourceExecution({ repoRoot: input.repoRoot, taskId: input.taskId, taskKind: input.flags.taskKind ?? input.taskKind, phase: "semantic-intake", inputIdentity: { documents: input.documents, flags: input.flags, title: input.title } }, () => runSemanticIntakeInExecution(input));
|
|
602
602
|
// Classification happens after the request. Admit only complete observed
|
|
603
603
|
// usage, after its source execution has closed, if the result selects frontend.
|
|
604
|
-
if (result.ok && result.draft.taskKind === "frontend-implementation" && input.fixtureAssistantText === undefined) {
|
|
604
|
+
if (result.ok && result.draft.taskKind === "frontend-implementation" && input.fixtureAssistantText === undefined && config.frontendRecovery?.maxProviderRequests !== null) {
|
|
605
605
|
await openTaskSourceProviderBudget({ ...input, maxProviderRequests: config.frontendRecovery?.maxProviderRequests ?? 1024 });
|
|
606
606
|
}
|
|
607
607
|
return result;
|
|
@@ -681,7 +681,7 @@ async function runSemanticIntakeInExecution(input) {
|
|
|
681
681
|
}
|
|
682
682
|
const config = await loadTaskConfig(input.repoRoot, input.taskId);
|
|
683
683
|
const taskKind = input.flags.taskKind ?? input.taskKind ?? config.taskKind;
|
|
684
|
-
const reserveProviderRequest = taskKind === "frontend-implementation" ? await openTaskSourceProviderBudget({
|
|
684
|
+
const reserveProviderRequest = taskKind === "frontend-implementation" && config.frontendRecovery?.maxProviderRequests !== null ? await openTaskSourceProviderBudget({
|
|
685
685
|
repoRoot: input.repoRoot, taskId: input.taskId,
|
|
686
686
|
maxProviderRequests: config.frontendRecovery?.maxProviderRequests ?? 1024,
|
|
687
687
|
}) : undefined;
|
|
@@ -435,6 +435,7 @@ export async function resolveProductionSourceFidelityPi(input) {
|
|
|
435
435
|
if (effectiveTaskKind !== SOURCE_FIDELITY_TASK_KIND)
|
|
436
436
|
return undefined;
|
|
437
437
|
const config = await loadTaskConfig(input.repoRoot, input.taskId);
|
|
438
|
-
const reserveProviderRequest =
|
|
438
|
+
const reserveProviderRequest = config.frontendRecovery?.maxProviderRequests === null ? undefined
|
|
439
|
+
: await openTaskSourceProviderBudget({ ...input, maxProviderRequests: config.frontendRecovery?.maxProviderRequests ?? 1024 });
|
|
439
440
|
return createProductionSourceFidelityPi({ repoRoot: input.repoRoot, taskId: input.taskId, reserveProviderRequest });
|
|
440
441
|
}
|
|
@@ -11,7 +11,13 @@ function asRecord(value) {
|
|
|
11
11
|
function readString(value) {
|
|
12
12
|
return typeof value === "string" ? value : undefined;
|
|
13
13
|
}
|
|
14
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Parse a persisted/SSE content array.
|
|
16
|
+
*
|
|
17
|
+
* Recognised blocks keep their typed shape; anything else is preserved as an
|
|
18
|
+
* `unknown` block rather than dropped, so a newer provider block type surfaces
|
|
19
|
+
* as a visible placeholder instead of vanishing from the message.
|
|
20
|
+
*/
|
|
15
21
|
export function parseAssistantContent(value) {
|
|
16
22
|
if (!Array.isArray(value))
|
|
17
23
|
return undefined;
|
|
@@ -44,9 +50,17 @@ export function parseAssistantContent(value) {
|
|
|
44
50
|
}
|
|
45
51
|
if (type === "text" || type === "output_text" || type === "") {
|
|
46
52
|
const text = readString(rec.text);
|
|
47
|
-
if (text !== undefined)
|
|
53
|
+
if (text !== undefined) {
|
|
48
54
|
blocks.push({ type: "text", text });
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
49
57
|
}
|
|
58
|
+
// Unrecognised: keep it visible instead of dropping it.
|
|
59
|
+
blocks.push({
|
|
60
|
+
type: "unknown",
|
|
61
|
+
blockType: type === "" ? "unknown" : type,
|
|
62
|
+
data: item,
|
|
63
|
+
});
|
|
50
64
|
}
|
|
51
65
|
return blocks;
|
|
52
66
|
}
|
|
@@ -98,7 +112,11 @@ export function isSemanticallyEmptyAssistantCompletion(message) {
|
|
|
98
112
|
return false;
|
|
99
113
|
const blocks = extractAssistantContentBlocks(message);
|
|
100
114
|
return (!blocks.some((block) => block.type === "text" && block.text.trim() !== "") &&
|
|
101
|
-
!blocks.some((block) => block.type === "toolCall")
|
|
115
|
+
!blocks.some((block) => block.type === "toolCall") &&
|
|
116
|
+
// An unknown block is still content the provider chose to send. Treating
|
|
117
|
+
// it as empty would trigger the empty-completion recovery and replace a
|
|
118
|
+
// real response with a retry prompt.
|
|
119
|
+
!blocks.some((block) => block.type === "unknown"));
|
|
102
120
|
}
|
|
103
121
|
export function isEmptyThinkingBlock(block, options = {}) {
|
|
104
122
|
return (block.type === "thinking" &&
|
|
@@ -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 {
|
|
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:
|
|
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
|
-
|
|
751
|
-
|
|
752
|
-
|
|
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;
|