eve 0.29.1 → 0.29.3
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 +30 -0
- package/dist/src/channel/types.d.ts +15 -0
- package/dist/src/cli/commands/integration-setup.d.ts +3 -7
- package/dist/src/cli/commands/integration-setup.js +1 -1
- package/dist/src/cli/commands/registry.d.ts +1 -0
- package/dist/src/cli/commands/registry.js +1 -1
- package/dist/src/cli/commands/trace.d.ts +7 -24
- package/dist/src/cli/commands/trace.js +7 -5
- package/dist/src/cli/dev/tui/blocks.js +1 -1
- package/dist/src/cli/dev/tui/clipboard.d.ts +17 -0
- package/dist/src/cli/dev/tui/clipboard.js +1 -0
- package/dist/src/cli/dev/tui/command-typeahead.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +3 -0
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/remote-auth.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +6 -0
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/stream-format.d.ts +8 -0
- package/dist/src/cli/dev/tui/stream-format.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.d.ts +3 -0
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/cli/dev/tui/test/mock-terminal.js +3 -3
- package/dist/src/cli/dev/tui/traces/trace-content.d.ts +28 -0
- package/dist/src/cli/dev/tui/traces/trace-content.js +2 -0
- package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +58 -0
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +2 -0
- package/dist/src/cli/dev/tui/traces/trace-store.d.ts +27 -0
- package/dist/src/cli/dev/tui/traces/trace-store.js +1 -0
- package/dist/src/cli/dev/tui/traces/trace-view.d.ts +48 -0
- package/dist/src/cli/dev/tui/traces/trace-view.js +2 -0
- package/dist/src/cli/dev/tui/traces/trace-viewer-session.d.ts +41 -0
- package/dist/src/cli/dev/tui/traces/trace-viewer-session.js +1 -0
- package/dist/src/cli/dev/tui/traces/trace-viewer-state.d.ts +110 -0
- package/dist/src/cli/dev/tui/traces/trace-viewer-state.js +1 -0
- package/dist/src/cli/ui/alt-screen.d.ts +42 -0
- package/dist/src/cli/ui/alt-screen.js +1 -0
- package/dist/src/cli/ui/terminal-text.d.ts +4 -0
- package/dist/src/cli/ui/terminal-text.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/LICENSE +21 -0
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/_spectrum-core.d.ts +3 -0
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/_spectrum-imessage.d.ts +2 -0
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.d.ts +496 -0
- package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.js +137 -0
- package/dist/src/compiled/@vercel/sandbox/index.js +13 -107
- package/dist/src/compiled/_chunks/node/auth-BS3UoyvT.js +2 -0
- package/dist/src/compiled/_chunks/node/compat-Dm2n85Mx.js +1 -0
- package/dist/src/compiled/_chunks/node/schemas-DtQwuPdM.js +65 -0
- package/dist/src/compiled/_chunks/node/undici-DWL_MYmT.js +95 -0
- package/dist/src/compiled/_chunks/node/version-Cztrk7z6.js +1 -0
- package/dist/src/compiled/shadcn-registry/index.js +461 -893
- package/dist/src/context/keys.d.ts +3 -1
- package/dist/src/context/keys.js +1 -1
- package/dist/src/evals/runner/execute-task.js +1 -1
- package/dist/src/evals/runner/run-evals.js +1 -1
- package/dist/src/execution/delegated-parent-notification.js +1 -1
- package/dist/src/execution/delegated-parent-result.js +1 -1
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/sandbox/glob-tool.js +3 -3
- package/dist/src/execution/sandbox/grep-tool.js +1 -1
- package/dist/src/execution/sandbox/read-file-tool.js +3 -3
- package/dist/src/execution/sandbox/require-sandbox.d.ts +3 -3
- package/dist/src/execution/sandbox/require-sandbox.js +1 -1
- package/dist/src/execution/sandbox/write-file-tool.js +1 -1
- package/dist/src/execution/subagent-adapter-state.d.ts +39 -0
- package/dist/src/execution/subagent-adapter-state.js +1 -0
- package/dist/src/execution/subagent-adapter.d.ts +0 -34
- package/dist/src/execution/subagent-adapter.js +1 -1
- package/dist/src/execution/subagent-tool.d.ts +2 -1
- package/dist/src/execution/subagent-tool.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/instrumentation-lifecycle.d.ts +18 -0
- package/dist/src/harness/instrumentation-native-events.d.ts +3 -1
- package/dist/src/harness/instrumentation-native-events.js +1 -1
- package/dist/src/harness/parent-lineage.d.ts +11 -0
- package/dist/src/harness/parent-lineage.js +1 -0
- package/dist/src/harness/runtime-actions.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/local-tracing-runtime-plugin.js +1 -1
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +7 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
- package/dist/src/public/channels/photon/inboundContent.d.ts +4 -0
- package/dist/src/public/channels/photon/inboundContent.js +1 -0
- package/dist/src/public/channels/photon/index.d.ts +1 -0
- package/dist/src/public/channels/photon/index.js +1 -0
- package/dist/src/public/channels/photon/photonIMessageChannel.d.ts +54 -0
- package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -0
- package/dist/src/runtime/channels/registry.js +1 -1
- package/dist/src/runtime/framework-tools/glob.js +1 -1
- package/dist/src/runtime/framework-tools/grep.js +1 -1
- package/dist/src/runtime/framework-tools/read-file.js +1 -1
- package/dist/src/runtime/framework-tools/write-file.js +1 -1
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/connect-provisioning.d.ts +32 -0
- package/dist/src/setup/connect-provisioning.js +1 -0
- package/dist/src/setup/flows/login.js +1 -1
- package/dist/src/setup/flows/registry.js +1 -1
- package/dist/src/setup/integrations/photon/connect.d.ts +40 -0
- package/dist/src/setup/integrations/photon/connect.js +1 -0
- package/dist/src/setup/integrations/photon/management.d.ts +34 -0
- package/dist/src/setup/integrations/photon/management.js +1 -0
- package/dist/src/setup/integrations/photon/setup-flow.d.ts +39 -0
- package/dist/src/setup/integrations/photon/setup-flow.js +20 -0
- package/dist/src/setup/integrations/photon/setup.d.ts +3 -0
- package/dist/src/setup/integrations/photon/setup.js +1 -0
- package/dist/src/setup/integrations/registry.d.ts +6 -0
- package/dist/src/setup/integrations/registry.js +1 -0
- package/dist/src/setup/integrations/runner.d.ts +25 -0
- package/dist/src/setup/integrations/runner.js +1 -0
- package/dist/src/setup/integrations/{channels → shared}/environment.d.ts +3 -3
- package/dist/src/setup/integrations/shared/environment.js +1 -0
- package/dist/src/setup/integrations/shared/scaffold.d.ts +19 -0
- package/dist/src/setup/integrations/shared/scaffold.js +1 -0
- package/dist/src/setup/integrations/{channels → shared}/ui.d.ts +3 -3
- package/dist/src/setup/integrations/shared/ui.js +2 -0
- package/dist/src/setup/integrations/slack/setup.d.ts +16 -0
- package/dist/src/setup/integrations/slack/setup.js +1 -0
- package/dist/src/setup/integrations/types.d.ts +26 -0
- package/dist/src/setup/integrations/web/setup.d.ts +3 -0
- package/dist/src/setup/integrations/web/setup.js +1 -0
- package/dist/src/setup/primitives/run-vercel.d.ts +2 -7
- package/dist/src/setup/primitives/run-vercel.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/update/channels.js +1 -1
- package/dist/src/setup/scaffold/update/connections.js +1 -1
- package/dist/src/setup/slack-connect-lifecycle.d.ts +2 -8
- package/dist/src/setup/slack-connect-lifecycle.js +1 -1
- package/dist/src/setup/state.d.ts +0 -12
- package/dist/src/setup/state.js +1 -1
- package/dist/src/shared/skill-paths.d.ts +10 -0
- package/dist/src/shared/skill-paths.js +2 -2
- package/dist/src/tracing/agent-otel-content.d.ts +32 -0
- package/dist/src/tracing/agent-otel-content.js +4 -0
- package/dist/src/{harness → tracing}/agent-otel-provider.d.ts +10 -1
- package/dist/src/tracing/agent-otel-provider.js +2 -0
- package/dist/src/{harness → tracing}/agent-trace-context-store.d.ts +8 -1
- package/dist/src/tracing/agent-trace-context-store.js +1 -0
- package/dist/src/{harness → tracing}/agent-trace-span-processor.d.ts +5 -1
- package/dist/src/tracing/agent-trace-span-processor.js +1 -0
- package/dist/src/tracing/local-instrumentation-runtime.js +1 -0
- package/dist/src/tracing/local-trace-reader.d.ts +57 -0
- package/dist/src/tracing/local-trace-reader.js +1 -0
- package/dist/src/{harness → tracing}/local-trace-retention.js +1 -1
- package/dist/src/{harness → tracing}/local-trace-span-processor.js +1 -1
- package/docs/channels/chat-sdk.mdx +18 -1
- package/docs/channels/meta.json +1 -0
- package/docs/channels/overview.mdx +1 -1
- package/docs/channels/photon.mdx +78 -0
- package/docs/concepts/default-harness.md +2 -0
- package/docs/guides/dev-tui.md +20 -1
- package/docs/guides/instrumentation.md +8 -7
- package/docs/reference/cli.md +9 -1
- package/docs/sandbox.mdx +1 -1
- package/package.json +7 -1
- package/dist/src/compiled/_chunks/node/auth-DMsLOrh7.js +0 -2
- package/dist/src/compiled/_chunks/node/version-BQBAL95V.js +0 -64
- package/dist/src/harness/agent-otel-provider.js +0 -1
- package/dist/src/harness/agent-trace-context-store.js +0 -1
- package/dist/src/harness/agent-trace-span-processor.js +0 -1
- package/dist/src/harness/local-instrumentation-runtime.js +0 -1
- package/dist/src/setup/integrations/channels/environment.js +0 -1
- package/dist/src/setup/integrations/channels/index.d.ts +0 -7
- package/dist/src/setup/integrations/channels/index.js +0 -1
- package/dist/src/setup/integrations/channels/runner.d.ts +0 -7
- package/dist/src/setup/integrations/channels/runner.js +0 -1
- package/dist/src/setup/integrations/channels/setup.d.ts +0 -130
- package/dist/src/setup/integrations/channels/setup.js +0 -2
- package/dist/src/setup/integrations/channels/slack.d.ts +0 -3
- package/dist/src/setup/integrations/channels/slack.js +0 -1
- package/dist/src/setup/integrations/channels/types.d.ts +0 -49
- package/dist/src/setup/integrations/channels/ui.js +0 -2
- package/dist/src/setup/integrations/channels/web.d.ts +0 -3
- package/dist/src/setup/integrations/channels/web.js +0 -1
- /package/dist/src/setup/integrations/{channels/types.js → types.js} +0 -0
- /package/dist/src/{harness → tracing}/local-instrumentation-runtime.d.ts +0 -0
- /package/dist/src/{harness → tracing}/local-trace-retention.d.ts +0 -0
- /package/dist/src/{harness → tracing}/local-trace-span-processor.d.ts +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.29.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 22bfa02: Add guided Photon setup through `eve add channel/photon-imessage`, including project creation, phone registration, Vercel Connect or portable credentials, and channel scaffolding.
|
|
8
|
+
- 0c0de19: Add an opt-in experimental steering policy to Chat SDK sends that cancels an active turn before delivering its replacement message.
|
|
9
|
+
- b00a79d: Add `photonIMessageChannel`, a first-class Photon iMessage channel with lazy credentials, Vercel OIDC webhook verification, and automatic eve session routing.
|
|
10
|
+
- 495e93b: Resolve leading `$HOME` paths in the built-in `read_file`, `write_file`, `glob`, and `grep` tools so agents can directly access packaged skill references advertised in their prompt.
|
|
11
|
+
- bf01952: Local trace spans now capture model and tool payloads: the system prompt, prompt messages, and response text/reasoning/tool calls on model spans, and call arguments/results on tool spans, each capped at 32 KB with provider transport metadata stripped. Set `EVE_TRACES_CONTENT=off` to keep payloads out of the spool.
|
|
12
|
+
- 680db59: Provider-executed tool calls (like a gateway's `web_search`) now show up in local traces: their calls and results are captured on the model span and the `/traces` viewer renders them as tool cards, with oversized outputs truncated to stay valid JSON.
|
|
13
|
+
- 7ab6d8a: Terminal text wrapping in the dev TUI is now linear-time, so views rendering large single-line payloads (long tool results, big JSON) no longer stall on every repaint.
|
|
14
|
+
- 52cee9c: Consolidate the three Vercel CLI subprocess runners onto one shared lifecycle. A `vercel` lookup killed by a signal (for example Ctrl-C during setup) now reports a cancellation failure instead of resolving as a success with truncated output.
|
|
15
|
+
- 7703448: The local trace spool reader behind `eve traces` moved into a shared internal module; command behavior is unchanged.
|
|
16
|
+
- 2d87acb: Subagent turn spans now record the dispatch that created them —
|
|
17
|
+
`agent.parent.session.id`, `agent.parent.turn.id`, `agent.parent.call_id`, and
|
|
18
|
+
`agent.subagent.name` — so a parent turn that fans out to several children can
|
|
19
|
+
be attributed to the exact tool call behind each one.
|
|
20
|
+
- 3c846bc: The `/traces` viewer supports drag-to-select: dragging with the mouse highlights text and releasing copies it to the clipboard (OSC 52 with tmux passthrough, plus the platform clipboard command) with a confirmation toast. Clicks now act on release so drags never toggle cards, and Esc cancels an in-flight selection.
|
|
21
|
+
- 3645c6e: The `/traces` viewer frame breathes: padding rows around the title and above the footer hints, the copy toast floats top-right as a small surface with a left edge bar, and the scroll wheel scrolls the attributes drawer when the pointer is over it.
|
|
22
|
+
- 8858403: The local tracing subsystem (spool writer/reader, retention, the zero-config local OTel runtime, and agent span capture) moved from `src/harness` into its own `src/tracing` module; no behavior change.
|
|
23
|
+
- 9adb455: Adds a `/traces` command to the dev TUI: a full-screen live viewer over the local trace spool that re-tells each trace as a chat-style conversation — system prompt, user and assistant messages, and tool calls render as expandable cards (arrow keys or mouse click to expand/collapse), with a right-side metadata drawer. Subagent turns are badged with their dispatch lineage (`subagent:<name>`), and the viewer opens on the trace containing the current session — including windowed sessions and subagent children recorded into a parent's trace. Expanded cards scroll line-by-line so content taller than the viewport is fully readable. Model spans with errors, token usage, or tool calls (but no text) now appear as cards instead of disappearing. Terminal escape sequences in trace payloads are stripped at render time. Tool-call arguments and results are captured without stripping domain-level `providerOptions`/`providerMetadata` keys. A single prompt message over 32 KiB is truncated at the text level so the serialized JSON stays parseable. Local spans capture system prompt, prompt messages, responses, reasoning, and tool arguments/results (`EVE_TRACES_CONTENT=off` to disable); long conversations truncate oldest messages first with an omission marker.
|
|
24
|
+
- 275271d: Subagent runs now record into the trace of the session that dispatched them instead of a disconnected trace of their own, and `eve traces` resolves either session id to it. Local traces also open a real `agent.session` root span rather than a synthesized parent, so an authored OTel sampler's root rule decides whether a session is sampled, and a session long enough to outgrow one trace rolls into numbered windows that `eve traces <session-id>` lists oldest first. Rows whose lifetime outlives the worker that opened them — `agent.session` and `agent.turn` — now show the extent of their descendants instead of `0ms`.
|
|
25
|
+
|
|
26
|
+
## 0.29.2
|
|
27
|
+
|
|
28
|
+
### Patch Changes
|
|
29
|
+
|
|
30
|
+
- f3ecdcd: Eval config timeouts are now applied to every eval and enforced even when an eval task does not cooperate with its abort signal, preventing stalled eval runs.
|
|
31
|
+
- f3ecdcd: Malformed raw tool arguments now preserve the original JSON syntax error and return it to the model as a failed tool result instead of reporting a misleading serialization error.
|
|
32
|
+
|
|
3
33
|
## 0.29.1
|
|
4
34
|
|
|
5
35
|
### Patch Changes
|
|
@@ -68,6 +68,16 @@ export interface SessionParent {
|
|
|
68
68
|
readonly sessionId: string;
|
|
69
69
|
readonly turn: SessionTurn;
|
|
70
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Serializable W3C span context identifying a parent's open trace window.
|
|
73
|
+
* Structural rather than an OTel `SpanContext` so the channel surface stays
|
|
74
|
+
* free of tracing dependencies.
|
|
75
|
+
*/
|
|
76
|
+
export interface SessionTraceContext {
|
|
77
|
+
readonly spanId: string;
|
|
78
|
+
readonly traceFlags: number;
|
|
79
|
+
readonly traceId: string;
|
|
80
|
+
}
|
|
71
81
|
/**
|
|
72
82
|
* Authenticated caller principal attached to a request.
|
|
73
83
|
*
|
|
@@ -281,6 +291,11 @@ export interface RunInput {
|
|
|
281
291
|
};
|
|
282
292
|
readonly mode: RunMode;
|
|
283
293
|
readonly parent?: SessionParent;
|
|
294
|
+
/**
|
|
295
|
+
* Dispatching parent's open trace window. Handed down rather than looked up
|
|
296
|
+
* because trace state is scoped to one session's context.
|
|
297
|
+
*/
|
|
298
|
+
readonly parentTraceContext?: SessionTraceContext;
|
|
284
299
|
/**
|
|
285
300
|
* Runtime-supplied session limits. Delegated local subagents use this to
|
|
286
301
|
* carry the parent's remaining quota and delegation caps with the same limit
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import type { AddChannelsDeps } from "#setup/integrations/channels/setup.js";
|
|
2
|
-
import { detectDeployment } from "#setup/project-resolution.js";
|
|
3
1
|
import { type Prompter } from "#setup/prompter.js";
|
|
4
|
-
import {
|
|
2
|
+
import { type IntegrationSetupRunnerDeps } from "#setup/integrations/runner.js";
|
|
5
3
|
import type { RegistryCommandLogger } from "./registry.js";
|
|
6
4
|
export interface IntegrationSetupOptions {
|
|
7
5
|
yes?: boolean;
|
|
@@ -9,9 +7,7 @@ export interface IntegrationSetupOptions {
|
|
|
9
7
|
}
|
|
10
8
|
export interface IntegrationSetupDependencies {
|
|
11
9
|
createPrompter?: () => Prompter;
|
|
12
|
-
|
|
13
|
-
getVercelAuthStatus: typeof getVercelAuthStatus;
|
|
14
|
-
addChannelsDeps?: AddChannelsDeps;
|
|
10
|
+
runnerDeps?: IntegrationSetupRunnerDeps;
|
|
15
11
|
}
|
|
16
|
-
/** Runs
|
|
12
|
+
/** Runs built-in integration setup after its registry payload is installed. */
|
|
17
13
|
export declare function runIntegrationSetupCommand(logger: RegistryCommandLogger, appRoot: string, kind: string, options?: IntegrationSetupOptions, dependencies?: IntegrationSetupDependencies): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NOT_AN_AGENT_MESSAGE}from"./preconditions.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{
|
|
1
|
+
import{NOT_AN_AGENT_MESSAGE}from"./preconditions.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{createRegistrySetupClient}from"#setup/registry-setup-client.js";import{runIntegrationSetup}from"#setup/integrations/runner.js";const defaultIntegrationSetupDependencies={};async function runIntegrationSetupCommand(n,r,i,a={},o=defaultIntegrationSetupDependencies){if(!await isEveProject(r)){n.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}let s=createRegistrySetupClient({signal:a.signal});try{let e=s?.prompter??o.createPrompter?.()??createPrompter(),t=await runIntegrationSetup(i,{appRoot:r,prompter:e,signal:s?.signal??a.signal,yes:a.yes},o.runnerDeps);if(t.kind===`cancelled`){s?.cancel(),process.env.EVE_SETUP===`1`&&(process.exitCode=130);return}e.outro(`Integration set up.`),s?.complete(t.facts)}catch(e){s?.fail(e),n.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}export{runIntegrationSetupCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NOT_AN_AGENT_MESSAGE}from"./preconditions.js";import{addRegistryMappings,readRegistryConfig}from"./registry-project.js";import{z}from"#compiled/zod/index.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{WizardCancelledError}from"#setup/step.js";import{addRegistryItems,getRegistryItems,searchRegistries}from"#compiled/shadcn-registry/index.js";import semver from"#compiled/semver/index.js";const defaultAddCommandDependencies={createPrompter,isInteractive:()=>process.stdin.isTTY===!0&&process.stdout.isTTY===!0,loadSetupCommandRunner:async()=>(await import(`./registry-setup-command.js`)).runRegistrySetupCommand},OFFICIAL_REGISTRY
|
|
1
|
+
import{NOT_AN_AGENT_MESSAGE}from"./preconditions.js";import{addRegistryMappings,readRegistryConfig}from"./registry-project.js";import{z}from"#compiled/zod/index.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{WizardCancelledError}from"#setup/step.js";import{addRegistryItems,getRegistryItems,searchRegistries}from"#compiled/shadcn-registry/index.js";import semver from"#compiled/semver/index.js";const defaultAddCommandDependencies={createPrompter,isInteractive:()=>process.stdin.isTTY===!0&&process.stdout.isTTY===!0,loadSetupCommandRunner:async()=>(await import(`./registry-setup-command.js`)).runRegistrySetupCommand},OFFICIAL_REGISTRY=process.env.EVE_DEV_OFFICIAL_REGISTRY_URL??`https://eve.dev/r`,OFFICIAL_CATALOG=`${OFFICIAL_REGISTRY}/registry.json`,OFFICIAL_CATALOG_TITLES=new Map([[`channel/photon-imessage`,`Photon iMessage`]]);function isRegistryAddress(e){return e.startsWith(`@`)||/^https?:\/\//.test(e)}function itemAddress(e){return isRegistryAddress(e)?e:`${OFFICIAL_REGISTRY}/${e}.json`}async function installOfficialRegistryItem(e,t,r={}){let i=await readRegistryConfig(e);await addRegistryItems([itemAddress(t)],{config:i,cwd:e,overwrite:r.overwrite})}const EveRegistryItemMetadataSchema=z.object({meta:z.object({eve:z.object({requires:z.string().optional(),setup:z.object({package:z.string().min(1),bin:z.string().min(1),args:z.array(z.string()).default([])}).optional()}).optional()}).optional()});function eveMetadataFromRegistryItem(e){return EveRegistryItemMetadataSchema.parse(e).meta?.eve}function setupResumeCommand(e){return`eve add ${/^[\w@./:-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`} --skip-install`}function setupReminder(e,t){return`${t===`cancelled`?`Setup cancelled.`:`Setup skipped.`} Run \`${setupResumeCommand(e)}\` when you're ready.`}function assertCompatibleEveVersion(e){if(e===void 0)return;let t=resolveInstalledPackageInfo().version;if(semver.validRange(e)===null)throw Error(`Registry item has an invalid eve version requirement: ${e}.`);if(!semver.subset(t,e))throw Error(`This registry item requires eve ${e}, but this project is using eve ${t}. Upgrade eve and run the command again.`)}function isOfficialItemAddress(e){return e.startsWith(`${OFFICIAL_REGISTRY}/`)}function errorMessage(e){return e instanceof Error?e.message:String(e)}async function runRegistryAction(t,n,r){if(!await isEveProject(n)){t.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}try{await r()}catch(e){t.error(errorMessage(e)),process.exitCode=1}}function configuredRegistrySources(e){return Object.keys(e.registries??{})}function validateRegistrySource(e){if(e!==void 0&&!isRegistryAddress(e))throw Error(`Registry sources must be a namespace or URL: ${e}`)}function printSearchResults(e,t,n){if(t.items.length===0){e.log(`No registry items found.`);return}let r=`${t.pagination.total} item${t.pagination.total===1?``:`s`}`,i=n.query===void 0?``:` matching "${n.query}"`,a=`${n.sources.length} registr${n.sources.length===1?`y`:`ies`}`;e.log(`Found ${r}${i} in ${a}`),e.log(``);for(let r of t.items){let t=r.registry===OFFICIAL_CATALOG?r.name:r.addCommandArgument,i=n.query===void 0&&r.description?` — ${r.description}`:``;e.log(`${t}${i}`)}}async function searchRegistryCatalog(e,t){validateRegistrySource(t.source);let r=await readRegistryConfig(e),i=t.source?[t.source]:[OFFICIAL_CATALOG,...configuredRegistrySources(r)];return{result:await searchRegistries(i,{config:r,continueOnError:i.length>1,query:t.query}),sources:i}}async function browseRegistryCatalog(e,t={}){let{result:n}=await searchRegistryCatalog(e,t);return{items:n.items.map(e=>{let t={address:e.registry===OFFICIAL_CATALOG?e.name:e.addCommandArgument,name:e.name,source:e.registry===OFFICIAL_CATALOG?`Vercel`:e.registry},n=OFFICIAL_CATALOG_TITLES.get(e.name);return n!==void 0&&e.registry===OFFICIAL_CATALOG&&(t.title=n),e.type!==void 0&&(t.type=e.type),e.description!==void 0&&(t.description=e.description),t}),total:n.pagination.total,errors:n.errors??[]}}async function browseRegistryItems(e,t,n,r){let{result:i,sources:a}=await searchRegistryCatalog(t,{query:n,source:r}),o=i.errors??[];o.length<a.length&&printSearchResults(e,i,{query:n,sources:a});for(let t of o)e.error(`${t.registry}: ${t.message}`);o.length>0&&(process.exitCode=1)}async function getRegistryItemManifest(e,t){let r=await readRegistryConfig(e),i=await getRegistryItems([itemAddress(t)],{config:r});return i.length===1?i[0]:i}async function runDeclaredSetup(e,t,n,r,i,a){if(r===void 0)return;let s=await a.loadSetupCommandRunner();try{let a=i.prompter??createPrompter(),c=await s(t,{...r,args:[...r.args,...i.yes?[`--yes`]:[]]},n,{prompter:a,signal:i.signal});if(c.kind===`cancelled`)e.log(setupReminder(n,`cancelled`));else for(let t of c.output)e.log(t)}catch(e){throw Error(`${errorMessage(e)} Try again with \`${setupResumeCommand(n)}\`.`)}}async function installRegistryItem(e,t,n={},r=defaultAddCommandDependencies){let i,a=[],o={error:e=>{i=e},log:e=>a.push(e)},s=process.exitCode;if(await runAddCommand(o,e,t,{...n,yes:!0},r),process.exitCode=s,i!==void 0)throw Error(i);return a}async function runAddCommand(e,t,r,i,a=defaultAddCommandDependencies){await runRegistryAction(e,t,async()=>{let o=await readRegistryConfig(t),l=itemAddress(r);if(i.skipInstall===!0){if(i.overwrite===!0)throw Error(`--overwrite cannot be used with --skip-install.`);if(i.skipSetup===!0)throw Error(`--skip-install cannot be used with --skip-setup.`);if(!isOfficialItemAddress(l))throw Error(`Setup flows are currently supported only for official eve registry items.`)}let[u]=await getRegistryItems([l],{config:o}),d=isOfficialItemAddress(l)?eveMetadataFromRegistryItem(u):void 0;if(assertCompatibleEveVersion(d?.requires),i.skipInstall===!0){if(d?.setup===void 0)throw Error(`Registry item "${r}" does not declare a setup flow.`);await runDeclaredSetup(e,t,r,d.setup,i,a);return}if(await addRegistryItems([l],{config:o,cwd:t,overwrite:i.overwrite,silent:i.silent}),d?.setup===void 0)return;let f=a.isInteractive?.()??defaultAddCommandDependencies.isInteractive();if(i.skipSetup===!0||!i.yes&&!f){e.log(setupReminder(r,`skipped`));return}if(!i.yes)try{if(await(a.createPrompter?.()??defaultAddCommandDependencies.createPrompter()).select({message:`Set up ${r} now?`,initialValue:`yes`,options:[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}]})===`no`){e.log(setupReminder(r,`skipped`));return}}catch(t){if(!(t instanceof WizardCancelledError))throw t;e.log(setupReminder(r,`cancelled`));return}await runDeclaredSetup(e,t,r,d.setup,i,a)})}async function runRegistryAddCommand(e,n,r){await runRegistryAction(e,n,async()=>{let i=await addRegistryMappings(n,r);for(let t of i.skippedBuiltIn)e.log(`Skipped ${t} because it is built in.`);for(let t of i.skippedExisting)e.log(`Skipped ${t} because it is already configured.`);i.added.length>0&&e.log(`Added ${i.added.join(`, `)} to package.json.`)})}async function runRegistryListCommand(e,t,n){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,void 0,n))}async function runRegistrySearchCommand(e,t,n,r){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,n,r))}async function runRegistryViewCommand(e,t,r){await runRegistryAction(e,t,async()=>{let i=await readRegistryConfig(t),a=await getRegistryItems([itemAddress(r)],{config:i});e.log(JSON.stringify(a.length===1?a[0]:a,null,2))})}export{browseRegistryCatalog,getRegistryItemManifest,installOfficialRegistryItem,installRegistryItem,runAddCommand,runRegistryAddCommand,runRegistryListCommand,runRegistrySearchCommand,runRegistryViewCommand};
|
|
@@ -1,32 +1,15 @@
|
|
|
1
|
+
import type { LocalTrace, LocalTraceSpan } from "#tracing/local-trace-reader.js";
|
|
1
2
|
interface CliTraceLogger {
|
|
2
3
|
error(message: string): void;
|
|
3
4
|
log(message: string): void;
|
|
4
5
|
}
|
|
5
|
-
export
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
readonly spanId: string;
|
|
12
|
-
readonly startTimeNs: bigint;
|
|
13
|
-
readonly statusCode: number;
|
|
14
|
-
readonly traceId: string;
|
|
15
|
-
}
|
|
16
|
-
export interface LocalTrace {
|
|
17
|
-
readonly agentName?: string;
|
|
18
|
-
readonly endTimeNs: bigint;
|
|
19
|
-
readonly sessionId?: string;
|
|
20
|
-
readonly spans: readonly LocalTraceSpan[];
|
|
21
|
-
readonly startTimeNs: bigint;
|
|
22
|
-
readonly traceId: string;
|
|
23
|
-
}
|
|
24
|
-
/** Reads valid local traces, newest first, while ignoring malformed segments. */
|
|
25
|
-
export declare function listLocalTraces(appRoot: string): Promise<LocalTrace[]>;
|
|
26
|
-
/** Resolves an exact trace/session id or an unambiguous prefix. */
|
|
27
|
-
export declare function resolveLocalTrace(traces: readonly LocalTrace[], reference: string): LocalTrace;
|
|
6
|
+
export type { LocalTrace, LocalTraceSpan };
|
|
7
|
+
/**
|
|
8
|
+
* Resolves an exact trace/session id or an unambiguous prefix. One session id
|
|
9
|
+
* can match several traces, since a long session windows into more than one.
|
|
10
|
+
*/
|
|
11
|
+
export declare function resolveLocalTraces(traces: readonly LocalTrace[], reference: string): readonly LocalTrace[];
|
|
28
12
|
export declare function runTraceListCommand(logger: CliTraceLogger, appRoot: string, options?: {
|
|
29
13
|
readonly json?: boolean;
|
|
30
14
|
}): Promise<void>;
|
|
31
15
|
export declare function runTraceShowCommand(logger: CliTraceLogger, appRoot: string, reference?: string): Promise<void>;
|
|
32
|
-
export {};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import{basename
|
|
2
|
-
`))}async function runTraceShowCommand(e,
|
|
1
|
+
import{basename}from"node:path";import{createCliTheme,renderCliSection,sanitizeForTerminal}from"#cli/ui/output.js";import{formatElapsed}from"#cli/format-elapsed.js";import{compareLocalTraceSpans,describeLocalTraceSpan,listLocalTraces}from"#tracing/local-trace-reader.js";const TRACE_DISPLAY_DIRECTORY=`.eve/traces/v1`;function resolveLocalTraces(t,n){let i=n.replaceAll(`\\`,`/`),a=basename(i),o=i===a?[i]:[i,a],s=t.find(e=>o.includes(e.traceId));if(s!==void 0)return[s];let c=t.filter(e=>e.sessionIds.some(e=>o.includes(e)));if(c.length>0)return orderWindows(c);let l=t.filter(e=>o.some(t=>e.traceId.startsWith(t)||e.sessionIds.some(e=>e.startsWith(t))));if(l.length===0)throw Error(`No local trace matches "${sanitizeForTerminal(n)}". Run \`eve traces ls\` to list traces.`);if(l.length===1)return l;if(new Set(l.map(e=>e.sessionId??e.traceId)).size>1)throw ambiguousTraceError(l,n);return orderWindows(l)}function orderWindows(e){return[...e].sort((e,t)=>e.startTimeNs===t.startTimeNs?e.traceId.localeCompare(t.traceId):e.startTimeNs<t.startTimeNs?-1:1)}async function runTraceListCommand(e,t,n={}){let a=await listLocalTraces(t);if(n.json===!0){e.log(JSON.stringify(a.map(e=>({agentName:e.agentName??null,durationMs:durationMs(e.startTimeNs,e.endTimeNs),sessionId:e.sessionId??null,spanCount:e.spans.length,startedAt:toDate(e.startTimeNs).toISOString(),traceId:e.traceId})),null,2));return}if(a.length===0){e.log(`No local traces found under ${TRACE_DISPLAY_DIRECTORY}.`);return}let o=a.map(e=>[e.traceId,sanitizeForTerminal(e.sessionId??`unknown`),sanitizeForTerminal(e.agentName??`unknown`),toDate(e.startTimeNs).toISOString(),formatElapsed(durationMs(e.startTimeNs,e.endTimeNs)),String(e.spans.length)]),l=[`TRACE`,`SESSION`,`AGENT`,`STARTED`,`DURATION`,`SPANS`],u=l.map((e,t)=>Math.max(e.length,...o.map(e=>e[t].length)));e.log([l,...o].map(e=>e.map((e,t)=>e.padEnd(u[t])).join(` `).trimEnd()).join(`
|
|
2
|
+
`))}async function runTraceShowCommand(e,r,a){let o=await listLocalTraces(r);if(o.length===0){let t=`No local traces found under ${TRACE_DISPLAY_DIRECTORY}.`;if(a!==void 0)throw Error(t);e.log(t);return}let l=a===void 0?[o[0]]:resolveLocalTraces(o,a),u=createCliTheme();e.log(l.map(e=>[renderCliSection(u,{rows:[{label:`Trace ID`,value:e.traceId},{label:`Session ID`,value:e.sessionId??`unknown`},...e.window===void 0?[]:[{label:`Window`,value:String(e.window)}],{label:`Agent`,value:e.agentName??`unknown`},{label:`Started`,value:toDate(e.startTimeNs).toISOString()},{label:`Duration`,value:formatElapsed(durationMs(e.startTimeNs,e.endTimeNs))},{label:`Spans`,value:String(e.spans.length)}],title:`Trace`}),`${u.accent(`Spans`)}\n${renderSpanTree(e.spans)}`].join(`
|
|
3
3
|
|
|
4
|
-
`))
|
|
5
|
-
|
|
6
|
-
`))}
|
|
4
|
+
`)).join(`
|
|
5
|
+
|
|
6
|
+
`))}function renderSpanTree(e){let t=new Map(e.map(e=>[e.spanId,e])),n=new Map,r=[];for(let i of e)if(i.parentSpanId===void 0||!t.has(i.parentSpanId))r.push(i);else{let e=n.get(i.parentSpanId)??[];e.push(i),n.set(i.parentSpanId,e)}r.sort(compareLocalTraceSpans);for(let e of n.values())e.sort(compareLocalTraceSpans);let i=subtreeExtents(e,n),o=[],s=new Set,render=(e,t,r)=>{if(s.has(e.spanId))return;s.add(e.spanId),o.push(`${t}${r}${spanLabel(e,i.get(e.spanId))}`);let a=n.get(e.spanId)??[];a.forEach((e,n)=>{let i=n===a.length-1;render(e,`${t}${r===``?``:r===`└─ `?` `:`│ `}`,i?`└─ `:`├─ `)})};for(let e of r)render(e,``,``);for(let t of[...e].sort(compareLocalTraceSpans))s.has(t.spanId)||render(t,``,``);return o.join(`
|
|
7
|
+
`)}function subtreeExtents(e,t){let n=new Map,r=new Set,visit=e=>{let i=n.get(e.spanId);if(i!==void 0)return i;if(r.has(e.spanId))return{endTimeNs:e.endTimeNs,startTimeNs:e.startTimeNs};r.add(e.spanId);let a=e.endTimeNs,o=e.startTimeNs;for(let n of t.get(e.spanId)??[]){let e=visit(n);e.startTimeNs<o&&(o=e.startTimeNs),e.endTimeNs>a&&(a=e.endTimeNs)}r.delete(e.spanId);let s={endTimeNs:a,startTimeNs:o};return n.set(e.spanId,s),s};for(let t of e)visit(t);return n}function spanLabel(e,t){let n=describeLocalTraceSpan(e).map(sanitizeForTerminal),a=n.length===0?``:` [${n.join(`, `)}]`,s=e.statusCode===2?` ERROR`:``,c=durationMs(e.startTimeNs,e.endTimeNs),l=c===0&&t!==void 0?durationMs(t.startTimeNs,t.endTimeNs):c;return`${sanitizeForTerminal(e.name)}${a} ${formatElapsed(l)}${s}`}function durationMs(e,t){return Number(t-e)/1e6}function toDate(e){return new Date(Number(e/1000000n))}function ambiguousTraceError(e,t){return Error([`"${sanitizeForTerminal(t)}" matches ${e.length} local traces:`,...e.map(e=>` ${e.traceId} ${sanitizeForTerminal(e.sessionId??`unknown session`)}`),`Pass a longer prefix or the full trace/session id.`].join(`
|
|
8
|
+
`))}export{resolveLocalTraces,runTraceListCommand,runTraceShowCommand};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{isPromptControlCommand}from"./prompt-commands.js";import{renderMarkdown}from"./markdown.js";import{elisionText}from"./rail.js";import{renderTool}from"./tool-rows.js";import{clipVisible,sliceVisible,visibleLength,wrapVisibleLine}from"#cli/ui/terminal-text.js";function renderBlockLines(e,t,n,r){let i=e.depth??0,a=nestingPrefix(i,n),s=renderBody(e,Math.max(8,t-visibleLength(a)),n,r);if(e.closesRail===!0&&i>0){let e=closingPrefix(i,n);return s.map((t,n)=>`${n===s.length-1?e:a}${t}`)}return s.map(e=>`${a}${e}`)}function nestingPrefix(e,t){return e<=0?``:` ${`${t.colors.dim(t.glyph.rule)} `.repeat(e)}`}function closingPrefix(e,t){return` ${`${t.colors.dim(t.glyph.rule)} `.repeat(e-1)}${t.colors.dim(t.glyph.corner)} `}function renderBody(e,t,a,o){if(e.elided!==void 0&&e.kind===`subagent-step`)return[` ${elisionText(e.elided,a)}`];switch(e.kind){case`user`:return renderUser(e,t,a);case`assistant`:case`subagent-step`:return renderProse(e,t,a);case`reasoning`:return renderReasoning(e,t,a);case`tool`:case`subagent-tool`:return renderTool(e,t,a,o);case`error`:return renderError(e,t,a);case`notice`:return renderNotice(e,t,a);case`warning`:return renderWarning(e,t,a);case`result`:return renderResult(e,t,a);case`flow`:return renderFlow(e,t,a);case`command`:return renderCommand(e,a);case`question`:case`connection-auth`:return renderPreformatted(e,t,a);case`sandbox`:return renderSandbox(e,t,a,o);case`log`:return renderLog(e,t,a);case`subagent`:return renderSubagentHeader(e,t,a,o);case`subagent-close`:{let n=` ${a.colors.dim(a.glyph.corner)}`;return e.body!==void 0&&e.body.length>0?[clipVisible(`${n} ${a.colors.dim(e.body)}`,Math.max(1,t))]:[n]}case`turn-stats`:return renderTurnStats(e,t,a);case`session-boundary`:case`todo-list`:case`agent-header`:return(e.body??``).split(`
|
|
2
2
|
`)}}function renderUser(e,t,n){let r=n.colors.cyan(n.glyph.user),i=wrap(e.body??``,t-2).map(e=>`${r} ${e}`),a=n.colors.cyan(n.glyph.arrowUp);return e.promptOrigin===`steer`?[a,...i]:e.promptOrigin===`queue`?[...i,a]:i}function renderProse(e,n,r){let i=[],o=e.kind===`subagent-step`;if(o&&e.collapsed===!0){let t=firstNonEmptyLine(e.body)??(e.reasoning===void 0?void 0:firstNonEmptyLine(e.reasoning));return t===void 0?[]:[r.colors.dim(sliceVisible(t,Math.max(1,n)))]}let c=o?``:`${r.colors.bold(r.glyph.brand)} `,l=o?``:` `;e.reasoning&&e.reasoning.trim().length>0&&i.push(...renderReasoningLines(e.reasoning,n,r));let u=(e.body??``).trim();return u.length===0&&i.length===0?[`${c}${r.colors.dim(`thinking${r.glyph.ellipsis}`)}`]:(u.length>0&&renderMarkdown(u,n-l.length).split(`
|
|
3
3
|
`).flatMap(e=>wrapVisibleLine(e,n-l.length)).forEach((e,t)=>{t===0&&!o&&i.length===0?i.push(`${c}${e}`):i.push(`${l}${e}`)}),i.length>0?i:[`${c}`])}function renderReasoning(e,t,n){return e.collapsed?[`${n.colors.gray(n.glyph.reasoning)} ${n.colors.dim(e.title??`thinking`)}`]:renderReasoningLines(e.body??``,t,n,n.glyph.reasoning)}function renderReasoningLines(e,t,n,r){let i=r?2:0,a=wrap(e.trim(),t-i);return a.length===0?[]:a.map((e,t)=>`${r?t===0?`${n.colors.gray(r)} `:` `:``}${n.colors.dim(n.colors.italic(e))}`)}function renderError(e,t,n){let r=n.colors.red(n.colors.bold(n.glyph.error)),i=e.title??`Error`,a=[`${r} ${n.colors.red(n.colors.bold(i))}`];for(let r of wrap(e.body??``,t-2))a.push(` ${colorizeError(r,n)}`);if(e.hint!==void 0&&e.hint.trim().length>0)for(let[r,i]of wrap(e.hint,t-4).entries()){let e=r===0?`${n.glyph.arrow} `:` `;a.push(` ${n.colors.cyan(`${e}${i}`)}`)}return a.push(...renderErrorDetail(e.detail,t,n)),a}function renderErrorDetail(e,t,n){if(e===void 0||e.trim().length===0)return[];let r=e.split(`
|
|
4
|
-
`),i=r.slice(0,12),a=i.map(e=>` ${n.colors.dim(truncatePlain(e,Math.max(1,t-2)))}`),o=r.length-i.length;return o>0&&a.push(` ${n.colors.dim(`${n.glyph.ellipsis} +${o} more line${o===1?``:`s`}`)}`),a}const URL_PATTERN=/(https?:\/\/\S+)/u;function colorizeError(e,t){return URL_PATTERN.test(e)?e.split(URL_PATTERN).map((e,n)=>n%2==1?t.colors.cyan(e):t.colors.red(e)).join(``):t.colors.red(e)}function renderNotice(e,t,n){let r=n.colors.dim(n.glyph.dot),i=wrap(e.body??``,t-2);return i.length===0?[r]:i.map(e=>`${r} ${n.colors.dim(e)}`)}function renderAttentionRows(e,t,n){let r=n.colors.yellow(n.glyph.warning);return wrap(e,t-2).map((e,t)=>`${t===0?r:` `} ${paintCommands(e,n)}`)}function renderWarning(e,t,n){return renderAttentionRows(e.body??``,t,n)}function paintCommands(t,n){return t.replace(/\/[a-z:-]+/g,t=>isPromptControlCommand(t)?n.colors.blue(t):t)}function renderCommand(e,t){let n=t.colors,r=e.status===`error`?`${n.red(t.glyph.error)} `:``;return[`${n.cyan(t.glyph.user)} ${r}${n.blue(e.body??``)}`]}function renderFlow(e,t,n){let r=n.colors,i=e.title??`info`,a=i===`success`?r.green(n.glyph.success):i===`warning`?r.yellow(n.glyph.warning):i===`error`?r.red(n.glyph.error):r.dim(n.glyph.dot),o=wrap(e.body??``,t-2),paint=e=>i===`info`?r.dim(e):e;return o.map((e,t)=>`${t===0?a:` `} ${paint(e)}`)}function renderResult(e,t,n){let r=n.colors.dim(n.glyph.elbow),i=
|
|
4
|
+
`),i=r.slice(0,12),a=i.map(e=>` ${n.colors.dim(truncatePlain(e,Math.max(1,t-2)))}`),o=r.length-i.length;return o>0&&a.push(` ${n.colors.dim(`${n.glyph.ellipsis} +${o} more line${o===1?``:`s`}`)}`),a}const URL_PATTERN=/(https?:\/\/\S+)/u;function colorizeError(e,t){return URL_PATTERN.test(e)?e.split(URL_PATTERN).map((e,n)=>n%2==1?t.colors.cyan(e):t.colors.red(e)).join(``):t.colors.red(e)}function renderNotice(e,t,n){let r=n.colors.dim(n.glyph.dot),i=wrap(e.body??``,t-2);return i.length===0?[r]:i.map(e=>`${r} ${n.colors.dim(e)}`)}function renderAttentionRows(e,t,n){let r=n.colors.yellow(n.glyph.warning);return wrap(e,t-2).map((e,t)=>`${t===0?r:` `} ${paintCommands(e,n)}`)}function renderWarning(e,t,n){return renderAttentionRows(e.body??``,t,n)}function paintCommands(t,n){return t.replace(/\/[a-z:-]+/g,t=>isPromptControlCommand(t)?n.colors.blue(t):t)}function renderCommand(e,t){let n=t.colors,r=e.status===`error`?`${n.red(t.glyph.error)} `:``;return[`${n.cyan(t.glyph.user)} ${r}${n.blue(e.body??``)}`]}function renderFlow(e,t,n){let r=n.colors,i=e.title??`info`,a=i===`success`?r.green(n.glyph.success):i===`warning`?r.yellow(n.glyph.warning):i===`error`?r.red(n.glyph.error):r.dim(n.glyph.dot),o=wrap(e.body??``,t-2),paint=e=>i===`info`?r.dim(e):e;return o.map((e,t)=>`${t===0?a:` `} ${paint(e)}`)}function renderResult(e,t,n){let r=wrap(e.body??``,t-7);if(e.status===`done`){let e=n.colors.dim(n.glyph.elbow),t=n.colors.green(n.glyph.success),i=n.colors.dim(n.glyph.rule),a=n.colors.dim(n.glyph.corner);return r.length===0?[` ${e} ${t}`]:r.map((n,o)=>o===0?` ${e} ${t} ${n}`:` ${o===r.length-1?a:i} ${n}`)}let i=n.colors.dim(n.glyph.elbow);if(r.length===0)return[` ${i}`];let dim=e=>n.colors.dim(e.replaceAll(`\x1B[22m`,`\x1B[22m\x1B[2m`));return r.map((e,t)=>t===0?` ${i} ${dim(e)}`:` ${dim(e)}`)}function renderPreformatted(e,t,n){let r=e.kind===`connection-auth`?n.colors.yellow(n.glyph.connection):n.colors.yellow(n.colors.bold(n.glyph.question)),i=e.kind===`question`?` `:` `,a=wrap(e.title??``,t-2),o=a.length===0?[`${r} `]:a.map((e,t)=>t===0?`${r} ${n.colors.bold(e)}`:` ${n.colors.bold(e)}`);for(let n of(e.body??``).split(`
|
|
5
5
|
`))for(let e of wrapVisibleLine(n,Math.max(1,t-i.length)))o.push(`${i}${e}`);return o}function renderSandbox(e,t,n,r){let i=n.colors.cyan(n.glyph.rule),a=n.colors.dim(`sandbox ${n.glyph.dot} `),c=visibleLength(a),l=` `.repeat(c),u=r.previous?.kind===`sandbox`,d=(e.body??``).split(`
|
|
6
6
|
`),f=[];for(let e of d){let r=wrapVisibleLine(e,Math.max(1,t-2-c));for(let e of r){let t=f.length===0&&!u?a:l;f.push(`${i} ${t}${n.colors.gray(e)}`)}}return f.length>0?f:[`${i}`]}function renderLog(e,t,r){let i=e.title===`stderr`,a=i?r.colors.red:r.colors.gray,o=r.colors.dim(r.glyph.rule),c=i?`stderr`:`stdout`,l=[`${r.colors.dim(r.glyph.reasoning)} ${r.colors.dim(c)}`];e.elided!==void 0&&e.elided>0&&l.push(`${o} ${elisionText(e.elided,r)}`);for(let n of(e.body??``).split(`
|
|
7
7
|
`))for(let e of wrapVisibleLine(n,Math.max(1,t-2)))l.push(`${o} ${r.colors.dim(a(e))}`);return l}function renderTurnStats(e,t,n){let r=`${n.glyph.corner} ${e.body??``}`;return[n.colors.dim(truncatePlain(r,Math.max(1,t)))]}function renderSubagentHeader(e,t,n,r){let i=truncatePlain(e.title===void 0||e.title===`agent`?`self`:e.title,Math.max(8,t-16)),a=e.subtitle!==void 0&&e.subtitle.startsWith(`#`),o=a?`:${e.subtitle.slice(1)}`:``,s=` ${e.status===`done`?n.colors.green(n.glyph.subagent):r.activityPulse.trim().length>0?n.colors.orange(n.glyph.subagent):n.colors.dim(n.glyph.subagent)} subagent(${i}${o})`;return!a&&e.subtitle!==void 0&&e.subtitle.length>0&&(s+=` ${n.colors.dim(e.subtitle)}`),[s]}function firstNonEmptyLine(e){return e===void 0?void 0:e.split(/\r?\n/u).find(e=>e.trim().length>0)?.trim()}function wrap(e,t){return e.trim().length===0?[]:e.split(`
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Best-effort clipboard writes for the dev TUI: an OSC 52 escape sequence
|
|
3
|
+
* (which reaches the user's terminal even over SSH, with tmux/screen
|
|
4
|
+
* passthrough) plus the platform's native clipboard command as a fallback
|
|
5
|
+
* for terminals that reject OSC 52. Both paths fail silently — copying is
|
|
6
|
+
* a convenience, never a hard dependency.
|
|
7
|
+
*/
|
|
8
|
+
/** The OSC 52 sequence for `text`, wrapped for tmux/screen when present. */
|
|
9
|
+
export declare function clipboardSequence(text: string, env?: Readonly<Record<string, string | undefined>>): string;
|
|
10
|
+
/** The native clipboard command for a platform, or `undefined` when unknown. */
|
|
11
|
+
export declare function clipboardCommand(platform: NodeJS.Platform, env?: Readonly<Record<string, string | undefined>>): readonly string[] | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Copies `text` to the clipboard: emits OSC 52 through `writeTerminal`
|
|
14
|
+
* (the same raw write the alt screen paints with) and pipes the text into
|
|
15
|
+
* the platform clipboard command in the background.
|
|
16
|
+
*/
|
|
17
|
+
export declare function copyTextToClipboard(text: string, writeTerminal: (chunk: string) => void): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn}from"node:child_process";function clipboardSequence(e,t=process.env){let n=`\x1b]52;c;${Buffer.from(e).toString(`base64`)}\x07`;return t.TMUX!==void 0||t.STY!==void 0?`\x1bPtmux;\x1b${n}\x1b\\`:n}function clipboardCommand(e,t=process.env){if(e===`darwin`)return[`pbcopy`];if(e===`linux`)return t.WAYLAND_DISPLAY===void 0?[`xclip`,`-selection`,`clipboard`]:[`wl-copy`];if(e===`win32`)return[`clip`]}function copyTextToClipboard(t,n){n(clipboardSequence(t));let r=clipboardCommand(process.platform);if(r!==void 0)try{let n=spawn(r[0],r.slice(1),{stdio:[`pipe`,`ignore`,`ignore`],detached:!1});n.on(`error`,()=>{}),n.stdin?.on(`error`,()=>{}),n.stdin?.end(t)}catch{}}export{clipboardCommand,clipboardSequence,copyTextToClipboard};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sliceVisible,visibleLength}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";function typeaheadFor(e,t,n){let r=matchingCommands(e,t),i=n===void 0?void 0:n.matches[n.selectedIndex],a=i===void 0?-1:r.indexOf(i);return{query:t,matches:r,selectedIndex:a>=0?a:0,dismissed:n!==void 0&&n.dismissed&&n.query===t}}function matchingCommands(e,t){if(!t.startsWith(`/`)||/\s/.test(t))return[];let n=t.slice(1);return e.filter(e=>[e.name,...e.aliases].some(e=>e.startsWith(n)))}function isTypeaheadOpen(e){return e.matches.length>0&&!e.dismissed}function moveTypeaheadSelection(e,t){let n=e.matches.length;if(n===0)return e;let r=(e.selectedIndex+t+n)%n;return{...e,selectedIndex:r}}function dismissTypeahead(e){return e.dismissed?e:{...e,dismissed:!0}}function selectedTypeaheadCommand(e){return e.matches[e.selectedIndex]}function typeaheadCompletion(e){return`/${e.name}${e.takesArgument?` `:``}`}function inlineCommandHint(e){if(e.dismissed||e.matches.length!==1)return;let t=e.matches[0],n=e.query.startsWith(`/`)?e.query.slice(1):e.query;if([t.name,...t.aliases].includes(n))return t.argumentHint??``}function renderCommandSuggestions(r,i,a){let o=i.colors,s=r.matches.length,c=Math.min(s,
|
|
1
|
+
import{sliceVisible,visibleLength}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";function typeaheadFor(e,t,n){let r=matchingCommands(e,t),i=n===void 0?void 0:n.matches[n.selectedIndex],a=i===void 0?-1:r.indexOf(i);return{query:t,matches:r,selectedIndex:a>=0?a:0,dismissed:n!==void 0&&n.dismissed&&n.query===t}}function matchingCommands(e,t){if(!t.startsWith(`/`)||/\s/.test(t))return[];let n=t.slice(1);return e.filter(e=>[e.name,...e.aliases].some(e=>e.startsWith(n)))}function isTypeaheadOpen(e){return e.matches.length>0&&!e.dismissed}function moveTypeaheadSelection(e,t){let n=e.matches.length;if(n===0)return e;let r=(e.selectedIndex+t+n)%n;return{...e,selectedIndex:r}}function dismissTypeahead(e){return e.dismissed?e:{...e,dismissed:!0}}function selectedTypeaheadCommand(e){return e.matches[e.selectedIndex]}function typeaheadCompletion(e){return`/${e.name}${e.takesArgument?` `:``}`}function inlineCommandHint(e){if(e.dismissed||e.matches.length!==1)return;let t=e.matches[0],n=e.query.startsWith(`/`)?e.query.slice(1):e.query;if([t.name,...t.aliases].includes(n))return t.argumentHint??``}function renderCommandSuggestions(r,i,a){let o=i.colors,s=r.matches.length,c=Math.min(s,11),l=Math.max(0,Math.min(r.selectedIndex-Math.floor(c/2),s-c)),u=Math.min(l+c,s),d=r.matches.slice(l,u),invocation=e=>{let t=e.aliases.map(e=>` (/${e})`).join(``);return`/${e.name}${t}`},f=Math.max(...d.map(e=>invocation(e).length))+2;return d.map((e,t)=>{let a=l+t===r.selectedIndex,s=`/${e.name}`,c=renderCursorRow(a?`${i.glyph.selectedPointer} ${s}`:` ${s}`,a,o),u=invocation(e).slice(`/${e.name}`.length),d=` `.repeat(f-invocation(e).length);return a&&(u.startsWith(` `)?u=u.slice(1):d=d.slice(1)),`${c}${o.dim(u)}${d}${o.dim(e.description)}`}).map(n=>visibleLength(n)>a?sliceVisible(n,a):n)}export{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const PROMPT_COMMAND_DEFINITIONS=[{name:`help`,aliases:[],description:`Show available commands`,takesArgument:!1,build:()=>({type:`help`}),targets:[`local`,`remote`]},{name:`new`,aliases:[],description:`Start a fresh session`,takesArgument:!1,build:()=>({type:`new`}),targets:[`local`,`remote`]},{name:`vc:install`,aliases:[],description:`Install the Vercel CLI`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:install`,argument:``}),targets:[`local`,`remote`]},{name:`vc:login`,aliases:[],description:`Authenticate with Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:login`,argument:``}),targets:[`local`,`remote`]},{name:`model`,aliases:[],description:`Configure the agent's model and provider`,argumentHint:`[provider/model]`,takesArgument:!0,build:e=>({type:`extension`,name:`model`,argument:e}),targets:[`local`]},{name:`loglevel`,aliases:[],description:`Show or hide captured stdout/stderr/sandbox logs`,argumentHint:`[all|stderr|sandbox|none]`,takesArgument:!0,build:e=>({type:`loglevel`,argument:e}),targets:[`local`,`remote`]},{name:`add`,aliases:[],description:`Browse and add registry integrations`,takesArgument:!1,build:()=>({type:`extension`,name:`add`,argument:``}),targets:[`local`]},{name:`deploy`,aliases:[],description:`Deploy the agent to Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`deploy`,argument:``}),targets:[`local`]},{name:`exit`,aliases:[`quit`],description:`Quit the TUI`,takesArgument:!1,build:()=>({type:`exit`}),targets:[`local`,`remote`]}],PROMPT_COMMANDS=PROMPT_COMMAND_DEFINITIONS;function promptCommandsFor(t){return PROMPT_COMMAND_DEFINITIONS.filter(e=>e.targets.some(e=>e===t))}function isPromptCommandAvailableFor(t,n){return(PROMPT_COMMAND_DEFINITIONS.find(e=>e.name===t)?.targets)?.includes(n)??!1}function parsePromptCommand(e){let n=e.trim();if(!n.startsWith(`/`))return null;for(let e of PROMPT_COMMANDS)for(let t of[e.name,...e.aliases]){let r=`/${t}`;if(n===r)return e.build(``);if(e.takesArgument&&n.startsWith(`${r} `))return e.build(n.slice(r.length).trim())}return null}function isPromptControlCommand(e){return parsePromptCommand(e)!==null}function formatPromptCommandHelp(e=PROMPT_COMMANDS){let n=e.map(e=>{let t=e.argumentHint===void 0?``:` ${e.argumentHint}`,n=e.aliases.map(e=>` (/${e})`).join(``);return{invocation:`/${e.name}${t}${n}`,description:e.description}}),r=Math.max(...n.map(e=>e.invocation.length))+2;return n.map(e=>e.invocation.padEnd(r)+e.description).join(`
|
|
1
|
+
const PROMPT_COMMAND_DEFINITIONS=[{name:`help`,aliases:[],description:`Show available commands`,takesArgument:!1,build:()=>({type:`help`}),targets:[`local`,`remote`]},{name:`new`,aliases:[],description:`Start a fresh session`,takesArgument:!1,build:()=>({type:`new`}),targets:[`local`,`remote`]},{name:`vc:install`,aliases:[],description:`Install the Vercel CLI`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:install`,argument:``}),targets:[`local`,`remote`]},{name:`vc:login`,aliases:[],description:`Authenticate with Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:login`,argument:``}),targets:[`local`,`remote`]},{name:`model`,aliases:[],description:`Configure the agent's model and provider`,argumentHint:`[provider/model]`,takesArgument:!0,build:e=>({type:`extension`,name:`model`,argument:e}),targets:[`local`]},{name:`loglevel`,aliases:[],description:`Show or hide captured stdout/stderr/sandbox logs`,argumentHint:`[all|stderr|sandbox|none]`,takesArgument:!0,build:e=>({type:`loglevel`,argument:e}),targets:[`local`,`remote`]},{name:`traces`,aliases:[],description:`Open the local trace viewer`,argumentHint:`[trace]`,takesArgument:!0,build:e=>({type:`traces`,argument:e}),targets:[`local`]},{name:`add`,aliases:[],description:`Browse and add registry integrations`,takesArgument:!1,build:()=>({type:`extension`,name:`add`,argument:``}),targets:[`local`]},{name:`deploy`,aliases:[],description:`Deploy the agent to Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`deploy`,argument:``}),targets:[`local`]},{name:`exit`,aliases:[`quit`],description:`Quit the TUI`,takesArgument:!1,build:()=>({type:`exit`}),targets:[`local`,`remote`]}],PROMPT_COMMANDS=PROMPT_COMMAND_DEFINITIONS;function promptCommandsFor(t){return PROMPT_COMMAND_DEFINITIONS.filter(e=>e.targets.some(e=>e===t))}function isPromptCommandAvailableFor(t,n){return(PROMPT_COMMAND_DEFINITIONS.find(e=>e.name===t)?.targets)?.includes(n)??!1}function parsePromptCommand(e){let n=e.trim();if(!n.startsWith(`/`))return null;for(let e of PROMPT_COMMANDS)for(let t of[e.name,...e.aliases]){let r=`/${t}`;if(n===r)return e.build(``);if(e.takesArgument&&n.startsWith(`${r} `))return e.build(n.slice(r.length).trim())}return null}function isPromptControlCommand(e){return parsePromptCommand(e)!==null}function formatPromptCommandHelp(e=PROMPT_COMMANDS){let n=e.map(e=>{let t=e.argumentHint===void 0?``:` ${e.argumentHint}`,n=e.aliases.map(e=>` (/${e})`).join(``);return{invocation:`/${e.name}${t}${n}`,description:e.description}}),r=Math.max(...n.map(e=>e.invocation.length))+2;return n.map(e=>e.invocation.padEnd(r)+e.description).join(`
|
|
2
2
|
`)}export{PROMPT_COMMANDS,formatPromptCommandHelp,isPromptCommandAvailableFor,isPromptControlCommand,parsePromptCommand,promptCommandsFor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__toESM}from"../../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{applyVercelTrustedSourceAccess,prepareVercelTrustedSourceAccess}from"./vercel-trusted-sources.js";import{appendRemoteAuthMutationSummary}from"./remote-auth-result.js";import{WizardCancelledError}from"#setup/step.js";import{
|
|
1
|
+
import{__toESM}from"../../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{applyVercelTrustedSourceAccess,prepareVercelTrustedSourceAccess}from"./vercel-trusted-sources.js";import{appendRemoteAuthMutationSummary}from"./remote-auth-result.js";import{WizardCancelledError}from"#setup/step.js";import{toErrorMessage}from"#shared/errors.js";import{resolveDevelopmentOidcToken}from"#services/dev-client/request-headers.js";import{formatDevelopmentOidcTokenFailure}from"#services/dev-client/vercel-auth-error.js";import{runLoginFlow}from"#setup/flows/login.js";import{pickTeam}from"#setup/vercel-project.js";import{resolveVercelDeployment}from"#setup/vercel-deployment.js";var import_picocolors=__toESM(require_picocolors(),1);const defaultDeps={runLoginFlow,pickTeam,resolveVercelDeployment,resolveOidcToken:resolveDevelopmentOidcToken,prepareVercelTrustedSourceAccess,applyVercelTrustedSourceAccess};function failed(e,t=[]){return{kind:`failed`,message:appendRemoteAuthMutationSummary(e,t),completedMutations:[...t]}}function cancelled(e=[]){return{kind:`cancelled`,completedMutations:[...e]}}function loginFailure(e){switch(e.kind){case`already`:case`logged-in`:return;case`cancelled`:return cancelled();case`cli-missing`:return failed("The Vercel CLI is not installed. Install it with `npm i -g vercel@latest`, then retry /vc:login.");case`failed`:return failed(`Vercel login did not complete. Retry /vc:login.`);case`unavailable`:return failed(`Vercel could not verify your account. Check your connection, then retry /vc:login.`)}}function deploymentFailureMessage(e){return e.cause===`vercel`?e.failure.message:e.message}async function selectVercelDeploymentScope(e,t,n,r,i){return await e.pickTeam(r,t,void 0,{signal:i,selectMessage:e=>`${import_picocolors.default.blue(n)} is not accessible via current team (${import_picocolors.default.bold(e)})\nYou can try selecting another team:`})}async function runRemoteAuthFlow(e){let{workspaceRoot:t,serverUrl:n,prompter:r,signal:i}=e,a=new URL(n).host,o={...defaultDeps,...e.deps},s=[],c=!1;try{let n=await o.runLoginFlow({appRoot:t,prompter:r,signal:i}),l=loginFailure(n);if(l!==void 0)return l;n.kind===`logged-in`&&s.push({kind:`vercel-login`});let u=await o.resolveVercelDeployment({workspaceRoot:t,host:a,signal:i});if(u.kind===`forbidden`){let e=await o.runLoginFlow({appRoot:t,force:!0,prompter:r,signal:i}),n=loginFailure(e);if(n!==void 0)return n;e.kind===`logged-in`&&s.push({kind:`vercel-login`}),i?.throwIfAborted(),u=await o.resolveVercelDeployment({workspaceRoot:t,host:a,signal:i})}if(u.kind===`not-found`)try{let e=await selectVercelDeploymentScope(o,t,a,r,i);i?.throwIfAborted(),u=await o.resolveVercelDeployment({workspaceRoot:t,host:a,scope:e,signal:i})}catch(e){return e instanceof WizardCancelledError?cancelled(s):(i?.throwIfAborted(),failed(`Could not select a Vercel team: ${toErrorMessage(e)}`,s))}let d;switch(u.kind){case`resolved`:d=u.target;break;case`cancelled`:return cancelled(s);case`forbidden`:return failed(`Could not access ${a}. Re-authenticate (for example to complete a team's SSO), then retry /vc:login.`,s);case`not-found`:return failed(`Vercel did not resolve ${a} for the selected Vercel team.`,s);case`project-mismatch`:return failed(`Could not verify ${a}: Vercel resolved project ${u.actualProjectId}, not ${u.expectedProjectId}.`,s);case`failed`:return failed(`Could not verify ${a} through Vercel: ${deploymentFailureMessage(u.failure)}`,s)}let f;if(e.configureTrustedSources===!0){let e=await o.prepareVercelTrustedSourceAccess({workspaceRoot:t,target:d,prompter:r,signal:i});if(i?.throwIfAborted(),e.kind===`cancelled`)return cancelled(s);if(e.kind===`failed`)return failed(e.message,s);e.kind===`approved`&&(f=e.grant)}if(i?.throwIfAborted(),f!==void 0){c=!0;let e=await o.applyVercelTrustedSourceAccess({workspaceRoot:t,grant:f,signal:i});if(e.kind===`failed`)return failed(e.message,s);e.kind===`updated`&&s.push({kind:`trusted-sources-updated`,targetProjectName:e.targetProjectName})}let p=await o.resolveOidcToken({ownerId:d.deployment.ownerId,projectId:d.deployment.projectId,forceRefresh:!0});if(i?.throwIfAborted(),p.kind!==`resolved`)return failed(formatDevelopmentOidcTokenFailure(p),s);let m=p.token.trim();return{kind:`prepared`,target:d,resolveToken:async()=>{let e=await o.resolveOidcToken(d.deployment);return e.kind===`resolved`&&(m=e.token.trim()),m},completedMutations:[...s]}}catch(e){return!c&&(e instanceof WizardCancelledError||i?.aborted===!0)?cancelled(s):failed(`Could not authenticate ${a}: ${toErrorMessage(e)}`,s)}}export{runRemoteAuthFlow};
|
|
@@ -7,6 +7,7 @@ import { type RemoteConnectionController, type RemoteConnectionControllerOptions
|
|
|
7
7
|
import type { DevelopmentCredentialGate } from "#services/dev-client/credential-gate.js";
|
|
8
8
|
import { type BootDetection } from "./setup-issues.js";
|
|
9
9
|
import type { SetupFlowRenderer } from "./setup-flow.js";
|
|
10
|
+
import type { TraceViewerRenderer } from "./traces/trace-viewer-session.js";
|
|
10
11
|
import type { RemoteDevelopmentTarget } from "./target.js";
|
|
11
12
|
import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode, TuiDisplayOptions } from "./types.js";
|
|
12
13
|
import { type TerminalInput, type TerminalOutput } from "./terminal-renderer.js";
|
|
@@ -184,6 +185,11 @@ export type AgentTUIRenderer = {
|
|
|
184
185
|
renderCommandInvocation?(text: string, status?: "failed"): void;
|
|
185
186
|
renderCommandResult?(text: string, tone?: "success" | "error"): void;
|
|
186
187
|
readonly setupFlow?: SetupFlowRenderer;
|
|
188
|
+
/**
|
|
189
|
+
* The renderer's full-screen local trace viewer, opened by `/traces`.
|
|
190
|
+
* The returned promise resolves when the user closes the viewer.
|
|
191
|
+
*/
|
|
192
|
+
readonly traceViewer?: TraceViewerRenderer;
|
|
187
193
|
readPrompt?(options?: AgentTUISessionOptions): Promise<string | undefined>;
|
|
188
194
|
/**
|
|
189
195
|
* Consumes the next prompt produced by mid-turn input: the Esc-popped
|
|
@@ -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{getVercelAuthStatus}from"#setup/vercel-project.js";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{toErrorMessage}from"#shared/errors.js";import"#client/index.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=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 l=this.#m===void 0?void 0:parsePromptCommand(this.#m);for(l?.type===`extension`&&l.name===`model`&&l.argument===``&&this.#p!==void 0&&this.#h!==void 0&&this.#n.setupFlow!==void 0&&(s=void 0,await this.#ae(e));;){if(this.#L?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;if(!o){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};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#W(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let l=parsePromptCommand(r);if(l?.type===`exit`)return;if(l?.type===`new`){if(!await this.#U()){i=void 0,o=!1,r=void 0;continue}i=void 0,o=!1,r=void 0;continue}if(l?.type===`help`){this.#ee(formatPromptCommandHelp(this.#g)),i=void 0,o=!1,r=void 0;continue}if(l?.type===`loglevel`){this.#ee(this.#se(l.argument)),i=void 0,o=!1,r=void 0;continue}if(l?.type===`extension`){try{await this.#ie(l,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let l=await this.#G({prompt:o?void 0:r,inputResponses:i}),u=this.#e.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=r,f=!1;try{for(;;){await this.#n.renderStream(l,{title:e,submittedPrompt:d,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=l.turnState?.pendingApprovals??[],n=l.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;o=!0,i=a,r=void 0,f=!0;break}if(this.#fe(l)){l=this.#q(),d=void 0;continue}if(l.turnState&&l.turnState.boundaryEvent===void 0)if(l.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(f)continue;o=!1,i=void 0,r=void 0;let p=l.turnState?.boundaryEvent;!this.#F&&(p===`session.waiting`||p===`session.completed`)&&(r=this.#n.takeQueuedPrompt?.()),this.#F&&(this.#F=!1,this.#H(),l.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.#ue()})}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.#ue()}),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.#de(e),onConnectionAuthCompleted:e=>this.#pe(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.#ce();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}))}#se(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#ce(){let e=this.#p;if(e===void 0)return;loadDevelopmentEnvironmentFiles(e);let t=this.#z(await this.#le());this.#Q(t)}async#le(){let e=this.#t;if(e===void 0)return;let t=await probeAgentInfo({client:e});return t.kind===`ready`?t.info:void 0}async#ue(){let e=this.#A,t=await this.#le();t!==void 0&&this.#z(t),(!this.#n.renderAgentHeader||t===void 0)&&this.#n.renderNotice?.(formatAgentUpdateNotice(e,t))}#de(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.#me(t)}#fe(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.#me(e),t=!0);return t&&this.#n.setConnectionAuthPendingCount?.(this.#P.size),this.#P.size>0}#pe(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.#me(t),this.#n.setConnectionAuthPendingCount?.(this.#P.size)}#me(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{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{toErrorMessage}from"#shared/errors.js";import{getVercelAuthStatus}from"#setup/vercel-project.js";import"#client/index.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=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 l=this.#m===void 0?void 0:parsePromptCommand(this.#m);for(l?.type===`extension`&&l.name===`model`&&l.argument===``&&this.#p!==void 0&&this.#h!==void 0&&this.#n.setupFlow!==void 0&&(s=void 0,await this.#ae(e));;){if(this.#L?.signal.aborted===!0||this.#n.exitRequested?.()===!0)return;if(!o){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};s!==void 0&&(t.initialDraft=s,s=void 0);try{r=await this.#W(t)}catch(e){if(isInterruptedError(e))return;throw e}if(r==null)return}let l=parsePromptCommand(r);if(l?.type===`exit`)return;if(l?.type===`new`){if(!await this.#U()){i=void 0,o=!1,r=void 0;continue}i=void 0,o=!1,r=void 0;continue}if(l?.type===`help`){this.#ee(formatPromptCommandHelp(this.#g)),i=void 0,o=!1,r=void 0;continue}if(l?.type===`loglevel`){this.#ee(this.#ce(l.argument)),i=void 0,o=!1,r=void 0;continue}if(l?.type===`traces`){await this.#se(l.argument),i=void 0,o=!1,r=void 0;continue}if(l?.type===`extension`){try{await this.#ie(l,e,{trigger:`command`})}catch(e){if(isInterruptedError(e))return;throw e}i=void 0,r=void 0,o=!1;continue}a=!0}let l=await this.#G({prompt:o?void 0:r,inputResponses:i}),u=this.#e.state.sessionId;u!==void 0&&this.#n.setSessionId?.(u);let d=r,f=!1;try{for(;;){await this.#n.renderStream(l,{title:e,submittedPrompt:d,continueSession:!!this.#n.readPrompt,tools:this.#i,reasoning:this.#a,subagents:this.#o,connectionAuth:this.#s,assistantResponseStats:this.#c,contextSize:this.#l});let t=l.turnState?.pendingApprovals??[],n=l.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;o=!0,i=a,r=void 0,f=!0;break}if(this.#pe(l)){l=this.#q(),d=void 0;continue}if(l.turnState&&l.turnState.boundaryEvent===void 0)if(l.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(f)continue;o=!1,i=void 0,r=void 0;let p=l.turnState?.boundaryEvent;!this.#F&&(p===`session.waiting`||p===`session.completed`)&&(r=this.#n.takeQueuedPrompt?.()),this.#F&&(this.#F=!1,this.#H(),l.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};
|
|
@@ -33,6 +33,14 @@ export type TerminalKey = {
|
|
|
33
33
|
type: "tab";
|
|
34
34
|
} | {
|
|
35
35
|
type: "escape";
|
|
36
|
+
} | {
|
|
37
|
+
type: "mouse";
|
|
38
|
+
action: "press" | "release";
|
|
39
|
+
/** SGR button code (0 = left). */
|
|
40
|
+
button: number;
|
|
41
|
+
/** 1-based terminal cell coordinates. */
|
|
42
|
+
x: number;
|
|
43
|
+
y: number;
|
|
36
44
|
} | {
|
|
37
45
|
type: "ctrl-a";
|
|
38
46
|
} | {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
const CSI_FINAL=/[\u0040-\u007e]/u,PASTE_START=`\x1B[200~`,PASTE_END=`\x1B[201~`;function sanitizePastedText(e){let t=``;for(let n of e.replace(/\r\n?/gu,`
|
|
2
2
|
`)){if(n===`
|
|
3
|
-
`||n===` `){t+=n;continue}let e=n.codePointAt(0);e!==void 0&&(e<32||e===127||e>=128&&e<=159||(t+=n))}return t}function isIncompletePaste(e){return e.startsWith(PASTE_START)&&!e.includes(PASTE_END,6)}function stripPasteStart(e){return e.startsWith(PASTE_START)?e.slice(6):e}function stripPromptControlCharacters(e){let t=``;for(let n of e)n>=` `&&n!==``&&(t+=n);return t}function nextKey(r){let i=r[0];if(i===void 0)return{consumed:0,incomplete:!0};if(i===`\x1B`){if(r.length===1)return{consumed:0,incomplete:!0};let i=r[1];if(i===`O`)return r.length<3?{consumed:0,incomplete:!0}:{key:parseKey(Buffer.from(r.slice(0,3))),consumed:3};if(i===`[`){if(r.startsWith(PASTE_START)){let e=r.indexOf(PASTE_END,6);return e===-1?{consumed:0,incomplete:!0}:{key:{type:`text`,value:sanitizePastedText(r.slice(6,e)),framing:`bracketed-paste`},consumed:e+6}}for(let t=2;t<r.length;t+=1)if(CSI_FINAL.test(r[t]))return{key:parseKey(Buffer.from(r.slice(0,t+1))),consumed:t+1};return{consumed:0,incomplete:!0}}return{key:{type:`escape`},consumed:1}}if(i<` `||i===``)return{key:parseKey(Buffer.from(i)),consumed:1};let a=1;for(;a<r.length;){let e=r[a];if(e===`\x1B`||e<` `||e===``)break;a+=1}return{key:parseKey(Buffer.from(r.slice(0,a))),consumed:a}}function parseKey(e){let t=e.toString(`utf8`);switch(t){case``:return{type:`ctrl-a`};case``:return{type:`ctrl-e`};case``:return{type:`ctrl-d`};case`\v`:return{type:`ctrl-k`};case``:return{type:`ctrl-n`};case``:return{type:`ctrl-p`};case`\f`:return{type:`ctrl-l`};case``:return{type:`ctrl-r`};case``:return{type:`ctrl-u`};case``:return{type:`ctrl-w`};case``:return{type:`ctrl-c`};case`\r`:case`
|
|
3
|
+
`||n===` `){t+=n;continue}let e=n.codePointAt(0);e!==void 0&&(e<32||e===127||e>=128&&e<=159||(t+=n))}return t}function isIncompletePaste(e){return e.startsWith(PASTE_START)&&!e.includes(PASTE_END,6)}function stripPasteStart(e){return e.startsWith(PASTE_START)?e.slice(6):e}function stripPromptControlCharacters(e){let t=``;for(let n of e)n>=` `&&n!==``&&(t+=n);return t}function nextKey(r){let i=r[0];if(i===void 0)return{consumed:0,incomplete:!0};if(i===`\x1B`){if(r.length===1)return{consumed:0,incomplete:!0};let i=r[1];if(i===`O`)return r.length<3?{consumed:0,incomplete:!0}:{key:parseKey(Buffer.from(r.slice(0,3))),consumed:3};if(i===`[`){if(r.startsWith(PASTE_START)){let e=r.indexOf(PASTE_END,6);return e===-1?{consumed:0,incomplete:!0}:{key:{type:`text`,value:sanitizePastedText(r.slice(6,e)),framing:`bracketed-paste`},consumed:e+6}}for(let t=2;t<r.length;t+=1)if(CSI_FINAL.test(r[t]))return{key:parseKey(Buffer.from(r.slice(0,t+1))),consumed:t+1};return{consumed:0,incomplete:!0}}return{key:{type:`escape`},consumed:1}}if(i<` `||i===``)return{key:parseKey(Buffer.from(i)),consumed:1};let a=1;for(;a<r.length;){let e=r[a];if(e===`\x1B`||e<` `||e===``)break;a+=1}return{key:parseKey(Buffer.from(r.slice(0,a))),consumed:a}}const SGR_MOUSE=RegExp(`^\x1B\\[<(\\d+);(\\d+);(\\d+)([Mm])$`,`u`);function parseKey(e){let t=e.toString(`utf8`),n=SGR_MOUSE.exec(t);if(n!==null)return{type:`mouse`,action:n[4]===`M`?`press`:`release`,button:Number(n[1]),x:Number(n[2]),y:Number(n[3])};switch(t){case``:return{type:`ctrl-a`};case``:return{type:`ctrl-e`};case``:return{type:`ctrl-d`};case`\v`:return{type:`ctrl-k`};case``:return{type:`ctrl-n`};case``:return{type:`ctrl-p`};case`\f`:return{type:`ctrl-l`};case``:return{type:`ctrl-r`};case``:return{type:`ctrl-u`};case``:return{type:`ctrl-w`};case``:return{type:`ctrl-c`};case`\r`:case`
|
|
4
4
|
`:return{type:`enter`};case`\x1B[27;2;13~`:case`\x1B[13;2u`:return{type:`newline`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=stripPromptControlCharacters(t);return e.length>0?{type:`text`,value:e,framing:`unframed`}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));try{for(;;){let e=n.next();e.catch(()=>{});let t=await Promise.race([e,r]);if(t.done)break;yield t.value}}finally{n.return?.()?.catch(()=>{})}}function formatCompactTokenCount(e){if(e<1e3)return`${e}`;let t=e<1e6?e/1e3:e/1e6,n=e<1e6?`K`:`M`;return`${t.toFixed(1).replace(/\.0$/,``)}${n}`}function typewriterText(e,t,n){let r=Math.floor(Math.max(0,t)/n)+1;return r>=e.length?e:e.slice(0,r)}function formatTurnDuration(e){let t=Math.max(1,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60);if(r===0)return`${n}s`;let i=r%60,a=Math.floor(r/60);return a===0?n===0?`${i}min`:`${i}min ${n}s`:i===0?`${a}h`:`${a}h ${i}min`}function formatTokenFlow(e,t){let n=formatCompactTokenCount(e.inputTokens),r=formatCompactTokenCount(e.outputTokens),i=`${t.arrowUp} ${n} ${t.arrowDown} ${r}`,a=formatContextPercentage(e.inputTokens,e.contextSize);return a==null?i:`${i} ${a}`}function formatContextPercentage(e,t){if(!(t==null||t<=0||!Number.isFinite(t)))return`${Math.round(e/t*100).toLocaleString()}%`}function formatAssistantResponseStats(e,t){if(t===`tokensPerSecond`)return formatTokensPerSecond(e.tokensPerSecond);if(e.outputTokens!=null)return`${e.outputTokens.toLocaleString()} output tokens`}function formatTokensPerSecond(e){if(e!=null)return`${formatNumber(e)} tok/s`}function formatNumber(e){return Number.isInteger(e)?e.toLocaleString():e.toLocaleString(void 0,{maximumFractionDigits:1})}export{formatAssistantResponseStats,formatCompactTokenCount,formatTokenFlow,formatTurnDuration,isIncompletePaste,nextKey,parseKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText};
|
|
@@ -4,6 +4,7 @@ import { type PromptCommandSpec } from "./prompt-commands.js";
|
|
|
4
4
|
import type { SetupFlowRenderer } from "./setup-flow.js";
|
|
5
5
|
import type { AssistantResponseStatsMode, LogDisplayMode, TerminalPartDisplayMode } from "./types.js";
|
|
6
6
|
import type { AgentInfoResult } from "#client/index.js";
|
|
7
|
+
import type { TraceViewerRenderer } from "./traces/trace-viewer-session.js";
|
|
7
8
|
import type { VercelStatusSnapshot } from "./vercel-status.js";
|
|
8
9
|
import type { RemoteConnectionSnapshot } from "./remote-connection.js";
|
|
9
10
|
export type TerminalInput = {
|
|
@@ -51,6 +52,8 @@ export type AgentHeaderOptions = {
|
|
|
51
52
|
export declare class TerminalRenderer implements AgentTUIRenderer {
|
|
52
53
|
#private;
|
|
53
54
|
readonly setupFlow: SetupFlowRenderer;
|
|
55
|
+
/** The `/traces` full-screen viewer; resolves when the user closes it. */
|
|
56
|
+
readonly traceViewer: TraceViewerRenderer;
|
|
54
57
|
constructor(options?: TerminalRendererOptions);
|
|
55
58
|
/**
|
|
56
59
|
* Commits the startup agent header (brand mark + resolved configuration) to
|