eve 0.37.0 → 0.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/src/channel/routes.d.ts +13 -3
  3. package/dist/src/channel/routes.js +1 -1
  4. package/dist/src/channel/session-callback.js +1 -1
  5. package/dist/src/channel/session.d.ts +2 -1
  6. package/dist/src/channel/session.js +1 -1
  7. package/dist/src/channel/types.d.ts +41 -0
  8. package/dist/src/chunks/{use-eve-agent-CnppTEFk.js → use-eve-agent-Bi5fRxcZ.js} +9 -1
  9. package/dist/src/chunks/{use-eve-agent-COmP-H8R.js → use-eve-agent-DbKUBhl-.js} +9 -1
  10. package/dist/src/cli/commands/init-git.js +1 -1
  11. package/dist/src/cli/commands/init-recovery.d.ts +3 -0
  12. package/dist/src/cli/commands/init-recovery.js +3 -0
  13. package/dist/src/cli/commands/init-target.d.ts +21 -0
  14. package/dist/src/cli/commands/init-target.js +1 -0
  15. package/dist/src/cli/commands/init.js +1 -1
  16. package/dist/src/cli/dev/tui/runner.d.ts +8 -0
  17. package/dist/src/cli/dev/tui/runner.js +1 -1
  18. package/dist/src/cli/dev/tui/subagent-pump.d.ts +27 -22
  19. package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
  20. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +16 -0
  21. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  22. package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
  23. package/dist/src/client/open-stream.d.ts +2 -0
  24. package/dist/src/client/open-stream.js +1 -1
  25. package/dist/src/client/session.js +1 -1
  26. package/dist/src/compiled/.vendor-stamp.json +2 -1
  27. package/dist/src/compiled/@modelcontextprotocol/server/LICENSE +216 -0
  28. package/dist/src/compiled/@modelcontextprotocol/server/index.d.ts +98 -0
  29. package/dist/src/compiled/@modelcontextprotocol/server/index.js +80 -0
  30. package/dist/src/compiler/extension-compatibility.d.ts +10 -10
  31. package/dist/src/compiler/extension-compatibility.js +1 -1
  32. package/dist/src/compiler/manifest.js +1 -1
  33. package/dist/src/compiler/normalize-agent-config.js +1 -1
  34. package/dist/src/compiler/normalize-manifest.js +1 -1
  35. package/dist/src/compiler/normalize-subagent.d.ts +1 -1
  36. package/dist/src/compiler/normalize-subagent.js +1 -1
  37. package/dist/src/context/serialized-dynamic-model-selection.d.ts +2 -0
  38. package/dist/src/context/serialized-dynamic-model-selection.js +1 -0
  39. package/dist/src/execution/agent-handle-dispatch.d.ts +15 -1
  40. package/dist/src/execution/agent-handle-dispatch.js +1 -1
  41. package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
  42. package/dist/src/execution/delegated-parent-notification.d.ts +17 -0
  43. package/dist/src/execution/delegated-parent-notification.js +1 -1
  44. package/dist/src/execution/deliver-payloads.js +1 -1
  45. package/dist/src/execution/dispatch-runtime-actions-shared.d.ts +155 -0
  46. package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -0
  47. package/dist/src/execution/dispatch-runtime-actions-step.d.ts +18 -14
  48. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  49. package/dist/src/execution/dispatch-workflow-runtime-actions-step.d.ts +7 -2
  50. package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
  51. package/dist/src/execution/effective-output-schema.d.ts +21 -0
  52. package/dist/src/execution/effective-output-schema.js +1 -0
  53. package/dist/src/execution/eve-workflow-attributes.d.ts +2 -0
  54. package/dist/src/execution/node-step.js +1 -1
  55. package/dist/src/execution/parked-delivery-wait.d.ts +8 -12
  56. package/dist/src/execution/parked-delivery-wait.js +1 -1
  57. package/dist/src/execution/{route-proxied-deliver-step.d.ts → proxied-deliver-step.d.ts} +7 -4
  58. package/dist/src/execution/proxied-deliver-step.js +1 -0
  59. package/dist/src/execution/remote-agent-dispatch.d.ts +32 -0
  60. package/dist/src/execution/remote-agent-dispatch.js +1 -1
  61. package/dist/src/execution/remote-agent-route-url.d.ts +2 -0
  62. package/dist/src/execution/remote-agent-route-url.js +1 -0
  63. package/dist/src/execution/route-child-delivery.d.ts +2 -1
  64. package/dist/src/execution/route-child-delivery.js +1 -1
  65. package/dist/src/execution/session-callback-step.d.ts +11 -0
  66. package/dist/src/execution/session-callback-step.js +1 -1
  67. package/dist/src/execution/session-command-wire.js +1 -1
  68. package/dist/src/execution/session-state-cursor.d.ts +25 -0
  69. package/dist/src/execution/session-state-cursor.js +1 -0
  70. package/dist/src/execution/settle-cancelled-turn-step.d.ts +2 -0
  71. package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
  72. package/dist/src/execution/subagent-event-proxy-step.d.ts +15 -0
  73. package/dist/src/execution/subagent-event-proxy-step.js +1 -1
  74. package/dist/src/execution/subagent-hitl-proxy.d.ts +14 -7
  75. package/dist/src/execution/subagent-hitl-proxy.js +1 -1
  76. package/dist/src/execution/subagent-start-local.d.ts +29 -0
  77. package/dist/src/execution/subagent-start-local.js +1 -0
  78. package/dist/src/execution/subagent-start-remote.d.ts +23 -0
  79. package/dist/src/execution/subagent-start-remote.js +1 -0
  80. package/dist/src/execution/task-event-callback.d.ts +13 -0
  81. package/dist/src/execution/task-event-callback.js +1 -0
  82. package/dist/src/execution/task-input-capability.d.ts +4 -0
  83. package/dist/src/execution/task-input-capability.js +1 -0
  84. package/dist/src/execution/tasks/child/steps.d.ts +46 -0
  85. package/dist/src/execution/tasks/child/steps.js +1 -0
  86. package/dist/src/execution/tasks/child/workflow.d.ts +31 -0
  87. package/dist/src/execution/tasks/child/workflow.js +1 -0
  88. package/dist/src/execution/tasks/parent/agent-identity.d.ts +13 -0
  89. package/dist/src/execution/tasks/parent/agent-identity.js +1 -0
  90. package/dist/src/execution/tasks/parent/agent-views.d.ts +6 -0
  91. package/dist/src/execution/tasks/parent/agent-views.js +1 -0
  92. package/dist/src/execution/tasks/parent/continuation-dispatch.d.ts +37 -0
  93. package/dist/src/execution/tasks/parent/continuation-dispatch.js +1 -0
  94. package/dist/src/execution/tasks/parent/control-shared.d.ts +36 -0
  95. package/dist/src/execution/tasks/parent/control-shared.js +1 -0
  96. package/dist/src/execution/tasks/parent/delegate.d.ts +70 -0
  97. package/dist/src/execution/tasks/parent/delegate.js +1 -0
  98. package/dist/src/execution/tasks/parent/dispatch-task-step.d.ts +19 -0
  99. package/dist/src/execution/tasks/parent/dispatch-task-step.js +1 -0
  100. package/dist/src/execution/tasks/parent/dispatch.d.ts +33 -0
  101. package/dist/src/execution/tasks/parent/dispatch.js +1 -0
  102. package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +29 -0
  103. package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -0
  104. package/dist/src/execution/tasks/parent/run-parent.d.ts +72 -0
  105. package/dist/src/execution/tasks/parent/run-parent.js +1 -0
  106. package/dist/src/execution/tasks/parent/send.d.ts +25 -0
  107. package/dist/src/execution/tasks/parent/send.js +1 -0
  108. package/dist/src/execution/tasks/workflow-target.d.ts +2 -0
  109. package/dist/src/execution/tasks/workflow-target.js +1 -0
  110. package/dist/src/execution/terminate-child-sessions-step.d.ts +1 -0
  111. package/dist/src/execution/terminate-child-sessions-step.js +1 -1
  112. package/dist/src/execution/turn-control-receiver.d.ts +10 -0
  113. package/dist/src/execution/turn-control-receiver.js +1 -1
  114. package/dist/src/execution/turn-dispatch.d.ts +2 -0
  115. package/dist/src/execution/turn-dispatch.js +1 -1
  116. package/dist/src/execution/turn-execution-cursor.d.ts +2 -8
  117. package/dist/src/execution/turn-execution-cursor.js +1 -1
  118. package/dist/src/execution/turn-workflow.js +1 -1
  119. package/dist/src/execution/workflow-callback-url.d.ts +5 -0
  120. package/dist/src/execution/workflow-callback-url.js +1 -1
  121. package/dist/src/execution/workflow-entry.js +1 -1
  122. package/dist/src/execution/workflow-runtime.d.ts +9 -0
  123. package/dist/src/execution/workflow-runtime.js +1 -1
  124. package/dist/src/execution/workflow-steps.d.ts +7 -21
  125. package/dist/src/execution/workflow-steps.js +1 -1
  126. package/dist/src/harness/advertised-tools.js +1 -1
  127. package/dist/src/harness/authorization.js +1 -1
  128. package/dist/src/harness/execute-tool.d.ts +7 -0
  129. package/dist/src/harness/handles/prompt.d.ts +12 -0
  130. package/dist/src/harness/handles/prompt.js +2 -1
  131. package/dist/src/harness/handles/query.js +1 -1
  132. package/dist/src/harness/handles/store.d.ts +9 -2
  133. package/dist/src/harness/handles/store.js +1 -1
  134. package/dist/src/harness/handles/transitions.d.ts +10 -1
  135. package/dist/src/harness/handles/transitions.js +1 -1
  136. package/dist/src/harness/proxy-input-requests.d.ts +21 -4
  137. package/dist/src/harness/proxy-input-requests.js +1 -1
  138. package/dist/src/harness/runtime-actions.d.ts +2 -0
  139. package/dist/src/harness/runtime-actions.js +1 -1
  140. package/dist/src/harness/session-limit-enforcement.js +1 -1
  141. package/dist/src/harness/tool-loop.js +2 -2
  142. package/dist/src/harness/workflow-runtime-action-state.js +1 -1
  143. package/dist/src/internal/application/package.js +1 -1
  144. package/dist/src/internal/authored-definition/core.js +1 -1
  145. package/dist/src/internal/invocation/agent-invocation.d.ts +54 -0
  146. package/dist/src/internal/invocation/agent-invocation.js +1 -0
  147. package/dist/src/internal/invocation/attributes.d.ts +2 -0
  148. package/dist/src/internal/invocation/attributes.js +1 -0
  149. package/dist/src/internal/invocation/metadata.d.ts +9 -0
  150. package/dist/src/internal/invocation/metadata.js +1 -0
  151. package/dist/src/internal/invocation/workflow-execution.d.ts +32 -0
  152. package/dist/src/internal/invocation/workflow-execution.js +1 -0
  153. package/dist/src/internal/mcp/http-security.d.ts +12 -0
  154. package/dist/src/internal/mcp/http-security.js +1 -0
  155. package/dist/src/internal/mcp/protected-resource.d.ts +9 -0
  156. package/dist/src/internal/mcp/protected-resource.js +1 -0
  157. package/dist/src/internal/mcp/streamable-http-server.d.ts +51 -0
  158. package/dist/src/internal/mcp/streamable-http-server.js +1 -0
  159. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  160. package/dist/src/internal/nitro/routes/channel-route-context.d.ts +14 -0
  161. package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
  162. package/dist/src/internal/nitro/routes/runtime-stack.d.ts +2 -0
  163. package/dist/src/internal/nitro/routes/runtime-stack.js +1 -1
  164. package/dist/src/internal/vercel-agent-summary.d.ts +1 -1
  165. package/dist/src/protocol/message.d.ts +28 -0
  166. package/dist/src/protocol/message.js +2 -2
  167. package/dist/src/protocol/routes.d.ts +14 -0
  168. package/dist/src/protocol/routes.js +1 -1
  169. package/dist/src/public/channels/auth.d.ts +36 -0
  170. package/dist/src/public/channels/auth.js +1 -1
  171. package/dist/src/public/channels/eve.js +1 -1
  172. package/dist/src/public/channels/mcp.d.ts +19 -0
  173. package/dist/src/public/channels/mcp.js +1 -0
  174. package/dist/src/public/definitions/channel.d.ts +2 -2
  175. package/dist/src/public/definitions/channel.js +1 -1
  176. package/dist/src/react/use-eve-agent.js +1 -1
  177. package/dist/src/runtime/actions/types.d.ts +9 -0
  178. package/dist/src/runtime/actions/types.js +1 -1
  179. package/dist/src/runtime/agent/bootstrap.js +1 -1
  180. package/dist/src/runtime/connections/authorization-complete-page.js +70 -28
  181. package/dist/src/runtime/framework-channels/index.js +1 -1
  182. package/dist/src/runtime/framework-tools/index.js +1 -1
  183. package/dist/src/runtime/framework-tools/tasks.d.ts +95 -0
  184. package/dist/src/runtime/framework-tools/tasks.js +1 -0
  185. package/dist/src/runtime/prompt/compose.d.ts +1 -0
  186. package/dist/src/runtime/prompt/compose.js +1 -1
  187. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  188. package/dist/src/runtime/resolve-agent.js +1 -1
  189. package/dist/src/runtime/session-callback-route.js +1 -1
  190. package/dist/src/runtime/task-input-response-route.d.ts +5 -0
  191. package/dist/src/runtime/task-input-response-route.js +1 -0
  192. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  193. package/dist/src/setup/scaffold/create/project.js +1 -1
  194. package/dist/src/shared/agent-definition.d.ts +7 -0
  195. package/dist/src/svelte/index.js +1 -1
  196. package/dist/src/svelte/use-eve-agent.js +1 -1
  197. package/dist/src/tasks/json.d.ts +88 -0
  198. package/dist/src/tasks/json.js +1 -0
  199. package/dist/src/tasks/session-index.d.ts +48 -0
  200. package/dist/src/tasks/session-index.js +1 -0
  201. package/dist/src/tasks/task-id.d.ts +34 -0
  202. package/dist/src/tasks/task-id.js +1 -0
  203. package/dist/src/tasks/transitions.d.ts +23 -0
  204. package/dist/src/tasks/transitions.js +1 -0
  205. package/dist/src/tasks/types.d.ts +295 -0
  206. package/dist/src/tasks/types.js +1 -0
  207. package/dist/src/tasks/wire.d.ts +26 -0
  208. package/dist/src/tasks/wire.js +1 -0
  209. package/dist/src/vue/index.js +1 -1
  210. package/dist/src/vue/use-eve-agent.js +1 -1
  211. package/docs/channels/eve.mdx +14 -0
  212. package/docs/guides/client/streaming.mdx +1 -1
  213. package/docs/tools/human-in-the-loop.md +3 -1
  214. package/package.json +7 -1
  215. package/dist/src/execution/route-proxied-deliver-step.js +0 -1
@@ -22,6 +22,10 @@ export interface SubagentView {
22
22
  callId: string;
23
23
  name: string;
24
24
  }): void;
25
+ /** Keeps a receipt-returned background call mutable across parent turns. */
26
+ background(update: {
27
+ callId: string;
28
+ }): void;
25
29
  upsertStep(update: SubagentStepUpdate): void;
26
30
  upsertTool(update: SubagentToolUpdate): void;
27
31
  /** Drops a child tool row whose call never materialized. */
@@ -31,6 +35,7 @@ export interface SubagentView {
31
35
  }): void;
32
36
  /** Marks a call complete so its section collapses on `└ Done…`. */
33
37
  complete(update: {
38
+ authoritative: boolean;
34
39
  callId: string;
35
40
  }): void;
36
41
  /** Suppresses the parent-level tool row for a child-owned call id. */
@@ -51,14 +56,16 @@ type SubagentToolState = {
51
56
  };
52
57
  export type SubagentRun = {
53
58
  name: string;
54
- /**
55
- * The run's one lifecycle authority. `settled` means the final assistant
56
- * message is in (the child's turn boundary, or the parent's
57
- * `subagent.completed` fallback); a late child event — a HITL-parked
58
- * turn resuming — explicitly reopens the run rather than mutating a
59
- * completed section by accident.
60
- */
61
- status: "running" | "settled";
59
+ /** Parent turn that originated this dispatch; cancellation is scoped to it. */
60
+ parentTurnId: string;
61
+ /** A receipt-returned task survives cancellation of its originating turn. */
62
+ background: boolean;
63
+ /** Parent completion is provisional; only a child boundary is authoritative. */
64
+ status: "open" | "provisional" | "authoritative";
65
+ /** Parent-authored route on the parent origin, valid for local and remote children. */
66
+ childStreamPath: string;
67
+ /** Absolute durable cursor retained across exhausted transport sources. */
68
+ childStreamIndex: number;
62
69
  /**
63
70
  * One entry per logical "child message" — independent of the child's
64
71
  * `stepIndex` field, which the harness can reuse across multiple
@@ -119,24 +126,22 @@ export declare class SubagentPump {
119
126
  */
120
127
  begin(called: SubagentCalledStreamEvent): void;
121
128
  /**
122
- * Parent reports subagent.completed. The child stream pump terminates
123
- * itself on the child's own turn boundary — the authoritative finish
124
- * signal, which already finalized the section — so this is a fallback
125
- * for runs whose boundary never reached us (a dropped child stream, a
126
- * HITL-parked turn resuming later). We do NOT abort the pump here,
127
- * because the child's `message.completed` event may still be in flight
128
- * (the parent and child streams are independent HTTP connections).
129
+ * Parent completion is provisional because the child's final events can be
130
+ * in flight on an independent connection. The pump remains open until the
131
+ * child boundary supplies authoritative completion.
129
132
  */
130
133
  settle(callId: string): void;
134
+ /**
135
+ * The originating call returned a task receipt, not the child's result.
136
+ * Keep the section open until the child stream reaches its own boundary.
137
+ * A child that already settled before the receipt raced in stays settled.
138
+ */
139
+ background(callId: string): void;
131
140
  abortAll(): void;
132
141
  /**
133
- * Settles every live run and stops its child stream. Called when the
134
- * parent turn is cancelled (`/cancel`, a key-driven steer, or an empty-queue
135
- * cancel): the server cancels the pending descendants, so their sections must
136
- * close now. A child still flushing reasoning would otherwise keep painting
137
- * stale sections into the next (steered) turn's transcript. Runs stay
138
- * registered so a late parent `subagent.completed` settles as a no-op.
142
+ * Settles and aborts only foreground descendants of the cancelled parent
143
+ * turn. Background tasks survive even when that same turn started them.
139
144
  */
140
- settleAll(): void;
145
+ settleCancelledTurn(turnId: string): void;
141
146
  }
142
147
  export {};
@@ -1 +1 @@
1
- import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,r=this.#r.get(t);r===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map,seenChildEvents:createEventDeduper()}):r.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}settleAll(){for(let e of this.#r.keys())this.#s(e);for(let e of this.#i.values())e.abort();this.#i.clear()}#a(n){let i=n.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.sessions.attach(n.data.childSessionId).stream({signal:o.signal});for await(let t of e){if(o.signal.aborted)break;if(this.#l(i,t),isCurrentTurnBoundaryEvent(t)){s=!0;break}}}catch(n){if(!isAbortLikeError(n)){let e=toErrorMessage(n),r=this.#r.get(i);if(r){let{key:t,step:n}=openCurrentSubagentSection(r);n.message=n.message?`${n.message}\n\nstream error: ${e}`:`stream error: ${e}`,n.finalized=!0,r.currentSectionKey=null,this.#t?.upsertStep({callId:i,subagentName:r.name,sectionKey:t,reasoning:n.reasoning,message:n.message,finalized:!0})}}}finally{this.#i.delete(i)}s&&this.#s(i)})()}#o(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e){let t=this.#r.get(e);if(!(!t||t.status===`settled`)){t.status=`settled`;for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null,this.#c(e,t),this.#t?.complete({callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n||!n.seenChildEvents.admit(t))return;n.status===`settled`&&(n.status=`running`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#o(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r?.upsertTool(o);break}default:break}}};function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{SubagentPump};
1
+ import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{readNdjsonStream}from"#client/ndjson.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(t){let n=t.data.callId,r=this.#r.get(n);r===void 0?this.#r.set(n,{name:t.data.name,parentTurnId:t.data.turnId,background:!1,status:`open`,childStreamPath:t.data.childStreamPath,childStreamIndex:0,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map,seenChildEvents:createEventDeduper()}):r.name=t.data.name,this.#t?.markChildToolCallId(n),!(r!==void 0&&r.status!==`open`)&&(this.#t?.begin({callId:n,name:t.data.name}),this.#a(t))}settle(e){this.#s(e,!1)}background(e){let t=this.#r.get(e);t!==void 0&&(t.background=!0,t.status!==`authoritative`&&this.#t?.background({callId:e}))}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}settleCancelledTurn(e){for(let[t,n]of this.#r)n.parentTurnId!==e||n.background||(this.#s(t,!0),this.#i.get(t)?.abort(),this.#i.delete(t))}#a(e){let r=e.data.callId;if(this.#i.has(r))return;let i=this.#e;if(!i)return;let a=this.#r.get(r);if(a===void 0||a.status===`authoritative`)return;let o=new AbortController;this.#i.set(r,o),(async()=>{let e=100;try{for(;!o.signal.aborted&&a.status!==`authoritative`;){let s=!1;try{let e=await i.fetch(streamPathAt(a.childStreamPath,a.childStreamIndex),{cache:`no-store`,signal:o.signal});if(!e.ok||e.body===null)throw await e.body?.cancel().catch(()=>{}),Error(`Child stream returned ${e.status}.`);for await(let i of readNdjsonStream(e.body)){if(o.signal.aborted)return;if(s=!0,a.childStreamIndex+=1,this.#l(r,i),isCurrentTurnBoundaryEvent(i)){this.#s(r,!0);return}}}catch{if(o.signal.aborted)return}e=s?100:Math.min(e*2,2e3),await abortableDelay(e,o.signal)}}finally{this.#i.get(r)===o&&this.#i.delete(r)}})()}#o(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e,t){let n=this.#r.get(e);if(!(!n||n.status===`authoritative`)&&!(!t&&n.status===`provisional`)){n.status=t?`authoritative`:`provisional`;for(let[t,r]of n.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:r.reasoning,message:r.message,finalized:!0}));n.currentSectionKey=null,this.#c(e,n),this.#t?.complete({authoritative:t,callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n||!n.seenChildEvents.admit(t))return;n.status===`provisional`&&(n.status=`open`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#o(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r?.upsertTool(o);break}default:break}}};function streamPathAt(e,t){return t===0?e:`${e}${e.includes(`?`)?`&`:`?`}startIndex=${t}`}async function abortableDelay(e,t){t.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t.removeEventListener(`abort`,onAbort),n()},e);r.unref?.(),t.addEventListener(`abort`,onAbort,{once:!0})})}function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{SubagentPump};
@@ -73,6 +73,12 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
73
73
  */
74
74
  takeQueuedPrompt(): string | undefined;
75
75
  renderStream(result: AgentTUIStreamResult, options?: AgentTUISessionOptions): Promise<void>;
76
+ /**
77
+ * Applies a wake-initiated turn without taking input ownership from the
78
+ * prompt. Paints use the same live region, so the editor redraws around
79
+ * incoming tool and assistant blocks exactly as it does for subagent pumps.
80
+ */
81
+ renderIdleStream(result: AgentTUIStreamResult, options?: AgentTUISessionOptions): Promise<void>;
76
82
  readToolApproval(request: AgentTUIToolApprovalRequest, options?: AgentTUISessionOptions): Promise<AgentTUIToolApprovalResponse>;
77
83
  readInputQuestion(question: AgentTUIInputQuestion, options?: AgentTUISessionOptions): Promise<AgentTUIInputQuestionResponse | undefined>;
78
84
  upsertSubagentStep(update: SubagentStepUpdate): void;
@@ -97,12 +103,21 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
97
103
  callId: string;
98
104
  name: string;
99
105
  }): void;
106
+ /**
107
+ * A background receipt closes the model tool call, not the child. Mark the
108
+ * header running so turn finalization cannot commit immutable scrollback
109
+ * before the child pump has folded in its later events.
110
+ */
111
+ backgroundSubagent(update: {
112
+ callId: string;
113
+ }): void;
100
114
  /**
101
115
  * Marks a subagent call complete — its final message has arrived — so the
102
116
  * section's closing corner reports `Done`. The header stays live until the
103
117
  * turn finalizes (committing mid-turn would freeze its child window).
104
118
  */
105
119
  completeSubagent(update: {
120
+ authoritative: boolean;
106
121
  callId: string;
107
122
  }): void;
108
123
  markChildToolCallId(callId: string): void;
@@ -140,6 +155,7 @@ export declare class TerminalRenderer implements AgentTUIRenderer {
140
155
  /** Last server session id the runner reported; named in the parting line. */
141
156
  setSessionId(sessionId: string): void;
142
157
  shutdown(): void;
158
+ suspendPromptForInput(): void;
143
159
  requestInterrupt(): void;
144
160
  exitRequested(): boolean;
145
161
  /** The log sources the transcript currently renders. */
@@ -1,15 +1,15 @@
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),replaceContent:e=>this.#mt(e),renderOutput:e=>this.#ht(e),withInheritedStdio:e=>this.#gt(e),withExclusiveTerminal:e=>this.#gt(e),waitForInterrupt:e=>this.#lt(e)};traceViewer={open:e=>this.#vt(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.#xt();let t=this.#un().join(`
2
- `);if(this.#T){t!==this.#E&&(this.#E=t,this.#Rt({kind:`agent-header`,body:t,live:!1})),this.#an();return}this.#T=!0,this.#E=t,this.#n.flush(this.#un(),[])}async readPrompt(e){this.#xt(e),this.#Lt(),this.#Bt(),this.#F=!0,this.#L=!0,this.#U={kind:`idle`},this.#G=``,this.#$=!1;let r=this.#Pe.restoreDraft()?.split(`
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 Set;#C=new Set;#w=new FileContentCache;#T=new Set;#E;#D=!1;#O;#k=[];#A;#j=0;#M;#N;#P=``;#F=0;#I=new PromptHistory;#L=!1;#R;#z=!1;#B=Date.now();#V=!1;#H=new TurnClock;#U=EMPTY_LINE;#W=!1;#G={kind:`idle`};#K;#q=STATUS.processing;#J;#Y=`eve`;#X=!1;#Z=!1;#Q=!1;#$=!1;#ee=!1;#te=!1;#ne;#re=!0;#ie=0;#ae=Date.now();#oe;#se;#ce;#le=!1;#ue;#de=``;#fe=new StringDecoder(`utf8`);#pe;#me;#he;#ge=!1;#_e=!1;#ve;#ye;#be;#xe;#Se;#Ce;#we;#Te=``;#Ee=``;#De;#Oe;#ke=0;#Ae;#je;#Me;#Ne;#Pe;#Fe;#Ie=new MessageQueue;#Le;#Re=!1;#ze;#Be;#Ve=!1;#He;#Ue;#We;#Ge;#Ke;setupFlow={begin:(e,t)=>this.#Qe(e,t),end:e=>this.#$e(e?.preserveDiagnostics??!0),readSelect:e=>this.#et(e),readEditableSelect:e=>this.#nt(e),readProviderPicker:e=>this.#rt(e),readModelEditor:e=>this.#it(e),readText:e=>this.#at(e),readAcknowledge:e=>this.#ot(e),readChoice:e=>this.#tt(e),setStatus:e=>this.#mt(e),renderLine:(e,t)=>this.#ht(e,t),replaceContent:e=>this.#gt(e),renderOutput:e=>this.#_t(e),withInheritedStdio:e=>this.#vt(e),withExclusiveTerminal:e=>this.#vt(e),waitForInterrupt:e=>this.#dt(e)};traceViewer={open:e=>this.#bt(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.#be=t?.contextSize,this.#u=t?.captureForeignOutput??this.#t===process.stdout,this.#d=t?.diagnostics,this.#ne=t?.onExitRequest,this.#p=t?.logs??`none`,this.#f=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#Y=e.name,this.#E=e,this.#Ct();let t=this.#pn().join(`
2
+ `);if(this.#D){t!==this.#O&&(this.#O=t,this.#Bt({kind:`agent-header`,body:t,live:!1})),this.#cn();return}this.#D=!0,this.#O=t,this.#n.flush(this.#pn(),[])}async readPrompt(e){this.#Ct(e),this.#zt(),this.#Ht(),this.#L=!0,this.#z=!0,this.#G={kind:`idle`},this.#q=``,this.#te=!1;let r=this.#Ie.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.#Mt(),this.#an(),await new Promise((e,r)=>{this.#W=r;let apply=e=>{a=e,this.#Pt(),this.#Ge(a),this.#I=typeaheadFor(this.#f,e.text,this.#I),this.#an()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#I=void 0,this.#Nt(),this.#Ct(),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.#an());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.#an();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.#an();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.#an());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.#Nt(),this.#G=STATUS.processing,isPromptControlCommand(i)?this.#Rt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#It(),this.#zt(i),this.#Oe=i,this.#B.arm()),this.#Ge(EMPTY_LINE),this.#an(),this.#Tt(),e(i);break}case`ctrl-d`:a.text.length===0?(this.#_t(),interrupt()):apply(deleteForward(a));break;case`ctrl-l`:this.#cn();break;case`ctrl-r`:this.#an();break;case`ctrl-c`:if(this.#$){this.#_t(),interrupt();break}this.#$=!0,apply(EMPTY_LINE);break;default:break}},this.#wt()})}#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.#xt(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.#Vt(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.#Ft(),this.#H=!0,this.#an();let r=new Promise(e=>{this.#pe=e});this.#ce=e=>this.#jt(e),this.#wt();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.#qt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Ht(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Ht(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#pe=void 0,this.#Z&&e.abort?.(),this.#Fe=void 0,this.#Tt(),this.#Lt(),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.#en(i),(this.#Z||this.#Ie)&&this.#$t(),this.#Kt(),this.#d?.reportStats(),this.#an(),t?.continueSession||this.#Ct()}}async readToolApproval(e,t){return this.#xt(t),this.#Lt(),this.#F=!1,this.#U={kind:`idle`},this.#G=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#Z=!1,this.#an(),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.#It(),this.#G=STATUS.processing,this.#Tt(),this.#an(),t({approved:!0})):n===`n`&&(this.#It(),this.#G=STATUS.processing,this.#qe(e.toolCallId),this.#Tt(),this.#an(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#an();break;case`ctrl-c`:this.#Z=!0,this.#Ct(),n(interruptedError());break;default:break}},this.#wt()})}async readInputQuestion(e,t){this.#xt(t),this.#Lt(),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.#Wt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#Mt():(this.#Nt(),this.#Pt())};s===`overlay`?(s=`overlay`,this.#F=!1,this.#Gt(o),this.#ke=overlayPanel,this.#G=``,syncFreeformCaret(),this.#an()):(s=`text`,this.#ke=void 0,renderTextSection(),this.#F=!0,this.#Ge(l),this.#G=``,this.#Mt(),this.#an());let finalize=t=>{this.#ke=void 0,this.#Wt({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.#It(),this.#G=STATUS.processing,this.#Nt(),this.#Tt(),this.#an();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.#Wt({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.#Nt(),this.#Tt(),this.#an(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#an())},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.#Pt(),s===`text`&&this.#Ge(l),this.#an();return}this.#Z=!0,this.#ke=void 0,this.#Nt(),this.#Ct(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#an();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.#Pt(),this.#an();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Pt(),this.#an());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.#an())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Pt(),this.#Ge(l),this.#an();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Pt(),this.#Ge(l),this.#an());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.#Pt(),this.#Ge(l),this.#an();break}dismiss();break;default:break}},this.#wt()})}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.#Ut(e.callId,e.subagentName),this.#s===`collapsed`){this.#an();return}this.#Wt({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.#an()}}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.#Ut(e.callId,e.subagentName),this.#s===`collapsed`){this.#an();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Zt({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.#Wt(r),this.#Ke(e.callId),this.#an()}#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.#Gt(subagentToolSectionId(e.callId,e.childCallId)),this.#an()}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.#Ut(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#an()}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#an())}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#Gt(t),this.#y.delete(e),this.#an())}#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.#Wt({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.#an()}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.#an()):n&&(this.#G=STATUS.processing,this.#an())}setVercelStatus(e){this.#A=e,this.#an()}setRemoteConnectionStatus(e){this.#j=e,this.#an()}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.#an())}renderSessionBoundary(){this.#Bt(),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.#Rt({kind:`session-boundary`,body:n,live:!1}),this.#an()}#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.#xt(),this.#Rt({kind:`notice`,body:t,live:!1}),this.#an())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#xt(),this.#Rt({kind:`sandbox`,body:t,live:!1}),this.#an())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ye();return}this.#xt(),this.#je=t,this.#an()}clearSetupWarning(){this.#Ye()}#Ye(){this.#je!==void 0&&(this.#je=void 0,this.#an())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#xt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Rt(r),this.#an()}renderCommandResult(e,t){let n=stripTerminalControls(e);n.trim().length!==0&&(this.#xt(),this.#Rt(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.#an())}#Xe(e,t=`spinner`){this.#xt(),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.#Ft(),this.#an()}#Ze(e){this.#Ve=void 0,this.#dt();let t=this.#Ae;if(t!==void 0){if(this.#Ae=void 0,this.#Lt(),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.#Rt({kind:`flow`,title:`info`,body:e.join(`
5
- `),live:!1}),this.#Rt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#an()}}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.#an()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#an();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.#an())}},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.#fn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#an(),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.#an();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.#an();return;case`update`:o=d.select,s=void 0,this.#an();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.#an();return;case`ignore`:return}}).promise}#$e(e){this.#xt();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.#an();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.#an();return;case`repaint`:this.#an();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.#Mt():(i=lineOf(``),this.#Nt())};return syncEditableRow(),this.#an(),await this.#ct((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Pt(),this.#an()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#an()},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.#an();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.#an();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Nt()).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.#Mt():this.#Nt()};return syncCaret(),this.#an(),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.#an();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#an();return;case`validate`:{n=o.state,syncCaret(),this.#an();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.#an();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.#Pt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Nt()}).promise}async#nt(e){let t=this.#at(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#an(),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.#an();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.#an();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
- `,` `))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.#Mt(),this.#an(),await this.#ct((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Pt(),this.#an()},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.#an();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#an();return}i(t);return}default:return}},()=>this.#Nt()).promise}async#it(e){let t=this.#at();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#i,t),this.#an(),await this.#ct((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#an();return;default:return}}).promise}#at(){return this.#xt(),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.#Tt(),this.#Ae!==void 0&&this.#ut(),this.#an()}#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.#At(),this.#ce=t=>{t.type===`ctrl-c`&&this.#_t(),e(t,settle,reject)},this.#wt(),{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.#_t();let e=this.#Ve;this.#Ve=void 0,this.#dt(),e?.();return}t.type===`ctrl-r`&&this.#an()};this.#He=consumer,this.#At(),this.#ce=consumer,this.#wt()}#dt(){this.#He!==void 0&&(this.#ce===this.#He&&this.#Tt(),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.#an();return}if(!(this.#F||this.#H)){if(t===void 0){this.#U={kind:`idle`},this.#K=void 0,this.#Lt(),this.#an();return}this.#xt(),this.#It(),this.#K=t.text,this.#an()}}#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.#an();return}this.#xt(),this.#Rt({kind:`flow`,title:t,body:n,live:!1}),this.#an()}#mt(e){let t=this.#Ae;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.summary=e===void 0?void 0:{headline:stripTerminalControls(e.headline),facts:e.facts.map(e=>({label:stripTerminalControls(e.label),value:stripTerminalControls(e.value)}))},this.#an())}#ht(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.#an()}async#gt(e){this.#le=``,this.#At(),this.#Ve=void 0,this.#dt(),this.#Tt(),this.#Lt(),this.#n.clear(),this.#n.showCursor(),this.#Dn(),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.#At(),this.#n.hideCursor(),this.#En(),this.#Ae!==void 0&&(this.#Ft(),this.#ut()),this.#n.reset(),this.#an()}}setSessionId(e){this.#Le=e}shutdown(){if(this.#Ct(),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.#Ct()}exitRequested(){return this.#Q}#_t(){this.#Q=!0,this.#ee?.()}async#vt(e){if(this.#Ue!==void 0||!this.#J)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#wn(),height:this.#Tn()}),paint:e=>this.#r.paint(e,this.#Tn()),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.#bt=e,this.#ce=e=>{t.handleKey(e)===`close`&&this.#yt()},this.#wt(),t.start()})}#yt(){let e=this.#Ue;if(e===void 0)return;this.#Ue=void 0,e.dispose(),this.#Tt(),this.#r.exit(),this.#n.hideCursor(),this.#an(),this.#n.showCursor();let t=this.#bt;this.#bt=void 0,t?.()}#bt;#xt(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.#En(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#fe=()=>this.#an(),this.#t.on(`resize`,this.#fe),process.on(`exit`,this.#St))}#St=()=>{this.#J&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#Ct(){this.#yt();let e=this.#W;if(this.#W=void 0,e?.(interruptedError()),this.#Tt(),this.#Nt(),this.#Lt(),this.#oe!==void 0&&(clearTimeout(this.#oe),this.#oe=void 0),this.#se=!1,this.#J){this.#Fn();for(let e of this.#m)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#an(),this.#n.clear(),this.#n.showCursor(),this.#Dn(),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.#St),this.#J=!1}}#wt(){this.#e.off(`data`,this.#Et),this.#e.on(`data`,this.#Et),this.#le.length>0&&queueMicrotask(()=>{this.#ce!==void 0&&this.#le.length>0&&(this.#Ot(),this.#Dt())})}#Tt(){this.#e.off(`data`,this.#Et),this.#At(),this.#ce=void 0}#Et=e=>{this.#At(),this.#le+=this.#ue.write(e),this.#Ot(),this.#Dt()};#Dt(){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?.()}}#Ot(){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.#kt(e.key.value);continue}this.#ce?.(e.key)}}}#kt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#We=t,this.#Ue?.setTerminalBackground(t))}#At(){this.#de&&=(clearTimeout(this.#de),void 0)}#jt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#an();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.#an();break}this.#Pe.enqueue(e)&&(this.#V=EMPTY_LINE),this.#an();break}case`ctrl-c`:case`escape`:if(this.#Pe.idle&&this.#Fe===void 0)break;this.#Pe.handleEscape(),this.#ze=!0,this.#Fe?.(),this.#an();break;default:{let t=applyLineEditorKey(this.#V,e,{multiline:!0});t!==void 0&&(this.#V=t,this.#an());break}}}#Mt(){this.#Nt(),this.#Pt(),this.#ie=setInterval(()=>{this.#te=!this.#te,this.#an()},500),this.#ie.unref?.()}#Nt(){this.#ie&&=(clearInterval(this.#ie),void 0),this.#te=!0}#Pt(){this.#te=!0}#Ft(){this.#Lt(),this.#ae=setInterval(()=>{this.#ne+=1,this.#an()},90),this.#ae.unref?.()}#It(){let e=Date.now();this.#re=e,this.#U={kind:`waiting`,startedAtMs:e},this.#Ft()}#Lt(){this.#ae&&=(clearInterval(this.#ae),void 0)}#Rt(e){e.id!==this.#Ee?.id&&this.#Fn(),e.updateSeq=++this.#b,this.#m.push(e),e.id&&this.#h.set(e.id,e)}#zt(e){this.#z=!0,this.#Rt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#an()}#Bt(){let e=this.#B.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#_n(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.#Rt({kind:`turn-stats`,body:t,live:!1})}#Vt(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.#Rt(n)}#Ht(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.#Rt(c),this.#an()}#Ut(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.#Rt(i)}#Wt(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.#Rt(e)}#Gt(e){this.#m=this.#m.filter(t=>t.id!==e),this.#h.delete(e)}#Kt(){for(let e of this.#m)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#qt(e,t,n){switch(e.type){case`step-finish`:this.#d?.recordStepUsage(e.usage),e.usage!==void 0&&this.#B.addUsage(e.usage),this.#en(n),this.#in(e.usage),this.#an();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Jt(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.#Jt(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.#Yt(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.#Yt(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#Xt({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.#Xt({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.#Xt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#rn(e.toolCallId,n);if(r===void 0)break;this.#Xt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#rn(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.#Xt({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#rn(e.toolCallId,n);if(r===void 0)break;this.#Xt({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Ht(`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.#in(e.usage),this.#an();break}}#Jt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Wt({id:e,kind:`assistant`,body:r,live:n}),this.#an())}#Yt(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Wt({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#an())}#Xt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#v.has(e.toolCallId)||this.#tn(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#y.set(e.toolCallId,r);let i=this.#Zt(e);this.#Wt(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#nn(n),this.#an()}#Zt(e){e.output!==void 0&&this.#S.observeRead(e.output);let t={};this.#Qt(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}#Qt(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)}#$t(){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)}#en(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.#Gt(r),this.#y.delete(t)}}#tn(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.#Rt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#wn(),this.#i).join(`
7
- `),live:!1})),this.#Me=void 0}else this.#Me=t.length>0?t:void 0,this.#Ne=void 0;return this.#an(),!0}#nn(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)}#rn(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`}}#in(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)}}#an(){if(this.#J){if(this.#me){this.#he=!0;return}this.#me=!0;try{do this.#he=!1,this.#on();while(this.#he)}finally{this.#me=!1}}}#on(){if(!this.#J)return;if(this.#Ue!==void 0){this.#Ue.repaint();return}let e=this.#wn(),t=this.#hn(e),n=Math.max(1,this.#Tn()-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.#Ln(t.display))continue;let n=this.#dn(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.#Ln(t))continue;let n=this.#dn(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)}#sn(){if(!this.#J)return;let e=this.#wn(),t=this.#hn(e),n=Math.max(1,this.#Tn()-t.length),r=this.#O,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#m)){if(this.#Ln(t))continue;let n=this.#dn(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.#un(),...this.#D],a)}logDisplayMode(){return this.#p}setLogDisplayMode(e){e!==this.#p&&(this.#p=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#ln(),this.#J&&this.#sn())}flushDelayedDevBuildErrors(){let e=this.#Te;e!==void 0&&(this.#Te=void 0,this.#Rt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#an())}#cn(){this.#se=!0,this.#oe!==void 0&&clearTimeout(this.#oe),this.#oe=setTimeout(()=>{this.#se=!1,this.#oe=void 0,this.#an()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#p)),this.#an()}#ln(){let e=this.#wn();this.#D.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#_,{logCoalescing:`runs`})){if(this.#Ln(n))continue;let r=this.#dn(n,e,t);t=previousBlockOf(n),this.#D.push(...r)}this.#O=t}#un(){let e=this.#w;if(e===void 0)return[];let t={name:e.name,theme:this.#i,width:this.#wn()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#dn(e,t,n){let r={activityPulse:this.#pn(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}#fn(){return this.#i.spinner[this.#ne%this.#i.spinner.length]??``}#pn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#mn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#fn(),color:`yellow`}:{glyph:this.#pn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#hn(e){let n=this.#i.colors,r=[``];if(this.#ke!==void 0)return r.push(...this.#ke(e),``),this.#xn(r,e),r;let a=this.#Ae;if(a!==void 0){let t=this.#mn(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.summary===void 0?a.hideLinesWhileQuestion===!0?[]:a.lines:[{text:a.summary.headline,tone:`success`},...a.summary.facts.map(e=>({text:`${e.label}: ${e.value}`,tone:`info`}))],content:i};return r.push(...renderFlowPanel(o,this.#i,e)),this.#Sn(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.#pn(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.#xn(s,e);let u=Math.max(1,this.#Tn()-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.#gn(e)),this.#yn(r,e);let t=[];return this.#xn(t,e),!this.#H&&t.length>0&&r.push(``),r.push(...t),r}if(this.#V.text.length>0)return this.#bn(r,e,{inert:!1}),this.#xn(r,e),r;let u=this.#K??(this.#G.length>0?this.#G:`Ready`),f=this.#Cn(),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.#xn(r,e),r}#gn(e){let t=this.#i.colors,n=this.#pn(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.#_n(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#_n(e){return`${formatTurnDuration(e)}${this.#vn()}`}#vn(){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)}`}#yn(e,t){this.#H&&this.#bn(e,t,{inert:!0})}#bn(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))}#xn(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))}#Sn(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))}#Cn(){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} `)):``}#wn(){return Math.max(20,this.#t.columns||80)}#Tn(){return Math.max(8,this.#t.rows||24)}#En(){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.#kn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#d?.subscribeLogRecords(e=>this.#On(e)),this.#Se=()=>{this.#d?.unsubscribeLogRecords(),e(),t()}}#Dn(){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.#In(`stdout`)&&process.stdout.write(`${this.#Ce}\n`),this.#Ce=``),this.#we.length>0&&(this.#d?.append({source:`stderr`,detail:this.#we}),this.#In(`stderr`)&&process.stderr.write(`${this.#we}\n`),this.#we=``))}#On(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#jn(`[eve:${e.namespace}] ${e.message}${t}`),this.#an()}#kn(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.#An(n.trimEnd()),this.#an();return}let r=n.lastIndexOf(`
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.#An(a):this.#jn(a),this.#an())}#An(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
9
- `);t=[],e.trim().length!==0&&this.#Rt({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
10
- `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Rt({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#Nn(r,n.trimEnd())}flushPending()}#jn(e){let t=e.split(`
11
- `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#d===void 0){this.#Rt({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#d.displayPath);if(t.kind===`inline`){this.#Rt({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#Rt({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#Rt({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
12
- `);r.trim().length>0&&this.#Rt({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
13
- `);this.#Mn(i)}#Mn(e){if(this.#p===`all`){if(e.trim().length===0)return;this.#Rt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#Te=e}#Nn(e,t){let n=this.#Pn();if(e.kind===`failed`){this.#Mn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#De}`;this.#De+=1,this.#Ee={id:r,summary:t},this.#Rt({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#Te=void 0);return}e.kind===`rebuilt`&&(this.#Te=void 0),this.#Rt({kind:`log`,title:`stdout`,body:t,live:!0})}#Pn(){let e=this.#Ee;if(e===void 0)return;let t=this.#h.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#Fn(){let e=this.#Ee;if(e===void 0)return;this.#Ee=void 0;let t=this.#h.get(e.id);t!==void 0&&(t.live=!1)}#In(e){switch(this.#p){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Ln(e){return e.kind===`sandbox`?!this.#In(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#p!==`stderr`:e.logVisibility===`all-only`?this.#p!==`all`:!this.#In(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${u.dim(r.glyph.promptIdle)} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
4
+ `),i=stripPromptControlCharacters(e?.initialDraft??this.#U.text),a=lineOf(r===void 0?i:i.length===0?r:`${r}\n\n${i}`);return this.#U=EMPTY_LINE,this.#I.begin(a.text),this.#qe(a),this.#R=typeaheadFor(this.#f,a.text),this.#Pt(),this.#cn(),await new Promise((e,r)=>{this.#K=r;let apply=e=>{a=e,this.#It(),this.#qe(a),this.#R=typeaheadFor(this.#f,e.text,this.#R),this.#cn()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#R=void 0,this.#Ft(),this.#Tt(),r(interruptedError())},suggestions=()=>this.#R!==void 0&&isTypeaheadOpen(this.#R)?this.#R:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ue=r=>{r.type!==`ctrl-c`&&this.#te&&(this.#te=!1,this.#cn());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.#R=moveTypeaheadSelection(e,-1),this.#cn();break}let t=movePromptLine(a,`up`);t===void 0?recall(this.#I.previous(a.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#R=moveTypeaheadSelection(e,1),this.#cn();break}let t=movePromptLine(a,`down`);t===void 0?recall(this.#I.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.#R=dismissTypeahead(e),this.#cn());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.#R=void 0,this.#I.add(i),this.#L=!1,this.#Ft(),this.#q=STATUS.processing,isPromptControlCommand(i)?this.#Bt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Rt(),this.#Vt(i),this.#Ae=i,this.#H.arm()),this.#qe(EMPTY_LINE),this.#cn(),this.#Dt(),e(i);break}case`ctrl-d`:a.text.length===0?(this.#yt(),interrupt()):apply(deleteForward(a));break;case`ctrl-l`:this.#dn();break;case`ctrl-r`:this.#cn();break;case`ctrl-c`:if(this.#te){this.#yt(),interrupt();break}this.#te=!0,apply(EMPTY_LINE);break;default:break}},this.#Et()})}#qe(e){this.#P=e.text,this.#F=e.cursor}takeQueuedPrompt(){let e=this.#Ie.view().steering,t=this.#Ie.takePrompt();return t!==void 0&&(this.#Be=e?`steer`:`queue`),t}async renderStream(e,t){this.#Ct(t),this.#g.clear(),this.#L=!1,this.#G.kind!==`waiting`&&(this.#G={kind:`waiting`,startedAtMs:Date.now()}),this.#q=this.#j>0?STATUS.connectionAuth:STATUS.processing,this.#Ut(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#d?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#H.armed&&this.#H.arm(),this.#$=!1,this.#Re=!1,this.#Ve=!1,this.#He=t?.submittedPrompt,this.#Ie.beginTurn(),this.#Le=e.cancel,this.#ve=void 0,this.#ye=void 0,this.#xe=void 0,this.#Se=void 0,this.#Ce=Date.now();let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l};this.#Lt(),this.#W=!0,this.#cn();let r=new Promise(e=>{this.#he=e});this.#ue=e=>this.#Nt(e),this.#Et();let i={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!0};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#$)break;this.#Xt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Wt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Wt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#he=void 0,this.#$&&e.abort?.(),this.#Le=void 0,this.#Dt(),this.#zt(),this.#W=!1,this.#G.kind===`waiting`&&(this.#G={kind:`idle`}),this.#q=completedTurnStatus({interrupted:this.#$,cancelled:this.#Re,continueSession:t?.continueSession===!0}),this.#rn(i),(this.#$||i.cancelled)&&this.#nn(i),this.#Yt(),this.#d?.reportStats(),this.#cn(),t?.continueSession||this.#Tt()}}async renderIdleStream(e,t){let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l},r={text:new Map,reasoning:new Map,tools:new Map,cancelled:!1,restoreCancelledPrompt:!1};try{for await(let t of iterateTUIStream(e.events))this.#Xt(t,n,r)}catch(e){let t=summarizeKnownError(e);t===null?this.#Wt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Wt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#rn(r),r.cancelled&&this.#nn(r),this.#Yt(),this.#d?.reportStats(),this.#cn()}}async readToolApproval(e,t){return this.#Ct(t),this.#zt(),this.#L=!1,this.#G={kind:`idle`},this.#q=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#$=!1,this.#cn(),await new Promise((t,n)=>{this.#K=n,this.#ue=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Rt(),this.#q=STATUS.processing,this.#Dt(),this.#cn(),t({approved:!0})):n===`n`&&(this.#Rt(),this.#q=STATUS.processing,this.#Ye(e.toolCallId),this.#Dt(),this.#cn(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#cn();break;case`ctrl-c`:this.#$=!0,this.#Tt(),n(interruptedError());break;default:break}},this.#Et()})}async readInputQuestion(e,t){this.#Ct(t),this.#zt(),this.#L=!1,this.#z=!1,this.#G={kind:`idle`},this.#$=!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.#re},this.#i,t),renderTextSection=()=>{this.#Kt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#Pt():(this.#Ft(),this.#It())};s===`overlay`?(s=`overlay`,this.#L=!1,this.#Jt(o),this.#je=overlayPanel,this.#q=``,syncFreeformCaret(),this.#cn()):(s=`text`,this.#je=void 0,renderTextSection(),this.#L=!0,this.#qe(l),this.#q=``,this.#Pt(),this.#cn());let finalize=t=>{this.#je=void 0,this.#Kt({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.#L=!1,this.#Rt(),this.#q=STATUS.processing,this.#Ft(),this.#Dt(),this.#cn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#je=void 0,this.#Kt({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.#L=!1,this.#q=``,this.#Ft(),this.#Dt(),this.#cn(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#cn())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#K=r,u=t,this.#ue=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#It(),s===`text`&&this.#qe(l),this.#cn();return}this.#$=!0,this.#je=void 0,this.#Ft(),this.#Tt(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#cn();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.#It(),this.#cn();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#It(),this.#cn());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.#cn())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#It(),this.#qe(l),this.#cn();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#It(),this.#qe(l),this.#cn());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.#It(),this.#qe(l),this.#cn();break}dismiss();break;default:break}},this.#Et()})}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.#Gt(e.callId,e.subagentName),this.#s===`collapsed`){this.#cn();return}this.#qt({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.#cn()}}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.#Gt(e.callId,e.subagentName),this.#s===`collapsed`){this.#cn();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#en({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.#qt(r),this.#Je(e.callId),this.#cn()}#Je(e){applyCohortLiveness(this.#m.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#Jt(subagentToolSectionId(e.callId,e.childCallId)),this.#cn()}subagents={begin:e=>this.beginSubagent(e),background:e=>this.backgroundSubagent(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.#Gt(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status===`done`&&delete t.status,t.live=!0),this.#C.delete(e.callId),this.#cn()}backgroundSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t===void 0||this.#g.has(subagentHeaderId(e.callId))||(t.status=`running`,t.live=!0,t.updateSeq=++this.#b,this.#S.add(e.callId),this.#cn())}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));if(t!==void 0){if(t.status=`done`,e.authoritative){this.#S.delete(e.callId),this.#C.delete(e.callId);for(let t of this.#m)t.subagentCallId===e.callId&&(t.live=!1)}else{this.#C.add(e.callId);for(let t of this.#m)t.subagentCallId===e.callId&&(t.live=!0)}this.#cn()}}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#Jt(t),this.#y.delete(e),this.#cn())}#Ye(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.#Kt({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.#cn()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#j)return;let n=this.#j>0;this.#j=t,t>0?(this.#q=STATUS.connectionAuth,this.#cn()):n&&(this.#q=STATUS.processing,this.#cn())}setVercelStatus(e){this.#M=e,this.#cn()}setRemoteConnectionStatus(e){this.#N=e,this.#cn()}reset(){this.#m=[],this.#h.clear(),this.#g.clear(),this.#A=void 0,this.#k.length=0,this.#_.length=0,this.#D=!1,this.#O=void 0,this.#Xe(),this.#V=!1,this.#Ae=void 0,this.#Oe=void 0,this.#j=0,this.#ve=void 0,this.#ye=void 0,this.#xe=void 0,this.#Se=void 0,this.#Ce=void 0,this.#X&&(this.#n.clearAll(),this.#cn())}renderSessionBoundary(){this.#Ht(),this.#Xe();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#Bt({kind:`session-boundary`,body:n,live:!1}),this.#cn()}#Xe(){this.#v.clear(),this.#y.clear(),this.#T.clear(),this.#S.clear(),this.#C.clear(),this.#x.clear(),this.#Pe=void 0,this.#Fe=void 0,this.#Ie.reset(),this.#Be=void 0,this.#w.clear(),this.#H.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ct(),this.#Bt({kind:`notice`,body:t,live:!1}),this.#cn())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#Ct(),this.#Bt({kind:`sandbox`,body:t,live:!1}),this.#cn())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ze();return}this.#Ct(),this.#Ne=t,this.#cn()}clearSetupWarning(){this.#Ze()}#Ze(){this.#Ne!==void 0&&(this.#Ne=void 0,this.#cn())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ct();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Bt(r),this.#cn()}renderCommandResult(e,t){let n=stripTerminalControls(e);n.trim().length!==0&&(this.#Ct(),this.#Bt(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.#cn())}#Qe(e,t=`spinner`){this.#Ct(),this.#L=!1,this.#G={kind:`idle`},this.#q=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Me={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Lt(),this.#cn()}#$e(e){this.#Ue=void 0,this.#pt();let t=this.#Me;if(t!==void 0){if(this.#Me=void 0,this.#zt(),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.#Bt({kind:`flow`,title:`info`,body:e.join(`
5
+ `),live:!1}),this.#Bt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#cn()}}async#et(e){let t=this.#st(),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.#cn()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#cn();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.#cn())}},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.#hn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#cn(),await this.#ut((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.#cn();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.#cn();return;case`update`:o=d.select,s=void 0,this.#cn();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.#cn();return;case`ignore`:return}}).promise}#tt(e){this.#Ct();let t=this.#ct();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.#cn();let r=this.#ut((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.#cn();return;case`repaint`:this.#cn();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#nt(e){let t=this.#st(),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.#re,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.#Pt():(i=lineOf(``),this.#Ft())};return syncEditableRow(),this.#cn(),await this.#ut((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#It(),this.#cn()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#cn()},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.#cn();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.#cn();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ft()).promise}async#rt(e){let t=this.#st(),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.#re,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.#Pt():this.#Ft()};return syncCaret(),this.#cn(),await this.#ut((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.#cn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#cn();return;case`validate`:{n=o.state,syncCaret(),this.#cn();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.#cn();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.#It(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ft()}).promise}async#it(e){let t=this.#st(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#cn(),await this.#ut((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#cn();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.#cn();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
+ `,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#at(e){let t=this.#st(),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.#re)},this.#Pt(),this.#cn(),await this.#ut((t,i)=>{let apply=e=>{n=e,r=void 0,this.#It(),this.#cn()},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.#cn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#cn();return}i(t);return}default:return}},()=>this.#Ft()).promise}async#ot(e){let t=this.#st();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#i,t),this.#cn(),await this.#ut((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#cn();return;default:return}}).promise}#st(){return this.#Ct(),this.#L=!1,this.#G={kind:`idle`},this.#q=``,this.#ct()}#ct(){return this.#Me===void 0&&(this.#Me={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Me}#lt(){this.#Me?.implicit===!0?this.#Me=void 0:this.#Me!==void 0&&(this.#Me.question=void 0,this.#Me.hideLinesWhileQuestion=!1),this.#ue=void 0,this.#Dt(),this.#Me!==void 0&&this.#ft(),this.#cn()}#ut(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#lt(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#lt(),i(e))};return this.#Mt(),this.#ue=t=>{t.type===`ctrl-c`&&this.#yt(),e(t,settle,reject)},this.#Et(),{promise:a,settle}}#dt(e){let t,n=new Promise(e=>{t=e});return this.#Ue=t,this.#ft(e?.interruptible??!0),{promise:n,dispose:()=>{this.#Ue===t&&(this.#Ue=void 0,this.#pt())}}}#ft(e=!0){if(this.#Ue===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#yt();let e=this.#Ue;this.#Ue=void 0,this.#pt(),e?.();return}t.type===`ctrl-r`&&this.#cn()};this.#We=consumer,this.#Mt(),this.#ue=consumer,this.#Et()}#pt(){this.#We!==void 0&&(this.#ue===this.#We&&this.#Dt(),this.#We=void 0)}#mt(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.#Me!==void 0){this.#Me.status=t,t===void 0&&(this.#Me.preview=void 0),this.#cn();return}if(!(this.#L||this.#W)){if(t===void 0){this.#G={kind:`idle`},this.#J=void 0,this.#zt(),this.#cn();return}this.#Ct(),this.#Rt(),this.#J=t.text,this.#cn()}}#ht(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Me;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.#cn();return}this.#Ct(),this.#Bt({kind:`flow`,title:t,body:n,live:!1}),this.#cn()}#gt(e){let t=this.#Me;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.summary=e===void 0?void 0:{headline:stripTerminalControls(e.headline),facts:e.facts.map(e=>({label:stripTerminalControls(e.label),value:stripTerminalControls(e.value)}))},this.#cn())}#_t(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Me;if(n===void 0){this.#ht(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#cn()}async#vt(e){this.#de=``,this.#Mt(),this.#Ue=void 0,this.#pt(),this.#Dt(),this.#zt(),this.#n.clear(),this.#n.showCursor(),this.#An(),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.#de=``,this.#Mt(),this.#n.hideCursor(),this.#kn(),this.#Me!==void 0&&(this.#Lt(),this.#ft()),this.#n.reset(),this.#cn()}}setSessionId(e){this.#ze=e}shutdown(){if(this.#Tt(),this.#Z&&!this.#Q){this.#Q=!0;let e=this.#ze===void 0?``:` ${this.#i.glyph.dot} session ${this.#ze}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}suspendPromptForInput(){this.#U={cursor:this.#F,text:this.#P},this.#Tt()}requestInterrupt(){this.#$=!0,this.#Me!==void 0&&this.#ue?.({type:`ctrl-c`}),this.#he?.(),this.#Tt()}exitRequested(){return this.#ee}#yt(){this.#ee=!0,this.#ne?.()}async#bt(e){if(this.#Ge!==void 0||!this.#X)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Dn(),height:this.#On()}),paint:e=>this.#r.paint(e,this.#On()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#Ke});this.#Ge=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#St=e,this.#ue=e=>{t.handleKey(e)===`close`&&this.#xt()},this.#Et(),t.start()})}#xt(){let e=this.#Ge;if(e===void 0)return;this.#Ge=void 0,e.dispose(),this.#Dt(),this.#r.exit(),this.#n.hideCursor(),this.#cn(),this.#n.showCursor();let t=this.#St;this.#St=void 0,t?.()}#St;#Ct(e){this.#Y=e?.title??this.#Y,e?.contextSize!==void 0&&(this.#be=e.contextSize),!this.#X&&(this.#X=!0,this.#Z=!0,this.#n.reset(),this.#n.hideCursor(),this.#kn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#me=()=>this.#cn(),this.#t.on(`resize`,this.#me),process.on(`exit`,this.#wt))}#wt=()=>{this.#X&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#Tt(){this.#xt();let e=this.#K;if(this.#K=void 0,e?.(interruptedError()),this.#Dt(),this.#Ft(),this.#zt(),this.#ce!==void 0&&(clearTimeout(this.#ce),this.#ce=void 0),this.#le=!1,this.#X){this.#Rn();for(let e of this.#m)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#cn(),this.#n.clear(),this.#n.showCursor(),this.#An(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#me&&=(this.#t.off(`resize`,this.#me),void 0),process.off(`exit`,this.#wt),this.#X=!1}}#Et(){this.#e.off(`data`,this.#Ot),this.#e.on(`data`,this.#Ot),this.#de.length>0&&queueMicrotask(()=>{this.#ue!==void 0&&this.#de.length>0&&(this.#At(),this.#kt())})}#Dt(){this.#e.off(`data`,this.#Ot),this.#Mt(),this.#ue=void 0}#Ot=e=>{this.#Mt(),this.#de+=this.#fe.write(e),this.#At(),this.#kt()};#kt(){if(this.#de===`\x1B`){this.#pe=setTimeout(()=>{this.#de===`\x1B`&&(this.#de=``,this.#ue?.({type:`escape`}))},30),this.#pe.unref?.();return}if(isIncompletePaste(this.#de)){let e=this.#de;this.#pe=setTimeout(()=>{if(this.#de!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#de=``,t.length>0&&this.#ue?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#pe.unref?.();return}if(isIncompleteOsc(this.#de)){let e=this.#de;this.#pe=setTimeout(()=>{this.#de===e&&(this.#de=``)},incompletePasteFlushMs),this.#pe.unref?.()}}#At(){for(;this.#de.length>0;){let e=nextKey(this.#de);if(e.incomplete)return;if(this.#de=this.#de.slice(e.consumed),!(e.key===void 0||e.key.type===`ignore`)){if(e.key.type===`osc`){this.#jt(e.key.value);continue}this.#ue?.(e.key)}}}#jt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#Ke=t,this.#Ge?.setTerminalBackground(t))}#Mt(){this.#pe&&=(clearTimeout(this.#pe),void 0)}#Nt(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#cn();break;case`enter`:{let e=this.#U.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Le!==void 0){this.#U=EMPTY_LINE,this.#Ie.requestCancellation(),this.#Ve=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Le(),this.#cn();break}this.#Ie.enqueue(e)&&(this.#U=EMPTY_LINE),this.#cn();break}case`ctrl-c`:case`escape`:if(this.#Ie.idle&&this.#Le===void 0)break;this.#Ie.handleEscape(),this.#Ve=!0,this.#Le?.(),this.#cn();break;default:{let t=applyLineEditorKey(this.#U,e,{multiline:!0});t!==void 0&&(this.#U=t,this.#cn());break}}}#Pt(){this.#Ft(),this.#It(),this.#oe=setInterval(()=>{this.#re=!this.#re,this.#cn()},500),this.#oe.unref?.()}#Ft(){this.#oe&&=(clearInterval(this.#oe),void 0),this.#re=!0}#It(){this.#re=!0}#Lt(){this.#zt(),this.#se=setInterval(()=>{this.#ie+=1,this.#cn()},90),this.#se.unref?.()}#Rt(){let e=Date.now();this.#ae=e,this.#G={kind:`waiting`,startedAtMs:e},this.#Lt()}#zt(){this.#se&&=(clearInterval(this.#se),void 0)}#Bt(e){e.id!==this.#Oe?.id&&this.#Rn(),e.updateSeq=++this.#b;let t=e.subagentCallId!==void 0&&this.#S.has(e.subagentCallId)?-1:this.#m.findIndex(e=>e.subagentCallId!==void 0&&this.#S.has(e.subagentCallId));t<0?this.#m.push(e):this.#m.splice(t,0,e),e.id&&this.#h.set(e.id,e)}#Vt(e){this.#V=!0,this.#Bt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#cn()}#Ht(){let e=this.#H.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#bn(e.elapsedMs)}`,n=this.#ye??0;if(this.#be!==void 0&&this.#be>0&&n>0){let e=Math.round(n/this.#be*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#Bt({kind:`turn-stats`,body:t,live:!1})}#Ut(e){if(e==null)return;let t=this.#Be;if(this.#Be=void 0,this.#Ae===e){this.#Ae=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#Bt(n)}#Wt(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.#Bt(c),this.#cn()}#Gt(e,t){if(this.#T.has(e))return;this.#T.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.#Bt(i)}#Kt(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.#Bt(e)}#qt(e){if(e.id&&this.#g.has(e.id))return;let t=e.id?this.#h.get(e.id):void 0;if(t!==void 0){Object.assign(t,e),t.updateSeq=++this.#b;return}let n=e.subagentCallId;if(n===void 0){this.#Bt(e);return}e.id!==this.#Oe?.id&&this.#Rn(),e.updateSeq=++this.#b;let r=-1;for(let e=0;e<this.#m.length;e+=1)this.#m[e]?.subagentCallId===n&&(r=e);this.#m.splice(r<0?this.#m.length:r+1,0,e),e.id!==void 0&&this.#h.set(e.id,e)}#Jt(e){this.#m=this.#m.filter(t=>t.id!==e),this.#h.delete(e)}#Yt(){for(let e of this.#m)e.subagentCallId!==void 0&&this.#C.has(e.subagentCallId)||e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Xt(e,t,n){switch(e.type){case`step-finish`:this.#d?.recordStepUsage(e.usage),e.usage!==void 0&&this.#H.addUsage(e.usage),this.#rn(n),this.#sn(e.usage),this.#cn();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#Zt(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.#Zt(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.#Qt(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.#Qt(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#$t({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.#$t({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.#$t({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#on(e.toolCallId,n);if(r===void 0)break;this.#$t({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#on(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.#$t({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#on(e.toolCallId,n);if(r===void 0)break;this.#$t({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Wt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:if(n.cancelled=!0,!n.restoreCancelledPrompt)break;this.#Re=!0,!this.#Ve&&this.#He!==void 0&&this.#U.text.length===0&&(this.#U=lineOf(this.#He),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#sn(e.usage),this.#cn();break}}#Zt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Kt({id:e,kind:`assistant`,body:r,live:n}),this.#cn())}#Qt(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Kt({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#cn())}#$t(e,t,n){if(n.tools.set(e.toolCallId,e),this.#v.has(e.toolCallId)||this.#in(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#y.set(e.toolCallId,r);let i=this.#en(e);this.#Kt(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#an(n),this.#cn()}#en(e){e.output!==void 0&&this.#w.observeRead(e.output);let t={};this.#tn(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.#w.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}#tn(e){let t=this.#E?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#nn(e){for(let t of e.tools.keys()){if(this.#v.has(t))continue;let e=this.#y.get(t)??toolSectionId(t),n=this.#h.get(e);n?.kind===`tool`&&n.status===`running`&&(n.status=`error`,n.result=`interrupted`,n.live=!1)}}#rn(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.#Jt(r),this.#y.delete(t)}}#in(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.#Fe!==e&&(this.#Fe=e,this.#Bt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Dn(),this.#i).join(`
7
+ `),live:!1})),this.#Pe=void 0}else this.#Pe=t.length>0?t:void 0,this.#Fe=void 0;return this.#cn(),!0}#an(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)}#on(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`}}#sn(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#ve=(t??0)+(n??0)),this.#ye=t??this.#ye,this.#xe=n??this.#xe,this.#xe!=null&&this.#Ce!==void 0){let e=(Date.now()-this.#Ce)/1e3;e>0&&(this.#Se=this.#xe/e)}}#cn(){if(this.#X){if(this.#ge){this.#_e=!0;return}this.#ge=!0;try{do this.#_e=!1,this.#ln();while(this.#_e)}finally{this.#ge=!1}}}#ln(){if(!this.#X)return;if(this.#Ge!==void 0){this.#Ge.repaint();return}let e=this.#Dn(),t=this.#vn(e),n=Math.max(1,this.#On()-t.length),r=[],i=this.#A,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.#Bn(t.display))continue;let n=this.#mn(t.display,e,i);i=previousBlockOf(t.display),this.#A=i,r.push(...n),this.#k.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#Bn(t))continue;let n=this.#mn(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)}#un(){if(!this.#X)return;let e=this.#Dn(),t=this.#vn(e),n=Math.max(1,this.#On()-t.length),r=this.#A,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#m)){if(this.#Bn(t))continue;let n=this.#mn(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.#pn(),...this.#k],a)}logDisplayMode(){return this.#p}setLogDisplayMode(e){e!==this.#p&&(this.#p=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#fn(),this.#X&&this.#un())}flushDelayedDevBuildErrors(){let e=this.#De;e!==void 0&&(this.#De=void 0,this.#Bt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#cn())}#dn(){this.#le=!0,this.#ce!==void 0&&clearTimeout(this.#ce),this.#ce=setTimeout(()=>{this.#le=!1,this.#ce=void 0,this.#cn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#p)),this.#cn()}#fn(){let e=this.#Dn();this.#k.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#_,{logCoalescing:`runs`})){if(this.#Bn(n))continue;let r=this.#mn(n,e,t);t=previousBlockOf(n),this.#k.push(...r)}this.#A=t}#pn(){let e=this.#E;if(e===void 0)return[];let t={name:e.name,theme:this.#i,width:this.#Dn()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#mn(e,t,n){let r={activityPulse:this.#gn(this.#ae,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}#hn(){return this.#i.spinner[this.#ie%this.#i.spinner.length]??``}#gn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#_n(e,t){return e.indicator.kind===`spinner`?{glyph:this.#hn(),color:`yellow`}:{glyph:this.#gn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#vn(e){let n=this.#i.colors,r=[``];if(this.#je!==void 0)return r.push(...this.#je(e),``),this.#wn(r,e),r;let a=this.#Me;if(a!==void 0){let t=this.#_n(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.summary===void 0?a.hideLinesWhileQuestion===!0?[]:a.lines:[{text:a.summary.headline,tone:`success`},...a.summary.facts.map(e=>({text:`${e.label}: ${e.value}`,tone:`info`}))],content:i};return r.push(...renderFlowPanel(o,this.#i,e)),this.#Tn(r,e),r}this.#Ne!==void 0&&r.push(...renderAttentionRows(this.#Ne,e,this.#i),``),this.#Pe!==void 0&&r.push(...renderTodoPanelRows({items:this.#Pe,width:e,theme:this.#i,working:this.#W||this.#G.kind===`waiting`,pulse:this.#gn(this.#ae,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let o=renderMessageQueueRows({view:this.#Ie.view(),width:e,theme:this.#i,working:this.#W});if(o.length>0&&r.push(...o,``),this.#L){let i=this.#R===void 0?void 0:inlineCommandHint(this.#R);i===void 0&&this.#R!==void 0&&isTypeaheadOpen(this.#R)&&r.push(...renderCommandSuggestions(this.#R,this.#i,e)),this.#te&&r.push(clip(n.dim(`Press Ctrl+C again to exit`),e),``);let a=isPromptControlCommand(this.#P),o=i?n.dim(` ${i}`):``,s=[];this.#wn(s,e);let u=Math.max(1,this.#On()-1-r.length-1-s.length),f={text:this.#P,cursor:this.#F,width:e,theme:this.#i,caretVisible:this.#re,isCommand:a,ghost:o,maxRows:u};return this.#z&&this.#P.length===0&&(f.placeholder=this.#V?``:promptPlaceholder(Date.now()-this.#B)),r.push(...promptInputRows(f)),r.push(...s),r}let s=this.#G.kind===`waiting`&&this.#J===void 0;if(this.#W||s){r.push(this.#yn(e)),this.#Sn(r,e);let t=[];return this.#wn(t,e),!this.#W&&t.length>0&&r.push(``),r.push(...t),r}if(this.#U.text.length>0)return this.#Cn(r,e,{inert:!1}),this.#wn(r,e),r;let u=this.#J??(this.#q.length>0?this.#q:`Ready`),f=this.#En(),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.#wn(r,e),r}#yn(e){let t=this.#i.colors,n=this.#gn(this.#ae,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#G,i=this.#H.startedAtMs??this.#Ce??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#bn(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#bn(e){return`${formatTurnDuration(e)}${this.#xn()}`}#xn(){let{inputTokens:e,outputTokens:t}=this.#H.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#Sn(e,t){this.#W&&this.#Cn(e,t,{inert:!0})}#Cn(e,t,n){e.push(``);let r={text:this.#U.text,cursor:this.#U.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#U.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#wn(e,t){let n=this.#N===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#le&&(i.logLevel=this.#p);let a=this.#E?.serverUrl;if(a!==void 0&&this.#N===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#E?.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.#M!==void 0&&(i.vercel=this.#M),this.#N!==void 0&&(i.remote=this.#N);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#Tn(e,t){if(this.#N===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#N,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#En(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#ve,outputTokens:this.#xe,tokensPerSecond:this.#Se},this.#l);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Dn(){return Math.max(20,this.#t.columns||80)}#On(){return Math.max(8,this.#t.rows||24)}#kn(){if(this.#we!==void 0||!this.#u)return;this.#Te=``,this.#Ee=``;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.#Mn(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#d?.subscribeLogRecords(e=>this.#jn(e)),this.#we=()=>{this.#d?.unsubscribeLogRecords(),e(),t()}}#An(){let e=this.#we;e!==void 0&&(this.#we=void 0,e(),this.#Te.length>0&&(this.#d?.append({source:`stdout`,detail:this.#Te}),this.#zn(`stdout`)&&process.stdout.write(`${this.#Te}\n`),this.#Te=``),this.#Ee.length>0&&(this.#d?.append({source:`stderr`,detail:this.#Ee}),this.#zn(`stderr`)&&process.stderr.write(`${this.#Ee}\n`),this.#Ee=``))}#jn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#Pn(`[eve:${e.namespace}] ${e.message}${t}`),this.#cn()}#Mn(e,t){let n=(e===`stdout`?this.#Te:this.#Ee)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Te=``,this.#d?.append({source:e,detail:n.trimEnd()}),this.#Nn(n.trimEnd()),this.#cn();return}let r=n.lastIndexOf(`
8
+ `),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Te=i:this.#Ee=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.#Nn(a):this.#Pn(a),this.#cn())}#Nn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
9
+ `);t=[],e.trim().length!==0&&this.#Bt({kind:`log`,title:`stdout`,body:e,live:!0})};for(let n of e.split(`
10
+ `)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Bt({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#In(r,n.trimEnd())}flushPending()}#Pn(e){let t=e.split(`
11
+ `),n=t.findIndex(e=>parseDevRebuildLogLine(e.trimEnd())?.kind===`failed`);if(n===-1){if(this.#d===void 0){this.#Bt({kind:`log`,title:`stderr`,body:e,live:!0});return}let t=presentDiagnostic(e,this.#d.displayPath);if(t.kind===`inline`){this.#Bt({kind:`log`,title:`stderr`,body:t.text,live:!0});return}this.#Bt({kind:`log`,title:`stderr`,body:formatStoredDiagnostic(t),logVisibility:`stderr-only`,live:!0}),this.#Bt({kind:`log`,title:`stderr`,body:e,logVisibility:`all-only`,live:!0});return}let r=t.slice(0,n).join(`
12
+ `);r.trim().length>0&&this.#Bt({kind:`log`,title:`stderr`,body:r,live:!0});let i=t.slice(n).join(`
13
+ `);this.#Fn(i)}#Fn(e){if(this.#p===`all`){if(e.trim().length===0)return;this.#Bt({kind:`log`,title:`stderr`,body:e,live:!0});return}this.#De=e}#In(e,t){let n=this.#Ln();if(e.kind===`failed`){this.#Fn(t);return}if(e.kind===`rebuilding`){let t=summarizeChangedFiles(e.events,e.more);if(n!==void 0){n.state.summary=t,n.block.body=formatDevRebuildStatus(t,`rebuilding`);return}let r=`dev-rebuild:${this.#ke}`;this.#ke+=1,this.#Oe={id:r,summary:t},this.#Bt({kind:`log`,id:r,title:`stdout`,body:formatDevRebuildStatus(t,`rebuilding`),live:!0});return}if(n!==void 0){n.block.body=formatDevRebuildStatus(n.state.summary,e.kind),e.kind===`rebuilt`&&(this.#De=void 0);return}e.kind===`rebuilt`&&(this.#De=void 0),this.#Bt({kind:`log`,title:`stdout`,body:t,live:!0})}#Ln(){let e=this.#Oe;if(e===void 0)return;let t=this.#h.get(e.id);if(!(t===void 0||t.live!==!0))return{state:e,block:t}}#Rn(){let e=this.#Oe;if(e===void 0)return;this.#Oe=void 0;let t=this.#h.get(e.id);t!==void 0&&(t.live=!1)}#zn(e){switch(this.#p){case`none`:return!1;case`stderr`:return e===`stderr`;case`sandbox`:return e===`sandbox`;case`all`:return!0}}#Bn(e){return e.kind===`sandbox`?!this.#zn(`sandbox`):e.kind===`log`?e.logVisibility===`stderr-only`?this.#p!==`stderr`:e.logVisibility===`all-only`?this.#p!==`all`:!this.#zn(e.title===`stderr`?`stderr`:`stdout`):!1}};function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}async function*iterateTUIStream(e){if(e instanceof ReadableStream){let t=e.getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}return}yield*e}function clip(e,t){return clipVisible(e,t)}function promptInputRows({text:e,cursor:t,width:n,theme:r,caretVisible:i,isCommand:a,ghost:o,maxRows:s,placeholder:c,inert:l}){let u=r.colors;if(e.length===0&&c!==void 0){let e=renderInputWithBlockCursor({...visibleLine({text:c,cursor:0},Math.max(1,n-3),r.glyph.ellipsis),visible:i,inverse:u.inverse,render:e=>u.dim(renderInputText(e))});return[clip(`${u.dim(r.glyph.promptIdle)} ${e}`,n),``]}let style=e=>{let t=renderInputText(e);return a&&t.length>0?u.blue(t):t},d=layoutPromptInput({text:e,cursor:t}),f=Math.min(Math.max(1,s),d.rows.length),p=Math.max(0,Math.min(d.caretRow-f+1,d.rows.length-f)),m=l===!0?u.dim(r.glyph.prompt):u.cyan(r.glyph.prompt),h=u.dim(r.glyph.ellipsis),g=Math.max(1,n-3),_=[];for(let e=p;e<p+f;e+=1){let t=d.rows[e],a=e===0?m:` `;(e===p&&p>0||e===p+f-1&&p+f<d.rows.length)&&(a=h);let s;if(e===d.caretRow){let{before:e,under:n,after:a}=visibleLine({text:t.text,cursor:d.caretOffset},g,r.glyph.ellipsis);s=renderInputWithBlockCursor({before:e,under:n,after:a,visible:i,inverse:u.inverse,render:style}),o.length>0&&d.rows.length===1&&(s+=o)}else s=style(t.text);_.push(clip(`${a} ${s}`,n))}return _.push(``),_}function previousBlockOf(e){let t={kind:e.kind};return e.title!==void 0&&(t.title=e.title),t}function isActiveToolStatus(e){return e===`running`||e===`approval`}function applyCohortLiveness(e){let t=e.some(e=>e.active);for(let n of e)n.block.live=t||n.active}function leadsWithGap(e,t){if(e.kind===`tool`&&(t?.kind===`user`||t?.kind===`assistant`||t?.kind===`question`))return!0;if(e.kind===`sandbox`&&t?.kind===`sandbox`)return!1;if(t?.kind===`sandbox`&&e.kind!==`sandbox`||t?.kind===`log`)return!0;switch(e.kind){case`user`:case`assistant`:case`reasoning`:case`subagent`:case`error`:case`notice`:case`question`:case`connection-auth`:case`sandbox`:case`log`:case`command`:case`warning`:case`flow`:case`turn-stats`:case`session-boundary`:case`todo-list`:case`agent-header`:return!0;default:return!1}}function parseSandboxLogLine(e){let t=e.trim();if(!t.startsWith(`eve: `))return;let n=t.slice(5);return/\bsandbox\b/i.test(n)&&!isLowValueSandboxLogLine(n)?n:void 0}function isLowValueSandboxLogLine(e){return/^initializing (?:\d+ )?sandbox templates?\b/i.test(e)||/^initialized \d+ sandbox\b/i.test(e)||/^reused cached sandbox template\b/i.test(e)||/^sandbox template "[^"]+" \([^)]+\): (checking|reusing|loading microsandbox runtime|microsandbox runtime ready)\b/i.test(e)}function clipLiveRows(e,t,n,r){if(e.length<=t)return[...e];if(t<=1)return[clip(hiddenRowsMarker(e.length,r),n)];let i=t-1;return[clip(hiddenRowsMarker(e.length-i,r),n),...e.slice(e.length-i)]}function hiddenRowsMarker(e,t){let n=e.toLocaleString(),r=e===1?`row`:`rows`;return t.colors.dim(`${t.glyph.dot} ${t.glyph.ellipsis} ${n} earlier ${r} hidden while streaming`)}function collapseReasoning(e,t){switch(e){case`collapsed`:return!0;case`auto-collapsed`:return!t;default:return!1}}function renderNativeToolBlock(e,t,n,r){let i=e.preparing===!0?presentPreparingTool(e.toolName,r):presentTool(e.toolName,e.input,r),a={id:t,kind:`tool`,title:stripTerminalControls(i.title),subtitle:stripTerminalControls(i.subtitle),status:e.status,live:e.status===`running`||e.status===`approval`,expanded:n,toolInput:e.input,toolName:e.toolName,toolGroup:i.group};return i.doneTitle!==void 0&&(a.doneTitle=stripTerminalControls(i.doneTitle)),i.detail!==void 0&&(a.detailLines=i.detail,a.keepDetailWhenDone=i.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(a.result=stripTerminalControls(e.errorText)):(a.result=i.summarizeResult(e.output),a.toolOutput=e.output),a}function writeExistedFlag(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.existed;return typeof t==`boolean`?t:void 0}function subagentToolStatus(e){switch(e){case`preparing`:return`running`;case`approval-requested`:return`approval`;case`executing`:return`running`;case`done`:return`done`;case`failed`:return`error`;case`rejected`:return`denied`}}function formatToolApprovalTitle(e){return stripTerminalControls(e.title??e.toolName)}function toolSectionId(e){return`tool:${e}`}function questionSectionId(e){return`question:${e}`}function subagentHeaderId(e){return`subagent:${e}:header`}function subagentStepSectionId(e,t){return`subagent:${e}:step:${t}`}function subagentToolSectionId(e,t){return`subagent:${e}:tool:${t}`}function connectionAuthSectionId(e){return`connection-auth:${e}`}function connectionAuthTerminalMessage(e){switch(e){case`authorized`:return`Authorization complete`;case`declined`:return`Authorization declined`;case`failed`:return`Authorization failed`;case`timed-out`:return`Authorization timed out`;case`required`:case`pending`:return}}function formatConnectionAuthContent(e,t){let n=[];if(t!==void 0)n.push(t);else{let t=stripTerminalControls(e.description);t.length>0&&n.push(t);let r=e.challenge;r?.url&&n.push(`URL: ${stripTerminalControls(r.url)}`),r?.userCode&&n.push(`Code: ${stripTerminalControls(r.userCode)}`),r?.expiresAt&&n.push(`Expires: ${stripTerminalControls(r.expiresAt)}`),r?.instructions&&n.push(stripTerminalControls(r.instructions))}if(e.reason!==void 0){let t=stripTerminalControls(e.reason);t.length>0&&n.push(`Reason: ${t}`)}return n.join(`
14
14
  `)}function formatQuestionContent(e,t,n){let r=n.colors,i=[],a=e.options??[];if(a.length>0){for(let[e,o]of a.entries()){let a=stripTerminalControls(o.label),s=o.description===void 0?``:stripTerminalControls(o.description),c=t===e,l=s.length>0?`${c?` `:` `}${r.dim(`— ${s}`)}`:``,u=renderCursorRow(c?`${n.glyph.selectedPointer} ${a}`:` ${a}`,c,r);i.push(`${u}${l}`)}if(e.allowFreeform===!0){let e=t===a.length,o=`Type your own answer`,s=e?`${n.glyph.selectedPointer} ${o}`:` ${r.dim(o)}`;i.push(renderCursorRow(s,e,r))}}else i.push(r.dim(` (type your answer)`));return i.join(`
15
15
  `)}function resolveQuestionText(e,t){let n=e.trim();if(n.length===0)return;let r=n.toLowerCase(),i=t.options??[];if(i.length>0){let e=matchQuestionOption(r,i);if(e!==void 0)return{optionId:e.id,label:e.label}}if(t.allowFreeform===!0||i.length===0)return{text:n,label:n}}function matchQuestionOption(e,t){let n=t.find(t=>t.id.toLowerCase()===e);if(n!==void 0)return n;let r=t.find(t=>t.label.toLowerCase()===e);if(r!==void 0)return r;let i=Number(e);if(Number.isInteger(i)&&i>0&&i<=t.length)return t[i-1]}export{TerminalRenderer};
@@ -1 +1 @@
1
- import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{diffWriteDetail}from"./line-diff.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";const WRITE_FILE_VERB=`Write`,DELEGATE_VERB=`Delegate`,FINAL_OUTPUT_TITLE=`Return final output`,BUILTIN_TOOL_COPY={agent:{verb:`Delegate`,pastVerb:`Delegated`,argKey:`message`,singularNoun:`task`,pluralNoun:`tasks`},ask_question:{verb:`Ask`,pastVerb:`Asked`,argKey:`prompt`,singularNoun:`question`,pluralNoun:`questions`},bash:{verb:`Run`,pastVerb:`Ran`,argKey:`command`,singularNoun:`command`,pluralNoun:`commands`},connection_search:{verb:`Discover`,pastVerb:`Discovered`,argKey:`keywords`,singularNoun:`tool search`,pluralNoun:`tool searches`},glob:{verb:`Glob`,pastVerb:`Globbed`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},grep:{verb:`Grep`,pastVerb:`Grepped`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},load_skill:{verb:`Load`,pastVerb:`Loaded`,argKey:`skill`,singularNoun:`skill`,pluralNoun:`skills`},read_file:{verb:`Read`,pastVerb:`Read`,argKey:`filePath`,singularNoun:`file`,pluralNoun:`files`},web_fetch:{verb:`Fetch`,pastVerb:`Fetched`,argKey:`url`,singularNoun:`URL`,pluralNoun:`URLs`},web_search:{verb:`Search`,pastVerb:`Searched`,argKey:`query`,extractItem:e=>salientArg(e,`objective`)??salientArg(e,`search_query`)??salientArg(e,`searchQuery`)??webSearchActionArg(e),singularNoun:`query`,pluralNoun:`queries`}};function presentWriteFileTool(a,o,s){let c=readWriteFileInput(a,o);if(c===void 0)return{title:a,subtitle:summarizeToolArgs(o),summarizeResult:summarizeToolResult};let l=diffWriteDetail(s?.previousContent,c.content,s?.existed).map(e=>e.kind===`gap`?e:{...e,text:stripTerminalControls(e.text)});return{title:`${WRITE_FILE_VERB} ${salientLine(c.path)??c.path}`,doneTitle:`Wrote ${salientLine(c.path)??c.path}`,subtitle:``,summarizeResult:()=>void 0,detail:l,keepDetailWhenDone:!0}}function readWriteFileInput(e,t){if(toolBaseName(e)!==`write_file`||typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.filePath,i=n.content;if(!(typeof r!=`string`||r.trim().length===0)&&typeof i==`string`)return{path:r,content:i}}function presentTool(n,r,i){let c=toolBaseName(n);if(c===`todo`)return presentTodoTool(r);if(c===`write_file`)return presentWriteFileTool(n,r,i);if(i?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${c}`,doneTitle:`Delegated ${c}`,subtitle:salientArg(r,`message`)??``,summarizeResult:()=>void 0};if(c===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};let l=BUILTIN_TOOL_COPY[c];if(l!==void 0){let e=salientArg(r,l.argKey)??l.extractItem?.(r);if(e!==void 0)return{title:`${l.verb} ${e}`,doneTitle:`${l.pastVerb} ${e}`,subtitle:``,summarizeResult:()=>void 0,group:{verb:l.verb,pastVerb:l.pastVerb,singularNoun:l.singularNoun,pluralNoun:l.pluralNoun,item:e}}}return{title:n,subtitle:summarizeToolArgs(r),summarizeResult:summarizeToolResult}}function presentPreparingTool(e,t){let n=toolBaseName(e);if(n===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};if(t?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${n} …`,subtitle:``,summarizeResult:()=>void 0};let r=n===`write_file`?WRITE_FILE_VERB:BUILTIN_TOOL_COPY[n]?.verb;return{title:r===void 0?e:`${r} …`,subtitle:r===void 0?`preparing…`:``,summarizeResult:()=>void 0}}function isPanelRoutedTool(e){let t=toolBaseName(e);return t===`todo`||t===`ask_question`}function toolBaseName(e){return e.split(/[.:/]/u).at(-1)??e}function presentTodoTool(e){let t=typeof e==`object`&&e&&!Array.isArray(e)?e.todos:void 0;return Array.isArray(t)?{title:`Update todo list`,subtitle:`${t.length} task${t.length===1?``:`s`}`,summarizeResult:()=>void 0}:{title:`Read todo list`,subtitle:``,summarizeResult:()=>void 0}}function webSearchActionArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.action;if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.queries;if(Array.isArray(r)){let e=r.filter(e=>typeof e==`string`).map(salientLine).filter(e=>e!==void 0).join(`, `);if(e.length>0)return e}for(let e of[`query`,`url`,`pattern`]){let t=n[e];if(typeof t==`string`){let e=salientLine(t);if(e!==void 0)return e}}}function salientArg(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];if(typeof n==`string`)return salientLine(n)}function salientLine(e){let t=stripTerminalControls(e).split(/\r?\n/u).find(e=>e.trim().length>0)?.trim()??``;return t.length>0?t:void 0}export{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName};
1
+ import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{diffWriteDetail}from"./line-diff.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";const WRITE_FILE_VERB=`Write`,DELEGATE_VERB=`Delegate`,FINAL_OUTPUT_TITLE=`Return final output`,BUILTIN_TOOL_COPY={agent:{verb:`Delegate`,pastVerb:`Delegated`,argKey:`message`,singularNoun:`task`,pluralNoun:`tasks`},ask_question:{verb:`Ask`,pastVerb:`Asked`,argKey:`prompt`,singularNoun:`question`,pluralNoun:`questions`},bash:{verb:`Run`,pastVerb:`Ran`,argKey:`command`,singularNoun:`command`,pluralNoun:`commands`},connection_search:{verb:`Discover`,pastVerb:`Discovered`,argKey:`keywords`,singularNoun:`tool search`,pluralNoun:`tool searches`},glob:{verb:`Glob`,pastVerb:`Globbed`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},grep:{verb:`Grep`,pastVerb:`Grepped`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},load_skill:{verb:`Load`,pastVerb:`Loaded`,argKey:`skill`,singularNoun:`skill`,pluralNoun:`skills`},read_file:{verb:`Read`,pastVerb:`Read`,argKey:`filePath`,singularNoun:`file`,pluralNoun:`files`},task_cancel:{verb:`Cancel`,pastVerb:`Cancelled`,argKey:`taskIds`,extractItem:taskIdsArg,singularNoun:`task`,pluralNoun:`tasks`},task_peek:{verb:`Check`,pastVerb:`Checked`,argKey:`taskIds`,extractItem:taskIdsArg,singularNoun:`task`,pluralNoun:`tasks`},task_send:{verb:`Send`,pastVerb:`Sent`,argKey:`taskId`,singularNoun:`task`,pluralNoun:`tasks`},task_sleep:{verb:`Pause`,pastVerb:`Paused`,argKey:`seconds`,extractItem:sleepSecondsArg,singularNoun:`pause`,pluralNoun:`pauses`},web_fetch:{verb:`Fetch`,pastVerb:`Fetched`,argKey:`url`,singularNoun:`URL`,pluralNoun:`URLs`},web_search:{verb:`Search`,pastVerb:`Searched`,argKey:`query`,extractItem:e=>salientArg(e,`objective`)??salientArg(e,`search_query`)??salientArg(e,`searchQuery`)??webSearchActionArg(e),singularNoun:`query`,pluralNoun:`queries`}};function presentWriteFileTool(a,o,s){let c=readWriteFileInput(a,o);if(c===void 0)return{title:a,subtitle:summarizeToolArgs(o),summarizeResult:summarizeToolResult};let l=diffWriteDetail(s?.previousContent,c.content,s?.existed).map(e=>e.kind===`gap`?e:{...e,text:stripTerminalControls(e.text)});return{title:`${WRITE_FILE_VERB} ${salientLine(c.path)??c.path}`,doneTitle:`Wrote ${salientLine(c.path)??c.path}`,subtitle:``,summarizeResult:()=>void 0,detail:l,keepDetailWhenDone:!0}}function readWriteFileInput(e,t){if(toolBaseName(e)!==`write_file`||typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.filePath,i=n.content;if(!(typeof r!=`string`||r.trim().length===0)&&typeof i==`string`)return{path:r,content:i}}function presentTool(n,r,i){let c=toolBaseName(n);if(c===`todo`)return presentTodoTool(r);if(c===`write_file`)return presentWriteFileTool(n,r,i);if(i?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${c}`,doneTitle:`Delegated ${c}`,subtitle:salientArg(r,`message`)??``,summarizeResult:()=>void 0};if(c===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};let l=BUILTIN_TOOL_COPY[c];if(l!==void 0){let e=salientArg(r,l.argKey)??l.extractItem?.(r);if(e!==void 0)return{title:`${l.verb} ${e}`,doneTitle:`${l.pastVerb} ${e}`,subtitle:``,summarizeResult:()=>void 0,group:{verb:l.verb,pastVerb:l.pastVerb,singularNoun:l.singularNoun,pluralNoun:l.pluralNoun,item:e}}}return{title:n,subtitle:summarizeToolArgs(r),summarizeResult:summarizeToolResult}}function presentPreparingTool(e,t){let n=toolBaseName(e);if(n===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};if(t?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${n} …`,subtitle:``,summarizeResult:()=>void 0};let r=n===`write_file`?WRITE_FILE_VERB:BUILTIN_TOOL_COPY[n]?.verb;return{title:r===void 0?e:`${r} …`,subtitle:r===void 0?`preparing…`:``,summarizeResult:()=>void 0}}function isPanelRoutedTool(e){let t=toolBaseName(e);return t===`todo`||t===`ask_question`}function toolBaseName(e){return e.split(/[.:/]/u).at(-1)??e}function presentTodoTool(e){let t=typeof e==`object`&&e&&!Array.isArray(e)?e.todos:void 0;return Array.isArray(t)?{title:`Update todo list`,subtitle:`${t.length} task${t.length===1?``:`s`}`,summarizeResult:()=>void 0}:{title:`Read todo list`,subtitle:``,summarizeResult:()=>void 0}}function webSearchActionArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.action;if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.queries;if(Array.isArray(r)){let e=r.filter(e=>typeof e==`string`).map(salientLine).filter(e=>e!==void 0).join(`, `);if(e.length>0)return e}for(let e of[`query`,`url`,`pattern`]){let t=n[e];if(typeof t==`string`){let e=salientLine(t);if(e!==void 0)return e}}}function taskIdsArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.taskIds;if(!Array.isArray(t))return;let n=t.filter(e=>typeof e==`string`);if(n.length!==0)return salientLine(n.join(`, `))}function sleepSecondsArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.seconds;if(!(typeof t!=`number`||!Number.isFinite(t)))return`${String(t)}s`}function salientArg(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];if(typeof n==`string`)return salientLine(n)}function salientLine(e){let t=stripTerminalControls(e).split(/\r?\n/u).find(e=>e.trim().length>0)?.trim()??``;return t.length>0?t:void 0}export{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName};
@@ -15,6 +15,8 @@ interface ResolvedStreamReconnectPolicy {
15
15
  */
16
16
  interface FollowStreamInput {
17
17
  readonly host: string;
18
+ /** Keep reconnecting after empty streams until the consumer aborts or stops iteration. */
19
+ readonly keepAlive?: boolean;
18
20
  readonly streamReconnectPolicy?: StreamReconnectPolicy;
19
21
  readonly resolveHeaders: () => Promise<Headers>;
20
22
  readonly redirect?: ClientRedirectPolicy;
@@ -1 +1 @@
1
- import{createEveSessionStreamRoutePath}from"#protocol/routes.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let t=e;return{retryableErrorStatuses:t?.retryableErrorStatuses?new Set(t.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(t?.streamIdleReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy),streamOpenReconnectPolicy:resolveRetryPolicy(t?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let n=resolveStreamReconnectPolicy(e.streamReconnectPolicy),r=n.streamIdleReconnectPolicy,a=e.startIndex,o=r.baseDelayMs,s=0,c=!0,l;for(;;){let u;try{u=await openStreamBody({...e,retryPolicy:n,startIndex:a,requestTailIndex:e.follow===!1&&l===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if(e.follow===!1&&l===void 0&&(l=u.tailIndex,l===void 0))throw await u.body.cancel().catch(()=>{}),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(l!==void 0&&a>l){await u.body.cancel().catch(()=>{});return}let d=!1;try{for await(let e of readNdjsonStream(u.body))if(a+=1,d=!0,o=r.baseDelayMs,s=0,yield e,l!==void 0&&a>l)return}catch(e){if(!isStreamDisconnectError(e))throw e}if(e.signal?.aborted||e.startIndex<0||r.maxAttempts===0||!d&&!c&&(s+=1)>=r.maxAttempts||(c=!1,await sleep(o,e.signal),e.signal?.aborted))return;o=Math.min(o*2,r.maxDelayMs)}}async function openStreamBody(t){let i=t.retryPolicy??DEFAULT_STREAM_RECONNECT_POLICY,o=i.streamOpenReconnectPolicy,s,c,l,u=o.baseDelayMs,d={};t.startIndex!==0&&(d.startIndex=String(t.startIndex)),t.requestTailIndex===!0&&(d.includeTailIndex=`1`);for(let a=0;a<o.maxAttempts;a+=1){let f=createClientUrl(t.host,createEveSessionStreamRoutePath(t.sessionId),Object.keys(d).length>0?d:void 0),p=await t.resolveHeaders(),m;try{m=await fetch(f,{cache:`no-store`,headers:p,redirect:t.redirect,signal:t.signal??null})}catch(e){if(t.signal?.aborted||!isStreamDisconnectError(e)||a===o.maxAttempts-1)throw e;await sleep(u,t.signal),u=Math.min(u*2,o.maxDelayMs);continue}if(m.ok){if(!m.body)throw new ClientError(m.status,`Response body is null.`,m.headers);return{body:m.body,tailIndex:parseTailIndexHeader(m.headers)}}if(s=m.status,c=await m.text(),l=m.headers,!i.retryableErrorStatuses.has(m.status))throw new ClientError(m.status,c,m.headers);a<o.maxAttempts-1&&(await sleep(u,t.signal),u=Math.min(u*2,o.maxDelayMs))}throw new ClientError(s??0,c??`Failed to open message stream.`,l)}function parseTailIndexHeader(e){let n=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(n===null||!/^-?\d+$/.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r:void 0}async function sleep(e,t){t?.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e);t?.addEventListener(`abort`,onAbort,{once:!0})})}export{followStreamIterable,openStreamBody};
1
+ import{createEveSessionStreamRoutePath}from"#protocol/routes.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let t=e;return{retryableErrorStatuses:t?.retryableErrorStatuses?new Set(t.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(t?.streamIdleReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy),streamOpenReconnectPolicy:resolveRetryPolicy(t?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let i=resolveStreamReconnectPolicy(e.streamReconnectPolicy),a=i.streamIdleReconnectPolicy,o=e.startIndex,s=a.baseDelayMs,c=0,l=!0,u;for(;;){let d;try{d=await openStreamBody({...e,retryPolicy:i,startIndex:o,requestTailIndex:e.follow===!1&&u===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if(e.follow===!1&&u===void 0&&(u=d.tailIndex,u===void 0))throw await d.body.cancel().catch(()=>{}),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(u!==void 0&&o>u){await d.body.cancel().catch(()=>{});return}let f=!1;try{for await(let e of readNdjsonStream(d.body))if(o+=1,f=!0,s=a.baseDelayMs,c=0,yield e,u!==void 0&&o>u)return}catch(e){if(!isStreamDisconnectError(e))throw e}if(e.signal?.aborted||e.startIndex<0||a.maxAttempts===0||e.keepAlive!==!0&&!f&&!l&&(c+=1)>=a.maxAttempts||(l=!1,await sleep(s,e.signal),e.signal?.aborted))return;s=Math.min(s*2,a.maxDelayMs)}}async function openStreamBody(t){let r=t.retryPolicy??DEFAULT_STREAM_RECONNECT_POLICY,s=r.streamOpenReconnectPolicy,c,l,u,d=s.baseDelayMs,f={};t.startIndex!==0&&(f.startIndex=String(t.startIndex)),t.requestTailIndex===!0&&(f.includeTailIndex=`1`);for(let o=0;o<s.maxAttempts;o+=1){let p=createClientUrl(t.host,createEveSessionStreamRoutePath(t.sessionId),Object.keys(f).length>0?f:void 0),m=await t.resolveHeaders(),h;try{h=await fetch(p,{cache:`no-store`,headers:m,redirect:t.redirect,signal:t.signal??null})}catch(e){if(t.signal?.aborted||!isStreamDisconnectError(e)||o===s.maxAttempts-1)throw e;await sleep(d,t.signal),d=Math.min(d*2,s.maxDelayMs);continue}if(h.ok){if(!h.body)throw new ClientError(h.status,`Response body is null.`,h.headers);return{body:h.body,tailIndex:parseTailIndexHeader(h.headers)}}if(c=h.status,l=await h.text(),u=h.headers,!r.retryableErrorStatuses.has(h.status))throw new ClientError(h.status,l,h.headers);o<s.maxAttempts-1&&(await sleep(d,t.signal),d=Math.min(d*2,s.maxDelayMs))}throw new ClientError(c??0,l??`Failed to open message stream.`,u)}function parseTailIndexHeader(e){let n=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(n===null||!/^-?\d+$/.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r:void 0}async function sleep(e,t){t?.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e);t?.addEventListener(`abort`,onAbort,{once:!0})})}export{followStreamIterable,openStreamBody};
@@ -1 +1 @@
1
- import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(t,n){let r=await postTurn(t,EVE_SESSION_ROUTE_PATH,n,!0),i=await readSessionId(r),a=new ClientSession(t,{sessionId:i,streamIndex:0});return{response:a.#r(r,n,0),session:a}}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#o({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e})}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e})}async#n(e){let n=this.#t.streamIndex,r=await postTurn(this.#e,createEveSessionRoutePath(this.#t.sessionId),e,!1);if(await readSessionId(r,this.#t.sessionId)!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);return this.#r(r,e,n)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}#r(e,t,n){return e.body?.cancel().catch(()=>{}),new MessageResponse({createStream:()=>this.#i(n,t),sessionId:this.#t.sessionId})}async*#i(e,t){let n=0;try{for await(let i of this.#o({headers:t.headers,signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy}))if(n+=1,yield i,isCurrentTurnBoundaryEvent(i))break}finally{this.#t={sessionId:this.#t.sessionId,streamIndex:e+n}}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;try{for await(let r of this.#o({follow:e?.follow,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,yield r}finally{t>=0&&(this.#t={sessionId:this.#t.sessionId,streamIndex:t+n})}}#o(e){return followStreamIterable({follow:e.follow,host:this.#e.host,resolveHeaders:()=>this.#e.resolveHeaders(e.headers),redirect:this.#e.redirect,sessionId:this.#t.sessionId,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy})}};async function postTurn(e,t,n,r){let o=createMessageBody(n,r);if(o===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let s=await e.resolveHeaders(n.headers);s.set(`content-type`,`application/json`);let c=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(o),headers:s,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!c.ok){let e=await c.text();throw new ClientError(c.status,e,c.headers)}return c}async function readSessionId(e,t){let r=await e.json(),i=(typeof r.sessionId==`string`?r.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!i)throw Error(`Message route did not return a session id.`);return i}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession};
1
+ import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(t,n){let r=await postTurn(t,EVE_SESSION_ROUTE_PATH,n,!0),i=await readSessionId(r),a=new ClientSession(t,{sessionId:i,streamIndex:0});return{response:a.#r(r,n,0),session:a}}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#o({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e})}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e})}async#n(e){let n=this.#t.streamIndex,r=await postTurn(this.#e,createEveSessionRoutePath(this.#t.sessionId),e,!1);if(await readSessionId(r,this.#t.sessionId)!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);return this.#r(r,e,n)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}#r(e,t,n){return e.body?.cancel().catch(()=>{}),new MessageResponse({createStream:()=>this.#i(n,t),sessionId:this.#t.sessionId})}async*#i(e,t){let n=0;try{for await(let i of this.#o({headers:t.headers,keepAlive:shouldKeepActiveTurnAlive(t.streamReconnectPolicy),signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy}))if(n+=1,yield i,isCurrentTurnBoundaryEvent(i))break}finally{this.#t={sessionId:this.#t.sessionId,streamIndex:e+n}}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;try{for await(let r of this.#o({follow:e?.follow,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,yield r}finally{t>=0&&(this.#t={sessionId:this.#t.sessionId,streamIndex:t+n})}}#o(e){return followStreamIterable({follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.headers),redirect:this.#e.redirect,sessionId:this.#t.sessionId,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy})}};function shouldKeepActiveTurnAlive(e){return e&&`reconnect`in e?!1:e?.streamIdleReconnectPolicy?.maxAttempts===void 0}async function postTurn(e,t,n,r){let o=createMessageBody(n,r);if(o===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let s=await e.resolveHeaders(n.headers);s.set(`content-type`,`application/json`);let c=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(o),headers:s,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!c.ok){let e=await c.text();throw new ClientError(c.status,e,c.headers)}return c}async function readSessionId(e,t){let r=await e.json(),i=(typeof r.sessionId==`string`?r.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!i)throw Error(`Message route did not return a session id.`);return i}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession};
@@ -18,6 +18,7 @@
18
18
  "@types/json-schema": "7.0.15",
19
19
  "marked": "17.0.6",
20
20
  "@ai-sdk/mcp": "2.0.29",
21
+ "@modelcontextprotocol/server": "2.0.0",
21
22
  "@ai-sdk/openai": "4.0.36",
22
23
  "@opentelemetry/api": "1.9.1",
23
24
  "@opentelemetry/otlp-transformer": "0.214.0",
@@ -44,5 +45,5 @@
44
45
  "zod": "4.4.3",
45
46
  "zod-validation-error": "5.0.0"
46
47
  },
47
- "scriptHash": "d687f51a324a012e639ff22d5f4ab77097037ec7ccc7e7817507c0f5a8e7d630"
48
+ "scriptHash": "bd91763436d47835c8e6d32a2a7949344c7e96657eda8bb10b7872e9464e2e7b"
48
49
  }