@tangle-network/agent-runtime 0.82.0 → 0.84.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.
Files changed (88) hide show
  1. package/README.md +4 -0
  2. package/dist/agent.d.ts +5 -3
  3. package/dist/agent.js +7 -7
  4. package/dist/agent.js.map +1 -1
  5. package/dist/analyst-loop.d.ts +3 -2
  6. package/dist/analyst-loop.js +2 -2
  7. package/dist/{chunk-A7LZR5DT.js → chunk-4WXGK6GV.js} +2 -2
  8. package/dist/chunk-4WXGK6GV.js.map +1 -0
  9. package/dist/{chunk-UZ5SODU7.js → chunk-5IBQAPVB.js} +1 -1
  10. package/dist/chunk-5IBQAPVB.js.map +1 -0
  11. package/dist/{chunk-5JAUQZQA.js → chunk-7LO5GMAO.js} +1 -1
  12. package/dist/chunk-7LO5GMAO.js.map +1 -0
  13. package/dist/{chunk-H7IBHAFT.js → chunk-BZF3KQ6G.js} +1 -1
  14. package/dist/chunk-BZF3KQ6G.js.map +1 -0
  15. package/dist/{chunk-WIR4HOOJ.js → chunk-DPEUKJRO.js} +1 -1
  16. package/dist/chunk-DPEUKJRO.js.map +1 -0
  17. package/dist/{chunk-DJQFJEOD.js → chunk-G7HQI6DB.js} +2 -2
  18. package/dist/chunk-G7HQI6DB.js.map +1 -0
  19. package/dist/{chunk-GRAGM4MC.js → chunk-NURIQBJQ.js} +1 -1
  20. package/dist/chunk-NURIQBJQ.js.map +1 -0
  21. package/dist/{chunk-FNMGYYSS.js → chunk-SGKPNBXE.js} +1 -1
  22. package/dist/chunk-SGKPNBXE.js.map +1 -0
  23. package/dist/{chunk-SRGV56W4.js → chunk-UD4BHQMI.js} +2 -2
  24. package/dist/{chunk-SRGV56W4.js.map → chunk-UD4BHQMI.js.map} +1 -1
  25. package/dist/{chunk-JYURIKPF.js → chunk-UJW6EVNY.js} +503 -218
  26. package/dist/chunk-UJW6EVNY.js.map +1 -0
  27. package/dist/{chunk-LWGVVP2C.js → chunk-VNOOH22O.js} +2 -2
  28. package/dist/chunk-VNOOH22O.js.map +1 -0
  29. package/dist/{chunk-KSGHI53L.js → chunk-XBSWWF6A.js} +6 -6
  30. package/dist/chunk-XBSWWF6A.js.map +1 -0
  31. package/dist/{chunk-CO2KBPRE.js → chunk-XN5TIJGP.js} +1011 -1011
  32. package/dist/chunk-XN5TIJGP.js.map +1 -0
  33. package/dist/{chunk-NBV35BR6.js → chunk-YEJR7IXO.js} +1 -1
  34. package/dist/chunk-YEJR7IXO.js.map +1 -0
  35. package/dist/{chunk-C2FZ6GR6.js → chunk-YPA5MLVE.js} +2 -2
  36. package/dist/chunk-YPA5MLVE.js.map +1 -0
  37. package/dist/{coordination-BI9tpcmF.d.ts → coordination-CuDLO8wj.d.ts} +53 -32
  38. package/dist/environment-provider.d.ts +2 -2
  39. package/dist/environment-provider.js +1 -1
  40. package/dist/{improvement-adapter-CioiEE2z.d.ts → improvement-adapter-CDR8QNVM.d.ts} +3 -0
  41. package/dist/index.d.ts +163 -49
  42. package/dist/index.js +43 -13
  43. package/dist/index.js.map +1 -1
  44. package/dist/intelligence.d.ts +14 -8
  45. package/dist/intelligence.js +1 -1
  46. package/dist/intelligence.js.map +1 -1
  47. package/dist/{kb-gate-CuzMYGYM.d.ts → kb-gate-CwHO0vz6.d.ts} +4 -2
  48. package/dist/lifecycle.d.ts +2 -2
  49. package/dist/lifecycle.js +3 -3
  50. package/dist/{local-harness-DU7yV6mG.d.ts → local-harness-sI0S_XNA.d.ts} +2 -1
  51. package/dist/{loop-runner-bin-CBkLsyFg.d.ts → loop-runner-bin-hQDUL8Ld.d.ts} +28 -13
  52. package/dist/loop-runner-bin.d.ts +7 -7
  53. package/dist/loop-runner-bin.js +10 -10
  54. package/dist/loops.d.ts +257 -48
  55. package/dist/loops.js +9 -7
  56. package/dist/mcp/bin.js +8 -8
  57. package/dist/mcp/bin.js.map +1 -1
  58. package/dist/mcp/index.d.ts +44 -38
  59. package/dist/mcp/index.js +11 -11
  60. package/dist/mcp/index.js.map +1 -1
  61. package/dist/{mcp-serve-verifier-BvMAV_8U.d.ts → mcp-serve-verifier-FL7-ZEb_.d.ts} +8 -3
  62. package/dist/{openai-tools-B-3v06BE.d.ts → openai-tools-BnrOmGjN.d.ts} +7 -4
  63. package/dist/platform.d.ts +4 -0
  64. package/dist/platform.js.map +1 -1
  65. package/dist/profiles.d.ts +36 -23
  66. package/dist/profiles.js +2 -2
  67. package/dist/profiles.js.map +1 -1
  68. package/dist/{router-client-D6Ocf4jG.d.ts → router-client-r8y_VFVM.d.ts} +1 -0
  69. package/dist/{substrate-rNj6TDc3.d.ts → substrate-DO2GHNg2.d.ts} +5 -3
  70. package/dist/{types-By9LXllv.d.ts → types-Driepl87.d.ts} +3 -2
  71. package/dist/{types-BF-MEsQB.d.ts → types-ESeMOj94.d.ts} +26 -11
  72. package/dist/{worktree-fanout-D9Z2dMS9.d.ts → worktree-fanout-D6xR2CIA.d.ts} +16 -10
  73. package/dist/{worktree-harness-Dx8XULW3.d.ts → worktree-harness-CX_McRLp.d.ts} +11 -8
  74. package/package.json +3 -3
  75. package/dist/chunk-5JAUQZQA.js.map +0 -1
  76. package/dist/chunk-A7LZR5DT.js.map +0 -1
  77. package/dist/chunk-C2FZ6GR6.js.map +0 -1
  78. package/dist/chunk-CO2KBPRE.js.map +0 -1
  79. package/dist/chunk-DJQFJEOD.js.map +0 -1
  80. package/dist/chunk-FNMGYYSS.js.map +0 -1
  81. package/dist/chunk-GRAGM4MC.js.map +0 -1
  82. package/dist/chunk-H7IBHAFT.js.map +0 -1
  83. package/dist/chunk-JYURIKPF.js.map +0 -1
  84. package/dist/chunk-KSGHI53L.js.map +0 -1
  85. package/dist/chunk-LWGVVP2C.js.map +0 -1
  86. package/dist/chunk-NBV35BR6.js.map +0 -1
  87. package/dist/chunk-UZ5SODU7.js.map +0 -1
  88. package/dist/chunk-WIR4HOOJ.js.map +0 -1
@@ -15,7 +15,7 @@ import {
15
15
  settledToIteration,
16
16
  supervise,
17
17
  withDriverExecutor
18
- } from "./chunk-CO2KBPRE.js";
18
+ } from "./chunk-XN5TIJGP.js";
19
19
  import {
20
20
  addTokenUsage,
21
21
  isAbortError,
@@ -23,12 +23,12 @@ import {
23
23
  sleep,
24
24
  stringifySafe,
25
25
  zeroTokenUsage
26
- } from "./chunk-H7IBHAFT.js";
26
+ } from "./chunk-BZF3KQ6G.js";
27
27
  import {
28
28
  AnalystError,
29
29
  PlannerError,
30
30
  ValidationError
31
- } from "./chunk-NBV35BR6.js";
31
+ } from "./chunk-YEJR7IXO.js";
32
32
 
33
33
  // src/runtime/index.ts
34
34
  import { computeFindingId, makeFinding as makeFinding2 } from "@tangle-network/agent-eval";
@@ -604,6 +604,480 @@ function deterministicCompletion(check) {
604
604
  };
605
605
  }
606
606
 
607
+ // src/runtime/define-leaderboard.ts
608
+ import { execFileSync } from "child_process";
609
+ import { mkdirSync, writeFileSync } from "fs";
610
+ import { tmpdir } from "os";
611
+ import { join } from "path";
612
+ import {
613
+ CODING_HARNESSES,
614
+ expandProfileAxes,
615
+ harnessAxisOf
616
+ } from "@tangle-network/agent-eval";
617
+ import {
618
+ runProfileMatrix
619
+ } from "@tangle-network/agent-eval/campaign";
620
+ import { collectAgentResponseText } from "@tangle-network/sandbox";
621
+
622
+ // src/runtime/report-usage.ts
623
+ function reportLoopUsage(cost, result, source = "loop") {
624
+ cost.observe(result.costUsd, source);
625
+ cost.observeTokens(result.tokenUsage);
626
+ }
627
+
628
+ // src/runtime/loop-dispatch.ts
629
+ function campaignTraceToLoopEmitter(trace) {
630
+ return {
631
+ emit(event) {
632
+ trace.span(event.kind, { runId: event.runId, timestamp: event.timestamp, ...event.payload }).end();
633
+ }
634
+ };
635
+ }
636
+ async function runLoopForCell(opts, scenario, profile, ctx) {
637
+ const loopOptions = opts.toLoopOptions(scenario, profile);
638
+ return runLoopWithCampaignContext(opts, loopOptions, ctx);
639
+ }
640
+ async function runLoopWithCampaignContext(opts, loopOptions, ctx) {
641
+ const result = await runLoop({
642
+ ...loopOptions,
643
+ ctx: {
644
+ sandboxClient: opts.sandboxClient,
645
+ signal: ctx.signal,
646
+ traceEmitter: opts.forwardTrace === false ? void 0 : campaignTraceToLoopEmitter(ctx.trace)
647
+ }
648
+ });
649
+ reportLoopUsage(ctx.cost, result, opts.costSource ?? "loop");
650
+ const toArtifact = opts.toArtifact ?? ((r) => r.winner?.output);
651
+ return toArtifact(result);
652
+ }
653
+ function loopCampaignDispatch(opts) {
654
+ return (scenario, ctx) => runLoopWithCampaignContext(opts, opts.toLoopOptions(scenario), ctx);
655
+ }
656
+ function loopDispatch(opts) {
657
+ return (profile, scenario, ctx) => runLoopForCell(opts, scenario, profile, ctx);
658
+ }
659
+
660
+ // src/runtime/inline-sandbox-client.ts
661
+ function isAsyncIterable(v) {
662
+ return typeof v === "object" && v !== null && Symbol.asyncIterator in v;
663
+ }
664
+ async function settle(exec, task, signal) {
665
+ const r = exec.execute(task, signal);
666
+ if (isAsyncIterable(r)) {
667
+ for await (const _ of r) {
668
+ }
669
+ return exec.resultArtifact();
670
+ }
671
+ return r;
672
+ }
673
+ function inlineSandboxClient(factory) {
674
+ let seq = 0;
675
+ return {
676
+ async create(options) {
677
+ const id = `inline-${seq++}`;
678
+ const createOptions = options;
679
+ return {
680
+ id,
681
+ async *streamPrompt(message) {
682
+ const controller = new AbortController();
683
+ const spec = { profile: { name: id }, harness: null };
684
+ const exec = factory(spec, { signal: controller.signal, seams: { createOptions } });
685
+ try {
686
+ const artifact = await settle(exec, message, controller.signal);
687
+ const out = artifact.out;
688
+ const tokensIn = artifact.spent.tokens.input;
689
+ const tokensOut = artifact.spent.tokens.output;
690
+ const costUsd = artifact.spent.usd;
691
+ if (tokensIn || tokensOut || costUsd) {
692
+ yield {
693
+ type: "llm_call",
694
+ data: { tokensIn, tokensOut, costUsd }
695
+ };
696
+ }
697
+ yield {
698
+ type: "result",
699
+ data: {
700
+ finalText: out?.content ?? "",
701
+ tokenUsage: {
702
+ inputTokens: tokensIn,
703
+ outputTokens: tokensOut
704
+ },
705
+ costUsd
706
+ }
707
+ };
708
+ } finally {
709
+ await exec.teardown("brutalKill").catch(() => {
710
+ });
711
+ }
712
+ },
713
+ async delete() {
714
+ }
715
+ };
716
+ }
717
+ };
718
+ }
719
+
720
+ // src/runtime/resolve-sandbox-client.ts
721
+ function resolveSandboxClient(opts) {
722
+ switch (opts.backend) {
723
+ case "sandbox": {
724
+ if (!opts.sandboxClient) {
725
+ throw new Error("resolveSandboxClient: backend 'sandbox' requires opts.sandboxClient");
726
+ }
727
+ return opts.sandboxClient;
728
+ }
729
+ case "bridge": {
730
+ const bridge = opts.bridge;
731
+ if (!bridge?.bearer || !bridge.model) {
732
+ throw new Error(
733
+ "resolveSandboxClient: backend 'bridge' requires bridge.bearer and bridge.model"
734
+ );
735
+ }
736
+ return inlineSandboxClient(
737
+ createExecutor({
738
+ backend: "bridge",
739
+ bridgeUrl: bridge.url ?? "http://127.0.0.1:3355",
740
+ bridgeBearer: bridge.bearer,
741
+ model: bridge.model,
742
+ timeoutMs: bridge.timeoutMs
743
+ })
744
+ );
745
+ }
746
+ case "router": {
747
+ const router = opts.router;
748
+ if (!router?.baseUrl || !router.key || !router.model) {
749
+ throw new Error(
750
+ "resolveSandboxClient: backend 'router' requires router.baseUrl, router.key and router.model"
751
+ );
752
+ }
753
+ return inlineSandboxClient(
754
+ createExecutor({
755
+ backend: "router",
756
+ routerBaseUrl: router.baseUrl,
757
+ routerKey: router.key,
758
+ model: router.model
759
+ })
760
+ );
761
+ }
762
+ }
763
+ }
764
+
765
+ // src/runtime/steering-drivers.ts
766
+ function decideUntilValidOrCapped(history, maxIterations) {
767
+ if (history.some((it) => it.verdict?.valid)) return "pick-winner";
768
+ return history.length < maxIterations ? "refine" : "fail";
769
+ }
770
+ function naiveDriver(options) {
771
+ const { continuation, applyContinuation, maxIterations, name = "naive" } = options;
772
+ return {
773
+ name,
774
+ plan(task, history) {
775
+ if (history.length === 0) return Promise.resolve([task]);
776
+ const last = history[history.length - 1];
777
+ if (last?.verdict?.valid) return Promise.resolve([]);
778
+ if (history.length >= maxIterations) return Promise.resolve([]);
779
+ return Promise.resolve([applyContinuation(task, continuation)]);
780
+ },
781
+ decide(history) {
782
+ return decideUntilValidOrCapped(history, maxIterations);
783
+ },
784
+ // Pure refine topology (one task per round) — render the steer move.
785
+ describePlan() {
786
+ return { kind: "refine", rationale: "naive fixed continuation (no grade signal)" };
787
+ }
788
+ };
789
+ }
790
+ function dumbDriver(options) {
791
+ const { onPass, onFail, applyContinuation, maxIterations, name = "dumb" } = options;
792
+ return {
793
+ name,
794
+ plan(task, history) {
795
+ if (history.length === 0) return Promise.resolve([task]);
796
+ const last = history[history.length - 1];
797
+ const passed = last?.verdict?.valid === true;
798
+ if (passed) return Promise.resolve([]);
799
+ if (history.length >= maxIterations) return Promise.resolve([]);
800
+ const continuation = passed ? onPass : onFail;
801
+ return Promise.resolve([applyContinuation(task, continuation)]);
802
+ },
803
+ decide(history) {
804
+ return decideUntilValidOrCapped(history, maxIterations);
805
+ },
806
+ describePlan() {
807
+ return { kind: "refine", rationale: "dumb pass/fail-only continuation (no grader findings)" };
808
+ }
809
+ };
810
+ }
811
+
812
+ // src/runtime/define-leaderboard.ts
813
+ function argOf(argv, name) {
814
+ const i = argv.indexOf(`--${name}`);
815
+ if (i >= 0 && i + 1 < argv.length) return argv[i + 1];
816
+ return void 0;
817
+ }
818
+ function splitList(v) {
819
+ if (v === void 0) return void 0;
820
+ const parts = v.split(",").map((s) => s.trim()).filter(Boolean);
821
+ return parts.length > 0 ? parts : void 0;
822
+ }
823
+ function withSnapshot(model, snapshot) {
824
+ return model.includes("@") ? model : `${model}@${snapshot}`;
825
+ }
826
+ function bareModel(model) {
827
+ return model.split("@")[0] ?? model;
828
+ }
829
+ function gitSha() {
830
+ try {
831
+ return execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
832
+ } catch {
833
+ return "unknown";
834
+ }
835
+ }
836
+ function normalizeScore(s) {
837
+ return typeof s === "number" ? { composite: s } : s;
838
+ }
839
+ function defineLeaderboard(spec) {
840
+ const caseId = (c) => {
841
+ const id = spec.caseId ? spec.caseId(c) : c.id;
842
+ if (typeof id !== "string" || id.length === 0) {
843
+ throw new Error(
844
+ `defineLeaderboard(${spec.name}): every case needs a stable string id \u2014 give cases an \`id\` property or supply spec.caseId`
845
+ );
846
+ }
847
+ return id;
848
+ };
849
+ const selectCases = (ids) => {
850
+ if (!ids) return spec.cases;
851
+ const byId = new Map(spec.cases.map((c) => [caseId(c), c]));
852
+ return ids.map((id) => {
853
+ const c = byId.get(id);
854
+ if (c === void 0) {
855
+ throw new Error(
856
+ `defineLeaderboard(${spec.name}): unknown case "${id}" (have: ${[...byId.keys()].join(", ")})`
857
+ );
858
+ }
859
+ return c;
860
+ });
861
+ };
862
+ const scoreJudge = {
863
+ name: `${spec.name}-score`,
864
+ dimensions: [{ key: "composite", description: `${spec.name} case score` }],
865
+ score({ artifact, scenario }) {
866
+ const s = normalizeScore(spec.score(artifact, scenario.case));
867
+ return {
868
+ composite: s.composite,
869
+ dimensions: { composite: s.composite, ...s.dimensions },
870
+ notes: s.notes ?? ""
871
+ };
872
+ }
873
+ };
874
+ async function run(argv = process.argv.slice(2)) {
875
+ const args = {};
876
+ for (const name of [
877
+ "backend",
878
+ "harnesses",
879
+ "models",
880
+ "cases",
881
+ "shots",
882
+ "reps",
883
+ "model-snapshot",
884
+ "run-dir",
885
+ "export-dir"
886
+ ]) {
887
+ args[name] = argOf(argv, name);
888
+ }
889
+ for (const [name, flag] of Object.entries(spec.flags ?? {})) {
890
+ args[name] = argOf(argv, name) ?? flag.default;
891
+ }
892
+ const backendName = args.backend ?? "sandbox";
893
+ const shots = Number(args.shots ?? spec.shots ?? 1);
894
+ const reps = Number(args.reps ?? spec.reps ?? 1);
895
+ const snapshot = args["model-snapshot"] ?? "leaderboard";
896
+ const runDir = args["run-dir"] ?? join(tmpdir(), `leaderboard-${spec.name}-${Date.now()}-${process.pid}`);
897
+ const exportDir = args["export-dir"] ?? join(runDir, "export");
898
+ mkdirSync(runDir, { recursive: true });
899
+ const cases = selectCases(splitList(args.cases));
900
+ if (cases.length === 0) throw new Error(`defineLeaderboard(${spec.name}): no cases to run`);
901
+ const scenarios = cases.map((c) => ({
902
+ id: caseId(c),
903
+ kind: spec.name,
904
+ case: c
905
+ }));
906
+ const harnesses = splitList(args.harnesses) ?? spec.axis?.harnesses ?? CODING_HARNESSES;
907
+ const rawModels = splitList(args.models) ?? spec.axis?.models ?? (spec.baseProfile?.model?.default !== void 0 ? [spec.baseProfile.model.default] : void 0);
908
+ if (!rawModels || rawModels.length === 0) {
909
+ throw new Error(
910
+ `defineLeaderboard(${spec.name}): no models \u2014 pass --models, set spec.axis.models, or give spec.baseProfile a model.default`
911
+ );
912
+ }
913
+ const models = rawModels.map((m) => withSnapshot(m, snapshot));
914
+ const base = spec.baseProfile ?? { name: spec.name, model: { default: bareModel(models[0] ?? "") } };
915
+ const profiles = expandProfileAxes({ base, harnesses, models });
916
+ const ctx = {
917
+ name: spec.name,
918
+ backend: backendName,
919
+ runDir,
920
+ exportDir,
921
+ args,
922
+ harnesses,
923
+ models,
924
+ caseIds: scenarios.map((s) => s.id),
925
+ shots,
926
+ reps
927
+ };
928
+ const backends = {
929
+ sandbox: () => {
930
+ throw new Error(
931
+ `defineLeaderboard(${spec.name}): the 'sandbox' backend needs your product's real SandboxClient \u2014 supply spec.backends.sandbox (e.g. () => new SandboxClient({ apiKey, baseUrl }))`
932
+ );
933
+ },
934
+ "cli-bridge": () => {
935
+ const bearer = process.env.BRIDGE_BEARER ?? process.env.CLI_BRIDGE_BEARER;
936
+ if (!bearer) {
937
+ throw new Error(
938
+ `defineLeaderboard(${spec.name}): backend 'cli-bridge' needs BRIDGE_BEARER or CLI_BRIDGE_BEARER set`
939
+ );
940
+ }
941
+ return resolveSandboxClient({
942
+ backend: "bridge",
943
+ bridge: {
944
+ url: process.env.CLI_BRIDGE_URL,
945
+ bearer,
946
+ model: bareModel(models[0] ?? ""),
947
+ timeoutMs: 9e5
948
+ }
949
+ });
950
+ },
951
+ ...spec.backends
952
+ };
953
+ const makeClient = backends[backendName];
954
+ if (!makeClient) {
955
+ throw new Error(
956
+ `defineLeaderboard(${spec.name}): unknown backend "${backendName}" (have: ${Object.keys(backends).join(", ")})`
957
+ );
958
+ }
959
+ const sandboxClient = makeClient();
960
+ const promptById = /* @__PURE__ */ new Map();
961
+ for (const s of scenarios) promptById.set(s.id, await spec.prompt(s.case));
962
+ const promptOf = (s) => {
963
+ const p = promptById.get(s.id);
964
+ if (p === void 0)
965
+ throw new Error(`defineLeaderboard(${spec.name}): no prompt for case "${s.id}"`);
966
+ return p;
967
+ };
968
+ let shotNonce = 0;
969
+ const dispatch = spec.dispatch ?? loopDispatch({
970
+ sandboxClient,
971
+ toLoopOptions: (scenario, profile) => {
972
+ const axis = harnessAxisOf(profile);
973
+ const modelId = bareModel(axis?.model ?? models[0] ?? "");
974
+ return {
975
+ // naiveDriver = the no-signal retry floor: re-run the same case as
976
+ // an independent attempt until one scores (>0) or the shot cap.
977
+ driver: naiveDriver({
978
+ continuation: "",
979
+ applyContinuation: (task) => task,
980
+ maxIterations: shots
981
+ }),
982
+ agentRun: {
983
+ profile,
984
+ taskToPrompt: (s) => `${promptOf(s)}
985
+
986
+ <!-- independent-attempt:${shotNonce++} -->`,
987
+ ...axis ? {
988
+ sandboxOverrides: {
989
+ backend: {
990
+ type: axis.harness,
991
+ model: { ...spec.modelBackend, model: modelId }
992
+ }
993
+ }
994
+ } : {}
995
+ },
996
+ output: {
997
+ parse: (events) => {
998
+ spec.onCellEvents?.(events, scenario.case);
999
+ return spec.parseOutput ? spec.parseOutput(events, scenario.case) : collectAgentResponseText(events) ?? "";
1000
+ }
1001
+ },
1002
+ validator: {
1003
+ validate: async (output) => {
1004
+ const s = normalizeScore(spec.score(output, scenario.case));
1005
+ return { valid: s.composite > 0, score: s.composite };
1006
+ }
1007
+ },
1008
+ task: scenario,
1009
+ maxIterations: shots
1010
+ };
1011
+ }
1012
+ });
1013
+ await spec.setup?.(ctx);
1014
+ try {
1015
+ const result = await runProfileMatrix({
1016
+ profiles,
1017
+ scenarios,
1018
+ dispatch,
1019
+ judges: spec.judges ?? [scoreJudge],
1020
+ runDir,
1021
+ commitSha: gitSha(),
1022
+ reps,
1023
+ ...spec.matrix
1024
+ });
1025
+ if (spec.export) {
1026
+ await spec.export(result, ctx);
1027
+ } else {
1028
+ mkdirSync(exportDir, { recursive: true });
1029
+ writeFileSync(join(runDir, "matrix-result.json"), `${JSON.stringify(result, null, 2)}
1030
+ `);
1031
+ const table = renderLeaderboardMarkdown(
1032
+ leaderboard(result.records, { title: spec.name, meta: { backend: backendName } })
1033
+ );
1034
+ writeFileSync(join(exportDir, "leaderboard.md"), table);
1035
+ console.log(table);
1036
+ }
1037
+ return result;
1038
+ } finally {
1039
+ await spec.teardown?.(ctx);
1040
+ }
1041
+ }
1042
+ function toBenchmarkAdapter() {
1043
+ return {
1044
+ name: spec.name,
1045
+ async preflight() {
1046
+ const seen = /* @__PURE__ */ new Set();
1047
+ for (const c of spec.cases) {
1048
+ const id = caseId(c);
1049
+ if (seen.has(id)) {
1050
+ throw new Error(`defineLeaderboard(${spec.name}): duplicate case id "${id}"`);
1051
+ }
1052
+ seen.add(id);
1053
+ }
1054
+ },
1055
+ async loadTasks(opts) {
1056
+ const selected = selectCases(opts?.ids);
1057
+ const limited = opts?.limit !== void 0 ? selected.slice(0, opts.limit) : selected;
1058
+ return Promise.all(
1059
+ limited.map(async (c) => ({
1060
+ id: caseId(c),
1061
+ prompt: await spec.prompt(c),
1062
+ metadata: { case: c }
1063
+ }))
1064
+ );
1065
+ },
1066
+ async judge(task, artifact) {
1067
+ const [c] = selectCases([task.id]);
1068
+ if (c === void 0)
1069
+ throw new Error(`defineLeaderboard(${spec.name}): no case "${task.id}"`);
1070
+ const s = normalizeScore(spec.score(artifact, c));
1071
+ return { resolved: s.composite > 0, score: s.composite, detail: s.notes };
1072
+ },
1073
+ async goldArtifact() {
1074
+ return void 0;
1075
+ }
1076
+ };
1077
+ }
1078
+ return { run, toBenchmarkAdapter };
1079
+ }
1080
+
607
1081
  // src/runtime/observe.ts
608
1082
  import { makeFinding } from "@tangle-network/agent-eval";
609
1083
  var observerId = "observe/trace";
@@ -815,9 +1289,9 @@ async function harvestCorpus(opts) {
815
1289
  // src/runtime/in-process-sandbox-client.ts
816
1290
  import { mkdtempSync, rmSync } from "fs";
817
1291
  import { mkdir, readFile, writeFile } from "fs/promises";
818
- import { tmpdir } from "os";
819
- import { dirname, join } from "path";
820
- function isAsyncIterable(v) {
1292
+ import { tmpdir as tmpdir2 } from "os";
1293
+ import { dirname, join as join2 } from "path";
1294
+ function isAsyncIterable2(v) {
821
1295
  return typeof v === "object" && v !== null && Symbol.asyncIterator in v;
822
1296
  }
823
1297
  function inProcessSandboxClient(options) {
@@ -827,15 +1301,15 @@ function inProcessSandboxClient(options) {
827
1301
  async create(_options) {
828
1302
  const current = seq++;
829
1303
  const id = typeof idOption === "function" ? idOption(current) : idOption ?? `in-process-${current}`;
830
- const boxWorkdir = workdirPrefix !== void 0 ? mkdtempSync(join(tmpdir(), `${workdirPrefix}-`)) : void 0;
1304
+ const boxWorkdir = workdirPrefix !== void 0 ? mkdtempSync(join2(tmpdir2(), `${workdirPrefix}-`)) : void 0;
831
1305
  let round = 0;
832
1306
  const fsMembers = boxWorkdir !== void 0 ? {
833
1307
  fs: {
834
1308
  async read(path) {
835
- return readFile(join(boxWorkdir, path), "utf8");
1309
+ return readFile(join2(boxWorkdir, path), "utf8");
836
1310
  },
837
1311
  async write(path, content) {
838
- const abs = join(boxWorkdir, path);
1312
+ const abs = join2(boxWorkdir, path);
839
1313
  await mkdir(dirname(abs), { recursive: true });
840
1314
  await writeFile(abs, content, "utf8");
841
1315
  }
@@ -868,7 +1342,7 @@ function inProcessSandboxClient(options) {
868
1342
  const ctx = { round, workdir: boxWorkdir, signal };
869
1343
  round += 1;
870
1344
  const produced = await onPrompt(prompt, ctx);
871
- if (isAsyncIterable(produced)) {
1345
+ if (isAsyncIterable2(produced)) {
872
1346
  for await (const ev of produced) yield ev;
873
1347
  } else {
874
1348
  for (const ev of produced) yield ev;
@@ -884,104 +1358,6 @@ function inProcessSandboxClient(options) {
884
1358
  };
885
1359
  }
886
1360
 
887
- // src/runtime/inline-sandbox-client.ts
888
- function isAsyncIterable2(v) {
889
- return typeof v === "object" && v !== null && Symbol.asyncIterator in v;
890
- }
891
- async function settle(exec, task, signal) {
892
- const r = exec.execute(task, signal);
893
- if (isAsyncIterable2(r)) {
894
- for await (const _ of r) {
895
- }
896
- return exec.resultArtifact();
897
- }
898
- return r;
899
- }
900
- function inlineSandboxClient(factory) {
901
- let seq = 0;
902
- return {
903
- async create(options) {
904
- const id = `inline-${seq++}`;
905
- const createOptions = options;
906
- return {
907
- id,
908
- async *streamPrompt(message) {
909
- const controller = new AbortController();
910
- const spec = { profile: { name: id }, harness: null };
911
- const exec = factory(spec, { signal: controller.signal, seams: { createOptions } });
912
- try {
913
- const artifact = await settle(exec, message, controller.signal);
914
- const out = artifact.out;
915
- const tokensIn = artifact.spent.tokens.input;
916
- const tokensOut = artifact.spent.tokens.output;
917
- const costUsd = artifact.spent.usd;
918
- if (tokensIn || tokensOut || costUsd) {
919
- yield {
920
- type: "llm_call",
921
- data: { tokensIn, tokensOut, costUsd }
922
- };
923
- }
924
- yield {
925
- type: "result",
926
- data: {
927
- finalText: out?.content ?? "",
928
- tokenUsage: {
929
- inputTokens: tokensIn,
930
- outputTokens: tokensOut
931
- },
932
- costUsd
933
- }
934
- };
935
- } finally {
936
- await exec.teardown("brutalKill").catch(() => {
937
- });
938
- }
939
- },
940
- async delete() {
941
- }
942
- };
943
- }
944
- };
945
- }
946
-
947
- // src/runtime/report-usage.ts
948
- function reportLoopUsage(cost, result, source = "loop") {
949
- cost.observe(result.costUsd, source);
950
- cost.observeTokens(result.tokenUsage);
951
- }
952
-
953
- // src/runtime/loop-dispatch.ts
954
- function campaignTraceToLoopEmitter(trace) {
955
- return {
956
- emit(event) {
957
- trace.span(event.kind, { runId: event.runId, timestamp: event.timestamp, ...event.payload }).end();
958
- }
959
- };
960
- }
961
- async function runLoopForCell(opts, scenario, profile, ctx) {
962
- const loopOptions = opts.toLoopOptions(scenario, profile);
963
- return runLoopWithCampaignContext(opts, loopOptions, ctx);
964
- }
965
- async function runLoopWithCampaignContext(opts, loopOptions, ctx) {
966
- const result = await runLoop({
967
- ...loopOptions,
968
- ctx: {
969
- sandboxClient: opts.sandboxClient,
970
- signal: ctx.signal,
971
- traceEmitter: opts.forwardTrace === false ? void 0 : campaignTraceToLoopEmitter(ctx.trace)
972
- }
973
- });
974
- reportLoopUsage(ctx.cost, result, opts.costSource ?? "loop");
975
- const toArtifact = opts.toArtifact ?? ((r) => r.winner?.output);
976
- return toArtifact(result);
977
- }
978
- function loopCampaignDispatch(opts) {
979
- return (scenario, ctx) => runLoopWithCampaignContext(opts, opts.toLoopOptions(scenario), ctx);
980
- }
981
- function loopDispatch(opts) {
982
- return (profile, scenario, ctx) => runLoopForCell(opts, scenario, profile, ctx);
983
- }
984
-
985
1361
  // src/runtime/mcp-environment.ts
986
1362
  async function rpc(endpoint, body) {
987
1363
  let lastErr;
@@ -2220,51 +2596,6 @@ function promotionGate(opts) {
2220
2596
  };
2221
2597
  }
2222
2598
 
2223
- // src/runtime/resolve-sandbox-client.ts
2224
- function resolveSandboxClient(opts) {
2225
- switch (opts.backend) {
2226
- case "sandbox": {
2227
- if (!opts.sandboxClient) {
2228
- throw new Error("resolveSandboxClient: backend 'sandbox' requires opts.sandboxClient");
2229
- }
2230
- return opts.sandboxClient;
2231
- }
2232
- case "bridge": {
2233
- const bridge = opts.bridge;
2234
- if (!bridge?.bearer || !bridge.model) {
2235
- throw new Error(
2236
- "resolveSandboxClient: backend 'bridge' requires bridge.bearer and bridge.model"
2237
- );
2238
- }
2239
- return inlineSandboxClient(
2240
- createExecutor({
2241
- backend: "bridge",
2242
- bridgeUrl: bridge.url ?? "http://127.0.0.1:3355",
2243
- bridgeBearer: bridge.bearer,
2244
- model: bridge.model,
2245
- timeoutMs: bridge.timeoutMs
2246
- })
2247
- );
2248
- }
2249
- case "router": {
2250
- const router = opts.router;
2251
- if (!router?.baseUrl || !router.key || !router.model) {
2252
- throw new Error(
2253
- "resolveSandboxClient: backend 'router' requires router.baseUrl, router.key and router.model"
2254
- );
2255
- }
2256
- return inlineSandboxClient(
2257
- createExecutor({
2258
- backend: "router",
2259
- routerBaseUrl: router.baseUrl,
2260
- routerKey: router.key,
2261
- model: router.model
2262
- })
2263
- );
2264
- }
2265
- }
2266
- }
2267
-
2268
2599
  // src/runtime/run-benchmark.ts
2269
2600
  import { pairedBootstrap as pairedBootstrap2, paretoFrontier } from "@tangle-network/agent-eval";
2270
2601
 
@@ -3267,56 +3598,9 @@ function errorMessage(error) {
3267
3598
  return error instanceof Error ? error.message : String(error);
3268
3599
  }
3269
3600
 
3270
- // src/runtime/steering-drivers.ts
3271
- function decideUntilValidOrCapped(history, maxIterations) {
3272
- if (history.some((it) => it.verdict?.valid)) return "pick-winner";
3273
- return history.length < maxIterations ? "refine" : "fail";
3274
- }
3275
- function naiveDriver(options) {
3276
- const { continuation, applyContinuation, maxIterations, name = "naive" } = options;
3277
- return {
3278
- name,
3279
- plan(task, history) {
3280
- if (history.length === 0) return Promise.resolve([task]);
3281
- const last = history[history.length - 1];
3282
- if (last?.verdict?.valid) return Promise.resolve([]);
3283
- if (history.length >= maxIterations) return Promise.resolve([]);
3284
- return Promise.resolve([applyContinuation(task, continuation)]);
3285
- },
3286
- decide(history) {
3287
- return decideUntilValidOrCapped(history, maxIterations);
3288
- },
3289
- // Pure refine topology (one task per round) — render the steer move.
3290
- describePlan() {
3291
- return { kind: "refine", rationale: "naive fixed continuation (no grade signal)" };
3292
- }
3293
- };
3294
- }
3295
- function dumbDriver(options) {
3296
- const { onPass, onFail, applyContinuation, maxIterations, name = "dumb" } = options;
3297
- return {
3298
- name,
3299
- plan(task, history) {
3300
- if (history.length === 0) return Promise.resolve([task]);
3301
- const last = history[history.length - 1];
3302
- const passed = last?.verdict?.valid === true;
3303
- if (passed) return Promise.resolve([]);
3304
- if (history.length >= maxIterations) return Promise.resolve([]);
3305
- const continuation = passed ? onPass : onFail;
3306
- return Promise.resolve([applyContinuation(task, continuation)]);
3307
- },
3308
- decide(history) {
3309
- return decideUntilValidOrCapped(history, maxIterations);
3310
- },
3311
- describePlan() {
3312
- return { kind: "refine", rationale: "dumb pass/fail-only continuation (no grader findings)" };
3313
- }
3314
- };
3315
- }
3316
-
3317
3601
  // src/runtime/strategy-author.ts
3318
- import { mkdirSync, writeFileSync } from "fs";
3319
- import { join as join2 } from "path";
3602
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3603
+ import { join as join3 } from "path";
3320
3604
  var strategyAuthorContract = `
3321
3605
  You author an OPTIMIZATION STRATEGY for an agentic loop system. A strategy decides how to
3322
3606
  spend a compute budget to beat a task's deployable check. You compose exactly two steps:
@@ -3434,9 +3718,9 @@ async function authorStrategy(opts) {
3434
3718
  code = await requestAuthoredCode(opts, opts.fallbackModel);
3435
3719
  }
3436
3720
  assertStrategyContract(code);
3437
- mkdirSync(opts.outDir, { recursive: true });
3438
- const file = join2(opts.outDir, `authored-${Date.now()}.mts`);
3439
- writeFileSync(file, code);
3721
+ mkdirSync2(opts.outDir, { recursive: true });
3722
+ const file = join3(opts.outDir, `authored-${Date.now()}.mts`);
3723
+ writeFileSync2(file, code);
3440
3724
  const mod = await import(`file://${file}`);
3441
3725
  if (!mod.default || typeof mod.default.driver !== "function" || !mod.default.name) {
3442
3726
  throw new Error(`authorStrategy: ${file} does not export a default Strategy`);
@@ -3445,7 +3729,7 @@ async function authorStrategy(opts) {
3445
3729
  }
3446
3730
 
3447
3731
  // src/runtime/strategy-evolution.ts
3448
- import { existsSync, readFileSync, writeFileSync as writeFileSync2 } from "fs";
3732
+ import { existsSync, readFileSync, writeFileSync as writeFileSync3 } from "fs";
3449
3733
  import { gzipSync } from "zlib";
3450
3734
  function discriminatingMeans(report, fieldOrder) {
3451
3735
  const rows = report.perTask.filter((r) => {
@@ -3557,7 +3841,7 @@ async function runStrategyEvolution(cfg) {
3557
3841
  }
3558
3842
  const save = (state) => {
3559
3843
  if (cfg.checkpoint)
3560
- writeFileSync2(cfg.checkpoint.path, JSON.stringify({ ...state, fingerprint }, null, 1));
3844
+ writeFileSync3(cfg.checkpoint.path, JSON.stringify({ ...state, fingerprint }, null, 1));
3561
3845
  };
3562
3846
  const bench = async (phase, tasks, strategies) => {
3563
3847
  await cfg.onPhase?.(phase);
@@ -4641,9 +4925,9 @@ function jjWorkspace(opts) {
4641
4925
  }
4642
4926
  async function runInWorkspace(ws, body, opts = {}) {
4643
4927
  const { mkdtempSync: mkdtempSync2, rmSync: rmSync2 } = await import("fs");
4644
- const { tmpdir: tmpdir2 } = await import("os");
4645
- const { join: join3 } = await import("path");
4646
- const dir = mkdtempSync2(join3(tmpdir2(), opts.tmpPrefix ?? "ws-run-"));
4928
+ const { tmpdir: tmpdir3 } = await import("os");
4929
+ const { join: join4 } = await import("path");
4930
+ const dir = mkdtempSync2(join4(tmpdir3(), opts.tmpPrefix ?? "ws-run-"));
4647
4931
  try {
4648
4932
  await ws.materialize(dir);
4649
4933
  const r = await body(dir);
@@ -4676,15 +4960,19 @@ export {
4676
4960
  stopSentinel,
4677
4961
  sentinelCompletion,
4678
4962
  deterministicCompletion,
4963
+ reportLoopUsage,
4964
+ loopCampaignDispatch,
4965
+ loopDispatch,
4966
+ inlineSandboxClient,
4967
+ resolveSandboxClient,
4968
+ naiveDriver,
4969
+ dumbDriver,
4970
+ defineLeaderboard,
4679
4971
  defaultAnalystInstruction,
4680
4972
  observe,
4681
4973
  renderReport,
4682
4974
  harvestCorpus,
4683
4975
  inProcessSandboxClient,
4684
- inlineSandboxClient,
4685
- reportLoopUsage,
4686
- loopCampaignDispatch,
4687
- loopDispatch,
4688
4976
  createMcpEnvironment,
4689
4977
  assertTraceDerivedFindings,
4690
4978
  createScopeAnalyst,
@@ -4709,7 +4997,6 @@ export {
4709
4997
  trajectoryReport,
4710
4998
  equalKOnCost,
4711
4999
  promotionGate,
4712
- resolveSandboxClient,
4713
5000
  depthStrategy,
4714
5001
  breadthStrategy,
4715
5002
  sample,
@@ -4722,8 +5009,6 @@ export {
4722
5009
  printBenchmarkReport,
4723
5010
  SandboxRunAbortError,
4724
5011
  openSandboxRun,
4725
- naiveDriver,
4726
- dumbDriver,
4727
5012
  strategyAuthorContract,
4728
5013
  assertStrategyContract,
4729
5014
  authorStrategy,
@@ -4751,4 +5036,4 @@ export {
4751
5036
  computeFindingId,
4752
5037
  makeFinding2 as makeFinding
4753
5038
  };
4754
- //# sourceMappingURL=chunk-JYURIKPF.js.map
5039
+ //# sourceMappingURL=chunk-UJW6EVNY.js.map