eve 0.12.3 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/src/cli/commands/deploy.js +1 -1
- package/dist/src/cli/commands/init.js +1 -1
- package/dist/src/cli/commands/link.d.ts +2 -2
- package/dist/src/cli/commands/link.js +1 -1
- package/dist/src/cli/dev/tui/setup-flow.d.ts +5 -0
- package/dist/src/cli/dev/tui/setup-panel.d.ts +4 -1
- package/dist/src/cli/dev/tui/setup-panel.js +1 -1
- package/dist/src/cli/dev/tui/setup-selection-input.d.ts +2 -1
- package/dist/src/cli/dev/tui/setup-selection-input.js +2 -2
- package/dist/src/cli/dev/tui/terminal-renderer.js +2 -2
- package/dist/src/cli/dev/tui/tui-prompter.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +3 -2
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/session.d.ts +4 -10
- package/dist/src/execution/session.js +2 -2
- package/dist/src/execution/tool-auth.d.ts +16 -39
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/public/channels/github/api.d.ts +5 -0
- package/dist/src/public/channels/github/api.js +1 -1
- package/dist/src/public/channels/github/dispatch.js +1 -1
- package/dist/src/public/channels/github/pr-context.d.ts +10 -0
- package/dist/src/public/channels/github/pr-context.js +2 -2
- package/dist/src/public/definitions/tool.d.ts +3 -48
- package/dist/src/public/definitions/tool.js +1 -1
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/types.d.ts +0 -10
- package/dist/src/setup/boxes/link-project.d.ts +8 -14
- package/dist/src/setup/boxes/link-project.js +1 -1
- package/dist/src/setup/boxes/resolve-provisioning.d.ts +2 -1
- package/dist/src/setup/boxes/resolve-provisioning.js +1 -1
- package/dist/src/setup/cli/select-component.d.ts +7 -1
- package/dist/src/setup/cli/select-component.js +1 -1
- package/dist/src/setup/cli/select-option-codec.d.ts +1 -0
- package/dist/src/setup/cli/select-option-codec.js +1 -1
- package/dist/src/setup/cli/select-state.d.ts +14 -1
- package/dist/src/setup/cli/select-state.js +1 -1
- package/dist/src/setup/flows/model.d.ts +2 -2
- package/dist/src/setup/index.d.ts +1 -1
- package/dist/src/setup/package-manager.d.ts +2 -1
- package/dist/src/setup/package-manager.js +1 -1
- package/dist/src/setup/primitives/pm/index.d.ts +1 -1
- package/dist/src/setup/primitives/pm/pnpm.d.ts +11 -1
- package/dist/src/setup/primitives/pm/pnpm.js +5 -2
- package/dist/src/setup/primitives/pm/types.d.ts +10 -1
- package/dist/src/setup/project-resolution.d.ts +9 -6
- package/dist/src/setup/project-resolution.js +1 -1
- package/dist/src/setup/prompter.d.ts +13 -0
- package/dist/src/setup/prompter.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.d.ts +8 -0
- package/dist/src/setup/scaffold/create/project.js +8 -7
- package/dist/src/setup/scaffold/update/channels.d.ts +8 -0
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/package-json.d.ts +3 -0
- package/dist/src/setup/scaffold/update/package-json.js +1 -1
- package/dist/src/setup/scaffold/workspace-glob.d.ts +5 -0
- package/dist/src/setup/scaffold/workspace-glob.js +1 -0
- package/dist/src/setup/scaffold/workspace-root.d.ts +29 -0
- package/dist/src/setup/scaffold/workspace-root.js +1 -0
- package/dist/src/setup/state.d.ts +7 -2
- package/dist/src/setup/vercel-api-failure.d.ts +9 -0
- package/dist/src/setup/vercel-api-failure.js +1 -0
- package/dist/src/setup/vercel-deployment.js +1 -1
- package/dist/src/setup/vercel-project-api.d.ts +25 -0
- package/dist/src/setup/vercel-project-api.js +1 -0
- package/dist/src/setup/vercel-project.d.ts +9 -51
- package/dist/src/setup/vercel-project.js +1 -1
- package/docs/concepts/execution-model-and-durability.md +2 -0
- package/docs/guides/auth-and-route-protection.md +2 -4
- package/docs/guides/dev-tui.md +1 -1
- package/docs/reference/cli.md +1 -1
- package/docs/reference/typescript-api.md +0 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.13.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 9d8bd6e: Existing production sessions now refresh their system prompt from the latest deployment before each model step. Long-lived channel conversations retain their history and state while adopting updated agent instructions.
|
|
8
|
+
|
|
9
|
+
## 0.13.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 306e14e: Remove the top-level `auth` field from `defineTool()` and require tool auth providers to be passed inline to `ctx.getToken(provider)` or `ctx.requireAuth(provider)`.
|
|
14
|
+
- f00ca73: Search every Vercel project in the selected team and preserve the selected project ID through linking.
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- 36b67fc: Make `eve init` respect ancestor package-manager workspaces when scaffolding nested packages. The scaffold now updates workspace-owned package policy at the npm, pnpm, Yarn, or Bun workspace root instead of writing nested root-only config into the generated package.
|
|
19
|
+
|
|
3
20
|
## 0.12.3
|
|
4
21
|
|
|
5
22
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NOT_AN_AGENT_MESSAGE,hasInteractiveTerminal}from"./preconditions.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";const defaultDependencies={isEveProject,hasInteractiveTerminal};async function runDeployCommand(t,n,r=defaultDependencies){if(!await r.isEveProject(n)){t.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}let i=r.createPrompter?.()??createPrompter();i.intro(`Deploy your eve agent to Vercel`);try{let e=await runDeployFlow({appRoot:n,prompter:i,interactive:r.hasInteractiveTerminal(),deps:r.flowDeps});if(e.kind===`needs-link`){t.error("This directory is not linked to a Vercel project. Run `eve link` first (or `vercel link --project <name> --yes` in CI), then re-run `eve deploy`."),process.exitCode=1;return}i.outro(e.kind===`cancelled`?`Cancelled.`:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`)}catch(e){t.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}export{runDeployCommand};
|
|
1
|
+
import{NOT_AN_AGENT_MESSAGE,hasInteractiveTerminal}from"./preconditions.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";const defaultDependencies={isEveProject,hasInteractiveTerminal};async function runDeployCommand(t,n,r=defaultDependencies){if(!await r.isEveProject(n)){t.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}let i=r.createPrompter?.()??createPrompter();i.intro(`Deploy your eve agent to Vercel`);try{let e=await runDeployFlow({appRoot:n,prompter:i,interactive:r.hasInteractiveTerminal(),deps:r.flowDeps});if(e.kind===`needs-link`){t.error("This directory is not linked to a Vercel project. Run `eve link` first (or `vercel link --project <name> --yes --non-interactive` in CI), then re-run `eve deploy`."),process.exitCode=1;return}i.outro(e.kind===`cancelled`?`Cancelled.`:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`)}catch(e){t.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}export{runDeployCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{initAgentDevHandoff,initAgentInstructions,initAgentReplPrompt}from"./agent-instructions.js";import{tryInitializeGit}from"./init-git.js";import{selectInitHandoff,spawnCodingAgentRepl}from"./init-repl.js";import{createLogger,isLogLevelEnabled}from"#internal/logging.js";import{basename,join,resolve}from"node:path";import{ensureChannel,scaffoldBaseProject}from"#setup/scaffold/index.js";import{mkdtemp,readdir,rename,rm,stat}from"node:fs/promises";import{performance}from"node:perf_hooks";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{EVE_WORDMARK}from"#cli/banner.js";import{formatElapsed}from"#cli/format-elapsed.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{formatNodeEngineOverrideWarning}from"#setup/node-engine.js";import{detectInvokingPackageManager,detectPackageManager}from"#setup/package-manager.js";import{pathExists}from"#setup/path-exists.js";import{parseProjectName}from"#setup/project-name.js";import{eveDevArguments,runPackageManagerInstall,spawnPackageManager}from"#setup/primitives/index.js";import{addAgentToProject}from"#setup/scaffold/create/add-to-project.js";import{WizardCancelledError}from"#setup/step.js";import{DEFAULT_EVE_PACKAGE_CONTRACT}from"#setup/scaffold/create/project.js";var import_picocolors=__toESM(require_picocolors(),1);const defaultDependencies={addAgentToProject,detectInvokingPackageManager,detectPackageManager,ensureChannel,isCodingAgentLaunch,now:()=>performance.now(),runPackageManagerInstall,scaffoldBaseProject,selectInitHandoff,spawnCodingAgentRepl,spawnPackageManager,tryInitializeGit},ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),EVE_INIT_PACKAGE_SPEC_ENV=`EVE_INIT_PACKAGE_SPEC`,initLog=createLogger(`init`);async function resolveTargetDirectory(e,t){let n=resolve(e,t);return(await stat(n).catch(()=>void 0))?.isDirectory()?n:void 0}function isCurrentDirectoryTarget(e){return/^\.(?:[/\\]+\.?)*$/u.test(e.trim())}async function assertCanScaffoldInPlace(e){let t=(await readdir(e)).filter(e=>!ALLOWED_CREATE_IN_PLACE_ENTRIES.has(e));if(t.length===0)return;let n=t.slice(0,5).join(`, `),r=t.length>5?`, and ${t.length-5} more`:``;throw Error(`Cannot create project in current directory because it is not empty. Found: ${n}${r}. Use an empty directory.`)}async function moveDirectoryContents(e,t){for(let n of await readdir(e))await rename(join(e,n),join(t,n))}async function addToExistingProject(e,t,n,r){if(t.channelWebNextjs===!0)throw Error("`--channel-web-nextjs` is not supported when adding an agent to an existing project. Run `eve channels add web` from the project afterwards instead.");let i=await n.detectPackageManager(e),a=await n.addAgentToProject({projectRoot:e,model:DEFAULT_AGENT_MODEL_ID,packageManager:i.kind,evePackage:r});return{packageManager:i.kind,nodeEngineOverride:a.nodeEngineOverride}}async function resolveScaffoldPackageManager(e,t){let n=await t.detectPackageManager(e);return n.source==="default"?t.detectInvokingPackageManager()??`pnpm`:n.kind}async function scaffoldProject(e,t,n,r,i,a){let o=resolve(e),s=t===`.`,c=s?o:join(o,t);if(s)await assertCanScaffoldInPlace(c);else if(await pathExists(c))throw Error(`Cannot create project because "${c}" already exists.`);let l=await mkdtemp(join(o,`.eve-init-`));try{let e={projectName:s?basename(c):t,model:DEFAULT_AGENT_MODEL_ID,evePackage:a,targetDirectory:l,packageManager:n},o=await i.scaffoldBaseProject(e);return r.channelWebNextjs===!0&&await i.ensureChannel({projectRoot:o,kind:`web`,packageManager:n,configureVercelServices:!1}),s?await moveDirectoryContents(o,c):await rename(o,c),c}finally{await rm(l,{recursive:!0,force:!0})}}function installProgressDetail(e,t){let n=t.text.trim();if(n===``||e!==`npm`)return n||void 0;let r=/^npm silly fetch manifest (.+)$/u.exec(n);if(r!==null)return`Resolving ${r[1]}`;let i=/^npm http fetch \S+ \S+ attempt (\d+) failed with (\S+)$/u.exec(n);if(i!==null)return`npm registry · attempt ${i[1]} failed: ${i[2]}`;if(t.stream===`stdout`||/^npm (?:error|warn)\b/u.test(n))return n}const NPM_NOISE_LINE=/^\s*npm (?:silly|verbose|http|timing)\b/u;async function runInitSteps(e){let{dependencies:t,logger:n,options:r,parentDirectory:i,target:a}=e,o=isLogLevelEnabled(`debug`),s=startCliLiveRow(n);s.update(`Preparing project`);try{let e=await t.isCodingAgentLaunch(),c=a??`.`,l=isCurrentDirectoryTarget(c),u=l?await pathExists(join(resolve(i),`package.json`))?resolve(i):void 0:await resolveTargetDirectory(i,c),p=resolveInitEvePackageOverride(),m=u===void 0?`creating agent`:`adding agent`;s.update(u===void 0?`Creating agent`:`Adding agent`),initLog.debug(m);let h=t.now(),g;if(u===void 0){let e=l?`.`:parseProjectName(c),n=resolve(i),a=await resolveScaffoldPackageManager(e===`.`?n:join(n,e),t)
|
|
1
|
+
import{__toESM}from"../../_virtual/_rolldown/runtime.js";import{require_picocolors}from"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js";import{initAgentDevHandoff,initAgentInstructions,initAgentReplPrompt}from"./agent-instructions.js";import{tryInitializeGit}from"./init-git.js";import{selectInitHandoff,spawnCodingAgentRepl}from"./init-repl.js";import{createLogger,isLogLevelEnabled}from"#internal/logging.js";import{basename,join,resolve}from"node:path";import{ensureChannel,scaffoldBaseProject}from"#setup/scaffold/index.js";import{mkdtemp,readdir,rename,rm,stat}from"node:fs/promises";import{performance}from"node:perf_hooks";import{isCodingAgentLaunch}from"#cli/agent-detection.js";import{EVE_WORDMARK}from"#cli/banner.js";import{formatElapsed}from"#cli/format-elapsed.js";import{startCliLiveRow}from"#cli/ui/live-row.js";import{DEFAULT_AGENT_MODEL_ID}from"#shared/default-agent-model.js";import{formatNodeEngineOverrideWarning}from"#setup/node-engine.js";import{detectInvokingPackageManager,detectPackageManager}from"#setup/package-manager.js";import{pathExists}from"#setup/path-exists.js";import{parseProjectName}from"#setup/project-name.js";import{eveDevArguments,runPackageManagerInstall,spawnPackageManager}from"#setup/primitives/index.js";import{addAgentToProject}from"#setup/scaffold/create/add-to-project.js";import{WizardCancelledError}from"#setup/step.js";import{DEFAULT_EVE_PACKAGE_CONTRACT}from"#setup/scaffold/create/project.js";var import_picocolors=__toESM(require_picocolors(),1);const defaultDependencies={addAgentToProject,detectInvokingPackageManager,detectPackageManager,ensureChannel,isCodingAgentLaunch,now:()=>performance.now(),runPackageManagerInstall,scaffoldBaseProject,selectInitHandoff,spawnCodingAgentRepl,spawnPackageManager,tryInitializeGit},ALLOWED_CREATE_IN_PLACE_ENTRIES=new Set([`.DS_Store`,`.git`,`.gitkeep`,`.hg`]),EVE_INIT_PACKAGE_SPEC_ENV=`EVE_INIT_PACKAGE_SPEC`,initLog=createLogger(`init`);async function resolveTargetDirectory(e,t){let n=resolve(e,t);return(await stat(n).catch(()=>void 0))?.isDirectory()?n:void 0}function isCurrentDirectoryTarget(e){return/^\.(?:[/\\]+\.?)*$/u.test(e.trim())}async function assertCanScaffoldInPlace(e){let t=(await readdir(e)).filter(e=>!ALLOWED_CREATE_IN_PLACE_ENTRIES.has(e));if(t.length===0)return;let n=t.slice(0,5).join(`, `),r=t.length>5?`, and ${t.length-5} more`:``;throw Error(`Cannot create project in current directory because it is not empty. Found: ${n}${r}. Use an empty directory.`)}async function moveDirectoryContents(e,t){for(let n of await readdir(e))await rename(join(e,n),join(t,n))}function uniqueWorkspaceRootMutations(e){let t=new Map;for(let n of e){let e=`${n.kind}:${n.path}`,r=t.get(e);t.set(e,{...n,nodeEngineOverride:n.nodeEngineOverride??r?.nodeEngineOverride})}return[...t.values()]}function formatWorkspaceRootMutationWarning(e){let t=e.kind===`package-json`?`package.json`:`configuration`,n=e.nodeEngineOverride===void 0?``:` (${formatNodeEngineOverrideWarning(e.nodeEngineOverride)})`;return`Updated workspace root ${t} at ${e.path}${n}`}async function addToExistingProject(e,t,n,r){if(t.channelWebNextjs===!0)throw Error("`--channel-web-nextjs` is not supported when adding an agent to an existing project. Run `eve channels add web` from the project afterwards instead.");let i=await n.detectPackageManager(e),a=await n.addAgentToProject({projectRoot:e,model:DEFAULT_AGENT_MODEL_ID,packageManager:i.kind,evePackage:r});return{packageManager:i.kind,nodeEngineOverride:a.nodeEngineOverride}}async function resolveScaffoldPackageManager(e,t){let n=await t.detectPackageManager(e);return n.source==="default"?t.detectInvokingPackageManager()??`pnpm`:n.kind}async function scaffoldProject(e,t,n,r,i,a){let o=resolve(e),s=t===`.`,c=s?o:join(o,t);if(s)await assertCanScaffoldInPlace(c);else if(await pathExists(c))throw Error(`Cannot create project because "${c}" already exists.`);let l=await mkdtemp(join(o,`.eve-init-`)),p=[];try{let e={projectName:s?basename(c):t,model:DEFAULT_AGENT_MODEL_ID,evePackage:a,targetDirectory:l,workspaceProbeDirectory:c,packageManager:n,onWorkspaceRootMutation:e=>{p.push(e)}},o=await i.scaffoldBaseProject(e);return r.channelWebNextjs===!0&&await i.ensureChannel({projectRoot:o,kind:`web`,packageManager:n,workspaceProbeDirectory:c,configureVercelServices:!1,onWorkspaceRootMutation:e=>{p.push(e)}}),s?await moveDirectoryContents(o,c):await rename(o,c),{projectPath:c,workspaceRootMutations:uniqueWorkspaceRootMutations(p)}}finally{await rm(l,{recursive:!0,force:!0})}}function installProgressDetail(e,t){let n=t.text.trim();if(n===``||e!==`npm`)return n||void 0;let r=/^npm silly fetch manifest (.+)$/u.exec(n);if(r!==null)return`Resolving ${r[1]}`;let i=/^npm http fetch \S+ \S+ attempt (\d+) failed with (\S+)$/u.exec(n);if(i!==null)return`npm registry · attempt ${i[1]} failed: ${i[2]}`;if(t.stream===`stdout`||/^npm (?:error|warn)\b/u.test(n))return n}const NPM_NOISE_LINE=/^\s*npm (?:silly|verbose|http|timing)\b/u;async function runInitSteps(e){let{dependencies:t,logger:n,options:r,parentDirectory:i,target:a}=e,o=isLogLevelEnabled(`debug`),s=startCliLiveRow(n);s.update(`Preparing project`);try{let e=await t.isCodingAgentLaunch(),c=a??`.`,l=isCurrentDirectoryTarget(c),u=l?await pathExists(join(resolve(i),`package.json`))?resolve(i):void 0:await resolveTargetDirectory(i,c),p=resolveInitEvePackageOverride(),m=u===void 0?`creating agent`:`adding agent`;s.update(u===void 0?`Creating agent`:`Adding agent`),initLog.debug(m);let h=t.now(),g;if(u===void 0){let e=l?`.`:parseProjectName(c),n=resolve(i),a=await resolveScaffoldPackageManager(e===`.`?n:join(n,e),t),o=await scaffoldProject(i,e,a,r,t,p);g={kind:`created`,packageManager:a,projectPath:o.projectPath,workspaceRootMutations:o.workspaceRootMutations}}else{let e=await addToExistingProject(u,r,t,p);g=e.nodeEngineOverride===void 0?{kind:`added`,packageManager:e.packageManager,projectPath:u}:{kind:`added`,nodeEngineOverride:e.nodeEngineOverride,packageManager:e.packageManager,projectPath:u}}let _=t.now()-h;initLog.debug(`${m} done`,{ms:_}),s.update(`Installing dependencies`,`${g.packageManager} install`),initLog.debug(`installing dependencies with ${g.packageManager}`);let v=t.now(),y=[],b=[],x=await t.runPackageManagerInstall(g.packageManager,g.projectPath,{bypassMinimumReleaseAge:!0,progressDetails:process.stdout.isTTY===!0&&!o,onOutput:e=>{e.text.trim()!==``&&(b.push(e.text),b.length>20&&b.shift(),NPM_NOISE_LINE.test(e.text)||y.push(e.text)),o&&initLog.debug(e.text);let t=installProgressDetail(g.packageManager,e);t!==void 0&&s.update(`Installing dependencies`,t)}}),S=t.now()-v;if(!x){initLog.debug(`dependency installation failed`,{ms:S}),s.stop();let e=y.length>0?y:b;for(let t of e)n.error(t);throw Error(`Failed to install dependencies in "${g.projectPath}".`)}return initLog.debug(`dependencies installed`,{ms:S}),g.kind===`created`?(s.update(`Initializing Git repository`),initLog.debug(`initializing git repository`),{...g,agentElapsedMs:_,agentLaunched:e,gitResult:await t.tryInitializeGit(g.projectPath),installElapsedMs:S}):{...g,agentElapsedMs:_,agentLaunched:e,installElapsedMs:S}}finally{s.stop()}}async function runInitCommand(e,t,a,o,s=defaultDependencies){if(a===void 0&&await s.isCodingAgentLaunch()){e.log(initAgentInstructions());return}let c=await runInitSteps({dependencies:s,logger:e,options:o,parentDirectory:t,target:a});if(c.kind===`created`){e.log(`${import_picocolors.default.green(`✓`)} Created an ${EVE_WORDMARK} agent in ${import_picocolors.default.bold(c.projectPath)} ${import_picocolors.default.dim(`in ${formatElapsed(c.agentElapsedMs)}`)}`);for(let t of c.workspaceRootMutations)e.log(import_picocolors.default.yellow(`⚠ ${formatWorkspaceRootMutationWarning(t)}`))}else e.log(`${import_picocolors.default.green(`✓`)} Added an ${EVE_WORDMARK} agent to ${import_picocolors.default.bold(c.projectPath)} ${import_picocolors.default.dim(`in ${formatElapsed(c.agentElapsedMs)}`)}`),c.nodeEngineOverride!==void 0&&e.log(import_picocolors.default.yellow(`⚠ ${formatNodeEngineOverrideWarning(c.nodeEngineOverride)}`));e.log(`${import_picocolors.default.green(`✓`)} Installed dependencies ${import_picocolors.default.dim(`in ${formatElapsed(c.installElapsedMs)}`)}`),c.kind===`created`&&c.gitResult.kind===`failed`&&e.error(import_picocolors.default.yellow(`Git initialization failed: ${c.gitResult.reason}`));let l=[c.packageManager,...eveDevArguments(c.packageManager)].join(` `),d=initAgentDevHandoff({projectPath:c.projectPath,devCommand:l});if(c.agentLaunched){e.log(d);return}let f;try{f=await s.selectInitHandoff({agentName:basename(c.projectPath)})}catch(e){if(e instanceof WizardCancelledError)return;throw e}if(f!==`eve-dev`){if(e.log(import_picocolors.default.dim(`$ ${f}`)),!await s.spawnCodingAgentRepl({command:f,cwd:c.projectPath,prompt:initAgentReplPrompt({devCommand:l}),onPromptUnseeded:t=>{e.log(import_picocolors.default.yellow(`Could not seed ${f} automatically. Paste this prompt into it:`)),e.log(t)}}))throw Error(`Coding-agent REPL exited unsuccessfully in "${c.projectPath}".`);return}let p=eveDevArguments(c.packageManager);if(e.log(import_picocolors.default.dim(`$ eve dev`)),!await s.spawnPackageManager(c.packageManager,c.projectPath,p))throw Error(`Development server exited unsuccessfully in "${c.projectPath}".`)}function resolveInitEvePackageOverride(){let e=process.env[EVE_INIT_PACKAGE_SPEC_ENV]?.trim();if(!(e===void 0||e.length===0))return{nodeEngine:DEFAULT_EVE_PACKAGE_CONTRACT.nodeEngine,version:e}}export{EVE_INIT_PACKAGE_SPEC_ENV,runInitCommand};
|
|
@@ -13,8 +13,8 @@ export interface LinkCommandDependencies {
|
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
15
|
* `eve link`: pick a Vercel team and project (re-linking when one is already
|
|
16
|
-
* linked), run `vercel link
|
|
17
|
-
* in `.env.local`. The flow itself is {@link runLinkFlow}, shared with the dev
|
|
16
|
+
* linked), run `vercel link` for the selected project, then pull env so the AI Gateway
|
|
17
|
+
* credential lands in `.env.local`. The flow itself is {@link runLinkFlow}, shared with the dev
|
|
18
18
|
* TUI `/model` menu's provider row. Interactive only: the pickers are the point of the command,
|
|
19
19
|
* so a non-TTY run refuses with guidance instead of guessing a project.
|
|
20
20
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NOT_AN_AGENT_MESSAGE,hasInteractiveTerminal}from"./preconditions.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{runLinkFlow}from"#setup/flows/link.js";const defaultDependencies={isEveProject,hasInteractiveTerminal};async function runLinkCommand(t,n,r=defaultDependencies){if(!await r.isEveProject(n)){t.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}if(!r.hasInteractiveTerminal()){t.error("`eve link` needs an interactive terminal to pick the team and project. In CI, run `vercel link --project <name> --yes` instead."),process.exitCode=1;return}let i=r.createPrompter?.()??createPrompter();i.intro(`Link your eve agent to Vercel`);try{let e=await runLinkFlow({appRoot:n,prompter:i,deps:r.flowDeps});i.outro(e.kind===`cancelled`?`Cancelled.`:`Project linked.`)}catch(e){t.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}export{runLinkCommand};
|
|
1
|
+
import{NOT_AN_AGENT_MESSAGE,hasInteractiveTerminal}from"./preconditions.js";import{isEveProject}from"#setup/scaffold/index.js";import{createPrompter}from"#setup/prompter.js";import{runLinkFlow}from"#setup/flows/link.js";const defaultDependencies={isEveProject,hasInteractiveTerminal};async function runLinkCommand(t,n,r=defaultDependencies){if(!await r.isEveProject(n)){t.error(NOT_AN_AGENT_MESSAGE),process.exitCode=1;return}if(!r.hasInteractiveTerminal()){t.error("`eve link` needs an interactive terminal to pick the team and project. In CI, run `vercel link --project <name> --yes --non-interactive` instead."),process.exitCode=1;return}let i=r.createPrompter?.()??createPrompter();i.intro(`Link your eve agent to Vercel`);try{let e=await runLinkFlow({appRoot:n,prompter:i,deps:r.flowDeps});i.outro(e.kind===`cancelled`?`Cancelled.`:`Project linked.`)}catch(e){t.error(e instanceof Error?e.message:String(e)),process.exitCode=1}}export{runLinkCommand};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ChannelSetupChoice, ChannelSetupChoiceOptions } from "#setup/cli/index.js";
|
|
2
|
+
import type { SearchActionOption } from "#setup/cli/select-state.js";
|
|
2
3
|
import type { SelectNotice } from "#setup/prompter.js";
|
|
3
4
|
import type { SetupPanelOption } from "./setup-panel.js";
|
|
4
5
|
export type SetupEditableSelectResult = {
|
|
@@ -20,10 +21,14 @@ interface SetupSingleSelectRequest extends SetupSelectRequestBase {
|
|
|
20
21
|
kind: "single" | "stacked" | "task-list";
|
|
21
22
|
initialValue?: string;
|
|
22
23
|
}
|
|
24
|
+
interface SetupSearchAction extends SearchActionOption {
|
|
25
|
+
load?(query: string): Promise<readonly SetupPanelOption[]>;
|
|
26
|
+
}
|
|
23
27
|
interface SetupSearchSelectRequest extends SetupSelectRequestBase {
|
|
24
28
|
kind: "search";
|
|
25
29
|
initialValue?: string;
|
|
26
30
|
placeholder?: string;
|
|
31
|
+
searchAction?: SetupSearchAction;
|
|
27
32
|
}
|
|
28
33
|
interface SetupMultiSelectRequest extends SetupSelectRequestBase {
|
|
29
34
|
kind: "multi";
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* column 3.
|
|
15
15
|
*/
|
|
16
16
|
import type { ChannelSetupAction, PromptOption } from "#setup/cli/index.js";
|
|
17
|
-
import { type SelectState } from "#setup/cli/select-state.js";
|
|
17
|
+
import { type SearchActionOption, type SelectState } from "#setup/cli/select-state.js";
|
|
18
18
|
import type { SelectNotice } from "#setup/prompter.js";
|
|
19
19
|
import { type LineState } from "./line-editor.js";
|
|
20
20
|
import type { Theme } from "./theme.js";
|
|
@@ -28,7 +28,10 @@ interface SetupQuestionPanelBase {
|
|
|
28
28
|
}
|
|
29
29
|
interface SetupSelectPanelBase extends SetupQuestionPanelBase {
|
|
30
30
|
options: readonly SetupPanelOption[];
|
|
31
|
+
searchAction?: SearchActionOption;
|
|
31
32
|
select: SelectState;
|
|
33
|
+
/** Live frame rendered beside a searchable input while it loads replacement rows. */
|
|
34
|
+
loadingFrame?: string;
|
|
32
35
|
}
|
|
33
36
|
interface SetupEditableRow {
|
|
34
37
|
/**
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{clipVisible,renderInputText,renderInputWithBlockCursor,visibleLength,wrapVisibleLine}from"./terminal-text.js";import{maskLine,visibleLine}from"./line-editor.js";import{renderCursorRow,renderOptionRow,renderOptionRowContinuation,resolveOptionRowState}from"#setup/cli/option-row.js";import{filterOptions,submitRowIndex}from"#setup/cli/select-state.js";function clip(t,n){return clipVisible(t,n)}function questionFooter(e,t){let n=t.colors;return[``,` ${n.dim(n.italic(e.join(` ${t.glyph.dot} `)))}`]}const BOLD_OR_DIM_CLOSE=`\x1B[22m`;function dimWithEmphasis(e,t){return t.colors.dim(e.replaceAll(BOLD_OR_DIM_CLOSE,`${BOLD_OR_DIM_CLOSE}[2m`))}function toneGlyph(e,t){let n=t.colors;switch(e){case`success`:return n.green(t.glyph.success);case`warning`:return n.yellow(t.glyph.warning);case`error`:return n.red(t.glyph.error);case`info`:return n.dim(t.glyph.dot)}}function renderIndicator(e,t){return e.color===`green`?t.colors.green(e.glyph):t.colors.yellow(e.glyph)}function renderFlowPanel(e,t,n){let r=t.colors,i=[r.dim(t.glyph.hrule.repeat(Math.max(1,n)))];e.title.length>0&&i.push(` ${r.bold(e.title)}`),i.push(``);let a=e.lines.slice(-6);for(let e of a){let n=e.tone===`info`?r.dim(e.text):e.text;i.push(` ${toneGlyph(e.tone,t)} ${n}`)}switch(a.length>0&&i.push(``),e.content.kind){case`question`:e.content.status!==void 0&&i.push(` ${renderIndicator(e.content.status.indicator,t)} ${r.dim(e.content.status.text)}`,``),i.push(...e.content.rows);break;case`status`:i.push(` ${renderIndicator(e.content.status.indicator,t)} ${r.dim(e.content.status.text)}`),e.content.preview!==void 0&&i.push(` ${r.dim(e.content.preview)}`);break;case`preview`:i.push(` ${renderIndicator(e.content.indicator,t)} ${r.dim(e.content.text)}`);break;case`idle`:i.push(` ${renderIndicator(e.content.indicator,t)} ${r.dim(`Working…`)}`);break}return i.map((e,t)=>t===0||e.length===0?clip(e,n):clip(` ${e}`,n))}function optionRow(e){let{option:t,theme:n}=e;return renderOptionRow({colors:n.colors,glyphs:{pointer:n.glyph.pointer,selectedPointer:n.glyph.selectedPointer,success:n.glyph.success,placeholder:n.glyph.option,dot:n.glyph.dot},label:t.label,hint:t.hint,focusHint:t.focusHint,accent:t.accent,isCursor:e.isCursor,state:resolveOptionRowState(t,e.isChecked),placeholder:e.placeholder,hintPadding:e.hintPadding})}function selectPresentation(e){switch(e.kind){case`single`:return{selection:`single`,filter:void 0,layout:`plain`,edit:void 0};case`search`:return{selection:`single`,filter:{placeholder:e.placeholder},layout:`plain`,edit:void 0};case`multi`:return{selection:`multiple`,filter:void 0,layout:`plain`,edit:void 0};case`searchable-multi`:return{selection:`multiple`,filter:{placeholder:e.placeholder},layout:`plain`,edit:void 0};case`stacked`:return{selection:`single`,filter:void 0,layout:`stacked`,edit:void 0};case`task-list`:return{selection:`single`,filter:void 0,layout:`task-list`,edit:void 0};case`editable`:return{selection:`single`,filter:void 0,layout:`task-list`,edit:e.edit}}}function selectMessageRows(e,t,n){if(e===``)return[];let r=e.split(`
|
|
2
|
-
`).map((e,r)=>` ${t===`stacked`||r>0?n.colors.bold(e):e}`);return r.push(``),r}function searchFilter(e,t,n){
|
|
2
|
+
`).map((e,r)=>` ${t===`stacked`||r>0?n.colors.bold(e):e}`);return r.push(``),r}function searchFilter(e,t,n,r){let i=r.colors.dim(r.glyph.caret),a=i;return e.length>0?a=e+i:t!==void 0&&(a=r.colors.dim(`> ${t}`)),n===void 0?a:`${a} ${r.colors.yellow(n)}`}function selectViewSize(e){return e.search?e.filter===``&&e.featuredLead>0?Math.min(e.featuredLead,8):8:e.optionCount}function noticeBody(e,t,n){return e.tone===`info`?n.colors.dim(e.text):e.tone===`success`&&t===`task-list`?n.colors.bold(e.text):e.text}function editableOption(e,t,n,r){if(!t||n?.optionValue!==e.value)return e;let i=n.editor.text||n.defaultValue,a=n.editor.text.length===0?i.length:n.editor.cursor,o=n.caretVisible?r.colors.cyan(r.glyph.caret):``,s=`${i.slice(0,a)}${o}${i.slice(a)}`;return{...e,hint:n.formatHint(s)}}function optionWithoutStackedHint(e,t){if(t!==`stacked`||e.hint===void 0)return{option:e,stackedHint:void 0};let{hint:n,...r}=e;return{option:r,stackedHint:n}}function optionUsesPlaceholder(e,t,n){let r=e.filter!==void 0,i=e.layout===`task-list`&&t===n-1,a=e.selection===`multiple`,o=e.layout!==`plain`;return!r&&!i&&(a||o)}function appendSelectOptionRows(e){let{rows:t,state:n,presentation:r,visible:i,start:a,end:o,cursor:s,visibleLabelWidth:c,theme:u}=e,d=u.colors;for(let e=a;e<o;e+=1){let f=i[e],p=e===s;r.layout===`task-list`&&e===o-1&&e>a&&t.push(``);let{option:m,stackedHint:h}=optionWithoutStackedHint(editableOption(f,p,r.edit,u),r.layout);t.push(` ${optionRow({option:m,isCursor:p,isChecked:r.selection===`multiple`&&n.select.selected.has(f.value),placeholder:optionUsesPlaceholder(r,e,i.length),hintPadding:c-f.label.length,theme:u})}`),h!==void 0&&t.push(` ${renderOptionRowContinuation(dimWithEmphasis(h,u))}`),f.description!==void 0&&(f.disabled===!0||p)&&t.push(` ${d.dim(f.description)}`),r.layout===`stacked`&&e<o-1&&t.push(``)}}function appendSubmitRow(e,t,n,r){if(n<0)return;let i=t===n,a=i?`${r.glyph.selectedPointer} ${r.colors.bold(`Submit`)}`:` Submit`;e.push(``,` ${renderCursorRow(a,i,r.colors)}`)}function appendSelectNotices(e,t,n,a,o){if(!(t===void 0||t.length===0)){e.push(``);for(let s of t){let t=toneGlyph(s.tone,a),c=` `.repeat(visibleLength(t)+1),l=Math.max(1,o-2-visibleLength(t)-1),u=wrapVisibleLine(s.text,l);for(let[r,i]of u.entries()){let o=noticeBody({...s,text:i},n,a);e.push(r===0?` ${t} ${o}`:` ${c}${o}`)}}}}function selectFooterHints(e,t,n){let r=[];return e.edit!==void 0&&t[n]?.value===e.edit.optionValue&&r.push(`type to rename`),e.filter!==void 0&&r.push(`type to filter`),r.push(`↑/↓ move`),r.push(e.selection===`multiple`?`space to toggle`:`enter to select`),e.selection===`multiple`&&r.push(`enter on Submit to confirm`),r.push(`esc to cancel`),r}function renderActionQuestion(e,t,n){let r=[` ${t.colors.dim(`${t.glyph.dot} ${e.context}`)}`,``];for(let[n,i]of e.actions.entries())r.push(` ${optionRow({option:i,isCursor:n===e.cursor,isChecked:!1,placeholder:!0,hintPadding:0,theme:t})}`);return r.push(...questionFooter([`↑/↓ move`,`enter to select`,`esc to cancel`],t)),r.map(e=>clip(e,n))}function renderSelectQuestion(e,t,n){if(e.kind===`actions`)return renderActionQuestion(e,t,n);let r=t.colors,i=selectPresentation(e),a=i.filter?filterOptions(e.options,e.select.filter,e.searchAction):e.options,o=i.selection===`multiple`?submitRowIndex(a):-1,s=e.select.cursor,c=selectMessageRows(e.message,i.layout,t);i.filter!==void 0&&c.push(` ${searchFilter(e.select.filter,i.filter.placeholder,e.loadingFrame,t)}`);let l=0;for(;a[l]?.featured;)l+=1;let u=selectViewSize({search:i.filter!==void 0,filter:e.select.filter,featuredLead:l,optionCount:a.length}),p=Math.max(0,Math.min(s-Math.floor(u/2),Math.max(0,a.length-u))),m=Math.min(p+u,a.length),h=a.slice(p,m).filter(e=>e.hint!==void 0||e.focusHint!==void 0).reduce((e,t)=>Math.max(e,t.label.length),0);return a.length===0&&c.push(` ${r.dim(`(no matches)`)}`),appendSelectOptionRows({rows:c,state:e,presentation:i,visible:a,start:p,end:m,cursor:s,visibleLabelWidth:h,theme:t}),appendSubmitRow(c,s,o,t),a.length>m-p&&c.push(` ${r.dim(`↑↓ ${a.length} options, showing ${p+1}–${m}`)}`),appendSelectNotices(c,e.notices,i.layout,t,n),e.error!==void 0&&c.push(``,` ${r.red(e.error)}`),c.push(...questionFooter(selectFooterHints(i,a,s),t)),c.map(e=>clip(e,n))}function renderTextQuestion(e,r,i,s){let c=r.colors,l=[];for(let t of e.notices??[]){let e=t.tone===`info`?c.dim(t.text):t.text;l.push(`${toneGlyph(t.tone,r)} ${e}`)}l.push(...e.message.split(`
|
|
3
3
|
`).map(e=>` ${c.bold(e)}`));let u=Math.max(4,i-4),d=e.mask?maskLine(e.editor):e.editor,f=e.editor.text.length===0?e.placeholder:void 0,p=renderInputWithBlockCursor({...visibleLine(f===void 0?d:{text:f,cursor:0},u,r.glyph.ellipsis),visible:s,inverse:c.inverse,render:f===void 0?renderInputText:e=>c.dim(renderInputText(e))});return l.push(` ${p}`),e.error!==void 0&&l.push(``,` ${c.red(e.error)}`),l.push(...questionFooter([`enter to submit`,`esc to cancel`],r)),l.map(e=>clip(e,i))}function renderAcknowledgeQuestion(e,t,n){let r=t.colors,i=[` ${r.bold(e.message)}`];if(e.lines.length>0){i.push(``);for(let t of e.lines)i.push(` ${r.dim(t)}`)}return i.push(...questionFooter([`enter to continue`],t)),i.map(e=>clip(e,n))}export{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { PromptOption } from "#setup/cli/index.js";
|
|
2
|
-
import { type SelectState } from "#setup/cli/select-state.js";
|
|
2
|
+
import { type SearchActionOption, type SelectState } from "#setup/cli/select-state.js";
|
|
3
3
|
import type { TerminalKey } from "./stream-format.js";
|
|
4
4
|
/** Shared navigation grammar for setup selects, actions, and editable selects. */
|
|
5
5
|
export type SetupSelectionIntent = {
|
|
@@ -33,6 +33,7 @@ export type SetupSelectInputResult = {
|
|
|
33
33
|
interface SetupSelectInput {
|
|
34
34
|
key: TerminalKey;
|
|
35
35
|
options: readonly PromptOption<string>[];
|
|
36
|
+
searchAction?: SearchActionOption;
|
|
36
37
|
select: SelectState;
|
|
37
38
|
}
|
|
38
39
|
type SetupSingleSelectInput = SetupSelectInput & {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{filterOptions,orderedSelection,reduceSelect,selectValueAtCursor,submitRowIndex}from"#setup/cli/select-state.js";function setupSelectionIntent(e){switch(e.type){case`ctrl-c`:case`escape`:return{kind:`cancel`};case`up`:return{kind:`move`,direction:`up`};case`down`:return{kind:`move`,direction:`down`};case`ctrl-r`:return{kind:`repaint`};case`enter`:return{kind:`submit`};default:return}}function isMultiSelect(e){return e.kind===`multi`||e.kind===`searchable-multi`}function isSearchableSelect(e){return e.kind===`search`||e.kind===`searchable-multi`}function updatedSelect(e,t){return{kind:`update`,select:reduceSelect(e.select,t,{options:e.options,submitRow:isMultiSelect(e)})}}function submitSetupSelect(n){let a=isSearchableSelect(n)?filterOptions(n.options,n.select.filter):[...n.options];if(isMultiSelect(n))return n.select.cursor===submitRowIndex(a)?n.required&&n.select.selected.size===0?{kind:`error`,message:`Select at least one option, then submit.`}:{kind:`submit`,values:orderedSelection(n.options,n.select.selected)}:updatedSelect(n,{type:`toggle`});let o=selectValueAtCursor(a,n.select.cursor);return o===void 0?a[n.select.cursor]?.completed?{kind:`ignore`}:{kind:`error`,message:`Type to match an option, then press enter.`}:{kind:`submit`,values:[o]}}function editSetupSelect(e){switch(e.key.type){case`backspace`:return isSearchableSelect(e)?updatedSelect(e,{type:`backspace`}):{kind:`ignore`};case`text`:{if(e.key.framing===`unframed`&&isMultiSelect(e)&&e.key.value===` `)return updatedSelect(e,{type:`toggle`});if(!isSearchableSelect(e))return{kind:`ignore`};let t=e.select,r={options:e.options,submitRow:isMultiSelect(e)};for(let i of e.key.value.replaceAll(`
|
|
2
|
-
`,` `))i>=` `&&i!==``&&(t=reduceSelect(t,{type:`char`,char:i},r));return{kind:`update`,select:t}}default:return{kind:`ignore`}}}function reduceSetupSelectInput(e){let t=setupSelectionIntent(e.key);switch(t?.kind){case`cancel`:return{kind:`cancel`};case`repaint`:return{kind:`repaint`};case`move`:return updatedSelect(e,{type:t.direction});case`submit`:return submitSetupSelect(e);case void 0:return editSetupSelect(e)}}export{reduceSetupSelectInput,setupSelectionIntent};
|
|
1
|
+
import{filterOptions,orderedSelection,reduceSelect,selectValueAtCursor,submitRowIndex}from"#setup/cli/select-state.js";function setupSelectionIntent(e){switch(e.type){case`ctrl-c`:case`escape`:return{kind:`cancel`};case`up`:return{kind:`move`,direction:`up`};case`down`:return{kind:`move`,direction:`down`};case`ctrl-r`:return{kind:`repaint`};case`enter`:return{kind:`submit`};default:return}}function isMultiSelect(e){return e.kind===`multi`||e.kind===`searchable-multi`}function isSearchableSelect(e){return e.kind===`search`||e.kind===`searchable-multi`}function updatedSelect(e,t){return{kind:`update`,select:reduceSelect(e.select,t,{options:e.options,searchAction:e.searchAction,submitRow:isMultiSelect(e)})}}function submitSetupSelect(n){let a=isSearchableSelect(n)?filterOptions(n.options,n.select.filter,n.searchAction):[...n.options];if(isMultiSelect(n))return n.select.cursor===submitRowIndex(a)?n.required&&n.select.selected.size===0?{kind:`error`,message:`Select at least one option, then submit.`}:{kind:`submit`,values:orderedSelection(n.options,n.select.selected)}:updatedSelect(n,{type:`toggle`});let o=selectValueAtCursor(a,n.select.cursor);return o===void 0?a[n.select.cursor]?.completed?{kind:`ignore`}:{kind:`error`,message:`Type to match an option, then press enter.`}:{kind:`submit`,values:[o]}}function editSetupSelect(e){switch(e.key.type){case`backspace`:return isSearchableSelect(e)?updatedSelect(e,{type:`backspace`}):{kind:`ignore`};case`text`:{if(e.key.framing===`unframed`&&isMultiSelect(e)&&e.key.value===` `)return updatedSelect(e,{type:`toggle`});if(!isSearchableSelect(e))return{kind:`ignore`};let t=e.select,r={options:e.options,searchAction:e.searchAction,submitRow:isMultiSelect(e)};for(let i of e.key.value.replaceAll(`
|
|
2
|
+
`,` `))i>=` `&&i!==``&&(t=reduceSelect(t,{type:`char`,char:i},r));return{kind:`update`,select:t}}default:return{kind:`ignore`}}}function reduceSetupSelectInput(e){let t=setupSelectionIntent(e.key);switch(t?.kind){case`cancel`:return e.key.type===`escape`&&isSearchableSelect(e)&&e.select.filter.length>0?updatedSelect(e,{type:`clear`}):{kind:`cancel`};case`repaint`:return{kind:`repaint`};case`move`:return updatedSelect(e,{type:t.direction});case`submit`:return submitSetupSelect(e);case void 0:return editSetupSelect(e)}}export{reduceSetupSelectInput,setupSelectionIntent};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{initialSelectState,reduceSelect,selectValueAtCursor}from"#setup/cli/select-state.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.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,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=[];#g=new Set;#_=new Map;#v=new Set;#y;#b=!1;#x;#S=[];#C;#w=0;#T;#E=``;#D=0;#O=new PromptHistory;#k=!1;#A;#j={kind:`idle`};#M=STATUS.processing;#N=`eve`;#P=!1;#F=!1;#I=!0;#L=0;#R;#z;#B;#V=!1;#H;#U=``;#W=new StringDecoder(`utf8`);#G;#K;#q;#J=!1;#Y=!1;#X;#Z;#Q;#$;#ee;#te;#ne;#re=``;#ie=``;#ae;#oe;#se=0;#ce;#le;#ue;#de;#fe;setupFlow={begin:(e,t)=>this.#ge(e,t),end:e=>this.#_e(e?.preserveDiagnostics??!0),readSelect:e=>this.#ve(e),readEditableSelect:e=>this.#be(e),readText:e=>this.#xe(e),readAcknowledge:e=>this.#Se(e),readChoice:e=>this.#ye(e),setStatus:e=>this.#Ae(e),renderLine:(e,t)=>this.#je(e,t),renderOutput:e=>this.#Me(e),waitForInterrupt:()=>this.#De()};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#Q=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`none`}renderAgentHeader(e){this.#N=e.name,this.#y=e,this.#Ne();let t=this.#ht().join(`
|
|
1
|
+
import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.js";import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{renderAttentionRows,renderBlockLines}from"./blocks.js";import{dismissTypeahead,inlineCommandHint,isTypeaheadOpen,moveTypeaheadSelection,renderCommandSuggestions,selectedTypeaheadCommand,typeaheadCompletion,typeaheadFor}from"./command-typeahead.js";import{formatDevRebuildStatus,summarizeChangedFiles}from"./dev-rebuild-status.js";import{interruptedError}from"./errors.js";import{EMPTY_LINE,PromptHistory,applyLineEditorKey,deleteForward,layoutPromptInput,lineOf,movePromptLine,visibleLine}from"./line-editor.js";import{LiveRegion}from"./live-region.js";import{nextLogDisplayMode}from"./log-display-mode.js";import{renderAcknowledgeQuestion,renderFlowPanel,renderSelectQuestion,renderTextQuestion}from"./setup-panel.js";import{buildStatusLine}from"./status-line.js";import{createTheme,detectUnicode}from"./theme.js";import{reduceSetupSelectInput,setupSelectionIntent}from"./setup-selection-input.js";import{formatAssistantResponseStats,formatTokenFlow,isIncompletePaste,nextKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil}from"./stream-format.js";import{renderCursorRow}from"#setup/cli/option-row.js";import{toErrorMessage}from"#shared/errors.js";import{StringDecoder}from"node:string_decoder";import{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{PROGRESS_PULSE_ASCII_GLYPH,PROGRESS_PULSE_GLYPH,isProgressPulseVisible}from"#cli/ui/progress-pulse.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,t){return e?`Interrupted`:t?`Ready`:`Done`}const STATUS={processing:`Working…`,toolResults:`Reading results…`,streaming:`Responding…`,executingTools:`Running tools…`,connectionAuth:`Waiting for connection authorization…`};var TerminalRenderer=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f=[];#p=new Map;#m=new Set;#h=[];#g=new Set;#_=new Map;#v=new Set;#y;#b=!1;#x;#S=[];#C;#w=0;#T;#E=``;#D=0;#O=new PromptHistory;#k=!1;#A;#j={kind:`idle`};#M=STATUS.processing;#N=`eve`;#P=!1;#F=!1;#I=!0;#L=0;#R;#z;#B;#V=!1;#H;#U=``;#W=new StringDecoder(`utf8`);#G;#K;#q;#J=!1;#Y=!1;#X;#Z;#Q;#$;#ee;#te;#ne;#re=``;#ie=``;#ae;#oe;#se=0;#ce;#le;#ue;#de;#fe;setupFlow={begin:(e,t)=>this.#ge(e,t),end:e=>this.#_e(e?.preserveDiagnostics??!0),readSelect:e=>this.#ve(e),readEditableSelect:e=>this.#be(e),readText:e=>this.#xe(e),readAcknowledge:e=>this.#Se(e),readChoice:e=>this.#ye(e),setStatus:e=>this.#Ae(e),renderLine:(e,t)=>this.#je(e,t),renderOutput:e=>this.#Me(e),waitForInterrupt:()=>this.#De()};constructor(e){this.#e=e?.input??process.stdin,this.#t=e?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:e?.color??!0,unicode:e?.unicode??detectUnicode()}),this.#i=e?.tools??`auto-collapsed`,this.#a=e?.reasoning??`full`,this.#o=e?.subagents??`auto-collapsed`,this.#s=e?.connectionAuth??`full`,this.#c=e?.assistantResponseStats??`tokensPerSecond`,this.#l=e?.contextSize,this.#Q=e?.contextSize,this.#u=e?.captureForeignOutput??this.#t===process.stdout,this.#d=e?.logs??`none`}renderAgentHeader(e){this.#N=e.name,this.#y=e,this.#Ne();let t=this.#ht().join(`
|
|
2
2
|
`);if(this.#b){t!==this.#x&&(this.#x=t,this.#Je({kind:`agent-header`,body:t,live:!1})),this.#ut();return}this.#b=!0,this.#x=t,this.#n.flush(this.#ht(),[])}async readPrompt(e){this.#Ne(e),this.#qe(),this.#k=!0,this.#j={kind:`idle`},this.#M=``;let t=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#O.begin(t.text),this.#pe(t),this.#A=typeaheadFor(PROMPT_COMMANDS,t.text),this.#He(),this.#ut(),await new Promise((e,n)=>{let apply=e=>{t=e,this.#We(),this.#pe(t),this.#A=typeaheadFor(PROMPT_COMMANDS,e.text,this.#A),this.#ut()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#A=void 0,this.#Ue(),this.#Pe(),n(interruptedError())},suggestions=()=>this.#A!==void 0&&isTypeaheadOpen(this.#A)?this.#A:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#H=n=>{let r=applyLineEditorKey(t,n,{multiline:!0});if(r!==void 0){apply(r);return}switch(n.type){case`up`:{let e=suggestions();if(e!==void 0){this.#A=moveTypeaheadSelection(e,-1),this.#ut();break}let n=movePromptLine(t,`up`);n===void 0?recall(this.#O.previous(t.text)):apply(n);break}case`down`:{let e=suggestions();if(e!==void 0){this.#A=moveTypeaheadSelection(e,1),this.#ut();break}let n=movePromptLine(t,`down`);n===void 0?recall(this.#O.next()):apply(n);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#A=dismissTypeahead(e),this.#ut());break}case`enter`:{let n=highlighted(),r=n!==void 0&&parsePromptCommand(t.text)===null?typeaheadCompletion(n).trimEnd():t.text;this.#A=void 0,this.#O.add(r),this.#k=!1,this.#Ue(),this.#Ke(),this.#M=STATUS.processing,isPromptControlCommand(r)?this.#Je({kind:`command`,body:stripTerminalControls(r.trim()),live:!1}):(this.#Ye(r),this.#ce=r),this.#pe(EMPTY_LINE),this.#ut(),this.#Ie(),e(r);break}case`ctrl-d`:t.text.length===0?interrupt():apply(deleteForward(t));break;case`ctrl-l`:this.#pt();break;case`ctrl-r`:this.#ut();break;case`ctrl-c`:t.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Fe()})}#pe(e){this.#E=e.text,this.#D=e.cursor}async renderStream(e,t){this.#Ne(t),this.#m.clear(),this.#k=!1,this.#j.kind!==`waiting`&&(this.#j={kind:`waiting`,startedAtMs:Date.now()}),this.#M=STATUS.processing,this.#Xe(t?.submittedPrompt),this.#F=!1,this.#X=void 0,this.#Z=void 0,this.#$=void 0,this.#ee=void 0,this.#te=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Ge(),this.#ut();let r=new Promise(e=>{this.#q=e});this.#H=e=>this.#Ve(e),this.#Fe();let i={text:new Map,reasoning:new Map,tools:new Map,hasPendingToolResults:!1};try{for await(let t of takeUntil(iterateTUIStream(e.events),r)){if(this.#F)break;this.#nt(t,n,i)}}catch(e){this.#Ze(`Error`,toErrorMessage(e))}finally{this.#q=void 0,this.#F&&e.abort?.(),this.#Ie(),this.#qe(),this.#j.kind===`waiting`&&(this.#j={kind:`idle`}),this.#M=completedTurnStatus(this.#F,t?.continueSession===!0),this.#tt(),this.#ut(),t?.continueSession||this.#Pe()}}async readToolApproval(e,t){return this.#Ne(t),this.#qe(),this.#k=!1,this.#j={kind:`idle`},this.#M=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#F=!1,this.#ut(),await new Promise((t,n)=>{this.#H=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ke(),this.#M=STATUS.processing,this.#Ie(),this.#ut(),t({approved:!0})):n===`n`&&(this.#Ke(),this.#M=STATUS.processing,this.#me(e.toolCallId),this.#Ie(),this.#ut(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#ut();break;case`ctrl-c`:this.#F=!0,this.#Pe(),n(interruptedError());break;default:break}},this.#Fe()})}async readInputQuestion(e,t){this.#Ne(t),this.#qe(),this.#k=!1,this.#j={kind:`idle`},this.#F=!1;let n=e.options??[],r=n.length>0,a=(e.allowFreeform===!0||!r)&&r,o=n.length+ +!!a,s=questionSectionId(e.requestId),c=r?`select`:`text`,l=0,u=EMPTY_LINE,isOnFreeformRow=()=>a&&l===n.length,renderSection=()=>{this.#$e({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:formatQuestionContent(e,l,this.#r),preformatted:!0,live:!0})},repaintStatus=()=>{if(c===`select`){let e=isOnFreeformRow()?`type`:`select`;this.#M=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#k=!1}else this.#k=!0,this.#pe(u),this.#M=``;this.#ut()};renderSection(),c===`text`&&this.#He(),repaintStatus();let finalize=t=>{this.#$e({id:s,kind:`question`,title:stripTerminalControls(e.prompt),body:` ${this.#r.colors.green(this.#r.glyph.success)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#k=!1,this.#Ke(),this.#M=STATUS.processing,this.#Ue(),this.#Ie(),this.#ut();let n={};return t.optionId!==void 0&&(n.optionId=t.optionId),t.text!==void 0&&(n.text=t.text),n};return await new Promise((t,i)=>{this.#H=a=>{if(a.type===`ctrl-c`){if(c===`text`&&u.text.length>0){u=EMPTY_LINE,this.#We(),repaintStatus();return}this.#F=!0,this.#Ue(),this.#Pe(),i(interruptedError());return}if(a.type===`ctrl-r`){this.#ut();return}if(c===`select`){switch(a.type){case`up`:o>0&&(l=(l-1+o)%o,renderSection(),repaintStatus());break;case`down`:o>0&&(l=(l+1)%o,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=EMPTY_LINE,this.#He(),repaintStatus();break}let e=n[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let s=applyLineEditorKey(u,a,{multiline:!0});if(s!==void 0){u=s,this.#We(),repaintStatus();return}switch(a.type){case`up`:case`down`:{let e=movePromptLine(u,a.type);e!==void 0&&(u=e,this.#We(),repaintStatus());break}case`enter`:{let n=resolveQuestionText(u.text,e);if(n===void 0)break;t(finalize(n));break}case`escape`:if(r){if(u.text.length>0){u=EMPTY_LINE,this.#We(),repaintStatus();break}c=`select`,u=EMPTY_LINE,this.#k=!1,this.#Ue(),repaintStatus();break}u=EMPTY_LINE,this.#We(),repaintStatus();break;default:break}},this.#Fe()})}upsertSubagentStep(e){if(this.#o===`hidden`)return;let t=stripTerminalControls(e.reasoning??``).trim(),n=stripTerminalControls(e.message??``).trim();if(!(t.length===0&&n.length===0)){if(this.#Qe(e.callId,e.subagentName),this.#o===`collapsed`){this.#ut();return}this.#$e({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#ut()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#Qe(e.callId,e.subagentName),this.#o===`collapsed`){this.#ut();return}let t=subagentToolStatus(e.status),n={id:subagentToolSectionId(e.callId,e.childCallId),kind:`subagent-tool`,depth:1,title:stripTerminalControls(e.toolName),subtitle:summarizeToolArgs(e.input),status:t,live:t===`running`||t===`approval`,expanded:this.#o===`full`,toolInput:e.input};e.output===void 0?e.errorText!==void 0&&(n.result=stripTerminalControls(e.errorText)):(n.result=summarizeToolResult(e.output),n.toolOutput=e.output),this.#$e(n),this.#ut()}markChildToolCallId(e){this.#g.add(e);let t=this.#_.get(e);t!==void 0&&(this.#et(t),this.#_.delete(e),this.#ut())}#me(e){let t=this.#p.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=e.state===`authorized`||e.state===`declined`||e.state===`failed`||e.state===`timed-out`;this.#$e({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e),preformatted:!0,live:!t}),this.#ut()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#w)return;let n=this.#w>0;this.#w=t,t>0?(this.#M=STATUS.connectionAuth,this.#ut()):n&&(this.#M=STATUS.processing,this.#ut())}setVercelStatus(e){this.#T=e,this.#ut()}reset(){this.#f=[],this.#p.clear(),this.#m.clear(),this.#C=void 0,this.#S.length=0,this.#h.length=0,this.#b=!1,this.#x=void 0,this.#g.clear(),this.#_.clear(),this.#v.clear(),this.#ce=void 0,this.#oe=void 0,this.#w=0,this.#X=void 0,this.#Z=void 0,this.#$=void 0,this.#ee=void 0,this.#te=void 0,this.#P&&(this.#n.clearAll(),this.#ut())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ne(),this.#Je({kind:`notice`,body:t,live:!1}),this.#ut())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ne(),this.#Je({kind:`sandbox`,body:t,live:!1}),this.#ut())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#he();return}this.#Ne(),this.#ue=t,this.#ut()}clearSetupWarning(){this.#he()}#he(){this.#ue!==void 0&&(this.#ue=void 0,this.#ut())}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ne(),this.#Je({kind:`result`,body:t,live:!1}),this.#ut())}#ge(e,t=`spinner`){this.#Ne(),this.#k=!1,this.#j={kind:`idle`},this.#M=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#le={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Ge(),this.#ut()}#_e(e){this.#de=void 0,this.#ke();let t=this.#le;if(t!==void 0){if(this.#le=void 0,this.#qe(),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.#Je({kind:`flow`,title:`info`,body:e.join(`
|
|
3
|
-
`),live:!1}),this.#Je({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#ut()}}async#ve(e){let t=this.#Ce(),n=isMultiSelectRequest(e),r={options:e.options,submitRow:n};`initialValue`in e&&e.initialValue!==void 0&&(r.defaultValue=e.initialValue),`initialValues`in e&&e.initialValues!==void 0&&(r.initialValues=e.initialValues);let i=initialSelectState(r),a,o=e.notices;if(e.kind===`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}));o=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,select:i};return o!==void 0&&o.length>0&&(t.notices=o),a!==void 0&&(t.error=a),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#ut(),await this.#Ee((t,r)=>{let o={key:t,options:e.options,select:i},s=reduceSetupSelectInput(n?{...o,kind:e.kind,required:e.required}:{...o,kind:e.kind});switch(s.kind){case`cancel`:r(void 0);return;case`repaint`:this.#ut();return;case`update`:i=s.select,a=void 0,this.#ut();return;case`submit`:r(s.values);return;case`error`:a=s.message,this.#ut();return;case`ignore`:return}}).promise}#ye(e){this.#Ne();let t=this.#we();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#ut();let r=this.#Ee((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.#ut();return;case`repaint`:this.#ut();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#be(e){let t=this.#Ce(),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:`editable`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint,caretVisible:this.#I}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#He()):(i=lineOf(``),this.#Ue())};return syncEditableRow(),this.#ut(),await this.#Ee((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#We(),this.#ut()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#ut()},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.#ut();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.#ut();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ue()).promise}async#xe(e){let t=this.#Ce(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#I)},this.#He(),this.#ut(),await this.#Ee((t,i)=>{let apply=e=>{n=e,r=void 0,this.#We(),this.#ut()},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.#ut();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#ut();return}i(t);return}default:return}},()=>this.#Ue()).promise}async#Se(e){let t=this.#Ce();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#ut(),await this.#Ee((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#ut();return;default:return}}).promise}#Ce(){return this.#Ne(),this.#k=!1,this.#j={kind:`idle`},this.#M=``,this.#we()}#we(){return this.#le===void 0&&(this.#le={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#le}#Te(){this.#le!==void 0&&(this.#le.question=void 0,this.#le.hideLinesWhileQuestion=!1),this.#H=void 0,this.#Ie(),this.#Oe(),this.#ut()}#Ee(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#Te(),r(e))};return this.#H=t=>e(t,settle),this.#Fe(),{promise:i,settle}}#De(){let e,t=new Promise(t=>{e=t});return this.#de=e,this.#Oe(),{promise:t,dispose:()=>{this.#de===e&&(this.#de=void 0,this.#ke())}}}#Oe(){if(this.#de===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#de;this.#de=void 0,this.#ke(),e?.();return}e.type===`ctrl-r`&&this.#ut()};this.#fe=consumer,this.#H=consumer,this.#Fe()}#ke(){this.#fe!==void 0&&(this.#H===this.#fe&&this.#Ie(),this.#fe=void 0)}#Ae(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#le!==void 0){this.#le.status=t,t===void 0&&(this.#le.preview=void 0),this.#ut();return}if(t===void 0){this.#j={kind:`idle`},this.#M=``,this.#qe(),this.#ut();return}this.#Ne(),this.#Ke(),this.#M=t,this.#ut()}#je(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#le;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.#ut();return}this.#Ne(),this.#Je({kind:`flow`,title:t,body:n,live:!1}),this.#ut()}#Me(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#le;if(n===void 0){this.#je(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#ut()}shutdown(){this.#Pe()}#Ne(e){this.#N=e?.title??this.#N,this.#Q=e?.contextSize??this.#l,!this.#P&&(this.#P=!0,this.#n.reset(),this.#n.hideCursor(),this.#Tt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#K=()=>this.#ut(),this.#t.on(`resize`,this.#K))}#Pe(){this.#Ie(),this.#Ue(),this.#qe(),this.#B!==void 0&&(clearTimeout(this.#B),this.#B=void 0),this.#V=!1,this.#P&&=(this.#Nt(),this.#ut(),this.#n.clear(),this.#n.showCursor(),this.#Et(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#K&&=(this.#t.off(`resize`,this.#K),void 0),!1)}#Fe(){this.#e.off(`data`,this.#Le),this.#e.on(`data`,this.#Le)}#Ie(){this.#e.off(`data`,this.#Le),this.#Be(),this.#U=``,this.#W=new StringDecoder(`utf8`),this.#H=void 0}#Le=e=>{this.#Be(),this.#U+=this.#W.write(e),this.#ze(),this.#Re()};#Re(){if(this.#U===`\x1B`){this.#G=setTimeout(()=>{this.#U===`\x1B`&&(this.#U=``,this.#H?.({type:`escape`}))},30),this.#G.unref?.();return}if(isIncompletePaste(this.#U)){let e=this.#U;this.#G=setTimeout(()=>{if(this.#U!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#U=``,t.length>0&&this.#H?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#G.unref?.()}}#ze(){for(;this.#U.length>0;){let e=nextKey(this.#U);if(e.incomplete)return;this.#U=this.#U.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#H?.(e.key)}}#Be(){this.#G&&=(clearTimeout(this.#G),void 0)}#Ve(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#ut();break;case`ctrl-c`:this.#F||(this.#F=!0,this.#j={kind:`idle`},this.#M=`Interrupted`,this.#q?.(),this.#ut());break;default:break}}#He(){this.#Ue(),this.#We(),this.#R=setInterval(()=>{this.#I=!this.#I,this.#ut()},500),this.#R.unref?.()}#Ue(){this.#R&&=(clearInterval(this.#R),void 0),this.#I=!0}#We(){this.#I=!0}#Ge(){this.#qe(),this.#z=setInterval(()=>{this.#L+=1,this.#ut()},90),this.#z.unref?.()}#Ke(){this.#j={kind:`waiting`,startedAtMs:Date.now()},this.#Ge()}#qe(){this.#z&&=(clearInterval(this.#z),void 0)}#Je(e){e.id!==this.#oe?.id&&this.#Nt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Ye(e){this.#Je({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#ut()}#Xe(e){if(e!=null){if(this.#ce===e){this.#ce=void 0;return}this.#Je({kind:`user`,body:stripTerminalControls(e),live:!1})}}#Ze(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Je(r),this.#ut()}#Qe(e,t){this.#v.has(e)||(this.#v.add(e),this.#Je({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#$e(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Je(e)}#et(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#tt(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#nt(e,t,n){switch(e.type){case`step-start`:this.#rt(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#lt(e.usage),this.#ut();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#it(t),this.#rt(STATUS.streaming),n.text.set(e.id,t),this.#at(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;this.#it(r),n.text.set(e.id,r),this.#at(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#it(r),this.#rt(STATUS.streaming),n.reasoning.set(e.id,r),this.#ot(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#it(r),this.#ot(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#rt(STATUS.executingTools),this.#st({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.#st({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#ct(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#rt(STATUS.toolResults),this.#st({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#ct(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#rt(STATUS.toolResults),this.#st({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#Ze(`Error`,e.errorText,e.detail);break;case`finish`:this.#lt(e.usage),this.#ut();break}}#rt(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#M!==t&&(this.#M=t,this.#ut())}#it(e){e.trim().length>0&&(this.#j={kind:`answering`})}#at(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#$e({id:e,kind:`assistant`,body:r,live:n}),this.#ut())}#ot(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#$e({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#ut())}#st(e,t,n){if(n.tools.set(e.toolCallId,e),this.#g.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#_.set(e.toolCallId,r),this.#$e(renderNativeToolBlock(e,r,t.tools===`full`)),this.#ut()}#ct(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#_.get(e)??toolSectionId(e),i=this.#p.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.title??`tool`}}#lt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#X=(t??0)+(n??0)),this.#Z=t??this.#Z,this.#$=n??this.#$,this.#$!=null&&this.#te!==void 0){let e=(Date.now()-this.#te)/1e3;e>0&&(this.#ee=this.#$/e)}}#ut(){if(this.#P){if(this.#J){this.#Y=!0;return}this.#J=!0;try{do this.#Y=!1,this.#dt();while(this.#Y)}finally{this.#J=!1}}}#dt(){if(!this.#P)return;let e=this.#Ct(),t=this.#bt(e),n=Math.max(1,this.#wt()-t.length),r=[],i=this.#C;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift();if(this.#h.push(t),t.id&&(this.#m.add(t.id),this.#p.delete(t.id)),this.#Ft(t))continue;let n=this.#gt(t,e,i);i=previousBlockOf(t),this.#C=i,r.push(...n),this.#S.push(...n)}let a=[];for(let t of this.#f){if(this.#Ft(t))continue;let n=this.#gt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ft(){if(!this.#P)return;let e=this.#Ct(),t=this.#bt(e),n=Math.max(1,this.#wt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#Ft(t))continue;let n=this.#gt(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#ht(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#mt(),this.#P&&this.#ft())}flushDelayedDevBuildErrors(){let e=this.#ae;e!==void 0&&(this.#ae=void 0,this.#Je({kind:`log`,title:`stderr`,body:e,live:!1}),this.#ut())}#pt(){this.#V=!0,this.#B!==void 0&&clearTimeout(this.#B),this.#B=setTimeout(()=>{this.#V=!1,this.#B=void 0,this.#ut()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#d)),this.#ut()}#mt(){let e=this.#Ct();this.#S.length=0;let t;for(let n of this.#h){if(this.#Ft(n))continue;let r=this.#gt(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#ht(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Ct()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#gt(e,t,n){let r={spinner:this.#_t()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#_t(){return this.#r.spinner[this.#L%this.#r.spinner.length]??``}#vt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#yt(e){return e.indicator.kind===`spinner`?{glyph:this.#_t(),color:`yellow`}:{glyph:this.#vt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#bt(e){let t=this.#r.colors,n=[``],r=this.#le;if(r!==void 0){let t=this.#yt(r),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),n}if(this.#ue!==void 0&&n.push(...renderAttentionRows(this.#ue,e,this.#r),``),this.#k){let r=this.#A===void 0?void 0:inlineCommandHint(this.#A);r===void 0&&this.#A!==void 0&&isTypeaheadOpen(this.#A)&&n.push(...renderCommandSuggestions(this.#A,this.#r,e));let i=isPromptControlCommand(this.#E),a=r?t.dim(` ${r}`):``,o=[];this.#xt(o,e);let s=Math.max(1,this.#wt()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#E,cursor:this.#D,width:e,theme:this.#r,caretVisible:this.#I,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#j;if(i.kind===`answering`)return this.#xt(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#vt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#M.length>0?this.#M:`Ready`,c=a?t.dim(s):s,u=this.#St(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#xt(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#xt(e,t){let n={theme:this.#r,width:t};this.#V&&(n.logLevel=this.#d);let r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#Z??0,o=this.#$??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#Q!==void 0&&(e.contextSize=this.#Q),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#St(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#X,outputTokens:this.#$,tokensPerSecond:this.#ee},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Ct(){return Math.max(20,this.#t.columns||80)}#wt(){return Math.max(8,this.#t.rows||24)}#Tt(){if(this.#ne!==void 0||!this.#u)return;this.#re=``,this.#ie=``;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.#Dt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ne=()=>{e(),t()}}#Et(){let e=this.#ne;e!==void 0&&(this.#ne=void 0,e(),this.#re.length>0&&(this.#Pt(`stdout`)&&process.stdout.write(`${this.#re}\n`),this.#re=``),this.#ie.length>0&&(this.#Pt(`stderr`)&&process.stderr.write(`${this.#ie}\n`),this.#ie=``))}#Dt(e,t){let n=(e===`stdout`?this.#re:this.#ie)+t,i=n.lastIndexOf(`
|
|
3
|
+
`),live:!1}),this.#Je({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#ut()}}async#ve(e){let t=this.#Ce(),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.#ut()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#ut();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.#ut())}},u=e.notices;if(e.kind===`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.#_t()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#ut(),await this.#Ee((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.#ut();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.#ut();return;case`update`:o=d.select,s=void 0,this.#ut();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.#ut();return;case`ignore`:return}}).promise}#ye(e){this.#Ne();let t=this.#we();t.status=e.status;let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#ut();let r=this.#Ee((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.#ut();return;case`repaint`:this.#ut();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#be(e){let t=this.#Ce(),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:`editable`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint,caretVisible:this.#I}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?(i.text.length===0&&(i=lineOf(e.editable.defaultValue)),this.#He()):(i=lineOf(``),this.#Ue())};return syncEditableRow(),this.#ut(),await this.#Ee((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#We(),this.#ut()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#ut()},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.#ut();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.#ut();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ue()).promise}async#xe(e){let t=this.#Ce(),n=lineOf(``),r;return t.question=t=>{let i={message:e.message,editor:n,mask:e.mask===!0};return e.placeholder!==void 0&&(i.placeholder=e.placeholder),e.notices!==void 0&&(i.notices=e.notices),r!==void 0&&(i.error=r),renderTextQuestion(i,this.#r,t,this.#I)},this.#He(),this.#ut(),await this.#Ee((t,i)=>{let apply=e=>{n=e,r=void 0,this.#We(),this.#ut()},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.#ut();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#ut();return}i(t);return}default:return}},()=>this.#Ue()).promise}async#Se(e){let t=this.#Ce();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#ut(),await this.#Ee((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#ut();return;default:return}}).promise}#Ce(){return this.#Ne(),this.#k=!1,this.#j={kind:`idle`},this.#M=``,this.#we()}#we(){return this.#le===void 0&&(this.#le={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#le}#Te(){this.#le!==void 0&&(this.#le.question=void 0,this.#le.hideLinesWhileQuestion=!1),this.#H=void 0,this.#Ie(),this.#Oe(),this.#ut()}#Ee(e,t){let n=!1,r,i=new Promise(e=>{r=e}),settle=e=>{n||(n=!0,t?.(),this.#Te(),r(e))};return this.#H=t=>e(t,settle),this.#Fe(),{promise:i,settle}}#De(){let e,t=new Promise(t=>{e=t});return this.#de=e,this.#Oe(),{promise:t,dispose:()=>{this.#de===e&&(this.#de=void 0,this.#ke())}}}#Oe(){if(this.#de===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#de;this.#de=void 0,this.#ke(),e?.();return}e.type===`ctrl-r`&&this.#ut()};this.#fe=consumer,this.#H=consumer,this.#Fe()}#ke(){this.#fe!==void 0&&(this.#H===this.#fe&&this.#Ie(),this.#fe=void 0)}#Ae(e){let t=e===void 0?void 0:stripTerminalControls(e);if(this.#le!==void 0){this.#le.status=t,t===void 0&&(this.#le.preview=void 0),this.#ut();return}if(t===void 0){this.#j={kind:`idle`},this.#M=``,this.#qe(),this.#ut();return}this.#Ne(),this.#Ke(),this.#M=t,this.#ut()}#je(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#le;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.#ut();return}this.#Ne(),this.#Je({kind:`flow`,title:t,body:n,live:!1}),this.#ut()}#Me(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#le;if(n===void 0){this.#je(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#ut()}shutdown(){this.#Pe()}#Ne(e){this.#N=e?.title??this.#N,this.#Q=e?.contextSize??this.#l,!this.#P&&(this.#P=!0,this.#n.reset(),this.#n.hideCursor(),this.#Tt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#K=()=>this.#ut(),this.#t.on(`resize`,this.#K))}#Pe(){this.#Ie(),this.#Ue(),this.#qe(),this.#B!==void 0&&(clearTimeout(this.#B),this.#B=void 0),this.#V=!1,this.#P&&=(this.#Nt(),this.#ut(),this.#n.clear(),this.#n.showCursor(),this.#Et(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#K&&=(this.#t.off(`resize`,this.#K),void 0),!1)}#Fe(){this.#e.off(`data`,this.#Le),this.#e.on(`data`,this.#Le)}#Ie(){this.#e.off(`data`,this.#Le),this.#Be(),this.#U=``,this.#W=new StringDecoder(`utf8`),this.#H=void 0}#Le=e=>{this.#Be(),this.#U+=this.#W.write(e),this.#ze(),this.#Re()};#Re(){if(this.#U===`\x1B`){this.#G=setTimeout(()=>{this.#U===`\x1B`&&(this.#U=``,this.#H?.({type:`escape`}))},30),this.#G.unref?.();return}if(isIncompletePaste(this.#U)){let e=this.#U;this.#G=setTimeout(()=>{if(this.#U!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#U=``,t.length>0&&this.#H?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#G.unref?.()}}#ze(){for(;this.#U.length>0;){let e=nextKey(this.#U);if(e.incomplete)return;this.#U=this.#U.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#H?.(e.key)}}#Be(){this.#G&&=(clearTimeout(this.#G),void 0)}#Ve(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#ut();break;case`ctrl-c`:this.#F||(this.#F=!0,this.#j={kind:`idle`},this.#M=`Interrupted`,this.#q?.(),this.#ut());break;default:break}}#He(){this.#Ue(),this.#We(),this.#R=setInterval(()=>{this.#I=!this.#I,this.#ut()},500),this.#R.unref?.()}#Ue(){this.#R&&=(clearInterval(this.#R),void 0),this.#I=!0}#We(){this.#I=!0}#Ge(){this.#qe(),this.#z=setInterval(()=>{this.#L+=1,this.#ut()},90),this.#z.unref?.()}#Ke(){this.#j={kind:`waiting`,startedAtMs:Date.now()},this.#Ge()}#qe(){this.#z&&=(clearInterval(this.#z),void 0)}#Je(e){e.id!==this.#oe?.id&&this.#Nt(),this.#f.push(e),e.id&&this.#p.set(e.id,e)}#Ye(e){this.#Je({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#ut()}#Xe(e){if(e!=null){if(this.#ce===e){this.#ce=void 0;return}this.#Je({kind:`user`,body:stripTerminalControls(e),live:!1})}}#Ze(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Je(r),this.#ut()}#Qe(e,t){this.#v.has(e)||(this.#v.add(e),this.#Je({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#$e(e){if(e.id&&this.#m.has(e.id))return;let t=e.id?this.#p.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Je(e)}#et(e){this.#f=this.#f.filter(t=>t.id!==e),this.#p.delete(e)}#tt(){for(let e of this.#f)e.status===`approval`||e.status===`running`||(e.live=!1)}#nt(e,t,n){switch(e.type){case`step-start`:this.#rt(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#lt(e.usage),this.#ut();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#it(t),this.#rt(STATUS.streaming),n.text.set(e.id,t),this.#at(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;this.#it(r),n.text.set(e.id,r),this.#at(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#it(r),this.#rt(STATUS.streaming),n.reasoning.set(e.id,r),this.#ot(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#it(r),this.#ot(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#rt(STATUS.executingTools),this.#st({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.#st({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#ct(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#rt(STATUS.toolResults),this.#st({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#ct(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#rt(STATUS.toolResults),this.#st({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#Ze(`Error`,e.errorText,e.detail);break;case`finish`:this.#lt(e.usage),this.#ut();break}}#rt(e){let t=this.#w>0?STATUS.connectionAuth:e;this.#M!==t&&(this.#M=t,this.#ut())}#it(e){e.trim().length>0&&(this.#j={kind:`answering`})}#at(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#$e({id:e,kind:`assistant`,body:r,live:n}),this.#ut())}#ot(e,t,n,r){let a=stripTerminalControls(t).trim();a.length!==0&&(this.#$e({id:e,kind:`reasoning`,body:a,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#ut())}#st(e,t,n){if(n.tools.set(e.toolCallId,e),this.#g.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#_.set(e.toolCallId,r),this.#$e(renderNativeToolBlock(e,r,t.tools===`full`)),this.#ut()}#ct(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#_.get(e)??toolSectionId(e),i=this.#p.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.title??`tool`}}#lt(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#X=(t??0)+(n??0)),this.#Z=t??this.#Z,this.#$=n??this.#$,this.#$!=null&&this.#te!==void 0){let e=(Date.now()-this.#te)/1e3;e>0&&(this.#ee=this.#$/e)}}#ut(){if(this.#P){if(this.#J){this.#Y=!0;return}this.#J=!0;try{do this.#Y=!1,this.#dt();while(this.#Y)}finally{this.#J=!1}}}#dt(){if(!this.#P)return;let e=this.#Ct(),t=this.#bt(e),n=Math.max(1,this.#wt()-t.length),r=[],i=this.#C;for(;this.#f.length>0&&this.#f[0].live===!1;){let t=this.#f.shift();if(this.#h.push(t),t.id&&(this.#m.add(t.id),this.#p.delete(t.id)),this.#Ft(t))continue;let n=this.#gt(t,e,i);i=previousBlockOf(t),this.#C=i,r.push(...n),this.#S.push(...n)}let a=[];for(let t of this.#f){if(this.#Ft(t))continue;let n=this.#gt(t,e,i);i=previousBlockOf(t);for(let e=0;e<n.length;e+=1)a.push({block:t,row:n[e]})}let o=[...clipLiveRows(a.map(e=>e.row),n,e,this.#r),...t];r.length>0?this.#n.flush(r,o):this.#n.update(o)}#ft(){if(!this.#P)return;let e=this.#Ct(),t=this.#bt(e),n=Math.max(1,this.#wt()-t.length),r=this.#C,i=[];for(let t of this.#f){if(this.#Ft(t))continue;let n=this.#gt(t,e,r);r=previousBlockOf(t),i.push(...n)}let a=[...clipLiveRows(i,n,e,this.#r),...t];this.#n.clearAll(),this.#n.flush([...this.#ht(),...this.#S],a)}logDisplayMode(){return this.#d}setLogDisplayMode(e){e!==this.#d&&(this.#d=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#mt(),this.#P&&this.#ft())}flushDelayedDevBuildErrors(){let e=this.#ae;e!==void 0&&(this.#ae=void 0,this.#Je({kind:`log`,title:`stderr`,body:e,live:!1}),this.#ut())}#pt(){this.#V=!0,this.#B!==void 0&&clearTimeout(this.#B),this.#B=setTimeout(()=>{this.#V=!1,this.#B=void 0,this.#ut()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#d)),this.#ut()}#mt(){let e=this.#Ct();this.#S.length=0;let t;for(let n of this.#h){if(this.#Ft(n))continue;let r=this.#gt(n,e,t);t=previousBlockOf(n),this.#S.push(...r)}this.#C=t}#ht(){let e=this.#y;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Ct()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#gt(e,t,n){let r={spinner:this.#_t()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#_t(){return this.#r.spinner[this.#L%this.#r.spinner.length]??``}#vt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#yt(e){return e.indicator.kind===`spinner`?{glyph:this.#_t(),color:`yellow`}:{glyph:this.#vt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:`green`}}#bt(e){let t=this.#r.colors,n=[``],r=this.#le;if(r!==void 0){let t=this.#yt(r),i;if(r.question!==void 0){let n=r.question(e);i={kind:`question`,rows:n},r.status!==void 0&&(i={kind:`question`,rows:n,status:{text:r.status,indicator:t}})}else r.status===void 0?i=r.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:r.preview,indicator:t}:(i={kind:`status`,status:{text:r.status,indicator:t}},r.preview!==void 0&&(i={kind:`status`,status:{text:r.status,indicator:t},preview:r.preview}));let a={title:r.title,lines:r.hideLinesWhileQuestion===!0?[]:r.lines,content:i};return n.push(...renderFlowPanel(a,this.#r,e)),n}if(this.#ue!==void 0&&n.push(...renderAttentionRows(this.#ue,e,this.#r),``),this.#k){let r=this.#A===void 0?void 0:inlineCommandHint(this.#A);r===void 0&&this.#A!==void 0&&isTypeaheadOpen(this.#A)&&n.push(...renderCommandSuggestions(this.#A,this.#r,e));let i=isPromptControlCommand(this.#E),a=r?t.dim(` ${r}`):``,o=[];this.#xt(o,e);let s=Math.max(1,this.#wt()-1-n.length-1-o.length);return n.push(...promptInputRows({text:this.#E,cursor:this.#D,width:e,theme:this.#r,caretVisible:this.#I,isCommand:i,ghost:a,maxRows:s})),n.push(...o),n}let i=this.#j;if(i.kind===`answering`)return this.#xt(n,e),n;let a=i.kind===`waiting`,o=a?t.green(this.#vt(i.startedAtMs,this.#r.unicode?`⊙`:`o`)):t.dim(this.#r.glyph.dot),s=this.#M.length>0?this.#M:`Ready`,c=a?t.dim(s):s,u=this.#St(),f=a?` `:``,p=u?`${f}${o} ${c} ${t.dim(this.#r.glyph.dot)} ${u}`:`${f}${o} ${c}`;n.push(clip(p,e));let g=[];return this.#xt(g,e),a&&g.length>0&&n.push(``),n.push(...g),n}#xt(e,t){let n={theme:this.#r,width:t};this.#V&&(n.logLevel=this.#d);let r=this.#y?.info?.agent.model.id;r!==void 0&&(n.model=r);let i=this.#y?.info?.agent.model.endpoint;i!==void 0&&(n.endpoint=i);let a=this.#Z??0,o=this.#$??0;if(a>0||o>0){let e={inputTokens:a,outputTokens:o};this.#Q!==void 0&&(e.contextSize=this.#Q),n.tokens=formatTokenFlow(e,this.#r.glyph)}this.#T!==void 0&&(n.vercel=this.#T);let s=buildStatusLine(n);s!==void 0&&e.push(s)}#St(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#X,outputTokens:this.#$,tokensPerSecond:this.#ee},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Ct(){return Math.max(20,this.#t.columns||80)}#wt(){return Math.max(8,this.#t.rows||24)}#Tt(){if(this.#ne!==void 0||!this.#u)return;this.#re=``,this.#ie=``;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.#Dt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ne=()=>{e(),t()}}#Et(){let e=this.#ne;e!==void 0&&(this.#ne=void 0,e(),this.#re.length>0&&(this.#Pt(`stdout`)&&process.stdout.write(`${this.#re}\n`),this.#re=``),this.#ie.length>0&&(this.#Pt(`stderr`)&&process.stderr.write(`${this.#ie}\n`),this.#ie=``))}#Dt(e,t){let n=(e===`stdout`?this.#re:this.#ie)+t,i=n.lastIndexOf(`
|
|
4
4
|
`),a=i===-1?n:n.slice(i+1);if(e===`stdout`?this.#re=a:this.#ie=a,i===-1)return;let o=stripAnsi(n.slice(0,i)).replace(/\s+$/u,``);o.trim().length!==0&&(e===`stdout`?this.#Ot(o):this.#kt(o),this.#ut())}#Ot(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
5
5
|
`);t=[],e.trim().length!==0&&this.#Je({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
|
|
6
6
|
`)){let e=parseSandboxLogLine(n.trimEnd());if(e!==void 0){flushPending(),this.#Je({kind:`sandbox`,body:e,live:!1});continue}let r=parseDevRebuildLogLine(n.trimEnd());if(r===void 0){t.push(n);continue}flushPending(),this.#jt(r,n.trimEnd())}flushPending()}#kt(e){let t=e.split(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WizardCancelledError}from"#setup/step.js";import{createSelectOptionCodec}from"#setup/cli/select-option-codec.js";function setupSelectRequest(e,t,n){let
|
|
1
|
+
import{WizardCancelledError}from"#setup/step.js";import{searchActionQuery}from"#setup/cli/select-state.js";import{createSelectOptionCodec}from"#setup/cli/select-option-codec.js";function setupSelectRequest(e,t,n,r){let i={message:e.message,options:t},withNotices=t=>(e.notices!==void 0&&(t.notices=e.notices),t);if(e.multiple===!0){if(e.hintLayout!==void 0)throw Error(`Multi-select setup questions do not support a hint layout.`);let t;return e.search===!0?(t={...i,kind:`searchable-multi`,required:e.required??!1},e.placeholder!==void 0&&(t.placeholder=e.placeholder)):t={...i,kind:`multi`,required:e.required??!1},e.initialValues!==void 0&&(t.initialValues=e.initialValues.map(n)),withNotices(t)}if(e.search===!0&&e.hintLayout!==void 0)throw Error(`Searchable setup questions do not support a hint layout.`);let a;if(e.search===!0){if(a={...i,kind:`search`},e.placeholder!==void 0&&(a.placeholder=e.placeholder),e.searchAction!==void 0){a.searchAction={label:e.searchAction.label};let t=e.searchAction.load;t!==void 0&&(a.searchAction.load=async e=>r(await t(e)))}}else{let t=e.hintLayout===`inline`?`task-list`:e.hintLayout??`single`;a={...i,kind:t}}return e.initialValue!==void 0&&(a.initialValue=n(e.initialValue)),withNotices(a)}function createTuiPrompter(r){function guardCancel(t){if(t===void 0)throw new WizardCancelledError;return t}async function select(e){let i=createSelectOptionCodec(e.options),a=setupSelectRequest(e,i.options,i.encode,i.encodeOptions),o=guardCancel(await r.readSelect(a)).map(n=>{let r=searchActionQuery(n);return r!==void 0&&e.multiple!==!0&&e.searchAction!==void 0?e.searchAction.value(r):i.decode(n)});if(e.multiple===!0)return o;let s=o[0];if(s===void 0)throw Error(`Single-select returned no option.`);return s}function line(e){return t=>r.renderLine(t,e)}return{async text(e){let t={message:e.message};return e.placeholder!==void 0&&(t.placeholder=e.placeholder),e.defaultValue!==void 0&&(t.defaultValue=e.defaultValue),e.validate!==void 0&&(t.validate=e.validate),e.notices!==void 0&&(t.notices=e.notices),guardCancel(await r.readText(t))},async password(e){let t={message:e.message,mask:!0};return e.validate!==void 0&&(t.validate=e.validate),guardCancel(await r.readText(t))},select,async selectEditable(e){let t=createSelectOptionCodec(e.options),i={value:t.encode(e.editable.value),defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint};e.editable.validate!==void 0&&(i.validate=e.editable.validate);let a={message:e.message,options:t.options,editable:i};e.initialValue!==void 0&&(a.initialValue=t.encode(e.initialValue));let o=guardCancel(await r.readEditableSelect(a)),s=t.decode(o.value);return o.kind===`edited`?{kind:`edited`,value:s,text:o.text}:{kind:`selected`,value:s}},async acknowledge(e){await r.readAcknowledge({message:e.message,lines:e.lines??[]})},awaitChoice(e){return r.readChoice(e)},note(e,t,n){let i=n?.tone===`success`?`success`:`warning`;t&&r.renderLine(t,i),r.renderLine(e,i)},intro(){},outro(){},log:{message:line(`info`),info:line(`info`),success:line(`success`),warning:line(`warning`),error:line(`error`),commandOutput:e=>r.renderOutput(e),section(e,t){r.renderLine(e,`info`);for(let e of t)r.renderLine(` ${e}`,`info`)},spinner(e){r.setStatus(e);let t=!1;return{stop(){t||(t=!0,r.setStatus(void 0))}}}}}}export{createTuiPrompter};
|
|
@@ -54,8 +54,9 @@ export interface DurableSessionState {
|
|
|
54
54
|
* `agent.compactionModelReference`, and the `compaction` thresholds —
|
|
55
55
|
* those are rebuilt every turn from `bundle.turnAgent` by
|
|
56
56
|
* {@link import("#execution/session.js").hydrateDurableSession}.
|
|
57
|
-
* `agent.system` is the
|
|
58
|
-
*
|
|
57
|
+
* `agent.system` is the last applied prompt snapshot. Before each model step,
|
|
58
|
+
* the execution layer replaces it from the current deployment's
|
|
59
|
+
* `bundle.turnAgent`.
|
|
59
60
|
*/
|
|
60
61
|
export interface DurableSession {
|
|
61
62
|
readonly sessionId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{jsonSchema}from"ai";import{createToolLoopHarness}from"#harness/tool-loop.js";import{resolveCodeModeEnabled}from"#shared/code-mode.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=createNodeHarnessTools({node:e.node});return createToolLoopHarness({capabilities:e.capabilities,codeMode:resolveCodeModeEnabled(e.node.agent.config?.experimental?.codeMode),workflow:e.node.agent.workflowEnabled===!0,handleEvent:e.handleEvent,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:n})}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version,modelId:e.turnAgent.model.id},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return t.has(`agent`)||t.set(`agent`,{description:`Launch a new agent to handle a complex, multi-step subtask.`,inputSchema:jsonSchema(SUBAGENT_TOOL_INPUT_SCHEMA),name:`agent`,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:`agent`}}),t}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`subagent-call`,nodeId:e.tool.nodeId,subagentName:e.tool.name}};if(e.tool.kind===`remote`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`remote-agent-call`,nodeId:e.tool.nodeId,remoteAgentName:e.tool.name,subagentName:e.tool.name}};let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(t===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=t.definition,i=r.sourceId.startsWith(`eve:`),a=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{jsonSchema}from"ai";import{createToolLoopHarness}from"#harness/tool-loop.js";import{resolveCodeModeEnabled}from"#shared/code-mode.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=createNodeHarnessTools({node:e.node});return createToolLoopHarness({capabilities:e.capabilities,codeMode:resolveCodeModeEnabled(e.node.agent.config?.experimental?.codeMode),workflow:e.node.agent.workflowEnabled===!0,handleEvent:e.handleEvent,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:n})}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version,modelId:e.turnAgent.model.id},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return t.has(`agent`)||t.set(`agent`,{description:`Launch a new agent to handle a complex, multi-step subtask.`,inputSchema:jsonSchema(SUBAGENT_TOOL_INPUT_SCHEMA),name:`agent`,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:`agent`}}),t}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`subagent-call`,nodeId:e.tool.nodeId,subagentName:e.tool.name}};if(e.tool.kind===`remote`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`remote-agent-call`,nodeId:e.tool.nodeId,remoteAgentName:e.tool.name,subagentName:e.tool.name}};let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(t===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=t.definition,i=r.sourceId.startsWith(`eve:`),a=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({isFrameworkTool:i,rawExecute:a,scope:r.name}),inputSchema:r.inputStandardSchema??jsonSchema(r.inputSchema??{}),name:r.name,needsApproval:r.needsApproval,outputSchema:r.outputStandardSchema??maybeJsonSchema(r.outputSchema),toModelOutput:r.toModelOutput}}function resolveAuthoredExecute(e){let{isFrameworkTool:t,rawExecute:n,scope:r}=e;return n===void 0?void 0:t?n:createToolExecuteWithAuth({execute:n,scope:r})}function maybeJsonSchema(e){return e===void 0?void 0:jsonSchema(e)}export{createExecutionNodeStep,createNodeHarnessTools};
|
|
@@ -33,22 +33,16 @@ export interface CreateSessionInput {
|
|
|
33
33
|
readonly turnAgent: RuntimeTurnAgent;
|
|
34
34
|
readonly outputSchema?: HarnessSession["outputSchema"];
|
|
35
35
|
}
|
|
36
|
-
/**
|
|
37
|
-
* Creates a fresh {@link HarnessSession}. The only site that derives
|
|
38
|
-
* `session.agent.system` from a `turnAgent` — every subsequent turn
|
|
39
|
-
* preserves the prompt via {@link refreshSessionFromTurnAgent}.
|
|
40
|
-
*/
|
|
36
|
+
/** Creates a fresh {@link HarnessSession} from the current `turnAgent`. */
|
|
41
37
|
export declare function createSession(input: CreateSessionInput): HarnessSession;
|
|
42
38
|
/**
|
|
43
|
-
* Refreshes a session with the latest `turnAgent` — replaces
|
|
44
|
-
* metadata and
|
|
45
|
-
*
|
|
46
|
-
* while dev HMR callers can opt into refreshing it from authored source.
|
|
39
|
+
* Refreshes a session with the latest `turnAgent` — replaces the system
|
|
40
|
+
* prompt, model/tool metadata, and compaction thresholds while preserving
|
|
41
|
+
* conversation history and state.
|
|
47
42
|
*/
|
|
48
43
|
export declare function refreshSessionFromTurnAgent(input: {
|
|
49
44
|
readonly session: HarnessSession;
|
|
50
45
|
readonly turnAgent: RuntimeTurnAgent;
|
|
51
|
-
readonly refreshSystemPrompt?: boolean;
|
|
52
46
|
readonly compactionOverrides?: {
|
|
53
47
|
readonly thresholdPercent?: number;
|
|
54
48
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
function createCompactionConfig(e={}){let t=e.thresholdPercent??.9,n={recentWindowSize:10,threshold:e.contextWindowTokens===void 0?1e5:Math.max(1,Math.floor(e.contextWindowTokens*t))};return e.lastKnownInputTokens===void 0?n:{...n,lastKnownInputTokens:e.lastKnownInputTokens,lastKnownPromptMessageCount:e.lastKnownPromptMessageCount}}function createSession(e){let{turnAgent:t}=e,n=createSessionToolDefinitions(t),r={agent:{compactionModelReference:t.compactionModel,modelReference:t.model,system:t.instructions.join(`
|
|
2
2
|
|
|
3
|
-
`),tools:n},compaction:createCompactionConfig({contextWindowTokens:t.model.contextWindowTokens,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:e.continuationToken,history:[],sessionId:e.sessionId};return e.rootSessionId!==void 0&&(r.rootSessionId=e.rootSessionId),e.outputSchema!==void 0&&(r.outputSchema=e.outputSchema),r}function refreshSessionFromTurnAgent(e){return{...e.session,agent:{compactionModelReference:e.turnAgent.compactionModel,modelReference:e.turnAgent.model,system:e.
|
|
3
|
+
`),tools:n},compaction:createCompactionConfig({contextWindowTokens:t.model.contextWindowTokens,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:e.continuationToken,history:[],sessionId:e.sessionId};return e.rootSessionId!==void 0&&(r.rootSessionId=e.rootSessionId),e.outputSchema!==void 0&&(r.outputSchema=e.outputSchema),r}function refreshSessionFromTurnAgent(e){return{...e.session,agent:{compactionModelReference:e.turnAgent.compactionModel,modelReference:e.turnAgent.model,system:e.turnAgent.instructions.join(`
|
|
4
4
|
|
|
5
|
-
`)
|
|
5
|
+
`),tools:createSessionToolDefinitions(e.turnAgent)},compaction:createCompactionConfig({contextWindowTokens:e.turnAgent.model.contextWindowTokens,lastKnownInputTokens:e.session.compaction.lastKnownInputTokens,lastKnownPromptMessageCount:e.session.compaction.lastKnownPromptMessageCount,thresholdPercent:e.compactionOverrides?.thresholdPercent})}}function mintSubagentContinuationToken(e){return`subagent:${e??crypto.randomUUID()}`}function projectToDurableSession(e){let t={agent:{system:e.agent.system},continuationToken:e.continuationToken,history:e.history,sessionId:e.sessionId};return(e.compaction.lastKnownInputTokens!==void 0||e.compaction.lastKnownPromptMessageCount!==void 0)&&(t.compaction={lastKnownInputTokens:e.compaction.lastKnownInputTokens,lastKnownPromptMessageCount:e.compaction.lastKnownPromptMessageCount}),e.rootSessionId!==void 0&&(t.rootSessionId=e.rootSessionId),e.outputSchema!==void 0&&(t.outputSchema=e.outputSchema),e.sandboxState!==void 0&&(t.sandboxState=e.sandboxState),e.state!==void 0&&(t.state=e.state),t}function hydrateDurableSession(e){let{durable:t,turnAgent:n}=e,r=createSessionToolDefinitions(n),i={agent:{compactionModelReference:n.compactionModel,modelReference:n.model,system:t.agent.system,tools:r},compaction:createCompactionConfig({contextWindowTokens:n.model.contextWindowTokens,lastKnownInputTokens:t.compaction?.lastKnownInputTokens,lastKnownPromptMessageCount:t.compaction?.lastKnownPromptMessageCount,thresholdPercent:e.compactionOverrides?.thresholdPercent}),continuationToken:t.continuationToken,history:t.history,sessionId:t.sessionId};return t.rootSessionId!==void 0&&(i.rootSessionId=t.rootSessionId),t.outputSchema!==void 0&&(i.outputSchema=t.outputSchema),t.sandboxState!==void 0&&(i.sandboxState=t.sandboxState),t.state!==void 0&&(i.state=t.state),i}function createSessionToolDefinitions(e){return e.tools.map(e=>({description:e.description??``,inputSchema:e.inputSchema,name:e.name,outputSchema:e.outputSchema}))}export{createCompactionConfig,createSession,hydrateDurableSession,mintSubagentContinuationToken,projectToDurableSession,refreshSessionFromTurnAgent};
|
|
@@ -1,56 +1,33 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Tool-hosted authorization wiring for authored tools that
|
|
3
|
-
*
|
|
2
|
+
* Tool-hosted authorization wiring for authored tools that resolve auth
|
|
3
|
+
* providers inline with {@link ToolContext.getToken} and
|
|
4
|
+
* {@link ToolContext.requireAuth}.
|
|
4
5
|
*
|
|
5
6
|
* Mirrors the connection authorization flow (see
|
|
6
7
|
* `runtime/framework-tools/connection-search-dynamic.ts`) but scopes the
|
|
7
8
|
* per-step token cache and framework-owned callback URL by the tool's
|
|
8
|
-
* path-derived name instead of a connection name. All the shared
|
|
9
|
+
* path-derived name and provider key instead of a connection name. All the shared
|
|
9
10
|
* machinery — principal resolution, cache reads/writes, the park/resume
|
|
10
11
|
* webhook dance, and the loop guard — lives in
|
|
11
12
|
* `runtime/connections/scoped-authorization.ts`; this module is the thin
|
|
12
13
|
* execution-layer adapter that wraps one tool's `execute`.
|
|
13
14
|
*/
|
|
14
|
-
import type { ToolContext } from "#public/definitions/tool.js";
|
|
15
|
-
import { type AuthorizationDefinition } from "#runtime/connections/types.js";
|
|
16
15
|
/**
|
|
17
|
-
* Wraps one authored tool's `execute` with
|
|
18
|
-
*
|
|
16
|
+
* Wraps one authored tool's `execute` with a context that supports inline
|
|
17
|
+
* provider auth (`ctx.getToken(connect("..."))`).
|
|
19
18
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* interactive strategy never rethrows the raw `Required` into the
|
|
31
|
-
* model: if no callback URL can be minted it fails with a classified
|
|
32
|
-
* {@link ConnectionAuthorizationFailedError} instead. Only
|
|
33
|
-
* non-interactive strategies rethrow the original error, since they
|
|
34
|
-
* have no consent flow to park on.
|
|
35
|
-
*/
|
|
36
|
-
export declare function createAuthorizedToolExecute(input: {
|
|
37
|
-
readonly scope: string;
|
|
38
|
-
readonly auth: AuthorizationDefinition;
|
|
39
|
-
readonly execute: (toolInput: unknown, ctx: unknown) => unknown;
|
|
40
|
-
}): (toolInput: unknown) => Promise<unknown>;
|
|
41
|
-
/**
|
|
42
|
-
* Wraps one authored tool's `execute` with a context that supports both
|
|
43
|
-
* top-level tool auth (`ctx.getToken()`) and inline provider auth
|
|
44
|
-
* (`ctx.getToken(connect("..."))`).
|
|
19
|
+
* On a thrown provider-scoped authorization request — implicit from
|
|
20
|
+
* `ctx.getToken(provider)` or explicit via `ctx.requireAuth(provider)` — the
|
|
21
|
+
* wrapper either fails terminally (token rejected immediately after sign-in)
|
|
22
|
+
* or evicts the rejected token from the per-step cache and starts the
|
|
23
|
+
* interactive flow, returning an `AuthorizationSignal` to park the turn.
|
|
24
|
+
* Interactive strategies never rethrow the raw `Required` into the model: if
|
|
25
|
+
* no callback URL can be minted, they fail with a classified
|
|
26
|
+
* {@link ConnectionAuthorizationFailedError} instead. Non-interactive
|
|
27
|
+
* strategies rethrow the original error because they have no consent flow to
|
|
28
|
+
* park on.
|
|
45
29
|
*/
|
|
46
30
|
export declare function createToolExecuteWithAuth(input: {
|
|
47
31
|
readonly scope: string;
|
|
48
32
|
readonly execute: (toolInput: unknown, ctx: unknown) => unknown;
|
|
49
|
-
readonly topLevelAuth?: AuthorizationDefinition;
|
|
50
33
|
}): (toolInput: unknown) => Promise<unknown>;
|
|
51
|
-
/**
|
|
52
|
-
* Builds the {@link ToolContext} for an authored tool without top-level
|
|
53
|
-
* `auth`. No-arg token accessors throw, but provider-scoped accessors
|
|
54
|
-
* still work.
|
|
55
|
-
*/
|
|
56
|
-
export declare function buildUnauthorizedToolContext(scope: string): ToolContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildCallbackContext}from"#context/build-callback-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
|
|
1
|
+
import{buildCallbackContext}from"#context/build-callback-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=>{let r=new Set;try{return await n(e,buildToolContext({inlineAuthState:{},justAuthorizedScopes: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{...buildCallbackContext(),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};
|