eve 0.30.5 → 0.30.7

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 (97) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/src/cli/commands/trace-detail.d.ts +53 -0
  3. package/dist/src/cli/commands/trace-detail.js +1 -0
  4. package/dist/src/cli/commands/trace.d.ts +4 -1
  5. package/dist/src/cli/commands/trace.js +4 -4
  6. package/dist/src/cli/dev/tui/terminal-renderer.js +2 -2
  7. package/dist/src/cli/dev/tui/traces/trace-content.d.ts +3 -3
  8. package/dist/src/cli/dev/tui/traces/trace-content.js +1 -1
  9. package/dist/src/cli/dev/tui/traces/trace-view.js +1 -1
  10. package/dist/src/cli/run.js +1 -1
  11. package/dist/src/compiler/extension-compatibility.d.ts +10 -10
  12. package/dist/src/compiler/extension-compatibility.js +1 -1
  13. package/dist/src/context/dynamic-subagent-lifecycle.d.ts +2 -0
  14. package/dist/src/context/dynamic-subagent-lifecycle.js +1 -1
  15. package/dist/src/execution/agent-continuation-bundle.d.ts +13 -0
  16. package/dist/src/execution/agent-continuation-bundle.js +1 -0
  17. package/dist/src/execution/agent-handle-dispatch.d.ts +32 -4
  18. package/dist/src/execution/agent-handle-dispatch.js +1 -1
  19. package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
  20. package/dist/src/execution/delegated-parent-notification.d.ts +30 -4
  21. package/dist/src/execution/delegated-parent-notification.js +1 -1
  22. package/dist/src/execution/delegated-parent-result.js +1 -1
  23. package/dist/src/execution/dispatch-action-failures.d.ts +8 -0
  24. package/dist/src/execution/dispatch-action-failures.js +1 -0
  25. package/dist/src/execution/dispatch-runtime-actions-step.d.ts +8 -7
  26. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  27. package/dist/src/execution/dispatch-start-operation.d.ts +15 -0
  28. package/dist/src/execution/dispatch-start-operation.js +1 -0
  29. package/dist/src/execution/forward-turn-cancellation-step.js +1 -1
  30. package/dist/src/execution/next-driver-action.d.ts +12 -0
  31. package/dist/src/execution/node-step.d.ts +1 -1
  32. package/dist/src/execution/node-step.js +1 -1
  33. package/dist/src/execution/parked-delivery-wait.d.ts +35 -0
  34. package/dist/src/execution/parked-delivery-wait.js +1 -0
  35. package/dist/src/execution/remote-agent-dispatch.d.ts +42 -0
  36. package/dist/src/execution/remote-agent-dispatch.js +1 -1
  37. package/dist/src/execution/sandbox/prewarm.js +1 -1
  38. package/dist/src/execution/session-timeout-steps.js +1 -1
  39. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  40. package/dist/src/execution/subagent-invocation.d.ts +3 -0
  41. package/dist/src/execution/subagent-invocation.js +1 -1
  42. package/dist/src/execution/subagent-tool.d.ts +7 -0
  43. package/dist/src/execution/subagent-tool.js +1 -1
  44. package/dist/src/execution/terminate-child-sessions-step.d.ts +15 -0
  45. package/dist/src/execution/terminate-child-sessions-step.js +1 -0
  46. package/dist/src/execution/turn-control-protocol.js +1 -1
  47. package/dist/src/execution/turn-execution-cursor.d.ts +3 -0
  48. package/dist/src/execution/turn-workflow.js +1 -1
  49. package/dist/src/execution/workflow-entry.js +1 -1
  50. package/dist/src/execution/workflow-runtime.js +1 -1
  51. package/dist/src/execution/workflow-steps.d.ts +8 -1
  52. package/dist/src/execution/workflow-steps.js +1 -1
  53. package/dist/src/harness/agent-handle-errors.d.ts +0 -2
  54. package/dist/src/harness/agent-handle-errors.js +1 -1
  55. package/dist/src/harness/handles/transitions.d.ts +16 -1
  56. package/dist/src/harness/handles/transitions.js +1 -1
  57. package/dist/src/harness/messages.d.ts +4 -2
  58. package/dist/src/harness/messages.js +1 -1
  59. package/dist/src/harness/runtime-actions.js +1 -1
  60. package/dist/src/harness/tool-loop.js +2 -2
  61. package/dist/src/harness/turn-tag-state.d.ts +16 -0
  62. package/dist/src/harness/turn-tag-state.js +1 -1
  63. package/dist/src/harness/types.d.ts +7 -2
  64. package/dist/src/internal/application/package.js +1 -1
  65. package/dist/src/internal/helpers/markdown.d.ts +8 -11
  66. package/dist/src/internal/helpers/markdown.js +2 -2
  67. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  68. package/dist/src/public/channels/eve.js +1 -1
  69. package/dist/src/runtime/actions/types.d.ts +11 -2
  70. package/dist/src/runtime/actions/types.js +1 -1
  71. package/dist/src/runtime/agent/bootstrap.js +1 -1
  72. package/dist/src/runtime/framework-tools/agent.d.ts +16 -0
  73. package/dist/src/runtime/framework-tools/agent.js +1 -1
  74. package/dist/src/runtime/prompt/compose.d.ts +7 -0
  75. package/dist/src/runtime/prompt/compose.js +1 -1
  76. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  77. package/dist/src/runtime/session-callback-route.js +1 -1
  78. package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
  79. package/dist/src/runtime/subagents/registry.d.ts +20 -1
  80. package/dist/src/runtime/subagents/registry.js +1 -1
  81. package/dist/src/setup/integrations/github/connect.d.ts +28 -0
  82. package/dist/src/setup/integrations/github/connect.js +1 -0
  83. package/dist/src/setup/integrations/github/setup.d.ts +15 -0
  84. package/dist/src/setup/integrations/github/setup.js +15 -0
  85. package/dist/src/setup/integrations/registry.js +1 -1
  86. package/dist/src/setup/scaffold/create/project.js +1 -1
  87. package/dist/src/tracing/local-trace-reader.d.ts +10 -0
  88. package/dist/src/tracing/local-trace-reader.js +1 -1
  89. package/docs/channels/github.mdx +11 -16
  90. package/docs/concepts/security-model.md +1 -0
  91. package/docs/guides/state.md +1 -0
  92. package/docs/reference/cli.md +4 -0
  93. package/docs/schedules.mdx +1 -0
  94. package/docs/skills.mdx +2 -0
  95. package/docs/subagents.mdx +28 -1
  96. package/docs/tools/human-in-the-loop.md +1 -0
  97. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # eve
2
2
 
3
+ ## 0.30.7
4
+
5
+ ### Patch Changes
6
+
7
+ - e5c9191: Add experimental agent messaging behind `experimental.subagentPersistentSessions` in `agent.ts`. Opted-in agents keep delegated children alive after they answer: each child is owned by a lifecycle handle, settles every turn with an explicit outcome carrying its per-turn token usage, and parks instead of terminating. The parent's subagent tools gain an `agentId` parameter to continue a parked child, discoverable from a per-model-call `<agents>` system injection that lists only parked (resumable) children. An omitted, empty, or unknown `agentId` starts a fresh child; continuing a child that is still starting or working fails with `AGENT_BUSY`. Without the opt-in, children keep running as one-shot tasks. The subagent tool input schema no longer includes the unused `description` field.
8
+ - bd21332: Cancelling a turn with running delegated children no longer leaks their handles as permanently `running`. The cancellation epilogue now parks each abandoned child as `"(cancelled)"`, so cancelled children stay resumable and later cancellations no longer stall retrying already-dead children.
9
+ - 1758161: Add guided GitHub channel setup through `eve add channel/github`. The flow provisions a Vercel Connect GitHub App, routes verified webhooks, scaffolds the channel, and explains how to install and use the app.
10
+ - 56de47b: Show far more of what local traces record in `eve traces`: span rows carry inline token/cost/tool chips, the header aggregates models, token totals, cost, and errors, and two new flags expose everything else — `--verbose` expands every span with all attributes and events, and `--json` dumps the full trace machine-readably.
11
+
12
+ ## 0.30.6
13
+
14
+ ### Patch Changes
15
+
16
+ - 7fa4d36: Accept unmodeled `SKILL.md` frontmatter when importing a skill from another runtime. These fields are no-ops in eve.
17
+
3
18
  ## 0.30.5
4
19
 
5
20
  ### Patch Changes
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Span-level detail rendering and trace-level usage aggregation for
3
+ * `eve traces`. Kept separate from the command module: the tree renderer
4
+ * stays compact while these helpers answer "what does this span carry" —
5
+ * inline metric chips for tree rows, the `--verbose` per-span block, and
6
+ * the usage/cost totals summarized in the trace header.
7
+ */
8
+ import type { LocalTraceSpan } from "#tracing/local-trace-reader.js";
9
+ /** Usage and cost totals aggregated over a trace's `agent.step` spans. */
10
+ export interface LocalTraceSummary {
11
+ readonly cacheReadTokens: number;
12
+ readonly cacheWriteTokens: number;
13
+ /** Total gateway cost in USD; undefined when no span reported cost. */
14
+ readonly costUsd?: number;
15
+ readonly errorCount: number;
16
+ readonly inputTokens: number;
17
+ /** Distinct model ids seen on any span, first-seen order. */
18
+ readonly models: readonly string[];
19
+ readonly outputTokens: number;
20
+ }
21
+ /**
22
+ * Compact metrics for one tree row: token chips (`↑1.4K`/`↓213`), cost
23
+ * (`$0.0031`), and the tool name for `ai.toolCall` spans. Only chips whose
24
+ * attributes the span actually carries — rows without usage stay clean.
25
+ * Raw values: callers sanitize for their output surface.
26
+ */
27
+ export declare function spanMetricChips(span: LocalTraceSpan): string[];
28
+ /**
29
+ * Aggregates usage, cost, models, and errors across one trace. Only
30
+ * `agent.step` spans contribute usage: model spans carry the same counters
31
+ * and a subagent's totals already appear as its own step spans in the same
32
+ * trace, so summing anything else would double-count.
33
+ */
34
+ export declare function summarizeLocalTrace(spans: readonly LocalTraceSpan[]): LocalTraceSummary;
35
+ /** One-line `Tokens` header value: `↑1.2K in · ↓340 out · 1.1K cached`. */
36
+ export declare function formatTokenSummary(summary: LocalTraceSummary): string;
37
+ /** Formats a USD cost: `$1.50` at scale, `$0.0031` for typical spans. */
38
+ export declare function formatCostUsd(costUsd: number): string;
39
+ /**
40
+ * The `--verbose` block for one span: facts (status, timing, ids), every
41
+ * attribute sorted with payloads rendered as transcripts/pretty JSON, then
42
+ * every event with its offset from span start, rendered as `tree(1)`-style
43
+ * entries: each fact, attribute key, and event is an entry with a connector
44
+ * beneath the span's row, so the rails never break. Payload content wraps
45
+ * under its key on a plain margin. `childrenFollow` decides whether the last
46
+ * entry closes the branch — child span rows come after the detail entries.
47
+ */
48
+ export declare function renderSpanDetailTree(span: LocalTraceSpan, options: {
49
+ readonly childrenFollow: boolean;
50
+ readonly margin: string;
51
+ readonly mute: (text: string) => string;
52
+ readonly width: number;
53
+ }): string[];
@@ -0,0 +1 @@
1
+ import{sanitizeForTerminal}from"#cli/ui/output.js";import{formatElapsed}from"#cli/format-elapsed.js";import{formatCompactTokenCount}from"#cli/dev/tui/stream-format.js";import{formatAttributeContent}from"#cli/dev/tui/traces/trace-content.js";function spanMetricChips(e){let t=[],r=numberAttribute(e,`agent.usage.input_tokens`),i=numberAttribute(e,`agent.usage.output_tokens`);r!==void 0&&t.push(`↑${formatCompactTokenCount(r)}`),i!==void 0&&t.push(`↓${formatCompactTokenCount(i)}`);let a=spanCostUsd(e);if(a!==void 0&&t.push(formatCostUsd(a)),e.name===`ai.toolCall`){let n=e.attributes[`gen_ai.tool.name`];typeof n==`string`&&n.length>0&&t.push(n)}return t}function summarizeLocalTrace(e){let t=[],n=0,r=0,i,a=0,o=0,s=0;for(let c of e){let e=stringAttribute(c,`agent.model.id`)??stringAttribute(c,`gen_ai.request.model`);if(e!==void 0&&!t.includes(e)&&t.push(e),c.statusCode===2&&(a+=1),c.name!==`agent.step`)continue;o+=numberAttribute(c,`agent.usage.input_tokens`)??0,s+=numberAttribute(c,`agent.usage.output_tokens`)??0,n+=numberAttribute(c,`gen_ai.usage.cache_read.input_tokens`)??0,r+=numberAttribute(c,`gen_ai.usage.cache_creation.input_tokens`)??0;let l=spanCostUsd(c);l!==void 0&&(i=(i??0)+l)}return{cacheReadTokens:n,cacheWriteTokens:r,costUsd:i,errorCount:a,inputTokens:o,models:t,outputTokens:s}}function formatTokenSummary(e){let t=[`↑${formatCompactTokenCount(e.inputTokens)} in`,`↓${formatCompactTokenCount(e.outputTokens)} out`];return e.cacheReadTokens>0&&t.push(`${formatCompactTokenCount(e.cacheReadTokens)} cached`),e.cacheWriteTokens>0&&t.push(`${formatCompactTokenCount(e.cacheWriteTokens)} cache write`),t.join(` · `)}function formatCostUsd(e){return e>=1?`$${e.toFixed(2)}`:`$${e.toFixed(4)}`}function renderSpanDetailTree(e,t){let n=spanDetailEntries(e,t.width-t.margin.length-3),r=[];return n.forEach((e,r)=>{let i=r===n.length-1&&!t.childrenFollow;emit(e,t.margin,i?`└─ `:`├─ `)}),r;function emit(e,n,i){r.push(t.mute(`${n}${i}${e.head}`));let a=`${n}${i===`└─ `?` `:`│ `}`;for(let n of e.lines)r.push(t.mute(`${a} ${n}`));e.entries.forEach((t,n)=>{emit(t,a,n===e.entries.length-1?`└─ `:`├─ `)})}}function spanDetailEntries(n,i){let dim=e=>e,a=Math.max(40,i),o=[],push=(e,t=[],n=[])=>{o.push({entries:n,head:e,lines:t})},s=n.statusCode===2;push(`status: ${s&&n.statusMessage!==void 0?`ERROR — ${sanitizeForTerminal(n.statusMessage)}`:s?`ERROR`:`ok`}`),push(`duration: ${formatElapsed(durationMs(n.startTimeNs,n.endTimeNs))}`),push(`started: ${new Date(Number(n.startTimeNs/1000000n)).toISOString()}`),push(`span: ${n.spanId}`),n.parentSpanId!==void 0&&push(`parent: ${n.parentSpanId}`),n.scope!==void 0&&push(`scope: ${sanitizeForTerminal(n.scope)}`),n.kind!==void 0&&n.kind!==1&&push(`kind: ${spanKind(n.kind)}`);for(let t of Object.keys(n.attributes).sort()){let i=formatAttributeContent(t,n.attributes[t],dim,a-2),o=sanitizeForTerminal(t);i.length===1?push(`${o}: ${i[0]}`):push(`${o}:`,i)}return n.events.length>0&&push(`events:`,[],n.events.map(i=>{let o=Math.max(0,durationMs(n.startTimeNs,i.timeNs)),s=[];for(let t of Object.keys(i.attributes).sort()){let n=formatAttributeContent(t,i.attributes[t],dim,a-6),o=sanitizeForTerminal(t);n.length===1?s.push(`${o}: ${n[0]}`):s.push(`${o}:`,...n.map(e=>` ${e}`))}return{entries:[],head:`${sanitizeForTerminal(i.name)} +${formatElapsed(o)}`,lines:s}})),o}function spanCostUsd(e){return numberAttribute(e,`gen_ai.usage.gateway_cost`)??numberAttribute(e,`gen_ai.usage.cost`)}function spanKind(e){switch(e){case 2:return`server`;case 3:return`client`;case 4:return`producer`;case 5:return`consumer`;default:return`unknown (${e})`}}function numberAttribute(e,t){let n=e.attributes[t];if(typeof n==`number`)return n;if(typeof n==`string`&&n!==``){let e=Number(n);return Number.isFinite(e)?e:void 0}}function stringAttribute(e,t){let n=e.attributes[t];return typeof n==`string`&&n.length>0?n:void 0}function durationMs(e,t){return Number(t-e)/1e6}export{formatCostUsd,formatTokenSummary,renderSpanDetailTree,spanMetricChips,summarizeLocalTrace};
@@ -11,5 +11,8 @@ export declare function resolveLocalTraces(traces: readonly LocalTrace[], refere
11
11
  export declare function runTraceListCommand(logger: CliTraceLogger, appRoot: string, options?: {
12
12
  readonly json?: boolean;
13
13
  }): Promise<void>;
14
- export declare function runTraceShowCommand(logger: CliTraceLogger, appRoot: string, reference?: string): Promise<void>;
14
+ export declare function runTraceShowCommand(logger: CliTraceLogger, appRoot: string, reference?: string, options?: {
15
+ readonly json?: boolean;
16
+ readonly verbose?: boolean;
17
+ }): Promise<void>;
15
18
  export {};
@@ -1,8 +1,8 @@
1
- import{basename}from"node:path";import{createCliTheme,renderCliSection,sanitizeForTerminal}from"#cli/ui/output.js";import{formatElapsed}from"#cli/format-elapsed.js";import{compareLocalTraceSpans,describeLocalTraceSpan,listLocalTraces}from"#tracing/local-trace-reader.js";const TRACE_DISPLAY_DIRECTORY=`.eve/traces/v1`;function resolveLocalTraces(t,n){let i=n.replaceAll(`\\`,`/`),a=basename(i),o=i===a?[i]:[i,a],s=t.find(e=>o.includes(e.traceId));if(s!==void 0)return[s];let c=t.filter(e=>e.sessionIds.some(e=>o.includes(e)));if(c.length>0)return orderWindows(c);let l=t.filter(e=>o.some(t=>e.traceId.startsWith(t)||e.sessionIds.some(e=>e.startsWith(t))));if(l.length===0)throw Error(`No local trace matches "${sanitizeForTerminal(n)}". Run \`eve traces ls\` to list traces.`);if(l.length===1)return l;if(new Set(l.map(e=>e.sessionId??e.traceId)).size>1)throw ambiguousTraceError(l,n);return orderWindows(l)}function orderWindows(e){return[...e].sort((e,t)=>e.startTimeNs===t.startTimeNs?e.traceId.localeCompare(t.traceId):e.startTimeNs<t.startTimeNs?-1:1)}async function runTraceListCommand(e,t,n={}){let a=await listLocalTraces(t);if(n.json===!0){e.log(JSON.stringify(a.map(e=>({agentName:e.agentName??null,durationMs:durationMs(e.startTimeNs,e.endTimeNs),sessionId:e.sessionId??null,spanCount:e.spans.length,startedAt:toDate(e.startTimeNs).toISOString(),traceId:e.traceId})),null,2));return}if(a.length===0){e.log(`No local traces found under ${TRACE_DISPLAY_DIRECTORY}.`);return}let o=a.map(e=>[e.traceId,sanitizeForTerminal(e.sessionId??`unknown`),sanitizeForTerminal(e.agentName??`unknown`),toDate(e.startTimeNs).toISOString(),formatElapsed(durationMs(e.startTimeNs,e.endTimeNs)),String(e.spans.length)]),l=[`TRACE`,`SESSION`,`AGENT`,`STARTED`,`DURATION`,`SPANS`],u=l.map((e,t)=>Math.max(e.length,...o.map(e=>e[t].length)));e.log([l,...o].map(e=>e.map((e,t)=>e.padEnd(u[t])).join(` `).trimEnd()).join(`
2
- `))}async function runTraceShowCommand(e,r,a){let o=await listLocalTraces(r);if(o.length===0){let t=`No local traces found under ${TRACE_DISPLAY_DIRECTORY}.`;if(a!==void 0)throw Error(t);e.log(t);return}let l=a===void 0?[o[0]]:resolveLocalTraces(o,a),u=createCliTheme();e.log(l.map(e=>[renderCliSection(u,{rows:[{label:`Trace ID`,value:e.traceId},{label:`Session ID`,value:e.sessionId??`unknown`},...e.window===void 0?[]:[{label:`Window`,value:String(e.window)}],{label:`Agent`,value:e.agentName??`unknown`},{label:`Started`,value:toDate(e.startTimeNs).toISOString()},{label:`Duration`,value:formatElapsed(durationMs(e.startTimeNs,e.endTimeNs))},{label:`Spans`,value:String(e.spans.length)}],title:`Trace`}),`${u.accent(`Spans`)}\n${renderSpanTree(e.spans)}`].join(`
1
+ import{basename}from"node:path";import{createCliTheme,renderCliSection,sanitizeForTerminal}from"#cli/ui/output.js";import{formatElapsed}from"#cli/format-elapsed.js";import{formatCostUsd,formatTokenSummary,renderSpanDetailTree,spanMetricChips,summarizeLocalTrace}from"#cli/commands/trace-detail.js";import{compareLocalTraceSpans,describeLocalTraceSpan,listLocalTraces}from"#tracing/local-trace-reader.js";const TRACE_DISPLAY_DIRECTORY=`.eve/traces/v1`;function resolveLocalTraces(t,n){let i=n.replaceAll(`\\`,`/`),a=basename(i),o=i===a?[i]:[i,a],s=t.find(e=>o.includes(e.traceId));if(s!==void 0)return[s];let c=t.filter(e=>e.sessionIds.some(e=>o.includes(e)));if(c.length>0)return orderWindows(c);let l=t.filter(e=>o.some(t=>e.traceId.startsWith(t)||e.sessionIds.some(e=>e.startsWith(t))));if(l.length===0)throw Error(`No local trace matches "${sanitizeForTerminal(n)}". Run \`eve traces ls\` to list traces.`);if(l.length===1)return l;if(new Set(l.map(e=>e.sessionId??e.traceId)).size>1)throw ambiguousTraceError(l,n);return orderWindows(l)}function orderWindows(e){return[...e].sort((e,t)=>e.startTimeNs===t.startTimeNs?e.traceId.localeCompare(t.traceId):e.startTimeNs<t.startTimeNs?-1:1)}async function runTraceListCommand(e,t,n={}){let a=await listLocalTraces(t);if(n.json===!0){e.log(JSON.stringify(a.map(e=>({agentName:e.agentName??null,durationMs:durationMs(e.startTimeNs,e.endTimeNs),sessionId:e.sessionId??null,spanCount:e.spans.length,startedAt:toDate(e.startTimeNs).toISOString(),traceId:e.traceId})),null,2));return}if(a.length===0){e.log(`No local traces found under ${TRACE_DISPLAY_DIRECTORY}.`);return}let o=a.map(e=>[e.traceId,sanitizeForTerminal(e.sessionId??`unknown`),sanitizeForTerminal(e.agentName??`unknown`),toDate(e.startTimeNs).toISOString(),formatElapsed(durationMs(e.startTimeNs,e.endTimeNs)),String(e.spans.length)]),s=[`TRACE`,`SESSION`,`AGENT`,`STARTED`,`DURATION`,`SPANS`],c=s.map((e,t)=>Math.max(e.length,...o.map(e=>e[t].length)));e.log([s,...o].map(e=>e.map((e,t)=>e.padEnd(c[t])).join(` `).trimEnd()).join(`
2
+ `))}async function runTraceShowCommand(e,r,i,a={}){let o=await listLocalTraces(r);if(o.length===0){let t=`No local traces found under ${TRACE_DISPLAY_DIRECTORY}.`;if(i!==void 0)throw Error(t);e.log(t);return}let s=i===void 0?[o[0]]:resolveLocalTraces(o,i);if(a.json===!0){e.log(JSON.stringify(s.map(serializeTraceForJson),null,2));return}let c=createCliTheme();e.log(s.map(e=>[renderCliSection(c,{rows:traceHeaderRows(e),title:`Trace`}),`${c.accent(`Spans`)}\n${renderSpanTree(e.spans,{dim:c.muted,verbose:a.verbose===!0})}`].join(`
3
3
 
4
4
  `)).join(`
5
5
 
6
- `))}function renderSpanTree(e){let t=new Map(e.map(e=>[e.spanId,e])),n=new Map,r=[];for(let i of e)if(i.parentSpanId===void 0||!t.has(i.parentSpanId))r.push(i);else{let e=n.get(i.parentSpanId)??[];e.push(i),n.set(i.parentSpanId,e)}r.sort(compareLocalTraceSpans);for(let e of n.values())e.sort(compareLocalTraceSpans);let i=subtreeExtents(e,n),o=[],s=new Set,render=(e,t,r)=>{if(s.has(e.spanId))return;s.add(e.spanId),o.push(`${t}${r}${spanLabel(e,i.get(e.spanId))}`);let a=n.get(e.spanId)??[];a.forEach((e,n)=>{let i=n===a.length-1;render(e,`${t}${r===``?``:r===`└─ `?` `:`│ `}`,i?`└─ `:`├─ `)})};for(let e of r)render(e,``,``);for(let t of[...e].sort(compareLocalTraceSpans))s.has(t.spanId)||render(t,``,``);return o.join(`
7
- `)}function subtreeExtents(e,t){let n=new Map,r=new Set,visit=e=>{let i=n.get(e.spanId);if(i!==void 0)return i;if(r.has(e.spanId))return{endTimeNs:e.endTimeNs,startTimeNs:e.startTimeNs};r.add(e.spanId);let a=e.endTimeNs,o=e.startTimeNs;for(let n of t.get(e.spanId)??[]){let e=visit(n);e.startTimeNs<o&&(o=e.startTimeNs),e.endTimeNs>a&&(a=e.endTimeNs)}r.delete(e.spanId);let s={endTimeNs:a,startTimeNs:o};return n.set(e.spanId,s),s};for(let t of e)visit(t);return n}function spanLabel(e,t){let n=describeLocalTraceSpan(e).map(sanitizeForTerminal),a=n.length===0?``:` [${n.join(`, `)}]`,s=e.statusCode===2?` ERROR`:``,c=durationMs(e.startTimeNs,e.endTimeNs),l=c===0&&t!==void 0?durationMs(t.startTimeNs,t.endTimeNs):c;return`${sanitizeForTerminal(e.name)}${a} ${formatElapsed(l)}${s}`}function durationMs(e,t){return Number(t-e)/1e6}function toDate(e){return new Date(Number(e/1000000n))}function ambiguousTraceError(e,t){return Error([`"${sanitizeForTerminal(t)}" matches ${e.length} local traces:`,...e.map(e=>` ${e.traceId} ${sanitizeForTerminal(e.sessionId??`unknown session`)}`),`Pass a longer prefix or the full trace/session id.`].join(`
6
+ `))}function traceHeaderRows(e){let t=summarizeLocalTrace(e.spans);return[{label:`Trace ID`,value:e.traceId},{label:`Session ID`,value:e.sessionId??`unknown`},...e.window===void 0?[]:[{label:`Window`,value:String(e.window)}],{label:`Agent`,value:e.agentName??`unknown`},{label:`Started`,value:toDate(e.startTimeNs).toISOString()},{label:`Duration`,value:formatElapsed(durationMs(e.startTimeNs,e.endTimeNs))},{label:`Spans`,value:String(e.spans.length)},...t.models.length===0?[]:[{label:`Models`,value:t.models.join(`, `)}],...t.inputTokens===0&&t.outputTokens===0?[]:[{label:`Tokens`,value:formatTokenSummary(t)}],...t.costUsd===void 0?[]:[{label:`Cost`,value:formatCostUsd(t.costUsd)}],...t.errorCount===0?[]:[{label:`Errors`,value:`${t.errorCount} span${t.errorCount===1?``:`s`}`}]]}function serializeTraceForJson(e){return{agentName:e.agentName??null,durationMs:durationMs(e.startTimeNs,e.endTimeNs),sessionId:e.sessionId??null,sessionIds:e.sessionIds,spanCount:e.spans.length,spans:e.spans.map(e=>({attributes:e.attributes,durationMs:durationMs(e.startTimeNs,e.endTimeNs),endTimeNs:e.endTimeNs.toString(),events:e.events.map(e=>({attributes:e.attributes,name:e.name,timeNs:e.timeNs.toString()})),kind:e.kind??null,name:e.name,parentSpanId:e.parentSpanId??null,scope:e.scope??null,spanId:e.spanId,startTimeNs:e.startTimeNs.toString(),statusCode:e.statusCode,statusMessage:e.statusMessage??null})),startedAt:toDate(e.startTimeNs).toISOString(),traceId:e.traceId,window:e.window??null}}function renderSpanTree(e,t={}){let n=new Map(e.map(e=>[e.spanId,e])),r=new Map,i=[];for(let t of e)if(t.parentSpanId===void 0||!n.has(t.parentSpanId))i.push(t);else{let e=r.get(t.parentSpanId)??[];e.push(t),r.set(t.parentSpanId,e)}i.sort(compareLocalTraceSpans);for(let e of r.values())e.sort(compareLocalTraceSpans);let a=subtreeExtents(e,r),o=terminalWidth(),c=[],l=new Set,d=t.dim??(e=>e),render=(e,n,i)=>{if(l.has(e.spanId))return;l.add(e.spanId);let u=`${n}${i}`;c.push(`${u===``?``:d(u)}${spanLabel(e,a.get(e.spanId))}`);let f=`${n}${i===``?``:i===`└─ `?` `:`│ `}`,p=r.get(e.spanId)??[];if(t.verbose===!0)for(let t of renderSpanDetailTree(e,{childrenFollow:p.length>0,margin:f,mute:d,width:o}))c.push(t);p.forEach((e,t)=>{let n=t===p.length-1;render(e,f,n?`└─ `:`├─ `)})};for(let e of i)render(e,``,``);for(let t of[...e].sort(compareLocalTraceSpans))l.has(t.spanId)||render(t,``,``);return c.join(`
7
+ `)}function subtreeExtents(e,t){let n=new Map,r=new Set,visit=e=>{let i=n.get(e.spanId);if(i!==void 0)return i;if(r.has(e.spanId))return{endTimeNs:e.endTimeNs,startTimeNs:e.startTimeNs};r.add(e.spanId);let a=e.endTimeNs,o=e.startTimeNs;for(let n of t.get(e.spanId)??[]){let e=visit(n);e.startTimeNs<o&&(o=e.startTimeNs),e.endTimeNs>a&&(a=e.endTimeNs)}r.delete(e.spanId);let s={endTimeNs:a,startTimeNs:o};return n.set(e.spanId,s),s};for(let t of e)visit(t);return n}function spanLabel(e,t){let n=describeLocalTraceSpan(e).map(sanitizeForTerminal),a=n.length===0?``:` [${n.join(`, `)}]`,o=spanMetricChips(e).map(sanitizeForTerminal),s=o.length===0?``:` ${o.join(` `)}`,l=e.statusCode===2?` ERROR`:``,u=durationMs(e.startTimeNs,e.endTimeNs),f=u===0&&t!==void 0?durationMs(t.startTimeNs,t.endTimeNs):u;return`${sanitizeForTerminal(e.name)}${a} ${formatElapsed(f)}${s}${l}`}function terminalWidth(){let e=process.stdout.columns;return typeof e==`number`&&e>=40?e:100}function durationMs(e,t){return Number(t-e)/1e6}function toDate(e){return new Date(Number(e/1000000n))}function ambiguousTraceError(e,t){return Error([`"${sanitizeForTerminal(t)}" matches ${e.length} local traces:`,...e.map(e=>` ${e.traceId} ${sanitizeForTerminal(e.sessionId??`unknown session`)}`),`Pass a longer prefix or the full trace/session id.`].join(`
8
8
  `))}export{resolveLocalTraces,runTraceListCommand,runTraceShowCommand};
@@ -1,8 +1,8 @@
1
1
  import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{copyTextToClipboard}from"./clipboard.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{TraceViewerSession}from"./traces/trace-viewer-session.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{AltScreen}from"#cli/ui/alt-screen.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const incompletePasteFlushMs=1e3,STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=[];#h=new Map;#g=new Set;#_=[];#v=new Set;#y=new Map;#b=0;#x=new Map;#S=new FileContentCache;#C=new Set;#w;#T=!1;#E;#D=[];#O;#k=0;#A;#j;#M=``;#N=0;#P=new PromptHistory;#F=!1;#I;#L=!1;#R=Date.now();#z=!1;#B=new TurnClock;#V=EMPTY_LINE;#H=!1;#U={kind:`idle`};#W;#G=STATUS.processing;#K;#q=`eve`;#J=!1;#Y=!1;#X=!1;#Z=!1;#Q=!1;#$=!1;#ee;#te=!0;#ne=0;#re=Date.now();#ie;#ae;#oe;#se=!1;#ce;#le=``;#ue=new StringDecoder(`utf8`);#de;#fe;#pe;#me=!1;#he=!1;#ge;#_e;#ve;#ye;#be;#xe;#Se;#Ce=``;#we=``;#Te;#Ee;#De=0;#Oe;#ke;#Ae;#je;#Me;#Ne;#Pe=new MessageQueue;#Fe;#Ie=!1;#Le;#Re;#ze=!1;#Be;#Ve;#He;#Ue;#We;setupFlow={begin:(e,t)=>this.#Xe(e,t),end:e=>this.#Ze(e?.preserveDiagnostics??!0),readSelect:e=>this.#Qe(e),readEditableSelect:e=>this.#et(e),readProviderPicker:e=>this.#tt(e),readModelEditor:e=>this.#nt(e),readText:e=>this.#rt(e),readAcknowledge:e=>this.#it(e),readChoice:e=>this.#$e(e),setStatus:e=>this.#ft(e),renderLine:(e,t)=>this.#pt(e,t),renderOutput:e=>this.#mt(e),withInheritedStdio:e=>this.#ht(e),withExclusiveTerminal:e=>this.#ht(e),waitForInterrupt:e=>this.#lt(e)};traceViewer={open:e=>this.#_t(e)};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=new AltScreen(this.#t),this.#i=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#a=t?.tools??`auto-collapsed`,this.#o=t?.reasoning??`auto-collapsed`,this.#s=t?.subagents??`auto-collapsed`,this.#c=t?.connectionAuth??`full`,this.#l=t?.assistantResponseStats??`tokensPerSecond`,this.#ve=t?.contextSize,this.#u=t?.captureForeignOutput??this.#t===process.stdout,this.#d=t?.diagnostics,this.#ee=t?.onExitRequest,this.#p=t?.logs??`none`,this.#f=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#q=e.name,this.#w=e,this.#bt();let t=this.#ln().join(`
2
2
  `);if(this.#T){t!==this.#E&&(this.#E=t,this.#Lt({kind:`agent-header`,body:t,live:!1})),this.#in();return}this.#T=!0,this.#E=t,this.#n.flush(this.#ln(),[])}async readPrompt(e){this.#bt(e),this.#It(),this.#zt(),this.#F=!0,this.#L=!0,this.#U={kind:`idle`},this.#G=``,this.#$=!1;let r=this.#Pe.restoreDraft()?.split(`
3
3
  `).map(stripPromptControlCharacters).join(`
4
- `),i=stripPromptControlCharacters(e?.initialDraft??this.#V.text),a=lineOf(r===void 0?i:i.length===0?r:`${r}\n\n${i}`);return this.#V=EMPTY_LINE,this.#P.begin(a.text),this.#Ge(a),this.#I=typeaheadFor(this.#f,a.text),this.#jt(),this.#in(),await new Promise((e,r)=>{this.#W=r;let apply=e=>{a=e,this.#Nt(),this.#Ge(a),this.#I=typeaheadFor(this.#f,e.text,this.#I),this.#in()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#I=void 0,this.#Mt(),this.#St(),r(interruptedError())},suggestions=()=>this.#I!==void 0&&isTypeaheadOpen(this.#I)?this.#I:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ce=r=>{r.type!==`ctrl-c`&&this.#$&&(this.#$=!1,this.#in());let i=applyLineEditorKey(a,r,{multiline:!0});if(i!==void 0){apply(i);return}switch(r.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,-1),this.#in();break}let t=movePromptLine(a,`up`);t===void 0?recall(this.#P.previous(a.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,1),this.#in();break}let t=movePromptLine(a,`down`);t===void 0?recall(this.#P.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#I=dismissTypeahead(e),this.#in());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(a.text)===null?typeaheadCompletion(r).trimEnd():a.text;if(i.trim().length===0)break;this.#I=void 0,this.#P.add(i),this.#F=!1,this.#Mt(),this.#G=STATUS.processing,isPromptControlCommand(i)?this.#Lt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Ft(),this.#Rt(i),this.#Oe=i,this.#B.arm()),this.#Ge(EMPTY_LINE),this.#in(),this.#wt(),e(i);break}case`ctrl-d`:a.text.length===0?(this.#gt(),interrupt()):apply(deleteForward(a));break;case`ctrl-l`:this.#sn();break;case`ctrl-r`:this.#in();break;case`ctrl-c`:if(this.#$){this.#gt(),interrupt();break}this.#$=!0,apply(EMPTY_LINE);break;default:break}},this.#Ct()})}#Ge(e){this.#M=e.text,this.#N=e.cursor}takeQueuedPrompt(){let e=this.#Pe.view().steering,t=this.#Pe.takePrompt();return t!==void 0&&(this.#Re=e?`steer`:`queue`),t}async renderStream(e,t){this.#bt(t),this.#g.clear(),this.#F=!1,this.#U.kind!==`waiting`&&(this.#U={kind:`waiting`,startedAtMs:Date.now()}),this.#G=this.#k>0?STATUS.connectionAuth:STATUS.processing,this.#Bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#d?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#B.armed&&this.#B.arm(),this.#Z=!1,this.#Ie=!1,this.#ze=!1,this.#Be=t?.submittedPrompt,this.#Pe.beginTurn(),this.#Fe=e.cancel,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=Date.now();let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l};this.#Pt(),this.#H=!0,this.#in();let r=new Promise(e=>{this.#pe=e});this.#ce=e=>this.#At(e),this.#Ct();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#Z)break;this.#Kt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Vt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Vt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#pe=void 0,this.#Z&&e.abort?.(),this.#Fe=void 0,this.#wt(),this.#It(),this.#H=!1,this.#U.kind===`waiting`&&(this.#U={kind:`idle`}),this.#G=completedTurnStatus({interrupted:this.#Z,cancelled:this.#Ie,continueSession:t?.continueSession===!0}),this.#$t(i),(this.#Z||this.#Ie)&&this.#Qt(),this.#Gt(),this.#d?.reportStats(),this.#in(),t?.continueSession||this.#St()}}async readToolApproval(e,t){return this.#bt(t),this.#It(),this.#F=!1,this.#U={kind:`idle`},this.#G=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#Z=!1,this.#in(),await new Promise((t,n)=>{this.#W=n,this.#ce=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ft(),this.#G=STATUS.processing,this.#wt(),this.#in(),t({approved:!0})):n===`n`&&(this.#Ft(),this.#G=STATUS.processing,this.#qe(e.toolCallId),this.#wt(),this.#in(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#in();break;case`ctrl-c`:this.#Z=!0,this.#St(),n(interruptedError());break;default:break}},this.#Ct()})}async readInputQuestion(e,t){this.#bt(t),this.#It(),this.#F=!1,this.#L=!1,this.#U={kind:`idle`},this.#Z=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#te},this.#i,t),renderTextSection=()=>{this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#jt():(this.#Mt(),this.#Nt())};s===`overlay`?(s=`overlay`,this.#F=!1,this.#Wt(o),this.#ke=overlayPanel,this.#G=``,syncFreeformCaret(),this.#in()):(s=`text`,this.#ke=void 0,renderTextSection(),this.#F=!0,this.#Ge(l),this.#G=``,this.#jt(),this.#in());let finalize=t=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#F=!1,this.#Ft(),this.#G=STATUS.processing,this.#Mt(),this.#wt(),this.#in();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#F=!1,this.#G=``,this.#Mt(),this.#wt(),this.#in(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#in())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#W=r,u=t,this.#ce=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),s===`text`&&this.#Ge(l),this.#in();return}this.#Z=!0,this.#ke=void 0,this.#Mt(),this.#St(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#in();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#in();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Nt(),this.#in());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#in())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Nt(),this.#Ge(l),this.#in();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Nt(),this.#Ge(l),this.#in());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#Ge(l),this.#in();break}dismiss();break;default:break}},this.#Ct()})}upsertSubagentStep(e){if(this.#d?.recordSubagentDispatch(e.callId),this.#s===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}this.#Ut({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#s!==`full`,live:!e.finalized}),this.#in()}}upsertSubagentTool(e){if(this.#d?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#d?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#s===`hidden`)return;if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Xt({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#s===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ut(r),this.#Ke(e.callId),this.#in()}#Ke(e){applyCohortLiveness(this.#m.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#Wt(subagentToolSectionId(e.callId,e.childCallId)),this.#in()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#s===`hidden`)return;this.#Ht(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#in()}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#in())}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#Wt(t),this.#y.delete(e),this.#in())}#qe(e){let t=this.#h.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#c===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Ut({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#in()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#k)return;let n=this.#k>0;this.#k=t,t>0?(this.#G=STATUS.connectionAuth,this.#in()):n&&(this.#G=STATUS.processing,this.#in())}setVercelStatus(e){this.#A=e,this.#in()}setRemoteConnectionStatus(e){this.#j=e,this.#in()}reset(){this.#m=[],this.#h.clear(),this.#g.clear(),this.#O=void 0,this.#D.length=0,this.#_.length=0,this.#T=!1,this.#E=void 0,this.#Je(),this.#z=!1,this.#Oe=void 0,this.#Ee=void 0,this.#k=0,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=void 0,this.#J&&(this.#n.clearAll(),this.#in())}renderSessionBoundary(){this.#zt(),this.#Je();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#Lt({kind:`session-boundary`,body:n,live:!1}),this.#in()}#Je(){this.#v.clear(),this.#y.clear(),this.#C.clear(),this.#x.clear(),this.#Me=void 0,this.#Ne=void 0,this.#Pe.reset(),this.#Re=void 0,this.#S.clear(),this.#B.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#bt(),this.#Lt({kind:`notice`,body:t,live:!1}),this.#in())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#bt(),this.#Lt({kind:`sandbox`,body:t,live:!1}),this.#in())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ye();return}this.#bt(),this.#je=t,this.#in()}clearSetupWarning(){this.#Ye()}#Ye(){this.#je!==void 0&&(this.#je=void 0,this.#in())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#bt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Lt(r),this.#in()}renderCommandResult(e,t){let n=stripTerminalControls(e);n.trim().length!==0&&(this.#bt(),this.#Lt(t===`success`?{kind:`result`,body:n,live:!1,status:`done`}:t===`error`?{kind:`flow`,title:t,body:n,live:!1}:{kind:`result`,body:n,live:!1}),this.#in())}#Xe(e,t=`spinner`){this.#bt(),this.#F=!1,this.#U={kind:`idle`},this.#G=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ae={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Pt(),this.#in()}#Ze(e){this.#Ve=void 0,this.#dt();let t=this.#Ae;if(t!==void 0){if(this.#Ae=void 0,this.#It(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#Lt({kind:`flow`,title:`info`,body:e.join(`
5
- `),live:!1}),this.#Lt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#in()}}async#Qe(e){let t=this.#at(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#in()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#in();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#in())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#dn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#in(),await this.#ct((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#in();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#in();return;case`update`:o=d.select,s=void 0,this.#in();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#in();return;case`ignore`:return}}).promise}#$e(e){this.#bt();let t=this.#ot();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#in();let r=this.#ct((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#in();return;case`repaint`:this.#in();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#et(e){let t=this.#at(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#te,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#jt():(i=lineOf(``),this.#Mt())};return syncEditableRow(),this.#in(),await this.#ct((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Nt(),this.#in()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#in()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#in();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#in();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Mt()).promise}async#tt(e){let t=this.#at(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#i,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#te,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#jt():this.#Mt()};return syncCaret(),this.#in(),await this.#ct((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#in();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#in();return;case`validate`:{n=o.state,syncCaret(),this.#in();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Nt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Mt()}).promise}async#nt(e){let t=this.#at(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#in(),await this.#ct((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#in();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
4
+ `),i=stripPromptControlCharacters(e?.initialDraft??this.#V.text),a=lineOf(r===void 0?i:i.length===0?r:`${r}\n\n${i}`);return this.#V=EMPTY_LINE,this.#P.begin(a.text),this.#Ge(a),this.#I=typeaheadFor(this.#f,a.text),this.#jt(),this.#in(),await new Promise((e,r)=>{this.#W=r;let apply=e=>{a=e,this.#Nt(),this.#Ge(a),this.#I=typeaheadFor(this.#f,e.text,this.#I),this.#in()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#I=void 0,this.#Mt(),this.#St(),r(interruptedError())},suggestions=()=>this.#I!==void 0&&isTypeaheadOpen(this.#I)?this.#I:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ce=r=>{r.type!==`ctrl-c`&&this.#$&&(this.#$=!1,this.#in());let i=applyLineEditorKey(a,r,{multiline:!0});if(i!==void 0){apply(i);return}switch(r.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,-1),this.#in();break}let t=movePromptLine(a,`up`);t===void 0?recall(this.#P.previous(a.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,1),this.#in();break}let t=movePromptLine(a,`down`);t===void 0?recall(this.#P.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#I=dismissTypeahead(e),this.#in());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(a.text)===null?typeaheadCompletion(r).trimEnd():a.text;if(i.trim().length===0)break;this.#I=void 0,this.#P.add(i),this.#F=!1,this.#Mt(),this.#G=STATUS.processing,isPromptControlCommand(i)?this.#Lt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Ft(),this.#Rt(i),this.#Oe=i,this.#B.arm()),this.#Ge(EMPTY_LINE),this.#in(),this.#wt(),e(i);break}case`ctrl-d`:a.text.length===0?(this.#gt(),interrupt()):apply(deleteForward(a));break;case`ctrl-l`:this.#sn();break;case`ctrl-r`:this.#in();break;case`ctrl-c`:if(this.#$){this.#gt(),interrupt();break}this.#$=!0,apply(EMPTY_LINE);break;default:break}},this.#Ct()})}#Ge(e){this.#M=e.text,this.#N=e.cursor}takeQueuedPrompt(){let e=this.#Pe.view().steering,t=this.#Pe.takePrompt();return t!==void 0&&(this.#Re=e?`steer`:`queue`),t}async renderStream(e,t){this.#bt(t),this.#g.clear(),this.#F=!1,this.#U.kind!==`waiting`&&(this.#U={kind:`waiting`,startedAtMs:Date.now()}),this.#G=this.#k>0?STATUS.connectionAuth:STATUS.processing,this.#Bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#d?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#B.armed&&this.#B.arm(),this.#Z=!1,this.#Ie=!1,this.#ze=!1,this.#Be=t?.submittedPrompt,this.#Pe.beginTurn(),this.#Fe=e.cancel,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=Date.now();let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l};this.#Pt(),this.#H=!0,this.#in();let r=new Promise(e=>{this.#pe=e});this.#ce=e=>this.#At(e),this.#Ct();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#Z)break;this.#Kt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Vt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Vt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#pe=void 0,this.#Z&&e.abort?.(),this.#Fe=void 0,this.#wt(),this.#It(),this.#H=!1,this.#U.kind===`waiting`&&(this.#U={kind:`idle`}),this.#G=completedTurnStatus({interrupted:this.#Z,cancelled:this.#Ie,continueSession:t?.continueSession===!0}),this.#$t(i),(this.#Z||this.#Ie)&&this.#Qt(),this.#Gt(),this.#d?.reportStats(),this.#in(),t?.continueSession||this.#St()}}async readToolApproval(e,t){return this.#bt(t),this.#It(),this.#F=!1,this.#U={kind:`idle`},this.#G=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#Z=!1,this.#in(),await new Promise((t,n)=>{this.#W=n,this.#ce=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ft(),this.#G=STATUS.processing,this.#wt(),this.#in(),t({approved:!0})):n===`n`&&(this.#Ft(),this.#G=STATUS.processing,this.#qe(e.toolCallId),this.#wt(),this.#in(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#in();break;case`ctrl-c`:this.#Z=!0,this.#St(),n(interruptedError());break;default:break}},this.#Ct()})}async readInputQuestion(e,t){this.#bt(t),this.#It(),this.#F=!1,this.#L=!1,this.#U={kind:`idle`},this.#Z=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#te},this.#i,t),renderTextSection=()=>{this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#jt():(this.#Mt(),this.#Nt())};s===`overlay`?(s=`overlay`,this.#F=!1,this.#Wt(o),this.#ke=overlayPanel,this.#G=``,syncFreeformCaret(),this.#in()):(s=`text`,this.#ke=void 0,renderTextSection(),this.#F=!0,this.#Ge(l),this.#G=``,this.#jt(),this.#in());let finalize=t=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#F=!1,this.#Ft(),this.#G=STATUS.processing,this.#Mt(),this.#wt(),this.#in();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#F=!1,this.#G=``,this.#Mt(),this.#wt(),this.#in(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#in())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#W=r,u=t,this.#ce=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),s===`text`&&this.#Ge(l),this.#in();return}this.#Z=!0,this.#ke=void 0,this.#Mt(),this.#St(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#in();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#in();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Nt(),this.#in());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#in())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Nt(),this.#Ge(l),this.#in();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Nt(),this.#Ge(l),this.#in());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#Ge(l),this.#in();break}dismiss();break;default:break}},this.#Ct()})}upsertSubagentStep(e){if(this.#d?.recordSubagentDispatch(e.callId),this.#s===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}this.#Ut({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#s!==`full`,live:!e.finalized}),this.#in()}}upsertSubagentTool(e){if(this.#d?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#d?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#s===`hidden`)return;if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Xt({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#s===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ut(r),this.#Ke(e.callId),this.#in()}#Ke(e){applyCohortLiveness(this.#m.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#Wt(subagentToolSectionId(e.callId,e.childCallId)),this.#in()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#s===`hidden`)return;this.#Ht(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#in()}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#in())}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#Wt(t),this.#y.delete(e),this.#in())}#qe(e){let t=this.#h.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#c===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Ut({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#in()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#k)return;let n=this.#k>0;this.#k=t,t>0?(this.#G=STATUS.connectionAuth,this.#in()):n&&(this.#G=STATUS.processing,this.#in())}setVercelStatus(e){this.#A=e,this.#in()}setRemoteConnectionStatus(e){this.#j=e,this.#in()}reset(){this.#m=[],this.#h.clear(),this.#g.clear(),this.#O=void 0,this.#D.length=0,this.#_.length=0,this.#T=!1,this.#E=void 0,this.#Je(),this.#z=!1,this.#Oe=void 0,this.#Ee=void 0,this.#k=0,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=void 0,this.#J&&(this.#n.clearAll(),this.#in())}renderSessionBoundary(){this.#zt(),this.#Je();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#Lt({kind:`session-boundary`,body:n,live:!1}),this.#in()}#Je(){this.#v.clear(),this.#y.clear(),this.#C.clear(),this.#x.clear(),this.#Me=void 0,this.#Ne=void 0,this.#Pe.reset(),this.#Re=void 0,this.#S.clear(),this.#B.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#bt(),this.#Lt({kind:`notice`,body:t,live:!1}),this.#in())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#bt(),this.#Lt({kind:`sandbox`,body:t,live:!1}),this.#in())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ye();return}this.#bt(),this.#je=t,this.#in()}clearSetupWarning(){this.#Ye()}#Ye(){this.#je!==void 0&&(this.#je=void 0,this.#in())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#bt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Lt(r),this.#in()}renderCommandResult(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#bt();let r=this.#m.at(-1);r?.kind===`command`&&(r.live=!1),this.#Lt(t===`success`?{kind:`result`,body:n,live:!1,status:`done`}:t===`error`?{kind:`flow`,title:t,body:n,live:!1}:{kind:`result`,body:n,live:!1}),this.#in()}#Xe(e,t=`spinner`){this.#bt(),this.#F=!1,this.#U={kind:`idle`},this.#G=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ae={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Pt(),this.#in()}#Ze(e){this.#Ve=void 0,this.#dt();let t=this.#Ae;if(t===void 0)return;this.#Ae=void 0,this.#It();let n=this.#m.at(-1);if(n?.kind===`command`&&(n.live=!0),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#Lt({kind:`flow`,title:`info`,body:e.join(`
5
+ `),live:!1}),this.#Lt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#in()}async#Qe(e){let t=this.#at(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#in()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#in();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#in())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#dn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#in(),await this.#ct((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#in();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#in();return;case`update`:o=d.select,s=void 0,this.#in();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#in();return;case`ignore`:return}}).promise}#$e(e){this.#bt();let t=this.#ot();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#in();let r=this.#ct((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#in();return;case`repaint`:this.#in();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#et(e){let t=this.#at(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#te,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#jt():(i=lineOf(``),this.#Mt())};return syncEditableRow(),this.#in(),await this.#ct((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Nt(),this.#in()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#in()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#in();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#in();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Mt()).promise}async#tt(e){let t=this.#at(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#i,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#te,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#jt():this.#Mt()};return syncCaret(),this.#in(),await this.#ct((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#in();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#in();return;case`validate`:{n=o.state,syncCaret(),this.#in();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Nt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Mt()}).promise}async#nt(e){let t=this.#at(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#in(),await this.#ct((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#in();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
6
6
  `,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#rt(e){let t=this.#at(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder===void 0?e.defaultValue!==void 0&&(i.placeholder=e.defaultValue):i.placeholder=e.placeholder,e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#i,t,this.#te)},this.#jt(),this.#in(),await this.#ct((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Nt(),this.#in()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#in();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#in();return}i(t);return}default:return}},()=>this.#Mt()).promise}async#it(e){let t=this.#at();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#i,t),this.#in(),await this.#ct((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#in();return;default:return}}).promise}#at(){return this.#bt(),this.#F=!1,this.#U={kind:`idle`},this.#G=``,this.#ot()}#ot(){return this.#Ae===void 0&&(this.#Ae={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ae}#st(){this.#Ae?.implicit===!0?this.#Ae=void 0:this.#Ae!==void 0&&(this.#Ae.question=void 0,this.#Ae.hideLinesWhileQuestion=!1),this.#ce=void 0,this.#wt(),this.#Ae!==void 0&&this.#ut(),this.#in()}#ct(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#st(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#st(),i(e))};return this.#kt(),this.#ce=t=>{t.type===`ctrl-c`&&this.#gt(),e(t,settle,reject)},this.#Ct(),{promise:a,settle}}#lt(e){let t,n=new Promise(e=>{t=e});return this.#Ve=t,this.#ut(e?.interruptible??!0),{promise:n,dispose:()=>{this.#Ve===t&&(this.#Ve=void 0,this.#dt())}}}#ut(e=!0){if(this.#Ve===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#gt();let e=this.#Ve;this.#Ve=void 0,this.#dt(),e?.();return}t.type===`ctrl-r`&&this.#in()};this.#He=consumer,this.#kt(),this.#ce=consumer,this.#Ct()}#dt(){this.#He!==void 0&&(this.#ce===this.#He&&this.#wt(),this.#He=void 0)}#ft(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e),startedAtMs:Date.now()}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis),startedAtMs:Date.now()};if(this.#Ae!==void 0){this.#Ae.status=t,t===void 0&&(this.#Ae.preview=void 0),this.#in();return}if(!(this.#F||this.#H)){if(t===void 0){this.#U={kind:`idle`},this.#K=void 0,this.#It(),this.#in();return}this.#bt(),this.#Ft(),this.#K=t.text,this.#in()}}#pt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ae;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#in();return}this.#bt(),this.#Lt({kind:`flow`,title:t,body:n,live:!1}),this.#in()}#mt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ae;if(n===void 0){this.#pt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#in()}async#ht(e){this.#le=``,this.#kt(),this.#Ve=void 0,this.#dt(),this.#wt(),this.#It(),this.#n.clear(),this.#n.showCursor(),this.#En(),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#le=``,this.#kt(),this.#n.hideCursor(),this.#Tn(),this.#Ae!==void 0&&(this.#Pt(),this.#ut()),this.#n.reset(),this.#in()}}setSessionId(e){this.#Le=e}shutdown(){if(this.#St(),this.#Y&&!this.#X){this.#X=!0;let e=this.#Le===void 0?``:` ${this.#i.glyph.dot} session ${this.#Le}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}requestInterrupt(){this.#Z=!0,this.#Ae!==void 0&&this.#ce?.({type:`ctrl-c`}),this.#pe?.(),this.#St()}exitRequested(){return this.#Q}#gt(){this.#Q=!0,this.#ee?.()}async#_t(e){if(this.#Ue!==void 0||!this.#J)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Cn(),height:this.#wn()}),paint:e=>this.#r.paint(e,this.#wn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#We});this.#Ue=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#yt=e,this.#ce=e=>{t.handleKey(e)===`close`&&this.#vt()},this.#Ct(),t.start()})}#vt(){let e=this.#Ue;if(e===void 0)return;this.#Ue=void 0,e.dispose(),this.#wt(),this.#r.exit(),this.#n.hideCursor(),this.#in(),this.#n.showCursor();let t=this.#yt;this.#yt=void 0,t?.()}#yt;#bt(e){this.#q=e?.title??this.#q,e?.contextSize!==void 0&&(this.#ve=e.contextSize),!this.#J&&(this.#J=!0,this.#Y=!0,this.#n.reset(),this.#n.hideCursor(),this.#Tn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#fe=()=>this.#in(),this.#t.on(`resize`,this.#fe),process.on(`exit`,this.#xt))}#xt=()=>{this.#J&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#St(){this.#vt();let e=this.#W;if(this.#W=void 0,e?.(interruptedError()),this.#wt(),this.#Mt(),this.#It(),this.#oe!==void 0&&(clearTimeout(this.#oe),this.#oe=void 0),this.#se=!1,this.#J){this.#Pn();for(let e of this.#m)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#in(),this.#n.clear(),this.#n.showCursor(),this.#En(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#fe&&=(this.#t.off(`resize`,this.#fe),void 0),process.off(`exit`,this.#xt),this.#J=!1}}#Ct(){this.#e.off(`data`,this.#Tt),this.#e.on(`data`,this.#Tt),this.#le.length>0&&queueMicrotask(()=>{this.#ce!==void 0&&this.#le.length>0&&(this.#Dt(),this.#Et())})}#wt(){this.#e.off(`data`,this.#Tt),this.#kt(),this.#ce=void 0}#Tt=e=>{this.#kt(),this.#le+=this.#ue.write(e),this.#Dt(),this.#Et()};#Et(){if(this.#le===`\x1B`){this.#de=setTimeout(()=>{this.#le===`\x1B`&&(this.#le=``,this.#ce?.({type:`escape`}))},30),this.#de.unref?.();return}if(isIncompletePaste(this.#le)){let e=this.#le;this.#de=setTimeout(()=>{if(this.#le!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#le=``,t.length>0&&this.#ce?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#de.unref?.();return}if(isIncompleteOsc(this.#le)){let e=this.#le;this.#de=setTimeout(()=>{this.#le===e&&(this.#le=``)},incompletePasteFlushMs),this.#de.unref?.()}}#Dt(){for(;this.#le.length>0;){let e=nextKey(this.#le);if(e.incomplete)return;if(this.#le=this.#le.slice(e.consumed),!(e.key===void 0||e.key.type===`ignore`)){if(e.key.type===`osc`){this.#Ot(e.key.value);continue}this.#ce?.(e.key)}}}#Ot(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#We=t,this.#Ue?.setTerminalBackground(t))}#kt(){this.#de&&=(clearTimeout(this.#de),void 0)}#At(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#in();break;case`enter`:{let e=this.#V.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Fe!==void 0){this.#V=EMPTY_LINE,this.#Pe.requestCancellation(),this.#ze=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Fe(),this.#in();break}this.#Pe.enqueue(e)&&(this.#V=EMPTY_LINE),this.#in();break}case`ctrl-c`:case`escape`:if(this.#Pe.idle&&this.#Fe===void 0)break;this.#Pe.handleEscape(),this.#ze=!0,this.#Fe?.(),this.#in();break;default:{let t=applyLineEditorKey(this.#V,e,{multiline:!0});t!==void 0&&(this.#V=t,this.#in());break}}}#jt(){this.#Mt(),this.#Nt(),this.#ie=setInterval(()=>{this.#te=!this.#te,this.#in()},500),this.#ie.unref?.()}#Mt(){this.#ie&&=(clearInterval(this.#ie),void 0),this.#te=!0}#Nt(){this.#te=!0}#Pt(){this.#It(),this.#ae=setInterval(()=>{this.#ne+=1,this.#in()},90),this.#ae.unref?.()}#Ft(){let e=Date.now();this.#re=e,this.#U={kind:`waiting`,startedAtMs:e},this.#Pt()}#It(){this.#ae&&=(clearInterval(this.#ae),void 0)}#Lt(e){e.id!==this.#Ee?.id&&this.#Pn(),e.updateSeq=++this.#b,this.#m.push(e),e.id&&this.#h.set(e.id,e)}#Rt(e){this.#z=!0,this.#Lt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#in()}#zt(){let e=this.#B.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#gn(e.elapsedMs)}`,n=this.#_e??0;if(this.#ve!==void 0&&this.#ve>0&&n>0){let e=Math.round(n/this.#ve*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#Lt({kind:`turn-stats`,body:t,live:!1})}#Bt(e){if(e==null)return;let t=this.#Re;if(this.#Re=void 0,this.#Oe===e){this.#Oe=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#Lt(n)}#Vt(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#d?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#d===void 0?a:`details: ${this.#d.displayPath}`),this.#Lt(c),this.#in()}#Ht(e,t){if(this.#C.has(e))return;this.#C.add(e);let n=stripTerminalControls(t),r=this.#x.get(n)??[];if(r.push(e),this.#x.set(n,r),r.length===2){let e=this.#h.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#Lt(i)}#Ut(e){if(e.id&&this.#g.has(e.id))return;let t=e.id?this.#h.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#b;return}this.#Lt(e)}#Wt(e){this.#m=this.#m.filter(t=>t.id!==e),this.#h.delete(e)}#Gt(){for(let e of this.#m)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Kt(e,t,n){switch(e.type){case`step-finish`:this.#d?.recordStepUsage(e.usage),e.usage!==void 0&&this.#B.addUsage(e.usage),this.#$t(n),this.#rn(e.usage),this.#in();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#qt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,r),this.#qt(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#Jt(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#Jt(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#Yt({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#d?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#Yt({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#Yt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#nn(e.toolCallId,n);if(r===void 0)break;this.#Yt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#nn(e.toolCallId,n);if(this.#d?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#Yt({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#nn(e.toolCallId,n);if(r===void 0)break;this.#Yt({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Vt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:this.#Ie=!0,!this.#ze&&this.#Be!==void 0&&this.#V.text.length===0&&(this.#V=lineOf(this.#Be),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#rn(e.usage),this.#in();break}}#qt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Ut({id:e,kind:`assistant`,body:r,live:n}),this.#in())}#Jt(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ut({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#in())}#Yt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#v.has(e.toolCallId)||this.#en(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#y.set(e.toolCallId,r);let i=this.#Xt(e);this.#Ut(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#tn(n),this.#in()}#Xt(e){e.output!==void 0&&this.#S.observeRead(e.output);let t={};this.#Zt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#S.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#Zt(e){let t=this.#w?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#Qt(){for(let e of this.#m)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#$t(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#y.get(t)??toolSectionId(t);this.#Wt(r),this.#y.delete(t)}}#en(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#Ne!==e&&(this.#Ne=e,this.#Lt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Cn(),this.#i).join(`
7
7
  `),live:!1})),this.#Me=void 0}else this.#Me=t.length>0?t:void 0,this.#Ne=void 0;return this.#in(),!0}#tn(e){let t=[];for(let n of e.tools.values()){if(this.#v.has(n.toolCallId))continue;let e=this.#y.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#h.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#nn(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#y.get(e)??toolSectionId(e),i=this.#h.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#rn(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#ge=(t??0)+(n??0)),this.#_e=t??this.#_e,this.#ye=n??this.#ye,this.#ye!=null&&this.#xe!==void 0){let e=(Date.now()-this.#xe)/1e3;e>0&&(this.#be=this.#ye/e)}}#in(){if(this.#J){if(this.#me){this.#he=!0;return}this.#me=!0;try{do this.#he=!1,this.#an();while(this.#he)}finally{this.#me=!1}}}#an(){if(!this.#J)return;if(this.#Ue!==void 0){this.#Ue.repaint();return}let e=this.#Cn(),t=this.#mn(e),n=Math.max(1,this.#wn()-t.length),r=[],i=this.#O,a=groupToolBlocksForDisplay(this.#m),o=0;for(;o<a.length&&a[o].display.live===!1;)o+=1;if(o>0){let e=new Set(a.slice(0,o).flatMap(e=>e.members));for(let t=this.#m.length-1;t>=0;--t)e.has(this.#m[t])&&this.#m.splice(t,1)}for(let t of a.slice(0,o)){for(let e of t.members)this.#_.push(e),e.id&&(this.#g.add(e.id),this.#h.delete(e.id));if(this.#In(t.display))continue;let n=this.#un(t.display,e,i);i=previousBlockOf(t.display),this.#O=i,r.push(...n),this.#D.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#In(t))continue;let n=this.#un(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)s.push({block:t,row:n[e]})}let c=[...clipLiveRows(s.map(e=>e.row),n,e,this.#i),...t];r.length>0?this.#n.flush(r,c):this.#n.update(c)}#on(){if(!this.#J)return;let e=this.#Cn(),t=this.#mn(e),n=Math.max(1,this.#wn()-t.length),r=this.#O,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#m)){if(this.#In(t))continue;let n=this.#un(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#i),...t];this.#n.clearAll(),this.#n.flush([...this.#ln(),...this.#D],a)}logDisplayMode(){return this.#p}setLogDisplayMode(e){e!==this.#p&&(this.#p=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#cn(),this.#J&&this.#on())}flushDelayedDevBuildErrors(){let e=this.#Te;e!==void 0&&(this.#Te=void 0,this.#Lt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#in())}#sn(){this.#se=!0,this.#oe!==void 0&&clearTimeout(this.#oe),this.#oe=setTimeout(()=>{this.#se=!1,this.#oe=void 0,this.#in()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#p)),this.#in()}#cn(){let e=this.#Cn();this.#D.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#_,{logCoalescing:`runs`})){if(this.#In(n))continue;let r=this.#un(n,e,t);t=previousBlockOf(n),this.#D.push(...r)}this.#O=t}#ln(){let e=this.#w;if(e===void 0)return[];let t={name:e.name,theme:this.#i,width:this.#Cn()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#un(e,t,n){let r={activityPulse:this.#fn(this.#re,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#i,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#dn(){return this.#i.spinner[this.#ne%this.#i.spinner.length]??``}#fn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#pn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#dn(),color:`yellow`}:{glyph:this.#fn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#mn(e){let n=this.#i.colors,r=[``];if(this.#ke!==void 0)return r.push(...this.#ke(e),``),this.#bn(r,e),r;let a=this.#Ae;if(a!==void 0){let t=this.#pn(a,a.status),n;if(a.status!==void 0){let{startedAtMs:e,...r}=a.status,i=Date.now()-e,o=i>=5e3?` ${formatTurnDuration(i)}`:``;n={...r,text:`${r.text}${o}`,indicator:t}}let i;if(a.question!==void 0){let t=a.question(e);i={kind:`question`,rows:t},n!==void 0&&(i={kind:`question`,rows:t,status:n})}else n===void 0?i=a.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:a.preview,indicator:t}:(i={kind:`status`,status:n},a.preview!==void 0&&(i={kind:`status`,status:n,preview:a.preview}));let o={title:a.title,lines:a.hideLinesWhileQuestion===!0?[]:a.lines,content:i};return r.push(...renderFlowPanel(o,this.#i,e)),this.#xn(r,e),r}this.#je!==void 0&&r.push(...renderAttentionRows(this.#je,e,this.#i),``),this.#Me!==void 0&&r.push(...renderTodoPanelRows({items:this.#Me,width:e,theme:this.#i,working:this.#H||this.#U.kind===`waiting`,pulse:this.#fn(this.#re,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let o=renderMessageQueueRows({view:this.#Pe.view(),width:e,theme:this.#i,working:this.#H});if(o.length>0&&r.push(...o,``),this.#F){let i=this.#I===void 0?void 0:inlineCommandHint(this.#I);i===void 0&&this.#I!==void 0&&isTypeaheadOpen(this.#I)&&r.push(...renderCommandSuggestions(this.#I,this.#i,e)),this.#$&&r.push(clip(n.dim(`Press Ctrl+C again to exit`),e),``);let a=isPromptControlCommand(this.#M),o=i?n.dim(` ${i}`):``,s=[];this.#bn(s,e);let u=Math.max(1,this.#wn()-1-r.length-1-s.length),f={text:this.#M,cursor:this.#N,width:e,theme:this.#i,caretVisible:this.#te,isCommand:a,ghost:o,maxRows:u};return this.#L&&this.#M.length===0&&(f.placeholder=this.#z?``:promptPlaceholder(Date.now()-this.#R)),r.push(...promptInputRows(f)),r.push(...s),r}let s=this.#U.kind===`waiting`&&this.#K===void 0;if(this.#H||s){r.push(this.#hn(e)),this.#vn(r,e);let t=[];return this.#bn(t,e),!this.#H&&t.length>0&&r.push(``),r.push(...t),r}if(this.#V.text.length>0)return this.#yn(r,e,{inert:!1}),this.#bn(r,e),r;let u=this.#K??(this.#G.length>0?this.#G:`Ready`),f=this.#Sn(),p=n.dim(this.#i.glyph.dot),m=f?`${p} ${u} ${n.dim(this.#i.glyph.dot)} ${f}`:`${p} ${u}`;return r.push(clip(m,e)),this.#bn(r,e),r}#hn(e){let t=this.#i.colors,n=this.#fn(this.#re,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#U,i=this.#B.startedAtMs??this.#xe??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#gn(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#gn(e){return`${formatTurnDuration(e)}${this.#_n()}`}#_n(){let{inputTokens:e,outputTokens:t}=this.#B.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#vn(e,t){this.#H&&this.#yn(e,t,{inert:!0})}#yn(e,t,n){e.push(``);let r={text:this.#V.text,cursor:this.#V.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#V.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#bn(e,t){let n=this.#j===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#se&&(i.logLevel=this.#p);let a=this.#w?.serverUrl;if(a!==void 0&&this.#j===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#w?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#A!==void 0&&(i.vercel=this.#A),this.#j!==void 0&&(i.remote=this.#j);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#xn(e,t){if(this.#j===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#j,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Sn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#ge,outputTokens:this.#ye,tokensPerSecond:this.#be},this.#l);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Cn(){return Math.max(20,this.#t.columns||80)}#wn(){return Math.max(8,this.#t.rows||24)}#Tn(){if(this.#Se!==void 0||!this.#u)return;this.#Ce=``,this.#we=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#On(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#d?.subscribeLogRecords(e=>this.#Dn(e)),this.#Se=()=>{this.#d?.unsubscribeLogRecords(),e(),t()}}#En(){let e=this.#Se;e!==void 0&&(this.#Se=void 0,e(),this.#Ce.length>0&&(this.#d?.append({source:`stdout`,detail:this.#Ce}),this.#Fn(`stdout`)&&process.stdout.write(`${this.#Ce}\n`),this.#Ce=``),this.#we.length>0&&(this.#d?.append({source:`stderr`,detail:this.#we}),this.#Fn(`stderr`)&&process.stderr.write(`${this.#we}\n`),this.#we=``))}#Dn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#An(`[eve:${e.namespace}] ${e.message}${t}`),this.#in()}#On(e,t){let n=(e===`stdout`?this.#Ce:this.#we)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Ce=``,this.#d?.append({source:e,detail:n.trimEnd()}),this.#kn(n.trimEnd()),this.#in();return}let r=n.lastIndexOf(`
8
8
  `),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Ce=i:this.#we=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#d?.append({source:e,detail:a}),e===`stdout`?this.#kn(a):this.#An(a),this.#in())}#kn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
@@ -9,14 +9,14 @@
9
9
  * Every returned line fits the given width; wrapped continuations keep a
10
10
  * two-space hanging indent so they read as part of their block.
11
11
  */
12
- import type { Theme } from "../theme.js";
13
12
  /**
14
13
  * Formats one attribute's value into display lines, each at most `width`
15
14
  * columns. A single scalar stays on one line so the panel can keep it beside
16
15
  * its key; multi-line content comes back unindented for the caller to nest
17
- * under the key.
16
+ * under the key. `dim` styles de-emphasized parts (role prefixes, the
17
+ * truncation notice), so callers pass their surface's dim style.
18
18
  */
19
- export declare function formatAttributeContent(key: string, value: unknown, theme: Theme, width: number): string[];
19
+ export declare function formatAttributeContent(key: string, value: unknown, dim: (text: string) => string, width: number): string[];
20
20
  /**
21
21
  * Wraps text to `width`, splitting on embedded newlines so a multi-line payload
22
22
  * keeps its shape, and stripping control bytes the frame must not carry.
@@ -1,2 +1,2 @@
1
- import{stripTerminalControls,visibleLength,wrapVisibleLine}from"#cli/ui/terminal-text.js";function formatAttributeContent(t,n,r,i){if(typeof n!=`string`)return Array.isArray(n)?prettyJson(n,i):[stripTerminalControls(shortJson(n))];if(t===`ai.prompt.messages`){let e=messageTranscript(n,r,i);if(e!==void 0)return e}return formatPayloadContent(n,i)}function wrapPlainText(t,r){return splitEmbeddedNewlines([stripTerminalControls(t)]).flatMap(e=>wrapVisibleLine(e,r))}function formatPayloadContent(e,t){let n=parseJson(e);return n!==void 0&&(Array.isArray(n)||isRecord(n))?prettyJson(n,t):wrapPlainText(e,t)}function messageTranscript(t,n,r){let i=parseJson(t);if(!Array.isArray(i))return;let a=0,o=[];for(let e of i){if(isRecord(e)&&isRecord(e[`eve.truncated`])){let t=e[`eve.truncated`].omittedMessages;if(typeof t==`number`){a+=t;continue}}o.push(e)}if(!o.every(e=>typeof e.role==`string`))return;let{colors:s}=n,c=[];a>0&&c.push(s.dim(`… ${a} earlier message${a===1?``:`s`} omitted (long context)`));for(let t of o){let n=messageContentParts(t.content),i=t.role===`tool`?toolRoleLabel(n):stripTerminalControls(String(t.role));n.forEach((e,t)=>{let n=t===0?`${s.dim(`${i}:`)} `:` `;c.push(...wrapPrefixed(n,e.text,e.dim?s.dim:void 0,r))})}return c}function toolRoleLabel(e){let t=e.find(e=>e.name!==void 0);return t?.name===void 0?`tool`:`tool ${t.name}`}function messageContentParts(t){if(typeof t==`string`)return[{text:stripTerminalControls(t)}];if(!Array.isArray(t))return[{text:shortJson(t)}];let n=[];for(let r of t){if(!isRecord(r)||typeof r.type!=`string`){n.push({text:shortJson(r)});continue}if(r.type===`text`&&typeof r.text==`string`)n.push({text:stripTerminalControls(r.text)});else if(r.type===`reasoning`){let t=typeof r.text==`string`?stripTerminalControls(r.text.trim()):``;n.push({dim:!0,text:t.length>0?`⟨reasoning⟩ ${t}`:`⟨reasoning⟩`})}else if(r.type===`tool-call`&&typeof r.toolName==`string`){let t=stripTerminalControls(r.toolName);n.push({name:t,text:`→ ${t}(${shortJson(r.input)})`})}else if(r.type===`tool-result`&&typeof r.toolName==`string`){let t=stripTerminalControls(r.toolName);n.push({name:t,text:toolOutputText(r.output)})}else n.push({text:shortJson(r)})}return n.length===0&&n.push({text:shortJson(t)}),n}function toolOutputText(t){return isRecord(t)&&typeof t.type==`string`&&`value`in t?t.type===`text`&&typeof t.value==`string`?stripTerminalControls(t.value):shortJson(t.value):shortJson(t)}function prettyJson(e,t){return JSON.stringify(e,null,2).split(`
1
+ import{stripTerminalControls,visibleLength,wrapVisibleLine}from"#cli/ui/terminal-text.js";function formatAttributeContent(t,n,r,i){if(typeof n!=`string`)return Array.isArray(n)?prettyJson(n,i):[stripTerminalControls(shortJson(n))];if(t===`ai.prompt.messages`){let e=messageTranscript(n,r,i);if(e!==void 0)return e}return formatPayloadContent(n,i)}function wrapPlainText(t,r){return splitEmbeddedNewlines([stripTerminalControls(t)]).flatMap(e=>wrapVisibleLine(e,r))}function formatPayloadContent(e,t){let n=parseJson(e);return n!==void 0&&(Array.isArray(n)||isRecord(n))?prettyJson(n,t):wrapPlainText(e,t)}function messageTranscript(t,n,r){let i=parseJson(t);if(!Array.isArray(i))return;let a=0,o=[];for(let e of i){if(isRecord(e)&&isRecord(e[`eve.truncated`])){let t=e[`eve.truncated`].omittedMessages;if(typeof t==`number`){a+=t;continue}}o.push(e)}if(!o.every(e=>typeof e.role==`string`))return;let s=[];a>0&&s.push(n(`… ${a} earlier message${a===1?``:`s`} omitted (long context)`));for(let t of o){let i=messageContentParts(t.content),a=t.role===`tool`?toolRoleLabel(i):stripTerminalControls(String(t.role));i.forEach((e,t)=>{let i=t===0?`${n(`${a}:`)} `:` `;s.push(...wrapPrefixed(i,e.text,e.dim?n:void 0,r))})}return s}function toolRoleLabel(e){let t=e.find(e=>e.name!==void 0);return t?.name===void 0?`tool`:`tool ${t.name}`}function messageContentParts(t){if(typeof t==`string`)return[{text:stripTerminalControls(t)}];if(!Array.isArray(t))return[{text:shortJson(t)}];let n=[];for(let r of t){if(!isRecord(r)||typeof r.type!=`string`){n.push({text:shortJson(r)});continue}if(r.type===`text`&&typeof r.text==`string`)n.push({text:stripTerminalControls(r.text)});else if(r.type===`reasoning`){let t=typeof r.text==`string`?stripTerminalControls(r.text.trim()):``;n.push({dim:!0,text:t.length>0?`⟨reasoning⟩ ${t}`:`⟨reasoning⟩`})}else if(r.type===`tool-call`&&typeof r.toolName==`string`){let t=stripTerminalControls(r.toolName);n.push({name:t,text:`→ ${t}(${shortJson(r.input)})`})}else if(r.type===`tool-result`&&typeof r.toolName==`string`){let t=stripTerminalControls(r.toolName);n.push({name:t,text:toolOutputText(r.output)})}else n.push({text:shortJson(r)})}return n.length===0&&n.push({text:shortJson(t)}),n}function toolOutputText(t){return isRecord(t)&&typeof t.type==`string`&&`value`in t?t.type===`text`&&typeof t.value==`string`?stripTerminalControls(t.value):shortJson(t.value):shortJson(t)}function prettyJson(e,t){return JSON.stringify(e,null,2).split(`
2
2
  `).flatMap(e=>wrapHanging(e,t,t))}function wrapPrefixed(e,n,r,i){let a=r??(e=>e),o=[];return splitEmbeddedNewlines([n]).forEach((n,r)=>{let s=r===0?e:` `,c=r===0?visibleLength(e):2;wrapHanging(n,i,Math.max(8,i-c)).forEach((e,t)=>{o.push(t===0?`${s}${a(e)}`:` ${a(e)}`)})}),o}function wrapHanging(e,r,i){let a=wrapVisibleLine(e,Math.max(8,r-2));if(visibleLength(a[0]??``)<=i)return a;let[o,...s]=wrapVisibleLine(a[0]??``,Math.max(8,i));return[o??``,...s,...a.slice(1)]}function splitEmbeddedNewlines(e){let t=e.flatMap(e=>e.split(/\r\n|\r|\n/));for(;t.length>1&&t[t.length-1]===``;)t.pop();return t}function shortJson(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function parseJson(e){try{return JSON.parse(e)}catch{return}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{formatAttributeContent,formatPayloadContent,prettyJson,splitEmbeddedNewlines,wrapPlainText};
@@ -1,2 +1,2 @@
1
- import{formatAttributeContent}from"./trace-content.js";import{renderConversationItem}from"./trace-conversation.js";import{orderedTextSelection,selectedTraceViewerSpan}from"./trace-viewer-state.js";import{formatElapsed}from"#cli/format-elapsed.js";import{clipVisible,sliceVisible,stripAnsi,stripTerminalControls,visibleLength,wrapVisibleLine}from"#cli/ui/terminal-text.js";import{describeLocalTraceSpan}from"#tracing/local-trace-reader.js";function renderTraceViewer(e,t){let{width:n,height:r,theme:i}=t,a=chromeStyles(i,t.surfaces),o=Math.max(1,r-3-3),s=e.panelOpen?panelWidthFor(n):0,c=Math.max(20,n-(s===0?0:s+1)),l=panelDetailLines(e,s,i,t.surfaces),u=o,d=[];if(d.push(...renderHeader(e,t)),e.traces.length===0)d.push(...renderEmptyState(t,i,o));else if(e.trace===void 0)d.push(...center(o,a.muted(`Loading trace…`)));else{let r=renderConversation(e,t,c,o);for(let t=0;t<o;t+=1){let i=r[t]??``;if(s===0){d.push(i);continue}let a=l[e.panelScroll+t]??``;e.textSelection!==void 0&&e.textSelection.region===`panel`&&(a=highlightSelection(a,e.panelScroll+t,e.textSelection,s)),d.push(joinPanels(i,c,a,n))}}return d.push(...renderFooter(e,n,i,t.surfaces)),t.toast!==void 0&&overlayToast(d,t.toast,n,i,t.surfaces),{rows:d,panelTotalRows:l.length,timelineViewportRows:o,panelViewportRows:u,contentWidth:c}}function chromeStyles(e,t){let n=e.color?t:void 0;return{muted:n?.mutedText??e.colors.dim,primary:n?.primaryText??(e=>e)}}function overlayToast(e,t,n,r,i){let a=` ${stripTerminalControls(t)} `,o=visibleLength(a),s=r.unicode?`▌`:r.glyph.rule,u=r.color?i:void 0,d=u===void 0?``:u.body,f=u?.primaryText??r.colors.white,p=r.color?`\x1B[0m`:``,m=[`${d}${f(s)}${` `.repeat(o)}${p}`,`${d}${f(s)}${f(a)}${p}`,`${d}${f(s)}${` `.repeat(o)}${p}`];for(let[t,r]of m.entries()){let i=2+t;if(i>=e.length)break;e[i]=overlayRight(e[i],r,n,1)}}function overlayRight(e,t,n,r){let i=Math.max(0,n-r-visibleLength(t)),a=visibleLength(e);return`${sliceVisible(a<i?e+` `.repeat(i-a):e,i)}\x1b[0m${t}`}const CONVERSATION_CONTENT_KEYS=new Set([`ai.prompt.messages`,`ai.prompt.system`,`ai.response.reasoning`,`ai.response.text`,`ai.response.tool_calls`,`ai.response.tool_results`,`gen_ai.tool.call.arguments`,`gen_ai.tool.call.result`]);function renderSpanDetail(t,n,r,o){let{colors:s}=r,{muted:l,primary:f}=chromeStyles(r,o?.surfaces),p=[],m=stripTerminalControls(t.name);p.push(...wrapVisibleLine(s.bold(f(m)),n));let h=describeLocalTraceSpan(t).map(stripTerminalControls);h.length>0&&p.push(l(h.join(`, `))),p.push(``);let fact=(e,t)=>`${l(e.padEnd(10))}${t}`,g=t.statusCode===2;p.push(fact(`status`,g?s.red(`ERROR`):s.green(`ok`))),p.push(fact(`duration`,formatElapsed(durationMs(t.startTimeNs,t.endTimeNs)))),p.push(fact(`started`,clockTime(t.startTimeNs))),p.push(fact(`span`,t.spanId)),t.parentSpanId!==void 0&&p.push(fact(`parent`,t.parentSpanId)),t.scope!==void 0&&p.push(fact(`scope`,stripTerminalControls(t.scope))),p.push(``);let _=Object.keys(t.attributes).filter(e=>o?.excludeKeys?.has(e)!==!0).sort();if(_.length===0)p.push(l(`no attributes`));else{p.push(l(`attributes (${_.length})`));for(let i of _){let a=formatAttributeContent(i,t.attributes[i],r,n-2),o=stripTerminalControls(i);if(a.length===1)p.push(...wrapVisibleLine(`${l(o)} ${a[0]}`,n));else{p.push(l(o));for(let e of a)p.push(` ${e}`)}}}return p.map(e=>clipVisible(e,n))}function renderHeader(e,t){let{theme:n,width:r}=t,{colors:o,glyph:s}=n,{muted:u,primary:d}=chromeStyles(n,t.surfaces),f=[];if(e.trace?.agentName!==void 0&&f.push(stripTerminalControls(e.trace.agentName)),e.trace?.sessionId!==void 0&&f.push(`session ${stripTerminalControls(e.trace.sessionId)}`),e.trace!==void 0){let n=t.activeWindowEndNs!==void 0&&t.activeWindowEndNs>e.trace.endTimeNs?t.activeWindowEndNs:e.trace.endTimeNs;f.push(clockTime(e.trace.startTimeNs),`${e.trace.spans.length} span${e.trace.spans.length===1?``:`s`}`,formatElapsed(durationMs(e.trace.startTimeNs,n)))}let p=`${o.bold(d(`${s.brand} traces`))}${f.length===0?``:u(` · ${f.join(` · `)}`)}`,m=e.traces.length===0?``:u(`[${e.traceIndex+1}/${e.traces.length}]`),h=[t.activeWindowEndNs===void 0?``:o.green(`● live`),m].filter(e=>e.length>0).join(` `);return[``,clipVisible(joinRight(` ${clipVisible(p,Math.max(0,r-visibleLength(h)-2))}`,h,r),r),``]}function renderConversation(e,t,n,r){let{theme:i}=t;if(e.conversationItems.length===0)return[chromeStyles(i,t.surfaces).muted(` No conversation content in this trace — content capture may be off (EVE_TRACES_CONTENT).`)];let a=conversationLines(e,n,i,t.surfaces).slice(e.scrollRow,e.scrollRow+r);return e.textSelection===void 0||e.textSelection.region!==`conversation`?a:a.map((t,r)=>highlightSelection(t,e.scrollRow+r,e.textSelection,n))}function conversationLines(e,n,r,i){let a=[];for(let o=0;o<e.conversationItems.length;o+=1)a.push(...renderConversationItem(e.conversationItems[o],n,r,o===e.selectedRow,e.expandedItems.has(o),i),``);return a}function panelDetailLines(e,t,n,i){let a=selectedTraceViewerSpan(e);return!e.panelOpen||t<=0||a===void 0?[]:[``,...renderSpanDetail(a,Math.max(16,t-3),n,{excludeKeys:CONVERSATION_CONTENT_KEYS,surfaces:i}).map(e=>` ${e}`)]}function conversationSelectionText(e,t,n,r,i){return selectionText(conversationLines(e,t,n,i),r)}function panelSelectionText(e,t,n,r){return selectionText(panelDetailLines(e,e.panelOpen?panelWidthFor(t):0,n),r)}function selectionText(e,t){let{start:r,end:i}=orderedTextSelection(t),a=[];for(let t=Math.max(0,r.line);t<=i.line&&t<e.length;t+=1){let n=stripAnsi(e[t]),c=t===r.line?r.column:0,l=t===i.line?i.column+1:1/0,u=l===1/0?n:sliceVisible(n,l),d=sliceVisible(n,c).length;a.push(u.slice(d).trimEnd())}return a.join(`
1
+ import{formatAttributeContent}from"./trace-content.js";import{renderConversationItem}from"./trace-conversation.js";import{orderedTextSelection,selectedTraceViewerSpan}from"./trace-viewer-state.js";import{formatElapsed}from"#cli/format-elapsed.js";import{clipVisible,sliceVisible,stripAnsi,stripTerminalControls,visibleLength,wrapVisibleLine}from"#cli/ui/terminal-text.js";import{describeLocalTraceSpan}from"#tracing/local-trace-reader.js";function renderTraceViewer(e,t){let{width:n,height:r,theme:i}=t,a=chromeStyles(i,t.surfaces),o=Math.max(1,r-3-3),s=e.panelOpen?panelWidthFor(n):0,c=Math.max(20,n-(s===0?0:s+1)),l=panelDetailLines(e,s,i,t.surfaces),u=o,d=[];if(d.push(...renderHeader(e,t)),e.traces.length===0)d.push(...renderEmptyState(t,i,o));else if(e.trace===void 0)d.push(...center(o,a.muted(`Loading trace…`)));else{let r=renderConversation(e,t,c,o);for(let t=0;t<o;t+=1){let i=r[t]??``;if(s===0){d.push(i);continue}let a=l[e.panelScroll+t]??``;e.textSelection!==void 0&&e.textSelection.region===`panel`&&(a=highlightSelection(a,e.panelScroll+t,e.textSelection,s)),d.push(joinPanels(i,c,a,n))}}return d.push(...renderFooter(e,n,i,t.surfaces)),t.toast!==void 0&&overlayToast(d,t.toast,n,i,t.surfaces),{rows:d,panelTotalRows:l.length,timelineViewportRows:o,panelViewportRows:u,contentWidth:c}}function chromeStyles(e,t){let n=e.color?t:void 0;return{muted:n?.mutedText??e.colors.dim,primary:n?.primaryText??(e=>e)}}function overlayToast(e,t,n,r,i){let a=` ${stripTerminalControls(t)} `,o=visibleLength(a),s=r.unicode?`▌`:r.glyph.rule,u=r.color?i:void 0,d=u===void 0?``:u.body,f=u?.primaryText??r.colors.white,p=r.color?`\x1B[0m`:``,m=[`${d}${f(s)}${` `.repeat(o)}${p}`,`${d}${f(s)}${f(a)}${p}`,`${d}${f(s)}${` `.repeat(o)}${p}`];for(let[t,r]of m.entries()){let i=2+t;if(i>=e.length)break;e[i]=overlayRight(e[i],r,n,1)}}function overlayRight(e,t,n,r){let i=Math.max(0,n-r-visibleLength(t)),a=visibleLength(e);return`${sliceVisible(a<i?e+` `.repeat(i-a):e,i)}\x1b[0m${t}`}const CONVERSATION_CONTENT_KEYS=new Set([`ai.prompt.messages`,`ai.prompt.system`,`ai.response.reasoning`,`ai.response.text`,`ai.response.tool_calls`,`ai.response.tool_results`,`gen_ai.tool.call.arguments`,`gen_ai.tool.call.result`]);function renderSpanDetail(t,n,r,o){let{colors:s}=r,{muted:l,primary:f}=chromeStyles(r,o?.surfaces),p=[],m=stripTerminalControls(t.name);p.push(...wrapVisibleLine(s.bold(f(m)),n));let h=describeLocalTraceSpan(t).map(stripTerminalControls);h.length>0&&p.push(l(h.join(`, `))),p.push(``);let fact=(e,t)=>`${l(e.padEnd(10))}${t}`,g=t.statusCode===2;p.push(fact(`status`,g?s.red(`ERROR`):s.green(`ok`))),p.push(fact(`duration`,formatElapsed(durationMs(t.startTimeNs,t.endTimeNs)))),p.push(fact(`started`,clockTime(t.startTimeNs))),p.push(fact(`span`,t.spanId)),t.parentSpanId!==void 0&&p.push(fact(`parent`,t.parentSpanId)),t.scope!==void 0&&p.push(fact(`scope`,stripTerminalControls(t.scope))),p.push(``);let _=Object.keys(t.attributes).filter(e=>o?.excludeKeys?.has(e)!==!0).sort();if(_.length===0)p.push(l(`no attributes`));else{p.push(l(`attributes (${_.length})`));for(let r of _){let i=formatAttributeContent(r,t.attributes[r],s.dim,n-2),a=stripTerminalControls(r);if(i.length===1)p.push(...wrapVisibleLine(`${l(a)} ${i[0]}`,n));else{p.push(l(a));for(let e of i)p.push(` ${e}`)}}}return p.map(e=>clipVisible(e,n))}function renderHeader(e,t){let{theme:n,width:r}=t,{colors:o,glyph:s}=n,{muted:u,primary:d}=chromeStyles(n,t.surfaces),f=[];if(e.trace?.agentName!==void 0&&f.push(stripTerminalControls(e.trace.agentName)),e.trace?.sessionId!==void 0&&f.push(`session ${stripTerminalControls(e.trace.sessionId)}`),e.trace!==void 0){let n=t.activeWindowEndNs!==void 0&&t.activeWindowEndNs>e.trace.endTimeNs?t.activeWindowEndNs:e.trace.endTimeNs;f.push(clockTime(e.trace.startTimeNs),`${e.trace.spans.length} span${e.trace.spans.length===1?``:`s`}`,formatElapsed(durationMs(e.trace.startTimeNs,n)))}let p=`${o.bold(d(`${s.brand} traces`))}${f.length===0?``:u(` · ${f.join(` · `)}`)}`,m=e.traces.length===0?``:u(`[${e.traceIndex+1}/${e.traces.length}]`),h=[t.activeWindowEndNs===void 0?``:o.green(`● live`),m].filter(e=>e.length>0).join(` `);return[``,clipVisible(joinRight(` ${clipVisible(p,Math.max(0,r-visibleLength(h)-2))}`,h,r),r),``]}function renderConversation(e,t,n,r){let{theme:i}=t;if(e.conversationItems.length===0)return[chromeStyles(i,t.surfaces).muted(` No conversation content in this trace — content capture may be off (EVE_TRACES_CONTENT).`)];let a=conversationLines(e,n,i,t.surfaces).slice(e.scrollRow,e.scrollRow+r);return e.textSelection===void 0||e.textSelection.region!==`conversation`?a:a.map((t,r)=>highlightSelection(t,e.scrollRow+r,e.textSelection,n))}function conversationLines(e,n,r,i){let a=[];for(let o=0;o<e.conversationItems.length;o+=1)a.push(...renderConversationItem(e.conversationItems[o],n,r,o===e.selectedRow,e.expandedItems.has(o),i),``);return a}function panelDetailLines(e,t,n,i){let a=selectedTraceViewerSpan(e);return!e.panelOpen||t<=0||a===void 0?[]:[``,...renderSpanDetail(a,Math.max(16,t-3),n,{excludeKeys:CONVERSATION_CONTENT_KEYS,surfaces:i}).map(e=>` ${e}`)]}function conversationSelectionText(e,t,n,r,i){return selectionText(conversationLines(e,t,n,i),r)}function panelSelectionText(e,t,n,r){return selectionText(panelDetailLines(e,e.panelOpen?panelWidthFor(t):0,n),r)}function selectionText(e,t){let{start:r,end:i}=orderedTextSelection(t),a=[];for(let t=Math.max(0,r.line);t<=i.line&&t<e.length;t+=1){let n=stripAnsi(e[t]),c=t===r.line?r.column:0,l=t===i.line?i.column+1:1/0,u=l===1/0?n:sliceVisible(n,l),d=sliceVisible(n,c).length;a.push(u.slice(d).trimEnd())}return a.join(`
2
2
  `)}function highlightSelection(e,t,r,i){let{start:a,end:s}=orderedTextSelection(r);if(t<a.line||t>s.line)return e;let c=t===a.line?a.column:0,u=t===s.line?s.column+1:i,d=visibleLength(e),f=d<u?e+` `.repeat(u-d):e,p=sliceVisible(f,c),m=sliceVisible(f,u),h=m.slice(p.length),g=f.slice(m.length);return h.length===0?e:`${p}\x1b[7m${h.replaceAll(`\x1B[0m`,`\x1B[0m\x1B[7m`)}\x1b[27m${g}`}function renderFooter(e,t,n,r){let{colors:i}=n,{muted:o}=chromeStyles(n,r),[s,c]=n.unicode?[`↑↓`,`←→`]:[`^/v`,`</>`],l=e.panelFocus?`${s} scroll · tab cards · esc back`:`${s} select · ${c} expand · enter attrs · tab focus · [ ] traces · q close`,u=e.conversationItems.length,d=u===0?``:o(`item ${e.selectedRow+1}/${u}`),f=[e.notice===void 0?``:i.yellow(e.notice),d].filter(e=>e.length>0).join(o(` · `));return[``,clipVisible(` ${o(l)}`,t),clipVisible(f.length===0?``:` ${f}`,t)]}function renderEmptyState(e,t,n){let{muted:r,primary:i}=chromeStyles(t,e.surfaces),[a,o]=e.tracingDisabled===!0?[`Tracing is disabled (EVE_TRACES=off).`,`Re-enable it and spans stream in live.`]:[`No local traces yet.`,`Chat with your agent — spans stream in live.`];return center(n,t.colors.bold(i(a)),r(o))}function center(e,...t){let n=Array.from({length:e},()=>``),r=Math.max(0,Math.floor(e/2)-1);return t.forEach((t,i)=>{r+i<e&&(n[r+i]=t)}),n}function joinPanels(e,t,n,r){let i=Math.max(0,r-t-1);return`${padTo(e,t)} ${clipVisible(n,i)}`}function joinRight(e,t,n){if(t.length===0)return e;let r=Math.max(1,n-visibleLength(e)-visibleLength(t));return`${e}${` `.repeat(r)}${t}`}function padTo(e,t){let n=visibleLength(e);return n>=t?clipVisible(e,t):e+` `.repeat(t-n)}function panelWidthFor(e){return e<42?0:Math.min(64,Math.max(20,Math.floor(e*.42)),e-20-1)}function durationMs(e,t){return Math.max(0,Number(t-e)/1e6)}function clockTime(e){let t=new Date(Number(e/1000000n)),pad=(e,t=2)=>String(e).padStart(t,`0`);return`${pad(t.getHours())}:${pad(t.getMinutes())}:${pad(t.getSeconds())}.${pad(t.getMilliseconds(),3)}`}export{conversationSelectionText,panelSelectionText,renderSpanDetail,renderTraceViewer};
@@ -1,4 +1,4 @@
1
1
  import{createLogger}from"#internal/logging.js";import{Command,CommanderError,InvalidArgumentError}from"#compiled/commander/index.js";import{parseDevelopmentHeaderOption,resolveDevelopmentUrlTarget}from"#cli/dev/url-target.js";import{parseDevelopmentServerUrl}from"#cli/dev/url.js";import{FORCED_EXIT_BACKSTOP_MS,installShutdownSignal,waitForShutdownSignal}from"#cli/shutdown.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,renderCliTaggedLine}from"#cli/ui/output.js";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{eveCliBanner}from"#cli/banner.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{registerBuildCommand}from"#cli/commands/build.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{registerIntegrationCommands}from"#cli/commands/register-integration-commands.js";import{registerProjectCommands}from"#cli/commands/register-project-commands.js";import{registerRegistryCommands}from"#cli/commands/register-registry-commands.js";import{resolveDevUiMode,resolveTuiDisplayOptions}from"#cli/dev/ui-options.js";import{registerAcpCommand}from"#cli/acp/command.js";import{waitForServerOrStop,waitForUiOrServer}from"#cli/dev/wait-for-ui.js";import{registerRuntimeInvokeCommand}from"#cli/invoke/command.js";import{parseContextSizeOption,parseDisplayMode,parseLogsMode,parsePortOption,parseStatsMode}from"#cli/option-parsers.js";import{resolveTuiTitle}from"#cli/dev/tui/target.js";import{resumeDevelopmentRuntimeArtifacts,suspendDevelopmentRuntimeArtifacts}from"#services/dev-client/runtime-artifacts.js";const devBootLog=createLogger(`dev.boot`);function createDevBootProgressReporter(e){return t=>{switch(t.type){case`phase-started`:e?.update(`Building your agent`,t.phase),devBootLog.debug(t.phase);return;case`phase-finished`:devBootLog.debug(`${t.phase} finished`,{ms:t.elapsedMs});return;case`before-first-paint`:e?.stop();return;default:return t}}}async function loadPrintApplicationInfo(){return(await import(`#cli/commands/info.js`)).printApplicationInfo}async function loadRunDevelopmentTui(){return(await import(`#cli/dev/tui/tui.js`)).runDevelopmentTui}async function loadRunEvalCommand(){return(await import(`#evals/cli/eval.js`)).runEvalCommand}async function loadStartHost(){return(await import(`#cli/dev/local-server-process.js`)).createDevelopmentServer}const loadIsActiveDevelopmentServerForApp=async()=>(await import(`#internal/nitro/host.js`)).isActiveDevelopmentServerForApp;async function loadStartProductionHost(){return(await import(`#internal/nitro/host.js`)).startProductionServer}function hasInteractiveTerminal(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function createCliProgram(e,n){let f=resolveApplicationRoot(),y=resolveInstalledPackageInfo().version,b=new Command,x=createCliTheme();b.name(`eve`).description(`Build and run an eve application.`).version(y).showHelpAfterError().exitOverride().hook(`preAction`,(t,n)=>{[`info`,`dev`,`init`].includes(n.name())&&e.log(eveCliBanner())}).configureOutput({writeErr:t=>{e.error(t.trimEnd())},writeOut:t=>{e.log(t.trimEnd())}}),b.command(`channels`).description(`Manage user-authored channels in the current project.`).command(`list`).description(`List user-authored channels in the current project.`).option(`--json`,`Output as JSON`).action(async t=>{let{runChannelsListCommand:n}=await import(`#cli/commands/channels.js`);await n(e,f,t)}),registerIntegrationCommands({program:b,logger:e,appRoot:f});let S=b.command(`extension`).description(`Create and build reusable eve extension packages.`);S.command(`init [target]`).description(`Create a new eve extension package.`).option(`-y, --yes`,`Accepted for compatibility; has no effect`).action(async(t,n)=>{n.yes&&e.error(`warning: --yes has no effect for eve extension init.`);let{runExtensionInitCommand:r}=await import(`#cli/commands/extension-init.js`);await r(e,f,t)}),S.command(`build`).description(`Build the current package as an eve extension.`).action(async()=>{let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);t(f);let{runExtensionBuildCommand:n}=await import(`#cli/commands/extension-build.js`);await n(e,f)}),registerRegistryCommands({program:b,logger:e,appRoot:f}),b.command(`init [target]`).description(`Create a new eve agent, or add one to an existing project directory.`).option(`--channel-web-nextjs`,`Add the Web Chat application (Next.js)`).option(`-y, --yes`,`Accepted for compatibility; has no effect`).action(async(t,n)=>{n.yes&&e.error(`warning: --yes has no effect for eve init.`);let{runInitCommand:r}=await import(`#cli/commands/init.js`);await r(e,f,t,{channelWebNextjs:n.channelWebNextjs})}),registerProjectCommands({program:b,logger:e,appRoot:f}),registerBuildCommand({appRoot:f,buildHost:n.buildHost,logger:e,program:b}),b.command(`start`).description(`Start a built eve application.`).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 3000)`,parsePortOption).action(async t=>{let{loadDevelopmentEnvironmentFiles:r}=await import(`#cli/dev/environment.js`);r(f);let i=await(n.startProductionHost??await loadStartProductionHost())(f,{host:t.host,port:t.port});e.log(renderCliTaggedLine(x,{message:`server listening at ${i.url}`,tag:`start`,tone:`success`})),await waitForShutdownSignal({close:()=>i.close(),wait:()=>i.wait()})}),registerRuntimeInvokeCommand({appRoot:f,logger:e,program:b,runtime:n}),registerAcpCommand({appRoot:f,eveVersion:y,program:b,resolveVerifiedRemoteDevelopmentClient:n.resolveVerifiedRemoteDevelopmentClient,runAcpServer:n.runAcpServer,startHost:n.startHost}),b.command(`dev`).description(`Start the eve development server or connect to an existing URL.`).argument(`[url]`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`--host <host>`,`Host interface to bind`).option(`--port <port>`,`Port to listen on (defaults to $PORT, then 2000)`,parsePortOption).option(`-u, --url <url>`,`Connect to an existing server URL`,parseDevelopmentServerUrl).option(`-H, --header <header>`,`Request header for a URL target, in "Name: value" form (repeatable)`,parseDevelopmentHeaderOption).option(`--no-ui`,`Start the server without an interactive UI`).option(`--name <name>`,`Title shown in the terminal UI (defaults to the app folder name)`).option(`--input <text>`,`Pre-fill the prompt input, or start onboarding with /model`).option(`--tools <mode>`,`How tool calls render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--reasoning <mode>`,`How reasoning renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--subagents <mode>`,`How subagent sections render: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--connection-auth <mode>`,`How connection authorization renders: full | collapsed | auto-collapsed | hidden`,parseDisplayMode).option(`--assistant-response-stats <mode>`,`Assistant header statistic: tokens | tokensPerSecond`,parseStatsMode).option(`--context-size <tokens>`,`Model context window size, shown as a usage percentage`,parseContextSizeOption).option(`--logs <mode>`,`Which server/agent logs to show: all | stderr | sandbox | none`,parseLogsMode).addHelpText(`after`,`
2
2
  You can also pass a bare URL, for example: eve dev https://example.com
3
3
  `).action(async(t,i)=>{let o=resolveDevelopmentUrlTarget(i,t),l=o?.serverUrl,u=hasInteractiveTerminal(),d=resolveDevUiMode({options:i,interactive:u});if(i.input!==void 0&&d===`headless`)throw new InvalidArgumentError(`--input requires the interactive UI.`);let p=!1;l!==void 0&&(p=await(n.isActiveDevelopmentServerForApp??await loadIsActiveDevelopmentServerForApp())({appRoot:f,serverUrl:l}));let runInteractiveUi=async(e,t,r)=>{let a=await devBootPhase(`loading interactive UI`,async()=>n.runDevelopmentTui??await loadRunDevelopmentTui(),t),s=resolveTuiDisplayOptions(i),c=l===void 0||p?{kind:`local`,serverUrl:e.serverUrl,workspaceRoot:e.appRoot??f}:{kind:`remote`,serverUrl:e.serverUrl,workspaceRoot:f},u=resolveTuiTitle({name:i.name,target:c});u!==void 0&&(s.name=u);let d={target:c,initialInput:i.input,onBootProgress:t,lifecycle:r,...s};c.kind===`local`&&(d.withExclusiveTerminal=async t=>await(async()=>{if(!await suspendDevelopmentRuntimeArtifacts({serverUrl:e.serverUrl}))throw Error(`Could not pause the development server for integration setup.`);try{return await t()}finally{await resumeDevelopmentRuntimeArtifacts({serverUrl:e.serverUrl,silent:!0})}})()),o?.headers===void 0?await a(d):await a({...d,headers:o.headers})};if(l){let{loadDevelopmentEnvironmentFiles:t}=await import(`#cli/dev/environment.js`);if(t(f),e.log(`↗ ${p?`local`:`remote`} mode targeting ${x.info(new URL(l).host)}`),d===`headless`){e.log(renderCliTaggedLine(x,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`}));return}e.log(``);let n=installShutdownSignal({exitAfterMs:FORCED_EXIT_BACKSTOP_MS});try{await runInteractiveUi({serverUrl:l},void 0,n)}finally{n.dispose()}return}d===`tui`&&e.log(``);let m=d===`tui`?startCliLiveRow(e):void 0,h=createDevBootProgressReporter(m);m?.update(`Building your agent`);let g,_,closeServer=()=>g===void 0?Promise.resolve():(_??=g.close(),_.catch(()=>void 0),_),v=installShutdownSignal({exitAfterMs:FORCED_EXIT_BACKSTOP_MS,onStop:()=>{closeServer()}});try{g=(n.startHost??await loadStartHost())(f,{existing:d===`tui`?`attach-if-unconfigured`:`reject`,host:i.host,onBootProgress:h,port:i.port});let t=(await Promise.race([g.start().then(e=>({handle:e})),v.stopped.then(()=>({handle:void 0}))])).handle;if(t===void 0)return;if(d!==`tui`&&e.log(renderCliTaggedLine(x,{message:`server listening at ${t.url}`,tag:`dev`,tone:`success`})),d===`headless`){i.ui!==!1&&!u&&e.log(renderCliTaggedLine(x,{message:`Interactive UI disabled because the current terminal is not a TTY.`,tag:`dev`,tone:`warning`})),await waitForServerOrStop(g,v);return}await waitForUiOrServer({handle:t,lifecycle:v,server:g,runUi:async()=>await runInteractiveUi({appRoot:t.appRoot,serverUrl:t.url},h,v)})}finally{m?.stop(),await closeServer(),v.dispose()}});let C=b.command(`logs`).description("Inspect local `eve dev` diagnostic logs (.eve/logs).");return C.command(`show [logid]`,{isDefault:!0}).description(`Print a diagnostic log (the most recent when logid is omitted).`).option(`--dump`,`Prepend the log's environment dump (.dump sibling)`).option(`--events`,`Interleave session events from the local workflow store`).action(async(t,n)=>{let{runLogsShowCommand:r}=await import(`#cli/commands/logs.js`);await r(e,f,t,n)}),C.command(`ls`).description(`List diagnostic logs, most recent first.`).option(`--json`,`Output as JSON`).action(async t=>{let{runLogsListCommand:n}=await import(`#cli/commands/logs.js`);await n(e,f,t)}),b.command(`traces [trace]`).usage(`[options] [trace]
4
- eve traces ls [options]`).description("Show a local `eve dev` trace (the most recent when trace is omitted).").action(async t=>{let{runTraceShowCommand:n}=await import(`#cli/commands/trace.js`);await n(e,f,t)}).command(`ls`).description(`List local traces, most recent first.`).option(`--json`,`Output as JSON`).action(async t=>{let{runTraceListCommand:n}=await import(`#cli/commands/trace.js`);await n(e,f,t)}),b.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async t=>{await(n.printApplicationInfo??await loadPrintApplicationInfo())(e,f,t)}),b.command(`eval`).description(`Run evals against an eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`,parseDevelopmentServerUrl).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--exclude-tag <tag...>`,`Skip evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval t.log lines to stdout`).action(async(t,r)=>{await(n.runEvalCommand??await loadRunEvalCommand())(t,r,e)}),b}async function runCli(e=process.argv.slice(2),t=console,r={}){let i=createCliProgram(t,r),a=e.length===0?[`dev`]:e;try{await i.parseAsync(a,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;let n=await(r.isCodingAgentLaunch??isCodingAgentLaunch)();if(a[0]===`init`&&n){let{initAgentInstructions:e}=await import(`#cli/commands/agent-instructions.js`);t.log(e())}throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,runCli};
4
+ eve traces ls [options]`).description("Show a local `eve dev` trace (the most recent when trace is omitted).").option(`--verbose`,`Expand every span with all attributes and events`).option(`--json`,`Output as JSON`).action(async(t,n)=>{let{runTraceShowCommand:r}=await import(`#cli/commands/trace.js`);await r(e,f,t,n)}).command(`ls`).description(`List local traces, most recent first.`).option(`--json`,`Output as JSON`).action(async t=>{let{runTraceListCommand:n}=await import(`#cli/commands/trace.js`);await n(e,f,t)}),b.command(`info`).description(`Print resolved application information.`).option(`--json`,`Output as JSON`).action(async t=>{await(n.printApplicationInfo??await loadPrintApplicationInfo())(e,f,t)}),b.command(`eval`).description(`Run evals against an eve agent.`).argument(`[evalIds...]`,`Eval ids (or directory prefixes) to run (all discovered evals when omitted)`).option(`--url <url>`,`Remote agent URL (skip local host startup)`,parseDevelopmentServerUrl).option(`--tag <tag...>`,`Run only evals carrying a tag`).option(`--exclude-tag <tag...>`,`Skip evals carrying a tag`).option(`--strict`,`Fail the exit code when any score falls below its threshold`).option(`--list`,`Print discovered evals without running them`).option(`--timeout <ms>`,`Per-eval timeout in milliseconds`).option(`--max-concurrency <n>`,`Max concurrent eval executions`).option(`--json`,`Output results as JSON`).option(`--junit <path>`,`Write JUnit XML results to a file`).option(`--skip-report`,`Skip eval-defined reporters (e.g. Braintrust)`).option(`--verbose`,`Stream per-eval t.log lines to stdout`).action(async(t,r)=>{await(n.runEvalCommand??await loadRunEvalCommand())(t,r,e)}),b}async function runCli(e=process.argv.slice(2),t=console,r={}){let i=createCliProgram(t,r),a=e.length===0?[`dev`]:e;try{await i.parseAsync(a,{from:`user`})}catch(e){if(e instanceof CommanderError){if(e.exitCode===0)return;let n=await(r.isCodingAgentLaunch??isCodingAgentLaunch)();if(a[0]===`init`&&n){let{initAgentInstructions:e}=await import(`#cli/commands/agent-instructions.js`);t.log(e())}throw Error(e.message)}throw e}}export{resolveDevUiMode,resolveTuiDisplayOptions,runCli};
@@ -11,13 +11,13 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
11
11
  readonly dropped: {};
12
12
  };
13
13
  readonly tool: {
14
- readonly current: 5;
15
- readonly supported: readonly [1, 2, 3, 4, 5];
14
+ readonly current: 6;
15
+ readonly supported: readonly [1, 2, 3, 4, 5, 6];
16
16
  readonly dropped: {};
17
17
  };
18
18
  readonly dynamicTool: {
19
- readonly current: 8;
20
- readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8];
19
+ readonly current: 9;
20
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9];
21
21
  readonly dropped: {};
22
22
  };
23
23
  readonly connection: {
@@ -26,8 +26,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
26
26
  readonly dropped: {};
27
27
  };
28
28
  readonly hook: {
29
- readonly current: 6;
30
- readonly supported: readonly [1, 2, 3, 4, 5, 6];
29
+ readonly current: 7;
30
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
31
31
  readonly dropped: {};
32
32
  };
33
33
  readonly skill: {
@@ -36,8 +36,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
36
36
  readonly dropped: {};
37
37
  };
38
38
  readonly dynamicSkill: {
39
- readonly current: 5;
40
- readonly supported: readonly [1, 2, 3, 4, 5];
39
+ readonly current: 6;
40
+ readonly supported: readonly [1, 2, 3, 4, 5, 6];
41
41
  readonly dropped: {};
42
42
  };
43
43
  readonly instructions: {
@@ -46,8 +46,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
46
46
  readonly dropped: {};
47
47
  };
48
48
  readonly dynamicInstructions: {
49
- readonly current: 5;
50
- readonly supported: readonly [1, 2, 3, 4, 5];
49
+ readonly current: 6;
50
+ readonly supported: readonly [1, 2, 3, 4, 5, 6];
51
51
  readonly dropped: {};
52
52
  };
53
53
  readonly config: {
@@ -1 +1 @@
1
- import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:5,supported:[1,2,3,4,5],dropped:{}},dynamicTool:{current:8,supported:[1,2,3,4,5,6,7,8],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:6,supported:[1,2,3,4,5,6],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:5,supported:[1,2,3,4,5],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:5,supported:[1,2,3,4,5],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:2,supported:[1,2],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(t){return parseExtensionCompatibilityManifest(await readFile(t,`utf8`),t)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
1
+ import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:6,supported:[1,2,3,4,5,6],dropped:{}},dynamicTool:{current:9,supported:[1,2,3,4,5,6,7,8,9],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:6,supported:[1,2,3,4,5,6],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:6,supported:[1,2,3,4,5,6],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:2,supported:[1,2],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(t){return parseExtensionCompatibilityManifest(await readFile(t,`utf8`),t)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
@@ -9,12 +9,14 @@ export declare function dispatchDynamicSubagentEvent(input: {
9
9
  readonly ctx: ContextContainer;
10
10
  readonly event: UnstampedMessageStreamEvent;
11
11
  readonly messages: readonly ModelMessage[];
12
+ readonly persistentSessions: boolean;
12
13
  readonly resolvers: readonly ResolvedDynamicSubagentResolver[];
13
14
  }): Promise<void>;
14
15
  export declare function refreshDynamicSessionSubagentsForRuntimeRevision(input: {
15
16
  readonly ctx: ContextContainer;
16
17
  readonly event: SessionStartedStreamEvent;
17
18
  readonly messages: readonly ModelMessage[];
19
+ readonly persistentSessions: boolean;
18
20
  readonly resolvers: readonly ResolvedDynamicSubagentResolver[];
19
21
  readonly runtimeRevision: string;
20
22
  }): Promise<void>;
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{createPreparedRuntimeSubagentTool}from"#runtime/subagents/registry.js";import{normalizeDynamicSubagentAgentConfig}from"#runtime/subagents/dynamic-agent-config.js";import{normalizeDynamicRemoteAgentConfig}from"#runtime/subagents/dynamic-remote-agent-config.js";const log=createLogger(`dynamic-subagents`),ALLOWED_DYNAMIC_SUBAGENT_EVENTS=new Set([`session.started`,`turn.started`]);async function resolveSelections(e){let t=await Promise.allSettled(e.resolvers.map(async t=>{let n=t.events[e.event.type];if(n===void 0)return[t.nodeId,null];let r=await n(e.event,buildResolveContext(e.ctx,e.messages));if(r==null)return[t.nodeId,null];if(isRemoteAgentDefinition(r)){let e=await normalizeDynamicRemoteAgentConfig({name:t.name,value:r}),n=createPreparedRuntimeSubagentTool({description:e.description,kind:`remote`,logicalPath:t.logicalPath,name:t.name,nodeId:t.nodeId,outputSchema:e.outputSchema,path:e.path,sourceId:t.sourceId,sourceKind:t.sourceKind,url:e.url});return[t.nodeId,{kind:`remote`,prepared:n,remoteAgent:e}]}let i=normalizeDynamicSubagentAgentConfig({name:t.name,value:r}),o=createPreparedRuntimeSubagentTool({description:i.description,kind:`subagent`,logicalPath:t.logicalPath,name:t.name,nodeId:t.nodeId,sourceId:t.sourceId,sourceKind:t.sourceKind});return[t.nodeId,{agentConfig:i,kind:`subagent`,prepared:o}]})),n={};for(let r=0;r<t.length;r+=1){let a=t[r],o=e.resolvers[r];if(a.status===`rejected`){log.error(`Dynamic subagent resolver (${e.event.type}) threw — omitting subagent.`,{error:toErrorMessage(a.reason),subagentName:o.name}),n[o.nodeId]=null;continue}n[a.value[0]]=a.value[1]}return n}function isRemoteAgentDefinition(e){return typeof e==`object`&&!!e&&e.kind===`remote`}async function dispatchDynamicSubagentEvent(e){if(!ALLOWED_DYNAMIC_SUBAGENT_EVENTS.has(e.event.type))return;let t=e.resolvers.filter(t=>t.eventNames.includes(e.event.type)),i=await resolveSelections({...e,resolvers:t});e.event.type===`session.started`?e.ctx.set(SessionDynamicSubagentSelectionsKey,i):e.ctx.set(TurnDynamicSubagentSelectionsKey,i)}async function refreshDynamicSessionSubagentsForRuntimeRevision(e){if(e.ctx.get(SessionDynamicSubagentRuntimeRevisionKey)===e.runtimeRevision)return;let r=e.resolvers.filter(e=>e.eventNames.includes(`session.started`)),i=await resolveSelections({...e,resolvers:r});e.ctx.set(SessionDynamicSubagentSelectionsKey,i),e.ctx.set(SessionDynamicSubagentRuntimeRevisionKey,e.runtimeRevision)}function buildDynamicSubagentTools(e){let t=e.get(SessionDynamicSubagentSelectionsKey)??{},i=e.get(TurnDynamicSubagentSelectionsKey)??{},a={...t,...i},s=[],c=new Set;for(let e of Object.values(a))if(e!==null){if(c.has(e.prepared.name))throw Error(`Found multiple active dynamic subagents named "${e.prepared.name}". Subagent names must be unique at runtime.`);c.add(e.prepared.name),s.push(createHarnessDelegationToolDefinition(e.prepared))}return s}function getDynamicSubagentSelection(e,t){let i=e.get(TurnDynamicSubagentSelectionsKey)??{};return Object.hasOwn(i,t)?i[t]??void 0:(e.get(SessionDynamicSubagentSelectionsKey)??{})[t]??void 0}export{buildDynamicSubagentTools,dispatchDynamicSubagentEvent,getDynamicSubagentSelection,refreshDynamicSessionSubagentsForRuntimeRevision};
1
+ import{createLogger}from"#internal/logging.js";import{SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{createHarnessDelegationToolDefinition}from"#execution/delegation-tool.js";import{createPreparedRuntimeSubagentTool,getSubagentToolInputJsonSchema}from"#runtime/subagents/registry.js";import{normalizeDynamicSubagentAgentConfig}from"#runtime/subagents/dynamic-agent-config.js";import{normalizeDynamicRemoteAgentConfig}from"#runtime/subagents/dynamic-remote-agent-config.js";const log=createLogger(`dynamic-subagents`),ALLOWED_DYNAMIC_SUBAGENT_EVENTS=new Set([`session.started`,`turn.started`]);async function resolveSelections(e){let t=getSubagentToolInputJsonSchema(e.persistentSessions),n=await Promise.allSettled(e.resolvers.map(async n=>{let r=n.events[e.event.type];if(r===void 0)return[n.nodeId,null];let i=await r(e.event,buildResolveContext(e.ctx,e.messages));if(i==null)return[n.nodeId,null];if(isRemoteAgentDefinition(i)){let e=await normalizeDynamicRemoteAgentConfig({name:n.name,value:i}),r=createPreparedRuntimeSubagentTool({description:e.description,kind:`remote`,logicalPath:n.logicalPath,name:n.name,nodeId:n.nodeId,outputSchema:e.outputSchema,path:e.path,sourceId:n.sourceId,sourceKind:n.sourceKind,url:e.url},t);return[n.nodeId,{kind:`remote`,prepared:r,remoteAgent:e}]}let o=normalizeDynamicSubagentAgentConfig({name:n.name,value:i}),c=createPreparedRuntimeSubagentTool({description:o.description,kind:`subagent`,logicalPath:n.logicalPath,name:n.name,nodeId:n.nodeId,sourceId:n.sourceId,sourceKind:n.sourceKind},t);return[n.nodeId,{agentConfig:o,kind:`subagent`,prepared:c}]})),r={};for(let t=0;t<n.length;t+=1){let a=n[t],o=e.resolvers[t];if(a.status===`rejected`){log.error(`Dynamic subagent resolver (${e.event.type}) threw — omitting subagent.`,{error:toErrorMessage(a.reason),subagentName:o.name}),r[o.nodeId]=null;continue}r[a.value[0]]=a.value[1]}return r}function isRemoteAgentDefinition(e){return typeof e==`object`&&!!e&&e.kind===`remote`}async function dispatchDynamicSubagentEvent(e){if(!ALLOWED_DYNAMIC_SUBAGENT_EVENTS.has(e.event.type))return;let t=e.resolvers.filter(t=>t.eventNames.includes(e.event.type)),i=await resolveSelections({...e,resolvers:t});e.event.type===`session.started`?e.ctx.set(SessionDynamicSubagentSelectionsKey,i):e.ctx.set(TurnDynamicSubagentSelectionsKey,i)}async function refreshDynamicSessionSubagentsForRuntimeRevision(e){if(e.ctx.get(SessionDynamicSubagentRuntimeRevisionKey)===e.runtimeRevision)return;let r=e.resolvers.filter(e=>e.eventNames.includes(`session.started`)),i=await resolveSelections({...e,resolvers:r});e.ctx.set(SessionDynamicSubagentSelectionsKey,i),e.ctx.set(SessionDynamicSubagentRuntimeRevisionKey,e.runtimeRevision)}function buildDynamicSubagentTools(e){let t=e.get(SessionDynamicSubagentSelectionsKey)??{},i=e.get(TurnDynamicSubagentSelectionsKey)??{},a={...t,...i},s=[],c=new Set;for(let e of Object.values(a))if(e!==null){if(c.has(e.prepared.name))throw Error(`Found multiple active dynamic subagents named "${e.prepared.name}". Subagent names must be unique at runtime.`);c.add(e.prepared.name),s.push(createHarnessDelegationToolDefinition(e.prepared))}return s}function getDynamicSubagentSelection(e,t){let i=e.get(TurnDynamicSubagentSelectionsKey)??{};return Object.hasOwn(i,t)?i[t]??void 0:(e.get(SessionDynamicSubagentSelectionsKey)??{})[t]??void 0}export{buildDynamicSubagentTools,dispatchDynamicSubagentEvent,getDynamicSubagentSelection,refreshDynamicSessionSubagentsForRuntimeRevision};
@@ -0,0 +1,13 @@
1
+ import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";
2
+ import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
3
+ import type { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
4
+ type DynamicRemoteAgentConfig = NonNullable<Extract<ReturnType<typeof getDynamicSubagentSelection>, {
5
+ readonly kind: "remote";
6
+ }>["remoteAgent"]>;
7
+ /** Overlays current dynamic credentials without replacing stored delivery coordinates. */
8
+ export declare function createAgentContinuationBundle(input: {
9
+ readonly action: RuntimeAgentHandleAction;
10
+ readonly bundle: CompiledBundle;
11
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
12
+ }): CompiledBundle;
13
+ export {};
@@ -0,0 +1 @@
1
+ import{resolveRemoteAgentForAction}from"#execution/remote-agent-dispatch.js";function createAgentContinuationBundle(e){let{action:t,dynamicRemoteAgent:n}=e;if(t.kind!==`remote-agent-call`||n===void 0)return e.bundle;let r=e.bundle.subagentRegistry.subagentsByNodeId,i=Object.assign(new Map(r),{get:e=>e===t.nodeId?{definition:resolveRemoteAgentForAction({dynamicRemoteAgent:n,nodeId:e,registry:r,remoteAgentName:t.remoteAgentName})}:r.get(e)});return{...e.bundle,subagentRegistry:{...e.bundle.subagentRegistry,subagentsByNodeId:i}}}export{createAgentContinuationBundle};
@@ -1,11 +1,20 @@
1
1
  /**
2
- * Shared shapes for the runtime-action dispatch step: the hydrated parent
3
- * session snapshot threaded through dispatch, and the per-action outcome
4
- * every dispatch helper resolves to.
2
+ * Continuation dispatch for stored agent handles.
3
+ *
4
+ * Owns the `agentId` leg of the runtime-action dispatch step: resolving a
5
+ * model-supplied agentId against the session's handle store via
6
+ * `prepareAgentContinuation`, delivering the follow-up message to the
7
+ * address the running handle records, and resolving delivery failures as
8
+ * dead (handle deleted) or retryable (handle restored to `parked`).
5
9
  */
6
10
  import type { AgentAddress } from "#harness/handles/store.js";
7
- import type { RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
11
+ import type { RuntimeActionRequest, RuntimeRemoteAgentCallActionRequest, RuntimeSubagentCallActionRequest, RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
12
+ import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
8
13
  import type { hydrateDurableSession } from "#execution/session.js";
14
+ /** Runtime action kinds that may address an agent handle via `agentId`. */
15
+ export type RuntimeAgentHandleAction = RuntimeRemoteAgentCallActionRequest | RuntimeSubagentCallActionRequest;
16
+ /** Narrows an action to the kinds that may carry an `agentId` continuation. */
17
+ export declare function isAgentHandleAction(action: RuntimeActionRequest): action is RuntimeAgentHandleAction;
9
18
  /** Hydrated parent session snapshot threaded through dispatch. */
10
19
  export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;
11
20
  /**
@@ -30,3 +39,22 @@ export type DispatchOutcome = {
30
39
  readonly result: RuntimeSubagentDispatchFailure;
31
40
  readonly session: RuntimeSession;
32
41
  };
42
+ /**
43
+ * Delivers one `agentId` continuation to the child the handle names.
44
+ *
45
+ * Planning converts initially unknown ids into fresh starts, so an id that
46
+ * matches no handle here disappeared mid-batch and reports
47
+ * `AGENT_UNREACHABLE`. Name mismatches and busy handles report
48
+ * `AGENT_MISMATCH` / `AGENT_BUSY` without touching the store. Delivery
49
+ * failures report `AGENT_UNREACHABLE`: permanent ones resolve the handle as
50
+ * dead, transient ones restore it to `parked` so the model can retry the
51
+ * same agentId.
52
+ */
53
+ export declare function dispatchToAgentHandle(input: {
54
+ readonly action: RuntimeAgentHandleAction;
55
+ readonly agentId: string;
56
+ readonly bundle: CompiledBundle;
57
+ readonly currentSession: RuntimeSession;
58
+ readonly parentToken: string;
59
+ readonly parentTurnId: string;
60
+ }): Promise<DispatchOutcome>;