eve 0.30.7 → 0.30.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/src/chunks/{use-eve-agent-BXMIf5fR.js → use-eve-agent-Bx-ONuyb.js} +22 -0
  3. package/dist/src/chunks/{use-eve-agent-k-XHfrJT.js → use-eve-agent-DDoDDmJ2.js} +22 -0
  4. package/dist/src/cli/commands/registry-metadata.d.ts +15 -0
  5. package/dist/src/cli/commands/registry-metadata.js +1 -0
  6. package/dist/src/cli/commands/registry-package.d.ts +46 -0
  7. package/dist/src/cli/commands/registry-package.js +1 -0
  8. package/dist/src/cli/commands/registry.d.ts +1 -1
  9. package/dist/src/cli/commands/registry.js +4 -4
  10. package/dist/src/cli/dev/tui/terminal-renderer.js +2 -2
  11. package/dist/src/client/index.d.ts +1 -1
  12. package/dist/src/client/message-reducer-types.d.ts +3 -0
  13. package/dist/src/client/message-reducer.js +1 -1
  14. package/dist/src/compiler/extension-compatibility.d.ts +10 -10
  15. package/dist/src/compiler/extension-compatibility.js +1 -1
  16. package/dist/src/execution/tool-auth.d.ts +1 -1
  17. package/dist/src/execution/tool-auth.js +1 -1
  18. package/dist/src/harness/emission-state.d.ts +25 -0
  19. package/dist/src/harness/emission-state.js +1 -0
  20. package/dist/src/harness/emission.d.ts +4 -36
  21. package/dist/src/harness/emission.js +1 -1
  22. package/dist/src/harness/ordered-stream-emitter.d.ts +3 -2
  23. package/dist/src/harness/ordered-stream-emitter.js +1 -1
  24. package/dist/src/harness/tools.d.ts +1 -1
  25. package/dist/src/harness/tools.js +1 -1
  26. package/dist/src/internal/application/package.js +1 -1
  27. package/dist/src/protocol/message.d.ts +23 -3
  28. package/dist/src/protocol/message.js +2 -2
  29. package/dist/src/public/channels/discord/discordChannel.d.ts +1 -0
  30. package/dist/src/public/channels/github/githubChannel.d.ts +1 -0
  31. package/dist/src/public/channels/linear/linearChannel.d.ts +1 -0
  32. package/dist/src/public/channels/slack/slackChannel.d.ts +1 -0
  33. package/dist/src/public/channels/teams/teamsChannel.d.ts +1 -0
  34. package/dist/src/public/channels/telegram/telegramChannel.d.ts +1 -0
  35. package/dist/src/public/channels/twilio/twilioChannel.d.ts +1 -0
  36. package/dist/src/public/definitions/channel.d.ts +1 -0
  37. package/dist/src/public/definitions/channel.js +1 -1
  38. package/dist/src/public/definitions/hook.d.ts +1 -0
  39. package/dist/src/public/definitions/tool.d.ts +5 -5
  40. package/dist/src/setup/integrations/linear/setup.js +1 -1
  41. package/dist/src/setup/scaffold/create/project.js +1 -1
  42. package/dist/src/shared/async-iterable.d.ts +2 -0
  43. package/dist/src/shared/async-iterable.js +1 -0
  44. package/dist/src/shared/tool-definition.d.ts +1 -1
  45. package/dist/src/svelte/index.js +1 -1
  46. package/dist/src/svelte/use-eve-agent.js +1 -1
  47. package/dist/src/vue/index.js +1 -1
  48. package/dist/src/vue/use-eve-agent.js +1 -1
  49. package/docs/channels/linear.mdx +4 -2
  50. package/docs/concepts/sessions-runs-and-streaming.md +3 -0
  51. package/docs/guides/client/streaming.mdx +1 -0
  52. package/docs/guides/hooks.md +1 -1
  53. package/docs/install-integrations.mdx +4 -2
  54. package/docs/reference/cli.md +4 -1
  55. package/docs/tools/overview.mdx +26 -2
  56. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # eve
2
2
 
3
+ ## 0.30.8
4
+
5
+ ### Patch Changes
6
+
7
+ - e6f4808: Add a single `eve add linear` flow that installs and configures both the Linear Channel and Linear MCP connection.
8
+ - f51f866: Tools can now use async generators to stream preliminary output snapshots. eve publishes local snapshots as `action.partial` events before the final `action.result`, and the default client reducer exposes provisional output with `partial: true`.
9
+
3
10
  ## 0.30.7
4
11
 
5
12
  ### Patch Changes
@@ -1836,6 +1836,25 @@ function reduceMessageData(data, event) {
1836
1836
  if (existing !== void 0) return updateToolPart(data, event.data.result.callId, nextPart);
1837
1837
  return updateAssistantMessage(data, event.data.turnId, (message) => upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart));
1838
1838
  }
1839
+ case "action.partial": {
1840
+ const existing = findToolPart(data, event.data.result.callId);
1841
+ if (existing !== void 0 && isSettledToolPart(existing)) return data;
1842
+ const descriptor = normalizeActionResult(event.data.result);
1843
+ const nextPart = {
1844
+ approval: approvedApproval(existing),
1845
+ input: existing?.input,
1846
+ output: event.data.result.output,
1847
+ partial: true,
1848
+ state: "output-available",
1849
+ stepIndex: event.data.stepIndex,
1850
+ toolCallId: event.data.result.callId,
1851
+ toolMetadata: mergeToolMetadata(existing?.toolMetadata, createToolMetadata(descriptor)),
1852
+ toolName: existing?.toolName ?? descriptor.toolName,
1853
+ type: "dynamic-tool"
1854
+ };
1855
+ if (existing !== void 0) return updateToolPart(data, event.data.result.callId, nextPart);
1856
+ return updateAssistantMessage(data, event.data.turnId, (message) => upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart));
1857
+ }
1839
1858
  case "authorization.required": return updateAssistantMessage(data, event.data.turnId, (message) => upsertPart(ensureStepStartPart(message, event.data.stepIndex), createAuthorizationRequiredPart(event)));
1840
1859
  case "authorization.completed": return completeAuthorization(data, event);
1841
1860
  case "message.appended": return updateAssistantMessage(data, event.data.turnId, (message) => upsertRun(ensureStepStartPart(message, event.data.stepIndex), {
@@ -1993,6 +2012,9 @@ function updateAuthorizationPart(data, existing, next) {
1993
2012
  function findToolPart(data, toolCallId) {
1994
2013
  for (const message of data.messages) for (const part of message.parts) if (part.type === "dynamic-tool" && part.toolCallId === toolCallId) return part;
1995
2014
  }
2015
+ function isSettledToolPart(part) {
2016
+ return part.state === "output-denied" || part.state === "output-error" || part.state === "output-available" && part.partial !== true;
2017
+ }
1996
2018
  function findLatestPendingAuthorizationPart(data, name) {
1997
2019
  for (let messageIndex = data.messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
1998
2020
  const message = data.messages[messageIndex];
@@ -1836,6 +1836,25 @@ function reduceMessageData(data, event) {
1836
1836
  if (existing !== void 0) return updateToolPart(data, event.data.result.callId, nextPart);
1837
1837
  return updateAssistantMessage(data, event.data.turnId, (message) => upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart));
1838
1838
  }
1839
+ case "action.partial": {
1840
+ const existing = findToolPart(data, event.data.result.callId);
1841
+ if (existing !== void 0 && isSettledToolPart(existing)) return data;
1842
+ const descriptor = normalizeActionResult(event.data.result);
1843
+ const nextPart = {
1844
+ approval: approvedApproval(existing),
1845
+ input: existing?.input,
1846
+ output: event.data.result.output,
1847
+ partial: true,
1848
+ state: "output-available",
1849
+ stepIndex: event.data.stepIndex,
1850
+ toolCallId: event.data.result.callId,
1851
+ toolMetadata: mergeToolMetadata(existing?.toolMetadata, createToolMetadata(descriptor)),
1852
+ toolName: existing?.toolName ?? descriptor.toolName,
1853
+ type: "dynamic-tool"
1854
+ };
1855
+ if (existing !== void 0) return updateToolPart(data, event.data.result.callId, nextPart);
1856
+ return updateAssistantMessage(data, event.data.turnId, (message) => upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart));
1857
+ }
1839
1858
  case "authorization.required": return updateAssistantMessage(data, event.data.turnId, (message) => upsertPart(ensureStepStartPart(message, event.data.stepIndex), createAuthorizationRequiredPart(event)));
1840
1859
  case "authorization.completed": return completeAuthorization(data, event);
1841
1860
  case "message.appended": return updateAssistantMessage(data, event.data.turnId, (message) => upsertRun(ensureStepStartPart(message, event.data.stepIndex), {
@@ -1993,6 +2012,9 @@ function updateAuthorizationPart(data, existing, next) {
1993
2012
  function findToolPart(data, toolCallId) {
1994
2013
  for (const message of data.messages) for (const part of message.parts) if (part.type === "dynamic-tool" && part.toolCallId === toolCallId) return part;
1995
2014
  }
2015
+ function isSettledToolPart(part) {
2016
+ return part.state === "output-denied" || part.state === "output-error" || part.state === "output-available" && part.partial !== true;
2017
+ }
1996
2018
  function findLatestPendingAuthorizationPart(data, name) {
1997
2019
  for (let messageIndex = data.messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
1998
2020
  const message = data.messages[messageIndex];
@@ -0,0 +1,15 @@
1
+ /** Parses eve-owned metadata from a registry item manifest. */
2
+ export declare function eveMetadataFromRegistryItem(item: unknown): {
3
+ requires?: string | undefined;
4
+ setup?: {
5
+ package: string;
6
+ bin: string;
7
+ args: string[];
8
+ }[] | undefined;
9
+ components?: {
10
+ item: string;
11
+ label: string;
12
+ description?: string | undefined;
13
+ default: boolean;
14
+ }[] | undefined;
15
+ } | undefined;
@@ -0,0 +1 @@
1
+ import{RegistryPackageComponentSchema}from"./registry-package.js";import{z}from"#compiled/zod/index.js";const RegistrySetupSchema=z.object({package:z.string().min(1),bin:z.string().min(1),args:z.array(z.string()).default([])}),EveRegistryItemMetadataSchema=z.object({meta:z.object({eve:z.object({requires:z.string().optional(),setup:z.union([RegistrySetupSchema,z.array(RegistrySetupSchema).min(1)]).transform(e=>Array.isArray(e)?e:[e]).optional(),components:z.array(RegistryPackageComponentSchema).min(1).optional()}).optional()}).optional()});function eveMetadataFromRegistryItem(e){return EveRegistryItemMetadataSchema.parse(e).meta?.eve}export{eveMetadataFromRegistryItem};
@@ -0,0 +1,46 @@
1
+ import { type RegistryConfig } from "#compiled/shadcn-registry/index.js";
2
+ import { z } from "#compiled/zod/index.js";
3
+ import { type Prompter } from "#setup/prompter.js";
4
+ import type { AddCommandOptions, RegistryCommandLogger } from "./registry.js";
5
+ import type { RegistrySetupCommand } from "./registry-setup-command.js";
6
+ export declare const RegistryPackageComponentSchema: z.ZodObject<{
7
+ item: z.ZodString;
8
+ label: z.ZodString;
9
+ description: z.ZodOptional<z.ZodString>;
10
+ default: z.ZodDefault<z.ZodBoolean>;
11
+ }, z.core.$strip>;
12
+ export type RegistryPackageComponent = z.infer<typeof RegistryPackageComponentSchema>;
13
+ interface PackageMetadata {
14
+ requires?: string;
15
+ setup?: RegistrySetupCommand[];
16
+ }
17
+ export interface RegistryPackageDependencies {
18
+ createPrompter?: () => Prompter;
19
+ hasInteractiveTerminal?: () => boolean;
20
+ }
21
+ export interface RegistryPackageOperations {
22
+ itemAddress(item: string): string;
23
+ metadata(item: unknown): PackageMetadata | undefined;
24
+ assertCompatibleVersion(requiredVersion: string | undefined): void;
25
+ runSetups(input: {
26
+ item: string;
27
+ setups: RegistrySetupCommand[];
28
+ prompter: Prompter;
29
+ }): Promise<boolean>;
30
+ setupReminder(item: string): string;
31
+ }
32
+ /** Resolves, installs, and configures the selected components of a registry package. */
33
+ export declare function runRegistryPackage(input: {
34
+ logger: RegistryCommandLogger;
35
+ appRoot: string;
36
+ item: string;
37
+ components: readonly RegistryPackageComponent[];
38
+ config: RegistryConfig;
39
+ options: AddCommandOptions & {
40
+ prompter?: Prompter;
41
+ signal?: AbortSignal;
42
+ };
43
+ dependencies: RegistryPackageDependencies;
44
+ operations: RegistryPackageOperations;
45
+ }): Promise<void>;
46
+ export {};
@@ -0,0 +1 @@
1
+ import{hasInteractiveTerminal}from"./preconditions.js";import{z}from"#compiled/zod/index.js";import{createPrompter}from"#setup/prompter.js";import{addRegistryItems,getRegistryItems}from"#compiled/shadcn-registry/index.js";const RegistryPackageComponentSchema=z.object({item:z.string().min(1),label:z.string().min(1),description:z.string().optional(),default:z.boolean().default(!1)});async function selectComponents(e,t,n,r,i){if(n.prompter===void 0&&(n.yes===!0||!r))return t.filter(e=>e.default);let a=await i().select({message:`Add ${e}`,description:`Select what you want to add to your agent.`,multiple:!0,required:!0,initialValues:t.filter(e=>e.default).map(e=>e.item),options:t.map(e=>({value:e.item,label:e.label,hint:e.description}))}),o=new Set(a);return t.filter(e=>o.has(e.item))}async function runRegistryPackage(t){let{logger:a,appRoot:o,item:s,components:c,config:l,options:u,dependencies:d,operations:f}=t,p=d.hasInteractiveTerminal?.()??hasInteractiveTerminal(),m=u.prompter,getPrompter=()=>m??=d.createPrompter?.()??createPrompter(),h=await selectComponents(s,c,u,p,getPrompter),g=h.map(e=>f.itemAddress(e.item)),_=await getRegistryItems(g,{config:l});if(_.length!==h.length)throw Error(`Registry package "${s}" could not resolve all selected components.`);let v=_.map(e=>{let t=f.metadata(e);return f.assertCompatibleVersion(t?.requires),t});if(u.skipInstall!==!0&&await addRegistryItems(g,{config:l,cwd:o,overwrite:u.overwrite,silent:u.silent}),u.skipSetup!==!0){if(u.yes!==!0&&u.prompter===void 0&&!p){a.log(f.setupReminder(s));return}for(let e of v)if(e?.setup!==void 0&&!await f.runSetups({item:s,setups:e.setup,prompter:getPrompter()}))return}}export{RegistryPackageComponentSchema,runRegistryPackage};
@@ -27,7 +27,7 @@ export interface RegistrySetupDependencies {
27
27
  }
28
28
  export interface AddCommandDependencies extends RegistrySetupDependencies {
29
29
  createPrompter?: () => Prompter;
30
- isInteractive?: () => boolean;
30
+ hasInteractiveTerminal?: () => boolean;
31
31
  }
32
32
  /** One discoverable item from an eve-compatible registry catalog. */
33
33
  export interface RegistryCatalogItem {
@@ -1,6 +1,6 @@
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{createCliTheme,sanitizeForTerminal}from"#cli/ui/output.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{clipVisible,wrapVisibleLine}from"#cli/ui/terminal-text.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};function resolveOfficialRegistryUrl(e=process.env.EVE_DEV_OFFICIAL_REGISTRY_URL){if(e===void 0)return`https://eve.dev/r`;let t;try{t=new URL(e)}catch{throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`);if(t.username!==``||t.password!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include credentials.`);if(t.search!==``||t.hash!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include a query or fragment.`);return t.pathname=t.pathname.replace(/\/+$/,``),t.toString().replace(/\/$/,``)}const OFFICIAL_REGISTRY=resolveOfficialRegistryUrl(),OFFICIAL_CATALOG=`${OFFICIAL_REGISTRY}/registry.json`,SKILLS_REGISTRY=`@skills`;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,n={}){let r=await readEveRegistryConfig(e);await addRegistryItems([itemAddress(t)],{config:r,cwd:e,overwrite:n.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 withBuiltInRegistries(e){return{...e,registries:{[SKILLS_REGISTRY]:`https://www.skills.sh/r/{name}?agent=eve`,...e.registries}}}async function readEveRegistryConfig(e){return withBuiltInRegistries(await readRegistryConfig(e))}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 normalizeRegistryText(e){return sanitizeForTerminal(e).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(/\s+/gu,` `).trim()}function registryDescriptionSummary(e){let t=normalizeRegistryText(e);return t.match(/^.*?[.!?](?=\s|$)/u)?.[0]??t}function searchItemAddress(e){return normalizeRegistryText(e.registry===OFFICIAL_CATALOG?e.name:e.addCommandArgument)}function searchItemFallbackTitle(e){let t=normalizeRegistryText(e.name);return t.split(`/`).at(-1)??t}function renderSearchItem(e,t,n){let r=Math.max(1,t-4),i=wrapVisibleLine(searchItemAddress(e),r),a=[` ${n.label(searchItemFallbackTitle(e))}`,...i.map(e=>` ${e}`)];if(!e.description)return a.join(`
1
+ import{NOT_AN_AGENT_MESSAGE,hasInteractiveTerminal}from"./preconditions.js";import{runRegistryPackage}from"./registry-package.js";import{eveMetadataFromRegistryItem}from"./registry-metadata.js";import{addRegistryMappings,readRegistryConfig}from"./registry-project.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createCliTheme,sanitizeForTerminal}from"#cli/ui/output.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{clipVisible,wrapVisibleLine}from"#cli/ui/terminal-text.js";import semver from"#compiled/semver/index.js";const defaultAddCommandDependencies={createPrompter,hasInteractiveTerminal,loadSetupCommandRunner:async()=>(await import(`./registry-setup-command.js`)).runRegistrySetupCommand};function resolveOfficialRegistryUrl(e=process.env.EVE_DEV_OFFICIAL_REGISTRY_URL){if(e===void 0)return`https://eve.dev/r`;let t;try{t=new URL(e)}catch{throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must be an HTTP(S) URL.`);if(t.username!==``||t.password!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include credentials.`);if(t.search!==``||t.hash!==``)throw Error(`EVE_DEV_OFFICIAL_REGISTRY_URL must not include a query or fragment.`);return t.pathname=t.pathname.replace(/\/+$/,``),t.toString().replace(/\/$/,``)}const OFFICIAL_REGISTRY=resolveOfficialRegistryUrl(),OFFICIAL_CATALOG=`${OFFICIAL_REGISTRY}/registry.json`,SKILLS_REGISTRY=`@skills`;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,n={}){let r=await readEveRegistryConfig(e);await addRegistryItems([itemAddress(t)],{config:r,cwd:e,overwrite:n.overwrite})}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){if(e instanceof WizardCancelledError)return;t.error(errorMessage(e)),process.exitCode=1}}function withBuiltInRegistries(e){return{...e,registries:{[SKILLS_REGISTRY]:`https://www.skills.sh/r/{name}?agent=eve`,...e.registries}}}async function readEveRegistryConfig(e){return withBuiltInRegistries(await readRegistryConfig(e))}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 normalizeRegistryText(e){return sanitizeForTerminal(e).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(/\s+/gu,` `).trim()}function registryDescriptionSummary(e){let t=normalizeRegistryText(e);return t.match(/^.*?[.!?](?=\s|$)/u)?.[0]??t}function searchItemAddress(e){return normalizeRegistryText(e.registry===OFFICIAL_CATALOG?e.name:e.addCommandArgument)}function searchItemFallbackTitle(e){let t=normalizeRegistryText(e.name);return t.split(`/`).at(-1)??t}function renderSearchItem(e,t,n){let r=Math.max(1,t-4),i=wrapVisibleLine(searchItemAddress(e),r),a=[` ${n.label(searchItemFallbackTitle(e))}`,...i.map(e=>` ${e}`)];if(!e.description)return a.join(`
2
2
  `);let o=registryDescriptionSummary(e.description);if(o.length===0)return a.join(`
3
3
  `);let s=wrapVisibleLine(o,r),c=s.length<=2?s:[s[0],`${clipVisible(s[1],Math.max(1,r-1)).trimEnd()}…`];return a.push(...c.map(e=>n.muted(` ${e}`))),a.join(`
4
- `)}function registrySourceLabel(e){return e===OFFICIAL_CATALOG?`eve`:e===SKILLS_REGISTRY?`skills.sh`:e}function printSearchResults(e,t,n){if(n.json){e.log(JSON.stringify(t,null,2));return}if(t.items.length===0){let t=n.query&&normalizeRegistryText(n.query);e.log(t?`No registry items match "${t}".`:`No registry items found.`);return}let r=createCliTheme(),i=Math.max(20,process.stdout.columns??80),o=n.sources.flatMap(e=>{let t=n.resultsBySource.get(e);if(t===void 0||t.items.length===0)return[];let{pagination:a}=t,o=`${a.total} result${a.total===1?``:`s`}`,s=t.items.length<a.total?`showing ${t.items.length} of ${o}`:o;return[[`${r.label(registrySourceLabel(e))} ${r.muted(`(${s})`)}`,...t.items.map(e=>renderSearchItem(e,i,r))].join(`
5
- `)]});e.log(o.join(`
6
- `))}async function searchRegistryCatalog(e,t){validateRegistrySource(t.source);let n=await readEveRegistryConfig(e),r=t.source?[t.source]:[OFFICIAL_CATALOG,...configuredRegistrySources(n).filter(e=>t.query!==void 0||e!==SKILLS_REGISTRY)],i=await Promise.all(r.map(async e=>{try{return{result:await searchRegistries([e],{config:n,limit:t.limit??100,query:t.query}),source:e}}catch(t){return{error:t,source:e}}})),a=[],o=new Map;for(let e of i)if(`error`in e)a.push({message:errorMessage(e.error),registry:e.source});else{let t=e.result.errors??[];if(a.push(...t),t.length===0){let t=e.result.items.filter(t=>t.registry===e.source);o.set(e.source,{...e.result,items:t,pagination:{...e.result.pagination,total:e.result.items.length===t.length?e.result.pagination.total:0}})}}let s=new Map(a.map(e=>[`${e.registry}\0${e.message}`,e])),c=[...o.values()];return{config:n,result:{items:c.flatMap(e=>e.items),pagination:{hasMore:c.some(e=>e.pagination.hasMore),limit:t.limit??100,offset:0,total:c.reduce((e,t)=>e+t.pagination.total,0)},...s.size>0?{errors:[...s.values()]}:{}},resultsBySource:o,sources:r}}function registryManifestTitle(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.title;return typeof t==`string`?t:void 0}async function browseRegistryCatalog(e,t={}){let{config:n,result:r}=await searchRegistryCatalog(e,t),i=await Promise.all(r.items.map(async e=>{let[t]=await getRegistryItems([e.addCommandArgument],{config:n});return t}));return{items:r.items.map((e,t)=>{let n={address:e.registry===OFFICIAL_CATALOG?e.name:e.addCommandArgument,name:e.name,source:e.registry===OFFICIAL_CATALOG?`Vercel`:e.registry},r=registryManifestTitle(i[t]);return r!==void 0&&(n.title=r),e.type!==void 0&&(n.type=e.type),e.description!==void 0&&(n.description=e.description),n}),total:r.pagination.total,errors:r.errors??[]}}async function browseRegistryItems(e,t,n,r,i={}){let{result:a,resultsBySource:o,sources:s}=await searchRegistryCatalog(t,{limit:i.limit,query:n,source:r}),c=a.errors??[];(i.json||o.size>0)&&printSearchResults(e,a,{...i,query:n,resultsBySource:o,sources:s});for(let t of c)e.error(`${t.registry}: ${t.message}`);c.length>0&&(process.exitCode=1)}async function getRegistryItemManifest(e,t){let n=await readEveRegistryConfig(e),r=await getRegistryItems([itemAddress(t)],{config:n});return r.length===1?r[0]:r}async function runDeclaredSetup(e,t,n,r,i,a){if(r===void 0)return;let o=await a.loadSetupCommandRunner();try{let a=i.prompter??createPrompter(),s=await o(t,{...r,args:[...r.args,...i.yes?[`--yes`]:[]]},n,{prompter:a,signal:i.signal});if(s.kind===`cancelled`)e.log(setupReminder(n,`cancelled`));else for(let t of s.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,n,r,i=defaultAddCommandDependencies){await runRegistryAction(e,t,async()=>{let a=await readEveRegistryConfig(t),o=itemAddress(n);if(r.skipInstall===!0){if(r.overwrite===!0)throw Error(`--overwrite cannot be used with --skip-install.`);if(r.skipSetup===!0)throw Error(`--skip-install cannot be used with --skip-setup.`);if(!isOfficialItemAddress(o))throw Error(`Setup flows are currently supported only for official eve registry items.`)}let[s]=await getRegistryItems([o],{config:a}),c=isOfficialItemAddress(o)?eveMetadataFromRegistryItem(s):void 0;if(assertCompatibleEveVersion(c?.requires),r.skipInstall===!0){if(c?.setup===void 0)throw Error(`Registry item "${n}" does not declare a setup flow.`);await runDeclaredSetup(e,t,n,c.setup,r,i);return}if(await addRegistryItems([o],{config:a,cwd:t,overwrite:r.overwrite,silent:r.silent}),c?.setup===void 0)return;let l=i.isInteractive?.()??defaultAddCommandDependencies.isInteractive();if(r.skipSetup===!0||!r.yes&&!l){e.log(setupReminder(n,`skipped`));return}if(!r.yes)try{if(await(i.createPrompter?.()??defaultAddCommandDependencies.createPrompter()).select({message:`Set up ${n} now?`,initialValue:`yes`,options:[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}]})===`no`){e.log(setupReminder(n,`skipped`));return}}catch(t){if(!(t instanceof WizardCancelledError))throw t;e.log(setupReminder(n,`cancelled`));return}await runDeclaredSetup(e,t,n,c.setup,r,i)})}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,r={}){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,void 0,n,r))}async function runRegistrySearchCommand(e,t,n,r,i={}){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,n,r,{...i,limit:i.limit??10}))}async function runRegistryViewCommand(e,t,n){await runRegistryAction(e,t,async()=>{let r=await readEveRegistryConfig(t),i=await getRegistryItems([itemAddress(n)],{config:r});e.log(JSON.stringify(i.length===1?i[0]:i,null,2))})}export{browseRegistryCatalog,getRegistryItemManifest,installOfficialRegistryItem,installRegistryItem,resolveOfficialRegistryUrl,runAddCommand,runRegistryAddCommand,runRegistryListCommand,runRegistrySearchCommand,runRegistryViewCommand};
4
+ `)}function registrySourceLabel(e){return e===OFFICIAL_CATALOG?`eve`:e===SKILLS_REGISTRY?`skills.sh`:e}function printSearchResults(e,t,n){if(n.json){e.log(JSON.stringify(t,null,2));return}if(t.items.length===0){let t=n.query&&normalizeRegistryText(n.query);e.log(t?`No registry items match "${t}".`:`No registry items found.`);return}let r=createCliTheme(),i=Math.max(20,process.stdout.columns??80),a=n.sources.flatMap(e=>{let t=n.resultsBySource.get(e);if(t===void 0||t.items.length===0)return[];let{pagination:a}=t,o=`${a.total} result${a.total===1?``:`s`}`,s=t.items.length<a.total?`showing ${t.items.length} of ${o}`:o;return[[`${r.label(registrySourceLabel(e))} ${r.muted(`(${s})`)}`,...t.items.map(e=>renderSearchItem(e,i,r))].join(`
5
+ `)]});e.log(a.join(`
6
+ `))}async function searchRegistryCatalog(e,t){validateRegistrySource(t.source);let n=await readEveRegistryConfig(e),r=t.source?[t.source]:[OFFICIAL_CATALOG,...configuredRegistrySources(n).filter(e=>t.query!==void 0||e!==SKILLS_REGISTRY)],i=await Promise.all(r.map(async e=>{try{return{result:await searchRegistries([e],{config:n,limit:t.limit??100,query:t.query}),source:e}}catch(t){return{error:t,source:e}}})),a=[],o=new Map;for(let e of i)if(`error`in e)a.push({message:errorMessage(e.error),registry:e.source});else{let t=e.result.errors??[];if(a.push(...t),t.length===0){let t=e.result.items.filter(t=>t.registry===e.source);o.set(e.source,{...e.result,items:t,pagination:{...e.result.pagination,total:e.result.items.length===t.length?e.result.pagination.total:0}})}}let s=new Map(a.map(e=>[`${e.registry}\0${e.message}`,e])),c=[...o.values()];return{config:n,result:{items:c.flatMap(e=>e.items),pagination:{hasMore:c.some(e=>e.pagination.hasMore),limit:t.limit??100,offset:0,total:c.reduce((e,t)=>e+t.pagination.total,0)},...s.size>0?{errors:[...s.values()]}:{}},resultsBySource:o,sources:r}}function registryManifestTitle(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.title;return typeof t==`string`?t:void 0}async function browseRegistryCatalog(e,t={}){let{config:n,result:r}=await searchRegistryCatalog(e,t),i=await Promise.all(r.items.map(async e=>{let[t]=await getRegistryItems([e.addCommandArgument],{config:n});return t}));return{items:r.items.map((e,t)=>{let n={address:e.registry===OFFICIAL_CATALOG?e.name:e.addCommandArgument,name:e.name,source:e.registry===OFFICIAL_CATALOG?`Vercel`:e.registry},r=registryManifestTitle(i[t]);return r!==void 0&&(n.title=r),e.type!==void 0&&(n.type=e.type),e.description!==void 0&&(n.description=e.description),n}),total:r.pagination.total,errors:r.errors??[]}}async function browseRegistryItems(e,t,n,r,i={}){let{result:a,resultsBySource:o,sources:s}=await searchRegistryCatalog(t,{limit:i.limit,query:n,source:r}),c=a.errors??[];(i.json||o.size>0)&&printSearchResults(e,a,{...i,query:n,resultsBySource:o,sources:s});for(let t of c)e.error(`${t.registry}: ${t.message}`);c.length>0&&(process.exitCode=1)}async function getRegistryItemManifest(e,t){let n=await readEveRegistryConfig(e),r=await getRegistryItems([itemAddress(t)],{config:n});return r.length===1?r[0]:r}async function runDeclaredSetups(e,t,n,r,i,a){if(r===void 0)return!0;let o=await a.loadSetupCommandRunner(),s=i.prompter??createPrompter();try{for(let a of r){let r=await o(t,{...a,args:[...a.args,...i.yes?[`--yes`]:[]]},n,{prompter:s,signal:i.signal});if(r.kind===`cancelled`)return e.log(setupReminder(n,`cancelled`)),!1;for(let t of r.output)e.log(t)}return!0}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:n.prompter===void 0||n.yes},r),process.exitCode=s,i!==void 0)throw Error(i);return a}async function runAddCommand(e,t,i,a,o=defaultAddCommandDependencies){await runRegistryAction(e,t,async()=>{let s=await readEveRegistryConfig(t),c=itemAddress(i);if(a.skipInstall===!0){if(a.overwrite===!0)throw Error(`--overwrite cannot be used with --skip-install.`);if(a.skipSetup===!0)throw Error(`--skip-install cannot be used with --skip-setup.`);if(!isOfficialItemAddress(c))throw Error(`Setup flows are currently supported only for official eve registry items.`)}let[l]=await getRegistryItems([c],{config:s}),u=isOfficialItemAddress(c)?eveMetadataFromRegistryItem(l):void 0;if(assertCompatibleEveVersion(u?.requires),u?.components!==void 0){if(!isOfficialItemAddress(c))throw Error(`Registry packages require the official eve registry.`);await runRegistryPackage({logger:e,appRoot:t,item:i,components:u.components,config:s,options:a,dependencies:o,operations:{itemAddress,metadata:eveMetadataFromRegistryItem,assertCompatibleVersion:assertCompatibleEveVersion,runSetups:({item:n,setups:r,prompter:i})=>runDeclaredSetups(e,t,n,r,{yes:a.yes,prompter:i,signal:a.signal},o),setupReminder:e=>setupReminder(e,`skipped`)}});return}if(a.skipInstall===!0){if(u?.setup===void 0)throw Error(`Registry item "${i}" does not declare a setup flow.`);await runDeclaredSetups(e,t,i,u.setup,a,o);return}if(await addRegistryItems([c],{config:s,cwd:t,overwrite:a.overwrite,silent:a.silent}),u?.setup===void 0)return;let d=o.hasInteractiveTerminal?.()??defaultAddCommandDependencies.hasInteractiveTerminal();if(a.skipSetup===!0||!a.yes&&!d){e.log(setupReminder(i,`skipped`));return}if(!a.yes)try{if(await(a.prompter??o.createPrompter?.()??defaultAddCommandDependencies.createPrompter()).select({message:`Set up ${i} now?`,initialValue:`yes`,options:[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}]})===`no`){e.log(setupReminder(i,`skipped`));return}}catch(t){if(!(t instanceof WizardCancelledError))throw t;e.log(setupReminder(i,`cancelled`));return}await runDeclaredSetups(e,t,i,u.setup,a,o)})}async function runRegistryAddCommand(e,t,n){await runRegistryAction(e,t,async()=>{let r=await addRegistryMappings(t,n);for(let t of r.skippedBuiltIn)e.log(`Skipped ${t} because it is built in.`);for(let t of r.skippedExisting)e.log(`Skipped ${t} because it is already configured.`);r.added.length>0&&e.log(`Added ${r.added.join(`, `)} to package.json.`)})}async function runRegistryListCommand(e,t,n,r={}){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,void 0,n,r))}async function runRegistrySearchCommand(e,t,n,r,i={}){await runRegistryAction(e,t,()=>browseRegistryItems(e,t,n,r,{...i,limit:i.limit??10}))}async function runRegistryViewCommand(e,t,n){await runRegistryAction(e,t,async()=>{let r=await readEveRegistryConfig(t),i=await getRegistryItems([itemAddress(n)],{config:r});e.log(JSON.stringify(i.length===1?i[0]:i,null,2))})}export{browseRegistryCatalog,getRegistryItemManifest,installOfficialRegistryItem,installRegistryItem,resolveOfficialRegistryUrl,runAddCommand,runRegistryAddCommand,runRegistryListCommand,runRegistrySearchCommand,runRegistryViewCommand};
@@ -1,8 +1,8 @@
1
1
  import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{buildAgentHeader}from"./agent-header.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{copyTextToClipboard}from"./clipboard.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{formatStoredDiagnostic,presentDiagnostic}from"./diagnostic-presentation.js";import{interruptedError}from"./errors.js";import{FileContentCache}from"./file-content-cache.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{MessageQueue,renderMessageQueueRows}from"./message-queue.js";import{initialModelEditorState,transitionModelEditor}from"./model-editor.js";import{promptPlaceholder}from"./prompt-placeholder.js";import{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.js";import{renderQuestionPanel}from"./question-panel.js";import{enterBadge,renderAcknowledgeQuestion,renderFlowPanel,renderModelEditorQuestion,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{formatAssistantResponseStats,formatTokenFlow,formatTurnDuration,isIncompleteOsc,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil,typewriterText}from"./stream-format.js";import{TraceViewerSession}from"./traces/trace-viewer-session.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName}from"./tool-presentation.js";import{groupToolBlocksForDisplay}from"./tool-block-groups.js";import{TurnClock}from"./turn-clock.js";import{allTodoItemsSettled,readTodoToolItems,renderFinishedTodoRows,renderTodoPanelRows}from"./todo-panel.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{BACKGROUND_COLOR_QUERY,parseBackgroundColorReply}from"./terminal-background.js";import{inspectError}from"#internal/logging.js";import{eveVersionTag}from"#cli/banner.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"#cli/ui/terminal-text.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{LiveRegion}from"#cli/ui/live-region.js";import{AltScreen}from"#cli/ui/alt-screen.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.js";import{readGatewayServiceTier}from"#shared/gateway-service-tier.js";function isMultiSelectRequest(e){return e.kind===`multi`||e.kind===`searchable-multi`}function moveActionCursor(e,t,n){return n===0?void 0:e===void 0?t===`down`?0:n-1:(e+(t===`down`?1:-1)+n)%n}function completedTurnStatus(e){return e.interrupted?`Interrupted`:e.cancelled?`Cancelled`:e.continueSession?`Ready`:`Done`}const incompletePasteFlushMs=1e3,STATUS={processing:`Working…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=[];#h=new Map;#g=new Set;#_=[];#v=new Set;#y=new Map;#b=0;#x=new Map;#S=new FileContentCache;#C=new Set;#w;#T=!1;#E;#D=[];#O;#k=0;#A;#j;#M=``;#N=0;#P=new PromptHistory;#F=!1;#I;#L=!1;#R=Date.now();#z=!1;#B=new TurnClock;#V=EMPTY_LINE;#H=!1;#U={kind:`idle`};#W;#G=STATUS.processing;#K;#q=`eve`;#J=!1;#Y=!1;#X=!1;#Z=!1;#Q=!1;#$=!1;#ee;#te=!0;#ne=0;#re=Date.now();#ie;#ae;#oe;#se=!1;#ce;#le=``;#ue=new StringDecoder(`utf8`);#de;#fe;#pe;#me=!1;#he=!1;#ge;#_e;#ve;#ye;#be;#xe;#Se;#Ce=``;#we=``;#Te;#Ee;#De=0;#Oe;#ke;#Ae;#je;#Me;#Ne;#Pe=new MessageQueue;#Fe;#Ie=!1;#Le;#Re;#ze=!1;#Be;#Ve;#He;#Ue;#We;setupFlow={begin:(e,t)=>this.#Xe(e,t),end:e=>this.#Ze(e?.preserveDiagnostics??!0),readSelect:e=>this.#Qe(e),readEditableSelect:e=>this.#et(e),readProviderPicker:e=>this.#tt(e),readModelEditor:e=>this.#nt(e),readText:e=>this.#rt(e),readAcknowledge:e=>this.#it(e),readChoice:e=>this.#$e(e),setStatus:e=>this.#ft(e),renderLine:(e,t)=>this.#pt(e,t),renderOutput:e=>this.#mt(e),withInheritedStdio:e=>this.#ht(e),withExclusiveTerminal:e=>this.#ht(e),waitForInterrupt:e=>this.#lt(e)};traceViewer={open:e=>this.#_t(e)};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=new AltScreen(this.#t),this.#i=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#a=t?.tools??`auto-collapsed`,this.#o=t?.reasoning??`auto-collapsed`,this.#s=t?.subagents??`auto-collapsed`,this.#c=t?.connectionAuth??`full`,this.#l=t?.assistantResponseStats??`tokensPerSecond`,this.#ve=t?.contextSize,this.#u=t?.captureForeignOutput??this.#t===process.stdout,this.#d=t?.diagnostics,this.#ee=t?.onExitRequest,this.#p=t?.logs??`none`,this.#f=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#q=e.name,this.#w=e,this.#bt();let t=this.#ln().join(`
2
2
  `);if(this.#T){t!==this.#E&&(this.#E=t,this.#Lt({kind:`agent-header`,body:t,live:!1})),this.#in();return}this.#T=!0,this.#E=t,this.#n.flush(this.#ln(),[])}async readPrompt(e){this.#bt(e),this.#It(),this.#zt(),this.#F=!0,this.#L=!0,this.#U={kind:`idle`},this.#G=``,this.#$=!1;let r=this.#Pe.restoreDraft()?.split(`
3
3
  `).map(stripPromptControlCharacters).join(`
4
- `),i=stripPromptControlCharacters(e?.initialDraft??this.#V.text),a=lineOf(r===void 0?i:i.length===0?r:`${r}\n\n${i}`);return this.#V=EMPTY_LINE,this.#P.begin(a.text),this.#Ge(a),this.#I=typeaheadFor(this.#f,a.text),this.#jt(),this.#in(),await new Promise((e,r)=>{this.#W=r;let apply=e=>{a=e,this.#Nt(),this.#Ge(a),this.#I=typeaheadFor(this.#f,e.text,this.#I),this.#in()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#I=void 0,this.#Mt(),this.#St(),r(interruptedError())},suggestions=()=>this.#I!==void 0&&isTypeaheadOpen(this.#I)?this.#I:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ce=r=>{r.type!==`ctrl-c`&&this.#$&&(this.#$=!1,this.#in());let i=applyLineEditorKey(a,r,{multiline:!0});if(i!==void 0){apply(i);return}switch(r.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,-1),this.#in();break}let t=movePromptLine(a,`up`);t===void 0?recall(this.#P.previous(a.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,1),this.#in();break}let t=movePromptLine(a,`down`);t===void 0?recall(this.#P.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#I=dismissTypeahead(e),this.#in());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(a.text)===null?typeaheadCompletion(r).trimEnd():a.text;if(i.trim().length===0)break;this.#I=void 0,this.#P.add(i),this.#F=!1,this.#Mt(),this.#G=STATUS.processing,isPromptControlCommand(i)?this.#Lt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Ft(),this.#Rt(i),this.#Oe=i,this.#B.arm()),this.#Ge(EMPTY_LINE),this.#in(),this.#wt(),e(i);break}case`ctrl-d`:a.text.length===0?(this.#gt(),interrupt()):apply(deleteForward(a));break;case`ctrl-l`:this.#sn();break;case`ctrl-r`:this.#in();break;case`ctrl-c`:if(this.#$){this.#gt(),interrupt();break}this.#$=!0,apply(EMPTY_LINE);break;default:break}},this.#Ct()})}#Ge(e){this.#M=e.text,this.#N=e.cursor}takeQueuedPrompt(){let e=this.#Pe.view().steering,t=this.#Pe.takePrompt();return t!==void 0&&(this.#Re=e?`steer`:`queue`),t}async renderStream(e,t){this.#bt(t),this.#g.clear(),this.#F=!1,this.#U.kind!==`waiting`&&(this.#U={kind:`waiting`,startedAtMs:Date.now()}),this.#G=this.#k>0?STATUS.connectionAuth:STATUS.processing,this.#Bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#d?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#B.armed&&this.#B.arm(),this.#Z=!1,this.#Ie=!1,this.#ze=!1,this.#Be=t?.submittedPrompt,this.#Pe.beginTurn(),this.#Fe=e.cancel,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=Date.now();let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l};this.#Pt(),this.#H=!0,this.#in();let r=new Promise(e=>{this.#pe=e});this.#ce=e=>this.#At(e),this.#Ct();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#Z)break;this.#Kt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Vt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Vt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#pe=void 0,this.#Z&&e.abort?.(),this.#Fe=void 0,this.#wt(),this.#It(),this.#H=!1,this.#U.kind===`waiting`&&(this.#U={kind:`idle`}),this.#G=completedTurnStatus({interrupted:this.#Z,cancelled:this.#Ie,continueSession:t?.continueSession===!0}),this.#$t(i),(this.#Z||this.#Ie)&&this.#Qt(),this.#Gt(),this.#d?.reportStats(),this.#in(),t?.continueSession||this.#St()}}async readToolApproval(e,t){return this.#bt(t),this.#It(),this.#F=!1,this.#U={kind:`idle`},this.#G=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#Z=!1,this.#in(),await new Promise((t,n)=>{this.#W=n,this.#ce=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ft(),this.#G=STATUS.processing,this.#wt(),this.#in(),t({approved:!0})):n===`n`&&(this.#Ft(),this.#G=STATUS.processing,this.#qe(e.toolCallId),this.#wt(),this.#in(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#in();break;case`ctrl-c`:this.#Z=!0,this.#St(),n(interruptedError());break;default:break}},this.#Ct()})}async readInputQuestion(e,t){this.#bt(t),this.#It(),this.#F=!1,this.#L=!1,this.#U={kind:`idle`},this.#Z=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#te},this.#i,t),renderTextSection=()=>{this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#jt():(this.#Mt(),this.#Nt())};s===`overlay`?(s=`overlay`,this.#F=!1,this.#Wt(o),this.#ke=overlayPanel,this.#G=``,syncFreeformCaret(),this.#in()):(s=`text`,this.#ke=void 0,renderTextSection(),this.#F=!0,this.#Ge(l),this.#G=``,this.#jt(),this.#in());let finalize=t=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#F=!1,this.#Ft(),this.#G=STATUS.processing,this.#Mt(),this.#wt(),this.#in();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#F=!1,this.#G=``,this.#Mt(),this.#wt(),this.#in(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#in())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#W=r,u=t,this.#ce=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),s===`text`&&this.#Ge(l),this.#in();return}this.#Z=!0,this.#ke=void 0,this.#Mt(),this.#St(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#in();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#in();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Nt(),this.#in());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#in())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Nt(),this.#Ge(l),this.#in();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Nt(),this.#Ge(l),this.#in());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#Ge(l),this.#in();break}dismiss();break;default:break}},this.#Ct()})}upsertSubagentStep(e){if(this.#d?.recordSubagentDispatch(e.callId),this.#s===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}this.#Ut({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#s!==`full`,live:!e.finalized}),this.#in()}}upsertSubagentTool(e){if(this.#d?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#d?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#s===`hidden`)return;if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Xt({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#s===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ut(r),this.#Ke(e.callId),this.#in()}#Ke(e){applyCohortLiveness(this.#m.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#Wt(subagentToolSectionId(e.callId,e.childCallId)),this.#in()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#s===`hidden`)return;this.#Ht(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#in()}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#in())}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#Wt(t),this.#y.delete(e),this.#in())}#qe(e){let t=this.#h.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#c===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Ut({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#in()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#k)return;let n=this.#k>0;this.#k=t,t>0?(this.#G=STATUS.connectionAuth,this.#in()):n&&(this.#G=STATUS.processing,this.#in())}setVercelStatus(e){this.#A=e,this.#in()}setRemoteConnectionStatus(e){this.#j=e,this.#in()}reset(){this.#m=[],this.#h.clear(),this.#g.clear(),this.#O=void 0,this.#D.length=0,this.#_.length=0,this.#T=!1,this.#E=void 0,this.#Je(),this.#z=!1,this.#Oe=void 0,this.#Ee=void 0,this.#k=0,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=void 0,this.#J&&(this.#n.clearAll(),this.#in())}renderSessionBoundary(){this.#zt(),this.#Je();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#Lt({kind:`session-boundary`,body:n,live:!1}),this.#in()}#Je(){this.#v.clear(),this.#y.clear(),this.#C.clear(),this.#x.clear(),this.#Me=void 0,this.#Ne=void 0,this.#Pe.reset(),this.#Re=void 0,this.#S.clear(),this.#B.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#bt(),this.#Lt({kind:`notice`,body:t,live:!1}),this.#in())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#bt(),this.#Lt({kind:`sandbox`,body:t,live:!1}),this.#in())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ye();return}this.#bt(),this.#je=t,this.#in()}clearSetupWarning(){this.#Ye()}#Ye(){this.#je!==void 0&&(this.#je=void 0,this.#in())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#bt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Lt(r),this.#in()}renderCommandResult(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#bt();let r=this.#m.at(-1);r?.kind===`command`&&(r.live=!1),this.#Lt(t===`success`?{kind:`result`,body:n,live:!1,status:`done`}:t===`error`?{kind:`flow`,title:t,body:n,live:!1}:{kind:`result`,body:n,live:!1}),this.#in()}#Xe(e,t=`spinner`){this.#bt(),this.#F=!1,this.#U={kind:`idle`},this.#G=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ae={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Pt(),this.#in()}#Ze(e){this.#Ve=void 0,this.#dt();let t=this.#Ae;if(t===void 0)return;this.#Ae=void 0,this.#It();let n=this.#m.at(-1);if(n?.kind===`command`&&(n.live=!0),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#Lt({kind:`flow`,title:`info`,body:e.join(`
5
- `),live:!1}),this.#Lt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#in()}async#Qe(e){let t=this.#at(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#in()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#in();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#in())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#dn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#in(),await this.#ct((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#in();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#in();return;case`update`:o=d.select,s=void 0,this.#in();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#in();return;case`ignore`:return}}).promise}#$e(e){this.#bt();let t=this.#ot();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#in();let r=this.#ct((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#in();return;case`repaint`:this.#in();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#et(e){let t=this.#at(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#te,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#jt():(i=lineOf(``),this.#Mt())};return syncEditableRow(),this.#in(),await this.#ct((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Nt(),this.#in()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#in()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#in();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#in();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Mt()).promise}async#tt(e){let t=this.#at(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#i,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#te,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#jt():this.#Mt()};return syncCaret(),this.#in(),await this.#ct((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#in();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#in();return;case`validate`:{n=o.state,syncCaret(),this.#in();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Nt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Mt()}).promise}async#nt(e){let t=this.#at(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#in(),await this.#ct((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#in();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
4
+ `),i=stripPromptControlCharacters(e?.initialDraft??this.#V.text),a=lineOf(r===void 0?i:i.length===0?r:`${r}\n\n${i}`);return this.#V=EMPTY_LINE,this.#P.begin(a.text),this.#Ge(a),this.#I=typeaheadFor(this.#f,a.text),this.#jt(),this.#in(),await new Promise((e,r)=>{this.#W=r;let apply=e=>{a=e,this.#Nt(),this.#Ge(a),this.#I=typeaheadFor(this.#f,e.text,this.#I),this.#in()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#I=void 0,this.#Mt(),this.#St(),r(interruptedError())},suggestions=()=>this.#I!==void 0&&isTypeaheadOpen(this.#I)?this.#I:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#ce=r=>{r.type!==`ctrl-c`&&this.#$&&(this.#$=!1,this.#in());let i=applyLineEditorKey(a,r,{multiline:!0});if(i!==void 0){apply(i);return}switch(r.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,-1),this.#in();break}let t=movePromptLine(a,`up`);t===void 0?recall(this.#P.previous(a.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#I=moveTypeaheadSelection(e,1),this.#in();break}let t=movePromptLine(a,`down`);t===void 0?recall(this.#P.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#I=dismissTypeahead(e),this.#in());break}case`enter`:{let r=highlighted(),i=r!==void 0&&parsePromptCommand(a.text)===null?typeaheadCompletion(r).trimEnd():a.text;if(i.trim().length===0)break;this.#I=void 0,this.#P.add(i),this.#F=!1,this.#Mt(),this.#G=STATUS.processing,isPromptControlCommand(i)?this.#Lt({kind:`command`,body:stripTerminalControls(i.trim()),live:!1}):(this.#Ft(),this.#Rt(i),this.#Oe=i,this.#B.arm()),this.#Ge(EMPTY_LINE),this.#in(),this.#wt(),e(i);break}case`ctrl-d`:a.text.length===0?(this.#gt(),interrupt()):apply(deleteForward(a));break;case`ctrl-l`:this.#sn();break;case`ctrl-r`:this.#in();break;case`ctrl-c`:if(this.#$){this.#gt(),interrupt();break}this.#$=!0,apply(EMPTY_LINE);break;default:break}},this.#Ct()})}#Ge(e){this.#M=e.text,this.#N=e.cursor}takeQueuedPrompt(){let e=this.#Pe.view().steering,t=this.#Pe.takePrompt();return t!==void 0&&(this.#Re=e?`steer`:`queue`),t}async renderStream(e,t){this.#bt(t),this.#g.clear(),this.#F=!1,this.#U.kind!==`waiting`&&(this.#U={kind:`waiting`,startedAtMs:Date.now()}),this.#G=this.#k>0?STATUS.connectionAuth:STATUS.processing,this.#Bt(t?.submittedPrompt),t?.submittedPrompt!==void 0&&this.#d?.recordPrompt(),t?.submittedPrompt!==void 0&&!this.#B.armed&&this.#B.arm(),this.#Z=!1,this.#Ie=!1,this.#ze=!1,this.#Be=t?.submittedPrompt,this.#Pe.beginTurn(),this.#Fe=e.cancel,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=Date.now();let n={tools:t?.tools??this.#a,reasoning:t?.reasoning??this.#o,assistantResponseStats:t?.assistantResponseStats??this.#l};this.#Pt(),this.#H=!0,this.#in();let r=new Promise(e=>{this.#pe=e});this.#ce=e=>this.#At(e),this.#Ct();let i={text:new Map,reasoning:new Map,tools:new Map};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#Z)break;this.#Kt(t,n,i)}}catch(e){let t=summarizeKnownError(e);t===null?this.#Vt(`Error`,toErrorMessage(e),{detail:inspectError(e)}):this.#Vt(t.name,t.message,{detail:inspectError(e),hint:t.hint})}finally{this.#pe=void 0,this.#Z&&e.abort?.(),this.#Fe=void 0,this.#wt(),this.#It(),this.#H=!1,this.#U.kind===`waiting`&&(this.#U={kind:`idle`}),this.#G=completedTurnStatus({interrupted:this.#Z,cancelled:this.#Ie,continueSession:t?.continueSession===!0}),this.#$t(i),(this.#Z||this.#Ie)&&this.#Qt(),this.#Gt(),this.#d?.reportStats(),this.#in(),t?.continueSession||this.#St()}}async readToolApproval(e,t){return this.#bt(t),this.#It(),this.#F=!1,this.#U={kind:`idle`},this.#G=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#Z=!1,this.#in(),await new Promise((t,n)=>{this.#W=n,this.#ce=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ft(),this.#G=STATUS.processing,this.#wt(),this.#in(),t({approved:!0})):n===`n`&&(this.#Ft(),this.#G=STATUS.processing,this.#qe(e.toolCallId),this.#wt(),this.#in(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#in();break;case`ctrl-c`:this.#Z=!0,this.#St(),n(interruptedError());break;default:break}},this.#Ct()})}async readInputQuestion(e,t){this.#bt(t),this.#It(),this.#F=!1,this.#L=!1,this.#U={kind:`idle`},this.#Z=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),s=r?`overlay`:`text`,c=0,l=EMPTY_LINE,isOnFreeformRow=()=>i&&c===n.length,overlayPanel=t=>renderQuestionPanel({prompt:stripTerminalControls(e.prompt),options:n,cursor:c,allowFreeform:i,editor:l,caretVisible:this.#te},this.#i,t),renderTextSection=()=>{this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,void 0,this.#i),preformatted:!0,live:!0})},syncFreeformCaret=()=>{isOnFreeformRow()?this.#jt():(this.#Mt(),this.#Nt())};s===`overlay`?(s=`overlay`,this.#F=!1,this.#Wt(o),this.#ke=overlayPanel,this.#G=``,syncFreeformCaret(),this.#in()):(s=`text`,this.#ke=void 0,renderTextSection(),this.#F=!0,this.#Ge(l),this.#G=``,this.#jt(),this.#in());let finalize=t=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#F=!1,this.#Ft(),this.#G=STATUS.processing,this.#Mt(),this.#wt(),this.#in();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n},dismiss=()=>{this.#ke=void 0,this.#Ut({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:`${this.#i.colors.dim(this.#i.glyph.elbow)} ${this.#i.colors.dim(`Dismissed.`)}`,preformatted:!0,live:!1}),this.#F=!1,this.#G=``,this.#Mt(),this.#wt(),this.#in(),u(void 0)},moveCursor=e=>{a!==0&&(c=(c+e+a)%a,syncFreeformCaret(),this.#in())},selectOptionAt=e=>{let t=n[e];t&&u(finalize({optionId:t.id,label:t.label}))},u;return await new Promise((t,r)=>{this.#W=r,u=t,this.#ce=t=>{if(t.type===`ctrl-c`){if((s===`text`||isOnFreeformRow())&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),s===`text`&&this.#Ge(l),this.#in();return}this.#Z=!0,this.#ke=void 0,this.#Mt(),this.#St(),r(interruptedError());return}if(t.type===`ctrl-r`){this.#in();return}if(s===`overlay`){switch(t.type){case`up`:case`ctrl-p`:moveCursor(-1);break;case`down`:case`ctrl-n`:moveCursor(1);break;case`enter`:if(isOnFreeformRow()){let t=resolveQuestionText(l.text,e);t!==void 0&&u(finalize(t));break}selectOptionAt(c);break;case`escape`:if(isOnFreeformRow()&&l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#in();break}dismiss();break;default:if(isOnFreeformRow()){let e=applyLineEditorKey(l,t);e!==void 0&&(l=e,this.#Nt(),this.#in());break}if(t.type===`text`&&/^[1-9]$/u.test(t.value)){let e=Number(t.value)-1;e<n.length?selectOptionAt(e):e===n.length&&i&&(c=e,syncFreeformCaret(),this.#in())}break}return}let a=applyLineEditorKey(l,t,{multiline:!0});if(a!==void 0){l=a,this.#Nt(),this.#Ge(l),this.#in();return}switch(t.type){case`up`:case`down`:{let e=movePromptLine(l,t.type);e!==void 0&&(l=e,this.#Nt(),this.#Ge(l),this.#in());break}case`enter`:{let t=resolveQuestionText(l.text,e);if(t===void 0)break;u(finalize(t));break}case`escape`:if(l.text.length>0){l=EMPTY_LINE,this.#Nt(),this.#Ge(l),this.#in();break}dismiss();break;default:break}},this.#Ct()})}upsertSubagentStep(e){if(this.#d?.recordSubagentDispatch(e.callId),this.#s===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}this.#Ut({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,subagentCallId:e.callId,depth:1,reasoning:t,body:n,collapsed:this.#s!==`full`,live:!e.finalized}),this.#in()}}upsertSubagentTool(e){if(this.#d?.recordSubagentDispatch(e.callId),e.status===`failed`&&e.errorText!==void 0&&this.#d?.append({source:`tool`,summary:`${e.toolName} failed (subagent ${e.subagentName})`,detail:e.errorText}),this.#s===`hidden`)return;if(this.#Ht(e.callId,e.subagentName),this.#s===`collapsed`){this.#in();return}let t=subagentToolStatus(e.status),n=e.status===`preparing`?presentPreparingTool(e.toolName):presentTool(e.toolName,e.input,this.#Xt({input:e.input,output:e.output,toolCallId:e.childCallId,toolName:e.toolName})),r={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,subagentCallId:e.callId,depth:1,title:stripTerminalControls(n.title),subtitle:stripTerminalControls(n.subtitle),status:t,live:t===`running`||t===`approval`,expanded:this.#s===`full`,toolName:e.toolName,toolGroup:n.group,toolInput:e.input};n.doneTitle!==void 0&&(r.doneTitle=stripTerminalControls(n.doneTitle)),n.detail!==void 0&&(r.detailLines=n.detail,r.keepDetailWhenDone=n.keepDetailWhenDone===!0),e.output===void 0?e.errorText!==void 0&&(r.result=stripTerminalControls(e.errorText)):(r.result=n.summarizeResult(e.output),r.toolOutput=e.output),this.#Ut(r),this.#Ke(e.callId),this.#in()}#Ke(e){applyCohortLiveness(this.#m.filter(t=>t.kind===`subagent-tool`&&t.subagentCallId===e).map(e=>({block:e,active:isActiveToolStatus(e.status)})))}removeSubagentTool(e){this.#Wt(subagentToolSectionId(e.callId,e.childCallId)),this.#in()}subagents={begin:e=>this.beginSubagent(e),upsertStep:e=>this.upsertSubagentStep(e),upsertTool:e=>this.upsertSubagentTool(e),removeTool:e=>this.removeSubagentTool(e),complete:e=>this.completeSubagent(e),markChildToolCallId:e=>this.markChildToolCallId(e)};beginSubagent(e){if(this.#s===`hidden`)return;this.#Ht(e.callId,e.name);let t=this.#h.get(subagentHeaderId(e.callId));t?.status===`done`&&delete t.status,this.#in()}completeSubagent(e){let t=this.#h.get(subagentHeaderId(e.callId));t!==void 0&&(t.status=`done`,this.#in())}markChildToolCallId(e){this.#v.add(e);let t=this.#y.get(e);t!==void 0&&(this.#Wt(t),this.#y.delete(e),this.#in())}#qe(e){let t=this.#h.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#c===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#Ut({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#in()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#k)return;let n=this.#k>0;this.#k=t,t>0?(this.#G=STATUS.connectionAuth,this.#in()):n&&(this.#G=STATUS.processing,this.#in())}setVercelStatus(e){this.#A=e,this.#in()}setRemoteConnectionStatus(e){this.#j=e,this.#in()}reset(){this.#m=[],this.#h.clear(),this.#g.clear(),this.#O=void 0,this.#D.length=0,this.#_.length=0,this.#T=!1,this.#E=void 0,this.#Je(),this.#z=!1,this.#Oe=void 0,this.#Ee=void 0,this.#k=0,this.#ge=void 0,this.#_e=void 0,this.#ye=void 0,this.#be=void 0,this.#xe=void 0,this.#J&&(this.#n.clearAll(),this.#in())}renderSessionBoundary(){this.#zt(),this.#Je();let e=this.#i.colors,t=this.#i.glyph,n=e.dim(`${t.cornerOpen}${t.dash.repeat(2)} Session restarted, clear context.`);this.#Lt({kind:`session-boundary`,body:n,live:!1}),this.#in()}#Je(){this.#v.clear(),this.#y.clear(),this.#C.clear(),this.#x.clear(),this.#Me=void 0,this.#Ne=void 0,this.#Pe.reset(),this.#Re=void 0,this.#S.clear(),this.#B.reset()}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#bt(),this.#Lt({kind:`notice`,body:t,live:!1}),this.#in())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#d?.append({source:`sandbox`,detail:t}),this.#bt(),this.#Lt({kind:`sandbox`,body:t,live:!1}),this.#in())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#Ye();return}this.#bt(),this.#je=t,this.#in()}clearSetupWarning(){this.#Ye()}#Ye(){this.#je!==void 0&&(this.#je=void 0,this.#in())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#bt();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Lt(r),this.#in()}renderCommandResult(e,t){let n=stripTerminalControls(e);n.trim().length!==0&&(this.#bt(),this.#Lt(t===`success`?{kind:`result`,body:n,live:!1,status:`done`}:t===`error`?{kind:`flow`,title:t,body:n,live:!1}:{kind:`result`,body:n,live:!1}),this.#in())}#Xe(e,t=`spinner`){this.#bt(),this.#F=!1,this.#U={kind:`idle`},this.#G=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#Ae={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Pt(),this.#in()}#Ze(e){this.#Ve=void 0,this.#dt();let t=this.#Ae;if(t!==void 0){if(this.#Ae=void 0,this.#It(),e){let e=[];for(let n of t.lines){if(n.evidence===!0){e.push(n.text);continue}(n.tone===`warning`||n.tone===`error`)&&(e.length>0&&this.#Lt({kind:`flow`,title:`info`,body:e.join(`
5
+ `),live:!1}),this.#Lt({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#in()}}async#Qe(e){let t=this.#at(),n=isMultiSelectRequest(e),r=e.kind===`search`?e.searchAction:void 0,i=e.options,a={options:i,searchAction:r,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(a.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(a.initialValues=e.initialValues);let o=initialSelectState(a),s,c=!1,l=0,isCurrentSearch=e=>e===l,clearSearch=()=>{l+=1,c=!1,o=reduceSelect(o,{type:`clear`},{options:i,searchAction:r,submitRow:n}),this.#in()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#in();try{let s=await t(e);if(!isCurrentSearch(a))return;let c=o.filter;i=s,o={...initialSelectState({options:s,searchAction:r,submitRow:n}),filter:c}}catch(e){isCurrentSearch(a)&&(s=toErrorMessage(e))}finally{isCurrentSearch(a)&&(c=!1,this.#in())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#dn()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#i,e),this.#in(),await this.#ct((t,a)=>{let close=e=>{l+=1,a(e)};if(c){t.type===`ctrl-c`?close(void 0):t.type===`escape`?clearSearch():t.type===`ctrl-r`&&this.#in();return}let u={key:t,options:i,searchAction:r,select:o},d=reduceSetupSelectInput(n?{...u,kind:e.kind,required:e.required}:{...u,kind:e.kind});switch(d.kind){case`cancel`:close(void 0);return;case`repaint`:this.#in();return;case`update`:o=d.select,s=void 0,this.#in();return;case`submit`:{let e=searchActionQuery(d.values[0]??``),t=r?.load;if(e===void 0||t===void 0){close(d.values);return}loadSearch(e,t);return}case`error`:s=d.message,this.#in();return;case`ignore`:return}}).promise}#$e(e){this.#bt();let t=this.#ot();t.status={kind:`progress`,text:stripTerminalControls(e.status),startedAtMs:Date.now()};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#i,t),this.#in();let r=this.#ct((t,r)=>{let i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:r(void 0);return;case`move`:n=moveActionCursor(n,i.direction,e.actions.length),this.#in();return;case`repaint`:this.#in();return;case`submit`:n!==void 0&&r(e.actions[n].value);return;case void 0:return}},()=>{t.status=void 0});return{choice:r.promise,close:()=>r.settle(void 0)}}async#et(e){let t=this.#at(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#te,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#i,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#jt():(i=lineOf(``),this.#Mt())};return syncEditableRow(),this.#in(),await this.#ct((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#Nt(),this.#in()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#in()},submit=()=>{let t=selectValueAtCursor([...e.options],r.cursor);if(t===void 0)return;if(t!==e.editable.value){n({kind:`selected`,value:t});return}let o=(i.text||e.editable.defaultValue).trim(),s=e.editable.validate?.(o);if(s!==void 0){a=s,this.#in();return}n(o===e.editable.defaultValue?{kind:`selected`,value:t}:{kind:`edited`,value:t,text:o})},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:n(void 0);return;case`move`:applySelect({type:o.direction});return;case`submit`:submit();return;case`repaint`:this.#in();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Mt()).promise}async#tt(e){let t=this.#at(),n=initialProviderPickerState(e.options,e.initialValue),r,cursorBadge=()=>{if(n.phase.kind!==`inactive`)return;let t=selectValueAtCursor([...e.options],n.select.cursor),r=e.options.find(e=>e.value===t);if(r!==void 0)return enterBadge(this.#i,r.checked===!0?`change`:void 0)};t.question=t=>{let r=cursorBadge(),i={kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#te,editor:{kind:`key`,phase:n.phase}}};return r!==void 0&&(i.cursorBadge=r),renderSelectQuestion(i,this.#i,t)};let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#jt():this.#Mt()};return syncCaret(),this.#in(),await this.#ct((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#in();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#in();return;case`validate`:{n=o.state,syncCaret(),this.#in();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#Nt(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Mt()}).promise}async#nt(e){let t=this.#at(),n=initialModelEditorState(e);return t.question=t=>renderModelEditorQuestion({request:e,state:n},this.#i,t),this.#in(),await this.#ct((t,r)=>{let dispatch=t=>{let i=transitionModelEditor(n,t,e);switch(i.kind){case`ignore`:return;case`render`:n=i.state,this.#in();return;case`cancel`:r(void 0);return;case`settle`:r(i.result);return}},i=setupSelectionIntent(t);switch(i?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:i.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#in();return;case void 0:break}if(t.type===`left`||t.type===`right`){dispatch({type:`adjust`,direction:t.type});return}if(t.type===`tab`){dispatch({type:`adjust`,direction:`right`});return}if(t.type===`backspace`){dispatch({type:`backspace`});return}if(t.type===`text`)for(let e of t.value.replaceAll(`
6
6
  `,` `))e>=` `&&e!==``&&dispatch({type:`char`,char:e})}).promise}async#rt(e){let t=this.#at(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder===void 0?e.defaultValue!==void 0&&(i.placeholder=e.defaultValue):i.placeholder=e.placeholder,e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#i,t,this.#te)},this.#jt(),this.#in(),await this.#ct((t,i)=>{let apply=e=>{n=e,r=void 0,this.#Nt(),this.#in()},a=applyLineEditorKey(n,t);if(a!==void 0){apply(a);return}switch(t.type){case`ctrl-c`:case`escape`:i(void 0);return;case`ctrl-r`:this.#in();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#in();return}i(t);return}default:return}},()=>this.#Mt()).promise}async#it(e){let t=this.#at();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#i,t),this.#in(),await this.#ct((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#in();return;default:return}}).promise}#at(){return this.#bt(),this.#F=!1,this.#U={kind:`idle`},this.#G=``,this.#ot()}#ot(){return this.#Ae===void 0&&(this.#Ae={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[],implicit:!0}),this.#Ae}#st(){this.#Ae?.implicit===!0?this.#Ae=void 0:this.#Ae!==void 0&&(this.#Ae.question=void 0,this.#Ae.hideLinesWhileQuestion=!1),this.#ce=void 0,this.#wt(),this.#Ae!==void 0&&this.#ut(),this.#in()}#ct(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#st(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#st(),i(e))};return this.#kt(),this.#ce=t=>{t.type===`ctrl-c`&&this.#gt(),e(t,settle,reject)},this.#Ct(),{promise:a,settle}}#lt(e){let t,n=new Promise(e=>{t=e});return this.#Ve=t,this.#ut(e?.interruptible??!0),{promise:n,dispose:()=>{this.#Ve===t&&(this.#Ve=void 0,this.#dt())}}}#ut(e=!0){if(this.#Ve===void 0)return;let consumer=t=>{if(e&&(t.type===`ctrl-c`||t.type===`escape`)){t.type===`ctrl-c`&&this.#gt();let e=this.#Ve;this.#Ve=void 0,this.#dt(),e?.();return}t.type===`ctrl-r`&&this.#in()};this.#He=consumer,this.#kt(),this.#ce=consumer,this.#Ct()}#dt(){this.#He!==void 0&&(this.#ce===this.#He&&this.#wt(),this.#He=void 0)}#ft(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e),startedAtMs:Date.now()}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis),startedAtMs:Date.now()};if(this.#Ae!==void 0){this.#Ae.status=t,t===void 0&&(this.#Ae.preview=void 0),this.#in();return}if(!(this.#F||this.#H)){if(t===void 0){this.#U={kind:`idle`},this.#K=void 0,this.#It(),this.#in();return}this.#bt(),this.#Ft(),this.#K=t.text,this.#in()}}#pt(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#Ae;if(r!==void 0){if(r.preview=void 0,t===`warning`||t===`error`)for(let e of r.outputBuffer)r.lines.push({text:e,tone:`info`,evidence:!0});r.outputBuffer=[],r.lines.push({text:n,tone:t}),this.#in();return}this.#bt(),this.#Lt({kind:`flow`,title:t,body:n,live:!1}),this.#in()}#mt(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#Ae;if(n===void 0){this.#pt(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#in()}async#ht(e){this.#le=``,this.#kt(),this.#Ve=void 0,this.#dt(),this.#wt(),this.#It(),this.#n.clear(),this.#n.showCursor(),this.#En(),this.#e.isTTY&&this.#e.setRawMode?.(!1),this.#e.pause();try{return await e()}finally{this.#e.isTTY&&this.#e.setRawMode?.(!0),this.#e.resume(),this.#le=``,this.#kt(),this.#n.hideCursor(),this.#Tn(),this.#Ae!==void 0&&(this.#Pt(),this.#ut()),this.#n.reset(),this.#in()}}setSessionId(e){this.#Le=e}shutdown(){if(this.#St(),this.#Y&&!this.#X){this.#X=!0;let e=this.#Le===void 0?``:` ${this.#i.glyph.dot} session ${this.#Le}`;this.#t.write(`${this.#i.colors.dim(`${eveVersionTag()}${e}`)}\n`)}}requestInterrupt(){this.#Z=!0,this.#Ae!==void 0&&this.#ce?.({type:`ctrl-c`}),this.#pe?.(),this.#St()}exitRequested(){return this.#Q}#gt(){this.#Q=!0,this.#ee?.()}async#_t(e){if(this.#Ue!==void 0||!this.#J)return;let t=new TraceViewerSession({...e,theme:this.#i,dimensions:()=>({width:this.#Cn(),height:this.#wn()}),paint:e=>this.#r.paint(e,this.#wn()),tracingDisabled:process.env.EVE_TRACES===`off`,copyText:e=>copyTextToClipboard(e,e=>this.#r.writeRaw(e)),terminalBackground:this.#We});this.#Ue=t,this.#r.enter(),this.#i.color&&this.#r.writeRaw(BACKGROUND_COLOR_QUERY),await new Promise(e=>{this.#yt=e,this.#ce=e=>{t.handleKey(e)===`close`&&this.#vt()},this.#Ct(),t.start()})}#vt(){let e=this.#Ue;if(e===void 0)return;this.#Ue=void 0,e.dispose(),this.#wt(),this.#r.exit(),this.#n.hideCursor(),this.#in(),this.#n.showCursor();let t=this.#yt;this.#yt=void 0,t?.()}#yt;#bt(e){this.#q=e?.title??this.#q,e?.contextSize!==void 0&&(this.#ve=e.contextSize),!this.#J&&(this.#J=!0,this.#Y=!0,this.#n.reset(),this.#n.hideCursor(),this.#Tn(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#fe=()=>this.#in(),this.#t.on(`resize`,this.#fe),process.on(`exit`,this.#xt))}#xt=()=>{this.#J&&(this.#r.exit(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1)),this.#n.showCursor())};#St(){this.#vt();let e=this.#W;if(this.#W=void 0,e?.(interruptedError()),this.#wt(),this.#Mt(),this.#It(),this.#oe!==void 0&&(clearTimeout(this.#oe),this.#oe=void 0),this.#se=!1,this.#J){this.#Pn();for(let e of this.#m)e.kind===`log`&&e.id===void 0&&(e.live=!1);this.#in(),this.#n.clear(),this.#n.showCursor(),this.#En(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#fe&&=(this.#t.off(`resize`,this.#fe),void 0),process.off(`exit`,this.#xt),this.#J=!1}}#Ct(){this.#e.off(`data`,this.#Tt),this.#e.on(`data`,this.#Tt),this.#le.length>0&&queueMicrotask(()=>{this.#ce!==void 0&&this.#le.length>0&&(this.#Dt(),this.#Et())})}#wt(){this.#e.off(`data`,this.#Tt),this.#kt(),this.#ce=void 0}#Tt=e=>{this.#kt(),this.#le+=this.#ue.write(e),this.#Dt(),this.#Et()};#Et(){if(this.#le===`\x1B`){this.#de=setTimeout(()=>{this.#le===`\x1B`&&(this.#le=``,this.#ce?.({type:`escape`}))},30),this.#de.unref?.();return}if(isIncompletePaste(this.#le)){let e=this.#le;this.#de=setTimeout(()=>{if(this.#le!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#le=``,t.length>0&&this.#ce?.({type:`text`,value:t,framing:`bracketed-paste`})},incompletePasteFlushMs),this.#de.unref?.();return}if(isIncompleteOsc(this.#le)){let e=this.#le;this.#de=setTimeout(()=>{this.#le===e&&(this.#le=``)},incompletePasteFlushMs),this.#de.unref?.()}}#Dt(){for(;this.#le.length>0;){let e=nextKey(this.#le);if(e.incomplete)return;if(this.#le=this.#le.slice(e.consumed),!(e.key===void 0||e.key.type===`ignore`)){if(e.key.type===`osc`){this.#Ot(e.key.value);continue}this.#ce?.(e.key)}}}#Ot(e){let t=parseBackgroundColorReply(e);t!==void 0&&(this.#We=t,this.#Ue?.setTerminalBackground(t))}#kt(){this.#de&&=(clearTimeout(this.#de),void 0)}#At(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#in();break;case`enter`:{let e=this.#V.text;if(e.trim().length===0)break;if(parsePromptCommand(e)?.type===`cancel`&&this.#Fe!==void 0){this.#V=EMPTY_LINE,this.#Pe.requestCancellation(),this.#ze=!0,this.renderCommandInvocation(e.trim()),this.renderCommandResult(`Turn cancellation requested.`),this.#Fe(),this.#in();break}this.#Pe.enqueue(e)&&(this.#V=EMPTY_LINE),this.#in();break}case`ctrl-c`:case`escape`:if(this.#Pe.idle&&this.#Fe===void 0)break;this.#Pe.handleEscape(),this.#ze=!0,this.#Fe?.(),this.#in();break;default:{let t=applyLineEditorKey(this.#V,e,{multiline:!0});t!==void 0&&(this.#V=t,this.#in());break}}}#jt(){this.#Mt(),this.#Nt(),this.#ie=setInterval(()=>{this.#te=!this.#te,this.#in()},500),this.#ie.unref?.()}#Mt(){this.#ie&&=(clearInterval(this.#ie),void 0),this.#te=!0}#Nt(){this.#te=!0}#Pt(){this.#It(),this.#ae=setInterval(()=>{this.#ne+=1,this.#in()},90),this.#ae.unref?.()}#Ft(){let e=Date.now();this.#re=e,this.#U={kind:`waiting`,startedAtMs:e},this.#Pt()}#It(){this.#ae&&=(clearInterval(this.#ae),void 0)}#Lt(e){e.id!==this.#Ee?.id&&this.#Pn(),e.updateSeq=++this.#b,this.#m.push(e),e.id&&this.#h.set(e.id,e)}#Rt(e){this.#z=!0,this.#Lt({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#in()}#zt(){let e=this.#B.settle();if(e===void 0||e.elapsedMs<=1e4&&e.inputTokens<=2e4)return;let t=`Done in ${this.#gn(e.elapsedMs)}`,n=this.#_e??0;if(this.#ve!==void 0&&this.#ve>0&&n>0){let e=Math.round(n/this.#ve*100);t+=` ${this.#i.glyph.dot} ${e}% context`}this.#Lt({kind:`turn-stats`,body:t,live:!1})}#Bt(e){if(e==null)return;let t=this.#Re;if(this.#Re=void 0,this.#Oe===e){this.#Oe=void 0;return}let n={kind:`user`,body:stripTerminalControls(e),live:!1};t!==void 0&&(n.promptOrigin=t),this.#Lt(n)}#Vt(e,t,n={}){let r=stripTerminalControls(e),i=stripTerminalControls(t),a=n.detail===void 0?void 0:stripTerminalControls(n.detail),o=n.hint===void 0?void 0:stripTerminalControls(n.hint),s={source:`workflow`,summary:`${r}: ${i}`,detail:a??i};this.#d?.append(o===void 0?s:{...s,hint:o});let c={kind:`error`,title:r,body:i,live:!1};o!==void 0&&(c.hint=o),a!==void 0&&(c.detail=this.#d===void 0?a:`details: ${this.#d.displayPath}`),this.#Lt(c),this.#in()}#Ht(e,t){if(this.#C.has(e))return;this.#C.add(e);let n=stripTerminalControls(t),r=this.#x.get(n)??[];if(r.push(e),this.#x.set(n,r),r.length===2){let e=this.#h.get(subagentHeaderId(r[0]));e!==void 0&&(e.subtitle=`#1`)}let i={id:subagentHeaderId(e),kind:`subagent`,subagentCallId:e,title:n,live:!0};r.length>1&&(i.subtitle=`#${r.length}`),this.#Lt(i)}#Ut(e){if(e.id&&this.#g.has(e.id))return;let t=e.id?this.#h.get(e.id):void 0;if(t){Object.assign(t,e),t.updateSeq=++this.#b;return}this.#Lt(e)}#Wt(e){this.#m=this.#m.filter(t=>t.id!==e),this.#h.delete(e)}#Gt(){for(let e of this.#m)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#Kt(e,t,n){switch(e.type){case`step-finish`:this.#d?.recordStepUsage(e.usage),e.usage!==void 0&&this.#B.addUsage(e.usage),this.#$t(n),this.#rn(e.usage),this.#in();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);n.text.set(e.id,t),this.#qt(e.id,t,!0);break}case`assistant-complete`:{let t=n.text.get(e.id)??``,r=e.text!==void 0&&t.length===0?stripTerminalControls(e.text??``):t;n.text.set(e.id,r),this.#qt(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);if(n.reasoning.set(e.id,r),t.reasoning===`full`){this.#Jt(e.id,r,!0,t);break}break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;if(t.reasoning===`full`){this.#Jt(e.id,r,!1,t);break}break}case`tool-call-preparing`:if(t.tools===`hidden`||isPanelRoutedTool(e.toolName))break;this.#Yt({input:void 0,preparing:!0,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-call`:if(this.#d?.recordToolCall(e.toolName),t.tools===`hidden`)break;this.#Yt({input:e.input,status:`running`,toolCallId:e.toolCallId,toolName:e.toolName},t,n);break;case`tool-approval-request`:{if(t.tools===`hidden`)break;let r=n.tools.get(e.toolCallId);if(r===void 0)break;this.#Yt({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#nn(e.toolCallId,n);if(r===void 0)break;this.#Yt({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{let r=this.#nn(e.toolCallId,n);if(this.#d?.append({source:`tool`,summary:`${r?.toolName??e.toolCallId} failed`,detail:e.errorText}),t.tools===`hidden`||r===void 0)break;this.#Yt({...r,errorText:e.errorText,status:`error`},t,n);break}case`tool-rejected`:{if(t.tools===`hidden`)break;let r=this.#nn(e.toolCallId,n);if(r===void 0)break;this.#Yt({...r,errorText:e.reason,status:`denied`},t,n);break}case`error`:this.#Vt(`Error`,e.errorText,{detail:e.detail,hint:e.hint});break;case`turn-cancelled`:this.#Ie=!0,!this.#ze&&this.#Be!==void 0&&this.#V.text.length===0&&(this.#V=lineOf(this.#Be),this.renderNotice(`The turn was cancelled from outside this prompt — the message was restored to the input.`));break;case`finish`:this.#rn(e.usage),this.#in();break}}#qt(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#Ut({id:e,kind:`assistant`,body:r,live:n}),this.#in())}#Jt(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#Ut({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#in())}#Yt(e,t,n){if(n.tools.set(e.toolCallId,e),this.#v.has(e.toolCallId)||this.#en(e)||toolBaseName(e.toolName)===`ask_question`)return;let r=toolSectionId(e.toolCallId);this.#y.set(e.toolCallId,r);let i=this.#Xt(e);this.#Ut(renderNativeToolBlock(e,r,t.tools===`full`,i)),this.#tn(n),this.#in()}#Xt(e){e.output!==void 0&&this.#S.observeRead(e.output);let t={};this.#Zt(e.toolName)&&(t.isSubagent=!0);let n=readWriteFileInput(e.toolName,e.input);if(n===void 0)return t.isSubagent===!0?t:void 0;let r=this.#S.observeWrite({path:n.path,content:n.content,callId:e.toolCallId});r!==void 0&&(t.previousContent=r);let i=writeExistedFlag(e.output);return i!==void 0&&(t.existed=i),t}#Zt(e){let t=this.#w?.info?.subagents.local;if(t===void 0||t.length===0)return!1;let n=toolBaseName(e);return t.some(e=>e.name===n)}#Qt(){for(let e of this.#m)e.kind!==`tool`&&e.kind!==`subagent-tool`||e.status===`running`&&(e.status=`error`,e.result=`interrupted`,e.live=!1)}#$t(e){for(let[t,n]of e.tools){if(n.preparing!==!0)continue;e.tools.delete(t);let r=this.#y.get(t)??toolSectionId(t);this.#Wt(r),this.#y.delete(t)}}#en(e){let t=readTodoToolItems(e.toolName,e.input);if(t===void 0)return!1;if(t.length>0&&allTodoItemsSettled(t)){let e=JSON.stringify(t);this.#Ne!==e&&(this.#Ne=e,this.#Lt({kind:`todo-list`,body:renderFinishedTodoRows(t,this.#Cn(),this.#i).join(`
7
7
  `),live:!1})),this.#Me=void 0}else this.#Me=t.length>0?t:void 0,this.#Ne=void 0;return this.#in(),!0}#tn(e){let t=[];for(let n of e.tools.values()){if(this.#v.has(n.toolCallId))continue;let e=this.#y.get(n.toolCallId)??toolSectionId(n.toolCallId),r=this.#h.get(e);r?.kind===`tool`&&t.push({block:r,active:isActiveToolStatus(n.status)})}applyCohortLiveness(t)}#nn(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#y.get(e)??toolSectionId(e),i=this.#h.get(r);if(!(i===void 0||i.kind!==`tool`))return{errorText:i.status===`error`&&typeof i.result==`string`?i.result:void 0,input:i.toolInput,output:i.toolOutput,status:i.status??`running`,toolCallId:e,toolName:i.toolName??i.title??`tool`}}#rn(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#ge=(t??0)+(n??0)),this.#_e=t??this.#_e,this.#ye=n??this.#ye,this.#ye!=null&&this.#xe!==void 0){let e=(Date.now()-this.#xe)/1e3;e>0&&(this.#be=this.#ye/e)}}#in(){if(this.#J){if(this.#me){this.#he=!0;return}this.#me=!0;try{do this.#he=!1,this.#an();while(this.#he)}finally{this.#me=!1}}}#an(){if(!this.#J)return;if(this.#Ue!==void 0){this.#Ue.repaint();return}let e=this.#Cn(),t=this.#mn(e),n=Math.max(1,this.#wn()-t.length),r=[],i=this.#O,a=groupToolBlocksForDisplay(this.#m),o=0;for(;o<a.length&&a[o].display.live===!1;)o+=1;if(o>0){let e=new Set(a.slice(0,o).flatMap(e=>e.members));for(let t=this.#m.length-1;t>=0;--t)e.has(this.#m[t])&&this.#m.splice(t,1)}for(let t of a.slice(0,o)){for(let e of t.members)this.#_.push(e),e.id&&(this.#g.add(e.id),this.#h.delete(e.id));if(this.#In(t.display))continue;let n=this.#un(t.display,e,i);i=previousBlockOf(t.display),this.#O=i,r.push(...n),this.#D.push(...n)}let s=[];for(let{display:t}of a.slice(o)){if(this.#In(t))continue;let n=this.#un(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)s.push({block:t,row:n[e]})}let c=[...clipLiveRows(s.map(e=>e.row),n,e,this.#i),...t];r.length>0?this.#n.flush(r,c):this.#n.update(c)}#on(){if(!this.#J)return;let e=this.#Cn(),t=this.#mn(e),n=Math.max(1,this.#wn()-t.length),r=this.#O,i=[];for(let{display:t}of groupToolBlocksForDisplay(this.#m)){if(this.#In(t))continue;let n=this.#un(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#i),...t];this.#n.clearAll(),this.#n.flush([...this.#ln(),...this.#D],a)}logDisplayMode(){return this.#p}setLogDisplayMode(e){e!==this.#p&&(this.#p=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#cn(),this.#J&&this.#on())}flushDelayedDevBuildErrors(){let e=this.#Te;e!==void 0&&(this.#Te=void 0,this.#Lt({kind:`log`,title:`stderr`,body:e,live:!0}),this.#in())}#sn(){this.#se=!0,this.#oe!==void 0&&clearTimeout(this.#oe),this.#oe=setTimeout(()=>{this.#se=!1,this.#oe=void 0,this.#in()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#p)),this.#in()}#cn(){let e=this.#Cn();this.#D.length=0;let t;for(let{display:n}of groupToolBlocksForDisplay(this.#_,{logCoalescing:`runs`})){if(this.#In(n))continue;let r=this.#un(n,e,t);t=previousBlockOf(n),this.#D.push(...r)}this.#O=t}#ln(){let e=this.#w;if(e===void 0)return[];let t={name:e.name,theme:this.#i,width:this.#Cn()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#un(e,t,n){let r={activityPulse:this.#fn(this.#re,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#i,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#dn(){return this.#i.spinner[this.#ne%this.#i.spinner.length]??``}#fn(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#pn(e,t){return e.indicator.kind===`spinner`?{glyph:this.#dn(),color:`yellow`}:{glyph:this.#fn(e.indicator.startedAtMs,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#mn(e){let n=this.#i.colors,r=[``];if(this.#ke!==void 0)return r.push(...this.#ke(e),``),this.#bn(r,e),r;let a=this.#Ae;if(a!==void 0){let t=this.#pn(a,a.status),n;if(a.status!==void 0){let{startedAtMs:e,...r}=a.status,i=Date.now()-e,o=i>=5e3?` ${formatTurnDuration(i)}`:``;n={...r,text:`${r.text}${o}`,indicator:t}}let i;if(a.question!==void 0){let t=a.question(e);i={kind:`question`,rows:t},n!==void 0&&(i={kind:`question`,rows:t,status:n})}else n===void 0?i=a.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:a.preview,indicator:t}:(i={kind:`status`,status:n},a.preview!==void 0&&(i={kind:`status`,status:n,preview:a.preview}));let o={title:a.title,lines:a.hideLinesWhileQuestion===!0?[]:a.lines,content:i};return r.push(...renderFlowPanel(o,this.#i,e)),this.#xn(r,e),r}this.#je!==void 0&&r.push(...renderAttentionRows(this.#je,e,this.#i),``),this.#Me!==void 0&&r.push(...renderTodoPanelRows({items:this.#Me,width:e,theme:this.#i,working:this.#H||this.#U.kind===`waiting`,pulse:this.#fn(this.#re,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH)}),``);let o=renderMessageQueueRows({view:this.#Pe.view(),width:e,theme:this.#i,working:this.#H});if(o.length>0&&r.push(...o,``),this.#F){let i=this.#I===void 0?void 0:inlineCommandHint(this.#I);i===void 0&&this.#I!==void 0&&isTypeaheadOpen(this.#I)&&r.push(...renderCommandSuggestions(this.#I,this.#i,e)),this.#$&&r.push(clip(n.dim(`Press Ctrl+C again to exit`),e),``);let a=isPromptControlCommand(this.#M),o=i?n.dim(` ${i}`):``,s=[];this.#bn(s,e);let u=Math.max(1,this.#wn()-1-r.length-1-s.length),f={text:this.#M,cursor:this.#N,width:e,theme:this.#i,caretVisible:this.#te,isCommand:a,ghost:o,maxRows:u};return this.#L&&this.#M.length===0&&(f.placeholder=this.#z?``:promptPlaceholder(Date.now()-this.#R)),r.push(...promptInputRows(f)),r.push(...s),r}let s=this.#U.kind===`waiting`&&this.#K===void 0;if(this.#H||s){r.push(this.#hn(e)),this.#vn(r,e);let t=[];return this.#bn(t,e),!this.#H&&t.length>0&&r.push(``),r.push(...t),r}if(this.#V.text.length>0)return this.#yn(r,e,{inert:!1}),this.#bn(r,e),r;let u=this.#K??(this.#G.length>0?this.#G:`Ready`),f=this.#Sn(),p=n.dim(this.#i.glyph.dot),m=f?`${p} ${u} ${n.dim(this.#i.glyph.dot)} ${f}`:`${p} ${u}`;return r.push(clip(m,e)),this.#bn(r,e),r}#hn(e){let t=this.#i.colors,n=this.#fn(this.#re,this.#i.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),r=this.#U,i=this.#B.startedAtMs??this.#xe??(r.kind===`waiting`?r.startedAtMs:Date.now()),a=Date.now()-i,o=`${typewriterText(`Working for`,a,80)} ${this.#gn(a)}`;return clip(`${t.yellow(n)} ${t.dim(o)}`,e)}#gn(e){return`${formatTurnDuration(e)}${this.#_n()}`}#_n(){let{inputTokens:e,outputTokens:t}=this.#B.usage;return e===0&&t===0?``:` ${this.#i.glyph.dash.repeat(2)} ${formatTokenFlow({inputTokens:e,outputTokens:t},this.#i.glyph)}`}#vn(e,t){this.#H&&this.#yn(e,t,{inert:!0})}#yn(e,t,n){e.push(``);let r={text:this.#V.text,cursor:this.#V.cursor,width:t,theme:this.#i,caretVisible:!0,isCommand:!1,ghost:``,maxRows:4,inert:n.inert};n.inert&&this.#V.text.length===0&&(r.placeholder=``),e.push(...promptInputRows(r))}#bn(e,t){let n=this.#j===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#i,width:r};this.#se&&(i.logLevel=this.#p);let a=this.#w?.serverUrl;if(a!==void 0&&this.#j===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#w?.info?.agent.model;o?.id!==void 0&&(i.model=o.id),o?.reasoning!==void 0&&o.reasoning!==`provider-default`&&(i.reasoning=o.reasoning),readGatewayServiceTier(o?.providerOptions).kind===`priority`&&(i.fastMode=!0);let s=o?.endpoint;s!==void 0&&(i.endpoint=s),this.#A!==void 0&&(i.vercel=this.#A),this.#j!==void 0&&(i.remote=this.#j);let c=buildStatusLine(i);c!==void 0&&e.push(clip(`${n}${c}`,t))}#xn(e,t){if(this.#j===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#j,theme:this.#i,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Sn(){let e=this.#i.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#ge,outputTokens:this.#ye,tokensPerSecond:this.#be},this.#l);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#i.glyph.dot} `)):``}#Cn(){return Math.max(20,this.#t.columns||80)}#wn(){return Math.max(8,this.#t.rows||24)}#Tn(){if(this.#Se!==void 0||!this.#u)return;this.#Ce=``,this.#we=``;let capture=(e,t)=>{let n=e.write.bind(e);return e.write=((e,n,r)=>{let i=typeof n==`string`?n:void 0,a=typeof n==`function`?n:r;return this.#On(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#d?.subscribeLogRecords(e=>this.#Dn(e)),this.#Se=()=>{this.#d?.unsubscribeLogRecords(),e(),t()}}#En(){let e=this.#Se;e!==void 0&&(this.#Se=void 0,e(),this.#Ce.length>0&&(this.#d?.append({source:`stdout`,detail:this.#Ce}),this.#Fn(`stdout`)&&process.stdout.write(`${this.#Ce}\n`),this.#Ce=``),this.#we.length>0&&(this.#d?.append({source:`stderr`,detail:this.#we}),this.#Fn(`stderr`)&&process.stderr.write(`${this.#we}\n`),this.#we=``))}#Dn(e){let t=e.fields===void 0?``:` ${JSON.stringify(e.fields)}`;this.#An(`[eve:${e.namespace}] ${e.message}${t}`),this.#in()}#On(e,t){let n=(e===`stdout`?this.#Ce:this.#we)+t;if(e===`stdout`&&parseDevRebuildLogLine(n.trimEnd())!==void 0){this.#Ce=``,this.#d?.append({source:e,detail:n.trimEnd()}),this.#kn(n.trimEnd()),this.#in();return}let r=n.lastIndexOf(`
8
8
  `),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#Ce=i:this.#we=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(this.#d?.append({source:e,detail:a}),e===`stdout`?this.#kn(a):this.#An(a),this.#in())}#kn(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
@@ -10,7 +10,7 @@ export type { EveAgentStoreCallbacks, EveAgentStoreInit, EveAgentStoreSnapshot,
10
10
  export type { AgentInfoEntry, AgentInfoChannelEntry, AgentInfoChannels, AgentInfoConnectionEntry, AgentInfoDynamicResolverEntry, AgentInfoFrameworkChannelEntry, AgentInfoFrameworkToolEntry, AgentInfoHookEntry, AgentInfoInstructions, AgentInfoInstructionsEntry, AgentInfoResult, AgentInfoSandboxEntry, AgentInfoScheduleEntry, AgentInfoSkillEntry, AgentInfoSource, AgentInfoSubagentEntry, AgentInfoToolEntry, AgentInfoTools, CancelSessionResult, ClearResult, CompactResult, ClientAuth, ClientOptions, ClientRedirectPolicy, HeadersValue, HealthResult, MessageResult, ResetResult, ResolvedStreamReconnectPolicy, SendTurnInput, SendTurnPayload, SessionSnapshot, SessionState, StreamOptions, StreamReconnectPolicy, StreamReconnectRetryPolicy, TokenValue, } from "#client/types.js";
11
11
  export type { EveAgentReducer, EveAgentReducerEvent, ClientInputRespondedEvent, ClientMessageFailedEvent, ClientMessageSubmittedEvent, } from "#client/reducer.js";
12
12
  export type { EveAuthorizationChallenge, EveAuthorizationOutcome, EveAuthorizationPart, EveMessageData, EveDynamicToolPart, EveMessageInputRequest, EveMessage, EveMessageMetadata, EveMessagePart, EveMessageToolMetadata, } from "#client/message-reducer.js";
13
- export type { ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, AuthorizationOutcome, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, MessageStreamEventMeta, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedPart, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, MessageStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCancelledStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
13
+ export type { ActionPartialStreamEvent, ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, AuthorizationOutcome, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, MessageStreamEventMeta, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedPart, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, MessageStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCancelledStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
14
14
  export { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
15
15
  export type { InputOption, InputRequest, InputRequestKind, InputResponse, } from "#runtime/input/types.js";
16
16
  export { inputOptionSchema, inputRequestKindSchema, inputRequestSchema, inputResponseSchema, isInputRequest, isInputResponse, } from "#runtime/input/types.js";
@@ -108,6 +108,8 @@ export type EveAuthorizationPart = {
108
108
  * `"output-available"`, `"output-error"` (`errorText` set), or `"output-denied"`
109
109
  * (`approval.approved` is `false`). Which of `input`, `output`, `errorText`, and
110
110
  * `approval` are present depends on `state`, so narrow on `state` before reading them.
111
+ * Preliminary generator output uses `"output-available"` with `partial: true`;
112
+ * the terminal tool result clears that flag.
111
113
  * `toolName` and `toolMetadata.eve` ({@link EveMessageToolMetadata}) record call identity.
112
114
  */
113
115
  export type EveDynamicToolPart = {
@@ -160,6 +162,7 @@ export type EveDynamicToolPart = {
160
162
  readonly errorText?: never;
161
163
  readonly input: unknown;
162
164
  readonly output: unknown;
165
+ readonly partial?: true;
163
166
  readonly state: "output-available";
164
167
  } | {
165
168
  readonly approval?: {
@@ -1 +1 @@
1
- import{createAuthorizationCompletedPart,createAuthorizationRequiredPart}from"#client/authorization-message-parts.js";import{approvedApproval,createToolMetadata,mergeToolMetadata,normalizeActionRequest,normalizeActionResult,stringifyUnknown,toMessageInputRequest}from"#client/message-action-parts.js";function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,s){switch(s.type){case`client.message.submitted`:return upsertMessage(e,{id:optimisticUserMessageId(s.data.submissionId),metadata:{optimistic:!0,status:`submitted`},parts:[{type:`text`,text:s.data.message}],role:`user`});case`client.message.failed`:return upsertMessage(e,{id:optimisticUserMessageId(s.data.submissionId),metadata:{optimistic:!0,status:`failed`},parts:[{type:`text`,text:s.data.message}],role:`user`});case`client.input.responded`:{let t=e;for(let e of s.data.responses)t=respondToInputRequest(t,e);return t}case`message.received`:return upsertMessage(e,{id:`${s.data.turnId}:user`,metadata:{status:`complete`,turnId:s.data.turnId},parts:projectReceivedParts(s.data.parts,s.data.message),role:`user`});case`step.started`:return updateAssistantMessage(e,s.data.turnId,e=>ensureStepStartPart(e,s.data.stepIndex));case`reasoning.appended`:return updateAssistantMessage(e,s.data.turnId,e=>upsertRun(ensureStepStartPart(e,s.data.stepIndex),{state:`streaming`,stepIndex:s.data.stepIndex,text:s.data.reasoningSoFar,type:`reasoning`}));case`reasoning.completed`:return updateAssistantMessage(e,s.data.turnId,e=>upsertRun(ensureStepStartPart(e,s.data.stepIndex),{state:`done`,stepIndex:s.data.stepIndex,text:s.data.reasoning,type:`reasoning`}));case`actions.requested`:{let t=e;for(let e of s.data.actions){let n=normalizeActionRequest(e);t=updateAssistantMessage(t,s.data.turnId,t=>upsertPart(ensureStepStartPart(t,s.data.stepIndex),{input:`input`in e?e.input:void 0,state:`input-available`,stepIndex:s.data.stepIndex,toolCallId:e.callId,toolMetadata:createToolMetadata(n),toolName:n.toolName,type:`dynamic-tool`}))}return t}case`input.requested`:{let t=e;for(let e of s.data.requests){let n=normalizeActionRequest(e.action);t=updateAssistantMessage(t,s.data.turnId,t=>upsertPart(ensureStepStartPart(t,s.data.stepIndex),{approval:{id:e.requestId},input:e.action.input,state:`approval-requested`,stepIndex:s.data.stepIndex,toolCallId:e.action.callId,toolMetadata:createToolMetadata(n,{inputRequest:toMessageInputRequest(e)}),toolName:n.toolName,type:`dynamic-tool`}))}return t}case`action.result`:{let t=normalizeActionResult(s.data.result),a=findToolPart(e,s.data.result.callId),o=s.data.error?.code===`TOOL_EXECUTION_DENIED`,c=s.data.status===`failed`&&!o,l=a?.approval?.id??s.data.result.callId,u=mergeToolMetadata(a?.toolMetadata,createToolMetadata(t)),d={input:a?.input,stepIndex:s.data.stepIndex,toolCallId:s.data.result.callId,toolMetadata:u,toolName:a?.toolName??t.toolName,type:`dynamic-tool`},f;return f=o?{...d,approval:{approved:!1,id:l,reason:s.data.error?.message},state:`output-denied`}:c?{...d,approval:approvedApproval(a),errorText:s.data.error?.message??stringifyUnknown(s.data.result.output),state:`output-error`}:{...d,approval:approvedApproval(a),output:s.data.result.output,state:`output-available`},a===void 0?updateAssistantMessage(e,s.data.turnId,e=>upsertPart(ensureStepStartPart(e,s.data.stepIndex),f)):updateToolPart(e,s.data.result.callId,f)}case`authorization.required`:return updateAssistantMessage(e,s.data.turnId,e=>upsertPart(ensureStepStartPart(e,s.data.stepIndex),createAuthorizationRequiredPart(s)));case`authorization.completed`:return completeAuthorization(e,s);case`message.appended`:return updateAssistantMessage(e,s.data.turnId,e=>upsertRun(ensureStepStartPart(e,s.data.stepIndex),{state:`streaming`,stepIndex:s.data.stepIndex,text:s.data.messageSoFar,type:`text`}));case`message.completed`:return updateAssistantMessage(e,s.data.turnId,e=>s.data.message===null?removeTextPart(e,s.data.stepIndex):upsertRun(ensureStepStartPart(e,s.data.stepIndex),{state:`done`,stepIndex:s.data.stepIndex,text:s.data.message,type:`text`}));case`result.completed`:return updateAssistantMetadata(e,s.data.turnId,{result:s.data.result});case`turn.completed`:return updateAssistantMetadata(e,s.data.turnId,{status:`complete`});case`turn.cancelled`:return updateAssistantMessage(e,s.data.turnId,e=>({...e,metadata:{...e.metadata,status:`complete`},parts:e.parts.map(e=>(e.type===`text`||e.type===`reasoning`)&&e.state===`streaming`?{...e,state:`done`}:e)}));case`turn.failed`:case`session.failed`:return e;default:return e}}function respondToInputRequest(e,t){let n=findToolPartByApprovalId(e,t.requestId);if(!n)return e;let r={id:t.requestId};return t.text!==void 0&&(r.reason=t.text),updateToolPart(e,n.toolCallId,{approval:r,input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:mergeToolMetadata(n.toolMetadata,{eve:{inputResponse:t,kind:n.toolMetadata?.eve?.kind??`unknown`,name:n.toolMetadata?.eve?.name??n.toolName}}),toolName:n.toolName,type:`dynamic-tool`})}function updateAssistantMessage(e,t,n){return upsertMessage(e,n(e.messages.find(e=>e.role===`assistant`&&e.metadata?.turnId===t)??createAssistantMessage(t)))}function updateAssistantMetadata(e,t,n){return updateAssistantMessage(e,t,e=>({...e,metadata:{...e.metadata,...n}}))}function createAssistantMessage(e){return{id:`${e}:assistant`,metadata:{status:`streaming`,turnId:e},parts:[],role:`assistant`}}function ensureStepStartPart(e,t){let n=e.parts.filter(e=>e.type===`step-start`).length;if(n>t)return e;let r=t-n+1;return{...e,parts:[...e.parts,...Array.from({length:r},()=>({type:`step-start`}))]}}function upsertPart(e,t){let n=e.parts.findIndex(e=>partKey(e)===partKey(t)),r=n===-1?[...e.parts,t]:[...e.parts.slice(0,n),t,...e.parts.slice(n+1)];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function upsertRun(e,t){let n=-1;for(let r=e.parts.length-1;r>=0;--r){let i=e.parts[r];if(i?.type===t.type&&i.stepIndex===t.stepIndex){n=r;break}}let r=n!==-1&&e.parts[n].state===`streaming`?[...e.parts.slice(0,n),t,...e.parts.slice(n+1)]:[...e.parts,t];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function removeTextPart(e,t){let n=e.parts.filter(e=>e.type!==`text`||e.stepIndex!==t);return n.length===e.parts.length?e:{...e,metadata:{...e.metadata,status:`complete`},parts:n}}function updateToolPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`dynamic-tool`&&e.toolCallId===t));return r?upsertMessage(e,upsertPart(r,n)):e}function completeAuthorization(t,n){let r=findLatestPendingAuthorizationPart(t,n.data.name),i=createAuthorizationCompletedPart(n,r);return r===void 0?updateAssistantMessage(t,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),i)):updateAuthorizationPart(t,r,i)}function updateAuthorizationPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e===t));return r?upsertMessage(e,upsertPart(r,n)):e}function findToolPart(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.toolCallId===t)return e}function findLatestPendingAuthorizationPart(e,t){for(let n=e.messages.length-1;n>=0;--n){let r=e.messages[n];if(r?.role===`assistant`)for(let e=r.parts.length-1;e>=0;--e){let n=r.parts[e];if(n?.type===`authorization`&&n.state===`required`&&n.name===t)return n}}}function findToolPartByApprovalId(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.approval?.id===t)return e}function projectReceivedParts(e,t){return e?.map(e=>e.type===`text`?{state:`done`,text:e.text,type:`text`}:{filename:e.filename,mediaType:e.mediaType,size:e.size,type:`file`,url:e.url})??[{state:`done`,text:t,type:`text`}]}function partKey(e){switch(e.type){case`text`:return`text:${e.stepIndex??0}`;case`reasoning`:return`reasoning:${e.stepIndex??0}`;case`file`:return`file:${e.stepIndex??0}:${e.filename??e.url??e.mediaType}`;case`step-start`:return`step-start`;case`authorization`:return`authorization:${e.turnId}:${e.stepIndex}:${e.name}`;case`dynamic-tool`:return`dynamic-tool:${e.toolCallId}`}}function upsertMessage(e,t){let n=e.messages.findIndex(e=>e.id===t.id);return n===-1?{messages:[...e.messages,t]}:{messages:[...e.messages.slice(0,n),t,...e.messages.slice(n+1)]}}function optimisticUserMessageId(e){return`optimistic:${e}:user`}export{defaultMessageReducer};
1
+ import{createAuthorizationCompletedPart,createAuthorizationRequiredPart}from"#client/authorization-message-parts.js";import{approvedApproval,createToolMetadata,mergeToolMetadata,normalizeActionRequest,normalizeActionResult,stringifyUnknown,toMessageInputRequest}from"#client/message-action-parts.js";function defaultMessageReducer(){return{initial(){return{messages:[]}},reduce(e,t){return reduceMessageData(e,t)}}}function reduceMessageData(e,c){switch(c.type){case`client.message.submitted`:return upsertMessage(e,{id:optimisticUserMessageId(c.data.submissionId),metadata:{optimistic:!0,status:`submitted`},parts:[{type:`text`,text:c.data.message}],role:`user`});case`client.message.failed`:return upsertMessage(e,{id:optimisticUserMessageId(c.data.submissionId),metadata:{optimistic:!0,status:`failed`},parts:[{type:`text`,text:c.data.message}],role:`user`});case`client.input.responded`:{let t=e;for(let e of c.data.responses)t=respondToInputRequest(t,e);return t}case`message.received`:return upsertMessage(e,{id:`${c.data.turnId}:user`,metadata:{status:`complete`,turnId:c.data.turnId},parts:projectReceivedParts(c.data.parts,c.data.message),role:`user`});case`step.started`:return updateAssistantMessage(e,c.data.turnId,e=>ensureStepStartPart(e,c.data.stepIndex));case`reasoning.appended`:return updateAssistantMessage(e,c.data.turnId,e=>upsertRun(ensureStepStartPart(e,c.data.stepIndex),{state:`streaming`,stepIndex:c.data.stepIndex,text:c.data.reasoningSoFar,type:`reasoning`}));case`reasoning.completed`:return updateAssistantMessage(e,c.data.turnId,e=>upsertRun(ensureStepStartPart(e,c.data.stepIndex),{state:`done`,stepIndex:c.data.stepIndex,text:c.data.reasoning,type:`reasoning`}));case`actions.requested`:{let t=e;for(let e of c.data.actions){let n=normalizeActionRequest(e);t=updateAssistantMessage(t,c.data.turnId,t=>upsertPart(ensureStepStartPart(t,c.data.stepIndex),{input:`input`in e?e.input:void 0,state:`input-available`,stepIndex:c.data.stepIndex,toolCallId:e.callId,toolMetadata:createToolMetadata(n),toolName:n.toolName,type:`dynamic-tool`}))}return t}case`input.requested`:{let t=e;for(let e of c.data.requests){let n=normalizeActionRequest(e.action);t=updateAssistantMessage(t,c.data.turnId,t=>upsertPart(ensureStepStartPart(t,c.data.stepIndex),{approval:{id:e.requestId},input:e.action.input,state:`approval-requested`,stepIndex:c.data.stepIndex,toolCallId:e.action.callId,toolMetadata:createToolMetadata(n,{inputRequest:toMessageInputRequest(e)}),toolName:n.toolName,type:`dynamic-tool`}))}return t}case`action.result`:{let t=normalizeActionResult(c.data.result),a=findToolPart(e,c.data.result.callId),s=c.data.error?.code===`TOOL_EXECUTION_DENIED`,l=c.data.status===`failed`&&!s,u=a?.approval?.id??c.data.result.callId,d=mergeToolMetadata(a?.toolMetadata,createToolMetadata(t)),f={input:a?.input,stepIndex:c.data.stepIndex,toolCallId:c.data.result.callId,toolMetadata:d,toolName:a?.toolName??t.toolName,type:`dynamic-tool`},p;return p=s?{...f,approval:{approved:!1,id:u,reason:c.data.error?.message},state:`output-denied`}:l?{...f,approval:approvedApproval(a),errorText:c.data.error?.message??stringifyUnknown(c.data.result.output),state:`output-error`}:{...f,approval:approvedApproval(a),output:c.data.result.output,state:`output-available`},a===void 0?updateAssistantMessage(e,c.data.turnId,e=>upsertPart(ensureStepStartPart(e,c.data.stepIndex),p)):updateToolPart(e,c.data.result.callId,p)}case`action.partial`:{let t=findToolPart(e,c.data.result.callId);if(t!==void 0&&isSettledToolPart(t))return e;let a=normalizeActionResult(c.data.result),o={approval:approvedApproval(t),input:t?.input,output:c.data.result.output,partial:!0,state:`output-available`,stepIndex:c.data.stepIndex,toolCallId:c.data.result.callId,toolMetadata:mergeToolMetadata(t?.toolMetadata,createToolMetadata(a)),toolName:t?.toolName??a.toolName,type:`dynamic-tool`};return t===void 0?updateAssistantMessage(e,c.data.turnId,e=>upsertPart(ensureStepStartPart(e,c.data.stepIndex),o)):updateToolPart(e,c.data.result.callId,o)}case`authorization.required`:return updateAssistantMessage(e,c.data.turnId,e=>upsertPart(ensureStepStartPart(e,c.data.stepIndex),createAuthorizationRequiredPart(c)));case`authorization.completed`:return completeAuthorization(e,c);case`message.appended`:return updateAssistantMessage(e,c.data.turnId,e=>upsertRun(ensureStepStartPart(e,c.data.stepIndex),{state:`streaming`,stepIndex:c.data.stepIndex,text:c.data.messageSoFar,type:`text`}));case`message.completed`:return updateAssistantMessage(e,c.data.turnId,e=>c.data.message===null?removeTextPart(e,c.data.stepIndex):upsertRun(ensureStepStartPart(e,c.data.stepIndex),{state:`done`,stepIndex:c.data.stepIndex,text:c.data.message,type:`text`}));case`result.completed`:return updateAssistantMetadata(e,c.data.turnId,{result:c.data.result});case`turn.completed`:return updateAssistantMetadata(e,c.data.turnId,{status:`complete`});case`turn.cancelled`:return updateAssistantMessage(e,c.data.turnId,e=>({...e,metadata:{...e.metadata,status:`complete`},parts:e.parts.map(e=>(e.type===`text`||e.type===`reasoning`)&&e.state===`streaming`?{...e,state:`done`}:e)}));case`turn.failed`:case`session.failed`:return e;default:return e}}function respondToInputRequest(e,t){let n=findToolPartByApprovalId(e,t.requestId);if(!n)return e;let r={id:t.requestId};return t.text!==void 0&&(r.reason=t.text),updateToolPart(e,n.toolCallId,{approval:r,input:n.input,state:`approval-responded`,stepIndex:n.stepIndex,toolCallId:n.toolCallId,toolMetadata:mergeToolMetadata(n.toolMetadata,{eve:{inputResponse:t,kind:n.toolMetadata?.eve?.kind??`unknown`,name:n.toolMetadata?.eve?.name??n.toolName}}),toolName:n.toolName,type:`dynamic-tool`})}function updateAssistantMessage(e,t,n){return upsertMessage(e,n(e.messages.find(e=>e.role===`assistant`&&e.metadata?.turnId===t)??createAssistantMessage(t)))}function updateAssistantMetadata(e,t,n){return updateAssistantMessage(e,t,e=>({...e,metadata:{...e.metadata,...n}}))}function createAssistantMessage(e){return{id:`${e}:assistant`,metadata:{status:`streaming`,turnId:e},parts:[],role:`assistant`}}function ensureStepStartPart(e,t){let n=e.parts.filter(e=>e.type===`step-start`).length;if(n>t)return e;let r=t-n+1;return{...e,parts:[...e.parts,...Array.from({length:r},()=>({type:`step-start`}))]}}function upsertPart(e,t){let n=e.parts.findIndex(e=>partKey(e)===partKey(t)),r=n===-1?[...e.parts,t]:[...e.parts.slice(0,n),t,...e.parts.slice(n+1)];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function upsertRun(e,t){let n=-1;for(let r=e.parts.length-1;r>=0;--r){let i=e.parts[r];if(i?.type===t.type&&i.stepIndex===t.stepIndex){n=r;break}}let r=n!==-1&&e.parts[n].state===`streaming`?[...e.parts.slice(0,n),t,...e.parts.slice(n+1)]:[...e.parts,t];return{...e,metadata:{...e.metadata,status:t.type===`text`&&t.state===`done`?`complete`:`streaming`},parts:r}}function removeTextPart(e,t){let n=e.parts.filter(e=>e.type!==`text`||e.stepIndex!==t);return n.length===e.parts.length?e:{...e,metadata:{...e.metadata,status:`complete`},parts:n}}function updateToolPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`dynamic-tool`&&e.toolCallId===t));return r?upsertMessage(e,upsertPart(r,n)):e}function completeAuthorization(t,n){let r=findLatestPendingAuthorizationPart(t,n.data.name),i=createAuthorizationCompletedPart(n,r);return r===void 0?updateAssistantMessage(t,n.data.turnId,e=>upsertPart(ensureStepStartPart(e,n.data.stepIndex),i)):updateAuthorizationPart(t,r,i)}function updateAuthorizationPart(e,t,n){let r=e.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e===t));return r?upsertMessage(e,upsertPart(r,n)):e}function findToolPart(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.toolCallId===t)return e}function isSettledToolPart(e){return e.state===`output-denied`||e.state===`output-error`||e.state===`output-available`&&e.partial!==!0}function findLatestPendingAuthorizationPart(e,t){for(let n=e.messages.length-1;n>=0;--n){let r=e.messages[n];if(r?.role===`assistant`)for(let e=r.parts.length-1;e>=0;--e){let n=r.parts[e];if(n?.type===`authorization`&&n.state===`required`&&n.name===t)return n}}}function findToolPartByApprovalId(e,t){for(let n of e.messages)for(let e of n.parts)if(e.type===`dynamic-tool`&&e.approval?.id===t)return e}function projectReceivedParts(e,t){return e?.map(e=>e.type===`text`?{state:`done`,text:e.text,type:`text`}:{filename:e.filename,mediaType:e.mediaType,size:e.size,type:`file`,url:e.url})??[{state:`done`,text:t,type:`text`}]}function partKey(e){switch(e.type){case`text`:return`text:${e.stepIndex??0}`;case`reasoning`:return`reasoning:${e.stepIndex??0}`;case`file`:return`file:${e.stepIndex??0}:${e.filename??e.url??e.mediaType}`;case`step-start`:return`step-start`;case`authorization`:return`authorization:${e.turnId}:${e.stepIndex}:${e.name}`;case`dynamic-tool`:return`dynamic-tool:${e.toolCallId}`}}function upsertMessage(e,t){let n=e.messages.findIndex(e=>e.id===t.id);return n===-1?{messages:[...e.messages,t]}:{messages:[...e.messages.slice(0,n),t,...e.messages.slice(n+1)]}}function optimisticUserMessageId(e){return`optimistic:${e}:user`}export{defaultMessageReducer};
@@ -11,13 +11,13 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
11
11
  readonly dropped: {};
12
12
  };
13
13
  readonly tool: {
14
- readonly current: 6;
15
- readonly supported: readonly [1, 2, 3, 4, 5, 6];
14
+ readonly current: 7;
15
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
16
16
  readonly dropped: {};
17
17
  };
18
18
  readonly dynamicTool: {
19
- readonly current: 9;
20
- readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9];
19
+ readonly current: 10;
20
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
21
21
  readonly dropped: {};
22
22
  };
23
23
  readonly connection: {
@@ -26,8 +26,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
26
26
  readonly dropped: {};
27
27
  };
28
28
  readonly hook: {
29
- readonly current: 7;
30
- readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
29
+ readonly current: 8;
30
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8];
31
31
  readonly dropped: {};
32
32
  };
33
33
  readonly skill: {
@@ -36,8 +36,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
36
36
  readonly dropped: {};
37
37
  };
38
38
  readonly dynamicSkill: {
39
- readonly current: 6;
40
- readonly supported: readonly [1, 2, 3, 4, 5, 6];
39
+ readonly current: 7;
40
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
41
41
  readonly dropped: {};
42
42
  };
43
43
  readonly instructions: {
@@ -46,8 +46,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
46
46
  readonly dropped: {};
47
47
  };
48
48
  readonly dynamicInstructions: {
49
- readonly current: 6;
50
- readonly supported: readonly [1, 2, 3, 4, 5, 6];
49
+ readonly current: 7;
50
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
51
51
  readonly dropped: {};
52
52
  };
53
53
  readonly config: {
@@ -1 +1 @@
1
- import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:6,supported:[1,2,3,4,5,6],dropped:{}},dynamicTool:{current:9,supported:[1,2,3,4,5,6,7,8,9],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:6,supported:[1,2,3,4,5,6],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:6,supported:[1,2,3,4,5,6],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:2,supported:[1,2],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(t){return parseExtensionCompatibilityManifest(await readFile(t,`utf8`),t)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
1
+ import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},dynamicTool:{current:10,supported:[1,2,3,4,5,6,7,8,9,10],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:8,supported:[1,2,3,4,5,6,7,8],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:2,supported:[1,2],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(t){return parseExtensionCompatibilityManifest(await readFile(t,`utf8`),t)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
@@ -31,4 +31,4 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";
31
31
  export declare function createToolExecuteWithAuth(input: {
32
32
  readonly scope: string;
33
33
  readonly execute: (toolInput: unknown, ctx: unknown) => unknown;
34
- }): (toolInput: unknown, options: ToolExecuteOptions) => Promise<unknown>;
34
+ }): (toolInput: unknown, options: ToolExecuteOptions) => Promise<unknown> | AsyncIterable<unknown>;
@@ -1 +1 @@
1
- import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{completeScopedAuthorization,evictScopedToken,resolveScopedToken,startScopedAuthorization}from"#runtime/connections/scoped-authorization.js";function createToolExecuteWithAuth(e){let{scope:t,execute:n}=e;return async(e,r)=>{let i=new Set;try{return await n(e,buildToolContext({inlineAuthState:{},justAuthorizedScopes:i,options:r,scope:t}))}catch(e){if(isToolAuthorizationRequiredError(e))return await handleAuthorizationRequests(e.requests);throw e}}}function buildToolContext(t){let{scope:n,justAuthorizedScopes:r,inlineAuthState:i}=t;return{...buildBaseToolContext({options:t.options,toolName:n}),async getToken(e,t){if(e===void 0)throw missingProviderError(`ctx.getToken`);return await resolveInlineToken({inlineAuthState:i,justAuthorizedScopes:r,options:t,provider:e,toolScope:n})},requireAuth(e,t){if(e===void 0)throw missingProviderError(`ctx.requireAuth`);let a=buildInlineScopedAuthorization({inlineAuthState:i,options:t,provider:e,toolScope:n});throw new ToolAuthorizationRequiredError([{justAuthorized:r.has(a.scope),scoped:a}])}}}async function resolveInlineToken(e){let{justAuthorizedScopes:t}=e,n=buildInlineScopedAuthorization(e);!t.has(n.scope)&&await completeScopedAuthorization(n)&&t.add(n.scope);try{return await resolveScopedToken(n)}catch(e){throw isConnectionAuthorizationRequiredError(e)?new ToolAuthorizationRequiredError([{cause:e,justAuthorized:t.has(n.scope),scoped:n}]):e}}async function handleAuthorizationRequests(e){let r=[],o;for(let i of e){let{scoped:e}=i;if(i.justAuthorized)throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" rejected the token immediately after authorization.`,reason:`token_rejected_after_authorization`,retryable:!1});await evictScopedToken(e);let s=await startScopedAuthorization(e);if(s!==void 0){r.push(...s.challenges);continue}if(supportsInteractiveAuthorization(e.authorization))throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" requires sign-in, but no authorization callback URL could be minted for this run (missing session context).`,reason:`authorization_callback_unavailable`,retryable:!1});o??=i.cause instanceof Error?i.cause:new ConnectionAuthorizationRequiredError(e.scope)}if(r.length>0)return requestAuthorization(r);throw o??Error(`Tool authorization is required.`)}function buildInlineScopedAuthorization(e){let t=normalizeInlineProvider(e.provider,e.options);return{authorization:t,connection:e.options?.connection??{url:``},scope:e.options?.authKey===void 0?deriveInlineScope({authorization:t,inlineAuthState:e.inlineAuthState,provider:e.provider,toolScope:e.toolScope}):validateInlineAuthKey(e.options.authKey)}}function normalizeInlineProvider(e,t){let n=normalizeAuthorizationSpec(e,`ctx.getToken:`,`provider`);if(t?.displayName===void 0)return n;if(t.displayName.length===0)throw Error(`ctx.getToken: The "options.displayName" field must be a non-empty string.`);return{...n,displayName:t.displayName}}function deriveInlineScope(e){let t=e.authorization.vercelConnect?.connector;if(t!==void 0)return`${e.toolScope}__${sanitizeScopeSegment(t)}`;if(e.inlineAuthState.anonymousProvider===void 0)e.inlineAuthState.anonymousProvider=e.provider;else if(e.inlineAuthState.anonymousProvider!==e.provider)throw Error(`ctx.getToken: Multiple inline auth providers without provider metadata need explicit auth keys. Pass options.authKey for each provider, for example ctx.getToken(auth, { authKey: "github" }).`);return`${e.toolScope}__inline_auth`}function validateInlineAuthKey(e){if(!/^[A-Za-z0-9_.:-]+$/u.test(e))throw Error(`ctx.getToken: The "options.authKey" field must contain only letters, digits, "_", "-", ".", or ":".`);return e}function sanitizeScopeSegment(e){let t=e.replace(/[^A-Za-z0-9_.:-]+/gu,`_`).replace(/^_+|_+$/gu,``);return t.length>0?t:`provider`}var ToolAuthorizationRequiredError=class extends Error{requests;constructor(e){super(`Tool authorization required.`),this.name=`ToolAuthorizationRequiredError`,this.requests=e}};function isToolAuthorizationRequiredError(e){return e instanceof Error&&e.name===`ToolAuthorizationRequiredError`}function missingProviderError(e){return Error(`${e}: Pass an auth provider, for example ${e}(connect("github/myagent")).`)}export{createToolExecuteWithAuth};
1
+ import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{ConnectionAuthorizationFailedError,ConnectionAuthorizationRequiredError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{normalizeAuthorizationSpec}from"#runtime/connections/validate-authorization.js";import{completeScopedAuthorization,evictScopedToken,resolveScopedToken,startScopedAuthorization}from"#runtime/connections/scoped-authorization.js";import{isAsyncIterable}from"#shared/async-iterable.js";function createToolExecuteWithAuth(e){let{scope:t,execute:n}=e;return(e,r)=>{let i=buildToolContext({inlineAuthState:{},justAuthorizedScopes:new Set,options:r,scope:t});try{let t=n(e,i);return isAsyncIterable(t)?handleToolIterableErrors(t):Promise.resolve(t).catch(handleToolError)}catch(e){return handleToolError(e)}async function handleToolError(e){if(isToolAuthorizationRequiredError(e))return await handleAuthorizationRequests(e.requests);throw e}async function*handleToolIterableErrors(e){try{for await(let t of e)yield t}catch(e){yield await handleToolError(e)}}}}function buildToolContext(t){let{scope:n,justAuthorizedScopes:r,inlineAuthState:i}=t;return{...buildBaseToolContext({options:t.options,toolName:n}),async getToken(e,t){if(e===void 0)throw missingProviderError(`ctx.getToken`);return await resolveInlineToken({inlineAuthState:i,justAuthorizedScopes:r,options:t,provider:e,toolScope:n})},requireAuth(e,t){if(e===void 0)throw missingProviderError(`ctx.requireAuth`);let a=buildInlineScopedAuthorization({inlineAuthState:i,options:t,provider:e,toolScope:n});throw new ToolAuthorizationRequiredError([{justAuthorized:r.has(a.scope),scoped:a}])}}}async function resolveInlineToken(e){let{justAuthorizedScopes:t}=e,n=buildInlineScopedAuthorization(e);!t.has(n.scope)&&await completeScopedAuthorization(n)&&t.add(n.scope);try{return await resolveScopedToken(n)}catch(e){throw isConnectionAuthorizationRequiredError(e)?new ToolAuthorizationRequiredError([{cause:e,justAuthorized:t.has(n.scope),scoped:n}]):e}}async function handleAuthorizationRequests(e){let r=[],o;for(let i of e){let{scoped:e}=i;if(i.justAuthorized)throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" rejected the token immediately after authorization.`,reason:`token_rejected_after_authorization`,retryable:!1});await evictScopedToken(e);let s=await startScopedAuthorization(e);if(s!==void 0){r.push(...s.challenges);continue}if(supportsInteractiveAuthorization(e.authorization))throw new ConnectionAuthorizationFailedError(e.scope,{message:`Tool "${e.scope}" requires sign-in, but no authorization callback URL could be minted for this run (missing session context).`,reason:`authorization_callback_unavailable`,retryable:!1});o??=i.cause instanceof Error?i.cause:new ConnectionAuthorizationRequiredError(e.scope)}if(r.length>0)return requestAuthorization(r);throw o??Error(`Tool authorization is required.`)}function buildInlineScopedAuthorization(e){let t=normalizeInlineProvider(e.provider,e.options);return{authorization:t,connection:e.options?.connection??{url:``},scope:e.options?.authKey===void 0?deriveInlineScope({authorization:t,inlineAuthState:e.inlineAuthState,provider:e.provider,toolScope:e.toolScope}):validateInlineAuthKey(e.options.authKey)}}function normalizeInlineProvider(e,t){let n=normalizeAuthorizationSpec(e,`ctx.getToken:`,`provider`);if(t?.displayName===void 0)return n;if(t.displayName.length===0)throw Error(`ctx.getToken: The "options.displayName" field must be a non-empty string.`);return{...n,displayName:t.displayName}}function deriveInlineScope(e){let t=e.authorization.vercelConnect?.connector;if(t!==void 0)return`${e.toolScope}__${sanitizeScopeSegment(t)}`;if(e.inlineAuthState.anonymousProvider===void 0)e.inlineAuthState.anonymousProvider=e.provider;else if(e.inlineAuthState.anonymousProvider!==e.provider)throw Error(`ctx.getToken: Multiple inline auth providers without provider metadata need explicit auth keys. Pass options.authKey for each provider, for example ctx.getToken(auth, { authKey: "github" }).`);return`${e.toolScope}__inline_auth`}function validateInlineAuthKey(e){if(!/^[A-Za-z0-9_.:-]+$/u.test(e))throw Error(`ctx.getToken: The "options.authKey" field must contain only letters, digits, "_", "-", ".", or ":".`);return e}function sanitizeScopeSegment(e){let t=e.replace(/[^A-Za-z0-9_.:-]+/gu,`_`).replace(/^_+|_+$/gu,``);return t.length>0?t:`provider`}var ToolAuthorizationRequiredError=class extends Error{requests;constructor(e){super(`Tool authorization required.`),this.name=`ToolAuthorizationRequiredError`,this.requests=e}};function isToolAuthorizationRequiredError(e){return e instanceof Error&&e.name===`ToolAuthorizationRequiredError`}function missingProviderError(e){return Error(`${e}: Pass an auth provider, for example ${e}(connect("github/myagent")).`)}export{createToolExecuteWithAuth};