@tangle-network/agent-runtime 0.141.0 → 0.142.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 (74) hide show
  1. package/README.md +97 -83
  2. package/dist/{activation-4Aa3qXFV.js → activation-CGtQJ3oe.js} +2 -2
  3. package/dist/{activation-4Aa3qXFV.js.map → activation-CGtQJ3oe.js.map} +1 -1
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +3 -3
  6. package/dist/{analyst-loop-DtOEXGzR.js → analyst-loop-xZWlVqS8.js} +2 -2
  7. package/dist/{analyst-loop-DtOEXGzR.js.map → analyst-loop-xZWlVqS8.js.map} +1 -1
  8. package/dist/analyst-loop.d.ts +1 -1
  9. package/dist/analyst-loop.js +1 -1
  10. package/dist/{authoring-Bzow2zKI.js → authoring-Y-OUn4rW.js} +2 -2
  11. package/dist/{authoring-Bzow2zKI.js.map → authoring-Y-OUn4rW.js.map} +1 -1
  12. package/dist/{conversation-C3eZCvLd.js → conversation-DhbLOQdF.js} +2 -2
  13. package/dist/{conversation-C3eZCvLd.js.map → conversation-DhbLOQdF.js.map} +1 -1
  14. package/dist/conversation.d.ts +1 -1
  15. package/dist/conversation.js +1 -1
  16. package/dist/durable.d.ts +2 -2
  17. package/dist/durable.js +1 -1
  18. package/dist/{environment-provider-B985TeIr.d.ts → environment-provider-BicwCDK5.d.ts} +3 -3
  19. package/dist/{environment-provider-BAO8wt1_.js → environment-provider-D1qUgO6B.js} +2 -2
  20. package/dist/{environment-provider-BAO8wt1_.js.map → environment-provider-D1qUgO6B.js.map} +1 -1
  21. package/dist/environment-provider.d.ts +1 -1
  22. package/dist/environment-provider.js +1 -1
  23. package/dist/{graph-BHR5SFUh.js → graph-C4vNgPGB.js} +2 -2
  24. package/dist/{graph-BHR5SFUh.js.map → graph-C4vNgPGB.js.map} +1 -1
  25. package/dist/{improvement-cycle-H_27-d1O.js → improvement-cycle-Bk4Lw_Rq.js} +5 -5
  26. package/dist/{improvement-cycle-H_27-d1O.js.map → improvement-cycle-Bk4Lw_Rq.js.map} +1 -1
  27. package/dist/{index-CTI6v7V6.d.ts → index-CV1xRWy2.d.ts} +3 -3
  28. package/dist/{index-Y7Wnmlip.d.ts → index-IMfesE5D.d.ts} +4 -4
  29. package/dist/{index-D4dUTLcs.d.ts → index-x_iXYWUV.d.ts} +65 -7
  30. package/dist/index.d.ts +9 -9
  31. package/dist/index.js +9 -9
  32. package/dist/intelligence.d.ts +5 -5
  33. package/dist/intelligence.js +4 -4
  34. package/dist/kernel.d.ts +7 -7
  35. package/dist/kernel.js +10 -10
  36. package/dist/{knowledge-C3qWCMJi.js → knowledge-Cf4HsD2i.js} +3 -3
  37. package/dist/{knowledge-C3qWCMJi.js.map → knowledge-Cf4HsD2i.js.map} +1 -1
  38. package/dist/knowledge.d.ts +1 -1
  39. package/dist/knowledge.js +1 -1
  40. package/dist/{loop-runner-bin-Cv-x6lzB.js → loop-runner-bin-B18hKrB1.js} +4 -4
  41. package/dist/{loop-runner-bin-Cv-x6lzB.js.map → loop-runner-bin-B18hKrB1.js.map} +1 -1
  42. package/dist/{loop-runner-bin-Clm1wCGW.d.ts → loop-runner-bin-BLrL1_hI.d.ts} +3 -3
  43. package/dist/loop-runner-bin.d.ts +1 -1
  44. package/dist/loop-runner-bin.js +1 -1
  45. package/dist/mcp/bin.js +3 -3
  46. package/dist/mcp/index.d.ts +5 -5
  47. package/dist/mcp/index.js +4 -4
  48. package/dist/{openai-tools-DabO2cOu.js → openai-tools-DtMJcw3r.js} +2 -2
  49. package/dist/{openai-tools-DabO2cOu.js.map → openai-tools-DtMJcw3r.js.map} +1 -1
  50. package/dist/{openai-tools-5p7xigAz.d.ts → openai-tools-t5-6h5bj.d.ts} +2 -2
  51. package/dist/primeintellect/index.d.ts +1 -1
  52. package/dist/profiles.d.ts +1 -1
  53. package/dist/{redact-D1qhbHWB.d.ts → redact-B0gDSTZO.d.ts} +3 -3
  54. package/dist/{runtime-Dy_u99XS.js → runtime-DCU6DOqI.js} +9 -9
  55. package/dist/{runtime-Dy_u99XS.js.map → runtime-DCU6DOqI.js.map} +1 -1
  56. package/dist/{runtime-CMIt1tII.d.ts → runtime-htqI3fKL.d.ts} +4 -4
  57. package/dist/{sandbox-events-DPmXlcKw.js → sandbox-events-UKNxOsgK.js} +152 -7
  58. package/dist/sandbox-events-UKNxOsgK.js.map +1 -0
  59. package/dist/{stream-agent-turn-4kUH8Nnn.js → stream-agent-turn-CVC9wvg4.js} +2 -2
  60. package/dist/{stream-agent-turn-4kUH8Nnn.js.map → stream-agent-turn-CVC9wvg4.js.map} +1 -1
  61. package/dist/{stream-agent-turn-D8Jaq70U.d.ts → stream-agent-turn-Dfy12OjG.d.ts} +3 -3
  62. package/dist/{structural-rollout-sr5KFnq4.js → structural-rollout-Bncu0lF7.js} +3 -3
  63. package/dist/{structural-rollout-sr5KFnq4.js.map → structural-rollout-Bncu0lF7.js.map} +1 -1
  64. package/dist/{supervise-CqN9ThOr.js → supervise-BA2aQ8vU.js} +2 -2
  65. package/dist/{supervise-CqN9ThOr.js.map → supervise-BA2aQ8vU.js.map} +1 -1
  66. package/dist/{supervisor-3cq3UHmU.js → supervisor-BO7B2eim.js} +104 -100
  67. package/dist/supervisor-BO7B2eim.js.map +1 -0
  68. package/dist/testing.d.ts +2 -2
  69. package/dist/testing.js +11 -11
  70. package/dist/{types-D9WBXD7G.d.ts → types-DZrBoBpN.d.ts} +3 -2
  71. package/dist/{types-CNGHfnk3.d.ts → types-_7w24mMg.d.ts} +2 -2
  72. package/package.json +12 -9
  73. package/dist/sandbox-events-DPmXlcKw.js.map +0 -1
  74. package/dist/supervisor-3cq3UHmU.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"analyst-loop-DtOEXGzR.js","names":[],"sources":["../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n *\n * @experimental\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async hasTrace(trace_id: string): Promise<boolean> {\n return byId.has(trace_id)\n },\n\n async hasSpans(opts): Promise<string[]> {\n const t = byId.get(opts.trace_id)\n if (!t) return []\n const present = new Set(t.spans.map((s) => s.span_id))\n return opts.span_ids.filter((id) => present.has(id))\n },\n\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n // Fill the response up to the per-call byte ceiling; requested spans that\n // exist but do not fit become `omitted_span_ids` continuation work. The\n // first span is always included even when it alone exceeds the ceiling —\n // otherwise a caller could never make progress on an oversized span.\n let truncated = 0\n let bytes = 0\n const spans: TraceAnalystSpan[] = []\n const omitted: string[] = []\n for (const s of found) {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n const projected = { ...s, attributes: capped }\n const size = bytesOf(projected)\n if (spans.length > 0 && bytes + size > budgets.perCallByteCeiling) {\n omitted.push(s.span_id)\n continue\n }\n truncated += n\n bytes += size\n spans.push(projected)\n }\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n omitted_span_ids: omitted,\n has_more: omitted.length > 0,\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const all = span ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget) : []\n const hits = all.slice(0, max)\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n has_more: all.length > hits.length,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge proposal source\n * 6. Hand the findings to the agent-surface proposal source\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Proposal sources are optional: the loop also works as a plain\n * \"run + diff + report\" primitive.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\n/** Analyze a run and apply accepted knowledge and agent-surface proposals. */\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before proposal generation so the ledger remains\n // the source of truth if a proposal source throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge proposals. This loop never writes live knowledge.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeProposalSource) {\n knowledge = await runKnowledgeProposalSource(opts, analystResult.findings, log, emit)\n }\n\n // 6. Agent-surface proposals. This loop never writes live agent state.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementProposalSource) {\n improvement = await runImprovementProposalSource(opts, analystResult.findings, log, emit)\n }\n\n const durationMs = Math.max(0, Date.now() - startedAt)\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n durationMs,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n const registryOptions = {\n ...(priorFindings ? { priorFindings } : {}),\n ...(opts.chainFindings !== undefined ? { chainFindings: opts.chainFindings } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n ...(opts.costPhase ? { costPhase: opts.costPhase } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n }\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, registryOptions)) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, registryOptions)\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeProposalSource<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const source = opts.knowledgeProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n proposals: batch.proposals as TProposal[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nasync function runImprovementProposalSource<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const source = opts.improvementProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n edits: batch.edits as TEdit[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, unknown>): void {\n if (fields) console.log(`[analyst-loop] ${msg}`, fields)\n else console.log(`[analyst-loop] ${msg}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,WAAW,MAAuB,OAAO,WAAW,KAAK,UAAU,CAAC,KAAK,IAAI,MAAM;AACzF,MAAM,OAAO,OAAuB,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;;;AAI7D,SAAS,mBAAmB,SAAyB;CACnD,OAAO,QACJ,QAAQ,mBAAmB,KAAK,CAAC,CACjC,QAAQ,gFAAgF,MAAM,CAAC,CAC/F,QAAQ,oBAAoB,MAAM,CAAC,CACnC,QAAQ,8BAA8B,KAAK,CAAC,CAC5C,QAAQ,YAAY,GAAG,CAAC,CACxB,QAAQ,QAAQ,GAAG,CAAC,CACpB,KAAK,CAAC,CACN,MAAM,GAAG,GAAG;AACjB;AAEA,SAAS,YACP,OACA,cAKA;CACA,MAAM,MAAM,oBAAoB,OAAO,YAAY;CACnD,IAAI,KAAK,OAAO;EAA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QAAQ,MADC,KAAK,0BACO,oBAAoB,QAAQ;CACvD,IAAI,mCAAmC;EACrC,OAAO,MAAM,MAAM;EACnB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,WAAW,MAAM,MAAM;EACvB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,OAAO,MAAM;EACb,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,SAAS,WAAW,KAAa,QAAwC;CACvE,IAAI,QAAQ,QAAQ,IAAI,kBAAkB,OAAO,MAAM;MAClD,QAAQ,IAAI,kBAAkB,KAAK;AAC1C"}
1
+ {"version":3,"file":"analyst-loop-xZWlVqS8.js","names":[],"sources":["../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n *\n * @experimental\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async hasTrace(trace_id: string): Promise<boolean> {\n return byId.has(trace_id)\n },\n\n async hasSpans(opts): Promise<string[]> {\n const t = byId.get(opts.trace_id)\n if (!t) return []\n const present = new Set(t.spans.map((s) => s.span_id))\n return opts.span_ids.filter((id) => present.has(id))\n },\n\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n // Fill the response up to the per-call byte ceiling; requested spans that\n // exist but do not fit become `omitted_span_ids` continuation work. The\n // first span is always included even when it alone exceeds the ceiling —\n // otherwise a caller could never make progress on an oversized span.\n let truncated = 0\n let bytes = 0\n const spans: TraceAnalystSpan[] = []\n const omitted: string[] = []\n for (const s of found) {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n const projected = { ...s, attributes: capped }\n const size = bytesOf(projected)\n if (spans.length > 0 && bytes + size > budgets.perCallByteCeiling) {\n omitted.push(s.span_id)\n continue\n }\n truncated += n\n bytes += size\n spans.push(projected)\n }\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n omitted_span_ids: omitted,\n has_more: omitted.length > 0,\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const all = span ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget) : []\n const hits = all.slice(0, max)\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n has_more: all.length > hits.length,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge proposal source\n * 6. Hand the findings to the agent-surface proposal source\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Proposal sources are optional: the loop also works as a plain\n * \"run + diff + report\" primitive.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\n/** Analyze a run and apply accepted knowledge and agent-surface proposals. */\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before proposal generation so the ledger remains\n // the source of truth if a proposal source throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge proposals. This loop never writes live knowledge.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeProposalSource) {\n knowledge = await runKnowledgeProposalSource(opts, analystResult.findings, log, emit)\n }\n\n // 6. Agent-surface proposals. This loop never writes live agent state.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementProposalSource) {\n improvement = await runImprovementProposalSource(opts, analystResult.findings, log, emit)\n }\n\n const durationMs = Math.max(0, Date.now() - startedAt)\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n durationMs,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n const registryOptions = {\n ...(priorFindings ? { priorFindings } : {}),\n ...(opts.chainFindings !== undefined ? { chainFindings: opts.chainFindings } : {}),\n ...(opts.costLedger ? { costLedger: opts.costLedger } : {}),\n ...(opts.costPhase ? { costPhase: opts.costPhase } : {}),\n ...(opts.signal ? { signal: opts.signal } : {}),\n }\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, registryOptions)) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, registryOptions)\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeProposalSource<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const source = opts.knowledgeProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n proposals: batch.proposals as TProposal[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nasync function runImprovementProposalSource<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const source = opts.improvementProposalSource!\n const batch = await source.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n return {\n edits: batch.edits as TEdit[],\n skipped: batch.skipped,\n errors: batch.errors,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, un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CAC3F,IAAI,aAAa,UAAU,MAAM,WAAW,GAAG,OAAO,KAAA;CACtD,MAAM,WAAW,MAAM,KAAK,EAAE,QAAQ,SAAS,GAAG,WAAW,IAAsB;CACnF,IAAI,aAAa,YACf,OAAO,EAAE,KAAK,SAAS;CAGzB,OAAO;AACT;AAEA,eAAe,2BACb,MACA,UACA,KACA,MACqC;CAErC,MAAM,QAAQ,MADC,KAAK,wBACO,oBAAoB,QAAQ;CACvD,IAAI,iCAAiC;EACnC,WAAW,MAAM,UAAU;EAC3B,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,eAAe,MAAM,UAAU;EAC/B,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,eAAe,6BACb,MACA,UACA,KACA,MACmC;CAEnC,MAAM,QAAQ,MADC,KAAK,0BACO,oBAAoB,QAAQ;CACvD,IAAI,mCAAmC;EACrC,OAAO,MAAM,MAAM;EACnB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CACD,MAAM,KAAK;EACT,MAAM;EACN,OAAO,KAAK;EACZ,WAAW,MAAM,MAAM;EACvB,SAAS,MAAM;EACf,QAAQ,MAAM,OAAO;CACvB,CAAC;CAED,OAAO;EACL,OAAO,MAAM;EACb,SAAS,MAAM;EACf,QAAQ,MAAM;CAChB;AACF;AAEA,SAAS,WAAW,KAAa,QAAwC;CACvE,IAAI,QAAQ,QAAQ,IAAI,kBAAkB,OAAO,MAAM;MAClD,QAAQ,IAAI,kBAAkB,KAAK;AAC1C"}
@@ -1,4 +1,4 @@
1
- import { a as Iteration } from "./types-D9WBXD7G.js";
1
+ import { a as Iteration } from "./types-DZrBoBpN.js";
2
2
  import { a as ImprovementEditBatch, c as KnowledgeProposalBatch, d as RunAnalystLoopOpts, f as RunAnalystLoopResult, i as FindingsStoreLike, l as KnowledgeProposalSource, n as AnalystRegistryLike, o as ImprovementProposalSource, r as AnalystRegistryStreamingLike, s as ImprovementReport, t as AnalystLoopEvent, u as KnowledgeReport } from "./types-zWfqDjeL.js";
3
3
  import { TraceAnalysisStore, TraceAnalystByteBudgets } from "@tangle-network/agent-eval";
4
4
  //#region src/analyst-loop/iterations-to-trace-store.d.ts
@@ -1,2 +1,2 @@
1
- import { n as iterationsToTraceStore, t as runAnalystLoop } from "./analyst-loop-DtOEXGzR.js";
1
+ import { n as iterationsToTraceStore, t as runAnalystLoop } from "./analyst-loop-xZWlVqS8.js";
2
2
  export { iterationsToTraceStore, runAnalystLoop };
@@ -1,4 +1,4 @@
1
- import { v as supervisorPolicyPrompt } from "./supervise-CqN9ThOr.js";
1
+ import { v as supervisorPolicyPrompt } from "./supervise-BA2aQ8vU.js";
2
2
  import { agentProfileSchema } from "@tangle-network/agent-interface";
3
3
  import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
4
4
  //#region src/runtime/supervise/authoring.ts
@@ -160,4 +160,4 @@ function profileRichnessFinding(richness, opts) {
160
160
  //#endregion
161
161
  export { supervisorInstructions as a, profileRichnessFinding as i, assessAuthoredProfile as n, defaultProfileRichnessThresholds as r, asAuthoredProfile as t };
162
162
 
163
- //# sourceMappingURL=authoring-Bzow2zKI.js.map
163
+ //# sourceMappingURL=authoring-Y-OUn4rW.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"authoring-Bzow2zKI.js","names":[],"sources":["../src/runtime/supervise/authoring.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,MAAM,eAAe,OAAO,KAAK,QAAQ;CACzC,IAAI,OAAO,iBAAiB,YAAY,aAAa,KAAK,CAAC,CAAC,WAAW,GAAG,OAAO;CACjF,OAAO;EACL,GAAG,OAAO;EACV,MACE,OAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK,SAAS,IAC9D,OAAO,KAAK,OACZ;EACN,QAAQ;GAAE,GAAG,OAAO,KAAK;GAAQ;EAAa;CAChD;AACF;;;;;;;;AASA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL,uBAAuB;EACvB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,MAAM,OAAO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QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"authoring-Y-OUn4rW.js","names":[],"sources":["../src/runtime/supervise/authoring.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;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;EACA;EACA;EACA;EACA;CACF;AACF;;;;AAKA,SAAgB,uBACd,UACA,MACgB;CAChB,MAAM,aAAa,MAAM,aAAa;CACtC,MAAM,UAAU,SAAS;CACzB,MAAM,QAAQ,SAAS,OACnB,WAAW,SAAS,KAAK,oCAAoC,SAAS,QAAQ,KAAK,IAAI,EAAE,KACzF,WAAW,SAAS,KAAK,8CAA8C,SAAS,WAAW,IAAA,CAAK,QAAQ,CAAC,EAAE;CAM/G,OAAO,YAAY;EACjB;EACA,UAP2C,SAAS,OAClD,SAAS,WAAW,MAClB,SACA,WACF;EAIF,MAAM;EACN;EACA;EACA,YAAY;EACZ,eAAe,CACb;GACE,MAAM;GACN,KAAK,WAAW;GAChB,SAAS,SAAS,SAAS,kBAAkB,SAAS,SAAS,kBAAkB,SAAS,SAAS,SAAS,UAAU,SAAS,UAAU,OAAO,SAAS,OAAO,YAAY,SAAS,SAAS,QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH"}
@@ -1,6 +1,6 @@
1
1
  import { D as providerMessageText } from "./retained-run-binding-Dp2e8xne.js";
2
2
  import { m as ValidationError, r as BackendTransportError } from "./errors-CDZ8XsVj.js";
3
- import { c as nowIso, l as startOrResumeRuntimeSession, n as streamAgentTurn, o as InMemoryRuntimeSessionStore, r as createIterableBackend, s as newRuntimeSession } from "./stream-agent-turn-4kUH8Nnn.js";
3
+ import { c as nowIso, l as startOrResumeRuntimeSession, n as streamAgentTurn, o as InMemoryRuntimeSessionStore, r as createIterableBackend, s as newRuntimeSession } from "./stream-agent-turn-CVC9wvg4.js";
4
4
  import { T as executableAgentProfileSnapshot } from "./materialization-CrdcfWXp.js";
5
5
  //#region src/runtime/profile-execution-backend.ts
6
6
  /**
@@ -1346,4 +1346,4 @@ function runPersonaDispatch(config) {
1346
1346
  //#endregion
1347
1347
  export { makePerAttemptSignal as C, defaultIsRetryable as S, createProfileExecutionBackend as T, readDepth as _, FileConversationJournal as a, DeadlineExceededError as b, createConversationBackend as c, slugifySpeaker as d, turnId as f, isDepthExceeded as g, buildForwardHeaders as h, d1ToSqlAdapter as i, runConversation as l, FORWARD_HEADERS as m, runPersonaDispatch as n, InMemoryConversationJournal as o, DEFAULT_MAX_DEPTH as p, SqlConversationJournal as r, defineConversation as s, runPersonaConversation as t, runConversationStream as u, CircuitBreakerState as v, sleep as w, computeBackoff as x, CircuitOpenError as y };
1348
1348
 
1349
- //# sourceMappingURL=conversation-C3eZCvLd.js.map
1349
+ //# sourceMappingURL=conversation-DhbLOQdF.js.map