@zenera/neo 1.1.10 → 1.1.12

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 (90) hide show
  1. package/README.md +3 -3
  2. package/dist/agent.d.ts +8 -7
  3. package/dist/agent.js +15 -8
  4. package/dist/architecture.d.ts +7 -5
  5. package/dist/architecture.js +20 -12
  6. package/dist/embedding.d.ts +20 -1
  7. package/dist/embedding.js +3 -2
  8. package/dist/embeddings/fanout.d.ts +51 -0
  9. package/dist/embeddings/fanout.js +76 -0
  10. package/dist/embeddings/gemini.d.ts +3 -10
  11. package/dist/embeddings/gemini.js +46 -30
  12. package/dist/embeddings/index.d.ts +3 -0
  13. package/dist/embeddings/index.js +3 -0
  14. package/dist/embeddings/limiter.d.ts +36 -0
  15. package/dist/embeddings/limiter.js +182 -0
  16. package/dist/embeddings/openai.d.ts +3 -2
  17. package/dist/embeddings/openai.js +54 -13
  18. package/dist/embeddings/openrouter.d.ts +2 -1
  19. package/dist/embeddings/openrouter.js +52 -23
  20. package/dist/embeddings/rate-limit.d.ts +16 -0
  21. package/dist/embeddings/rate-limit.js +131 -0
  22. package/dist/failure.d.ts +82 -0
  23. package/dist/failure.js +323 -0
  24. package/dist/index.d.ts +13 -2
  25. package/dist/index.js +13 -2
  26. package/dist/inspect/client.d.ts +1 -1
  27. package/dist/inspect/client.js +42 -26
  28. package/dist/kernel.d.ts +1 -1
  29. package/dist/kernel.js +40 -23
  30. package/dist/memory/files.d.ts +24 -0
  31. package/dist/memory/files.js +85 -0
  32. package/dist/memory/graph.d.ts +56 -0
  33. package/dist/memory/graph.js +159 -0
  34. package/dist/memory/index.d.ts +93 -0
  35. package/dist/memory/index.js +357 -0
  36. package/dist/memory/instructions.d.ts +15 -0
  37. package/dist/memory/instructions.js +103 -0
  38. package/dist/memory/page.d.ts +8 -0
  39. package/dist/memory/page.js +797 -0
  40. package/dist/memory/recall.d.ts +35 -0
  41. package/dist/memory/recall.js +161 -0
  42. package/dist/memory/render.d.ts +10 -0
  43. package/dist/memory/render.js +228 -0
  44. package/dist/memory/report.d.ts +57 -0
  45. package/dist/memory/report.js +113 -0
  46. package/dist/memory/store.d.ts +49 -0
  47. package/dist/memory/store.js +226 -0
  48. package/dist/memory/tools.d.ts +11 -0
  49. package/dist/memory/tools.js +310 -0
  50. package/dist/memory/types.d.ts +192 -0
  51. package/dist/memory/types.js +105 -0
  52. package/dist/memory/vectors.d.ts +29 -0
  53. package/dist/memory/vectors.js +152 -0
  54. package/dist/models/anthropic.d.ts +2 -1
  55. package/dist/models/anthropic.js +11 -4
  56. package/dist/models/factory.d.ts +15 -0
  57. package/dist/models/factory.js +49 -10
  58. package/dist/models/gemini.d.ts +2 -1
  59. package/dist/models/gemini.js +8 -3
  60. package/dist/models/openai-chat.d.ts +2 -1
  61. package/dist/models/openai-chat.js +10 -5
  62. package/dist/models/openai-responses.d.ts +2 -1
  63. package/dist/models/openai-responses.js +22 -7
  64. package/dist/models/openrouter.d.ts +2 -1
  65. package/dist/models/openrouter.js +14 -6
  66. package/dist/project/config.d.ts +55 -3
  67. package/dist/project/config.js +76 -1
  68. package/dist/project/index.d.ts +2 -2
  69. package/dist/project/index.js +1 -1
  70. package/dist/project/load.d.ts +16 -2
  71. package/dist/project/load.js +67 -1
  72. package/dist/runner.d.ts +4 -2
  73. package/dist/runner.js +29 -30
  74. package/dist/services.d.ts +23 -6
  75. package/dist/services.js +25 -15
  76. package/dist/tools/workspace.js +195 -17
  77. package/dist/trajectory.d.ts +14 -12
  78. package/dist/types.d.ts +5 -5
  79. package/dist/types.js +3 -3
  80. package/package.json +2 -5
  81. package/dist/memory-stores/factory.d.ts +0 -15
  82. package/dist/memory-stores/factory.js +0 -29
  83. package/dist/memory-stores/file.d.ts +0 -37
  84. package/dist/memory-stores/file.js +0 -174
  85. package/dist/memory-stores/in-memory.d.ts +0 -17
  86. package/dist/memory-stores/in-memory.js +0 -80
  87. package/dist/memory-stores/index.d.ts +0 -4
  88. package/dist/memory-stores/index.js +0 -5
  89. package/dist/memory.d.ts +0 -115
  90. package/dist/memory.js +0 -213
@@ -1,2 +1,2 @@
1
- export declare const CLIENT = "\nconst DATA = JSON.parse(document.getElementById('run-data').textContent);\nconst STATE = DATA.state;\nconst BLOBS = DATA.blobs;\nconst MEDIA = DATA.media || [];\nconst CUT = new Set(DATA.truncated || []);\n\n// --- payload access -------------------------------------------------------\n\nfunction blob(ref) {\n if (!ref || typeof ref.sha256 !== 'string') return '';\n const v = BLOBS[ref.sha256];\n if (v === undefined) return '[payload not resolved: ' + ref.sha256.slice(0, 12) + ']';\n return CUT.has(ref.sha256) ? v + '\\n\\n[\u2026 truncated, ' + ref.size + ' bytes total]' : v;\n}\n\nfunction pretty(raw) {\n try { return JSON.stringify(JSON.parse(raw), null, 2); } catch (e) { return raw; }\n}\n\n// --- flatten the trajectory ----------------------------------------------\n\nconst ENTRIES = [];\nconst BY_KEY = new Map();\n\nfunction covered(nodes) {\n const out = new Set();\n for (const n of nodes) if (n.type === 'compaction') for (const id of n.covers) out.add(id);\n return out;\n}\n\nfunction flatten(nodes, depth, branch) {\n const hidden = covered(nodes);\n const level = [];\n for (const node of nodes) {\n const e = {\n key: '', node: node, depth: depth, branch: branch,\n covered: hidden.has(node.id), children: []\n };\n // A join's branches ran between the fork and the join, so they are\n // numbered and listed there \u2014 which means recursing before this entry\n // takes its own number.\n if (node.type === 'join') {\n for (const b of node.branches) e.children.push({ name: b.name, entries: flatten(b.nodes, depth + 1, b.name) });\n }\n e.key = 'n' + ENTRIES.length;\n ENTRIES.push(e); BY_KEY.set(e.key, e); level.push(e);\n }\n return level;\n}\nconst ROOT = flatten(STATE.trajectory, 0, null);\n\n// --- labels ---------------------------------------------------------------\n\nfunction names(list) { return list.join(', '); }\n\nfunction base(path) { return path.split('/').pop() || path; }\n\nfunction label(n) {\n switch (n.type) {\n case 'user_input': return n.synthetic ? 'user input (synthetic)' : 'user input';\n case 'system_prompt': return 'system prompt'\n + (n.sources && n.sources.length ? ': ' + names(n.sources.map(function (s) { return base(s.path); })) : '');\n case 'load_skills': return 'skills: ' + names(n.skills.map(function (s) { return s.name; }));\n case 'memory_recall': return 'memory recall: ' + n.scope;\n case 'memory_op': return 'memory ' + n.op;\n case 'llm_call': return 'llm: ' + n.model + (n.toolCalls.length\n ? ' -> ' + names(n.toolCalls.map(function (c) { return c.name; })) : '');\n case 'tool_call': return 'call: ' + n.name;\n case 'tool_result': return 'result: ' + n.name + (n.isError ? ' (error)' : '');\n case 'handoff': return 'handoff: ' + n.from + ' -> ' + n.to;\n case 'fork': return 'fork: ' + names(n.branches.map(function (b) { return b.name; }));\n case 'join': return 'join: ' + names(n.branches.map(function (b) { return b.name + '=' + b.status; }));\n case 'compaction': return 'compaction: ' + n.reason + ' (' + n.covers.length + ' nodes)';\n case 'final_output': return 'final output';\n default: return n.type;\n }\n}\n\nfunction preview(n) {\n switch (n.type) {\n case 'user_input': {\n const t = n.content.find(function (p) { return p.type === 'text'; });\n return t ? blob(t.text) : '';\n }\n case 'system_prompt': return blob(n.prompt);\n case 'llm_call': return blob(n.text);\n case 'tool_call': return blob(n.args);\n case 'tool_result': return blob(n.result);\n case 'compaction': return blob(n.summary);\n case 'final_output': return blob(n.output);\n case 'memory_recall': return blob(n.content);\n case 'load_skills': return blob(n.content);\n default: return '';\n }\n}\n\n// --- DOM helpers ----------------------------------------------------------\n\nfunction el(tag, cls, text) {\n const e = document.createElement(tag);\n if (cls) e.className = cls;\n if (text !== undefined && text !== null) e.textContent = String(text);\n return e;\n}\n\nfunction block(title, tag) {\n const s = el('section', 'blk');\n const h = el('h3', null, title);\n if (tag) h.appendChild(el('span', 'tag', tag));\n s.appendChild(h);\n return s;\n}\n\nfunction textBlock(title, body, tag) {\n const s = block(title, tag);\n if (body) s.appendChild(el('pre', 'text', body));\n else s.appendChild(el('div', 'empty', '(empty)'));\n return s;\n}\n\nfunction foldBlock(title, body) {\n const s = block(title);\n const d = document.createElement('details');\n d.appendChild(el('summary', null, 'show'));\n d.appendChild(el('pre', null, body));\n s.appendChild(d);\n return s;\n}\n\n// An <img> never runs script, but the src is still pinned to shapes we\n// understand: a raster data: uri (svg is excluded on principle) or an http url.\nconst IMG_SUBTYPES = ['png', 'jpeg', 'jpg', 'gif', 'webp', 'avif', 'bmp'];\n\n/** Undoes the report's media hoisting; anything else passes through. */\nfunction mediaUrl(u) {\n if (typeof u !== 'string' || u.indexOf('media:') !== 0) return u;\n const v = MEDIA[Number(u.slice(6))];\n return v === undefined ? u : v;\n}\n\nfunction imageSrc(p) {\n if (p.type !== 'image') return null;\n const u = mediaUrl(p.url);\n if (typeof u !== 'string') return null;\n if (u.indexOf('https://') === 0 || u.indexOf('http://') === 0) return u;\n if (u.indexOf('data:image/') !== 0) return null;\n const sub = u.slice(11).split(/[;,]/)[0].toLowerCase();\n return IMG_SUBTYPES.indexOf(sub) < 0 ? null : u;\n}\n\n/** The rendered picture, or null when the part is not one we will inline. */\nfunction imageEl(p, thumb) {\n const src = imageSrc(p);\n if (!src) return null;\n const img = el('img', thumb ? 'media thumb' : 'media');\n img.src = src;\n img.alt = p.type + (p.mimeType ? ' ' + p.mimeType : '');\n img.loading = 'lazy';\n if (thumb) {\n img.title = 'click to enlarge';\n img.addEventListener('click', function () { img.classList.toggle('thumb'); });\n }\n return img;\n}\n\nfunction mediaBlock(title, p) {\n const tag = p.type + (p.mimeType ? ' \u00B7 ' + p.mimeType : '');\n const src = imageSrc(p);\n const img = imageEl(p, false);\n if (!img) return textBlock(title, mediaUrl(p.url), tag);\n const s = block(title, tag);\n s.appendChild(img);\n // The bytes stay reachable; they just no longer own the screen.\n const d = document.createElement('details');\n d.appendChild(el('summary', null, 'source'));\n d.appendChild(el('pre', null, src));\n s.appendChild(d);\n return s;\n}\n\n// A titled container for several blocks. Returns the element to append and the\n// body to fill, so callers never have to know the internal structure.\nfunction group(title, kind, tag) {\n const s = el('section', 'group ' + kind);\n const h = el('div', 'ghdr', title);\n if (tag) h.appendChild(el('span', 'tag', tag));\n s.appendChild(h);\n const body = el('div', 'body');\n s.appendChild(body);\n return { el: s, body: body };\n}\n\nfunction stat(key, value) {\n const d = el('span', 'stat', key + ' ');\n d.appendChild(el('b', null, value));\n return d;\n}\n\n// --- header ---------------------------------------------------------------\n\nfunction kv(key, value) {\n const d = el('div', 'kv');\n d.appendChild(document.createTextNode(key + ' '));\n d.appendChild(el('b', null, value));\n return d;\n}\n\n(function head() {\n const h = document.getElementById('head');\n const u = STATE.usage || {};\n const llm = ENTRIES.filter(function (e) { return e.node.type === 'llm_call'; }).length;\n h.appendChild(el('h1', null, DATA.title));\n h.appendChild(kv('run', STATE.runId));\n h.appendChild(kv('agent', STATE.agentName));\n h.appendChild(kv('phase', STATE.phase));\n h.appendChild(kv('nodes', ENTRIES.length));\n h.appendChild(kv('llm calls', llm));\n h.appendChild(kv('tokens', (u.inputTokens || 0) + ' in / ' + (u.outputTokens || 0) + ' out'));\n if (STATE.error) h.appendChild(kv('error', STATE.error));\n h.appendChild(kv('generated', DATA.generatedAt));\n})();\n\n// --- timing ---------------------------------------------------------------\n//\n// A node is stamped when it is appended, which is when the work behind it\n// finished. So the interval between a node and the one before it in the same\n// lane *is* that work: an llm_call's interval is the model latency, a\n// tool_result's is the tool. That gives every node a start and a duration\n// without storing either.\n//\n// Offsets are counted from the start of the turn, not of the run: in a\n// follow-up the interesting question is \"how long did this answer take\", and\n// counting from a conversation that began an hour ago answers nothing. A trunk\n// user_input opens a new turn; a branch inherits the turn that forked it, so\n// ten branches starting at one offset still read as parallel.\n\nfunction stampOf(node) {\n const t = Date.parse(node.ts);\n return isNaN(t) ? null : t;\n}\n\n(function time(level, lanePrev, turnStart) {\n let prev = lanePrev;\n let t0 = turnStart;\n level.forEach(function (e) {\n const ts = stampOf(e.node);\n // A real user turn resets the clock and starts at itself: the gap since\n // the previous run is waiting, not work. Synthetic inputs (a branch seed,\n // a re-injection) are not turns \u2014 same rule the kernel uses.\n const opensTurn = !e.branch && e.node.type === 'user_input' && !e.node.synthetic;\n if (opensTurn) t0 = ts;\n e.turnStart = t0 === null ? ts : t0;\n e.startMs = opensTurn || prev === null ? ts : prev;\n e.endMs = ts;\n // Branches run between the fork and the join, so they start where the\n // trunk left off \u2014 and the join's own duration is the whole parallel\n // section it waited on.\n if (e.node.type === 'join') {\n let slowest = null;\n e.children.forEach(function (br) {\n time(br.entries, prev, e.turnStart);\n // The branch as a whole gets the same shape as a node \u2014 start, end,\n // turn \u2014 so a reader sees how long *it* ran instead of having to\n // subtract two offsets to find out that ten branches were parallel.\n const last = br.entries[br.entries.length - 1];\n br.turnStart = e.turnStart;\n br.startMs = prev;\n br.endMs = last ? last.endMs : prev;\n if (br.entries.length) br.entries[0].branchSpan = br;\n // The join costs exactly its slowest branch, so that branch is the\n // only one worth optimizing: it gets marked and rendered lighter.\n if (br.entries.length && (!slowest || br.endMs > slowest.endMs)) slowest = br;\n });\n if (slowest) slowest.slowest = true;\n }\n prev = ts;\n });\n})(ROOT, null, null);\n\nfunction fmtSecs(ms) {\n const s = ms / 1000;\n if (s < 100) return s.toFixed(1) + 's';\n const m = Math.floor(s / 60);\n return m + 'm' + String(Math.floor(s - m * 60)).padStart(2, '0');\n}\n\n/** Offset of a node's start from the beginning of its turn. */\nfunction startedAt(e) {\n if (e.startMs === null || e.turnStart === null) return '';\n return fmtSecs(e.startMs - e.turnStart);\n}\n\n/** How long the work behind a node took. Blank when it is not worth a number. */\nfunction took(e) {\n if (e.startMs === null || e.endMs === null) return '';\n const ms = e.endMs - e.startMs;\n if (ms < 10) return '';\n return fmtDur(ms);\n}\n\nfunction fmtDur(ms) {\n return ms < 1000 ? Math.round(ms) + 'ms' : fmtSecs(ms);\n}\n\nfunction spanMs(e) {\n return e.startMs === null || e.endMs === null ? 0 : e.endMs - e.startMs;\n}\n\n// One colour per branch, stable for the life of the page. The trunk keeps the\n// neutral accent so branches are the thing that stands out.\nconst PALETTE = ['#6ea8fe', '#4ec9a0', '#e2b341', '#d1a6ff', '#f0776c',\n '#5fd0d8', '#f09a5c', '#a3d160', '#ef8ec0', '#9aa4ff'];\nconst BRANCH_COLOR = new Map();\nfunction branchColor(name) {\n if (!name) return null;\n if (!BRANCH_COLOR.has(name)) BRANCH_COLOR.set(name, PALETTE[BRANCH_COLOR.size % PALETTE.length]);\n return BRANCH_COLOR.get(name);\n}\n\n// --- timeline -------------------------------------------------------------\n\nconst listEl = document.getElementById('timeline');\nlet lastBranch = false;\nlet lastStamp = null;\n\nENTRIES.forEach(function (e, i) {\n // Branch histories are contiguous in the flattened order, so a change of\n // branch is a group boundary: label it and restart the elapsed column.\n if (e.branch !== lastBranch) {\n const sep = el('li', 'sep');\n const color = branchColor(e.branch);\n if (color) sep.style.setProperty('--bc', color);\n sep.appendChild(el('span', 'dot'));\n sep.appendChild(el('span', null, e.branch ? 'branch \u00B7 ' + e.branch : 'trunk'));\n if (e.branchSpan) {\n const bd = took(e.branchSpan);\n if (e.branchSpan.slowest) sep.classList.add('slow');\n if (bd) {\n sep.appendChild(el('span', 'dur',\n 't+' + startedAt(e.branchSpan) + ' \u00B7 ' + bd + (e.branchSpan.slowest ? ' \u00B7 slowest' : '')));\n }\n }\n listEl.appendChild(sep);\n lastBranch = e.branch;\n lastStamp = null;\n }\n\n const li = el('li', e.branch ? 'branch' : '');\n if (e.covered) li.classList.add('covered');\n const color = branchColor(e.branch);\n if (color) li.style.setProperty('--bc', color);\n li.dataset.key = e.key;\n\n const row = el('div', 'row');\n // Consecutive nodes often start at the same instant (a tool call is recorded\n // the moment the response carrying it is applied). Repeating the offset\n // would only bury the moments where time actually moved.\n const at = startedAt(e);\n row.appendChild(el('span', 't' + (at === lastStamp ? ' same' : ''), at === lastStamp ? '\u00B7' : at));\n lastStamp = at;\n row.appendChild(el('span', 'idx', '#' + (i + 1)));\n const badge = el('span', 'type ' + e.node.type\n + (e.node.type === 'tool_result' && e.node.isError ? ' err' : ''), e.node.type.replace(/_/g, ' '));\n row.appendChild(badge);\n const d = took(e);\n if (d) row.appendChild(el('span', 'dur', d));\n li.appendChild(row);\n li.appendChild(el('div', 'prev', label(e.node)\n + (preview(e.node) ? ' \u2014 ' + preview(e.node).slice(0, 90) : '')));\n li.addEventListener('click', function () { select(e.key, true); });\n listEl.appendChild(li);\n});\n\n// A group header is only worth showing while something in its group is.\nfunction applyFilter(q) {\n const rows = Array.prototype.slice.call(listEl.children);\n rows.forEach(function (li) {\n if (li.classList.contains('sep')) return;\n const e = BY_KEY.get(li.dataset.key);\n const hay = (label(e.node) + ' ' + e.node.type + ' ' + (e.branch || '')\n + ' ' + preview(e.node)).toLowerCase();\n li.hidden = q.length > 0 && hay.indexOf(q) === -1;\n });\n let sep = null, kept = false;\n rows.forEach(function (li) {\n if (li.classList.contains('sep')) {\n if (sep) sep.hidden = !kept;\n sep = li; kept = false;\n } else if (!li.hidden) kept = true;\n });\n if (sep) sep.hidden = !kept;\n}\n\ndocument.getElementById('filter').addEventListener('input', function (ev) {\n applyFilter(ev.target.value.toLowerCase());\n});\n\n// --- detail ---------------------------------------------------------------\n\nfunction message(m) {\n const wrap = el('div', 'msg ' + m.role + (m.isError ? ' err' : ''));\n const role = el('div', 'role');\n role.appendChild(el('span', null, m.role + (m.agent ? ' \u00B7 ' + m.agent : '')\n + (m.name ? ' \u00B7 ' + m.name : '')));\n if (m.callId) role.appendChild(el('span', 'badge', m.callId));\n wrap.appendChild(role);\n\n if (m.role === 'user' && Array.isArray(m.content)) {\n m.content.forEach(function (p) {\n if (p.type === 'text') { wrap.appendChild(el('pre', 'text', p.text)); return; }\n const img = imageEl(p, true);\n wrap.appendChild(img || el('pre', 'text', '[' + p.type + '] ' + mediaUrl(p.url)));\n });\n } else if (typeof m.content === 'string' && m.content) {\n wrap.appendChild(el('pre', 'text', m.role === 'tool' ? pretty(m.content) : m.content));\n } else if (!m.toolCalls) {\n wrap.appendChild(el('div', 'empty', '(no content)'));\n }\n\n (m.toolCalls || []).forEach(function (c) {\n const box = el('div', 'call');\n box.appendChild(el('div', 'name', c.name + '(' + c.id + ')'));\n box.appendChild(el('pre', null, pretty(c.args)));\n wrap.appendChild(box);\n });\n return wrap;\n}\n\nfunction requestBlocks(raw, into) {\n let req;\n try { req = JSON.parse(raw); } catch (e) {\n into.appendChild(textBlock('Request (unparsed)', raw));\n return;\n }\n if (req.system) into.appendChild(textBlock('System prompt', req.system)).classList.add('sys');\n\n const conv = block('Messages', (req.messages || []).length + ' messages');\n (req.messages || []).forEach(function (m) { conv.appendChild(message(m)); });\n if (!(req.messages || []).length) conv.appendChild(el('div', 'empty', '(none)'));\n into.appendChild(conv);\n\n const tools = block('Tools offered', (req.tools || []).length + ' tools');\n (req.tools || []).forEach(function (t) {\n const d = document.createElement('details');\n d.appendChild(el('summary', null, t.name + (t.description ? ' \u2014 ' + t.description : '')));\n d.appendChild(el('pre', null, JSON.stringify(t.parameters, null, 2)));\n tools.appendChild(d);\n });\n if (!(req.tools || []).length) tools.appendChild(el('div', 'empty', '(none)'));\n into.appendChild(tools);\n}\n\nfunction usageTag(u) {\n if (!u) return '';\n return (u.inputTokens || 0) + ' in (' + (u.cachedInputTokens || 0) + ' cached) / '\n + (u.outputTokens || 0) + ' out (' + (u.reasoningTokens || 0) + ' reasoning)';\n}\n\nfunction detailFor(e) {\n const n = e.node;\n const out = document.createDocumentFragment();\n\n const h = el('h2', 'dt');\n h.appendChild(el('span', 'type ' + n.type, n.type.replace(/_/g, ' ')));\n h.appendChild(el('span', null, label(n)));\n out.appendChild(h);\n\n const meta = el('div', 'meta');\n meta.appendChild(el('span', null, 'id ' + n.id));\n meta.appendChild(el('span', null, 'agent ' + n.agent));\n meta.appendChild(el('span', null, n.ts));\n meta.appendChild(el('span', null, 'started t+' + startedAt(e) + (took(e) ? ' \u00B7 took ' + took(e) : '')));\n if (e.branch) {\n const br = el('span', null, 'branch ' + e.branch);\n br.style.color = branchColor(e.branch);\n meta.appendChild(br);\n }\n if (e.covered) meta.appendChild(el('span', null, 'hidden by a later compaction'));\n out.appendChild(meta);\n\n switch (n.type) {\n case 'system_prompt':\n out.appendChild(textBlock('Prompt', blob(n.prompt)));\n // The editable half: which file to open when the instruction is wrong.\n (n.sources || []).forEach(function (s) {\n out.appendChild(textBlock(s.path, blob(s.content), 'prompt file'));\n });\n break;\n\n case 'user_input':\n n.content.forEach(function (p, i) {\n out.appendChild(p.type === 'text'\n ? textBlock('Text part ' + (i + 1), blob(p.text))\n : mediaBlock('Media part ' + (i + 1), p));\n });\n break;\n\n case 'load_skills':\n out.appendChild(textBlock('Skills', n.skills.map(function (s) {\n return s.name + (s.version ? '@' + s.version : '') + ' ' + s.contentHash.slice(0, 12)\n + (s.file ? ' ' + s.file : '');\n }).join('\\n'), n.provider));\n out.appendChild(textBlock('Injected instructions', blob(n.content)));\n out.appendChild(textBlock('Tools unlocked', n.toolNames.join('\\n')));\n break;\n\n case 'memory_recall':\n out.appendChild(textBlock('Query', JSON.stringify(n.query, null, 2), n.store + ' \u00B7 ' + n.scope));\n out.appendChild(textBlock('Hits', n.hits.map(function (hit) {\n return hit.id + ' score=' + hit.score + ' rev=' + hit.revision;\n }).join('\\n')));\n out.appendChild(textBlock('Injected block', blob(n.content)));\n break;\n\n case 'memory_op':\n out.appendChild(textBlock('Operation',\n n.op + ' ' + n.recordId + ' (rev ' + n.revision + ')', n.store + ' \u00B7 ' + n.scope));\n if (n.before) out.appendChild(textBlock('Before', blob(n.before)));\n if (n.after) out.appendChild(textBlock('After', blob(n.after)));\n break;\n\n case 'llm_call': {\n const u = n.usage || {};\n const strip = el('div', 'stats');\n strip.appendChild(stat('model', n.model));\n strip.appendChild(stat('in', u.inputTokens || 0));\n strip.appendChild(stat('cached', u.cachedInputTokens || 0));\n strip.appendChild(stat('out', u.outputTokens || 0));\n if (u.reasoningTokens) strip.appendChild(stat('reasoning', u.reasoningTokens));\n strip.appendChild(stat('stop', n.stopReason || '?'));\n out.appendChild(strip);\n\n const req = group('Request', 'req', 'sent to ' + n.model);\n if (n.request) requestBlocks(blob(n.request), req.body);\n else {\n req.body.appendChild(el('div', 'empty',\n 'not recorded \u2014 construct the runner with { recordRequests: true } to capture it'));\n }\n out.appendChild(req.el);\n\n const res = group('Response', 'res', n.stopReason);\n if (n.thinking) res.body.appendChild(textBlock('Reasoning', blob(n.thinking)));\n res.body.appendChild(textBlock('Text', blob(n.text)));\n n.toolCalls.forEach(function (c) {\n res.body.appendChild(textBlock('Tool call \u00B7 ' + c.name, pretty(blob(c.args)), c.callId));\n });\n out.appendChild(res.el);\n\n out.appendChild(textBlock('Request digest', n.requestDigest || '(not recorded)'));\n break;\n }\n\n case 'tool_call':\n out.appendChild(textBlock('Arguments', pretty(blob(n.args)), n.name + ' \u00B7 ' + n.callId));\n break;\n\n case 'tool_result':\n out.appendChild(textBlock(n.isError ? 'Error result' : 'Result',\n pretty(blob(n.result)),\n n.name + (n.durationMs !== undefined ? ' \u00B7 ' + n.durationMs + 'ms' : '')));\n break;\n\n case 'handoff':\n out.appendChild(textBlock('Handoff', n.from + ' -> ' + n.to\n + (n.reason ? '\\n\\nreason: ' + n.reason : '')));\n break;\n\n case 'fork':\n n.branches.forEach(function (b) {\n out.appendChild(textBlock('Branch \u00B7 ' + b.name, blob(b.instructions),\n b.agent + ' \u00B7 ' + n.contextMode + ' \u00B7 ' + b.childRunId));\n });\n break;\n\n case 'join':\n n.branches.forEach(function (b, i) {\n const br = e.children[i];\n const bd = br ? took(br) : '';\n out.appendChild(textBlock('Branch \u00B7 ' + b.name,\n b.status === 'ok' ? blob(b.output) : (b.error || blob(b.output)),\n b.status + ' \u00B7 ' + b.agent + ' \u00B7 ' + b.nodes.length + ' nodes'\n + (bd ? ' \u00B7 ' + bd : '') + ' \u00B7 ' + usageTag(b.usage)));\n });\n break;\n\n case 'compaction': {\n out.appendChild(textBlock('Summary', blob(n.summary), n.reason));\n const cov = block('Replaces', n.covers.length + ' nodes');\n const line = el('div', 'empty', '');\n line.textContent = '';\n n.covers.forEach(function (id) {\n const hit = ENTRIES.find(function (x) { return x.node.id === id; });\n const b = el('button', 'link', hit ? label(hit.node) : id);\n if (hit) b.addEventListener('click', function () { select(hit.key, true); });\n line.appendChild(b);\n });\n cov.appendChild(line);\n out.appendChild(cov);\n out.appendChild(textBlock('Summarizer usage', usageTag(n.usage)));\n break;\n }\n\n case 'final_output':\n out.appendChild(textBlock('Output', blob(n.output)));\n if (n.parsed !== undefined) out.appendChild(textBlock('Parsed', JSON.stringify(n.parsed, null, 2)));\n break;\n }\n\n out.appendChild(foldBlock('Raw node', JSON.stringify(n, null, 2)));\n return out;\n}\n\nconst detailEl = document.getElementById('detail');\nconst statsEl = document.getElementById('stats');\nlet selected = null;\n\nfunction select(key, focus) {\n const e = BY_KEY.get(key);\n if (!e) return;\n selected = key;\n detailEl.replaceChildren(detailFor(e));\n Array.prototype.forEach.call(listEl.children, function (li) {\n li.classList.toggle('sel', li.dataset.key === key);\n });\n const li = listEl.querySelector('li[data-key=\"' + key + '\"]');\n if (li) li.scrollIntoView({ block: 'nearest' });\n if (focus) show('detail');\n detailEl.scrollTop = 0;\n}\n\n// --- stats ----------------------------------------------------------------\n//\n// Tokens are not fungible across models and seconds are not fungible across\n// lanes: a thousand tokens cost a different amount on a different model, and\n// branch time runs in parallel with other branch time. So every number here\n// is broken down by model and by agent, and the wall clock sits next to the\n// sums so the gap between them is visible instead of misleading.\n\nfunction bucket() {\n return { calls: 0, errors: 0, ms: 0, in: 0, cached: 0, out: 0, reasoning: 0 };\n}\n\nfunction bucketOf(map, key) {\n if (!map.has(key)) map.set(key, bucket());\n return map.get(key);\n}\n\nfunction addUsage(into, u) {\n if (!u) return;\n into.in += u.inputTokens || 0;\n into.cached += u.cachedInputTokens || 0;\n into.out += u.outputTokens || 0;\n into.reasoning += u.reasoningTokens || 0;\n}\n\nfunction num(n) { return n.toLocaleString('en-US'); }\n\nfunction table(cols, rows, foot) {\n const t = el('table', 'st');\n const head = document.createElement('thead');\n const hr = document.createElement('tr');\n cols.forEach(function (c) { hr.appendChild(el('th', null, c)); });\n head.appendChild(hr);\n t.appendChild(head);\n const body = document.createElement('tbody');\n rows.forEach(function (r) {\n const tr = document.createElement('tr');\n r.forEach(function (v) { tr.appendChild(el('td', null, v)); });\n body.appendChild(tr);\n });\n t.appendChild(body);\n if (foot) {\n const tf = document.createElement('tfoot');\n const fr = document.createElement('tr');\n foot.forEach(function (v) { fr.appendChild(el('td', null, v)); });\n tf.appendChild(fr);\n t.appendChild(tf);\n }\n return t;\n}\n\nconst TOKEN_COLS = ['calls', 'in', 'cached', 'out', 'reasoning', 'time', 'avg'];\n\nfunction tokenRow(name, b) {\n return [name, num(b.calls), num(b.in), num(b.cached), num(b.out), num(b.reasoning),\n fmtDur(b.ms), b.calls ? fmtDur(b.ms / b.calls) : '\u2014'];\n}\n\nfunction byTokens(a, b) { return (b[1].in + b[1].out) - (a[1].in + a[1].out); }\n\nfunction buildStats() {\n const byModel = new Map(), byAgent = new Map(), byTool = new Map(), byType = new Map();\n const all = bucket();\n let llmMs = 0, toolMs = 0, toolCalls = 0, from = null, to = null;\n\n ENTRIES.forEach(function (e) {\n const n = e.node;\n byType.set(n.type, (byType.get(n.type) || 0) + 1);\n if (e.startMs !== null && (from === null || e.startMs < from)) from = e.startMs;\n if (e.endMs !== null && (to === null || e.endMs > to)) to = e.endMs;\n\n // A join's usage is the sum of its branches, whose nodes are already in\n // this list, so counting it too would double every branch token. A\n // compaction has no model of its own but did burn a summarizer.\n if (n.type === 'llm_call' || n.type === 'compaction') {\n const ms = spanMs(e);\n const model = n.type === 'compaction' ? 'summarizer' : n.model;\n [bucketOf(byModel, model), bucketOf(byAgent, n.agent), all].forEach(function (b) {\n addUsage(b, n.usage);\n b.calls += 1;\n b.ms += ms;\n });\n llmMs += ms;\n return;\n }\n // The tool's own measurement when the runner took one; the gap to the\n // previous node otherwise.\n if (n.type === 'tool_result') {\n const b = bucketOf(byTool, n.name);\n const ms = n.durationMs !== undefined ? n.durationMs : spanMs(e);\n b.calls += 1;\n b.ms += ms;\n if (n.isError) b.errors += 1;\n toolCalls += 1;\n toolMs += ms;\n }\n });\n\n const pills = el('div', 'stats');\n pills.appendChild(stat('wall clock', from === null ? '\u2014' : fmtDur(to - from)));\n pills.appendChild(stat('in llm', fmtDur(llmMs)));\n pills.appendChild(stat('in tools', fmtDur(toolMs)));\n pills.appendChild(stat('llm calls', num(all.calls)));\n pills.appendChild(stat('tool calls', num(toolCalls)));\n pills.appendChild(stat('tokens', num(all.in) + ' in / ' + num(all.out) + ' out'));\n pills.appendChild(stat('cached', num(all.cached)));\n pills.appendChild(stat('nodes', num(ENTRIES.length)));\n statsEl.replaceChildren(pills);\n\n const note = el('div', 'hint', 'Branches run in parallel, so llm and tool time are sums '\n + 'over every lane and add up to more than the wall clock.');\n note.style.marginBottom = '14px';\n statsEl.appendChild(note);\n\n const models = Array.from(byModel.entries()).sort(byTokens);\n const modelBlock = block('Tokens by model', models.length + (models.length === 1 ? ' model' : ' models'));\n modelBlock.appendChild(table(['model'].concat(TOKEN_COLS),\n models.map(function (m) { return tokenRow(m[0], m[1]); }), tokenRow('total', all)));\n statsEl.appendChild(modelBlock);\n\n const agents = Array.from(byAgent.entries()).sort(byTokens);\n const agentBlock = block('Tokens by agent', agents.length + (agents.length === 1 ? ' agent' : ' agents'));\n agentBlock.appendChild(table(['agent'].concat(TOKEN_COLS),\n agents.map(function (a) { return tokenRow(a[0], a[1]); }), tokenRow('total', all)));\n statsEl.appendChild(agentBlock);\n\n const tools = Array.from(byTool.entries()).sort(function (a, b) { return b[1].ms - a[1].ms; });\n const toolBlock = block('Tool calls', num(toolCalls) + ' calls \u00B7 ' + fmtDur(toolMs));\n if (tools.length) {\n toolBlock.appendChild(table(['tool', 'calls', 'errors', 'time', 'avg'],\n tools.map(function (t) {\n const b = t[1];\n return [t[0], num(b.calls), b.errors ? num(b.errors) : '', fmtDur(b.ms),\n b.calls ? fmtDur(b.ms / b.calls) : '\u2014'];\n })));\n } else {\n toolBlock.appendChild(el('div', 'empty', '(none)'));\n }\n statsEl.appendChild(toolBlock);\n\n const types = Array.from(byType.entries()).sort(function (a, b) { return b[1] - a[1]; });\n const typeBlock = block('Nodes by type', num(ENTRIES.length) + ' nodes');\n typeBlock.appendChild(table(['type', 'count'],\n types.map(function (t) { return [t[0].replace(/_/g, ' '), num(t[1])]; })));\n statsEl.appendChild(typeBlock);\n}\n\n// --- views ----------------------------------------------------------------\n\n// Panes that hold a zoomable diagram, by view name. A pane laid out while it\n// was hidden has no width to fit against, so becoming visible is the moment it\n// gets a second chance.\nconst PANES = {};\n\nfunction show(view) {\n document.getElementById('graph').hidden = view !== 'graph';\n document.getElementById('agents').hidden = view !== 'agents';\n detailEl.hidden = view !== 'detail';\n statsEl.hidden = view !== 'stats';\n Array.prototype.forEach.call(document.getElementById('viewtabs').children, function (b) {\n b.classList.toggle('on', b.dataset.view === view);\n });\n if (PANES[view]) PANES[view].refit();\n}\nArray.prototype.forEach.call(document.getElementById('viewtabs').children, function (b) {\n b.addEventListener('click', function () { show(b.dataset.view); });\n});\n\n// --- zoom and pan ---------------------------------------------------------\n//\n// A diagram grows with what it describes, so a fixed scale is useless past a\n// dozen nodes. The canvas is moved with a CSS transform rather than scrolled:\n// that keeps zooming anchored on the pointer and costs no layout.\n//\n// Written as a factory because there are two of these \u2014 the run graph and the\n// architecture \u2014 and they must not share a scale, a pan or a drag.\n\nconst MIN_ZOOM = 0.1;\nconst MAX_ZOOM = 4;\n\nfunction panZoom(paneId) {\n const pane = document.getElementById(paneId);\n const viewportEl = pane.querySelector('.viewport');\n const canvasEl = pane.querySelector('.canvas');\n const zoomEl = pane.querySelector('.lvl');\n let zoom = 1, panX = 0, panY = 0;\n let natW = 0, natH = 0;\n let pendingFit = false;\n\n function applyView() {\n canvasEl.style.transform = 'translate(' + panX + 'px,' + panY + 'px) scale(' + zoom + ')';\n zoomEl.textContent = Math.round(zoom * 100) + '%';\n }\n\n function zoomAt(factor, cx, cy) {\n const next = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom * factor));\n const ratio = next / zoom;\n // Keep the point under the cursor fixed while the scale changes.\n panX = cx - (cx - panX) * ratio;\n panY = cy - (cy - panY) * ratio;\n zoom = next;\n applyView();\n }\n\n function zoomCenter(factor) {\n const r = viewportEl.getBoundingClientRect();\n zoomAt(factor, r.width / 2, r.height / 2);\n }\n\n function fit() {\n const r = viewportEl.getBoundingClientRect();\n if (!r.width || !natW || !natH) { pendingFit = true; return; }\n pendingFit = false;\n zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM,\n Math.min((r.width - 32) / natW, (r.height - 32) / natH)));\n panX = (r.width - natW * zoom) / 2;\n panY = Math.max(16, (r.height - natH * zoom) / 2);\n applyView();\n }\n\n pane.querySelector('.gtools').addEventListener('click', function (ev) {\n const what = ev.target.dataset ? ev.target.dataset.zoom : null;\n if (what === 'in') zoomCenter(1.25);\n else if (what === 'out') zoomCenter(1 / 1.25);\n else if (what === 'fit') fit();\n else if (what === 'reset') { zoom = 1; panX = 16; panY = 16; applyView(); }\n });\n\n viewportEl.addEventListener('wheel', function (ev) {\n ev.preventDefault();\n const r = viewportEl.getBoundingClientRect();\n zoomAt(Math.exp(-ev.deltaY * 0.002), ev.clientX - r.left, ev.clientY - r.top);\n }, { passive: false });\n\n let dragging = false, dragMoved = false, startX = 0, startY = 0, baseX = 0, baseY = 0;\n\n viewportEl.addEventListener('pointerdown', function (ev) {\n if (ev.button !== 0) return;\n dragging = true; dragMoved = false;\n startX = ev.clientX; startY = ev.clientY; baseX = panX; baseY = panY;\n });\n viewportEl.addEventListener('pointermove', function (ev) {\n if (!dragging) return;\n const dx = ev.clientX - startX, dy = ev.clientY - startY;\n if (!dragMoved) {\n if (Math.abs(dx) + Math.abs(dy) <= 4) return;\n dragMoved = true;\n // Captured only once this is a drag: capturing on pointerdown would\n // retarget the following click to the viewport and no node would ever\n // receive it.\n viewportEl.setPointerCapture(ev.pointerId);\n viewportEl.classList.add('drag');\n }\n panX = baseX + dx; panY = baseY + dy;\n applyView();\n });\n function endDrag(ev) {\n if (!dragging) return;\n dragging = false;\n viewportEl.classList.remove('drag');\n if (viewportEl.hasPointerCapture(ev.pointerId)) viewportEl.releasePointerCapture(ev.pointerId);\n }\n viewportEl.addEventListener('pointerup', endDrag);\n viewportEl.addEventListener('pointercancel', endDrag);\n viewportEl.addEventListener('dblclick', function () { fit(); });\n window.addEventListener('resize', function () { if (pendingFit) fit(); });\n\n return {\n canvas: canvasEl,\n setNatural: function (w, h) { natW = w; natH = h; fit(); },\n refit: function () { if (pendingFit) fit(); },\n // A pan that ends on a node must not be read as a click on it.\n moved: function () { return dragMoved; }\n };\n}\n\nPANES.graph = panZoom('graph');\nPANES.agents = panZoom('agents');\n\n// --- diagram --------------------------------------------------------------\n\nconst CLASSES = {\n llm_call: 'llm', tool_call: 'tool', tool_result: 'tool', compaction: 'comp',\n fork: 'fork', join: 'fork', final_output: 'final', handoff: 'hand'\n};\n\n// A failed call is the one thing in a trace people look for, so it is coloured\n// by outcome rather than by type \u2014 the same red the sidebar badge uses.\nfunction nodeClass(n) {\n if (n.type === 'tool_result' && n.isError) return 'err';\n return CLASSES[n.type];\n}\n\n// Diagram labels are built from node types and identifiers only, and are\n// stripped to a conservative character set: nothing a model wrote can reach\n// the Mermaid parser, let alone the SVG.\nfunction safe(text) {\n return String(text).replace(/[^\\w .:\\-\\/>+=()]/g, ' ').slice(0, 60).trim();\n}\n\nfunction shape(e, i) {\n const n = e.node;\n // The timing is ours, not the run's: digits and a unit, appended after\n // sanitizing. It stays on one line because Mermaid's strict mode drops the\n // <br/> that would break it.\n const d = took(e);\n const text = '\"' + (i + 1) + '. ' + safe(label(n))\n + ' t+' + startedAt(e) + (d ? ' \u00B7 ' + d : '') + '\"';\n if (n.type === 'fork' || n.type === 'join') return e.key + '{{' + text + '}}';\n if (n.type === 'final_output') return e.key + '([' + text + '])';\n if (n.type === 'user_input' || n.type === 'system_prompt') return e.key + '[/' + text + '/]';\n return e.key + '[' + text + ']';\n}\n\nfunction chain(level, lines) {\n let prev = null;\n level.forEach(function (e) {\n const i = ENTRIES.indexOf(e);\n lines.push(' ' + shape(e, i));\n const cls = nodeClass(e.node);\n if (cls) lines.push(' class ' + e.key + ' ' + cls + ';');\n if (e.covered) lines.push(' class ' + e.key + ' covered;');\n if (prev) lines.push(' ' + prev.key + ' --> ' + e.key);\n\n if (e.node.type === 'join' && e.children.length) {\n // A branch hangs off the fork that opened it and rejoins at the join.\n const fork = level.find(function (x) {\n return x.node.type === 'fork' && x.node.callId === e.node.callId;\n });\n e.children.forEach(function (br, bi) {\n if (!br.entries.length) return;\n const bd = took(br);\n const sg = 'sg_' + e.key + '_' + bi;\n lines.push(' subgraph ' + sg + '[\"' + safe(br.name)\n + ' t+' + startedAt(br) + (bd ? ' \u00B7 ' + bd : '')\n + (br.slowest ? ' \u00B7 slowest' : '') + '\"]');\n lines.push(' direction TB');\n chain(br.entries, lines);\n lines.push(' end');\n // The one branch the join actually waited for, lifted out of the pack.\n if (br.slowest) lines.push(' style ' + sg + ' fill:#5b6070,stroke:#a9b2c6,color:#f2f4f8;');\n if (fork) lines.push(' ' + fork.key + ' -.-> ' + br.entries[0].key);\n lines.push(' ' + br.entries[br.entries.length - 1].key + ' -.-> ' + e.key);\n });\n }\n prev = e;\n });\n}\n\nfunction diagram() {\n const lines = ['flowchart TD'];\n lines.push(' classDef llm fill:#1e3357,stroke:#3d5f9e,color:#cfe0ff;');\n lines.push(' classDef tool fill:#1e3d33,stroke:#3d7a66,color:#c8f0e2;');\n lines.push(' classDef comp fill:#40331a,stroke:#7a6535,color:#f0dfb4;');\n lines.push(' classDef fork fill:#3a2450,stroke:#6b4b90,color:#e6d3ff;');\n lines.push(' classDef final fill:#14392c,stroke:#2f7a5c,color:#c6f5e0;');\n lines.push(' classDef hand fill:#3d2a1b,stroke:#7a5535,color:#f2d9c2;');\n lines.push(' classDef err fill:#4a1f1c,stroke:#8a3a33,color:#f0776c;');\n lines.push(' classDef covered opacity:0.45,stroke-dasharray:4 3;');\n chain(ROOT, lines);\n return lines.join('\\n');\n}\n\n// One Mermaid, two diagrams. Loading it is the only network the page does, so\n// it happens once and both panes wait on the same promise.\nlet mermaidLib = null;\nfunction mermaid() {\n if (!mermaidLib) {\n mermaidLib = import(MERMAID_URL).then(function (m) {\n m.default.initialize({\n startOnLoad: false, theme: 'dark', securityLevel: 'strict',\n flowchart: { htmlLabels: false }\n });\n return m.default;\n });\n }\n return mermaidLib;\n}\n\n/** Renders one diagram into a pane and wires its nodes. False when it failed. */\nasync function draw(pane, id, source, onNode) {\n let lib;\n try {\n lib = await mermaid();\n } catch (err) {\n pane.canvas.replaceChildren(el('div', 'hint pad',\n 'Mermaid could not be loaded (offline?). The timeline on the left has the same nodes.'));\n return false;\n }\n try {\n const rendered = await lib.render(id, source);\n // Mermaid produced this markup from labels we sanitized above; no payload\n // text reaches it.\n pane.canvas.innerHTML = rendered.svg;\n } catch (err) {\n pane.canvas.replaceChildren(el('pre', null, 'diagram failed: ' + err.message + '\\n\\n' + source));\n return false;\n }\n const svg = pane.canvas.querySelector('svg');\n if (svg) {\n // Mermaid sizes the SVG to fit its container; we want its natural size so\n // the transform above is the only thing deciding scale.\n const box = svg.viewBox && svg.viewBox.baseVal;\n const w = (box && box.width) || svg.getBoundingClientRect().width;\n const h = (box && box.height) || svg.getBoundingClientRect().height;\n svg.removeAttribute('width');\n svg.removeAttribute('height');\n svg.style.maxWidth = 'none';\n svg.style.width = w + 'px';\n svg.style.height = h + 'px';\n pane.setNatural(w, h);\n }\n pane.canvas.querySelectorAll('.node').forEach(onNode);\n return true;\n}\n\nasync function drawGraph() {\n const ok = await draw(PANES.graph, 'run-graph', diagram(), function (g) {\n // Mermaid ids are '<renderId>-flowchart-<ourKey>-<seq>'; only the key matters.\n const m = /-(n\\d+)-\\d+$/.exec(g.id || '');\n const key = m ? m[1] : null;\n if (!key || !BY_KEY.has(key)) return;\n g.addEventListener('click', function () { if (!PANES.graph.moved()) select(key, true); });\n });\n if (!ok) show('detail');\n}\n\n// --- architecture ---------------------------------------------------------\n//\n// The run graph answers \"what happened\". This one answers \"what was wired up\",\n// which is the question a trajectory structurally cannot: the agent nobody\n// handed off to and the tool nobody called leave no node behind. The declared\n// wiring arrives with the report when a runner was there to describe itself;\n// otherwise the run is read backwards into the same shape, which is smaller\n// but never wrong.\n\nconst SEP = '::';\n\nfunction bump(map, key, entryKey) {\n const cur = map.get(key);\n if (cur) { cur.count += 1; return; }\n map.set(key, { count: 1, key: entryKey });\n}\n\n// What this run actually exercised, keyed the same way the diagram names\n// things \u2014 so drawing \"used\" is a lookup rather than a search.\nconst USED = {\n agents: new Map(), models: new Map(), tools: new Map(),\n skills: new Map(), handoffs: new Map(), memory: new Map(), forks: new Map()\n};\n\nENTRIES.forEach(function (e) {\n const n = e.node;\n bump(USED.agents, n.agent, e.key);\n if (n.type === 'llm_call') {\n if (!USED.models.has(n.agent)) USED.models.set(n.agent, n.model);\n } else if (n.type === 'tool_call') {\n bump(USED.tools, n.agent + SEP + n.name, e.key);\n } else if (n.type === 'load_skills') {\n n.skills.forEach(function (s) { bump(USED.skills, n.agent + SEP + s.name, e.key); });\n } else if (n.type === 'handoff') {\n bump(USED.handoffs, n.from + SEP + n.to, e.key);\n } else if (n.type === 'memory_recall' || n.type === 'memory_op') {\n bump(USED.memory, n.agent + SEP + n.store + '/' + n.scope, e.key);\n } else if (n.type === 'fork') {\n n.branches.forEach(function (b) { bump(USED.forks, n.agent + SEP + b.agent, e.key); });\n }\n});\n\nfunction has(list, name) {\n return list.some(function (x) { return x.name === name; });\n}\n\n/** The run read backwards into the same shape. Used when none was supplied. */\nfunction observedArchitecture() {\n const byName = new Map();\n function agentOf(name) {\n if (!byName.has(name)) {\n byName.set(name, { name: name, tools: [], handoffs: [], memory: [] });\n }\n return byName.get(name);\n }\n ENTRIES.forEach(function (e) {\n const n = e.node;\n const a = agentOf(n.agent);\n if (n.type === 'llm_call') {\n if (!a.model) a.model = n.model;\n } else if (n.type === 'tool_call') {\n // Handoff tools are drawn as edges between agents, never as tool nodes.\n const handoff = n.name.indexOf('transfer_to_') === 0;\n if (!handoff && !has(a.tools, n.name)) a.tools.push({ name: n.name });\n } else if (n.type === 'load_skills') {\n if (!a.skills) a.skills = { provider: n.provider, discovery: 'index', catalog: [] };\n n.skills.forEach(function (s) {\n if (has(a.skills.catalog, s.name)) return;\n // The unlocked tools are recorded per activation, not per skill, so\n // they can only be attributed when one skill loaded on its own.\n a.skills.catalog.push({\n name: s.name, version: s.version,\n toolNames: n.skills.length === 1 ? n.toolNames : undefined\n });\n });\n } else if (n.type === 'handoff') {\n const from = agentOf(n.from);\n agentOf(n.to);\n if (from.handoffs.indexOf(n.to) < 0) from.handoffs.push(n.to);\n } else if (n.type === 'memory_recall' || n.type === 'memory_op') {\n const known = a.memory.some(function (m) {\n return m.store === n.store && m.scope === n.scope;\n });\n if (!known) {\n a.memory.push({\n store: n.store, scope: n.scope,\n access: n.type === 'memory_op' ? 'read-write' : 'read'\n });\n }\n } else if (n.type === 'fork') {\n if (!a.fork) a.fork = { agents: [] };\n n.branches.forEach(function (b) {\n agentOf(b.agent);\n if (a.fork.agents.indexOf(b.agent) < 0) a.fork.agents.push(b.agent);\n });\n }\n });\n return { source: 'observed', agents: Array.from(byName.values()) };\n}\n\nconst ARCH = DATA.architecture || observedArchitecture();\n\n// Diagram key -> the first trajectory node that exercised the thing it names,\n// or null when nothing did. Clicking is only offered for the former.\nconst ARCH_KEYS = new Map();\nlet archSeq = 0;\nfunction archKey(used) {\n const k = 'x' + archSeq++;\n ARCH_KEYS.set(k, used ? used.key : null);\n return k;\n}\n\n/** An agent with more tools than this gets a \"+N more\" node instead of a wall. */\nconst MAX_TOOLS = 12;\n\nfunction times(used) {\n return used ? ' x' + used.count : '';\n}\n\nfunction archDiagram() {\n const lines = ['flowchart LR'];\n lines.push(' classDef agent fill:#1e3357,stroke:#3d5f9e,color:#cfe0ff;');\n lines.push(' classDef start fill:#14392c,stroke:#2f7a5c,color:#c6f5e0;');\n lines.push(' classDef tool fill:#1e3d33,stroke:#3d7a66,color:#c8f0e2;');\n lines.push(' classDef skill fill:#3a2450,stroke:#6b4b90,color:#e6d3ff;');\n lines.push(' classDef mem fill:#40331a,stroke:#7a6535,color:#f0dfb4;');\n lines.push(' classDef more fill:#1b202c,stroke:#39415a,color:#8a92a6;');\n lines.push(' classDef idle opacity:0.4,stroke-dasharray:4 3;');\n\n const startAgent = (STATE.spec && STATE.spec.startAgent) || STATE.agentName;\n const selfKey = new Map();\n // Minted up front so a hand-off can name an agent declared further down.\n ARCH.agents.forEach(function (a) {\n selfKey.set(a.name, archKey(USED.agents.get(a.name)));\n });\n\n ARCH.agents.forEach(function (a) {\n const self = selfKey.get(a.name);\n const live = USED.agents.get(a.name);\n // The model on the node is the declared one, or \u2014 when the report carries\n // no wiring \u2014 whatever this run was seen using.\n const model = a.model || USED.models.get(a.name);\n lines.push(' subgraph sg_' + self + '[\"' + safe(a.name)\n + (a.description ? ' - ' + safe(a.description) : '') + '\"]');\n lines.push(' direction LR');\n lines.push(' ' + self + '[[\"' + safe(a.name)\n + (model ? ' ' + safe(model) + (a.inheritedModel ? ' (inherited)' : '') : '')\n + '\"]]');\n lines.push(' class ' + self + ' ' + (a.name === startAgent ? 'start' : 'agent') + ';');\n if (!live) lines.push(' class ' + self + ' idle;');\n\n // Skills first: a skill owns tools, so its node has to exist before the\n // tools it unlocks can point back at it.\n const skillKey = new Map();\n const catalog = (a.skills && a.skills.catalog) || [];\n catalog.forEach(function (s) {\n const used = USED.skills.get(a.name + SEP + s.name);\n const k = archKey(used);\n skillKey.set(s.name, k);\n lines.push(' ' + k + '([\"' + safe(s.name) + (s.preload ? ' (preloaded)' : '')\n + times(used) + '\"])');\n lines.push(' class ' + k + ' skill;');\n if (!used) lines.push(' class ' + k + ' idle;');\n lines.push(' ' + self + ' --- ' + k);\n });\n if (a.skills && a.skills.unresolved) {\n const k = archKey(null);\n lines.push(' ' + k + '([\"catalog unavailable: ' + safe(a.skills.provider) + '\"])');\n lines.push(' class ' + k + ' skill;');\n lines.push(' class ' + k + ' idle;');\n lines.push(' ' + self + ' --- ' + k);\n }\n\n const shown = a.tools.slice(0, MAX_TOOLS);\n shown.forEach(function (t) {\n const used = USED.tools.get(a.name + SEP + t.name);\n const k = archKey(used);\n lines.push(' ' + k + '[\"' + safe(t.name) + times(used) + '\"]');\n lines.push(' class ' + k + ' tool;');\n if (!used) lines.push(' class ' + k + ' idle;');\n // A skill-owned tool hangs off the skill that unlocks it, not off the\n // agent: that edge is the whole point of a locked tool.\n const owner = t.skill ? skillKey.get(t.skill) : null;\n if (owner) lines.push(' ' + owner + ' -.-> ' + k);\n else lines.push(' ' + self + ' --- ' + k);\n });\n if (a.tools.length > shown.length) {\n const k = archKey(null);\n lines.push(' ' + k + '[\"+' + (a.tools.length - shown.length) + ' more tools\"]');\n lines.push(' class ' + k + ' more;');\n lines.push(' ' + self + ' --- ' + k);\n }\n\n a.memory.forEach(function (m) {\n const used = USED.memory.get(a.name + SEP + m.store + '/' + m.scope);\n const k = archKey(used);\n lines.push(' ' + k + '[(\"' + safe(m.store) + ' / ' + safe(m.scope)\n + (m.access === 'read-write' ? ' (rw)' : ' (ro)') + '\")]');\n lines.push(' class ' + k + ' mem;');\n if (!used) lines.push(' class ' + k + ' idle;');\n lines.push(' ' + self + ' --- ' + k);\n });\n lines.push(' end');\n // Mermaid's default subgraph is a light box, which on a dark page reads as\n // the foreground rather than as the container. An agent nobody entered is\n // outlined rather than filled, so a dead corner of the wiring is visible\n // from across the diagram.\n lines.push(' style sg_' + self + ' fill:#12151d,color:#8a92a6,stroke:'\n + (live ? '#39415a;' : '#2b3346,stroke-dasharray:5 4;'));\n });\n\n // Edges between agents live outside every subgraph, so Mermaid routes them\n // between the boxes instead of trying to keep them inside one.\n ARCH.agents.forEach(function (a) {\n const self = selfKey.get(a.name);\n a.handoffs.forEach(function (to) {\n if (!selfKey.has(to)) return;\n const used = USED.handoffs.get(a.name + SEP + to);\n lines.push(' ' + self + (used ? ' -- \"handoff' + times(used) + '\" --> ' : ' -.-> ')\n + selfKey.get(to));\n });\n ((a.fork && a.fork.agents) || []).forEach(function (to) {\n if (!selfKey.has(to) || to === a.name) return;\n const used = USED.forks.get(a.name + SEP + to);\n lines.push(' ' + self + ' == \"fork' + times(used) + '\" ==> ' + selfKey.get(to));\n });\n });\n return lines.join('\\n');\n}\n\nfunction archLegend() {\n const agents = ARCH.agents.length;\n const tools = ARCH.agents.reduce(function (n, a) { return n + a.tools.length; }, 0);\n const skills = ARCH.agents.reduce(function (n, a) {\n return n + ((a.skills && a.skills.catalog.length) || 0);\n }, 0);\n const idle = ARCH.agents.filter(function (a) { return !USED.agents.has(a.name); }).length;\n return (ARCH.source === 'declared' ? 'declared' : 'observed only')\n + ' \\u00b7 ' + agents + ' agents \\u00b7 ' + tools + ' tools \\u00b7 ' + skills + ' skills'\n + (idle ? ' \\u00b7 ' + idle + ' idle' : '')\n + ' \\u00b7 dimmed = unused \\u00b7 click to jump';\n}\n\nasync function drawArch() {\n document.getElementById('alegend').textContent = archLegend();\n if (!ARCH.agents.length) {\n PANES.agents.canvas.replaceChildren(el('div', 'hint pad', 'No agents to draw.'));\n return;\n }\n await draw(PANES.agents, 'arch-graph', archDiagram(), function (g) {\n const m = /-(x\\d+)-\\d+$/.exec(g.id || '');\n const key = m && ARCH_KEYS.get(m[1]);\n if (!key) return;\n g.addEventListener('click', function () { if (!PANES.agents.moved()) select(key, true); });\n });\n}\n\ndrawGraph().then(drawArch);\nbuildStats();\nif (ENTRIES.length) select('n0', false);\n";
1
+ export declare const CLIENT = "\nconst DATA = JSON.parse(document.getElementById('run-data').textContent);\nconst STATE = DATA.state;\nconst BLOBS = DATA.blobs;\nconst MEDIA = DATA.media || [];\nconst CUT = new Set(DATA.truncated || []);\n\n// --- payload access -------------------------------------------------------\n\nfunction blob(ref) {\n if (!ref || typeof ref.sha256 !== 'string') return '';\n const v = BLOBS[ref.sha256];\n if (v === undefined) return '[payload not resolved: ' + ref.sha256.slice(0, 12) + ']';\n return CUT.has(ref.sha256) ? v + '\\n\\n[\u2026 truncated, ' + ref.size + ' bytes total]' : v;\n}\n\nfunction pretty(raw) {\n try { return JSON.stringify(JSON.parse(raw), null, 2); } catch (e) { return raw; }\n}\n\n// --- flatten the trajectory ----------------------------------------------\n\nconst ENTRIES = [];\nconst BY_KEY = new Map();\n\nfunction covered(nodes) {\n const out = new Set();\n for (const n of nodes) if (n.type === 'compaction') for (const id of n.covers) out.add(id);\n return out;\n}\n\nfunction flatten(nodes, depth, branch) {\n const hidden = covered(nodes);\n const level = [];\n for (const node of nodes) {\n const e = {\n key: '', node: node, depth: depth, branch: branch,\n covered: hidden.has(node.id), children: []\n };\n // A join's branches ran between the fork and the join, so they are\n // numbered and listed there \u2014 which means recursing before this entry\n // takes its own number.\n if (node.type === 'join') {\n for (const b of node.branches) e.children.push({ name: b.name, entries: flatten(b.nodes, depth + 1, b.name) });\n }\n e.key = 'n' + ENTRIES.length;\n ENTRIES.push(e); BY_KEY.set(e.key, e); level.push(e);\n }\n return level;\n}\nconst ROOT = flatten(STATE.trajectory, 0, null);\n\n// --- labels ---------------------------------------------------------------\n\nfunction names(list) { return list.join(', '); }\n\n// The edges are what makes a recollection a subgraph rather than a hit list,\n// so they are shown even though the injected block already renders them.\nfunction edgeLines(edges) {\n if (!edges || !edges.length) return '';\n return '\\n\\n' + edges.map(function (e) {\n return e.source + ' --' + e.relation + '--> ' + e.target;\n }).join('\\n');\n}\n\nfunction base(path) { return path.split('/').pop() || path; }\n\nfunction label(n) {\n switch (n.type) {\n case 'user_input': return n.synthetic ? 'user input (synthetic)' : 'user input';\n case 'system_prompt': return 'system prompt'\n + (n.sources && n.sources.length ? ': ' + names(n.sources.map(function (s) { return base(s.path); })) : '');\n case 'load_skills': return 'skills: ' + names(n.skills.map(function (s) { return s.name; }));\n case 'memory_recall': return 'memory recall: ' + n.nodes.length + ' nodes';\n case 'memory_op': return 'memory ' + n.op + ': ' + n.nodes.length + ' nodes';\n case 'llm_call': return 'llm: ' + n.model + (n.toolCalls.length\n ? ' -> ' + names(n.toolCalls.map(function (c) { return c.name; })) : '');\n case 'tool_call': return 'call: ' + n.name;\n case 'tool_result': return 'result: ' + n.name + (n.isError ? ' (error)' : '');\n case 'handoff': return 'handoff: ' + n.from + ' -> ' + n.to;\n case 'fork': return 'fork: ' + names(n.branches.map(function (b) { return b.name; }));\n case 'join': return 'join: ' + names(n.branches.map(function (b) { return b.name + '=' + b.status; }));\n case 'compaction': return 'compaction: ' + n.reason + ' (' + n.covers.length + ' nodes)';\n case 'final_output': return 'final output';\n default: return n.type;\n }\n}\n\nfunction preview(n) {\n switch (n.type) {\n case 'user_input': {\n const t = n.content.find(function (p) { return p.type === 'text'; });\n return t ? blob(t.text) : '';\n }\n case 'system_prompt': return blob(n.prompt);\n case 'llm_call': return blob(n.text);\n case 'tool_call': return blob(n.args);\n case 'tool_result': return blob(n.result);\n case 'compaction': return blob(n.summary);\n case 'final_output': return blob(n.output);\n case 'memory_recall': return blob(n.content);\n case 'load_skills': return blob(n.content);\n default: return '';\n }\n}\n\n// --- DOM helpers ----------------------------------------------------------\n\nfunction el(tag, cls, text) {\n const e = document.createElement(tag);\n if (cls) e.className = cls;\n if (text !== undefined && text !== null) e.textContent = String(text);\n return e;\n}\n\nfunction block(title, tag) {\n const s = el('section', 'blk');\n const h = el('h3', null, title);\n if (tag) h.appendChild(el('span', 'tag', tag));\n s.appendChild(h);\n return s;\n}\n\nfunction textBlock(title, body, tag) {\n const s = block(title, tag);\n if (body) s.appendChild(el('pre', 'text', body));\n else s.appendChild(el('div', 'empty', '(empty)'));\n return s;\n}\n\nfunction foldBlock(title, body) {\n const s = block(title);\n const d = document.createElement('details');\n d.appendChild(el('summary', null, 'show'));\n d.appendChild(el('pre', null, body));\n s.appendChild(d);\n return s;\n}\n\n// An <img> never runs script, but the src is still pinned to shapes we\n// understand: a raster data: uri (svg is excluded on principle) or an http url.\nconst IMG_SUBTYPES = ['png', 'jpeg', 'jpg', 'gif', 'webp', 'avif', 'bmp'];\n\n/** Undoes the report's media hoisting; anything else passes through. */\nfunction mediaUrl(u) {\n if (typeof u !== 'string' || u.indexOf('media:') !== 0) return u;\n const v = MEDIA[Number(u.slice(6))];\n return v === undefined ? u : v;\n}\n\nfunction imageSrc(p) {\n if (p.type !== 'image') return null;\n const u = mediaUrl(p.url);\n if (typeof u !== 'string') return null;\n if (u.indexOf('https://') === 0 || u.indexOf('http://') === 0) return u;\n if (u.indexOf('data:image/') !== 0) return null;\n const sub = u.slice(11).split(/[;,]/)[0].toLowerCase();\n return IMG_SUBTYPES.indexOf(sub) < 0 ? null : u;\n}\n\n/** The rendered picture, or null when the part is not one we will inline. */\nfunction imageEl(p, thumb) {\n const src = imageSrc(p);\n if (!src) return null;\n const img = el('img', thumb ? 'media thumb' : 'media');\n img.src = src;\n img.alt = p.type + (p.mimeType ? ' ' + p.mimeType : '');\n img.loading = 'lazy';\n if (thumb) {\n img.title = 'click to enlarge';\n img.addEventListener('click', function () { img.classList.toggle('thumb'); });\n }\n return img;\n}\n\nfunction mediaBlock(title, p) {\n const tag = p.type + (p.mimeType ? ' \u00B7 ' + p.mimeType : '');\n const src = imageSrc(p);\n const img = imageEl(p, false);\n if (!img) return textBlock(title, mediaUrl(p.url), tag);\n const s = block(title, tag);\n s.appendChild(img);\n // The bytes stay reachable; they just no longer own the screen.\n const d = document.createElement('details');\n d.appendChild(el('summary', null, 'source'));\n d.appendChild(el('pre', null, src));\n s.appendChild(d);\n return s;\n}\n\n// A titled container for several blocks. Returns the element to append and the\n// body to fill, so callers never have to know the internal structure.\nfunction group(title, kind, tag) {\n const s = el('section', 'group ' + kind);\n const h = el('div', 'ghdr', title);\n if (tag) h.appendChild(el('span', 'tag', tag));\n s.appendChild(h);\n const body = el('div', 'body');\n s.appendChild(body);\n return { el: s, body: body };\n}\n\nfunction stat(key, value) {\n const d = el('span', 'stat', key + ' ');\n d.appendChild(el('b', null, value));\n return d;\n}\n\n// --- header ---------------------------------------------------------------\n\nfunction kv(key, value) {\n const d = el('div', 'kv');\n d.appendChild(document.createTextNode(key + ' '));\n d.appendChild(el('b', null, value));\n return d;\n}\n\n(function head() {\n const h = document.getElementById('head');\n const u = STATE.usage || {};\n const llm = ENTRIES.filter(function (e) { return e.node.type === 'llm_call'; }).length;\n h.appendChild(el('h1', null, DATA.title));\n h.appendChild(kv('run', STATE.runId));\n h.appendChild(kv('agent', STATE.agentName));\n h.appendChild(kv('phase', STATE.phase));\n h.appendChild(kv('nodes', ENTRIES.length));\n h.appendChild(kv('llm calls', llm));\n h.appendChild(kv('tokens', (u.inputTokens || 0) + ' in / ' + (u.outputTokens || 0) + ' out'));\n if (STATE.error) h.appendChild(kv('error', STATE.error));\n h.appendChild(kv('generated', DATA.generatedAt));\n})();\n\n// --- timing ---------------------------------------------------------------\n//\n// A node is stamped when it is appended, which is when the work behind it\n// finished. So the interval between a node and the one before it in the same\n// lane *is* that work: an llm_call's interval is the model latency, a\n// tool_result's is the tool. That gives every node a start and a duration\n// without storing either.\n//\n// Offsets are counted from the start of the turn, not of the run: in a\n// follow-up the interesting question is \"how long did this answer take\", and\n// counting from a conversation that began an hour ago answers nothing. A trunk\n// user_input opens a new turn; a branch inherits the turn that forked it, so\n// ten branches starting at one offset still read as parallel.\n\nfunction stampOf(node) {\n const t = Date.parse(node.ts);\n return isNaN(t) ? null : t;\n}\n\n(function time(level, lanePrev, turnStart) {\n let prev = lanePrev;\n let t0 = turnStart;\n level.forEach(function (e) {\n const ts = stampOf(e.node);\n // A real user turn resets the clock and starts at itself: the gap since\n // the previous run is waiting, not work. Synthetic inputs (a branch seed,\n // a re-injection) are not turns \u2014 same rule the kernel uses.\n const opensTurn = !e.branch && e.node.type === 'user_input' && !e.node.synthetic;\n if (opensTurn) t0 = ts;\n e.turnStart = t0 === null ? ts : t0;\n e.startMs = opensTurn || prev === null ? ts : prev;\n e.endMs = ts;\n // Branches run between the fork and the join, so they start where the\n // trunk left off \u2014 and the join's own duration is the whole parallel\n // section it waited on.\n if (e.node.type === 'join') {\n let slowest = null;\n e.children.forEach(function (br) {\n time(br.entries, prev, e.turnStart);\n // The branch as a whole gets the same shape as a node \u2014 start, end,\n // turn \u2014 so a reader sees how long *it* ran instead of having to\n // subtract two offsets to find out that ten branches were parallel.\n const last = br.entries[br.entries.length - 1];\n br.turnStart = e.turnStart;\n br.startMs = prev;\n br.endMs = last ? last.endMs : prev;\n if (br.entries.length) br.entries[0].branchSpan = br;\n // The join costs exactly its slowest branch, so that branch is the\n // only one worth optimizing: it gets marked and rendered lighter.\n if (br.entries.length && (!slowest || br.endMs > slowest.endMs)) slowest = br;\n });\n if (slowest) slowest.slowest = true;\n }\n prev = ts;\n });\n})(ROOT, null, null);\n\nfunction fmtSecs(ms) {\n const s = ms / 1000;\n if (s < 100) return s.toFixed(1) + 's';\n const m = Math.floor(s / 60);\n return m + 'm' + String(Math.floor(s - m * 60)).padStart(2, '0');\n}\n\n/** Offset of a node's start from the beginning of its turn. */\nfunction startedAt(e) {\n if (e.startMs === null || e.turnStart === null) return '';\n return fmtSecs(e.startMs - e.turnStart);\n}\n\n/** How long the work behind a node took. Blank when it is not worth a number. */\nfunction took(e) {\n if (e.startMs === null || e.endMs === null) return '';\n const ms = e.endMs - e.startMs;\n if (ms < 10) return '';\n return fmtDur(ms);\n}\n\nfunction fmtDur(ms) {\n return ms < 1000 ? Math.round(ms) + 'ms' : fmtSecs(ms);\n}\n\nfunction spanMs(e) {\n return e.startMs === null || e.endMs === null ? 0 : e.endMs - e.startMs;\n}\n\n// One colour per branch, stable for the life of the page. The trunk keeps the\n// neutral accent so branches are the thing that stands out.\nconst PALETTE = ['#6ea8fe', '#4ec9a0', '#e2b341', '#d1a6ff', '#f0776c',\n '#5fd0d8', '#f09a5c', '#a3d160', '#ef8ec0', '#9aa4ff'];\nconst BRANCH_COLOR = new Map();\nfunction branchColor(name) {\n if (!name) return null;\n if (!BRANCH_COLOR.has(name)) BRANCH_COLOR.set(name, PALETTE[BRANCH_COLOR.size % PALETTE.length]);\n return BRANCH_COLOR.get(name);\n}\n\n// --- timeline -------------------------------------------------------------\n\nconst listEl = document.getElementById('timeline');\nlet lastBranch = false;\nlet lastStamp = null;\n\nENTRIES.forEach(function (e, i) {\n // Branch histories are contiguous in the flattened order, so a change of\n // branch is a group boundary: label it and restart the elapsed column.\n if (e.branch !== lastBranch) {\n const sep = el('li', 'sep');\n const color = branchColor(e.branch);\n if (color) sep.style.setProperty('--bc', color);\n sep.appendChild(el('span', 'dot'));\n sep.appendChild(el('span', null, e.branch ? 'branch \u00B7 ' + e.branch : 'trunk'));\n if (e.branchSpan) {\n const bd = took(e.branchSpan);\n if (e.branchSpan.slowest) sep.classList.add('slow');\n if (bd) {\n sep.appendChild(el('span', 'dur',\n 't+' + startedAt(e.branchSpan) + ' \u00B7 ' + bd + (e.branchSpan.slowest ? ' \u00B7 slowest' : '')));\n }\n }\n listEl.appendChild(sep);\n lastBranch = e.branch;\n lastStamp = null;\n }\n\n const li = el('li', e.branch ? 'branch' : '');\n if (e.covered) li.classList.add('covered');\n const color = branchColor(e.branch);\n if (color) li.style.setProperty('--bc', color);\n li.dataset.key = e.key;\n\n const row = el('div', 'row');\n // Consecutive nodes often start at the same instant (a tool call is recorded\n // the moment the response carrying it is applied). Repeating the offset\n // would only bury the moments where time actually moved.\n const at = startedAt(e);\n row.appendChild(el('span', 't' + (at === lastStamp ? ' same' : ''), at === lastStamp ? '\u00B7' : at));\n lastStamp = at;\n row.appendChild(el('span', 'idx', '#' + (i + 1)));\n const badge = el('span', 'type ' + e.node.type\n + (e.node.type === 'tool_result' && e.node.isError ? ' err' : ''), e.node.type.replace(/_/g, ' '));\n row.appendChild(badge);\n const d = took(e);\n if (d) row.appendChild(el('span', 'dur', d));\n li.appendChild(row);\n li.appendChild(el('div', 'prev', label(e.node)\n + (preview(e.node) ? ' \u2014 ' + preview(e.node).slice(0, 90) : '')));\n li.addEventListener('click', function () { select(e.key, true); });\n listEl.appendChild(li);\n});\n\n// A group header is only worth showing while something in its group is.\nfunction applyFilter(q) {\n const rows = Array.prototype.slice.call(listEl.children);\n rows.forEach(function (li) {\n if (li.classList.contains('sep')) return;\n const e = BY_KEY.get(li.dataset.key);\n const hay = (label(e.node) + ' ' + e.node.type + ' ' + (e.branch || '')\n + ' ' + preview(e.node)).toLowerCase();\n li.hidden = q.length > 0 && hay.indexOf(q) === -1;\n });\n let sep = null, kept = false;\n rows.forEach(function (li) {\n if (li.classList.contains('sep')) {\n if (sep) sep.hidden = !kept;\n sep = li; kept = false;\n } else if (!li.hidden) kept = true;\n });\n if (sep) sep.hidden = !kept;\n}\n\ndocument.getElementById('filter').addEventListener('input', function (ev) {\n applyFilter(ev.target.value.toLowerCase());\n});\n\n// --- detail ---------------------------------------------------------------\n\nfunction message(m) {\n const wrap = el('div', 'msg ' + m.role + (m.isError ? ' err' : ''));\n const role = el('div', 'role');\n role.appendChild(el('span', null, m.role + (m.agent ? ' \u00B7 ' + m.agent : '')\n + (m.name ? ' \u00B7 ' + m.name : '')));\n if (m.callId) role.appendChild(el('span', 'badge', m.callId));\n wrap.appendChild(role);\n\n if (m.role === 'user' && Array.isArray(m.content)) {\n m.content.forEach(function (p) {\n if (p.type === 'text') { wrap.appendChild(el('pre', 'text', p.text)); return; }\n const img = imageEl(p, true);\n wrap.appendChild(img || el('pre', 'text', '[' + p.type + '] ' + mediaUrl(p.url)));\n });\n } else if (typeof m.content === 'string' && m.content) {\n wrap.appendChild(el('pre', 'text', m.role === 'tool' ? pretty(m.content) : m.content));\n } else if (!m.toolCalls) {\n wrap.appendChild(el('div', 'empty', '(no content)'));\n }\n\n (m.toolCalls || []).forEach(function (c) {\n const box = el('div', 'call');\n box.appendChild(el('div', 'name', c.name + '(' + c.id + ')'));\n box.appendChild(el('pre', null, pretty(c.args)));\n wrap.appendChild(box);\n });\n return wrap;\n}\n\nfunction requestBlocks(raw, into) {\n let req;\n try { req = JSON.parse(raw); } catch (e) {\n into.appendChild(textBlock('Request (unparsed)', raw));\n return;\n }\n if (req.system) into.appendChild(textBlock('System prompt', req.system)).classList.add('sys');\n\n const conv = block('Messages', (req.messages || []).length + ' messages');\n (req.messages || []).forEach(function (m) { conv.appendChild(message(m)); });\n if (!(req.messages || []).length) conv.appendChild(el('div', 'empty', '(none)'));\n into.appendChild(conv);\n\n const tools = block('Tools offered', (req.tools || []).length + ' tools');\n (req.tools || []).forEach(function (t) {\n const d = document.createElement('details');\n d.appendChild(el('summary', null, t.name + (t.description ? ' \u2014 ' + t.description : '')));\n d.appendChild(el('pre', null, JSON.stringify(t.parameters, null, 2)));\n tools.appendChild(d);\n });\n if (!(req.tools || []).length) tools.appendChild(el('div', 'empty', '(none)'));\n into.appendChild(tools);\n}\n\nfunction usageTag(u) {\n if (!u) return '';\n return (u.inputTokens || 0) + ' in (' + (u.cachedInputTokens || 0) + ' cached) / '\n + (u.outputTokens || 0) + ' out (' + (u.reasoningTokens || 0) + ' reasoning)';\n}\n\nfunction detailFor(e) {\n const n = e.node;\n const out = document.createDocumentFragment();\n\n const h = el('h2', 'dt');\n h.appendChild(el('span', 'type ' + n.type, n.type.replace(/_/g, ' ')));\n h.appendChild(el('span', null, label(n)));\n out.appendChild(h);\n\n const meta = el('div', 'meta');\n meta.appendChild(el('span', null, 'id ' + n.id));\n meta.appendChild(el('span', null, 'agent ' + n.agent));\n meta.appendChild(el('span', null, n.ts));\n meta.appendChild(el('span', null, 'started t+' + startedAt(e) + (took(e) ? ' \u00B7 took ' + took(e) : '')));\n if (e.branch) {\n const br = el('span', null, 'branch ' + e.branch);\n br.style.color = branchColor(e.branch);\n meta.appendChild(br);\n }\n if (e.covered) meta.appendChild(el('span', null, 'hidden by a later compaction'));\n out.appendChild(meta);\n\n switch (n.type) {\n case 'system_prompt':\n out.appendChild(textBlock('Prompt', blob(n.prompt)));\n // The editable half: which file to open when the instruction is wrong.\n (n.sources || []).forEach(function (s) {\n out.appendChild(textBlock(s.path, blob(s.content), 'prompt file'));\n });\n break;\n\n case 'user_input':\n n.content.forEach(function (p, i) {\n out.appendChild(p.type === 'text'\n ? textBlock('Text part ' + (i + 1), blob(p.text))\n : mediaBlock('Media part ' + (i + 1), p));\n });\n break;\n\n case 'load_skills':\n out.appendChild(textBlock('Skills', n.skills.map(function (s) {\n return s.name + (s.version ? '@' + s.version : '') + ' ' + s.contentHash.slice(0, 12)\n + (s.file ? ' ' + s.file : '');\n }).join('\\n'), n.provider));\n out.appendChild(textBlock('Injected instructions', blob(n.content)));\n out.appendChild(textBlock('Tools unlocked', n.toolNames.join('\\n')));\n break;\n\n case 'memory_recall':\n out.appendChild(textBlock('Query', JSON.stringify(n.query, null, 2),\n n.seeds.length + ' seed(s)'));\n out.appendChild(textBlock('Subgraph', n.nodes.map(function (m) {\n return m.id + ' ' + m.kind\n + (n.seeds.indexOf(m.id) >= 0 ? ' score=' + m.score.toFixed(3) : ' (stitched)');\n }).join('\\n') + edgeLines(n.edges)));\n out.appendChild(textBlock('Injected block', blob(n.content)));\n break;\n\n case 'memory_op':\n out.appendChild(textBlock('Operation', n.nodes.map(function (m) {\n return n.op + ' ' + m.id + ' ' + m.kind + ' rev ' + m.revision;\n }).join('\\n') + edgeLines(n.edges),\n n.files ? n.files + ' file(s)' : undefined));\n break;\n\n case 'llm_call': {\n const u = n.usage || {};\n const strip = el('div', 'stats');\n strip.appendChild(stat('model', n.model));\n strip.appendChild(stat('in', u.inputTokens || 0));\n strip.appendChild(stat('cached', u.cachedInputTokens || 0));\n strip.appendChild(stat('out', u.outputTokens || 0));\n if (u.reasoningTokens) strip.appendChild(stat('reasoning', u.reasoningTokens));\n strip.appendChild(stat('stop', n.stopReason || '?'));\n out.appendChild(strip);\n\n const req = group('Request', 'req', 'sent to ' + n.model);\n if (n.request) requestBlocks(blob(n.request), req.body);\n else {\n req.body.appendChild(el('div', 'empty',\n 'not recorded \u2014 construct the runner with { recordRequests: true } to capture it'));\n }\n out.appendChild(req.el);\n\n const res = group('Response', 'res', n.stopReason);\n if (n.thinking) res.body.appendChild(textBlock('Reasoning', blob(n.thinking)));\n res.body.appendChild(textBlock('Text', blob(n.text)));\n n.toolCalls.forEach(function (c) {\n res.body.appendChild(textBlock('Tool call \u00B7 ' + c.name, pretty(blob(c.args)), c.callId));\n });\n out.appendChild(res.el);\n\n out.appendChild(textBlock('Request digest', n.requestDigest || '(not recorded)'));\n break;\n }\n\n case 'tool_call':\n out.appendChild(textBlock('Arguments', pretty(blob(n.args)), n.name + ' \u00B7 ' + n.callId));\n break;\n\n case 'tool_result':\n out.appendChild(textBlock(n.isError ? 'Error result' : 'Result',\n pretty(blob(n.result)),\n n.name + (n.durationMs !== undefined ? ' \u00B7 ' + n.durationMs + 'ms' : '')));\n break;\n\n case 'handoff':\n out.appendChild(textBlock('Handoff', n.from + ' -> ' + n.to\n + (n.reason ? '\\n\\nreason: ' + n.reason : '')));\n break;\n\n case 'fork':\n n.branches.forEach(function (b) {\n out.appendChild(textBlock('Branch \u00B7 ' + b.name, blob(b.instructions),\n b.agent + ' \u00B7 ' + n.contextMode + ' \u00B7 ' + b.childRunId));\n });\n break;\n\n case 'join':\n n.branches.forEach(function (b, i) {\n const br = e.children[i];\n const bd = br ? took(br) : '';\n out.appendChild(textBlock('Branch \u00B7 ' + b.name,\n b.status === 'ok' ? blob(b.output) : (b.error || blob(b.output)),\n b.status + ' \u00B7 ' + b.agent + ' \u00B7 ' + b.nodes.length + ' nodes'\n + (bd ? ' \u00B7 ' + bd : '') + ' \u00B7 ' + usageTag(b.usage)));\n });\n break;\n\n case 'compaction': {\n out.appendChild(textBlock('Summary', blob(n.summary), n.reason));\n const cov = block('Replaces', n.covers.length + ' nodes');\n const line = el('div', 'empty', '');\n line.textContent = '';\n n.covers.forEach(function (id) {\n const hit = ENTRIES.find(function (x) { return x.node.id === id; });\n const b = el('button', 'link', hit ? label(hit.node) : id);\n if (hit) b.addEventListener('click', function () { select(hit.key, true); });\n line.appendChild(b);\n });\n cov.appendChild(line);\n out.appendChild(cov);\n out.appendChild(textBlock('Summarizer usage', usageTag(n.usage)));\n break;\n }\n\n case 'final_output':\n out.appendChild(textBlock('Output', blob(n.output)));\n if (n.parsed !== undefined) out.appendChild(textBlock('Parsed', JSON.stringify(n.parsed, null, 2)));\n break;\n }\n\n out.appendChild(foldBlock('Raw node', JSON.stringify(n, null, 2)));\n return out;\n}\n\nconst detailEl = document.getElementById('detail');\nconst statsEl = document.getElementById('stats');\nlet selected = null;\n\nfunction select(key, focus) {\n const e = BY_KEY.get(key);\n if (!e) return;\n selected = key;\n detailEl.replaceChildren(detailFor(e));\n Array.prototype.forEach.call(listEl.children, function (li) {\n li.classList.toggle('sel', li.dataset.key === key);\n });\n const li = listEl.querySelector('li[data-key=\"' + key + '\"]');\n if (li) li.scrollIntoView({ block: 'nearest' });\n if (focus) show('detail');\n detailEl.scrollTop = 0;\n}\n\n// --- stats ----------------------------------------------------------------\n//\n// Tokens are not fungible across models and seconds are not fungible across\n// lanes: a thousand tokens cost a different amount on a different model, and\n// branch time runs in parallel with other branch time. So every number here\n// is broken down by model and by agent, and the wall clock sits next to the\n// sums so the gap between them is visible instead of misleading.\n\nfunction bucket() {\n return { calls: 0, errors: 0, ms: 0, in: 0, cached: 0, out: 0, reasoning: 0 };\n}\n\nfunction bucketOf(map, key) {\n if (!map.has(key)) map.set(key, bucket());\n return map.get(key);\n}\n\nfunction addUsage(into, u) {\n if (!u) return;\n into.in += u.inputTokens || 0;\n into.cached += u.cachedInputTokens || 0;\n into.out += u.outputTokens || 0;\n into.reasoning += u.reasoningTokens || 0;\n}\n\nfunction num(n) { return n.toLocaleString('en-US'); }\n\nfunction table(cols, rows, foot) {\n const t = el('table', 'st');\n const head = document.createElement('thead');\n const hr = document.createElement('tr');\n cols.forEach(function (c) { hr.appendChild(el('th', null, c)); });\n head.appendChild(hr);\n t.appendChild(head);\n const body = document.createElement('tbody');\n rows.forEach(function (r) {\n const tr = document.createElement('tr');\n r.forEach(function (v) { tr.appendChild(el('td', null, v)); });\n body.appendChild(tr);\n });\n t.appendChild(body);\n if (foot) {\n const tf = document.createElement('tfoot');\n const fr = document.createElement('tr');\n foot.forEach(function (v) { fr.appendChild(el('td', null, v)); });\n tf.appendChild(fr);\n t.appendChild(tf);\n }\n return t;\n}\n\nconst TOKEN_COLS = ['calls', 'in', 'cached', 'out', 'reasoning', 'time', 'avg'];\n\nfunction tokenRow(name, b) {\n return [name, num(b.calls), num(b.in), num(b.cached), num(b.out), num(b.reasoning),\n fmtDur(b.ms), b.calls ? fmtDur(b.ms / b.calls) : '\u2014'];\n}\n\nfunction byTokens(a, b) { return (b[1].in + b[1].out) - (a[1].in + a[1].out); }\n\nfunction buildStats() {\n const byModel = new Map(), byAgent = new Map(), byTool = new Map(), byType = new Map();\n const all = bucket();\n let llmMs = 0, toolMs = 0, toolCalls = 0, from = null, to = null;\n\n ENTRIES.forEach(function (e) {\n const n = e.node;\n byType.set(n.type, (byType.get(n.type) || 0) + 1);\n if (e.startMs !== null && (from === null || e.startMs < from)) from = e.startMs;\n if (e.endMs !== null && (to === null || e.endMs > to)) to = e.endMs;\n\n // A join's usage is the sum of its branches, whose nodes are already in\n // this list, so counting it too would double every branch token. A\n // compaction has no model of its own but did burn a summarizer.\n if (n.type === 'llm_call' || n.type === 'compaction') {\n const ms = spanMs(e);\n const model = n.type === 'compaction' ? 'summarizer' : n.model;\n [bucketOf(byModel, model), bucketOf(byAgent, n.agent), all].forEach(function (b) {\n addUsage(b, n.usage);\n b.calls += 1;\n b.ms += ms;\n });\n llmMs += ms;\n return;\n }\n // The tool's own measurement when the runner took one; the gap to the\n // previous node otherwise.\n if (n.type === 'tool_result') {\n const b = bucketOf(byTool, n.name);\n const ms = n.durationMs !== undefined ? n.durationMs : spanMs(e);\n b.calls += 1;\n b.ms += ms;\n if (n.isError) b.errors += 1;\n toolCalls += 1;\n toolMs += ms;\n }\n });\n\n const pills = el('div', 'stats');\n pills.appendChild(stat('wall clock', from === null ? '\u2014' : fmtDur(to - from)));\n pills.appendChild(stat('in llm', fmtDur(llmMs)));\n pills.appendChild(stat('in tools', fmtDur(toolMs)));\n pills.appendChild(stat('llm calls', num(all.calls)));\n pills.appendChild(stat('tool calls', num(toolCalls)));\n pills.appendChild(stat('tokens', num(all.in) + ' in / ' + num(all.out) + ' out'));\n pills.appendChild(stat('cached', num(all.cached)));\n pills.appendChild(stat('nodes', num(ENTRIES.length)));\n statsEl.replaceChildren(pills);\n\n const note = el('div', 'hint', 'Branches run in parallel, so llm and tool time are sums '\n + 'over every lane and add up to more than the wall clock.');\n note.style.marginBottom = '14px';\n statsEl.appendChild(note);\n\n const models = Array.from(byModel.entries()).sort(byTokens);\n const modelBlock = block('Tokens by model', models.length + (models.length === 1 ? ' model' : ' models'));\n modelBlock.appendChild(table(['model'].concat(TOKEN_COLS),\n models.map(function (m) { return tokenRow(m[0], m[1]); }), tokenRow('total', all)));\n statsEl.appendChild(modelBlock);\n\n const agents = Array.from(byAgent.entries()).sort(byTokens);\n const agentBlock = block('Tokens by agent', agents.length + (agents.length === 1 ? ' agent' : ' agents'));\n agentBlock.appendChild(table(['agent'].concat(TOKEN_COLS),\n agents.map(function (a) { return tokenRow(a[0], a[1]); }), tokenRow('total', all)));\n statsEl.appendChild(agentBlock);\n\n const tools = Array.from(byTool.entries()).sort(function (a, b) { return b[1].ms - a[1].ms; });\n const toolBlock = block('Tool calls', num(toolCalls) + ' calls \u00B7 ' + fmtDur(toolMs));\n if (tools.length) {\n toolBlock.appendChild(table(['tool', 'calls', 'errors', 'time', 'avg'],\n tools.map(function (t) {\n const b = t[1];\n return [t[0], num(b.calls), b.errors ? num(b.errors) : '', fmtDur(b.ms),\n b.calls ? fmtDur(b.ms / b.calls) : '\u2014'];\n })));\n } else {\n toolBlock.appendChild(el('div', 'empty', '(none)'));\n }\n statsEl.appendChild(toolBlock);\n\n const types = Array.from(byType.entries()).sort(function (a, b) { return b[1] - a[1]; });\n const typeBlock = block('Nodes by type', num(ENTRIES.length) + ' nodes');\n typeBlock.appendChild(table(['type', 'count'],\n types.map(function (t) { return [t[0].replace(/_/g, ' '), num(t[1])]; })));\n statsEl.appendChild(typeBlock);\n}\n\n// --- views ----------------------------------------------------------------\n\n// Panes that hold a zoomable diagram, by view name. A pane laid out while it\n// was hidden has no width to fit against, so becoming visible is the moment it\n// gets a second chance.\nconst PANES = {};\n\nfunction show(view) {\n document.getElementById('graph').hidden = view !== 'graph';\n document.getElementById('agents').hidden = view !== 'agents';\n detailEl.hidden = view !== 'detail';\n statsEl.hidden = view !== 'stats';\n Array.prototype.forEach.call(document.getElementById('viewtabs').children, function (b) {\n b.classList.toggle('on', b.dataset.view === view);\n });\n if (PANES[view]) PANES[view].refit();\n}\nArray.prototype.forEach.call(document.getElementById('viewtabs').children, function (b) {\n b.addEventListener('click', function () { show(b.dataset.view); });\n});\n\n// --- zoom and pan ---------------------------------------------------------\n//\n// A diagram grows with what it describes, so a fixed scale is useless past a\n// dozen nodes. The canvas is moved with a CSS transform rather than scrolled:\n// that keeps zooming anchored on the pointer and costs no layout.\n//\n// Written as a factory because there are two of these \u2014 the run graph and the\n// architecture \u2014 and they must not share a scale, a pan or a drag.\n\nconst MIN_ZOOM = 0.1;\nconst MAX_ZOOM = 4;\n\nfunction panZoom(paneId) {\n const pane = document.getElementById(paneId);\n const viewportEl = pane.querySelector('.viewport');\n const canvasEl = pane.querySelector('.canvas');\n const zoomEl = pane.querySelector('.lvl');\n let zoom = 1, panX = 0, panY = 0;\n let natW = 0, natH = 0;\n let pendingFit = false;\n\n function applyView() {\n canvasEl.style.transform = 'translate(' + panX + 'px,' + panY + 'px) scale(' + zoom + ')';\n zoomEl.textContent = Math.round(zoom * 100) + '%';\n }\n\n function zoomAt(factor, cx, cy) {\n const next = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom * factor));\n const ratio = next / zoom;\n // Keep the point under the cursor fixed while the scale changes.\n panX = cx - (cx - panX) * ratio;\n panY = cy - (cy - panY) * ratio;\n zoom = next;\n applyView();\n }\n\n function zoomCenter(factor) {\n const r = viewportEl.getBoundingClientRect();\n zoomAt(factor, r.width / 2, r.height / 2);\n }\n\n function fit() {\n const r = viewportEl.getBoundingClientRect();\n if (!r.width || !natW || !natH) { pendingFit = true; return; }\n pendingFit = false;\n zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM,\n Math.min((r.width - 32) / natW, (r.height - 32) / natH)));\n panX = (r.width - natW * zoom) / 2;\n panY = Math.max(16, (r.height - natH * zoom) / 2);\n applyView();\n }\n\n pane.querySelector('.gtools').addEventListener('click', function (ev) {\n const what = ev.target.dataset ? ev.target.dataset.zoom : null;\n if (what === 'in') zoomCenter(1.25);\n else if (what === 'out') zoomCenter(1 / 1.25);\n else if (what === 'fit') fit();\n else if (what === 'reset') { zoom = 1; panX = 16; panY = 16; applyView(); }\n });\n\n viewportEl.addEventListener('wheel', function (ev) {\n ev.preventDefault();\n const r = viewportEl.getBoundingClientRect();\n zoomAt(Math.exp(-ev.deltaY * 0.002), ev.clientX - r.left, ev.clientY - r.top);\n }, { passive: false });\n\n let dragging = false, dragMoved = false, startX = 0, startY = 0, baseX = 0, baseY = 0;\n\n viewportEl.addEventListener('pointerdown', function (ev) {\n if (ev.button !== 0) return;\n dragging = true; dragMoved = false;\n startX = ev.clientX; startY = ev.clientY; baseX = panX; baseY = panY;\n });\n viewportEl.addEventListener('pointermove', function (ev) {\n if (!dragging) return;\n const dx = ev.clientX - startX, dy = ev.clientY - startY;\n if (!dragMoved) {\n if (Math.abs(dx) + Math.abs(dy) <= 4) return;\n dragMoved = true;\n // Captured only once this is a drag: capturing on pointerdown would\n // retarget the following click to the viewport and no node would ever\n // receive it.\n viewportEl.setPointerCapture(ev.pointerId);\n viewportEl.classList.add('drag');\n }\n panX = baseX + dx; panY = baseY + dy;\n applyView();\n });\n function endDrag(ev) {\n if (!dragging) return;\n dragging = false;\n viewportEl.classList.remove('drag');\n if (viewportEl.hasPointerCapture(ev.pointerId)) viewportEl.releasePointerCapture(ev.pointerId);\n }\n viewportEl.addEventListener('pointerup', endDrag);\n viewportEl.addEventListener('pointercancel', endDrag);\n viewportEl.addEventListener('dblclick', function () { fit(); });\n window.addEventListener('resize', function () { if (pendingFit) fit(); });\n\n return {\n canvas: canvasEl,\n setNatural: function (w, h) { natW = w; natH = h; fit(); },\n refit: function () { if (pendingFit) fit(); },\n // A pan that ends on a node must not be read as a click on it.\n moved: function () { return dragMoved; }\n };\n}\n\nPANES.graph = panZoom('graph');\nPANES.agents = panZoom('agents');\n\n// --- diagram --------------------------------------------------------------\n\nconst CLASSES = {\n llm_call: 'llm', tool_call: 'tool', tool_result: 'tool', compaction: 'comp',\n fork: 'fork', join: 'fork', final_output: 'final', handoff: 'hand'\n};\n\n// A failed call is the one thing in a trace people look for, so it is coloured\n// by outcome rather than by type \u2014 the same red the sidebar badge uses.\nfunction nodeClass(n) {\n if (n.type === 'tool_result' && n.isError) return 'err';\n return CLASSES[n.type];\n}\n\n// Diagram labels are built from node types and identifiers only, and are\n// stripped to a conservative character set: nothing a model wrote can reach\n// the Mermaid parser, let alone the SVG.\nfunction safe(text) {\n return String(text).replace(/[^\\w .:\\-\\/>+=()]/g, ' ').slice(0, 60).trim();\n}\n\nfunction shape(e, i) {\n const n = e.node;\n // The timing is ours, not the run's: digits and a unit, appended after\n // sanitizing. It stays on one line because Mermaid's strict mode drops the\n // <br/> that would break it.\n const d = took(e);\n const text = '\"' + (i + 1) + '. ' + safe(label(n))\n + ' t+' + startedAt(e) + (d ? ' \u00B7 ' + d : '') + '\"';\n if (n.type === 'fork' || n.type === 'join') return e.key + '{{' + text + '}}';\n if (n.type === 'final_output') return e.key + '([' + text + '])';\n if (n.type === 'user_input' || n.type === 'system_prompt') return e.key + '[/' + text + '/]';\n return e.key + '[' + text + ']';\n}\n\nfunction chain(level, lines) {\n let prev = null;\n level.forEach(function (e) {\n const i = ENTRIES.indexOf(e);\n lines.push(' ' + shape(e, i));\n const cls = nodeClass(e.node);\n if (cls) lines.push(' class ' + e.key + ' ' + cls + ';');\n if (e.covered) lines.push(' class ' + e.key + ' covered;');\n if (prev) lines.push(' ' + prev.key + ' --> ' + e.key);\n\n if (e.node.type === 'join' && e.children.length) {\n // A branch hangs off the fork that opened it and rejoins at the join.\n const fork = level.find(function (x) {\n return x.node.type === 'fork' && x.node.callId === e.node.callId;\n });\n e.children.forEach(function (br, bi) {\n if (!br.entries.length) return;\n const bd = took(br);\n const sg = 'sg_' + e.key + '_' + bi;\n lines.push(' subgraph ' + sg + '[\"' + safe(br.name)\n + ' t+' + startedAt(br) + (bd ? ' \u00B7 ' + bd : '')\n + (br.slowest ? ' \u00B7 slowest' : '') + '\"]');\n lines.push(' direction TB');\n chain(br.entries, lines);\n lines.push(' end');\n // The one branch the join actually waited for, lifted out of the pack.\n if (br.slowest) lines.push(' style ' + sg + ' fill:#5b6070,stroke:#a9b2c6,color:#f2f4f8;');\n if (fork) lines.push(' ' + fork.key + ' -.-> ' + br.entries[0].key);\n lines.push(' ' + br.entries[br.entries.length - 1].key + ' -.-> ' + e.key);\n });\n }\n prev = e;\n });\n}\n\nfunction diagram() {\n const lines = ['flowchart TD'];\n lines.push(' classDef llm fill:#1e3357,stroke:#3d5f9e,color:#cfe0ff;');\n lines.push(' classDef tool fill:#1e3d33,stroke:#3d7a66,color:#c8f0e2;');\n lines.push(' classDef comp fill:#40331a,stroke:#7a6535,color:#f0dfb4;');\n lines.push(' classDef fork fill:#3a2450,stroke:#6b4b90,color:#e6d3ff;');\n lines.push(' classDef final fill:#14392c,stroke:#2f7a5c,color:#c6f5e0;');\n lines.push(' classDef hand fill:#3d2a1b,stroke:#7a5535,color:#f2d9c2;');\n lines.push(' classDef err fill:#4a1f1c,stroke:#8a3a33,color:#f0776c;');\n lines.push(' classDef covered opacity:0.45,stroke-dasharray:4 3;');\n chain(ROOT, lines);\n return lines.join('\\n');\n}\n\n// Mermaid refuses a diagram past either of these (defaults 500 edges and\n// 50000 characters, which a long run passes easily) and the pane then shows\n// only its error. Both are \"secure\" options, so initialize() is the one place\n// they can be raised from. The report is a file on disk, not a live page \u2014\n// a slow render beats a refused one.\nconst MAX_EDGES = 20000;\nconst MAX_TEXT_SIZE = 5000000;\n\n// One Mermaid, two diagrams. Loading it is the only network the page does, so\n// it happens once and both panes wait on the same promise.\nlet mermaidLib = null;\nfunction mermaid() {\n if (!mermaidLib) {\n mermaidLib = import(MERMAID_URL).then(function (m) {\n m.default.initialize({\n startOnLoad: false, theme: 'dark', securityLevel: 'strict',\n maxEdges: MAX_EDGES, maxTextSize: MAX_TEXT_SIZE,\n flowchart: { htmlLabels: false }\n });\n return m.default;\n });\n }\n return mermaidLib;\n}\n\n/** Renders one diagram into a pane and wires its nodes. False when it failed. */\nasync function draw(pane, id, source, onNode) {\n let lib;\n try {\n lib = await mermaid();\n } catch (err) {\n pane.canvas.replaceChildren(el('div', 'hint pad',\n 'Mermaid could not be loaded (offline?). The timeline on the left has the same nodes.'));\n return false;\n }\n try {\n const rendered = await lib.render(id, source);\n // Mermaid produced this markup from labels we sanitized above; no payload\n // text reaches it.\n pane.canvas.innerHTML = rendered.svg;\n } catch (err) {\n pane.canvas.replaceChildren(el('pre', null, 'diagram failed: ' + err.message + '\\n\\n' + source));\n return false;\n }\n const svg = pane.canvas.querySelector('svg');\n if (svg) {\n // Mermaid sizes the SVG to fit its container; we want its natural size so\n // the transform above is the only thing deciding scale.\n const box = svg.viewBox && svg.viewBox.baseVal;\n const w = (box && box.width) || svg.getBoundingClientRect().width;\n const h = (box && box.height) || svg.getBoundingClientRect().height;\n svg.removeAttribute('width');\n svg.removeAttribute('height');\n svg.style.maxWidth = 'none';\n svg.style.width = w + 'px';\n svg.style.height = h + 'px';\n pane.setNatural(w, h);\n }\n pane.canvas.querySelectorAll('.node').forEach(onNode);\n return true;\n}\n\nasync function drawGraph() {\n const ok = await draw(PANES.graph, 'run-graph', diagram(), function (g) {\n // Mermaid ids are '<renderId>-flowchart-<ourKey>-<seq>'; only the key matters.\n const m = /-(n\\d+)-\\d+$/.exec(g.id || '');\n const key = m ? m[1] : null;\n if (!key || !BY_KEY.has(key)) return;\n g.addEventListener('click', function () { if (!PANES.graph.moved()) select(key, true); });\n });\n if (!ok) show('detail');\n}\n\n// --- architecture ---------------------------------------------------------\n//\n// The run graph answers \"what happened\". This one answers \"what was wired up\",\n// which is the question a trajectory structurally cannot: the agent nobody\n// handed off to and the tool nobody called leave no node behind. The declared\n// wiring arrives with the report when a runner was there to describe itself;\n// otherwise the run is read backwards into the same shape, which is smaller\n// but never wrong.\n\nconst SEP = '::';\n\nfunction bump(map, key, entryKey) {\n const cur = map.get(key);\n if (cur) { cur.count += 1; return; }\n map.set(key, { count: 1, key: entryKey });\n}\n\n// What this run actually exercised, keyed the same way the diagram names\n// things \u2014 so drawing \"used\" is a lookup rather than a search.\nconst USED = {\n agents: new Map(), models: new Map(), tools: new Map(),\n skills: new Map(), handoffs: new Map(), memory: new Map(), forks: new Map()\n};\n\nENTRIES.forEach(function (e) {\n const n = e.node;\n bump(USED.agents, n.agent, e.key);\n if (n.type === 'llm_call') {\n if (!USED.models.has(n.agent)) USED.models.set(n.agent, n.model);\n } else if (n.type === 'tool_call') {\n bump(USED.tools, n.agent + SEP + n.name, e.key);\n } else if (n.type === 'load_skills') {\n n.skills.forEach(function (s) { bump(USED.skills, n.agent + SEP + s.name, e.key); });\n } else if (n.type === 'handoff') {\n bump(USED.handoffs, n.from + SEP + n.to, e.key);\n } else if (n.type === 'memory_recall' || n.type === 'memory_op') {\n bump(USED.memory, n.agent, e.key);\n } else if (n.type === 'fork') {\n n.branches.forEach(function (b) { bump(USED.forks, n.agent + SEP + b.agent, e.key); });\n }\n});\n\nfunction has(list, name) {\n return list.some(function (x) { return x.name === name; });\n}\n\n/** The run read backwards into the same shape. Used when none was supplied. */\nfunction observedArchitecture() {\n const byName = new Map();\n function agentOf(name) {\n if (!byName.has(name)) {\n byName.set(name, { name: name, tools: [], handoffs: [] });\n }\n return byName.get(name);\n }\n ENTRIES.forEach(function (e) {\n const n = e.node;\n const a = agentOf(n.agent);\n if (n.type === 'llm_call') {\n if (!a.model) a.model = n.model;\n } else if (n.type === 'tool_call') {\n // Handoff tools are drawn as edges between agents, never as tool nodes.\n const handoff = n.name.indexOf('transfer_to_') === 0;\n if (!handoff && !has(a.tools, n.name)) a.tools.push({ name: n.name });\n } else if (n.type === 'load_skills') {\n if (!a.skills) a.skills = { provider: n.provider, discovery: 'index', catalog: [] };\n n.skills.forEach(function (s) {\n if (has(a.skills.catalog, s.name)) return;\n // The unlocked tools are recorded per activation, not per skill, so\n // they can only be attributed when one skill loaded on its own.\n a.skills.catalog.push({\n name: s.name, version: s.version,\n toolNames: n.skills.length === 1 ? n.toolNames : undefined\n });\n });\n } else if (n.type === 'handoff') {\n const from = agentOf(n.from);\n agentOf(n.to);\n if (from.handoffs.indexOf(n.to) < 0) from.handoffs.push(n.to);\n } else if (n.type === 'memory_recall' || n.type === 'memory_op') {\n // A run shows that an agent reached the memory, never how wide its mask\n // was: nothing it did not read leaves a trace to read the mask off.\n if (!a.memory) a.memory = { access: 'read', sees: [], writes: [] };\n if (n.type === 'memory_op') a.memory.access = 'read-write';\n } else if (n.type === 'fork') {\n if (!a.fork) a.fork = { agents: [] };\n n.branches.forEach(function (b) {\n agentOf(b.agent);\n if (a.fork.agents.indexOf(b.agent) < 0) a.fork.agents.push(b.agent);\n });\n }\n });\n return { source: 'observed', agents: Array.from(byName.values()) };\n}\n\nconst ARCH = DATA.architecture || observedArchitecture();\n\n// Diagram key -> the first trajectory node that exercised the thing it names,\n// or null when nothing did. Clicking is only offered for the former.\nconst ARCH_KEYS = new Map();\nlet archSeq = 0;\nfunction archKey(used) {\n const k = 'x' + archSeq++;\n ARCH_KEYS.set(k, used ? used.key : null);\n return k;\n}\n\n/** An agent with more tools than this gets a \"+N more\" node instead of a wall. */\nconst MAX_TOOLS = 12;\n\nfunction times(used) {\n return used ? ' x' + used.count : '';\n}\n\nfunction archDiagram() {\n const lines = ['flowchart LR'];\n lines.push(' classDef agent fill:#1e3357,stroke:#3d5f9e,color:#cfe0ff;');\n lines.push(' classDef start fill:#14392c,stroke:#2f7a5c,color:#c6f5e0;');\n lines.push(' classDef tool fill:#1e3d33,stroke:#3d7a66,color:#c8f0e2;');\n lines.push(' classDef skill fill:#3a2450,stroke:#6b4b90,color:#e6d3ff;');\n lines.push(' classDef mem fill:#40331a,stroke:#7a6535,color:#f0dfb4;');\n lines.push(' classDef more fill:#1b202c,stroke:#39415a,color:#8a92a6;');\n lines.push(' classDef idle opacity:0.4,stroke-dasharray:4 3;');\n\n const startAgent = (STATE.spec && STATE.spec.startAgent) || STATE.agentName;\n const selfKey = new Map();\n // Minted up front so a hand-off can name an agent declared further down.\n ARCH.agents.forEach(function (a) {\n selfKey.set(a.name, archKey(USED.agents.get(a.name)));\n });\n\n ARCH.agents.forEach(function (a) {\n const self = selfKey.get(a.name);\n const live = USED.agents.get(a.name);\n // The model on the node is the declared one, or \u2014 when the report carries\n // no wiring \u2014 whatever this run was seen using.\n const model = a.model || USED.models.get(a.name);\n lines.push(' subgraph sg_' + self + '[\"' + safe(a.name)\n + (a.description ? ' - ' + safe(a.description) : '') + '\"]');\n lines.push(' direction LR');\n lines.push(' ' + self + '[[\"' + safe(a.name)\n + (model ? ' ' + safe(model) + (a.inheritedModel ? ' (inherited)' : '') : '')\n + '\"]]');\n lines.push(' class ' + self + ' ' + (a.name === startAgent ? 'start' : 'agent') + ';');\n if (!live) lines.push(' class ' + self + ' idle;');\n\n // Skills first: a skill owns tools, so its node has to exist before the\n // tools it unlocks can point back at it.\n const skillKey = new Map();\n const catalog = (a.skills && a.skills.catalog) || [];\n catalog.forEach(function (s) {\n const used = USED.skills.get(a.name + SEP + s.name);\n const k = archKey(used);\n skillKey.set(s.name, k);\n lines.push(' ' + k + '([\"' + safe(s.name) + (s.preload ? ' (preloaded)' : '')\n + times(used) + '\"])');\n lines.push(' class ' + k + ' skill;');\n if (!used) lines.push(' class ' + k + ' idle;');\n lines.push(' ' + self + ' --- ' + k);\n });\n if (a.skills && a.skills.unresolved) {\n const k = archKey(null);\n lines.push(' ' + k + '([\"catalog unavailable: ' + safe(a.skills.provider) + '\"])');\n lines.push(' class ' + k + ' skill;');\n lines.push(' class ' + k + ' idle;');\n lines.push(' ' + self + ' --- ' + k);\n }\n\n const shown = a.tools.slice(0, MAX_TOOLS);\n shown.forEach(function (t) {\n const used = USED.tools.get(a.name + SEP + t.name);\n const k = archKey(used);\n lines.push(' ' + k + '[\"' + safe(t.name) + times(used) + '\"]');\n lines.push(' class ' + k + ' tool;');\n if (!used) lines.push(' class ' + k + ' idle;');\n // A skill-owned tool hangs off the skill that unlocks it, not off the\n // agent: that edge is the whole point of a locked tool.\n const owner = t.skill ? skillKey.get(t.skill) : null;\n if (owner) lines.push(' ' + owner + ' -.-> ' + k);\n else lines.push(' ' + self + ' --- ' + k);\n });\n if (a.tools.length > shown.length) {\n const k = archKey(null);\n lines.push(' ' + k + '[\"+' + (a.tools.length - shown.length) + ' more tools\"]');\n lines.push(' class ' + k + ' more;');\n lines.push(' ' + self + ' --- ' + k);\n }\n\n if (a.memory) {\n const used = USED.memory.get(a.name);\n const k = archKey(used);\n const sees = Array.isArray(a.memory.sees) ? a.memory.sees : [a.memory.sees];\n lines.push(' ' + k + '[(\"memory ' + (a.memory.access === 'read' ? '(ro)' : '(rw)')\n + ' sees ' + safe(sees.join(' ') || '*') + '\")]');\n lines.push(' class ' + k + ' mem;');\n if (!used) lines.push(' class ' + k + ' idle;');\n lines.push(' ' + self + ' --- ' + k);\n }\n lines.push(' end');\n // Mermaid's default subgraph is a light box, which on a dark page reads as\n // the foreground rather than as the container. An agent nobody entered is\n // outlined rather than filled, so a dead corner of the wiring is visible\n // from across the diagram.\n lines.push(' style sg_' + self + ' fill:#12151d,color:#8a92a6,stroke:'\n + (live ? '#39415a;' : '#2b3346,stroke-dasharray:5 4;'));\n });\n\n // Edges between agents live outside every subgraph, so Mermaid routes them\n // between the boxes instead of trying to keep them inside one.\n ARCH.agents.forEach(function (a) {\n const self = selfKey.get(a.name);\n a.handoffs.forEach(function (to) {\n if (!selfKey.has(to)) return;\n const used = USED.handoffs.get(a.name + SEP + to);\n lines.push(' ' + self + (used ? ' -- \"handoff' + times(used) + '\" --> ' : ' -.-> ')\n + selfKey.get(to));\n });\n ((a.fork && a.fork.agents) || []).forEach(function (to) {\n if (!selfKey.has(to) || to === a.name) return;\n const used = USED.forks.get(a.name + SEP + to);\n lines.push(' ' + self + ' == \"fork' + times(used) + '\" ==> ' + selfKey.get(to));\n });\n });\n return lines.join('\\n');\n}\n\nfunction archLegend() {\n const agents = ARCH.agents.length;\n const tools = ARCH.agents.reduce(function (n, a) { return n + a.tools.length; }, 0);\n const skills = ARCH.agents.reduce(function (n, a) {\n return n + ((a.skills && a.skills.catalog.length) || 0);\n }, 0);\n const idle = ARCH.agents.filter(function (a) { return !USED.agents.has(a.name); }).length;\n return (ARCH.source === 'declared' ? 'declared' : 'observed only')\n + ' \\u00b7 ' + agents + ' agents \\u00b7 ' + tools + ' tools \\u00b7 ' + skills + ' skills'\n + (idle ? ' \\u00b7 ' + idle + ' idle' : '')\n + ' \\u00b7 dimmed = unused \\u00b7 click to jump';\n}\n\nasync function drawArch() {\n document.getElementById('alegend').textContent = archLegend();\n if (!ARCH.agents.length) {\n PANES.agents.canvas.replaceChildren(el('div', 'hint pad', 'No agents to draw.'));\n return;\n }\n await draw(PANES.agents, 'arch-graph', archDiagram(), function (g) {\n const m = /-(x\\d+)-\\d+$/.exec(g.id || '');\n const key = m && ARCH_KEYS.get(m[1]);\n if (!key) return;\n g.addEventListener('click', function () { if (!PANES.agents.moved()) select(key, true); });\n });\n}\n\ndrawGraph().then(drawArch);\nbuildStats();\nif (ENTRIES.length) select('n0', false);\n";
2
2
  //# sourceMappingURL=client.d.ts.map
@@ -60,6 +60,15 @@ const ROOT = flatten(STATE.trajectory, 0, null);
60
60
 
61
61
  function names(list) { return list.join(', '); }
62
62
 
63
+ // The edges are what makes a recollection a subgraph rather than a hit list,
64
+ // so they are shown even though the injected block already renders them.
65
+ function edgeLines(edges) {
66
+ if (!edges || !edges.length) return '';
67
+ return '\\n\\n' + edges.map(function (e) {
68
+ return e.source + ' --' + e.relation + '--> ' + e.target;
69
+ }).join('\\n');
70
+ }
71
+
63
72
  function base(path) { return path.split('/').pop() || path; }
64
73
 
65
74
  function label(n) {
@@ -68,8 +77,8 @@ function label(n) {
68
77
  case 'system_prompt': return 'system prompt'
69
78
  + (n.sources && n.sources.length ? ': ' + names(n.sources.map(function (s) { return base(s.path); })) : '');
70
79
  case 'load_skills': return 'skills: ' + names(n.skills.map(function (s) { return s.name; }));
71
- case 'memory_recall': return 'memory recall: ' + n.scope;
72
- case 'memory_op': return 'memory ' + n.op;
80
+ case 'memory_recall': return 'memory recall: ' + n.nodes.length + ' nodes';
81
+ case 'memory_op': return 'memory ' + n.op + ': ' + n.nodes.length + ' nodes';
73
82
  case 'llm_call': return 'llm: ' + n.model + (n.toolCalls.length
74
83
  ? ' -> ' + names(n.toolCalls.map(function (c) { return c.name; })) : '');
75
84
  case 'tool_call': return 'call: ' + n.name;
@@ -512,18 +521,20 @@ function detailFor(e) {
512
521
  break;
513
522
 
514
523
  case 'memory_recall':
515
- out.appendChild(textBlock('Query', JSON.stringify(n.query, null, 2), n.store + ' · ' + n.scope));
516
- out.appendChild(textBlock('Hits', n.hits.map(function (hit) {
517
- return hit.id + ' score=' + hit.score + ' rev=' + hit.revision;
518
- }).join('\\n')));
524
+ out.appendChild(textBlock('Query', JSON.stringify(n.query, null, 2),
525
+ n.seeds.length + ' seed(s)'));
526
+ out.appendChild(textBlock('Subgraph', n.nodes.map(function (m) {
527
+ return m.id + ' ' + m.kind
528
+ + (n.seeds.indexOf(m.id) >= 0 ? ' score=' + m.score.toFixed(3) : ' (stitched)');
529
+ }).join('\\n') + edgeLines(n.edges)));
519
530
  out.appendChild(textBlock('Injected block', blob(n.content)));
520
531
  break;
521
532
 
522
533
  case 'memory_op':
523
- out.appendChild(textBlock('Operation',
524
- n.op + ' ' + n.recordId + ' (rev ' + n.revision + ')', n.store + ' · ' + n.scope));
525
- if (n.before) out.appendChild(textBlock('Before', blob(n.before)));
526
- if (n.after) out.appendChild(textBlock('After', blob(n.after)));
534
+ out.appendChild(textBlock('Operation', n.nodes.map(function (m) {
535
+ return n.op + ' ' + m.id + ' ' + m.kind + ' rev ' + m.revision;
536
+ }).join('\\n') + edgeLines(n.edges),
537
+ n.files ? n.files + ' file(s)' : undefined));
527
538
  break;
528
539
 
529
540
  case 'llm_call': {
@@ -998,6 +1009,14 @@ function diagram() {
998
1009
  return lines.join('\\n');
999
1010
  }
1000
1011
 
1012
+ // Mermaid refuses a diagram past either of these (defaults 500 edges and
1013
+ // 50000 characters, which a long run passes easily) and the pane then shows
1014
+ // only its error. Both are "secure" options, so initialize() is the one place
1015
+ // they can be raised from. The report is a file on disk, not a live page —
1016
+ // a slow render beats a refused one.
1017
+ const MAX_EDGES = 20000;
1018
+ const MAX_TEXT_SIZE = 5000000;
1019
+
1001
1020
  // One Mermaid, two diagrams. Loading it is the only network the page does, so
1002
1021
  // it happens once and both panes wait on the same promise.
1003
1022
  let mermaidLib = null;
@@ -1006,6 +1025,7 @@ function mermaid() {
1006
1025
  mermaidLib = import(MERMAID_URL).then(function (m) {
1007
1026
  m.default.initialize({
1008
1027
  startOnLoad: false, theme: 'dark', securityLevel: 'strict',
1028
+ maxEdges: MAX_EDGES, maxTextSize: MAX_TEXT_SIZE,
1009
1029
  flowchart: { htmlLabels: false }
1010
1030
  });
1011
1031
  return m.default;
@@ -1098,7 +1118,7 @@ ENTRIES.forEach(function (e) {
1098
1118
  } else if (n.type === 'handoff') {
1099
1119
  bump(USED.handoffs, n.from + SEP + n.to, e.key);
1100
1120
  } else if (n.type === 'memory_recall' || n.type === 'memory_op') {
1101
- bump(USED.memory, n.agent + SEP + n.store + '/' + n.scope, e.key);
1121
+ bump(USED.memory, n.agent, e.key);
1102
1122
  } else if (n.type === 'fork') {
1103
1123
  n.branches.forEach(function (b) { bump(USED.forks, n.agent + SEP + b.agent, e.key); });
1104
1124
  }
@@ -1113,7 +1133,7 @@ function observedArchitecture() {
1113
1133
  const byName = new Map();
1114
1134
  function agentOf(name) {
1115
1135
  if (!byName.has(name)) {
1116
- byName.set(name, { name: name, tools: [], handoffs: [], memory: [] });
1136
+ byName.set(name, { name: name, tools: [], handoffs: [] });
1117
1137
  }
1118
1138
  return byName.get(name);
1119
1139
  }
@@ -1142,15 +1162,10 @@ function observedArchitecture() {
1142
1162
  agentOf(n.to);
1143
1163
  if (from.handoffs.indexOf(n.to) < 0) from.handoffs.push(n.to);
1144
1164
  } else if (n.type === 'memory_recall' || n.type === 'memory_op') {
1145
- const known = a.memory.some(function (m) {
1146
- return m.store === n.store && m.scope === n.scope;
1147
- });
1148
- if (!known) {
1149
- a.memory.push({
1150
- store: n.store, scope: n.scope,
1151
- access: n.type === 'memory_op' ? 'read-write' : 'read'
1152
- });
1153
- }
1165
+ // A run shows that an agent reached the memory, never how wide its mask
1166
+ // was: nothing it did not read leaves a trace to read the mask off.
1167
+ if (!a.memory) a.memory = { access: 'read', sees: [], writes: [] };
1168
+ if (n.type === 'memory_op') a.memory.access = 'read-write';
1154
1169
  } else if (n.type === 'fork') {
1155
1170
  if (!a.fork) a.fork = { agents: [] };
1156
1171
  n.branches.forEach(function (b) {
@@ -1255,15 +1270,16 @@ function archDiagram() {
1255
1270
  lines.push(' ' + self + ' --- ' + k);
1256
1271
  }
1257
1272
 
1258
- a.memory.forEach(function (m) {
1259
- const used = USED.memory.get(a.name + SEP + m.store + '/' + m.scope);
1273
+ if (a.memory) {
1274
+ const used = USED.memory.get(a.name);
1260
1275
  const k = archKey(used);
1261
- lines.push(' ' + k + '[("' + safe(m.store) + ' / ' + safe(m.scope)
1262
- + (m.access === 'read-write' ? ' (rw)' : ' (ro)') + '")]');
1276
+ const sees = Array.isArray(a.memory.sees) ? a.memory.sees : [a.memory.sees];
1277
+ lines.push(' ' + k + '[("memory ' + (a.memory.access === 'read' ? '(ro)' : '(rw)')
1278
+ + ' sees ' + safe(sees.join(' ') || '*') + '")]');
1263
1279
  lines.push(' class ' + k + ' mem;');
1264
1280
  if (!used) lines.push(' class ' + k + ' idle;');
1265
1281
  lines.push(' ' + self + ' --- ' + k);
1266
- });
1282
+ }
1267
1283
  lines.push(' end');
1268
1284
  // Mermaid's default subgraph is a light box, which on a dark page reads as
1269
1285
  // the foreground rather than as the container. An agent nobody entered is
package/dist/kernel.d.ts CHANGED
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { Agent, AgentRegistry } from './agent.ts';
3
3
  import type { PendingToolCall } from './events.ts';
4
4
  import { type IdClock } from './ids.ts';
5
- import { type MemoryOpSpec, type MemoryRecallSpec } from './memory.ts';
5
+ import type { MemoryOpSpec, MemoryRecallSpec } from './memory/types.ts';
6
6
  import type { ModelRequest, ModelResponse } from './model.ts';
7
7
  import type { Services } from './services.ts';
8
8
  import { type Skill } from './skills.ts';
package/dist/kernel.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { z } from 'zod';
2
2
  import { Agent, AgentRegistry, handoffTarget, handoffTool } from "./agent.js";
3
3
  import { systemClock } from "./ids.js";
4
- import { memoryTools } from "./memory.js";
4
+ import { memoryInstructions, renderPreferences } from "./memory/instructions.js";
5
+ import { memoryTools } from "./memory/tools.js";
5
6
  import { hash } from "./payload.js";
6
7
  import { composePrompt } from "./prompt.js";
7
8
  import { allows, lockedSkillTools, renderSkillIndex, renderSkills, skillContentHash, skillTools, } from "./skills.js";
@@ -285,7 +286,10 @@ export async function resolveTools(state, reg, env) {
285
286
  for (const name of agent.handoffs) {
286
287
  tools.push(handoffTool(name, reg.find(name)?.description));
287
288
  }
288
- tools.push(...memoryTools(agent.memoryBindings(ctx)));
289
+ const binding = agent.memoryBinding(ctx);
290
+ if (binding && env.services.memory) {
291
+ tools.push(...memoryTools({ index: env.services.memory, binding }));
292
+ }
289
293
  if (agent.skills) {
290
294
  const binding = agent.skills;
291
295
  tools.push(...skillTools(binding));
@@ -318,14 +322,24 @@ function toSchema(t) {
318
322
  return { name: t.name, description: t.description, parameters: t.parameters };
319
323
  }
320
324
  /**
321
- * Prompt text the runtime owns rather than the author: the skill index and the
322
- * `final_output` instruction. Both used to be appended inside `buildRequest`,
323
- * which meant part of the system prompt existed in no node and showed up in no
324
- * audit. Composed in now, always last, so the volatile tail never invalidates
325
- * the cacheable prefix.
325
+ * Prompt text the runtime owns rather than the author: how to use memory, the
326
+ * user's standing preferences, the skill index and the `final_output`
327
+ * instruction. Most used to be appended inside `buildRequest`, which meant part
328
+ * of the system prompt existed in no node and showed up in no audit. Composed
329
+ * in now, always last, so the volatile tail never invalidates the cacheable
330
+ * prefix.
326
331
  */
327
332
  async function derivedPrompt(agent, state, env) {
328
333
  const out = [];
334
+ const memory = agent.memoryBinding(state.context);
335
+ if (memory && env.services.memory) {
336
+ // The one part of the prompt that reads mutable state. It is allowed
337
+ // because preferences change at most once in a run and
338
+ // `applySystemPrompt` is keyed on the rendered bytes, so a commit
339
+ // re-renders the prefix once rather than every turn.
340
+ out.push(memoryInstructions(memory));
341
+ out.push(renderPreferences(env.services.memory.preferences(memory.sees)));
342
+ }
329
343
  if (agent.skills?.discovery === 'index') {
330
344
  const binding = agent.skills;
331
345
  const provider = env.services.skillProvider(binding.provider);
@@ -654,11 +668,14 @@ export async function applyToolResult(state, callId, outcome, env) {
654
668
  durationMs: outcome.durationMs,
655
669
  });
656
670
  for (const effect of outcome.effects ?? []) {
657
- if (effect.kind === 'memory_op') {
671
+ if (effect.kind === 'skill_load') {
672
+ await addSkillLoad(b, env, effect.spec);
673
+ }
674
+ else if (effect.spec.kind === 'op') {
658
675
  await addMemoryOp(b, env, effect.spec);
659
676
  }
660
677
  else {
661
- await addSkillLoad(b, env, effect.spec);
678
+ await addMemoryRecall(b, env, effect.spec);
662
679
  }
663
680
  }
664
681
  const target = outcome.isError ? undefined : handoffTarget(call.name);
@@ -694,13 +711,20 @@ async function addMemoryOp(b, env, spec) {
694
711
  b.add({
695
712
  type: 'memory_op',
696
713
  op: spec.op,
697
- store: spec.store,
698
- scope: spec.scope,
699
714
  opId: spec.opId,
700
- recordId: spec.recordId,
701
- revision: spec.revision,
702
- before: spec.before === undefined ? undefined : await put(env, spec.before),
703
- after: spec.after === undefined ? undefined : await put(env, spec.after),
715
+ nodes: spec.nodes,
716
+ edges: spec.edges,
717
+ files: spec.files,
718
+ });
719
+ }
720
+ async function addMemoryRecall(b, env, spec) {
721
+ b.add({
722
+ type: 'memory_recall',
723
+ query: spec.query,
724
+ seeds: spec.seeds,
725
+ nodes: spec.nodes,
726
+ edges: spec.edges,
727
+ content: await put(env, spec.content),
704
728
  });
705
729
  }
706
730
  async function addSkillLoad(b, env, spec) {
@@ -724,14 +748,7 @@ export async function applyMemoryEffect(state, effect, env) {
724
748
  await addMemoryOp(b, env, effect);
725
749
  }
726
750
  else {
727
- b.add({
728
- type: 'memory_recall',
729
- store: effect.store,
730
- scope: effect.scope,
731
- query: effect.query,
732
- hits: effect.hits,
733
- content: await put(env, effect.content),
734
- });
751
+ await addMemoryRecall(b, env, effect);
735
752
  }
736
753
  return b.commit({});
737
754
  }
@@ -0,0 +1,24 @@
1
+ import { type MemoryFile } from './types.ts';
2
+ /** Where remembered files appear in the agent's namespace. */
3
+ export declare const MEMORY_MOUNT = "/memory";
4
+ /**
5
+ * Big enough for any script or config worth re-running, small enough that the
6
+ * memory directory cannot become a place where build outputs go to hide.
7
+ */
8
+ export declare const MAX_FILE_BYTES: number;
9
+ export interface RememberOptions {
10
+ maxBytes?: number;
11
+ }
12
+ /**
13
+ * Copy `source` into the memory directory under `id` and describe it.
14
+ *
15
+ * The bytes are read once and both hashed and written from that one buffer, so
16
+ * the digest provably belongs to the copy that was kept — re-reading the source
17
+ * to hash it would leave a window for it to change in between.
18
+ */
19
+ export declare function rememberFile(dir: string, source: string, id: string, opts?: RememberOptions): Promise<MemoryFile>;
20
+ /** The host path of a remembered file, for reading it back or deleting it. */
21
+ export declare function hostPath(dir: string, file: MemoryFile): string;
22
+ /** Drop the bytes of a forgotten node. Missing is success — the goal is absence. */
23
+ export declare function forgetFile(dir: string, file: MemoryFile): Promise<void>;
24
+ //# sourceMappingURL=files.d.ts.map