@tangle-network/agent-runtime 0.104.0 → 0.105.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 (73) hide show
  1. package/README.md +176 -42
  2. package/dist/agent.js +4 -4
  3. package/dist/candidate-execution/index.d.ts +2 -2
  4. package/dist/candidate-execution/index.js +4 -4
  5. package/dist/{chunk-2QJSNOGK.js → chunk-C5RTIBNZ.js} +2 -2
  6. package/dist/{chunk-SNSMRT6H.js → chunk-CTRA64LY.js} +3 -3
  7. package/dist/{chunk-ZXICDSAK.js → chunk-H5QPIZNX.js} +2 -2
  8. package/dist/{chunk-2X65HYMI.js → chunk-HLKC4UYB.js} +1 -13
  9. package/dist/chunk-HLKC4UYB.js.map +1 -0
  10. package/dist/{chunk-3PPVCS75.js → chunk-HNP72PNU.js} +3 -10
  11. package/dist/chunk-HNP72PNU.js.map +1 -0
  12. package/dist/chunk-OPVWXJ2H.js +75 -0
  13. package/dist/chunk-OPVWXJ2H.js.map +1 -0
  14. package/dist/{chunk-B7K7V22Y.js → chunk-RDOAVVHY.js} +2 -2
  15. package/dist/{chunk-L5DST3QC.js → chunk-SMQXZGLZ.js} +1 -1
  16. package/dist/chunk-SMQXZGLZ.js.map +1 -0
  17. package/dist/{chunk-FJI3EXU3.js → chunk-UHEZW5BU.js} +1104 -588
  18. package/dist/chunk-UHEZW5BU.js.map +1 -0
  19. package/dist/{chunk-HAO4CXHP.js → chunk-VISA6CI3.js} +3 -3
  20. package/dist/{chunk-2UABGGUB.js → chunk-WMTCUOQL.js} +5 -5
  21. package/dist/{chunk-ATDFUJYI.js → chunk-WRTOVNN4.js} +4 -4
  22. package/dist/{chunk-ATDFUJYI.js.map → chunk-WRTOVNN4.js.map} +1 -1
  23. package/dist/{chunk-SBTWKPVR.js → chunk-WSTRQZYQ.js} +1 -1
  24. package/dist/chunk-WSTRQZYQ.js.map +1 -0
  25. package/dist/{chunk-5HNDYWUT.js → chunk-XBG2W2VW.js} +13 -3
  26. package/dist/chunk-XBG2W2VW.js.map +1 -0
  27. package/dist/{chunk-STJEHM5F.js → chunk-YJZA2BIK.js} +2 -2
  28. package/dist/{chunk-STJEHM5F.js.map → chunk-YJZA2BIK.js.map} +1 -1
  29. package/dist/{completion-gate-Bv47cOnn.d.ts → completion-gate-BMy5LGoP.d.ts} +1 -1
  30. package/dist/{coordination-CxtzMxSM.d.ts → coordination-BZZSVYpZ.d.ts} +2 -2
  31. package/dist/index.d.ts +101 -177
  32. package/dist/index.js +373 -235
  33. package/dist/index.js.map +1 -1
  34. package/dist/intelligence.d.ts +49 -40
  35. package/dist/intelligence.js +14 -57
  36. package/dist/intelligence.js.map +1 -1
  37. package/dist/knowledge.d.ts +4 -4
  38. package/dist/knowledge.js +8 -8
  39. package/dist/{local-harness-CtK9dSny.d.ts → local-harness-BDNcl6jI.d.ts} +1 -1
  40. package/dist/{loop-runner-bin-DUOGtvOl.d.ts → loop-runner-bin-68aoM9-7.d.ts} +3 -11
  41. package/dist/loop-runner-bin.d.ts +4 -6
  42. package/dist/loop-runner-bin.js +5 -5
  43. package/dist/loops.d.ts +11 -11
  44. package/dist/loops.js +5 -5
  45. package/dist/mcp/bin.js +2 -2
  46. package/dist/mcp/index.d.ts +7 -8
  47. package/dist/mcp/index.js +6 -6
  48. package/dist/mcp/memory-bin.js +1 -1
  49. package/dist/primeintellect/index.d.ts +2 -3
  50. package/dist/primeintellect/index.js +5 -6
  51. package/dist/primeintellect/index.js.map +1 -1
  52. package/dist/{protected-model-port-DzkUY3HQ.d.ts → protected-model-port-B4t-OQjL.d.ts} +1 -1
  53. package/dist/{improve--2A0gK1-.d.ts → redact-BuFjxBUJ.d.ts} +201 -160
  54. package/dist/{structural-rollout-C4mabf87.d.ts → structural-rollout-DEh6CEsa.d.ts} +2 -2
  55. package/dist/{supervise-7q9F5brx.d.ts → supervise-4_48wwvy.d.ts} +2 -2
  56. package/dist/testing.js +9 -9
  57. package/dist/testing.js.map +1 -1
  58. package/dist/{worktree-fanout-WsOzt8qu.d.ts → worktree-fanout-DxhAWr5Z.d.ts} +2 -2
  59. package/package.json +6 -5
  60. package/skills/build-with-agent-runtime/SKILL.md +15 -9
  61. package/skills/loop-writer/SKILL.md +1 -1
  62. package/dist/chunk-2X65HYMI.js.map +0 -1
  63. package/dist/chunk-3PPVCS75.js.map +0 -1
  64. package/dist/chunk-5HNDYWUT.js.map +0 -1
  65. package/dist/chunk-FJI3EXU3.js.map +0 -1
  66. package/dist/chunk-L5DST3QC.js.map +0 -1
  67. package/dist/chunk-SBTWKPVR.js.map +0 -1
  68. /package/dist/{chunk-2QJSNOGK.js.map → chunk-C5RTIBNZ.js.map} +0 -0
  69. /package/dist/{chunk-SNSMRT6H.js.map → chunk-CTRA64LY.js.map} +0 -0
  70. /package/dist/{chunk-ZXICDSAK.js.map → chunk-H5QPIZNX.js.map} +0 -0
  71. /package/dist/{chunk-B7K7V22Y.js.map → chunk-RDOAVVHY.js.map} +0 -0
  72. /package/dist/{chunk-HAO4CXHP.js.map → chunk-VISA6CI3.js.map} +0 -0
  73. /package/dist/{chunk-2UABGGUB.js.map → chunk-WMTCUOQL.js.map} +0 -0
package/dist/index.js CHANGED
@@ -6,19 +6,18 @@ import {
6
6
  researchLoopRunner,
7
7
  runDelegatedLoop,
8
8
  runLoopRunnerCli,
9
- selfImproveLoopRunner,
10
9
  worktreeLoopRunner
11
- } from "./chunk-3PPVCS75.js";
10
+ } from "./chunk-HNP72PNU.js";
12
11
  import {
13
12
  FileAgentCandidateExecutionClaimStore,
14
13
  buildAgentCandidateBundle,
15
14
  disposePreparedAgentCandidateExecution,
16
15
  recoverExpiredAgentCandidateExecution
17
- } from "./chunk-SNSMRT6H.js";
16
+ } from "./chunk-CTRA64LY.js";
18
17
  import {
19
18
  mcpToolsForRuntimeMcp,
20
19
  mcpToolsForRuntimeMcpSubset
21
- } from "./chunk-2QJSNOGK.js";
20
+ } from "./chunk-C5RTIBNZ.js";
22
21
  import "./chunk-SGKPNBXE.js";
23
22
  import {
24
23
  DEFAULT_ROUTER_BASE_URL,
@@ -54,14 +53,19 @@ import {
54
53
  slugifySpeaker,
55
54
  turnId
56
55
  } from "./chunk-2KGAN2HM.js";
56
+ import {
57
+ defaultRedactor,
58
+ defaultRedactorIdentityMaterial,
59
+ resolveRedactor
60
+ } from "./chunk-OPVWXJ2H.js";
57
61
  import {
58
62
  createProtectedAgentCandidateModelPort,
59
63
  exactProcessProviderAsCandidateExecutor
60
- } from "./chunk-ZXICDSAK.js";
64
+ } from "./chunk-H5QPIZNX.js";
61
65
  import {
62
66
  McpSpawnFault,
63
67
  connectStdioMcp
64
- } from "./chunk-ATDFUJYI.js";
68
+ } from "./chunk-WRTOVNN4.js";
65
69
  import {
66
70
  InMemoryRuntimeSessionStore,
67
71
  createIterableBackend,
@@ -82,40 +86,37 @@ import {
82
86
  knowledgeReadinessDeliverable,
83
87
  runKnowledgeImprovementJob,
84
88
  runSupervisedKnowledgeUpdate
85
- } from "./chunk-2UABGGUB.js";
89
+ } from "./chunk-WMTCUOQL.js";
86
90
  import "./chunk-5QOB7H74.js";
87
91
  import {
88
92
  captureAgentCandidateWorkspace,
89
93
  captureAgentCandidateWorkspaceFiles,
90
94
  createAgentCandidateWorkspacePort,
91
95
  sealAgentCandidateBundle
92
- } from "./chunk-B7K7V22Y.js";
93
- import "./chunk-HAO4CXHP.js";
96
+ } from "./chunk-RDOAVVHY.js";
97
+ import "./chunk-VISA6CI3.js";
94
98
  import {
95
99
  AGENTIC_PROFILE_RESOURCE_ROOT,
96
100
  LIFTED_FINDING_ANALYST_ID,
97
- ROLLOUT_POLICY_BOUNDS,
98
101
  ROLLOUT_POLICY_EXTENSION,
99
102
  agenticGenerator,
100
103
  applyRolloutPolicyToProfile,
101
104
  commandVerifier,
102
105
  defaultBuildPrompt,
103
- enumerateNeighborPolicies,
104
106
  improve,
105
- improvementDriver,
106
107
  isAnalystFinding,
107
108
  normalizeRolloutPolicy,
108
109
  parseRolloutPolicy,
109
110
  rawTraceDistiller,
110
111
  rawTraceEvidenceProblem,
111
112
  requiresRawTraceEvidence,
112
- rolloutPolicyProposer,
113
113
  serializeRolloutPolicy,
114
114
  structuralRolloutPolicyFromProfile,
115
115
  summarizeFindings,
116
116
  toAnalystFindings,
117
+ withMethodRuntimeControls,
117
118
  worktreeChangedPaths
118
- } from "./chunk-FJI3EXU3.js";
119
+ } from "./chunk-UHEZW5BU.js";
119
120
  import {
120
121
  AGENT_CANDIDATE_EXECUTION_SUPPORT,
121
122
  CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV,
@@ -134,15 +135,15 @@ import {
134
135
  persistCandidateOutputArtifact,
135
136
  prepareAgentCandidateExecution,
136
137
  verifyAgentCandidateBundle
137
- } from "./chunk-SBTWKPVR.js";
138
- import "./chunk-5HNDYWUT.js";
138
+ } from "./chunk-WSTRQZYQ.js";
139
+ import "./chunk-XBG2W2VW.js";
139
140
  import "./chunk-DPEUKJRO.js";
140
141
  import {
141
142
  buildDriverSystem,
142
143
  optimizerMethod,
143
144
  researchDriverNote,
144
145
  strategyAuthorMethod
145
- } from "./chunk-STJEHM5F.js";
146
+ } from "./chunk-YJZA2BIK.js";
146
147
  import "./chunk-UPWGXKXB.js";
147
148
  import {
148
149
  INTELLIGENCE_WIRE_VERSION,
@@ -165,7 +166,7 @@ import {
165
166
  notifyRuntimeHookEvent,
166
167
  runBrainLoop,
167
168
  runLocalHarness
168
- } from "./chunk-2X65HYMI.js";
169
+ } from "./chunk-HLKC4UYB.js";
169
170
  import "./chunk-ISPWRSEC.js";
170
171
  import "./chunk-KRBFHMV6.js";
171
172
  import "./chunk-3MDZX7YU.js";
@@ -333,161 +334,10 @@ function mcpBuildPrompt(args) {
333
334
  ].join("\n");
334
335
  }
335
336
 
336
- // src/improvement/campaign-otlp.ts
337
- import { readdirSync, readFileSync } from "fs";
338
- import { basename, dirname, join, resolve } from "path";
339
- import { OPENINFERENCE_SPAN_KIND } from "@tangle-network/agent-eval/traces";
340
- var MAX_WALK_DEPTH = 4;
341
- function campaignCellSpansToOtlp(content, cell, opts = {}) {
342
- const records = parseCampaignSpans(content, cell.cellId);
343
- if (records.length === 0) return [];
344
- const serviceName = opts.serviceName ?? "campaign";
345
- const key = cell.cellKey ?? cell.cellId;
346
- const traceId = foldTo32Hex(key);
347
- const rootSpanId = foldTo16Hex(`${key}::root`);
348
- const startMs = Math.min(...records.map((r) => r.startMs));
349
- const endMs = Math.max(...records.map((r) => r.startMs + (r.durationMs ?? 0)));
350
- const anyError = records.some((r) => r.error !== void 0);
351
- const resource = {
352
- attributes: {
353
- "service.name": serviceName,
354
- "campaign.cell_id": cell.cellId,
355
- ...cell.cellKey ? { "campaign.cell_dir": cell.cellKey } : {}
356
- }
357
- };
358
- const lines = [
359
- JSON.stringify({
360
- trace_id: traceId,
361
- span_id: rootSpanId,
362
- parent_span_id: "",
363
- name: `cell.${cell.cellId}`,
364
- start_time: msToIso(startMs),
365
- end_time: msToIso(endMs),
366
- status: anyError ? { code: "STATUS_CODE_ERROR", message: "one or more spans errored" } : { code: "STATUS_CODE_OK", message: "" },
367
- resource,
368
- attributes: {
369
- [OPENINFERENCE_SPAN_KIND]: "AGENT",
370
- "agent.name": cell.cellId
371
- }
372
- })
373
- ];
374
- for (let i = 0; i < records.length; i++) {
375
- const r = records[i];
376
- lines.push(
377
- JSON.stringify({
378
- trace_id: traceId,
379
- span_id: foldTo16Hex(`${key}::${i}`),
380
- parent_span_id: rootSpanId,
381
- name: r.name,
382
- start_time: msToIso(r.startMs),
383
- end_time: msToIso(r.startMs + (r.durationMs ?? 0)),
384
- status: r.error === void 0 ? { code: "STATUS_CODE_OK", message: "" } : { code: "STATUS_CODE_ERROR", message: r.error },
385
- resource,
386
- attributes: r.attributes
387
- })
388
- );
389
- }
390
- return lines;
391
- }
392
- function convertCampaignDirToOtlp(dir, opts = {}) {
393
- const root = resolve(dir);
394
- const files = findSpansFiles(root, MAX_WALK_DEPTH);
395
- const lines = [];
396
- for (const file of files) {
397
- let content;
398
- try {
399
- content = readFileSync(file, "utf8");
400
- } catch {
401
- continue;
402
- }
403
- const cellDir = dirname(file);
404
- lines.push(
405
- ...campaignCellSpansToOtlp(content, { cellId: basename(cellDir), cellKey: cellDir }, opts)
406
- );
407
- }
408
- return lines.length > 0 ? `${lines.join("\n")}
409
- ` : "";
410
- }
411
- function campaignTraceResolver(opts) {
412
- return (ctx) => {
413
- const priorDir = ctx.generation <= 0 ? join(opts.runDir, "baseline") : join(opts.runDir, `gen-${ctx.generation - 1}`);
414
- const prior = convertCampaignDirToOtlp(priorDir, opts);
415
- if (prior) return prior;
416
- return convertCampaignDirToOtlp(opts.runDir, opts);
417
- };
418
- }
419
- function parseCampaignSpans(content, cellId) {
420
- const out = [];
421
- for (const line of content.split("\n")) {
422
- const trimmed = line.trim();
423
- if (!trimmed) continue;
424
- let raw;
425
- try {
426
- raw = JSON.parse(trimmed);
427
- } catch {
428
- continue;
429
- }
430
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
431
- const o = raw;
432
- if (typeof o.name !== "string" || typeof o.startMs !== "number") continue;
433
- const attributes = { "campaign.cell_id": cellId };
434
- for (const [k, v] of Object.entries(o)) {
435
- if (k === "name" || k === "cellId" || k === "startMs" || k === "durationMs") continue;
436
- attributes[k] = v;
437
- }
438
- out.push({
439
- name: o.name,
440
- cellId,
441
- startMs: o.startMs,
442
- ...typeof o.durationMs === "number" ? { durationMs: o.durationMs } : {},
443
- attributes,
444
- ...typeof o.error === "string" ? { error: o.error } : {}
445
- });
446
- }
447
- return out;
448
- }
449
- function findSpansFiles(dir, depth) {
450
- const out = [];
451
- let entries;
452
- try {
453
- entries = readdirSync(dir, { withFileTypes: true });
454
- } catch {
455
- return out;
456
- }
457
- for (const entry of entries) {
458
- const full = join(dir, entry.name);
459
- if (entry.isFile() && entry.name === "spans.jsonl") {
460
- out.push(full);
461
- } else if (depth > 0 && entry.isDirectory() && !entry.isSymbolicLink()) {
462
- out.push(...findSpansFiles(full, depth - 1));
463
- }
464
- }
465
- return out.sort();
466
- }
467
- function msToIso(ms) {
468
- return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
469
- }
470
- function foldTo16Hex(s) {
471
- const a = fnv1a(s);
472
- const b = fnv1a(`${s}::salt`);
473
- return a + b;
474
- }
475
- function foldTo32Hex(s) {
476
- return foldTo16Hex(s) + foldTo16Hex(`${s}::trace`);
477
- }
478
- function fnv1a(s) {
479
- let h = 2166136261;
480
- for (let i = 0; i < s.length; i++) {
481
- h ^= s.charCodeAt(i);
482
- h = Math.imul(h, 16777619) >>> 0;
483
- }
484
- return h.toString(16).padStart(8, "0");
485
- }
486
-
487
337
  // src/improvement/driver-loop-generator.ts
488
338
  import { spawnSync } from "child_process";
489
- import { readFileSync as readFileSync2, statSync } from "fs";
490
- import { resolve as resolve2, sep } from "path";
339
+ import { readFileSync, statSync } from "fs";
340
+ import { resolve, sep } from "path";
491
341
  var workerOutputTailChars = 2e3;
492
342
  var diffMaxChars = 6e3;
493
343
  var readFileDefaultBytes = 8192;
@@ -701,15 +551,15 @@ function worktreeDiff(worktreePath) {
701
551
  function readWorktreeFile(worktreePath, args) {
702
552
  const rel = typeof args.path === "string" ? args.path : "";
703
553
  if (rel.length === 0) return "error: read_file requires `path`";
704
- const root = resolve2(worktreePath);
705
- const target = resolve2(root, rel);
554
+ const root = resolve(worktreePath);
555
+ const target = resolve(root, rel);
706
556
  if (target !== root && !target.startsWith(root + sep)) {
707
557
  return `error: path escapes the worktree: ${rel}`;
708
558
  }
709
559
  const maxBytes = typeof args.maxBytes === "number" && args.maxBytes > 0 ? Math.min(args.maxBytes, 65536) : readFileDefaultBytes;
710
560
  try {
711
561
  const size = statSync(target).size;
712
- const body = readFileSync2(target, "utf-8").slice(0, maxBytes);
562
+ const body = readFileSync(target, "utf-8").slice(0, maxBytes);
713
563
  return size > maxBytes ? `${body}
714
564
  \u2026 (${size - maxBytes} bytes truncated)` : body;
715
565
  } catch (e) {
@@ -757,68 +607,362 @@ function mcpServeVerifier(spec) {
757
607
  };
758
608
  }
759
609
 
760
- // src/improvement/profile-diff-proposer.ts
610
+ // src/improvement/official-optimizers.ts
611
+ import { isDeepStrictEqual } from "util";
761
612
  import { canonicalJson } from "@tangle-network/agent-eval";
762
613
  import {
763
- changedAgentProfileAxes
764
- } from "@tangle-network/agent-interface";
765
- function profileDiffProposer(options) {
766
- return {
767
- kind: "agent-profile-diff",
768
- async propose(ctx) {
769
- if (typeof ctx.currentSurface !== "string") {
770
- throw new Error("profileDiffProposer requires a serialized AgentProfile surface");
771
- }
772
- const profile = parseSerializedProfile(ctx.currentSurface);
773
- const proposals = await options.proposeDiffs({
774
- ...ctx,
775
- profile
776
- });
777
- const candidates = [];
778
- const normalizedBaseline = applyExactAgentProfileDiff(
779
- profile,
780
- { kind: "agent-profile-diff" },
781
- "profile diff baseline"
614
+ gepaOptimizationMethod,
615
+ skillOptOptimizationMethod
616
+ } from "@tangle-network/agent-eval/campaign";
617
+ var defaultMaxFindingsChars = 5e4;
618
+ var pythonClientDocs = "https://github.com/tangle-network/agent-eval/tree/main/clients/python";
619
+ var bridgeInstall = '`python -m pip install "agent-eval-rpc==0.126.6"`';
620
+ var gepaWheelInstall = '`python -m pip install "gepa[full]==0.1.4"`';
621
+ var gepaSourceInstall = '`python -m pip install "gepa[full] @ git+https://github.com/gepa-ai/gepa.git@f919db0a622e2e9f9204779b81fe00cc1b2d808f"`';
622
+ var skillOptInstall = `${bridgeInstall}, then \`python -m pip install "skillopt @ git+https://github.com/microsoft/SkillOpt.git@61735e3922efc2b90c6d6cab561e62e98452ca90"\``;
623
+ var OfficialOptimizerUnavailableError = class extends ConfigError {
624
+ optimizer;
625
+ constructor(optimizer, cause) {
626
+ const detail = cause instanceof Error ? cause.message : String(cause);
627
+ const install = optimizer === "gepa" ? [
628
+ `Install the Python bridge: ${bridgeInstall}.`,
629
+ `The direct GEPA engine uses the published wheel: ${gepaWheelInstall}.`,
630
+ `Composed recipes and source-only engines use the tested source revision: ${gepaSourceInstall}.`
631
+ ].join(" ") : `Install Microsoft SkillOpt: ${skillOptInstall}.`;
632
+ super(
633
+ [
634
+ `Official ${optimizer === "gepa" ? "GEPA" : "SkillOpt"} could not start.`,
635
+ "Runtime did not use a local fallback.",
636
+ install,
637
+ `Setup: ${pythonClientDocs}.`,
638
+ `Cause: ${detail}`
639
+ ].join(" "),
640
+ { cause }
641
+ );
642
+ this.optimizer = optimizer;
643
+ }
644
+ };
645
+ function officialGepa(options) {
646
+ const {
647
+ background,
648
+ includeFindings = true,
649
+ maxFindingsChars,
650
+ describeScenario,
651
+ describeArtifact,
652
+ redact,
653
+ authorizeSensitiveCandidate,
654
+ ...config
655
+ } = options;
656
+ const redactor = resolveRedactor(redact);
657
+ const redactionPolicyRef = optimizerRedactionPolicyRef(redact);
658
+ assertMaxFindingsChars("officialGepa", maxFindingsChars);
659
+ const objective = redactOptimizerText("officialGepa", "objective", config.objective, redactor);
660
+ return (context) => {
661
+ const externalEvaluationRef = optimizerEvidencePolicyRef({
662
+ runtimeEvaluationRef: context.evaluationRef,
663
+ redactionPolicyRef,
664
+ describeScenario,
665
+ describeArtifact,
666
+ authorizeSensitiveCandidate
667
+ });
668
+ const method = withDependencyHelp(
669
+ "gepa",
670
+ externalEvaluationRef,
671
+ redactor,
672
+ redactionPolicyRef,
673
+ gepaOptimizationMethod({
674
+ ...config,
675
+ objective,
676
+ evaluationId: externalEvaluationRef,
677
+ background: methodBackground({
678
+ context,
679
+ background,
680
+ includeFindings,
681
+ maxFindingsChars,
682
+ label: "officialGepa",
683
+ redactor
684
+ }),
685
+ ...describeScenario ? {
686
+ describeScenario: (scenario) => redactOptimizerEvidence(
687
+ "officialGepa",
688
+ "scenario descriptor",
689
+ describeScenario(scenario),
690
+ redactor
691
+ )
692
+ } : {},
693
+ ...describeArtifact ? {
694
+ describeArtifact: (artifact, scenario) => redactOptimizerEvidence(
695
+ "officialGepa",
696
+ "artifact descriptor",
697
+ describeArtifact(artifact, scenario),
698
+ redactor
699
+ )
700
+ } : {}
701
+ })
702
+ );
703
+ return withMethodRuntimeControls(method, {
704
+ costAttribution: "optimizer-run",
705
+ validateCandidate: (input) => assertSafeOptimizerCandidate("officialGepa", input, authorizeSensitiveCandidate)
706
+ });
707
+ };
708
+ }
709
+ function officialSkillOpt(options) {
710
+ const {
711
+ background,
712
+ includeFindings = true,
713
+ maxFindingsChars,
714
+ describeScenario,
715
+ describeArtifact,
716
+ redact,
717
+ authorizeSensitiveCandidate,
718
+ ...config
719
+ } = options;
720
+ const redactor = resolveRedactor(redact);
721
+ const redactionPolicyRef = optimizerRedactionPolicyRef(redact);
722
+ assertMaxFindingsChars("officialSkillOpt", maxFindingsChars);
723
+ const objective = redactOptimizerText("officialSkillOpt", "objective", config.objective, redactor);
724
+ return (context) => {
725
+ const externalEvaluationRef = optimizerEvidencePolicyRef({
726
+ runtimeEvaluationRef: context.evaluationRef,
727
+ redactionPolicyRef,
728
+ describeScenario,
729
+ describeArtifact,
730
+ authorizeSensitiveCandidate
731
+ });
732
+ const method = withDependencyHelp(
733
+ "skillopt",
734
+ externalEvaluationRef,
735
+ redactor,
736
+ redactionPolicyRef,
737
+ skillOptOptimizationMethod({
738
+ ...config,
739
+ objective,
740
+ evaluationId: externalEvaluationRef,
741
+ background: methodBackground({
742
+ context,
743
+ background,
744
+ includeFindings,
745
+ maxFindingsChars,
746
+ label: "officialSkillOpt",
747
+ redactor
748
+ }),
749
+ ...describeScenario ? {
750
+ describeScenario: (scenario) => redactOptimizerEvidence(
751
+ "officialSkillOpt",
752
+ "scenario descriptor",
753
+ describeScenario(scenario),
754
+ redactor
755
+ )
756
+ } : {},
757
+ ...describeArtifact ? {
758
+ describeArtifact: (artifact, scenario) => redactOptimizerEvidence(
759
+ "officialSkillOpt",
760
+ "artifact descriptor",
761
+ describeArtifact(artifact, scenario),
762
+ redactor
763
+ )
764
+ } : {}
765
+ })
766
+ );
767
+ return withMethodRuntimeControls(method, {
768
+ costAttribution: "optimizer-run",
769
+ validateCandidate: (input) => assertSafeOptimizerCandidate("officialSkillOpt", input, authorizeSensitiveCandidate)
770
+ });
771
+ };
772
+ }
773
+ function assertMaxFindingsChars(label, value) {
774
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0)) {
775
+ throw new ConfigError(`${label}: maxFindingsChars must be a positive safe integer`);
776
+ }
777
+ }
778
+ function methodBackground(options) {
779
+ const {
780
+ context,
781
+ background,
782
+ includeFindings,
783
+ maxFindingsChars = defaultMaxFindingsChars,
784
+ label,
785
+ redactor
786
+ } = options;
787
+ const safeBackground = background === void 0 ? void 0 : redactOptimizerText(label, "background", background, redactor);
788
+ const safeProfileName = context.profile.name === void 0 ? void 0 : redactOptimizerText(label, "profile name", context.profile.name, redactor);
789
+ const sections = [
790
+ safeBackground?.trim(),
791
+ safeProfileName ? `Agent profile: ${safeProfileName}. Surface: ${context.surface}.` : `Agent surface: ${context.surface}.`
792
+ ].filter((value) => Boolean(value));
793
+ if (includeFindings && context.findings.length > 0) {
794
+ let serialized;
795
+ try {
796
+ serialized = canonicalJson(
797
+ redactOptimizerEvidence(label, "findings", context.findings, redactor)
782
798
  );
783
- const seen = /* @__PURE__ */ new Set([canonicalJson(normalizedBaseline)]);
784
- for (const [index, proposal] of proposals.entries()) {
785
- if (candidates.length >= ctx.populationSize || ctx.signal.aborted) break;
786
- const diff = parseExactAgentProfileDiff(proposal, `profile diff proposal ${index}`);
787
- const axes = changedAgentProfileAxes(diff);
788
- if (axes.length === 0) continue;
789
- const candidate = applyExactAgentProfileDiff(
790
- profile,
791
- diff,
792
- `profile diff candidate ${index}`
793
- );
794
- const surface = canonicalJson(candidate);
795
- if (seen.has(surface)) continue;
796
- seen.add(surface);
797
- candidates.push({
798
- surface,
799
- label: diff.title ?? diff.id ?? `Change ${axes.join(", ")}`,
800
- rationale: candidateRationale(diff, axes)
801
- });
799
+ } catch (cause) {
800
+ throw new ConfigError(`${label}: findings must be JSON-serializable`, { cause });
801
+ }
802
+ if (serialized.length > maxFindingsChars) {
803
+ throw new ConfigError(
804
+ `${label}: serialized findings exceed maxFindingsChars (${serialized.length} > ${maxFindingsChars})`
805
+ );
806
+ }
807
+ sections.push(`Observed failures:
808
+ ${serialized}`);
809
+ }
810
+ return sections.join("\n\n");
811
+ }
812
+ function assertSafeOptimizerCandidate(label, input, authorizeSensitiveCandidate) {
813
+ const redactedValue = defaultRedactor(input.value);
814
+ const redactedSurface = defaultRedactor(input.candidateSurface);
815
+ if (!isDeepStrictEqual(input.value, redactedValue) || !isDeepStrictEqual(input.candidateSurface, redactedSurface)) {
816
+ throw new ConfigError(
817
+ `${label}: the selected profile surface contains a common credential or private value. Store live credentials as provider references, or remove private data before starting an external optimizer.`
818
+ );
819
+ }
820
+ const sensitivePaths = sensitiveProfileSurfacePaths(input);
821
+ if (sensitivePaths.length === 0) return;
822
+ let authorized = false;
823
+ if (authorizeSensitiveCandidate) {
824
+ try {
825
+ authorized = authorizeSensitiveCandidate(
826
+ Object.freeze({
827
+ ...input,
828
+ sensitivePaths: Object.freeze([...sensitivePaths])
829
+ })
830
+ ) === true;
831
+ } catch (cause) {
832
+ throw new ConfigError(`${label}: sensitive candidate authorization failed`, { cause });
833
+ }
834
+ }
835
+ if (!authorized) {
836
+ throw new ConfigError(
837
+ `${label}: the selected profile surface contains fields that may carry private values: ${sensitivePaths.slice(0, 8).join(", ")}. Remove them, replace values with safe references, or authorize the exact profile with authorizeSensitiveCandidate.`
838
+ );
839
+ }
840
+ }
841
+ function sensitiveProfileSurfacePaths(input) {
842
+ const paths = /* @__PURE__ */ new Set();
843
+ if (input.surface === "tools" || input.surface === "mcp" || input.surface === "hooks" || input.surface === "subagents" || input.surface === "agent-profile") {
844
+ paths.add("$");
845
+ }
846
+ const seen = /* @__PURE__ */ new WeakSet();
847
+ const visit = (current, path) => {
848
+ if (current === null || typeof current !== "object") return;
849
+ if (seen.has(current)) return;
850
+ seen.add(current);
851
+ if (Array.isArray(current)) {
852
+ current.forEach((child, index) => {
853
+ visit(child, `${path}[${index}]`);
854
+ });
855
+ return;
856
+ }
857
+ for (const [key, child] of Object.entries(current)) {
858
+ const childPath = `${path}.${key}`;
859
+ if (["env", "headers", "url", "metadata", "extensions"].includes(key.toLowerCase())) {
860
+ paths.add(childPath);
861
+ continue;
802
862
  }
803
- return candidates;
863
+ visit(child, childPath);
804
864
  }
805
865
  };
866
+ visit(input.value, "$");
867
+ return [...paths];
806
868
  }
807
- function candidateRationale(diff, axes) {
808
- const reason = diff.rationale ?? `Changes profile axes: ${axes.join(", ")}.`;
809
- const source = diff.source ? [diff.source.kind, ...diff.source.artifacts ?? []].join(" \xB7 ") : "source unspecified";
810
- return `${reason} Source: ${source}. Diff: ${canonicalCandidateDigest(diff)}.`;
811
- }
812
- function parseSerializedProfile(surface) {
813
- let raw;
869
+ function redactOptimizerEvidence(label, field, value, redactor) {
814
870
  try {
815
- raw = JSON.parse(surface);
871
+ return redactor(value);
816
872
  } catch (cause) {
817
- throw new Error("profileDiffProposer current surface is not valid AgentProfile JSON", {
818
- cause
819
- });
873
+ throw new ConfigError(`${label}: ${field} redaction failed`, { cause });
820
874
  }
821
- return parseExactAgentProfile(raw, "profileDiffProposer current profile");
875
+ }
876
+ function redactOptimizerText(label, field, value, redactor) {
877
+ const redacted = redactOptimizerEvidence(label, field, value, redactor);
878
+ if (typeof redacted !== "string" || !redacted.trim()) {
879
+ throw new ConfigError(`${label}: ${field} redaction must return a non-empty string`);
880
+ }
881
+ return redacted;
882
+ }
883
+ function redactJudgeScore(score, redactor) {
884
+ const notes = redactOptimizerEvidence("official optimizer", "judge notes", score.notes, redactor);
885
+ return {
886
+ ...score,
887
+ notes: typeof notes === "string" ? notes : "[redacted]"
888
+ };
889
+ }
890
+ function optimizerRedactionPolicyRef(redact, builtInIdentity = defaultRedactorIdentityMaterial()) {
891
+ if (redact === false) return "caller-approved-raw";
892
+ return canonicalCandidateDigest({
893
+ kind: redact === void 0 ? "default-redactor" : "caller-redactor-with-default",
894
+ builtIn: builtInIdentity,
895
+ ...redact === void 0 ? {} : {
896
+ callerSource: Function.prototype.toString.call(redact),
897
+ composition: Function.prototype.toString.call(resolveRedactor)
898
+ }
899
+ });
900
+ }
901
+ function optimizerEvidencePolicyRef(input) {
902
+ return canonicalCandidateDigest({
903
+ runtimeEvaluationRef: input.runtimeEvaluationRef,
904
+ redactionPolicyRef: input.redactionPolicyRef,
905
+ describeScenario: callbackSource(input.describeScenario),
906
+ describeArtifact: callbackSource(input.describeArtifact),
907
+ authorizeSensitiveCandidate: callbackSource(input.authorizeSensitiveCandidate)
908
+ });
909
+ }
910
+ function callbackSource(callback) {
911
+ return typeof callback === "function" ? Function.prototype.toString.call(callback) : null;
912
+ }
913
+ function withDependencyHelp(optimizer, evaluationRef, redactor, redactionPolicyRef, method) {
914
+ return {
915
+ ...method,
916
+ async optimize(input) {
917
+ try {
918
+ const judges = input.judges.map(
919
+ (judge) => Object.freeze({
920
+ ...judge,
921
+ judgeVersion: canonicalCandidateDigest({
922
+ evaluationRef,
923
+ name: judge.name,
924
+ dimensions: judge.dimensions,
925
+ judgeVersion: judge.judgeVersion ?? null,
926
+ outwardEvidence: redactionPolicyRef
927
+ }),
928
+ async score(scoreInput) {
929
+ return redactJudgeScore(await judge.score(scoreInput), redactor);
930
+ }
931
+ })
932
+ );
933
+ return await method.optimize({
934
+ ...input,
935
+ judges: Object.freeze(judges)
936
+ });
937
+ } catch (cause) {
938
+ if (isMissingDependency(optimizer, cause)) {
939
+ throw new OfficialOptimizerUnavailableError(optimizer, cause);
940
+ }
941
+ throw cause;
942
+ }
943
+ }
944
+ };
945
+ }
946
+ function isMissingDependency(optimizer, cause) {
947
+ const message = cause instanceof Error ? cause.message : String(cause);
948
+ const common = [
949
+ `${optimizer === "gepa" ? "GEPA" : "SkillOpt"} bridge could not start`,
950
+ "source inspection could not start",
951
+ "No module named 'agent_eval_rpc'",
952
+ `No module named 'agent_eval_rpc.${optimizer === "gepa" ? "gepa_bridge" : "skillopt_bridge"}'`
953
+ ];
954
+ const specific = optimizer === "gepa" ? [
955
+ "requires GEPA",
956
+ "requires GEPA's Optimize Anything",
957
+ "No module named 'gepa'",
958
+ "gepa is importable but its package metadata is unavailable"
959
+ ] : [
960
+ "requires skillopt",
961
+ "requires SkillOpt",
962
+ "No module named 'skillopt'",
963
+ "skillopt is importable but its package metadata is unavailable"
964
+ ];
965
+ return [...common, ...specific].some((fragment) => message.includes(fragment));
822
966
  }
823
967
 
824
968
  // src/improvement/reflective-generator.ts
@@ -1925,9 +2069,9 @@ export {
1925
2069
  JudgeError,
1926
2070
  LIFTED_FINDING_ANALYST_ID,
1927
2071
  NotFoundError,
2072
+ OfficialOptimizerUnavailableError,
1928
2073
  PlannerError,
1929
2074
  RESEARCH_SUPERVISOR_SYSTEM_PROMPT,
1930
- ROLLOUT_POLICY_BOUNDS,
1931
2075
  ROLLOUT_POLICY_EXTENSION,
1932
2076
  RuntimeRunStateError,
1933
2077
  SqlConversationJournal,
@@ -1945,8 +2089,6 @@ export {
1945
2089
  buildLoopOtelSpans,
1946
2090
  buildLoopSpanNodes,
1947
2091
  buildRuntimeEventOtelSpans,
1948
- campaignCellSpansToOtlp,
1949
- campaignTraceResolver,
1950
2092
  candidateExecutionClaim,
1951
2093
  candidateKnowledgeExecutionPaths,
1952
2094
  captureAgentCandidateWorkspace,
@@ -1955,7 +2097,6 @@ export {
1955
2097
  commandVerifier,
1956
2098
  composeRuntimeHooks,
1957
2099
  computeBackoff,
1958
- convertCampaignDirToOtlp,
1959
2100
  createAgentCandidateWorkspacePort,
1960
2101
  createAgentKnowledgeReadinessCheck,
1961
2102
  createConversationBackend,
@@ -1977,7 +2118,6 @@ export {
1977
2118
  deriveExecutionId,
1978
2119
  disposePreparedAgentCandidateExecution,
1979
2120
  driverLoopGenerator,
1980
- enumerateNeighborPolicies,
1981
2121
  exactProcessProviderAsCandidateExecutor,
1982
2122
  executePreparedAgentCandidate,
1983
2123
  exportEvalRuns,
@@ -1986,7 +2126,6 @@ export {
1986
2126
  getModels,
1987
2127
  handleChatTurn,
1988
2128
  improve,
1989
- improvementDriver,
1990
2129
  isAnalystFinding,
1991
2130
  isDelegatedLoopMode,
1992
2131
  isDepthExceeded,
@@ -2000,6 +2139,8 @@ export {
2000
2139
  normalizeRolloutPolicy,
2001
2140
  notifyRuntimeDecisionPoint,
2002
2141
  notifyRuntimeHookEvent,
2142
+ officialGepa,
2143
+ officialSkillOpt,
2003
2144
  optimizerMethod,
2004
2145
  parseExactAgentProfile,
2005
2146
  parseExactAgentProfileDiff,
@@ -2007,7 +2148,6 @@ export {
2007
2148
  parseRolloutPolicy,
2008
2149
  persistCandidateOutputArtifact,
2009
2150
  prepareAgentCandidateExecution,
2010
- profileDiffProposer,
2011
2151
  rawTraceDistiller,
2012
2152
  readDepth,
2013
2153
  readinessServerSentEvent,
@@ -2018,7 +2158,6 @@ export {
2018
2158
  resolveAgentBackend,
2019
2159
  resolveChatModel,
2020
2160
  resolveRouterBaseUrl,
2021
- rolloutPolicyProposer,
2022
2161
  runAgentTask,
2023
2162
  runAgentTaskStream,
2024
2163
  runConversation,
@@ -2035,7 +2174,6 @@ export {
2035
2174
  sanitizeKnowledgeReadinessReport,
2036
2175
  sanitizeRuntimeStreamEvent,
2037
2176
  sealAgentCandidateBundle,
2038
- selfImproveLoopRunner,
2039
2177
  serializeRolloutPolicy,
2040
2178
  sleep,
2041
2179
  slugifySpeaker,