eve 0.30.8 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +5 -6
- package/dist/src/acp/adapter.d.ts +10 -4
- package/dist/src/acp/adapter.js +1 -1
- package/dist/src/channel/adapter-context.d.ts +1 -1
- package/dist/src/channel/adapter.d.ts +2 -4
- package/dist/src/channel/adapter.js +1 -1
- package/dist/src/channel/channel-address.d.ts +58 -0
- package/dist/src/channel/channel-address.js +1 -0
- package/dist/src/channel/channel-operations.d.ts +72 -0
- package/dist/src/channel/channel-operations.js +1 -0
- package/dist/src/channel/compiled-channel.d.ts +10 -6
- package/dist/src/channel/cross-channel-receive.d.ts +13 -25
- package/dist/src/channel/cross-channel-receive.js +2 -2
- package/dist/src/channel/receive-target.d.ts +1 -2
- package/dist/src/channel/routes.d.ts +21 -149
- package/dist/src/channel/schedule.d.ts +1 -1
- package/dist/src/channel/schedule.js +1 -1
- package/dist/src/channel/send-input.d.ts +6 -0
- package/dist/src/channel/send-input.js +1 -0
- package/dist/src/channel/session.d.ts +44 -30
- package/dist/src/channel/session.js +1 -1
- package/dist/src/channel/types.d.ts +8 -35
- package/dist/src/chunks/{use-eve-agent-DDoDDmJ2.js → use-eve-agent-CF5D6jSV.js} +339 -367
- package/dist/src/chunks/{use-eve-agent-Bx-ONuyb.js → use-eve-agent-DbYZLG0h.js} +342 -368
- package/dist/src/cli/commands/agent-prompt/build-and-verify.md +1 -2
- package/dist/src/cli/commands/channel-add-conflicts.js +1 -1
- package/dist/src/cli/commands/info.d.ts +1 -1
- package/dist/src/cli/commands/info.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +1 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/dev/tui/tui.js +1 -1
- package/dist/src/cli/invoke/invoke.d.ts +1 -1
- package/dist/src/cli/invoke/invoke.js +1 -1
- package/dist/src/cli/invoke/result.d.ts +0 -11
- package/dist/src/cli/invoke/result.js +1 -1
- package/dist/src/client/client-error.d.ts +2 -0
- package/dist/src/client/client-error.js +1 -1
- package/dist/src/client/client.d.ts +7 -14
- package/dist/src/client/client.js +1 -1
- package/dist/src/client/eve-agent-store.d.ts +4 -4
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/index.d.ts +2 -1
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-response.d.ts +2 -7
- package/dist/src/client/message-response.js +1 -1
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session-controls.d.ts +29 -0
- package/dist/src/client/session-controls.js +1 -0
- package/dist/src/client/session-utils.d.ts +0 -20
- package/dist/src/client/session-utils.js +1 -1
- package/dist/src/client/session.d.ts +26 -90
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/sessions.d.ts +20 -0
- package/dist/src/client/sessions.js +1 -0
- package/dist/src/client/types.d.ts +26 -47
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/evals/cli/eval-client.js +1 -1
- package/dist/src/evals/context.js +1 -1
- package/dist/src/evals/session.d.ts +7 -6
- package/dist/src/evals/session.js +1 -1
- package/dist/src/evals/types.d.ts +9 -9
- package/dist/src/execution/agent-handle-dispatch.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +1 -3
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/runtime-errors.d.ts +1 -1
- package/dist/src/execution/session-command-token.d.ts +2 -0
- package/dist/src/execution/session-command-token.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/turn-control-receiver.d.ts +2 -2
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/cancelled-turn-emission.d.ts +1 -1
- package/dist/src/harness/cancelled-turn-emission.js +1 -1
- package/dist/src/harness/emission.d.ts +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/handles/prompt.d.ts +22 -3
- package/dist/src/harness/handles/prompt.js +1 -1
- package/dist/src/harness/handles/store.d.ts +0 -5
- package/dist/src/harness/handles/store.js +1 -1
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-artifacts.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-local-roots.d.ts +15 -0
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-local-roots.js +1 -0
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.d.ts +14 -2
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
- package/dist/src/internal/nitro/host/dev-server-http.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.d.ts +2 -5
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-route-context.d.ts +4 -3
- package/dist/src/internal/nitro/routes/channel-route-context.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/protocol/cancel-turn.d.ts +9 -4
- package/dist/src/protocol/cancel-turn.js +1 -1
- package/dist/src/protocol/message.d.ts +4 -14
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/protocol/reset-session.d.ts +1 -1
- package/dist/src/protocol/routes.d.ts +27 -47
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +19 -21
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
- package/dist/src/public/channels/discord/discordChannel.d.ts +4 -4
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/eve.d.ts +11 -10
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/github/dispatch.d.ts +8 -8
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/githubChannel.d.ts +3 -3
- package/dist/src/public/channels/github/githubChannel.js +1 -1
- package/dist/src/public/channels/github/pr-context.d.ts +1 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/channels/linear/linearChannel.d.ts +3 -3
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/interactions.d.ts +3 -4
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/session-operations.d.ts +37 -0
- package/dist/src/public/channels/slack/session-operations.js +1 -0
- package/dist/src/public/channels/slack/slackChannel.d.ts +55 -74
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +3 -3
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +4 -4
- package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
- package/dist/src/public/channels/twilio/twilioChannel.d.ts +3 -3
- package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
- package/dist/src/public/definitions/callback-context.d.ts +1 -2
- package/dist/src/public/definitions/channel.d.ts +21 -86
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/remote-agent.js +1 -1
- package/dist/src/public/definitions/schedule.d.ts +16 -16
- package/dist/src/public/schedules/index.d.ts +1 -1
- package/dist/src/react/use-eve-agent.d.ts +7 -4
- package/dist/src/react/use-eve-agent.js +1 -1
- package/dist/src/runtime/agent/bootstrap-model-utils.d.ts +11 -0
- package/dist/src/runtime/agent/bootstrap-model-utils.js +1 -1
- package/dist/src/runtime/agent/mock-model-adapter.js +1 -1
- package/dist/src/runtime/agent/mock-model-fixtures.js +2 -2
- package/dist/src/runtime/prompt/compose.js +1 -1
- package/dist/src/runtime/subagents/dynamic-remote-agent-config.js +1 -1
- package/dist/src/runtime/types.d.ts +2 -2
- package/dist/src/services/inspect-application.d.ts +1 -1
- package/dist/src/services/inspect-application.js +1 -1
- package/dist/src/setup/channel-add-conflicts.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +29 -17
- package/dist/src/shared/channel-definition.d.ts +7 -7
- package/dist/src/shared/schedule-definition.d.ts +2 -2
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +8 -5
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +8 -5
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/README.md +6 -6
- package/docs/channels/chat-sdk.mdx +5 -6
- package/docs/channels/custom.mdx +116 -144
- package/docs/channels/discord.mdx +1 -1
- package/docs/channels/eve.mdx +76 -30
- package/docs/channels/github.mdx +1 -1
- package/docs/channels/linear.mdx +6 -8
- package/docs/channels/overview.mdx +2 -2
- package/docs/channels/slack.mdx +46 -15
- package/docs/channels/telegram.mdx +1 -1
- package/docs/channels/twilio.mdx +1 -1
- package/docs/concepts/default-harness.md +11 -3
- package/docs/concepts/execution-model-and-durability.mdx +17 -5
- package/docs/concepts/sessions-runs-and-streaming.md +42 -16
- package/docs/evals/cases.mdx +3 -3
- package/docs/evals/targets.mdx +1 -1
- package/docs/guides/auth-and-route-protection.md +2 -1
- package/docs/guides/client/continuations.mdx +50 -77
- package/docs/guides/client/messages.mdx +29 -33
- package/docs/guides/client/output-schema.mdx +7 -14
- package/docs/guides/client/overview.mdx +40 -11
- package/docs/guides/client/streaming.mdx +17 -23
- package/docs/guides/frontend/nuxt.mdx +1 -1
- package/docs/guides/frontend/overview.mdx +40 -36
- package/docs/guides/frontend/sveltekit.mdx +1 -1
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +19 -23
- package/docs/guides/frontend/use-eve-agent-vue.mdx +21 -25
- package/docs/guides/instrumentation.md +1 -1
- package/docs/patterns/dynamic-scheduling.md +16 -15
- package/docs/schedules.mdx +10 -11
- package/docs/subagents.mdx +1 -1
- package/docs/tools/human-in-the-loop.md +1 -1
- package/docs/tutorial/ship-it.mdx +1 -1
- package/package.json +1 -1
- package/dist/src/channel/cancel.d.ts +0 -6
- package/dist/src/channel/cancel.js +0 -1
- package/dist/src/channel/clear-session.d.ts +0 -4
- package/dist/src/channel/clear-session.js +0 -1
- package/dist/src/channel/compact-session.d.ts +0 -4
- package/dist/src/channel/compact-session.js +0 -1
- package/dist/src/channel/reset-session.d.ts +0 -6
- package/dist/src/channel/reset-session.js +0 -1
- package/dist/src/channel/resolve-active-session.d.ts +0 -4
- package/dist/src/channel/resolve-active-session.js +0 -1
- package/dist/src/channel/send.d.ts +0 -6
- package/dist/src/channel/send.js +0 -1
|
@@ -28,8 +28,7 @@ terminal UI in a controllable background process instead:
|
|
|
28
28
|
|
|
29
29
|
Wait for the server URL, then exercise the HTTP API: create a session with
|
|
30
30
|
`POST /eve/v1/session`, attach to `GET /eve/v1/session/:id/stream`, and send a
|
|
31
|
-
follow-up
|
|
32
|
-
verification.
|
|
31
|
+
follow-up to `POST /eve/v1/session/:id`. Stop the dev process after verification.
|
|
33
32
|
|
|
34
33
|
When the user is ready to use their agent's REPL, give them the interactive
|
|
35
34
|
command to run from the project directory:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{EVE_SESSION_ROUTE_PATH}from"#protocol/routes.js";import{join}from"node:path";import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{discoverAgent}from"#discover/discover-agent.js";const SCAFFOLDED_WEB_CHANNEL_LOGICAL_PATH=`channels/eve.ts`;async function inspectExistingChannelRegistrations(a){let o=join(a,`agent`),{manifest:s}=await discoverAgent({agentRoot:o,appRoot:a}),c=new Set,l=new Set;for(let t of s.channels){let r=await compileChannelDefinition(o,t),i=Array.isArray(r)?r:[r];for(let n of i)n.kind===`channel`&&(n.method===`POST`&&n.urlPath===EVE_SESSION_ROUTE_PATH&&c.add(t.logicalPath),n.adapterKind===`slack`&&l.add(t.logicalPath))}let u={};return[...c].some(e=>e!==SCAFFOLDED_WEB_CHANNEL_LOGICAL_PATH)&&(u.web=`POST ${EVE_SESSION_ROUTE_PATH} already registered`),l.size>0&&(u.slack=`Slack channel already registered`),{disabledChannelReasons:u,webRouteOwners:[...c],slackOwners:[...l]}}function assertCanAddSelectedChannels(t,n){if(t.includes(`web`)){let t=n.webRouteOwners.find(e=>e!==SCAFFOLDED_WEB_CHANNEL_LOGICAL_PATH);if(t!==void 0)throw Error(`Cannot scaffold Web Chat because agent/${t} already defines POST ${EVE_SESSION_ROUTE_PATH}. Web Chat scaffolds the same eve session routes.`)}if(t.includes(`slack`)){let e=n.slackOwners.find(e=>e!==`channels/slack.ts`);if(e!==void 0)throw Error(`Cannot scaffold Slack because agent/${e} already defines a Slack channel. Slack scaffolding would register the channel again.`)}}export{assertCanAddSelectedChannels,inspectExistingChannelRegistrations};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createCliTheme,renderCliBanner,renderCliSection}from"#cli/ui/output.js";import{inspectApplication}from"#services/inspect-application.js";function buildApplicationInfoJson(e){let{application:t,compiledState:n,messaging:r}=e;return{appRoot:t.appRoot,agentRoot:n?.project.agentRoot??null,layout:n?.project.layout??null,status:n?.metadata.status??`unavailable`,diagnostics:n?{errors:n.metadata.discovery.summary.errors,warnings:n.metadata.discovery.summary.warnings}:null,model:n?.manifest.config.model.id??null,instructions:n?.manifest.instructions?.logicalPath??null,skills:(n?.manifest.skills??[]).map(e=>e.name),tools:(n?.manifest.tools??[]).map(e=>e.name),subagents:(n?.manifest.subagents??[]).map(e=>e.name),schedules:(n?.manifest.schedules??[]).map(e=>e.name),channels:(n?.manifest.channels??[]).map(e=>e.kind===`channel`?{name:e.name,kind:e.adapterKind??null,method:e.method,urlPath:e.urlPath}:{name:e.name,kind:`disabled`,method:null,urlPath:null}),messaging:{create:r.createSessionRoutePath,
|
|
1
|
+
import{createCliTheme,renderCliBanner,renderCliSection}from"#cli/ui/output.js";import{inspectApplication}from"#services/inspect-application.js";function buildApplicationInfoJson(e){let{application:t,compiledState:n,messaging:r}=e;return{appRoot:t.appRoot,agentRoot:n?.project.agentRoot??null,layout:n?.project.layout??null,status:n?.metadata.status??`unavailable`,diagnostics:n?{errors:n.metadata.discovery.summary.errors,warnings:n.metadata.discovery.summary.warnings}:null,model:n?.manifest.config.model.id??null,instructions:n?.manifest.instructions?.logicalPath??null,skills:(n?.manifest.skills??[]).map(e=>e.name),tools:(n?.manifest.tools??[]).map(e=>e.name),subagents:(n?.manifest.subagents??[]).map(e=>e.name),schedules:(n?.manifest.schedules??[]).map(e=>e.name),channels:(n?.manifest.channels??[]).map(e=>e.kind===`channel`?{name:e.name,kind:e.adapterKind??null,method:e.method,urlPath:e.urlPath}:{name:e.name,kind:`disabled`,method:null,urlPath:null}),messaging:{create:r.createSessionRoutePath,messages:r.sessionMessagesRoutePattern,stream:r.streamRoutePattern},artifacts:n?{compiledManifest:n.paths.compiledManifestPath,discoveryManifest:n.paths.discoveryManifestPath,diagnostics:n.paths.diagnosticsPath,moduleMap:n.paths.moduleMapPath,metadata:n.paths.compileMetadataPath}:null}}function pluralize(e,t){return`${e} ${t}${e===1?``:`s`}`}function formatDiscoverySummary(e,t){return`${pluralize(e,`error`)}, ${pluralize(t,`warning`)}`}function resolveCompileTone(e){switch(e){case`ready`:return`success`;case`failed`:return`danger`;default:return`warning`}}async function printApplicationInfo(i,a,o={}){let s=await inspectApplication(a);if(o.json){i.log(JSON.stringify(buildApplicationInfoJson(s),null,2));return}let c=s.compiledState,l=s.application,u=createCliTheme(),d=[{label:`App Root`,value:l.appRoot}],f=[{label:`Workflow Build`,value:l.workflowBuildDir},{label:`Output`,value:l.outputDir}],p=[];c===null?d.push({label:`Compile`,tone:`warning`,value:`unavailable`}):(d.push({label:`Agent Root`,value:c.project.agentRoot},{label:`Layout`,value:c.project.layout},{label:`Compile`,tone:resolveCompileTone(c.metadata.status),value:c.metadata.status},{label:`Diagnostics`,tone:c.metadata.discovery.summary.errors>0?`danger`:c.metadata.discovery.summary.warnings>0?`warning`:`success`,value:formatDiscoverySummary(c.metadata.discovery.summary.errors,c.metadata.discovery.summary.warnings)},{label:`Instructions`,value:c.manifest.instructions?.logicalPath??`none`},{label:`Skills`,value:pluralize(c.manifest.skills.length,`skill`)},{label:`Tools`,value:pluralize(c.manifest.tools.length,`tool`)},{label:`Subagents`,value:pluralize(c.manifest.subagents.length,`subagent`)},{label:`Schedules`,value:pluralize(c.manifest.schedules.length,`schedule`)}),f.unshift({label:`Compiled Manifest`,value:c.paths.compiledManifestPath},{label:`Discovery Manifest`,value:c.paths.discoveryManifestPath},{label:`Diagnostics`,value:c.paths.diagnosticsPath},{label:`Module Map`,value:c.paths.moduleMapPath},{label:`Metadata`,value:c.paths.compileMetadataPath}),p.push(c.manifest.instructions===void 0?{label:`Instructions`,value:`No instructions prompt discovered.`}:{label:`Instructions`,value:c.manifest.instructions.logicalPath})),i.log([renderCliBanner(u,{subtitle:`Resolved application paths and the active message contract.`,title:`eve Info`}),``,renderCliSection(u,{rows:d,title:`Application`}),``,renderCliSection(u,{rows:f,title:`Artifacts`}),...c===null?[]:[``,renderCliSection(u,{rows:p,title:`Instructions`})],``,renderCliSection(u,{rows:[{label:`Workflow ID`,value:l.workflowId},{label:`Source Dir`,value:l.workflowSourceDir},{label:`Create`,tone:`info`,value:`POST ${s.messaging.createSessionRoutePath}`},{label:`Messages`,tone:`info`,value:`POST ${s.messaging.sessionMessagesRoutePattern}`},{label:`Stream`,tone:`info`,value:`GET ${s.messaging.streamRoutePattern}`}],title:`Messaging`})].join(`
|
|
2
2
|
`))}export{buildApplicationInfoJson,printApplicationInfo};
|
|
@@ -307,7 +307,7 @@ export interface PromptCommandHandler {
|
|
|
307
307
|
}>, context: PromptCommandHandlerContext): Promise<PromptCommandOutcome | undefined>;
|
|
308
308
|
}
|
|
309
309
|
export type EveTUIRunnerOptions = TuiDisplayOptions & {
|
|
310
|
-
session
|
|
310
|
+
session?: ClientSession;
|
|
311
311
|
/** Production TUI probe injected by the launcher; omitted in hermetic runners. */
|
|
312
312
|
probeMcpConnection?: McpConnectionProbe;
|
|
313
313
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{pickAgentHeaderTip}from"./agent-header.js";import{failureKey,formatFailureDetail,formatFailureHint,formatFailureMessage,isInterruptedError,localFailureHint}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createMcpConnectionStatusTracker}from"./mcp-connection-status.js";import{createRemoteConnectionController}from"./remote-connection.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{probeAgentInfo}from"#services/dev-client/agent-info-probe.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";async function delayMs(e){await new Promise(t=>{setTimeout(t,e).unref?.()})}function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S=!1;#C=new AbortController;#w=!1;#T=[];#E;#D;#O;#k=pickAgentHeaderTip();#A;#j=new Map;#M;#N=new Map;#P=new Set;#F=!1;#I;#L;constructor(t){this.#e=t.session,t.client!==void 0&&(this.#t=t.client),t.lifecycle!==void 0&&(this.#L=t.lifecycle),this.#n=createRenderer(t);let n={formatActionResultError};if(this.#t!==void 0&&(n.client=this.#t),this.#n.subagents!==void 0&&(n.view=this.#n.subagents),this.#M=new SubagentPump(n),this.#r=t.name??`eve`,this.#_=t.withExclusiveTerminal,this.#i=t.tools??`full`,this.#a=t.reasoning??`full`,this.#o=t.subagents??`full`,this.#s=t.connectionAuth??`full`,this.#c=t.assistantResponseStats??`tokensPerSecond`,this.#l=t.contextSize,this.#u=t.formatTransportError??toErrorMessage,t.initialInput!==void 0&&(this.#m=t.initialInput),t.appRoot!==void 0){this.#p=t.appRoot;let e={appRoot:t.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};t.detectProjectIdentity!==void 0&&(e.detectIdentity=t.detectProjectIdentity),this.#D=createVercelStatusTracker(e),t.probeMcpConnection!==void 0&&(this.#O=createMcpConnectionStatusTracker({onChange:()=>{},probe:t.probeMcpConnection}))}if(t.promptCommandHandler!==void 0&&(this.#h=t.promptCommandHandler),this.#g=t.availablePromptCommands??PROMPT_COMMANDS,t.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#v=createRemoteConnectionController({client:this.#t,credentials:t.remote.credentials,target:t.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:t.remote.resolveOidcToken,resolveDeployment:t.remote.resolveDeployment})}this.#y=t.bootDetections??BOOT_DETECTIONS,this.#b=t.getVercelAuthStatus??getVercelAuthStatus,t.onBootProgress!==void 0&&(this.#x=t.onBootProgress),t.serverUrl!==void 0&&(this.#f=t.serverUrl),t.serverUrl!==void 0&&t.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:t.serverUrl}))}async#R(){if(this.#f===void 0){this.#B(),await this.#Y(void 0);return}let e;if(this.#v!==void 0){let t=await this.#v.check();t.state===`ready`&&(e=t.info)}else{let t=this.#t;if(t!==void 0)try{let n=await devBootPhase(`connecting to agent`,()=>probeAgentInfo({client:t}),this.#x);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}this.#B();let t=this.#z(e);await this.#Y(t)}#z(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#A=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#k),this.#n.renderAgentHeader?.(r),t}#B(){let e=this.#x;this.#x=void 0,e?.({type:`before-first-paint`})}async run(){let onStop=()=>this.#n.requestInterrupt?.();this.#L?.signal.aborted===!0?onStop():this.#L?.signal.addEventListener(`abort`,onStop,{once:!0});try{await this.#V()}finally{this.#L?.signal.removeEventListener(`abort`,onStop),this.#S=!0,this.#C.abort(),this.#M.abortAll(),this.#I?.(),this.#I=void 0,this.#n.shutdown?.(),this.#D?.dispose(),this.#O?.dispose(),this.#v?.dispose()}}async#V(){let e=this.#r,r,i,a=!1,o=!1,s=!1,l=this.#m;await this.#R(),this.#v?.current().connection.state===`auth-required`&&await this.#ie({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`}),this.#$(),this.#D?.refreshIdentity(),this.#O?.refresh();let u=this.#m===void 0?void 0:parsePromptCommand(this.#m);for(u?.type===`extension`&&u.name===`model`&&u.argument===``&&this.#p!==void 0&&this.#h!==void 0&&this.#n.setupFlow!==void 0&&(l=void 0,await this.#ae(e));;){if(this.#L?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;if(!s){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};l!==void 0&&(t.initialDraft=l,l=void 0);try{r=await this.#W(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let u=parsePromptCommand(r);if(u?.type===`exit`){this.#L?.requestStop();return}if(u?.type===`cancel`){if(this.#e.state.sessionId===void 0){this.#ee(`No active turn to cancel.`),i=void 0,o=!1,s=!1,r=void 0;continue}try{let e=await this.#e.cancel();if(this.#ee(e.status===`accepted`?`Turn cancellation requested.`:`No active turn to cancel.`),e.status===`no_active_turn`){i=void 0,o=!1,s=!1,r=void 0;continue}}catch(e){this.#ee(`Couldn't cancel the turn: ${toErrorMessage(e)}`),i=void 0,o=!1,s=!1,r=void 0;continue}i=void 0,o=!0,s=!1,r=void 0}if(u?.type===`reset`){if(!await this.#U()){i=void 0,s=!1,r=void 0;continue}i=void 0,s=!1,r=void 0;continue}if(u?.type===`compact`){try{let e=await this.#e.compact();if(this.#ee(e.status===`accepted`?`Compaction requested.`:`No active session to compact.`),e.status===`no_active_session`){i=void 0,o=!1,s=!1,r=void 0;continue}}catch(e){this.#ee(`Couldn't compact the session: ${toErrorMessage(e)}`),i=void 0,o=!1,s=!1,r=void 0;continue}i=void 0,o=!0,s=!1,r=void 0}if(u?.type===`clear`){try{let e=await this.#e.clear();if(this.#ee(e.status===`accepted`?`Context clear requested.`:`No active session to clear.`),e.status===`no_active_session`){i=void 0,o=!1,s=!1,r=void 0;continue}}catch(e){this.#ee(`Couldn't clear the session: ${toErrorMessage(e)}`),i=void 0,o=!1,s=!1,r=void 0;continue}i=void 0,o=!0,s=!1,r=void 0}if(u?.type===`help`){this.#ee(formatPromptCommandHelp(this.#g)),i=void 0,s=!1,r=void 0;continue}if(u?.type===`loglevel`){this.#ee(this.#ce(u.argument)),i=void 0,s=!1,r=void 0;continue}if(u?.type===`traces`){await this.#se(u.argument),i=void 0,s=!1,r=void 0;continue}if(u?.type===`extension`){try{await this.#ie(u,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,s=!1;continue}a=!0}let u=o?this.#q():await this.#G({prompt:s?void 0:r,inputResponses:i}),d=this.#e.state.sessionId;d!==void 0&&this.#n.setSessionId?.(d);let f=r,p=!1;try{for(;;){await this.#n.renderStream(u,{title:e,submittedPrompt:f,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=u.turnState?.pendingApprovals??[],n=u.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#j.delete(n.approvalId)}}if(n.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of n){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#j.delete(t.requestId)}}if(a.length===0)break;s=!0,i=a,r=void 0,p=!0;break}if(this.#pe(u)){u=this.#q(),f=void 0;continue}if(u.turnState&&u.turnState.boundaryEvent===void 0)if(u.turnState.aborted)this.#F=!0;else{let e=this.#e.state.sessionId;this.#n.renderNotice?.(e?`Lost the event stream — the turn may still be running on the server (session ${e}). Your next message resumes this session; use /cancel to stop the turn.`:`Lost the connection to the running turn.`)}break}}catch(e){if(isInterruptedError(e))return;throw e}if(p)continue;o=!1,s=!1,i=void 0,r=void 0;let m=u.turnState?.boundaryEvent;!this.#F&&(m===`session.waiting`||m===`session.completed`)&&(r=this.#n.takeQueuedPrompt?.()),this.#F&&(this.#F=!1,this.#H(),u.turnState?.aborted?this.#n.renderNotice?.(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`):this.#n.renderSessionBoundary===void 0?this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary())}}#H(){this.#M.abortAll(),this.#j.clear(),this.#N.clear(),this.#P.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#t&&(this.#e=this.#t.session()),this.#d?.clear()}async#U(){try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#H(),this.#n.reset?.(),!0}async#W(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#d;if(n===void 0)return await t;let r=!1,i=!1,a,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#de()})}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let o=setInterval(()=>{startRefresh()},500);o.unref?.();try{return await t}finally{r=!0,clearInterval(o),await a}}async#G(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r;try{this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#de()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),r=await this.#e.send(n)}catch(e){if(isInterruptedError(e))throw e;return this.#v?.reportFailure(e),this.#F=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#J(r,()=>t.abort())}async#K(e){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let t=0;t<8;t+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let t=e.turnId;try{if((await this.#e.cancel(t===void 0?void 0:{turnId:t})).status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#q(){let e=new AbortController;return this.#J(this.#e.stream({signal:e.signal}),()=>e.abort())}#J(e,t){let n=createTurnState();return{abort:()=>{n.aborted=!0,t()},cancel:()=>{this.#K(n)},events:eveEventsToTUIStream({events:e,pendingInputRequests:this.#j,turnState:n,onSubagentCalled:e=>this.#M.begin(e),onSubagentCompleted:e=>this.#M.settle(e),onTurnCancelled:()=>this.#M.settleAll(),onConnectionAuthRequired:e=>this.#fe(e),onConnectionAuthCompleted:e=>this.#me(e),onTerminalFailure:()=>{this.#F=!0},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:n}}async#Y(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#T=await detectSetupIssues(t,this.#y),this.#n.renderSetupWarning!==void 0&&(this.#X(),this.#Z())}#X(){let e=orderedSetupIssues(this.#T,this.#E);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#Z(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#b(e,{signal:this.#C.signal})}catch{return}this.#S||this.#w||(this.#E=authIssueForStatus(t),this.#X())}async#Q(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#T=await detectSetupIssues(n,this.#y);let e=await this.#b(t,{signal:this.#C.signal});this.#E=authIssueForStatus(e)}catch{return}this.#S||this.#X()}#$(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#I===void 0&&(this.#I=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#ee(e,t){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e,t);return}this.#n.renderNotice?.(e)}}async#te(e,t){let n=this.#h;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r={renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#v,withExclusiveTerminal:this.#_},i=this.#O?.current(),a=i!==void 0&&Object.keys(i).length>0?{...r,disabledConnectionReasons:i}:r;return t.keepSetupFlowOpen===!0?await n.handle(e,{...a,keepSetupFlowOpen:!0}):await n.handle(e,a)}#ne(e,t){if(t!==`startup`)return;let n=this.#v?.current().connection.state,r=n===`auth-failed`||n===`unavailable`?`failed`:void 0,i=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${i}`,r)}async#re(e){if(e?.kind===`model-access-changed`){this.#D?.applyEffect({kind:`refresh-identity`}),this.#w=!0,await this.#le();return}e!==void 0&&(this.#D?.applyEffect(e),this.#w=!0,this.#Q(this.#A))}async#ie(e,t,n){let r=await this.#te(e,{initialModelStep:n.initialModelStep,keepSetupFlowOpen:n.keepSetupFlowOpen,title:t});this.#ne(e,n.trigger),this.#ee(r?.message,r?.tone),await this.#re(r?.effect),this.#oe()}async#ae(e){let t=this.#p;if(t===void 0)return;let authStatus=async()=>{try{return await this.#b(t,{signal:this.#C.signal})}catch{return}},n=await authStatus();if(n===`cli-missing`&&(await this.#ie({type:`extension`,name:`vc:install`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`)){this.#n.setupFlow?.end();return}if(n===`logged-out`&&(await this.#ie({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`||n===`logged-out`)){this.#n.setupFlow?.end();return}await this.#ie({type:`extension`,name:`model`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`}),await this.#ie({type:`extension`,name:`add`,argument:``},e,{trigger:`startup`})}#oe(){let e=this.#v?.current().connection;e?.state!==`ready`||e.info===this.#A||(this.#A=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}async#se(e){if(this.#p===void 0||this.#n.traceViewer===void 0){this.#ee(`/traces is only available in local dev sessions.`);return}try{await this.#n.traceViewer.open({appRoot:this.#p,sessionId:this.#e.state.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}}#ce(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 all|stderr|sandbox|none — 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 all, stderr, sandbox, or none.`;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`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#le(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#z(await this.#ue());this.#Q(t)}async#ue(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}async#de(){let e=this.#A,t=await this.#ue();t!==void 0&&this.#z(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#fe(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#N.set(e.data.name,t),this.#he(t)}#pe(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#N.values())e.state!==`required`||e.webhookUrl===void 0||(e.state=`pending`,this.#P.add(e.name),this.#he(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#P.size),this.#P.size>0}#me(e){let t=this.#N.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#N.set(e.data.name,t),this.#P.delete(e.data.name),this.#he(t),this.#n.setConnectionAuthPendingCount?.(this.#P.size)}#he(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}};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,input:e.userInput,output:e.screen,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentCompleted:a,onTurnCancelled:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureHintOverride:u}=e,d=new Map,f=new Map,p=createEventDeduper(),m=0,h=new Set,g=new Set,_=new Set,v=!1,y=!1,b;for await(let e of t)if(p.admit(e)&&!(y&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`message.received`:break;case`turn.started`:r.turnId=e.data.turnId;break;case`step.started`:m+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;b=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(m<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||m<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=m,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=m,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=m,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=m,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(m<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||m<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=m;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=m,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data.actions.filter(e=>e.kind===`tool-call`);if(t.length===0)break;for(let e of t)h.has(e.callId)||(h.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data.requests.filter(e=>e.action.kind===`tool-call`);if(t.length===0)break;for(let e of t){let t=e.action.callId;if(e.kind!==`session-limit`&&!h.has(t)&&(h.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),!g.has(e.requestId)){if(g.add(e.requestId),n.set(e.requestId,e),e.kind!==`tool-approval`){upsertPendingQuestion(r,e);continue}upsertPendingApproval(r,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(!h.has(n))break;switch(t.data.status){case`completed`:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break;case`failed`:yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:n,reason:formatActionResultError(t)};break}break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,_,u);t&&(yield t);break}case`session.failed`:{r.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),r.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`finish`,usage:b},v=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`finish`,usage:b},v=!0;return;case`turn.completed`:y=!0,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m);break;case`turn.cancelled`:o?.(),yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(e);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:a?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}v||(yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`finish`,usage:b})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{aborted:!1,pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let r=failureKey(e);if(t.has(r))return;t.add(r);let c={type:`error`,errorText:formatFailureMessage(e)},l=n?.(e)??formatFailureHint(e);l!==void 0&&(c.hint=l);let u=formatFailureDetail(e);return u!==void 0&&(c.detail=u),c}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}export{EveTUIRunner,parsePromptCommand};
|
|
1
|
+
import{PROMPT_COMMANDS,formatPromptCommandHelp,parsePromptCommand}from"./prompt-commands.js";import{pickAgentHeaderTip}from"./agent-header.js";import{failureKey,formatFailureDetail,formatFailureHint,formatFailureMessage,isInterruptedError,localFailureHint}from"./errors.js";import{parseLogDisplayMode}from"./log-display-mode.js";import{createMcpConnectionStatusTracker}from"./mcp-connection-status.js";import{createRemoteConnectionController}from"./remote-connection.js";import{SubagentPump}from"./subagent-pump.js";import{BOOT_DETECTIONS,CLI_MISSING_SETUP_ISSUE,LOGIN_SETUP_ISSUE,detectSetupIssues,formatSetupIssuesLine,orderedSetupIssues,resolveModelProviderState}from"./setup-issues.js";import{TerminalRenderer}from"./terminal-renderer.js";import{createVercelStatusTracker}from"./vercel-status.js";import"#client/index.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import{probeAgentInfo}from"#services/dev-client/agent-info-probe.js";import{subscribeDevelopmentSandboxPrewarmLogs}from"#execution/sandbox/development-prewarm.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{createDevelopmentRuntimeArtifactRefresher}from"#services/dev-client.js";import{devBootPhase}from"#internal/dev-boot-progress.js";async function delayMs(e){await new Promise(t=>{setTimeout(t,e).unref?.()})}function authIssueForStatus(e){if(e===`logged-out`)return LOGIN_SETUP_ISSUE;if(e===`cli-missing`)return CLI_MISSING_SETUP_ISSUE}var EveTUIRunner=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S=!1;#C=new AbortController;#w=!1;#T=[];#E;#D;#O;#k=pickAgentHeaderTip();#A;#j=new Map;#M;#N=new Map;#P=new Set;#F=!1;#I;#L;constructor(t){this.#e=t.session,t.client!==void 0&&(this.#t=t.client),t.lifecycle!==void 0&&(this.#L=t.lifecycle),this.#n=createRenderer(t);let n={formatActionResultError};if(this.#t!==void 0&&(n.client=this.#t),this.#n.subagents!==void 0&&(n.view=this.#n.subagents),this.#M=new SubagentPump(n),this.#r=t.name??`eve`,this.#_=t.withExclusiveTerminal,this.#i=t.tools??`full`,this.#a=t.reasoning??`full`,this.#o=t.subagents??`full`,this.#s=t.connectionAuth??`full`,this.#c=t.assistantResponseStats??`tokensPerSecond`,this.#l=t.contextSize,this.#u=t.formatTransportError??toErrorMessage,t.initialInput!==void 0&&(this.#m=t.initialInput),t.appRoot!==void 0){this.#p=t.appRoot;let e={appRoot:t.appRoot,onChange:e=>this.#n.setVercelStatus?.(e)};t.detectProjectIdentity!==void 0&&(e.detectIdentity=t.detectProjectIdentity),this.#D=createVercelStatusTracker(e),t.probeMcpConnection!==void 0&&(this.#O=createMcpConnectionStatusTracker({onChange:()=>{},probe:t.probeMcpConnection}))}if(t.promptCommandHandler!==void 0&&(this.#h=t.promptCommandHandler),this.#g=t.availablePromptCommands??PROMPT_COMMANDS,t.remote!==void 0){if(this.#t===void 0)throw Error(`A remote TUI requires a configured development client.`);this.#v=createRemoteConnectionController({client:this.#t,credentials:t.remote.credentials,target:t.remote.target,onChange:e=>this.#n.setRemoteConnectionStatus?.(e),resolveOidcToken:t.remote.resolveOidcToken,resolveDeployment:t.remote.resolveDeployment})}this.#y=t.bootDetections??BOOT_DETECTIONS,this.#b=t.getVercelAuthStatus??getVercelAuthStatus,t.onBootProgress!==void 0&&(this.#x=t.onBootProgress),t.serverUrl!==void 0&&(this.#f=t.serverUrl),t.serverUrl!==void 0&&t.remote===void 0&&(this.#d=createDevelopmentRuntimeArtifactRefresher({serverUrl:t.serverUrl}))}async#R(){if(this.#f===void 0){this.#B(),await this.#Y(void 0);return}let e;if(this.#v!==void 0){let t=await this.#v.check();t.state===`ready`&&(e=t.info)}else{let t=this.#t;if(t!==void 0)try{let n=await devBootPhase(`connecting to agent`,()=>probeAgentInfo({client:t}),this.#x);n.kind===`ready`&&(e=n.info)}catch{e=void 0}}this.#B();let t=this.#z(e);await this.#Y(t)}#z(e){let t=this.#p===void 0?e:resolveModelProviderState(e,process.env);this.#A=t;let n=this.#f;if(n===void 0)return t;let r={name:this.#r,serverUrl:n};return t!==void 0&&(r.info=t),this.#p!==void 0&&(r.tip=this.#k),this.#n.renderAgentHeader?.(r),t}#B(){let e=this.#x;this.#x=void 0,e?.({type:`before-first-paint`})}async run(){let onStop=()=>this.#n.requestInterrupt?.();this.#L?.signal.aborted===!0?onStop():this.#L?.signal.addEventListener(`abort`,onStop,{once:!0});try{await this.#V()}finally{this.#L?.signal.removeEventListener(`abort`,onStop),this.#S=!0,this.#C.abort(),this.#M.abortAll(),this.#I?.(),this.#I=void 0,this.#n.shutdown?.(),this.#D?.dispose(),this.#O?.dispose(),this.#v?.dispose()}}async#V(){let e=this.#r,r,i,a=!1,o=!1,s=!1,l=this.#m;await this.#R(),this.#v?.current().connection.state===`auth-required`&&await this.#ie({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`}),this.#$(),this.#D?.refreshIdentity(),this.#O?.refresh();let u=this.#m===void 0?void 0:parsePromptCommand(this.#m);for(u?.type===`extension`&&u.name===`model`&&u.argument===``&&this.#p!==void 0&&this.#h!==void 0&&this.#n.setupFlow!==void 0&&(l=void 0,await this.#ae(e));;){if(this.#L?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;if(!s){if(r==null){if(!this.#n.readPrompt){if(a)return;throw Error(`No prompt was provided and the renderer does not support prompt input.`)}let t={title:e};l!==void 0&&(t.initialDraft=l,l=void 0);try{r=await this.#W(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let u=parsePromptCommand(r);if(u?.type===`exit`){this.#L?.requestStop();return}if(u?.type===`cancel`){if(this.#e===void 0){this.#ee(`No active turn to cancel.`),i=void 0,o=!1,s=!1,r=void 0;continue}try{let e=await this.#e.cancel();if(this.#ee(e.status===`accepted`?`Turn cancellation requested.`:`No active turn to cancel.`),e.status===`no_active_turn`){i=void 0,o=!1,s=!1,r=void 0;continue}}catch(e){this.#ee(`Couldn't cancel the turn: ${toErrorMessage(e)}`),i=void 0,o=!1,s=!1,r=void 0;continue}i=void 0,o=!0,s=!1,r=void 0}if(u?.type===`reset`){if(!await this.#U()){i=void 0,s=!1,r=void 0;continue}i=void 0,s=!1,r=void 0;continue}if(u?.type===`compact`){if(this.#e===void 0){this.#ee(`No active session to compact.`),i=void 0,o=!1,s=!1,r=void 0;continue}try{let e=await this.#e.compact();if(this.#ee(e.status===`accepted`?`Compaction requested.`:`No active session to compact.`),e.status===`no_active_session`){i=void 0,o=!1,s=!1,r=void 0;continue}}catch(e){this.#ee(`Couldn't compact the session: ${toErrorMessage(e)}`),i=void 0,o=!1,s=!1,r=void 0;continue}i=void 0,o=!0,s=!1,r=void 0}if(u?.type===`clear`){if(this.#e===void 0){this.#ee(`No active session to clear.`),i=void 0,o=!1,s=!1,r=void 0;continue}try{let e=await this.#e.clear();if(this.#ee(e.status===`accepted`?`Context clear requested.`:`No active session to clear.`),e.status===`no_active_session`){i=void 0,o=!1,s=!1,r=void 0;continue}}catch(e){this.#ee(`Couldn't clear the session: ${toErrorMessage(e)}`),i=void 0,o=!1,s=!1,r=void 0;continue}i=void 0,o=!0,s=!1,r=void 0}if(u?.type===`help`){this.#ee(formatPromptCommandHelp(this.#g)),i=void 0,s=!1,r=void 0;continue}if(u?.type===`loglevel`){this.#ee(this.#ce(u.argument)),i=void 0,s=!1,r=void 0;continue}if(u?.type===`traces`){await this.#se(u.argument),i=void 0,s=!1,r=void 0;continue}if(u?.type===`extension`){try{await this.#ie(u,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,s=!1;continue}a=!0}let u=o?this.#q():await this.#G({prompt:s?void 0:r,inputResponses:i}),d=this.#e?.state.sessionId;d!==void 0&&this.#n.setSessionId?.(d);let f=r,p=!1;try{for(;;){await this.#n.renderStream(u,{title:e,submittedPrompt:f,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=u.turnState?.pendingApprovals??[],n=u.turnState?.pendingQuestions??[];if(t.length>0||n.length>0){let a=[];if(t.length>0){if(!this.#n.readToolApproval)throw Error(`Tool approval was requested, but the renderer does not support tool approval input.`);for(let n of t){let t=await this.#n.readToolApproval(n,{title:e});a.push({requestId:n.approvalId,optionId:t.approved?`approve`:`deny`}),this.#j.delete(n.approvalId)}}if(n.length>0){if(!this.#n.readInputQuestion)throw Error(`An interactive question was requested, but the renderer does not support input questions.`);for(let t of n){let n=toAgentTUIInputQuestion(t),r=await this.#n.readInputQuestion(n,{title:e});if(r===void 0)continue;let i={requestId:t.requestId};r.optionId!==void 0&&(i.optionId=r.optionId),r.text!==void 0&&(i.text=r.text),a.push(i),this.#j.delete(t.requestId)}}if(a.length===0)break;s=!0,i=a,r=void 0,p=!0;break}if(this.#pe(u)){u=this.#q(),f=void 0;continue}if(u.turnState&&u.turnState.boundaryEvent===void 0)if(u.turnState.aborted)this.#F=!0;else{let e=this.#e?.state.sessionId;this.#n.renderNotice?.(e?`Lost the event stream — the turn may still be running on the server (session ${e}). Your next message resumes this session; use /cancel to stop the turn.`:`Lost the connection to the running turn.`)}break}}catch(e){if(isInterruptedError(e))return;throw e}if(p)continue;o=!1,s=!1,i=void 0,r=void 0;let m=u.turnState?.boundaryEvent;!this.#F&&(m===`session.waiting`||m===`session.completed`)&&(r=this.#n.takeQueuedPrompt?.()),this.#F&&(this.#F=!1,this.#H(),u.turnState?.aborted?this.#n.renderNotice?.(`Stopped following the turn and started a new session. Earlier context was cleared; the interrupted turn may still be running on the server.`):this.#n.renderSessionBoundary===void 0?this.#n.renderNotice?.(`Session ended — started a new session. Earlier context was cleared.`):this.#n.renderSessionBoundary())}}#H(){this.#M.abortAll(),this.#j.clear(),this.#N.clear(),this.#P.clear(),this.#n.setConnectionAuthPendingCount?.(0),this.#e=void 0,this.#d?.clear()}async#U(){if(this.#e===void 0)return this.#H(),this.#n.reset?.(),!0;try{await this.#e.reset()}catch(e){return this.#n.renderNotice?.(`Couldn't reset the session: ${toErrorMessage(e)}`),!1}return this.#H(),this.#n.reset?.(),!0}async#W(e){if(!this.#n.readPrompt)return;let t=this.#n.readPrompt(e),n=this.#d;if(n===void 0)return await t;let r=!1,i=!1,a,refresh=async()=>{if(!(r||i)){i=!0;try{await n.refreshIdle({onRuntimeArtifactsChanged:()=>this.#de()})}finally{i=!1}}},startRefresh=()=>{if(r||i)return;let e=refresh().finally(()=>{a===e&&(a=void 0)});a=e};startRefresh();let o=setInterval(()=>{startRefresh()},500);o.unref?.();try{return await t}finally{r=!0,clearInterval(o),await a}}async#G(e){let t=new AbortController,n={signal:t.signal};e.prompt!==void 0&&(n.message=e.prompt),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses);let r;try{if(this.#d!==void 0&&await this.#d.refresh({inputResponses:n.inputResponses,message:n.message,onRuntimeArtifactsChanged:()=>this.#de()}),n.message!==void 0&&(n.inputResponses?.length??0)===0&&this.#n.flushDelayedDevBuildErrors?.(),this.#e===void 0){if(this.#t===void 0)throw Error(`Cannot create a session without an eve client.`);if(n.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let e=await this.#t.sessions.create({...n,message:n.message});this.#e=e.session,r=e.response}else r=n.inputResponses===void 0?await this.#e.send(n.message,{signal:n.signal}):await this.#e.respond(n.inputResponses,{signal:n.signal})}catch(e){if(isInterruptedError(e))throw e;return this.#v?.reportFailure(e),this.#F=!0,{events:errorOnlyTUIStream({errorText:this.#u(e)}),turnState:createTurnState()}}return this.#J(r,()=>t.abort())}async#K(e){if(e.cancelInFlight!==!0){e.cancelInFlight=!0;try{for(let t=0;t<8;t+=1){if(e.boundaryEvent!==void 0||e.aborted===!0)return;let t=e.turnId;try{if((await this.#e?.cancel(t===void 0?void 0:{turnId:t}))?.status===`accepted`)return}catch{}await delayMs(250)}}finally{e.cancelInFlight=!1}}}#q(){if(this.#e===void 0)throw Error(`Cannot stream a session before its first turn is accepted.`);let e=new AbortController;return this.#J(this.#e.stream({signal:e.signal}),()=>e.abort())}#J(e,t){let n=createTurnState();return{abort:()=>{n.aborted=!0,t()},cancel:()=>{this.#K(n)},events:eveEventsToTUIStream({events:e,pendingInputRequests:this.#j,turnState:n,onSubagentCalled:e=>this.#M.begin(e),onSubagentCompleted:e=>this.#M.settle(e),onTurnCancelled:()=>this.#M.settleAll(),onConnectionAuthRequired:e=>this.#fe(e),onConnectionAuthCompleted:e=>this.#me(e),onTerminalFailure:()=>{this.#F=!0},failureHintOverride:this.#p===void 0?void 0:localFailureHint}),turnState:n}}async#Y(e){if(this.#p===void 0)return;let t={appRoot:this.#p,env:process.env};e!==void 0&&(t.info=e),this.#T=await detectSetupIssues(t,this.#y),this.#n.renderSetupWarning!==void 0&&(this.#X(),this.#Z())}#X(){let e=orderedSetupIssues(this.#T,this.#E);e.length>0?this.#n.renderSetupWarning?.(formatSetupIssuesLine(e)):this.#n.clearSetupWarning?.()}async#Z(){let e=this.#p;if(e===void 0)return;let t;try{t=await this.#b(e,{signal:this.#C.signal})}catch{return}this.#S||this.#w||(this.#E=authIssueForStatus(t),this.#X())}async#Q(e){let t=this.#p;if(t===void 0||this.#n.renderSetupWarning===void 0)return;let n={appRoot:t,env:process.env};e!==void 0&&(n.info=e);try{this.#T=await detectSetupIssues(n,this.#y);let e=await this.#b(t,{signal:this.#C.signal});this.#E=authIssueForStatus(e)}catch{return}this.#S||this.#X()}#$(){this.#p===void 0||this.#n.renderSandboxLog===void 0||this.#I===void 0&&(this.#I=subscribeDevelopmentSandboxPrewarmLogs({appRoot:this.#p,log:e=>this.#n.renderSandboxLog?.(e)}))}#ee(e,t){if(e!==void 0){if(this.#n.renderCommandResult!==void 0){this.#n.renderCommandResult(e,t);return}this.#n.renderNotice?.(e)}}async#te(e,t){let n=this.#h;if(n===void 0)return{message:`/${e.name} is not available in this session.`};let r={renderer:this.#n,title:t.title,initialModelStep:t.initialModelStep,remoteConnection:this.#v,withExclusiveTerminal:this.#_},i=this.#O?.current(),a=i!==void 0&&Object.keys(i).length>0?{...r,disabledConnectionReasons:i}:r;return t.keepSetupFlowOpen===!0?await n.handle(e,{...a,keepSetupFlowOpen:!0}):await n.handle(e,a)}#ne(e,t){if(t!==`startup`)return;let n=this.#v?.current().connection.state,r=n===`auth-failed`||n===`unavailable`?`failed`:void 0,i=e.argument.length===0?``:` ${e.argument}`;this.#n.renderCommandInvocation?.(`/${e.name}${i}`,r)}async#re(e){if(e?.kind===`model-access-changed`){this.#D?.applyEffect({kind:`refresh-identity`}),this.#w=!0,await this.#le();return}e!==void 0&&(this.#D?.applyEffect(e),this.#w=!0,this.#Q(this.#A))}async#ie(e,t,n){let r=await this.#te(e,{initialModelStep:n.initialModelStep,keepSetupFlowOpen:n.keepSetupFlowOpen,title:t});this.#ne(e,n.trigger),this.#ee(r?.message,r?.tone),await this.#re(r?.effect),this.#oe()}async#ae(e){let t=this.#p;if(t===void 0)return;let authStatus=async()=>{try{return await this.#b(t,{signal:this.#C.signal})}catch{return}},n=await authStatus();if(n===`cli-missing`&&(await this.#ie({type:`extension`,name:`vc:install`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`)){this.#n.setupFlow?.end();return}if(n===`logged-out`&&(await this.#ie({type:`extension`,name:`vc:login`,argument:``},e,{trigger:`startup`,keepSetupFlowOpen:!0}),n=await authStatus(),n===`cli-missing`||n===`logged-out`)){this.#n.setupFlow?.end();return}await this.#ie({type:`extension`,name:`model`,argument:``},e,{trigger:`startup`,initialModelStep:`provider`}),await this.#ie({type:`extension`,name:`add`,argument:``},e,{trigger:`startup`})}#oe(){let e=this.#v?.current().connection;e?.state!==`ready`||e.info===this.#A||(this.#A=e.info,this.#f!==void 0&&this.#n.renderAgentHeader?.({info:e.info,name:this.#r,serverUrl:this.#f}))}async#se(e){if(this.#p===void 0||this.#n.traceViewer===void 0){this.#ee(`/traces is only available in local dev sessions.`);return}try{await this.#n.traceViewer.open({appRoot:this.#p,sessionId:this.#e?.state.sessionId,reference:e===``?void 0:e})}catch(e){if(isInterruptedError(e))return;throw e}}#ce(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 all|stderr|sandbox|none — 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 all, stderr, sandbox, or none.`;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`stderr`:return`Showing stderr logs only.`;case`sandbox`:return`Showing sandbox logs only.`;case`all`:return`Showing all logs.`}}async#le(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#z(await this.#ue());this.#Q(t)}async#ue(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}async#de(){let e=this.#A,t=await this.#ue();t!==void 0&&this.#z(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#fe(e){let t={name:e.data.name,description:e.data.description,state:`required`};e.data.authorization!==void 0&&(t.challenge=e.data.authorization),e.data.webhookUrl!==void 0&&(t.webhookUrl=e.data.webhookUrl),this.#N.set(e.data.name,t),this.#he(t)}#pe(e){if(e.turnState?.boundaryEvent!==`session.waiting`)return!1;let t=!1;for(let e of this.#N.values())e.state!==`required`||e.webhookUrl===void 0||(e.state=`pending`,this.#P.add(e.name),this.#he(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#P.size),this.#P.size>0}#me(e){let t=this.#N.get(e.data.name)??{name:e.data.name,description:``,state:e.data.outcome};t.state=e.data.outcome,e.data.reason!==void 0&&(t.reason=e.data.reason),this.#N.set(e.data.name,t),this.#P.delete(e.data.name),this.#he(t),this.#n.setConnectionAuthPendingCount?.(this.#P.size)}#he(e){let t={name:e.name,description:e.description,state:e.state};e.challenge!==void 0&&(t.challenge=e.challenge),e.reason!==void 0&&(t.reason=e.reason),this.#n.upsertConnectionAuth?.(t)}};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,input:e.userInput,output:e.screen,diagnostics:e.diagnostics,onExitRequest:e.lifecycle?.requestStop})}function formatAgentUpdateNotice(e,t){let n=e?.agent.model.id,r=t?.agent.model.id;return n!==void 0&&r!==void 0&&n!==r?`Agent updated: Model ${n} -> ${r}`:`Agent updated.`}async function*eveEventsToTUIStream(e){let{events:t,pendingInputRequests:n,turnState:r,onSubagentCalled:i,onSubagentCompleted:a,onTurnCancelled:o,onConnectionAuthRequired:s,onConnectionAuthCompleted:c,onTerminalFailure:l,failureHintOverride:u}=e,d=new Map,f=new Map,p=createEventDeduper(),m=0,h=new Set,g=new Set,_=new Set,v=!1,y=!1,b;for await(let e of t)if(p.admit(e)&&!(y&&isPostTurnVisibleEvent(e)))switch(e.type){case`session.started`:case`message.received`:break;case`turn.started`:r.turnId=e.data.turnId;break;case`step.started`:m+=1,yield{type:`step-start`};break;case`step.completed`:{let t=e;b=t.data.usage,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`step-finish`,usage:t.data.usage};break}case`message.appended`:{let t=e,n=textPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(d,n),i=t.data.messageSoFar;if(r.completed){if(m<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`assistant-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`message.completed`:{let t=textPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(d,t),r=e.data.message;if(n.completed){if(r===null||m<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=m,yield{type:`assistant-complete`,id:partGenerationId(t,n.generation),text:r};break}let i=partGenerationId(t,n.generation);if(r!==null){if(n.text.length===0)n.text=r,n.completed=!0,n.completedEpoch=m,yield{type:`assistant-complete`,id:i,text:r};else if(r.startsWith(n.text)){let e=r.slice(n.text.length);e.length>0&&(yield{type:`assistant-delta`,id:i,delta:e}),n.text=r,n.completed=!0,n.completedEpoch=m,yield{type:`assistant-complete`,id:i}}}else n.text.length>0&&(n.completed=!0,n.completedEpoch=m,yield{type:`assistant-complete`,id:i});break}case`reasoning.appended`:{let t=e,n=reasoningPartId(t.data.turnId,t.data.stepIndex),r=partStateFor(f,n),i=t.data.reasoningSoFar;if(r.completed){if(m<=r.completedEpoch)break;r.generation+=1,r.text=``,r.completed=!1}if(!i.startsWith(r.text)||i.length<=r.text.length)break;let a=i.slice(r.text.length);r.text=i,yield{type:`reasoning-delta`,id:partGenerationId(n,r.generation),delta:a};break}case`reasoning.completed`:{let t=reasoningPartId(e.data.turnId,e.data.stepIndex),n=partStateFor(f,t),r=e.data.reasoning;if(n.completed){if(r.length===0||m<=n.completedEpoch)break;n.generation+=1,n.text=r,n.completedEpoch=m;let e=partGenerationId(t,n.generation);yield{type:`reasoning-delta`,id:e,delta:r},yield{type:`reasoning-complete`,id:e};break}let i=partGenerationId(t,n.generation);if(n.text.length===0&&r.length>0)n.text=r,yield{type:`reasoning-delta`,id:i,delta:r};else if(r.length>0&&!r.startsWith(n.text))break;n.completed=!0,n.completedEpoch=m,yield{type:`reasoning-complete`,id:i};break}case`actions.requested`:{let t=e.data.actions.filter(e=>e.kind===`tool-call`);if(t.length===0)break;for(let e of t)h.has(e.callId)||(h.add(e.callId),yield{type:`tool-call`,toolCallId:e.callId,toolName:e.toolName,input:e.input});break}case`input.requested`:{let t=e.data.requests.filter(e=>e.action.kind===`tool-call`);if(t.length===0)break;for(let e of t){let t=e.action.callId;if(e.kind!==`session-limit`&&!h.has(t)&&(h.add(t),yield{type:`tool-call`,toolCallId:t,toolName:e.action.toolName,input:e.action.input}),!g.has(e.requestId)){if(g.add(e.requestId),n.set(e.requestId,e),e.kind!==`tool-approval`){upsertPendingQuestion(r,e);continue}upsertPendingApproval(r,e),yield{type:`tool-approval-request`,approvalId:e.requestId,toolCallId:t}}}break}case`action.result`:{let t=e;if(t.data.result.kind!==`tool-result`)break;let n=t.data.result.callId;if(!h.has(n))break;switch(t.data.status){case`completed`:yield{type:`tool-result`,toolCallId:n,output:t.data.result.output};break;case`failed`:yield{type:`tool-error`,toolCallId:n,errorText:formatActionResultError(t)};break;case`rejected`:yield{type:`tool-rejected`,toolCallId:n,reason:formatActionResultError(t)};break}break}case`step.failed`:case`turn.failed`:{let t=toFailureEvent(e,_,u);t&&(yield t);break}case`session.failed`:{r.sawSessionFailure=!0,l?.(e);let t=toFailureEvent(e,_,u);t&&(yield t),r.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`finish`,usage:b},v=!0;return}case`session.waiting`:case`session.completed`:r.boundaryEvent=e.type,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`finish`,usage:b},v=!0;return;case`turn.completed`:y=!0,yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m);break;case`turn.cancelled`:o?.(),yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`turn-cancelled`};break;case`subagent.called`:i?.(e);break;case`subagent.started`:case`subagent.event`:break;case`subagent.completed`:a?.(e.data.callId);break;case`authorization.required`:s?.(e);break;case`authorization.completed`:c?.(e);break;default:break}v||(yield*closeOpenParts(d,`assistant-complete`,m),yield*closeOpenParts(f,`reasoning-complete`,m),yield{type:`finish`,usage:b})}async function*errorOnlyTUIStream(e){yield{type:`error`,errorText:e.errorText},yield{type:`finish`}}function createTurnState(){return{aborted:!1,pendingApprovals:[],pendingQuestions:[],sawSessionFailure:!1}}function upsertPendingApproval(e,t){let n=toAgentTUIToolApprovalRequest(t),r=e.pendingApprovals.findIndex(e=>e.approvalId===n.approvalId);r===-1?e.pendingApprovals.push(n):e.pendingApprovals[r]=n}function toAgentTUIToolApprovalRequest(e){return{approvalId:e.requestId,toolCallId:e.action.callId,toolName:e.action.toolName,input:e.action.input}}function upsertPendingQuestion(e,t){let n=e.pendingQuestions.findIndex(e=>e.requestId===t.requestId);n===-1?e.pendingQuestions.push(t):e.pendingQuestions[n]=t}function textPartId(e,t){return`text:${e}:${t}`}function reasoningPartId(e,t){return`reasoning:${e}:${t}`}function partStateFor(e,t){let n=e.get(t);return n===void 0&&(n={generation:0,text:``,completed:!1,completedEpoch:0},e.set(t,n)),n}function partGenerationId(e,t){return t===0?e:`${e}#${t}`}function*closeOpenParts(e,t,n){for(let[r,i]of e)i.completed||i.text.length===0||(i.completed=!0,i.completedEpoch=n,yield{type:t,id:partGenerationId(r,i.generation)})}function isPostTurnVisibleEvent(e){switch(e.type){case`actions.requested`:case`authorization.completed`:case`authorization.required`:case`input.requested`:case`message.appended`:case`message.completed`:case`reasoning.appended`:case`reasoning.completed`:case`result.completed`:case`step.completed`:case`step.failed`:case`step.started`:case`subagent.called`:case`subagent.completed`:case`subagent.event`:case`subagent.started`:case`turn.completed`:case`turn.failed`:return!0;default:return!1}}function formatActionResultError(e){if(e.data.error?.message)return e.data.error.message;let t=e.data.result.output;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return`Tool execution failed.`}}function toFailureEvent(e,t,n){let r=failureKey(e);if(t.has(r))return;t.add(r);let c={type:`error`,errorText:formatFailureMessage(e)},l=n?.(e)??formatFailureHint(e);l!==void 0&&(c.hint=l);let u=formatFailureDetail(e);return u!==void 0&&(c.detail=u),c}function toAgentTUIInputQuestion(e){let t=e.display===`text`?`text`:e.display===`select`||e.options!==void 0&&e.options.length>0?`select`:`text`,n={requestId:e.requestId,prompt:e.prompt,display:t};return e.options!==void 0&&(n.options=e.options.map(e=>{let t={id:e.id,label:e.label};return e.description!==void 0&&(t.description=e.description),e.style!==void 0&&(t.style=e.style),t})),e.allowFreeform!==void 0&&(n.allowFreeform=e.allowFreeform),n}export{EveTUIRunner,parsePromptCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,r=this.#r.get(t);r===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map,seenChildEvents:createEventDeduper()}):r.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}settleAll(){for(let e of this.#r.keys())this.#s(e);for(let e of this.#i.values())e.abort();this.#i.clear()}#a(n){let i=n.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.
|
|
1
|
+
import{isAbortLikeError}from"./errors.js";import{toErrorMessage}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";var SubagentPump=class{#e;#t;#n;#r=new Map;#i=new Map;constructor(e){this.#e=e.client,this.#t=e.view,this.#n=e.formatActionResultError}begin(e){let t=e.data.callId,r=this.#r.get(t);r===void 0?this.#r.set(t,{name:e.data.name,status:`running`,steps:new Map,currentSectionKey:null,nextSectionKey:0,tools:new Map,seenChildEvents:createEventDeduper()}):r.name=e.data.name,this.#t?.markChildToolCallId(t),this.#t?.begin({callId:t,name:e.data.name}),this.#a(e)}settle(e){this.#s(e)}abortAll(){for(let e of this.#i.values())e.abort();this.#i.clear(),this.#r.clear()}settleAll(){for(let e of this.#r.keys())this.#s(e);for(let e of this.#i.values())e.abort();this.#i.clear()}#a(n){let i=n.data.callId;if(this.#i.has(i))return;let a=this.#e;if(!a)return;let o=new AbortController;this.#i.set(i,o),(async()=>{let s=!1;try{let e=a.sessions.attach(n.data.childSessionId).stream({signal:o.signal});for await(let t of e){if(o.signal.aborted)break;if(this.#l(i,t),isCurrentTurnBoundaryEvent(t)){s=!0;break}}}catch(n){if(!isAbortLikeError(n)){let e=toErrorMessage(n),r=this.#r.get(i);if(r){let{key:t,step:n}=openCurrentSubagentSection(r);n.message=n.message?`${n.message}\n\nstream error: ${e}`:`stream error: ${e}`,n.finalized=!0,r.currentSectionKey=null,this.#t?.upsertStep({callId:i,subagentName:r.name,sectionKey:t,reasoning:n.reasoning,message:n.message,finalized:!0})}}}finally{this.#i.delete(i)}s&&this.#s(i)})()}#o(e,t,n){let r=t.tools.get(n.childCallId),i=r??{toolName:n.toolName,input:n.input,status:n.status};if(r){let e={preparing:0,"approval-requested":1,executing:2,done:3,failed:3,rejected:3};e[n.status]>e[r.status]&&(r.status=n.status),n.input!==void 0&&(r.input=n.input)}else t.tools.set(n.childCallId,i);this.#t?.markChildToolCallId(n.childCallId),this.#t?.upsertTool({callId:e,subagentName:t.name,childCallId:n.childCallId,toolName:i.toolName,input:i.input,status:i.status})}#s(e){let t=this.#r.get(e);if(!(!t||t.status===`settled`)){t.status=`settled`;for(let[n,r]of t.steps)r.finalized||(r.finalized=!0,this.#t?.upsertStep({callId:e,subagentName:t.name,sectionKey:n,reasoning:r.reasoning,message:r.message,finalized:!0}));t.currentSectionKey=null,this.#c(e,t),this.#t?.complete({callId:e})}}#c(e,t){for(let[n,r]of t.tools)r.status===`preparing`&&(t.tools.delete(n),this.#t?.removeTool({callId:e,childCallId:n}))}#l(e,t){let n=this.#r.get(e);if(!n||!n.seenChildEvents.admit(t))return;n.status===`settled`&&(n.status=`running`,this.#t?.begin({callId:e,name:n.name}));let r=this.#t,emit=(t,i)=>{r?.upsertStep({callId:e,subagentName:n.name,sectionKey:t,reasoning:i.reasoning,message:i.message,finalized:i.finalized})},finalizeCurrent=()=>{if(n.currentSectionKey===null)return;let e=n.steps.get(n.currentSectionKey);e&&(e.finalized=!0,emit(n.currentSectionKey,e)),n.currentSectionKey=null};switch(t.type){case`reasoning.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.reasoning+=t.data.reasoningDelta,emit(e,r);break}case`reasoning.completed`:break;case`message.appended`:{let{key:e,step:r}=openCurrentSubagentSection(n);r.message+=t.data.messageDelta,emit(e,r);break}case`message.completed`:{let{key:e,step:r}=openCurrentSubagentSection(n);t.data.message!==null&&r.message.length===0&&(r.message=t.data.message),r.finalized=!0,emit(e,r),n.currentSectionKey=null;break}case`step.completed`:finalizeCurrent(),this.#c(e,n);break;case`actions.requested`:finalizeCurrent();for(let r of t.data.actions)r.kind===`tool-call`&&this.#o(e,n,{childCallId:r.callId,toolName:r.toolName,input:r.input,status:`executing`});break;case`input.requested`:finalizeCurrent();for(let r of t.data.requests)r.action.kind===`tool-call`&&this.#o(e,n,{childCallId:r.action.callId,toolName:r.action.toolName,input:r.action.input,status:`approval-requested`});break;case`action.result`:{let i=t.data.result;if(i.kind!==`tool-result`)break;let a=n.tools.get(i.callId);if(!a)break;switch(t.data.status){case`completed`:a.status=`done`,a.output=i.output;break;case`failed`:a.status=`failed`,a.errorText=this.#n(t);break;case`rejected`:a.status=`rejected`,a.errorText=this.#n(t);break}let o={callId:e,subagentName:n.name,childCallId:i.callId,toolName:a.toolName,input:a.input,status:a.status};a.output!==void 0&&(o.output=a.output),a.errorText!==void 0&&(o.errorText=a.errorText),r?.upsertTool(o);break}default:break}}};function openCurrentSubagentSection(e){e.currentSectionKey===null&&(e.currentSectionKey=e.nextSectionKey++,e.steps.set(e.currentSectionKey,{reasoning:``,message:``,finalized:!1}));let t=e.steps.get(e.currentSectionKey);if(!t)throw Error(`invariant: subagent section state missing for current key`);return{key:e.currentSectionKey,step:t}}export{SubagentPump};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDevDiagnostics}from"../diagnostics.js";import{promptCommandsFor}from"./prompt-commands.js";import{probeMcpConnection}from"./mcp-connection-status.js";import{createPromptCommandHandler}from"./prompt-command-handler.js";import{formatRemoteAuthChallengeMessage}from"./remote-auth-result.js";import{remoteHost}from"./target.js";import{EveTUIRunner}from"./runner.js";import{Client}from"#client/index.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentOidcToken,resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";import{resolveVercelDeployment}from"#setup/vercel-deployment.js";import{resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{createDevelopmentCredentialGate}from"#services/dev-client/credential-gate.js";function prepareRemoteTarget(e){return{target:e,credentials:createDevelopmentCredentialGate(e.serverUrl),resolveOidcToken:resolveDevelopmentOidcToken,resolveDeployment:t=>resolveVercelDeployment({workspaceRoot:e.workspaceRoot,host:remoteHost(e),signal:t})}}function prepareDevelopmentTarget(e){return e.kind===`local`?{kind:`local`,target:e}:{kind:`remote`,target:e,remote:prepareRemoteTarget(e)}}async function runDevelopmentTui(n){let{target:r,headers:i,initialInput:a,onBootProgress:o,lifecycle:s,withExclusiveTerminal:c,...l}=n,u=prepareDevelopmentTarget(r),{serverUrl:d}=r,f=i===void 0?{}:{headers:i},p=new Client(u.kind===`local`?resolveLocalDevelopmentClientOptions({...f,serverUrl:d,token:()=>resolveLinkedDevelopmentOidcToken(u.target.workspaceRoot)}):resolveRemoteDevelopmentClientOptions({...f,serverUrl:d,credentials:u.remote.credentials})),m={...l,
|
|
1
|
+
import{createDevDiagnostics}from"../diagnostics.js";import{promptCommandsFor}from"./prompt-commands.js";import{probeMcpConnection}from"./mcp-connection-status.js";import{createPromptCommandHandler}from"./prompt-command-handler.js";import{formatRemoteAuthChallengeMessage}from"./remote-auth-result.js";import{remoteHost}from"./target.js";import{EveTUIRunner}from"./runner.js";import{Client}from"#client/index.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentOidcToken,resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{isVercelAuthChallenge}from"#services/dev-client/vercel-auth-error.js";import{resolveVercelDeployment}from"#setup/vercel-deployment.js";import{resolveLocalDevelopmentClientOptions,resolveRemoteDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{createDevelopmentCredentialGate}from"#services/dev-client/credential-gate.js";function prepareRemoteTarget(e){return{target:e,credentials:createDevelopmentCredentialGate(e.serverUrl),resolveOidcToken:resolveDevelopmentOidcToken,resolveDeployment:t=>resolveVercelDeployment({workspaceRoot:e.workspaceRoot,host:remoteHost(e),signal:t})}}function prepareDevelopmentTarget(e){return e.kind===`local`?{kind:`local`,target:e}:{kind:`remote`,target:e,remote:prepareRemoteTarget(e)}}async function runDevelopmentTui(n){let{target:r,headers:i,initialInput:a,onBootProgress:o,lifecycle:s,withExclusiveTerminal:c,...l}=n,u=prepareDevelopmentTarget(r),{serverUrl:d}=r,f=i===void 0?{}:{headers:i},p=new Client(u.kind===`local`?resolveLocalDevelopmentClientOptions({...f,serverUrl:d,token:()=>resolveLinkedDevelopmentOidcToken(u.target.workspaceRoot)}):resolveRemoteDevelopmentClientOptions({...f,serverUrl:d,credentials:u.remote.credentials})),m={...l,client:p,serverUrl:d,promptCommandHandler:createPromptCommandHandler({target:r}),availablePromptCommands:promptCommandsFor(r.kind),formatTransportError:e=>isVercelAuthChallenge(e)?formatRemoteAuthChallengeMessage(d):toErrorMessage(e)};u.kind===`local`?(m.appRoot=u.target.workspaceRoot,m.probeMcpConnection=probeMcpConnection):m.remote=u.remote,a!==void 0&&(m.initialInput=a),o!==void 0&&(m.onBootProgress=o),s!==void 0&&(m.lifecycle=s),c!==void 0&&(m.withExclusiveTerminal=c);let h=u.kind===`local`?await createDevDiagnostics(u.target.workspaceRoot).catch(()=>void 0):void 0;h!==void 0&&(m.diagnostics=h);try{await new EveTUIRunner(m).run()}finally{await h?.close()}}export{runDevelopmentTui};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { SendTurnPayload } from "#client/types.js";
|
|
2
2
|
import type { DevelopmentTarget } from "#services/dev-client/target.js";
|
|
3
3
|
import { type InvokeResult, type InvokeResume } from "./result.js";
|
|
4
4
|
export type InvokeOperation = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{projectInvocationInputRequest}from"./result.js";import{Client,ClientError}from"#client/index.js";import{resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{formatVercelTrustedSourcesFailure,isVercelAuthChallenge,vercelTrustedSourcesErrorCode}from"#services/dev-client/vercel-auth-error.js";import{resolveLocalDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{collectTurnEvents,summarizeTurnEvents}from"#client/session-utils.js";import{resolveVerifiedRemoteDevelopmentClient}from"#setup/verified-remote-client.js";async function runInvoke(e){let{client:t,deploymentResolution:n}=await createInvokeClient(e),r=e.operation.resume
|
|
1
|
+
import{projectInvocationInputRequest}from"./result.js";import{Client,ClientError}from"#client/index.js";import{resolveLinkedDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{formatVercelTrustedSourcesFailure,isVercelAuthChallenge,vercelTrustedSourcesErrorCode}from"#services/dev-client/vercel-auth-error.js";import{resolveLocalDevelopmentClientOptions}from"#services/dev-client/client-options.js";import{collectTurnEvents,summarizeTurnEvents}from"#client/session-utils.js";import{resolveVerifiedRemoteDevelopmentClient}from"#setup/verified-remote-client.js";async function runInvoke(e){let{client:t,deploymentResolution:n}=await createInvokeClient(e),r=e.operation.resume;if(e.operation.kind===`follow`){let i=t.sessions.attach(r.session.sessionId,{streamIndex:r.session.streamIndex});return observeSafely(e,i,i.stream({signal:e.signal}),n)}let i,a;try{let n={...e.operation.payload,signal:e.signal};if(r===void 0){if(n.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let e=await t.sessions.create({...n,message:n.message});a=e.session,i=e.response}else{a=t.sessions.attach(r.session.sessionId,{streamIndex:r.session.streamIndex});let{inputResponses:e,message:o,...s}=n;i=e===void 0?await a.send(o,s):await a.respond(e,s)}}catch(e){let t=authenticationFailure(e,void 0,n);if(t!==void 0)return t;throw e}return observeSafely(e,a,i,n)}function resolveInvokeOperation(e){let t=e.prompt?.trim(),n=e.previous;if(n===void 0){if(!t)throw Error(`eve invoke requires a prompt unless --resume is provided.`);return{kind:`send`,payload:{message:t}}}if(n.status===`input-required`){if(!t)throw Error(`This invocation is waiting for an input response.`);return{kind:`send`,payload:{message:t},resume:n.resume}}if(n.status===`running`||n.status===`authorization-required`||n.status===`authentication-required`){if(t)throw Error(n.status===`running`?`A running invocation cannot accept a follow-up prompt.`:`Complete the requested authorization, then resume without a prompt.`);return{kind:`follow`,resume:n.resume}}if(n.status!==`ready`)throw Error(`A terminal ${n.status} invocation cannot be resumed.`);if(!t)throw Error(`A ready invocation requires a follow-up prompt.`);return{kind:`send`,payload:{message:t},resume:n.resume}}async function createInvokeClient(e){if(e.target.kind===`local`)return{client:new Client({...resolveLocalDevelopmentClientOptions({headers:e.headers,serverUrl:e.target.serverUrl,token:()=>resolveLinkedDevelopmentOidcToken(e.target.workspaceRoot)})})};let{deploymentResolution:n,options:i}=await resolveVerifiedRemoteDevelopmentClient({headers:e.headers,serverUrl:e.target.serverUrl,signal:e.signal,vercelScope:e.vercelScope,workspaceRoot:e.target.workspaceRoot});return{client:new Client(i),deploymentResolution:n}}async function observeSafely(e,t,n,r){try{return await observeInvocation(e.target,t,n)}catch(n){if(e.signal?.aborted===!0)return runningResult(e.target,t.state);let i=authenticationFailure(n,createResume(e.target,t.state),r);if(i!==void 0)return i;throw n}}async function observeInvocation(t,n,r){let i=summarizeTurnEvents(await collectTurnEvents(r));if(i.boundary===void 0)return runningResult(t,n.state);if(i.boundary.type===`session.failed`)return{status:`failed`,message:i.boundary.data.message};let a=createResume(t,n.state);if(i.failure?.type===`turn.failed`)return{status:`ready`,outcome:{status:`failed`,message:i.failure.data.message},resume:a};if(i.inputRequests.length>0)return{status:`input-required`,requests:i.inputRequests.map(projectInvocationInputRequest),resume:a};let o=i.pendingAuthorizations;return o.length>0?t.kind===`local`&&o.some(e=>e.webhookUrl!==void 0)?{status:`failed`,message:`Local eve invoke cannot pause for connection authorization because its temporary server must remain available for the callback. Run eve dev, then invoke its URL with --url.`}:{status:`authorization-required`,authorizations:o,resume:a}:{status:`ready`,outcome:i.message===void 0?{status:`completed`}:{status:`completed`,message:i.message},resume:a}}function runningResult(e,t){return{status:`running`,resume:createResume(e,t)}}function createResume(e,t){return{session:t,target:e.kind===`local`?{kind:`local`}:{kind:`remote`,serverUrl:e.serverUrl}}}function authenticationFailure(e,t,r){let s,c;if(r?.kind===`not-found`?s=`Vercel could not resolve this deployment in the selected scope. Retry with the owning team's slug via --scope <team-slug>, or provide an explicit Authorization header with -H.`:isVercelAuthChallenge(e)?s=`Vercel Deployment Protection rejected the available credentials. Configure Trusted Sources or set VERCEL_AUTOMATION_BYPASS_SECRET, then retry.`:e instanceof ClientError&&(c=vercelTrustedSourcesErrorCode(e.message),e.status===403&&c===`TRUSTED_SOURCES_ENVIRONMENT_MISMATCH`?s=formatVercelTrustedSourcesFailure(e.message):isEveAuthorizationError(e)&&(s=`The deployment rejected the available credentials. Confirm its eve channel authorization and that your account can access the owning project.`)),s!==void 0)return t===void 0?c===void 0?{status:`authentication-required`,message:s}:{status:`authentication-required`,code:c,message:s}:c===void 0?{status:`authentication-required`,message:s,resume:t}:{status:`authentication-required`,code:c,message:s,resume:t}}function isEveAuthorizationError(e){if(e.status!==401)return!1;try{let t=JSON.parse(e.body);return t.ok===!1&&t.code===`unauthorized`}catch{return!1}}export{resolveInvokeOperation,runInvoke};
|
|
@@ -3,7 +3,6 @@ import { type InputRequest } from "#client/index.js";
|
|
|
3
3
|
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
|
|
4
4
|
declare const invokeResumeSchema: z.ZodObject<{
|
|
5
5
|
session: z.ZodObject<{
|
|
6
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
7
6
|
sessionId: z.ZodString;
|
|
8
7
|
streamIndex: z.ZodNumber;
|
|
9
8
|
}, z.core.$strict>;
|
|
@@ -32,7 +31,6 @@ declare const invocationInputRequestSchema: z.ZodObject<{
|
|
|
32
31
|
declare const invokeResultSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
33
32
|
resume: z.ZodObject<{
|
|
34
33
|
session: z.ZodObject<{
|
|
35
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
36
34
|
sessionId: z.ZodString;
|
|
37
35
|
streamIndex: z.ZodNumber;
|
|
38
36
|
}, z.core.$strict>;
|
|
@@ -62,7 +60,6 @@ declare const invokeResultSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
62
60
|
}, z.core.$strict>>>;
|
|
63
61
|
resume: z.ZodObject<{
|
|
64
62
|
session: z.ZodObject<{
|
|
65
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
66
63
|
sessionId: z.ZodString;
|
|
67
64
|
streamIndex: z.ZodNumber;
|
|
68
65
|
}, z.core.$strict>;
|
|
@@ -83,7 +80,6 @@ declare const invokeResultSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
83
80
|
}, z.core.$strict>>>;
|
|
84
81
|
resume: z.ZodObject<{
|
|
85
82
|
session: z.ZodObject<{
|
|
86
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
87
83
|
sessionId: z.ZodString;
|
|
88
84
|
streamIndex: z.ZodNumber;
|
|
89
85
|
}, z.core.$strict>;
|
|
@@ -105,7 +101,6 @@ declare const invokeResultSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
105
101
|
}, z.core.$strict>], "status">;
|
|
106
102
|
resume: z.ZodObject<{
|
|
107
103
|
session: z.ZodObject<{
|
|
108
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
109
104
|
sessionId: z.ZodString;
|
|
110
105
|
streamIndex: z.ZodNumber;
|
|
111
106
|
}, z.core.$strict>;
|
|
@@ -125,7 +120,6 @@ declare const invokeResultSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
125
120
|
message: z.ZodString;
|
|
126
121
|
resume: z.ZodOptional<z.ZodObject<{
|
|
127
122
|
session: z.ZodObject<{
|
|
128
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
129
123
|
sessionId: z.ZodString;
|
|
130
124
|
streamIndex: z.ZodNumber;
|
|
131
125
|
}, z.core.$strict>;
|
|
@@ -216,7 +210,6 @@ export declare const invokeResultJsonSchema: {
|
|
|
216
210
|
"~standard": z.core.ZodStandardSchemaWithJSON<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
217
211
|
resume: z.ZodObject<{
|
|
218
212
|
session: z.ZodObject<{
|
|
219
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
220
213
|
sessionId: z.ZodString;
|
|
221
214
|
streamIndex: z.ZodNumber;
|
|
222
215
|
}, z.core.$strict>;
|
|
@@ -246,7 +239,6 @@ export declare const invokeResultJsonSchema: {
|
|
|
246
239
|
}, z.core.$strict>>>;
|
|
247
240
|
resume: z.ZodObject<{
|
|
248
241
|
session: z.ZodObject<{
|
|
249
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
250
242
|
sessionId: z.ZodString;
|
|
251
243
|
streamIndex: z.ZodNumber;
|
|
252
244
|
}, z.core.$strict>;
|
|
@@ -267,7 +259,6 @@ export declare const invokeResultJsonSchema: {
|
|
|
267
259
|
}, z.core.$strict>>>;
|
|
268
260
|
resume: z.ZodObject<{
|
|
269
261
|
session: z.ZodObject<{
|
|
270
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
271
262
|
sessionId: z.ZodString;
|
|
272
263
|
streamIndex: z.ZodNumber;
|
|
273
264
|
}, z.core.$strict>;
|
|
@@ -289,7 +280,6 @@ export declare const invokeResultJsonSchema: {
|
|
|
289
280
|
}, z.core.$strict>], "status">;
|
|
290
281
|
resume: z.ZodObject<{
|
|
291
282
|
session: z.ZodObject<{
|
|
292
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
293
283
|
sessionId: z.ZodString;
|
|
294
284
|
streamIndex: z.ZodNumber;
|
|
295
285
|
}, z.core.$strict>;
|
|
@@ -309,7 +299,6 @@ export declare const invokeResultJsonSchema: {
|
|
|
309
299
|
message: z.ZodString;
|
|
310
300
|
resume: z.ZodOptional<z.ZodObject<{
|
|
311
301
|
session: z.ZodObject<{
|
|
312
|
-
continuationToken: z.ZodOptional<z.ZodString>;
|
|
313
302
|
sessionId: z.ZodString;
|
|
314
303
|
streamIndex: z.ZodNumber;
|
|
315
304
|
}, z.core.$strict>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inputOptionSchema,inputRequestSchema}from"#client/index.js";import{z}from"#compiled/zod/index.js";const sessionCursorSchema=z.object({
|
|
1
|
+
import{inputOptionSchema,inputRequestSchema}from"#client/index.js";import{z}from"#compiled/zod/index.js";const sessionCursorSchema=z.object({sessionId:z.string().min(1),streamIndex:z.number().int().nonnegative()}).strict(),targetSchema=z.discriminatedUnion(`kind`,[z.object({kind:z.literal(`local`)}).strict(),z.object({kind:z.literal(`remote`),serverUrl:z.url()}).strict()]),invokeResumeSchema=z.object({session:sessionCursorSchema,target:targetSchema}).strict(),invocationInputRequestSchema=inputRequestSchema.omit({action:!0,display:!0,options:!0}).extend({options:z.array(inputOptionSchema.omit({style:!0})).optional()}),authorizationChallengeSchema=z.object({displayName:z.string().optional(),expiresAt:z.string().optional(),instructions:z.string().optional(),url:z.string().optional(),userCode:z.string().optional()}).strict(),authorizationInterruptSchema=z.object({authorization:authorizationChallengeSchema.optional(),description:z.string(),name:z.string(),webhookUrl:z.string().optional()}).strict(),turnOutcomeSchema=z.discriminatedUnion(`status`,[z.object({message:z.string().optional(),status:z.literal(`completed`)}).strict(),z.object({message:z.string(),status:z.literal(`failed`)}).strict()]),invokeResultSchema=z.discriminatedUnion(`status`,[z.object({resume:invokeResumeSchema,status:z.literal(`running`)}).strict(),z.object({requests:z.array(invocationInputRequestSchema).readonly(),resume:invokeResumeSchema,status:z.literal(`input-required`)}).strict(),z.object({authorizations:z.array(authorizationInterruptSchema).min(1).readonly(),resume:invokeResumeSchema,status:z.literal(`authorization-required`)}).strict(),z.object({outcome:turnOutcomeSchema,resume:invokeResumeSchema,status:z.literal(`ready`)}).strict(),z.object({message:z.string(),status:z.literal(`failed`)}).strict(),z.object({code:z.string().optional(),message:z.string(),resume:invokeResumeSchema.optional(),status:z.literal(`authentication-required`)}).strict()]);function projectInvocationInputRequest(e){let{allowFreeform:t,kind:n,options:r,prompt:i,requestId:a}=e;return{allowFreeform:t,kind:n,options:r?.map(({description:e,id:t,label:n})=>({description:e,id:t,label:n})),prompt:i,requestId:a}}function parseInvokeResumeInput(e){let t=invokeResultSchema.safeParse(e);if(t.success&&`resume`in t.data&&t.data.resume!==void 0)return t.data;throw Error(`Resume JSON is not a valid resumable eve invoke result.`)}const invokeResultJsonSchema={...z.toJSONSchema(invokeResultSchema,{io:`input`,target:`draft-2020-12`,unrepresentable:`any`}),$id:`https://eve.dev/schemas/invoke-result.json`,title:`eve invoke result`};export{invokeResultJsonSchema,parseInvokeResumeInput,projectInvocationInputRequest};
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* Error thrown when the eve server returns a non-successful HTTP response.
|
|
3
3
|
*/
|
|
4
4
|
export declare class ClientError extends Error {
|
|
5
|
+
/** Stable eve error code when the response body provides one. */
|
|
6
|
+
readonly code: string | undefined;
|
|
5
7
|
/**
|
|
6
8
|
* HTTP status code returned by the server.
|
|
7
9
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";var ClientError=class extends Error{status;body;headers;constructor(e,t,n){let r=t||`Server returned ${e}
|
|
1
|
+
import{isObject}from"#shared/guards.js";var ClientError=class extends Error{code;status;body;headers;constructor(e,t,n){let r=t||`Server returned ${e}.`,i;try{let e=JSON.parse(t);isObject(e)&&(typeof e.error==`string`&&(r=e.error),typeof e.code==`string`&&(i=e.code))}catch{}super(r),this.name=`ClientError`,this.code=i,this.status=e,this.body=t,this.headers=Object.freeze(Object.fromEntries(new Headers(n).entries()))}};export{ClientError};
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { AgentInfoResult, ClientOptions, HealthResult
|
|
1
|
+
import { ClientSessions } from "#client/sessions.js";
|
|
2
|
+
import type { AgentInfoResult, ClientOptions, HealthResult } from "#client/types.js";
|
|
3
3
|
/**
|
|
4
4
|
* HTTP client for talking to a deployed eve agent.
|
|
5
5
|
*
|
|
6
|
-
* A single client is bound to one host and auth configuration.
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* A single client is bound to one host and auth configuration. Its
|
|
7
|
+
* `sessions` collection can create or attach many independent fixed session
|
|
8
|
+
* handles.
|
|
9
9
|
*/
|
|
10
10
|
export declare class Client {
|
|
11
11
|
#private;
|
|
12
|
+
/** Explicit create/attach surface for ID-addressed sessions. */
|
|
13
|
+
readonly sessions: ClientSessions;
|
|
12
14
|
constructor(options: ClientOptions);
|
|
13
15
|
/**
|
|
14
16
|
* Checks the health of the eve agent server.
|
|
@@ -38,13 +40,4 @@ export declare class Client {
|
|
|
38
40
|
* auth/header cascade used by {@link health}, {@link info}, and sessions.
|
|
39
41
|
*/
|
|
40
42
|
fetch(path: string, init?: RequestInit): Promise<Response>;
|
|
41
|
-
/**
|
|
42
|
-
* Creates a {@link ClientSession} handle for one conversation.
|
|
43
|
-
*
|
|
44
|
-
* - **No arguments**: starts a fresh conversation. The first
|
|
45
|
-
* `session.send()` call creates the run on the server.
|
|
46
|
-
* - **{@link SessionState}**: resumes a previously serialized session.
|
|
47
|
-
* - **string**: shorthand for resuming with a continuation token alone.
|
|
48
|
-
*/
|
|
49
|
-
session(state?: SessionState | string): ClientSession;
|
|
50
43
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH}from"#protocol/routes.js";import{encodeBasicCredentials}from"#internal/http/basic-auth.js";import{
|
|
1
|
+
import{EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH}from"#protocol/routes.js";import{encodeBasicCredentials}from"#internal/http/basic-auth.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{AgentInfoResultSchema}from"#client/agent-info-schema.js";import{ClientError}from"#client/client-error.js";import{ClientSessions}from"#client/sessions.js";import{createClientUrl}from"#client/url.js";import{VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER}from"#client/types.js";var Client=class{#e;#t;#n;#r;sessions;constructor(e){this.#n=e.host,this.#e=e.auth,this.#t=e.headers,this.#r=e.redirect,this.sessions=new ClientSessions({host:this.#n,redirect:this.#r,resolveHeaders:e=>this.#i(e)})}async health(){let t=createClientUrl(this.#n,EVE_HEALTH_ROUTE_PATH),n=await this.#i(),r=await fetch(t,withRedirectPolicy({headers:n},this.#r));if(!r.ok){let e=await r.text();throw new ClientError(r.status,e,r.headers)}return await r.json()}async info(){let e=await this.fetch(EVE_INFO_ROUTE_PATH);if(!e.ok){let t=await e.text();throw new ClientError(e.status,t,e.headers)}let n;try{n=await e.json()}catch{throw new AgentInfoResponseError}let i=AgentInfoResultSchema.safeParse(n);if(!i.success)throw new AgentInfoResponseError(i.error.issues.slice(0,5).map(e=>{let t=e.path.join(`.`);return t.length===0?e.message:`${t}: ${e.message}`}));return i.data}async fetch(e,t={}){let n=createClientUrl(this.#n,e),r=await this.#i(headersInitToRecord(t.headers));return await fetch(n,withRedirectPolicy({...t,headers:r},this.#r))}async#i(e){let t=new Headers,[n,r]=await Promise.all([resolveHeadersValue(this.#t),this.#a()]);for(let[e,r]of Object.entries(n))t.set(e,r);for(let[e,n]of Object.entries(r))t.set(e,n);if(e)for(let[n,r]of Object.entries(e))t.set(n,r);return t}async#a(){let e=this.#e;if(!e)return{};if(`vercelOidc`in e){let t=(await resolveTokenValue(e.vercelOidc.token)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`,[VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER]:t}}if(`bearer`in e){let t=(await resolveTokenValue(e.bearer)).trim();return t.length===0?{}:{authorization:`Bearer ${t}`}}if(`basic`in e){let t=await resolveTokenValue(e.basic.password);return{authorization:`Basic ${encodeBasicCredentials(e.basic.username,t)}`}}return{}}};async function resolveTokenValue(e){return typeof e==`function`?e():e}async function resolveHeadersValue(e){return e===void 0?{}:typeof e==`function`?await e():e}function headersInitToRecord(e){return e===void 0?{}:Object.fromEntries(new Headers(e).entries())}function withRedirectPolicy(e,t){return t===void 0?e:{...e,redirect:t}}export{Client};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { EveAgentReducer } from "#client/reducer.js";
|
|
2
2
|
import type { ClientSession } from "#client/session.js";
|
|
3
3
|
import type { MessageStreamEvent } from "#protocol/message.js";
|
|
4
|
-
import type { ClientAuth, HeadersValue, SendTurnPayload,
|
|
4
|
+
import type { ClientAuth, HeadersValue, SendTurnPayload, ClientSessionState } from "#client/types.js";
|
|
5
5
|
/**
|
|
6
6
|
* Lifecycle state of an {@link EveAgentStore}: `ready` (idle), `submitted`
|
|
7
7
|
* (turn sent, awaiting the first event), `streaming` (events arriving), and
|
|
@@ -25,7 +25,7 @@ export interface EveAgentStoreSnapshot<TData> {
|
|
|
25
25
|
readonly data: TData;
|
|
26
26
|
readonly error: Error | undefined;
|
|
27
27
|
readonly events: readonly MessageStreamEvent[];
|
|
28
|
-
readonly session:
|
|
28
|
+
readonly session: ClientSessionState | undefined;
|
|
29
29
|
readonly status: EveAgentStoreStatus;
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
@@ -39,7 +39,7 @@ export interface EveAgentStoreCallbacks<TData> {
|
|
|
39
39
|
readonly onError?: (error: Error) => void;
|
|
40
40
|
readonly onEvent?: (event: MessageStreamEvent) => void;
|
|
41
41
|
readonly onFinish?: (snapshot: EveAgentStoreSnapshot<TData>) => void;
|
|
42
|
-
readonly onSessionChange?: (session:
|
|
42
|
+
readonly onSessionChange?: (session: ClientSessionState | undefined) => void;
|
|
43
43
|
readonly prepareSend?: PrepareSend;
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
@@ -62,7 +62,7 @@ export interface EveAgentStoreInit<TData> {
|
|
|
62
62
|
readonly host?: string;
|
|
63
63
|
/** Ordered prefix of the session stream used to rehydrate projected state. */
|
|
64
64
|
readonly initialEvents?: readonly MessageStreamEvent[];
|
|
65
|
-
readonly initialSession?:
|
|
65
|
+
readonly initialSession?: ClientSessionState;
|
|
66
66
|
readonly optimistic?: boolean;
|
|
67
67
|
readonly reducer: EveAgentReducer<TData>;
|
|
68
68
|
readonly session?: ClientSession;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{Client}from"#client/client.js";var EveAgentStore=class{#e;#t;#n;#r=new Set;#
|
|
1
|
+
import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{Client}from"#client/client.js";var EveAgentStore=class{#e;#t;#n;#r;#i=new Set;#a=createEventDeduper();#o;#s={};#c;#l;#u;#d=0;#f;#p;#m;#h;#g=`ready`;constructor(e){this.#t=e.session!==void 0,this.#e=this.#t?void 0:new Client({auth:e.auth,headers:e.headers,host:e.host??``});let t=[];for(let n of e.initialEvents??[])this.#a.admit(n)&&t.push(n);this.#u=t,this.#p=[...this.#u],this.#n=e.optimistic??!0,this.#r=e.reducer,this.#m=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#c=this.#k(this.#p),this.#h=this.#A()}get snapshot(){return this.#h}setCallbacks(e){this.#s=e}subscribe(e){return this.#i.add(e),()=>{this.#i.delete(e)}}async send(t){if(this.#g===`streaming`||this.#g===`submitted`)throw Error(`eve session is already processing a turn.`);let n=this.#y(),r=new AbortController;this.#o=r,this.#l=void 0,this.#g=`submitted`,this.#j();try{let e=await this.#s.prepareSend?.(t)??t;if(assertExclusiveTurnInput(e),!this.#x(n))return;this.#S(e),this.#C(e),this.#j();let i={...e,signal:createAbortSignal(e.signal,r.signal)},a=await this.#v(i),o=!1;for await(let e of a){if(!this.#x(n))return;o||(o=!0,this.#g=`streaming`),this.#a.admit(e)&&(this.#u=[...this.#u,e],this.#w(e),this.#s.onEvent?.(e),this.#T(e),this.#j())}if(!this.#x(n))return;this.#g=this.#l===void 0?`ready`:`error`}catch(t){if(!this.#x(n))return;isAbortError(t)?(this.#g=`ready`,this.#E(toError(t))):(this.#l=toError(t),this.#g=`error`,this.#E(this.#l),this.#s.onError?.(this.#l))}finally{this.#x(n)&&(this.#o=void 0,this.#s.onSessionChange?.(this.#m?.state),this.#j(),this.#s.onFinish?.(this.#h))}}stop(){this.#o?.abort()}reset(){this.#b(),this.stop(),this.#o=void 0,this.#t||(this.#m=void 0),this.#u=[],this.#a=createEventDeduper(),this.#f=void 0,this.#p=[],this.#c=this.#r.initial(),this.#l=void 0,this.#g=`ready`,this.#s.onSessionChange?.(this.#m?.state),this.#j()}async#_(e){if(this.#e===void 0)throw Error(`An external eve session is required before sending.`);if(e.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let t=await this.#e.sessions.create({...e,message:e.message});return this.#m=t.session,this.#s.onSessionChange?.(t.session.state),this.#j(),t.response}async#v(e){if(this.#m===void 0)return await this.#_(e);if(e.inputResponses===void 0){let{message:t,...n}=e;return await this.#m.send(t,n)}let{inputResponses:t,...n}=e;return await this.#m.respond(t,n)}#y(){return this.#d+=1,this.#d}#b(){this.#d+=1}#x(e){return this.#d===e}#S(e){if(!this.#n||e.message===void 0)return;let t=createSubmissionId(),n={createdAt:Date.now(),id:t,message:summarizeUserContent(e.message)};this.#f=n,this.#D({data:{createdAt:n.createdAt,message:n.message,submissionId:n.id},type:`client.message.submitted`})}#C(e){e.inputResponses===void 0||e.inputResponses.length===0||this.#D({data:{createdAt:Date.now(),responses:e.inputResponses},type:`client.input.responded`})}#w(e){if(e.type===`message.received`&&this.#f!==void 0){let t=this.#f.id;this.#f=void 0,this.#O(e=>e.type===`client.message.submitted`&&e.data.submissionId===t,e);return}this.#D(e)}#T(e){let t=toTerminalStreamFailureError(e);t!==void 0&&(this.#g=`error`,this.#E(t),this.#l===void 0&&(this.#l=t,this.#s.onError?.(t)))}#E(e){let t=this.#f;t!==void 0&&(this.#f=void 0,this.#O(e=>e.type===`client.message.submitted`&&e.data.submissionId===t.id,{data:{createdAt:t.createdAt,error:{message:e.message},message:t.message,submissionId:t.id},type:`client.message.failed`}))}#D(e){this.#p=[...this.#p,e],this.#c=this.#r.reduce(this.#c,e)}#O(e,t){let n=!1;this.#p=this.#p.map(r=>!n&&e(r)?(n=!0,t):r),n||(this.#p=[...this.#p,t]),this.#c=this.#k(this.#p)}#k(e){let t=this.#r.initial();for(let n of e)t=this.#r.reduce(t,n);return t}#A(){return{data:this.#c,error:this.#l,events:this.#u,session:this.#m?.state,status:this.#g}}#j(){this.#h=this.#A();for(let e of this.#i)e()}};function assertExclusiveTurnInput(e){if(e.message!==void 0==(e.inputResponses!==void 0))throw Error(`A turn requires exactly one of message or inputResponses.`)}let submissionSequence=0;function createSubmissionId(){let e=globalThis.crypto?.randomUUID;return e===void 0?(submissionSequence+=1,`submission_${submissionSequence.toString()}`):e.call(globalThis.crypto)}function createAbortSignal(e,t){return e?AbortSignal.any([e,t]):t}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e){if(n.type===`text`){t.push(n.text);continue}n.type===`file`&&t.push(n.filename?`[file: ${n.filename}]`:`[file]`)}return t.join(`
|
|
2
2
|
`)}function isAbortError(e){return e instanceof Error&&e.name===`AbortError`}function toTerminalStreamFailureError(e){if(e.type!==`session.failed`)return;let t=Error(e.data.message);return t.name=e.data.code,t}export{EveAgentStore};
|
|
@@ -6,8 +6,9 @@ export { defaultMessageReducer } from "#client/message-reducer.js";
|
|
|
6
6
|
export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-parts.js";
|
|
7
7
|
export { MessageResponse } from "#client/message-response.js";
|
|
8
8
|
export { ClientSession } from "#client/session.js";
|
|
9
|
+
export { ClientSessions, type CreatedClientSession } from "#client/sessions.js";
|
|
9
10
|
export type { EveAgentStoreCallbacks, EveAgentStoreInit, EveAgentStoreSnapshot, EveAgentStoreStatus, PrepareSend, } from "#client/eve-agent-store.js";
|
|
10
|
-
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, CancelSessionResult, ClearResult, CompactResult, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, ResetResult, ResolvedStreamReconnectPolicy, SendTurnInput,
|
|
11
|
+
export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, CancelSessionResult, ClearResult, CompactResult, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, RespondTurnOptions, ResetResult, ResolvedStreamReconnectPolicy, SendTurnInput, SendTurnOptions, SessionSnapshot, ClientSessionState, StreamOptions, StreamReconnectPolicy, StreamReconnectRetryPolicy, TokenValue, } from "#client/types.js";
|
|
11
12
|
export type { EveAgentReducer, EveAgentReducerEvent, ClientInputRespondedEvent, ClientMessageFailedEvent, ClientMessageSubmittedEvent, } from "#client/reducer.js";
|
|
12
13
|
export type { EveAuthorizationChallenge, EveAuthorizationOutcome, EveAuthorizationPart, EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer.js";
|
|
13
14
|
export type { ActionPartialStreamEvent, ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, AuthorizationOutcome, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, MessageStreamEventMeta, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedPart, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, MessageStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCancelledStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
|
package/dist/src/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{ClientError}from"#client/client-error.js";import{
|
|
1
|
+
import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{ClientError}from"#client/client-error.js";import{ClientSessions}from"#client/sessions.js";import{Client}from"#client/client.js";import{EveAgentStore}from"#client/eve-agent-store.js";import{defaultMessageReducer}from"#client/message-reducer.js";import{createDataUrlFilePart,createTextWithFileContent}from"#client/file-parts.js";import{MessageResponse}from"#client/message-response.js";import{ClientSession}from"#client/session.js";import{inputOptionSchema,inputRequestKindSchema,inputRequestSchema,inputResponseSchema,isInputRequest,isInputResponse}from"#runtime/input/types.js";import{resolveTextToResponse,resolveTextToResponses}from"#channel/resolve-text.js";export{AgentInfoResponseError,Client,ClientError,ClientSession,ClientSessions,EveAgentStore,MessageResponse,createDataUrlFilePart,createTextWithFileContent,defaultMessageReducer,inputOptionSchema,inputRequestKindSchema,inputRequestSchema,inputResponseSchema,isCurrentTurnBoundaryEvent,isInputRequest,isInputResponse,isTurnFailureEvent,resolveTextToResponse,resolveTextToResponses};
|
|
@@ -4,23 +4,18 @@ import type { MessageResult } from "#client/types.js";
|
|
|
4
4
|
* Internal configuration passed to construct a {@link MessageResponse}.
|
|
5
5
|
*/
|
|
6
6
|
interface MessageResponseInput {
|
|
7
|
-
readonly continuationToken?: string;
|
|
8
7
|
readonly createStream: () => AsyncGenerator<MessageStreamEvent>;
|
|
9
8
|
readonly sessionId: string;
|
|
10
9
|
}
|
|
11
10
|
/**
|
|
12
11
|
* The response from {@link ClientSession.send}.
|
|
13
12
|
*
|
|
14
|
-
* Like `fetch()`, the response exposes
|
|
15
|
-
*
|
|
13
|
+
* Like `fetch()`, the response exposes its session ID as soon as the POST
|
|
14
|
+
* completes. Collect the event stream via
|
|
16
15
|
* {@link result} or iterate it with `for await...of`.
|
|
17
16
|
*/
|
|
18
17
|
export declare class MessageResponse<TOutput = unknown> implements AsyncIterable<MessageStreamEvent> {
|
|
19
18
|
#private;
|
|
20
|
-
/**
|
|
21
|
-
* Continuation token returned by the server for follow-up messages.
|
|
22
|
-
*/
|
|
23
|
-
readonly continuationToken: string | undefined;
|
|
24
19
|
/**
|
|
25
20
|
* Session ID assigned by the server.
|
|
26
21
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{summarizeTurnEvents}from"#client/session-utils.js";import{extractCompletedResult}from"#client/output-schema.js";var MessageResponse=class{
|
|
1
|
+
import{summarizeTurnEvents}from"#client/session-utils.js";import{extractCompletedResult}from"#client/output-schema.js";var MessageResponse=class{sessionId;#e=!1;#t;constructor(e){this.sessionId=e.sessionId,this.#t=e.createStream}async result(){let t=[];for await(let e of this)t.push(e);let n=summarizeTurnEvents(t);return{data:extractCompletedResult(t),events:t,inputRequests:n.inputRequests,message:n.message,sessionId:this.sessionId,status:n.status}}[Symbol.asyncIterator](){if(this.#e)throw Error(`MessageResponse has already been consumed.`);return this.#e=!0,this.#t()}};export{MessageResponse};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createEveSessionStreamRoutePath}from"#protocol/routes.js";import{EVE_STREAM_TAIL_INDEX_HEADER}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{isStreamDisconnectError,readNdjsonStream}from"#client/ndjson.js";const DEFAULT_STREAM_RECONNECT_POLICY={retryableErrorStatuses:new Set([404,409,425,500,502,503,504]),streamIdleReconnectPolicy:{baseDelayMs:250,maxAttempts:5,maxDelayMs:4e3},streamOpenReconnectPolicy:{baseDelayMs:250,maxAttempts:12,maxDelayMs:5e3}},NO_STREAM_RECONNECT_POLICY={...DEFAULT_STREAM_RECONNECT_POLICY,streamIdleReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy,maxAttempts:0},streamOpenReconnectPolicy:{...DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy,maxAttempts:1}};function resolveRetryPolicy(e,t){return{...t,...e}}function resolveStreamReconnectPolicy(e){if(e&&`reconnect`in e&&e.reconnect===!1)return NO_STREAM_RECONNECT_POLICY;let t=e;return{retryableErrorStatuses:t?.retryableErrorStatuses?new Set(t.retryableErrorStatuses):DEFAULT_STREAM_RECONNECT_POLICY.retryableErrorStatuses,streamIdleReconnectPolicy:resolveRetryPolicy(t?.streamIdleReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamIdleReconnectPolicy),streamOpenReconnectPolicy:resolveRetryPolicy(t?.streamOpenReconnectPolicy,DEFAULT_STREAM_RECONNECT_POLICY.streamOpenReconnectPolicy)}}async function*followStreamIterable(e){if(e.follow===!1&&e.startIndex<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);let n=resolveStreamReconnectPolicy(e.streamReconnectPolicy),r=n.streamIdleReconnectPolicy,a=e.startIndex,o=r.baseDelayMs,s=0,c=!0,l;for(;;){let u;try{u=await openStreamBody({...e,retryPolicy:n,startIndex:a,requestTailIndex:e.follow===!1&&l===void 0})}catch(t){if(e.signal?.aborted)return;throw t}if(e.follow===!1&&l===void 0&&(l=u.tailIndex,l===void 0))throw await u.body.cancel().catch(()=>{}),Error(`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. The agent may be running an older eve version.`);if(l!==void 0&&a>l){await u.body.cancel().catch(()=>{});return}let d=!1;try{for await(let e of readNdjsonStream(u.body))if(a+=1,d=!0,o=r.baseDelayMs,s=0,yield e,l!==void 0&&a>l)return}catch(e){if(!isStreamDisconnectError(e))throw e}if(e.signal?.aborted||e.startIndex<0||r.maxAttempts===0||!d&&!c&&(s+=1)>=r.maxAttempts||(c=!1,await sleep(o,e.signal),e.signal?.aborted))return;o=Math.min(o*2,r.maxDelayMs)}}async function openStreamBody(t){let i=t.retryPolicy??DEFAULT_STREAM_RECONNECT_POLICY,o=i.streamOpenReconnectPolicy,s,c,l,u=o.baseDelayMs,d={};t.startIndex!==0&&(d.startIndex=String(t.startIndex)),t.requestTailIndex===!0&&(d.includeTailIndex=`1`);for(let a=0;a<o.maxAttempts;a+=1){let f=createClientUrl(t.host,createEveSessionStreamRoutePath(t.sessionId),Object.keys(d).length>0?d:void 0),p=await t.resolveHeaders(),m;try{m=await fetch(f,{cache:`no-store`,headers:p,redirect:t.redirect,signal:t.signal??null})}catch(e){if(t.signal?.aborted||!isStreamDisconnectError(e)||a===o.maxAttempts-1)throw e;await sleep(u,t.signal),u=Math.min(u*2,o.maxDelayMs);continue}if(m.ok){if(!m.body)throw new ClientError(m.status,`Response body is null.`,m.headers);return{body:m.body,tailIndex:parseTailIndexHeader(m.headers)}}if(s=m.status,c=await m.text(),l=m.headers,!i.retryableErrorStatuses.has(m.status))throw new ClientError(m.status,c,m.headers);a<o.maxAttempts-1&&(await sleep(u,t.signal),u=Math.min(u*2,o.maxDelayMs))}throw new ClientError(s??0,c??`Failed to open message stream.`,l)}function parseTailIndexHeader(e){let n=e.get(EVE_STREAM_TAIL_INDEX_HEADER);if(n===null||!/^-?\d+$/.test(n))return;let r=Number(n);return Number.isSafeInteger(r)?r:void 0}async function sleep(e,t){t?.aborted||await new Promise(n=>{let onAbort=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e);t?.addEventListener(`abort`,onAbort,{once:!0})})}export{followStreamIterable,openStreamBody};
|