eve 1.0.0-rc.8 → 1.0.0-rc.9
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.
- package/CHANGELOG.md +13 -21
- package/dist/src/acp/adapter.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +2 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/context/container.js +1 -1
- package/dist/src/context/workflow-step.d.ts +3 -0
- package/dist/src/context/workflow-step.js +1 -0
- package/dist/src/execution/dynamic-workflow/tool.js +1 -1
- package/dist/src/execution/tools/agent-router-workflow.js +1 -1
- package/dist/src/execution/tools/workflow/ask.js +1 -1
- package/dist/src/execution/tools/workflow/owner-inbox.js +1 -1
- package/dist/src/execution/tools/workflow/step-execution.d.ts +2 -0
- package/dist/src/execution/tools/workflow/step-execution.js +1 -1
- package/dist/src/extensions/git/extension/lib/attribution.d.ts +3 -1
- package/dist/src/extensions/git/extension/lib/attribution.js +1 -1
- package/dist/src/extensions/git/extension/lib/github-shell.d.ts +15 -0
- package/dist/src/extensions/git/extension/lib/github-shell.js +1 -1
- package/dist/src/extensions/git/extension/lib/repository-root.d.ts +7 -1
- package/dist/src/extensions/git/extension/lib/repository-root.js +1 -1
- package/dist/src/extensions/git/extension/lib/sandbox-lease-lock.js +3 -3
- package/dist/src/extensions/git/extension/lib/sandbox.d.ts +1 -1
- package/dist/src/extensions/git/extension/lib/sandbox.js +1 -1
- package/dist/src/harness/compaction/config.js +1 -1
- package/dist/src/harness/compaction/engine.d.ts +18 -7
- package/dist/src/harness/compaction/engine.js +2 -2
- package/dist/src/harness/compaction/step.js +1 -1
- package/dist/src/harness/step/after-model.js +1 -1
- package/dist/src/harness/types.d.ts +14 -0
- package/dist/src/internal/application/stamped-package-version.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-transformer.js +1 -1
- package/dist/src/protocol/interaction-json.d.ts +1 -0
- package/dist/src/protocol/session-events/families/interaction.d.ts +6 -0
- package/dist/src/protocol/session-events/families/interaction.js +1 -1
- package/dist/src/public/channels/discord/hitl.js +1 -1
- package/dist/src/public/channels/slack/hitl.d.ts +2 -0
- package/dist/src/public/channels/slack/hitl.js +1 -1
- package/dist/src/public/channels/teams/hitl.js +1 -1
- package/dist/src/public/definitions/state.d.ts +2 -1
- package/dist/src/public/definitions/state.js +1 -1
- package/dist/src/runtime/subagents/workflow.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/tools/definition.d.ts +1 -1
- package/dist/src/tools/provided/ask-question-workflow.js +1 -1
- package/dist/src/tools/provided/sleep-workflow.js +1 -1
- package/docs/channels/discord/reference.mdx +2 -0
- package/docs/channels/slack/index.mdx +2 -0
- package/docs/channels/slack/reference.mdx +2 -0
- package/docs/channels/teams/reference.mdx +1 -1
- package/docs/code-extension.mdx +1 -1
- package/docs/concepts/default-harness.md +2 -2
- package/docs/concepts/state.md +44 -0
- package/docs/patterns/ambient-listening.mdx +300 -0
- package/docs/patterns/meta.json +1 -0
- package/docs/tools/workflows.mdx +23 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,29 +1,21 @@
|
|
|
1
|
-
# eve 1.0.0-rc.
|
|
1
|
+
# eve 1.0.0-rc.9
|
|
2
2
|
|
|
3
|
-
Released 2026-11-10 · [Compare with 1.0.0-rc.
|
|
3
|
+
Released 2026-11-10 · [Compare with 1.0.0-rc.8](https://github.com/vercel/eve/compare/eve%401.0.0-rc.8...eve%401.0.0-rc.9)
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
|
|
9
|
-
-
|
|
10
|
-
|
|
7
|
+
- Preselect an option in a `display: "select"` question by passing `initialOptionId` to `ctx.ask`.
|
|
8
|
+
Slack, Discord, Microsoft Teams, and the `eve dev` terminal UI start with that option selected, and ACP clients receive it as the form field's default. On Slack and Discord, a **Use** button submits the preselected option, because those platforms send nothing when a person keeps the current selection. When `initialOptionId` matches none of the question's `options`, `ctx.ask` throws a `TypeError`. ([#6202](https://github.com/vercel/eve/pull/6202))
|
|
9
|
+
- `executeGitHubShell` now throws `GitHubCommandInputError` when a command's own input is refused, so a custom GitHub tool can tell the agent's mistakes from real failures.
|
|
10
|
+
Shell syntax, an invalid repository, a `workingDirectory` outside the workspace, a `gh-signed-commit` directory that is not a repository root, and a missing `--body-file` used to throw a plain `Error`, like a missing configuration or an empty Connect token. Detect the new error with `isGitHubCommandInputError(error)` from `eve/extensions/git/sandbox`; its messages are unchanged. ([#6181](https://github.com/vercel/eve/pull/6181))
|
|
11
|
+
- Each wait for a `gh` command's sandbox credential lock is recorded as an `agent.github.lease.wait` span, with `agent.github.lease.outcome` and `agent.github.lease.attempts`. ([#6196](https://github.com/vercel/eve/pull/6196))
|
|
11
12
|
|
|
12
13
|
## Bug Fixes
|
|
13
14
|
|
|
14
|
-
-
|
|
15
|
-
|
|
16
|
-
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
The `gh` tool's credential lease replaces the sandbox's network policy for the duration of one command. Leases were serialized per session, so sessions sharing a sandbox, such as parallel subagents, could replace or clear each other's credential mid-command; the stranded command got a 401 from GitHub, which asked the user to sign in again even though their grant was valid. Leases are now serialized per sandbox by a lock inside the sandbox, which works across processes. A command waits up to a minute for another to finish, then fails with a retryable error. ([#6029](https://github.com/vercel/eve/pull/6029))
|
|
20
|
-
- Name the memory store on memory provider tool calls, so a trace query by `gen_ai.memory.store.id` finds a scope's tool reads and writes as well as its recall and capture.
|
|
21
|
-
The `execute_tool` span of a memory provider tool, such as `profile__save`, now carries `gen_ai.memory.store.id` and `agent.memory.slot`, matching the `search_memory` and `upsert_memory` spans of the same slot. The store ID is the slot's opaque scope key, so it is recorded whatever the trace policy captures. `@vercel/agent-runs` adds an optional `memory` lifecycle to `ActiveOperation` on tool operations to record it. ([#6147](https://github.com/vercel/eve/pull/6147))
|
|
22
|
-
- Agent builds now build a workspace extension that only another workspace extension mounts or depends on, instead of failing with a missing compatibility manifest on a clean checkout. ([#6160](https://github.com/vercel/eve/pull/6160))
|
|
23
|
-
- The Vercel project overview card now shows the agents' tools, schedules, and connections for a Next.js app that hosts an `agents/` workspace through `withEve` from `eve/next`.
|
|
24
|
-
During `next build`, `withEve` now writes the workspace's `.eve/agent-summary.json` index, the same index that `withEve` from `eve/vercel` writes since #5710. Standalone agents and agents configured with the `agents` option do not change. ([#6163](https://github.com/vercel/eve/pull/6163))
|
|
25
|
-
- Send a Slack sign-in prompt to the person's DM when the session has no thread, instead of posting a status top-level in the channel.
|
|
26
|
-
The DM names the channel the request came from, is edited in place with the outcome, and needs no Slack scope beyond `chat:write`. If the DM can't be sent, eve posts in the channel as before. Threaded sessions and code channels are unchanged. ([#6007](https://github.com/vercel/eve/pull/6007))
|
|
27
|
-
- `eve__task_wait` now waits at most 30 minutes when a call omits `timeoutSeconds`, so a task that never reports can't hold a turn open indefinitely. ([#5300](https://github.com/vercel/eve/pull/5300))
|
|
15
|
+
- Compaction now summarizes directly and must bring the input under half the context window on the provider's token count, so a long session compacts once instead of several times in a row.
|
|
16
|
+
It no longer caps old tool output first. A compaction whose result is still over the threshold on the next call skips the stage that fell short. ([#6126](https://github.com/vercel/eve/pull/6126))
|
|
17
|
+
- A `gh` command whose lock was taken over after 10 minutes no longer clears the next command's GitHub credential when it finishes. ([#6189](https://github.com/vercel/eve/pull/6189))
|
|
18
|
+
- Throw a clear, non-retrying error when a `defineState()` handle is read or updated inside a workflow tool's `"use step"` function.
|
|
19
|
+
A step runs outside the session that owns the state, so `get()` silently returned `initial()` and `update()` silently discarded its write. Code that relied on that now fails the step without a retry. Return the value from the workflow tool and update state in a `call.settled` hook instead; see the [State](https://eve.dev/docs/concepts/state#update-state-from-a-workflow-tool) docs. ([#6201](https://github.com/vercel/eve/pull/6201))
|
|
28
20
|
|
|
29
|
-
For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%401.0.0-rc.
|
|
21
|
+
For an upgrade across multiple releases, review each version between the installed and target versions in the [target version's changelog](https://raw.githubusercontent.com/vercel/eve/refs/tags/eve%401.0.0-rc.9/packages/eve/CHANGELOG.md).
|
package/dist/src/acp/adapter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{realpath}from"node:fs/promises";import{PROTOCOL_VERSION,RequestError,methods}from"#compiled/@agentclientprotocol/sdk/index.js";import{Client,ClientError}from"#client/index.js";import{isFactType}from"#protocol/session-events/catalog.js";import{emptySessionView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{interaction}from"#protocol/session-projection/reader.js";import{callLabel,callOutputSource,callState,showsActivity}from"#protocol/session-projection/selectors.js";import{actionLabel}from"#shared/action-label.js";import{failureOf}from"#client/session-utils.js";const ANSWER_FIELD=`answer`;const ERROR_CODE_EVE=-32002;function acpStatus(e,t){switch(callState(e,t)){case void 0:return;case`requested`:case`approval`:return`pending`;case`running`:case`blocked`:return`in_progress`;case`completed`:return`completed`;default:return`failed`}}var EveAcpAdapter=class{#e;#t;#n;#r=!1;#i=new Map;constructor(e){this.#t=e.eveVersion,this.#n=e.workspaceRoot,this.#e=e.client??new Client({auth:e.auth,headers:e.headers,baseUrl:e.serverUrl,redirect:`manual`})}initialize(e){return this.#r=e.clientCapabilities?.elicitation?.form!==void 0,{protocolVersion:PROTOCOL_VERSION,agentCapabilities:{loadSession:!1,promptCapabilities:{},sessionCapabilities:{close:{}}},agentInfo:{name:`eve`,title:`eve`,version:this.#t},authMethods:[]}}async newSession(e){if(e.mcpServers.length>0)throw unsupported(`Client-provided MCP servers are not supported by eve ACP mode.`);if((e.additionalDirectories?.length??0)>0)throw unsupported(`Additional workspace directories are not supported by eve ACP mode.`);if(this.#n!==void 0){let t=await normalizedRealpath(e.cwd,`session/new.cwd`);let n=await normalizedRealpath(this.#n,`the eve application root`);if(t!==n)throw RequestError.invalidParams({cwd:e.cwd,workspaceRoot:n},`ACP cwd must be the eve application root`)}let t=randomUUID();return this.#i.set(t,{view:emptySessionView(),tools:new Map,parts:new Map}),{sessionId:t}}async prompt(e,t,n){let r=this.#s(e.sessionId);if(r.active!==void 0)throw new RequestError(-32001,`ACP session ${e.sessionId} already has an active prompt.`);let i=promptContent(e);r.tools.clear(),r.parts.clear();let a=Promise.withResolvers();let o={cancelRequested:!1,protocolCancelled:!1,outboundController:new AbortController,settled:a.promise,resolveSettled:a.resolve};r.active=o;let onProtocolCancel=()=>{o.protocolCancelled=!0,this.#o(r).catch(()=>void 0)};n.aborted?onProtocolCancel():n.addEventListener(`abort`,onProtocolCancel,{once:!0});try{if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});let a={message:i};for(;;){let i;if(r.client===void 0){if(a.message===void 0)throw Error(`ACP session has not started.`);let e=await this.#e.sessions.create({...a,message:a.message});r.client=e.session,i=e.delivery}else i=a.answers===void 0?await r.client.send(a.message):await r.client.respond(a.answers);(o.cancelRequested||o.protocolCancelled)&&await this.#o(r);let s=[];let c=!1;let l;let u;for await(let n of i.stream()){let i=`data`in n?n.data:void 0;let a=i!==void 0&&`turnId`in i?i.turnId:void 0;if(typeof a==`string`&&(o.turnId=a),n.type===`interaction.opened`&&n.data.request.kind===`sign-in`&&(u=unsupported(`Connection authorization cannot be completed through eve ACP mode.`)),n.type===`turn.settled`&&n.data.outcome===`cancelled`&&(c=!0),l=failureOf(n)??l,await this.#c(e.sessionId,r,n,t),n.type===`interaction.opened`){let e=interaction(r.view,n.data.interactionId);e!==void 0&&e.request.kind!==`sign-in`&&s.push(e)}}if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested||c&&l===void 0)return{stopReason:`cancelled`};if(l!==void 0)throw await this.#l(e.sessionId,r,t),eveFailure(l);if(u!==void 0)throw u;if(s.length===0)return{stopReason:`end_turn`};let d;try{d=await Promise.all(s.map(i=>this.#d(e.sessionId,r,i,t,n)))}catch(t){if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested)return{stopReason:`cancelled`};throw t}if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested)return{stopReason:`cancelled`};a={answers:d}}}catch(e){throw acpRequestError(e)}finally{n.removeEventListener(`abort`,onProtocolCancel),r.tools.clear(),o.resolveSettled(),r.active===o&&(r.active=void 0)}}async cancel(e){let t=this.#i.get(e);t!==void 0&&t.active!==void 0&&(t.active.cancelRequested=!0,await this.#o(t))}async closeSession(e){let t=this.#s(e);this.#i.delete(e),await this.#a(t)}async close(){let e=[...this.#i.values()];this.#i.clear(),await Promise.allSettled(e.map(e=>this.#a(e)))}async#a(e){let t;if(e.active!==void 0){let n=e.active;n.cancelRequested=!0;try{await this.#o(e)}catch(e){t=e}await n.settled}try{await e.client?.end()}catch(e){throw t===void 0?e:AggregateError([t,e],`Could not cancel or end the eve session`)}if(t!==void 0)throw t}async#o(e){e.active?.outboundController.abort(),e.client!==void 0&&await e.client.cancel(e.active?.turnId===void 0?void 0:{turnId:e.active.turnId})}#s(e){let t=this.#i.get(e);if(t===void 0)throw RequestError.invalidParams({sessionId:e},`Unknown or closed ACP session`);return t}async#c(e,t,n,r){if(!isFactType(n.type)){await this.#u(e,t,n,r);return}if(foldReceivedEvent(t.view,n),await this.#u(e,t,n,r),n.type===`call.requested`)return;let i=n.type===`call.settled`?n.data.callId:void 0;for(let[a,o]of t.tools){let s=acpStatus(t.view,a);if(s===void 0)continue;let c=callOutput(n,a,t.view);(s!==o.status||a===i&&`content`in c)&&(t.tools.set(a,{...o,status:s}),await notifyUpdate(r,e,{sessionUpdate:`tool_call_update`,toolCallId:a,status:s,...c,...resultTitle(n,a)}))}}async#l(e,t,n){for(let r of t.tools.keys())acpStatus(t.view,r)===`in_progress`&&await notifyUpdate(n,e,{sessionUpdate:`tool_call_update`,toolCallId:r,status:`failed`})}async#u(e,t,n,r){switch(n.type){case`content.delta`:{let{partId:i,kind:a,delta:o}=n.data;a===`text`?t.parts.set(i,`text`):a===`reasoning`&&t.parts.set(i,`reasoning`);let s=t.parts.get(i);if(s===void 0||o===void 0)return;await notifyUpdate(r,e,{sessionUpdate:s===`text`?`agent_message_chunk`:`agent_thought_chunk`,content:{type:`text`,text:o},messageId:i});return}case`content.completed`:{let{partId:i,kind:a,value:o}=n.data;if(t.parts.has(i)||typeof o!=`string`||a!==`text`&&a!==`reasoning`)return;t.parts.set(i,a===`text`?`text`:`reasoning`),await notifyUpdate(r,e,{sessionUpdate:a===`text`?`agent_message_chunk`:`agent_thought_chunk`,content:{type:`text`,text:o},messageId:i});return}case`call.requested`:{let{callId:i,capability:a,input:o}=n.data;let s=t.view.calls[i];if(!showsActivity(a)||s===void 0)return;let c={toolCallId:i,title:callLabel(s),kind:`other`,status:`pending`,rawInput:o};t.tools.set(i,c),await notifyUpdate(r,e,{sessionUpdate:`tool_call`,...c});return}default:return}}async#d(e,t,n,r,i){let a=AbortSignal.any([i,t.active.outboundController.signal]);if(n.request.display===`confirmation`){let i=`${n.interactionId}:approve`;let o=`${n.interactionId}:deny`;let s=(n.call===void 0?void 0:t.tools.get(n.call.callId))??toolCallForAsked(n);let c=await r.request(methods.client.session.requestPermission,{sessionId:e,toolCall:s,options:[{kind:`allow_once`,name:`Approve`,optionId:i},{kind:`reject_once`,name:`Deny`,optionId:o}]},{cancellationSignal:a});if(c.outcome.outcome===`cancelled`)return this.#f(t),{interactionId:n.interactionId};if(c.outcome.optionId===i)return{interactionId:n.interactionId,optionId:`approve`};if(c.outcome.optionId===o)return{interactionId:n.interactionId,optionId:`deny`};throw RequestError.invalidParams({optionId:c.outcome.optionId},`Unknown ACP permission option`)}if(!this.#r)throw unsupported(`The ACP client does not support form elicitation required by this eve question.`);let o=elicitationProperty(n);let s=await r.request(methods.client.elicitation.create,{mode:`form`,sessionId:e,message:n.request.prompt,requestedSchema:{type:`object`,properties:{[ANSWER_FIELD]:o},required:[ANSWER_FIELD]}},{cancellationSignal:a});if(s.action!==`accept`)return this.#f(t),{interactionId:n.interactionId};let c=s.content?.[ANSWER_FIELD];if(typeof c!=`string`)throw RequestError.invalidParams(s.content,`ACP elicitation response must contain a string answer`);if(n.request.display===`select`){if(!n.request.options?.some(e=>e.id===c))throw RequestError.invalidParams({answer:c},`Unknown eve question option`);return{interactionId:n.interactionId,optionId:c}}return{interactionId:n.interactionId,text:c}}#f(e){let t=e.active;t.cancelRequested=!0,t.outboundController.abort()}};async function normalizedRealpath(e,t){try{return await realpath(e)}catch(n){throw RequestError.invalidParams({path:e},`Could not resolve ${t}: ${errorMessage(n)}`)}}function promptContent(e){let t=e.prompt.map(e=>{if(e.type!==`text`)throw unsupported(`ACP prompt content type ${JSON.stringify(e.type)} is not supported.`);return{type:`text`,text:e.text}});if(t.every(e=>e.text.length===0))throw RequestError.invalidParams(e.prompt,`ACP prompt must contain at least one non-empty text block`);return t}function toolCallForAsked(e){let t=e.call?.name??e.request.kind;return{toolCallId:e.call?.callId??e.interactionId,title:actionLabel({callId:e.call?.callId??``,input:{},kind:`tool-call`,toolName:t},void 0),kind:`other`,status:`pending`,rawInput:e.call?.input??{}}}function elicitationProperty(e){if(e.request.display===`select`&&e.request.allowFreeform!==!0&&e.request.options?.length)return{type:`string`,title:e.request.prompt,oneOf:e.request.options.map(e=>({const:e.id,title:e.label,description:e.description}))};if(e.request.display===`text`&&e.request.allowFreeform!==!1)return{type:`string`,title:e.request.prompt,minLength:1};throw unsupported(`This eve question shape cannot be represented by ACP form elicitation.`)}async function notifyUpdate(e,t,n){await e.notify(methods.client.session.update,{sessionId:t,update:n})}function stringifyOutput(e){return typeof e==`string`?e:JSON.stringify(e,null,2)}function unsupported(e){return new RequestError(-32003,e)}function eveFailure(e){return new RequestError(ERROR_CODE_EVE,e.message,{code:e.code,id:e.id,hint:e.hint})}function acpRequestError(e){return e instanceof RequestError?e:e instanceof ClientError?new RequestError(ERROR_CODE_EVE,e.message,{httpStatus:e.status}):new RequestError(ERROR_CODE_EVE,errorMessage(e))}function errorMessage(e){return e instanceof Error?e.message:String(e)}function resultTitle(e,t){let n=e.type===`call.settled`&&e.data.callId===t?e.data.label:void 0;return n===void 0?{}:{title:n}}function callOutput(e,t,n){if(e.type!==`call.settled`||e.data.callId!==t)return{};let r=e.data.outputOf;let i=r===void 0?void 0:callOutputSource(n,r.callId)?.output;let a=e.data.output===void 0?i===void 0?e.data.error?.message:i:e.data.output;return a===void 0?{}:{content:[{type:`content`,content:{type:`text`,text:stringifyOutput(a)}}],rawOutput:a}}export{EveAcpAdapter};
|
|
1
|
+
import{randomUUID}from"node:crypto";import{realpath}from"node:fs/promises";import{PROTOCOL_VERSION,RequestError,methods}from"#compiled/@agentclientprotocol/sdk/index.js";import{Client,ClientError}from"#client/index.js";import{isFactType}from"#protocol/session-events/catalog.js";import{emptySessionView,foldReceivedEvent}from"#protocol/session-projection/fold.js";import{interaction}from"#protocol/session-projection/reader.js";import{callLabel,callOutputSource,callState,showsActivity}from"#protocol/session-projection/selectors.js";import{actionLabel}from"#shared/action-label.js";import{failureOf}from"#client/session-utils.js";const ANSWER_FIELD=`answer`;const ERROR_CODE_EVE=-32002;function acpStatus(e,t){switch(callState(e,t)){case void 0:return;case`requested`:case`approval`:return`pending`;case`running`:case`blocked`:return`in_progress`;case`completed`:return`completed`;default:return`failed`}}var EveAcpAdapter=class{#e;#t;#n;#r=!1;#i=new Map;constructor(e){this.#t=e.eveVersion,this.#n=e.workspaceRoot,this.#e=e.client??new Client({auth:e.auth,headers:e.headers,baseUrl:e.serverUrl,redirect:`manual`})}initialize(e){return this.#r=e.clientCapabilities?.elicitation?.form!==void 0,{protocolVersion:PROTOCOL_VERSION,agentCapabilities:{loadSession:!1,promptCapabilities:{},sessionCapabilities:{close:{}}},agentInfo:{name:`eve`,title:`eve`,version:this.#t},authMethods:[]}}async newSession(e){if(e.mcpServers.length>0)throw unsupported(`Client-provided MCP servers are not supported by eve ACP mode.`);if((e.additionalDirectories?.length??0)>0)throw unsupported(`Additional workspace directories are not supported by eve ACP mode.`);if(this.#n!==void 0){let t=await normalizedRealpath(e.cwd,`session/new.cwd`);let n=await normalizedRealpath(this.#n,`the eve application root`);if(t!==n)throw RequestError.invalidParams({cwd:e.cwd,workspaceRoot:n},`ACP cwd must be the eve application root`)}let t=randomUUID();return this.#i.set(t,{view:emptySessionView(),tools:new Map,parts:new Map}),{sessionId:t}}async prompt(e,t,n){let r=this.#s(e.sessionId);if(r.active!==void 0)throw new RequestError(-32001,`ACP session ${e.sessionId} already has an active prompt.`);let i=promptContent(e);r.tools.clear(),r.parts.clear();let a=Promise.withResolvers();let o={cancelRequested:!1,protocolCancelled:!1,outboundController:new AbortController,settled:a.promise,resolveSettled:a.resolve};r.active=o;let onProtocolCancel=()=>{o.protocolCancelled=!0,this.#o(r).catch(()=>void 0)};n.aborted?onProtocolCancel():n.addEventListener(`abort`,onProtocolCancel,{once:!0});try{if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});let a={message:i};for(;;){let i;if(r.client===void 0){if(a.message===void 0)throw Error(`ACP session has not started.`);let e=await this.#e.sessions.create({...a,message:a.message});r.client=e.session,i=e.delivery}else i=a.answers===void 0?await r.client.send(a.message):await r.client.respond(a.answers);(o.cancelRequested||o.protocolCancelled)&&await this.#o(r);let s=[];let c=!1;let l;let u;for await(let n of i.stream()){let i=`data`in n?n.data:void 0;let a=i!==void 0&&`turnId`in i?i.turnId:void 0;if(typeof a==`string`&&(o.turnId=a),n.type===`interaction.opened`&&n.data.request.kind===`sign-in`&&(u=unsupported(`Connection authorization cannot be completed through eve ACP mode.`)),n.type===`turn.settled`&&n.data.outcome===`cancelled`&&(c=!0),l=failureOf(n)??l,await this.#c(e.sessionId,r,n,t),n.type===`interaction.opened`){let e=interaction(r.view,n.data.interactionId);e!==void 0&&e.request.kind!==`sign-in`&&s.push(e)}}if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested||c&&l===void 0)return{stopReason:`cancelled`};if(l!==void 0)throw await this.#l(e.sessionId,r,t),eveFailure(l);if(u!==void 0)throw u;if(s.length===0)return{stopReason:`end_turn`};let d;try{d=await Promise.all(s.map(i=>this.#d(e.sessionId,r,i,t,n)))}catch(t){if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested)return{stopReason:`cancelled`};throw t}if(o.protocolCancelled)throw RequestError.requestCancelled({sessionId:e.sessionId});if(o.cancelRequested)return{stopReason:`cancelled`};a={answers:d}}}catch(e){throw acpRequestError(e)}finally{n.removeEventListener(`abort`,onProtocolCancel),r.tools.clear(),o.resolveSettled(),r.active===o&&(r.active=void 0)}}async cancel(e){let t=this.#i.get(e);t!==void 0&&t.active!==void 0&&(t.active.cancelRequested=!0,await this.#o(t))}async closeSession(e){let t=this.#s(e);this.#i.delete(e),await this.#a(t)}async close(){let e=[...this.#i.values()];this.#i.clear(),await Promise.allSettled(e.map(e=>this.#a(e)))}async#a(e){let t;if(e.active!==void 0){let n=e.active;n.cancelRequested=!0;try{await this.#o(e)}catch(e){t=e}await n.settled}try{await e.client?.end()}catch(e){throw t===void 0?e:AggregateError([t,e],`Could not cancel or end the eve session`)}if(t!==void 0)throw t}async#o(e){e.active?.outboundController.abort(),e.client!==void 0&&await e.client.cancel(e.active?.turnId===void 0?void 0:{turnId:e.active.turnId})}#s(e){let t=this.#i.get(e);if(t===void 0)throw RequestError.invalidParams({sessionId:e},`Unknown or closed ACP session`);return t}async#c(e,t,n,r){if(!isFactType(n.type)){await this.#u(e,t,n,r);return}if(foldReceivedEvent(t.view,n),await this.#u(e,t,n,r),n.type===`call.requested`)return;let i=n.type===`call.settled`?n.data.callId:void 0;for(let[a,o]of t.tools){let s=acpStatus(t.view,a);if(s===void 0)continue;let c=callOutput(n,a,t.view);(s!==o.status||a===i&&`content`in c)&&(t.tools.set(a,{...o,status:s}),await notifyUpdate(r,e,{sessionUpdate:`tool_call_update`,toolCallId:a,status:s,...c,...resultTitle(n,a)}))}}async#l(e,t,n){for(let r of t.tools.keys())acpStatus(t.view,r)===`in_progress`&&await notifyUpdate(n,e,{sessionUpdate:`tool_call_update`,toolCallId:r,status:`failed`})}async#u(e,t,n,r){switch(n.type){case`content.delta`:{let{partId:i,kind:a,delta:o}=n.data;a===`text`?t.parts.set(i,`text`):a===`reasoning`&&t.parts.set(i,`reasoning`);let s=t.parts.get(i);if(s===void 0||o===void 0)return;await notifyUpdate(r,e,{sessionUpdate:s===`text`?`agent_message_chunk`:`agent_thought_chunk`,content:{type:`text`,text:o},messageId:i});return}case`content.completed`:{let{partId:i,kind:a,value:o}=n.data;if(t.parts.has(i)||typeof o!=`string`||a!==`text`&&a!==`reasoning`)return;t.parts.set(i,a===`text`?`text`:`reasoning`),await notifyUpdate(r,e,{sessionUpdate:a===`text`?`agent_message_chunk`:`agent_thought_chunk`,content:{type:`text`,text:o},messageId:i});return}case`call.requested`:{let{callId:i,capability:a,input:o}=n.data;let s=t.view.calls[i];if(!showsActivity(a)||s===void 0)return;let c={toolCallId:i,title:callLabel(s),kind:`other`,status:`pending`,rawInput:o};t.tools.set(i,c),await notifyUpdate(r,e,{sessionUpdate:`tool_call`,...c});return}default:return}}async#d(e,t,n,r,i){let a=AbortSignal.any([i,t.active.outboundController.signal]);if(n.request.display===`confirmation`){let i=`${n.interactionId}:approve`;let o=`${n.interactionId}:deny`;let s=(n.call===void 0?void 0:t.tools.get(n.call.callId))??toolCallForAsked(n);let c=await r.request(methods.client.session.requestPermission,{sessionId:e,toolCall:s,options:[{kind:`allow_once`,name:`Approve`,optionId:i},{kind:`reject_once`,name:`Deny`,optionId:o}]},{cancellationSignal:a});if(c.outcome.outcome===`cancelled`)return this.#f(t),{interactionId:n.interactionId};if(c.outcome.optionId===i)return{interactionId:n.interactionId,optionId:`approve`};if(c.outcome.optionId===o)return{interactionId:n.interactionId,optionId:`deny`};throw RequestError.invalidParams({optionId:c.outcome.optionId},`Unknown ACP permission option`)}if(!this.#r)throw unsupported(`The ACP client does not support form elicitation required by this eve question.`);let o=elicitationProperty(n);let s=await r.request(methods.client.elicitation.create,{mode:`form`,sessionId:e,message:n.request.prompt,requestedSchema:{type:`object`,properties:{[ANSWER_FIELD]:o},required:[ANSWER_FIELD]}},{cancellationSignal:a});if(s.action!==`accept`)return this.#f(t),{interactionId:n.interactionId};let c=s.content?.[ANSWER_FIELD];if(typeof c!=`string`)throw RequestError.invalidParams(s.content,`ACP elicitation response must contain a string answer`);if(n.request.display===`select`){if(!n.request.options?.some(e=>e.id===c))throw RequestError.invalidParams({answer:c},`Unknown eve question option`);return{interactionId:n.interactionId,optionId:c}}return{interactionId:n.interactionId,text:c}}#f(e){let t=e.active;t.cancelRequested=!0,t.outboundController.abort()}};async function normalizedRealpath(e,t){try{return await realpath(e)}catch(n){throw RequestError.invalidParams({path:e},`Could not resolve ${t}: ${errorMessage(n)}`)}}function promptContent(e){let t=e.prompt.map(e=>{if(e.type!==`text`)throw unsupported(`ACP prompt content type ${JSON.stringify(e.type)} is not supported.`);return{type:`text`,text:e.text}});if(t.every(e=>e.text.length===0))throw RequestError.invalidParams(e.prompt,`ACP prompt must contain at least one non-empty text block`);return t}function toolCallForAsked(e){let t=e.call?.name??e.request.kind;return{toolCallId:e.call?.callId??e.interactionId,title:actionLabel({callId:e.call?.callId??``,input:{},kind:`tool-call`,toolName:t},void 0),kind:`other`,status:`pending`,rawInput:e.call?.input??{}}}function elicitationProperty(e){if(e.request.display===`select`&&e.request.allowFreeform!==!0&&e.request.options?.length){let{initialOptionId:t,options:n}=e.request;return{type:`string`,title:e.request.prompt,oneOf:n.map(e=>({const:e.id,title:e.label,description:e.description})),default:n.some(e=>e.id===t)?t:void 0}}if(e.request.display===`text`&&e.request.allowFreeform!==!1)return{type:`string`,title:e.request.prompt,minLength:1};throw unsupported(`This eve question shape cannot be represented by ACP form elicitation.`)}async function notifyUpdate(e,t,n){await e.notify(methods.client.session.update,{sessionId:t,update:n})}function stringifyOutput(e){return typeof e==`string`?e:JSON.stringify(e,null,2)}function unsupported(e){return new RequestError(-32003,e)}function eveFailure(e){return new RequestError(ERROR_CODE_EVE,e.message,{code:e.code,id:e.id,hint:e.hint})}function acpRequestError(e){return e instanceof RequestError?e:e instanceof ClientError?new RequestError(ERROR_CODE_EVE,e.message,{httpStatus:e.status}):new RequestError(ERROR_CODE_EVE,errorMessage(e))}function errorMessage(e){return e instanceof Error?e.message:String(e)}function resultTitle(e,t){let n=e.type===`call.settled`&&e.data.callId===t?e.data.label:void 0;return n===void 0?{}:{title:n}}function callOutput(e,t,n){if(e.type!==`call.settled`||e.data.callId!==t)return{};let r=e.data.outputOf;let i=r===void 0?void 0:callOutputSource(n,r.callId)?.output;let a=e.data.output===void 0?i===void 0?e.data.error?.message:i:e.data.output;return a===void 0?{}:{content:[{type:`content`,content:{type:`text`,text:stringifyOutput(a)}}],rawOutput:a}}export{EveAcpAdapter};
|
|
@@ -83,6 +83,8 @@ export type AgentTUIInputQuestion = {
|
|
|
83
83
|
prompt: string;
|
|
84
84
|
display: "select" | "text";
|
|
85
85
|
options?: ReadonlyArray<AgentTUIInputOption>;
|
|
86
|
+
/** The option the cursor starts on. */
|
|
87
|
+
initialOptionId?: string;
|
|
86
88
|
allowFreeform?: boolean;
|
|
87
89
|
context?: AgentTUIInputContext;
|
|
88
90
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{formatStrandedSessionNotice}from"./stranded-session.js";import{isTerminalToolCallPart}from"./terminal-tool-part.js";import{conversationView,isWorking,tuiSessionData}from"./conversation-view.js";import{formatFailureDetail,formatFailureMessage,interruptedError,isInterruptedError,localFailureHint}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{createRemoteConnectionController}from"./remote-connection.js";import{describeRemoteAuthCompletedMutations}from"./remote-auth-result.js";import{prepareRemoteTuiAccess}from"./remote-startup.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,normalizeLocalModelEndpoint,orderedSetupIssues}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import{createMcpConnectionStatusTracker}from"./mcp-connection-status.js";import{optionStyle}from"#channel/interaction-prompts.js";import{activeTurn,delivery,failure,openInteractions,task,turn}from"#protocol/session-projection/public-view.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{inspectApplication}from"#services/inspect-application.js";import{devBootPhase}from"#internal/dev-boot-progress.js";import{toErrorMessage}from"#shared/errors.js";import{isTaskAdmissionRefused}from"#protocol/task-tools.js";import{probeAgentInfo}from"#services/dev-client/agent-info-probe.js";import{APPROVE_OPTION_ID,DENY_OPTION_ID}from"#protocol/interaction-options.js";import"#client/conversation-state.js";import{SessionStore,attachSessionStore,detachSessionStore}from"#client/session-store.js";import{isAbortError}from"#client/session-store-helpers.js";import{renderApplicationInfo}from"#cli/commands/info.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}function hasOpenTurn(e){return activeTurn(e.view)!==void 0}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=!1;#m;#h;#g=!0;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E=!1;#D;#O=!1;#k=new AbortController;#A=!1;#j=0;#M=0;#N=[];#P;#F;#I;#L;#R;#z=new Set;#B=new Set;#V=[];#H;#U=new Set;#W;#G=0;#K=new Set;#q=new Map;#J;constructor(e){if(this.#e=e.client,e.lifecycle!==void 0&&(this.#J=e.lifecycle),e.diagnostics!==void 0&&(this.#r=e.diagnostics),this.#n=createRenderer(e),this.#t=new SessionStore({client:e.client,followAgents:!0}),this.#t.setCallbacks({onEvent:e=>this.#Ue(e),onSessionChange:e=>{e!==void 0&&this.#n.setSessionId?.(e.sessionId)},prepareSend:e=>this.#ne(e)}),this.#i=e.name??`eve`,this.#y=e.withExclusiveTerminal,this.#a=e.formatTransportError??toErrorMessage,e.initialInput!==void 0&&(this.#l=e.initialInput),e.startup!==void 0&&(this.#u=e.startup),this.#f=e.onboard===!0,this.#m=e.onOnboardingStep,this.#h=e.onOnboardingTerminal,e.appRoot!==void 0){this.#c=e.appRoot;let t={appRoot:e.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};e.detectProjectIdentity!==void 0&&(t.detectIdentity=e.detectProjectIdentity),this.#F=createVercelStatusTracker(t),e.probeMcpConnection!==void 0&&(this.#I=createMcpConnectionStatusTracker({onChange:()=>{},probe:e.probeMcpConnection}))}e.promptCommandHandler!==void 0&&(this.#_=e.promptCommandHandler),this.#v=e.availablePromptCommands??PROMPT_COMMANDS,e.remote!==void 0&&(this.#x=e.remote.runAuthFlow,this.#b=createRemoteConnectionController({client:this.#e,credentials:e.remote.credentials,target:e.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:e.remote.resolveOidcToken,resolveDeployment:e.remote.resolveDeployment})),this.#S=e.bootDetections??BOOT_DETECTIONS,this.#C=e.getVercelAuthStatus??getVercelAuthStatus,this.#w=e.inspectApplication??inspectApplication,e.onBootProgress!==void 0&&(this.#T=e.onBootProgress),e.serverUrl!==void 0&&(this.#s=e.serverUrl),e.serverUrl!==void 0&&e.remote===void 0&&(this.#o=createDevelopmentRuntimeArtifactRefresher({serverUrl:e.serverUrl}))}async#Y(){if(this.#s===void 0){this.#Q(),this.#f||await this.#we(void 0);return}let e;if(this.#b!==void 0){let t=await this.#b.check();t.state===`ready`&&(e=t.info)}else{let t=this.#e;if(t!==void 0)try{let n=await devBootPhase(`connecting to agent`,()=>probeAgentInfo({client:t,timeoutMs:2e3}),this.#T);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}this.#Q();let t=this.#Z(e);this.#f||await this.#we(t)}#X(){let e=this.#u?.finish();return this.#d=e?.queuedPrompt,e?.draft??this.#l}#Z(e){let t=this.#c===void 0?e:normalizeLocalModelEndpoint(e,process.env);this.#L=t;let n=this.#s;if(n===void 0||this.#g)return t;let r={name:this.#i,serverUrl:n,localDevelopment:this.#c!==void 0};return t!==void 0&&(r.info=t),this.#n.renderAgentHeader?.(r),t}#Q(){let e=this.#T;this.#T=void 0,e?.({type:`before-first-paint`})}async run(){let onStop=()=>this.#n.requestInterrupt?.();this.#J?.signal.aborted===!0?onStop():this.#J?.signal.addEventListener(`abort`,onStop,{once:!0});let e=this.#t.subscribe(()=>this.#re());attachSessionStore(this.#t);try{await this.#$()}catch(e){if(!isInterruptedError(e))throw e}finally{this.#J?.signal.removeEventListener(`abort`,onStop),this.#E=!0,this.#k.abort(),this.#R?.abort(),e(),detachSessionStore(this.#t),this.#n.shutdown?.(),this.#F?.dispose(),this.#I?.dispose(),this.#b?.dispose()}}async#$(){let e=this.#i;let t;this.#n.setStartupPhase?.(`starting`),await this.#Y(),this.#F?.refreshIdentity(),this.#I?.refresh();let n=(this.#f||this.#L?.agent.model.endpoint?.kind===`gateway`&&!this.#L.agent.model.endpoint.connected)&&this.#c!==void 0&&this.#_!==void 0&&this.#n.setupFlow!==void 0;let r;if(this.#b!==void 0&&this.#n.setupFlow!==void 0){let e=await prepareRemoteTuiAccess({connection:this.#b,renderer:this.#n.setupFlow,signal:this.#J?.signal,runAuthFlow:this.#x});if(e?.kind===`authenticated`){let e=this.#b.current().connection;e.state===`ready`&&this.#Z(e.info)}else e?.kind===`failed`||e?.kind===`unavailable`?r={failed:!0,message:e.kind===`failed`?e.message:e.failure.message}:e?.kind===`cancelled`&&(r={cancelled:!0},e.completedMutations.length>0&&(r.message=`Completed before cancellation: ${describeRemoteAuthCompletedMutations(e.completedMutations).join(`, `)}.`))}let i=this.#b?.current().connection;r===void 0&&i?.state===`ready`&&i.warning!==void 0&&(r={message:i.warning}),n&&(this.#n.setStartupPhase?.(`connecting`),r=await this.#Ne(e));let a=this.#X();for(r?.cancelled||r?.failed?a=[this.#d,a].filter(Boolean).join(`
|
|
2
2
|
|
|
3
3
|
`)||void 0:t=this.#d,this.#g=!1,this.#Z(this.#L),this.#Te(),this.#n.setStartupPhase?.(void 0),(!n||r?.cancelled||r?.failed)&&r?.message!==void 0&&this.#Oe({kind:`result`,message:r.message});this.#J?.signal.aborted!==!0&&this.#n.exitRequested?.()!==!0;){if(this.#ie()){this.#me();continue}if(this.#de().length>0){await this.#fe(e);continue}let n=isWorking(this.#t.snapshot.status)?void 0:this.#V.shift();if(n!==void 0){this.#H=n;try{await this.#Ce(n)}finally{this.#H=void 0}continue}if(t===void 0){let n=await this.#be({title:e,initialDraft:a});if(a=void 0,n===void 0)continue;if(n.type===`cancel`){this.#_e();continue}if(n.type===`interrupt`){this.#me(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`);continue}t=n.text}let r=t;t=void 0;let i=parsePromptCommand(r);if(i===null){this.#te(r);continue}let o=await this.#ee(i,e);if(o===`exit`)return;o!==void 0&&(a=o.draft)}}async#ee(e,t){switch(e.type){case`exit`:return this.#Oe({kind:`dismiss`}),this.#J?.requestStop(),`exit`;case`cancel`:{let e=hasOpenTurn(this.#t.snapshot);e&&this.#_e(),this.#Oe({kind:`result`,summary:e?`Cancellation requested`:`No active turn to cancel`});return}case`new`:await this.#ye();return;case`compact`:await this.#ve({absent:`No active session to compact`,accepted:`Compaction requested`,failed:`Couldn't compact the session`,invoke:()=>this.#t.compact()});return;case`clear`:await this.#ve({absent:`No active session to clear`,accepted:`Session context cleared`,failed:`Couldn't clear the session`,invoke:()=>this.#t.clear()});return;case`help`:{if(this.#n.choosePromptCommand===void 0){this.#Oe({kind:`result`,message:formatPromptCommandHelp(this.#v)});return}let e=await this.#n.choosePromptCommand(this.#v);return e===void 0?void 0:{draft:e}}case`info`:await this.#Ie();return;case`loglevel`:{let t=this.#Le(e.argument);let n=t.startsWith(`/loglevel is not available`)||t.startsWith(`Unknown log level`);this.#Oe(n?{kind:`result`,message:t}:{kind:`result`,summary:t});return}case`traces`:await this.#Fe(e.argument);return;case`extension`:await this.#Me(e,t,{trigger:`command`});return}}#te(e){let t=this.#t.snapshot;let n=hasOpenTurn(t);let r={text:e};this.#D=r,n||(this.#O=!1);let i=n?{message:e,turnPolicy:`steer`}:t.session===void 0?{message:e}:{message:e,turnPolicy:`queue`};this.#t.send(i).then(({deliveryId:e})=>{r.deliveryId=e,this.#E||this.#ae(this.#t.snapshot)}).catch(e=>{this.#E||isAbortError(e)||this.#se(n?`Steering failed`:`Error`,e)})}async#ne(e){return e.turnPolicy===`steer`||(this.#o!==void 0&&await this.#o.refresh({answers:e.answers,message:typeof e.message==`string`?e.message:void 0,onRuntimeArtifactsChanged:()=>this.#Ve()}),e.message!==void 0&&this.#n.flushDelayedDevBuildErrors?.()),e}#re(){let e=this.#t.snapshot;let t=tuiSessionData(e);this.#n.renderConversation?.(conversationView(e,t,this.#c===void 0?void 0:localFailureHint)),this.#oe(e.error,t.sessionFailed),this.#We(t.failures),this.#He(e),this.#ue(e),this.#Se(e),this.#ae(e),(t.sessionFailed||this.#de().length>0||!isWorking(e.status)&&this.#V.length>0)&&this.#R?.abort()}#ie(){return tuiSessionData(this.#t.snapshot).sessionFailed}#ae(e){let t=this.#D;if(t?.deliveryId===void 0)return;let n=delivery(e.view,t.deliveryId)?.turnId;if(n===void 0)return;let r=turn(e.view,n);if(r===void 0||r.status===`running`)return;let i=r.outcome;this.#D=void 0,i===`cancelled`&&!this.#O&&failure(e.view,n)===void 0&&this.#n.restoreDraft?.(t.text)}#oe(e,t){e!==void 0&&e!==this.#W&&(this.#W=e,t||this.#le(e)||(this.#b?.reportFailure(e),this.#n.renderError?.(`Error`,this.#a(e))))}#se(e,t){this.#le(t)||this.#n.renderError?.(e,this.#a(t))}#ce(e){return formatStrandedSessionNotice(e,{localServer:this.#c!==void 0,sessionId:this.#t.snapshot.session?.sessionId})}#le(e){let t=this.#ce(e);return t!==void 0&&(this.#n.renderError?.(`Session stranded`,t),!0)}#ue(e){!this.#f||this.#p||!e.messages.some(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`text`&&e.text.length>0))||(this.#p=!0,this.#m?.({flow:`onboarding`,step:`first_response`}))}#de(){return openInteractions(this.#t.snapshot.view).filter(e=>e.request.kind!==`sign-in`&&!this.#z.has(e.interactionId)&&!this.#B.has(e.interactionId))}async#fe(e){for(let t=0;;t+=1){let n=this.#de();let r=n[0];if(r===void 0)return;let i=inputContext(r,t+1,t+n.length);let a=await this.#pe(r,i,e);a===void 0?this.#z.add(r.interactionId):(this.#B.add(r.interactionId),this.#t.send({answers:[a]}).catch(e=>{this.#B.delete(r.interactionId),this.#E||isAbortError(e)||this.#se(`Error`,e)}))}}async#pe(e,t,n){if(e.request.kind===`approval`){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);let r=await this.#n.readToolApproval(toAgentTUIToolApprovalRequest(e,t),{title:n});return{interactionId:e.interactionId,optionId:r.approved?APPROVE_OPTION_ID:DENY_OPTION_ID}}if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);let r=await this.#n.readInputQuestion(toAgentTUIInputQuestion(e,t),{title:n});if(r!==void 0)return{interactionId:e.interactionId,...r.optionId!==void 0&&{optionId:r.optionId},...r.text!==void 0&&{text:r.text}}}#me(e){this.#n.renderSessionBoundary===void 0?e===void 0&&this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary(),e!==void 0&&this.#n.renderNotice?.(e),this.#he()}#he(){this.#t.newSession(),this.#ge()}#ge(){this.#z.clear(),this.#B.clear(),this.#U.clear(),this.#q.clear(),this.#G=0,this.#o?.clear()}#_e(){this.#O=!0,this.#t.cancel().catch(e=>{this.#n.renderNotice?.(`Couldn't cancel the turn: ${toErrorMessage(e)}`)})}async#ve(e){if(this.#t.snapshot.session===void 0)this.#Oe({kind:`result`,summary:e.absent});else try{let t=await(await e.invoke()).result();if(t.status!==`completed`)throw Error(`The command settled ${t.status}.`);this.#Oe({kind:`result`,summary:e.accepted})}catch(t){this.#Oe({kind:`result`,message:this.#ce(t)??toErrorMessage(t),summary:e.failed})}}async#ye(){try{this.#t.snapshot.session!==void 0&&await(await this.#t.end()).result(),this.#t.newSession()}catch(e){this.#Oe({kind:`result`,message:`Couldn't end the session: ${toErrorMessage(e)}`});return}this.#ge(),this.#n.reset?.(),this.#Oe({kind:`dismiss`})}async#be(e){if(!this.#n.readInput)throw Error(`The renderer does not support prompt input.`);let t=new AbortController;this.#R=t;try{let n=await this.#xe(this.#n.readInput({...e,signal:t.signal}));if(n===void 0&&!t.signal.aborted)throw interruptedError();return n}finally{this.#R===t&&(this.#R=void 0)}}async#xe(e){let t=this.#o;if(t===void 0)return await e;let n=!1;let r=!1;let i;let a=!1;let o=0;let refresh=async()=>{if(!(n||r)){r=!0;try{await t.refreshIdle({onRuntimeArtifactsChanged:()=>this.#Ve()}),this.#c!==void 0&&this.#L===void 0&&!a&&(a=!0,this.#ze().finally(()=>{a=!1}));let e=this.#L?.agent.model.endpoint;let n=e?.kind===`chatgpt`&&(e.state===`signed-out`||e.state===`reauth-required`);let r=Date.now();n&&r-o>=5e3&&(o=r,this.#ze())}finally{r=!1}}};let startRefresh=()=>{if(n||r)return;let e=refresh().finally(()=>{i===e&&(i=void 0)});i=e};startRefresh();let s=setInterval(()=>{startRefresh()},500);s.unref?.();try{return await e}finally{n=!0,clearInterval(s),await i}}#Se(e){if(this.#c!==void 0)for(let{callId:t,address:n}of registryHandoffs(e))this.#U.has(t)||(this.#U.add(t),this.#H===n||this.#V.includes(n)||this.#V.push(n))}async#Ce(e){this.#n.renderCommandInvocation?.(`/add ${e}`),await this.#Me({type:`extension`,name:`add`,argument:e},`Add to your agent`,{trigger:`command`})}async#we(e){if(this.#c===void 0)return;let t={appRoot:this.#c,env:process.env};e!==void 0&&(t.info=e),this.#N=await detectSetupIssues(t,this.#S),this.#n.renderSetupWarning!==void 0&&(this.#Te(),this.#Ee())}#Te(){if(this.#g)return;let e=orderedSetupIssues(this.#N,this.#P);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#Ee(){let e=this.#c;if(e===void 0||process.env.EVE_MODEL_CONNECTION!==`ai-gateway-project`)return;let t;try{t=await this.#C(e,{signal:this.#k.signal})}catch{return}this.#E||this.#A||(this.#P=authIssueForStatus(t),this.#Te())}async#De(e){let t=this.#c;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n=++this.#j;let r={appRoot:t,env:process.env};e!==void 0&&(r.info=e);try{let[e,i]=await Promise.all([detectSetupIssues(r,this.#S),process.env.EVE_MODEL_CONNECTION===`ai-gateway-project`?this.#C(t,{signal:this.#k.signal}):void 0]);if(this.#E||n!==this.#j)return;this.#N=e,this.#P=i===void 0?void 0:authIssueForStatus(i),this.#Te()}catch{return}}#Oe(e){if(this.#n.finishCommand!==void 0)this.#n.finishCommand(e);else if(e.kind===`result`){let t=[e.summary,e.message].filter(Boolean).join(`
|
|
4
|
-
`);t!==``&&this.#n.renderNotice?.(t)}}async#ke(e,t){let n=this.#_;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r=this.#L?.agent.model.endpoint;let i={...t,renderer:this.#n,settleOutcome:e=>this.#je(e),chatGptAccountLabel:r?.kind===`chatgpt`&&r.state===`ready`?r.accountLabel:void 0,withExclusiveTerminal:this.#y};let a=this.#I?.current();let o=a!==void 0&&Object.keys(a).length>0?{...i,disabledConnectionReasons:a}:i;return await n.handle(e,o)}async#Ae(e){e?.kind===`model-access-changed`?(this.#F?.applyEffect({kind:`refresh-identity`}),this.#A=!0,await this.#Re(e)):e!==void 0&&(this.#F?.applyEffect(e),this.#A=!0,this.#De(this.#L))}async#je(e){if(e.effect===void 0)return e;let t=e.effect.kind===`model-access-changed`&&e.effect.reload?setTimeout(()=>{this.#g&&this.#n.setStartupPhase?.(`updating`),this.#n.setupFlow?.setStatus(`Loading selected model…`)},150):void 0;try{await this.#Ae(e.effect);let{effect:t,...n}=e;return n}catch{return{failed:!0,message:`Settings were saved, but the agent could not reload. Retry the command or restart eve dev.`}}finally{clearTimeout(t)}}async#Me(e,t,n){let r=await this.#ke(e,{...n,title:t});let i=r===void 0?void 0:await this.#je(r);return!(n.suppressSuccessfulTranscript===!0&&i?.failed!==!0||n.suppressCancelledTranscript===!0&&i?.cancelled===!0)&&n.trigger!==`startup`&&(i===void 0?this.#Oe({kind:`result`}):this.#Oe({kind:`result`,message:i.message,summary:i.summary})),this.#Pe(),i}async#Ne(e){this.#m?.({flow:`onboarding`,step:`model_provider`});let t=await this.#Me({type:`extension`,name:`login`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`});return!t?.cancelled&&t?.failed!==!0&&this.#m?.({flow:`onboarding`,step:`connection_ready`}),this.#h?.({flow:`onboarding`,step:`model_provider`,result:t?.cancelled?`cancelled`:t?.failed===!0?`error`:`completed`}),t}#Pe(){if(this.#g)return;let e=this.#b?.current().connection;e?.state===`ready`&&e.info!==this.#L&&(this.#L=e.info,this.#s!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#i,serverUrl:this.#s}))}async#Fe(e){if(this.#c===void 0||this.#n.traceViewer===void 0)this.#Oe({kind:`result`,message:`/traces is only available in local dev sessions.`});else try{await this.#n.traceViewer.open({appRoot:this.#c,sessionId:this.#t.snapshot.session?.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}finally{this.#Oe({kind:`dismiss`})}}async#Ie(){let e=this.#c;if(e===void 0)this.#Oe({kind:`result`,message:`/info is only available in local dev sessions.`});else try{let t=renderApplicationInfo(await this.#w(e));this.#n.showInfoPanel===void 0?this.#Oe({kind:`result`,message:t}):await this.#n.showInfoPanel(t)}catch(e){this.#Oe({kind:`result`,message:`Couldn't inspect the application: ${toErrorMessage(e)}`})}}#Le(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel none|error|warn|debug|all — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use none, error, warn, debug, or all.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`error`:return`Showing errors.`;case`warn`:return`Showing warnings and errors.`;case`debug`:return`Showing all severity-tagged logs.`;case`all`:return`Showing all logs.`}}async#Re(e){let t=this.#c;t!==void 0&&(++this.#M,++this.#j,await loadDevelopmentEnvironmentFiles(t),e.reload&&await this.#o?.refreshAfterSourceChange({}),e.model&&this.#L?this.#Z({...this.#L,agent:{...this.#L.agent,model:{...this.#L.agent.model,...e.model}}}):this.#Z(this.#L),this.#N=[],this.#P=void 0,this.#Te(),this.#ze())}async#ze(e=!1){let t=this.#L;let n=++this.#M;let r=await this.#Be();this.#E||n!==this.#M||r===void 0||(this.#Z(r),e&&!this.#n.renderAgentHeader&&this.#n.renderNotice?.(formatAgentUpdateNotice(t,r)),this.#De(this.#L))}async#Be(){let e=this.#e;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}#Ve(){this.#ze(!0)}#He(e){let t=this.#r;if(t!==void 0){for(let n of Object.values(e.agents))if(n.observation.status!==`not-followed`)for(let e of n.observation.conversation?.messages??[])for(let r of e.parts)r.type===`tool`&&r.state===`failed`&&(this.#K.has(r.callId)||(this.#K.add(r.callId),t.append({source:`tool`,summary:`${r.name} failed (subagent ${n.name})`,detail:r.error?.message??`Failed.`})))}}#Ue(e){let t=this.#r;if(t!==void 0)switch(e.type){case`call.requested`:this.#q.set(e.data.callId,e.data.capability.name),e.data.capability.kind===`tool`&&t.recordToolCall(e.data.capability.name);break;case`call.settled`:{let n=this.#q.get(e.data.callId)??e.data.callId;isTaskAdmissionRefused(e.data)?t.append({source:`tool`,summary:`${n} was refused for the model to retry`,detail:e.data.error?.message??`Refused.`}):e.data.outcome===`failed`&&t.append({source:`tool`,summary:`${n} failed`,detail:e.data.error?.message??`Tool failed.`});break}case`task.ended`:e.data.outcome===`failed`&&t.append({source:`tool`,summary:`${task(this.#t.snapshot.view,e.data.taskId)?.name??`A task`} ended with an error`,detail:e.data.error?.message??`Task failed.`});break;case`child.opened`:`callId`in e.data.owner&&t.recordSubagentDispatch(e.data.owner.callId);break;case`usage.recorded`:t.recordStepUsage(e.data.usage)}}#We(e){e.length<this.#G&&(this.#G=0);for(let{error:t}of e.slice(this.#G)){let e=formatFailureMessage(t);let n={detail:formatFailureDetail(t)??e,source:`workflow`,summary:`Error: ${e}`};this.#r?.append(t.hint===void 0?n:{...n,hint:t.hint})}this.#G=e.length}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,availablePromptCommands:e.availablePromptCommands,argumentSuggestions:e.argumentSuggestions,input:e.userInput,output:e.screen,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id;let r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}function registryHandoffs(e){let t=[];let collect=(e,n)=>{for(let r of e.messages)for(let e of r.parts){if(!isTerminalToolCallPart(e)||e.state!==`completed`)continue;let r=registryHandoffAddress(n,e.name,e.output);r!==void 0&&t.push({callId:e.callId,address:r})}};for(let t of Object.values(e.agents)){if(t.observation.status===`not-followed`)continue;let e=t.observation.conversation;e!==void 0&&collect(e,t.name)}return t}function registryHandoffAddress(e,t,n){if(e!==`self-modification__agent`||t!==`registry_add`||typeof n!=`object`||!n)return;let r=n;return r.status===`needs-terminal`&&typeof r.address==`string`?r.address:void 0}function inputContext(e,t,n){let r={};return n>1&&(r.position={index:t,total:n}),e.taskId!==void 0&&(r.taskId=e.taskId),r.position===void 0&&r.taskId===void 0?void 0:r}function toAgentTUIToolApprovalRequest(e,t){let n={approvalId:e.interactionId,toolCallId:e.call?.callId??e.interactionId,toolName:e.call?.name??e.request.kind,prompt:e.request.prompt,input:e.call?.input??{}};return t!==void 0&&(n.context=t),n}function toAgentTUIInputQuestion(e,t){let n=e.request.display===`text`?`text`:e.request.display===`select`||e.request.options!==void 0&&e.request.options.length>0?`select`:`text`;let r={requestId:e.interactionId,prompt:e.request.prompt,display:n};return e.request.options!==void 0&&(r.options=e.request.options.map(e=>{let t={id:e.id,label:e.label};e.description!==void 0&&(t.description=e.description);let n=optionStyle(e);return n!==void 0&&(t.style=n),t})),e.request.allowFreeform!==void 0&&(r.allowFreeform=e.request.allowFreeform),t!==void 0&&(r.context=t),r}export{EveTUIRunner,registryHandoffAddress};
|
|
4
|
+
`);t!==``&&this.#n.renderNotice?.(t)}}async#ke(e,t){let n=this.#_;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r=this.#L?.agent.model.endpoint;let i={...t,renderer:this.#n,settleOutcome:e=>this.#je(e),chatGptAccountLabel:r?.kind===`chatgpt`&&r.state===`ready`?r.accountLabel:void 0,withExclusiveTerminal:this.#y};let a=this.#I?.current();let o=a!==void 0&&Object.keys(a).length>0?{...i,disabledConnectionReasons:a}:i;return await n.handle(e,o)}async#Ae(e){e?.kind===`model-access-changed`?(this.#F?.applyEffect({kind:`refresh-identity`}),this.#A=!0,await this.#Re(e)):e!==void 0&&(this.#F?.applyEffect(e),this.#A=!0,this.#De(this.#L))}async#je(e){if(e.effect===void 0)return e;let t=e.effect.kind===`model-access-changed`&&e.effect.reload?setTimeout(()=>{this.#g&&this.#n.setStartupPhase?.(`updating`),this.#n.setupFlow?.setStatus(`Loading selected model…`)},150):void 0;try{await this.#Ae(e.effect);let{effect:t,...n}=e;return n}catch{return{failed:!0,message:`Settings were saved, but the agent could not reload. Retry the command or restart eve dev.`}}finally{clearTimeout(t)}}async#Me(e,t,n){let r=await this.#ke(e,{...n,title:t});let i=r===void 0?void 0:await this.#je(r);return!(n.suppressSuccessfulTranscript===!0&&i?.failed!==!0||n.suppressCancelledTranscript===!0&&i?.cancelled===!0)&&n.trigger!==`startup`&&(i===void 0?this.#Oe({kind:`result`}):this.#Oe({kind:`result`,message:i.message,summary:i.summary})),this.#Pe(),i}async#Ne(e){this.#m?.({flow:`onboarding`,step:`model_provider`});let t=await this.#Me({type:`extension`,name:`login`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`});return!t?.cancelled&&t?.failed!==!0&&this.#m?.({flow:`onboarding`,step:`connection_ready`}),this.#h?.({flow:`onboarding`,step:`model_provider`,result:t?.cancelled?`cancelled`:t?.failed===!0?`error`:`completed`}),t}#Pe(){if(this.#g)return;let e=this.#b?.current().connection;e?.state===`ready`&&e.info!==this.#L&&(this.#L=e.info,this.#s!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#i,serverUrl:this.#s}))}async#Fe(e){if(this.#c===void 0||this.#n.traceViewer===void 0)this.#Oe({kind:`result`,message:`/traces is only available in local dev sessions.`});else try{await this.#n.traceViewer.open({appRoot:this.#c,sessionId:this.#t.snapshot.session?.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}finally{this.#Oe({kind:`dismiss`})}}async#Ie(){let e=this.#c;if(e===void 0)this.#Oe({kind:`result`,message:`/info is only available in local dev sessions.`});else try{let t=renderApplicationInfo(await this.#w(e));this.#n.showInfoPanel===void 0?this.#Oe({kind:`result`,message:t}):await this.#n.showInfoPanel(t)}catch(e){this.#Oe({kind:`result`,message:`Couldn't inspect the application: ${toErrorMessage(e)}`})}}#Le(e){let t=this.#n;if(t.logDisplayMode===void 0||t.setLogDisplayMode===void 0)return`/loglevel is not available in this session.`;if(e===``)return`Logs: ${t.logDisplayMode()}. Use /loglevel none|error|warn|debug|all — logs stay buffered, so switching also hides or restores past lines.`;let n=parseLogDisplayMode(e);if(n===void 0)return`Unknown log level "${e}". Use none, error, warn, debug, or all.`;if(n===t.logDisplayMode())return`Logs already set to ${n}.`;switch(t.setLogDisplayMode(n),n){case`none`:return`Logs hidden. Output stays buffered — /loglevel all restores it.`;case`error`:return`Showing errors.`;case`warn`:return`Showing warnings and errors.`;case`debug`:return`Showing all severity-tagged logs.`;case`all`:return`Showing all logs.`}}async#Re(e){let t=this.#c;t!==void 0&&(++this.#M,++this.#j,await loadDevelopmentEnvironmentFiles(t),e.reload&&await this.#o?.refreshAfterSourceChange({}),e.model&&this.#L?this.#Z({...this.#L,agent:{...this.#L.agent,model:{...this.#L.agent.model,...e.model}}}):this.#Z(this.#L),this.#N=[],this.#P=void 0,this.#Te(),this.#ze())}async#ze(e=!1){let t=this.#L;let n=++this.#M;let r=await this.#Be();this.#E||n!==this.#M||r===void 0||(this.#Z(r),e&&!this.#n.renderAgentHeader&&this.#n.renderNotice?.(formatAgentUpdateNotice(t,r)),this.#De(this.#L))}async#Be(){let e=this.#e;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}#Ve(){this.#ze(!0)}#He(e){let t=this.#r;if(t!==void 0){for(let n of Object.values(e.agents))if(n.observation.status!==`not-followed`)for(let e of n.observation.conversation?.messages??[])for(let r of e.parts)r.type===`tool`&&r.state===`failed`&&(this.#K.has(r.callId)||(this.#K.add(r.callId),t.append({source:`tool`,summary:`${r.name} failed (subagent ${n.name})`,detail:r.error?.message??`Failed.`})))}}#Ue(e){let t=this.#r;if(t!==void 0)switch(e.type){case`call.requested`:this.#q.set(e.data.callId,e.data.capability.name),e.data.capability.kind===`tool`&&t.recordToolCall(e.data.capability.name);break;case`call.settled`:{let n=this.#q.get(e.data.callId)??e.data.callId;isTaskAdmissionRefused(e.data)?t.append({source:`tool`,summary:`${n} was refused for the model to retry`,detail:e.data.error?.message??`Refused.`}):e.data.outcome===`failed`&&t.append({source:`tool`,summary:`${n} failed`,detail:e.data.error?.message??`Tool failed.`});break}case`task.ended`:e.data.outcome===`failed`&&t.append({source:`tool`,summary:`${task(this.#t.snapshot.view,e.data.taskId)?.name??`A task`} ended with an error`,detail:e.data.error?.message??`Task failed.`});break;case`child.opened`:`callId`in e.data.owner&&t.recordSubagentDispatch(e.data.owner.callId);break;case`usage.recorded`:t.recordStepUsage(e.data.usage)}}#We(e){e.length<this.#G&&(this.#G=0);for(let{error:t}of e.slice(this.#G)){let e=formatFailureMessage(t);let n={detail:formatFailureDetail(t)??e,source:`workflow`,summary:`Error: ${e}`};this.#r?.append(t.hint===void 0?n:{...n,hint:t.hint})}this.#G=e.length}};function createRenderer(e){return e.renderer?e.renderer:new TerminalRenderer({tools:e.tools,reasoning:e.reasoning,subagents:e.subagents,connectionAuth:e.connectionAuth,assistantResponseStats:e.assistantResponseStats,contextSize:e.contextSize,logs:e.logs,availablePromptCommands:e.availablePromptCommands,argumentSuggestions:e.argumentSuggestions,input:e.userInput,output:e.screen,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id;let r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}function registryHandoffs(e){let t=[];let collect=(e,n)=>{for(let r of e.messages)for(let e of r.parts){if(!isTerminalToolCallPart(e)||e.state!==`completed`)continue;let r=registryHandoffAddress(n,e.name,e.output);r!==void 0&&t.push({callId:e.callId,address:r})}};for(let t of Object.values(e.agents)){if(t.observation.status===`not-followed`)continue;let e=t.observation.conversation;e!==void 0&&collect(e,t.name)}return t}function registryHandoffAddress(e,t,n){if(e!==`self-modification__agent`||t!==`registry_add`||typeof n!=`object`||!n)return;let r=n;return r.status===`needs-terminal`&&typeof r.address==`string`?r.address:void 0}function inputContext(e,t,n){let r={};return n>1&&(r.position={index:t,total:n}),e.taskId!==void 0&&(r.taskId=e.taskId),r.position===void 0&&r.taskId===void 0?void 0:r}function toAgentTUIToolApprovalRequest(e,t){let n={approvalId:e.interactionId,toolCallId:e.call?.callId??e.interactionId,toolName:e.call?.name??e.request.kind,prompt:e.request.prompt,input:e.call?.input??{}};return t!==void 0&&(n.context=t),n}function toAgentTUIInputQuestion(e,t){let n=e.request.display===`text`?`text`:e.request.display===`select`||e.request.options!==void 0&&e.request.options.length>0?`select`:`text`;let r={requestId:e.interactionId,prompt:e.request.prompt,display:n};return e.request.options!==void 0&&(r.options=e.request.options.map(e=>{let t={id:e.id,label:e.label};e.description!==void 0&&(t.description=e.description);let n=optionStyle(e);return n!==void 0&&(t.style=n),t})),e.request.display===`select`&&e.request.initialOptionId!==void 0&&(r.initialOptionId=e.request.initialOptionId),e.request.allowFreeform!==void 0&&(r.allowFreeform=e.request.allowFreeform),t!==void 0&&(r.context=t),r}export{EveTUIRunner,registryHandoffAddress};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{ConversationTranscript,turnActivity}from"./transcript.js";import{renderTaskPanelRows}from"./task-activity.js";import{interruptedError}from"./errors.js";import{argumentTypeaheadCompletion,argumentTypeaheadFor,argumentTypeaheadLoadingLabel,argumentTypeaheadQuery,moveArgumentTypeaheadSelection,renderArgumentSuggestions,selectedArgumentSuggestion}from"./argument-typeahead.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand,promptCommandSpec}from"./prompt-commands.js";import{enterBadge,flowMessageRows,renderAcknowledgeQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{renderFlowDrawer,renderTransientDrawer}from"./flow-drawer.js";import{initialPromptPlaceholder}from"./prompt-placeholder.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{buildAgentHeader}from"./agent-header.js";import{detectMarkdownRendering}from"./markdown.js";import{EMPTY_LINE,KillRing,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{copyTextToClipboard}from"./clipboard.js";import{TraceViewerSession}from"./traces/trace-viewer-session.js";import{buildStatusLine}from"./status-line.js";import{isLogVisible,nextLogDisplayMode}from"./log-display-mode.js";import{setConsoleRecordSubscriber}from"../console-records.js";import{createTheme,detectUnicode}from"./theme.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{fitQuestionPanel,inputContextLabel,renderQuestionPanel,renderQuestionPrompt}from"./question-panel.js";import{TurnClock}from"./turn-clock.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters}from"./stream-format.js";import{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.js";import{eveVersionTag}from"#cli/banner.js";import{format}from"node:util";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls,wrapVisibleLine}from"#cli/ui/terminal-text.js";import{toErrorMessage}from"#shared/errors.js";import{initialSelectState,orderedSelection,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{StringDecoder}from"node:string_decoder";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}const incompletePasteFlushMs=1e3;var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h=[];#g=new Map;#_;#v=new Set;#y=[];#b=0;#x=new ConversationTranscript;#S;#C=new Set;#w=[];#T;#E=`Send a message…`;#D;#O;#k;#A;#j=0;#M;#N=!1;#P;#F=[];#I;#L;#R;#z=``;#B=0;#V=new PromptHistory;#H=new KillRing;#U=!1;#W;#G;#K;#q=new Map;#J=new Map;#Y=!1;#X=!1;#Z=new TurnClock;#Q;#$=EMPTY_LINE;#ee;#te=!1;#ne;#re;#ie=`eve`;#ae=!1;#oe=!1;#se=!1;#ce=!1;#le=!1;#ue=!1;#de;#fe=!0;#pe=0;#me=Date.now();#he;#ge;#_e;#ve=!1;#ye;#be=``;#xe=new StringDecoder(`utf8`);#Se;#Ce;#we=!1;#Te=!1;#Ee;#De;#Oe=``;#ke=``;#Ae;#je;#Me;#Ne=!1;#Pe;#Fe=0;#Ie;#Le;#Re;#ze;#Be;#Ve=new MessageQueue;#He;#Ue;#We;#Ge;#Ke;setupFlow={begin:e=>this.#ot(e),setNavigation:e=>this.#st(e),end:e=>this.#ct(e?.preserveDiagnostics??!0),readSelect:e=>this.#lt(e),readEditableSelect:e=>this.#dt(e),readProviderPicker:e=>this.#ft(e),readText:e=>this.#pt(e),readAcknowledge:e=>this.#mt(e),readChoice:e=>this.#ut(e),setStatus:e=>this.#St(e),renderLine:(e,t)=>this.#Ct(e,t),replaceContent:e=>this.#wt(e),renderOutput:e=>this.#Tt(e),withInheritedStdio:e=>this.#Et(e),withExclusiveTerminal:e=>this.#Et(e),waitForInterrupt:e=>this.#yt(e)};traceViewer={open:e=>this.#Ot(e)};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=new AltScreen(this.#t),this.#i=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#a=e?.renderMarkdown??detectMarkdownRendering(),this.#o=e?.tools??`auto-collapsed`,this.#s=e?.reasoning??`auto-collapsed`,this.#c=e?.subagents??`collapsed`,this.#l=e?.connectionAuth??`full`,this.#u=e?.assistantResponseStats??`tokensPerSecond`,this.#Ee=e?.contextSize,this.#d=e?.captureForeignOutput??this.#t===process.stdout,this.#f=e?.diagnostics,this.#de=e?.onExitRequest,this.#K=e?.argumentSuggestions,this.#m=e?.logs??`error`,this.#p=e?.availablePromptCommands??PROMPT_COMMANDS}#qe(e){this.#W=typeaheadFor(this.#p,e,this.#W);let t=argumentTypeaheadQuery(e);if(t===void 0||this.#K===void 0){this.#G=void 0;return}let n=this.#q.get(t.command);if(n===void 0){this.#q.set(t.command,{kind:`loading`,visible:!1});let e=t.command;this.#J.set(e,setTimeout(()=>{this.#J.delete(e),this.#q.get(e)?.kind===`loading`&&(this.#q.set(e,{kind:`loading`,visible:!0}),this.#rn())},500)),this.#K(e).catch(()=>[]).then(t=>{let n=this.#J.get(e);n!==void 0&&clearTimeout(n),this.#J.delete(e),this.#q.set(e,{kind:`ready`,suggestions:t}),this.#U&&this.#qe(this.#z),this.#rn()}),this.#G=void 0}else this.#G=n.kind===`loading`?void 0:argumentTypeaheadFor(t,n.suggestions,this.#G)}#Je(e){let t=argumentTypeaheadQuery(this.#z);let n=t===void 0?void 0:this.#q.get(t.command);return n?.kind===`loading`&&n.visible&&t!==void 0?[clip(this.#i.colors.dim(`Loading ${argumentTypeaheadLoadingLabel(t.command)}…`),e)]:this.#G===void 0?this.#W!==void 0&&isTypeaheadOpen(this.#W)?renderCommandSuggestions(this.#W,this.#i,e):[]:renderArgumentSuggestions(this.#G,this.#i,e)}setStartupPhase(e){this.#O=e,e===void 0?this.#Kt():this.#Gt(),this.#rn()}renderAgentHeader(e){this.#M=void 0,this.#ie=e.name,this.#T=e,this.#D=e.info?.subagents.local.map(e=>e.name),this.#E=initialPromptPlaceholder(e.info,e.localDevelopment===!0),this.#jt();let t=this.#cn().join(`
|
|
2
|
-
`);this.#N?(t!==this.#P&&(this.#P=t,this.#Zt({kind:`agent-header`,body:t,live:!1})),this.#rn()):(this.#N=!0,this.#P=t,this.#n.flush(this.#cn(),this.#pn(this.#bn())))}beginStartupDraft(e){this.#jt({title:e.title}),this.#U=!0,this.#Y=!0,this.#O=`starting`,this.#M={name:e.title},this.#j=Date.now();let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#k=t,this.#$e(t),this.#Ht(),this.#Gt(),this.#rn();let apply=e=>{t=e,this.#k=e,this.#Wt(),this.#$e(t),this.#rn()};this.#A=e=>{if(e.type===`escape`&&this.#Ue!==void 0){this.#Ue(`escape`);return}if(e.type===`ctrl-c`&&this.#Ue!==void 0){this.#Dt(),this.#Ue(`ctrl-c`);return}let n=this.#H.apply(t,e,{multiline:!0});n===void 0?e.type===`enter`&&t.text.trim().length>0?this.#Ve.enqueue(t.text)&&apply(EMPTY_LINE):e.type===`ctrl-c`&&this.#de?.():apply(n)},this.#Ye()}#Ye(){this.#k!==void 0&&this.#A!==void 0&&(this.#Vt(),this.#$e(this.#k),this.#U=!0,this.#ye=this.#A,this.#Pt())}finishStartupDraft(){let e={draft:this.#k?.text??this.#z,queuedPrompt:this.#Ve.takePrompt()};return this.#k=void 0,this.#A=void 0,this.#Ft(),this.#Ut(),this.#U=!1,this.#Y=!1,e}async readInput(e){this.#jt(e),this.#S?.working!==!0&&this.#Qt(),this.#U=!0,this.#Y=!0,this.#le=this.#ue,this.#ue=!1;let t=e?.initialDraft===void 0?this.#$:lineOf(stripPromptControlCharacters(e.initialDraft));return this.#V.begin(t.text),this.#$e(t),this.#qe(t.text),this.#Ht(),this.#rn(),await new Promise((n,r)=>{let i=e?.signal;let release=()=>{this.#ee=void 0,i?.removeEventListener(`abort`,onAbort),this.#W=void 0,this.#G=void 0,this.#U=!1,this.#Ut(),this.#Ft(),this.#rn()};let finish=e=>{release(),n(e)};let onAbort=()=>finish(void 0);if(i?.addEventListener(`abort`,onAbort,{once:!0}),i?.aborted){onAbort();return}this.#ne=e=>{i?.removeEventListener(`abort`,onAbort),r(e)};let apply=e=>{t=e,this.#$=e,this.#Wt(),this.#$e(t),this.#qe(e.text),this.#rn()};this.#ee=apply;let recall=e=>{e!==void 0&&apply(lineOf(e))};let interrupt=()=>{this.#W=void 0,this.#Ut(),this.#Nt(),r(interruptedError())};let cancel=()=>{this.#te=!0,finish({type:`cancel`})};let suggestions=()=>this.#W!==void 0&&isTypeaheadOpen(this.#W)?this.#W:void 0;let argumentSuggestions=()=>this.#G?.suggestions.length?this.#G:void 0;let highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ye=e=>{e.type!==`ctrl-c`&&this.#le&&(this.#le=!1,this.#rn());let n=this.#H.apply(t,e,{multiline:!0});if(n!==void 0){apply(n);return}let r=this.#S?.working===!0;switch(e.type){case`up`:case`ctrl-p`:{let e=argumentSuggestions();if(e!==void 0){this.#G=moveArgumentTypeaheadSelection(e,-1),this.#rn();break}let n=suggestions();if(n!==void 0){this.#W=moveTypeaheadSelection(n,-1),this.#rn();break}let r=movePromptLine(t,`up`);r===void 0?recall(this.#V.previous(t.text)):apply(r);break}case`down`:case`ctrl-n`:{let e=argumentSuggestions();if(e!==void 0){this.#G=moveArgumentTypeaheadSelection(e,1),this.#rn();break}let n=suggestions();if(n!==void 0){this.#W=moveTypeaheadSelection(n,1),this.#rn();break}let r=movePromptLine(t,`down`);r===void 0?recall(this.#V.next()):apply(r);break}case`tab`:{let e=argumentSuggestions();let t=e===void 0?void 0:selectedArgumentSuggestion(e);if(e!==void 0&&t!==void 0){apply(lineOf(argumentTypeaheadCompletion(e,t)));break}let n=highlighted();n!==void 0&&apply(lineOf(typeaheadCompletion(n)));break}case`escape`:{if(this.#G!==void 0){this.#G=void 0,this.#rn();break}let e=suggestions();if(e!==void 0){this.#W=dismissTypeahead(e),this.#rn();break}r&&!this.#te&&cancel();break}case`enter`:{let e=argumentSuggestions();let n=e===void 0?void 0:selectedArgumentSuggestion(e);let i=highlighted();if(e!==void 0&&n?.next!==void 0&&e.completed.length===0){apply(lineOf(`${argumentTypeaheadCompletion(e,n)} `));break}if(e===void 0&&i!==void 0&&this.#K!==void 0&&(i.name===`add`||i.name===`login`||i.name===`loglevel`||i.name===`model`)){apply(lineOf(typeaheadCompletion(i)));break}let a=e!==void 0&&n!==void 0?argumentTypeaheadCompletion(e,n):i!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(i).trimEnd():t.text;if(a.trim().length===0)break;promptCommandSpec(a)?.spec.history!==`omit`&&this.#V.add(a),this.#$=EMPTY_LINE,this.#$e(EMPTY_LINE),isPromptControlCommand(a)?(this.#it(stripTerminalControls(a.trim())),r&&parsePromptCommand(a)?.type===`cancel`&&(this.#te=!0)):(this.#X=!0,this.#f?.recordPrompt(),r&&this.#w.push(a)),finish({type:`submit`,text:a});break}case`ctrl-d`:t.text.length===0?(this.#Dt(),interrupt()):apply(deleteForward(t));break;case`ctrl-l`:this.#on();break;case`ctrl-r`:this.#rn();break;case`ctrl-c`:if(r){if(!this.#te){cancel();break}this.#te=!1,this.#ue=!0,finish({type:`interrupt`});break}if(this.#le){this.#Dt(),interrupt();break}this.#le=!0,apply(EMPTY_LINE)}},this.#Pt()})}renderConversation(e){let t=this.#S?.working===!0;this.#S=e,e.conversation.messages.some(e=>e.role===`user`)&&(this.#X=!0);let n=this.#x.project(e,this.#Ze());let r=new Set;for(let[e,t]of n.entries()){let i=t.id;if(this.#v.has(i))continue;r.add(i);let a=this.#g.get(i);if(a!==t){if(t.updateSeq=++this.#b,a!==void 0)this.#h[this.#h.indexOf(a)]=t,this.#g.set(i,t);else{if(t.kind===`user`){let e=this.#w.indexOf(t.body??``);e!==-1&&(this.#w.splice(e,1),t.promptOrigin=`steer`)}this.#Xe(t,n.slice(e+1))}}}for(let e of this.#C)r.has(e)||this.#nn(e);this.#C=r,e.working&&!t?this.#Z.armed||this.#Z.arm(e.data.usage):!e.working&&t&&(this.#te=!1,this.#U&&this.#Qt()),this.#Xt(),this.#rn()}#Xe(e,t){let n=t.find(e=>this.#g.has(e.id));let r=n===void 0?-1:this.#h.indexOf(this.#g.get(n.id));r===-1?this.#Zt(e):(e.id!==this.#je?.id&&this.#Pn(),this.#h.splice(r,0,e),this.#g.set(e.id,e))}#Ze(){return{tools:this.#o,reasoning:this.#s,subagents:this.#c,connectionAuth:this.#l,subagentNames:this.#D,diagnosticsPath:this.#f?.displayPath,dot:this.#i.glyph.dot}}#Qe(e){if(e?.taskId===void 0||e.requester!==void 0||this.#S===void 0)return inputContextLabel(e,this.#i);let t=this.#x.taskLabel(this.#S.conversation,e.taskId);return inputContextLabel(t===void 0?e:{...e,requester:t},this.#i)}#$e(e){this.#z=e.text,this.#B=e.cursor}async readToolApproval(e,t){this.#jt(t),this.#U=!1;let n=0;return this.#Ie=t=>renderTransientDrawer(renderQuestionPanel({prompt:e.prompt,options:[{id:`yes`,label:`Yes`},{id:`no`,label:`No`}],cursor:n,allowFreeform:!1,editor:EMPTY_LINE,caretVisible:!1,maxRows:this.#xn()-5},this.#i,t),[`y yes · n no · Ctrl-C cancel`],this.#i,t,this.#Qe(e.context),!1,`left`),this.#rn(),await new Promise((e,t)=>{let approve=()=>{this.#Ie=void 0,this.#Ft(),this.#rn(),e({approved:!0})};let deny=()=>{this.#Ie=void 0,this.#Ft(),this.#rn(),e({approved:!1,reason:`Denied by user.`})};this.#ne=t,this.#ye=e=>{switch(e.type){case`text`:{if(e.framing!==`unframed`)break;let t=e.value.toLowerCase();t===`y`?approve():t===`n`&&deny();break}case`up`:case`ctrl-p`:n=0,this.#rn();break;case`down`:case`ctrl-n`:n=1,this.#rn();break;case`enter`:n===0?approve():deny();break;case`ctrl-r`:this.#rn();break;case`ctrl-c`:this.#Ie=void 0,this.#Nt(),t(interruptedError())}},this.#Pt()})}async readInputQuestion(e,t){this.#jt(t),this.#U=!1,this.#Y=!1;let n=e.options??[];let r=n.length>0;let i=(e.allowFreeform===!0||!r)&&r;let a=n.length+ +!!i;let o=questionSectionId(e.requestId);let s=r?`select`:`text`;let c=0;let l=EMPTY_LINE;let isOnFreeformRow=()=>i&&c===n.length;let selectDrawer=t=>renderTransientDrawer([...renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#fe,maxRows:this.#xn()-5},this.#i,t)],[`↑/↓ move · enter to select · esc to dismiss`],this.#i,t,this.#Qe(e.context),!1,`left`);let textPanel=t=>{let n=promptInputRows({text:l.text,cursor:l.cursor,width:Math.max(1,t-2),theme:this.#i,caretVisible:this.#fe,ghost:``,maxRows:3});return n.at(-1)===``&&n.pop(),renderTransientDrawer(fitQuestionPanel([...renderQuestionPrompt(e.prompt,this.#i,t),``,...n.map(e=>` ${e}`)],this.#xn()-5),[`Enter submit · Esc dismiss`],this.#i,t,this.#Qe(e.context),!1,`left`)};let syncFreeformCaret=()=>{isOnFreeformRow()?this.#Ht():(this.#Ut(),this.#Wt())};s===`select`?(s=`select`,this.#U=!1,this.#nn(o),this.#Ie=selectDrawer,syncFreeformCaret(),this.#rn()):(s=`text`,this.#Ie=textPanel,this.#U=!0,this.#$e(l),this.#Ht(),this.#rn());let finalize=t=>{this.#Ie=void 0,this.#tn({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.#U=!1,this.#Ut(),this.#Ft(),this.#rn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};let dismiss=()=>{this.#Ie=void 0,this.#tn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Skipped. The question stays open.`)}`,preformatted:!0,live:!1}),this.#U=!1,this.#Ut(),this.#Ft(),this.#rn(),u(void 0)};let moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#rn())};let selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))};let u;return await new Promise((t,n)=>{this.#ne=n,u=t,this.#ye=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Wt(),s===`text`&&this.#$e(l),this.#rn();return}this.#Ie=void 0,this.#Ut(),this.#Nt(),n(interruptedError());return}if(t.type===`ctrl-r`){this.#rn();return}if(s===`select`){let n=setupSelectionIntent(t,{textNavigation:!isOnFreeformRow()});if(n?.kind===`move`){moveCursor(n.direction===`up`?-1:1);return}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.#Wt(),this.#rn();break}dismiss();break;default:if(isOnFreeformRow()){let e=this.#H.apply(l,t);e!==void 0&&(l=e,this.#Wt(),this.#rn())}}return}let r=this.#H.apply(l,t,{multiline:!0});if(r!==void 0)l=r,this.#Wt(),this.#$e(l),this.#rn();else switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Wt(),this.#$e(l),this.#rn());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.#Wt(),this.#$e(l),this.#rn();break}dismiss()}},this.#Pt()})}setVercelStatus(e){this.#L=e,this.#rn()}setRemoteConnectionStatus(e){this.#R=e,this.#rn()}reset(){this.#h=[],this.#g.clear(),this.#v.clear(),this.#I=void 0,this.#F.length=0,this.#y.length=0,this.#N=!1,this.#P=void 0,this.#et(),this.#X=!1,this.#je=void 0,this.#ae&&(this.#n.clearAll(),this.#rn())}renderSessionBoundary(){this.#Qt();let e=this.#x.stopWorking(this.#Ze());for(let e of this.#C){let t=this.#g.get(e);if(t===void 0)continue;this.#g.delete(e);let n=this.#h.indexOf(t);let{id:r,...i}=t;this.#h[n]={...i,live:!1}}for(let{id:t,...n}of e)this.#Zt(n);this.#v.clear(),this.#et();let t=this.#i.colors;let n=this.#i.glyph;let r=t.dim(`${n.cornerOpen}${n.dash.repeat(2)} Session restarted, clear context.`);this.#Zt({kind:`session-boundary`,body:r,live:!1}),this.#rn()}#et(){this.#x.reset(),this.#S=void 0,this.#C=new Set,this.#w.length=0,this.#te=!1,this.#Z.reset(),this.#Xt()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#jt(),this.#Zt({kind:`notice`,body:t,live:!1}),this.#rn())}restoreDraft(e){let t=this.#U?this.#ee:void 0;if((t===void 0?this.#$.text:this.#z).length>0)return;let n=lineOf(stripPromptControlCharacters(e));t===void 0?this.#$=n:t(n),this.renderNotice(`The turn was cancelled from outside this prompt, so its message is back in the input.`)}renderSetupWarning(e){let t=stripTerminalControls(e);t.trim().length===0?this.#tt():(this.#jt(),this.#Be=t,this.#rn())}clearSetupWarning(){this.#tt()}#tt(){this.#Be!==void 0&&(this.#Be=void 0,this.#rn())}renderCommandInvocation(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#jt(),this.#it(t),this.#rn())}async choosePromptCommand(e){this.#jt(),this.#U=!1;let t=typeaheadFor(e,`/`);return this.#Le=e=>{let n=renderCommandSuggestions(t,this.#i,e);let r=Math.max(1,this.#xn()-7);let i=Math.max(0,Math.min(t.selectedIndex-r+1,n.length-r));return renderTransientDrawer(n.slice(i,i+r),[`↑/↓ move · Enter select · Esc close`],this.#i,e)},this.#rn(),await new Promise(e=>{this.#Re=()=>e(void 0),this.#ye=n=>{if(n.type===`up`||n.type===`ctrl-p`)t=moveTypeaheadSelection(t,-1),this.#rn();else if(n.type===`down`||n.type===`ctrl-n`)t=moveTypeaheadSelection(t,1),this.#rn();else if(n.type===`enter`){let n=selectedTypeaheadCommand(t);this.#nt(),e(n===void 0?void 0:typeaheadCompletion(n))}else(n.type===`escape`||n.type===`ctrl-c`)&&(this.#nt(),e(void 0))},this.#Pt()})}async showInfoPanel(e){this.#jt(),this.#U=!1;let t=stripAnsi(e);let n=0;let infoRows=e=>t.split(`
|
|
2
|
+
`);this.#N?(t!==this.#P&&(this.#P=t,this.#Zt({kind:`agent-header`,body:t,live:!1})),this.#rn()):(this.#N=!0,this.#P=t,this.#n.flush(this.#cn(),this.#pn(this.#bn())))}beginStartupDraft(e){this.#jt({title:e.title}),this.#U=!0,this.#Y=!0,this.#O=`starting`,this.#M={name:e.title},this.#j=Date.now();let t=lineOf(stripPromptControlCharacters(e.initialDraft??``));this.#k=t,this.#$e(t),this.#Ht(),this.#Gt(),this.#rn();let apply=e=>{t=e,this.#k=e,this.#Wt(),this.#$e(t),this.#rn()};this.#A=e=>{if(e.type===`escape`&&this.#Ue!==void 0){this.#Ue(`escape`);return}if(e.type===`ctrl-c`&&this.#Ue!==void 0){this.#Dt(),this.#Ue(`ctrl-c`);return}let n=this.#H.apply(t,e,{multiline:!0});n===void 0?e.type===`enter`&&t.text.trim().length>0?this.#Ve.enqueue(t.text)&&apply(EMPTY_LINE):e.type===`ctrl-c`&&this.#de?.():apply(n)},this.#Ye()}#Ye(){this.#k!==void 0&&this.#A!==void 0&&(this.#Vt(),this.#$e(this.#k),this.#U=!0,this.#ye=this.#A,this.#Pt())}finishStartupDraft(){let e={draft:this.#k?.text??this.#z,queuedPrompt:this.#Ve.takePrompt()};return this.#k=void 0,this.#A=void 0,this.#Ft(),this.#Ut(),this.#U=!1,this.#Y=!1,e}async readInput(e){this.#jt(e),this.#S?.working!==!0&&this.#Qt(),this.#U=!0,this.#Y=!0,this.#le=this.#ue,this.#ue=!1;let t=e?.initialDraft===void 0?this.#$:lineOf(stripPromptControlCharacters(e.initialDraft));return this.#V.begin(t.text),this.#$e(t),this.#qe(t.text),this.#Ht(),this.#rn(),await new Promise((n,r)=>{let i=e?.signal;let release=()=>{this.#ee=void 0,i?.removeEventListener(`abort`,onAbort),this.#W=void 0,this.#G=void 0,this.#U=!1,this.#Ut(),this.#Ft(),this.#rn()};let finish=e=>{release(),n(e)};let onAbort=()=>finish(void 0);if(i?.addEventListener(`abort`,onAbort,{once:!0}),i?.aborted){onAbort();return}this.#ne=e=>{i?.removeEventListener(`abort`,onAbort),r(e)};let apply=e=>{t=e,this.#$=e,this.#Wt(),this.#$e(t),this.#qe(e.text),this.#rn()};this.#ee=apply;let recall=e=>{e!==void 0&&apply(lineOf(e))};let interrupt=()=>{this.#W=void 0,this.#Ut(),this.#Nt(),r(interruptedError())};let cancel=()=>{this.#te=!0,finish({type:`cancel`})};let suggestions=()=>this.#W!==void 0&&isTypeaheadOpen(this.#W)?this.#W:void 0;let argumentSuggestions=()=>this.#G?.suggestions.length?this.#G:void 0;let highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ye=e=>{e.type!==`ctrl-c`&&this.#le&&(this.#le=!1,this.#rn());let n=this.#H.apply(t,e,{multiline:!0});if(n!==void 0){apply(n);return}let r=this.#S?.working===!0;switch(e.type){case`up`:case`ctrl-p`:{let e=argumentSuggestions();if(e!==void 0){this.#G=moveArgumentTypeaheadSelection(e,-1),this.#rn();break}let n=suggestions();if(n!==void 0){this.#W=moveTypeaheadSelection(n,-1),this.#rn();break}let r=movePromptLine(t,`up`);r===void 0?recall(this.#V.previous(t.text)):apply(r);break}case`down`:case`ctrl-n`:{let e=argumentSuggestions();if(e!==void 0){this.#G=moveArgumentTypeaheadSelection(e,1),this.#rn();break}let n=suggestions();if(n!==void 0){this.#W=moveTypeaheadSelection(n,1),this.#rn();break}let r=movePromptLine(t,`down`);r===void 0?recall(this.#V.next()):apply(r);break}case`tab`:{let e=argumentSuggestions();let t=e===void 0?void 0:selectedArgumentSuggestion(e);if(e!==void 0&&t!==void 0){apply(lineOf(argumentTypeaheadCompletion(e,t)));break}let n=highlighted();n!==void 0&&apply(lineOf(typeaheadCompletion(n)));break}case`escape`:{if(this.#G!==void 0){this.#G=void 0,this.#rn();break}let e=suggestions();if(e!==void 0){this.#W=dismissTypeahead(e),this.#rn();break}r&&!this.#te&&cancel();break}case`enter`:{let e=argumentSuggestions();let n=e===void 0?void 0:selectedArgumentSuggestion(e);let i=highlighted();if(e!==void 0&&n?.next!==void 0&&e.completed.length===0){apply(lineOf(`${argumentTypeaheadCompletion(e,n)} `));break}if(e===void 0&&i!==void 0&&this.#K!==void 0&&(i.name===`add`||i.name===`login`||i.name===`loglevel`||i.name===`model`)){apply(lineOf(typeaheadCompletion(i)));break}let a=e!==void 0&&n!==void 0?argumentTypeaheadCompletion(e,n):i!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(i).trimEnd():t.text;if(a.trim().length===0)break;promptCommandSpec(a)?.spec.history!==`omit`&&this.#V.add(a),this.#$=EMPTY_LINE,this.#$e(EMPTY_LINE),isPromptControlCommand(a)?(this.#it(stripTerminalControls(a.trim())),r&&parsePromptCommand(a)?.type===`cancel`&&(this.#te=!0)):(this.#X=!0,this.#f?.recordPrompt(),r&&this.#w.push(a)),finish({type:`submit`,text:a});break}case`ctrl-d`:t.text.length===0?(this.#Dt(),interrupt()):apply(deleteForward(t));break;case`ctrl-l`:this.#on();break;case`ctrl-r`:this.#rn();break;case`ctrl-c`:if(r){if(!this.#te){cancel();break}this.#te=!1,this.#ue=!0,finish({type:`interrupt`});break}if(this.#le){this.#Dt(),interrupt();break}this.#le=!0,apply(EMPTY_LINE)}},this.#Pt()})}renderConversation(e){let t=this.#S?.working===!0;this.#S=e,e.conversation.messages.some(e=>e.role===`user`)&&(this.#X=!0);let n=this.#x.project(e,this.#Ze());let r=new Set;for(let[e,t]of n.entries()){let i=t.id;if(this.#v.has(i))continue;r.add(i);let a=this.#g.get(i);if(a!==t){if(t.updateSeq=++this.#b,a!==void 0)this.#h[this.#h.indexOf(a)]=t,this.#g.set(i,t);else{if(t.kind===`user`){let e=this.#w.indexOf(t.body??``);e!==-1&&(this.#w.splice(e,1),t.promptOrigin=`steer`)}this.#Xe(t,n.slice(e+1))}}}for(let e of this.#C)r.has(e)||this.#nn(e);this.#C=r,e.working&&!t?this.#Z.armed||this.#Z.arm(e.data.usage):!e.working&&t&&(this.#te=!1,this.#U&&this.#Qt()),this.#Xt(),this.#rn()}#Xe(e,t){let n=t.find(e=>this.#g.has(e.id));let r=n===void 0?-1:this.#h.indexOf(this.#g.get(n.id));r===-1?this.#Zt(e):(e.id!==this.#je?.id&&this.#Pn(),this.#h.splice(r,0,e),this.#g.set(e.id,e))}#Ze(){return{tools:this.#o,reasoning:this.#s,subagents:this.#c,connectionAuth:this.#l,subagentNames:this.#D,diagnosticsPath:this.#f?.displayPath,dot:this.#i.glyph.dot}}#Qe(e){if(e?.taskId===void 0||e.requester!==void 0||this.#S===void 0)return inputContextLabel(e,this.#i);let t=this.#x.taskLabel(this.#S.conversation,e.taskId);return inputContextLabel(t===void 0?e:{...e,requester:t},this.#i)}#$e(e){this.#z=e.text,this.#B=e.cursor}async readToolApproval(e,t){this.#jt(t),this.#U=!1;let n=0;return this.#Ie=t=>renderTransientDrawer(renderQuestionPanel({prompt:e.prompt,options:[{id:`yes`,label:`Yes`},{id:`no`,label:`No`}],cursor:n,allowFreeform:!1,editor:EMPTY_LINE,caretVisible:!1,maxRows:this.#xn()-5},this.#i,t),[`y yes · n no · Ctrl-C cancel`],this.#i,t,this.#Qe(e.context),!1,`left`),this.#rn(),await new Promise((e,t)=>{let approve=()=>{this.#Ie=void 0,this.#Ft(),this.#rn(),e({approved:!0})};let deny=()=>{this.#Ie=void 0,this.#Ft(),this.#rn(),e({approved:!1,reason:`Denied by user.`})};this.#ne=t,this.#ye=e=>{switch(e.type){case`text`:{if(e.framing!==`unframed`)break;let t=e.value.toLowerCase();t===`y`?approve():t===`n`&&deny();break}case`up`:case`ctrl-p`:n=0,this.#rn();break;case`down`:case`ctrl-n`:n=1,this.#rn();break;case`enter`:n===0?approve():deny();break;case`ctrl-r`:this.#rn();break;case`ctrl-c`:this.#Ie=void 0,this.#Nt(),t(interruptedError())}},this.#Pt()})}async readInputQuestion(e,t){this.#jt(t),this.#U=!1,this.#Y=!1;let n=e.options??[];let r=n.length>0;let i=(e.allowFreeform===!0||!r)&&r;let a=n.length+ +!!i;let o=questionSectionId(e.requestId);let s=r?`select`:`text`;let c=Math.max(0,n.findIndex(t=>t.id===e.initialOptionId));let l=EMPTY_LINE;let isOnFreeformRow=()=>i&&c===n.length;let selectDrawer=t=>renderTransientDrawer([...renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#fe,maxRows:this.#xn()-5},this.#i,t)],[`↑/↓ move · enter to select · esc to dismiss`],this.#i,t,this.#Qe(e.context),!1,`left`);let textPanel=t=>{let n=promptInputRows({text:l.text,cursor:l.cursor,width:Math.max(1,t-2),theme:this.#i,caretVisible:this.#fe,ghost:``,maxRows:3});return n.at(-1)===``&&n.pop(),renderTransientDrawer(fitQuestionPanel([...renderQuestionPrompt(e.prompt,this.#i,t),``,...n.map(e=>` ${e}`)],this.#xn()-5),[`Enter submit · Esc dismiss`],this.#i,t,this.#Qe(e.context),!1,`left`)};let syncFreeformCaret=()=>{isOnFreeformRow()?this.#Ht():(this.#Ut(),this.#Wt())};s===`select`?(s=`select`,this.#U=!1,this.#nn(o),this.#Ie=selectDrawer,syncFreeformCaret(),this.#rn()):(s=`text`,this.#Ie=textPanel,this.#U=!0,this.#$e(l),this.#Ht(),this.#rn());let finalize=t=>{this.#Ie=void 0,this.#tn({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.#U=!1,this.#Ut(),this.#Ft(),this.#rn();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};let dismiss=()=>{this.#Ie=void 0,this.#tn({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Skipped. The question stays open.`)}`,preformatted:!0,live:!1}),this.#U=!1,this.#Ut(),this.#Ft(),this.#rn(),u(void 0)};let moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#rn())};let selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))};let u;return await new Promise((t,n)=>{this.#ne=n,u=t,this.#ye=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Wt(),s===`text`&&this.#$e(l),this.#rn();return}this.#Ie=void 0,this.#Ut(),this.#Nt(),n(interruptedError());return}if(t.type===`ctrl-r`){this.#rn();return}if(s===`select`){let n=setupSelectionIntent(t,{textNavigation:!isOnFreeformRow()});if(n?.kind===`move`){moveCursor(n.direction===`up`?-1:1);return}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.#Wt(),this.#rn();break}dismiss();break;default:if(isOnFreeformRow()){let e=this.#H.apply(l,t);e!==void 0&&(l=e,this.#Wt(),this.#rn())}}return}let r=this.#H.apply(l,t,{multiline:!0});if(r!==void 0)l=r,this.#Wt(),this.#$e(l),this.#rn();else switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Wt(),this.#$e(l),this.#rn());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.#Wt(),this.#$e(l),this.#rn();break}dismiss()}},this.#Pt()})}setVercelStatus(e){this.#L=e,this.#rn()}setRemoteConnectionStatus(e){this.#R=e,this.#rn()}reset(){this.#h=[],this.#g.clear(),this.#v.clear(),this.#I=void 0,this.#F.length=0,this.#y.length=0,this.#N=!1,this.#P=void 0,this.#et(),this.#X=!1,this.#je=void 0,this.#ae&&(this.#n.clearAll(),this.#rn())}renderSessionBoundary(){this.#Qt();let e=this.#x.stopWorking(this.#Ze());for(let e of this.#C){let t=this.#g.get(e);if(t===void 0)continue;this.#g.delete(e);let n=this.#h.indexOf(t);let{id:r,...i}=t;this.#h[n]={...i,live:!1}}for(let{id:t,...n}of e)this.#Zt(n);this.#v.clear(),this.#et();let t=this.#i.colors;let n=this.#i.glyph;let r=t.dim(`${n.cornerOpen}${n.dash.repeat(2)} Session restarted, clear context.`);this.#Zt({kind:`session-boundary`,body:r,live:!1}),this.#rn()}#et(){this.#x.reset(),this.#S=void 0,this.#C=new Set,this.#w.length=0,this.#te=!1,this.#Z.reset(),this.#Xt()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#jt(),this.#Zt({kind:`notice`,body:t,live:!1}),this.#rn())}restoreDraft(e){let t=this.#U?this.#ee:void 0;if((t===void 0?this.#$.text:this.#z).length>0)return;let n=lineOf(stripPromptControlCharacters(e));t===void 0?this.#$=n:t(n),this.renderNotice(`The turn was cancelled from outside this prompt, so its message is back in the input.`)}renderSetupWarning(e){let t=stripTerminalControls(e);t.trim().length===0?this.#tt():(this.#jt(),this.#Be=t,this.#rn())}clearSetupWarning(){this.#tt()}#tt(){this.#Be!==void 0&&(this.#Be=void 0,this.#rn())}renderCommandInvocation(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#jt(),this.#it(t),this.#rn())}async choosePromptCommand(e){this.#jt(),this.#U=!1;let t=typeaheadFor(e,`/`);return this.#Le=e=>{let n=renderCommandSuggestions(t,this.#i,e);let r=Math.max(1,this.#xn()-7);let i=Math.max(0,Math.min(t.selectedIndex-r+1,n.length-r));return renderTransientDrawer(n.slice(i,i+r),[`↑/↓ move · Enter select · Esc close`],this.#i,e)},this.#rn(),await new Promise(e=>{this.#Re=()=>e(void 0),this.#ye=n=>{if(n.type===`up`||n.type===`ctrl-p`)t=moveTypeaheadSelection(t,-1),this.#rn();else if(n.type===`down`||n.type===`ctrl-n`)t=moveTypeaheadSelection(t,1),this.#rn();else if(n.type===`enter`){let n=selectedTypeaheadCommand(t);this.#nt(),e(n===void 0?void 0:typeaheadCompletion(n))}else(n.type===`escape`||n.type===`ctrl-c`)&&(this.#nt(),e(void 0))},this.#Pt()})}async showInfoPanel(e){this.#jt(),this.#U=!1;let t=stripAnsi(e);let n=0;let infoRows=e=>t.split(`
|
|
3
3
|
`).flatMap(t=>wrapVisibleLine(t,Math.max(1,e-4)).map(e=>` ${e}`));this.#Le=e=>{let t=infoRows(e);let r=Math.max(1,this.#xn()-7);return n=Math.min(n,Math.max(0,t.length-r)),renderTransientDrawer(t.slice(n,n+r),[t.length>r?`↑/↓ scroll · Esc close`:`Esc to close`],this.#i,e)},this.#rn(),await new Promise(e=>{this.#Re=e,this.#ye=t=>{if(t.type===`up`||t.type===`ctrl-p`)n=Math.max(0,n-1),this.#rn();else if(t.type===`down`||t.type===`ctrl-n`){let e=Math.max(1,this.#xn()-7);n=Math.min(n+1,Math.max(0,infoRows(this.#bn()).length-e)),this.#rn()}else(t.type===`escape`||t.type===`ctrl-c`||t.type===`enter`)&&(this.#nt(),e())},this.#Pt()})}#nt(){this.#Le=void 0,this.finishCommand({kind:`dismiss`}),this.#ye=void 0,this.#Re=void 0,this.#Ft(),this.#rn()}finishCommand(e){if(e.kind===`dismiss`){this.#rt()&&this.#rn();return}let t=this.#at(e.summary);t!==void 0&&(t.status=`done`);let n=e.message===void 0?``:stripAnsi(e.message);if(n.trim().length===0){t!==void 0&&this.#rn();return}this.#jt();let r={kind:`result`,body:n,live:!1};this.#Zt(r);let i=t===void 0?-1:this.#h.indexOf(t);i!==-1&&(this.#h.pop(),this.#h.splice(i+1,0,r)),this.#rn()}#rt(){let e=this.#_;return e!==void 0&&(this.#_=void 0,this.#h=this.#h.filter(t=>t!==e),!0)}#it(e){this.#_!==void 0&&this.#at();let t={kind:`command`,body:e,live:!0};this.#_=t,this.#Zt(t)}#at(e){let t=this.#_;if(t!==void 0)return this.#_=void 0,t.live=!1,e!==void 0&&(t.result=stripTerminalControls(e)),t}#ot(e){this.#jt(),this.#k===void 0&&(this.#U=!1),this.#ze={title:stripTerminalControls(e),startedAtMs:Date.now(),lines:[],outputBuffer:[]},this.#Gt(),this.#rn()}#st(e){this.#ze!==void 0&&(this.#ze.navigation=e,this.#rn())}#ct(e){this.#Ue=void 0,this.#xt();let t=this.#ze;if(t!==void 0){if(this.#ze=void 0,this.#k===void 0?this.#Kt():this.#Ye(),e){let e=[];for(let n of t.lines)n.evidence===!0?e.push(n.text):((n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#Zt({kind:`flow`,title:`info`,body:e.join(`
|
|
4
4
|
`),live:!1}),this.#Zt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[])}this.#rn()}}async#lt(e){let t=this.#ht(e.message);let n=isMultiSelectRequest(e);let r=e.kind===`search`?e.searchAction:void 0;let i=e.kind===`search`&&e.layout===void 0;let a=e.options;let o=e.navigation?.kind===`planner`;let s={options:a,searchAction:r,submitRow:n&&!o};`initialValue`in e&&e.initialValue!==void 0&&(s.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(s.initialValues=e.initialValues);let c=initialSelectState(s);let l;let u=!1;let d=0;let isCurrentSearch=e=>e===d;let clearSearch=()=>{d+=1,u=!1,c=reduceSelect(c,{type:`clear`},{options:a,searchAction:r,submitRow:n&&!o}),this.#rn()};let loadSearch=async(e,t)=>{u=!0,l=void 0;let i=++d;this.#rn();try{let s=await t(e);if(!isCurrentSearch(i))return;let l=c.filter;a=s,c={...initialSelectState({options:s,searchAction:r,submitRow:n&&!o}),filter:l}}catch(e){isCurrentSearch(i)&&(l=toErrorMessage(e))}finally{isCurrentSearch(i)&&(u=!1,this.#rn())}};let f=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length;let r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));f=e.notices??r,t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,message:``,options:a,select:c};return f!==void 0&&f.length>0&&(t.notices=f),l!==void 0&&(t.error=l),u&&(t.loadingFrame=this.#un()),i&&(t.caretVisible=this.#fe),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),i&&this.#Ht(),this.#rn(),await this.#vt((t,s)=>{let close=e=>{d+=1,s(e)};if(u){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#rn();return}let f=e.navigation?.kind===`planner`?e.navigation:void 0;let p=t.type===`left`&&(f?.activeStep??0)>(f?.firstNavigableStep??0)?`back`:t.type===`right`&&f!==void 0&&f.activeStep>=(f.firstNavigableStep??0)&&f.activeStep<f.steps.length-1?`forward`:void 0;if(p!==void 0){close({kind:`navigate`,direction:p,values:n?orderedSelection(a,c.selected):[]});return}let m={key:t,options:a,searchAction:r,select:c};let h=reduceSetupSelectInput(n?{...m,kind:e.kind,required:e.required,plannerNavigation:o||void 0}:{...m,kind:e.kind});switch(h.kind){case`cancel`:close(void 0);return;case`repaint`:this.#rn();return;case`update`:c=h.select,l=void 0,i&&this.#Wt(),this.#rn();return;case`submit`:{let e=searchActionQuery(h.values[0]??``);let t=r?.load;if(e===void 0||t===void 0){close(h.values);return}loadSearch(e,t);return}case`error`:l=h.message,this.#rn();return;case`ignore`:return}},i?()=>this.#Ut():void 0).promise}#ut(e){this.#jt();let t=this.#gt();t.status={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.#rn();let r=this.#vt((t,r)=>{let i=setupSelectionIntent(t,{textNavigation:!0});switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#rn();return;case`repaint`:this.#rn();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#dt(e){let t=this.#ht(e.message);let n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n);let i=lineOf(``);let a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:``,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#fe,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;let syncEditableRow=()=>{onEditableRow()?this.#Ht():(i=lineOf(``),this.#Ut())};return syncEditableRow(),this.#rn(),await this.#vt((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Wt(),this.#rn()};let applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#rn()};let 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();let s=e.editable.validate?.(o);s===void 0?n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o}):(a=s,this.#rn())};let o=setupSelectionIntent(t,{textNavigation:!onEditableRow()});switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#rn();return;case void 0:}if(!onEditableRow())return;let s=this.#H.apply(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ut()).promise}async#ft(e){this.#H.clear();let t=this.#ht(e.message);let n=initialProviderPickerState(e.options,e.initialValue);let r;let cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor);let 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();let i={kind:`inline-edit`,layout:`stacked`,message:``,options:e.options,select:n.select,edit:{optionValue:`ai-gateway-key`,caretVisible:this.#fe,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.#Ht():this.#Ut()};return syncCaret(),this.#rn(),await this.#vt((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.#rn();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#rn();return;case`validate`:{n=o.state,syncCaret(),this.#rn();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}};let o=setupSelectionIntent(t,{textNavigation:n.phase.kind===`inactive`});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.#rn();return;case void 0:}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Wt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ut()}).promise}async#pt(e){e.mask===!0&&this.#H.clear();let t=this.#ht(e.message);let n=lineOf(``);let r;return t.question=t=>{let i={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.#fe)},this.#Ht(),this.#rn(),await this.#vt((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Wt(),this.#rn()};let a=e.mask?applyLineEditorKey(n,t):this.#H.apply(n,t);if(a!==void 0)apply(a);else switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#rn();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``;let a=e.validate?.(t);if(a!==void 0){r=a,this.#rn();return}i(t);return}default:return}},()=>this.#Ut()).promise}async#mt(e){let t=this.#ht(e.message);return t.question=t=>renderAcknowledgeQuestion({message:``,lines:e.lines},this.#i,t),this.#rn(),await this.#vt((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#rn();return;default:return}}).promise}#ht(e){this.#jt(),this.#U=!1;let t=this.#gt();return t.questionTitle=stripTerminalControls(e),t.status!==void 0&&(t.status=void 0,t.summary=void 0,t.preview=void 0),t}#gt(){return this.#ze===void 0&&(this.#ze={title:``,startedAtMs:Date.now(),lines:[],outputBuffer:[],implicit:!0}),this.#ze}#_t(){this.#ze?.implicit===!0?this.#ze=void 0:this.#ze!==void 0&&(this.#ze.question=void 0,this.#ze.questionTitle=void 0,this.#ze.hideLinesWhileQuestion=!1),this.#ye=void 0,this.#Ft(),this.#k===void 0?this.#ze!==void 0&&this.#bt():this.#Ye(),this.#ze===void 0&&this.#rn()}#vt(e,t){let n=!1;let r;let i;let a=new Promise((e,t)=>{r=e,i=t});let settle=e=>{n||(n=!0,t?.(),this.#_t(),r(e))};let reject=e=>{n||(n=!0,t?.(),this.#_t(),i(e))};return this.#Vt(),this.#ye=t=>{t.type===`ctrl-c`&&this.#Dt(),e(t,settle,reject)},this.#Pt(),{promise:a,settle}}#yt(e){let t;let n=new Promise(e=>{t=e});return this.#Ue=t,this.#bt(e?.interruptible??!0),{promise:n,dispose:()=>{this.#Ue===t&&(this.#Ue=void 0,this.#xt())}}}#bt(e=!0){if(this.#k!==void 0){this.#Ye();return}if(this.#Ue===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#Dt();let e=this.#Ue;this.#Ue=void 0,this.#xt(),e?.(t.type===`ctrl-c`?`ctrl-c`:`escape`)}else t.type===`ctrl-r`&&this.#rn()};this.#We=consumer,this.#Vt(),this.#ye=consumer,this.#Pt()}#xt(){this.#We!==void 0&&(this.#ye===this.#We&&this.#Ft(),this.#We=void 0)}#St(e){let t=e===void 0?void 0:{text:stripTerminalControls(e),startedAtMs:Date.now()};this.#ze===void 0?this.#U||this.#S?.working===!0||(t===void 0?(this.#re=void 0,this.#Kt(),this.#rn()):(this.#jt(),this.#me=Date.now(),this.#Gt(),this.#re=t.text,this.#rn())):(this.#ze.status=t,t===void 0&&(this.#ze.preview=void 0),this.#rn())}#Ct(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#ze;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.#rn()}else this.#jt(),this.#Zt({kind:`flow`,title:t,body:n,live:!1}),this.#rn()}#wt(e){let t=this.#ze;t!==void 0&&(t.lines=[],t.outputBuffer=[],t.preview=void 0,t.status=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.#rn())}#Tt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#ze;n===void 0?this.#Ct(t,`info`):(n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#rn())}async#Et(e){this.#be=``,this.#Vt(),this.#Ue=void 0,this.#xt(),this.#Ft(),this.#qt(),this.#n.clear(),this.#Cn(),this.#r.enter({cursor:`visible`,mouse:!1}),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#r.exit(),this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#be=``,this.#Vt(),this.#n.hideCursor(),this.#Sn(),this.#ze===void 0?this.#Xt():(this.#Gt(),this.#bt()),this.#n.reset(),this.#rn()}}setSessionId(e){this.#He=e}shutdown(){this.#Nt();for(let e of this.#J.values())clearTimeout(e);if(this.#J.clear(),this.#oe&&!this.#se){this.#se=!0;let e=this.#He===void 0?``:` ${this.#i.glyph.dot} session ${this.#He}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}requestInterrupt(){this.#ze!==void 0&&this.#ye?.({type:`ctrl-c`}),this.#Nt()}exitRequested(){return this.#ce}#Dt(){this.#ce=!0,this.#de?.()}async#Ot(e){if(this.#Ge!==void 0||!this.#ae)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#bn(),height:this.#xn()}),paint:e=>this.#r.paint(e,this.#xn()),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.#At=e,this.#ye=e=>{t.handleKey(e)===`close`&&this.#kt()},this.#Pt(),t.start()})}#kt(){let e=this.#Ge;if(e===void 0)return;this.#Ge=void 0,e.dispose(),this.#Ft(),this.#r.exit(),this.#n.hideCursor(),this.#rn(),this.#n.showCursor();let t=this.#At;this.#At=void 0,t?.()}#At;#jt(e){this.#ie=e?.title??this.#ie,this.#ae||(this.#ae=!0,this.#oe=!0,this.#n.reset(),this.#n.hideCursor(),this.#Sn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#Ce=()=>this.#rn(),this.#t.on(`resize`,this.#Ce),process.on(`exit`,this.#Mt))}#Mt=()=>{this.#ae&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#Nt(){this.#Ie=void 0;let e=this.#Re;e!==void 0&&(this.#Re=void 0,this.#Le=void 0,this.finishCommand({kind:`dismiss`}),this.#ye=void 0,e()),this.#kt();let t=this.#ne;if(this.#ne=void 0,t?.(interruptedError()),this.#Ft(),this.#Ut(),this.#qt(),this.#_e!==void 0&&(clearTimeout(this.#_e),this.#_e=void 0),this.#ve=!1,this.#Mn(),this.#ae){this.#Pn(),this.#at();for(let e of this.#h)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#rn(),this.#n.clear(),this.#n.showCursor(),this.#Cn(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#Ce&&=(this.#t.off(`resize`,this.#Ce),void 0),process.off(`exit`,this.#Mt),this.#ae=!1}}#Pt(){this.#e.off(`data`,this.#It),this.#e.on(`data`,this.#It),this.#be.length>0&&queueMicrotask(()=>{this.#ye!==void 0&&this.#be.length>0&&(this.#zt(),this.#Lt())})}#Ft(){this.#e.off(`data`,this.#It),this.#Vt(),this.#ye=void 0}#It=e=>{this.#Vt(),this.#be+=this.#xe.write(e),this.#zt(),this.#Lt()};#Lt(){if(this.#be===`\x1B`)this.#Se=setTimeout(()=>{this.#be===`\x1B`&&(this.#be=``,this.#Rt({type:`escape`}))},30),this.#Se.unref?.();else if(isIncompletePaste(this.#be)){let e=this.#be;this.#Se=setTimeout(()=>{if(this.#be!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#be=``,t.length>0&&this.#Rt({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#Se.unref?.()}else if(isIncompleteOsc(this.#be)){let e=this.#be;this.#Se=setTimeout(()=>{this.#be===e&&(this.#be=``)},incompletePasteFlushMs),this.#Se.unref?.()}}#Rt(e){this.#H.interruptYank(e),this.#ye?.(e)}#zt(){for(;this.#be.length>0;){let e=nextKey(this.#be);if(e.incomplete)return;this.#be=this.#be.slice(e.consumed),e.key!==void 0&&e.key.type!==`ignore`&&(e.key.type===`osc`?this.#Bt(e.key.value):this.#Rt(e.key))}}#Bt(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#Ke=t,this.#Ge?.setTerminalBackground(t))}#Vt(){this.#Se&&=(clearTimeout(this.#Se),void 0)}#Ht(){this.#Ut(),this.#Wt(),this.#he=setInterval(()=>{this.#fe=!this.#fe,this.#rn()},500),this.#he.unref?.()}#Ut(){this.#he&&=(clearInterval(this.#he),void 0),this.#fe=!0}#Wt(){this.#fe=!0}#Gt(){this.#qt(),this.#ge=setInterval(()=>{this.#pe+=1,this.#rn()},90),this.#ge.unref?.()}#Kt(){this.#Jt()||this.#qt()}#qt(){this.#ge&&=(clearInterval(this.#ge),void 0)}#Jt(){return this.#S?.working===!0||this.#x.tasks.length>0}#Yt(e,t=Math.max(8,Math.floor(this.#xn()/2))){let n=this.#x.tasks;if(n.length===0)return[];let r=this.#S?.working===!0&&this.#re===void 0;let i=Date.now();let a=r&&this.#S!==void 0?turnActivity(this.#S,n):`Working`;return renderTaskPanelRows(n,{width:e,theme:this.#i,nowMs:i,maxRows:t,activity:a.startsWith(`Waiting for `)?`Waiting`:a,turnElapsedMs:r?Math.max(0,i-(this.#Z.startedAtMs??i)):void 0})}#Xt(){this.#Jt()?this.#ge===void 0&&(this.#me=Date.now(),this.#Gt()):this.#ze===void 0&&this.#O===void 0&&this.#re===void 0&&this.#qt()}#Zt(e){e.id!==this.#je?.id&&this.#Pn(),e.updateSeq=++this.#b,this.#h.push(e),e.id&&this.#g.set(e.id,e)}#Qt(){let e=this.#Z.settle(this.#$t());if(e===void 0||(this.#Q=e,this.#f?.reportStats(),e.elapsedMs<=1e4&&e.inputTokens<=2e4))return;let t=`Done in ${this.#hn(e)}`;let n=this.#S?.data.lastStepUsage?.inputTokens??0;if(this.#Ee!==void 0&&this.#Ee>0&&n>0){let e=Math.round(n/this.#Ee*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#Zt({kind:`turn-stats`,body:t,live:!1})}#$t(){return this.#S?.data.usage??{inputTokens:0,outputTokens:0}}renderError(e,t){this.#jt(),this.#en(e,t)}#en(e,t,n={}){let r=stripTerminalControls(e);let i=stripTerminalControls(t);let a=n.detail===void 0?void 0:stripTerminalControls(n.detail);let o=n.hint===void 0?void 0:stripTerminalControls(n.hint);let s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#f?.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.#f===void 0?a:`details: ${this.#f.displayPath}`),this.#Zt(c),this.#rn()}#tn(e){if(e.id&&this.#v.has(e.id))return;let t=e.id?this.#g.get(e.id):void 0;t?(Object.assign(t,e),t.updateSeq=++this.#b):this.#Zt(e)}#nn(e){this.#h=this.#h.filter(t=>t.id!==e),this.#g.delete(e)}#rn(){if(this.#ae){if(this.#we)this.#Te=!0;else{this.#we=!0;try{do this.#Te=!1,this.#in();while(this.#Te)}finally{this.#we=!1}}}}#in(){if(!this.#ae)return;if(this.#Ge!==void 0){this.#Ge.repaint();return}let e=this.#bn();let t=this.#pn(e);let n=this.#M===void 0?[]:this.#cn();let r=Math.max(0,this.#xn()-n.length-t.length);let i=[];let a=this.#I;let o=groupToolBlocksForDisplay(this.#h);let s=0;for(;s<o.length&&o[s].display.live===!1;)s+=1;if(s>0){let e=new Set(o.slice(0,s).flatMap(e=>e.members));for(let t=this.#h.length-1;t>=0;--t)e.has(this.#h[t])&&this.#h.splice(t,1)}for(let t of o.slice(0,s)){for(let e of t.members)this.#y.push(e),e.id&&(this.#v.add(e.id),this.#g.delete(e.id));if(this.#In(t.display))continue;let n=this.#ln(t.display,e,a);a=previousBlockOf(t.display),this.#I=a,i.push(...n),this.#F.push(...n)}let c=[];for(let{display:t}of o.slice(s)){if(this.#In(t))continue;let n=this.#ln(t,e,a);a=previousBlockOf(t);for(let e=0;e<n.length;e+=1)c.push({block:t,row:n[e]})}let l=[...n,...clipLiveRows(c.map(e=>e.row),r,e,this.#i),...t];i.length>0?this.#n.flush(i,l):this.#n.update(l)}#an(){if(!this.#ae)return;let e=this.#bn();let t=this.#pn(e);let n=Math.max(0,this.#xn()-t.length);let r=this.#I;let i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#h)){if(this.#In(t))continue;let n=this.#ln(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.#cn(),...this.#F],a)}logDisplayMode(){return this.#m}setLogDisplayMode(e){e!==this.#m&&(this.#m=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#sn(),this.#ae&&this.#an())}flushDelayedDevBuildErrors(){let e=this.#Ae;e!==void 0&&(this.#Ae=void 0,this.#Zt({kind:`log`,title:`stderr`,logLevel:`error`,body:e,live:!1}),this.#rn())}#on(){this.#ve=!0,this.#_e!==void 0&&clearTimeout(this.#_e),this.#_e=setTimeout(()=>{this.#ve=!1,this.#_e=void 0,this.#rn()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#m)),this.#rn()}#sn(){let e=this.#bn();this.#F.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#y,{logCoalescing:`runs`})){if(this.#In(n))continue;let r=this.#ln(n,e,t);t=previousBlockOf(n),this.#F.push(...r)}this.#I=t}#cn(){let e=this.#T;let t=this.#M;if(e===void 0&&t===void 0)return[];let n={name:e?.name??t?.name,theme:this.#i,width:this.#bn()};return e?.info!==void 0&&(n.info=e.info),buildAgentHeader(n)}#ln(e,t,n){let r={renderMarkdown:this.#a,activityPulse:this.#dn(this.#me,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n),this.#ze!==void 0&&(r.setupFlowOpen=!0),this.#Le!==void 0&&(r.transientPanelOpen=!0);let i=renderBlockLines(e,t,this.#i,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#un(){return this.#i.spinner[this.#pe%this.#i.spinner.length]??``}#dn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#fn(e){return{glyph:this.#dn(e.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}}#pn(e){let t=this.#i.colors;let n=[``];if(this.#Le!==void 0){let t=this.#Le(e);return[...t.rows,...t.controls]}if(this.#Ie!==void 0){let t=this.#Ie(e);let n=this.#xn()-t.rows.length-t.controls.length-1;return[...(n>=4?this.#Yt(e,n+1):[]).slice(0,-1),...t.rows,...t.controls].map(t=>clip(t,e))}let r=this.#ze;if(r!==void 0&&(this.#k===void 0||r.question!==void 0)){let t=this.#fn(r);let i;if(r.status!==void 0){let{startedAtMs:e,...n}=r.status;let a=Date.now()-e;let o=a>=5e3?` ${formatTurnDuration(a)}`:``;i={...n,text:`${n.text}${o}`,indicator:t}}let a;if(r.question!==void 0){let t=r.question(e);a={kind:`question`,title:r.questionTitle,rows:t},i!==void 0&&(a={kind:`question`,title:r.questionTitle,rows:t,status:i})}else i===void 0?a=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(a={kind:`status`,status:i},r.preview!==void 0&&(a={kind:`status`,status:i,preview:r.preview}));let o={title:r.title,navigation:r.navigation,lines:r.summary===void 0?r.hideLinesWhileQuestion===!0?[]:r.lines:[{text:r.summary.headline,tone:`success`},...r.summary.facts.map(e=>({text:`${e.label}: ${e.value}`,tone:`info`}))],content:a};let s=renderFlowDrawer(o,this.#i,e);return n.length===1&&n[0]===``&&(n.length=0),n.push(...s.rows),s.controls.length>0&&n.push(...s.controls),this.#vn(n,e),n}r!==void 0&&n.push(...flowMessageRows(r.lines,this.#i).map(t=>t.length===0?``:clip(` ${t}`,e))),this.#O===void 0&&this.#Be!==void 0&&n.push(...renderAttentionRows(this.#Be,e,this.#i),``);let i=this.#S?.working===!0&&this.#re===void 0;let a=this.#Yt(e);a.length>0&&n.push(...a);let o=renderMessageQueueRows({view:this.#Ve.view(),width:e,theme:this.#i});if(o.length>0&&n.push(...o,``),i&&(a.length===0&&n.push(this.#mn(e)),this.#te&&n.push(clip(`${t.yellow(this.#i.glyph.dotActive)} ${t.dim(`Cancelling turn… · Ctrl+C to stop waiting, then again to exit`)}`,e)),(a.length===0||this.#te)&&n.push(``)),this.#U){let r=this.#W===void 0?void 0:inlineCommandHint(this.#W);let a=this.#Je(e);this.#le&&n.push(clip(t.dim(`Press Ctrl+C again to exit`),e),``);let o=r?t.dim(` ${r}`):``;let s=[];this.#_n(s,e);let c=Math.max(1,this.#xn()-1-n.length-1-a.length-s.length-(a.length>0?2:0));let l={text:this.#z,cursor:this.#B,width:e,theme:this.#i,caretVisible:this.#fe,ghost:o,maxRows:c};this.#Y&&this.#z.length===0&&(l.placeholder=this.#k===void 0?this.#X||i?``:this.#E:`Message · Enter to queue`);let u=promptInputRows(l);return a.length>0&&u.at(-1)===``&&u.pop(),n.push(...u),a.length>0&&n.push(t.dim(this.#i.glyph.dash.repeat(e))),n.push(...a),a.length>0&&s.length>0&&n.push(t.dim(this.#i.glyph.dash.repeat(e))),n.push(...s),n}if(i||this.#$.text.length>0)return this.#gn(n,e,{inert:i,adjacent:a.length>0}),this.#_n(n,e),n;let s=this.#re??`Ready`;let c=this.#yn();let l=t.dim(this.#i.glyph.dot);let u=c?`${l} ${s} ${t.dim(this.#i.glyph.dot)} ${c}`:`${l} ${s}`;return n.push(clip(u,e)),this.#_n(n,e),n}#mn(e){let t=this.#i.colors;let n=this.#Z.startedAtMs??Date.now();let r=Math.max(0,Date.now()-n);let i=r%1e3<500?this.#i.unicode?`•`:`*`:` `;let a=r<1e3?`0s`:formatTurnDuration(Math.floor(r/1e3)*1e3);let o=`${this.#S===void 0?`Thinking`:turnActivity(this.#S,this.#x.tasks)} (${a})`;let{inputTokens:s,outputTokens:c}=this.#Z.usage(this.#$t());return clip(`${i} ${o}${s>0||c>0?t.dim(` (${formatTokenFlow({inputTokens:s,outputTokens:c},this.#i.glyph)})`):``}`,e)}#hn(e){let{inputTokens:t,outputTokens:n}=e;let r=t===0&&n===0?``:` (${formatTokenFlow({inputTokens:t,outputTokens:n},this.#i.glyph)})`;return`${formatTurnDuration(e.elapsedMs)}${r}`}#gn(e,t,n){!n.adjacent&&e.at(-1)!==``&&e.push(``);let r={text:this.#$.text,cursor:this.#$.cursor,width:t,theme:this.#i,caretVisible:!0,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#$.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#_n(e,t){if(this.#O!==void 0){let n=this.#ze?.status?.text??{starting:`Starting agent…`,connecting:`Reading saved connection…`,updating:`Loading selected model…`}[this.#O];let r=this.#dn(this.#j,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH);e.push(clip(this.#i.colors.dim(`${r} ${n}`),t));return}let n=this.#R===void 0?``:` `;let r=Math.max(1,t-n.length);let i={theme:this.#i,width:r};this.#Ne&&this.#Me!==void 0&&(i.devBuild=this.#Me),this.#ve&&(i.logLevel=this.#m);let a=this.#T?.info?.agent.model;if(a?.routing.kind===`dynamic`){let e=this.#S?.data.modelId;i.dynamicModel=!0,e!==void 0&&(i.model=e)}else a?.id!==void 0&&(i.model=a.id);a?.reasoning!==void 0&&a.reasoning!==`provider-default`&&(i.reasoning=a.reasoning),readGatewayServiceTier(a?.providerOptions).kind===`priority`&&(i.fastMode=!0);let o=a?.endpoint;o!==void 0&&(i.endpoint=o),this.#L!==void 0&&(i.vercel=this.#L),this.#R!==void 0&&(i.remote=this.#R);let s=buildStatusLine(i);s!==void 0&&e.push(clip(`${n}${s}`,t))}#vn(e,t){if(this.#R===void 0)return;let n=Math.max(1,t-2);let r=buildStatusLine({remote:this.#R,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#yn(){let e=this.#i.colors;let t=[];let n=this.#Q;let r=n===void 0?void 0:formatAssistantResponseStats({totalTokens:n.inputTokens+n.outputTokens,outputTokens:n.outputTokens,tokensPerSecond:n.elapsedMs>0?n.outputTokens/(n.elapsedMs/1e3):void 0},this.#u);return r&&t.push(r),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#bn(){return Math.max(20,this.#t.columns||80)}#xn(){return Math.max(8,this.#t.rows||24)}#Sn(){if(this.#De!==void 0||!this.#d)return;this.#Oe=``,this.#ke=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0;let a=typeof n==`function`?n:r;return this.#En(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}};let e=[`error`,`warn`,`log`,`info`,`debug`];let t=e.map(e=>[e,console[e]]);for(let t of e)console[t]=(...e)=>this.#Tn({level:t===`log`?`info`:t,text:format(...e)});setConsoleRecordSubscriber(e=>this.#Tn(e));let n=capture(process.stdout,`stdout`);let r=capture(process.stderr,`stderr`);this.#f?.subscribeLogRecords(e=>this.#wn(e)),this.#De=()=>{this.#f?.unsubscribeLogRecords(),setConsoleRecordSubscriber(void 0);for(let[e,n]of t)console[e]=n;n(),r()}}#Cn(){let e=this.#De;e!==void 0&&(this.#De=void 0,e(),this.#Oe.length>0&&(this.#f?.append({source:`stdout`,detail:this.#Oe}),this.#Fn()&&process.stdout.write(`${this.#Oe}\n`),this.#Oe=``),this.#ke.length>0&&(this.#f?.append({source:`stderr`,detail:this.#ke}),this.#Fn()&&process.stderr.write(`${this.#ke}\n`),this.#ke=``))}#wn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#On(`[eve:${e.namespace}] ${e.message}${t}`,e.level),this.#rn()}#Tn(e){let t=e.level===`error`||e.level===`warn`?`stderr`:`stdout`;this.#f?.append({source:t,level:e.level,detail:e.text}),t===`stderr`?this.#On(stripAnsi(e.text),e.level):this.#Dn(stripAnsi(e.text),e.level),this.#rn()}#En(e,t){let n=(e===`stdout`?this.#Oe:this.#ke)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Oe=``,this.#f?.append({source:e,detail:n.trimEnd()}),this.#Dn(n.trimEnd()),this.#rn();return}let r=n.lastIndexOf(`
|
|
5
5
|
`);let i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Oe=i:this.#ke=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#f?.append({source:e,detail:a}),e===`stdout`?this.#Dn(a):this.#On(a),this.#rn())}#Dn(e,t){let n=[];let flushPending=()=>{if(n.length===0)return;let e=n.join(`
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"zod": "4.5.4",
|
|
62
62
|
"zod-validation-error": "5.0.0"
|
|
63
63
|
},
|
|
64
|
-
"scriptHash": "
|
|
64
|
+
"scriptHash": "4f5dac0b788b070979ca67258e39f27040a05aa1fd86e8bd3f74aeb3a8061341",
|
|
65
65
|
"toolVersions": {
|
|
66
66
|
"env-runner>crossws": "0.4.17",
|
|
67
67
|
"env-runner>srvx": "1.0.8",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalDevRequestKey}from"#context/keys.js";import{AsyncLocalStorage}from"node:async_hooks";import{resolveKey}from"#context/key.js";const EVE_CONTEXT_STORAGE_KEY=Symbol.for(`eve.context-storage`);var ContextContainer=class{_durableValues=new Map;_virtualValues=new Map;constructor(e){let t=e!==void 0&&Object.hasOwn(e,`localDevRequest`)?e.localDevRequest:contextStorage.getStore()?.localDevRequest;t!==void 0&&this._durableValues.set(LocalDevRequestKey.name,t)}get localDevRequest(){return this.get(LocalDevRequestKey)}get(e){return this._virtualValues.has(e.name)?this._virtualValues.get(e.name):this._durableValues.get(e.name)}require(e){if(!this.has(e))throw Error(`Context key "${e.name}" is not set.`);return this.get(e)}has(e){return this._virtualValues.has(e.name)||this._durableValues.has(e.name)}set(e,t){let n=typeof t==`function`?t(this.get(e)):t;return this._durableValues.set(e.name,n),n}ensure(e,t){return this.has(e)?this.require(e):this.set(e,t())}delete(e){let t=this._durableValues.delete(e.name);let n=this._virtualValues.delete(e.name);return t||n}clearVirtualContext(){this._virtualValues.clear()}setVirtualContext(e,t){this._virtualValues.set(e.name,t)}*entries(){for(let[e,t]of this._durableValues){let n=resolveKey(e);n!==void 0&&(yield[n,t])}}};const globalContextStorage=globalThis;globalContextStorage[EVE_CONTEXT_STORAGE_KEY]===void 0&&(globalContextStorage[EVE_CONTEXT_STORAGE_KEY]=new AsyncLocalStorage);const storage=globalContextStorage[EVE_CONTEXT_STORAGE_KEY];const contextStorage={getStore:()=>storage.getStore()?.context,run:(e,t)=>storage.run({context:e},t)};function contextScopeValue(e){return storage.getStore()?.values?.get(e)}function withContextScopeValue(e,t,n){let r=storage.getStore();let i=new Map(r?.values);return i.set(e,t),storage.run({context:r?.context,values:i},n)}function loadContext(){let e=contextStorage.getStore();if(e===void 0)throw Error(`No active eve context. Call this function only from
|
|
1
|
+
import{LocalDevRequestKey}from"#context/keys.js";import{AsyncLocalStorage}from"node:async_hooks";import{resolveKey}from"#context/key.js";const EVE_CONTEXT_STORAGE_KEY=Symbol.for(`eve.context-storage`);var ContextContainer=class{_durableValues=new Map;_virtualValues=new Map;constructor(e){let t=e!==void 0&&Object.hasOwn(e,`localDevRequest`)?e.localDevRequest:contextStorage.getStore()?.localDevRequest;t!==void 0&&this._durableValues.set(LocalDevRequestKey.name,t)}get localDevRequest(){return this.get(LocalDevRequestKey)}get(e){return this._virtualValues.has(e.name)?this._virtualValues.get(e.name):this._durableValues.get(e.name)}require(e){if(!this.has(e))throw Error(`Context key "${e.name}" is not set.`);return this.get(e)}has(e){return this._virtualValues.has(e.name)||this._durableValues.has(e.name)}set(e,t){let n=typeof t==`function`?t(this.get(e)):t;return this._durableValues.set(e.name,n),n}ensure(e,t){return this.has(e)?this.require(e):this.set(e,t())}delete(e){let t=this._durableValues.delete(e.name);let n=this._virtualValues.delete(e.name);return t||n}clearVirtualContext(){this._virtualValues.clear()}setVirtualContext(e,t){this._virtualValues.set(e.name,t)}*entries(){for(let[e,t]of this._durableValues){let n=resolveKey(e);n!==void 0&&(yield[n,t])}}};const globalContextStorage=globalThis;globalContextStorage[EVE_CONTEXT_STORAGE_KEY]===void 0&&(globalContextStorage[EVE_CONTEXT_STORAGE_KEY]=new AsyncLocalStorage);const storage=globalContextStorage[EVE_CONTEXT_STORAGE_KEY];const contextStorage={getStore:()=>storage.getStore()?.context,run:(e,t)=>storage.run({context:e},t)};function contextScopeValue(e){return storage.getStore()?.values?.get(e)}function withContextScopeValue(e,t,n){let r=storage.getStore();let i=new Map(r?.values);return i.set(e,t),storage.run({context:r?.context,values:i},n)}function loadContext(){let e=contextStorage.getStore();if(e===void 0)throw Error(`No active eve context. Call this function only from code eve runs, such as tools, hooks, channel handlers, and model callbacks.`);return e}export{ContextContainer,contextScopeValue,contextStorage,loadContext,withContextScopeValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{contextScopeValue,withContextScopeValue}from"#context/container.js";const WORKFLOW_STEP=Symbol.for(`eve.workflowStep`);function runInWorkflowStep(e){return withContextScopeValue(WORKFLOW_STEP,!0,e)}function isInWorkflowStep(){return contextScopeValue(WORKFLOW_STEP)===!0}export{isInWorkflowStep,runInWorkflowStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@1.0.0-rc.
|
|
1
|
+
import{runJsProgram}from"#execution/dynamic-workflow/workflow.js";async function runWorkflowProgramTask(e,t){"use workflow";return runJsProgram(e.js,t,{maxSubagents:e.maxSubagents??0})}runWorkflowProgramTask.workflowId=`workflow//eve@1.0.0-rc.9//runWorkflowProgramTask`;export{runWorkflowProgramTask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);let{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@1.0.0-rc.
|
|
1
|
+
import{decide}from"#ai/decide.js";async function runAgentRouterTask(e,t){"use workflow";let n=await chooseTarget(e.message,descriptions(t),t.abortSignal);let{reply:r,status:i}=await(await t.agent(n).send(e.message,{signal:t.abortSignal})).result();if(i===`failed`)throw Error(`Agent "${n}" failed to handle the task.`);return r??null}async function chooseTarget(e,t,n){"use step";let r=Object.keys(t);if(r.length===0)throw Error(`agentRouter requires at least one available agent with a description.`);return r.length===1?r[0]:(await decide({signal:n,state:{message:e},questions:{route:{type:`choice`,instructions:`Which subagent should handle this task?`,criteria:t}}})).answers.route.choice}function descriptions(e){return Object.fromEntries(Object.entries(e.agents).flatMap(([e,t])=>{let n=t.description.trim();return n.length===0?[]:[[e,n]]}))}runAgentRouterTask.workflowId=`workflow//eve@1.0.0-rc.9//runAgentRouterTask`;export{runAgentRouterTask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{workflowToolContextErrorMessage}from"#shared/workflow-tool-context.js";const WORKFLOW_TOOL_RUN_CONTEXT=Symbol.for(`eve.workflow-tool-run.context`);function attachWorkflowToolRunContext(e,t){Object.defineProperty(e,WORKFLOW_TOOL_RUN_CONTEXT,{enumerable:!1,value:t})}function readWorkflowToolRunContext(e,t){let n=e?.[WORKFLOW_TOOL_RUN_CONTEXT];if(n===void 0)throw Error(workflowToolContextErrorMessage(t));return n}function findWorkflowToolRunContext(e){return typeof e==`object`&&e?e[WORKFLOW_TOOL_RUN_CONTEXT]:void 0}const CANCELLED={status:`cancelled`};const UNAVAILABLE={status:`unavailable`};var WorkflowToolRunAsks=class{opened=0;pending=new Map;withdrawing=new Set;runId;constructor(e){this.runId=e}open(e){this.opened+=1;let t=`${this.runId}-ask-${String(this.opened)}`;let n;let r=new Promise(e=>{n={resolve:e,withdraw:void 0}});return this.pending.set(t,n),n.withdraw=e(t),{answer:r,requestId:t}}withdraw(e){let t=this.pending.get(e);let n=t?.withdraw;if(t===void 0||n===void 0)return;t.withdraw=void 0;let r=n();this.withdrawing.add(r),r.then(()=>this.withdrawing.delete(r))}withdrawAll(){for(let e of this.pending.keys())this.withdraw(e)}async flush(){for(;this.withdrawing.size>0;)await Promise.all(this.withdrawing)}settle(e){let t=e.kind===`answer`?e.response:CANCELLED;this.take(e.requestId)?.resolve(t)}cancelAll(){for(let e of this.pending.keys())this.take(e)?.resolve(CANCELLED)}take(e){let t=this.pending.get(e);return this.pending.delete(e),t}};function ask(e,t,n={}){let r=readWorkflowToolRunContext(e,`ask`);if(r.agentContext.capabilities?.requestInput!==!0)return Promise.resolve(UNAVAILABLE);let
|
|
1
|
+
import{workflowToolContextErrorMessage}from"#shared/workflow-tool-context.js";const WORKFLOW_TOOL_RUN_CONTEXT=Symbol.for(`eve.workflow-tool-run.context`);function attachWorkflowToolRunContext(e,t){Object.defineProperty(e,WORKFLOW_TOOL_RUN_CONTEXT,{enumerable:!1,value:t})}function readWorkflowToolRunContext(e,t){let n=e?.[WORKFLOW_TOOL_RUN_CONTEXT];if(n===void 0)throw Error(workflowToolContextErrorMessage(t));return n}function findWorkflowToolRunContext(e){return typeof e==`object`&&e?e[WORKFLOW_TOOL_RUN_CONTEXT]:void 0}const CANCELLED={status:`cancelled`};const UNAVAILABLE={status:`unavailable`};var WorkflowToolRunAsks=class{opened=0;pending=new Map;withdrawing=new Set;runId;constructor(e){this.runId=e}open(e){this.opened+=1;let t=`${this.runId}-ask-${String(this.opened)}`;let n;let r=new Promise(e=>{n={resolve:e,withdraw:void 0}});return this.pending.set(t,n),n.withdraw=e(t),{answer:r,requestId:t}}withdraw(e){let t=this.pending.get(e);let n=t?.withdraw;if(t===void 0||n===void 0)return;t.withdraw=void 0;let r=n();this.withdrawing.add(r),r.then(()=>this.withdrawing.delete(r))}withdrawAll(){for(let e of this.pending.keys())this.withdraw(e)}async flush(){for(;this.withdrawing.size>0;)await Promise.all(this.withdrawing)}settle(e){let t=e.kind===`answer`?e.response:CANCELLED;this.take(e.requestId)?.resolve(t)}cancelAll(){for(let e of this.pending.keys())this.take(e)?.resolve(CANCELLED)}take(e){let t=this.pending.get(e);return this.pending.delete(e),t}};function ask(e,t,n={}){let r=readWorkflowToolRunContext(e,`ask`);let{initialOptionId:i}=t;if(t.display===`select`&&i!==void 0&&!t.options?.some(e=>e.id===i))throw TypeError(`ctx.ask(): \`initialOptionId\` ${JSON.stringify(i)} must match one of the question's \`options\` ids.`);if(r.agentContext.capabilities?.requestInput!==!0)return Promise.resolve(UNAVAILABLE);let a=[e.abortSignal];if(n.signal!==void 0&&a.push(n.signal),a.some(e=>e.aborted))return Promise.resolve(CANCELLED);let{asks:o,control:s,owner:c}=r;let l=r.from;let{answer:u,requestId:d}=o.open(e=>{let n=c.send({kind:`request`,from:l,replyTo:e,request:{control:s,kind:`ask`,request:t}});return()=>n.then(()=>c.send({control:s,from:l,kind:`withdraw`,replyTo:e}))});let requestWithdrawal=()=>o.withdraw(d);for(let e of a)e.addEventListener(`abort`,requestWithdrawal,{once:!0});return u.finally(()=>{for(let e of a)e.removeEventListener(`abort`,requestWithdrawal)})}export{WorkflowToolRunAsks,ask,attachWorkflowToolRunContext,findWorkflowToolRunContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseJsonValue}from"#shared/json.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";import{relayEvent}from"#channel/relay-event.js";function workflowToolRunOutcomeToToolResult(e){let{from:t,result:n}=e;return n.status===`completed`?{callId:t.callId,kind:`tool-result`,output:n.output,toolName:t.toolName}:{callId:t.callId,...n.status===`failed`&&{errorName:rebuildSerializableError(n.error).name},isError:!0,kind:`tool-result`,output:n.status===`failed`?workflowToolRunFailureOutput(e):n.reason??`The workflow tool run was cancelled.`,toolName:t.toolName}}function workflowToolRunFailureOutput(e){if(e.result.status!==`failed`)throw TypeError(`Expected a failed workflow outcome.`);let t=parseJsonValueOrUndefined(e.result.error);return t!==void 0&&typeof t==`object`&&t&&!Array.isArray(t)&&typeof Reflect.get(t,`code`)==`string`?t:errorMessage(e.result.error)}function errorMessage(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`)return t}return String(e)}function parseJsonValueOrUndefined(e){try{return parseJsonValue(e)}catch{return}}function workflowAskPayload(e){let{from:t,replyTo:n}=e;let r=e.request.request;if(typeof r.prompt!=`string`||r.prompt.length===0)throw TypeError("A workflow tool run request needs a non-empty `prompt`.");let i={kind:`question`,prompt:r.prompt};return r.allowFreeform!==void 0&&(i.allowFreeform=r.allowFreeform),r.display!==void 0&&(i.display=r.display),r.title!==void 0&&(i.title=r.title),r.options!==void 0&&(i.options=[...r.options]),{callId:t.callId,childSessionId:t.runId,events:[relayEvent(`interaction.opened`,{interactionId:n,origin:{call:{callId:t.callId,input:t.input,name:t.toolName},interactionId:n,sessionId:t.runId},request:i,subject:{callId:t.callId}})],kind:`subagent-interaction`,route:{childContinuationToken:n},subagentName:t.toolName}}export{workflowAskPayload,workflowToolRunFailureOutput,workflowToolRunOutcomeToToolResult};
|
|
1
|
+
import{parseJsonValue}from"#shared/json.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";import{relayEvent}from"#channel/relay-event.js";function workflowToolRunOutcomeToToolResult(e){let{from:t,result:n}=e;return n.status===`completed`?{callId:t.callId,kind:`tool-result`,output:n.output,toolName:t.toolName}:{callId:t.callId,...n.status===`failed`&&{errorName:rebuildSerializableError(n.error).name},isError:!0,kind:`tool-result`,output:n.status===`failed`?workflowToolRunFailureOutput(e):n.reason??`The workflow tool run was cancelled.`,toolName:t.toolName}}function workflowToolRunFailureOutput(e){if(e.result.status!==`failed`)throw TypeError(`Expected a failed workflow outcome.`);let t=parseJsonValueOrUndefined(e.result.error);return t!==void 0&&typeof t==`object`&&t&&!Array.isArray(t)&&typeof Reflect.get(t,`code`)==`string`?t:errorMessage(e.result.error)}function errorMessage(e){if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`)return t}return String(e)}function parseJsonValueOrUndefined(e){try{return parseJsonValue(e)}catch{return}}function workflowAskPayload(e){let{from:t,replyTo:n}=e;let r=e.request.request;if(typeof r.prompt!=`string`||r.prompt.length===0)throw TypeError("A workflow tool run request needs a non-empty `prompt`.");let i={kind:`question`,prompt:r.prompt};return r.allowFreeform!==void 0&&(i.allowFreeform=r.allowFreeform),r.display!==void 0&&(i.display=r.display),r.title!==void 0&&(i.title=r.title),r.options!==void 0&&(i.options=[...r.options]),r.initialOptionId!==void 0&&(i.initialOptionId=r.initialOptionId),{callId:t.callId,childSessionId:t.runId,events:[relayEvent(`interaction.opened`,{interactionId:n,origin:{call:{callId:t.callId,input:t.input,name:t.toolName},interactionId:n,sessionId:t.runId},request:i,subject:{callId:t.callId}})],kind:`subagent-interaction`,route:{childContinuationToken:n},subagentName:t.toolName}}export{workflowAskPayload,workflowToolRunFailureOutput,workflowToolRunOutcomeToToolResult};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import { type WorkflowStepInvocation } from "#execution/tools/workflow/step-context.js";
|
|
2
2
|
/** Keeps token capabilities and bearer values inside the executing step. */
|
|
3
3
|
export declare function withWorkflowStepAuthorization(execute: (...args: never[]) => unknown): (this: unknown, invocation: WorkflowStepInvocation) => Promise<unknown>;
|
|
4
|
+
/** Runs a workflow tool's `"use step"` function that its caller invoked without the tool context. */
|
|
5
|
+
export declare function withWorkflowStepScope(execute: (...args: never[]) => unknown): (this: unknown, ...args: unknown[]) => unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SandboxKey,SessionIdKey,SessionKey}from"#context/keys.js";import{ensureSandboxAccess}from"#execution/sandbox/ensure.js";import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{getStepMetadata}from"#compiled/@workflow/core/index.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{isConnectionAuthorizationFailedError}from"#connections/errors.js";import{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,isAuthorizationSignal}from"#harness/authorization.js";import{createToolChannelTo}from"#execution/tools/channel-to.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{completeWorkflowStepAuthorization}from"#execution/tools/workflow/authorization-completion.js";import"#execution/tools/workflow/step-context.js";const log=createLogger(`workflow-step`);function withWorkflowStepAuthorization(e){let wrapped=async function(t){let{args:n,context:r}=t;getStepMetadata();let i=new ContextContainer;i.set(AuthKey,r.session.auth.current),i.set(InitiatorAuthKey,r.session.auth.initiator),i.set(SessionIdKey,r.session.id),i.setVirtualContext(SessionKey,{...r.session,sessionId:r.session.id}),i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(r.baseUrl)),i.setVirtualContext(AuthorizationHookKey,r.token),i.setVirtualContext(PendingAuthorizationResultKey,r.authorizationResults);let a=stepAgentLoader(r);let o=openStepSandbox(r,a);return contextStorage.run(i,async()=>{let s=createAuthorizationContext({scope:r.toolName,completeAuthorization:completeWorkflowStepAuthorization});let c=buildBaseToolContext({toolName:r.toolName,options:{abortSignal:r.abortSignal,toolCallId:r.callId}});let l={...c,agent:()=>unavailableInStep(`ctx.agent()`,`Call ctx.agent() in the workflow body.`),ask:()=>unavailableInStep(`ctx.ask()`,`Call ctx.ask() in the workflow body.`),getSandbox:(async e=>{let t=await o.open();if(e!==void 0&&t.environment?.provider!==e.provider)throw fatal(`ctx.getSandbox() in a "use step" function received a sandbox environment the session's sandbox does not use. Pass the environment the agent's sandbox definition opens, or call ctx.getSandbox() without one.`);return i.setVirtualContext(SandboxKey,t),await c.getSandbox()}),getToken:s.getToken,requireAuth:s.requireAuth,channel:r.channel,to:createToolChannelTo({delegated:r.delegated,loadBundle:a})};Object.defineProperty(l,"agents",{get:()=>unavailableInStep(`ctx.agents`,`Read ctx.agents in the workflow body and pass the required serializable metadata into the step.`)});let u;try{u=await s.run(()=>Reflect.apply(e,this,n.map((e,n)=>t.contextIndexes.includes(n)?l:e)))}catch(e){throw isConnectionAuthorizationFailedError(e)&&!e.retryable&&Object.assign(e,{fatal:!0}),e}finally{await o.release()}let d=i.get(PendingAuthorizationResultKey)??[];let f=r.authorizationResults.filter(e=>!d.includes(e)).map(e=>e.attemptId);return isAuthorizationSignal(u)?{kind:`authorization-required`,challenges:u.challenges,authorized:f}:{kind:`result`,output:u,authorized:f}})};return Object.defineProperty(wrapped,"maxRetries",{get:()=>Reflect.get(e,`maxRetries`)}),wrapped}function stepAgentLoader(e){let{bundle:t}=e.sandbox;let n=contextStorage.getStore();let resolveSource=()=>resolveDurableCompiledArtifactsSource(t.source);return async()=>await getCompiledRuntimeAgentBundle({compiledArtifactsSource:n===void 0?resolveSource():contextStorage.run(n,resolveSource),nodeId:t.nodeId})}function openStepSandbox(e,t){let{sessionId:n,state:r}=e.sandbox;let i;let a=!1;let open=async()=>{let e=await t();let i=e.graph.root;return await ensureSandboxAccess({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:i.nodeId,ownsSandbox:!1,registry:i.sandboxRegistry,sessionId:n,state:r??null,shutdownTracking:`none`})};let openOnce=()=>(i??=open().catch(e=>{throw i=void 0,e}),i);return{async open(){if(a)throw fatal(`ctx.getSandbox() was called after the "use step" function of tool "${e.toolName}" returned. Call it inside the step, which lets go of the sandbox when it ends.`);return{...await openOnce(),delete:()=>unavailableInStep(`sandbox.delete()`,`The step borrows the session's sandbox, and only the session can delete it.`),stop:()=>unavailableInStep(`sandbox.stop()`,`The session's turns may be using the sandbox; eve closes the step's connection when the step ends.`)}},async release(){a=!0;let t=await i?.catch(()=>void 0);try{await t?.release()}catch(t){logError(log,`failed to release a workflow step's sandbox`,t,{sessionId:n,toolName:e.toolName})}}}}function unavailableInStep(e,t){throw fatal(`${e} is unavailable inside a "use step" function. ${t}`)}function fatal(e){return Object.assign(Error(e),{fatal:!0})}export{withWorkflowStepAuthorization};
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{ContextContainer,contextStorage}from"#context/container.js";import{AuthKey,InitiatorAuthKey,SandboxKey,SessionIdKey,SessionKey}from"#context/keys.js";import{ensureSandboxAccess}from"#execution/sandbox/ensure.js";import{resolveDurableCompiledArtifactsSource}from"#runtime/durable-compiled-artifacts-source.js";import{getStepMetadata}from"#compiled/@workflow/core/index.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{isConnectionAuthorizationFailedError}from"#connections/errors.js";import{AuthorizationHookKey,CallbackBaseUrlKey,PendingAuthorizationResultKey,isAuthorizationSignal}from"#harness/authorization.js";import{createToolChannelTo}from"#execution/tools/channel-to.js";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{createAuthorizationContext}from"#runtime/authorization-context.js";import{runInWorkflowStep}from"#context/workflow-step.js";import{completeWorkflowStepAuthorization}from"#execution/tools/workflow/authorization-completion.js";import"#execution/tools/workflow/step-context.js";const log=createLogger(`workflow-step`);function withWorkflowStepAuthorization(e){let wrapped=async function(t){let{args:n,context:r}=t;getStepMetadata();let i=new ContextContainer;i.set(AuthKey,r.session.auth.current),i.set(InitiatorAuthKey,r.session.auth.initiator),i.set(SessionIdKey,r.session.id),i.setVirtualContext(SessionKey,{...r.session,sessionId:r.session.id}),i.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(r.baseUrl)),i.setVirtualContext(AuthorizationHookKey,r.token),i.setVirtualContext(PendingAuthorizationResultKey,r.authorizationResults);let a=stepAgentLoader(r);let o=openStepSandbox(r,a);return contextStorage.run(i,async()=>{let s=createAuthorizationContext({scope:r.toolName,completeAuthorization:completeWorkflowStepAuthorization});let c=buildBaseToolContext({toolName:r.toolName,options:{abortSignal:r.abortSignal,toolCallId:r.callId}});let l={...c,agent:()=>unavailableInStep(`ctx.agent()`,`Call ctx.agent() in the workflow body.`),ask:()=>unavailableInStep(`ctx.ask()`,`Call ctx.ask() in the workflow body.`),getSandbox:(async e=>{let t=await o.open();if(e!==void 0&&t.environment?.provider!==e.provider)throw fatal(`ctx.getSandbox() in a "use step" function received a sandbox environment the session's sandbox does not use. Pass the environment the agent's sandbox definition opens, or call ctx.getSandbox() without one.`);return i.setVirtualContext(SandboxKey,t),await c.getSandbox()}),getToken:s.getToken,requireAuth:s.requireAuth,channel:r.channel,to:createToolChannelTo({delegated:r.delegated,loadBundle:a})};Object.defineProperty(l,"agents",{get:()=>unavailableInStep(`ctx.agents`,`Read ctx.agents in the workflow body and pass the required serializable metadata into the step.`)});let u;try{u=await runInWorkflowStep(()=>s.run(()=>Reflect.apply(e,this,n.map((e,n)=>t.contextIndexes.includes(n)?l:e))))}catch(e){throw isConnectionAuthorizationFailedError(e)&&!e.retryable&&Object.assign(e,{fatal:!0}),e}finally{await o.release()}let d=i.get(PendingAuthorizationResultKey)??[];let f=r.authorizationResults.filter(e=>!d.includes(e)).map(e=>e.attemptId);return isAuthorizationSignal(u)?{kind:`authorization-required`,challenges:u.challenges,authorized:f}:{kind:`result`,output:u,authorized:f}})};return Object.defineProperty(wrapped,"maxRetries",{get:()=>Reflect.get(e,`maxRetries`)}),wrapped}function withWorkflowStepScope(e){let wrapped=function(...t){return runInWorkflowStep(()=>Reflect.apply(e,this,t))};return Object.defineProperty(wrapped,"maxRetries",{get:()=>Reflect.get(e,`maxRetries`)}),wrapped}function stepAgentLoader(e){let{bundle:t}=e.sandbox;let n=contextStorage.getStore();let resolveSource=()=>resolveDurableCompiledArtifactsSource(t.source);return async()=>await getCompiledRuntimeAgentBundle({compiledArtifactsSource:n===void 0?resolveSource():contextStorage.run(n,resolveSource),nodeId:t.nodeId})}function openStepSandbox(e,t){let{sessionId:n,state:r}=e.sandbox;let i;let a=!1;let open=async()=>{let e=await t();let i=e.graph.root;return await ensureSandboxAccess({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:i.nodeId,ownsSandbox:!1,registry:i.sandboxRegistry,sessionId:n,state:r??null,shutdownTracking:`none`})};let openOnce=()=>(i??=open().catch(e=>{throw i=void 0,e}),i);return{async open(){if(a)throw fatal(`ctx.getSandbox() was called after the "use step" function of tool "${e.toolName}" returned. Call it inside the step, which lets go of the sandbox when it ends.`);return{...await openOnce(),delete:()=>unavailableInStep(`sandbox.delete()`,`The step borrows the session's sandbox, and only the session can delete it.`),stop:()=>unavailableInStep(`sandbox.stop()`,`The session's turns may be using the sandbox; eve closes the step's connection when the step ends.`)}},async release(){a=!0;let t=await i?.catch(()=>void 0);try{await t?.release()}catch(t){logError(log,`failed to release a workflow step's sandbox`,t,{sessionId:n,toolName:e.toolName})}}}}function unavailableInStep(e,t){throw fatal(`${e} is unavailable inside a "use step" function. ${t}`)}function fatal(e){return Object.assign(Error(e),{fatal:!0})}export{withWorkflowStepAuthorization,withWorkflowStepScope};
|
|
@@ -19,4 +19,6 @@ export declare function isAttributable(argv: readonly string[]): boolean;
|
|
|
19
19
|
* messages and `gh pr create` descriptions. Other commands are unchanged.
|
|
20
20
|
* A `--body-file` is copied to `bodyFile`, so the model's file stays intact.
|
|
21
21
|
*/
|
|
22
|
-
export declare function attributeCommand(argv: readonly string[], trailer: string, sandbox: Pick<SandboxSession, "readTextFile" | "writeTextFile">, workingDirectory: string, bodyFile: string): Promise<string[]
|
|
22
|
+
export declare function attributeCommand(argv: readonly string[], trailer: string, sandbox: Pick<SandboxSession, "readTextFile" | "writeTextFile">, workingDirectory: string, bodyFile: string): Promise<string[] | {
|
|
23
|
+
readonly missingBodyFile: string;
|
|
24
|
+
}>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{posix}from"node:path";const BODY_FLAGS=new Set([`-b`,`--body`]);const BODY_FILE_FLAGS=new Set([`-F`,`--body-file`]);const TRAILER_LINE=/^[A-Za-z0-9][A-Za-z0-9-]*: \S/u;function coAuthorTrailer(e){let t=e.name.trim();let n=e.email.trim();if(!t||/[\r\n<>]/u.test(t))throw Error(`Invalid co-author name ${JSON.stringify(e.name)}.`);if(!/^[^\s<>@]+@[^\s<>@]+$/u.test(n))throw Error(`Invalid co-author email ${JSON.stringify(e.email)}.`);return`Co-authored-by: ${t} <${n}>`}function withTrailer(e,t){if(e.split(/\r?\n/u).map(e=>e.trim().toLowerCase()).includes(t.toLowerCase()))return e;let n=e.trimEnd();if(!n)return t;let r=n.split(/\r?\n[ \t]*\r?\n/u);let i=r.at(-1).split(/\r?\n/u);return`${n}${r.length>1&&i.every(e=>TRAILER_LINE.test(e))?`
|
|
2
2
|
`:`
|
|
3
3
|
|
|
4
|
-
`}${t}`}function isAttributable(e){return e[0]===`gh-signed-commit`||e[0]===`gh`&&e[1]===`pr`&&e[2]===`create`}async function attributeCommand(e,t,n,r,i){let a=[...e];if(e[0]===`gh-signed-commit`){let e=a.lastIndexOf(`-b`);return e===-1?a.push(`-b`,t):a[e+1]=withTrailer(a[e+1]??``,t),a}if(e[0]!==`gh`||e[1]!==`pr`||e[2]!==`create`)return a;for(let e=a.length-1;e>=3;--e){let o=a[e];let[s,c]=splitInline(o);if(BODY_FLAGS.has(s)){let n=withTrailer(c??a[e+1]??``,t);return c===void 0?a[e+1]=n:a[e]=`${s}=${n}`,a}if(BODY_FILE_FLAGS.has(s)){let o=c??a[e+1];if(!o||o===`-`)return a;let l=await n.readTextFile({path:posix.resolve(r,o)});
|
|
4
|
+
`}${t}`}function isAttributable(e){return e[0]===`gh-signed-commit`||e[0]===`gh`&&e[1]===`pr`&&e[2]===`create`}async function attributeCommand(e,t,n,r,i){let a=[...e];if(e[0]===`gh-signed-commit`){let e=a.lastIndexOf(`-b`);return e===-1?a.push(`-b`,t):a[e+1]=withTrailer(a[e+1]??``,t),a}if(e[0]!==`gh`||e[1]!==`pr`||e[2]!==`create`)return a;for(let e=a.length-1;e>=3;--e){let o=a[e];let[s,c]=splitInline(o);if(BODY_FLAGS.has(s)){let n=withTrailer(c??a[e+1]??``,t);return c===void 0?a[e+1]=n:a[e]=`${s}=${n}`,a}if(BODY_FILE_FLAGS.has(s)){let o=c??a[e+1];if(!o||o===`-`)return a;let l=await n.readTextFile({path:posix.resolve(r,o)});return l===null?{missingBodyFile:o}:(await n.writeTextFile({content:withTrailer(l,t),path:i}),c===void 0?a[e+1]=i:a[e]=`${s}=${i}`,a)}}return a}function splitInline(e){if(!e.startsWith(`--`)){if(!e.startsWith(`-`)||e.length<=2)return[e,void 0];let t=e.slice(2);return[e.slice(0,2),t.startsWith(`=`)?t.slice(1):t]}let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}export{attributeCommand,coAuthorTrailer,isAttributable,withTrailer};
|
|
@@ -112,6 +112,21 @@ interface GitHubShellDependencies {
|
|
|
112
112
|
/** Stops waiting for another command's credential lease when the tool call is cancelled. */
|
|
113
113
|
readonly abortSignal?: AbortSignal;
|
|
114
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Thrown when a GitHub command's own input is refused before it runs, such as
|
|
117
|
+
* shell syntax, a working directory outside the workspace, or a missing body
|
|
118
|
+
* file. The agent can fix these by changing the call.
|
|
119
|
+
*/
|
|
120
|
+
export declare class GitHubCommandInputError extends Error {
|
|
121
|
+
constructor(message: string);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Type guard for {@link GitHubCommandInputError}.
|
|
125
|
+
*
|
|
126
|
+
* Uses `err.name` rather than `instanceof` because consumers and eve can end
|
|
127
|
+
* up with different class identities after bundling.
|
|
128
|
+
*/
|
|
129
|
+
export declare function isGitHubCommandInputError(err: unknown): err is GitHubCommandInputError;
|
|
115
130
|
export declare function githubShellApproval(input: GitHubShellInput | undefined): "not-applicable" | {
|
|
116
131
|
type: "denied";
|
|
117
132
|
reason: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{attributeCommand,coAuthorTrailer,isAttributable}from"./attribution.js";import{validateRepositoryRoot}from"./repository-root.js";import{withSandboxLeaseLock}from"./sandbox-lease-lock.js";import{connectUserAuthorization}from"./connect-user-auth.js";import{GITHUB_TARGET}from"./github-shell-schema.js";import{shellQuote}from"./shell.js";import{GITHUB_TOOLING_PATHS}from"./tooling.js";import{posix}from"node:path";import{getToken}from"#compiled/@vercel/connect/index.js";const MAX_OUTPUT_BYTES=1e5;const leaseQueues=new Map;const EXECUTABLES=new Set([`gh`,`git`,`gh-signed-commit`]);const GITHUB_UNAUTHORIZED=/HTTP 401\b|Bad credentials|Authentication failed for|failed: 401\b/u;function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let{argv:r,target:{owner:i,repository:a,name:o}}=validateGitHubShellInput(e);if(t.principalType===`user`?i&&!a:!i)throw
|
|
1
|
+
import{attributeCommand,coAuthorTrailer,isAttributable}from"./attribution.js";import{validateRepositoryRoot}from"./repository-root.js";import{withSandboxLeaseLock}from"./sandbox-lease-lock.js";import{connectUserAuthorization}from"./connect-user-auth.js";import{GITHUB_TARGET}from"./github-shell-schema.js";import{shellQuote}from"./shell.js";import{GITHUB_TOOLING_PATHS}from"./tooling.js";import{posix}from"node:path";import{getToken}from"#compiled/@vercel/connect/index.js";const MAX_OUTPUT_BYTES=1e5;const leaseQueues=new Map;const EXECUTABLES=new Set([`gh`,`git`,`gh-signed-commit`]);const GITHUB_UNAUTHORIZED=/HTTP 401\b|Bad credentials|Authentication failed for|failed: 401\b/u;var GitHubCommandInputError=class extends Error{constructor(e){super(e),this.name=`GitHubCommandInputError`}};function isGitHubCommandInputError(e){return e instanceof Error&&e.name===`GitHubCommandInputError`}function githubShellApproval(e){if(!e)return`not-applicable`;try{return validateGitHubShellInput(e),`not-applicable`}catch(e){return{type:`denied`,reason:e instanceof Error?e.message:`Invalid GitHub command.`}}}async function executeGitHubShell(e,t,n){if(!t)throw Error(`GitHub command access is not configured for this agent.`);let{argv:r,target:{owner:i,repository:a,name:o}}=validateGitHubShellInput(e);if(t.principalType===`user`?i&&!a:!i)throw new GitHubCommandInputError(t.principalType===`user`?`Set repository to owner/name or omit it; user tokens are not scoped to an owner.`:`App tokens need repository set to an owner or owner/name.`);let s=await n.getSandbox();let c=resolveWorkingDirectory(s,e.workingDirectory);if(r[0]===`gh-signed-commit`){let e=await validateRepositoryRoot(s,c);if(`refused`in e)throw new GitHubCommandInputError(e.refused);c=e.root}let l=crypto.randomUUID();let u=`/tmp/eve-git-body-${l}.md`;let d=n.auth??null;let f;let p;if(t.principalType===`user`){if(!n.getToken||!n.requireAuth)throw Error(`User-scoped GitHub access requires ctx.getToken and ctx.requireAuth.`);f=connectUserAuthorization(t.connector),{token:p}=await n.getToken(f)}else{let e={type:`github_app_installation`,org:i};o&&(e.repositories=[o]),t.permissions&&(e.permissions=[...t.permissions]),p=await(n.getConnectToken??getToken)(t.connector,{authorizationDetails:[e],subject:{type:`app`}})}if(!p)throw Error(`Connect returned an empty token for ${JSON.stringify(t.connector)}.`);if(!(t.principalType===`user`?await t.authorize({argv:r,auth:d,repository:null,token:p}):await t.authorize({argv:r,auth:d,owner:i,repository:a,token:p})))throw Error(`The current caller is not authorized to run this command${a?` on ${a}`:i?` for ${i}`:``}.`);let m=t.attribution&&n.context&&isAttributable(r)?await t.attribution(n.context):null;let h=m?await attributeCommand(r,coAuthorTrailer(m),s,c,u):r;if(!Array.isArray(h))throw new GitHubCommandInputError(`Pull request body file ${JSON.stringify(h.missingBodyFile)} not found.`);let g=executablePath(h[0]);let _=`cd ${shellQuote(c)} && exec ${shellQuote(g)} ${h.slice(1).map(shellQuote).join(` `)}`;let v=`Basic ${Buffer.from(`x-access-token:${p}`).toString(`base64`)}`;let y=`eve-github-${l}`;let b=`/tmp/eve-code-gh-${l}`;let x=`Basic ${Buffer.from(`x-access-token:${y}`).toString(`base64`)}`;let S;try{S=await withGitHubCredentialLease(s,n,{authorization:v,placeholder:y,placeholderAuthorization:x,token:p},()=>{let e={GH_CONFIG_DIR:b,GH_PROMPT_DISABLED:`1`};r[0]!==`git`&&(e.GH_TOKEN=y);let t=[[`http.https://github.com/.extraheader`,`Authorization: ${x}`],[`url.https://github.com/.insteadOf`,`git@github.com:`],[`url.https://github.com/.insteadOf`,`ssh://git@github.com/`],[`core.hooksPath`,`/dev/null`],[`protocol.allow`,`never`],[`protocol.https.allow`,`always`]];return e.GIT_CONFIG_COUNT=String(t.length),t.forEach(([t,n],r)=>{e[`GIT_CONFIG_KEY_${r}`]=t,e[`GIT_CONFIG_VALUE_${r}`]=n}),e.GIT_TERMINAL_PROMPT=`0`,e.PATH=`/usr/local/bin:/usr/bin:/bin`,s.run({command:_,env:e})},t.broker)}finally{await s.removePath({path:b,recursive:!0,force:!0}),await s.removePath({path:u,force:!0})}f&&S.exitCode!==0&&GITHUB_UNAUTHORIZED.test(S.stderr)&&n.requireAuth(f);let C=sanitizeOutput(S.stdout,p,v);let w=sanitizeOutput(S.stderr,p,v);return{exitCode:S.exitCode,stdout:C.value,stderr:w.value,truncated:C.truncated||w.truncated}}async function withGitHubCredentialLease(e,{sessionId:t,abortSignal:n},r,i,a){let o=leaseQueues.get(t)??Promise.resolve();let s;let c=new Promise(e=>{s=e});let l=o.then(()=>c);leaseQueues.set(t,l),await o;try{return await withSandboxLeaseLock(e,r.placeholder,()=>leaseCredential(e,r,i,a),{cleanup:()=>a(e,null),...n!==void 0&&{signal:n}})}finally{s(),leaseQueues.get(t)===l&&leaseQueues.delete(t)}}async function leaseCredential(e,t,n,r){let i=[{match:{headers:[{key:{exact:`authorization`},value:{regex:`^(?:token|Bearer) ${t.placeholder}$`}}]},transform:[{headers:{authorization:`Bearer ${t.token}`}}]}];return await r(e,{"api.github.com":i,"uploads.github.com":i,"github.com":[{match:{headers:[{key:{exact:`authorization`},value:{exact:t.placeholderAuthorization}}]},transform:[{headers:{authorization:t.authorization}}]}]}),await n()}function parseCommand(e){let t=e.trim();if(!t)throw new GitHubCommandInputError(`GitHub command must not be empty.`);let n=[];let r=``;let i=null;let a=!1;let o=!1;for(let e of t)if(a)r+=e,a=!1,o=!0;else if(e===`\\`&&i!==`single`)a=!0,o=!0;else if(i===`single`)e===`'`?i=null:r+=e;else if(i===`double`){if(e===`"`)i=null;else if(e===`$`||e==="`")throw unsupportedSyntax();else r+=e}else if(e===`'`)i=`single`,o=!0;else if(e===`"`)i=`double`,o=!0;else if(/\s/u.test(e))o&&=(n.push(r),r=``,!1);else if(";&|<>$`(){}".includes(e))throw unsupportedSyntax();else r+=e,o=!0;if(a||i)throw new GitHubCommandInputError(`GitHub command contains an unfinished quote or escape.`);if(o&&n.push(r),n.length===0)throw new GitHubCommandInputError(`GitHub command must not be empty.`);return n}function validateGitHubShellInput(e){let t=parseCommand(e.command);if(!e.description.trim())throw new GitHubCommandInputError(`description must describe the intended result.`);if(!EXECUTABLES.has(t[0]))throw new GitHubCommandInputError(`GitHub commands must use gh, git, or gh-signed-commit.`);if(t.length<2)throw new GitHubCommandInputError(`A ${t[0]} subcommand or argument is required.`);return{argv:t,target:declaredTarget(e.repository)}}function declaredTarget(e){let t=e?.trim();if(!t)return{owner:null,repository:null,name:null};let n=GITHUB_TARGET.exec(t.replace(/\.git$/iu,``));if(!n)throw new GitHubCommandInputError(`Invalid GitHub repository or owner ${JSON.stringify(e)}.`);let[,r,i]=n;return{owner:r,repository:i?`${r}/${i}`:null,name:i??null}}function executablePath(e){return e===`gh`?GITHUB_TOOLING_PATHS.ghReal:e===`gh-signed-commit`?GITHUB_TOOLING_PATHS.trustedSignedCommit:`git`}function resolveWorkingDirectory(e,t){let n=posix.resolve(`/`,e.resolvePath(``));let r=posix.resolve(`/`,e.resolvePath(t?.trim()||``));if(r!==n&&!r.startsWith(`${n}/`))throw new GitHubCommandInputError(`GitHub command workingDirectory must stay inside the sandbox workspace.`);return r}function sanitizeOutput(e,t,n){let r=e.replaceAll(t,`[redacted]`).replaceAll(n,`[redacted]`);return Buffer.byteLength(r)<=MAX_OUTPUT_BYTES?{value:r,truncated:!1}:{value:`[output truncated: showing final ${MAX_OUTPUT_BYTES} bytes]\n${Buffer.from(r).subarray(-1e5).toString()}`,truncated:!0}}function unsupportedSyntax(){return new GitHubCommandInputError(`GitHub commands support argv syntax only, not pipes, redirects, substitutions, or shell operators.`)}export{GitHubCommandInputError,executeGitHubShell,githubShellApproval,isGitHubCommandInputError,parseCommand};
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import type { SandboxSession } from "eve/sandbox";
|
|
2
2
|
type RootSandbox = Pick<SandboxSession, "resolvePath" | "run">;
|
|
3
|
+
/** The resolved root, or why the given directory cannot be one. */
|
|
4
|
+
export type RepositoryRoot = {
|
|
5
|
+
readonly root: string;
|
|
6
|
+
} | {
|
|
7
|
+
readonly refused: string;
|
|
8
|
+
};
|
|
3
9
|
/** A workspace directory that must also be the top of a git work tree. */
|
|
4
|
-
export declare function validateRepositoryRoot(sandbox: RootSandbox, root: string): Promise<
|
|
10
|
+
export declare function validateRepositoryRoot(sandbox: RootSandbox, root: string): Promise<RepositoryRoot>;
|
|
5
11
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{shellQuote}from"./shell.js";async function validateRepositoryRoot(e,t){if(!t.startsWith(`/`))
|
|
1
|
+
import{shellQuote}from"./shell.js";async function validateRepositoryRoot(e,t){if(!t.startsWith(`/`))return{refused:`root must be an absolute sandbox path`};let n=await realPath(e,e.resolvePath(``),`sandbox workspace`);if(typeof n!=`string`)throw Error(n.unresolved);let r=await realPath(e,t,`root`);if(typeof r!=`string`)return{refused:r.unresolved};if(!(n===`/`||r===n||r.startsWith(`${n}/`)))return{refused:`root resolves outside the workspace ${n}: ${r}`};let i=await e.run({command:`git -C ${shellQuote(r)} rev-parse --show-toplevel`});return i.exitCode!==0||i.stdout.trim()!==r?{refused:`root is not a git work tree root: ${t}`}:{root:r}}async function realPath(e,t,n){let r=await e.run({command:`realpath -e -z -- ${shellQuote(t)}`});if(r.exitCode!==0)return{unresolved:`${n} could not be resolved: ${(r.stderr.trim()||r.stdout.trim()||`no command output`).slice(0,2e3)}`};let i=r.stdout.endsWith(`\0`)?r.stdout.slice(0,-1):r.stdout;if(i.length===0||i.includes(`\0`))throw Error(`${n} returned an invalid realpath`);return i}export{validateRepositoryRoot};
|