@tea-agent/loop-agent 0.43.0-next.1 → 0.43.0-next.10
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 +129 -9
- package/dist/application/dag/run-dag.js +5 -0
- package/dist/application/evaluation/budget.js +19 -1
- package/dist/application/task-lifecycle/advance.js +17 -4
- package/dist/application/task-lifecycle/observe.js +43 -29
- package/dist/application/task-lifecycle/plan-transitions.js +5 -4
- package/dist/build-stamp.json +3 -3
- package/dist/executors/dag-pi-executor.js +1214 -584
- package/dist/executors/pi-executor.js +22 -1
- package/dist/executors/pi-sdk-executor.js +140 -39
- package/dist/executors/shell-executor.js +5 -2
- package/dist/shared/frontend-execution-policy.js +23 -0
- package/dist/task/config-types.js +4 -0
- package/dist/task/source-prepare/ledger-reconciliation.js +2 -2
- package/dist/task/source-prepare/ledger-review.js +6 -9
- package/dist/task/source-prepare/semantic-intake.js +16 -26
- package/dist/task/source-prepare/source-fidelity-pi.js +28 -9
- package/dist/task/source-references.js +48 -23
- package/dist/worker/console/chat/assistant-content.js +23 -2
- package/dist/worker/console/chat/browser-policy.js +143 -0
- package/dist/worker/console/chat/browser-routes.js +148 -0
- package/dist/worker/console/chat/explore-tools.js +13 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/ask-user-question.js +44 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/explore-tools.js +202 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/goal-tools.js +78 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/operator-tools.js +86 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/todo-write.js +38 -0
- package/dist/worker/console/chat/pi-runtime/inspection-types.js +28 -0
- package/dist/worker/console/chat/pi-runtime/inspection.js +439 -0
- package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +153 -0
- package/dist/worker/console/chat/pi-runtime/sdk-session.js +5 -0
- package/dist/worker/console/chat/pi-runtime.js +213 -1181
- package/dist/worker/console/chat/routes.js +212 -71
- package/dist/worker/console/chat/scm-routes.js +217 -0
- package/dist/worker/console/chat/scm-service.js +283 -0
- package/dist/worker/console/chat/scm-tools.js +111 -0
- package/dist/worker/console/chat/sdd-data-alignment.js +65 -9
- package/dist/worker/console/chat/session-catalog.js +32 -0
- package/dist/worker/console/chat/session-mode-view.js +48 -0
- package/dist/worker/console/chat/session-mode.js +218 -0
- package/dist/worker/console/chat/session-store.js +22 -6
- package/dist/worker/console/chat/shortcuts.js +6 -0
- package/dist/worker/console/chat/terminal-routes.js +216 -0
- package/dist/worker/console/chat/terminal-sessions.js +348 -0
- package/dist/worker/console/chat/terminal-tools.js +211 -0
- package/dist/worker/console/chat/tool-preview.js +11 -0
- package/dist/worker/console/chat/tools.js +2 -0
- package/dist/worker/console/server.js +2 -28
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-B0Q0nClf.js → abnfDiagram-N423BO3Z-D_fNbWc_.js} +1 -1
- package/dist/worker/console/static/assets/{arc-DCPjC19G.js → arc-_HuqLW6m.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CP5n9jmG.js → architectureDiagram-T3A2C74G-Djy2qY1m.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-CmaWi_Wg.js → blockDiagram-VBNYF7ZC-bB-1TSyY.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-Ct5tcMfZ.js → c4Diagram-5PPSVZJV-C5Hmghrz.js} +1 -1
- package/dist/worker/console/static/assets/channel-C0A6UEIa.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-C0osm1Zf.js → chunk-2GRJ4B5K-Duyl39oy.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-CDWviED7.js → chunk-2Q5K7J3B-x6mdnSyf.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-mtSk1-j7.js → chunk-5RXB4S5H-WlBuFj7W.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-D5J9PHC7.js → chunk-5VM5RSS4-CTF429HX.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-Begg4WAa.js → chunk-6Q2QTUOP-Dwd6r-SF.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-sF1AEy7T.js → chunk-GF5L2VYU-C-Br82D1.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BqbsWXZb.js → chunk-JWPE2WC7-CuGp0DeE.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BKJrPcJ6.js → chunk-KBJHAD2P-CJhFX6Lh.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CcwNMRho.js → chunk-RYQCIY6F-DpGOa_jT.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-BEJi3iIs.js → chunk-XXDRQBXY-DXJaTynd.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DzguNppy.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DzguNppy.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-DRLgTvVu.js → cose-bilkent-JH36ORCC-CRBZWjE4.js} +1 -1
- package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BoAVG3cs.js → cynefin-VYW2F7L2-BdXcxtlb.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-Bzol06hR.js → cynefinDiagram-MW4NZA55-07UKsOts.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-UmliJM77.js → dagre-VZM6K2ZE-D38p9__S.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BWLcJkFo.js → diagram-7IWD3JNH-nSiBNNjH.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CgApOm-O.js → diagram-B4RE2ZJO-BFOTot5D.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-Bh3RgTLs.js → diagram-LBJQPF4R-DypKaZ6k.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-Dsh-D5nE.js → diagram-Q27KOJAE-B6yoOQeW.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-Dkbbpcpb.js → diagram-UB23O5K3-BHYS6viX.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-3EBaA3t3.js → ebnfDiagram-BXEA7PRR-D2VD5Snj.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-Bq2Dc5ok.js → erDiagram-JOGREHBK-E98mWxN1.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-De7y55ha.js → flowDiagram-UKHOOZJN-CT1zxhqP.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-fLiDbQRh.js → ganttDiagram-PKOTCBZU-6GcngNcy.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Du617mp1.js → gitGraphDiagram-DS77QQ5N-DCL6NvKe.js} +1 -1
- package/dist/worker/console/static/assets/index-24jp3aBh.js +468 -0
- package/dist/worker/console/static/assets/index-CY6y6I8M.css +1 -0
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-BwmlF-XP.js → infoDiagram-6WML65LV-C0627e-9.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-zsGtS59u.js → ishikawaDiagram-WSZJBQD7-C_u3P6Ik.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DTTPTe3f.js → journeyDiagram-NVQOT4AX-DPDPv9HL.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BkXg9aP-.js → kanban-definition-27J2QSJJ-D3OHdWiO.js} +1 -1
- package/dist/worker/console/static/assets/{linear-7U2ue5IE.js → linear-DI88zD7n.js} +1 -1
- package/dist/worker/console/static/assets/{mermaid.core-BUuGHmWO.js → mermaid.core-p2l8IrWY.js} +5 -5
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-7q6fX0Sv.js → mindmap-definition-FAOFIHXS-B1bAX-oS.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CkQPJN55.js → pegDiagram-VL7TDLO6-DwOnWxdD.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-CCal_tfX.js → pieDiagram-7S7Q4E2Y-xRkTXnJC.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-B7bpxyAZ.js → quadrantDiagram-CIZ2JOQS-_9UC5Zio.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CJmww7D-.js → railroadDiagram-AXF67PYL-CgEUirWJ.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-D6ldWJEv.js → requirementDiagram-LRYGKXZP-Czbpwiyz.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-VGh33I9e.js → sankeyDiagram-W5VNT64P-_j7_KiqY.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-CCkDrIjU.js → sequenceDiagram-SI44F4Z6-BNJa6Hyi.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-NC8f5Otb.js → sizeCapture-X5ZJPWSS-DedpKtOc.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-_92ezZdF.js → stateDiagram-OKZ733FA-BBvthr7c.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BABVQnfM.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BdUCGtbP.js → swimlanes-SLNWSIFB-Ds7umgEM.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-D0qsLaxR.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-CdD1H8ia.js → timeline-definition-Z64GVDOM-CKa-p1nF.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-Dkdk3oFo.js → vennDiagram-T6HMQDX7-LoUNR56o.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-CKu2uPPY.js → wardleyDiagram-T6FBY63Y-Bqbl6ym7.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-ClqAnuG8.js → xychartDiagram-ELKLHX3M-B8dUg4lf.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/active-turn-tail.js +10 -0
- package/dist/worker/console/static-src/operator-chat/chat-link.js +94 -0
- package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +122 -10
- package/dist/worker/console/static-src/operator-chat/compaction-message.js +7 -0
- package/dist/worker/console/static-src/operator-chat/pending-user-message.js +27 -15
- package/dist/worker/console/static-src/operator-chat/process-label.js +41 -0
- package/dist/worker/console/static-src/operator-chat/turn-group-equality.js +13 -0
- package/dist/worker/console/static-src/operator-chat/turn-process-disclosure.js +10 -0
- package/dist/worker/console/static-src/operator-chat/use-searchable-hidden.js +51 -0
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +44 -24
- package/dist/worker/console/static-src/operator-chat/useChatStream.js +18 -2
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +41 -8
- package/dist/worker/console/static-src/operator-chat/useComposer.js +26 -11
- package/dist/worker/console/static-src/operator-chat/user-turn-anchor-equality.js +21 -0
- package/dist/worker/console/workspace-context.js +15 -1
- package/dist/worker/observe/node-transparency.js +81 -72
- package/dist/worker/observe/routes.js +20 -1
- package/dist/worker/observe/static/dag-inspector-humanize.js +3 -0
- package/dist/worker/observe/static/dom.js +20 -1
- package/dist/worker/observe/static/format-pool.d.ts +2 -0
- package/dist/worker/observe/static/format-pool.js +6 -0
- package/dist/worker/observe/static/format.js +7 -0
- package/dist/worker/observe/static/inspect-workspace.js +34 -7
- package/dist/worker/observe/static/inspector-submission.js +32 -0
- package/dist/worker/observe/static/kpi.js +1 -0
- package/dist/worker/observe/static/relations.js +2 -0
- package/dist/worker/observe/static/router.js +13 -0
- package/dist/worker/observe/static/run-processing.js +2 -0
- package/dist/worker/observe/static/shell-chrome.js +36 -3
- package/dist/worker/observe/static/state.js +35 -2
- package/dist/worker/observe/static/styles.css +263 -39
- package/dist/worker/observe/static/task-failure-labels.d.ts +4 -0
- package/dist/worker/observe/static/task-failure-labels.js +67 -0
- package/dist/worker/observe/static/task-history.js +12 -0
- package/dist/worker/observe/static/views/batch.js +6 -13
- package/dist/worker/observe/static/views/dag-graph.js +50 -3
- package/dist/worker/observe/static/views/dag-inspector.js +742 -268
- package/dist/worker/observe/static/views/dag-trajectory.js +3 -0
- package/dist/worker/observe/static/views/dag.d.ts +6 -0
- package/dist/worker/observe/static/views/dag.js +49 -11
- package/dist/worker/observe/static/views/dags.js +2 -0
- package/dist/worker/observe/static/views/dashboard.js +21 -12
- package/dist/worker/observe/static/views/failures.js +21 -11
- package/dist/worker/observe/static/views/feature.js +11 -29
- package/dist/worker/observe/static/views/pool.js +37 -28
- package/dist/worker/observe/static/views/run.js +48 -5
- package/dist/worker/observe/static/views/session-timeline.js +189 -240
- package/dist/worker/observe/static/views/task.js +81 -62
- package/dist/workflows/dag/budget-enforcement.js +53 -3
- package/dist/workflows/dag/frontend-capacity.js +9 -0
- package/dist/workflows/dag/frontend-design-policy.js +2 -1
- package/dist/workflows/dag/frontend-durable-tools.js +193 -0
- package/dist/workflows/dag/frontend-execution-groups.js +24 -0
- package/dist/workflows/dag/frontend-implementation-contract.js +13 -0
- package/dist/workflows/dag/frontend-input-projection.js +76 -0
- package/dist/workflows/dag/frontend-plan-completeness.js +186 -0
- package/dist/workflows/dag/frontend-plan-recovery-policy.js +18 -0
- package/dist/workflows/dag/frontend-plan-render.js +10 -3
- package/dist/workflows/dag/frontend-recovery-controller.js +7 -7
- package/dist/workflows/dag/frontend-recovery-lineage.js +13 -0
- package/dist/workflows/dag/frontend-recovery-run.js +4 -0
- package/dist/workflows/dag/frontend-review-scopes.js +139 -0
- package/dist/workflows/dag/frontend-session-budget.js +249 -0
- package/dist/workflows/dag/frontend-shadow-dual-write.js +20 -2
- package/dist/workflows/dag/frontend-shape-facts.js +12 -2
- package/dist/workflows/dag/frontend-shape.js +30 -1
- package/dist/workflows/dag/frontend-test-execution-evidence.js +3 -2
- package/dist/workflows/dag/frontend-typed-event-store.js +11 -0
- package/dist/workflows/dag/init-hybrid.js +16 -10
- package/dist/workflows/dag/node-execution.js +38 -155
- package/dist/workflows/dag/prompt.js +4 -0
- package/dist/workflows/dag/rerun-plan.js +7 -1
- package/dist/workflows/dag/runner.js +26 -1
- package/dist/workflows/dag/types.js +6 -0
- package/docs/operations/README.md +1 -0
- package/docs/templates/frontend-design-contract.md +4 -4
- package/docs/templates/frontend-implementation-contract.schema.json +34 -2
- package/docs/templates/frontend-implementation-dag.json +5 -5
- package/package.json +6 -3
- package/skills/frontend-contract/SKILL.md +2 -1
- package/skills/frontend-contract/references/contract-protocol.md +19 -3
- package/skills/frontend-design-review/SKILL.md +12 -11
- package/skills/frontend-plan/SKILL.md +9 -2
- package/skills/frontend-plan/references/decision-contract.md +18 -5
- package/skills/frontend-review/SKILL.md +10 -11
- package/skills/frontend-scout/references/scout-evidence.md +4 -0
- package/dist/worker/console/static/assets/channel-DAS07MdS.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-Cwk-5jiW.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-Cwk-5jiW.js +0 -1
- package/dist/worker/console/static/assets/index-C0O48S_P.js +0 -449
- package/dist/worker/console/static/assets/index-CzKf4U8P.css +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DyJg5gzW.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-B1cw_0Uy.js +0 -8
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { collectFrontendUsage, createFrontendReadObservation, observeFrontendAttempt } from "../workflows/dag/frontend-session-budget.js";
|
|
1
2
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
3
|
import { existsSync } from "node:fs";
|
|
3
4
|
import { homedir } from "node:os";
|
|
@@ -453,6 +454,9 @@ export function extractPiEventStopReason(event) {
|
|
|
453
454
|
return undefined;
|
|
454
455
|
}
|
|
455
456
|
export class PiJsonlStreamCollector {
|
|
457
|
+
frontendReads = createFrontendReadObservation();
|
|
458
|
+
frontendUsageEvents = [];
|
|
459
|
+
frontendObservation() { return { readObservation: this.frontendReads.snapshot(), usageObservation: collectFrontendUsage(this.frontendUsageEvents) }; }
|
|
456
460
|
lineBuffer = "";
|
|
457
461
|
discardUntilNewline = false;
|
|
458
462
|
assistantText = "";
|
|
@@ -518,6 +522,13 @@ export class PiJsonlStreamCollector {
|
|
|
518
522
|
}
|
|
519
523
|
}
|
|
520
524
|
consumeEvent(event) {
|
|
525
|
+
try {
|
|
526
|
+
this.frontendReads.observe(event);
|
|
527
|
+
const message = isRecord(event.message) ? event.message : undefined;
|
|
528
|
+
if (event.usage || message?.usage || event.tokenUsage)
|
|
529
|
+
this.frontendUsageEvents.push({ responseId: event.responseId, messageId: event.messageId, usage: event.usage, tokenUsage: event.tokenUsage, message: message ? { role: message.role, id: message.id, responseId: message.responseId, usage: message.usage } : undefined });
|
|
530
|
+
}
|
|
531
|
+
catch { /* observation only */ }
|
|
521
532
|
const stopReason = extractPiEventStopReason(event);
|
|
522
533
|
if (stopReason === "length" || !this.stopReason) {
|
|
523
534
|
this.stopReason = stopReason ?? this.stopReason;
|
|
@@ -696,6 +707,8 @@ function shouldFallbackSdkToCli(sdkResult, validationIssues, options) {
|
|
|
696
707
|
return true;
|
|
697
708
|
if (!sdkResult.ok &&
|
|
698
709
|
(sdkResult.failureCategory === "auth" ||
|
|
710
|
+
sdkResult.failureCategory === "output-limit" ||
|
|
711
|
+
sdkResult.failureCategory === "cancelled" ||
|
|
699
712
|
sdkResult.failureCategory === "timeout" ||
|
|
700
713
|
sdkResult.failureCategory === "termination-unconfirmed")) {
|
|
701
714
|
return false;
|
|
@@ -730,6 +743,8 @@ function writerPolicyFailureResult(options, message, extras) {
|
|
|
730
743
|
export async function executePiStep(options) {
|
|
731
744
|
const backendMode = resolvePiBackend();
|
|
732
745
|
const writerRequiresSdk = options.writerToolPolicy?.requireSdk === true;
|
|
746
|
+
if (options.reserveProviderRequest && backendMode === "cli-only")
|
|
747
|
+
return { ...writerPolicyFailureResult(options, "FRONTEND_PROVIDER_BUDGET_UNSUPPORTED: actual request admission requires SDK", { sdkAttempted: false }), failureCategory: "budget_breach" };
|
|
733
748
|
if (backendMode === "cli-only") {
|
|
734
749
|
if (writerRequiresSdk) {
|
|
735
750
|
return writerPolicyFailureResult(options, "pi writer tool policy requires SDK backend; CODE_AGENT_PI_BACKEND=cli-only is fail-closed for writers", { sdkAttempted: false, backend: "cli" });
|
|
@@ -745,6 +760,8 @@ export async function executePiStep(options) {
|
|
|
745
760
|
const { checkPiSdkAvailability, executeSingleSdkAttempt, getActivePiSdkReuseScope, } = await import("./pi-sdk-executor.js");
|
|
746
761
|
const sdkCheck = await checkPiSdkAvailability(options.repoRoot);
|
|
747
762
|
if (!sdkCheck.ok) {
|
|
763
|
+
if (options.reserveProviderRequest)
|
|
764
|
+
return { ...writerPolicyFailureResult(options, `FRONTEND_PROVIDER_BUDGET_UNSUPPORTED: ${sdkCheck.detail}`, { sdkAttempted: false }), failureCategory: "budget_breach" };
|
|
748
765
|
if (writerRequiresSdk) {
|
|
749
766
|
return writerPolicyFailureResult(options, `pi writer tool policy requires SDK; ${sdkCheck.detail}`, { sdkAttempted: false });
|
|
750
767
|
}
|
|
@@ -773,7 +790,7 @@ export async function executePiStep(options) {
|
|
|
773
790
|
reuseRuntimeActive,
|
|
774
791
|
});
|
|
775
792
|
}
|
|
776
|
-
if (!shouldFallbackSdkToCli(sdkResult, validationIssues, options)) {
|
|
793
|
+
if (options.reserveProviderRequest || !shouldFallbackSdkToCli(sdkResult, validationIssues, options)) {
|
|
777
794
|
const failureCategory = validationIssues.length > 0
|
|
778
795
|
? "invalid-output"
|
|
779
796
|
: sdkResult.failureCategory;
|
|
@@ -798,6 +815,9 @@ export async function executePiStep(options) {
|
|
|
798
815
|
return { ...cliResult, reuseRuntimeActive };
|
|
799
816
|
}
|
|
800
817
|
async function executeSingleCliAttempt(options, modelConfig, promptFilePath) {
|
|
818
|
+
return observeFrontendAttempt({ backend: "cli", model: [modelConfig.provider, modelConfig.model].filter(Boolean).join("/"), observer: options.onAttemptObservation }, () => executeSingleCliAttemptInternal(options, modelConfig, promptFilePath));
|
|
819
|
+
}
|
|
820
|
+
async function executeSingleCliAttemptInternal(options, modelConfig, promptFilePath) {
|
|
801
821
|
const modelDisplay = modelConfig.provider && modelConfig.model
|
|
802
822
|
? `${modelConfig.provider}/${modelConfig.model}`
|
|
803
823
|
: (modelConfig.model ?? "default");
|
|
@@ -900,6 +920,7 @@ async function executeSingleCliAttempt(options, modelConfig, promptFilePath) {
|
|
|
900
920
|
});
|
|
901
921
|
resolve({
|
|
902
922
|
assistantText: collected.assistantText,
|
|
923
|
+
...stdoutCollector.frontendObservation(),
|
|
903
924
|
command: ["pi", ...recordedPiArgs],
|
|
904
925
|
durationMs,
|
|
905
926
|
exitCode: code,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { collectFrontendUsage, createFrontendReadObservation, observeFrontendAttempt } from "../workflows/dag/frontend-session-budget.js";
|
|
2
|
+
import { frontendModelCapabilities, measureFrontendRequestEnvelope } from "../shared/frontend-execution-policy.js";
|
|
1
3
|
import { appendFile, mkdir } from "node:fs/promises";
|
|
2
4
|
import os from "node:os";
|
|
3
5
|
import path from "node:path";
|
|
@@ -7,6 +9,42 @@ import { BoundedTextPreview, classifyPiFailure, createPiJsonlStreamCollector, DE
|
|
|
7
9
|
import { serializeSessionEvent } from "./pi-event-serializer.js";
|
|
8
10
|
import { PI_RECOMMENDED_COMPACTION, PI_RECOMMENDED_RETRY, } from "../shared/pi-retry-settings.js";
|
|
9
11
|
import { createCompactionController, createContextPressureExtension, createSiftBridgeState, inMemoryCompactionSettings, isDagSiftEnabled, parseCompactionPolicy, parseSiftBridgeConfig, SIFT_RETRIEVE_TOOL_NAME, } from "../shared/pi-context-pressure/index.js";
|
|
12
|
+
/** Maximum number of same-session continuations after provider output truncation. */
|
|
13
|
+
export const PI_SDK_OUTPUT_LIMIT_CONTINUE_MAX = 3;
|
|
14
|
+
export const PI_SDK_OUTPUT_LIMIT_CONTINUE_PROMPT = "继续。上一轮因输出长度上限(stopReason=length)截断;当前会话、工具与已完成工作仍保留。只完成尚未完成的部分,不重做已成功的写入或事实提交。";
|
|
15
|
+
/** Wrap the actual stream seam: tool turns, retries and compaction all await it. */
|
|
16
|
+
export async function installPiProviderRequestBudget(session, reserve, onFailure, capacity) {
|
|
17
|
+
const agent = session.agent;
|
|
18
|
+
const original = agent?.streamFunction;
|
|
19
|
+
if (!agent || typeof original !== "function")
|
|
20
|
+
throw Error("FRONTEND_PROVIDER_BUDGET_UNSUPPORTED: SDK actual request stream unavailable");
|
|
21
|
+
const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
|
|
22
|
+
agent.streamFunction = async (...args) => {
|
|
23
|
+
try {
|
|
24
|
+
if (args[2]?.signal?.aborted)
|
|
25
|
+
throw Error("FRONTEND_PROVIDER_REQUEST_ABORTED");
|
|
26
|
+
if (capacity) {
|
|
27
|
+
const measurement = measureFrontendRequestEnvelope(args[1], args[0], capacity.policy);
|
|
28
|
+
capacity.observe(measurement);
|
|
29
|
+
if (measurement.exceedsEstimate)
|
|
30
|
+
throw Error(`FRONTEND_CONTEXT_ESTIMATE_EXCEEDED: estimated=${measurement.estimatedTokens} available=${measurement.availableInputTokens}; estimator=${measurement.estimatorVersion}; registry capability is not a measured gateway limit`);
|
|
31
|
+
}
|
|
32
|
+
await reserve();
|
|
33
|
+
if (args[2]?.signal?.aborted)
|
|
34
|
+
throw Error("FRONTEND_PROVIDER_REQUEST_ABORTED");
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
38
|
+
onFailure(message);
|
|
39
|
+
const stream = createAssistantMessageEventStream();
|
|
40
|
+
const model = args[0] ?? {};
|
|
41
|
+
stream.push({ type: "error", reason: "error", error: { role: "assistant", content: [], api: model.api ?? "unknown", provider: model.provider ?? "unknown", model: model.id ?? "unknown", usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "error", errorMessage: message, timestamp: Date.now() } });
|
|
42
|
+
stream.end();
|
|
43
|
+
return stream;
|
|
44
|
+
}
|
|
45
|
+
return original.apply(agent, args);
|
|
46
|
+
};
|
|
47
|
+
}
|
|
10
48
|
/** Same-session recovery after a transport stall. Exactly one continue per SDK attempt. */
|
|
11
49
|
export const PI_SDK_STALL_CONTINUE_MAX = 1;
|
|
12
50
|
/**
|
|
@@ -544,6 +582,9 @@ function aggregateSdkTokenUsage(samples) {
|
|
|
544
582
|
* same session; that is in-attempt recovery, not cross-step session reuse.
|
|
545
583
|
*/
|
|
546
584
|
export async function executeSingleSdkAttempt(options) {
|
|
585
|
+
return observeFrontendAttempt({ backend: "sdk", model: [options.modelConfig.provider, options.modelConfig.model].filter(Boolean).join("/"), observer: options.onAttemptObservation }, () => executeSingleSdkAttemptInternal(options));
|
|
586
|
+
}
|
|
587
|
+
async function executeSingleSdkAttemptInternal(options) {
|
|
547
588
|
const modelConfig = options.modelConfig;
|
|
548
589
|
const modelDisplay = modelConfig.provider && modelConfig.model
|
|
549
590
|
? `${modelConfig.provider}/${modelConfig.model}`
|
|
@@ -568,9 +609,16 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
568
609
|
let timedOut = false;
|
|
569
610
|
let terminationConfirmed = true;
|
|
570
611
|
let stderr = "";
|
|
612
|
+
let providerBudgetFailure;
|
|
613
|
+
let capabilitiesObservation = frontendModelCapabilities(undefined);
|
|
614
|
+
const requestEnvelopeObservation = { peakBytes: 0, peakEstimatedTokens: 0, estimatorVersion: "utf8-bytes-div3-v1-estimate" };
|
|
571
615
|
const stdoutPreview = new BoundedTextPreview("stdout");
|
|
572
616
|
const stdoutCollector = createPiJsonlStreamCollector();
|
|
617
|
+
let turnCollector = createPiJsonlStreamCollector();
|
|
618
|
+
let committedTerminalObserved = false;
|
|
573
619
|
const usageSamples = [];
|
|
620
|
+
const observationEvents = [];
|
|
621
|
+
const readObservation = createFrontendReadObservation();
|
|
574
622
|
let observedTurns = 0;
|
|
575
623
|
let contextBudgetExhausted = false;
|
|
576
624
|
let contextBudgetDetail = "";
|
|
@@ -579,6 +627,9 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
579
627
|
// length-stopped thinking-only attempt with no persisted write tool calls is
|
|
580
628
|
// still distinguishable from generic empty output.
|
|
581
629
|
let stopReason;
|
|
630
|
+
let providerErrorMessage;
|
|
631
|
+
let promptIndex = 0;
|
|
632
|
+
let outputContinuesSent = 0;
|
|
582
633
|
let thinkingObserved = false;
|
|
583
634
|
let writeToolCallCount = 0;
|
|
584
635
|
const observeWriterThinkingExhaustionEvidence = (event) => {
|
|
@@ -660,6 +711,13 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
660
711
|
? { additionalExtensionPaths: options.piExtensionPaths }
|
|
661
712
|
: {}),
|
|
662
713
|
});
|
|
714
|
+
capabilitiesObservation = frontendModelCapabilities(session.agent?.state?.model);
|
|
715
|
+
if (options.reserveProviderRequest || options.frontendExecutionPolicy)
|
|
716
|
+
await installPiProviderRequestBudget(session, options.reserveProviderRequest ?? (async () => { }), message => { providerBudgetFailure = message; appendStderr(message); }, options.frontendExecutionPolicy ? { policy: options.frontendExecutionPolicy, observe: measurement => {
|
|
717
|
+
capabilitiesObservation = measurement.capabilities;
|
|
718
|
+
requestEnvelopeObservation.peakBytes = Math.max(requestEnvelopeObservation.peakBytes, measurement.bytes);
|
|
719
|
+
requestEnvelopeObservation.peakEstimatedTokens = Math.max(requestEnvelopeObservation.peakEstimatedTokens, measurement.estimatedTokens);
|
|
720
|
+
} } : undefined);
|
|
663
721
|
let resolveStall;
|
|
664
722
|
let resolveSettlement;
|
|
665
723
|
let resolveContextBudget;
|
|
@@ -718,6 +776,8 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
718
776
|
resolveContextBudget?.("context-budget");
|
|
719
777
|
};
|
|
720
778
|
unsubscribe = session.subscribe((event) => {
|
|
779
|
+
if (event.type === "tool_execution_end" && event.isError !== true && typeof event.toolName === "string" && options.outputLimitRecovery?.terminalToolNames.includes(event.toolName) && isRecord(event.result) && isRecord(event.result.details) && event.result.details.ok === true)
|
|
780
|
+
committedTerminalObserved = true;
|
|
721
781
|
if (event.type === "agent_settled" && !settled) {
|
|
722
782
|
settled = true;
|
|
723
783
|
resolveSettlement?.("settled");
|
|
@@ -737,9 +797,18 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
737
797
|
// best-effort: activity must never change Pi result
|
|
738
798
|
}
|
|
739
799
|
}
|
|
800
|
+
const observationMessage = isRecord(event.message) ? event.message : undefined;
|
|
801
|
+
if (typeof observationMessage?.errorMessage === "string")
|
|
802
|
+
providerErrorMessage = observationMessage.errorMessage;
|
|
803
|
+
try {
|
|
804
|
+
readObservation.observe(event);
|
|
805
|
+
}
|
|
806
|
+
catch { /* observation must not change execution */ }
|
|
807
|
+
if (!(typeof observationMessage?.errorMessage === "string" && observationMessage.errorMessage.startsWith("FRONTEND_PROVIDER_")) && (event.usage || observationMessage?.usage || event.tokenUsage))
|
|
808
|
+
observationEvents.push({ responseId: event.responseId, messageId: event.messageId, usage: event.usage, tokenUsage: event.tokenUsage, message: observationMessage ? { role: observationMessage.role, id: observationMessage.id, responseId: observationMessage.responseId, usage: observationMessage.usage } : undefined });
|
|
740
809
|
const usageSample = extractSdkUsageSample(event);
|
|
741
810
|
if (usageSample)
|
|
742
|
-
usageSamples.push(usageSample);
|
|
811
|
+
usageSamples.push({ ...usageSample, responseKey: usageSample.responseKey ?? `turn-${promptIndex}` });
|
|
743
812
|
if (event.type === "turn_end")
|
|
744
813
|
observedTurns += 1;
|
|
745
814
|
checkContextBudget();
|
|
@@ -753,6 +822,7 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
753
822
|
const line = serializeSessionEvent(event);
|
|
754
823
|
stdoutPreview.append(`${line}\n`);
|
|
755
824
|
stdoutCollector.append(`${line}\n`);
|
|
825
|
+
turnCollector.append(`${line}\n`);
|
|
756
826
|
sessionEventAppender?.append(line, event);
|
|
757
827
|
});
|
|
758
828
|
const timeoutPromise = timeoutMs > 0
|
|
@@ -763,6 +833,9 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
763
833
|
})
|
|
764
834
|
: null;
|
|
765
835
|
const runTurn = async (userMessage) => {
|
|
836
|
+
promptIndex += 1;
|
|
837
|
+
stopReason = undefined;
|
|
838
|
+
turnCollector = createPiJsonlStreamCollector();
|
|
766
839
|
const settlementPromise = resetSettlement();
|
|
767
840
|
const stallPromise = resetStallPromise();
|
|
768
841
|
const contextBudgetPromise = options.contextBudget
|
|
@@ -808,48 +881,61 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
808
881
|
: options.userMessage;
|
|
809
882
|
let continuesSent = 0;
|
|
810
883
|
let raced = await runTurn(promptMessage);
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
884
|
+
while (true) {
|
|
885
|
+
if (raced === "context-budget") {
|
|
886
|
+
appendStderr(contextBudgetDetail);
|
|
887
|
+
abortConfirmed = await runSessionActionWithGrace("abort", () => session.abort());
|
|
888
|
+
await disposeSession();
|
|
889
|
+
}
|
|
890
|
+
else if (raced === "stall") {
|
|
891
|
+
abortConfirmed = await runSessionActionWithGrace("abort", () => session.abort());
|
|
892
|
+
const withinAbsoluteTimeout = timeoutMs <= 0 || Date.now() - startedAt < timeoutMs;
|
|
893
|
+
const canContinue = abortConfirmed &&
|
|
894
|
+
writeToolCallCount === 0 &&
|
|
895
|
+
withinAbsoluteTimeout &&
|
|
896
|
+
continuesSent < PI_SDK_STALL_CONTINUE_MAX;
|
|
897
|
+
if (canContinue) {
|
|
898
|
+
// The aborted turn's stopReason must not leak onto a recovered continue.
|
|
899
|
+
stopReason = undefined;
|
|
900
|
+
continuesSent += 1;
|
|
901
|
+
persistRuntimeNote({
|
|
902
|
+
type: "loop-agent-stall-continue",
|
|
903
|
+
prompt: PI_SDK_STALL_CONTINUE_PROMPT,
|
|
904
|
+
maxContinues: PI_SDK_STALL_CONTINUE_MAX,
|
|
905
|
+
});
|
|
906
|
+
raced = await runTurn(PI_SDK_STALL_CONTINUE_PROMPT);
|
|
907
|
+
if (raced !== "done" && raced !== "settled") {
|
|
908
|
+
await failClosedAfterWait(raced === "stall" ? "stall" : "absolute-timeout", raced === "stall"
|
|
909
|
+
? "pi SDK stall continue did not recover; treating as timeout"
|
|
910
|
+
: "pi SDK stall continue hit the absolute timeout", true);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
else {
|
|
914
|
+
await failClosedAfterWait("stall", !abortConfirmed
|
|
915
|
+
? undefined
|
|
916
|
+
: writeToolCallCount > 0
|
|
917
|
+
? "pi SDK stall continue skipped because write tools already ran"
|
|
918
|
+
: "pi SDK stall continue skipped because absolute timeout elapsed", false);
|
|
837
919
|
}
|
|
838
920
|
}
|
|
839
|
-
else {
|
|
840
|
-
await failClosedAfterWait("
|
|
841
|
-
? undefined
|
|
842
|
-
: writeToolCallCount > 0
|
|
843
|
-
? "pi SDK stall continue skipped because write tools already ran"
|
|
844
|
-
: "pi SDK stall continue skipped because absolute timeout elapsed", false);
|
|
921
|
+
else if (raced === "absolute-timeout") {
|
|
922
|
+
await failClosedAfterWait("absolute-timeout");
|
|
845
923
|
}
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
924
|
+
if (options.outputLimitRecovery && stopReason === "length" && !committedTerminalObserved && !stderr && outputContinuesSent < PI_SDK_OUTPUT_LIMIT_CONTINUE_MAX && !timedOut) {
|
|
925
|
+
outputContinuesSent += 1;
|
|
926
|
+
const note = serializeSessionEvent({ type: "loop-agent-output-limit-continue", continue: outputContinuesSent, maxContinues: PI_SDK_OUTPUT_LIMIT_CONTINUE_MAX, prompt: PI_SDK_OUTPUT_LIMIT_CONTINUE_PROMPT });
|
|
927
|
+
stdoutPreview.append(`${note}\n`);
|
|
928
|
+
stdoutCollector.append(`${note}\n`);
|
|
929
|
+
raced = await runTurn(PI_SDK_OUTPUT_LIMIT_CONTINUE_PROMPT);
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
break;
|
|
849
933
|
}
|
|
850
934
|
}
|
|
851
935
|
catch (error) {
|
|
852
936
|
const message = error instanceof Error ? error.message : String(error);
|
|
937
|
+
if (options.reserveProviderRequest && message.startsWith("FRONTEND_PROVIDER_"))
|
|
938
|
+
providerBudgetFailure = message;
|
|
853
939
|
appendStderr(message);
|
|
854
940
|
}
|
|
855
941
|
finally {
|
|
@@ -872,20 +958,29 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
872
958
|
}
|
|
873
959
|
}
|
|
874
960
|
}
|
|
961
|
+
if (providerErrorMessage && stopReason === "error" && !stderr)
|
|
962
|
+
appendStderr(providerErrorMessage);
|
|
963
|
+
if (options.outputLimitRecovery && stopReason === "length" && !committedTerminalObserved && outputContinuesSent >= PI_SDK_OUTPUT_LIMIT_CONTINUE_MAX) {
|
|
964
|
+
const note = serializeSessionEvent({ type: "loop-agent-output-limit-exhausted", maxContinues: PI_SDK_OUTPUT_LIMIT_CONTINUE_MAX });
|
|
965
|
+
stdoutPreview.append(`${note}\n`);
|
|
966
|
+
}
|
|
875
967
|
const stdout = stdoutPreview.text();
|
|
876
968
|
const durationMs = Date.now() - startedAt;
|
|
877
969
|
const collected = stdoutCollector.finish();
|
|
878
970
|
const fallbackParsed = collected.parsedEvents > 0
|
|
879
971
|
? undefined
|
|
880
972
|
: extractAssistantTextFromPiJson(stdout);
|
|
973
|
+
const finalTurn = turnCollector.finish();
|
|
881
974
|
const assistantText = collected.parsedEvents > 0
|
|
882
|
-
?
|
|
975
|
+
? finalTurn.assistantText
|
|
883
976
|
: (fallbackParsed?.assistantText ?? "");
|
|
884
977
|
const parsedEvents = collected.parsedEvents > 0
|
|
885
978
|
? collected.parsedEvents
|
|
886
979
|
: (fallbackParsed?.parsedEvents ?? 0);
|
|
887
980
|
const tokensUsed = aggregateSdkTokenUsage(usageSamples);
|
|
888
|
-
const
|
|
981
|
+
const cancelled = stopReason === "aborted";
|
|
982
|
+
const outputLimitExhausted = Boolean(options.outputLimitRecovery && stopReason === "length" && !committedTerminalObserved && !timedOut && !stderr);
|
|
983
|
+
const failureCategory = !terminationConfirmed ? "termination-unconfirmed" : stopReason === "aborted" ? "cancelled" : outputLimitExhausted ? "output-limit" : providerBudgetFailure ? (providerBudgetFailure.includes("REQUEST_ABORTED") ? "interrupted" : providerBudgetFailure.startsWith("FRONTEND_CONTEXT_ESTIMATE_EXCEEDED") ? "context-budget-exhausted" : "budget_breach") : terminationConfirmed
|
|
889
984
|
? classifyPiFailure({
|
|
890
985
|
assistantText,
|
|
891
986
|
exitCode: timedOut ? 1 : stderr ? 1 : 0,
|
|
@@ -900,12 +995,14 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
900
995
|
backend: "sdk",
|
|
901
996
|
command: ["pi-sdk", ...piSdkArgs],
|
|
902
997
|
durationMs,
|
|
903
|
-
exitCode: timedOut || stderr ? 1 : 0,
|
|
998
|
+
exitCode: timedOut || stderr || outputLimitExhausted || cancelled ? 1 : 0,
|
|
904
999
|
failureCategory,
|
|
905
1000
|
modelDisplay,
|
|
906
1001
|
ok: terminationConfirmed &&
|
|
907
1002
|
!timedOut &&
|
|
908
1003
|
!stderr &&
|
|
1004
|
+
!outputLimitExhausted &&
|
|
1005
|
+
!cancelled &&
|
|
909
1006
|
assistantText.length > 0 &&
|
|
910
1007
|
!collected.outputTooLarge,
|
|
911
1008
|
parsedEvents,
|
|
@@ -915,6 +1012,10 @@ export async function executeSingleSdkAttempt(options) {
|
|
|
915
1012
|
outputTooLarge: collected.outputTooLarge,
|
|
916
1013
|
timedOut,
|
|
917
1014
|
tokensUsed,
|
|
1015
|
+
usageObservation: collectFrontendUsage(observationEvents),
|
|
1016
|
+
readObservation: readObservation.snapshot(),
|
|
1017
|
+
capabilitiesObservation,
|
|
1018
|
+
...(options.frontendExecutionPolicy ? { requestEnvelopeObservation } : {}),
|
|
918
1019
|
subagentStats: collected.subagentStats,
|
|
919
1020
|
// Writer-thinking-exhausted diagnosis evidence (AC-002). Carried through
|
|
920
1021
|
// the object spread in executePiStep so executeDagPiNode can read them
|
|
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
|
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { withFrontendTestReporter, parseFrontendTestExecutionReport } from "../workflows/dag/frontend-test-execution-evidence.js";
|
|
4
4
|
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
5
|
-
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { writeDagNodeJsonArtifact, writeDagNodeTextArtifact, writeDagRunJsonArtifact, } from "../infrastructure/harness/artifact-store.js";
|
|
8
8
|
import { captureWorkspaceCheckpoint } from "../workflows/dag/workspace-checkpoint.js";
|
|
@@ -2065,7 +2065,10 @@ async function executeFrontendVerificationBundle(input, meta) {
|
|
|
2065
2065
|
let reportError;
|
|
2066
2066
|
if (observedCommand && result.ok) {
|
|
2067
2067
|
try {
|
|
2068
|
-
|
|
2068
|
+
// Vitest reports physical paths (e.g. /private/var on macOS).
|
|
2069
|
+
// Match those in workspace coordinates even when shell.cwd is
|
|
2070
|
+
// a subdirectory or the caller used a directory alias.
|
|
2071
|
+
commandExecutionEvidence.set(key, parseFrontendTestExecutionReport(JSON.parse(await readFile(reportPath, "utf8")), await realpath(cwd), await realpath(input.cwd)));
|
|
2069
2072
|
}
|
|
2070
2073
|
catch (error) {
|
|
2071
2074
|
reportError = `frontend test execution report unavailable: ${error instanceof Error ? error.message : String(error)}`;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** Execution hints and estimation reserves, never model-name capacity defaults. */
|
|
3
|
+
export const frontendExecutionPolicySchema = z.object({
|
|
4
|
+
scopeTargetBytes: z.number().int().positive().default(24_000),
|
|
5
|
+
maxScopeUnits: z.number().int().positive().default(4),
|
|
6
|
+
maxCoverageConcurrency: z.number().int().min(1).max(4).default(4),
|
|
7
|
+
outputReserveTokens: z.number().int().positive().default(4096),
|
|
8
|
+
readGrowthReserveTokens: z.number().int().nonnegative().default(2048),
|
|
9
|
+
safetyRatio: z.number().min(0).max(0.5).default(0.15),
|
|
10
|
+
}).strict();
|
|
11
|
+
export function frontendModelCapabilities(model) {
|
|
12
|
+
const value = model && typeof model === "object" ? model : {};
|
|
13
|
+
const positive = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null;
|
|
14
|
+
return { model: typeof value.id === "string" ? `${value.provider ?? "unknown"}/${value.id}` : null, source: Object.keys(value).length ? "model-registry" : "unknown", inputLimit: positive(value.inputLimit), totalContextLimit: positive(value.contextWindow), outputLimit: positive(value.maxTokens), reasoningControllability: "unknown" };
|
|
15
|
+
}
|
|
16
|
+
export function measureFrontendRequestEnvelope(context, model, policy) {
|
|
17
|
+
const bytes = Buffer.byteLength(JSON.stringify(context));
|
|
18
|
+
const estimatedTokens = Math.ceil(bytes / 3);
|
|
19
|
+
const capabilities = frontendModelCapabilities(model);
|
|
20
|
+
const outputReserve = Math.min(policy.outputReserveTokens, capabilities.outputLimit ?? policy.outputReserveTokens);
|
|
21
|
+
const availableInputTokens = Math.min(capabilities.inputLimit ?? Infinity, capabilities.totalContextLimit === null ? Infinity : Math.floor(capabilities.totalContextLimit * (1 - policy.safetyRatio)) - outputReserve - policy.readGrowthReserveTokens);
|
|
22
|
+
return { bytes, estimatedTokens, estimatorVersion: "utf8-bytes-div3-v1-estimate", capabilities, availableInputTokens: Number.isFinite(availableInputTokens) ? availableInputTokens : null, exceedsEstimate: estimatedTokens > availableInputTokens };
|
|
23
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { frontendExecutionPolicySchema } from "../shared/frontend-execution-policy.js";
|
|
2
3
|
import { DEFAULT_FRONTEND_SPEC_ROOTS, isFrontendSpecFilePath, isValidFrontendSpecRoot, } from "../shared/openspec-spec.js";
|
|
3
4
|
export const taskFlowSchema = z.enum([
|
|
4
5
|
"auto",
|
|
@@ -300,6 +301,8 @@ const taskConfigObjectSchema = z.object({
|
|
|
300
301
|
* default; raise to 2-3 for more tolerance of transient verify failures). */
|
|
301
302
|
frontendRecovery: z
|
|
302
303
|
.object({
|
|
304
|
+
/** Frozen request quota across the original run and recovery lineage; not a model capacity. */
|
|
305
|
+
maxProviderRequests: z.number().int().positive().optional(),
|
|
303
306
|
maxContinuations: z
|
|
304
307
|
.number()
|
|
305
308
|
.int()
|
|
@@ -310,6 +313,7 @@ const taskConfigObjectSchema = z.object({
|
|
|
310
313
|
})
|
|
311
314
|
.strict()
|
|
312
315
|
.optional(),
|
|
316
|
+
frontendExecutionPolicy: frontendExecutionPolicySchema.optional(),
|
|
313
317
|
/** Outer loop auto mode never writes by default; DAG execute requires this policy plus path/writeSet gates. */
|
|
314
318
|
loopAutoExecutionPolicy: loopAutoExecutionPolicySchema
|
|
315
319
|
.optional()
|
|
@@ -3,7 +3,7 @@ import { normalizeFragmentText } from "./fragment-inventory.js";
|
|
|
3
3
|
// 顺序 reconciliation(AC-006 / AC-FIDELITY-REPAIR-006)
|
|
4
4
|
// 结构化确定性片段走代码映射(显式 AC ID / 文本精确匹配),绝不调用 executor;
|
|
5
5
|
// 仅叙述性/歧义 chunk 调用可注入 executor,按标题顺序串行、逐块有界处理
|
|
6
|
-
// (budgetChars
|
|
6
|
+
// (budgetChars 仅为调用提示,不截断判定所需的原文)。executor 超时/异常/无效
|
|
7
7
|
// 返回/identity 越界一律 fail closed(SOURCE_FIDELITY_RECONCILIATION_FAILED),
|
|
8
8
|
// 不回退 heuristics。
|
|
9
9
|
// ---------------------------------------------------------------------------
|
|
@@ -65,7 +65,7 @@ export async function reconcileLedgerFragments(input) {
|
|
|
65
65
|
path: fragment.path,
|
|
66
66
|
headingPath: fragment.headingPath,
|
|
67
67
|
lineRange: fragment.lineRange,
|
|
68
|
-
text: fragment.text
|
|
68
|
+
text: fragment.text,
|
|
69
69
|
},
|
|
70
70
|
canonicalRequirements,
|
|
71
71
|
budgetChars,
|
|
@@ -7,8 +7,7 @@ import { mergeInventoryItems } from "./ledger-reconciliation.js";
|
|
|
7
7
|
// context-only 仅 reviewer pass 放行,高风险 context-only 始终阻断;duplicate
|
|
8
8
|
// 保留全部来源但审核失败(含修订后仍拒绝)以稳定码 fail closed。
|
|
9
9
|
// ---------------------------------------------------------------------------
|
|
10
|
-
/**
|
|
11
|
-
* prompt;沿用 MAX_SOURCE_EXCERPT_CHARS 边界语义。 */
|
|
10
|
+
/** Historical caller hint; it must never clip the fragment used for a decision. */
|
|
12
11
|
export const LEDGER_REVIEW_DEFAULT_BUDGET_CHARS = 2000;
|
|
13
12
|
export const LEDGER_REVIEW_MAX_REVISIONS = 1;
|
|
14
13
|
/** review 失败(reviewer 异常/第二次不通过)统一稳定错误码。 */
|
|
@@ -180,12 +179,9 @@ export const defaultLedgerReviewer = async (request) => {
|
|
|
180
179
|
: "conflict 无有效 human resolution 覆盖,保持阻断",
|
|
181
180
|
};
|
|
182
181
|
};
|
|
183
|
-
/**
|
|
184
|
-
*
|
|
185
|
-
* (AC-004 / AC-HARD-004):请求携带非空有界原文与精确 fragment id,完整文档
|
|
186
|
-
* 绝不进入下游 prompt;原文不可得时退化为 reason / id 保证非空。 */
|
|
182
|
+
/** Resolve complete source fragments for independent review; missing original text
|
|
183
|
+
* cannot be replaced with its reason or identity. */
|
|
187
184
|
export function ledgerReviewItemsFromRecords(records, input) {
|
|
188
|
-
const budgetChars = input?.budgetChars ?? LEDGER_REVIEW_DEFAULT_BUDGET_CHARS;
|
|
189
185
|
const merged = input?.fragments
|
|
190
186
|
? mergeInventoryItems({ records, fragments: input.fragments })
|
|
191
187
|
: records.map((record) => ({
|
|
@@ -200,8 +196,9 @@ export function ledgerReviewItemsFromRecords(records, input) {
|
|
|
200
196
|
canonicalRequirementIds: record.canonicalRequirementIds,
|
|
201
197
|
}));
|
|
202
198
|
return merged.map((item) => {
|
|
203
|
-
const
|
|
204
|
-
|
|
199
|
+
const text = item.text;
|
|
200
|
+
if (!text.trim() && ["context-only", "duplicate", "conflict"].includes(item.disposition))
|
|
201
|
+
throw new LedgerReviewError(`SOURCE_FIDELITY_ORIGINAL_MISSING: ${item.id}; independent review needs the full source text`);
|
|
205
202
|
return {
|
|
206
203
|
id: item.id,
|
|
207
204
|
text,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { observeFrontendSession } from "../../workflows/dag/frontend-session-budget.js";
|
|
1
3
|
/**
|
|
2
4
|
* P2 Semantic Intake: one-shot, read-only Pi structuring of imported PRDs
|
|
3
5
|
* into TaskContractDraftV1. Does not write source/需求.md directly — caller
|
|
@@ -411,24 +413,6 @@ export async function buildRepoHint(repoRoot) {
|
|
|
411
413
|
}
|
|
412
414
|
return lines.join("\n");
|
|
413
415
|
}
|
|
414
|
-
/**
|
|
415
|
-
* 在 maxChars 附近回退到最近的标题边界再截断(AC-005 / AC-FIDELITY-REPAIR-005
|
|
416
|
-
* 回归点移除):避免把可执行项/列表项从中间切开吞掉。仅用于模型提示词预算;
|
|
417
|
-
* ledger fragment inventory 始终消费完整原文,不经过此裁剪。
|
|
418
|
-
*/
|
|
419
|
-
function clipAtSectionBoundary(content, maxChars) {
|
|
420
|
-
if (content.length <= maxChars)
|
|
421
|
-
return content;
|
|
422
|
-
const prefix = content.slice(0, maxChars);
|
|
423
|
-
const headingRe = /^(?:#{1,6})\s+.+$/gm;
|
|
424
|
-
let boundary = prefix.length;
|
|
425
|
-
let match;
|
|
426
|
-
while ((match = headingRe.exec(prefix)) !== null) {
|
|
427
|
-
if (match.index >= maxChars * 0.4)
|
|
428
|
-
boundary = match.index;
|
|
429
|
-
}
|
|
430
|
-
return `${content.slice(0, boundary)}\n\n[truncated at section boundary]`;
|
|
431
|
-
}
|
|
432
416
|
async function buildPrompt(input) {
|
|
433
417
|
const bodies = input.documents
|
|
434
418
|
.map((doc, index) => {
|
|
@@ -436,14 +420,14 @@ async function buildPrompt(input) {
|
|
|
436
420
|
const metaLine = meta.recognized
|
|
437
421
|
? `artifact_type=${meta.artifactType} status=${meta.requirementStatus ?? meta.analysisStatus ?? "n/a"}`
|
|
438
422
|
: "artifact_type=unknown";
|
|
439
|
-
const
|
|
423
|
+
const complete = doc.content;
|
|
440
424
|
return [
|
|
441
425
|
`### Document ${index + 1}`,
|
|
442
426
|
`role: ${doc.role}`,
|
|
443
427
|
`path: ${doc.materializedPath}`,
|
|
444
428
|
metaLine,
|
|
445
429
|
"```markdown",
|
|
446
|
-
|
|
430
|
+
complete,
|
|
447
431
|
"```",
|
|
448
432
|
].join("\n");
|
|
449
433
|
})
|
|
@@ -609,9 +593,7 @@ export async function runSemanticIntake(input) {
|
|
|
609
593
|
message: "semantic intake has no MED/HIGH/LOW or Pi-supported models to try",
|
|
610
594
|
};
|
|
611
595
|
}
|
|
612
|
-
|
|
613
|
-
.map((d) => d.absolutePath)
|
|
614
|
-
.filter((p) => Boolean(p));
|
|
596
|
+
// Complete text is already inline; attaching the same documents duplicates it.
|
|
615
597
|
const prompt = await buildPrompt({
|
|
616
598
|
taskId: input.taskId,
|
|
617
599
|
title: input.title,
|
|
@@ -623,8 +605,12 @@ export async function runSemanticIntake(input) {
|
|
|
623
605
|
let chosenText;
|
|
624
606
|
for (const modelRef of queue) {
|
|
625
607
|
try {
|
|
626
|
-
const result = await
|
|
627
|
-
|
|
608
|
+
const result = await observeFrontendSession({
|
|
609
|
+
phase: "semantic-intake", userMessage: "Structure the imported requirement documents into the required JSON only.", prompt, model: modelRef, taskId: input.taskId,
|
|
610
|
+
artifactPath: path.join(getTaskPaths(input.repoRoot, input.taskId).taskDir, "artifacts", "session-budget", `${randomUUID()}.json`),
|
|
611
|
+
}, observer => execute({
|
|
612
|
+
onAttemptObservation: observer,
|
|
613
|
+
attachedFiles: [],
|
|
628
614
|
modelConfig: resolveDagPiModelConfig(modelRef),
|
|
629
615
|
prompt,
|
|
630
616
|
repoRoot: input.repoRoot,
|
|
@@ -643,7 +629,7 @@ export async function runSemanticIntake(input) {
|
|
|
643
629
|
return [error instanceof Error ? error.message : String(error)];
|
|
644
630
|
}
|
|
645
631
|
},
|
|
646
|
-
});
|
|
632
|
+
}));
|
|
647
633
|
attempted.push({
|
|
648
634
|
model: result.modelDisplay || modelRef,
|
|
649
635
|
ok: result.ok,
|
|
@@ -656,6 +642,10 @@ export async function runSemanticIntake(input) {
|
|
|
656
642
|
}
|
|
657
643
|
lastFailure =
|
|
658
644
|
`${result.failureCategory}: ${result.stderr || result.assistantText}`.slice(0, 2000);
|
|
645
|
+
if (result.stopReason === "length" || ["context-overflow", "context-budget-exhausted"].includes(result.failureCategory)) {
|
|
646
|
+
lastFailure = `SEMANTIC_INTAKE_CAPACITY_EXHAUSTED: refine the complete source into independently reviewable documents; ${lastFailure}`;
|
|
647
|
+
break;
|
|
648
|
+
}
|
|
659
649
|
}
|
|
660
650
|
catch (error) {
|
|
661
651
|
const message = error instanceof Error ? error.message : String(error);
|