@tangle-network/agent-runtime 0.68.0 → 0.70.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 (78) hide show
  1. package/README.md +81 -13
  2. package/dist/agent.d.ts +4 -5
  3. package/dist/agent.js +3 -6
  4. package/dist/agent.js.map +1 -1
  5. package/dist/chunk-BYZCXQHF.js +474 -0
  6. package/dist/chunk-BYZCXQHF.js.map +1 -0
  7. package/dist/{chunk-OYU5LR4T.js → chunk-EDCVUZZC.js} +2 -2
  8. package/dist/{chunk-QNUEFNU7.js → chunk-L5ZFBVT6.js} +6 -6
  9. package/dist/chunk-L5ZFBVT6.js.map +1 -0
  10. package/dist/{chunk-VKUHUFX7.js → chunk-QXWGSDAQ.js} +914 -590
  11. package/dist/chunk-QXWGSDAQ.js.map +1 -0
  12. package/dist/{chunk-LTEF2LYD.js → chunk-ZNQVMMR5.js} +3 -3
  13. package/dist/{coordination-Curpzeyc.d.ts → coordination-C7WxwHXq.d.ts} +8 -1
  14. package/dist/{delegates-CLFNAKyi.d.ts → delegates-DqAgo32T.d.ts} +105 -10
  15. package/dist/{improvement-adapter-BC4HhuAR.d.ts → improvement-adapter-BVuMragr.d.ts} +1 -1
  16. package/dist/index.d.ts +439 -100
  17. package/dist/index.js +583 -125
  18. package/dist/index.js.map +1 -1
  19. package/dist/intelligence.d.ts +2 -3
  20. package/dist/{loop-runner-bin-B6dzNZC8.d.ts → loop-runner-bin-B0NeLTRd.d.ts} +4 -4
  21. package/dist/loop-runner-bin.d.ts +7 -10
  22. package/dist/loop-runner-bin.js +4 -7
  23. package/dist/loops.d.ts +3149 -16
  24. package/dist/loops.js +34 -63
  25. package/dist/mcp/bin.js +14 -16
  26. package/dist/mcp/bin.js.map +1 -1
  27. package/dist/mcp/index.d.ts +8 -12
  28. package/dist/mcp/index.js +16 -19
  29. package/dist/mcp/index.js.map +1 -1
  30. package/dist/{openai-tools-CA2N3-Ak.d.ts → openai-tools-DPx9Gzvn.d.ts} +1 -1
  31. package/dist/profiles.d.ts +94 -6
  32. package/dist/profiles.js +320 -9
  33. package/dist/profiles.js.map +1 -1
  34. package/dist/{router-client-30Y_pca8.d.ts → router-client-C7kp_ECN.d.ts} +37 -1
  35. package/dist/{substrate-CUgk7F7s.d.ts → substrate-BoRXgvka.d.ts} +52 -1
  36. package/dist/{types-Crxftafi.d.ts → types-BYa2ZOAx.d.ts} +83 -2
  37. package/dist/{types-p8dWBIXL.d.ts → types-DJu6TBGp.d.ts} +2 -16
  38. package/dist/{worktree-fanout-DUiKPApb.d.ts → worktree-fanout-gNfl0Byj.d.ts} +9 -37
  39. package/package.json +9 -39
  40. package/dist/analyst-loop.d.ts +0 -52
  41. package/dist/analyst-loop.js +0 -11
  42. package/dist/analyst-loop.js.map +0 -1
  43. package/dist/audit.d.ts +0 -93
  44. package/dist/audit.js +0 -312
  45. package/dist/audit.js.map +0 -1
  46. package/dist/chunk-4B6U4CVQ.js +0 -15
  47. package/dist/chunk-4B6U4CVQ.js.map +0 -1
  48. package/dist/chunk-FCIPUALH.js +0 -214
  49. package/dist/chunk-FCIPUALH.js.map +0 -1
  50. package/dist/chunk-O2UPHN7X.js +0 -114
  51. package/dist/chunk-O2UPHN7X.js.map +0 -1
  52. package/dist/chunk-P5OKDSLB.js +0 -580
  53. package/dist/chunk-P5OKDSLB.js.map +0 -1
  54. package/dist/chunk-QNUEFNU7.js.map +0 -1
  55. package/dist/chunk-VKUHUFX7.js.map +0 -1
  56. package/dist/chunk-VLF5RHEQ.js +0 -143
  57. package/dist/chunk-VLF5RHEQ.js.map +0 -1
  58. package/dist/coder-2leJPOvC.d.ts +0 -52
  59. package/dist/improvement.d.ts +0 -208
  60. package/dist/improvement.js +0 -343
  61. package/dist/improvement.js.map +0 -1
  62. package/dist/local-harness-BE_h8szs.d.ts +0 -93
  63. package/dist/platform.d.ts +0 -255
  64. package/dist/platform.js +0 -229
  65. package/dist/platform.js.map +0 -1
  66. package/dist/run-loop-D3PwlG7J.d.ts +0 -112
  67. package/dist/runtime-hooks-C7JwKb9E.d.ts +0 -70
  68. package/dist/runtime.d.ts +0 -3108
  69. package/dist/runtime.js +0 -263
  70. package/dist/runtime.js.map +0 -1
  71. package/dist/topology.d.ts +0 -126
  72. package/dist/topology.js +0 -333
  73. package/dist/topology.js.map +0 -1
  74. package/dist/workflow.d.ts +0 -551
  75. package/dist/workflow.js +0 -1781
  76. package/dist/workflow.js.map +0 -1
  77. /package/dist/{chunk-OYU5LR4T.js.map → chunk-EDCVUZZC.js.map} +0 -0
  78. /package/dist/{chunk-LTEF2LYD.js.map → chunk-ZNQVMMR5.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  mcpToolsForRuntimeMcp,
3
3
  mcpToolsForRuntimeMcpSubset
4
- } from "./chunk-OYU5LR4T.js";
4
+ } from "./chunk-EDCVUZZC.js";
5
5
  import {
6
6
  DEFAULT_ROUTER_BASE_URL,
7
7
  cleanModelId,
@@ -21,18 +21,9 @@ import {
21
21
  runLoopRunnerCli,
22
22
  selfImproveLoopRunner,
23
23
  worktreeLoopRunner
24
- } from "./chunk-FCIPUALH.js";
24
+ } from "./chunk-BYZCXQHF.js";
25
25
  import "./chunk-FNMGYYSS.js";
26
- import "./chunk-QNUEFNU7.js";
27
- import "./chunk-DVQGYDN5.js";
28
- import "./chunk-P5OKDSLB.js";
29
- import {
30
- composeRuntimeHooks,
31
- defineRuntimeHooks,
32
- notifyRuntimeDecisionPoint,
33
- notifyRuntimeHookEvent
34
- } from "./chunk-VKUHUFX7.js";
35
- import "./chunk-WIR4HOOJ.js";
26
+ import "./chunk-L5ZFBVT6.js";
36
27
  import {
37
28
  AgentEvalError,
38
29
  BackendTransportError,
@@ -42,9 +33,14 @@ import {
42
33
  PlannerError,
43
34
  RuntimeRunStateError,
44
35
  SessionMismatchError,
45
- ValidationError
46
- } from "./chunk-VLF5RHEQ.js";
47
- import "./chunk-O2UPHN7X.js";
36
+ ValidationError,
37
+ assertModelAllowed,
38
+ composeRuntimeHooks,
39
+ defineRuntimeHooks,
40
+ notifyRuntimeDecisionPoint,
41
+ notifyRuntimeHookEvent,
42
+ runLocalHarness
43
+ } from "./chunk-QXWGSDAQ.js";
48
44
  import {
49
45
  INTELLIGENCE_WIRE_VERSION,
50
46
  buildLoopOtelSpans,
@@ -53,6 +49,8 @@ import {
53
49
  exportEvalRuns,
54
50
  loopEventToOtelSpan
55
51
  } from "./chunk-G3RGMA7C.js";
52
+ import "./chunk-DVQGYDN5.js";
53
+ import "./chunk-WIR4HOOJ.js";
56
54
  import "./chunk-DGUM43GV.js";
57
55
 
58
56
  // src/sessions.ts
@@ -1420,6 +1418,146 @@ function normalizePolicy(policy, participantCount) {
1420
1418
  return { ...policy, turnOrder };
1421
1419
  }
1422
1420
 
1421
+ // src/conversation/run-persona.ts
1422
+ function withProfilePrompt(inner, systemPrompt, counter) {
1423
+ return {
1424
+ kind: inner.kind,
1425
+ start: inner.start ? (input, ctx) => inner.start(input, ctx) : void 0,
1426
+ resume: inner.resume ? (session, input, ctx) => inner.resume(session, input, ctx) : void 0,
1427
+ stop: inner.stop ? (session, reason) => inner.stop(session, reason) : void 0,
1428
+ async *stream(input, context) {
1429
+ const base = input.messages ?? (input.message ? [{ role: "user", content: input.message }] : []);
1430
+ const messages = base[0]?.role === "system" ? base : [{ role: "system", content: systemPrompt }, ...base];
1431
+ for await (const event of inner.stream({ ...input, messages }, context)) {
1432
+ if (counter && event.type === "llm_call") {
1433
+ counter.tokensIn += event.tokensIn ?? 0;
1434
+ counter.tokensOut += event.tokensOut ?? 0;
1435
+ counter.costUsd += event.costUsd ?? 0;
1436
+ }
1437
+ yield event;
1438
+ }
1439
+ }
1440
+ };
1441
+ }
1442
+ function scriptedPersonaBackend(turns) {
1443
+ let idx = 0;
1444
+ return createIterableBackend({
1445
+ kind: "persona-user",
1446
+ async *stream(_input, context) {
1447
+ const text = turns[idx];
1448
+ if (text === void 0) {
1449
+ throw new Error(
1450
+ `persona-user: ran out of scripted turns at index ${idx} (had ${turns.length})`
1451
+ );
1452
+ }
1453
+ idx += 1;
1454
+ yield {
1455
+ type: "text_delta",
1456
+ task: context.task,
1457
+ session: context.session,
1458
+ text,
1459
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1460
+ };
1461
+ }
1462
+ });
1463
+ }
1464
+ async function runPersonaConversation(opts) {
1465
+ const counter = { tokensIn: 0, tokensOut: 0, costUsd: 0 };
1466
+ const workerName = opts.workerName ?? "agent";
1467
+ const worker = withProfilePrompt(
1468
+ opts.backendFor(opts.worker, "worker"),
1469
+ opts.systemPromptOf(opts.worker),
1470
+ counter
1471
+ );
1472
+ let persona;
1473
+ let maxTurns;
1474
+ if (opts.persona.kind === "scripted") {
1475
+ if (opts.persona.turns.length === 0) {
1476
+ throw new Error("runPersonaConversation: scripted persona has no turns");
1477
+ }
1478
+ persona = scriptedPersonaBackend(opts.persona.turns);
1479
+ maxTurns = opts.maxTurns ?? 2 * opts.persona.turns.length;
1480
+ } else {
1481
+ persona = withProfilePrompt(
1482
+ opts.backendFor(opts.persona.profile, "persona"),
1483
+ opts.systemPromptOf(opts.persona.profile)
1484
+ );
1485
+ if (opts.maxTurns === void 0) {
1486
+ throw new Error("runPersonaConversation: maxTurns is required for a profile-driven persona");
1487
+ }
1488
+ maxTurns = opts.maxTurns;
1489
+ }
1490
+ const conversation = defineConversation({
1491
+ // Persona leads (participant 0): the seed routes to it, it produces the
1492
+ // user turn, the worker answers, alternate.
1493
+ participants: [
1494
+ { name: "user", backend: persona },
1495
+ { name: workerName, backend: worker }
1496
+ ],
1497
+ policy: { maxTurns, turnOrder: "alternate", ...opts.haltOn ? { haltOn: opts.haltOn } : {} }
1498
+ });
1499
+ const result = await runConversation(conversation, {
1500
+ seed: opts.seed ?? "Begin.",
1501
+ signal: opts.signal
1502
+ });
1503
+ const costUsd = counter.costUsd > 0 ? counter.costUsd : opts.persona.kind === "scripted" ? result.spentCreditsCents / 100 : 0;
1504
+ return {
1505
+ transcript: result.transcript,
1506
+ turns: result.turns,
1507
+ halted: result.halted,
1508
+ costUsd,
1509
+ tokensIn: counter.tokensIn,
1510
+ tokensOut: counter.tokensOut
1511
+ };
1512
+ }
1513
+ function runPersonaDispatch(config) {
1514
+ return async (worker, scenario, ctx) => {
1515
+ const result = await runPersonaConversation({
1516
+ worker,
1517
+ persona: config.personaOf(scenario),
1518
+ backendFor: config.backendFor,
1519
+ systemPromptOf: config.systemPromptOf,
1520
+ maxTurns: config.maxTurns?.(scenario),
1521
+ seed: config.seed?.(scenario),
1522
+ signal: ctx.signal,
1523
+ workerName: config.workerName
1524
+ });
1525
+ ctx.cost.observe(result.costUsd, "persona-conversation");
1526
+ ctx.cost.observeTokens({ input: result.tokensIn, output: result.tokensOut });
1527
+ return config.artifactOf(result.transcript, scenario);
1528
+ };
1529
+ }
1530
+
1531
+ // src/conversation/eval-persona.ts
1532
+ function evalPersona(worker, persona, opts = {}) {
1533
+ const defaultBackendFor = () => {
1534
+ if (!opts.apiKey || !opts.baseUrl || !opts.model) {
1535
+ throw new Error(
1536
+ "evalPersona: provide opts.{apiKey,baseUrl,model} for the default backend, or opts.backendFor"
1537
+ );
1538
+ }
1539
+ const { apiKey, baseUrl, model } = opts;
1540
+ return () => createOpenAICompatibleBackend({ apiKey, baseUrl, model });
1541
+ };
1542
+ const backendFor = opts.backendFor ?? defaultBackendFor();
1543
+ const systemPromptOf = opts.systemPromptOf ?? ((p) => p.prompt?.systemPrompt ?? "");
1544
+ return runPersonaConversation({
1545
+ // runPersonaConversation types its profile as the benchmark-cell AgentProfile; here it is the
1546
+ // authored AgentProfile (the carrier of prompt.systemPrompt). The runner never inspects the
1547
+ // profile itself — only backendFor/systemPromptOf do, and both are typed for THIS profile — so
1548
+ // the cast at this single boundary is sound.
1549
+ worker,
1550
+ persona,
1551
+ backendFor,
1552
+ systemPromptOf,
1553
+ ...opts.maxTurns !== void 0 ? { maxTurns: opts.maxTurns } : {},
1554
+ ...opts.haltOn ? { haltOn: opts.haltOn } : {},
1555
+ ...opts.seed !== void 0 ? { seed: opts.seed } : {},
1556
+ ...opts.signal ? { signal: opts.signal } : {},
1557
+ ...opts.workerName !== void 0 ? { workerName: opts.workerName } : {}
1558
+ });
1559
+ }
1560
+
1423
1561
  // src/conversation/journal.ts
1424
1562
  var InMemoryConversationJournal = class {
1425
1563
  entries = /* @__PURE__ */ new Map();
@@ -1673,116 +1811,6 @@ var SqlConversationJournal = class {
1673
1811
  }
1674
1812
  };
1675
1813
 
1676
- // src/conversation/run-persona.ts
1677
- function withProfilePrompt(inner, systemPrompt, counter) {
1678
- return {
1679
- kind: inner.kind,
1680
- start: inner.start ? (input, ctx) => inner.start(input, ctx) : void 0,
1681
- resume: inner.resume ? (session, input, ctx) => inner.resume(session, input, ctx) : void 0,
1682
- stop: inner.stop ? (session, reason) => inner.stop(session, reason) : void 0,
1683
- async *stream(input, context) {
1684
- const base = input.messages ?? (input.message ? [{ role: "user", content: input.message }] : []);
1685
- const messages = base[0]?.role === "system" ? base : [{ role: "system", content: systemPrompt }, ...base];
1686
- for await (const event of inner.stream({ ...input, messages }, context)) {
1687
- if (counter && event.type === "llm_call") {
1688
- counter.tokensIn += event.tokensIn ?? 0;
1689
- counter.tokensOut += event.tokensOut ?? 0;
1690
- counter.costUsd += event.costUsd ?? 0;
1691
- }
1692
- yield event;
1693
- }
1694
- }
1695
- };
1696
- }
1697
- function scriptedPersonaBackend(turns) {
1698
- let idx = 0;
1699
- return createIterableBackend({
1700
- kind: "persona-user",
1701
- async *stream(_input, context) {
1702
- const text = turns[idx];
1703
- if (text === void 0) {
1704
- throw new Error(
1705
- `persona-user: ran out of scripted turns at index ${idx} (had ${turns.length})`
1706
- );
1707
- }
1708
- idx += 1;
1709
- yield {
1710
- type: "text_delta",
1711
- task: context.task,
1712
- session: context.session,
1713
- text,
1714
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1715
- };
1716
- }
1717
- });
1718
- }
1719
- async function runPersonaConversation(opts) {
1720
- const counter = { tokensIn: 0, tokensOut: 0, costUsd: 0 };
1721
- const workerName = opts.workerName ?? "agent";
1722
- const worker = withProfilePrompt(
1723
- opts.backendFor(opts.worker, "worker"),
1724
- opts.systemPromptOf(opts.worker),
1725
- counter
1726
- );
1727
- let persona;
1728
- let maxTurns;
1729
- if (opts.persona.kind === "scripted") {
1730
- if (opts.persona.turns.length === 0) {
1731
- throw new Error("runPersonaConversation: scripted persona has no turns");
1732
- }
1733
- persona = scriptedPersonaBackend(opts.persona.turns);
1734
- maxTurns = opts.maxTurns ?? 2 * opts.persona.turns.length;
1735
- } else {
1736
- persona = withProfilePrompt(
1737
- opts.backendFor(opts.persona.profile, "persona"),
1738
- opts.systemPromptOf(opts.persona.profile)
1739
- );
1740
- if (opts.maxTurns === void 0) {
1741
- throw new Error("runPersonaConversation: maxTurns is required for a profile-driven persona");
1742
- }
1743
- maxTurns = opts.maxTurns;
1744
- }
1745
- const conversation = defineConversation({
1746
- // Persona leads (participant 0): the seed routes to it, it produces the
1747
- // user turn, the worker answers, alternate.
1748
- participants: [
1749
- { name: "user", backend: persona },
1750
- { name: workerName, backend: worker }
1751
- ],
1752
- policy: { maxTurns, turnOrder: "alternate" }
1753
- });
1754
- const result = await runConversation(conversation, {
1755
- seed: opts.seed ?? "Begin.",
1756
- signal: opts.signal
1757
- });
1758
- const costUsd = counter.costUsd > 0 ? counter.costUsd : opts.persona.kind === "scripted" ? result.spentCreditsCents / 100 : 0;
1759
- return {
1760
- transcript: result.transcript,
1761
- turns: result.turns,
1762
- halted: result.halted,
1763
- costUsd,
1764
- tokensIn: counter.tokensIn,
1765
- tokensOut: counter.tokensOut
1766
- };
1767
- }
1768
- function runPersonaDispatch(config) {
1769
- return async (worker, scenario, ctx) => {
1770
- const result = await runPersonaConversation({
1771
- worker,
1772
- persona: config.personaOf(scenario),
1773
- backendFor: config.backendFor,
1774
- systemPromptOf: config.systemPromptOf,
1775
- maxTurns: config.maxTurns?.(scenario),
1776
- seed: config.seed?.(scenario),
1777
- signal: ctx.signal,
1778
- workerName: config.workerName
1779
- });
1780
- ctx.cost.observe(result.costUsd, "persona-conversation");
1781
- ctx.cost.observeTokens({ input: result.tokensIn, output: result.tokensOut });
1782
- return config.artifactOf(result.transcript, scenario);
1783
- };
1784
- }
1785
-
1786
1814
  // src/durable/chat-engine.ts
1787
1815
  var encoder = new TextEncoder();
1788
1816
  function encodeLine(event) {
@@ -1869,6 +1897,427 @@ function deriveExecutionId(input) {
1869
1897
  return `${input.projectId}:${input.sessionId}:${input.turnIndex}`;
1870
1898
  }
1871
1899
 
1900
+ // src/improvement/agentic-generator.ts
1901
+ import { spawnSync } from "child_process";
1902
+ function agenticGenerator(opts = {}) {
1903
+ const harness = opts.harness ?? "claude";
1904
+ const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt;
1905
+ const run = opts.runHarness ?? runLocalHarness;
1906
+ const dirty = opts.isDirty ?? worktreeDirty;
1907
+ const verify = opts.verify;
1908
+ return {
1909
+ kind: `agentic:${harness}`,
1910
+ async generate({ worktreePath, report, findings, maxShots, signal }) {
1911
+ const basePrompt = buildPrompt({ report, findings });
1912
+ const shots = Math.max(1, maxShots);
1913
+ let attemptNote = "";
1914
+ for (let shot = 0; shot < shots; shot++) {
1915
+ if (signal.aborted) break;
1916
+ await run({
1917
+ harness,
1918
+ cwd: worktreePath,
1919
+ taskPrompt: attemptNote ? `${basePrompt}
1920
+
1921
+ ${attemptNote}` : basePrompt,
1922
+ timeoutMs: opts.timeoutMs,
1923
+ signal
1924
+ });
1925
+ if (!dirty(worktreePath)) {
1926
+ attemptNote = EMPTY_TREE_NOTE;
1927
+ continue;
1928
+ }
1929
+ if (!verify) {
1930
+ return { applied: true, summary: summarize(findings) };
1931
+ }
1932
+ const result = await verify(worktreePath);
1933
+ if (result.ok) {
1934
+ return { applied: true, summary: summarize(findings) };
1935
+ }
1936
+ attemptNote = failureNote(result.feedback);
1937
+ }
1938
+ return { applied: false, summary: "" };
1939
+ }
1940
+ };
1941
+ }
1942
+ function defaultBuildPrompt(args) {
1943
+ const lines = [
1944
+ "You are improving this codebase based on an evaluation analysis.",
1945
+ "Make the smallest set of edits that addresses the findings below, then stop.",
1946
+ "Do not change unrelated code. Do not commit \u2014 leave changes in the working tree.",
1947
+ "",
1948
+ "Findings:"
1949
+ ];
1950
+ for (const f of args.findings) {
1951
+ const where = f.subject ? ` [${f.subject}]` : "";
1952
+ lines.push(`- (${f.severity})${where} ${f.claim}`);
1953
+ if (f.recommended_action) lines.push(` \u2192 ${f.recommended_action}`);
1954
+ }
1955
+ return lines.join("\n");
1956
+ }
1957
+ var EMPTY_TREE_NOTE = "NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.";
1958
+ function failureNote(feedback) {
1959
+ const detail = feedback?.trim();
1960
+ return [
1961
+ "NOTE: your edits are in the working tree but verification FAILED.",
1962
+ "Fix the problem in place \u2014 build on your existing edits, do not revert them.",
1963
+ detail ? `Verifier output:
1964
+ ${truncate(detail, 4e3)}` : "No verifier detail was captured."
1965
+ ].join("\n");
1966
+ }
1967
+ function commandVerifier(command, args = [], timeoutMs = 3e5) {
1968
+ return (worktreePath) => {
1969
+ const result = spawnSync(command, args, {
1970
+ cwd: worktreePath,
1971
+ encoding: "utf-8",
1972
+ timeout: timeoutMs
1973
+ });
1974
+ if (result.signal) {
1975
+ return {
1976
+ ok: false,
1977
+ feedback: `verifier '${command}' killed by ${result.signal} (likely timeout after ${timeoutMs}ms)`
1978
+ };
1979
+ }
1980
+ if (result.error) {
1981
+ const code = result.error.code;
1982
+ if (code === "ENOENT") {
1983
+ throw new Error(
1984
+ `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`
1985
+ );
1986
+ }
1987
+ throw new Error(`commandVerifier: '${command}' failed to spawn: ${result.error.message}`);
1988
+ }
1989
+ if (result.status === 0) return { ok: true };
1990
+ const out = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
1991
+ return { ok: false, feedback: out.length > 0 ? out : `exit ${result.status}` };
1992
+ };
1993
+ }
1994
+ function summarize(findings) {
1995
+ if (findings.length === 0) return "agentic improvement";
1996
+ if (findings.length === 1) return `agentic: ${truncate(findings[0].claim, 64)}`;
1997
+ return `agentic: ${findings.length} findings addressed`;
1998
+ }
1999
+ function truncate(s, n) {
2000
+ return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
2001
+ }
2002
+ function worktreeDirty(worktreePath) {
2003
+ const result = spawnSync("git", ["status", "--porcelain"], {
2004
+ cwd: worktreePath,
2005
+ encoding: "utf-8"
2006
+ });
2007
+ if (result.error) {
2008
+ throw new Error(
2009
+ `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`
2010
+ );
2011
+ }
2012
+ if (result.status !== 0) {
2013
+ throw new Error(
2014
+ `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`
2015
+ );
2016
+ }
2017
+ return result.stdout.trim().length > 0;
2018
+ }
2019
+
2020
+ // src/improvement/build-prompts.ts
2021
+ function findingLines(findings) {
2022
+ return findings.map((f) => {
2023
+ const where = f.subject ? ` [${f.subject}]` : "";
2024
+ const action = f.recommended_action ? ` \u2192 ${f.recommended_action}` : "";
2025
+ return `- (${f.severity})${where} ${f.claim}${action}`;
2026
+ });
2027
+ }
2028
+ function toolBuildPrompt(args) {
2029
+ return [
2030
+ "You are building a new TOOL for this codebase to address the gaps below.",
2031
+ "Write the tool as a small, self-contained module PLUS tests that exercise it.",
2032
+ "The tool must compile and its tests must pass \u2014 they will be run automatically;",
2033
+ "if verification fails you will get the error and another attempt. Do not commit;",
2034
+ "leave the changes in the working tree.",
2035
+ "",
2036
+ "Gaps the tool should close:",
2037
+ ...findingLines(args.findings)
2038
+ ].join("\n");
2039
+ }
2040
+ function mcpBuildPrompt(args) {
2041
+ return [
2042
+ "You are building a new MCP SERVER (Model Context Protocol) that exposes",
2043
+ "tool(s) addressing the gaps below, so any harness can mount it.",
2044
+ "Requirements that WILL be checked by booting the server:",
2045
+ "- it starts over stdio and answers the MCP `initialize` handshake,",
2046
+ "- `tools/list` returns at least one tool with a valid input schema.",
2047
+ "Newline-delimited JSON-RPC 2.0, protocol version 2024-11-05. Include a start",
2048
+ "command (e.g. a package.json `start` script or a clear entrypoint). If the",
2049
+ "boot-and-probe fails you will get the error and another attempt. Do not",
2050
+ "commit; leave the changes in the working tree.",
2051
+ "",
2052
+ "Capabilities the server should provide:",
2053
+ ...findingLines(args.findings)
2054
+ ].join("\n");
2055
+ }
2056
+
2057
+ // src/improvement/improve.ts
2058
+ import { skillOptProposer } from "@tangle-network/agent-eval/campaign";
2059
+ import {
2060
+ gepaProposer,
2061
+ selfImprove
2062
+ } from "@tangle-network/agent-eval/contract";
2063
+ var defaultReflectionModel = "deepseek-v4-flash";
2064
+ function llmClientOptions(llm) {
2065
+ return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey };
2066
+ }
2067
+ function defaultGeneratorFor(surface, llm) {
2068
+ const model = llm?.model ?? defaultReflectionModel;
2069
+ switch (surface) {
2070
+ case "prompt":
2071
+ return gepaProposer({ llm: llmClientOptions(llm), model, target: "agent system prompt" });
2072
+ case "skills":
2073
+ return skillOptProposer({ llm: llmClientOptions(llm), model, target: "agent skill document" });
2074
+ default:
2075
+ return void 0;
2076
+ }
2077
+ }
2078
+ function baselineSurfaceFor(profile, surface) {
2079
+ switch (surface) {
2080
+ case "prompt":
2081
+ return profile.prompt?.systemPrompt ?? "";
2082
+ case "skills":
2083
+ return JSON.stringify(profile.resources?.skills ?? []);
2084
+ case "tools":
2085
+ return JSON.stringify(profile.tools ?? {});
2086
+ case "mcp":
2087
+ return JSON.stringify(profile.mcp ?? {});
2088
+ case "hooks":
2089
+ return JSON.stringify(profile.hooks ?? {});
2090
+ case "code":
2091
+ return "";
2092
+ }
2093
+ }
2094
+ function parseWinnerJson(winner, surface) {
2095
+ try {
2096
+ return JSON.parse(winner);
2097
+ } catch (cause) {
2098
+ throw new ConfigError(
2099
+ `improve(): the shipped '${surface}' winner is not valid JSON, so it cannot be applied back to the profile: ${cause.message}`
2100
+ );
2101
+ }
2102
+ }
2103
+ function applyWinnerToProfile(profile, surface, winner) {
2104
+ if (typeof winner !== "string") return profile;
2105
+ switch (surface) {
2106
+ case "prompt":
2107
+ return { ...profile, prompt: { ...profile.prompt, systemPrompt: winner } };
2108
+ case "skills":
2109
+ return {
2110
+ ...profile,
2111
+ resources: { ...profile.resources, skills: parseWinnerJson(winner, surface) }
2112
+ };
2113
+ case "tools":
2114
+ return { ...profile, tools: parseWinnerJson(winner, surface) };
2115
+ case "mcp":
2116
+ return { ...profile, mcp: parseWinnerJson(winner, surface) };
2117
+ case "hooks":
2118
+ return { ...profile, hooks: parseWinnerJson(winner, surface) };
2119
+ case "code":
2120
+ return profile;
2121
+ }
2122
+ }
2123
+ async function improve(profile, findings, opts) {
2124
+ const surface = opts.surface ?? "prompt";
2125
+ const gate = opts.gate ?? "holdout";
2126
+ assertModelAllowed(opts.llm?.model ?? defaultReflectionModel, opts.allowedModels);
2127
+ const proposer = opts.generator ?? defaultGeneratorFor(surface, opts.llm);
2128
+ if (!proposer) {
2129
+ throw new ConfigError(
2130
+ `improve(): surface '${surface}' has no default generator \u2014 pass opts.generator (a SurfaceProposer) explicitly`
2131
+ );
2132
+ }
2133
+ const budget = gate === "none" ? { ...opts.budget, generations: 0 } : { ...opts.budget };
2134
+ const raw = await selfImprove({
2135
+ agent: opts.agent,
2136
+ scenarios: opts.scenarios,
2137
+ judge: opts.judge,
2138
+ baselineSurface: baselineSurfaceFor(profile, surface),
2139
+ proposer,
2140
+ budget,
2141
+ llm: opts.llm,
2142
+ findings
2143
+ });
2144
+ const shipped = raw.gateDecision === "ship";
2145
+ const nextProfile = shipped ? applyWinnerToProfile(profile, surface, raw.winner.surface) : profile;
2146
+ return { profile: nextProfile, shipped, lift: raw.lift, gateDecision: raw.gateDecision, raw };
2147
+ }
2148
+
2149
+ // src/improvement/improvement-driver.ts
2150
+ function improvementDriver(opts) {
2151
+ const baseRef = opts.baseRef ?? "main";
2152
+ return {
2153
+ kind: `improvement:${opts.generator.kind}`,
2154
+ async propose(ctx) {
2155
+ const findings = resolveFindings(ctx);
2156
+ if (findings.length === 0 && ctx.report === void 0) return [];
2157
+ const surfaces = [];
2158
+ for (let i = 0; i < ctx.populationSize; i++) {
2159
+ if (ctx.signal.aborted) break;
2160
+ const wt = await opts.worktree.create({
2161
+ baseRef,
2162
+ label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`
2163
+ });
2164
+ try {
2165
+ const { applied, summary } = await opts.generator.generate({
2166
+ worktreePath: wt.path,
2167
+ report: ctx.report,
2168
+ findings,
2169
+ dataset: ctx.dataset,
2170
+ maxShots: ctx.maxImprovementShots ?? 1,
2171
+ signal: ctx.signal
2172
+ });
2173
+ if (!applied) {
2174
+ await opts.worktree.discard(wt);
2175
+ continue;
2176
+ }
2177
+ surfaces.push(await opts.worktree.finalize(wt, summary));
2178
+ } catch (err) {
2179
+ await opts.worktree.discard(wt).catch(() => {
2180
+ });
2181
+ throw err;
2182
+ }
2183
+ }
2184
+ return surfaces;
2185
+ }
2186
+ };
2187
+ }
2188
+ function resolveFindings(ctx) {
2189
+ const report = ctx.report;
2190
+ if (report && typeof report === "object" && "findings" in report) {
2191
+ const f = report.findings;
2192
+ if (Array.isArray(f) && f.length > 0) return f;
2193
+ }
2194
+ return ctx.findings;
2195
+ }
2196
+
2197
+ // src/improvement/mcp-serve-verifier.ts
2198
+ import { spawn } from "child_process";
2199
+ import { createInterface } from "readline";
2200
+ var PROTOCOL_VERSION = "2024-11-05";
2201
+ function mcpServeVerifier(spec) {
2202
+ const timeoutMs = spec.timeoutMs ?? 3e4;
2203
+ const minTools = spec.minTools ?? 1;
2204
+ return (worktreePath) => new Promise((resolve, reject) => {
2205
+ const child = spawn(spec.command, spec.args ?? [], {
2206
+ cwd: worktreePath,
2207
+ stdio: ["pipe", "pipe", "pipe"],
2208
+ env: { ...process.env, ...spec.env }
2209
+ });
2210
+ const stderr = [];
2211
+ let settled = false;
2212
+ let nextId = 1;
2213
+ const initId = nextId++;
2214
+ let listId = -1;
2215
+ const settle = (fn) => {
2216
+ if (settled) return;
2217
+ settled = true;
2218
+ clearTimeout(timer);
2219
+ rl.close();
2220
+ child.kill("SIGKILL");
2221
+ fn();
2222
+ };
2223
+ const withStderr = (msg) => stderr.length > 0 ? `${msg}
2224
+ stderr:
2225
+ ${stderr.join("").slice(-2e3)}` : msg;
2226
+ const pass = () => settle(() => resolve({ ok: true }));
2227
+ const failCandidate = (msg) => settle(() => resolve({ ok: false, feedback: withStderr(msg) }));
2228
+ const setupFault = (err) => settle(() => reject(err));
2229
+ const send = (msg) => {
2230
+ try {
2231
+ child.stdin.write(`${JSON.stringify(msg)}
2232
+ `);
2233
+ return true;
2234
+ } catch (err) {
2235
+ failCandidate(`writing to MCP server stdin failed: ${err.message}`);
2236
+ return false;
2237
+ }
2238
+ };
2239
+ child.on("error", (err) => {
2240
+ const code = err.code;
2241
+ setupFault(
2242
+ code === "ENOENT" ? new Error(
2243
+ `mcpServeVerifier: '${spec.command}' not found in PATH (setup bug, not a failed candidate)`
2244
+ ) : new Error(`mcpServeVerifier: '${spec.command}' failed to spawn: ${err.message}`)
2245
+ );
2246
+ });
2247
+ child.on("exit", (code, signal) => {
2248
+ failCandidate(`MCP server exited (code ${code}, signal ${signal}) before serving`);
2249
+ });
2250
+ child.stderr.on("data", (d) => stderr.push(String(d)));
2251
+ const rl = createInterface({ input: child.stdout });
2252
+ rl.on("line", (line) => {
2253
+ let msg;
2254
+ try {
2255
+ msg = JSON.parse(line);
2256
+ } catch {
2257
+ return;
2258
+ }
2259
+ if (!msg || typeof msg !== "object") return;
2260
+ if (msg.id === initId) {
2261
+ if (msg.error) return failCandidate(`initialize errored: ${JSON.stringify(msg.error)}`);
2262
+ if (!send({ jsonrpc: "2.0", method: "notifications/initialized" })) return;
2263
+ listId = nextId++;
2264
+ send({ jsonrpc: "2.0", id: listId, method: "tools/list" });
2265
+ return;
2266
+ }
2267
+ if (msg.id === listId) {
2268
+ if (msg.error) return failCandidate(`tools/list errored: ${JSON.stringify(msg.error)}`);
2269
+ const tools = msg.result?.tools;
2270
+ if (!Array.isArray(tools)) return failCandidate("tools/list result has no tools array");
2271
+ if (tools.length < minTools) {
2272
+ return failCandidate(`tools/list returned ${tools.length} tool(s), need >= ${minTools}`);
2273
+ }
2274
+ return pass();
2275
+ }
2276
+ });
2277
+ const timer = setTimeout(
2278
+ () => failCandidate(`MCP server did not complete the handshake within ${timeoutMs}ms`),
2279
+ timeoutMs
2280
+ );
2281
+ send({
2282
+ jsonrpc: "2.0",
2283
+ id: initId,
2284
+ method: "initialize",
2285
+ params: {
2286
+ protocolVersion: PROTOCOL_VERSION,
2287
+ capabilities: {},
2288
+ clientInfo: { name: "agent-runtime-mcp-verify", version: "0" }
2289
+ }
2290
+ });
2291
+ });
2292
+ }
2293
+
2294
+ // src/improvement/reflective-generator.ts
2295
+ import { spawnSync as spawnSync2 } from "child_process";
2296
+ function reflectiveGenerator(opts) {
2297
+ return {
2298
+ kind: "reflective",
2299
+ async generate({ worktreePath, findings }) {
2300
+ const batch = await opts.improvementAdapter.proposeFromFindings(findings);
2301
+ if (batch.edits.length === 0) return { applied: false, summary: "" };
2302
+ let applied = 0;
2303
+ for (const edit of batch.edits) {
2304
+ if (applyPatch(edit.patch, worktreePath)) applied++;
2305
+ }
2306
+ if (applied === 0) return { applied: false, summary: "" };
2307
+ const summary = batch.edits.length === 1 ? batch.edits[0].summary : `analyst: ${applied} surface edit${applied === 1 ? "" : "s"}`;
2308
+ return { applied: true, summary };
2309
+ }
2310
+ };
2311
+ }
2312
+ function applyPatch(patch, cwd) {
2313
+ const result = spawnSync2("git", ["apply", "--whitespace=fix", "-p0", "-"], {
2314
+ cwd,
2315
+ input: patch,
2316
+ encoding: "utf-8"
2317
+ });
2318
+ return result.status === 0;
2319
+ }
2320
+
1872
2321
  // src/readiness.ts
1873
2322
  var DEFAULT_MINIMUM_READINESS_SCORE = 0.7;
1874
2323
  function decideKnowledgeReadiness(report, options = {}) {
@@ -3292,6 +3741,7 @@ export {
3292
3741
  RuntimeRunStateError,
3293
3742
  SqlConversationJournal,
3294
3743
  ValidationError,
3744
+ agenticGenerator,
3295
3745
  applyRunRecordDefaults,
3296
3746
  auditLoopRunner,
3297
3747
  buildForwardHeaders,
@@ -3299,6 +3749,7 @@ export {
3299
3749
  buildLoopSpanNodes,
3300
3750
  cleanModelId,
3301
3751
  coderLoopRunner,
3752
+ commandVerifier,
3302
3753
  composeRuntimeHooks,
3303
3754
  computeBackoff,
3304
3755
  createConversationBackend,
@@ -3314,13 +3765,18 @@ export {
3314
3765
  defineConversation,
3315
3766
  defineRuntimeHooks,
3316
3767
  deriveExecutionId,
3768
+ evalPersona,
3317
3769
  exportEvalRuns,
3318
3770
  getModels,
3319
3771
  handleChatTurn,
3772
+ improve,
3773
+ improvementDriver,
3320
3774
  isDelegatedLoopMode,
3321
3775
  isDepthExceeded,
3322
3776
  loopEventToOtelSpan,
3323
3777
  makePerAttemptSignal,
3778
+ mcpBuildPrompt,
3779
+ mcpServeVerifier,
3324
3780
  mcpToolsForRuntimeMcp,
3325
3781
  mcpToolsForRuntimeMcpSubset,
3326
3782
  notifyRuntimeDecisionPoint,
@@ -3328,6 +3784,7 @@ export {
3328
3784
  parseLoopRunnerArgv,
3329
3785
  readDepth,
3330
3786
  readinessServerSentEvent,
3787
+ reflectiveGenerator,
3331
3788
  researchLoopRunner,
3332
3789
  resolveChatModel,
3333
3790
  resolveRouterBaseUrl,
@@ -3349,6 +3806,7 @@ export {
3349
3806
  slugifySpeaker,
3350
3807
  startRuntimeRun,
3351
3808
  streamToolLoop,
3809
+ toolBuildPrompt,
3352
3810
  turnId,
3353
3811
  validateChatModelId,
3354
3812
  worktreeLoopRunner