@tangle-network/agent-eval 0.129.0 → 0.130.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +1 -0
- package/dist/active-curriculum-C4mk67HP.js +214 -0
- package/dist/active-curriculum-C4mk67HP.js.map +1 -0
- package/dist/adversarial-smnADNFS.d.ts +21 -0
- package/dist/adversarial-smnADNFS.d.ts.map +1 -0
- package/dist/analyst/index.d.ts +81 -2872
- package/dist/analyst/index.d.ts.map +1 -0
- package/dist/analyst/index.js +319 -360
- package/dist/analyst/index.js.map +1 -1
- package/dist/analyst-BkTS3C58.d.ts +89 -0
- package/dist/analyst-BkTS3C58.d.ts.map +1 -0
- package/dist/analyst-LsnNpSkm.js +152 -0
- package/dist/analyst-LsnNpSkm.js.map +1 -0
- package/dist/analyze-runs-C1CavBMk.js +1067 -0
- package/dist/analyze-runs-C1CavBMk.js.map +1 -0
- package/dist/analyze-runs-FsgYCinh.d.ts +72 -0
- package/dist/analyze-runs-FsgYCinh.d.ts.map +1 -0
- package/dist/attribute-vocabulary-DLJ6303h.d.ts +54 -0
- package/dist/attribute-vocabulary-DLJ6303h.d.ts.map +1 -0
- package/dist/authenticity/index.d.ts +81 -79
- package/dist/authenticity/index.d.ts.map +1 -0
- package/dist/authenticity/index.js +209 -193
- package/dist/authenticity/index.js.map +1 -1
- package/dist/baseline-HsBvw_dk.js +550 -0
- package/dist/baseline-HsBvw_dk.js.map +1 -0
- package/dist/baseline-hG3K85h4.d.ts +125 -0
- package/dist/baseline-hG3K85h4.d.ts.map +1 -0
- package/dist/belief-state/index.d.ts +448 -1188
- package/dist/belief-state/index.d.ts.map +1 -0
- package/dist/belief-state/index.js +1617 -1709
- package/dist/belief-state/index.js.map +1 -1
- package/dist/benchmarks/index.d.ts +2 -891
- package/dist/benchmarks/index.js +2 -60
- package/dist/benchmarks-DviOvUNr.js +754 -0
- package/dist/benchmarks-DviOvUNr.js.map +1 -0
- package/dist/builder-eval/index.d.ts +150 -662
- package/dist/builder-eval/index.d.ts.map +1 -0
- package/dist/builder-eval/index.js +356 -345
- package/dist/builder-eval/index.js.map +1 -1
- package/dist/calibration-CNWWA6K8.js +94 -0
- package/dist/calibration-CNWWA6K8.js.map +1 -0
- package/dist/campaign/index.d.ts +5 -6381
- package/dist/campaign/index.js +3 -213
- package/dist/campaign-CBKZvQ1H.js +3885 -0
- package/dist/campaign-CBKZvQ1H.js.map +1 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +164 -175
- package/dist/cli.js.map +1 -1
- package/dist/client-C97NMzqi.d.ts +581 -0
- package/dist/client-C97NMzqi.d.ts.map +1 -0
- package/dist/client-CYzbdJOZ.js +637 -0
- package/dist/client-CYzbdJOZ.js.map +1 -0
- package/dist/code-agent-session-BjkMTQ7H.js +1390 -0
- package/dist/code-agent-session-BjkMTQ7H.js.map +1 -0
- package/dist/code-agent-session-DqqgOJaz.d.ts +143 -0
- package/dist/code-agent-session-DqqgOJaz.d.ts.map +1 -0
- package/dist/concurrency-DIxRZF_J.js +85 -0
- package/dist/concurrency-DIxRZF_J.js.map +1 -0
- package/dist/contract/index.d.ts +645 -5565
- package/dist/contract/index.d.ts.map +1 -0
- package/dist/contract/index.js +1730 -1938
- package/dist/contract/index.js.map +1 -1
- package/dist/control.d.ts +3 -1030
- package/dist/control.js +2 -33
- package/dist/cost-ledger-DIgQUFZZ.js +801 -0
- package/dist/cost-ledger-DIgQUFZZ.js.map +1 -0
- package/dist/cost-ledger-Dye6jCgg.d.ts +236 -0
- package/dist/cost-ledger-Dye6jCgg.d.ts.map +1 -0
- package/dist/dataset-BvtnC8Dc.d.ts +115 -0
- package/dist/dataset-BvtnC8Dc.d.ts.map +1 -0
- package/dist/default-registry-C-vFCSEc.js +2579 -0
- package/dist/default-registry-C-vFCSEc.js.map +1 -0
- package/dist/default-registry-CNPo-Vsb.d.ts +540 -0
- package/dist/default-registry-CNPo-Vsb.d.ts.map +1 -0
- package/dist/emitter-CPBAhxum.js +266 -0
- package/dist/emitter-CPBAhxum.js.map +1 -0
- package/dist/emitter-DGQGoLyj.d.ts +113 -0
- package/dist/emitter-DGQGoLyj.d.ts.map +1 -0
- package/dist/errors-8YnH8WlF.js +64 -0
- package/dist/errors-8YnH8WlF.js.map +1 -0
- package/dist/errors-CEk209JS.d.ts +76 -0
- package/dist/errors-CEk209JS.d.ts.map +1 -0
- package/dist/eval-campaign-DEm6c8ru.js +349 -0
- package/dist/eval-campaign-DEm6c8ru.js.map +1 -0
- package/dist/execution-tracks-CpgFPpS5.js +93 -0
- package/dist/execution-tracks-CpgFPpS5.js.map +1 -0
- package/dist/exporters-q9iL-2Jf.js +148 -0
- package/dist/exporters-q9iL-2Jf.js.map +1 -0
- package/dist/extract-usage-BrQ8mCLX.js +155 -0
- package/dist/extract-usage-BrQ8mCLX.js.map +1 -0
- package/dist/failure-cluster-CqcvCcdR.d.ts +59 -0
- package/dist/failure-cluster-CqcvCcdR.d.ts.map +1 -0
- package/dist/feedback-trajectory-CVaeREXV.d.ts +340 -0
- package/dist/feedback-trajectory-CVaeREXV.d.ts.map +1 -0
- package/dist/fuzz.d.ts +320 -646
- package/dist/fuzz.d.ts.map +1 -0
- package/dist/fuzz.js +670 -618
- package/dist/fuzz.js.map +1 -1
- package/dist/hf-dataset-DBJXXoY1.js +763 -0
- package/dist/hf-dataset-DBJXXoY1.js.map +1 -0
- package/dist/hosted/index.d.ts +11 -831
- package/dist/hosted/index.d.ts.map +1 -0
- package/dist/hosted/index.js +2 -37
- package/dist/index-2JJSA6-r2.d.ts +926 -0
- package/dist/index-2JJSA6-r2.d.ts.map +1 -0
- package/dist/index-6N0aYmpW.d.ts +217 -0
- package/dist/index-6N0aYmpW.d.ts.map +1 -0
- package/dist/index-BAvgST_9.d.ts +131 -0
- package/dist/index-BAvgST_9.d.ts.map +1 -0
- package/dist/index-BvnJuTGD.d.ts +68 -0
- package/dist/index-BvnJuTGD.d.ts.map +1 -0
- package/dist/index-C61Wi7yg.d.ts +547 -0
- package/dist/index-C61Wi7yg.d.ts.map +1 -0
- package/dist/index-CAPUUKaM.d.ts +335 -0
- package/dist/index-CAPUUKaM.d.ts.map +1 -0
- package/dist/index-DE5fb3EC.d.ts +2244 -0
- package/dist/index-DE5fb3EC.d.ts.map +1 -0
- package/dist/index-DSC51roc.d.ts +102 -0
- package/dist/index-DSC51roc.d.ts.map +1 -0
- package/dist/index.d.ts +3755 -15555
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11182 -11216
- package/dist/index.js.map +1 -1
- package/dist/integrity-BzRbCHzi.js +424 -0
- package/dist/integrity-BzRbCHzi.js.map +1 -0
- package/dist/integrity-rmVhXWA7.d.ts +61 -0
- package/dist/integrity-rmVhXWA7.d.ts.map +1 -0
- package/dist/judge-calibration-DFtEMlde.d.ts +146 -0
- package/dist/judge-calibration-DFtEMlde.d.ts.map +1 -0
- package/dist/ledger-core/index.d.ts +2 -0
- package/dist/ledger-core/index.js +2 -0
- package/dist/ledger-core-DtZz1RG0.js +388 -0
- package/dist/ledger-core-DtZz1RG0.js.map +1 -0
- package/dist/llm-client--GR4JbZE.js +687 -0
- package/dist/llm-client--GR4JbZE.js.map +1 -0
- package/dist/llm-client-B_nIBlYo.d.ts +290 -0
- package/dist/llm-client-B_nIBlYo.d.ts.map +1 -0
- package/dist/matrix/index.d.ts +3 -155
- package/dist/matrix/index.js +2 -8
- package/dist/matrix-BzQnu2S6.js +270 -0
- package/dist/matrix-BzQnu2S6.js.map +1 -0
- package/dist/meta-eval/index.d.ts +4 -1027
- package/dist/meta-eval/index.js +393 -390
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/metrics-C9YY1OcL.js +239 -0
- package/dist/metrics-C9YY1OcL.js.map +1 -0
- package/dist/mint-yN2M2eh0.js +201 -0
- package/dist/mint-yN2M2eh0.js.map +1 -0
- package/dist/multi-layer-verifier-BHY1gWAc.d.ts +138 -0
- package/dist/multi-layer-verifier-BHY1gWAc.d.ts.map +1 -0
- package/dist/multishot/index.d.ts +273 -480
- package/dist/multishot/index.d.ts.map +1 -0
- package/dist/multishot/index.js +595 -548
- package/dist/multishot/index.js.map +1 -1
- package/dist/off-policy-DvgzvtIx.js +220 -0
- package/dist/off-policy-DvgzvtIx.js.map +1 -0
- package/dist/off-policy-mskQw8Mb.d.ts +153 -0
- package/dist/off-policy-mskQw8Mb.d.ts.map +1 -0
- package/dist/openapi.json +1 -1
- package/dist/opencode-sqlite-BGrHeDu3.js +318 -0
- package/dist/opencode-sqlite-BGrHeDu3.js.map +1 -0
- package/dist/outcome-store-BYHIuO0e.d.ts +65 -0
- package/dist/outcome-store-BYHIuO0e.d.ts.map +1 -0
- package/dist/outcome-store-ChBKlTd_.js +75 -0
- package/dist/outcome-store-ChBKlTd_.js.map +1 -0
- package/dist/paired-arms-D9D0wXj2.js +260 -0
- package/dist/paired-arms-D9D0wXj2.js.map +1 -0
- package/dist/pipelines/index.d.ts +95 -532
- package/dist/pipelines/index.d.ts.map +1 -0
- package/dist/pipelines/index.js +497 -478
- package/dist/pipelines/index.js.map +1 -1
- package/dist/pre-registration-DakwTRXk.js +96 -0
- package/dist/pre-registration-DakwTRXk.js.map +1 -0
- package/dist/propose-review-control-LhIWGzHl.js +1458 -0
- package/dist/propose-review-control-LhIWGzHl.js.map +1 -0
- package/dist/query-CJ_DX8vl.d.ts +28 -0
- package/dist/query-CJ_DX8vl.d.ts.map +1 -0
- package/dist/query-Di7eEQ79.js +83 -0
- package/dist/query-Di7eEQ79.js.map +1 -0
- package/dist/raw-provider-sink-BQd7mzyT.js +201 -0
- package/dist/raw-provider-sink-BQd7mzyT.js.map +1 -0
- package/dist/raw-provider-sink-BU29Sh8h.d.ts +134 -0
- package/dist/raw-provider-sink-BU29Sh8h.d.ts.map +1 -0
- package/dist/redact-7Aq1ukl-.js +107 -0
- package/dist/redact-7Aq1ukl-.js.map +1 -0
- package/dist/release-report-Cz9NKH39.js +603 -0
- package/dist/release-report-Cz9NKH39.js.map +1 -0
- package/dist/release-report-mvB2G4_J.d.ts +244 -0
- package/dist/release-report-mvB2G4_J.d.ts.map +1 -0
- package/dist/replay-GnyotH0J.js +1741 -0
- package/dist/replay-GnyotH0J.js.map +1 -0
- package/dist/replay-OoidtG1E.d.ts +749 -0
- package/dist/replay-OoidtG1E.d.ts.map +1 -0
- package/dist/reporting.d.ts +6 -1312
- package/dist/reporting.js +6 -51
- package/dist/researcher-CwTdwXG1.d.ts +314 -0
- package/dist/researcher-CwTdwXG1.d.ts.map +1 -0
- package/dist/reward-hacking-eAnOsynk.d.ts +224 -0
- package/dist/reward-hacking-eAnOsynk.d.ts.map +1 -0
- package/dist/reward-hacking-qipEpKvY.js +596 -0
- package/dist/reward-hacking-qipEpKvY.js.map +1 -0
- package/dist/reward-nw2xZGZG.js +137 -0
- package/dist/reward-nw2xZGZG.js.map +1 -0
- package/dist/rl.d.ts +760 -4010
- package/dist/rl.d.ts.map +1 -0
- package/dist/rl.js +2325 -1958
- package/dist/rl.js.map +1 -1
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/rollout/index.d.ts +3 -2087
- package/dist/rollout/index.js +8 -168
- package/dist/rollout-BOYjemfR.js +624 -0
- package/dist/rollout-BOYjemfR.js.map +1 -0
- package/dist/rubric-predictive-validity-B3xmbmS1.js +141 -0
- package/dist/rubric-predictive-validity-B3xmbmS1.js.map +1 -0
- package/dist/rubric-predictive-validity-Ku_clp_1.d.ts +74 -0
- package/dist/rubric-predictive-validity-Ku_clp_1.d.ts.map +1 -0
- package/dist/run-evidence-ClRX_8A9.d.ts +225 -0
- package/dist/run-evidence-ClRX_8A9.d.ts.map +1 -0
- package/dist/run-record-BuoE80Dq.js +467 -0
- package/dist/{chunk-56TAVBOK.js.map → run-record-BuoE80Dq.js.map} +1 -1
- package/dist/run-record-CnZu_gjl.d.ts +357 -0
- package/dist/run-record-CnZu_gjl.d.ts.map +1 -0
- package/dist/run-score-iEEAWiBY.js +41 -0
- package/dist/run-score-iEEAWiBY.js.map +1 -0
- package/dist/runtime-trajectory-1gyaTOoC.js +93 -0
- package/dist/runtime-trajectory-1gyaTOoC.js.map +1 -0
- package/dist/runtime-trajectory-BvSZcCHD.d.ts +50 -0
- package/dist/runtime-trajectory-BvSZcCHD.d.ts.map +1 -0
- package/dist/schema-BtVldJ3T.d.ts +206 -0
- package/dist/schema-BtVldJ3T.d.ts.map +1 -0
- package/dist/schema-C6DW4ZHR.js +821 -0
- package/dist/schema-C6DW4ZHR.js.map +1 -0
- package/dist/schema-CRhEY1SO.js +69 -0
- package/dist/schema-CRhEY1SO.js.map +1 -0
- package/dist/schema-Cef2cFmb.d.ts +408 -0
- package/dist/schema-Cef2cFmb.d.ts.map +1 -0
- package/dist/semantic-concept-judge-B6cWNJ2K.js +725 -0
- package/dist/semantic-concept-judge-B6cWNJ2K.js.map +1 -0
- package/dist/sequential-Br0mAPHA.js +148 -0
- package/dist/sequential-Br0mAPHA.js.map +1 -0
- package/dist/sequential-CYwq6Ff_.d.ts +141 -0
- package/dist/sequential-CYwq6Ff_.d.ts.map +1 -0
- package/dist/series-convergence-CjO2QdRW.js +43 -0
- package/dist/series-convergence-CjO2QdRW.js.map +1 -0
- package/dist/series-convergence-ofsqPWhs.d.ts +35 -0
- package/dist/series-convergence-ofsqPWhs.d.ts.map +1 -0
- package/dist/server-m5D9cvnG.js +1040 -0
- package/dist/server-m5D9cvnG.js.map +1 -0
- package/dist/skill-usage-C_pXm7lP.d.ts +534 -0
- package/dist/skill-usage-C_pXm7lP.d.ts.map +1 -0
- package/dist/skillopt-optimization-method-B7wX7XkF.d.ts +1739 -0
- package/dist/skillopt-optimization-method-B7wX7XkF.d.ts.map +1 -0
- package/dist/skillopt-optimization-method-D4ODwFVV.js +7712 -0
- package/dist/skillopt-optimization-method-D4ODwFVV.js.map +1 -0
- package/dist/statistics-Cmj6nynr.d.ts +514 -0
- package/dist/statistics-Cmj6nynr.d.ts.map +1 -0
- package/dist/statistics-CnnxdpOg.js +1437 -0
- package/dist/statistics-CnnxdpOg.js.map +1 -0
- package/dist/store-CT9YIIve.d.ts +117 -0
- package/dist/store-CT9YIIve.d.ts.map +1 -0
- package/dist/store-CxJry_cs.d.ts +229 -0
- package/dist/store-CxJry_cs.d.ts.map +1 -0
- package/dist/storyboard/index.d.ts +84 -203
- package/dist/storyboard/index.d.ts.map +1 -0
- package/dist/storyboard/index.js +609 -542
- package/dist/storyboard/index.js.map +1 -1
- package/dist/summary-report-BNs5nmXI.js +862 -0
- package/dist/summary-report-BNs5nmXI.js.map +1 -0
- package/dist/summary-report-Cj9gdw4i.d.ts +407 -0
- package/dist/summary-report-Cj9gdw4i.d.ts.map +1 -0
- package/dist/supervisor-run/index.d.ts +2 -959
- package/dist/supervisor-run/index.js +2 -65
- package/dist/supervisor-run-_lnTLM3z.js +1679 -0
- package/dist/supervisor-run-_lnTLM3z.js.map +1 -0
- package/dist/task-failure-attributes-CQZlB3et.js +311 -0
- package/dist/task-failure-attributes-CQZlB3et.js.map +1 -0
- package/dist/test-graded-scenario-BsqWLmPt.js +318 -0
- package/dist/test-graded-scenario-BsqWLmPt.js.map +1 -0
- package/dist/test-graded-scenario-D1TaI2va.d.ts +141 -0
- package/dist/test-graded-scenario-D1TaI2va.d.ts.map +1 -0
- package/dist/tools-BmuN627J.js +1085 -0
- package/dist/tools-BmuN627J.js.map +1 -0
- package/dist/trace-attributes.d.ts +2 -52
- package/dist/trace-attributes.js +131 -61
- package/dist/trace-attributes.js.map +1 -1
- package/dist/traces.d.ts +12 -2365
- package/dist/traces.js +12 -252
- package/dist/trajectory-D_7rLrvE.js +56 -0
- package/dist/trajectory-D_7rLrvE.js.map +1 -0
- package/dist/types-DGsxbAEd.d.ts +387 -0
- package/dist/types-DGsxbAEd.d.ts.map +1 -0
- package/dist/types-k9tZGKUg.d.ts +640 -0
- package/dist/types-k9tZGKUg.d.ts.map +1 -0
- package/dist/verdict-Dps8_okt.d.ts +37 -0
- package/dist/verdict-Dps8_okt.d.ts.map +1 -0
- package/dist/wire/index.d.ts +702 -1173
- package/dist/wire/index.d.ts.map +1 -0
- package/dist/wire/index.js +2 -81
- package/package.json +17 -9
- package/dist/benchmarks/index.js.map +0 -1
- package/dist/campaign/index.js.map +0 -1
- package/dist/chunk-2QU3YOPR.js +0 -7374
- package/dist/chunk-2QU3YOPR.js.map +0 -1
- package/dist/chunk-3OCR4R5I.js +0 -728
- package/dist/chunk-3OCR4R5I.js.map +0 -1
- package/dist/chunk-3RF76KTD.js +0 -84
- package/dist/chunk-3RF76KTD.js.map +0 -1
- package/dist/chunk-56TAVBOK.js +0 -698
- package/dist/chunk-5DTSBUL2.js +0 -159
- package/dist/chunk-5DTSBUL2.js.map +0 -1
- package/dist/chunk-7FO3TNPI.js +0 -232
- package/dist/chunk-7FO3TNPI.js.map +0 -1
- package/dist/chunk-7ZZMD7UK.js +0 -386
- package/dist/chunk-7ZZMD7UK.js.map +0 -1
- package/dist/chunk-BOD4O7OF.js +0 -40
- package/dist/chunk-BOD4O7OF.js.map +0 -1
- package/dist/chunk-BSO5JDQH.js +0 -2335
- package/dist/chunk-BSO5JDQH.js.map +0 -1
- package/dist/chunk-C6LXANRU.js +0 -1550
- package/dist/chunk-C6LXANRU.js.map +0 -1
- package/dist/chunk-DODXQREJ.js +0 -752
- package/dist/chunk-DODXQREJ.js.map +0 -1
- package/dist/chunk-DRYIUNWY.js +0 -622
- package/dist/chunk-DRYIUNWY.js.map +0 -1
- package/dist/chunk-E7QXT7SX.js +0 -183
- package/dist/chunk-E7QXT7SX.js.map +0 -1
- package/dist/chunk-EG66UGL4.js +0 -341
- package/dist/chunk-EG66UGL4.js.map +0 -1
- package/dist/chunk-FXTVJPYD.js +0 -576
- package/dist/chunk-FXTVJPYD.js.map +0 -1
- package/dist/chunk-G7MGMCZD.js +0 -153
- package/dist/chunk-G7MGMCZD.js.map +0 -1
- package/dist/chunk-GGE4NNQT.js +0 -65
- package/dist/chunk-GGE4NNQT.js.map +0 -1
- package/dist/chunk-H23X7XKK.js +0 -181
- package/dist/chunk-H23X7XKK.js.map +0 -1
- package/dist/chunk-HHWE3POT.js +0 -94
- package/dist/chunk-HHWE3POT.js.map +0 -1
- package/dist/chunk-HPWUNB47.js +0 -289
- package/dist/chunk-HPWUNB47.js.map +0 -1
- package/dist/chunk-IYCLP2N2.js +0 -766
- package/dist/chunk-IYCLP2N2.js.map +0 -1
- package/dist/chunk-JHCHEVET.js +0 -274
- package/dist/chunk-JHCHEVET.js.map +0 -1
- package/dist/chunk-JQSF5DQT.js +0 -701
- package/dist/chunk-JQSF5DQT.js.map +0 -1
- package/dist/chunk-K4DBDHLK.js +0 -158
- package/dist/chunk-K4DBDHLK.js.map +0 -1
- package/dist/chunk-K6N6XJJX.js +0 -306
- package/dist/chunk-K6N6XJJX.js.map +0 -1
- package/dist/chunk-M4YBQKIJ.js +0 -1040
- package/dist/chunk-M4YBQKIJ.js.map +0 -1
- package/dist/chunk-MA6HLL3S.js +0 -65
- package/dist/chunk-MA6HLL3S.js.map +0 -1
- package/dist/chunk-MAZ26DC7.js +0 -99
- package/dist/chunk-MAZ26DC7.js.map +0 -1
- package/dist/chunk-NPCTHQIO.js +0 -91
- package/dist/chunk-NPCTHQIO.js.map +0 -1
- package/dist/chunk-NY44NC4A.js +0 -1056
- package/dist/chunk-NY44NC4A.js.map +0 -1
- package/dist/chunk-OIUOT4QD.js +0 -44
- package/dist/chunk-OIUOT4QD.js.map +0 -1
- package/dist/chunk-ONWEPEDO.js +0 -57
- package/dist/chunk-ONWEPEDO.js.map +0 -1
- package/dist/chunk-OWN5NPMC.js +0 -152
- package/dist/chunk-OWN5NPMC.js.map +0 -1
- package/dist/chunk-P6FYH6K4.js +0 -1161
- package/dist/chunk-P6FYH6K4.js.map +0 -1
- package/dist/chunk-PC4UYEBM.js +0 -166
- package/dist/chunk-PC4UYEBM.js.map +0 -1
- package/dist/chunk-PC5DOSM7.js +0 -579
- package/dist/chunk-PC5DOSM7.js.map +0 -1
- package/dist/chunk-PXE2VKMX.js +0 -140
- package/dist/chunk-PXE2VKMX.js.map +0 -1
- package/dist/chunk-PZ5AY32C.js +0 -10
- package/dist/chunk-PZ5AY32C.js.map +0 -1
- package/dist/chunk-QB6BDBP2.js +0 -4464
- package/dist/chunk-QB6BDBP2.js.map +0 -1
- package/dist/chunk-RXHCETDZ.js +0 -536
- package/dist/chunk-RXHCETDZ.js.map +0 -1
- package/dist/chunk-RZTMDUO7.js +0 -49
- package/dist/chunk-RZTMDUO7.js.map +0 -1
- package/dist/chunk-SFLLL76A.js +0 -669
- package/dist/chunk-SFLLL76A.js.map +0 -1
- package/dist/chunk-SZLVEKMJ.js +0 -1446
- package/dist/chunk-SZLVEKMJ.js.map +0 -1
- package/dist/chunk-T4SQEITX.js +0 -95
- package/dist/chunk-T4SQEITX.js.map +0 -1
- package/dist/chunk-T6RLYGAD.js +0 -158
- package/dist/chunk-T6RLYGAD.js.map +0 -1
- package/dist/chunk-TJVT4QFF.js +0 -911
- package/dist/chunk-TJVT4QFF.js.map +0 -1
- package/dist/chunk-TQ7LNKZ3.js +0 -136
- package/dist/chunk-TQ7LNKZ3.js.map +0 -1
- package/dist/chunk-U4L7JRPZ.js +0 -1706
- package/dist/chunk-U4L7JRPZ.js.map +0 -1
- package/dist/chunk-U4PHLT2N.js +0 -419
- package/dist/chunk-U4PHLT2N.js.map +0 -1
- package/dist/chunk-VCZ5FQYW.js +0 -928
- package/dist/chunk-VCZ5FQYW.js.map +0 -1
- package/dist/chunk-VI2UW6B6.js +0 -162
- package/dist/chunk-VI2UW6B6.js.map +0 -1
- package/dist/chunk-VQMK5FMP.js +0 -247
- package/dist/chunk-VQMK5FMP.js.map +0 -1
- package/dist/chunk-WGXIEX7P.js +0 -116
- package/dist/chunk-WGXIEX7P.js.map +0 -1
- package/dist/chunk-WVATSFCP.js +0 -1553
- package/dist/chunk-WVATSFCP.js.map +0 -1
- package/dist/chunk-X4YIBDER.js +0 -1662
- package/dist/chunk-X4YIBDER.js.map +0 -1
- package/dist/chunk-YQN4ICPP.js +0 -355
- package/dist/chunk-YQN4ICPP.js.map +0 -1
- package/dist/chunk-ZET2UAYW.js +0 -89
- package/dist/chunk-ZET2UAYW.js.map +0 -1
- package/dist/chunk-ZHTZ4EYI.js +0 -1212
- package/dist/chunk-ZHTZ4EYI.js.map +0 -1
- package/dist/control.js.map +0 -1
- package/dist/hosted/index.js.map +0 -1
- package/dist/matrix/index.js.map +0 -1
- package/dist/reporting.js.map +0 -1
- package/dist/rollout/index.js.map +0 -1
- package/dist/run-campaign-OJJ7CZF4.js +0 -18
- package/dist/run-campaign-OJJ7CZF4.js.map +0 -1
- package/dist/supervisor-run/index.js.map +0 -1
- package/dist/traces.js.map +0 -1
- package/dist/wire/index.js.map +0 -1
package/dist/chunk-BSO5JDQH.js
DELETED
|
@@ -1,2335 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
executionTrackByLane
|
|
3
|
-
} from "./chunk-HHWE3POT.js";
|
|
4
|
-
import {
|
|
5
|
-
combineAbortSignals
|
|
6
|
-
} from "./chunk-WGXIEX7P.js";
|
|
7
|
-
import {
|
|
8
|
-
LlmClient,
|
|
9
|
-
callLlm,
|
|
10
|
-
costReceiptFromLlm,
|
|
11
|
-
costReceiptFromLlmError,
|
|
12
|
-
maximumChargeForLlmRequest
|
|
13
|
-
} from "./chunk-SFLLL76A.js";
|
|
14
|
-
import {
|
|
15
|
-
CostLedger
|
|
16
|
-
} from "./chunk-VCZ5FQYW.js";
|
|
17
|
-
import {
|
|
18
|
-
buildTraceAnalystTools,
|
|
19
|
-
runTraceAnalysisLoop,
|
|
20
|
-
spanEpochMillis
|
|
21
|
-
} from "./chunk-P6FYH6K4.js";
|
|
22
|
-
import {
|
|
23
|
-
LLM_CONTEXT_TOKENS,
|
|
24
|
-
LLM_INPUT_TOKEN_ATTR_KEYS,
|
|
25
|
-
LLM_OUTPUT_TOKEN_ATTR_KEYS,
|
|
26
|
-
TOOL_NAME_ATTR_KEYS
|
|
27
|
-
} from "./chunk-K4DBDHLK.js";
|
|
28
|
-
|
|
29
|
-
// src/analyst/ax-service.ts
|
|
30
|
-
import { ai } from "@ax-llm/ax";
|
|
31
|
-
var configuredModels = /* @__PURE__ */ new WeakMap();
|
|
32
|
-
function createAnalystAi(config) {
|
|
33
|
-
const model = config.model.trim();
|
|
34
|
-
if (!model) throw new TypeError("createAnalystAi: model must be a non-empty string");
|
|
35
|
-
const args = {
|
|
36
|
-
name: config.provider ?? "openai",
|
|
37
|
-
apiKey: config.apiKey,
|
|
38
|
-
...config.baseUrl ? { apiURL: config.baseUrl } : {},
|
|
39
|
-
...config.headers ? { headers: config.headers } : {},
|
|
40
|
-
config: { model }
|
|
41
|
-
};
|
|
42
|
-
const service = ai(args);
|
|
43
|
-
configuredModels.set(service, model);
|
|
44
|
-
return service;
|
|
45
|
-
}
|
|
46
|
-
function getConfiguredAnalystModel(service) {
|
|
47
|
-
return configuredModels.get(service);
|
|
48
|
-
}
|
|
49
|
-
function resolveAnalystModel(service, override) {
|
|
50
|
-
if (override !== void 0) {
|
|
51
|
-
const model2 = override.trim();
|
|
52
|
-
if (!model2) throw new TypeError("createTraceAnalystKind: model must be a non-empty string");
|
|
53
|
-
return model2;
|
|
54
|
-
}
|
|
55
|
-
const model = getConfiguredAnalystModel(service)?.trim();
|
|
56
|
-
if (!model) {
|
|
57
|
-
throw new TypeError(
|
|
58
|
-
"createTraceAnalystKind: model is required for Ax services not created by createAnalystAi()"
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
return model;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// src/analyst/chat-client.ts
|
|
65
|
-
function createChatClient(opts) {
|
|
66
|
-
switch (opts.transport) {
|
|
67
|
-
case "router":
|
|
68
|
-
return wrapLlmClient(
|
|
69
|
-
opts.transport,
|
|
70
|
-
opts.defaultModel,
|
|
71
|
-
new LlmClient({
|
|
72
|
-
baseUrl: opts.baseUrl ?? "https://router.tangle.tools/v1",
|
|
73
|
-
apiKey: opts.apiKey,
|
|
74
|
-
maximumAttempts: opts.maximumAttempts
|
|
75
|
-
})
|
|
76
|
-
);
|
|
77
|
-
case "cli-bridge":
|
|
78
|
-
return wrapLlmClient(
|
|
79
|
-
opts.transport,
|
|
80
|
-
opts.defaultModel,
|
|
81
|
-
new LlmClient({
|
|
82
|
-
baseUrl: opts.baseUrl ?? "http://127.0.0.1:3344/v1",
|
|
83
|
-
apiKey: opts.bearer ?? "",
|
|
84
|
-
maximumAttempts: opts.maximumAttempts
|
|
85
|
-
})
|
|
86
|
-
);
|
|
87
|
-
case "direct-provider":
|
|
88
|
-
return wrapLlmClient(
|
|
89
|
-
opts.transport,
|
|
90
|
-
opts.defaultModel,
|
|
91
|
-
new LlmClient({
|
|
92
|
-
baseUrl: opts.baseUrl,
|
|
93
|
-
apiKey: opts.apiKey,
|
|
94
|
-
maximumAttempts: opts.maximumAttempts
|
|
95
|
-
})
|
|
96
|
-
);
|
|
97
|
-
case "sandbox-sdk":
|
|
98
|
-
return {
|
|
99
|
-
transport: "sandbox-sdk",
|
|
100
|
-
defaultModel: opts.defaultModel,
|
|
101
|
-
maximumAttempts: opts.maximumAttempts,
|
|
102
|
-
chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts)
|
|
103
|
-
};
|
|
104
|
-
case "custom":
|
|
105
|
-
return {
|
|
106
|
-
transport: "custom",
|
|
107
|
-
defaultModel: opts.defaultModel,
|
|
108
|
-
maximumAttempts: opts.maximumAttempts,
|
|
109
|
-
chat: async (req, callOpts) => opts.chat(resolveModel(req, opts.defaultModel), callOpts)
|
|
110
|
-
};
|
|
111
|
-
case "mock":
|
|
112
|
-
return {
|
|
113
|
-
transport: "mock",
|
|
114
|
-
defaultModel: opts.defaultModel,
|
|
115
|
-
maximumAttempts: 1,
|
|
116
|
-
chat: async (req, callOpts) => opts.handler(resolveModel(req, opts.defaultModel), callOpts)
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
function wrapLlmClient(transport, defaultModel, inner) {
|
|
121
|
-
return {
|
|
122
|
-
transport,
|
|
123
|
-
defaultModel,
|
|
124
|
-
maximumAttempts: inner.maximumAttempts,
|
|
125
|
-
chat: (req, callOpts) => {
|
|
126
|
-
const resolved = resolveModel(req, defaultModel);
|
|
127
|
-
const request = {
|
|
128
|
-
model: resolved.model,
|
|
129
|
-
messages: req.messages,
|
|
130
|
-
jsonMode: req.jsonMode,
|
|
131
|
-
jsonSchema: req.jsonSchema,
|
|
132
|
-
temperature: req.temperature,
|
|
133
|
-
maxTokens: req.maxTokens,
|
|
134
|
-
thinking: req.thinking,
|
|
135
|
-
timeoutMs: req.timeoutMs
|
|
136
|
-
};
|
|
137
|
-
return inner.call(request, {
|
|
138
|
-
signal: callOpts?.signal,
|
|
139
|
-
idempotencyKey: callOpts?.idempotencyKey
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
function resolveModel(req, defaultModel) {
|
|
145
|
-
if (req.model) return req;
|
|
146
|
-
if (!defaultModel) {
|
|
147
|
-
throw new Error(
|
|
148
|
-
"ChatClient.chat: no model on request and no defaultModel on the client. Either pass req.model or bind defaultModel at createChatClient()."
|
|
149
|
-
);
|
|
150
|
-
}
|
|
151
|
-
return { ...req, model: defaultModel };
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
// src/trace-analyst/behavioral-metrics.ts
|
|
155
|
-
var INPUT_GROWTH_FACTOR = 3;
|
|
156
|
-
var MIN_TOOL_CALLS = 3;
|
|
157
|
-
var VERIFY_RE = /verif|eval|inspect|check|assert|validat|review|confirm|read|grep|glob|search|view|\blist\b|\bls\b|\bcat\b|\bfind\b|diff|status|\btest|lint|typecheck/i;
|
|
158
|
-
function num(v) {
|
|
159
|
-
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
160
|
-
}
|
|
161
|
-
function numAttr(attrs, keys) {
|
|
162
|
-
for (const key of keys) {
|
|
163
|
-
const value = num(attrs[key]);
|
|
164
|
-
if (value !== null) return value;
|
|
165
|
-
}
|
|
166
|
-
return null;
|
|
167
|
-
}
|
|
168
|
-
function inputTokensOf(s) {
|
|
169
|
-
const exactContext = num(s.attributes[LLM_CONTEXT_TOKENS]);
|
|
170
|
-
if (exactContext !== null) return exactContext;
|
|
171
|
-
return numAttr(s.attributes, LLM_INPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes["llm.usage.input_tokens"]);
|
|
172
|
-
}
|
|
173
|
-
function outputTokensOf(s) {
|
|
174
|
-
return numAttr(s.attributes, LLM_OUTPUT_TOKEN_ATTR_KEYS) ?? num(s.attributes["llm.usage.output_tokens"]);
|
|
175
|
-
}
|
|
176
|
-
function stepOf(s) {
|
|
177
|
-
return num(s.attributes.step);
|
|
178
|
-
}
|
|
179
|
-
function toolNameOf(s) {
|
|
180
|
-
if (s.tool_name) return s.tool_name;
|
|
181
|
-
for (const key of TOOL_NAME_ATTR_KEYS) {
|
|
182
|
-
const t = s.attributes[key];
|
|
183
|
-
if (typeof t === "string" && t.length > 0) return t;
|
|
184
|
-
}
|
|
185
|
-
return null;
|
|
186
|
-
}
|
|
187
|
-
function computeTraceMetrics(spans) {
|
|
188
|
-
const traceIds = new Set(spans.map((span) => span.trace_id));
|
|
189
|
-
if (traceIds.size > 1) {
|
|
190
|
-
throw new Error(
|
|
191
|
-
`computeTraceMetrics: expected spans from one trace, received ${traceIds.size} traces`
|
|
192
|
-
);
|
|
193
|
-
}
|
|
194
|
-
const traceId = traceIds.values().next().value ?? null;
|
|
195
|
-
const samples = spans.map((span) => ({
|
|
196
|
-
span,
|
|
197
|
-
input: inputTokensOf(span),
|
|
198
|
-
output: outputTokensOf(span),
|
|
199
|
-
step: stepOf(span)
|
|
200
|
-
}));
|
|
201
|
-
const llmSamples = samples.filter((sample) => sample.span.kind === "LLM");
|
|
202
|
-
const tokenSamples = llmSamples.length > 0 ? llmSamples : samples.filter((sample) => sample.input !== null || sample.output !== null);
|
|
203
|
-
const tokenSequences = buildTokenSequences(tokenSamples, spans);
|
|
204
|
-
const primarySequence = tokenSequences[0];
|
|
205
|
-
const inputTokenTrajectory = primarySequence?.inputTokenTrajectory.filter((value) => value !== null) ?? [];
|
|
206
|
-
const outputTokenTrajectory = primarySequence?.outputTokenTrajectory.filter((value) => value !== null) ?? [];
|
|
207
|
-
const toolHistogram = {};
|
|
208
|
-
let hasSelfVerification = false;
|
|
209
|
-
for (const s of spans) {
|
|
210
|
-
const tool = toolNameOf(s);
|
|
211
|
-
if (tool) {
|
|
212
|
-
toolHistogram[tool] = (toolHistogram[tool] ?? 0) + 1;
|
|
213
|
-
if (VERIFY_RE.test(tool)) hasSelfVerification = true;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
const totalToolCalls = Object.values(toolHistogram).reduce((a, b) => a + b, 0);
|
|
217
|
-
const distinctTools = Object.keys(toolHistogram).length;
|
|
218
|
-
const toolDiversityRatio = totalToolCalls === 0 ? 1 : distinctTools / totalToolCalls;
|
|
219
|
-
const signals = [];
|
|
220
|
-
const seenTokenSignals = /* @__PURE__ */ new Set();
|
|
221
|
-
for (const sequence of tokenSequences) {
|
|
222
|
-
for (const signal of tokenSignals(sequence)) {
|
|
223
|
-
if (seenTokenSignals.has(signal.code)) continue;
|
|
224
|
-
seenTokenSignals.add(signal.code);
|
|
225
|
-
signals.push(signal);
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
if (totalToolCalls >= MIN_TOOL_CALLS && distinctTools === 1) {
|
|
229
|
-
const only = Object.keys(toolHistogram)[0];
|
|
230
|
-
signals.push({
|
|
231
|
-
code: "single-tool-dependency",
|
|
232
|
-
severity: "medium",
|
|
233
|
-
detail: `All ${totalToolCalls} observed tool calls are \`${only}\`; no alternate tool call was observed.`,
|
|
234
|
-
evidence: { tool: only, calls: totalToolCalls, distinct_tools: 1 }
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
if (totalToolCalls >= MIN_TOOL_CALLS && !hasSelfVerification) {
|
|
238
|
-
signals.push({
|
|
239
|
-
code: "no-self-verification",
|
|
240
|
-
severity: "medium",
|
|
241
|
-
detail: `${totalToolCalls} tool calls were observed without a verification-named tool call.`,
|
|
242
|
-
evidence: { tool_calls: totalToolCalls, verification_calls: 0 }
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
return {
|
|
246
|
-
traceId,
|
|
247
|
-
llmCallCount: tokenSamples.length,
|
|
248
|
-
tokenSequences,
|
|
249
|
-
inputTokenTrajectory,
|
|
250
|
-
outputTokenTrajectory,
|
|
251
|
-
toolHistogram,
|
|
252
|
-
totalToolCalls,
|
|
253
|
-
distinctTools,
|
|
254
|
-
toolDiversityRatio,
|
|
255
|
-
hasSelfVerification,
|
|
256
|
-
signals
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
function buildTokenSequences(samples, spans) {
|
|
260
|
-
const spansById = new Map(spans.map((span) => [span.span_id, span]));
|
|
261
|
-
const executionScopeFor = createTokenExecutionScopeResolver(spansById);
|
|
262
|
-
const scopedSamples = samples.map((sample) => ({
|
|
263
|
-
sample,
|
|
264
|
-
...executionScopeFor(sample.span)
|
|
265
|
-
}));
|
|
266
|
-
const trackByLane = executionTrackByLane(scopedSamples);
|
|
267
|
-
const byTrack = /* @__PURE__ */ new Map();
|
|
268
|
-
for (const scoped of scopedSamples) {
|
|
269
|
-
const trackId = trackByLane.get(scoped.key);
|
|
270
|
-
const track = byTrack.get(trackId) ?? { scopeId: scoped.scopeId, samples: [] };
|
|
271
|
-
track.samples.push(scoped.sample);
|
|
272
|
-
byTrack.set(trackId, track);
|
|
273
|
-
}
|
|
274
|
-
const sequences = [];
|
|
275
|
-
for (const { scopeId, samples: tracked } of byTrack.values()) {
|
|
276
|
-
const runs = serialTokenRuns([...tracked].sort(compareTokenSamples));
|
|
277
|
-
runs.forEach((run, index) => {
|
|
278
|
-
sequences.push({
|
|
279
|
-
scopeId: runs.length === 1 ? scopeId : `${scopeId}#${index + 1}`,
|
|
280
|
-
spanIds: run.map((sample) => sample.span.span_id),
|
|
281
|
-
inputTokenTrajectory: run.map((sample) => sample.input),
|
|
282
|
-
outputTokenTrajectory: run.map((sample) => sample.output)
|
|
283
|
-
});
|
|
284
|
-
});
|
|
285
|
-
}
|
|
286
|
-
return sequences.sort(
|
|
287
|
-
(a, b) => b.spanIds.length - a.spanIds.length || a.scopeId.localeCompare(b.scopeId) || a.spanIds[0].localeCompare(b.spanIds[0])
|
|
288
|
-
);
|
|
289
|
-
}
|
|
290
|
-
function createTokenExecutionScopeResolver(spansById) {
|
|
291
|
-
const cache = /* @__PURE__ */ new Map();
|
|
292
|
-
return (span) => {
|
|
293
|
-
const ancestry = resolveAncestorScope(span.parent_span_id, spansById, cache);
|
|
294
|
-
const rootId = ancestry.rootId;
|
|
295
|
-
const scopeId = ancestry.agentId ? `span:${ancestry.agentId}` : ancestry.missingParentId ? `parent:${ancestry.missingParentId}` : rootId ? `root:${rootId}` : span.agent_name ? `agent:${span.agent_name}` : `trace:${span.trace_id}`;
|
|
296
|
-
const scopeSpanId = ancestry.agentId ?? ancestry.missingParentId ?? rootId;
|
|
297
|
-
const laneSpan = ancestry.laneSpanId ? spansById.get(ancestry.laneSpanId) : void 0;
|
|
298
|
-
const direct = scopeSpanId === null || ancestry.laneSpanId === scopeSpanId;
|
|
299
|
-
const timedSpan = direct ? span : laneSpan;
|
|
300
|
-
return {
|
|
301
|
-
key: JSON.stringify([scopeId, direct ? span.span_id : ancestry.laneSpanId]),
|
|
302
|
-
scopeKey: scopeId,
|
|
303
|
-
scopeId,
|
|
304
|
-
start: timedSpan ? spanEpochMillis(timedSpan.start_time) : null,
|
|
305
|
-
end: timedSpan ? spanEpochMillis(timedSpan.end_time) : null
|
|
306
|
-
};
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
function resolveAncestorScope(startId, spansById, cache) {
|
|
310
|
-
const empty = {
|
|
311
|
-
agentId: null,
|
|
312
|
-
rootId: null,
|
|
313
|
-
missingParentId: null,
|
|
314
|
-
laneSpanId: null
|
|
315
|
-
};
|
|
316
|
-
if (!startId) return empty;
|
|
317
|
-
const path = [];
|
|
318
|
-
const pathIndex = /* @__PURE__ */ new Map();
|
|
319
|
-
let currentId = startId;
|
|
320
|
-
let resolved = empty;
|
|
321
|
-
while (currentId) {
|
|
322
|
-
const cached = cache.get(currentId);
|
|
323
|
-
if (cached) {
|
|
324
|
-
resolved = cached;
|
|
325
|
-
break;
|
|
326
|
-
}
|
|
327
|
-
const cycleStart = pathIndex.get(currentId);
|
|
328
|
-
if (cycleStart !== void 0) {
|
|
329
|
-
resolved = {
|
|
330
|
-
agentId: null,
|
|
331
|
-
rootId: [...path.slice(cycleStart)].sort()[0],
|
|
332
|
-
missingParentId: null,
|
|
333
|
-
laneSpanId: [...path.slice(cycleStart)].sort()[0]
|
|
334
|
-
};
|
|
335
|
-
break;
|
|
336
|
-
}
|
|
337
|
-
const current = spansById.get(currentId);
|
|
338
|
-
if (!current) {
|
|
339
|
-
resolved = {
|
|
340
|
-
agentId: null,
|
|
341
|
-
rootId: null,
|
|
342
|
-
missingParentId: currentId,
|
|
343
|
-
laneSpanId: currentId
|
|
344
|
-
};
|
|
345
|
-
break;
|
|
346
|
-
}
|
|
347
|
-
if (current.kind === "AGENT") {
|
|
348
|
-
resolved = {
|
|
349
|
-
agentId: current.span_id,
|
|
350
|
-
rootId: null,
|
|
351
|
-
missingParentId: null,
|
|
352
|
-
laneSpanId: current.span_id
|
|
353
|
-
};
|
|
354
|
-
break;
|
|
355
|
-
}
|
|
356
|
-
pathIndex.set(currentId, path.length);
|
|
357
|
-
path.push(currentId);
|
|
358
|
-
currentId = current.parent_span_id;
|
|
359
|
-
}
|
|
360
|
-
for (let index = path.length - 1; index >= 0; index -= 1) {
|
|
361
|
-
if (resolved.agentId === null && resolved.rootId === null) {
|
|
362
|
-
resolved = { ...resolved, rootId: path[index], laneSpanId: path[index] };
|
|
363
|
-
} else if (resolved.laneSpanId === (resolved.agentId ?? resolved.missingParentId ?? resolved.rootId)) {
|
|
364
|
-
resolved = { ...resolved, laneSpanId: path[index] };
|
|
365
|
-
}
|
|
366
|
-
cache.set(path[index], resolved);
|
|
367
|
-
}
|
|
368
|
-
return resolved;
|
|
369
|
-
}
|
|
370
|
-
function compareTokenSamples(a, b) {
|
|
371
|
-
const aStart = spanEpochMillis(a.span.start_time);
|
|
372
|
-
const bStart = spanEpochMillis(b.span.start_time);
|
|
373
|
-
if (aStart === null && bStart !== null) return 1;
|
|
374
|
-
if (aStart !== null && bStart === null) return -1;
|
|
375
|
-
if (aStart !== null && bStart !== null && aStart !== bStart) return aStart - bStart;
|
|
376
|
-
if (a.step !== null && b.step !== null && a.step !== b.step) return a.step - b.step;
|
|
377
|
-
return a.span.span_id.localeCompare(b.span.span_id);
|
|
378
|
-
}
|
|
379
|
-
function serialTokenRuns(ordered) {
|
|
380
|
-
const runs = [];
|
|
381
|
-
let serial = [];
|
|
382
|
-
let overlap = [];
|
|
383
|
-
let overlapEnd = Number.NEGATIVE_INFINITY;
|
|
384
|
-
const flushSerial = () => {
|
|
385
|
-
if (serial.length > 0) runs.push(serial);
|
|
386
|
-
serial = [];
|
|
387
|
-
};
|
|
388
|
-
const flushOverlap = () => {
|
|
389
|
-
if (overlap.length === 1) {
|
|
390
|
-
serial.push(overlap[0]);
|
|
391
|
-
} else if (overlap.length > 1) {
|
|
392
|
-
flushSerial();
|
|
393
|
-
for (const sample of overlap) runs.push([sample]);
|
|
394
|
-
}
|
|
395
|
-
overlap = [];
|
|
396
|
-
overlapEnd = Number.NEGATIVE_INFINITY;
|
|
397
|
-
};
|
|
398
|
-
for (const sample of ordered) {
|
|
399
|
-
const start = spanEpochMillis(sample.span.start_time);
|
|
400
|
-
const end = spanEpochMillis(sample.span.end_time);
|
|
401
|
-
if (start === null || end === null || sample.span.duration_ms <= 0 || end < start) {
|
|
402
|
-
flushOverlap();
|
|
403
|
-
flushSerial();
|
|
404
|
-
runs.push([sample]);
|
|
405
|
-
continue;
|
|
406
|
-
}
|
|
407
|
-
if (overlap.length > 0 && start >= overlapEnd) flushOverlap();
|
|
408
|
-
overlap.push(sample);
|
|
409
|
-
overlapEnd = Math.max(overlapEnd, end);
|
|
410
|
-
}
|
|
411
|
-
flushOverlap();
|
|
412
|
-
flushSerial();
|
|
413
|
-
return runs;
|
|
414
|
-
}
|
|
415
|
-
function tokenSignals(sequence) {
|
|
416
|
-
const signals = [];
|
|
417
|
-
const inputs = sequence.inputTokenTrajectory;
|
|
418
|
-
const outputs = sequence.outputTokenTrajectory;
|
|
419
|
-
if (inputs.length >= 3 && inputs.every((value) => value !== null)) {
|
|
420
|
-
const first = inputs[0];
|
|
421
|
-
const last = inputs[inputs.length - 1];
|
|
422
|
-
const isMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous);
|
|
423
|
-
const growthFromZero = first === 0 && last > 0;
|
|
424
|
-
const growth = growthFromZero ? Infinity : first > 0 ? last / first : 0;
|
|
425
|
-
if (isMonotonic && last > first && growth >= INPUT_GROWTH_FACTOR) {
|
|
426
|
-
const growthLabel = growthFromZero ? "0\u2192nonzero (unbounded)" : `${growth.toFixed(1)}x`;
|
|
427
|
-
signals.push({
|
|
428
|
-
code: "monotonic-input-growth",
|
|
429
|
-
severity: "high",
|
|
430
|
-
detail: `LLM input tokens grew ${growthLabel} (${first}\u2192${last}) across ${inputs.length} serial calls without an intervening decrease.`,
|
|
431
|
-
evidence: {
|
|
432
|
-
first,
|
|
433
|
-
last,
|
|
434
|
-
growth_x: growthFromZero ? "unbounded" : Number(growth.toFixed(2)),
|
|
435
|
-
calls: inputs.length,
|
|
436
|
-
scope: sequence.scopeId,
|
|
437
|
-
first_span_id: sequence.spanIds[0],
|
|
438
|
-
last_span_id: sequence.spanIds[sequence.spanIds.length - 1]
|
|
439
|
-
}
|
|
440
|
-
});
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
if (inputs.length >= 3 && inputs.length === outputs.length && inputs.every((value) => value !== null) && outputs.every((value) => value !== null)) {
|
|
444
|
-
const first = outputs[0];
|
|
445
|
-
const last = outputs[outputs.length - 1];
|
|
446
|
-
const inputIsMonotonic = everyAdjacent(inputs, (previous, current) => current >= previous);
|
|
447
|
-
const outputIsMonotonic = everyAdjacent(outputs, (previous, current) => current <= previous);
|
|
448
|
-
const inputGrew = inputs[inputs.length - 1] > inputs[0];
|
|
449
|
-
if (inputIsMonotonic && inputGrew && outputIsMonotonic && last < first) {
|
|
450
|
-
signals.push({
|
|
451
|
-
code: "output-length-decay",
|
|
452
|
-
severity: "medium",
|
|
453
|
-
detail: `LLM output tokens shrank ${first}\u2192${last} over ${outputs.length} serial calls while input tokens increased monotonically.`,
|
|
454
|
-
evidence: {
|
|
455
|
-
first,
|
|
456
|
-
last,
|
|
457
|
-
calls: outputs.length,
|
|
458
|
-
scope: sequence.scopeId,
|
|
459
|
-
first_span_id: sequence.spanIds[0],
|
|
460
|
-
last_span_id: sequence.spanIds[sequence.spanIds.length - 1]
|
|
461
|
-
}
|
|
462
|
-
});
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
return signals;
|
|
466
|
-
}
|
|
467
|
-
function everyAdjacent(values, predicate) {
|
|
468
|
-
return values.slice(1).every((current, index) => predicate(values[index], current));
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
// src/analyst/types.ts
|
|
472
|
-
import { createHash } from "crypto";
|
|
473
|
-
function computeFindingId(input) {
|
|
474
|
-
const basis = JSON.stringify({
|
|
475
|
-
a: input.analyst_id,
|
|
476
|
-
r: input.area,
|
|
477
|
-
s: input.subject ?? "",
|
|
478
|
-
c: normalizeClaim(input.id_basis ?? input.claim)
|
|
479
|
-
});
|
|
480
|
-
return `f_${createHash("sha256").update(basis).digest("hex").slice(0, 20)}`;
|
|
481
|
-
}
|
|
482
|
-
function normalizeClaim(c) {
|
|
483
|
-
return c.toLowerCase().replace(/\s+/g, " ").replace(/[.!?;:,]+$/g, "").trim();
|
|
484
|
-
}
|
|
485
|
-
function makeFinding(init) {
|
|
486
|
-
const { id_basis, produced_at, ...rest } = init;
|
|
487
|
-
return {
|
|
488
|
-
schema_version: "1.0.0",
|
|
489
|
-
finding_id: computeFindingId({
|
|
490
|
-
analyst_id: rest.analyst_id,
|
|
491
|
-
area: rest.area,
|
|
492
|
-
subject: rest.subject,
|
|
493
|
-
claim: rest.claim,
|
|
494
|
-
id_basis
|
|
495
|
-
}),
|
|
496
|
-
produced_at: produced_at ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
497
|
-
...rest
|
|
498
|
-
};
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
// src/analyst/behavioral-analyst.ts
|
|
502
|
-
var RECOMMENDED_ACTION = {
|
|
503
|
-
"monotonic-input-growth": "Inspect context assembly; if prior history is repeatedly included, summarize completed work before the next model call.",
|
|
504
|
-
"output-length-decay": "Check late-step completeness; if shorter responses omit required work, add explicit completion criteria to the agent instructions.",
|
|
505
|
-
"single-tool-dependency": "Test whether an inspect or verification tool improves outcomes after the repeated call fails or returns no progress.",
|
|
506
|
-
"no-self-verification": "After state-changing actions, require an observable check before the agent proceeds."
|
|
507
|
-
};
|
|
508
|
-
var ANALYST_ID = "efficiency-behavioral";
|
|
509
|
-
var AGGREGATE_CLAIM = {
|
|
510
|
-
"monotonic-input-growth": (observed, analyzed) => `${observed}/${analyzed} analyzed traces showed input tokens grow from zero to nonzero or to at least 3x their initial value across at least 3 serial model calls without a decrease.`,
|
|
511
|
-
"output-length-decay": (observed, analyzed) => `${observed}/${analyzed} analyzed traces showed output tokens decrease while input tokens increased monotonically across at least 3 serial model calls.`,
|
|
512
|
-
"single-tool-dependency": (observed, analyzed) => `${observed}/${analyzed} analyzed traces used only one named tool across at least 3 tool calls.`,
|
|
513
|
-
"no-self-verification": (observed, analyzed) => `${observed}/${analyzed} analyzed traces had at least 3 tool calls without a verification-named tool call.`
|
|
514
|
-
};
|
|
515
|
-
function deriveEfficiencyFindings(metrics, opts = {}) {
|
|
516
|
-
const analystId = opts.analystId ?? ANALYST_ID;
|
|
517
|
-
const traceId = metrics.traceId;
|
|
518
|
-
return metrics.signals.map(
|
|
519
|
-
(sig) => makeFinding({
|
|
520
|
-
analyst_id: analystId,
|
|
521
|
-
area: "efficiency",
|
|
522
|
-
subject: sig.code,
|
|
523
|
-
claim: sig.detail,
|
|
524
|
-
severity: sig.severity,
|
|
525
|
-
// Deterministic arithmetic over spans, not a model judgment → certain.
|
|
526
|
-
confidence: 1,
|
|
527
|
-
evidence_refs: [
|
|
528
|
-
{
|
|
529
|
-
kind: "metric",
|
|
530
|
-
uri: traceId ? `metric://trace/${encodeURIComponent(traceId)}/efficiency/${sig.code}` : `metric://efficiency/${sig.code}`,
|
|
531
|
-
excerpt: JSON.stringify(sig.evidence)
|
|
532
|
-
}
|
|
533
|
-
],
|
|
534
|
-
recommended_action: RECOMMENDED_ACTION[sig.code],
|
|
535
|
-
metadata: {
|
|
536
|
-
deterministic: true,
|
|
537
|
-
evidence: sig.evidence,
|
|
538
|
-
...traceId ? { trace_id: traceId } : {}
|
|
539
|
-
},
|
|
540
|
-
id_basis: sig.code,
|
|
541
|
-
...opts.producedAt ? { produced_at: opts.producedAt } : {}
|
|
542
|
-
})
|
|
543
|
-
);
|
|
544
|
-
}
|
|
545
|
-
function behavioralAnalyst() {
|
|
546
|
-
return {
|
|
547
|
-
id: ANALYST_ID,
|
|
548
|
-
description: "Deterministic behavioral/efficiency findings over OTLP spans \u2014 token-growth, output-decay, tool-monoculture, missing self-verification. Zero LLM; model-agnostic by construction.",
|
|
549
|
-
inputKind: "trace-store",
|
|
550
|
-
cost: { kind: "deterministic" },
|
|
551
|
-
version: "2.0.0",
|
|
552
|
-
async analyze(store) {
|
|
553
|
-
const overview = await store.getOverview();
|
|
554
|
-
const analyzedTraceIds = [...new Set(overview.sample_trace_ids)].sort();
|
|
555
|
-
const findingsById = /* @__PURE__ */ new Map();
|
|
556
|
-
for (const traceId of analyzedTraceIds) {
|
|
557
|
-
const viewed = await store.viewTrace({ trace_id: traceId });
|
|
558
|
-
if (viewed.trace_id !== traceId) {
|
|
559
|
-
throw new Error(
|
|
560
|
-
`behavioralAnalyst: requested trace '${traceId}', received '${viewed.trace_id}'`
|
|
561
|
-
);
|
|
562
|
-
}
|
|
563
|
-
if (!viewed.spans) {
|
|
564
|
-
throw new Error(
|
|
565
|
-
`behavioralAnalyst: trace '${traceId}' is oversized; complete spans are required`
|
|
566
|
-
);
|
|
567
|
-
}
|
|
568
|
-
const metrics = computeTraceMetrics(viewed.spans);
|
|
569
|
-
if (metrics.traceId !== null && metrics.traceId !== traceId) {
|
|
570
|
-
throw new Error(
|
|
571
|
-
`behavioralAnalyst: requested trace '${traceId}', received '${metrics.traceId}'`
|
|
572
|
-
);
|
|
573
|
-
}
|
|
574
|
-
for (const finding of deriveEfficiencyFindings(metrics)) {
|
|
575
|
-
const current = findingsById.get(finding.finding_id);
|
|
576
|
-
if (!current) {
|
|
577
|
-
findingsById.set(finding.finding_id, {
|
|
578
|
-
finding,
|
|
579
|
-
traceIds: [traceId],
|
|
580
|
-
evidence: [...finding.evidence_refs]
|
|
581
|
-
});
|
|
582
|
-
continue;
|
|
583
|
-
}
|
|
584
|
-
current.traceIds.push(traceId);
|
|
585
|
-
current.evidence.push(...finding.evidence_refs);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
return [...findingsById.values()].map(({ finding, traceIds, evidence }) => ({
|
|
589
|
-
...finding,
|
|
590
|
-
claim: AGGREGATE_CLAIM[finding.subject](
|
|
591
|
-
traceIds.length,
|
|
592
|
-
analyzedTraceIds.length
|
|
593
|
-
),
|
|
594
|
-
rationale: `${traceIds.length}/${analyzedTraceIds.length} analyzed traces exhibited this pattern.`,
|
|
595
|
-
evidence_refs: evidence,
|
|
596
|
-
metadata: {
|
|
597
|
-
deterministic: true,
|
|
598
|
-
trace_ids: traceIds,
|
|
599
|
-
observed_trace_count: traceIds.length,
|
|
600
|
-
analyzed_trace_count: analyzedTraceIds.length
|
|
601
|
-
}
|
|
602
|
-
}));
|
|
603
|
-
}
|
|
604
|
-
};
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
// src/analyst/finding-subject.ts
|
|
608
|
-
import { z } from "zod";
|
|
609
|
-
var FINDING_SUBJECT_KINDS = [
|
|
610
|
-
"knowledge.wiki",
|
|
611
|
-
"knowledge.claim",
|
|
612
|
-
"knowledge.raw",
|
|
613
|
-
"knowledge.stale",
|
|
614
|
-
"system-prompt",
|
|
615
|
-
"skill",
|
|
616
|
-
"tool-doc",
|
|
617
|
-
"new-tool",
|
|
618
|
-
"mcp",
|
|
619
|
-
"hook",
|
|
620
|
-
"subagent",
|
|
621
|
-
"workflow",
|
|
622
|
-
"rollout-policy",
|
|
623
|
-
"agent-profile",
|
|
624
|
-
"code",
|
|
625
|
-
"rag",
|
|
626
|
-
"memory",
|
|
627
|
-
"scaffolding",
|
|
628
|
-
"output-schema",
|
|
629
|
-
"websearch.outdated",
|
|
630
|
-
"prior-run-summary",
|
|
631
|
-
"cluster"
|
|
632
|
-
];
|
|
633
|
-
function parseFindingSubject(raw) {
|
|
634
|
-
if (raw === null || raw === void 0) return null;
|
|
635
|
-
const trimmed = raw.trim();
|
|
636
|
-
if (trimmed.length === 0) return null;
|
|
637
|
-
const wiki = trimmed.match(
|
|
638
|
-
/^agent-knowledge:wiki:([a-z0-9][a-z0-9-]*)(?:#([a-z0-9][a-z0-9-]*))?$/
|
|
639
|
-
);
|
|
640
|
-
if (wiki)
|
|
641
|
-
return { kind: "knowledge.wiki", slug: wiki[1], ...wiki[2] ? { heading: wiki[2] } : {} };
|
|
642
|
-
const claim = trimmed.match(/^agent-knowledge:claim:(.+)$/);
|
|
643
|
-
if (claim && claim[1].trim().length > 0)
|
|
644
|
-
return { kind: "knowledge.claim", topic: claim[1].trim() };
|
|
645
|
-
const raw_ = trimmed.match(/^agent-knowledge:raw:(.+)$/);
|
|
646
|
-
if (raw_ && raw_[1].trim().length > 0)
|
|
647
|
-
return { kind: "knowledge.raw", sourceId: raw_[1].trim() };
|
|
648
|
-
const stale = trimmed.match(/^agent-knowledge:stale:([a-z0-9][a-z0-9-]*)$/);
|
|
649
|
-
if (stale) return { kind: "knowledge.stale", slug: stale[1] };
|
|
650
|
-
const sp = trimmed.match(/^system-prompt:(.+)$/);
|
|
651
|
-
if (sp && sp[1].trim().length > 0) return { kind: "system-prompt", section: sp[1].trim() };
|
|
652
|
-
const skill = trimmed.match(/^skill:([a-z0-9][a-z0-9_.-]*)$/);
|
|
653
|
-
if (skill) return { kind: "skill", name: skill[1] };
|
|
654
|
-
const tdAspect = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*):(.+)$/);
|
|
655
|
-
if (tdAspect && tdAspect[2].trim().length > 0) {
|
|
656
|
-
return { kind: "tool-doc", tool: tdAspect[1], aspect: tdAspect[2].trim() };
|
|
657
|
-
}
|
|
658
|
-
const td = trimmed.match(/^tool-doc:([a-z0-9][a-z0-9_-]*)$/);
|
|
659
|
-
if (td) return { kind: "tool-doc", tool: td[1] };
|
|
660
|
-
const nt = trimmed.match(/^new-tool:([a-z0-9][a-z0-9_-]*)$/);
|
|
661
|
-
if (nt) return { kind: "new-tool", name: nt[1] };
|
|
662
|
-
const mcp = trimmed.match(/^mcp:([a-z0-9][a-z0-9_.-]*)(?::([a-z0-9][a-z0-9_.-]*))?$/);
|
|
663
|
-
if (mcp) {
|
|
664
|
-
return { kind: "mcp", server: mcp[1], ...mcp[2] ? { tool: mcp[2] } : {} };
|
|
665
|
-
}
|
|
666
|
-
const hook = trimmed.match(/^hook:([a-z0-9][a-z0-9_.-]*)$/);
|
|
667
|
-
if (hook) return { kind: "hook", name: hook[1] };
|
|
668
|
-
const subagent = trimmed.match(/^subagent:([a-z0-9][a-z0-9_.-]*)$/);
|
|
669
|
-
if (subagent) return { kind: "subagent", name: subagent[1] };
|
|
670
|
-
const workflow = trimmed.match(/^workflow:([a-z0-9][a-z0-9_.-]*)$/);
|
|
671
|
-
if (workflow) return { kind: "workflow", name: workflow[1] };
|
|
672
|
-
const rolloutPolicy = trimmed.match(/^rollout-policy:(.+)$/);
|
|
673
|
-
if (rolloutPolicy && rolloutPolicy[1].trim().length > 0) {
|
|
674
|
-
return { kind: "rollout-policy", field: rolloutPolicy[1].trim() };
|
|
675
|
-
}
|
|
676
|
-
const agentProfile = trimmed.match(/^agent-profile:(.+)$/);
|
|
677
|
-
if (agentProfile && agentProfile[1].trim().length > 0) {
|
|
678
|
-
return { kind: "agent-profile", field: agentProfile[1].trim() };
|
|
679
|
-
}
|
|
680
|
-
const code = trimmed.match(/^code:(.+)$/);
|
|
681
|
-
if (code && code[1].trim().length > 0) return { kind: "code", path: code[1].trim() };
|
|
682
|
-
const rag = trimmed.match(/^rag:([a-z0-9][a-z0-9_-]*):(.+)$/);
|
|
683
|
-
if (rag && rag[2].trim().length > 0) {
|
|
684
|
-
return { kind: "rag", corpus: rag[1], docId: rag[2].trim() };
|
|
685
|
-
}
|
|
686
|
-
const mem = trimmed.match(/^memory:(.+)$/);
|
|
687
|
-
if (mem && mem[1].trim().length > 0) return { kind: "memory", key: mem[1].trim() };
|
|
688
|
-
const sc = trimmed.match(/^scaffolding:(.+)$/);
|
|
689
|
-
if (sc && sc[1].trim().length > 0) return { kind: "scaffolding", concern: sc[1].trim() };
|
|
690
|
-
const os = trimmed.match(/^output-schema:(.+)$/);
|
|
691
|
-
if (os && os[1].trim().length > 0) return { kind: "output-schema", field: os[1].trim() };
|
|
692
|
-
const ws = trimmed.match(/^websearch:outdated:(.+)$/);
|
|
693
|
-
if (ws && ws[1].trim().length > 0) return { kind: "websearch.outdated", topic: ws[1].trim() };
|
|
694
|
-
const prs = trimmed.match(/^prior-run-summary:(.+)$/);
|
|
695
|
-
if (prs && prs[1].trim().length > 0) return { kind: "prior-run-summary", topic: prs[1].trim() };
|
|
696
|
-
if (/^[a-z0-9][a-z0-9._-]*$/.test(trimmed) && trimmed.length <= 80) {
|
|
697
|
-
return { kind: "cluster", label: trimmed };
|
|
698
|
-
}
|
|
699
|
-
return null;
|
|
700
|
-
}
|
|
701
|
-
function renderFindingSubject(s) {
|
|
702
|
-
switch (s.kind) {
|
|
703
|
-
case "knowledge.wiki":
|
|
704
|
-
return s.heading ? `agent-knowledge:wiki:${s.slug}#${s.heading}` : `agent-knowledge:wiki:${s.slug}`;
|
|
705
|
-
case "knowledge.claim":
|
|
706
|
-
return `agent-knowledge:claim:${s.topic}`;
|
|
707
|
-
case "knowledge.raw":
|
|
708
|
-
return `agent-knowledge:raw:${s.sourceId}`;
|
|
709
|
-
case "knowledge.stale":
|
|
710
|
-
return `agent-knowledge:stale:${s.slug}`;
|
|
711
|
-
case "system-prompt":
|
|
712
|
-
return `system-prompt:${s.section}`;
|
|
713
|
-
case "skill":
|
|
714
|
-
return `skill:${s.name}`;
|
|
715
|
-
case "tool-doc":
|
|
716
|
-
return s.aspect ? `tool-doc:${s.tool}:${s.aspect}` : `tool-doc:${s.tool}`;
|
|
717
|
-
case "new-tool":
|
|
718
|
-
return `new-tool:${s.name}`;
|
|
719
|
-
case "mcp":
|
|
720
|
-
return s.tool ? `mcp:${s.server}:${s.tool}` : `mcp:${s.server}`;
|
|
721
|
-
case "hook":
|
|
722
|
-
return `hook:${s.name}`;
|
|
723
|
-
case "subagent":
|
|
724
|
-
return `subagent:${s.name}`;
|
|
725
|
-
case "workflow":
|
|
726
|
-
return `workflow:${s.name}`;
|
|
727
|
-
case "rollout-policy":
|
|
728
|
-
return `rollout-policy:${s.field}`;
|
|
729
|
-
case "agent-profile":
|
|
730
|
-
return `agent-profile:${s.field}`;
|
|
731
|
-
case "code":
|
|
732
|
-
return `code:${s.path}`;
|
|
733
|
-
case "rag":
|
|
734
|
-
return `rag:${s.corpus}:${s.docId}`;
|
|
735
|
-
case "memory":
|
|
736
|
-
return `memory:${s.key}`;
|
|
737
|
-
case "scaffolding":
|
|
738
|
-
return `scaffolding:${s.concern}`;
|
|
739
|
-
case "output-schema":
|
|
740
|
-
return `output-schema:${s.field}`;
|
|
741
|
-
case "websearch.outdated":
|
|
742
|
-
return `websearch:outdated:${s.topic}`;
|
|
743
|
-
case "prior-run-summary":
|
|
744
|
-
return `prior-run-summary:${s.topic}`;
|
|
745
|
-
case "cluster":
|
|
746
|
-
return s.label;
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
var FINDING_SUBJECT_SYNTAX = {
|
|
750
|
-
"knowledge.wiki": "agent-knowledge:wiki:<slug>[#<heading>]",
|
|
751
|
-
"knowledge.claim": "agent-knowledge:claim:<topic>",
|
|
752
|
-
"knowledge.raw": "agent-knowledge:raw:<source-id>",
|
|
753
|
-
"knowledge.stale": "agent-knowledge:stale:<slug>",
|
|
754
|
-
"system-prompt": "system-prompt:<section>",
|
|
755
|
-
skill: "skill:<name>",
|
|
756
|
-
"tool-doc": "tool-doc:<tool>[:<aspect>]",
|
|
757
|
-
"new-tool": "new-tool:<name>",
|
|
758
|
-
mcp: "mcp:<server>[:<tool>]",
|
|
759
|
-
hook: "hook:<name>",
|
|
760
|
-
subagent: "subagent:<name>",
|
|
761
|
-
workflow: "workflow:<name>",
|
|
762
|
-
"rollout-policy": "rollout-policy:<field>",
|
|
763
|
-
"agent-profile": "agent-profile:<field>",
|
|
764
|
-
code: "code:<path>",
|
|
765
|
-
rag: "rag:<corpus>:<doc-id>",
|
|
766
|
-
memory: "memory:<key>",
|
|
767
|
-
scaffolding: "scaffolding:<concern>",
|
|
768
|
-
"output-schema": "output-schema:<field>",
|
|
769
|
-
"websearch.outdated": "websearch:outdated:<topic>",
|
|
770
|
-
"prior-run-summary": "prior-run-summary:<topic>",
|
|
771
|
-
cluster: "<lowercase-cluster-label>"
|
|
772
|
-
};
|
|
773
|
-
var FINDING_SUBJECT_PURPOSE = {
|
|
774
|
-
"knowledge.wiki": "create or update a wiki page",
|
|
775
|
-
"knowledge.claim": "draft a claim or relation",
|
|
776
|
-
"knowledge.raw": "curate a raw source",
|
|
777
|
-
"knowledge.stale": "mark a stale page",
|
|
778
|
-
"system-prompt": "revise a system-prompt section",
|
|
779
|
-
skill: "create or revise a skill",
|
|
780
|
-
"tool-doc": "revise a tool contract",
|
|
781
|
-
"new-tool": "propose a new tool",
|
|
782
|
-
mcp: "revise an MCP server or tool",
|
|
783
|
-
hook: "revise a lifecycle hook",
|
|
784
|
-
subagent: "revise a delegated agent",
|
|
785
|
-
workflow: "revise an orchestration workflow",
|
|
786
|
-
"rollout-policy": "revise budget, sampling, or stop policy",
|
|
787
|
-
"agent-profile": "revise another AgentProfile field",
|
|
788
|
-
code: "revise an implementation path",
|
|
789
|
-
rag: "ingest or correct a RAG document",
|
|
790
|
-
memory: "invalidate or set memory",
|
|
791
|
-
scaffolding: "revise preconditions, retries, or verification",
|
|
792
|
-
"output-schema": "constrain the output shape",
|
|
793
|
-
"websearch.outdated": "identify a stale web result",
|
|
794
|
-
"prior-run-summary": "identify a stale prior-run summary",
|
|
795
|
-
cluster: "name one failure cluster"
|
|
796
|
-
};
|
|
797
|
-
function renderFindingSubjectGrammar(kinds) {
|
|
798
|
-
return [
|
|
799
|
-
"Subjects MUST match one of these forms \u2014 anything else is rejected at parse time:",
|
|
800
|
-
...kinds.map((kind) => ` ${FINDING_SUBJECT_SYNTAX[kind]} \u2014 ${FINDING_SUBJECT_PURPOSE[kind]}`),
|
|
801
|
-
"Runtime ids are lowercase [a-z0-9_.-]+. Topics, keys, paths, and sections are free-form and trimmed."
|
|
802
|
-
].join("\n");
|
|
803
|
-
}
|
|
804
|
-
var FINDING_SUBJECT_GRAMMAR_PROMPT = renderFindingSubjectGrammar(FINDING_SUBJECT_KINDS);
|
|
805
|
-
var KIND_EXPECTED_SUBJECTS = {
|
|
806
|
-
"failure-mode": ["cluster"],
|
|
807
|
-
"knowledge-gap": [
|
|
808
|
-
"knowledge.wiki",
|
|
809
|
-
"knowledge.claim",
|
|
810
|
-
"knowledge.raw",
|
|
811
|
-
"knowledge.stale",
|
|
812
|
-
"tool-doc",
|
|
813
|
-
"system-prompt",
|
|
814
|
-
"skill",
|
|
815
|
-
"mcp",
|
|
816
|
-
"subagent",
|
|
817
|
-
"workflow",
|
|
818
|
-
"memory",
|
|
819
|
-
"websearch.outdated",
|
|
820
|
-
"prior-run-summary"
|
|
821
|
-
],
|
|
822
|
-
"knowledge-poisoning": [
|
|
823
|
-
"knowledge.wiki",
|
|
824
|
-
"knowledge.claim",
|
|
825
|
-
"knowledge.raw",
|
|
826
|
-
"tool-doc",
|
|
827
|
-
"system-prompt",
|
|
828
|
-
"skill",
|
|
829
|
-
"mcp",
|
|
830
|
-
"hook",
|
|
831
|
-
"memory",
|
|
832
|
-
"websearch.outdated",
|
|
833
|
-
"prior-run-summary"
|
|
834
|
-
],
|
|
835
|
-
improvement: [
|
|
836
|
-
"system-prompt",
|
|
837
|
-
"skill",
|
|
838
|
-
"tool-doc",
|
|
839
|
-
"new-tool",
|
|
840
|
-
"mcp",
|
|
841
|
-
"hook",
|
|
842
|
-
"subagent",
|
|
843
|
-
"workflow",
|
|
844
|
-
"rollout-policy",
|
|
845
|
-
"agent-profile",
|
|
846
|
-
"code",
|
|
847
|
-
"rag",
|
|
848
|
-
"memory",
|
|
849
|
-
"scaffolding",
|
|
850
|
-
"output-schema",
|
|
851
|
-
"knowledge.wiki",
|
|
852
|
-
"knowledge.claim"
|
|
853
|
-
]
|
|
854
|
-
};
|
|
855
|
-
function findingSubjectGrammarPromptFor(kindId) {
|
|
856
|
-
const kinds = KIND_EXPECTED_SUBJECTS[kindId];
|
|
857
|
-
if (!kinds) throw new Error(`unknown analyst kind: ${kindId}`);
|
|
858
|
-
return renderFindingSubjectGrammar(kinds);
|
|
859
|
-
}
|
|
860
|
-
var FindingSubjectStringSchema = z.string().refine((s) => parseFindingSubject(s) !== null, {
|
|
861
|
-
message: "subject does not match the finding-subject grammar"
|
|
862
|
-
});
|
|
863
|
-
|
|
864
|
-
// src/analyst/parse-tolerant.ts
|
|
865
|
-
function stripCodeFences(text) {
|
|
866
|
-
const t = text.trim();
|
|
867
|
-
const fence = /^```[a-zA-Z0-9]*\s*\n?([\s\S]*?)\n?```$/;
|
|
868
|
-
const m = t.match(fence);
|
|
869
|
-
return m ? m[1].trim() : t;
|
|
870
|
-
}
|
|
871
|
-
function dropTrailingCommas(s) {
|
|
872
|
-
return s.replace(/,(\s*[}\]])/g, "$1");
|
|
873
|
-
}
|
|
874
|
-
function coerceJson(text) {
|
|
875
|
-
const candidate = dropTrailingCommas(stripCodeFences(text));
|
|
876
|
-
try {
|
|
877
|
-
return JSON.parse(candidate);
|
|
878
|
-
} catch {
|
|
879
|
-
return void 0;
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
function coerceToFindingRows(raw) {
|
|
883
|
-
let value = raw;
|
|
884
|
-
if (typeof value === "string") {
|
|
885
|
-
const parsed = coerceJson(value);
|
|
886
|
-
if (parsed === void 0) return [];
|
|
887
|
-
value = parsed;
|
|
888
|
-
}
|
|
889
|
-
if (Array.isArray(value)) return value;
|
|
890
|
-
if (value && typeof value === "object") {
|
|
891
|
-
const inner = value.findings;
|
|
892
|
-
if (Array.isArray(inner)) return inner;
|
|
893
|
-
return [value];
|
|
894
|
-
}
|
|
895
|
-
return [];
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
// src/analyst/finding-signature.ts
|
|
899
|
-
import { z as z2 } from "zod";
|
|
900
|
-
var ANALYST_SEVERITIES = ["critical", "high", "medium", "low", "info"];
|
|
901
|
-
var RawAnalystEvidenceSchema = z2.object({
|
|
902
|
-
uri: z2.string().trim().min(1).max(2e3),
|
|
903
|
-
excerpt: z2.string().max(2e3).optional()
|
|
904
|
-
}).strict();
|
|
905
|
-
var RawAnalystFindingBaseShape = {
|
|
906
|
-
severity: z2.enum(ANALYST_SEVERITIES),
|
|
907
|
-
claim: z2.string().min(1).max(2e3),
|
|
908
|
-
subject: z2.string().max(400).refine((subject) => parseFindingSubject(subject) !== null, {
|
|
909
|
-
message: "subject does not match the finding-subject grammar"
|
|
910
|
-
}).optional(),
|
|
911
|
-
confidence: z2.number().min(0).max(1),
|
|
912
|
-
rationale: z2.string().max(4e3).optional(),
|
|
913
|
-
recommended_action: z2.string().max(2e3).optional()
|
|
914
|
-
};
|
|
915
|
-
var RawAnalystFindingSchema = z2.object({
|
|
916
|
-
...RawAnalystFindingBaseShape,
|
|
917
|
-
evidence: z2.array(RawAnalystEvidenceSchema).min(1)
|
|
918
|
-
}).strict();
|
|
919
|
-
var RAW_FINDING_SCHEMA_PROMPT = `Each finding MUST be a strict JSON object with:
|
|
920
|
-
- severity: "critical" | "high" | "medium" | "low" | "info"
|
|
921
|
-
- claim: one-sentence statement (max 2000 chars)
|
|
922
|
-
- subject?: one exact subject form listed by this kind; omit rather than guess
|
|
923
|
-
- evidence: REQUIRED non-empty array of {"uri": string, "excerpt"?: string}. Use real identifiers with span://, event://, artifact://, metric://, or finding://. Include a short exact quote in excerpt when available. If nothing is citable, do not emit the finding.
|
|
924
|
-
- confidence: number 0..1 (0.9+ exact evidence; 0.6-0.8 inferred pattern; <0.5 speculative)
|
|
925
|
-
- rationale?: one or two reasoning sentences
|
|
926
|
-
- recommended_action?: concrete imperative change; omit for descriptive findings
|
|
927
|
-
|
|
928
|
-
Unknown fields are rejected. Do not emit area; the factory assigns it. Emit [] when there are no findings. Never fabricate evidence.`;
|
|
929
|
-
function evidenceRefsFromRawFinding(finding) {
|
|
930
|
-
return finding.evidence.map(({ uri, excerpt }) => ({
|
|
931
|
-
kind: evidenceKindFromUri(uri),
|
|
932
|
-
uri,
|
|
933
|
-
excerpt
|
|
934
|
-
}));
|
|
935
|
-
}
|
|
936
|
-
function parseRawFinding(row, log) {
|
|
937
|
-
return parseFindingWithSchema(RawAnalystFindingSchema, row, log);
|
|
938
|
-
}
|
|
939
|
-
function parseFindingWithSchema(schema, row, log) {
|
|
940
|
-
const result = schema.safeParse(row);
|
|
941
|
-
if (result.success) return result.data;
|
|
942
|
-
if (typeof row === "string") {
|
|
943
|
-
const coerced = coerceJson(row);
|
|
944
|
-
if (coerced !== void 0) {
|
|
945
|
-
const retry = schema.safeParse(coerced);
|
|
946
|
-
if (retry.success) return retry.data;
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
log?.("finding rejected: schema failure", {
|
|
950
|
-
issues: result.error.issues.map((i) => ({
|
|
951
|
-
path: i.path.join("."),
|
|
952
|
-
code: i.code,
|
|
953
|
-
message: i.message
|
|
954
|
-
}))
|
|
955
|
-
});
|
|
956
|
-
return null;
|
|
957
|
-
}
|
|
958
|
-
function evidenceKindFromUri(uri) {
|
|
959
|
-
if (uri.startsWith("span://")) return "span";
|
|
960
|
-
if (uri.startsWith("event://")) return "event";
|
|
961
|
-
if (uri.startsWith("finding://")) return "finding";
|
|
962
|
-
if (uri.startsWith("metric://")) return "metric";
|
|
963
|
-
return "artifact";
|
|
964
|
-
}
|
|
965
|
-
|
|
966
|
-
// src/analyst/structure-findings.ts
|
|
967
|
-
var SYSTEM = [
|
|
968
|
-
"You convert a free-form trace-analysis report into a STRICT JSON array of findings.",
|
|
969
|
-
"Output ONLY the JSON array \u2014 no prose, no code fences.",
|
|
970
|
-
RAW_FINDING_SCHEMA_PROMPT,
|
|
971
|
-
"Omit subject when the report does not contain an exact valid locus.",
|
|
972
|
-
"If the report asserts NO problems, output exactly []."
|
|
973
|
-
].join(" ");
|
|
974
|
-
function buildRows(raw, opts) {
|
|
975
|
-
const rows = coerceToFindingRows(raw);
|
|
976
|
-
const out = [];
|
|
977
|
-
for (const row of rows) {
|
|
978
|
-
const parsed = parseRawFinding(row);
|
|
979
|
-
if (!parsed) continue;
|
|
980
|
-
const callbackResult = opts.processRow ? opts.processRow(parsed) : parsed;
|
|
981
|
-
if (!callbackResult) continue;
|
|
982
|
-
const processed = parseRawFinding(callbackResult);
|
|
983
|
-
if (!processed) continue;
|
|
984
|
-
out.push(
|
|
985
|
-
makeFinding({
|
|
986
|
-
analyst_id: opts.analystId,
|
|
987
|
-
area: opts.area,
|
|
988
|
-
subject: processed.subject,
|
|
989
|
-
claim: processed.claim,
|
|
990
|
-
rationale: processed.rationale,
|
|
991
|
-
severity: processed.severity,
|
|
992
|
-
confidence: processed.confidence,
|
|
993
|
-
evidence_refs: evidenceRefsFromRawFinding(processed),
|
|
994
|
-
recommended_action: processed.recommended_action,
|
|
995
|
-
...opts.findingMetadata ? { metadata: { ...opts.findingMetadata } } : {}
|
|
996
|
-
})
|
|
997
|
-
);
|
|
998
|
-
}
|
|
999
|
-
return out;
|
|
1000
|
-
}
|
|
1001
|
-
async function structureFindings(opts) {
|
|
1002
|
-
const maxReasks = opts.maxReasks ?? 1;
|
|
1003
|
-
if (!Number.isSafeInteger(maxReasks) || maxReasks < 0) {
|
|
1004
|
-
throw new RangeError("structureFindings: maxReasks must be a non-negative safe integer");
|
|
1005
|
-
}
|
|
1006
|
-
const llm = { baseUrl: opts.baseUrl, apiKey: opts.apiKey, fetch: opts.fetchImpl };
|
|
1007
|
-
const costLedger = opts.costLedger ?? new CostLedger();
|
|
1008
|
-
let user = `TRACE-ANALYSIS REPORT:
|
|
1009
|
-
${opts.report}
|
|
1010
|
-
|
|
1011
|
-
Return the findings JSON array.`;
|
|
1012
|
-
for (let attempt = 0; attempt <= maxReasks; attempt++) {
|
|
1013
|
-
const request = {
|
|
1014
|
-
model: opts.model,
|
|
1015
|
-
messages: [
|
|
1016
|
-
{ role: "system", content: SYSTEM },
|
|
1017
|
-
{ role: "user", content: user }
|
|
1018
|
-
],
|
|
1019
|
-
maxTokens: opts.maxTokens ?? 2e3
|
|
1020
|
-
};
|
|
1021
|
-
const paid = await costLedger.runPaidCall({
|
|
1022
|
-
channel: "analyst",
|
|
1023
|
-
phase: opts.costPhase ?? "analyst.structure-findings",
|
|
1024
|
-
actor: "structure-findings",
|
|
1025
|
-
model: opts.model,
|
|
1026
|
-
signal: opts.signal,
|
|
1027
|
-
maximumCharge: maximumChargeForLlmRequest(request, llm),
|
|
1028
|
-
tags: { ...opts.costTags, analystId: opts.analystId, attempt: String(attempt) },
|
|
1029
|
-
execute: (signal, callId) => callLlm(request, { ...llm, signal, idempotencyKey: callId }),
|
|
1030
|
-
receipt: costReceiptFromLlm,
|
|
1031
|
-
receiptFromError: costReceiptFromLlmError
|
|
1032
|
-
});
|
|
1033
|
-
if (!paid.succeeded) throw paid.error;
|
|
1034
|
-
const res = paid.value;
|
|
1035
|
-
const text = res.content.trim();
|
|
1036
|
-
const findings = buildRows(text, opts);
|
|
1037
|
-
if (findings.length > 0) return { findings, outcome: "ok" };
|
|
1038
|
-
if (opts.report.trim().length < 200) return { findings: [], outcome: "ok" };
|
|
1039
|
-
user = `${user}
|
|
1040
|
-
|
|
1041
|
-
That produced no valid findings. The report DOES describe issues \u2014 re-extract them as the strict JSON array described in the system prompt. Output ONLY the array.`;
|
|
1042
|
-
}
|
|
1043
|
-
return { findings: [], outcome: "extraction_failed" };
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
// src/analyst/ax-cost-service.ts
|
|
1047
|
-
function meterAxChatService(ai2, options) {
|
|
1048
|
-
assertPositiveInteger(options.maxOutputTokens, "maxOutputTokens");
|
|
1049
|
-
const source = ai2;
|
|
1050
|
-
if (typeof source.chat !== "function") {
|
|
1051
|
-
throw new TypeError("meterAxChatService: Ax service must implement chat()");
|
|
1052
|
-
}
|
|
1053
|
-
const providerChat = source.chat.bind(ai2);
|
|
1054
|
-
const chat = async (request, callOptions = {}) => {
|
|
1055
|
-
const boundedRequest = boundOutputTokens(request, options.maxOutputTokens);
|
|
1056
|
-
const model = modelName(boundedRequest.model) || options.defaultModel || "";
|
|
1057
|
-
const canTurnOffThinking = canDisableThinking(ai2, model);
|
|
1058
|
-
const combined = combineSignals(options.signal, callOptions.abortSignal);
|
|
1059
|
-
try {
|
|
1060
|
-
const paid = await options.ledger.runPaidCall({
|
|
1061
|
-
channel: "analyst",
|
|
1062
|
-
phase: options.phase ?? "analyst.ax.chat",
|
|
1063
|
-
actor: options.actor,
|
|
1064
|
-
model,
|
|
1065
|
-
tags: options.tags,
|
|
1066
|
-
signal: combined.signal,
|
|
1067
|
-
maximumCharge: maximumChargeForAxChatRequest(boundedRequest, model),
|
|
1068
|
-
execute: async (executionSignal) => {
|
|
1069
|
-
const providerOptions = {
|
|
1070
|
-
...callOptions,
|
|
1071
|
-
abortSignal: executionSignal,
|
|
1072
|
-
retry: { ...callOptions.retry, maxRetries: 0 },
|
|
1073
|
-
stream: false,
|
|
1074
|
-
showThoughts: false
|
|
1075
|
-
};
|
|
1076
|
-
if (canTurnOffThinking) providerOptions.thinkingTokenBudget = "none";
|
|
1077
|
-
else Reflect.deleteProperty(providerOptions, "thinkingTokenBudget");
|
|
1078
|
-
const response = await providerChat(boundedRequest, providerOptions);
|
|
1079
|
-
if (response instanceof ReadableStream) {
|
|
1080
|
-
throw new Error("meterAxChatService: provider returned a stream after stream:false");
|
|
1081
|
-
}
|
|
1082
|
-
return response;
|
|
1083
|
-
},
|
|
1084
|
-
receipt: (response) => costReceiptFromAxResponse(response, model)
|
|
1085
|
-
});
|
|
1086
|
-
if (!paid.succeeded) throw paid.error;
|
|
1087
|
-
return paid.value;
|
|
1088
|
-
} finally {
|
|
1089
|
-
combined.dispose();
|
|
1090
|
-
}
|
|
1091
|
-
};
|
|
1092
|
-
return new Proxy(ai2, {
|
|
1093
|
-
get(target, property) {
|
|
1094
|
-
if (property === "chat") return chat;
|
|
1095
|
-
const value = Reflect.get(target, property, target);
|
|
1096
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
1097
|
-
}
|
|
1098
|
-
});
|
|
1099
|
-
}
|
|
1100
|
-
function maximumChargeForAxChatRequest(request, defaultModel) {
|
|
1101
|
-
const model = modelName(request.model) || defaultModel || "";
|
|
1102
|
-
const maxTokens = request.modelConfig?.maxTokens;
|
|
1103
|
-
const completions = request.modelConfig?.n;
|
|
1104
|
-
if (!model || maxTokens === void 0 || completions === void 0) return void 0;
|
|
1105
|
-
assertPositiveInteger(maxTokens, "request.modelConfig.maxTokens");
|
|
1106
|
-
assertPositiveInteger(completions, "request.modelConfig.n");
|
|
1107
|
-
const maximumOutputTokens = maxTokens * completions;
|
|
1108
|
-
assertPositiveInteger(maximumOutputTokens, "maximum output tokens");
|
|
1109
|
-
if (containsUnboundedOrCacheableContent(request)) return void 0;
|
|
1110
|
-
let inputTokens;
|
|
1111
|
-
try {
|
|
1112
|
-
const pricedRequest = request.model === void 0 ? { ...request, model } : request;
|
|
1113
|
-
inputTokens = new TextEncoder().encode(JSON.stringify(pricedRequest)).byteLength * completions;
|
|
1114
|
-
} catch {
|
|
1115
|
-
return void 0;
|
|
1116
|
-
}
|
|
1117
|
-
assertPositiveInteger(inputTokens, "maximum input tokens");
|
|
1118
|
-
return { model, inputTokens, outputTokens: maximumOutputTokens };
|
|
1119
|
-
}
|
|
1120
|
-
function boundOutputTokens(request, limit) {
|
|
1121
|
-
const requested = request.modelConfig?.maxTokens;
|
|
1122
|
-
if (requested !== void 0) {
|
|
1123
|
-
assertPositiveInteger(requested, "request.modelConfig.maxTokens");
|
|
1124
|
-
}
|
|
1125
|
-
const completions = request.modelConfig?.n ?? 1;
|
|
1126
|
-
assertPositiveInteger(completions, "request.modelConfig.n");
|
|
1127
|
-
const maxTokens = requested === void 0 ? limit : Math.min(requested, limit);
|
|
1128
|
-
return {
|
|
1129
|
-
...request,
|
|
1130
|
-
modelConfig: { ...request.modelConfig, maxTokens, n: completions }
|
|
1131
|
-
};
|
|
1132
|
-
}
|
|
1133
|
-
function costReceiptFromAxResponse(response, fallbackModel) {
|
|
1134
|
-
const usage = response.modelUsage;
|
|
1135
|
-
const tokens = usage?.tokens;
|
|
1136
|
-
const model = usage?.model || fallbackModel;
|
|
1137
|
-
if (!tokens || !validUsage(tokens.promptTokens) || !validUsage(tokens.completionTokens) || !validUsage(tokens.totalTokens) || tokens.totalTokens < tokens.promptTokens + tokens.completionTokens || !validOptionalUsage(tokens.cacheReadTokens) || !validOptionalUsage(tokens.cacheCreationTokens) || !validOptionalUsage(tokens.reasoningTokens) || !validOptionalUsage(tokens.thoughtsTokens)) {
|
|
1138
|
-
return {
|
|
1139
|
-
model,
|
|
1140
|
-
inputTokens: 0,
|
|
1141
|
-
outputTokens: 0,
|
|
1142
|
-
usageUnknown: true
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
const cacheReadTokens = validUsage(tokens.cacheReadTokens) ? tokens.cacheReadTokens : 0;
|
|
1146
|
-
const cacheCreationTokens = validUsage(tokens.cacheCreationTokens) ? tokens.cacheCreationTokens : 0;
|
|
1147
|
-
const totalCacheTokens = cacheReadTokens + cacheCreationTokens;
|
|
1148
|
-
const thoughtsTokens = validUsage(tokens.thoughtsTokens) ? tokens.thoughtsTokens : 0;
|
|
1149
|
-
const reasoningTokens = Math.max(
|
|
1150
|
-
validUsage(tokens.reasoningTokens) ? tokens.reasoningTokens : 0,
|
|
1151
|
-
thoughtsTokens
|
|
1152
|
-
);
|
|
1153
|
-
const separateReasoningTokens = reasoningTokens > tokens.completionTokens ? reasoningTokens : 0;
|
|
1154
|
-
const additionalOutputTokens = Math.max(thoughtsTokens, separateReasoningTokens);
|
|
1155
|
-
const outputTokens = tokens.completionTokens + additionalOutputTokens;
|
|
1156
|
-
const directTotal = tokens.promptTokens + tokens.completionTokens;
|
|
1157
|
-
const validTotals = /* @__PURE__ */ new Set([
|
|
1158
|
-
directTotal,
|
|
1159
|
-
directTotal + totalCacheTokens,
|
|
1160
|
-
directTotal + additionalOutputTokens,
|
|
1161
|
-
directTotal + totalCacheTokens + additionalOutputTokens
|
|
1162
|
-
]);
|
|
1163
|
-
if (!validTotals.has(tokens.totalTokens)) {
|
|
1164
|
-
return {
|
|
1165
|
-
model,
|
|
1166
|
-
inputTokens: 0,
|
|
1167
|
-
outputTokens: 0,
|
|
1168
|
-
usageUnknown: true
|
|
1169
|
-
};
|
|
1170
|
-
}
|
|
1171
|
-
return {
|
|
1172
|
-
model,
|
|
1173
|
-
inputTokens: tokens.promptTokens,
|
|
1174
|
-
outputTokens,
|
|
1175
|
-
...reasoningTokens > 0 ? { reasoningTokens } : {},
|
|
1176
|
-
...cacheReadTokens > 0 ? { cachedTokens: cacheReadTokens } : {},
|
|
1177
|
-
...cacheCreationTokens > 0 ? { cacheWriteTokens: cacheCreationTokens } : {}
|
|
1178
|
-
};
|
|
1179
|
-
}
|
|
1180
|
-
function combineSignals(first, second) {
|
|
1181
|
-
if (!first) return { signal: second, dispose: () => {
|
|
1182
|
-
} };
|
|
1183
|
-
if (!second || first === second) return { signal: first, dispose: () => {
|
|
1184
|
-
} };
|
|
1185
|
-
if (typeof AbortSignal.any === "function") {
|
|
1186
|
-
return { signal: AbortSignal.any([first, second]), dispose: () => {
|
|
1187
|
-
} };
|
|
1188
|
-
}
|
|
1189
|
-
const controller = new AbortController();
|
|
1190
|
-
const dispose = () => {
|
|
1191
|
-
first.removeEventListener("abort", abortFromFirst);
|
|
1192
|
-
second.removeEventListener("abort", abortFromSecond);
|
|
1193
|
-
};
|
|
1194
|
-
const abortFrom = (source) => {
|
|
1195
|
-
if (!controller.signal.aborted) controller.abort(source.reason);
|
|
1196
|
-
dispose();
|
|
1197
|
-
};
|
|
1198
|
-
const abortFromFirst = () => abortFrom(first);
|
|
1199
|
-
const abortFromSecond = () => abortFrom(second);
|
|
1200
|
-
if (first.aborted) abortFrom(first);
|
|
1201
|
-
else if (second.aborted) abortFrom(second);
|
|
1202
|
-
else {
|
|
1203
|
-
first.addEventListener("abort", abortFromFirst, { once: true });
|
|
1204
|
-
second.addEventListener("abort", abortFromSecond, { once: true });
|
|
1205
|
-
}
|
|
1206
|
-
return { signal: controller.signal, dispose };
|
|
1207
|
-
}
|
|
1208
|
-
function containsUnboundedOrCacheableContent(request) {
|
|
1209
|
-
if (request.functions?.some((fn) => fn.cache === true)) return true;
|
|
1210
|
-
return request.chatPrompt.some((message) => {
|
|
1211
|
-
if (message.cache === true) return true;
|
|
1212
|
-
if (!("content" in message) || !Array.isArray(message.content)) return false;
|
|
1213
|
-
return message.content.some((part) => part.cache === true || part.type !== "text");
|
|
1214
|
-
});
|
|
1215
|
-
}
|
|
1216
|
-
function modelName(value) {
|
|
1217
|
-
return typeof value === "string" ? value : "";
|
|
1218
|
-
}
|
|
1219
|
-
function canDisableThinking(ai2, model) {
|
|
1220
|
-
const namedAi = ai2;
|
|
1221
|
-
const serviceName = typeof namedAi.getName === "function" ? namedAi.getName() : "";
|
|
1222
|
-
const modelId = model.slice(model.lastIndexOf("/") + 1);
|
|
1223
|
-
return serviceName !== "GoogleGeminiAI" || !/^gemini-3(?:[.-]|$)/i.test(modelId);
|
|
1224
|
-
}
|
|
1225
|
-
function validUsage(value) {
|
|
1226
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
1227
|
-
}
|
|
1228
|
-
function validOptionalUsage(value) {
|
|
1229
|
-
return value === void 0 || validUsage(value);
|
|
1230
|
-
}
|
|
1231
|
-
function assertPositiveInteger(value, field) {
|
|
1232
|
-
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
1233
|
-
throw new RangeError(`meterAxChatService: ${field} must be a positive integer`);
|
|
1234
|
-
}
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
// src/analyst/usage-receipt.ts
|
|
1238
|
-
var DEFAULT_USAGE_SETTLEMENT_TIMEOUT_MS = 5e3;
|
|
1239
|
-
function usageReceiptFromCostLedger(ledger, filter = "analyst") {
|
|
1240
|
-
const resolvedFilter = typeof filter === "string" ? { channel: filter } : filter;
|
|
1241
|
-
const summary = ledger.summary(resolvedFilter);
|
|
1242
|
-
const receipts = ledger.list(resolvedFilter);
|
|
1243
|
-
const hasReasoningUsage = receipts.some((receipt) => receipt.reasoningTokens !== void 0);
|
|
1244
|
-
const hasCacheWriteUsage = receipts.some((receipt) => receipt.cacheWriteTokens !== void 0);
|
|
1245
|
-
const costUncaptured = summary.pendingCalls > 0 || receipts.some((receipt) => receipt.costUnknown);
|
|
1246
|
-
const cost = costUncaptured ? { kind: "uncaptured", usd: null } : receipts.every((receipt) => receipt.actualCostUsd !== void 0) ? { kind: "observed", usd: summary.totalCostUsd } : { kind: "estimated", usd: summary.totalCostUsd };
|
|
1247
|
-
return {
|
|
1248
|
-
calls: summary.totalCalls + summary.pendingCalls,
|
|
1249
|
-
tokens: summary.usageComplete ? {
|
|
1250
|
-
input: summary.inputTokens,
|
|
1251
|
-
output: summary.outputTokens,
|
|
1252
|
-
...hasReasoningUsage ? { reasoning: summary.reasoningTokens ?? 0 } : {},
|
|
1253
|
-
...summary.cachedTokens > 0 ? { cached: summary.cachedTokens } : {},
|
|
1254
|
-
...hasCacheWriteUsage ? { cacheWrite: summary.cacheWriteTokens ?? 0 } : {}
|
|
1255
|
-
} : null,
|
|
1256
|
-
cost,
|
|
1257
|
-
...cost.kind === "uncaptured" ? { knownCostUsd: summary.totalCostUsd } : {}
|
|
1258
|
-
};
|
|
1259
|
-
}
|
|
1260
|
-
async function settleUsageReceiptFromCostLedger(ledger, options = {}) {
|
|
1261
|
-
const { timeoutMs: requestedTimeoutMs, ...requestedFilter } = options;
|
|
1262
|
-
const filter = {
|
|
1263
|
-
channel: requestedFilter.channel ?? "analyst",
|
|
1264
|
-
...requestedFilter.phase === void 0 ? {} : { phase: requestedFilter.phase },
|
|
1265
|
-
...requestedFilter.tags === void 0 ? {} : { tags: requestedFilter.tags }
|
|
1266
|
-
};
|
|
1267
|
-
const timeoutMs = validateUsageSettlementTimeout(requestedTimeoutMs);
|
|
1268
|
-
const initial = ledger.summary(filter);
|
|
1269
|
-
const waitResult = initial.pendingCalls === 0 ? true : ledger.waitForIdle ? await ledger.waitForIdle({ timeoutMs }) : false;
|
|
1270
|
-
const pendingCalls = ledger.summary(filter).pendingCalls;
|
|
1271
|
-
return {
|
|
1272
|
-
settled: waitResult && pendingCalls === 0,
|
|
1273
|
-
pendingCalls,
|
|
1274
|
-
receipt: usageReceiptFromCostLedger(ledger, filter)
|
|
1275
|
-
};
|
|
1276
|
-
}
|
|
1277
|
-
function validateUsageSettlementTimeout(timeoutMs) {
|
|
1278
|
-
const resolved = timeoutMs ?? DEFAULT_USAGE_SETTLEMENT_TIMEOUT_MS;
|
|
1279
|
-
if (!Number.isSafeInteger(resolved) || resolved < 0 || resolved > 2147483647) {
|
|
1280
|
-
throw new TypeError(
|
|
1281
|
-
"settlementTimeoutMs must be a non-negative safe integer no greater than 2147483647"
|
|
1282
|
-
);
|
|
1283
|
-
}
|
|
1284
|
-
return resolved;
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
// src/analyst/kind-factory.ts
|
|
1288
|
-
function createTraceAnalystKind(spec, opts) {
|
|
1289
|
-
rejectRemovedKindOptions(spec);
|
|
1290
|
-
const version = opts.versionSuffix ? `${spec.version}+${opts.versionSuffix}` : spec.version;
|
|
1291
|
-
const model = resolveAnalystModel(opts.ai, opts.model);
|
|
1292
|
-
const minimumEvidenceCitations = spec.minimumEvidenceCitations ?? 1;
|
|
1293
|
-
if (!Number.isInteger(minimumEvidenceCitations) || minimumEvidenceCitations < 1) {
|
|
1294
|
-
throw new TypeError("minimumEvidenceCitations must be a positive integer");
|
|
1295
|
-
}
|
|
1296
|
-
const settlementTimeoutMs = validateUsageSettlementTimeout(opts.settlementTimeoutMs);
|
|
1297
|
-
return {
|
|
1298
|
-
id: spec.id,
|
|
1299
|
-
description: spec.description,
|
|
1300
|
-
inputKind: "trace-store",
|
|
1301
|
-
cost: { ...spec.cost, settlement_timeout_ms: settlementTimeoutMs },
|
|
1302
|
-
version,
|
|
1303
|
-
async analyze(store, ctx) {
|
|
1304
|
-
const maxOutputTokens = spec.maxOutputTokens ?? 4096;
|
|
1305
|
-
const costLedger = ctx.costLedger ?? new CostLedger(ctx.budgetUsd);
|
|
1306
|
-
const costTags = {
|
|
1307
|
-
...ctx.tags ?? {},
|
|
1308
|
-
analystId: spec.id,
|
|
1309
|
-
...ctx.correlationId ? { analystRunId: ctx.correlationId } : {}
|
|
1310
|
-
};
|
|
1311
|
-
const meteredAi = meterAxChatService(opts.ai, {
|
|
1312
|
-
ledger: costLedger,
|
|
1313
|
-
actor: spec.id,
|
|
1314
|
-
maxOutputTokens,
|
|
1315
|
-
defaultModel: model,
|
|
1316
|
-
phase: ctx.costPhase,
|
|
1317
|
-
signal: ctx.signal,
|
|
1318
|
-
tags: costTags
|
|
1319
|
-
});
|
|
1320
|
-
try {
|
|
1321
|
-
const tools = spec.buildTools(store);
|
|
1322
|
-
const maxSubqueries = spec.subqueries?.maxCalls ?? 0;
|
|
1323
|
-
const maxParallel = spec.subqueries?.maxParallel ?? 2;
|
|
1324
|
-
const priorContext = renderPriorFindings(ctx.priorFindings);
|
|
1325
|
-
const upstreamContext = renderUpstreamFindings(ctx.upstreamFindings);
|
|
1326
|
-
const actorDescription = spec.actorDescription.trim() + priorContext + upstreamContext + "\n\n" + RAW_FINDING_SCHEMA_PROMPT + (minimumEvidenceCitations > 1 ? `
|
|
1327
|
-
|
|
1328
|
-
This kind requires at least ${minimumEvidenceCitations} evidence citations per finding; rows with fewer are rejected.` : "") + "\n\nFirst write `report`: a concise free-form prose diagnosis of what the traces show \u2014 what succeeded, what was suboptimal or failed \u2014 with concrete trace ids and numbers. THEN return the structured `findings` array (it MAY be empty when there is nothing to report).";
|
|
1329
|
-
ctx.log?.(`analyst.kind ${spec.id} forward`, {
|
|
1330
|
-
max_subqueries: maxSubqueries,
|
|
1331
|
-
tool_count: tools.length,
|
|
1332
|
-
tags: ctx.tags
|
|
1333
|
-
});
|
|
1334
|
-
const completed = await runTraceAnalysisLoop({
|
|
1335
|
-
id: spec.id,
|
|
1336
|
-
description: spec.description,
|
|
1337
|
-
prompt: actorDescription,
|
|
1338
|
-
question: deriveQuestion(ctx, spec),
|
|
1339
|
-
ai: meteredAi,
|
|
1340
|
-
model,
|
|
1341
|
-
tools,
|
|
1342
|
-
findingType: "object",
|
|
1343
|
-
maxSubqueries,
|
|
1344
|
-
maxParallelSubqueries: maxParallel,
|
|
1345
|
-
maxTurns: spec.maxTurns ?? 12,
|
|
1346
|
-
maxRuntimeChars: spec.maxRuntimeChars ?? 6e3,
|
|
1347
|
-
...ctx.signal ? { signal: ctx.signal } : {}
|
|
1348
|
-
});
|
|
1349
|
-
const { report, findings: submittedFindings } = completed;
|
|
1350
|
-
const expectedSubjects = KIND_EXPECTED_SUBJECTS[spec.id];
|
|
1351
|
-
const out = [];
|
|
1352
|
-
const rawRows = submittedFindings;
|
|
1353
|
-
let rejectedWrongKind = 0;
|
|
1354
|
-
let rejectedInsufficientEvidence = 0;
|
|
1355
|
-
const processRow = (parsed) => {
|
|
1356
|
-
const callbackResult = spec.postProcess ? spec.postProcess(parsed, ctx) : parsed;
|
|
1357
|
-
if (!callbackResult) return null;
|
|
1358
|
-
const postProcessed = parseRawFinding(callbackResult, ctx.log);
|
|
1359
|
-
if (!postProcessed) return null;
|
|
1360
|
-
if (expectedSubjects && postProcessed.subject !== void 0) {
|
|
1361
|
-
const parsedSubject = parseFindingSubject(postProcessed.subject);
|
|
1362
|
-
if (parsedSubject === null) {
|
|
1363
|
-
ctx.log?.("finding rejected: subject failed to parse", {
|
|
1364
|
-
kind: spec.id,
|
|
1365
|
-
subject: postProcessed.subject
|
|
1366
|
-
});
|
|
1367
|
-
rejectedWrongKind += 1;
|
|
1368
|
-
return null;
|
|
1369
|
-
}
|
|
1370
|
-
if (!expectedSubjects.includes(parsedSubject.kind)) {
|
|
1371
|
-
ctx.log?.("finding rejected: subject variant not allowed for this kind", {
|
|
1372
|
-
kind: spec.id,
|
|
1373
|
-
subject_kind: parsedSubject.kind,
|
|
1374
|
-
subject: postProcessed.subject,
|
|
1375
|
-
allowed: expectedSubjects
|
|
1376
|
-
});
|
|
1377
|
-
rejectedWrongKind += 1;
|
|
1378
|
-
return null;
|
|
1379
|
-
}
|
|
1380
|
-
}
|
|
1381
|
-
const distinctEvidenceCitations = new Set(
|
|
1382
|
-
postProcessed.evidence.map((citation) => citation.uri.trim())
|
|
1383
|
-
).size;
|
|
1384
|
-
if (distinctEvidenceCitations < minimumEvidenceCitations) {
|
|
1385
|
-
ctx.log?.("finding rejected: insufficient evidence citations", {
|
|
1386
|
-
kind: spec.id,
|
|
1387
|
-
required: minimumEvidenceCitations,
|
|
1388
|
-
received: postProcessed.evidence.length,
|
|
1389
|
-
distinct: distinctEvidenceCitations
|
|
1390
|
-
});
|
|
1391
|
-
rejectedInsufficientEvidence += 1;
|
|
1392
|
-
return null;
|
|
1393
|
-
}
|
|
1394
|
-
return postProcessed;
|
|
1395
|
-
};
|
|
1396
|
-
for (const row of rawRows) {
|
|
1397
|
-
const parsed = parseRawFinding(row, ctx.log);
|
|
1398
|
-
if (!parsed) continue;
|
|
1399
|
-
const postProcessed = processRow(parsed);
|
|
1400
|
-
if (!postProcessed) continue;
|
|
1401
|
-
out.push(toAnalystFinding(spec, version, postProcessed));
|
|
1402
|
-
}
|
|
1403
|
-
ctx.log?.(`analyst.kind ${spec.id} done`, {
|
|
1404
|
-
emitted: rawRows.length,
|
|
1405
|
-
accepted: out.length,
|
|
1406
|
-
rejected_wrong_subject: rejectedWrongKind,
|
|
1407
|
-
rejected_insufficient_evidence: rejectedInsufficientEvidence
|
|
1408
|
-
});
|
|
1409
|
-
if (out.length === 0 && report.trim().length >= 200) {
|
|
1410
|
-
if (opts.recovery) {
|
|
1411
|
-
const wrongKindBefore = rejectedWrongKind;
|
|
1412
|
-
const insufficientEvidenceBefore = rejectedInsufficientEvidence;
|
|
1413
|
-
const recovered = await structureFindings({
|
|
1414
|
-
report,
|
|
1415
|
-
analystId: spec.id,
|
|
1416
|
-
area: spec.area,
|
|
1417
|
-
model: opts.recovery.model ?? model,
|
|
1418
|
-
baseUrl: opts.recovery.baseUrl,
|
|
1419
|
-
apiKey: opts.recovery.apiKey,
|
|
1420
|
-
fetchImpl: opts.recovery.fetchImpl,
|
|
1421
|
-
costLedger,
|
|
1422
|
-
costPhase: ctx.costPhase,
|
|
1423
|
-
costTags,
|
|
1424
|
-
signal: ctx.signal,
|
|
1425
|
-
maxTokens: Math.min(maxOutputTokens, 2e3),
|
|
1426
|
-
processRow,
|
|
1427
|
-
findingMetadata: { kind_version: version }
|
|
1428
|
-
});
|
|
1429
|
-
out.push(...recovered.findings);
|
|
1430
|
-
ctx.log?.(`analyst.kind ${spec.id} recovery`, {
|
|
1431
|
-
outcome: recovered.outcome,
|
|
1432
|
-
recovered: recovered.findings.length,
|
|
1433
|
-
rejected_wrong_subject: rejectedWrongKind - wrongKindBefore,
|
|
1434
|
-
rejected_insufficient_evidence: rejectedInsufficientEvidence - insufficientEvidenceBefore
|
|
1435
|
-
});
|
|
1436
|
-
}
|
|
1437
|
-
if (out.length === 0) {
|
|
1438
|
-
const fallback = processRow({
|
|
1439
|
-
claim: "Analyst produced a diagnosis but no structured findings \u2014 see report.",
|
|
1440
|
-
rationale: report.slice(0, 1500),
|
|
1441
|
-
severity: "info",
|
|
1442
|
-
confidence: 0.3,
|
|
1443
|
-
evidence: [{ uri: "report://summary", excerpt: report.slice(0, 2e3) }]
|
|
1444
|
-
});
|
|
1445
|
-
if (fallback) {
|
|
1446
|
-
out.push(toAnalystFinding(spec, version, fallback, { outcome: "extraction_failed" }));
|
|
1447
|
-
} else {
|
|
1448
|
-
throw new Error(
|
|
1449
|
-
`Trace analyst '${spec.id}' produced a substantive report, but no finding satisfied its acceptance rules`
|
|
1450
|
-
);
|
|
1451
|
-
}
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
return out;
|
|
1455
|
-
} finally {
|
|
1456
|
-
const usage = await settleUsageReceiptFromCostLedger(costLedger, {
|
|
1457
|
-
tags: {
|
|
1458
|
-
analystId: spec.id,
|
|
1459
|
-
...ctx.correlationId ? { analystRunId: ctx.correlationId } : {}
|
|
1460
|
-
},
|
|
1461
|
-
timeoutMs: settlementTimeoutMs
|
|
1462
|
-
});
|
|
1463
|
-
if (!usage.settled) {
|
|
1464
|
-
ctx.log?.(`analyst.kind ${spec.id} provider settlement timed out`, {
|
|
1465
|
-
pending_calls: usage.pendingCalls,
|
|
1466
|
-
timeout_ms: settlementTimeoutMs
|
|
1467
|
-
});
|
|
1468
|
-
}
|
|
1469
|
-
ctx.recordUsage?.(usage.receipt);
|
|
1470
|
-
}
|
|
1471
|
-
}
|
|
1472
|
-
};
|
|
1473
|
-
}
|
|
1474
|
-
function rejectRemovedKindOptions(spec) {
|
|
1475
|
-
const supplied = spec;
|
|
1476
|
-
const migrations = [
|
|
1477
|
-
["recursion", "subqueries"],
|
|
1478
|
-
["responderDescription", "actorDescription"],
|
|
1479
|
-
["maxDepth", "subqueries"],
|
|
1480
|
-
["maxParallelSubagents", "subqueries.maxParallel"],
|
|
1481
|
-
["subagentDescription", "actorDescription"]
|
|
1482
|
-
];
|
|
1483
|
-
for (const [removed, replacement] of migrations) {
|
|
1484
|
-
if (removed in supplied) {
|
|
1485
|
-
throw new TypeError(
|
|
1486
|
-
`createTraceAnalystKind: '${removed}' is unsupported; use '${replacement}'`
|
|
1487
|
-
);
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
function deriveQuestion(ctx, spec) {
|
|
1492
|
-
const focus = ctx.tags?.focus?.trim();
|
|
1493
|
-
const task = `Analyze this trace dataset with the available tools and report ${spec.area} findings. ${spec.description}`;
|
|
1494
|
-
return focus ? `${task} Focus: ${focus}.` : task;
|
|
1495
|
-
}
|
|
1496
|
-
function toAnalystFinding(spec, version, raw, metadata = {}) {
|
|
1497
|
-
return makeFinding({
|
|
1498
|
-
analyst_id: spec.id,
|
|
1499
|
-
area: spec.area,
|
|
1500
|
-
subject: raw.subject,
|
|
1501
|
-
claim: raw.claim,
|
|
1502
|
-
rationale: raw.rationale,
|
|
1503
|
-
severity: raw.severity,
|
|
1504
|
-
confidence: raw.confidence,
|
|
1505
|
-
evidence_refs: evidenceRefsFromRawFinding(raw),
|
|
1506
|
-
recommended_action: raw.recommended_action,
|
|
1507
|
-
metadata: { kind_version: version, ...metadata }
|
|
1508
|
-
});
|
|
1509
|
-
}
|
|
1510
|
-
function renderPriorFindings(prior) {
|
|
1511
|
-
if (!prior || prior.length === 0) return "";
|
|
1512
|
-
const MAX_ROWS = 40;
|
|
1513
|
-
const rows = prior.slice(0, MAX_ROWS).map((f) => {
|
|
1514
|
-
const subject = f.subject ? ` [${f.subject}]` : "";
|
|
1515
|
-
return ` - id=${f.finding_id} ${f.severity}${subject} ${truncateForContext(f.claim, 160)}`;
|
|
1516
|
-
});
|
|
1517
|
-
const overflow = prior.length > MAX_ROWS ? `
|
|
1518
|
-
... +${prior.length - MAX_ROWS} more prior findings (older history truncated)` : "";
|
|
1519
|
-
return [
|
|
1520
|
-
"",
|
|
1521
|
-
"",
|
|
1522
|
-
"PRIOR FINDINGS (from a previous run on related data):",
|
|
1523
|
-
"When the work you do now matches a row below, REUSE the `finding_id` (pass it as `id_basis`) so the cross-run diff stays stable.",
|
|
1524
|
-
"A finding that reappears with no remediation evidence SHOULD raise its `confidence` and may justify a higher `severity`.",
|
|
1525
|
-
...rows,
|
|
1526
|
-
overflow
|
|
1527
|
-
].filter(Boolean).join("\n");
|
|
1528
|
-
}
|
|
1529
|
-
function renderUpstreamFindings(upstream) {
|
|
1530
|
-
if (!upstream || upstream.length === 0) return "";
|
|
1531
|
-
const MAX_ROWS = 40;
|
|
1532
|
-
const rows = upstream.slice(0, MAX_ROWS).map((finding) => {
|
|
1533
|
-
const subject = finding.subject ? ` [${finding.subject}]` : "";
|
|
1534
|
-
const action = finding.recommended_action ? ` action=${truncateForContext(finding.recommended_action, 120)}` : "";
|
|
1535
|
-
const evidence = finding.evidence_refs[0] ? ` evidence=${truncateForContext(finding.evidence_refs[0].uri, 120)}` : "";
|
|
1536
|
-
return ` - id=${finding.finding_id} source=${finding.analyst_id} ${finding.severity}${subject} claim=${truncateForContext(finding.claim, 160)}${action}${evidence}`;
|
|
1537
|
-
});
|
|
1538
|
-
const overflow = upstream.length > MAX_ROWS ? `
|
|
1539
|
-
... +${upstream.length - MAX_ROWS} more upstream findings (truncated)` : "";
|
|
1540
|
-
return [
|
|
1541
|
-
"",
|
|
1542
|
-
"",
|
|
1543
|
-
"UPSTREAM FINDINGS (produced earlier in this same registry run):",
|
|
1544
|
-
"Use these as intermediate evidence. Build on them instead of repeating the same diagnosis, and cite a dependency with `finding://<id>`.",
|
|
1545
|
-
...rows,
|
|
1546
|
-
overflow
|
|
1547
|
-
].filter(Boolean).join("\n");
|
|
1548
|
-
}
|
|
1549
|
-
function truncateForContext(s, max) {
|
|
1550
|
-
if (s.length <= max) return s;
|
|
1551
|
-
return `${s.slice(0, max - 1).trimEnd()}\u2026`;
|
|
1552
|
-
}
|
|
1553
|
-
|
|
1554
|
-
// src/analyst/tool-groups.ts
|
|
1555
|
-
var TOOL_NAMES_BY_GROUP = {
|
|
1556
|
-
all: /* @__PURE__ */ new Set(),
|
|
1557
|
-
discovery: /* @__PURE__ */ new Set(["getDatasetOverview", "queryTraces", "countTraces"]),
|
|
1558
|
-
discoveryAndRead: /* @__PURE__ */ new Set([
|
|
1559
|
-
"getDatasetOverview",
|
|
1560
|
-
"queryTraces",
|
|
1561
|
-
"countTraces",
|
|
1562
|
-
"viewTrace",
|
|
1563
|
-
"viewSpans"
|
|
1564
|
-
]),
|
|
1565
|
-
discoveryAndSearch: /* @__PURE__ */ new Set([
|
|
1566
|
-
"getDatasetOverview",
|
|
1567
|
-
"queryTraces",
|
|
1568
|
-
"countTraces",
|
|
1569
|
-
"searchTrace",
|
|
1570
|
-
"searchSpan"
|
|
1571
|
-
]),
|
|
1572
|
-
targeted: /* @__PURE__ */ new Set(["getDatasetOverview", "queryTraces", "viewSpans", "searchSpan"])
|
|
1573
|
-
};
|
|
1574
|
-
function buildTraceToolsForGroup(group, store) {
|
|
1575
|
-
const all = buildTraceAnalystTools({ store });
|
|
1576
|
-
if (group === "all") return all;
|
|
1577
|
-
const allow = TOOL_NAMES_BY_GROUP[group];
|
|
1578
|
-
if (!allow) throw new Error(`unknown trace tool group: ${group}`);
|
|
1579
|
-
return all.filter((tool) => allow.has(tool.name));
|
|
1580
|
-
}
|
|
1581
|
-
|
|
1582
|
-
// src/analyst/kinds/failure-mode.ts
|
|
1583
|
-
var subjectGrammar = findingSubjectGrammarPromptFor("failure-mode");
|
|
1584
|
-
var ACTOR_PROMPT = `You are a failure-mode classifier for an OTLP trace dataset. Your job is to identify the **distinct ways agents failed** in this dataset, not to grade individual runs.
|
|
1585
|
-
|
|
1586
|
-
${subjectGrammar}
|
|
1587
|
-
|
|
1588
|
-
DISCOVERY \u2192 CLUSTER \u2192 CITE protocol:
|
|
1589
|
-
|
|
1590
|
-
1. Call \`traces.getDatasetOverview({})\` first. Use \`has_errors\`, \`models\`, \`agent_names\`, \`tools\`, and \`sample_trace_ids\` to size the failure surface.
|
|
1591
|
-
2. Use \`traces.queryTraces({ filters: { has_errors: true }, limit })\` to pull error-bearing traces. Combine with \`traces.countTraces\` to see what fraction of the dataset failed.
|
|
1592
|
-
3. For each candidate failure cluster, use \`traces.searchTrace\` with regex like \`STATUS_CODE_ERROR\`, \`MaxTurnsExceeded\`, \`assertion\`, \`unauthorized\`, \`timeout\`, \`429\`, \`5\\d\\d\`, the agent's specific error strings, or the names of its tools. Pull one or two representative traces per cluster, **not all** of them.
|
|
1593
|
-
4. **Cluster, do not enumerate.** Two failures with the same root cause should be ONE finding citing both traces, not two findings. The point of this analyst is to compress N runs into K modes.
|
|
1594
|
-
5. For each defensible cluster, emit ONE finding. Use a lowercase cluster label matching the subject grammar ("tool-call-loop", "auth-revoked-mid-run", ...). Rate it critical when it blocks the run, high when the run finishes degraded, and medium when it slows convergence. Cite representative spans and include exact error, payload, or contradictory-output quotes. Use confidence 0.85+ when multiple traces show the same shape, 0.6-0.8 for a single-trace inference, and <0.5 for speculation. Keep the imperative fix idea short; the improvement analyst expands it.
|
|
1595
|
-
|
|
1596
|
-
If the dataset has no failures, return an empty findings array \u2014 do NOT pad with low-confidence speculation.
|
|
1597
|
-
|
|
1598
|
-
**Use subqueries over loaded evidence.** After the first scan, load representative span excerpts for each candidate cluster. Then send one bounded \`llmQuery\` per cluster in one batch, including the exact excerpts and asking it to classify the root cause. Subqueries cannot call trace tools. Merge or split clusters yourself from their classifications and the cited source evidence.
|
|
1599
|
-
|
|
1600
|
-
OBSERVABILITY rules:
|
|
1601
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.
|
|
1602
|
-
- Reuse runtime variables across turns; don't recompute.`;
|
|
1603
|
-
var FAILURE_MODE_KIND_SPEC = {
|
|
1604
|
-
id: "failure-mode",
|
|
1605
|
-
description: "Clusters trace-dataset failures into distinct failure modes with cited evidence and a short recommended action.",
|
|
1606
|
-
area: "failure-mode",
|
|
1607
|
-
version: "1.2.0",
|
|
1608
|
-
actorDescription: ACTOR_PROMPT,
|
|
1609
|
-
buildTools: (store) => buildTraceToolsForGroup("all", store),
|
|
1610
|
-
subqueries: { maxCalls: 8, maxParallel: 4 },
|
|
1611
|
-
maxTurns: 24,
|
|
1612
|
-
cost: { kind: "llm" }
|
|
1613
|
-
};
|
|
1614
|
-
|
|
1615
|
-
// src/analyst/kinds/improvement.ts
|
|
1616
|
-
var subjectGrammar2 = findingSubjectGrammarPromptFor("improvement");
|
|
1617
|
-
var ACTOR_PROMPT2 = `You are a self-improvement analyst. Your job is to propose **concrete, locus-named edits** the agent's runtime should adopt to fix the failure modes, knowledge gaps, and poisonings present in this dataset.
|
|
1618
|
-
|
|
1619
|
-
Upstream analysts have already classified the problems. Your job is to convert each problem into a *change to make* and grade its expected leverage. Each finding is one proposed edit.
|
|
1620
|
-
|
|
1621
|
-
${subjectGrammar2}
|
|
1622
|
-
|
|
1623
|
-
DISCOVERY \u2192 CANDIDATE-FIXES \u2192 COMPETE \u2192 CITE protocol:
|
|
1624
|
-
|
|
1625
|
-
1. \`traces.getDatasetOverview({})\` first. Note the agents, tools, and any system-prompt fingerprints (look for the prompt text echoed in early spans).
|
|
1626
|
-
2. For each high-severity failure pattern, generate 2-3 candidate fixes. Real candidate axes:
|
|
1627
|
-
- **System-prompt edit** \u2014 add an instruction, remove a misleading one, restructure precedence
|
|
1628
|
-
- **Tool description edit** \u2014 rewrite a tool's description so the agent picks it correctly / passes valid args
|
|
1629
|
-
- **New tool** \u2014 add a tool the agent kept emulating in code
|
|
1630
|
-
- **RAG ingestion** \u2014 add a document or correct a stale one
|
|
1631
|
-
- **Memory invalidation** \u2014 clear cached prior-run decisions that no longer apply
|
|
1632
|
-
- **Scaffolding** \u2014 add a precondition check, a retry policy, a turn budget, a verification step
|
|
1633
|
-
- **Output schema** \u2014 narrow the agent's output to forbid the failure shape
|
|
1634
|
-
- **Skill / MCP / hook / subagent** \u2014 change the reusable profile component responsible for the behavior
|
|
1635
|
-
- **Workflow / rollout policy** \u2014 change orchestration, budget, sampling, or stopping behavior
|
|
1636
|
-
- **Code** \u2014 change an implementation path when profile edits cannot repair the behavior
|
|
1637
|
-
3. **Compare candidate fixes with bounded subqueries.** Load the representative failure excerpts, then send one \`llmQuery\` per candidate-fix axis the same evidence. Ask for likely effect, side effects, and implementation scope. Subqueries cannot call trace tools; trace ids alone are insufficient context.
|
|
1638
|
-
4. After the comparisons return, **pick the winning candidate per cluster** based on expected effect and risk, then emit ONE finding. Keep the alternatives and rejection reasons in the rationale so the recommendation is auditable.
|
|
1639
|
-
5. **Cross-reference upstream findings.** Cite prior failure-mode or knowledge-gap findings as \`finding://<prior-finding-id>\`. This builds the dependency graph that lets the dashboard show "fix #X resolves failure modes A, B, C."
|
|
1640
|
-
|
|
1641
|
-
For each winning recommendation, emit ONE finding. Use one exact locus from the subject grammar and state the edit in one sentence. Match leverage to the source failure's severity; use medium for quality-of-life changes and info for cleanup with no behavioral effect. Cite the targeted \`finding://<id>\` when available and the most representative span when useful. Quote the problem being fixed. Use confidence 0.85+ for a mechanical fix to a well-evidenced failure, 0.6-0.8 when judgment is required, and <0.5 for speculation. Explain in at most two sentences why this candidate beat its alternatives. The recommended action must be the literal diff, quoted replacement, tool description, or setting change.
|
|
1642
|
-
|
|
1643
|
-
If no upstream failure findings exist in this run, derive your own from the trace dataset using the failure-mode protocol inline (\`searchTrace\` for STATUS_CODE_ERROR / MaxTurnsExceeded / etc.). But prefer to consume upstream findings when present \u2014 the kinds are designed to chain.
|
|
1644
|
-
|
|
1645
|
-
Do NOT propose a fix you cannot defend with evidence. "Tighten the prompt" is not a finding; "Add 'When the user asks for X, always Y' to the system prompt section "request-classification"" is.
|
|
1646
|
-
|
|
1647
|
-
OBSERVABILITY rules:
|
|
1648
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.`;
|
|
1649
|
-
var IMPROVEMENT_KIND_SPEC = {
|
|
1650
|
-
id: "improvement",
|
|
1651
|
-
description: "Converts upstream failure / gap / poisoning findings into concrete locus-named edits (prompt, tool-doc, RAG, scaffolding) with leverage grades.",
|
|
1652
|
-
area: "improvement",
|
|
1653
|
-
version: "1.2.0",
|
|
1654
|
-
actorDescription: ACTOR_PROMPT2,
|
|
1655
|
-
buildTools: (store) => buildTraceToolsForGroup("all", store),
|
|
1656
|
-
subqueries: { maxCalls: 8, maxParallel: 4 },
|
|
1657
|
-
maxTurns: 30,
|
|
1658
|
-
maxRuntimeChars: 12e3,
|
|
1659
|
-
cost: { kind: "llm" }
|
|
1660
|
-
};
|
|
1661
|
-
|
|
1662
|
-
// src/analyst/kinds/knowledge-gap.ts
|
|
1663
|
-
var subjectGrammar3 = findingSubjectGrammarPromptFor("knowledge-gap");
|
|
1664
|
-
var ACTOR_PROMPT3 = `You are a knowledge-gap analyst for an OTLP trace dataset. Your job is to identify the **specific pieces of information the agent lacked, or that were stale**, that caused poor decisions.
|
|
1665
|
-
|
|
1666
|
-
The agent under analysis maintains a curated knowledge base via \`@tangle-network/agent-knowledge\` \u2014 a wiki of \`KnowledgePage\`s with raw source anchors, claims, and relations. The primary expected store of agent-knowable facts IS that wiki. A "knowledge gap" is anything the agent had to discover or guess at run-time that the wiki should have held \u2014 or an outdated/contradictory fact the agent picked up from a non-wiki source.
|
|
1667
|
-
|
|
1668
|
-
${subjectGrammar3}
|
|
1669
|
-
|
|
1670
|
-
DISCOVERY \u2192 ATTRIBUTE-TO-LAYER \u2192 CITE protocol:
|
|
1671
|
-
|
|
1672
|
-
1. \`traces.getDatasetOverview({})\` first. Note which agents, tools, and models appear.
|
|
1673
|
-
2. Pull traces where the agent shows gap signals. The strongest signals are:
|
|
1674
|
-
- Self-correction turns ("I assumed X but\u2026", "let me re-check", "actually,")
|
|
1675
|
-
- Clarifying-question turns where the agent asked the user something the runtime should have surfaced
|
|
1676
|
-
- Repeated retrieval / lookup calls for the same artifact with slightly varied queries
|
|
1677
|
-
- Tool errors that name a missing argument or unknown resource
|
|
1678
|
-
- Web-search calls returning pages dated before a known cutoff for content that changes (versioned APIs, schemas, policies)
|
|
1679
|
-
- Agent quoting a tool's docs / system prompt incorrectly because the actual text was insufficient
|
|
1680
|
-
- Fabricated identifiers that don't appear in dataset \`sample_trace_ids\`
|
|
1681
|
-
Use \`traces.searchTrace\` with patterns like \`I (don.?t|do not) know\`, \`assumed\`, \`unclear\`, \`could you (clarify|tell me|provide)\`, \`not found\`, \`undefined\`, \`unknown\`, \`null\`, dates older than the analysis window, or the agent's specific clarification phrases.
|
|
1682
|
-
3. For each gap, identify the **layer of the runtime that should have prevented it** and use its exact locus from the subject grammar above.
|
|
1683
|
-
4. For each defensible gap, emit ONE finding. Use an exact locus from the subject grammar and name the missing or stale knowledge (for example, "wiki has no page on invoice line-item shape; agent re-derived it from raw spans"). Rate it high when it caused failure or a clarifying question, medium for unnecessary turns, and low for minor inefficiency. Cite the span where the question, correction, retrieval miss, or stale result surfaced and quote it exactly. Use confidence 0.85+ when the agent articulated the gap and 0.6-0.8 when inferred. Recommend a concrete wiki edit for an agent-knowledge locus or a prompt/tool-description edit otherwise.
|
|
1684
|
-
|
|
1685
|
-
**Compare layers over loaded evidence.** After the first scan, load the exact excerpts behind candidates across \`agent-knowledge:*\`, \`websearch:outdated\`, \`tool-doc:*\`, \`system-prompt:*\`, and \`memory:*\`. Use one bounded \`llmQuery\` per layer to classify those excerpts. Subqueries cannot call trace tools. Merge their classifications into the final finding set only when the source excerpts support them.
|
|
1686
|
-
|
|
1687
|
-
Do NOT report a gap that the agent later recovered from cleanly within the same turn \u2014 that's resilience, not a gap. Cite the *non-recovery* version when both exist.
|
|
1688
|
-
|
|
1689
|
-
OBSERVABILITY rules:
|
|
1690
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.`;
|
|
1691
|
-
var KNOWLEDGE_GAP_KIND_SPEC = {
|
|
1692
|
-
id: "knowledge-gap",
|
|
1693
|
-
description: "Identifies missing or stale pieces of knowledge \u2014 primarily against the agent-knowledge wiki \u2014 and attributes each to the runtime layer (wiki page, claim, raw source, websearch, tool-doc, system-prompt, memory) that should have held it.",
|
|
1694
|
-
area: "knowledge-gap",
|
|
1695
|
-
version: "1.2.0",
|
|
1696
|
-
actorDescription: ACTOR_PROMPT3,
|
|
1697
|
-
buildTools: (store) => buildTraceToolsForGroup("discoveryAndSearch", store),
|
|
1698
|
-
subqueries: { maxCalls: 5, maxParallel: 4 },
|
|
1699
|
-
maxTurns: 18,
|
|
1700
|
-
cost: { kind: "llm" }
|
|
1701
|
-
};
|
|
1702
|
-
|
|
1703
|
-
// src/analyst/kinds/knowledge-poisoning.ts
|
|
1704
|
-
var subjectGrammar4 = findingSubjectGrammarPromptFor("knowledge-poisoning");
|
|
1705
|
-
var ACTOR_PROMPT4 = `You are a knowledge-poisoning analyst for an OTLP trace dataset. Your job is to identify cases where the agent **confidently used wrong information** \u2014 not where it lacked information (that's the knowledge-gap analyst).
|
|
1706
|
-
|
|
1707
|
-
${subjectGrammar4}
|
|
1708
|
-
|
|
1709
|
-
DISCOVERY \u2192 DUAL-VERIFY \u2192 CITE protocol:
|
|
1710
|
-
|
|
1711
|
-
1. \`traces.getDatasetOverview({})\` first. Identify the agents, models, and tools.
|
|
1712
|
-
2. Pull traces where the agent's confident action was later contradicted. Strongest signals:
|
|
1713
|
-
- Agent stated a fact in one span; a later span surfaced contradictory evidence; the agent then proceeded anyway or fabricated reconciliation.
|
|
1714
|
-
- Tool call with stale arguments (an id that no longer exists, an API shape that changed).
|
|
1715
|
-
- Agent cited an \`agent-knowledge\` wiki page or claim whose content contradicts the trace's own evidence \u2014 the wiki itself drifted.
|
|
1716
|
-
- Web-search result the agent cited that returned an outdated page; agent treated it as canonical.
|
|
1717
|
-
- System-prompt instruction the agent followed that ground-truth evidence in the trace contradicts (e.g. prompt says "use endpoint A"; tool reply says "endpoint A deprecated, use B").
|
|
1718
|
-
- Repeated wrong-shape parsing despite the tool's actual output proving the shape.
|
|
1719
|
-
3. Use \`traces.searchTrace\` with regex on phrases like \`actually\`, \`turns out\`, \`previously assumed\`, \`old version\`, \`deprecated\`, \`updated to\`, \`now uses\`, or specific entity names you suspect have changed.
|
|
1720
|
-
4. For each candidate poisoning, **DUAL-VERIFY**:
|
|
1721
|
-
- Confirm the agent actually acted on the false belief (cite the span where it did)
|
|
1722
|
-
- Confirm the belief is actually false in this trace's own evidence (cite the span that contradicts it)
|
|
1723
|
-
Only emit a finding when both halves are nailed down. If you can only nail one, drop it \u2014 single-evidence poisoning findings are too speculative to be useful.
|
|
1724
|
-
|
|
1725
|
-
**Independently assess both halves.** Load the action excerpt and contradicting excerpt yourself, then send bounded \`llmQuery\` calls the exact evidence for "did the agent act?" and "does the trace contradict the belief?" Subqueries cannot call trace tools. Accept a poisoning only when both assessments and the source excerpts support it.
|
|
1726
|
-
|
|
1727
|
-
For each confirmed poisoning, emit ONE finding. Use the source of the false belief as the exact subject. State "agent believed X (from source S); trace evidence shows X is false." Rate it critical for a wrong user-visible action, high when caught internally after significant waste, and medium for inefficiency. Cite BOTH the action span and the contradicting span with exact quotes. Use confidence 0.85+ when both halves have exact quotes and 0.6-0.8 when one half is inferred. Recommend the literal source correction: update the wiki claim, invalidate and re-curate the raw source, or replace the stale prompt/tool instruction.
|
|
1728
|
-
|
|
1729
|
-
Do NOT report a finding if the agent caught and corrected the false belief in the same turn \u2014 that's the system working. Reserve poisoning for cases where the false belief shaped downstream action.
|
|
1730
|
-
|
|
1731
|
-
OBSERVABILITY rules:
|
|
1732
|
-
- Each non-final turn must emit at least one \`console.log\` for evidence.`;
|
|
1733
|
-
var KNOWLEDGE_POISONING_KIND_SPEC = {
|
|
1734
|
-
id: "knowledge-poisoning",
|
|
1735
|
-
description: "Identifies confident-but-wrong actions caused by stale memory, contradicting RAG, deprecated tool docs, or outdated system-prompt instructions.",
|
|
1736
|
-
area: "knowledge-poisoning",
|
|
1737
|
-
version: "1.2.0",
|
|
1738
|
-
actorDescription: ACTOR_PROMPT4,
|
|
1739
|
-
buildTools: (store) => buildTraceToolsForGroup("all", store),
|
|
1740
|
-
subqueries: { maxCalls: 8, maxParallel: 4 },
|
|
1741
|
-
maxTurns: 20,
|
|
1742
|
-
minimumEvidenceCitations: 2,
|
|
1743
|
-
cost: { kind: "llm" }
|
|
1744
|
-
};
|
|
1745
|
-
|
|
1746
|
-
// src/analyst/kinds/index.ts
|
|
1747
|
-
var DEFAULT_TRACE_ANALYST_KINDS = [
|
|
1748
|
-
FAILURE_MODE_KIND_SPEC,
|
|
1749
|
-
KNOWLEDGE_GAP_KIND_SPEC,
|
|
1750
|
-
KNOWLEDGE_POISONING_KIND_SPEC,
|
|
1751
|
-
IMPROVEMENT_KIND_SPEC
|
|
1752
|
-
];
|
|
1753
|
-
|
|
1754
|
-
// src/analyst/registry.ts
|
|
1755
|
-
import { randomUUID } from "crypto";
|
|
1756
|
-
var AnalystRegistry = class {
|
|
1757
|
-
analysts = /* @__PURE__ */ new Map();
|
|
1758
|
-
options;
|
|
1759
|
-
constructor(options = {}) {
|
|
1760
|
-
this.options = options;
|
|
1761
|
-
}
|
|
1762
|
-
register(analyst) {
|
|
1763
|
-
if (!analyst.id) throw new Error("AnalystRegistry.register: analyst.id is required");
|
|
1764
|
-
if (this.analysts.has(analyst.id)) {
|
|
1765
|
-
throw new Error(`AnalystRegistry.register: duplicate analyst id "${analyst.id}"`);
|
|
1766
|
-
}
|
|
1767
|
-
if (!analyst.version) {
|
|
1768
|
-
throw new Error(`AnalystRegistry.register: analyst "${analyst.id}" must declare a version`);
|
|
1769
|
-
}
|
|
1770
|
-
if (analyst.cost.kind === "deterministic" && analyst.cost.settlement_timeout_ms !== void 0) {
|
|
1771
|
-
throw new TypeError(
|
|
1772
|
-
`AnalystRegistry.register: deterministic analyst "${analyst.id}" cannot declare settlement_timeout_ms`
|
|
1773
|
-
);
|
|
1774
|
-
}
|
|
1775
|
-
if (analyst.cost.settlement_timeout_ms !== void 0) {
|
|
1776
|
-
validateUsageSettlementTimeout(analyst.cost.settlement_timeout_ms);
|
|
1777
|
-
}
|
|
1778
|
-
this.analysts.set(analyst.id, analyst);
|
|
1779
|
-
}
|
|
1780
|
-
list() {
|
|
1781
|
-
return Array.from(this.analysts.values()).map((a) => ({
|
|
1782
|
-
id: a.id,
|
|
1783
|
-
description: a.description,
|
|
1784
|
-
version: a.version,
|
|
1785
|
-
cost: a.cost
|
|
1786
|
-
}));
|
|
1787
|
-
}
|
|
1788
|
-
async run(runId, inputs, runOpts = {}) {
|
|
1789
|
-
for await (const ev of this.runStream(runId, inputs, runOpts)) {
|
|
1790
|
-
if (ev.type === "run-completed") return ev.result;
|
|
1791
|
-
}
|
|
1792
|
-
throw new Error("AnalystRegistry.run: stream completed without run-completed event");
|
|
1793
|
-
}
|
|
1794
|
-
/**
|
|
1795
|
-
* Streaming counterpart to `run()`. Emits `AnalystRunEvent` values
|
|
1796
|
-
* in real time — `run-started`, then per-analyst `skipped` /
|
|
1797
|
-
* `started` / `completed`, then a terminal `run-completed` whose
|
|
1798
|
-
* payload is the full `AnalystRunResult`. UIs use this to render
|
|
1799
|
-
* progress; persistence consumers use `run()` and read the result.
|
|
1800
|
-
*
|
|
1801
|
-
* Hooks (`onBeforeAnalyze` / `onAfterAnalyze` / `onError` /
|
|
1802
|
-
* `onComplete`) fire as before — streaming is additive, not a hook
|
|
1803
|
-
* replacement.
|
|
1804
|
-
*/
|
|
1805
|
-
async *runStream(runId, inputs, runOpts = {}) {
|
|
1806
|
-
const correlationId = `ar_${randomUUID().slice(0, 12)}`;
|
|
1807
|
-
const log = this.options.log ?? (() => {
|
|
1808
|
-
});
|
|
1809
|
-
const hooks = this.options.hooks ?? {};
|
|
1810
|
-
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1811
|
-
const started = Date.now();
|
|
1812
|
-
const timeoutMs = validateTimeout(runOpts.timeoutMs);
|
|
1813
|
-
const deadlineMs = timeoutMs === void 0 ? void 0 : started + timeoutMs;
|
|
1814
|
-
const timeoutSignal = timeoutMs === void 0 ? void 0 : AbortSignal.timeout(timeoutMs);
|
|
1815
|
-
const runSignal = combineAbortSignals(runOpts.signal, timeoutSignal);
|
|
1816
|
-
const selected = this.selectAnalysts(runOpts);
|
|
1817
|
-
const budget = runOpts.budget ?? this.options.defaultBudget;
|
|
1818
|
-
validateBudgetPolicy(budget);
|
|
1819
|
-
yield {
|
|
1820
|
-
type: "run-started",
|
|
1821
|
-
run_id: runId,
|
|
1822
|
-
correlation_id: correlationId,
|
|
1823
|
-
started_at: startedAt,
|
|
1824
|
-
analyst_ids: selected.map((a) => a.id)
|
|
1825
|
-
};
|
|
1826
|
-
const summaries = [];
|
|
1827
|
-
const allFindings = [];
|
|
1828
|
-
let totalCost = 0;
|
|
1829
|
-
let remainingUsd = budget?.totalUsd;
|
|
1830
|
-
const runnableAnalysts = selected.filter((a) => this.routeInput(a, inputs).kind !== "missing");
|
|
1831
|
-
const runnableCount = runnableAnalysts.length;
|
|
1832
|
-
const weights = budget?.weights;
|
|
1833
|
-
const totalWeight = weights && budget?.totalUsd != null && !budget.allocate && runnableCount > 0 ? runnableAnalysts.reduce((sum, analyst) => sum + analystWeight(weights, analyst.id), 0) : void 0;
|
|
1834
|
-
if (totalWeight === 0) {
|
|
1835
|
-
throw new Error("BudgetPolicy.weights must allocate positive weight to a runnable analyst");
|
|
1836
|
-
}
|
|
1837
|
-
for (const analyst of selected) {
|
|
1838
|
-
const t0 = Date.now();
|
|
1839
|
-
if (runSignal?.aborted) {
|
|
1840
|
-
const summary2 = abortedBeforeStartSummary(analyst, runSignal);
|
|
1841
|
-
summaries.push(summary2);
|
|
1842
|
-
log(`[analyst] skip ${analyst.id} \u2014 run aborted`, { runId, reason: summary2.reason });
|
|
1843
|
-
yield { type: "analyst-skipped", summary: summary2 };
|
|
1844
|
-
continue;
|
|
1845
|
-
}
|
|
1846
|
-
const input = this.routeInput(analyst, inputs);
|
|
1847
|
-
if (input.kind === "missing") {
|
|
1848
|
-
const summary2 = {
|
|
1849
|
-
analyst_id: analyst.id,
|
|
1850
|
-
status: "skipped",
|
|
1851
|
-
reason: `missing input of kind '${analyst.inputKind}'`,
|
|
1852
|
-
findings_count: 0,
|
|
1853
|
-
latency_ms: 0,
|
|
1854
|
-
usage: zeroUsage()
|
|
1855
|
-
};
|
|
1856
|
-
summaries.push(summary2);
|
|
1857
|
-
log(`[analyst] skip ${analyst.id} \u2014 missing input`, { runId, kind: analyst.inputKind });
|
|
1858
|
-
await waitForHook(
|
|
1859
|
-
hooks.onAfterAnalyze ? () => hooks.onAfterAnalyze?.({ analyst, summary: summary2, findings: [], runId }) : void 0,
|
|
1860
|
-
runSignal
|
|
1861
|
-
);
|
|
1862
|
-
yield { type: "analyst-skipped", summary: summary2 };
|
|
1863
|
-
continue;
|
|
1864
|
-
}
|
|
1865
|
-
const perBudget = allocateBudget(budget, {
|
|
1866
|
-
analyst,
|
|
1867
|
-
remainingUsd,
|
|
1868
|
-
runningCount: runnableCount,
|
|
1869
|
-
totalWeight
|
|
1870
|
-
});
|
|
1871
|
-
const usageReceipts = [];
|
|
1872
|
-
const ctx = {
|
|
1873
|
-
runId,
|
|
1874
|
-
correlationId,
|
|
1875
|
-
deadlineMs,
|
|
1876
|
-
budgetUsd: perBudget,
|
|
1877
|
-
costLedger: runOpts.costLedger,
|
|
1878
|
-
costPhase: runOpts.costPhase,
|
|
1879
|
-
chat: this.options.chat,
|
|
1880
|
-
tags: runOpts.tags,
|
|
1881
|
-
log: (msg, fields) => log(`[${analyst.id}] ${msg}`, { runId, correlationId, ...fields }),
|
|
1882
|
-
signal: runSignal,
|
|
1883
|
-
priorFindings: selectPriorFindings(runOpts.priorFindings, analyst.id),
|
|
1884
|
-
upstreamFindings: runOpts.chainFindings && allFindings.length > 0 ? [...allFindings] : void 0,
|
|
1885
|
-
recordUsage: (receipt) => {
|
|
1886
|
-
assertValidUsageReceipt(receipt);
|
|
1887
|
-
usageReceipts.push(receipt);
|
|
1888
|
-
}
|
|
1889
|
-
};
|
|
1890
|
-
await waitForHook(
|
|
1891
|
-
hooks.onBeforeAnalyze ? () => hooks.onBeforeAnalyze?.({ analyst, ctx, runId }) : void 0,
|
|
1892
|
-
runSignal
|
|
1893
|
-
);
|
|
1894
|
-
if (runSignal?.aborted) {
|
|
1895
|
-
const summary2 = abortedBeforeStartSummary(analyst, runSignal, Date.now() - t0);
|
|
1896
|
-
summaries.push(summary2);
|
|
1897
|
-
log(`[analyst] skip ${analyst.id} \u2014 run aborted`, { runId, reason: summary2.reason });
|
|
1898
|
-
yield { type: "analyst-skipped", summary: summary2 };
|
|
1899
|
-
continue;
|
|
1900
|
-
}
|
|
1901
|
-
const effectiveBudget = validateEffectiveBudget(ctx.budgetUsd, remainingUsd, analyst.id);
|
|
1902
|
-
yield {
|
|
1903
|
-
type: "analyst-started",
|
|
1904
|
-
analyst_id: analyst.id,
|
|
1905
|
-
started_at: new Date(t0).toISOString()
|
|
1906
|
-
};
|
|
1907
|
-
let findings;
|
|
1908
|
-
let summary;
|
|
1909
|
-
try {
|
|
1910
|
-
if (runSignal?.aborted) throw abortReason(runSignal);
|
|
1911
|
-
findings = await waitForOperation(
|
|
1912
|
-
analyst.analyze(input.value, ctx),
|
|
1913
|
-
runSignal,
|
|
1914
|
-
analystAbortGraceMs(analyst)
|
|
1915
|
-
);
|
|
1916
|
-
const latency = Date.now() - t0;
|
|
1917
|
-
const usage = resolveUsage(analyst, usageReceipts);
|
|
1918
|
-
const cost = knownCostUsd(usage);
|
|
1919
|
-
totalCost += cost;
|
|
1920
|
-
if (typeof remainingUsd === "number") {
|
|
1921
|
-
remainingUsd = Math.max(0, remainingUsd - budgetDebit(usage, effectiveBudget));
|
|
1922
|
-
}
|
|
1923
|
-
allFindings.push(...findings);
|
|
1924
|
-
summary = {
|
|
1925
|
-
analyst_id: analyst.id,
|
|
1926
|
-
status: "ok",
|
|
1927
|
-
findings_count: findings.length,
|
|
1928
|
-
latency_ms: latency,
|
|
1929
|
-
usage
|
|
1930
|
-
};
|
|
1931
|
-
summaries.push(summary);
|
|
1932
|
-
log(`[analyst] ok ${analyst.id}`, {
|
|
1933
|
-
runId,
|
|
1934
|
-
findings: findings.length,
|
|
1935
|
-
latency_ms: latency,
|
|
1936
|
-
cost_usd: cost,
|
|
1937
|
-
cost_kind: usage.cost.kind,
|
|
1938
|
-
input_tokens: usage.tokens?.input ?? null,
|
|
1939
|
-
output_tokens: usage.tokens?.output ?? null
|
|
1940
|
-
});
|
|
1941
|
-
if (effectiveBudget !== void 0 && usage.cost.kind === "uncaptured") {
|
|
1942
|
-
log(`[analyst] WARN ${analyst.id} \u2014 USD cost uncaptured; budget not reconciled`, {
|
|
1943
|
-
runId,
|
|
1944
|
-
budget_usd: effectiveBudget,
|
|
1945
|
-
cost_captured: false
|
|
1946
|
-
});
|
|
1947
|
-
}
|
|
1948
|
-
} catch (err) {
|
|
1949
|
-
const latency = Date.now() - t0;
|
|
1950
|
-
const e = err instanceof Error ? err : new Error(String(err));
|
|
1951
|
-
const hookFindings = runSignal?.aborted ? [] : await hooks.onError?.({ analyst, error: e, runId }) ?? [];
|
|
1952
|
-
if (hookFindings.length) allFindings.push(...hookFindings);
|
|
1953
|
-
const usage = resolveUsage(analyst, usageReceipts);
|
|
1954
|
-
const cost = knownCostUsd(usage);
|
|
1955
|
-
totalCost += cost;
|
|
1956
|
-
if (typeof remainingUsd === "number") {
|
|
1957
|
-
remainingUsd = Math.max(0, remainingUsd - budgetDebit(usage, effectiveBudget));
|
|
1958
|
-
}
|
|
1959
|
-
const summary2 = {
|
|
1960
|
-
analyst_id: analyst.id,
|
|
1961
|
-
status: "failed",
|
|
1962
|
-
findings_count: hookFindings.length,
|
|
1963
|
-
latency_ms: latency,
|
|
1964
|
-
usage,
|
|
1965
|
-
error: { class: e.constructor.name, message: e.message }
|
|
1966
|
-
};
|
|
1967
|
-
summaries.push(summary2);
|
|
1968
|
-
log(`[analyst] FAIL ${analyst.id}`, {
|
|
1969
|
-
runId,
|
|
1970
|
-
error_class: e.constructor.name,
|
|
1971
|
-
error: e.message,
|
|
1972
|
-
cost_usd: cost,
|
|
1973
|
-
cost_kind: usage.cost.kind
|
|
1974
|
-
});
|
|
1975
|
-
if (effectiveBudget !== void 0 && usage.cost.kind === "uncaptured") {
|
|
1976
|
-
log(`[analyst] WARN ${analyst.id} \u2014 USD cost uncaptured; budget not reconciled`, {
|
|
1977
|
-
runId,
|
|
1978
|
-
budget_usd: effectiveBudget,
|
|
1979
|
-
cost_captured: false
|
|
1980
|
-
});
|
|
1981
|
-
}
|
|
1982
|
-
await waitForHook(
|
|
1983
|
-
hooks.onAfterAnalyze ? () => hooks.onAfterAnalyze?.({ analyst, summary: summary2, findings: hookFindings, runId }) : void 0,
|
|
1984
|
-
runSignal
|
|
1985
|
-
);
|
|
1986
|
-
yield { type: "analyst-completed", summary: summary2, findings: hookFindings };
|
|
1987
|
-
continue;
|
|
1988
|
-
}
|
|
1989
|
-
await waitForHook(
|
|
1990
|
-
hooks.onAfterAnalyze ? () => hooks.onAfterAnalyze?.({ analyst, summary, findings, runId }) : void 0,
|
|
1991
|
-
runSignal
|
|
1992
|
-
);
|
|
1993
|
-
yield { type: "analyst-completed", summary, findings };
|
|
1994
|
-
}
|
|
1995
|
-
const result = {
|
|
1996
|
-
run_id: runId,
|
|
1997
|
-
correlation_id: correlationId,
|
|
1998
|
-
started_at: startedAt,
|
|
1999
|
-
ended_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2000
|
-
findings: allFindings,
|
|
2001
|
-
per_analyst: summaries,
|
|
2002
|
-
total_cost_usd: totalCost,
|
|
2003
|
-
total_cost_provenance: aggregateCostProvenance(
|
|
2004
|
-
summaries.map((summary) => summary.usage?.cost ?? { kind: "uncaptured", usd: null })
|
|
2005
|
-
)
|
|
2006
|
-
};
|
|
2007
|
-
await waitForHook(
|
|
2008
|
-
hooks.onComplete ? () => hooks.onComplete?.({ result }) : void 0,
|
|
2009
|
-
runSignal
|
|
2010
|
-
);
|
|
2011
|
-
yield { type: "run-completed", result };
|
|
2012
|
-
}
|
|
2013
|
-
selectAnalysts(opts) {
|
|
2014
|
-
let candidates = Array.from(this.analysts.values());
|
|
2015
|
-
if (opts.only?.length) {
|
|
2016
|
-
const only = new Set(opts.only);
|
|
2017
|
-
candidates = candidates.filter((a) => only.has(a.id));
|
|
2018
|
-
}
|
|
2019
|
-
if (opts.skip?.length) {
|
|
2020
|
-
const skip = new Set(opts.skip);
|
|
2021
|
-
candidates = candidates.filter((a) => !skip.has(a.id));
|
|
2022
|
-
}
|
|
2023
|
-
return candidates;
|
|
2024
|
-
}
|
|
2025
|
-
routeInput(analyst, inputs) {
|
|
2026
|
-
switch (analyst.inputKind) {
|
|
2027
|
-
case "trace-store":
|
|
2028
|
-
return inputs.traceStore ? { kind: "present", value: inputs.traceStore } : { kind: "missing" };
|
|
2029
|
-
case "artifact-dir":
|
|
2030
|
-
return inputs.artifactDir ? { kind: "present", value: inputs.artifactDir } : { kind: "missing" };
|
|
2031
|
-
case "run-record":
|
|
2032
|
-
return inputs.runRecord ? { kind: "present", value: inputs.runRecord } : { kind: "missing" };
|
|
2033
|
-
case "judge-input":
|
|
2034
|
-
return inputs.judgeInput ? { kind: "present", value: inputs.judgeInput } : { kind: "missing" };
|
|
2035
|
-
case "custom": {
|
|
2036
|
-
const v = inputs.custom?.[analyst.id];
|
|
2037
|
-
return v !== void 0 ? { kind: "present", value: v } : { kind: "missing" };
|
|
2038
|
-
}
|
|
2039
|
-
}
|
|
2040
|
-
}
|
|
2041
|
-
};
|
|
2042
|
-
function validateTimeout(timeoutMs) {
|
|
2043
|
-
if (timeoutMs === void 0) return void 0;
|
|
2044
|
-
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
|
|
2045
|
-
throw new TypeError(
|
|
2046
|
-
"RegistryRunOpts.timeoutMs must be a positive safe integer no greater than 2147483647"
|
|
2047
|
-
);
|
|
2048
|
-
}
|
|
2049
|
-
return timeoutMs;
|
|
2050
|
-
}
|
|
2051
|
-
async function waitForOperation(operation, signal, abortGraceMs) {
|
|
2052
|
-
if (!signal) return operation;
|
|
2053
|
-
if (signal.aborted) {
|
|
2054
|
-
void operation.catch(() => {
|
|
2055
|
-
});
|
|
2056
|
-
throw abortReason(signal);
|
|
2057
|
-
}
|
|
2058
|
-
return new Promise((resolve, reject) => {
|
|
2059
|
-
let settlementTimer;
|
|
2060
|
-
const cleanup = () => {
|
|
2061
|
-
signal.removeEventListener("abort", onAbort);
|
|
2062
|
-
if (settlementTimer) clearTimeout(settlementTimer);
|
|
2063
|
-
};
|
|
2064
|
-
const onAbort = () => {
|
|
2065
|
-
if (abortGraceMs === 0) {
|
|
2066
|
-
cleanup();
|
|
2067
|
-
reject(abortReason(signal));
|
|
2068
|
-
return;
|
|
2069
|
-
}
|
|
2070
|
-
settlementTimer = setTimeout(() => {
|
|
2071
|
-
cleanup();
|
|
2072
|
-
reject(abortReason(signal));
|
|
2073
|
-
}, abortGraceMs);
|
|
2074
|
-
};
|
|
2075
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
2076
|
-
operation.then(
|
|
2077
|
-
(value) => {
|
|
2078
|
-
cleanup();
|
|
2079
|
-
if (signal.aborted) reject(abortReason(signal));
|
|
2080
|
-
else resolve(value);
|
|
2081
|
-
},
|
|
2082
|
-
(error) => {
|
|
2083
|
-
cleanup();
|
|
2084
|
-
reject(signal.aborted ? abortReason(signal) : error);
|
|
2085
|
-
}
|
|
2086
|
-
);
|
|
2087
|
-
});
|
|
2088
|
-
}
|
|
2089
|
-
async function waitForHook(operation, signal) {
|
|
2090
|
-
if (operation === void 0 || signal?.aborted) return void 0;
|
|
2091
|
-
try {
|
|
2092
|
-
return await waitForOperation(
|
|
2093
|
-
Promise.resolve().then(() => {
|
|
2094
|
-
if (signal?.aborted) throw abortReason(signal);
|
|
2095
|
-
return operation();
|
|
2096
|
-
}),
|
|
2097
|
-
signal,
|
|
2098
|
-
0
|
|
2099
|
-
);
|
|
2100
|
-
} catch (error) {
|
|
2101
|
-
if (signal?.aborted) return void 0;
|
|
2102
|
-
throw error;
|
|
2103
|
-
}
|
|
2104
|
-
}
|
|
2105
|
-
function analystAbortGraceMs(analyst) {
|
|
2106
|
-
if (analyst.cost.kind === "deterministic") return 0;
|
|
2107
|
-
const settlementMs = validateUsageSettlementTimeout(analyst.cost.settlement_timeout_ms);
|
|
2108
|
-
if (settlementMs === 0) return 0;
|
|
2109
|
-
return Math.min(settlementMs + 100, 2147483647);
|
|
2110
|
-
}
|
|
2111
|
-
function abortedBeforeStartSummary(analyst, signal, latencyMs = 0) {
|
|
2112
|
-
const reason = abortReason(signal);
|
|
2113
|
-
return {
|
|
2114
|
-
analyst_id: analyst.id,
|
|
2115
|
-
status: "skipped",
|
|
2116
|
-
reason: `${reason.name}: ${reason.message}`,
|
|
2117
|
-
findings_count: 0,
|
|
2118
|
-
latency_ms: latencyMs,
|
|
2119
|
-
usage: zeroUsage()
|
|
2120
|
-
};
|
|
2121
|
-
}
|
|
2122
|
-
function abortReason(signal) {
|
|
2123
|
-
return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
|
|
2124
|
-
}
|
|
2125
|
-
function allocateBudget(policy, args) {
|
|
2126
|
-
if (!policy) return void 0;
|
|
2127
|
-
if (policy.allocate) {
|
|
2128
|
-
const allocated2 = policy.allocate({
|
|
2129
|
-
analyst: args.analyst,
|
|
2130
|
-
totalUsd: policy.totalUsd,
|
|
2131
|
-
remainingUsd: args.remainingUsd,
|
|
2132
|
-
runningCount: args.runningCount
|
|
2133
|
-
});
|
|
2134
|
-
if (allocated2 === void 0) {
|
|
2135
|
-
if (policy.totalUsd !== void 0) {
|
|
2136
|
-
throw new Error(
|
|
2137
|
-
`BudgetPolicy.allocate('${args.analyst.id}') cannot return undefined when totalUsd is set`
|
|
2138
|
-
);
|
|
2139
|
-
}
|
|
2140
|
-
return void 0;
|
|
2141
|
-
}
|
|
2142
|
-
assertBudgetAmount(allocated2, `BudgetPolicy.allocate('${args.analyst.id}')`);
|
|
2143
|
-
return args.remainingUsd === void 0 ? allocated2 : Math.min(allocated2, args.remainingUsd);
|
|
2144
|
-
}
|
|
2145
|
-
if (policy.totalUsd == null) return void 0;
|
|
2146
|
-
const allocated = policy.weights ? policy.totalUsd * analystWeight(policy.weights, args.analyst.id) / args.totalWeight : policy.totalUsd / Math.max(1, args.runningCount);
|
|
2147
|
-
return args.remainingUsd === void 0 ? allocated : Math.min(allocated, args.remainingUsd);
|
|
2148
|
-
}
|
|
2149
|
-
function validateBudgetPolicy(policy) {
|
|
2150
|
-
if (!policy) return;
|
|
2151
|
-
if (policy.totalUsd !== void 0) assertBudgetAmount(policy.totalUsd, "BudgetPolicy.totalUsd");
|
|
2152
|
-
for (const [analystId, weight] of Object.entries(policy.weights ?? {})) {
|
|
2153
|
-
assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`);
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
function assertBudgetAmount(value, field) {
|
|
2157
|
-
if (!Number.isFinite(value) || value < 0) {
|
|
2158
|
-
throw new Error(`${field} must be a non-negative finite number`);
|
|
2159
|
-
}
|
|
2160
|
-
}
|
|
2161
|
-
function validateEffectiveBudget(budgetUsd, remainingUsd, analystId) {
|
|
2162
|
-
if (budgetUsd !== void 0) {
|
|
2163
|
-
assertBudgetAmount(budgetUsd, `AnalystContext.budgetUsd for '${analystId}'`);
|
|
2164
|
-
}
|
|
2165
|
-
if (remainingUsd === void 0) return budgetUsd;
|
|
2166
|
-
if (budgetUsd === void 0) {
|
|
2167
|
-
throw new Error(
|
|
2168
|
-
`AnalystContext.budgetUsd for '${analystId}' cannot be removed while an overall budget remains`
|
|
2169
|
-
);
|
|
2170
|
-
}
|
|
2171
|
-
if (budgetUsd > remainingUsd) {
|
|
2172
|
-
throw new Error(
|
|
2173
|
-
`AnalystContext.budgetUsd for '${analystId}' (${budgetUsd}) exceeds the remaining overall budget (${remainingUsd})`
|
|
2174
|
-
);
|
|
2175
|
-
}
|
|
2176
|
-
return budgetUsd;
|
|
2177
|
-
}
|
|
2178
|
-
function analystWeight(weights, analystId) {
|
|
2179
|
-
const weight = weights[analystId] ?? 1;
|
|
2180
|
-
assertBudgetAmount(weight, `BudgetPolicy.weights['${analystId}']`);
|
|
2181
|
-
return weight;
|
|
2182
|
-
}
|
|
2183
|
-
function zeroUsage() {
|
|
2184
|
-
return {
|
|
2185
|
-
calls: 0,
|
|
2186
|
-
tokens: { input: 0, output: 0 },
|
|
2187
|
-
cost: { kind: "observed", usd: 0 }
|
|
2188
|
-
};
|
|
2189
|
-
}
|
|
2190
|
-
function resolveUsage(analyst, receipts) {
|
|
2191
|
-
if (receipts.length > 0) return mergeUsageReceipts(receipts);
|
|
2192
|
-
if (analyst.cost.kind === "deterministic") return zeroUsage();
|
|
2193
|
-
return { calls: null, tokens: null, cost: { kind: "uncaptured", usd: null } };
|
|
2194
|
-
}
|
|
2195
|
-
function mergeUsageReceipts(receipts) {
|
|
2196
|
-
const calls = receipts.every((receipt) => receipt.calls !== null) ? receipts.reduce((sum, receipt) => sum + (receipt.calls ?? 0), 0) : null;
|
|
2197
|
-
const tokens = receipts.every((receipt) => receipt.tokens !== null) ? receipts.reduce(
|
|
2198
|
-
(sum, receipt) => ({
|
|
2199
|
-
input: sum.input + (receipt.tokens?.input ?? 0),
|
|
2200
|
-
output: sum.output + (receipt.tokens?.output ?? 0),
|
|
2201
|
-
...sum.reasoning !== void 0 || receipt.tokens?.reasoning !== void 0 ? { reasoning: (sum.reasoning ?? 0) + (receipt.tokens?.reasoning ?? 0) } : {},
|
|
2202
|
-
...sum.cached !== void 0 || receipt.tokens?.cached !== void 0 ? { cached: (sum.cached ?? 0) + (receipt.tokens?.cached ?? 0) } : {},
|
|
2203
|
-
...sum.cacheWrite !== void 0 || receipt.tokens?.cacheWrite !== void 0 ? { cacheWrite: (sum.cacheWrite ?? 0) + (receipt.tokens?.cacheWrite ?? 0) } : {}
|
|
2204
|
-
}),
|
|
2205
|
-
{ input: 0, output: 0 }
|
|
2206
|
-
) : null;
|
|
2207
|
-
const cost = aggregateCostProvenance(receipts.map((receipt) => receipt.cost));
|
|
2208
|
-
return {
|
|
2209
|
-
calls,
|
|
2210
|
-
tokens,
|
|
2211
|
-
cost,
|
|
2212
|
-
...cost.kind === "uncaptured" ? {
|
|
2213
|
-
knownCostUsd: receipts.reduce((sum, receipt) => sum + knownCostUsd(receipt), 0)
|
|
2214
|
-
} : {}
|
|
2215
|
-
};
|
|
2216
|
-
}
|
|
2217
|
-
function knownCostUsd(receipt) {
|
|
2218
|
-
return receipt.cost.kind === "uncaptured" ? receipt.knownCostUsd ?? 0 : receipt.cost.usd;
|
|
2219
|
-
}
|
|
2220
|
-
function budgetDebit(receipt, allocatedUsd) {
|
|
2221
|
-
const known = knownCostUsd(receipt);
|
|
2222
|
-
return receipt.cost.kind === "uncaptured" && allocatedUsd !== void 0 ? Math.max(known, allocatedUsd) : known;
|
|
2223
|
-
}
|
|
2224
|
-
function aggregateCostProvenance(costs) {
|
|
2225
|
-
if (costs.some((cost) => cost.kind === "uncaptured")) {
|
|
2226
|
-
return { kind: "uncaptured", usd: null };
|
|
2227
|
-
}
|
|
2228
|
-
const usd = costs.reduce((sum, cost) => sum + (cost.usd ?? 0), 0);
|
|
2229
|
-
return costs.some((cost) => cost.kind === "estimated") ? { kind: "estimated", usd } : { kind: "observed", usd };
|
|
2230
|
-
}
|
|
2231
|
-
function assertValidUsageReceipt(receipt) {
|
|
2232
|
-
if (receipt.calls !== null && (!Number.isInteger(receipt.calls) || receipt.calls < 0)) {
|
|
2233
|
-
throw new Error("AnalystContext.recordUsage: calls must be a non-negative integer or null");
|
|
2234
|
-
}
|
|
2235
|
-
if (receipt.tokens) {
|
|
2236
|
-
assertNonNegativeFinite(receipt.tokens.input, "tokens.input");
|
|
2237
|
-
assertNonNegativeFinite(receipt.tokens.output, "tokens.output");
|
|
2238
|
-
if (receipt.tokens.reasoning !== void 0) {
|
|
2239
|
-
assertNonNegativeFinite(receipt.tokens.reasoning, "tokens.reasoning");
|
|
2240
|
-
if (receipt.tokens.reasoning > receipt.tokens.output) {
|
|
2241
|
-
throw new Error(
|
|
2242
|
-
"AnalystContext.recordUsage: tokens.reasoning must not exceed tokens.output"
|
|
2243
|
-
);
|
|
2244
|
-
}
|
|
2245
|
-
}
|
|
2246
|
-
if (receipt.tokens.cached !== void 0) {
|
|
2247
|
-
assertNonNegativeFinite(receipt.tokens.cached, "tokens.cached");
|
|
2248
|
-
}
|
|
2249
|
-
if (receipt.tokens.cacheWrite !== void 0) {
|
|
2250
|
-
assertNonNegativeFinite(receipt.tokens.cacheWrite, "tokens.cacheWrite");
|
|
2251
|
-
}
|
|
2252
|
-
}
|
|
2253
|
-
if (receipt.cost.kind !== "uncaptured") {
|
|
2254
|
-
assertNonNegativeFinite(receipt.cost.usd, "cost.usd");
|
|
2255
|
-
} else if (receipt.cost.usd !== null) {
|
|
2256
|
-
throw new Error("AnalystContext.recordUsage: uncaptured cost.usd must be null");
|
|
2257
|
-
}
|
|
2258
|
-
if (receipt.knownCostUsd !== void 0) {
|
|
2259
|
-
assertNonNegativeFinite(receipt.knownCostUsd, "knownCostUsd");
|
|
2260
|
-
}
|
|
2261
|
-
}
|
|
2262
|
-
function assertNonNegativeFinite(value, field) {
|
|
2263
|
-
if (!Number.isFinite(value) || value < 0) {
|
|
2264
|
-
throw new Error(`AnalystContext.recordUsage: ${field} must be a non-negative finite number`);
|
|
2265
|
-
}
|
|
2266
|
-
}
|
|
2267
|
-
function selectPriorFindings(source, analystId) {
|
|
2268
|
-
if (!source) return void 0;
|
|
2269
|
-
if (Array.isArray(source)) {
|
|
2270
|
-
const own2 = source.filter((f) => f.analyst_id === analystId);
|
|
2271
|
-
return own2.length > 0 ? own2 : void 0;
|
|
2272
|
-
}
|
|
2273
|
-
const record = source;
|
|
2274
|
-
const own = record[analystId] ?? [];
|
|
2275
|
-
const wildcard = record["*"] ?? [];
|
|
2276
|
-
const merged = [...own, ...wildcard];
|
|
2277
|
-
return merged.length > 0 ? merged : void 0;
|
|
2278
|
-
}
|
|
2279
|
-
|
|
2280
|
-
// src/analyst/default-registry.ts
|
|
2281
|
-
function buildDefaultAnalystRegistry(opts = {}) {
|
|
2282
|
-
const registry = new AnalystRegistry(opts.registry);
|
|
2283
|
-
if (opts.includeBehavioral !== false) {
|
|
2284
|
-
registry.register(behavioralAnalyst());
|
|
2285
|
-
}
|
|
2286
|
-
if (opts.ai) {
|
|
2287
|
-
const kinds = opts.kinds ?? DEFAULT_TRACE_ANALYST_KINDS;
|
|
2288
|
-
for (const spec of kinds) {
|
|
2289
|
-
registry.register(createTraceAnalystKind(spec, { ai: opts.ai, model: opts.model }));
|
|
2290
|
-
}
|
|
2291
|
-
}
|
|
2292
|
-
return registry;
|
|
2293
|
-
}
|
|
2294
|
-
|
|
2295
|
-
export {
|
|
2296
|
-
createAnalystAi,
|
|
2297
|
-
createChatClient,
|
|
2298
|
-
computeTraceMetrics,
|
|
2299
|
-
computeFindingId,
|
|
2300
|
-
makeFinding,
|
|
2301
|
-
deriveEfficiencyFindings,
|
|
2302
|
-
behavioralAnalyst,
|
|
2303
|
-
FINDING_SUBJECT_KINDS,
|
|
2304
|
-
parseFindingSubject,
|
|
2305
|
-
renderFindingSubject,
|
|
2306
|
-
FINDING_SUBJECT_SYNTAX,
|
|
2307
|
-
FINDING_SUBJECT_GRAMMAR_PROMPT,
|
|
2308
|
-
KIND_EXPECTED_SUBJECTS,
|
|
2309
|
-
findingSubjectGrammarPromptFor,
|
|
2310
|
-
FindingSubjectStringSchema,
|
|
2311
|
-
stripCodeFences,
|
|
2312
|
-
coerceJson,
|
|
2313
|
-
coerceToFindingRows,
|
|
2314
|
-
ANALYST_SEVERITIES,
|
|
2315
|
-
RawAnalystEvidenceSchema,
|
|
2316
|
-
RawAnalystFindingSchema,
|
|
2317
|
-
RAW_FINDING_SCHEMA_PROMPT,
|
|
2318
|
-
evidenceRefsFromRawFinding,
|
|
2319
|
-
parseRawFinding,
|
|
2320
|
-
structureFindings,
|
|
2321
|
-
settleUsageReceiptFromCostLedger,
|
|
2322
|
-
validateUsageSettlementTimeout,
|
|
2323
|
-
createTraceAnalystKind,
|
|
2324
|
-
renderPriorFindings,
|
|
2325
|
-
renderUpstreamFindings,
|
|
2326
|
-
buildTraceToolsForGroup,
|
|
2327
|
-
FAILURE_MODE_KIND_SPEC,
|
|
2328
|
-
IMPROVEMENT_KIND_SPEC,
|
|
2329
|
-
KNOWLEDGE_GAP_KIND_SPEC,
|
|
2330
|
-
KNOWLEDGE_POISONING_KIND_SPEC,
|
|
2331
|
-
DEFAULT_TRACE_ANALYST_KINDS,
|
|
2332
|
-
AnalystRegistry,
|
|
2333
|
-
buildDefaultAnalystRegistry
|
|
2334
|
-
};
|
|
2335
|
-
//# sourceMappingURL=chunk-BSO5JDQH.js.map
|