@tangle-network/agent-eval 0.208.2 → 0.210.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 +26 -0
- package/README.md +1 -1
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-CEhxR_I3.d.ts → agent-profile-BGyt2z8U.d.ts} +3 -3
- package/dist/{agent-profile-CEhxR_I3.d.ts.map → agent-profile-BGyt2z8U.d.ts.map} +1 -1
- package/dist/{agent-profile-cell-BHcB-mZX.d.ts → agent-profile-cell-BNp-Js9F.d.ts} +2 -3
- package/dist/agent-profile-cell-BNp-Js9F.d.ts.map +1 -0
- package/dist/{agent-profile-cell-DcFW4vOc.js → agent-profile-cell-BYc0bxsL.js} +2 -2
- package/dist/agent-profile-cell-BYc0bxsL.js.map +1 -0
- package/dist/analyst/index.d.ts +12 -12
- package/dist/analyst/index.js +5 -5
- package/dist/{analyze-runs-GZ0VSwui.js → analyze-runs-3xpby3p2.js} +6 -6
- package/dist/analyze-runs-3xpby3p2.js.map +1 -0
- package/dist/{analyze-runs-CTJyUplR.d.ts → analyze-runs-BlslTkOJ.d.ts} +4 -4
- package/dist/{analyze-runs-CTJyUplR.d.ts.map → analyze-runs-BlslTkOJ.d.ts.map} +1 -1
- package/dist/{benchmark-command-BC265T1r.js → benchmark-command-S8tCtkxh.js} +6 -6
- package/dist/{benchmark-command-BC265T1r.js.map → benchmark-command-S8tCtkxh.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +5 -7
- package/dist/benchmarks/index.d.ts.map +1 -1
- package/dist/benchmarks/index.js +3 -3
- package/dist/builder-eval/index.js +1 -1
- package/dist/campaign/index.d.ts +6 -6
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-evidence-DW3Krxov.js → campaign-evidence-OcUciD-N.js} +4 -4
- package/dist/campaign-evidence-OcUciD-N.js.map +1 -0
- package/dist/{campaign-C5pjR-Qn.js → campaign-wvvJA1ps.js} +14 -14
- package/dist/{campaign-C5pjR-Qn.js.map → campaign-wvvJA1ps.js.map} +1 -1
- package/dist/claude-jsonl-dZir12m6.js +86 -0
- package/dist/claude-jsonl-dZir12m6.js.map +1 -0
- package/dist/cli.js +7 -7
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +92 -16
- package/dist/contract/index.js.map +1 -1
- package/dist/counterfactual-DtMWvn7D.js.map +1 -1
- package/dist/{default-registry-DZFWY2_E.d.ts → default-registry-Crk3QEy1.d.ts} +6 -6
- package/dist/{default-registry-DZFWY2_E.d.ts.map → default-registry-Crk3QEy1.d.ts.map} +1 -1
- package/dist/{default-registry-DX5R7_n9.js → default-registry-DF4Yp7HQ.js} +2 -2
- package/dist/{default-registry-DX5R7_n9.js.map → default-registry-DF4Yp7HQ.js.map} +1 -1
- package/dist/{define-agent-eval-C8zBSbsc.d.ts → define-agent-eval-B_zZY2AZ.d.ts} +7 -7
- package/dist/{define-agent-eval-C8zBSbsc.d.ts.map → define-agent-eval-B_zZY2AZ.d.ts.map} +1 -1
- package/dist/{define-agent-eval-BjKXcDQp.js → define-agent-eval-CoXXDCMu.js} +7 -7
- package/dist/{define-agent-eval-BjKXcDQp.js.map → define-agent-eval-CoXXDCMu.js.map} +1 -1
- package/dist/diagnosis/index.d.ts +2 -5
- package/dist/diagnosis/index.d.ts.map +1 -1
- package/dist/diagnosis/index.js +2 -26
- package/dist/diagnosis/index.js.map +1 -1
- package/dist/{dspy-rlm-engine-sHwdSxK3.js → dspy-rlm-engine-BpaKVKJA.js} +2 -2
- package/dist/{dspy-rlm-engine-sHwdSxK3.js.map → dspy-rlm-engine-BpaKVKJA.js.map} +1 -1
- package/dist/{engine-DProXJ7A.d.ts → engine-D-YZ32ZJ.d.ts} +5 -12
- package/dist/engine-D-YZ32ZJ.d.ts.map +1 -0
- package/dist/{eval-campaign-DU_p8qVt.js → eval-campaign-4byTtqrf.js} +4 -4
- package/dist/{eval-campaign-DU_p8qVt.js.map → eval-campaign-4byTtqrf.js.map} +1 -1
- package/dist/evaluation.d.ts +2 -2
- package/dist/{exact-types-Cq6xXNVR.d.ts → exact-types-DjhfZglz.d.ts} +2 -2
- package/dist/{exact-types-Cq6xXNVR.d.ts.map → exact-types-DjhfZglz.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +2 -2
- package/dist/experiment/index.js +8 -8
- package/dist/{feedback-trajectory-C6Z8PRoF.d.ts → feedback-trajectory-CX01700m.d.ts} +3 -3
- package/dist/{feedback-trajectory-C6Z8PRoF.d.ts.map → feedback-trajectory-CX01700m.d.ts.map} +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/{index-CbBfavbT.d.ts → index-D0_l25We.d.ts} +21 -42
- package/dist/{index-CbBfavbT.d.ts.map → index-D0_l25We.d.ts.map} +1 -1
- package/dist/{index-nwNoS582.d.ts → index-DnZdBxCL.d.ts} +14 -11
- package/dist/{index-nwNoS582.d.ts.map → index-DnZdBxCL.d.ts.map} +1 -1
- package/dist/{index-DkucR0KJ.d.ts → index-UxNTvn-w.d.ts} +6 -6
- package/dist/{index-DkucR0KJ.d.ts.map → index-UxNTvn-w.d.ts.map} +1 -1
- package/dist/{index-Bzto04CY.d.ts → index-xnhRdqik.d.ts} +9 -20
- package/dist/{index-Bzto04CY.d.ts.map → index-xnhRdqik.d.ts.map} +1 -1
- package/dist/index.d.ts +28 -37
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +28 -90
- package/dist/index.js.map +1 -1
- package/dist/judge-gate-C59znGmR.js +638 -0
- package/dist/judge-gate-C59znGmR.js.map +1 -0
- package/dist/judge-gate-D2hCppem.d.ts +439 -0
- package/dist/judge-gate-D2hCppem.d.ts.map +1 -0
- package/dist/{kind-factory-Cn1lbsAd.js → kind-factory-ivTx6koH.js} +2 -11
- package/dist/{kind-factory-Cn1lbsAd.js.map → kind-factory-ivTx6koH.js.map} +1 -1
- package/dist/{llm-judge-HLWASwUJ.js → llm-judge-Tr7MBUnf.js} +9 -9
- package/dist/llm-judge-Tr7MBUnf.js.map +1 -0
- package/dist/{matrix-Cqkk7eYI.d.ts → matrix-jHTsHEkR.d.ts} +2 -2
- package/dist/{matrix-Cqkk7eYI.d.ts.map → matrix-jHTsHEkR.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +3 -133
- package/dist/meta-eval/index.d.ts.map +1 -1
- package/dist/meta-eval/index.js +3 -276
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/{mint-C1W8w5wo.d.ts → mint-CDy-brUR.d.ts} +2 -2
- package/dist/{mint-C1W8w5wo.d.ts.map → mint-CDy-brUR.d.ts.map} +1 -1
- package/dist/{mint-CWG-s2mI.js → mint-Csor1BLJ.js} +2 -2
- package/dist/{mint-CWG-s2mI.js.map → mint-Csor1BLJ.js.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{paired-arms-CgWT7sHy.js → paired-arms-DzKn0TfY.js} +3 -5
- package/dist/{paired-arms-CgWT7sHy.js.map → paired-arms-DzKn0TfY.js.map} +1 -1
- package/dist/{paired-binary-b2L3WKqr.js → paired-binary-Q36bhn2R.js} +13 -9
- package/dist/paired-binary-Q36bhn2R.js.map +1 -0
- package/dist/{paired-promotion-decision-2deJ7sDX.js → paired-promotion-decision-BN6IQTiu.js} +2 -2
- package/dist/{paired-promotion-decision-2deJ7sDX.js.map → paired-promotion-decision-BN6IQTiu.js.map} +1 -1
- package/dist/pipelines/index.d.ts +1 -1
- package/dist/pipelines/index.js +2 -2
- package/dist/{prime-protocol-Csr9kcOM.d.ts → prime-protocol-B7et3tI7.d.ts} +2 -2
- package/dist/{prime-protocol-Csr9kcOM.d.ts.map → prime-protocol-B7et3tI7.d.ts.map} +1 -1
- package/dist/{produced-state-Bzlh09oj.js → produced-state-CKybuR9F.js} +3 -3
- package/dist/produced-state-CKybuR9F.js.map +1 -0
- package/dist/profile-cell.d.ts +2 -2
- package/dist/profile-cell.js +2 -2
- package/dist/{promotion-policy-CCmyEH_c.js → promotion-policy-CWW35UWq.js} +3 -3
- package/dist/{promotion-policy-CCmyEH_c.js.map → promotion-policy-CWW35UWq.js.map} +1 -1
- package/dist/{query-DlV0pdx4.js → query-B1D1qp2Z.js} +2 -2
- package/dist/{query-DlV0pdx4.js.map → query-B1D1qp2Z.js.map} +1 -1
- package/dist/{query-DBUQhehH.d.ts → query-DK1nWcmp.d.ts} +2 -3
- package/dist/{query-DBUQhehH.d.ts.map → query-DK1nWcmp.d.ts.map} +1 -1
- package/dist/{registry-DMkmhBQ5.d.ts → registry-BL7H33tj.d.ts} +3 -3
- package/dist/{registry-DMkmhBQ5.d.ts.map → registry-BL7H33tj.d.ts.map} +1 -1
- package/dist/{release-confidence-CkoXFx9I.d.ts → release-confidence-C4kI7lQi.d.ts} +4 -12
- package/dist/release-confidence-C4kI7lQi.d.ts.map +1 -0
- package/dist/{release-confidence-CiFg1EPq.js → release-confidence-Dbe9AS_X.js} +2 -2
- package/dist/{release-confidence-CiFg1EPq.js.map → release-confidence-Dbe9AS_X.js.map} +1 -1
- package/dist/{report-command-pXtxg5YK.js → report-command-CtIIsQKP.js} +3 -28
- package/dist/{report-command-pXtxg5YK.js.map → report-command-CtIIsQKP.js.map} +1 -1
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +3 -3
- package/dist/{researcher-CZFZjj-u.d.ts → researcher-DuIJ9IaA.d.ts} +4 -4
- package/dist/{researcher-CZFZjj-u.d.ts.map → researcher-DuIJ9IaA.d.ts.map} +1 -1
- package/dist/{reward-hacking-Cyk-QHk9.d.ts → reward-hacking-C6Kp54Av.d.ts} +2 -2
- package/dist/{reward-hacking-Cyk-QHk9.d.ts.map → reward-hacking-C6Kp54Av.d.ts.map} +1 -1
- package/dist/reward-nw2xZGZG.js.map +1 -1
- package/dist/rl.d.ts +10 -29
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +7 -7
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +3 -3
- package/dist/rollout/index.js +4 -4
- package/dist/{rollout-l9w3Gdvh.js → rollout-D9bKKBnZ.js} +30 -165
- package/dist/rollout-D9bKKBnZ.js.map +1 -0
- package/dist/{rubric-predictive-validity-DIUwJJ9Y.d.ts → rubric-predictive-validity-BiNNEjpG.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-DIUwJJ9Y.d.ts.map → rubric-predictive-validity-BiNNEjpG.d.ts.map} +1 -1
- package/dist/{run-record-BRlM99rX.js → run-record-DlTZ_lqe.js} +3 -13
- package/dist/run-record-DlTZ_lqe.js.map +1 -0
- package/dist/{run-record-BB290Y9A.js → run-record-ES07wfz9.js} +2 -2
- package/dist/{run-record-BB290Y9A.js.map → run-record-ES07wfz9.js.map} +1 -1
- package/dist/{run-record-DF-fuu31.d.ts → run-record-p2AYTrCn.d.ts} +3 -7
- package/dist/run-record-p2AYTrCn.d.ts.map +1 -0
- package/dist/search/index.d.ts +2 -24
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +3 -3
- package/dist/{search-kernel-CIie6xig.js → search-kernel-BIXWM7YV.js} +4 -4
- package/dist/search-kernel-BIXWM7YV.js.map +1 -0
- package/dist/{search-kernel-uKdPVRAe.d.ts → search-kernel-ah2GESe3.d.ts} +3 -3
- package/dist/{search-kernel-uKdPVRAe.d.ts.map → search-kernel-ah2GESe3.d.ts.map} +1 -1
- package/dist/{search-ledger-CXQPwdWz.js → search-ledger-aMTNQn_m.js} +2 -2
- package/dist/{search-ledger-CXQPwdWz.js.map → search-ledger-aMTNQn_m.js.map} +1 -1
- package/dist/{search-shipper-DhhofkDX.js → search-shipper-DKXWuLnp.js} +2 -2
- package/dist/{search-shipper-DhhofkDX.js.map → search-shipper-DKXWuLnp.js.map} +1 -1
- package/dist/{search-summary-BV5uehLd.js → search-summary-nwrtXxC_.js} +3 -3
- package/dist/{search-summary-BV5uehLd.js.map → search-summary-nwrtXxC_.js.map} +1 -1
- package/dist/{semantic-concept-judge-D1wH-YKc.js → semantic-concept-judge-BQxZyXdN.js} +3 -3
- package/dist/{semantic-concept-judge-D1wH-YKc.js.map → semantic-concept-judge-BQxZyXdN.js.map} +1 -1
- package/dist/{sequential-DMqr3sni.js → sequential-D-1PPCmM.js} +3 -3
- package/dist/{sequential-DMqr3sni.js.map → sequential-D-1PPCmM.js.map} +1 -1
- package/dist/{skillopt-optimization-method-Dcnh5Pvr.js → skillopt-optimization-method-DujPOiwD.js} +5 -5
- package/dist/{skillopt-optimization-method-Dcnh5Pvr.js.map → skillopt-optimization-method-DujPOiwD.js.map} +1 -1
- package/dist/{statistical-heldout-BP6iEJvR.js → statistical-heldout-1Gbmex7v.js} +2 -2
- package/dist/{statistical-heldout-BP6iEJvR.js.map → statistical-heldout-1Gbmex7v.js.map} +1 -1
- package/dist/{statistical-heldout-DFKtp-Qm.d.ts → statistical-heldout-8RGPIeyo.d.ts} +17 -14
- package/dist/statistical-heldout-8RGPIeyo.d.ts.map +1 -0
- package/dist/{store-otlp-BA7G1Du-.js → store-otlp-__ebQ6Hn.js} +2 -2
- package/dist/{store-otlp-BA7G1Du-.js.map → store-otlp-__ebQ6Hn.js.map} +1 -1
- package/dist/{store-tool-spans-DKoVbE-w.js → store-tool-spans-TbRBuIM7.js} +3 -3
- package/dist/{store-tool-spans-DKoVbE-w.js.map → store-tool-spans-TbRBuIM7.js.map} +1 -1
- package/dist/{store-tool-spans-9YJNMP-z.d.ts → store-tool-spans-wQ9idsnn.d.ts} +5 -5
- package/dist/{store-tool-spans-9YJNMP-z.d.ts.map → store-tool-spans-wQ9idsnn.d.ts.map} +1 -1
- package/dist/{summary-report-DvvesgR_.d.ts → summary-report-CK0ueoJd.d.ts} +2 -2
- package/dist/{summary-report-DvvesgR_.d.ts.map → summary-report-CK0ueoJd.d.ts.map} +1 -1
- package/dist/{summary-report-fXurE2TR.js → summary-report-DtdRucM0.js} +3 -3
- package/dist/{summary-report-fXurE2TR.js.map → summary-report-DtdRucM0.js.map} +1 -1
- package/dist/supervisor-run/index.d.ts +0 -8
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +36 -71
- package/dist/supervisor-run/index.js.map +1 -1
- package/dist/{systemone-review-Bt4JcxMc.d.ts → systemone-review-BReh3mvm.d.ts} +2 -2
- package/dist/{systemone-review-Bt4JcxMc.d.ts.map → systemone-review-BReh3mvm.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/{tool-groups-j19pmOfP.d.ts → tool-groups-v28A-ZAF.d.ts} +3 -3
- package/dist/tool-groups-v28A-ZAF.d.ts.map +1 -0
- package/dist/{tool-waste-x_E8h9Ih.js → tool-waste-BYt5rdt8.js} +2 -2
- package/dist/{tool-waste-x_E8h9Ih.js.map → tool-waste-BYt5rdt8.js.map} +1 -1
- package/dist/{tool-waste-DxlebQkx.d.ts → tool-waste-Wi4g6Ekb.d.ts} +2 -2
- package/dist/{tool-waste-DxlebQkx.d.ts.map → tool-waste-Wi4g6Ekb.d.ts.map} +1 -1
- package/dist/{trace-questions-dRvmsbTk.d.ts → trace-questions-C26UvI3D.d.ts} +3 -3
- package/dist/{trace-questions-dRvmsbTk.d.ts.map → trace-questions-C26UvI3D.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +2 -9
- package/dist/trace-repair/index.d.ts.map +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/traces.d.ts +6 -8
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +6 -6
- package/dist/trajectory-replay/index.d.ts +0 -2
- package/dist/trajectory-replay/index.d.ts.map +1 -1
- package/dist/trajectory-replay/index.js +1 -1
- package/dist/{tree-CJOXbVcv.js → tree-kc1d80yF.js} +5 -25
- package/dist/tree-kc1d80yF.js.map +1 -0
- package/dist/{types-CFCUZk0B.d.ts → types-Dv9sYwBB.d.ts} +4 -4
- package/dist/{types-CFCUZk0B.d.ts.map → types-Dv9sYwBB.d.ts.map} +1 -1
- package/dist/{types-DAPpAkd4.d.ts → types-KEkKkETv.d.ts} +2 -2
- package/dist/{types-DAPpAkd4.d.ts.map → types-KEkKkETv.d.ts.map} +1 -1
- package/dist/{types-BlSBUNRd.d.ts → types-tWFY6bON.d.ts} +3 -3
- package/dist/{types-BlSBUNRd.d.ts.map → types-tWFY6bON.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +1 -1
- package/docs/concepts.md +13 -0
- package/docs/experiment.md +10 -0
- package/docs/public-api.md +399 -424
- package/docs/trace-analysis.md +3 -0
- package/package.json +6 -5
- package/dist/agent-profile-cell-BHcB-mZX.d.ts.map +0 -1
- package/dist/agent-profile-cell-DcFW4vOc.js.map +0 -1
- package/dist/analyze-runs-GZ0VSwui.js.map +0 -1
- package/dist/campaign-evidence-DW3Krxov.js.map +0 -1
- package/dist/claude-jsonl-CG3JUbTJ.js +0 -211
- package/dist/claude-jsonl-CG3JUbTJ.js.map +0 -1
- package/dist/engine-DProXJ7A.d.ts.map +0 -1
- package/dist/llm-judge-HLWASwUJ.js.map +0 -1
- package/dist/paired-binary-b2L3WKqr.js.map +0 -1
- package/dist/produced-state-Bzlh09oj.js.map +0 -1
- package/dist/release-confidence-CkoXFx9I.d.ts.map +0 -1
- package/dist/rollout-l9w3Gdvh.js.map +0 -1
- package/dist/run-record-BRlM99rX.js.map +0 -1
- package/dist/run-record-DF-fuu31.d.ts.map +0 -1
- package/dist/search-kernel-CIie6xig.js.map +0 -1
- package/dist/series-convergence-CjO2QdRW.js +0 -43
- package/dist/series-convergence-CjO2QdRW.js.map +0 -1
- package/dist/series-convergence-hEfKdoi-.d.ts +0 -126
- package/dist/series-convergence-hEfKdoi-.d.ts.map +0 -1
- package/dist/statistical-heldout-DFKtp-Qm.d.ts.map +0 -1
- package/dist/tool-groups-j19pmOfP.d.ts.map +0 -1
- package/dist/tree-CJOXbVcv.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { o as SearchLedgerIntegrityError } from "./search-ledger-file-DY0AXX3W.js";
|
|
2
|
-
import { r as parseSearchLedgerLine } from "./search-ledger-
|
|
2
|
+
import { r as parseSearchLedgerLine } from "./search-ledger-aMTNQn_m.js";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
@@ -775,4 +775,4 @@ async function shipBestEffort(ship, ledgerPath) {
|
|
|
775
775
|
//#endregion
|
|
776
776
|
export { TraceSpanEventSchema as C, IngestTracesRequestSchema as S, HOSTED_WIRE_VERSION as T, admitSearchLedgerBatch as _, HostedRequestError as a, searchLedgerHeadPath as b, hostedTenantFromEnv as c, SEARCH_LEDGER_BATCH_MAX_LINES as d, SEARCH_LEDGER_INGEST_PATH as f, SearchRunKindSchema as g, SearchLedgerHeadSchema as h, startSearchShipper as i, IngestSearchLedgerRequestSchema as l, SearchLedgerConflictSchema as m, shipBestEffort as n, createHostedClient as o, SearchBlobPutResponseSchema as p, shipSearchLedger as r, hostedClientFromEnv as s, SearchShipConflictError as t, SEARCH_LEDGER_BATCH_MAX_BYTES as u, searchBlobPath as v, UnixNanoTimestampSchema as w, IngestResponseSchema as x, searchLedgerArtifactRefs as y };
|
|
777
777
|
|
|
778
|
-
//# sourceMappingURL=search-shipper-
|
|
778
|
+
//# sourceMappingURL=search-shipper-DKXWuLnp.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search-shipper-DhhofkDX.js","names":[],"sources":["../src/hosted/types.ts","../src/hosted/schemas.ts","../src/hosted/search-ledger-wire.ts","../src/hosted/client.ts","../src/hosted/search-shipper.ts"],"sourcesContent":["/**\n * # Hosted-tier wire format: the shapes every orchestrator (ours, a partner's\n * self-hosted one, a future open implementation) must accept.\n *\n * This package implements exactly one wire version. Servers reject every\n * other version instead of translating old payloads.\n *\n * The wire carries two streams in one transport:\n *\n * 1. **Search ledgers** (`/v1/search-blobs/*`, `/v1/ingest/search-ledger`).\n * A producer ships a search's hash-chained ledger lines and the blobs\n * they name; `./search-ledger-wire.ts` owns those shapes.\n *\n * 2. **Trace spans** (`POST /v1/ingest/traces`). Standard OTLP-shaped\n * spans with a few additional attributes so the orchestrator can\n * pivot from a search cell to its underlying execution. Compatible\n * with any OTel collector.\n *\n * Every endpoint is authenticated with a bearer token and a tenant id\n * header. Tenants isolate everything downstream of ingest; no tenant\n * ever sees another tenant's data.\n */\n\nexport const HOSTED_WIRE_VERSION = '2026-07-24.v1' as const\nexport type HostedWireVersion = typeof HOSTED_WIRE_VERSION\n\n// ── Transport headers ───────────────────────────────────────────────\n\n/** Every ingest request carries these. */\nexport interface HostedIngestHeaders {\n /** Bearer token. The orchestrator validates against the tenant key. */\n authorization: `Bearer ${string}`\n /** Stable tenant id (the orchestrator-side primary key for the tenant). */\n 'x-tangle-tenant-id': string\n /** Wire-version pin so the server can reject incompatible payloads. */\n 'x-tangle-wire-version': HostedWireVersion\n /** Stable request key generated once and reused across retries. */\n 'idempotency-key': string\n}\n\n// ── Trace span event ────────────────────────────────────────────────\n\n/**\n * Canonical unsigned 64-bit integer encoded as a base-10 string.\n * JSON numbers cannot represent OTLP nanosecond timestamps exactly.\n */\nexport type UnixNanoTimestamp = string\n\n/**\n * OTel-shape span with a few additional attributes for pivoting.\n * Compatible with any OTLP collector — `name`, `traceId`, `spanId`,\n * `startTimeUnixNano`, `endTimeUnixNano`, `attributes` are stock OTel.\n */\nexport interface TraceSpanEvent {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n startTimeUnixNano: UnixNanoTimestamp\n endTimeUnixNano: UnixNanoTimestamp\n attributes: Record<string, string | number | boolean>\n events?: Array<{\n timeUnixNano: UnixNanoTimestamp\n name: string\n attributes?: Record<string, string | number | boolean>\n }>\n status?: { code: 'OK' | 'ERROR' | 'UNSET'; message?: string }\n /** Pivot to the producing run. */\n 'tangle.runId'?: string\n /** Pivot to the specific generation. */\n 'tangle.generation'?: number\n /** Pivot to the specific cell. */\n 'tangle.cellId'?: string\n /** Pivot to the specific scenario. */\n 'tangle.scenarioId'?: string\n}\n\n// ── Ingest request bodies ───────────────────────────────────────────\n\nexport interface IngestTracesRequest {\n wireVersion: HostedWireVersion\n spans: TraceSpanEvent[]\n}\n\nexport interface IngestResponse {\n /** Accepted spans count. */\n accepted: number\n /** Rejected spans with reasons (validation failures, conflicting identity). */\n rejected: Array<{ index: number; reason: string }>\n}\n","import { z } from 'zod'\nimport type {\n IngestResponse,\n IngestTracesRequest,\n TraceSpanEvent,\n UnixNanoTimestamp,\n} from './types'\nimport { HOSTED_WIRE_VERSION } from './types'\n\nconst finiteNumber = z.number().finite()\nconst nonNegativeInteger = z.number().int().nonnegative()\nconst nonEmptyString = z\n .string()\n .min(1)\n .refine((value) => value.trim().length > 0, 'must not be blank')\nconst attributeValue = z.union([z.string(), finiteNumber, z.boolean()])\nconst attributes = z.record(z.string(), attributeValue)\nconst UINT64_MAX = 18_446_744_073_709_551_615n\n\nexport const UnixNanoTimestampSchema: z.ZodType<UnixNanoTimestamp> = z\n .string()\n .regex(/^(0|[1-9][0-9]*)$/, 'expected an unsigned base-10 integer string')\n .refine((value) => BigInt(value) <= UINT64_MAX, 'must fit in an unsigned 64-bit integer')\n\nconst TraceSpanEventEntrySchema = z\n .object({\n timeUnixNano: UnixNanoTimestampSchema,\n name: nonEmptyString,\n attributes: attributes.optional(),\n })\n .strict()\n\nexport const TraceSpanEventSchema: z.ZodType<TraceSpanEvent> = z\n .object({\n traceId: nonEmptyString,\n spanId: nonEmptyString,\n parentSpanId: nonEmptyString.optional(),\n name: nonEmptyString,\n startTimeUnixNano: UnixNanoTimestampSchema,\n endTimeUnixNano: UnixNanoTimestampSchema,\n attributes,\n events: z.array(TraceSpanEventEntrySchema).optional(),\n status: z\n .object({\n code: z.enum(['OK', 'ERROR', 'UNSET']),\n message: z.string().optional(),\n })\n .strict()\n .optional(),\n 'tangle.runId': nonEmptyString.optional(),\n 'tangle.generation': nonNegativeInteger.optional(),\n 'tangle.cellId': nonEmptyString.optional(),\n 'tangle.scenarioId': nonEmptyString.optional(),\n })\n .strict()\n .refine((span) => BigInt(span.endTimeUnixNano) >= BigInt(span.startTimeUnixNano), {\n path: ['endTimeUnixNano'],\n message: 'endTimeUnixNano must be greater than or equal to startTimeUnixNano',\n })\n\nexport const IngestTracesEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestTracesRequestSchema: z.ZodType<IngestTracesRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(TraceSpanEventSchema),\n })\n .strict()\n\nexport const IngestResponseSchema: z.ZodType<IngestResponse> = z\n .object({\n accepted: nonNegativeInteger,\n rejected: z.array(\n z\n .object({\n index: nonNegativeInteger,\n reason: nonEmptyString,\n })\n .strict(),\n ),\n })\n .strict()\n","/**\n * The search-ledger wire: how a producer ships a search ledger to a hosted\n * store, and the rule a store applies to each batch.\n *\n * A producer ships three things, in this order:\n *\n * 1. Blobs: `PUT /v1/search-blobs/<sha256 hex>` with the exact bytes an\n * entry's artifact ref names. The store re-hashes them; the call is\n * idempotent by content.\n * 2. Head: `GET /v1/ingest/search-ledger/<searchId>/head` tells a restarted\n * producer where the store's copy of the chain ends.\n * 3. Entries: `POST /v1/ingest/search-ledger` with canonical ledger lines,\n * starting at `fromSequence`. The store verifies every line, links it to\n * its stored head, and answers with its new head.\n *\n * The lines are the ledger's own bytes, so producer and store hash identical\n * input. A line below the store's head with an equal hash is a no-op; a\n * different hash is a fork (`409 chain_conflict`); a batch that starts past\n * the head is a gap (`409 sequence_gap`). Both 409s carry the store's head,\n * so a producer resends from there or stops on a fork.\n */\n\nimport { z } from 'zod'\nimport { parseSearchLedgerLine } from '../campaign/search-ledger'\nimport { SearchLedgerIntegrityError } from '../campaign/search-ledger-errors'\nimport type {\n SearchArtifactRef,\n SearchLedgerEntry,\n SearchLedgerEvent,\n SearchLedgerHash,\n} from '../campaign/search-ledger-types'\nimport { HOSTED_WIRE_VERSION } from './types'\n\n/** At most this many lines in one ingest request. */\nexport const SEARCH_LEDGER_BATCH_MAX_LINES = 1000\n/** At most this many UTF-8 bytes across one request's lines. A single line\n * larger than this cannot be shipped. */\nexport const SEARCH_LEDGER_BATCH_MAX_BYTES = 1_048_576\n\nexport const SEARCH_LEDGER_INGEST_PATH = '/v1/ingest/search-ledger'\n\nexport function searchLedgerHeadPath(searchId: string): string {\n return `${SEARCH_LEDGER_INGEST_PATH}/${encodeURIComponent(searchId)}/head`\n}\n\n/** Blobs are addressed by the hex digest alone. */\nexport function searchBlobPath(sha256: SearchLedgerHash): string {\n return `/v1/search-blobs/${sha256.slice('sha256:'.length)}`\n}\n\nconst HASH = z.custom<SearchLedgerHash>(\n (value) => typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value),\n 'expected sha256:<64 lowercase hex characters>',\n)\nconst SEARCH_ID = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value, 'must not contain surrounding whitespace')\nconst SEQUENCE = z.number().int().nonnegative().safe()\n\n/** What the run is for: an optimization, or an eval (a one-node search). */\nexport const SearchRunKindSchema = z.enum(['optimization', 'eval'])\nexport type SearchRunKind = z.infer<typeof SearchRunKindSchema>\n\n/** Where a store's copy of one search's chain ends. `headHash` is null exactly\n * when the store holds no entry. */\nexport const SearchLedgerHeadSchema = z\n .object({ searchId: SEARCH_ID, nextSequence: SEQUENCE, headHash: HASH.nullable() })\n .strict()\n .refine((head) => (head.nextSequence === 0) === (head.headHash === null), {\n message: 'headHash must be null exactly when nextSequence is 0',\n path: ['headHash'],\n })\nexport type SearchLedgerHead = z.infer<typeof SearchLedgerHeadSchema>\n\nexport const IngestSearchLedgerRequestSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n searchId: SEARCH_ID,\n runKind: SearchRunKindSchema,\n fromSequence: SEQUENCE,\n lines: z.array(z.string().min(1)).min(1).max(SEARCH_LEDGER_BATCH_MAX_LINES),\n })\n .strict()\n .superRefine((request, ctx) => {\n const bytes = searchLedgerLinesByteLength(request.lines)\n if (bytes > SEARCH_LEDGER_BATCH_MAX_BYTES) {\n ctx.addIssue({\n code: 'custom',\n path: ['lines'],\n message: `lines hold ${bytes} bytes; at most ${SEARCH_LEDGER_BATCH_MAX_BYTES} per request`,\n })\n }\n })\nexport type IngestSearchLedgerRequest = z.infer<typeof IngestSearchLedgerRequestSchema>\n\n/** The body of a `409`: a fork or a gap, with the store's head. */\nexport const SearchLedgerConflictSchema = z\n .object({\n error: z.enum(['chain_conflict', 'sequence_gap']),\n message: z.string().min(1),\n head: SearchLedgerHeadSchema,\n })\n .strict()\nexport type SearchLedgerConflict = z.infer<typeof SearchLedgerConflictSchema>\n\n/** What a store kept of one blob. `masked` and `withheld` come from the\n * store's own redaction scan or the tenant's content posture. */\nexport const SearchBlobPutResponseSchema = z\n .object({\n sha256: HASH,\n byteLength: SEQUENCE,\n state: z.enum(['stored', 'masked', 'withheld']),\n })\n .strict()\nexport type SearchBlobPutResponse = z.infer<typeof SearchBlobPutResponseSchema>\n\nconst UTF8 = new TextEncoder()\n\nexport function searchLedgerLinesByteLength(lines: readonly string[]): number {\n let bytes = 0\n for (const line of lines) bytes += UTF8.encode(line).byteLength\n return bytes\n}\n\n/** Every blob an event names, once each. Ship these before the event. */\nexport function searchLedgerArtifactRefs(event: SearchLedgerEvent): SearchArtifactRef[] {\n const refs: SearchArtifactRef[] = [...event.artifacts]\n switch (event.kind) {\n case 'node-registered':\n refs.push(event.artifact, ...event.surfaces.map((surface) => surface.artifact))\n break\n case 'edge-recorded':\n for (const ref of [event.rationale, ...event.diffs]) if ('uri' in ref) refs.push(ref)\n break\n case 'cell-settled':\n for (const evidence of event.surfaceEvidence) refs.push(...evidence.evidence)\n break\n default:\n break\n }\n const unique = new Map<string, SearchArtifactRef>()\n for (const ref of refs) if (!unique.has(ref.sha256)) unique.set(ref.sha256, ref)\n return [...unique.values()]\n}\n\nexport type SearchLedgerBatchAdmission =\n | {\n status: 'accepted'\n /** Entries past the stored head, in order, with their exact lines. */\n entries: SearchLedgerEntry[]\n lines: string[]\n /** The head after storing `entries`. */\n head: SearchLedgerHead\n }\n | { status: 'conflict'; conflict: SearchLedgerConflict }\n\nexport interface AdmitSearchLedgerBatchInput {\n request: IngestSearchLedgerRequest\n /** The store's head for `request.searchId` before this batch. */\n head: SearchLedgerHead\n /** The stored hash at a sequence below the head. */\n storedEntryHash(sequence: number): SearchLedgerHash | undefined\n}\n\n/**\n * Apply the wire's chain rule to one batch. Each line is verified in isolation\n * (`parseSearchLedgerLine`) and linked to the stored head. A malformed line\n * throws `SearchLedgerIntegrityError`, which a store answers with 422; the\n * state machine (`SearchState`) runs after admission, on `entries`.\n */\nexport function admitSearchLedgerBatch(\n input: AdmitSearchLedgerBatchInput,\n): SearchLedgerBatchAdmission {\n const { request, head } = input\n if (request.searchId !== head.searchId) {\n throw new Error(`head is for search ${head.searchId}, request is for ${request.searchId}`)\n }\n if (request.fromSequence > head.nextSequence) {\n return conflict(\n 'sequence_gap',\n `batch starts at sequence ${request.fromSequence}; the store expects ${head.nextSequence}`,\n head,\n )\n }\n const entries: SearchLedgerEntry[] = []\n const lines: string[] = []\n let previousHash = head.headHash\n for (let index = 0; index < request.lines.length; index++) {\n const sequence = request.fromSequence + index\n const line = request.lines[index]!\n const entry = parseSearchLedgerLine(line, request.searchId, {\n path: `search ${request.searchId}`,\n line: sequence + 1,\n })\n if (entry.sequence !== sequence) {\n throw new SearchLedgerIntegrityError(\n `line ${index} of the batch holds sequence ${entry.sequence}, expected ${sequence}`,\n )\n }\n if (sequence < head.nextSequence) {\n if (input.storedEntryHash(sequence) !== entry.entryHash) {\n return conflict(\n 'chain_conflict',\n `sequence ${sequence} differs from the stored entry; the ledger forked`,\n head,\n )\n }\n continue\n }\n if (entry.previousHash !== previousHash) {\n if (sequence === head.nextSequence) {\n return conflict(\n 'chain_conflict',\n `sequence ${sequence} does not extend the stored head; the ledger forked`,\n head,\n )\n }\n throw new SearchLedgerIntegrityError(\n `sequence ${sequence} does not extend sequence ${sequence - 1} in the same batch`,\n )\n }\n entries.push(entry)\n lines.push(line)\n previousHash = entry.entryHash\n }\n const last = entries.at(-1)\n return {\n status: 'accepted',\n entries,\n lines,\n head: last\n ? { searchId: head.searchId, nextSequence: last.sequence + 1, headHash: last.entryHash }\n : head,\n }\n}\n\nfunction conflict(\n error: SearchLedgerConflict['error'],\n message: string,\n head: SearchLedgerHead,\n): SearchLedgerBatchAdmission {\n return { status: 'conflict', conflict: { error, message, head } }\n}\n","/**\n * # Hosted-tier ingest client.\n *\n * Ships search ledgers and trace spans to any orchestrator (ours, a\n * partner's self-hosted one, or a future open implementation) that speaks\n * the wire format in `./types.ts` and `./search-ledger-wire.ts`.\n *\n * Three modes:\n * - **Ours:** point at `https://orchestrator.tangle.tools` (the host root —\n * the client appends the versioned `/v1/...` path itself; a trailing\n * `/v1` on the endpoint is tolerated and normalized away).\n * - **Self-hosted:** point at whatever URL runs the reference receiver\n * from `examples/hosted-ingest-server/`.\n * - **Off (default):** when no tenant is configured, nothing is sent.\n * Everything stays local.\n *\n * Every call retries network errors, 408, 429 and 5xx. When the server sends\n * `Retry-After`, the client waits exactly that long before the next attempt.\n */\n\nimport type { z } from 'zod'\nimport { IngestResponseSchema, IngestTracesRequestSchema } from './schemas'\nimport {\n type IngestSearchLedgerRequest,\n IngestSearchLedgerRequestSchema,\n SEARCH_LEDGER_INGEST_PATH,\n type SearchBlobPutResponse,\n SearchBlobPutResponseSchema,\n type SearchLedgerConflict,\n SearchLedgerConflictSchema,\n type SearchLedgerHead,\n SearchLedgerHeadSchema,\n searchBlobPath,\n searchLedgerHeadPath,\n} from './search-ledger-wire'\nimport {\n HOSTED_WIRE_VERSION,\n type HostedWireVersion,\n type IngestResponse,\n type IngestTracesRequest,\n type TraceSpanEvent,\n} from './types'\n\nexport interface HostedTenant {\n /** Orchestrator endpoint base URL (no trailing slash). Required. */\n endpoint: string\n /** Bearer token issued by the orchestrator. Required. */\n apiKey: string\n /** Tenant id — the orchestrator's primary key for this consumer. Required. */\n tenantId: string\n /** Optional `fetch` override (auth wrappers, custom agent). */\n fetchImpl?: typeof fetch\n /** Per-attempt timeout in ms. Default 30s. */\n timeoutMs?: number\n /** Retries on network errors, 408, 429 and 5xx. Default 2. */\n retries?: number\n}\n\n/** A search-ledger batch the store accepted, or the fork or gap it refused. */\nexport type SearchLedgerIngestOutcome =\n | { status: 'accepted'; head: SearchLedgerHead }\n | { status: 'conflict'; conflict: SearchLedgerConflict }\n\nexport interface HostedClient {\n ingestTraces(spans: TraceSpanEvent[], idempotencyKey?: string): Promise<IngestResponse>\n /** The store's head for one search; `nextSequence` 0 when it holds nothing. */\n searchLedgerHead(searchId: string, signal?: AbortSignal): Promise<SearchLedgerHead>\n ingestSearchLedger(\n request: IngestSearchLedgerRequest,\n signal?: AbortSignal,\n ): Promise<SearchLedgerIngestOutcome>\n putSearchBlob(\n sha256: `sha256:${string}`,\n bytes: Uint8Array<ArrayBuffer>,\n contentType: string,\n signal?: AbortSignal,\n ): Promise<SearchBlobPutResponse>\n readonly tenant: HostedTenant\n readonly wireVersion: HostedWireVersion\n}\n\n/** A request the server refused, after any retries. */\nexport class HostedRequestError extends Error {\n readonly status: number\n readonly body: string\n constructor(url: string, status: number, body: string) {\n super(`hosted ${url} failed (${status}): ${body.slice(0, 500)}`)\n this.name = 'HostedRequestError'\n this.status = status\n this.body = body\n }\n}\n\ninterface HostedRequest {\n method: 'GET' | 'POST' | 'PUT'\n path: string\n body?: string | Uint8Array<ArrayBuffer>\n contentType?: string\n idempotencyKey?: string\n signal?: AbortSignal\n /** Statuses returned to the caller instead of thrown. */\n expected?: readonly number[]\n}\n\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n reject(signal!.reason)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/** `Retry-After` as milliseconds: delay-seconds or an HTTP date. Null when\n * absent or unreadable, so the caller falls back to its own backoff. */\nfunction retryAfterMs(value: string | null, now = Date.now()): number | null {\n if (value === null) return null\n const trimmed = value.trim()\n if (/^\\d+$/.test(trimmed)) return Number(trimmed) * 1000\n const at = Date.parse(trimmed)\n return Number.isFinite(at) ? Math.max(0, at - now) : null\n}\n\nfunction backoffMs(attempt: number): number {\n return 2 ** attempt * 200 + Math.random() * 200\n}\n\nfunction normalizeHostedBase(endpoint: string): string {\n return endpoint.trim().replace(/\\/+$/, '').replace(/\\/v1$/, '')\n}\n\nfunction resolveIdempotencyKey(key: string | undefined): string {\n const resolved = key ?? globalThis.crypto.randomUUID()\n if (resolved.trim().length === 0) throw new Error('idempotency key must not be blank')\n if (resolved.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n throw new Error(`idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters`)\n }\n return resolved\n}\n\nfunction isRetryable(status: number): boolean {\n return status >= 500 || status === 408 || status === 429\n}\n\nasync function send(\n tenant: HostedTenant,\n request: HostedRequest,\n): Promise<{ status: number; json: unknown; url: string }> {\n const timeoutMs = tenant.timeoutMs ?? 30_000\n const maxRetries = tenant.retries ?? 2\n const f: typeof fetch = tenant.fetchImpl ?? ((...args) => fetch(...args))\n const url = `${normalizeHostedBase(tenant.endpoint)}${request.path}`\n const headers: Record<string, string> = {\n authorization: `Bearer ${tenant.apiKey}`,\n 'x-tangle-tenant-id': tenant.tenantId,\n 'x-tangle-wire-version': HOSTED_WIRE_VERSION,\n }\n if (request.method !== 'GET') {\n headers['idempotency-key'] = resolveIdempotencyKey(request.idempotencyKey)\n headers['content-type'] = request.contentType ?? 'application/json'\n }\n\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const timeout = AbortSignal.timeout(timeoutMs)\n const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout\n let res: Response\n try {\n res = await f(url, {\n method: request.method,\n headers,\n ...(request.body === undefined ? {} : { body: request.body }),\n signal,\n })\n } catch (err) {\n if (request.signal?.aborted) throw err\n lastError = err\n if (attempt === maxRetries) throw err\n await sleep(backoffMs(attempt), request.signal)\n continue\n }\n\n if (!res.ok && !request.expected?.includes(res.status)) {\n const text = await res.text().catch(() => '')\n const error = new HostedRequestError(url, res.status, text)\n if (!isRetryable(res.status) || attempt === maxRetries) throw error\n lastError = error\n await sleep(\n retryAfterMs(res.headers.get('retry-after')) ?? backoffMs(attempt),\n request.signal,\n )\n continue\n }\n\n try {\n return { status: res.status, json: await res.json(), url }\n } catch (error) {\n throw new Error(`hosted ${url} returned invalid JSON`, { cause: error })\n }\n }\n throw lastError ?? new Error('hosted request exhausted retries')\n}\n\nfunction parseResponse<T>(schema: z.ZodType<T>, value: unknown, url: string): T {\n const parsed = schema.safeParse(value)\n if (parsed.success) return parsed.data\n const reason = parsed.error.issues\n .map((issue) => `${issue.path.map(String).join('.') || 'value'}: ${issue.message}`)\n .join('; ')\n throw new Error(`hosted ${url} returned an invalid response: ${reason}`)\n}\n\nexport function createHostedClient(tenant: HostedTenant): HostedClient {\n if (normalizeHostedBase(tenant.endpoint).length === 0) throw new Error('endpoint is required')\n if (tenant.apiKey.trim().length === 0) throw new Error('apiKey is required')\n if (tenant.tenantId.trim().length === 0) throw new Error('tenantId is required')\n if (\n tenant.timeoutMs !== undefined &&\n (!Number.isFinite(tenant.timeoutMs) || tenant.timeoutMs <= 0)\n ) {\n throw new Error('timeoutMs must be greater than 0')\n }\n if (tenant.retries !== undefined && (!Number.isInteger(tenant.retries) || tenant.retries < 0)) {\n throw new Error('retries must be a non-negative integer')\n }\n\n return {\n tenant,\n wireVersion: HOSTED_WIRE_VERSION,\n\n async ingestTraces(spans, idempotencyKey) {\n const body: IngestTracesRequest = IngestTracesRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n spans,\n })\n const res = await send(tenant, {\n method: 'POST',\n path: '/v1/ingest/traces',\n body: JSON.stringify(body),\n idempotencyKey,\n })\n return parseResponse(IngestResponseSchema, res.json, res.url)\n },\n\n async searchLedgerHead(searchId, signal) {\n const res = await send(tenant, {\n method: 'GET',\n path: searchLedgerHeadPath(searchId),\n signal,\n })\n const head = parseResponse(SearchLedgerHeadSchema, res.json, res.url)\n if (head.searchId !== searchId) {\n throw new Error(`hosted ${res.url} returned the head of search ${head.searchId}`)\n }\n return head\n },\n\n async ingestSearchLedger(request, signal) {\n const body = IngestSearchLedgerRequestSchema.parse(request)\n const last = body.lines.at(-1)!\n const res = await send(tenant, {\n method: 'POST',\n path: SEARCH_LEDGER_INGEST_PATH,\n body: JSON.stringify(body),\n // Equal key exactly when the batch is equal, so a cached response is\n // always the response to these lines.\n idempotencyKey: `search-ledger:${await sha256Hex(\n `${body.searchId}\\n${body.runKind}\\n${body.fromSequence}\\n${body.lines.length}\\n${last}`,\n )}`,\n signal,\n expected: [409],\n })\n if (res.status === 409) {\n return {\n status: 'conflict',\n conflict: parseResponse(SearchLedgerConflictSchema, res.json, res.url),\n }\n }\n return { status: 'accepted', head: parseResponse(SearchLedgerHeadSchema, res.json, res.url) }\n },\n\n async putSearchBlob(sha256, bytes, contentType, signal) {\n const res = await send(tenant, {\n method: 'PUT',\n path: searchBlobPath(sha256),\n body: bytes,\n contentType,\n idempotencyKey: `search-blob:${sha256}`,\n signal,\n })\n const stored = parseResponse(SearchBlobPutResponseSchema, res.json, res.url)\n if (stored.sha256 !== sha256) {\n throw new Error(`hosted ${res.url} acknowledged blob ${stored.sha256}, sent ${sha256}`)\n }\n return stored\n },\n }\n}\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Build a {@link HostedTenant} from env, or `undefined` when ingest is not\n * configured, so a product wires it unconditionally and it stays off until the\n * env is set. Env precedence:\n * - endpoint: `TANGLE_INGEST_URL` → `TANGLE_ORCHESTRATOR_URL`\n * - apiKey: `TANGLE_INGEST_API_KEY` → `TANGLE_API_KEY`\n * - tenantId: `TANGLE_TENANT_ID`\n * A trailing slash on the endpoint is stripped. `overrides` win over env.\n */\nexport function hostedTenantFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedTenant | undefined {\n const env = overrides.env ?? process.env\n const endpoint = (\n overrides.endpoint ??\n env.TANGLE_INGEST_URL ??\n env.TANGLE_ORCHESTRATOR_URL\n )?.trim()\n const apiKey = (overrides.apiKey ?? env.TANGLE_INGEST_API_KEY ?? env.TANGLE_API_KEY)?.trim()\n const tenantId = (overrides.tenantId ?? env.TANGLE_TENANT_ID)?.trim()\n if (!endpoint || !apiKey || !tenantId) return undefined\n const tenant: HostedTenant = { endpoint: endpoint.replace(/\\/+$/, ''), apiKey, tenantId }\n if (overrides.fetchImpl) tenant.fetchImpl = overrides.fetchImpl\n if (overrides.timeoutMs !== undefined) tenant.timeoutMs = overrides.timeoutMs\n if (overrides.retries !== undefined) tenant.retries = overrides.retries\n return tenant\n}\n\n/** {@link createHostedClient} over {@link hostedTenantFromEnv}; `undefined`\n * when ingest is not configured. */\nexport function hostedClientFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedClient | undefined {\n const tenant = hostedTenantFromEnv(overrides)\n return tenant ? createHostedClient(tenant) : undefined\n}\n","/**\n * Ship a search ledger to a hosted store while the search runs, or after.\n *\n * The local ledger is the source of truth and the search never waits on the\n * network: the shipper reads the ledger file the recorder already made\n * durable, uploads the blobs each entry names, then posts the entries. It\n * starts from the store's head, so a restarted process, a lost response, or a\n * second shipper continues where the store's chain ends instead of resending\n * the search. A store that holds a different chain for the same search stops\n * the shipper with `SearchShipConflictError`; nothing is overwritten.\n */\n\nimport { createHash } from 'node:crypto'\nimport { open, readFile } from 'node:fs/promises'\nimport { fileURLToPath } from 'node:url'\nimport type { SearchLedgerEntry, SearchLedgerHash } from '../campaign/search-ledger-types'\nimport { createHostedClient, type HostedClient, type HostedTenant } from './client'\nimport {\n SEARCH_LEDGER_BATCH_MAX_BYTES,\n SEARCH_LEDGER_BATCH_MAX_LINES,\n type SearchLedgerConflict,\n type SearchLedgerHead,\n type SearchRunKind,\n searchLedgerArtifactRefs,\n} from './search-ledger-wire'\nimport { HOSTED_WIRE_VERSION } from './types'\n\nexport interface SearchShipOptions {\n tenant: HostedTenant\n ledger: { path: string; searchId: string }\n runKind: SearchRunKind\n /** `full` (default) uploads every blob an entry names; `digests` ships the\n * entries alone, so the store holds refs and digests without content. */\n content?: 'full' | 'digests'\n signal?: AbortSignal\n}\n\n/** A blob an entry names that was not uploaded, and why. */\nexport interface SearchShipMissingBlob {\n sha256: SearchLedgerHash\n uri: string\n reason: string\n}\n\nexport interface SearchShipResult {\n searchId: string\n /** The store's head after the last accepted batch. */\n head: SearchLedgerHead\n /** Local complete lines, which the store now holds when `head` reaches them. */\n localLines: number\n /** Ledger lines posted, counting resends after a gap. */\n linesPosted: number\n batches: number\n /** Resends after the store answered `sequence_gap`. */\n gapResends: number\n blobs: {\n content: 'full' | 'digests'\n uploaded: number\n stored: number\n masked: number\n withheld: number\n missing: SearchShipMissingBlob[]\n }\n}\n\n/** The store holds a different chain for this search. */\nexport class SearchShipConflictError extends Error {\n readonly conflict: SearchLedgerConflict\n constructor(conflict: SearchLedgerConflict) {\n super(\n `search ${conflict.head.searchId}: ${conflict.error}: ${conflict.message} (store head ${conflict.head.nextSequence} ${conflict.head.headHash ?? 'empty'})`,\n )\n this.name = 'SearchShipConflictError'\n this.conflict = conflict\n }\n}\n\n/** Ship every complete line of the ledger file now, then return. */\nexport async function shipSearchLedger(options: SearchShipOptions): Promise<SearchShipResult> {\n return new SearchLedgerTail(options).ship()\n}\n\nexport interface SearchShipper {\n /** Ship what is in the file now without waiting for the next tick. */\n flush(): Promise<SearchShipResult>\n /** Stop tailing, ship the rest of the file, and return the final result. */\n stop(): Promise<SearchShipResult>\n /** The last transient failure, cleared by the next successful tick. */\n readonly lastError: Error | null\n}\n\n/**\n * Tail the ledger: ship new lines every `intervalMs` (default 2 s) until\n * `stop()`. A transient failure is kept on `lastError` and retried on the next\n * tick; a conflict stops tailing and is thrown by `stop()`.\n */\nexport function startSearchShipper(\n options: SearchShipOptions & { intervalMs?: number },\n): SearchShipper {\n const tail = new SearchLedgerTail(options)\n const intervalMs = options.intervalMs ?? 2000\n const stopping = new AbortController()\n let lastError: Error | null = null\n let conflict: SearchShipConflictError | null = null\n let running: Promise<unknown> = Promise.resolve()\n\n const tick = (): Promise<unknown> => {\n running = running.then(async () => {\n if (conflict) return\n try {\n await tail.ship()\n lastError = null\n } catch (error) {\n if (error instanceof SearchShipConflictError) conflict = error\n else lastError = error instanceof Error ? error : new Error(String(error))\n }\n })\n return running\n }\n\n const loop = (async () => {\n while (!stopping.signal.aborted && !conflict) {\n await tick()\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, intervalMs)\n stopping.signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer)\n resolve()\n },\n { once: true },\n )\n })\n }\n })()\n\n return {\n get lastError() {\n return lastError\n },\n async flush() {\n await tick()\n if (conflict) throw conflict\n if (lastError) throw lastError\n return tail.result()\n },\n async stop() {\n stopping.abort()\n await loop\n await running\n if (conflict) throw conflict\n return tail.ship()\n },\n }\n}\n\n/** One full batch of lines with their newlines, plus a byte to see where a\n * maximal line ends. */\nconst READ_CHUNK_BYTES = SEARCH_LEDGER_BATCH_MAX_BYTES + SEARCH_LEDGER_BATCH_MAX_LINES + 1\n\ninterface LocalLine {\n text: string\n entry: SearchLedgerEntry\n bytes: number\n}\n\nclass SearchLedgerTail {\n private readonly client: HostedClient\n private readonly options: SearchShipOptions\n private readonly content: 'full' | 'digests'\n /** Where the store's chain ends, and the byte offset of that line locally. */\n private head: SearchLedgerHead | null = null\n private offset = 0\n private localLines = 0\n private readonly uploaded = new Set<string>()\n private readonly missing = new Map<string, SearchShipMissingBlob>()\n private readonly counts = {\n linesPosted: 0,\n batches: 0,\n gapResends: 0,\n uploaded: 0,\n stored: 0,\n masked: 0,\n withheld: 0,\n }\n\n constructor(options: SearchShipOptions) {\n this.options = options\n this.content = options.content ?? 'full'\n this.client = createHostedClient(options.tenant)\n }\n\n result(): SearchShipResult {\n const { linesPosted, batches, gapResends, uploaded, stored, masked, withheld } = this.counts\n return {\n searchId: this.options.ledger.searchId,\n head: this.head ?? {\n searchId: this.options.ledger.searchId,\n nextSequence: 0,\n headHash: null,\n },\n localLines: this.localLines,\n linesPosted,\n batches,\n gapResends,\n blobs: {\n content: this.content,\n uploaded,\n stored,\n masked,\n withheld,\n missing: [...this.missing.values()],\n },\n }\n }\n\n async ship(): Promise<SearchShipResult> {\n const { signal } = this.options\n if (this.head === null) {\n await this.syncTo(await this.client.searchLedgerHead(this.options.ledger.searchId, signal))\n }\n for (;;) {\n const lines = await this.readChunk(this.offset, this.head!)\n if (lines.length === 0) return this.result()\n const batch = takeBatch(lines)\n if (this.content === 'full') await this.uploadBlobs(batch)\n const fromSequence = this.head!.nextSequence\n const outcome = await this.client.ingestSearchLedger(\n {\n wireVersion: HOSTED_WIRE_VERSION,\n searchId: this.options.ledger.searchId,\n runKind: this.options.runKind,\n fromSequence,\n lines: batch.map((line) => line.text),\n },\n signal,\n )\n this.counts.batches++\n this.counts.linesPosted += batch.length\n if (outcome.status === 'conflict') {\n if (outcome.conflict.error === 'chain_conflict') {\n throw new SearchShipConflictError(outcome.conflict)\n }\n this.counts.gapResends++\n await this.syncTo(outcome.conflict.head)\n continue\n }\n const last = batch.at(-1)!.entry\n if (\n outcome.head.nextSequence < last.sequence + 1 ||\n (outcome.head.nextSequence === last.sequence + 1 &&\n outcome.head.headHash !== last.entryHash)\n ) {\n throw new Error(\n `store acknowledged sequence ${fromSequence}..${last.sequence} with head ${outcome.head.nextSequence} ${outcome.head.headHash}`,\n )\n }\n await this.syncTo(outcome.head)\n }\n }\n\n /** Move the cursor to the store's head, checking that the local ledger holds\n * the same entry there. A different entry is a fork; a store ahead of the\n * local file holds lines this ledger never wrote. */\n private async syncTo(head: SearchLedgerHead): Promise<void> {\n if (head.searchId !== this.options.ledger.searchId) {\n throw new Error(`store answered for search ${head.searchId}`)\n }\n const fork = (message: string) =>\n new SearchShipConflictError({ error: 'chain_conflict', message, head })\n const empty: SearchLedgerHead = { searchId: head.searchId, nextSequence: 0, headHash: null }\n const forward = this.head !== null && head.nextSequence >= this.head.nextSequence\n let offset = forward ? this.offset : 0\n let cursor = forward ? this.head! : empty\n while (cursor.nextSequence < head.nextSequence) {\n const lines = await this.readChunk(offset, cursor)\n if (lines.length === 0) {\n throw fork(\n `the store holds ${head.nextSequence} entries; the local ledger holds ${cursor.nextSequence}`,\n )\n }\n const take = Math.min(lines.length, head.nextSequence - cursor.nextSequence)\n for (let index = 0; index < take; index++) offset += lines[index]!.bytes\n const last = lines[take - 1]!.entry\n cursor = {\n searchId: head.searchId,\n nextSequence: last.sequence + 1,\n headHash: last.entryHash,\n }\n }\n if (cursor.headHash !== head.headHash) {\n throw fork(`the store's entry ${head.nextSequence - 1} differs from the local ledger's`)\n }\n this.offset = offset\n this.head = head\n }\n\n /** The complete lines in one read chunk from `offset`, checked to continue\n * the chain at `head`. A chunk holds at least one full batch. */\n private async readChunk(offset: number, head: SearchLedgerHead): Promise<LocalLine[]> {\n const bytes = await readRange(this.options.ledger.path, offset, READ_CHUNK_BYTES)\n const lines: LocalLine[] = []\n let start = 0\n let expectedSequence = head.nextSequence\n let previousHash = head.headHash\n for (;;) {\n const newline = bytes.indexOf(0x0a, start)\n // A line without its newline is still being written, or continues in\n // the next chunk.\n if (newline < 0) break\n const text = bytes.toString('utf8', start, newline)\n const entry = JSON.parse(text) as SearchLedgerEntry\n if (\n entry.searchId !== this.options.ledger.searchId ||\n entry.sequence !== expectedSequence ||\n entry.previousHash !== previousHash\n ) {\n throw new Error(\n `${this.options.ledger.path} line ${expectedSequence + 1} does not continue the chain at sequence ${expectedSequence}`,\n )\n }\n lines.push({ text, entry, bytes: newline + 1 - start })\n expectedSequence++\n previousHash = entry.entryHash\n start = newline + 1\n }\n if (lines.length === 0 && bytes.byteLength === READ_CHUNK_BYTES) {\n throw new Error(\n `${this.options.ledger.path} line ${expectedSequence + 1} is longer than ${SEARCH_LEDGER_BATCH_MAX_BYTES} bytes; one request carries at most that`,\n )\n }\n this.localLines = Math.max(this.localLines, expectedSequence)\n return lines\n }\n\n private async uploadBlobs(batch: LocalLine[]): Promise<void> {\n for (const line of batch) {\n for (const ref of searchLedgerArtifactRefs(line.entry.event)) {\n if (this.uploaded.has(ref.sha256) || this.missing.has(ref.sha256)) continue\n const bytes = await readBlob(ref.uri)\n if (typeof bytes === 'string') {\n this.missing.set(ref.sha256, { sha256: ref.sha256, uri: ref.uri, reason: bytes })\n continue\n }\n const digest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n if (digest !== ref.sha256 || bytes.byteLength !== ref.byteLength) {\n this.missing.set(ref.sha256, {\n sha256: ref.sha256,\n uri: ref.uri,\n reason: `local bytes are ${digest} (${bytes.byteLength} bytes), not the ref's ${ref.sha256} (${ref.byteLength} bytes)`,\n })\n continue\n }\n const stored = await this.client.putSearchBlob(\n ref.sha256,\n new Uint8Array(bytes),\n ref.uri.endsWith('.json') ? 'application/json' : 'application/octet-stream',\n this.options.signal,\n )\n this.uploaded.add(ref.sha256)\n this.counts.uploaded++\n this.counts[stored.state]++\n }\n }\n }\n}\n\n/** The longest prefix of `lines` within one request's limits. */\nfunction takeBatch(lines: LocalLine[]): LocalLine[] {\n const batch: LocalLine[] = []\n let bytes = 0\n for (const line of lines) {\n const size = line.bytes - 1\n if (size > SEARCH_LEDGER_BATCH_MAX_BYTES) {\n throw new Error(\n `ledger line ${line.entry.sequence} holds ${size} bytes; one request carries at most ${SEARCH_LEDGER_BATCH_MAX_BYTES}`,\n )\n }\n if (\n batch.length === SEARCH_LEDGER_BATCH_MAX_LINES ||\n bytes + size > SEARCH_LEDGER_BATCH_MAX_BYTES\n )\n break\n batch.push(line)\n bytes += size\n }\n return batch\n}\n\n/** Up to `limit` bytes of the file from `offset`; empty before the recorder\n * created the file. */\nasync function readRange(path: string, offset: number, limit: number): Promise<Buffer> {\n let handle: Awaited<ReturnType<typeof open>>\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT' && offset === 0) return Buffer.alloc(0)\n throw error\n }\n try {\n const { size } = await handle.stat()\n if (size < offset) throw new Error(`${path} shrank below byte ${offset}`)\n const bytes = Buffer.alloc(Math.min(limit, size - offset))\n let read = 0\n while (read < bytes.byteLength) {\n const { bytesRead } = await handle.read(bytes, read, bytes.byteLength - read, offset + read)\n if (bytesRead === 0) break\n read += bytesRead\n }\n return bytes.subarray(0, read)\n } finally {\n await handle.close()\n }\n}\n\n/** The bytes at a `file:` ref, or why there are none. */\nasync function readBlob(uri: string): Promise<Buffer | string> {\n if (!uri.startsWith('file:'))\n return `the shipper reads only file: refs, not ${uri.split(':')[0]}:`\n try {\n return await readFile(fileURLToPath(uri))\n } catch (error) {\n return `unreadable: ${(error as NodeJS.ErrnoException).code ?? String(error)}`\n }\n}\n\n/**\n * Run a ship that must never fail its caller, such as the one a loop runs at\n * its end. A failure, a store short of the local ledger, or a blob that did\n * not upload is logged with the command that resumes it.\n */\nexport async function shipBestEffort(\n ship: () => Promise<SearchShipResult>,\n ledgerPath: string,\n): Promise<SearchShipResult | undefined> {\n const resume = `agent-eval search ship ${ledgerPath}`\n try {\n const shipped = await ship()\n if (shipped.head.nextSequence < shipped.localLines) {\n console.warn(\n `[agent-eval] search ${shipped.searchId}: the store holds ${shipped.head.nextSequence} of ${shipped.localLines} ledger entries; resume with ${resume}`,\n )\n }\n if (shipped.blobs.missing.length > 0) {\n console.warn(\n `[agent-eval] search ${shipped.searchId}: ${shipped.blobs.missing.length} blob(s) were not uploaded, first: ${shipped.blobs.missing[0]!.reason}`,\n )\n }\n return shipped\n } catch (error) {\n console.warn(\n `[agent-eval] search ledger ship failed (continuing; resume with ${resume}): ${error instanceof Error ? error.message : String(error)}`,\n )\n return undefined\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,sBAAsB;;;ACdnC,MAAM,eAAe,EAAE,OAAO,CAAC,CAAC,OAAO;AACvC,MAAM,qBAAqB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY;AACxD,MAAM,iBAAiB,EACpB,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,QAAQ,UAAU,MAAM,KAAK,CAAC,CAAC,SAAS,GAAG,mBAAmB;AACjE,MAAM,iBAAiB,EAAE,MAAM;CAAC,EAAE,OAAO;CAAG;CAAc,EAAE,QAAQ;AAAC,CAAC;AACtE,MAAM,aAAa,EAAE,OAAO,EAAE,OAAO,GAAG,cAAc;AACtD,MAAM,aAAa;AAEnB,MAAa,0BAAwD,EAClE,OAAO,CAAC,CACR,MAAM,qBAAqB,6CAA6C,CAAC,CACzE,QAAQ,UAAU,OAAO,KAAK,KAAK,YAAY,wCAAwC;AAE1F,MAAM,4BAA4B,EAC/B,OAAO;CACN,cAAc;CACd,MAAM;CACN,YAAY,WAAW,SAAS;AAClC,CAAC,CAAC,CACD,OAAO;AAEV,MAAa,uBAAkD,EAC5D,OAAO;CACN,SAAS;CACT,QAAQ;CACR,cAAc,eAAe,SAAS;CACtC,MAAM;CACN,mBAAmB;CACnB,iBAAiB;CACjB;CACA,QAAQ,EAAE,MAAM,yBAAyB,CAAC,CAAC,SAAS;CACpD,QAAQ,EACL,OAAO;EACN,MAAM,EAAE,KAAK;GAAC;GAAM;GAAS;EAAO,CAAC;EACrC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,CAAC,CAAC,CACD,OAAO,CAAC,CACR,SAAS;CACZ,gBAAgB,eAAe,SAAS;CACxC,qBAAqB,mBAAmB,SAAS;CACjD,iBAAiB,eAAe,SAAS;CACzC,qBAAqB,eA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,OAAO,MAAM,YAAY;GAC9B,MAAM,EAAE,cAAc,MAAM,OAAO,KAAK,OAAO,MAAM,MAAM,aAAa,MAAM,SAAS,IAAI;GAC3F,IAAI,cAAc,GAAG;GACrB,QAAQ;EACV;EACA,OAAO,MAAM,SAAS,GAAG,IAAI;CAC/B,UAAU;EACR,MAAM,OAAO,MAAM;CACrB;AACF;;AAGA,eAAe,SAAS,KAAuC;CAC7D,IAAI,CAAC,IAAI,WAAW,OAAO,GACzB,OAAO,0CAA0C,IAAI,MAAM,GAAG,CAAC,CAAC,GAAG;CACrE,IAAI;EACF,OAAO,MAAM,SAAS,cAAc,GAAG,CAAC;CAC1C,SAAS,OAAO;EACd,OAAO,eAAgB,MAAgC,QAAQ,OAAO,KAAK;CAC7E;AACF;;;;;;AAOA,eAAsB,eACpB,MACA,YACuC;CACvC,MAAM,SAAS,0BAA0B;CACzC,IAAI;EACF,MAAM,UAAU,MAAM,KAAK;EAC3B,IAAI,QAAQ,KAAK,eAAe,QAAQ,YACtC,QAAQ,KACN,uBAAuB,QAAQ,SAAS,oBAAoB,QAAQ,KAAK,aAAa,MAAM,QAAQ,WAAW,+BAA+B,QAChJ;EAEF,IAAI,QAAQ,MAAM,QAAQ,SAAS,GACjC,QAAQ,KACN,uBAAuB,QAAQ,SAAS,IAAI,QAAQ,MAAM,QAAQ,OAAO,qCAAqC,QAAQ,MAAM,QAAQ,EAAE,CAAE,QAC1I;EAEF,OAAO;CACT,SAAS,OAAO;EACd,QAAQ,KACN,mEAAmE,OAAO,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACtI;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"search-shipper-DKXWuLnp.js","names":[],"sources":["../src/hosted/types.ts","../src/hosted/schemas.ts","../src/hosted/search-ledger-wire.ts","../src/hosted/client.ts","../src/hosted/search-shipper.ts"],"sourcesContent":["/**\n * # Hosted-tier wire format: the shapes every orchestrator (ours, a partner's\n * self-hosted one, a future open implementation) must accept.\n *\n * This package implements exactly one wire version. Servers reject every\n * other version instead of translating old payloads.\n *\n * The wire carries two streams in one transport:\n *\n * 1. **Search ledgers** (`/v1/search-blobs/*`, `/v1/ingest/search-ledger`).\n * A producer ships a search's hash-chained ledger lines and the blobs\n * they name; `./search-ledger-wire.ts` owns those shapes.\n *\n * 2. **Trace spans** (`POST /v1/ingest/traces`). Standard OTLP-shaped\n * spans with a few additional attributes so the orchestrator can\n * pivot from a search cell to its underlying execution. Compatible\n * with any OTel collector.\n *\n * Every endpoint is authenticated with a bearer token and a tenant id\n * header. Tenants isolate everything downstream of ingest; no tenant\n * ever sees another tenant's data.\n */\n\nexport const HOSTED_WIRE_VERSION = '2026-07-24.v1' as const\nexport type HostedWireVersion = typeof HOSTED_WIRE_VERSION\n\n// ── Transport headers ───────────────────────────────────────────────\n\n/** Every ingest request carries these. */\nexport interface HostedIngestHeaders {\n /** Bearer token. The orchestrator validates against the tenant key. */\n authorization: `Bearer ${string}`\n /** Stable tenant id (the orchestrator-side primary key for the tenant). */\n 'x-tangle-tenant-id': string\n /** Wire-version pin so the server can reject incompatible payloads. */\n 'x-tangle-wire-version': HostedWireVersion\n /** Stable request key generated once and reused across retries. */\n 'idempotency-key': string\n}\n\n// ── Trace span event ────────────────────────────────────────────────\n\n/**\n * Canonical unsigned 64-bit integer encoded as a base-10 string.\n * JSON numbers cannot represent OTLP nanosecond timestamps exactly.\n */\nexport type UnixNanoTimestamp = string\n\n/**\n * OTel-shape span with a few additional attributes for pivoting.\n * Compatible with any OTLP collector — `name`, `traceId`, `spanId`,\n * `startTimeUnixNano`, `endTimeUnixNano`, `attributes` are stock OTel.\n */\nexport interface TraceSpanEvent {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n startTimeUnixNano: UnixNanoTimestamp\n endTimeUnixNano: UnixNanoTimestamp\n attributes: Record<string, string | number | boolean>\n events?: Array<{\n timeUnixNano: UnixNanoTimestamp\n name: string\n attributes?: Record<string, string | number | boolean>\n }>\n status?: { code: 'OK' | 'ERROR' | 'UNSET'; message?: string }\n /** Pivot to the producing run. */\n 'tangle.runId'?: string\n /** Pivot to the specific generation. */\n 'tangle.generation'?: number\n /** Pivot to the specific cell. */\n 'tangle.cellId'?: string\n /** Pivot to the specific scenario. */\n 'tangle.scenarioId'?: string\n}\n\n// ── Ingest request bodies ───────────────────────────────────────────\n\nexport interface IngestTracesRequest {\n wireVersion: HostedWireVersion\n spans: TraceSpanEvent[]\n}\n\nexport interface IngestResponse {\n /** Accepted spans count. */\n accepted: number\n /** Rejected spans with reasons (validation failures, conflicting identity). */\n rejected: Array<{ index: number; reason: string }>\n}\n","import { z } from 'zod'\nimport type {\n IngestResponse,\n IngestTracesRequest,\n TraceSpanEvent,\n UnixNanoTimestamp,\n} from './types'\nimport { HOSTED_WIRE_VERSION } from './types'\n\nconst finiteNumber = z.number().finite()\nconst nonNegativeInteger = z.number().int().nonnegative()\nconst nonEmptyString = z\n .string()\n .min(1)\n .refine((value) => value.trim().length > 0, 'must not be blank')\nconst attributeValue = z.union([z.string(), finiteNumber, z.boolean()])\nconst attributes = z.record(z.string(), attributeValue)\nconst UINT64_MAX = 18_446_744_073_709_551_615n\n\nexport const UnixNanoTimestampSchema: z.ZodType<UnixNanoTimestamp> = z\n .string()\n .regex(/^(0|[1-9][0-9]*)$/, 'expected an unsigned base-10 integer string')\n .refine((value) => BigInt(value) <= UINT64_MAX, 'must fit in an unsigned 64-bit integer')\n\nconst TraceSpanEventEntrySchema = z\n .object({\n timeUnixNano: UnixNanoTimestampSchema,\n name: nonEmptyString,\n attributes: attributes.optional(),\n })\n .strict()\n\nexport const TraceSpanEventSchema: z.ZodType<TraceSpanEvent> = z\n .object({\n traceId: nonEmptyString,\n spanId: nonEmptyString,\n parentSpanId: nonEmptyString.optional(),\n name: nonEmptyString,\n startTimeUnixNano: UnixNanoTimestampSchema,\n endTimeUnixNano: UnixNanoTimestampSchema,\n attributes,\n events: z.array(TraceSpanEventEntrySchema).optional(),\n status: z\n .object({\n code: z.enum(['OK', 'ERROR', 'UNSET']),\n message: z.string().optional(),\n })\n .strict()\n .optional(),\n 'tangle.runId': nonEmptyString.optional(),\n 'tangle.generation': nonNegativeInteger.optional(),\n 'tangle.cellId': nonEmptyString.optional(),\n 'tangle.scenarioId': nonEmptyString.optional(),\n })\n .strict()\n .refine((span) => BigInt(span.endTimeUnixNano) >= BigInt(span.startTimeUnixNano), {\n path: ['endTimeUnixNano'],\n message: 'endTimeUnixNano must be greater than or equal to startTimeUnixNano',\n })\n\nexport const IngestTracesEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestTracesRequestSchema: z.ZodType<IngestTracesRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(TraceSpanEventSchema),\n })\n .strict()\n\nexport const IngestResponseSchema: z.ZodType<IngestResponse> = z\n .object({\n accepted: nonNegativeInteger,\n rejected: z.array(\n z\n .object({\n index: nonNegativeInteger,\n reason: nonEmptyString,\n })\n .strict(),\n ),\n })\n .strict()\n","/**\n * The search-ledger wire: how a producer ships a search ledger to a hosted\n * store, and the rule a store applies to each batch.\n *\n * A producer ships three things, in this order:\n *\n * 1. Blobs: `PUT /v1/search-blobs/<sha256 hex>` with the exact bytes an\n * entry's artifact ref names. The store re-hashes them; the call is\n * idempotent by content.\n * 2. Head: `GET /v1/ingest/search-ledger/<searchId>/head` tells a restarted\n * producer where the store's copy of the chain ends.\n * 3. Entries: `POST /v1/ingest/search-ledger` with canonical ledger lines,\n * starting at `fromSequence`. The store verifies every line, links it to\n * its stored head, and answers with its new head.\n *\n * The lines are the ledger's own bytes, so producer and store hash identical\n * input. A line below the store's head with an equal hash is a no-op; a\n * different hash is a fork (`409 chain_conflict`); a batch that starts past\n * the head is a gap (`409 sequence_gap`). Both 409s carry the store's head,\n * so a producer resends from there or stops on a fork.\n */\n\nimport { z } from 'zod'\nimport { parseSearchLedgerLine } from '../campaign/search-ledger'\nimport { SearchLedgerIntegrityError } from '../campaign/search-ledger-errors'\nimport type {\n SearchArtifactRef,\n SearchLedgerEntry,\n SearchLedgerEvent,\n SearchLedgerHash,\n} from '../campaign/search-ledger-types'\nimport { HOSTED_WIRE_VERSION } from './types'\n\n/** At most this many lines in one ingest request. */\nexport const SEARCH_LEDGER_BATCH_MAX_LINES = 1000\n/** At most this many UTF-8 bytes across one request's lines. A single line\n * larger than this cannot be shipped. */\nexport const SEARCH_LEDGER_BATCH_MAX_BYTES = 1_048_576\n\nexport const SEARCH_LEDGER_INGEST_PATH = '/v1/ingest/search-ledger'\n\nexport function searchLedgerHeadPath(searchId: string): string {\n return `${SEARCH_LEDGER_INGEST_PATH}/${encodeURIComponent(searchId)}/head`\n}\n\n/** Blobs are addressed by the hex digest alone. */\nexport function searchBlobPath(sha256: SearchLedgerHash): string {\n return `/v1/search-blobs/${sha256.slice('sha256:'.length)}`\n}\n\nconst HASH = z.custom<SearchLedgerHash>(\n (value) => typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value),\n 'expected sha256:<64 lowercase hex characters>',\n)\nconst SEARCH_ID = z\n .string()\n .min(1)\n .refine((value) => value.trim() === value, 'must not contain surrounding whitespace')\nconst SEQUENCE = z.number().int().nonnegative().safe()\n\n/** What the run is for: an optimization, or an eval (a one-node search). */\nexport const SearchRunKindSchema = z.enum(['optimization', 'eval'])\nexport type SearchRunKind = z.infer<typeof SearchRunKindSchema>\n\n/** Where a store's copy of one search's chain ends. `headHash` is null exactly\n * when the store holds no entry. */\nexport const SearchLedgerHeadSchema = z\n .object({ searchId: SEARCH_ID, nextSequence: SEQUENCE, headHash: HASH.nullable() })\n .strict()\n .refine((head) => (head.nextSequence === 0) === (head.headHash === null), {\n message: 'headHash must be null exactly when nextSequence is 0',\n path: ['headHash'],\n })\nexport type SearchLedgerHead = z.infer<typeof SearchLedgerHeadSchema>\n\nexport const IngestSearchLedgerRequestSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n searchId: SEARCH_ID,\n runKind: SearchRunKindSchema,\n fromSequence: SEQUENCE,\n lines: z.array(z.string().min(1)).min(1).max(SEARCH_LEDGER_BATCH_MAX_LINES),\n })\n .strict()\n .superRefine((request, ctx) => {\n const bytes = searchLedgerLinesByteLength(request.lines)\n if (bytes > SEARCH_LEDGER_BATCH_MAX_BYTES) {\n ctx.addIssue({\n code: 'custom',\n path: ['lines'],\n message: `lines hold ${bytes} bytes; at most ${SEARCH_LEDGER_BATCH_MAX_BYTES} per request`,\n })\n }\n })\nexport type IngestSearchLedgerRequest = z.infer<typeof IngestSearchLedgerRequestSchema>\n\n/** The body of a `409`: a fork or a gap, with the store's head. */\nexport const SearchLedgerConflictSchema = z\n .object({\n error: z.enum(['chain_conflict', 'sequence_gap']),\n message: z.string().min(1),\n head: SearchLedgerHeadSchema,\n })\n .strict()\nexport type SearchLedgerConflict = z.infer<typeof SearchLedgerConflictSchema>\n\n/** What a store kept of one blob. `masked` and `withheld` come from the\n * store's own redaction scan or the tenant's content posture. */\nexport const SearchBlobPutResponseSchema = z\n .object({\n sha256: HASH,\n byteLength: SEQUENCE,\n state: z.enum(['stored', 'masked', 'withheld']),\n })\n .strict()\nexport type SearchBlobPutResponse = z.infer<typeof SearchBlobPutResponseSchema>\n\nconst UTF8 = new TextEncoder()\n\nexport function searchLedgerLinesByteLength(lines: readonly string[]): number {\n let bytes = 0\n for (const line of lines) bytes += UTF8.encode(line).byteLength\n return bytes\n}\n\n/** Every blob an event names, once each. Ship these before the event. */\nexport function searchLedgerArtifactRefs(event: SearchLedgerEvent): SearchArtifactRef[] {\n const refs: SearchArtifactRef[] = [...event.artifacts]\n switch (event.kind) {\n case 'node-registered':\n refs.push(event.artifact, ...event.surfaces.map((surface) => surface.artifact))\n break\n case 'edge-recorded':\n for (const ref of [event.rationale, ...event.diffs]) if ('uri' in ref) refs.push(ref)\n break\n case 'cell-settled':\n for (const evidence of event.surfaceEvidence) refs.push(...evidence.evidence)\n break\n default:\n break\n }\n const unique = new Map<string, SearchArtifactRef>()\n for (const ref of refs) if (!unique.has(ref.sha256)) unique.set(ref.sha256, ref)\n return [...unique.values()]\n}\n\nexport type SearchLedgerBatchAdmission =\n | {\n status: 'accepted'\n /** Entries past the stored head, in order, with their exact lines. */\n entries: SearchLedgerEntry[]\n lines: string[]\n /** The head after storing `entries`. */\n head: SearchLedgerHead\n }\n | { status: 'conflict'; conflict: SearchLedgerConflict }\n\nexport interface AdmitSearchLedgerBatchInput {\n request: IngestSearchLedgerRequest\n /** The store's head for `request.searchId` before this batch. */\n head: SearchLedgerHead\n /** The stored hash at a sequence below the head. */\n storedEntryHash(sequence: number): SearchLedgerHash | undefined\n}\n\n/**\n * Apply the wire's chain rule to one batch. Each line is verified in isolation\n * (`parseSearchLedgerLine`) and linked to the stored head. A malformed line\n * throws `SearchLedgerIntegrityError`, which a store answers with 422; the\n * state machine (`SearchState`) runs after admission, on `entries`.\n */\nexport function admitSearchLedgerBatch(\n input: AdmitSearchLedgerBatchInput,\n): SearchLedgerBatchAdmission {\n const { request, head } = input\n if (request.searchId !== head.searchId) {\n throw new Error(`head is for search ${head.searchId}, request is for ${request.searchId}`)\n }\n if (request.fromSequence > head.nextSequence) {\n return conflict(\n 'sequence_gap',\n `batch starts at sequence ${request.fromSequence}; the store expects ${head.nextSequence}`,\n head,\n )\n }\n const entries: SearchLedgerEntry[] = []\n const lines: string[] = []\n let previousHash = head.headHash\n for (let index = 0; index < request.lines.length; index++) {\n const sequence = request.fromSequence + index\n const line = request.lines[index]!\n const entry = parseSearchLedgerLine(line, request.searchId, {\n path: `search ${request.searchId}`,\n line: sequence + 1,\n })\n if (entry.sequence !== sequence) {\n throw new SearchLedgerIntegrityError(\n `line ${index} of the batch holds sequence ${entry.sequence}, expected ${sequence}`,\n )\n }\n if (sequence < head.nextSequence) {\n if (input.storedEntryHash(sequence) !== entry.entryHash) {\n return conflict(\n 'chain_conflict',\n `sequence ${sequence} differs from the stored entry; the ledger forked`,\n head,\n )\n }\n continue\n }\n if (entry.previousHash !== previousHash) {\n if (sequence === head.nextSequence) {\n return conflict(\n 'chain_conflict',\n `sequence ${sequence} does not extend the stored head; the ledger forked`,\n head,\n )\n }\n throw new SearchLedgerIntegrityError(\n `sequence ${sequence} does not extend sequence ${sequence - 1} in the same batch`,\n )\n }\n entries.push(entry)\n lines.push(line)\n previousHash = entry.entryHash\n }\n const last = entries.at(-1)\n return {\n status: 'accepted',\n entries,\n lines,\n head: last\n ? { searchId: head.searchId, nextSequence: last.sequence + 1, headHash: last.entryHash }\n : head,\n }\n}\n\nfunction conflict(\n error: SearchLedgerConflict['error'],\n message: string,\n head: SearchLedgerHead,\n): SearchLedgerBatchAdmission {\n return { status: 'conflict', conflict: { error, message, head } }\n}\n","/**\n * # Hosted-tier ingest client.\n *\n * Ships search ledgers and trace spans to any orchestrator (ours, a\n * partner's self-hosted one, or a future open implementation) that speaks\n * the wire format in `./types.ts` and `./search-ledger-wire.ts`.\n *\n * Three modes:\n * - **Ours:** point at `https://orchestrator.tangle.tools` (the host root —\n * the client appends the versioned `/v1/...` path itself; a trailing\n * `/v1` on the endpoint is tolerated and normalized away).\n * - **Self-hosted:** point at whatever URL runs the reference receiver\n * from `examples/hosted-ingest-server/`.\n * - **Off (default):** when no tenant is configured, nothing is sent.\n * Everything stays local.\n *\n * Every call retries network errors, 408, 429 and 5xx. When the server sends\n * `Retry-After`, the client waits exactly that long before the next attempt.\n */\n\nimport type { z } from 'zod'\nimport { IngestResponseSchema, IngestTracesRequestSchema } from './schemas'\nimport {\n type IngestSearchLedgerRequest,\n IngestSearchLedgerRequestSchema,\n SEARCH_LEDGER_INGEST_PATH,\n type SearchBlobPutResponse,\n SearchBlobPutResponseSchema,\n type SearchLedgerConflict,\n SearchLedgerConflictSchema,\n type SearchLedgerHead,\n SearchLedgerHeadSchema,\n searchBlobPath,\n searchLedgerHeadPath,\n} from './search-ledger-wire'\nimport {\n HOSTED_WIRE_VERSION,\n type HostedWireVersion,\n type IngestResponse,\n type IngestTracesRequest,\n type TraceSpanEvent,\n} from './types'\n\nexport interface HostedTenant {\n /** Orchestrator endpoint base URL (no trailing slash). Required. */\n endpoint: string\n /** Bearer token issued by the orchestrator. Required. */\n apiKey: string\n /** Tenant id — the orchestrator's primary key for this consumer. Required. */\n tenantId: string\n /** Optional `fetch` override (auth wrappers, custom agent). */\n fetchImpl?: typeof fetch\n /** Per-attempt timeout in ms. Default 30s. */\n timeoutMs?: number\n /** Retries on network errors, 408, 429 and 5xx. Default 2. */\n retries?: number\n}\n\n/** A search-ledger batch the store accepted, or the fork or gap it refused. */\nexport type SearchLedgerIngestOutcome =\n | { status: 'accepted'; head: SearchLedgerHead }\n | { status: 'conflict'; conflict: SearchLedgerConflict }\n\nexport interface HostedClient {\n ingestTraces(spans: TraceSpanEvent[], idempotencyKey?: string): Promise<IngestResponse>\n /** The store's head for one search; `nextSequence` 0 when it holds nothing. */\n searchLedgerHead(searchId: string, signal?: AbortSignal): Promise<SearchLedgerHead>\n ingestSearchLedger(\n request: IngestSearchLedgerRequest,\n signal?: AbortSignal,\n ): Promise<SearchLedgerIngestOutcome>\n putSearchBlob(\n sha256: `sha256:${string}`,\n bytes: Uint8Array<ArrayBuffer>,\n contentType: string,\n signal?: AbortSignal,\n ): Promise<SearchBlobPutResponse>\n readonly tenant: HostedTenant\n readonly wireVersion: HostedWireVersion\n}\n\n/** A request the server refused, after any retries. */\nexport class HostedRequestError extends Error {\n readonly status: number\n readonly body: string\n constructor(url: string, status: number, body: string) {\n super(`hosted ${url} failed (${status}): ${body.slice(0, 500)}`)\n this.name = 'HostedRequestError'\n this.status = status\n this.body = body\n }\n}\n\ninterface HostedRequest {\n method: 'GET' | 'POST' | 'PUT'\n path: string\n body?: string | Uint8Array<ArrayBuffer>\n contentType?: string\n idempotencyKey?: string\n signal?: AbortSignal\n /** Statuses returned to the caller instead of thrown. */\n expected?: readonly number[]\n}\n\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n reject(signal!.reason)\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/** `Retry-After` as milliseconds: delay-seconds or an HTTP date. Null when\n * absent or unreadable, so the caller falls back to its own backoff. */\nfunction retryAfterMs(value: string | null, now = Date.now()): number | null {\n if (value === null) return null\n const trimmed = value.trim()\n if (/^\\d+$/.test(trimmed)) return Number(trimmed) * 1000\n const at = Date.parse(trimmed)\n return Number.isFinite(at) ? Math.max(0, at - now) : null\n}\n\nfunction backoffMs(attempt: number): number {\n return 2 ** attempt * 200 + Math.random() * 200\n}\n\nfunction normalizeHostedBase(endpoint: string): string {\n return endpoint.trim().replace(/\\/+$/, '').replace(/\\/v1$/, '')\n}\n\nfunction resolveIdempotencyKey(key: string | undefined): string {\n const resolved = key ?? globalThis.crypto.randomUUID()\n if (resolved.trim().length === 0) throw new Error('idempotency key must not be blank')\n if (resolved.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n throw new Error(`idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters`)\n }\n return resolved\n}\n\nfunction isRetryable(status: number): boolean {\n return status >= 500 || status === 408 || status === 429\n}\n\nasync function send(\n tenant: HostedTenant,\n request: HostedRequest,\n): Promise<{ status: number; json: unknown; url: string }> {\n const timeoutMs = tenant.timeoutMs ?? 30_000\n const maxRetries = tenant.retries ?? 2\n const f: typeof fetch = tenant.fetchImpl ?? ((...args) => fetch(...args))\n const url = `${normalizeHostedBase(tenant.endpoint)}${request.path}`\n const headers: Record<string, string> = {\n authorization: `Bearer ${tenant.apiKey}`,\n 'x-tangle-tenant-id': tenant.tenantId,\n 'x-tangle-wire-version': HOSTED_WIRE_VERSION,\n }\n if (request.method !== 'GET') {\n headers['idempotency-key'] = resolveIdempotencyKey(request.idempotencyKey)\n headers['content-type'] = request.contentType ?? 'application/json'\n }\n\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const timeout = AbortSignal.timeout(timeoutMs)\n const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout\n let res: Response\n try {\n res = await f(url, {\n method: request.method,\n headers,\n ...(request.body === undefined ? {} : { body: request.body }),\n signal,\n })\n } catch (err) {\n if (request.signal?.aborted) throw err\n lastError = err\n if (attempt === maxRetries) throw err\n await sleep(backoffMs(attempt), request.signal)\n continue\n }\n\n if (!res.ok && !request.expected?.includes(res.status)) {\n const text = await res.text().catch(() => '')\n const error = new HostedRequestError(url, res.status, text)\n if (!isRetryable(res.status) || attempt === maxRetries) throw error\n lastError = error\n await sleep(\n retryAfterMs(res.headers.get('retry-after')) ?? backoffMs(attempt),\n request.signal,\n )\n continue\n }\n\n try {\n return { status: res.status, json: await res.json(), url }\n } catch (error) {\n throw new Error(`hosted ${url} returned invalid JSON`, { cause: error })\n }\n }\n throw lastError ?? new Error('hosted request exhausted retries')\n}\n\nfunction parseResponse<T>(schema: z.ZodType<T>, value: unknown, url: string): T {\n const parsed = schema.safeParse(value)\n if (parsed.success) return parsed.data\n const reason = parsed.error.issues\n .map((issue) => `${issue.path.map(String).join('.') || 'value'}: ${issue.message}`)\n .join('; ')\n throw new Error(`hosted ${url} returned an invalid response: ${reason}`)\n}\n\nexport function createHostedClient(tenant: HostedTenant): HostedClient {\n if (normalizeHostedBase(tenant.endpoint).length === 0) throw new Error('endpoint is required')\n if (tenant.apiKey.trim().length === 0) throw new Error('apiKey is required')\n if (tenant.tenantId.trim().length === 0) throw new Error('tenantId is required')\n if (\n tenant.timeoutMs !== undefined &&\n (!Number.isFinite(tenant.timeoutMs) || tenant.timeoutMs <= 0)\n ) {\n throw new Error('timeoutMs must be greater than 0')\n }\n if (tenant.retries !== undefined && (!Number.isInteger(tenant.retries) || tenant.retries < 0)) {\n throw new Error('retries must be a non-negative integer')\n }\n\n return {\n tenant,\n wireVersion: HOSTED_WIRE_VERSION,\n\n async ingestTraces(spans, idempotencyKey) {\n const body: IngestTracesRequest = IngestTracesRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n spans,\n })\n const res = await send(tenant, {\n method: 'POST',\n path: '/v1/ingest/traces',\n body: JSON.stringify(body),\n idempotencyKey,\n })\n return parseResponse(IngestResponseSchema, res.json, res.url)\n },\n\n async searchLedgerHead(searchId, signal) {\n const res = await send(tenant, {\n method: 'GET',\n path: searchLedgerHeadPath(searchId),\n signal,\n })\n const head = parseResponse(SearchLedgerHeadSchema, res.json, res.url)\n if (head.searchId !== searchId) {\n throw new Error(`hosted ${res.url} returned the head of search ${head.searchId}`)\n }\n return head\n },\n\n async ingestSearchLedger(request, signal) {\n const body = IngestSearchLedgerRequestSchema.parse(request)\n const last = body.lines.at(-1)!\n const res = await send(tenant, {\n method: 'POST',\n path: SEARCH_LEDGER_INGEST_PATH,\n body: JSON.stringify(body),\n // Equal key exactly when the batch is equal, so a cached response is\n // always the response to these lines.\n idempotencyKey: `search-ledger:${await sha256Hex(\n `${body.searchId}\\n${body.runKind}\\n${body.fromSequence}\\n${body.lines.length}\\n${last}`,\n )}`,\n signal,\n expected: [409],\n })\n if (res.status === 409) {\n return {\n status: 'conflict',\n conflict: parseResponse(SearchLedgerConflictSchema, res.json, res.url),\n }\n }\n return { status: 'accepted', head: parseResponse(SearchLedgerHeadSchema, res.json, res.url) }\n },\n\n async putSearchBlob(sha256, bytes, contentType, signal) {\n const res = await send(tenant, {\n method: 'PUT',\n path: searchBlobPath(sha256),\n body: bytes,\n contentType,\n idempotencyKey: `search-blob:${sha256}`,\n signal,\n })\n const stored = parseResponse(SearchBlobPutResponseSchema, res.json, res.url)\n if (stored.sha256 !== sha256) {\n throw new Error(`hosted ${res.url} acknowledged blob ${stored.sha256}, sent ${sha256}`)\n }\n return stored\n },\n }\n}\n\nasync function sha256Hex(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Build a {@link HostedTenant} from env, or `undefined` when ingest is not\n * configured, so a product wires it unconditionally and it stays off until the\n * env is set. Env precedence:\n * - endpoint: `TANGLE_INGEST_URL` → `TANGLE_ORCHESTRATOR_URL`\n * - apiKey: `TANGLE_INGEST_API_KEY` → `TANGLE_API_KEY`\n * - tenantId: `TANGLE_TENANT_ID`\n * A trailing slash on the endpoint is stripped. `overrides` win over env.\n */\nexport function hostedTenantFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedTenant | undefined {\n const env = overrides.env ?? process.env\n const endpoint = (\n overrides.endpoint ??\n env.TANGLE_INGEST_URL ??\n env.TANGLE_ORCHESTRATOR_URL\n )?.trim()\n const apiKey = (overrides.apiKey ?? env.TANGLE_INGEST_API_KEY ?? env.TANGLE_API_KEY)?.trim()\n const tenantId = (overrides.tenantId ?? env.TANGLE_TENANT_ID)?.trim()\n if (!endpoint || !apiKey || !tenantId) return undefined\n const tenant: HostedTenant = { endpoint: endpoint.replace(/\\/+$/, ''), apiKey, tenantId }\n if (overrides.fetchImpl) tenant.fetchImpl = overrides.fetchImpl\n if (overrides.timeoutMs !== undefined) tenant.timeoutMs = overrides.timeoutMs\n if (overrides.retries !== undefined) tenant.retries = overrides.retries\n return tenant\n}\n\n/** {@link createHostedClient} over {@link hostedTenantFromEnv}; `undefined`\n * when ingest is not configured. */\nexport function hostedClientFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedClient | undefined {\n const tenant = hostedTenantFromEnv(overrides)\n return tenant ? createHostedClient(tenant) : undefined\n}\n","/**\n * Ship a search ledger to a hosted store while the search runs, or after.\n *\n * The local ledger is the source of truth and the search never waits on the\n * network: the shipper reads the ledger file the recorder already made\n * durable, uploads the blobs each entry names, then posts the entries. It\n * starts from the store's head, so a restarted process, a lost response, or a\n * second shipper continues where the store's chain ends instead of resending\n * the search. A store that holds a different chain for the same search stops\n * the shipper with `SearchShipConflictError`; nothing is overwritten.\n */\n\nimport { createHash } from 'node:crypto'\nimport { open, readFile } from 'node:fs/promises'\nimport { fileURLToPath } from 'node:url'\nimport type { SearchLedgerEntry, SearchLedgerHash } from '../campaign/search-ledger-types'\nimport { createHostedClient, type HostedClient, type HostedTenant } from './client'\nimport {\n SEARCH_LEDGER_BATCH_MAX_BYTES,\n SEARCH_LEDGER_BATCH_MAX_LINES,\n type SearchLedgerConflict,\n type SearchLedgerHead,\n type SearchRunKind,\n searchLedgerArtifactRefs,\n} from './search-ledger-wire'\nimport { HOSTED_WIRE_VERSION } from './types'\n\nexport interface SearchShipOptions {\n tenant: HostedTenant\n ledger: { path: string; searchId: string }\n runKind: SearchRunKind\n /** `full` (default) uploads every blob an entry names; `digests` ships the\n * entries alone, so the store holds refs and digests without content. */\n content?: 'full' | 'digests'\n signal?: AbortSignal\n}\n\n/** A blob an entry names that was not uploaded, and why. */\nexport interface SearchShipMissingBlob {\n sha256: SearchLedgerHash\n uri: string\n reason: string\n}\n\nexport interface SearchShipResult {\n searchId: string\n /** The store's head after the last accepted batch. */\n head: SearchLedgerHead\n /** Local complete lines, which the store now holds when `head` reaches them. */\n localLines: number\n /** Ledger lines posted, counting resends after a gap. */\n linesPosted: number\n batches: number\n /** Resends after the store answered `sequence_gap`. */\n gapResends: number\n blobs: {\n content: 'full' | 'digests'\n uploaded: number\n stored: number\n masked: number\n withheld: number\n missing: SearchShipMissingBlob[]\n }\n}\n\n/** The store holds a different chain for this search. */\nexport class SearchShipConflictError extends Error {\n readonly conflict: SearchLedgerConflict\n constructor(conflict: SearchLedgerConflict) {\n super(\n `search ${conflict.head.searchId}: ${conflict.error}: ${conflict.message} (store head ${conflict.head.nextSequence} ${conflict.head.headHash ?? 'empty'})`,\n )\n this.name = 'SearchShipConflictError'\n this.conflict = conflict\n }\n}\n\n/** Ship every complete line of the ledger file now, then return. */\nexport async function shipSearchLedger(options: SearchShipOptions): Promise<SearchShipResult> {\n return new SearchLedgerTail(options).ship()\n}\n\nexport interface SearchShipper {\n /** Ship what is in the file now without waiting for the next tick. */\n flush(): Promise<SearchShipResult>\n /** Stop tailing, ship the rest of the file, and return the final result. */\n stop(): Promise<SearchShipResult>\n /** The last transient failure, cleared by the next successful tick. */\n readonly lastError: Error | null\n}\n\n/**\n * Tail the ledger: ship new lines every `intervalMs` (default 2 s) until\n * `stop()`. A transient failure is kept on `lastError` and retried on the next\n * tick; a conflict stops tailing and is thrown by `stop()`.\n */\nexport function startSearchShipper(\n options: SearchShipOptions & { intervalMs?: number },\n): SearchShipper {\n const tail = new SearchLedgerTail(options)\n const intervalMs = options.intervalMs ?? 2000\n const stopping = new AbortController()\n let lastError: Error | null = null\n let conflict: SearchShipConflictError | null = null\n let running: Promise<unknown> = Promise.resolve()\n\n const tick = (): Promise<unknown> => {\n running = running.then(async () => {\n if (conflict) return\n try {\n await tail.ship()\n lastError = null\n } catch (error) {\n if (error instanceof SearchShipConflictError) conflict = error\n else lastError = error instanceof Error ? error : new Error(String(error))\n }\n })\n return running\n }\n\n const loop = (async () => {\n while (!stopping.signal.aborted && !conflict) {\n await tick()\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, intervalMs)\n stopping.signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer)\n resolve()\n },\n { once: true },\n )\n })\n }\n })()\n\n return {\n get lastError() {\n return lastError\n },\n async flush() {\n await tick()\n if (conflict) throw conflict\n if (lastError) throw lastError\n return tail.result()\n },\n async stop() {\n stopping.abort()\n await loop\n await running\n if (conflict) throw conflict\n return tail.ship()\n },\n }\n}\n\n/** One full batch of lines with their newlines, plus a byte to see where a\n * maximal line ends. */\nconst READ_CHUNK_BYTES = SEARCH_LEDGER_BATCH_MAX_BYTES + SEARCH_LEDGER_BATCH_MAX_LINES + 1\n\ninterface LocalLine {\n text: string\n entry: SearchLedgerEntry\n bytes: number\n}\n\nclass SearchLedgerTail {\n private readonly client: HostedClient\n private readonly options: SearchShipOptions\n private readonly content: 'full' | 'digests'\n /** Where the store's chain ends, and the byte offset of that line locally. */\n private head: SearchLedgerHead | null = null\n private offset = 0\n private localLines = 0\n private readonly uploaded = new Set<string>()\n private readonly missing = new Map<string, SearchShipMissingBlob>()\n private readonly counts = {\n linesPosted: 0,\n batches: 0,\n gapResends: 0,\n uploaded: 0,\n stored: 0,\n masked: 0,\n withheld: 0,\n }\n\n constructor(options: SearchShipOptions) {\n this.options = options\n this.content = options.content ?? 'full'\n this.client = createHostedClient(options.tenant)\n }\n\n result(): SearchShipResult {\n const { linesPosted, batches, gapResends, uploaded, stored, masked, withheld } = this.counts\n return {\n searchId: this.options.ledger.searchId,\n head: this.head ?? {\n searchId: this.options.ledger.searchId,\n nextSequence: 0,\n headHash: null,\n },\n localLines: this.localLines,\n linesPosted,\n batches,\n gapResends,\n blobs: {\n content: this.content,\n uploaded,\n stored,\n masked,\n withheld,\n missing: [...this.missing.values()],\n },\n }\n }\n\n async ship(): Promise<SearchShipResult> {\n const { signal } = this.options\n if (this.head === null) {\n await this.syncTo(await this.client.searchLedgerHead(this.options.ledger.searchId, signal))\n }\n for (;;) {\n const lines = await this.readChunk(this.offset, this.head!)\n if (lines.length === 0) return this.result()\n const batch = takeBatch(lines)\n if (this.content === 'full') await this.uploadBlobs(batch)\n const fromSequence = this.head!.nextSequence\n const outcome = await this.client.ingestSearchLedger(\n {\n wireVersion: HOSTED_WIRE_VERSION,\n searchId: this.options.ledger.searchId,\n runKind: this.options.runKind,\n fromSequence,\n lines: batch.map((line) => line.text),\n },\n signal,\n )\n this.counts.batches++\n this.counts.linesPosted += batch.length\n if (outcome.status === 'conflict') {\n if (outcome.conflict.error === 'chain_conflict') {\n throw new SearchShipConflictError(outcome.conflict)\n }\n this.counts.gapResends++\n await this.syncTo(outcome.conflict.head)\n continue\n }\n const last = batch.at(-1)!.entry\n if (\n outcome.head.nextSequence < last.sequence + 1 ||\n (outcome.head.nextSequence === last.sequence + 1 &&\n outcome.head.headHash !== last.entryHash)\n ) {\n throw new Error(\n `store acknowledged sequence ${fromSequence}..${last.sequence} with head ${outcome.head.nextSequence} ${outcome.head.headHash}`,\n )\n }\n await this.syncTo(outcome.head)\n }\n }\n\n /** Move the cursor to the store's head, checking that the local ledger holds\n * the same entry there. A different entry is a fork; a store ahead of the\n * local file holds lines this ledger never wrote. */\n private async syncTo(head: SearchLedgerHead): Promise<void> {\n if (head.searchId !== this.options.ledger.searchId) {\n throw new Error(`store answered for search ${head.searchId}`)\n }\n const fork = (message: string) =>\n new SearchShipConflictError({ error: 'chain_conflict', message, head })\n const empty: SearchLedgerHead = { searchId: head.searchId, nextSequence: 0, headHash: null }\n const forward = this.head !== null && head.nextSequence >= this.head.nextSequence\n let offset = forward ? this.offset : 0\n let cursor = forward ? this.head! : empty\n while (cursor.nextSequence < head.nextSequence) {\n const lines = await this.readChunk(offset, cursor)\n if (lines.length === 0) {\n throw fork(\n `the store holds ${head.nextSequence} entries; the local ledger holds ${cursor.nextSequence}`,\n )\n }\n const take = Math.min(lines.length, head.nextSequence - cursor.nextSequence)\n for (let index = 0; index < take; index++) offset += lines[index]!.bytes\n const last = lines[take - 1]!.entry\n cursor = {\n searchId: head.searchId,\n nextSequence: last.sequence + 1,\n headHash: last.entryHash,\n }\n }\n if (cursor.headHash !== head.headHash) {\n throw fork(`the store's entry ${head.nextSequence - 1} differs from the local ledger's`)\n }\n this.offset = offset\n this.head = head\n }\n\n /** The complete lines in one read chunk from `offset`, checked to continue\n * the chain at `head`. A chunk holds at least one full batch. */\n private async readChunk(offset: number, head: SearchLedgerHead): Promise<LocalLine[]> {\n const bytes = await readRange(this.options.ledger.path, offset, READ_CHUNK_BYTES)\n const lines: LocalLine[] = []\n let start = 0\n let expectedSequence = head.nextSequence\n let previousHash = head.headHash\n for (;;) {\n const newline = bytes.indexOf(0x0a, start)\n // A line without its newline is still being written, or continues in\n // the next chunk.\n if (newline < 0) break\n const text = bytes.toString('utf8', start, newline)\n const entry = JSON.parse(text) as SearchLedgerEntry\n if (\n entry.searchId !== this.options.ledger.searchId ||\n entry.sequence !== expectedSequence ||\n entry.previousHash !== previousHash\n ) {\n throw new Error(\n `${this.options.ledger.path} line ${expectedSequence + 1} does not continue the chain at sequence ${expectedSequence}`,\n )\n }\n lines.push({ text, entry, bytes: newline + 1 - start })\n expectedSequence++\n previousHash = entry.entryHash\n start = newline + 1\n }\n if (lines.length === 0 && bytes.byteLength === READ_CHUNK_BYTES) {\n throw new Error(\n `${this.options.ledger.path} line ${expectedSequence + 1} is longer than ${SEARCH_LEDGER_BATCH_MAX_BYTES} bytes; one request carries at most that`,\n )\n }\n this.localLines = Math.max(this.localLines, expectedSequence)\n return lines\n }\n\n private async uploadBlobs(batch: LocalLine[]): Promise<void> {\n for (const line of batch) {\n for (const ref of searchLedgerArtifactRefs(line.entry.event)) {\n if (this.uploaded.has(ref.sha256) || this.missing.has(ref.sha256)) continue\n const bytes = await readBlob(ref.uri)\n if (typeof bytes === 'string') {\n this.missing.set(ref.sha256, { sha256: ref.sha256, uri: ref.uri, reason: bytes })\n continue\n }\n const digest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n if (digest !== ref.sha256 || bytes.byteLength !== ref.byteLength) {\n this.missing.set(ref.sha256, {\n sha256: ref.sha256,\n uri: ref.uri,\n reason: `local bytes are ${digest} (${bytes.byteLength} bytes), not the ref's ${ref.sha256} (${ref.byteLength} bytes)`,\n })\n continue\n }\n const stored = await this.client.putSearchBlob(\n ref.sha256,\n new Uint8Array(bytes),\n ref.uri.endsWith('.json') ? 'application/json' : 'application/octet-stream',\n this.options.signal,\n )\n this.uploaded.add(ref.sha256)\n this.counts.uploaded++\n this.counts[stored.state]++\n }\n }\n }\n}\n\n/** The longest prefix of `lines` within one request's limits. */\nfunction takeBatch(lines: LocalLine[]): LocalLine[] {\n const batch: LocalLine[] = []\n let bytes = 0\n for (const line of lines) {\n const size = line.bytes - 1\n if (size > SEARCH_LEDGER_BATCH_MAX_BYTES) {\n throw new Error(\n `ledger line ${line.entry.sequence} holds ${size} bytes; one request carries at most ${SEARCH_LEDGER_BATCH_MAX_BYTES}`,\n )\n }\n if (\n batch.length === SEARCH_LEDGER_BATCH_MAX_LINES ||\n bytes + size > SEARCH_LEDGER_BATCH_MAX_BYTES\n )\n break\n batch.push(line)\n bytes += size\n }\n return batch\n}\n\n/** Up to `limit` bytes of the file from `offset`; empty before the recorder\n * created the file. */\nasync function readRange(path: string, offset: number, limit: number): Promise<Buffer> {\n let handle: Awaited<ReturnType<typeof open>>\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT' && offset === 0) return Buffer.alloc(0)\n throw error\n }\n try {\n const { size } = await handle.stat()\n if (size < offset) throw new Error(`${path} shrank below byte ${offset}`)\n const bytes = Buffer.alloc(Math.min(limit, size - offset))\n let read = 0\n while (read < bytes.byteLength) {\n const { bytesRead } = await handle.read(bytes, read, bytes.byteLength - read, offset + read)\n if (bytesRead === 0) break\n read += bytesRead\n }\n return bytes.subarray(0, read)\n } finally {\n await handle.close()\n }\n}\n\n/** The bytes at a `file:` ref, or why there are none. */\nasync function readBlob(uri: string): Promise<Buffer | string> {\n if (!uri.startsWith('file:'))\n return `the shipper reads only file: refs, not ${uri.split(':')[0]}:`\n try {\n return await readFile(fileURLToPath(uri))\n } catch (error) {\n return `unreadable: ${(error as NodeJS.ErrnoException).code ?? String(error)}`\n }\n}\n\n/**\n * Run a ship that must never fail its caller, such as the one a loop runs at\n * its end. A failure, a store short of the local ledger, or a blob that did\n * not upload is logged with the command that resumes it.\n */\nexport async function shipBestEffort(\n ship: () => Promise<SearchShipResult>,\n ledgerPath: string,\n): Promise<SearchShipResult | undefined> {\n const resume = `agent-eval search ship ${ledgerPath}`\n try {\n const shipped = await ship()\n if (shipped.head.nextSequence < shipped.localLines) {\n console.warn(\n `[agent-eval] search ${shipped.searchId}: the store holds ${shipped.head.nextSequence} of ${shipped.localLines} ledger entries; resume with ${resume}`,\n )\n }\n if (shipped.blobs.missing.length > 0) {\n console.warn(\n `[agent-eval] search ${shipped.searchId}: ${shipped.blobs.missing.length} blob(s) were not uploaded, first: ${shipped.blobs.missing[0]!.reason}`,\n )\n }\n return shipped\n } catch (error) {\n console.warn(\n `[agent-eval] search ledger ship failed (continuing; resume with ${resume}): ${error instanceof Error ? error.message : String(error)}`,\n )\n return undefined\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,sBAAsB;;;ACdnC,MAAM,eAAe,EAAE,OAAO,CAAC,CAAC,OAAO;AACvC,MAAM,qBAAqB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY;AACxD,MAAM,iBAAiB,EACpB,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,QAAQ,UAAU,MAAM,KAAK,CAAC,CAAC,SAAS,GAAG,mBAAmB;AACjE,MAAM,iBAAiB,EAAE,MAAM;CAAC,EAAE,OAAO;CAAG;CAAc,EAAE,QAAQ;AAAC,CAAC;AACtE,MAAM,aAAa,EAAE,OAAO,EAAE,OAAO,GAAG,cAAc;AACtD,MAAM,aAAa;AAEnB,MAAa,0BAAwD,EAClE,OAAO,CAAC,CACR,MAAM,qBAAqB,6CAA6C,CAAC,CACzE,QAAQ,UAAU,OAAO,KAAK,KAAK,YAAY,wCAAwC;AAE1F,MAAM,4BAA4B,EAC/B,OAAO;CACN,cAAc;CACd,MAAM;CACN,YAAY,WAAW,SAAS;AAClC,CAAC,CAAC,CACD,OAAO;AAEV,MAAa,uBAAkD,EAC5D,OAAO;CACN,SAAS;CACT,QAAQ;CACR,cAAc,eAAe,SAAS;CACtC,MAAM;CACN,mBAAmB;CACnB,iBAAiB;CACjB;CACA,QAAQ,EAAE,MAAM,yBAAyB,CAAC,CAAC,SAAS;CACpD,QAAQ,EACL,OAAO;EACN,MAAM,EAAE,KAAK;GAAC;GAA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7 +1,7 @@
|
|
|
1
1
|
import "./paired-tests-jbwPdSz5.js";
|
|
2
|
-
import { r as minimumPairsForPairedDeltaTest } from "./paired-promotion-decision-
|
|
2
|
+
import { r as minimumPairsForPairedDeltaTest } from "./paired-promotion-decision-BN6IQTiu.js";
|
|
3
3
|
import { a as SearchLedgerError } from "./search-ledger-file-DY0AXX3W.js";
|
|
4
|
-
import { x as estimateNode } from "./search-kernel-
|
|
4
|
+
import { x as estimateNode } from "./search-kernel-BIXWM7YV.js";
|
|
5
5
|
//#region src/campaign/search-summary.ts
|
|
6
6
|
/**
|
|
7
7
|
* The agent's view of a search: the same projection a human reads.
|
|
@@ -130,4 +130,4 @@ function formatEstimate(estimate) {
|
|
|
130
130
|
//#endregion
|
|
131
131
|
export { searchProposerView as n, renderSearchSummary as t };
|
|
132
132
|
|
|
133
|
-
//# sourceMappingURL=search-summary-
|
|
133
|
+
//# sourceMappingURL=search-summary-nwrtXxC_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search-summary-BV5uehLd.js","names":[],"sources":["../src/campaign/search-summary.ts"],"sourcesContent":["/**\n * The agent's view of a search: the same projection a human reads.\n *\n * `renderSearchSummary` turns a `SearchStateView` into compact text — the\n * leading nodes with their estimates, the most recently discarded ideas with\n * why they were discarded, and a log of recent proposals — as AIDE's journal\n * summary does for its own search. `agent-eval search show <ledger>` prints\n * the same text for a terminal; `runOptimization` puts it on every\n * `ProposeContext` a proposer receives.\n *\n * `searchProposerView` is the train-only read `ProposeContext.train` carries.\n * It has no parameter that can select another split, so a proposer built on\n * it cannot reach the selection or test split even by mistake: the sealed\n * splits (§6.6 of the search-tree design) are unreachable by construction,\n * not by convention.\n */\n\nimport { minimumPairsForPairedDeltaTest } from '../paired-delta-test'\nimport { BOOTSTRAP_GATE_MIN_N } from '../statistics'\nimport { estimateNode } from './estimate-node'\nimport { SearchLedgerError } from './search-ledger-errors'\nimport type { NodeEstimate, SearchSplit } from './search-ledger-types'\nimport type { SearchNode, SearchScoredCell, SearchStateView, SearchUnitScore } from './search-state'\n\nconst DESCRIPTIVE_FROM = minimumPairsForPairedDeltaTest(0.95)\n\n/** The proposer's own read of a search: its node's cells on the train split,\n * the only split a proposer may ever see. */\nexport interface SearchProposerView {\n readonly searchId: string\n readonly direction: 'maximize' | 'minimize'\n /** `nodeId`'s scored train cells. Unscored cells (errored, cancelled or in\n * flight) are absent, never zero. */\n scoredCells(nodeId: string): readonly SearchScoredCell[]\n /** Per-unit train-split means of `nodeId`, in unitId order. */\n unitScores(nodeId: string): readonly SearchUnitScore[]\n}\n\n/** The train-only view `ProposeContext.train` carries. */\nexport function searchProposerView(state: SearchStateView): SearchProposerView {\n const header = state.header\n if (!header) throw new SearchLedgerError(`search ${state.searchId} has not been opened`)\n return {\n searchId: state.searchId,\n direction: header.objective.direction,\n scoredCells: (nodeId) => state.scoredCells(nodeId, 'train'),\n unitScores: (nodeId) => state.unitScores(nodeId, 'train'),\n }\n}\n\nexport interface SearchSummaryOptions {\n /**\n * The split every estimate in the summary is computed on. A proposer's\n * context must always pass `'train'`: the selection and test splits stay\n * unread by anything a proposer's text can reach. The CLI passes the\n * search's own ranking split, `'selection'` when the search declares one\n * else `'train'`, matching `searchPolicyView`.\n */\n split: SearchSplit\n /** Nodes shown under \"Leading\" and under \"Recently discarded\". Default 5. */\n limit?: number\n}\n\n/**\n * `SearchState` as compact text: a header line with the search's shape and\n * spend, the leading nodes against the root with their estimates, the most\n * recently discarded nodes with the measurement that discarded them, and a\n * log of recent proposals (operator and label — the ledger's inline,\n * redacted summary of each rationale; the full rationale is a blob this\n * function never reads, so it stays a pure, I/O-free projection of the\n * state already in hand).\n */\nexport function renderSearchSummary(state: SearchStateView, options: SearchSummaryOptions): string {\n const header = state.header\n if (!header) return `search ${state.searchId}: not yet opened`\n const limit = options.limit ?? 5\n if (limit < 1 || !Number.isInteger(limit)) {\n throw new SearchLedgerError(\n `renderSearchSummary: limit must be a positive integer, got ${limit}`,\n )\n }\n const split = options.split\n const direction = header.objective.direction\n const root = state.rootNodeId\n const lines: string[] = [headerLine(state), spendLine(state), statusLine(state)]\n\n if (root === null) {\n lines.push('', 'No nodes yet.')\n return lines.join('\\n')\n }\n\n const others = state.nodes().filter((node) => node.nodeId !== root)\n const estimated = others\n .filter((node) => node.status !== 'invalid')\n .map((node) => ({ node, estimate: estimateNode(state, node.nodeId, { against: root, split }) }))\n\n const leading = estimated\n .filter(({ estimate }) => estimate.delta !== null)\n .sort((a, b) => signed(b.estimate, direction) - signed(a.estimate, direction))\n .slice(0, limit)\n lines.push('', `Leading nodes (vs root, ${split} split):`)\n if (leading.length === 0) lines.push(' none measured yet')\n for (const { node, estimate } of leading)\n lines.push(` ${nodeLine(node)}: ${formatEstimate(estimate)}`)\n\n const discarded = others\n .filter(\n (node) => node.status === 'pruned' || node.status === 'rejected' || node.status === 'invalid',\n )\n .sort((a, b) => b.updatedSequence - a.updatedSequence)\n .slice(0, limit)\n lines.push('', 'Recently discarded:')\n if (discarded.length === 0) lines.push(' none yet')\n for (const node of discarded) lines.push(` ${nodeLine(node)}: ${discardLine(node)}`)\n\n const recent = [...state.edges()].reverse().slice(0, limit)\n lines.push('', 'Recent proposals:')\n if (recent.length === 0) lines.push(' none yet')\n for (const edge of recent) {\n const childId = edge.childNodeId\n const label = edge.label.length > 0 ? edge.label : '(no label)'\n lines.push(` ${edge.operator} → ${childId}: ${label}`)\n }\n\n return lines.join('\\n')\n}\n\nfunction headerLine(state: SearchStateView): string {\n const header = state.header!\n return `search ${state.searchId} — ${header.subject} — ${header.objective.direction} ${header.objective.metric}`\n}\n\nfunction spendLine(state: SearchStateView): string {\n const { audit } = state\n const known = audit.spend.knownUsd.toFixed(2)\n const floor = audit.spend.floorUsd.toFixed(2)\n const unknown = audit.spend.unknownCostCells\n const floorPart =\n unknown > 0\n ? ` + floor $${floor} across ${unknown} unknown-cost cell${unknown === 1 ? '' : 's'}`\n : ''\n return ` ${audit.nodes} nodes · ${audit.cells.settled} settled cells (${audit.cells.open} open) · $${known} known${floorPart}`\n}\n\nfunction statusLine(state: SearchStateView): string {\n if (!state.closed) return ' status: open'\n const claim = state.closed.claim\n const claimText =\n claim === null\n ? ''\n : claim.decision === 'ship'\n ? ` · claim: ship ${claim.selected}`\n : ` · claim: ${claim.decision}`\n return ` status: closed (${state.closed.reason})${claimText}`\n}\n\nfunction nodeLine(node: SearchNode): string {\n const rung = node.status === 'advanced' ? ` rung ${node.rung}` : ''\n return `${node.nodeId} (${node.status ?? 'undecided'}${rung})`\n}\n\nfunction discardLine(node: SearchNode): string {\n const decision = node.decisions.at(-1)\n if (!decision) return 'no decision recorded'\n const basis = decision.basis === null ? 'no measured basis' : formatEstimate(decision.basis)\n return `${basis} — ${decision.rule}: ${decision.reason}`\n}\n\n/** `estimate.delta` in the objective's own units; positive is always better. */\nfunction signed(estimate: NodeEstimate, direction: 'maximize' | 'minimize'): number {\n if (estimate.delta === null) return Number.NEGATIVE_INFINITY\n return direction === 'maximize' ? estimate.delta : -estimate.delta\n}\n\n/** The display rules of search-tree-design §6.4: no whisker below 6 shared\n * units, a dashed descriptive interval with its exact sign p from 6 to 19,\n * a decision-grade whisker from `BOOTSTRAP_GATE_MIN_N`. */\nfunction formatEstimate(estimate: NodeEstimate): string {\n const unit = (n: number) => `${n} unit${n === 1 ? '' : 's'}`\n if (estimate.method === 'none') return `unknown (${unit(estimate.pairs)})`\n if (estimate.indeterminate)\n return `no measurable difference (indeterminate, ${unit(estimate.pairs)})`\n const delta =\n estimate.delta === null ? 'null' : (estimate.delta >= 0 ? '+' : '') + estimate.delta.toFixed(4)\n if (estimate.method === 'insufficient') {\n return `Δ=${delta} (${estimate.pairs} of ${DESCRIPTIVE_FROM} units, insufficient)`\n }\n const interval = estimate.interval\n ? ` [${estimate.interval[0].toFixed(4)}, ${estimate.interval[1].toFixed(4)}]`\n : ''\n if (estimate.method === 'descriptive') {\n const signP = estimate.exactSignP === null ? 'null' : estimate.exactSignP.toPrecision(3)\n return `Δ=${delta}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Y,KAAK,SAAS,KAAK,EAAE;CACxE,IAAI,SAAS,eACX,OAAO,4CAA4C,KAAK,SAAS,KAAK,EAAE;CAC1E,MAAM,QACJ,SAAS,UAAU,OAAO,UAAU,SAAS,SAAS,IAAI,MAAM,MAAM,SAAS,MAAM,QAAQ,CAAC;CAChG,IAAI,SAAS,WAAW,gBACtB,OAAO,KAAK,MAAM,IAAI,SAAS,MAAM,MAAM,iBAAiB;CAE9D,MAAM,WAAW,SAAS,WACtB,KAAK,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,KACzE;CACJ,IAAI,SAAS,WAAW,eAEtB,OAAO,KAAK,QAAQ,SAAS,kBADf,SAAS,eAAe,OAAO,SAAS,SAAS,WAAW,YAAY,CAAC,EAClC,IAAI,KAAK,SAAS,KAAK,EAAE;CAEhF,OAAO,KAAK,QAAQ,SAAS,IAAI,KAAK,SAAS,KAAK,EAAE;AACxD"}
|
|
1
|
+
{"version":3,"file":"search-summary-nwrtXxC_.js","names":[],"sources":["../src/campaign/search-summary.ts"],"sourcesContent":["/**\n * The agent's view of a search: the same projection a human reads.\n *\n * `renderSearchSummary` turns a `SearchStateView` into compact text — the\n * leading nodes with their estimates, the most recently discarded ideas with\n * why they were discarded, and a log of recent proposals — as AIDE's journal\n * summary does for its own search. `agent-eval search show <ledger>` prints\n * the same text for a terminal; `runOptimization` puts it on every\n * `ProposeContext` a proposer receives.\n *\n * `searchProposerView` is the train-only read `ProposeContext.train` carries.\n * It has no parameter that can select another split, so a proposer built on\n * it cannot reach the selection or test split even by mistake: the sealed\n * splits (§6.6 of the search-tree design) are unreachable by construction,\n * not by convention.\n */\n\nimport { minimumPairsForPairedDeltaTest } from '../paired-delta-test'\nimport { BOOTSTRAP_GATE_MIN_N } from '../statistics'\nimport { estimateNode } from './estimate-node'\nimport { SearchLedgerError } from './search-ledger-errors'\nimport type { NodeEstimate, SearchSplit } from './search-ledger-types'\nimport type { SearchNode, SearchScoredCell, SearchStateView, SearchUnitScore } from './search-state'\n\nconst DESCRIPTIVE_FROM = minimumPairsForPairedDeltaTest(0.95)\n\n/** The proposer's own read of a search: its node's cells on the train split,\n * the only split a proposer may ever see. */\nexport interface SearchProposerView {\n readonly searchId: string\n readonly direction: 'maximize' | 'minimize'\n /** `nodeId`'s scored train cells. Unscored cells (errored, cancelled or in\n * flight) are absent, never zero. */\n scoredCells(nodeId: string): readonly SearchScoredCell[]\n /** Per-unit train-split means of `nodeId`, in unitId order. */\n unitScores(nodeId: string): readonly SearchUnitScore[]\n}\n\n/** The train-only view `ProposeContext.train` carries. */\nexport function searchProposerView(state: SearchStateView): SearchProposerView {\n const header = state.header\n if (!header) throw new SearchLedgerError(`search ${state.searchId} has not been opened`)\n return {\n searchId: state.searchId,\n direction: header.objective.direction,\n scoredCells: (nodeId) => state.scoredCells(nodeId, 'train'),\n unitScores: (nodeId) => state.unitScores(nodeId, 'train'),\n }\n}\n\nexport interface SearchSummaryOptions {\n /**\n * The split every estimate in the summary is computed on. A proposer's\n * context must always pass `'train'`: the selection and test splits stay\n * unread by anything a proposer's text can reach. The CLI passes the\n * search's own ranking split, `'selection'` when the search declares one\n * else `'train'`, matching `searchPolicyView`.\n */\n split: SearchSplit\n /** Nodes shown under \"Leading\" and under \"Recently discarded\". Default 5. */\n limit?: number\n}\n\n/**\n * `SearchState` as compact text: a header line with the search's shape and\n * spend, the leading nodes against the root with their estimates, the most\n * recently discarded nodes with the measurement that discarded them, and a\n * log of recent proposals (operator and label — the ledger's inline,\n * redacted summary of each rationale; the full rationale is a blob this\n * function never reads, so it stays a pure, I/O-free projection of the\n * state already in hand).\n */\nexport function renderSearchSummary(state: SearchStateView, options: SearchSummaryOptions): string {\n const header = state.header\n if (!header) return `search ${state.searchId}: not yet opened`\n const limit = options.limit ?? 5\n if (limit < 1 || !Number.isInteger(limit)) {\n throw new SearchLedgerError(\n `renderSearchSummary: limit must be a positive integer, got ${limit}`,\n )\n }\n const split = options.split\n const direction = header.objective.direction\n const root = state.rootNodeId\n const lines: string[] = [headerLine(state), spendLine(state), statusLine(state)]\n\n if (root === null) {\n lines.push('', 'No nodes yet.')\n return lines.join('\\n')\n }\n\n const others = state.nodes().filter((node) => node.nodeId !== root)\n const estimated = others\n .filter((node) => node.status !== 'invalid')\n .map((node) => ({ node, estimate: estimateNode(state, node.nodeId, { against: root, split }) }))\n\n const leading = estimated\n .filter(({ estimate }) => estimate.delta !== null)\n .sort((a, b) => signed(b.estimate, direction) - signed(a.estimate, direction))\n .slice(0, limit)\n lines.push('', `Leading nodes (vs root, ${split} split):`)\n if (leading.length === 0) lines.push(' none measured yet')\n for (const { node, estimate } of leading)\n lines.push(` ${nodeLine(node)}: ${formatEstimate(estimate)}`)\n\n const discarded = others\n .filter(\n (node) => node.status === 'pruned' || node.status === 'rejected' || node.status === 'invalid',\n )\n .sort((a, b) => b.updatedSequence - a.updatedSequence)\n .slice(0, limit)\n lines.push('', 'Recently discarded:')\n if (discarded.length === 0) lines.push(' none yet')\n for (const node of discarded) lines.push(` ${nodeLine(node)}: ${discardLine(node)}`)\n\n const recent = [...state.edges()].reverse().slice(0, limit)\n lines.push('', 'Recent proposals:')\n if (recent.length === 0) lines.push(' none yet')\n for (const edge of recent) {\n const childId = edge.childNodeId\n const label = edge.label.length > 0 ? edge.label : '(no label)'\n lines.push(` ${edge.operator} → ${childId}: ${label}`)\n }\n\n return lines.join('\\n')\n}\n\nfunction headerLine(state: SearchStateView): string {\n const header = state.header!\n return `search ${state.searchId} — ${header.subject} — ${header.objective.direction} ${header.objective.metric}`\n}\n\nfunction spendLine(state: SearchStateView): string {\n const { audit } = state\n const known = audit.spend.knownUsd.toFixed(2)\n const floor = audit.spend.floorUsd.toFixed(2)\n const unknown = audit.spend.unknownCostCells\n const floorPart =\n unknown > 0\n ? ` + floor $${floor} across ${unknown} unknown-cost cell${unknown === 1 ? '' : 's'}`\n : ''\n return ` ${audit.nodes} nodes · ${audit.cells.settled} settled cells (${audit.cells.open} open) · $${known} known${floorPart}`\n}\n\nfunction statusLine(state: SearchStateView): string {\n if (!state.closed) return ' status: open'\n const claim = state.closed.claim\n const claimText =\n claim === null\n ? ''\n : claim.decision === 'ship'\n ? ` · claim: ship ${claim.selected}`\n : ` · claim: ${claim.decision}`\n return ` status: closed (${state.closed.reason})${claimText}`\n}\n\nfunction nodeLine(node: SearchNode): string {\n const rung = node.status === 'advanced' ? ` rung ${node.rung}` : ''\n return `${node.nodeId} (${node.status ?? 'undecided'}${rung})`\n}\n\nfunction discardLine(node: SearchNode): string {\n const decision = node.decisions.at(-1)\n if (!decision) return 'no decision recorded'\n const basis = decision.basis === null ? 'no measured basis' : formatEstimate(decision.basis)\n return `${basis} — ${decision.rule}: ${decision.reason}`\n}\n\n/** `estimate.delta` in the objective's own units; positive is always better. */\nfunction signed(estimate: NodeEstimate, direction: 'maximize' | 'minimize'): number {\n if (estimate.delta === null) return Number.NEGATIVE_INFINITY\n return direction === 'maximize' ? estimate.delta : -estimate.delta\n}\n\n/** The display rules of search-tree-design §6.4: no whisker below 6 shared\n * units, a dashed descriptive interval with its exact sign p from 6 to 19,\n * a decision-grade whisker from `BOOTSTRAP_GATE_MIN_N`. */\nfunction formatEstimate(estimate: NodeEstimate): string {\n const unit = (n: number) => `${n} unit${n === 1 ? '' : 's'}`\n if (estimate.method === 'none') return `unknown (${unit(estimate.pairs)})`\n if (estimate.indeterminate)\n return `no measurable difference (indeterminate, ${unit(estimate.pairs)})`\n const delta =\n estimate.delta === null ? 'null' : (estimate.delta >= 0 ? '+' : '') + estimate.delta.toFixed(4)\n if (estimate.method === 'insufficient') {\n return `Δ=${delta} (${estimate.pairs} of ${DESCRIPTIVE_FROM} units, insufficient)`\n }\n const interval = estimate.interval\n ? ` [${estimate.interval[0].toFixed(4)}, ${estimate.interval[1].toFixed(4)}]`\n : ''\n if (estimate.method === 'descriptive') {\n const signP = estimate.exactSignP === null ? 'null' : estimate.exactSignP.toPrecision(3)\n return `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OAAO,YAAY,KAAK,SAAS,KAAK,EAAE;CACxE,IAAI,SAAS,eACX,OAAO,4CAA4C,KAAK,SAAS,KAAK,EAAE;CAC1E,MAAM,QACJ,SAAS,UAAU,OAAO,UAAU,SAAS,SAAS,IAAI,MAAM,MAAM,SAAS,MAAM,QAAQ,CAAC;CAChG,IAAI,SAAS,WAAW,gBACtB,OAAO,KAAK,MAAM,IAAI,SAAS,MAAM,MAAM,iBAAiB;CAE9D,MAAM,WAAW,SAAS,WACtB,KAAK,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,SAAS,SAAS,EAAE,CAAC,QAAQ,CAAC,EAAE,KACzE;CACJ,IAAI,SAAS,WAAW,eAEtB,OAAO,KAAK,QAAQ,SAAS,kBADf,SAAS,eAAe,OAAO,SAAS,SAAS,WAAW,YAAY,CAAC,EAClC,IAAI,KAAK,SAAS,KAAK,EAAE;CAEhF,OAAO,KAAK,QAAQ,SAAS,IAAI,KAAK,SAAS,KAAK,EAAE;AACxD"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { i as CostLedger } from "./cost-ledger-_IbkejCF.js";
|
|
2
2
|
import { p as Mutex } from "./journal-DvKCvjty.js";
|
|
3
3
|
import { c as extractJsonPayload } from "./llm-client-v968tWw8.js";
|
|
4
|
-
import {
|
|
4
|
+
import { N as RawAnalystFindingSchema } from "./kind-factory-ivTx6koH.js";
|
|
5
5
|
import { n as paidJsonChat, t as paidChat } from "./chat-json-call-BJJdJ2uj.js";
|
|
6
|
-
import { n as decodeRawFindingArray } from "./dspy-rlm-engine-
|
|
6
|
+
import { n as decodeRawFindingArray } from "./dspy-rlm-engine-BpaKVKJA.js";
|
|
7
7
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import { dirname } from "node:path";
|
|
@@ -777,4 +777,4 @@ async function runSemanticConceptJudge(input, options) {
|
|
|
777
777
|
//#endregion
|
|
778
778
|
export { diffFindings as a, defaultIsMaterial as i, runSemanticConceptJudge as n, createChatTraceEngine as o, FindingsStore as r, SEMANTIC_CONCEPT_JUDGE_VERSION as t };
|
|
779
779
|
|
|
780
|
-
//# sourceMappingURL=semantic-concept-judge-
|
|
780
|
+
//# sourceMappingURL=semantic-concept-judge-BQxZyXdN.js.map
|