@tea-agent/loop-agent 0.51.0-next.1 → 0.51.0-next.3
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 +33 -1
- package/dist/application/task-lifecycle/advance.js +6 -0
- package/dist/build-stamp.json +3 -3
- package/dist/commands/init.js +12 -3
- package/dist/executors/dag-pi/plan/facts.js +18 -4
- package/dist/executors/dag-pi/plan/record-tools.js +34 -3
- package/dist/executors/dag-pi/sessions/scout-parallel.js +11 -2
- package/dist/executors/dag-pi/sessions/segmented-plan.js +170 -16
- package/dist/executors/dag-pi/tools/contract-read-tool.js +34 -0
- package/dist/executors/dag-pi/tools/scout-evidence-tools.js +9 -7
- package/dist/executors/dag-pi-executor.js +82 -82
- package/dist/shared/pi-context-pressure/checkpoint.js +22 -4
- package/dist/shared/pi-context-pressure/compaction-policy.js +5 -1
- package/dist/shared/pi-context-pressure/extension.js +64 -5
- package/dist/shared/pi-context-pressure/sift-bridge.js +2 -1
- package/dist/shared/pi-context-pressure/telemetry.js +4 -0
- package/dist/shared/pi-context-pressure/tool-result-pruner.js +8 -3
- package/dist/task/source-prepare/completeness.js +2 -2
- package/dist/task/source-prepare/diagnostic.js +76 -0
- package/dist/task/source-prepare/ledger-reconciliation.js +65 -9
- package/dist/task/source-prepare/ledger-review.js +18 -2
- package/dist/task/source-prepare/ledger.js +3 -1
- package/dist/task/source-prepare/prepare.js +23 -3
- package/dist/task/source-prepare/source-fidelity-pi.js +12 -1
- package/dist/task/source-prepare/types.js +1 -1
- package/dist/worker/console/chat/chat-event-projection.js +13 -0
- package/dist/worker/console/chat/chat-event-store.js +1 -0
- package/dist/worker/console/chat/compaction-errors.js +1 -1
- package/dist/worker/console/chat/context-accounting.js +58 -0
- package/dist/worker/console/chat/context-insights.js +131 -22
- package/dist/worker/console/chat/context-usage.js +57 -1
- package/dist/worker/console/chat/pi-runtime/context-edit.js +91 -0
- package/dist/worker/console/chat/pi-runtime.js +36 -3
- package/dist/worker/console/chat/routes.js +3 -0
- package/dist/worker/console/chat/terminal-routes.js +12 -0
- package/dist/worker/console/chat/terminal-sessions.js +6 -0
- package/dist/worker/console/chat/vcp-prompt.js +28 -15
- package/dist/worker/console/recovery-error-copy.js +4 -1
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DUtUeeEa.js → abnfDiagram-N423BO3Z-GerMJfMU.js} +1 -1
- package/dist/worker/console/static/assets/{arc-Cs0DSwTY.js → arc-DHRoAcBA.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-C80FSNgl.js → architectureDiagram-T3A2C74G-Bna7kqEi.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DFgOZUzn.js → blockDiagram-VBNYF7ZC-B8yw7WTX.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-CB9nkTjT.js → c4Diagram-5PPSVZJV-BaUWiyqi.js} +1 -1
- package/dist/worker/console/static/assets/channel-CLhtAowh.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DbjpoOrh.js → chunk-2GRJ4B5K-D4iZ2ZNv.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BsWVWnWY.js → chunk-2Q5K7J3B-BtQpibwB.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BwwP_1AG.js → chunk-5RXB4S5H-ez-kfSyS.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DDEzW9MV.js → chunk-5VM5RSS4-6L4-OV-3.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D-fLZDni.js → chunk-6Q2QTUOP-CPUweABC.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DY9q3jMo.js → chunk-GF5L2VYU-6DTw-5Ov.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-rkUPkzPh.js → chunk-JWPE2WC7-DFAS-DH8.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Ci9ZksX4.js → chunk-KBJHAD2P-Du7LoER5.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DKU-3Ef6.js → chunk-RYQCIY6F-D9UugPlg.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-A-xOwXvl.js → chunk-XXDRQBXY-BLh5yptc.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DB7nfjpK.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DB7nfjpK.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Bfs1rphL.js → cose-bilkent-JH36ORCC-DjmHXa8h.js} +1 -1
- package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BTlXtGR2.js → cynefin-VYW2F7L2-D5jbf1gi.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-D8c9vCCr.js → cynefinDiagram-MW4NZA55-BudjeLTi.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B-e-tfgY.js → dagre-VZM6K2ZE-6YP-wMO0.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-CG_5dIVJ.js → diagram-7IWD3JNH-CA3LtUAB.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmP40HmK.js → diagram-B4RE2ZJO-BAjJeYaD.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-RFt8vi9Y.js → diagram-LBJQPF4R-Dh4zb-ds.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-CM5Sb2jB.js → diagram-Q27KOJAE-aMKj_Gkp.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-Bm4zh0WJ.js → diagram-UB23O5K3-D_0_rqQ6.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-b3GekSN4.js → ebnfDiagram-BXEA7PRR--C9HfGgB.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CFZh4C_o.js → erDiagram-JOGREHBK-BuqX0vmt.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CzxniD3z.js → flowDiagram-UKHOOZJN-IneEK8zO.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Czp6xUXj.js → ganttDiagram-PKOTCBZU-DK2RiNlb.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-B66oX4sn.js → gitGraphDiagram-DS77QQ5N-CuN5z0rP.js} +1 -1
- package/dist/worker/console/static/assets/{index-BVMJjujb.css → index-CzfumEW1.css} +1 -1
- package/dist/worker/console/static/assets/{index-Bq_vMDO3.js → index-DS6dteCl.js} +159 -147
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-rTveEtft.js → infoDiagram-6WML65LV-B6enpqSl.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-N2jiPnrD.js → ishikawaDiagram-WSZJBQD7-DepH_7eq.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DtnLwtAE.js → journeyDiagram-NVQOT4AX-BftlRwcR.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-t9D_2QMN.js → kanban-definition-27J2QSJJ-CEIZMo9g.js} +1 -1
- package/dist/worker/console/static/assets/{linear-BP6ZG0tB.js → linear-DkgtGbsw.js} +1 -1
- package/dist/worker/console/static/assets/{mermaid.core-Cc5_ZtUy.js → mermaid.core-CIMKKPgL.js} +5 -5
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zztwmHj8.js → mindmap-definition-FAOFIHXS-dzbp1VuW.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CmXQOyPH.js → pegDiagram-VL7TDLO6-C5b5i7KO.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BodwfpEp.js → pieDiagram-7S7Q4E2Y-Ugdko1lm.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DIgybsTM.js → quadrantDiagram-CIZ2JOQS-B2s1OZu8.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CZb_4Cv2.js → railroadDiagram-AXF67PYL-BVafp-Z6.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BvRNauBA.js → requirementDiagram-LRYGKXZP-BVxBjdbs.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BQ30kRWi.js → sankeyDiagram-W5VNT64P-CorSImxl.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-B7sGR3r3.js → sequenceDiagram-SI44F4Z6-eVj3geQV.js} +1 -1
- package/dist/worker/console/static/assets/{sheet-workbook-CK8pzw-q.js → sheet-workbook-DNnJDCal.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-1HZrTeyl.js → sizeCapture-X5ZJPWSS-OQWfzgrL.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-BKCXlJRS.js → stateDiagram-OKZ733FA-DJr_pPmG.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cr-50jJB.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BhT8u6Vm.js → swimlanes-SLNWSIFB-CQG0Q9vK.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-kZpEmem6.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Dnczuw3j.js → timeline-definition-Z64GVDOM-DxWuWIZ5.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-PgJCj-16.js → vennDiagram-T6HMQDX7-BJt03ecs.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BjuszbFn.js → wardleyDiagram-T6FBY63Y-BB3rPfNJ.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dhtjuxrn.js → xychartDiagram-ELKLHX3M-aVR9TCu0.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +99 -16
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +27 -5
- package/dist/worker/console/static-src/operator-chat/vcp-fonts.js +1 -6
- package/dist/worker/console/workspace-context.js +56 -1
- package/dist/worker/observe/static/dag-history-labels.js +2 -0
- package/dist/worker/observe/static/views/dag.js +28 -0
- package/dist/workflows/dag/frontend-durable-tools.js +5 -2
- package/dist/workflows/dag/frontend-implementation-contract.js +19 -6
- package/dist/workflows/dag/frontend-recovery-run.js +20 -1
- package/dist/workflows/dag/frontend-review-scopes.js +2 -2
- package/dist/workflows/dag/frontend-session-budget.js +1 -1
- package/dist/workflows/dag/frontend-writer-baseline-guard.js +11 -5
- package/dist/workflows/dag/hybrid/templates/frontend.js +35 -5
- package/dist/workflows/dag/prompt.js +8 -2
- package/dist/workflows/dag/rerun-plan.js +50 -3
- package/dist/workflows/dag/rerun-run.js +4 -0
- package/dist/workflows/dag/runner.js +11 -0
- package/package.json +6 -3
- package/dist/worker/console/static/assets/channel-BddnaJc4.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CqfGeesl.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CqfGeesl.js +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DzDcqZJM.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DgnnY3K8.js +0 -8
- package/dist/worker/console/static/vcp/fonts/Lanxi-GreatVibes.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-MaShanZheng.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-/347/202/271/351/273/221.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-/351/235/231/351/273/221/350/266/205/347/273/206.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-/351/261/274/345/260/276/350/241/214/344/271/246.woff2 +0 -0
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* so it works for idle and restored sessions alike.
|
|
19
19
|
*/
|
|
20
20
|
import { conservativeTokenEstimate } from "../../../shared/pi-context-pressure/compaction-policy.js";
|
|
21
|
+
import { readPruneAccounting, reclaimedAmount, } from "./context-accounting.js";
|
|
21
22
|
/** Fixed-density token estimate for preview text (chars → tokens). */
|
|
22
23
|
export function estimateTokensFromText(text) {
|
|
23
24
|
if (!text)
|
|
@@ -253,9 +254,21 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
253
254
|
const browserMessages = [];
|
|
254
255
|
const browserInjected = [];
|
|
255
256
|
const browserToolResults = [];
|
|
257
|
+
// Keep an immutable-by-retention history separate from the live surface. A
|
|
258
|
+
// prune removes a node from the next request, but it must remain visible in
|
|
259
|
+
// every historical step that predates the removal (dsh-context's `gone`
|
|
260
|
+
// boundary semantics).
|
|
261
|
+
const historyMessages = [];
|
|
262
|
+
const historyInjected = [];
|
|
263
|
+
const historyToolResults = [];
|
|
264
|
+
const archivedElements = [];
|
|
265
|
+
const removedAtBySeq = new Map();
|
|
256
266
|
const liveNodes = [];
|
|
267
|
+
const pendingShadow = new Map();
|
|
268
|
+
const pruneEventsById = new Map();
|
|
269
|
+
const seenReplacementIds = new Set();
|
|
257
270
|
/** Remove the ledger nodes whose seq the removal claims; deduct slices and browser rows. */
|
|
258
|
-
function claimNodes(claimed) {
|
|
271
|
+
function claimNodes(claimed, removedAtSeq, pruneId, replacementId) {
|
|
259
272
|
if (claimed.size === 0)
|
|
260
273
|
return [];
|
|
261
274
|
const removedIds = [];
|
|
@@ -266,6 +279,14 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
266
279
|
slice.tokens = Math.max(0, slice.tokens - node.tokens);
|
|
267
280
|
slice.items = Math.max(0, slice.items - 1);
|
|
268
281
|
removedIds.push(node.element.id);
|
|
282
|
+
if (removedAtSeq !== undefined)
|
|
283
|
+
removedAtBySeq.set(node.seq, removedAtSeq);
|
|
284
|
+
archivedElements.push({
|
|
285
|
+
...node.element,
|
|
286
|
+
...(removedAtSeq === undefined ? {} : { removedAtSeq }),
|
|
287
|
+
...(pruneId === undefined ? {} : { pruneId }),
|
|
288
|
+
...(replacementId === undefined ? {} : { replacementId }),
|
|
289
|
+
});
|
|
269
290
|
}
|
|
270
291
|
else {
|
|
271
292
|
kept.push(node);
|
|
@@ -341,6 +362,7 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
341
362
|
at: event.at,
|
|
342
363
|
};
|
|
343
364
|
browserMessages.push(element);
|
|
365
|
+
historyMessages.push(element);
|
|
344
366
|
liveNodes.push({ seq: event.seq, tokens, category: "user", element });
|
|
345
367
|
if (!turnUserBrief.has(event.turnId)) {
|
|
346
368
|
turnUserBrief.set(event.turnId, text.slice(0, 200));
|
|
@@ -375,6 +397,7 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
375
397
|
at: event.at,
|
|
376
398
|
};
|
|
377
399
|
browserMessages.push(element);
|
|
400
|
+
historyMessages.push(element);
|
|
378
401
|
liveNodes.push({ seq: event.seq, tokens, category: "assistant", element });
|
|
379
402
|
}
|
|
380
403
|
const toolsCalled = stepToolsCalled.get(event.turnId) ?? [];
|
|
@@ -445,6 +468,7 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
445
468
|
seq: event.seq,
|
|
446
469
|
at: event.at,
|
|
447
470
|
});
|
|
471
|
+
historyInjected.push(browserInjected[browserInjected.length - 1]);
|
|
448
472
|
}
|
|
449
473
|
if (toolName && atTime > 0) {
|
|
450
474
|
const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId : "";
|
|
@@ -491,6 +515,39 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
491
515
|
break;
|
|
492
516
|
}
|
|
493
517
|
case "tool_result": {
|
|
518
|
+
const replacementId = typeof data.replacementId === "string" ? data.replacementId : undefined;
|
|
519
|
+
if (replacementId) {
|
|
520
|
+
if (seenReplacementIds.has(replacementId))
|
|
521
|
+
break;
|
|
522
|
+
seenReplacementIds.add(replacementId);
|
|
523
|
+
}
|
|
524
|
+
const surfaceOp = asRecord(data.surfaceOp);
|
|
525
|
+
const replacementPruneId = typeof data.pruneId === "string" ? data.pruneId : undefined;
|
|
526
|
+
let claimedKey;
|
|
527
|
+
let claimed;
|
|
528
|
+
if (replacementPruneId && pendingShadow.has(replacementPruneId)) {
|
|
529
|
+
claimedKey = replacementPruneId;
|
|
530
|
+
claimed = pendingShadow.get(replacementPruneId);
|
|
531
|
+
}
|
|
532
|
+
if (claimed) {
|
|
533
|
+
const sourceSeqs = Array.isArray(data.sourceEventSeqs)
|
|
534
|
+
? data.sourceEventSeqs.filter((value) => typeof value === "number" && Number.isInteger(value) && value >= 0)
|
|
535
|
+
: [];
|
|
536
|
+
const startSeq = surfaceOp && typeof surfaceOp.startSeq === "number" ? surfaceOp.startSeq : undefined;
|
|
537
|
+
const endSeq = surfaceOp && typeof surfaceOp.endSeq === "number" ? surfaceOp.endSeq : undefined;
|
|
538
|
+
const minSeq = sourceSeqs.length > 0 ? Math.min(...sourceSeqs) : undefined;
|
|
539
|
+
const maxSeq = sourceSeqs.length > 0 ? Math.max(...sourceSeqs) : undefined;
|
|
540
|
+
const valid = surfaceOp?.op === "replace" && startSeq !== undefined && endSeq !== undefined &&
|
|
541
|
+
startSeq === minSeq && endSeq === maxSeq && sourceSeqs.length === claimed.size &&
|
|
542
|
+
new Set(sourceSeqs).size === claimed.size && sourceSeqs.every((seq) => claimed.has(seq));
|
|
543
|
+
if (valid) {
|
|
544
|
+
pendingShadow.delete(claimedKey);
|
|
545
|
+
claimNodes(claimed, event.seq, claimedKey, replacementId);
|
|
546
|
+
const pruneEvent = pruneEventsById.get(claimedKey);
|
|
547
|
+
if (pruneEvent)
|
|
548
|
+
pruneEvent.pruneStatus = "durable-completed";
|
|
549
|
+
}
|
|
550
|
+
}
|
|
494
551
|
const resultPreview = typeof data.resultPreview === "string"
|
|
495
552
|
? data.resultPreview
|
|
496
553
|
: undefined;
|
|
@@ -516,6 +573,7 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
516
573
|
at: event.at,
|
|
517
574
|
};
|
|
518
575
|
browserToolResults.push(element);
|
|
576
|
+
historyToolResults.push(element);
|
|
519
577
|
liveNodes.push({ seq: event.seq, tokens, category: "toolResults", element });
|
|
520
578
|
}
|
|
521
579
|
break;
|
|
@@ -559,9 +617,11 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
559
617
|
case "compaction_start":
|
|
560
618
|
case "compaction_end":
|
|
561
619
|
case "compact": {
|
|
562
|
-
const
|
|
563
|
-
const
|
|
564
|
-
const
|
|
620
|
+
const accounting = readPruneAccounting(data);
|
|
621
|
+
const before = accounting.tokensBefore;
|
|
622
|
+
const after = accounting.tokensAfter;
|
|
623
|
+
const reclaimedInfo = reclaimedAmount(accounting);
|
|
624
|
+
const reclaimed = reclaimedInfo.unit === "tokens" && reclaimedInfo.value !== null ? reclaimedInfo.value : null;
|
|
565
625
|
const pruned = data.pruned === true || data.kind === "prune";
|
|
566
626
|
// Only explicit ring sequence claims can update the live ledger.
|
|
567
627
|
// Pi firstKeptEntryId values are opaque entry identities, not event
|
|
@@ -571,12 +631,15 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
571
631
|
: undefined;
|
|
572
632
|
let removedIds = [];
|
|
573
633
|
let removalBasis;
|
|
574
|
-
if (explicitSeqs && explicitSeqs.length > 0) {
|
|
575
|
-
|
|
634
|
+
if (pruned && typeof data.pruneId === "string" && explicitSeqs && explicitSeqs.length > 0) {
|
|
635
|
+
pendingShadow.set(data.pruneId, new Set(explicitSeqs));
|
|
636
|
+
}
|
|
637
|
+
else if (explicitSeqs && explicitSeqs.length > 0) {
|
|
638
|
+
removedIds = claimNodes(new Set(explicitSeqs), event.seq);
|
|
576
639
|
if (removedIds.length > 0)
|
|
577
640
|
removalBasis = "seqs";
|
|
578
641
|
}
|
|
579
|
-
|
|
642
|
+
const contextEvent = {
|
|
580
643
|
seq: event.seq,
|
|
581
644
|
at: event.at,
|
|
582
645
|
turnId: event.turnId,
|
|
@@ -590,13 +653,26 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
590
653
|
tokenDelta: reclaimed,
|
|
591
654
|
...(before !== undefined ? { tokensBefore: before } : {}),
|
|
592
655
|
...(after !== undefined ? { tokensAfter: after } : {}),
|
|
656
|
+
...(num(data.charsBefore) !== undefined ? { charsBefore: num(data.charsBefore) } : {}),
|
|
657
|
+
...(num(data.charsAfter) !== undefined ? { charsAfter: num(data.charsAfter) } : {}),
|
|
658
|
+
...(accounting.shadowedTokenCount !== undefined ? { shadowedTokenCount: accounting.shadowedTokenCount } : {}),
|
|
659
|
+
...(accounting.replacementTokenCount !== undefined ? { replacementTokenCount: accounting.replacementTokenCount } : {}),
|
|
660
|
+
...(accounting.netTokensFreed !== undefined ? { netTokensFreed: accounting.netTokensFreed } : {}),
|
|
661
|
+
...(accounting.accounting !== undefined
|
|
662
|
+
? { accounting: accounting.accounting }
|
|
663
|
+
: accounting.charsBefore !== undefined && accounting.charsAfter !== undefined
|
|
664
|
+
? { accounting: "estimated-chars" }
|
|
665
|
+
: {}),
|
|
593
666
|
...(Array.isArray(data.shadowedSeqs) ? { shadowedItems: data.shadowedSeqs.length } : {}),
|
|
594
667
|
...(typeof data.reason === "string" ? { reason: data.reason } : {}),
|
|
595
|
-
...(pruned ? { pruned: true } : {}),
|
|
668
|
+
...(pruned ? { pruned: true, pruneStatus: "durable-pending" } : {}),
|
|
596
669
|
...(removedIds.length > 0 ? { removedIds } : {}),
|
|
597
670
|
...(removalBasis !== undefined ? { removalBasis } : {}),
|
|
598
671
|
detail: boundedText(asRecord(data.details)?.text, 300),
|
|
599
|
-
}
|
|
672
|
+
};
|
|
673
|
+
contextEvents.push(contextEvent);
|
|
674
|
+
if (pruned && typeof data.pruneId === "string")
|
|
675
|
+
pruneEventsById.set(data.pruneId, contextEvent);
|
|
600
676
|
const lastStep = trend.at(-1);
|
|
601
677
|
if (lastStep && event.kind !== "compaction_start") {
|
|
602
678
|
lastStep.eventMark = pruned ? "prune" : "compact";
|
|
@@ -607,6 +683,15 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
607
683
|
break;
|
|
608
684
|
}
|
|
609
685
|
}
|
|
686
|
+
for (const [pruneId, pruneEvent] of pruneEventsById) {
|
|
687
|
+
if (pendingShadow.has(pruneId))
|
|
688
|
+
pruneEvent.pruneStatus = "durable-unresolved";
|
|
689
|
+
}
|
|
690
|
+
for (const pruneEvent of contextEvents) {
|
|
691
|
+
if (pruneEvent.kind === "prune" && pruneEvent.pruneStatus === "durable-pending") {
|
|
692
|
+
pruneEvent.pruneStatus = "durable-unresolved";
|
|
693
|
+
}
|
|
694
|
+
}
|
|
610
695
|
composition.totalTokens = composition.slices.reduce((sum, slice) => sum + slice.tokens, 0);
|
|
611
696
|
composition.contextWindow = contextWindow;
|
|
612
697
|
composition.providerTotal = providerTotal;
|
|
@@ -650,9 +735,15 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
650
735
|
}
|
|
651
736
|
// --- Browser snapshots: live + one per trend step (rolling elements) ---
|
|
652
737
|
const browserSteps = [];
|
|
653
|
-
const
|
|
654
|
-
|
|
655
|
-
|
|
738
|
+
const bounded = (elements) => ({
|
|
739
|
+
elements: capElements(elements),
|
|
740
|
+
missing: Math.max(0, elements.length - ELEMENT_LIST_CAP),
|
|
741
|
+
});
|
|
742
|
+
const liveMessages = bounded(browserMessages);
|
|
743
|
+
const liveInjected = bounded(browserInjected);
|
|
744
|
+
const liveToolResults = bounded(browserToolResults);
|
|
745
|
+
const liveArchive = bounded(archivedElements);
|
|
746
|
+
const liveMissing = liveMessages.missing + liveInjected.missing + liveToolResults.missing + liveArchive.missing;
|
|
656
747
|
const liveCategories = [];
|
|
657
748
|
const pushCategory = (category, elements) => {
|
|
658
749
|
if (elements.length === 0)
|
|
@@ -674,14 +765,17 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
674
765
|
}]
|
|
675
766
|
: []);
|
|
676
767
|
pushCategory("tools", browserTools);
|
|
677
|
-
pushCategory("messages", liveMessages);
|
|
678
|
-
pushCategory("injected", liveInjected);
|
|
679
|
-
pushCategory("toolResults", liveToolResults);
|
|
768
|
+
pushCategory("messages", liveMessages.elements);
|
|
769
|
+
pushCategory("injected", liveInjected.elements);
|
|
770
|
+
pushCategory("toolResults", liveToolResults.elements);
|
|
680
771
|
pushCategory("skills", browserSkills);
|
|
681
772
|
browserSteps.push({
|
|
682
773
|
stepId: "live",
|
|
683
774
|
categories: liveCategories,
|
|
684
775
|
totalTokens: liveCategories.reduce((sum, c) => sum + c.totalTokens, 0),
|
|
776
|
+
archive: liveArchive.elements,
|
|
777
|
+
coverage: liveMissing > 0 ? "approximate" : "complete",
|
|
778
|
+
missingItems: liveMissing,
|
|
685
779
|
});
|
|
686
780
|
// Retained steps: rebuild each step's makeup from cumulative snapshots at
|
|
687
781
|
// that point in the ring (bounded to the most recent steps).
|
|
@@ -690,10 +784,20 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
690
784
|
for (let i = 0; i < recentTrend.length; i++) {
|
|
691
785
|
const step = recentTrend[i];
|
|
692
786
|
const cutoffSeq = step.seq;
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
const
|
|
787
|
+
// Historical surfaces are reconstructed from the full ledger. A node is
|
|
788
|
+
// visible before its removal boundary and absent afterwards; using the
|
|
789
|
+
// current live arrays here would incorrectly erase pre-prune history.
|
|
790
|
+
const upto = (list) => bounded(list.filter((e) => {
|
|
791
|
+
if (e.seq > cutoffSeq)
|
|
792
|
+
return false;
|
|
793
|
+
const removedAt = removedAtBySeq.get(e.seq);
|
|
794
|
+
return removedAt === undefined || removedAt > cutoffSeq;
|
|
795
|
+
}));
|
|
796
|
+
const messagesAt = upto(historyMessages);
|
|
797
|
+
const injectedAt = upto(historyInjected);
|
|
798
|
+
const resultsAt = upto(historyToolResults);
|
|
799
|
+
const archiveAt = bounded(archivedElements.filter((element) => element.removedAtSeq === undefined || element.removedAtSeq <= cutoffSeq));
|
|
800
|
+
const missingItems = messagesAt.missing + injectedAt.missing + resultsAt.missing + archiveAt.missing;
|
|
697
801
|
const categories = [];
|
|
698
802
|
const push = (category, elements) => {
|
|
699
803
|
if (elements.length === 0)
|
|
@@ -715,9 +819,9 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
715
819
|
}]
|
|
716
820
|
: []);
|
|
717
821
|
push("tools", browserTools);
|
|
718
|
-
push("messages", messagesAt);
|
|
719
|
-
push("injected", injectedAt);
|
|
720
|
-
push("toolResults", resultsAt);
|
|
822
|
+
push("messages", messagesAt.elements);
|
|
823
|
+
push("injected", injectedAt.elements);
|
|
824
|
+
push("toolResults", resultsAt.elements);
|
|
721
825
|
push("skills", browserSkills);
|
|
722
826
|
browserSteps.push({
|
|
723
827
|
stepId: String(step.index),
|
|
@@ -725,6 +829,9 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
725
829
|
at: step.at,
|
|
726
830
|
categories,
|
|
727
831
|
totalTokens: categories.reduce((sum, c) => sum + c.totalTokens, 0),
|
|
832
|
+
archive: archiveAt.elements,
|
|
833
|
+
coverage: missingItems > 0 ? "approximate" : "complete",
|
|
834
|
+
missingItems,
|
|
728
835
|
});
|
|
729
836
|
}
|
|
730
837
|
return {
|
|
@@ -743,6 +850,7 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
743
850
|
return a.path.localeCompare(b.path);
|
|
744
851
|
}),
|
|
745
852
|
browser: browserSteps,
|
|
853
|
+
browserDroppedSteps: Math.max(0, trend.length - recentTrend.length),
|
|
746
854
|
usage,
|
|
747
855
|
timing,
|
|
748
856
|
systemPromptChars: options.systemPromptChars ?? null,
|
|
@@ -753,5 +861,6 @@ export function deriveContextInsights(events, options = {}) {
|
|
|
753
861
|
tokens: t.tokens,
|
|
754
862
|
})),
|
|
755
863
|
skillInjections: options.skillInjections ?? [],
|
|
864
|
+
...(options.contextPressure ? { contextPressure: options.contextPressure } : {}),
|
|
756
865
|
};
|
|
757
866
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseAssistantContent } from "./assistant-content.js";
|
|
2
|
+
import { readPruneAccounting } from "./context-accounting.js";
|
|
2
3
|
const tokensForText = (value) => typeof value === "string" ? Math.ceil(value.length / 4) : 0;
|
|
3
4
|
function finiteCount(value) {
|
|
4
5
|
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
@@ -14,6 +15,8 @@ export function deriveChatContextUsage(events) {
|
|
|
14
15
|
let prompt;
|
|
15
16
|
const prices = new Map();
|
|
16
17
|
const beforeAssistant = new Map();
|
|
18
|
+
const pendingShadow = new Map();
|
|
19
|
+
const seenReplacementIds = new Set();
|
|
17
20
|
const seen = new Set();
|
|
18
21
|
const assistants = new Set();
|
|
19
22
|
const append = (seq, tokens) => {
|
|
@@ -52,6 +55,53 @@ export function deriveChatContextUsage(events) {
|
|
|
52
55
|
append(event.seq, tokensForText(data.argsPreview));
|
|
53
56
|
}
|
|
54
57
|
else if (event.kind === "tool_result") {
|
|
58
|
+
const replacementId = typeof data.replacementId === "string" ? data.replacementId : undefined;
|
|
59
|
+
if (replacementId) {
|
|
60
|
+
if (seenReplacementIds.has(replacementId))
|
|
61
|
+
continue;
|
|
62
|
+
seenReplacementIds.add(replacementId);
|
|
63
|
+
}
|
|
64
|
+
const surfaceOp = data.surfaceOp;
|
|
65
|
+
const pruneId = typeof data.pruneId === "string" ? data.pruneId : undefined;
|
|
66
|
+
let claimed;
|
|
67
|
+
let claimedKey;
|
|
68
|
+
if (pruneId && pendingShadow.has(pruneId)) {
|
|
69
|
+
claimedKey = pruneId;
|
|
70
|
+
claimed = pendingShadow.get(pruneId);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
const first = pendingShadow.entries().next();
|
|
74
|
+
if (!first.done) {
|
|
75
|
+
claimedKey = first.value[0];
|
|
76
|
+
claimed = first.value[1];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (claimed) {
|
|
80
|
+
const sourceSeqs = Array.isArray(data.sourceEventSeqs)
|
|
81
|
+
? data.sourceEventSeqs.filter((value) => typeof value === "number" && Number.isInteger(value) && value >= 0)
|
|
82
|
+
: [];
|
|
83
|
+
const startSeq = surfaceOp && typeof surfaceOp.startSeq === "number" ? surfaceOp.startSeq : undefined;
|
|
84
|
+
const endSeq = surfaceOp && typeof surfaceOp.endSeq === "number" ? surfaceOp.endSeq : undefined;
|
|
85
|
+
const minSeq = sourceSeqs.length > 0 ? Math.min(...sourceSeqs) : undefined;
|
|
86
|
+
const maxSeq = sourceSeqs.length > 0 ? Math.max(...sourceSeqs) : undefined;
|
|
87
|
+
const valid = surfaceOp?.op === "replace" && startSeq !== undefined && endSeq !== undefined &&
|
|
88
|
+
startSeq === minSeq && endSeq === maxSeq && sourceSeqs.length === claimed.length &&
|
|
89
|
+
new Set(sourceSeqs).size === claimed.length && claimed.every((seq) => sourceSeqs.includes(seq));
|
|
90
|
+
pendingShadow.delete(claimedKey);
|
|
91
|
+
if (valid) {
|
|
92
|
+
for (const seq of claimed) {
|
|
93
|
+
surface -= prices.get(seq) ?? 0;
|
|
94
|
+
prices.delete(seq);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (valid) {
|
|
98
|
+
// A valid replacement is priced as a new ordinary tool result below.
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
// dsh-context consumes the pending claim on the next surface event;
|
|
102
|
+
// malformed metadata therefore keeps the source live and appends this result.
|
|
103
|
+
}
|
|
104
|
+
}
|
|
55
105
|
append(event.seq, 8 + tokensForText(data.resultPreview));
|
|
56
106
|
}
|
|
57
107
|
else if (event.kind === "usage") {
|
|
@@ -71,7 +121,8 @@ export function deriveChatContextUsage(events) {
|
|
|
71
121
|
else if (event.kind === "compact" || event.kind === "compaction_end") {
|
|
72
122
|
if (data.status !== undefined && data.status !== "completed")
|
|
73
123
|
continue;
|
|
74
|
-
const
|
|
124
|
+
const accounting = readPruneAccounting(data);
|
|
125
|
+
const after = accounting.tokensAfter;
|
|
75
126
|
if (after !== undefined) {
|
|
76
127
|
prompt = after;
|
|
77
128
|
surface = 0;
|
|
@@ -79,6 +130,11 @@ export function deriveChatContextUsage(events) {
|
|
|
79
130
|
prices.clear();
|
|
80
131
|
}
|
|
81
132
|
else if (Array.isArray(data.shadowedSeqs)) {
|
|
133
|
+
if (data.pruned === true && typeof data.pruneId === "string") {
|
|
134
|
+
pendingShadow.set(data.pruneId, data.shadowedSeqs.filter((seq) => typeof seq === "number" && Number.isInteger(seq) && seq >= 0));
|
|
135
|
+
beforeAssistant.clear();
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
82
138
|
for (const seq of new Set(data.shadowedSeqs)) {
|
|
83
139
|
if (typeof seq !== "number")
|
|
84
140
|
continue;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
function recordOf(value) {
|
|
2
|
+
return value && typeof value === "object" ? value : undefined;
|
|
3
|
+
}
|
|
4
|
+
function sameContent(left, right) {
|
|
5
|
+
try {
|
|
6
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function entryMessage(entry) {
|
|
13
|
+
const message = recordOf(entry.message);
|
|
14
|
+
return entry.type === "message" && message?.role === "toolResult" ? message : undefined;
|
|
15
|
+
}
|
|
16
|
+
function findToolResultEntry(manager, sourceMessage) {
|
|
17
|
+
const raw = manager.getEntries?.();
|
|
18
|
+
if (!Array.isArray(raw))
|
|
19
|
+
return undefined;
|
|
20
|
+
const entries = raw;
|
|
21
|
+
const sourceToolCallId = typeof sourceMessage.toolCallId === "string"
|
|
22
|
+
? sourceMessage.toolCallId
|
|
23
|
+
: undefined;
|
|
24
|
+
const candidates = [];
|
|
25
|
+
const contentMatches = [];
|
|
26
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
27
|
+
const entry = entries[index];
|
|
28
|
+
const id = typeof entry?.id === "string" ? entry.id : undefined;
|
|
29
|
+
const message = entry ? entryMessage(entry) : undefined;
|
|
30
|
+
if (!id || !message)
|
|
31
|
+
continue;
|
|
32
|
+
if (sourceToolCallId && message.toolCallId === sourceToolCallId)
|
|
33
|
+
candidates.push({ id, message });
|
|
34
|
+
}
|
|
35
|
+
if (candidates.length === 1)
|
|
36
|
+
return candidates[0];
|
|
37
|
+
if (candidates.length > 1) {
|
|
38
|
+
const exact = candidates.filter((candidate) => sameContent(candidate.message, sourceMessage));
|
|
39
|
+
return exact.length === 1 ? exact[0] : undefined;
|
|
40
|
+
}
|
|
41
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
42
|
+
const entry = entries[index];
|
|
43
|
+
const id = typeof entry?.id === "string" ? entry.id : undefined;
|
|
44
|
+
const message = entry ? entryMessage(entry) : undefined;
|
|
45
|
+
if (!id || !message)
|
|
46
|
+
continue;
|
|
47
|
+
if (sameContent(message, sourceMessage))
|
|
48
|
+
contentMatches.push({ id, message });
|
|
49
|
+
}
|
|
50
|
+
return contentMatches.length === 1 ? contentMatches[0] : undefined;
|
|
51
|
+
}
|
|
52
|
+
function replacementContent(message) {
|
|
53
|
+
if (typeof message.content === "string")
|
|
54
|
+
return message.content;
|
|
55
|
+
return Array.isArray(message.content) ? message.content : undefined;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Build the smallest safe bridge around Pi 1.2's append-only context edits.
|
|
59
|
+
* Missing capabilities return undefined and callers keep their in-memory
|
|
60
|
+
* fail-open pruning behavior.
|
|
61
|
+
*/
|
|
62
|
+
export function createPiContextEditAdapter(manager, session) {
|
|
63
|
+
const candidate = recordOf(manager);
|
|
64
|
+
if (!candidate || typeof candidate.appendContextEdit !== "function" || typeof candidate.getEntries !== "function")
|
|
65
|
+
return undefined;
|
|
66
|
+
if (typeof session.refreshContext !== "function")
|
|
67
|
+
return undefined;
|
|
68
|
+
const appendContextEdit = (targetId, replacement) => {
|
|
69
|
+
const result = candidate.appendContextEdit(targetId, replacement);
|
|
70
|
+
if (typeof result !== "string" || !result)
|
|
71
|
+
throw new Error("Pi appendContextEdit returned an invalid entry id");
|
|
72
|
+
return result;
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
appendContextEdit,
|
|
76
|
+
refreshContext: () => session.refreshContext(),
|
|
77
|
+
replaceToolResult: (sourceMessage, replacementMessage) => {
|
|
78
|
+
const source = findToolResultEntry(candidate, sourceMessage);
|
|
79
|
+
const content = replacementContent(replacementMessage);
|
|
80
|
+
if (!source || content === undefined)
|
|
81
|
+
return undefined;
|
|
82
|
+
const contextEditEntryId = appendContextEdit(source.id, { content });
|
|
83
|
+
session.refreshContext();
|
|
84
|
+
return {
|
|
85
|
+
sourcePiEntryId: source.id,
|
|
86
|
+
contextEditEntryId,
|
|
87
|
+
...(typeof source.message.toolCallId === "string" ? { toolCallId: source.message.toolCallId } : {}),
|
|
88
|
+
};
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -50,7 +50,7 @@ import { applySkillAutoInvocationPreferences, loadResourcePreferences, } from ".
|
|
|
50
50
|
import { buildPiModeLoopIsolationOptions } from "./pi-mode-loop-isolation.js";
|
|
51
51
|
import { applyWorkflowIntakeSkillAuthority, resolveWorkflowIntakeCapability, verifyWorkflowIntakeSkillInventory, workflowIntakeMaterializationFailure, } from "./workflow-intake-skills.js";
|
|
52
52
|
import { applyProcessRetryOverride, } from "../../../shared/pi-retry-settings.js";
|
|
53
|
-
import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parsePiToolResultPruneConfig, parseSiftBridgeConfig, projectPromptPressure, deriveEffectiveWindow, projectSafeTelemetry, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
|
|
53
|
+
import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parsePiToolResultPruneConfig, parseSiftBridgeConfig, projectPromptPressure, deriveEffectiveWindow, projectSafeTelemetry, isContextOverflow, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
|
|
54
54
|
import { incrementCounter as incrementPressureCounter } from "../../../shared/pi-context-pressure/telemetry.js";
|
|
55
55
|
import { resolveDefaultChatModel, resolveLowChatModel, } from "./model-resolver.js";
|
|
56
56
|
import { filterActiveInterviewTools } from "../interview/tools.js";
|
|
@@ -70,6 +70,7 @@ import { buildScheduledGoalTools } from "./pi-runtime/custom-tools/scheduled-goa
|
|
|
70
70
|
import { WorkflowToolExposure, configuredToolExposure, isScheduledBookingTurn, pinScheduledBookingTurnTools, } from "./pi-runtime/progressive-tools.js";
|
|
71
71
|
import { buildCustomOperatorTools } from "./pi-runtime/custom-tools/operator-tools.js";
|
|
72
72
|
import { buildBrowserTools } from "./pi-runtime/custom-tools/browser-tools.js";
|
|
73
|
+
import { createPiContextEditAdapter } from "./pi-runtime/context-edit.js";
|
|
73
74
|
import { activeBrowserTools, BROWSER_AUTOMATION_DISABLED, browserAutomationEnabled, browserGroupForTarget, BROWSER_TOOL_GROUPS, configuredBrowserAutomation, defaultBrowserExposureForSession, isBrowserToolName, readBrowserExposureEntry, writeBrowserExposureEntry, } from "./browser-exposure.js";
|
|
74
75
|
import { buildAskUserQuestionTool } from "./pi-runtime/custom-tools/ask-user-question.js";
|
|
75
76
|
import { buildTodoWriteTool } from "./pi-runtime/custom-tools/todo-write.js";
|
|
@@ -536,6 +537,8 @@ export class ConsolePiRuntime {
|
|
|
536
537
|
disposeAllPromise;
|
|
537
538
|
/** Synchronous prompt ownership per session (admission before first await). */
|
|
538
539
|
promptOwners = new Set();
|
|
540
|
+
/** Current durable turn identity exposed to synchronous context-hook callbacks. */
|
|
541
|
+
activeTurnIds = new Map();
|
|
539
542
|
/** Steering requests accepted by the SDK but not yet consumed into Pi context. */
|
|
540
543
|
pendingSteering = new Map();
|
|
541
544
|
/** At most one detached automatic-title task per durable Console session. */
|
|
@@ -836,6 +839,14 @@ export class ConsolePiRuntime {
|
|
|
836
839
|
controller: this.getCompactionController(sessionId),
|
|
837
840
|
sift,
|
|
838
841
|
normalizeTransientProviderErrors: true,
|
|
842
|
+
contextEdit: () => this.sessions.get(sessionId)?.contextEdit,
|
|
843
|
+
onPrune: (input) => {
|
|
844
|
+
this.options.onDurablePrune?.({
|
|
845
|
+
sessionId,
|
|
846
|
+
turnId: this.activeTurnIds.get(sessionId),
|
|
847
|
+
...input,
|
|
848
|
+
});
|
|
849
|
+
},
|
|
839
850
|
...(pruneSettings.enabled && policy.mode !== "off" ? { prune: pruneSettings.config } : {}),
|
|
840
851
|
});
|
|
841
852
|
}
|
|
@@ -846,6 +857,10 @@ export class ConsolePiRuntime {
|
|
|
846
857
|
applyProcessCompactionOverride(manager, {
|
|
847
858
|
policy: parseCompactionPolicy(),
|
|
848
859
|
...(typeof window === "number" ? { contextWindow: window } : {}),
|
|
860
|
+
// Console should allow an explicit compact as soon as there is a
|
|
861
|
+
// previous turn. Pi's 20k default is a useful retention policy for
|
|
862
|
+
// the TUI, but becomes a hard "session too small" gate here.
|
|
863
|
+
keepRecentTokens: 0,
|
|
849
864
|
});
|
|
850
865
|
void sessionId;
|
|
851
866
|
}
|
|
@@ -1245,6 +1260,9 @@ export class ConsolePiRuntime {
|
|
|
1245
1260
|
...(resolvedModel ? { model: resolvedModel } : {}),
|
|
1246
1261
|
});
|
|
1247
1262
|
liveSession = session;
|
|
1263
|
+
const contextEdit = createPiContextEditAdapter(init.sessionManager, session);
|
|
1264
|
+
if (contextEdit)
|
|
1265
|
+
session.contextEdit = contextEdit;
|
|
1248
1266
|
if (aborted()) {
|
|
1249
1267
|
abandon();
|
|
1250
1268
|
await disposeSessionExtensions(session).catch(() => undefined);
|
|
@@ -2789,6 +2807,8 @@ export class ConsolePiRuntime {
|
|
|
2789
2807
|
throw new Error("CHAT_TURN_ACTIVE");
|
|
2790
2808
|
}
|
|
2791
2809
|
this.promptOwners.add(sessionId);
|
|
2810
|
+
if (options?.turnId)
|
|
2811
|
+
this.activeTurnIds.set(sessionId, options.turnId);
|
|
2792
2812
|
let unsub;
|
|
2793
2813
|
let abortPromise;
|
|
2794
2814
|
let initialUserMessageStarted = false;
|
|
@@ -3274,6 +3294,7 @@ export class ConsolePiRuntime {
|
|
|
3274
3294
|
// identities into a later prompt.
|
|
3275
3295
|
this.pendingSteering.delete(sessionId);
|
|
3276
3296
|
this.turnEventForwarders.delete(sessionId);
|
|
3297
|
+
this.activeTurnIds.delete(sessionId);
|
|
3277
3298
|
this.promptOwners.delete(sessionId);
|
|
3278
3299
|
}
|
|
3279
3300
|
}
|
|
@@ -3407,8 +3428,20 @@ export class ConsolePiRuntime {
|
|
|
3407
3428
|
if (typeof session.compact !== "function")
|
|
3408
3429
|
throw new Error("COMPACTION_UNSUPPORTED");
|
|
3409
3430
|
incrementPressureCounter(this.getCompactionController(sessionId).counters, "manual");
|
|
3410
|
-
const
|
|
3411
|
-
|
|
3431
|
+
const controller = this.getCompactionController(sessionId);
|
|
3432
|
+
try {
|
|
3433
|
+
const result = await session.compact(customInstructions);
|
|
3434
|
+
return projectCompactSnapshot(result ?? {});
|
|
3435
|
+
}
|
|
3436
|
+
catch (error) {
|
|
3437
|
+
// The first manual attempt uses the Provider summary. The extension
|
|
3438
|
+
// arms this fallback only after Pi reports a context-overflow failure.
|
|
3439
|
+
if (!isContextOverflow(error) || !controller.manualCheckpointFallbackArmed) {
|
|
3440
|
+
throw error;
|
|
3441
|
+
}
|
|
3442
|
+
const result = await session.compact(customInstructions);
|
|
3443
|
+
return projectCompactSnapshot(result ?? {});
|
|
3444
|
+
}
|
|
3412
3445
|
}
|
|
3413
3446
|
listDatabaseConnections() {
|
|
3414
3447
|
return this.dbConnections.list();
|
|
@@ -3856,6 +3856,9 @@ export async function handleContextInsights(res, deps, sessionId) {
|
|
|
3856
3856
|
.map((name) => ({ id: name, description: "" }));
|
|
3857
3857
|
const insights = deriveContextInsights(snapshot, {
|
|
3858
3858
|
sessionId,
|
|
3859
|
+
contextPressure: typeof deps.runtime.getContextPressureTelemetry === "function"
|
|
3860
|
+
? deps.runtime.getContextPressureTelemetry(sessionId)
|
|
3861
|
+
: undefined,
|
|
3859
3862
|
...(systemPromptChars !== undefined ? { systemPromptChars } : {}),
|
|
3860
3863
|
...(systemPromptPreview !== undefined
|
|
3861
3864
|
? { systemPromptPreview }
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* GET /terminals/:id session info + buffered output
|
|
8
8
|
* POST /terminals/:id/input { data } write to the PTY
|
|
9
9
|
* POST /terminals/:id/resize { cols, rows }
|
|
10
|
+
* POST /terminals/:id/rename { name }
|
|
10
11
|
* POST /terminals/:id/interrupt send Ctrl+C
|
|
11
12
|
* POST /terminals/:id/kill stop and await full exit
|
|
12
13
|
* GET /terminals/:id/stream SSE: buffered replay + live chunks
|
|
@@ -195,6 +196,17 @@ export async function handleTerminalRequest(req, res, deps, pathname) {
|
|
|
195
196
|
sendJson(res, 200, { ok: true });
|
|
196
197
|
return true;
|
|
197
198
|
}
|
|
199
|
+
if (method === "POST" && sub === "rename" && parts.length === 2) {
|
|
200
|
+
const body = await readJsonBody(req);
|
|
201
|
+
const name = typeof body.name === "string" ? body.name.trim() : "";
|
|
202
|
+
if (!name || name.length > 60) {
|
|
203
|
+
sendJson(res, 400, { ok: false, error: { code: "INVALID_INPUT", message: "name (1..60 chars) is required" } });
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
const info = deps.terminals.rename(sessionId, name);
|
|
207
|
+
sendJson(res, 200, { ok: true, data: info });
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
198
210
|
if (method === "POST" && sub === "interrupt" && parts.length === 2) {
|
|
199
211
|
deps.terminals.interrupt(sessionId);
|
|
200
212
|
sendJson(res, 200, { ok: true });
|
|
@@ -327,6 +327,12 @@ export class TerminalSessionRegistry {
|
|
|
327
327
|
return;
|
|
328
328
|
entry.pty.write("\x03");
|
|
329
329
|
}
|
|
330
|
+
/** Rename a session (display label only). */
|
|
331
|
+
rename(sessionId, name) {
|
|
332
|
+
const entry = this.mustGet(sessionId);
|
|
333
|
+
entry.info.name = name;
|
|
334
|
+
return { ...entry.info };
|
|
335
|
+
}
|
|
330
336
|
/** Kill and wait for full stop, then remove the registry entry so closed
|
|
331
337
|
* terminals disappear from the list (explicit close = forget). Idempotent. */
|
|
332
338
|
async kill(sessionId) {
|