@tangle-network/agent-runtime 0.69.0 → 0.70.1

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