eve 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/src/cli/dev/tui/setup-selection-input.js +1 -1
- package/dist/src/cli/dev/tui/stream-format.d.ts +4 -0
- package/dist/src/cli/dev/tui/stream-format.js +1 -1
- package/dist/src/cli/dev/tui/terminal-renderer.js +1 -1
- package/dist/src/cli/dev/tui/test/mock-terminal.d.ts +2 -0
- package/dist/src/cli/dev/tui/test/mock-terminal.js +1 -1
- package/dist/src/context/build-base-tool-context.d.ts +9 -0
- package/dist/src/context/build-base-tool-context.js +1 -0
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/evals/cli/eval.js +4 -1
- package/dist/src/evals/runner/discover.d.ts +10 -0
- package/dist/src/evals/runner/discover.js +1 -1
- package/dist/src/execution/durable-session-migrations/turn-workflow.d.ts +2 -0
- package/dist/src/execution/node-step.d.ts +2 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/sandbox/abort-bound-session.d.ts +6 -0
- package/dist/src/execution/sandbox/abort-bound-session.js +1 -0
- package/dist/src/execution/sandbox/active-handles.d.ts +29 -0
- package/dist/src/execution/sandbox/active-handles.js +1 -0
- package/dist/src/execution/sandbox/bindings/docker.d.ts +2 -2
- package/dist/src/execution/sandbox/bindings/docker.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-provider-state.d.ts +11 -0
- package/dist/src/execution/sandbox/bindings/microsandbox-provider-state.js +1 -0
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +7 -4
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/sandbox/require-sandbox.d.ts +3 -1
- package/dist/src/execution/sandbox/require-sandbox.js +1 -1
- package/dist/src/execution/tool-auth.d.ts +2 -1
- package/dist/src/execution/tool-auth.js +1 -1
- package/dist/src/execution/web-fetch/tool.d.ts +6 -1
- package/dist/src/execution/web-fetch/tool.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/harness/compaction.d.ts +1 -1
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +2 -1
- package/dist/src/harness/model-call-error.js +1 -1
- package/dist/src/harness/step-hooks.d.ts +1 -1
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/tools.d.ts +2 -3
- package/dist/src/harness/tools.js +1 -1
- package/dist/src/harness/turn-cancellation.d.ts +8 -0
- package/dist/src/harness/turn-cancellation.js +1 -0
- package/dist/src/harness/turn-tag-state.d.ts +2 -0
- package/dist/src/harness/turn-tag-state.js +1 -1
- package/dist/src/harness/types.d.ts +2 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/host/sandbox-shutdown-plugin.d.ts +40 -0
- package/dist/src/internal/nitro/host/sandbox-shutdown-plugin.js +1 -0
- package/dist/src/internal/nitro/host/start-production-server.js +1 -1
- package/dist/src/protocol/message.d.ts +14 -2
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/definitions/approval.d.ts +4 -1
- package/dist/src/public/definitions/tool.d.ts +7 -0
- package/dist/src/public/tools/internal.d.ts +3 -2
- package/dist/src/public/tools/internal.js +1 -1
- package/dist/src/runtime/connections/mcp-client.d.ts +2 -2
- package/dist/src/runtime/connections/mcp-client.js +1 -1
- package/dist/src/runtime/connections/openapi-client.d.ts +2 -2
- package/dist/src/runtime/connections/openapi-client.js +1 -1
- package/dist/src/runtime/connections/types.d.ts +6 -1
- package/dist/src/runtime/framework-tools/bash.js +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
- package/dist/src/runtime/framework-tools/glob.js +1 -1
- package/dist/src/runtime/framework-tools/grep.js +1 -1
- package/dist/src/runtime/framework-tools/read-file.js +1 -1
- package/dist/src/runtime/framework-tools/web-fetch.js +1 -1
- package/dist/src/runtime/framework-tools/write-file.js +1 -1
- package/dist/src/sandbox/state.d.ts +0 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/dynamic-tool-definition.d.ts +4 -1
- package/dist/src/shared/sandbox-backend.d.ts +7 -1
- package/dist/src/shared/tool-definition.d.ts +1 -1
- package/docs/sandbox.mdx +3 -1
- package/docs/tools/human-in-the-loop.md +1 -1
- package/docs/tools/overview.mdx +2 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.20.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 6f9364a: Sandboxes are now stopped when the eve server shuts down. Self-hosted production servers stop every open sandbox (microsandbox VMs, Docker containers, Vercel sandboxes, just-bash interpreters) on `SIGTERM`/`SIGINT`, matching the cleanup `eve dev` already performs, and sessions reattach from persisted state on the next start. Breaking change for custom sandbox backends: `SandboxBackendHandle` gains a required `shutdown()` and the unused `dispose()` is removed.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- 7699e98: `eve eval` now prints a clear, actionable message when it finds no evals but detects `*.eval.ts` files placed inside `agent/`. Instead of the generic "No evals found", it names the offending directories and reminds you that eval files belong in the top-level `evals/` directory (a sibling of `agent/`).
|
|
12
|
+
- f3a05c5: `ToolContext` and `ApprovalContext` now expose `callId`, the tool call id carried by the call's stream events, so approval-gated tools can key records to one identity across proposal, rejection, and execution.
|
|
13
|
+
- f9621b6: Resuming a durable session whose history references a file attachment no longer fails the turn when the staged bytes are gone (for example after a redeploy pointed the session at a fresh sandbox). The missing attachment degrades to a `FileNotFound` text notice the model can interpret, so the run continues instead of ending in `session.failed`.
|
|
14
|
+
- c233a6a: The turn harness now propagates a cooperative `AbortSignal` end to end: model calls, retries, recovery, compaction, and tool executions all honor it, and an aborted turn settles with a canonical `TurnCancelledError` that is never retried or misclassified as a failure. Authored tools receive the signal as `ctx.abortSignal` (and via the AI SDK execute options), and framework tools forward it into sandbox commands, file I/O, `web_fetch`, and MCP/OpenAPI connection calls. This is the lowest layer of turn cancellation — no trigger exists yet, so runtime behavior is unchanged until the cancellation API ships.
|
|
15
|
+
|
|
3
16
|
## 0.19.0
|
|
4
17
|
|
|
5
18
|
### Minor Changes
|
|
@@ -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,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(`
|
|
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`:case`ctrl-p`:return{kind:`move`,direction:`up`};case`down`:case`ctrl-n`: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
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,4 +1,4 @@
|
|
|
1
1
|
const CSI_FINAL=/[\u0040-\u007e]/u,PASTE_START=`\x1B[200~`,PASTE_END=`\x1B[201~`;function sanitizePastedText(e){let t=``;for(let n of e.replace(/\r\n?/gu,`
|
|
2
2
|
`)){if(n===`
|
|
3
|
-
`||n===` `){t+=n;continue}let e=n.codePointAt(0);e!==void 0&&(e<32||e===127||e>=128&&e<=159||(t+=n))}return t}function isIncompletePaste(e){return e.startsWith(PASTE_START)&&!e.includes(PASTE_END,6)}function stripPasteStart(e){return e.startsWith(PASTE_START)?e.slice(6):e}function stripPromptControlCharacters(e){let t=``;for(let n of e)n>=` `&&n!==``&&(t+=n);return t}function nextKey(r){let i=r[0];if(i===void 0)return{consumed:0,incomplete:!0};if(i===`\x1B`){if(r.length===1)return{consumed:0,incomplete:!0};let i=r[1];if(i===`O`)return r.length<3?{consumed:0,incomplete:!0}:{key:parseKey(Buffer.from(r.slice(0,3))),consumed:3};if(i===`[`){if(r.startsWith(PASTE_START)){let e=r.indexOf(PASTE_END,6);return e===-1?{consumed:0,incomplete:!0}:{key:{type:`text`,value:sanitizePastedText(r.slice(6,e)),framing:`bracketed-paste`},consumed:e+6}}for(let t=2;t<r.length;t+=1)if(CSI_FINAL.test(r[t]))return{key:parseKey(Buffer.from(r.slice(0,t+1))),consumed:t+1};return{consumed:0,incomplete:!0}}return{key:{type:`escape`},consumed:1}}if(i<` `||i===``)return{key:parseKey(Buffer.from(i)),consumed:1};let a=1;for(;a<r.length;){let e=r[a];if(e===`\x1B`||e<` `||e===``)break;a+=1}return{key:parseKey(Buffer.from(r.slice(0,a))),consumed:a}}function parseKey(e){let t=e.toString(`utf8`);switch(t){case``:return{type:`ctrl-a`};case``:return{type:`ctrl-e`};case``:return{type:`ctrl-d`};case`\v`:return{type:`ctrl-k`};case`\f`:return{type:`ctrl-l`};case``:return{type:`ctrl-r`};case``:return{type:`ctrl-u`};case``:return{type:`ctrl-w`};case``:return{type:`ctrl-c`};case`\r`:case`
|
|
3
|
+
`||n===` `){t+=n;continue}let e=n.codePointAt(0);e!==void 0&&(e<32||e===127||e>=128&&e<=159||(t+=n))}return t}function isIncompletePaste(e){return e.startsWith(PASTE_START)&&!e.includes(PASTE_END,6)}function stripPasteStart(e){return e.startsWith(PASTE_START)?e.slice(6):e}function stripPromptControlCharacters(e){let t=``;for(let n of e)n>=` `&&n!==``&&(t+=n);return t}function nextKey(r){let i=r[0];if(i===void 0)return{consumed:0,incomplete:!0};if(i===`\x1B`){if(r.length===1)return{consumed:0,incomplete:!0};let i=r[1];if(i===`O`)return r.length<3?{consumed:0,incomplete:!0}:{key:parseKey(Buffer.from(r.slice(0,3))),consumed:3};if(i===`[`){if(r.startsWith(PASTE_START)){let e=r.indexOf(PASTE_END,6);return e===-1?{consumed:0,incomplete:!0}:{key:{type:`text`,value:sanitizePastedText(r.slice(6,e)),framing:`bracketed-paste`},consumed:e+6}}for(let t=2;t<r.length;t+=1)if(CSI_FINAL.test(r[t]))return{key:parseKey(Buffer.from(r.slice(0,t+1))),consumed:t+1};return{consumed:0,incomplete:!0}}return{key:{type:`escape`},consumed:1}}if(i<` `||i===``)return{key:parseKey(Buffer.from(i)),consumed:1};let a=1;for(;a<r.length;){let e=r[a];if(e===`\x1B`||e<` `||e===``)break;a+=1}return{key:parseKey(Buffer.from(r.slice(0,a))),consumed:a}}function parseKey(e){let t=e.toString(`utf8`);switch(t){case``:return{type:`ctrl-a`};case``:return{type:`ctrl-e`};case``:return{type:`ctrl-d`};case`\v`:return{type:`ctrl-k`};case``:return{type:`ctrl-n`};case``:return{type:`ctrl-p`};case`\f`:return{type:`ctrl-l`};case``:return{type:`ctrl-r`};case``:return{type:`ctrl-u`};case``:return{type:`ctrl-w`};case``:return{type:`ctrl-c`};case`\r`:case`
|
|
4
4
|
`:return{type:`enter`};case`\x1B[27;2;13~`:case`\x1B[13;2u`:return{type:`newline`};case``:case`\b`:return{type:`backspace`};case`\x1B[A`:case`\x1BOA`:return{type:`up`};case`\x1B[B`:case`\x1BOB`:return{type:`down`};case`\x1B[C`:case`\x1BOC`:return{type:`right`};case`\x1B[D`:case`\x1BOD`:return{type:`left`};case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:return{type:`home`};case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:return{type:`end`};case`\x1B[3~`:return{type:`delete`};case` `:return{type:`tab`};case`\x1B`:return{type:`escape`};default:{let e=stripPromptControlCharacters(t);return e.length>0?{type:`text`,value:e,framing:`unframed`}:{type:`ignore`}}}}async function*takeUntil(e,t){let n=e[Symbol.asyncIterator](),r=t.then(()=>({done:!0,value:void 0}));try{for(;;){let e=n.next();e.catch(()=>{});let t=await Promise.race([e,r]);if(t.done)break;yield t.value}}finally{n.return?.()?.catch(()=>{})}}function formatCompactTokenCount(e){if(e<1e3)return`${e}`;let t=e<1e6?e/1e3:e/1e6,n=e<1e6?`K`:`M`;return`${t.toFixed(1).replace(/\.0$/,``)}${n}`}function formatTokenFlow(e,t){let n=formatCompactTokenCount(e.inputTokens),r=formatCompactTokenCount(e.outputTokens),i=`${t.arrowUp} ${n} ${t.arrowDown} ${r}`,a=formatContextPercentage(e.inputTokens,e.contextSize);return a==null?i:`${i} ${a}`}function formatContextPercentage(e,t){if(!(t==null||t<=0||!Number.isFinite(t)))return`${Math.round(e/t*100).toLocaleString()}%`}function formatAssistantResponseStats(e,t){if(t===`tokensPerSecond`)return formatTokensPerSecond(e.tokensPerSecond);if(e.outputTokens!=null)return`${e.outputTokens.toLocaleString()} output tokens`}function formatTokensPerSecond(e){if(e!=null)return`${formatNumber(e)} tok/s`}function formatNumber(e){return Number.isInteger(e)?e.toLocaleString():e.toLocaleString(void 0,{maximumFractionDigits:1})}export{formatAssistantResponseStats,formatCompactTokenCount,formatTokenFlow,isIncompletePaste,nextKey,parseKey,sanitizePastedText,stripPasteStart,stripPromptControlCharacters,takeUntil};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{PROMPT_COMMANDS,isPromptControlCommand,parsePromptCommand}from"./prompt-commands.js";import{clipVisible,renderInputText,renderInputWithBlockCursor,stripAnsi,stripTerminalControls}from"./terminal-text.js";import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{buildAgentHeader}from"./agent-header.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{initialProviderPickerState,transitionProviderPicker}from"./provider-picker.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{initialSelectState,reduceSelect,searchActionQuery,selectValueAtCursor}from"#setup/cli/select-state.js";import{StringDecoder}from"node:string_decoder";import{parseDevRebuildLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{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=[];#m=new Map;#h=new Set;#g=[];#_=new Set;#v=new Map;#y=new Set;#b;#x=!1;#S;#C=[];#w;#T=0;#E;#D;#O=``;#k=0;#A=new PromptHistory;#j=!1;#M;#N={kind:`idle`};#P=STATUS.processing;#F=`eve`;#I=!1;#L=!1;#R=!0;#z=0;#B;#V;#H;#U=!1;#W;#G=``;#K=new StringDecoder(`utf8`);#q;#J;#Y;#X=!1;#Z=!1;#Q;#$;#ee;#te;#ne;#re;#ie;#ae=``;#oe=``;#se;#ce;#le=0;#ue;#de;#fe;#pe;#me;setupFlow={begin:(e,t)=>this.#ve(e,t),end:e=>this.#ye(e?.preserveDiagnostics??!0),readSelect:e=>this.#be(e),readEditableSelect:e=>this.#Se(e),readProviderPicker:e=>this.#Ce(e),readText:e=>this.#we(e),readAcknowledge:e=>this.#Te(e),readChoice:e=>this.#xe(e),setStatus:e=>this.#Ne(e),renderLine:(e,t)=>this.#Pe(e,t),renderOutput:e=>this.#Fe(e),waitForInterrupt:()=>this.#Ae()};constructor(t){this.#e=t?.input??process.stdin,this.#t=t?.output??process.stdout,this.#n=new LiveRegion(this.#t),this.#r=createTheme({color:t?.color??!0,unicode:t?.unicode??detectUnicode()}),this.#i=t?.tools??`auto-collapsed`,this.#a=t?.reasoning??`full`,this.#o=t?.subagents??`auto-collapsed`,this.#s=t?.connectionAuth??`full`,this.#c=t?.assistantResponseStats??`tokensPerSecond`,this.#l=t?.contextSize,this.#ee=t?.contextSize,this.#u=t?.captureForeignOutput??this.#t===process.stdout,this.#f=t?.logs??`none`,this.#d=t?.availablePromptCommands??PROMPT_COMMANDS}renderAgentHeader(e){this.#F=e.name,this.#b=e,this.#Ie();let t=this.#vt().join(`
|
|
2
|
-
`);if(this.#x){t!==this.#S&&(this.#S=t,this.#Ze({kind:`agent-header`,body:t,live:!1})),this.#pt();return}this.#x=!0,this.#S=t,this.#n.flush(this.#vt(),[])}async readPrompt(e){this.#Ie(e),this.#Xe(),this.#j=!0,this.#N={kind:`idle`},this.#P=``;let r=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#A.begin(r.text),this.#he(r),this.#M=typeaheadFor(this.#d,r.text),this.#Ge(),this.#pt(),await new Promise((e,i)=>{let apply=e=>{r=e,this.#qe(),this.#he(r),this.#M=typeaheadFor(this.#d,e.text,this.#M),this.#pt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#M=void 0,this.#Ke(),this.#Le(),i(interruptedError())},suggestions=()=>this.#M!==void 0&&isTypeaheadOpen(this.#M)?this.#M:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#W=i=>{let a=applyLineEditorKey(r,i,{multiline:!0});if(a!==void 0){apply(a);return}switch(i.type){case`up`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,-1),this.#pt();break}let t=movePromptLine(r,`up`);t===void 0?recall(this.#A.previous(r.text)):apply(t);break}case`down`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,1),this.#pt();break}let t=movePromptLine(r,`down`);t===void 0?recall(this.#A.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#M=dismissTypeahead(e),this.#pt());break}case`enter`:{let i=highlighted(),a=i!==void 0&&parsePromptCommand(r.text)===null?typeaheadCompletion(i).trimEnd():r.text;this.#M=void 0,this.#A.add(a),this.#j=!1,this.#Ke(),this.#Ye(),this.#P=STATUS.processing,isPromptControlCommand(a)?this.#Ze({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#Qe(a),this.#ue=a),this.#he(EMPTY_LINE),this.#pt(),this.#ze(),e(a);break}case`ctrl-d`:r.text.length===0?interrupt():apply(deleteForward(r));break;case`ctrl-l`:this.#gt();break;case`ctrl-r`:this.#pt();break;case`ctrl-c`:r.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Re()})}#he(e){this.#O=e.text,this.#k=e.cursor}async renderStream(e,t){this.#Ie(t),this.#h.clear(),this.#j=!1,this.#N.kind!==`waiting`&&(this.#N={kind:`waiting`,startedAtMs:Date.now()}),this.#P=this.#T>0?STATUS.connectionAuth:STATUS.processing,this.#$e(t?.submittedPrompt),this.#L=!1,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Je(),this.#pt();let r=new Promise(e=>{this.#Y=e});this.#W=e=>this.#We(e),this.#Re();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.#L)break;this.#at(t,n,i)}}catch(e){this.#et(`Error`,toErrorMessage(e))}finally{this.#Y=void 0,this.#L&&e.abort?.(),this.#ze(),this.#Xe(),this.#N.kind===`waiting`&&(this.#N={kind:`idle`}),this.#P=completedTurnStatus(this.#L,t?.continueSession===!0),this.#it(),this.#pt(),t?.continueSession||this.#Le()}}async readToolApproval(e,t){return this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#P=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#L=!1,this.#pt(),await new Promise((t,n)=>{this.#W=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ye(),this.#P=STATUS.processing,this.#ze(),this.#pt(),t({approved:!0})):n===`n`&&(this.#Ye(),this.#P=STATUS.processing,this.#ge(e.toolCallId),this.#ze(),this.#pt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L=!0,this.#Le(),n(interruptedError());break;default:break}},this.#Re()})}async readInputQuestion(e,t){this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#L=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),c=r?`select`:`text`,l=0,u=EMPTY_LINE,isOnFreeformRow=()=>i&&l===n.length,renderSection=()=>{this.#nt({id:o,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.#P=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#j=!1}else this.#j=!0,this.#he(u),this.#P=``;this.#pt()};renderSection(),c===`text`&&this.#Ge(),repaintStatus();let finalize=t=>{this.#nt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:` ${this.#r.colors.green(this.#r.glyph.success)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#j=!1,this.#Ye(),this.#P=STATUS.processing,this.#Ke(),this.#ze(),this.#pt();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.#W=o=>{if(o.type===`ctrl-c`){if(c===`text`&&u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();return}this.#L=!0,this.#Ke(),this.#Le(),i(interruptedError());return}if(o.type===`ctrl-r`){this.#pt();return}if(c===`select`){switch(o.type){case`up`:a>0&&(l=(l-1+a)%a,renderSection(),repaintStatus());break;case`down`:a>0&&(l=(l+1)%a,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=EMPTY_LINE,this.#Ge(),repaintStatus();break}let e=n[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let s=applyLineEditorKey(u,o,{multiline:!0});if(s!==void 0){u=s,this.#qe(),repaintStatus();return}switch(o.type){case`up`:case`down`:{let e=movePromptLine(u,o.type);e!==void 0&&(u=e,this.#qe(),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.#qe(),repaintStatus();break}c=`select`,u=EMPTY_LINE,this.#j=!1,this.#Ke(),repaintStatus();break}u=EMPTY_LINE,this.#qe(),repaintStatus();break;default:break}},this.#Re()})}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.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}this.#nt({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#pt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();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.#nt(n),this.#pt()}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#rt(t),this.#v.delete(e),this.#pt())}#ge(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#nt({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#pt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#T)return;let n=this.#T>0;this.#T=t,t>0?(this.#P=STATUS.connectionAuth,this.#pt()):n&&(this.#P=STATUS.processing,this.#pt())}setVercelStatus(e){this.#E=e,this.#pt()}setRemoteConnectionStatus(e){this.#D=e,this.#pt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#w=void 0,this.#C.length=0,this.#g.length=0,this.#x=!1,this.#S=void 0,this.#_.clear(),this.#v.clear(),this.#y.clear(),this.#ue=void 0,this.#ce=void 0,this.#T=0,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=void 0,this.#I&&(this.#n.clearAll(),this.#pt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`notice`,body:t,live:!1}),this.#pt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ie(),this.#Ze({kind:`sandbox`,body:t,live:!1}),this.#pt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#_e();return}this.#Ie(),this.#fe=t,this.#pt()}clearSetupWarning(){this.#_e()}#_e(){this.#fe!==void 0&&(this.#fe=void 0,this.#pt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ie();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Ze(r),this.#pt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`result`,body:t,live:!1}),this.#pt())}#ve(e,t=`spinner`){this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#de={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Je(),this.#pt()}#ye(e){this.#pe=void 0,this.#Me();let t=this.#de;if(t!==void 0){if(this.#de=void 0,this.#Xe(),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.#Ze({kind:`flow`,title:`info`,body:e.join(`
|
|
2
|
+
`);if(this.#x){t!==this.#S&&(this.#S=t,this.#Ze({kind:`agent-header`,body:t,live:!1})),this.#pt();return}this.#x=!0,this.#S=t,this.#n.flush(this.#vt(),[])}async readPrompt(e){this.#Ie(e),this.#Xe(),this.#j=!0,this.#N={kind:`idle`},this.#P=``;let r=lineOf(stripPromptControlCharacters(e?.initialDraft??``));return this.#A.begin(r.text),this.#he(r),this.#M=typeaheadFor(this.#d,r.text),this.#Ge(),this.#pt(),await new Promise((e,i)=>{let apply=e=>{r=e,this.#qe(),this.#he(r),this.#M=typeaheadFor(this.#d,e.text,this.#M),this.#pt()},recall=e=>{e!==void 0&&apply(lineOf(e))},interrupt=()=>{this.#M=void 0,this.#Ke(),this.#Le(),i(interruptedError())},suggestions=()=>this.#M!==void 0&&isTypeaheadOpen(this.#M)?this.#M:void 0,highlighted=()=>{let e=suggestions();return e===void 0?void 0:selectedTypeaheadCommand(e)};this.#W=i=>{let a=applyLineEditorKey(r,i,{multiline:!0});if(a!==void 0){apply(a);return}switch(i.type){case`up`:case`ctrl-p`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,-1),this.#pt();break}let t=movePromptLine(r,`up`);t===void 0?recall(this.#A.previous(r.text)):apply(t);break}case`down`:case`ctrl-n`:{let e=suggestions();if(e!==void 0){this.#M=moveTypeaheadSelection(e,1),this.#pt();break}let t=movePromptLine(r,`down`);t===void 0?recall(this.#A.next()):apply(t);break}case`tab`:{let e=highlighted();e!==void 0&&apply(lineOf(typeaheadCompletion(e)));break}case`escape`:{let e=suggestions();e!==void 0&&(this.#M=dismissTypeahead(e),this.#pt());break}case`enter`:{let i=highlighted(),a=i!==void 0&&parsePromptCommand(r.text)===null?typeaheadCompletion(i).trimEnd():r.text;this.#M=void 0,this.#A.add(a),this.#j=!1,this.#Ke(),this.#Ye(),this.#P=STATUS.processing,isPromptControlCommand(a)?this.#Ze({kind:`command`,body:stripTerminalControls(a.trim()),live:!1}):(this.#Qe(a),this.#ue=a),this.#he(EMPTY_LINE),this.#pt(),this.#ze(),e(a);break}case`ctrl-d`:r.text.length===0?interrupt():apply(deleteForward(r));break;case`ctrl-l`:this.#gt();break;case`ctrl-r`:this.#pt();break;case`ctrl-c`:r.text.length===0?interrupt():apply(EMPTY_LINE);break;default:break}},this.#Re()})}#he(e){this.#O=e.text,this.#k=e.cursor}async renderStream(e,t){this.#Ie(t),this.#h.clear(),this.#j=!1,this.#N.kind!==`waiting`&&(this.#N={kind:`waiting`,startedAtMs:Date.now()}),this.#P=this.#T>0?STATUS.connectionAuth:STATUS.processing,this.#$e(t?.submittedPrompt),this.#L=!1,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=Date.now();let n={tools:t?.tools??this.#i,reasoning:t?.reasoning??this.#a,assistantResponseStats:t?.assistantResponseStats??this.#c};this.#Je(),this.#pt();let r=new Promise(e=>{this.#Y=e});this.#W=e=>this.#We(e),this.#Re();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.#L)break;this.#at(t,n,i)}}catch(e){this.#et(`Error`,toErrorMessage(e))}finally{this.#Y=void 0,this.#L&&e.abort?.(),this.#ze(),this.#Xe(),this.#N.kind===`waiting`&&(this.#N={kind:`idle`}),this.#P=completedTurnStatus(this.#L,t?.continueSession===!0),this.#it(),this.#pt(),t?.continueSession||this.#Le()}}async readToolApproval(e,t){return this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#P=`Approve ${formatToolApprovalTitle(e)}? (y/n)`,this.#L=!1,this.#pt(),await new Promise((t,n)=>{this.#W=r=>{switch(r.type){case`text`:{if(r.framing!==`unframed`)break;let n=r.value.toLowerCase();n===`y`?(this.#Ye(),this.#P=STATUS.processing,this.#ze(),this.#pt(),t({approved:!0})):n===`n`&&(this.#Ye(),this.#P=STATUS.processing,this.#ge(e.toolCallId),this.#ze(),this.#pt(),t({approved:!1,reason:`Denied by user.`}));break}case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L=!0,this.#Le(),n(interruptedError());break;default:break}},this.#Re()})}async readInputQuestion(e,t){this.#Ie(t),this.#Xe(),this.#j=!1,this.#N={kind:`idle`},this.#L=!1;let n=e.options??[],r=n.length>0,i=(e.allowFreeform===!0||!r)&&r,a=n.length+ +!!i,o=questionSectionId(e.requestId),c=r?`select`:`text`,l=0,u=EMPTY_LINE,isOnFreeformRow=()=>i&&l===n.length,renderSection=()=>{this.#nt({id:o,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.#P=`↑/↓ move · enter ${e} · Ctrl+C quit`,this.#j=!1}else this.#j=!0,this.#he(u),this.#P=``;this.#pt()};renderSection(),c===`text`&&this.#Ge(),repaintStatus();let finalize=t=>{this.#nt({id:o,kind:`question`,title:stripTerminalControls(e.prompt),body:` ${this.#r.colors.green(this.#r.glyph.success)} ${stripTerminalControls(t.label)}`,preformatted:!0,live:!1}),this.#j=!1,this.#Ye(),this.#P=STATUS.processing,this.#Ke(),this.#ze(),this.#pt();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.#W=o=>{if(o.type===`ctrl-c`){if(c===`text`&&u.text.length>0){u=EMPTY_LINE,this.#qe(),repaintStatus();return}this.#L=!0,this.#Ke(),this.#Le(),i(interruptedError());return}if(o.type===`ctrl-r`){this.#pt();return}if(c===`select`){switch(o.type){case`up`:case`ctrl-p`:a>0&&(l=(l-1+a)%a,renderSection(),repaintStatus());break;case`down`:case`ctrl-n`:a>0&&(l=(l+1)%a,renderSection(),repaintStatus());break;case`enter`:{if(isOnFreeformRow()){c=`text`,u=EMPTY_LINE,this.#Ge(),repaintStatus();break}let e=n[l];e&&t(finalize({optionId:e.id,label:e.label}));break}default:break}return}let s=applyLineEditorKey(u,o,{multiline:!0});if(s!==void 0){u=s,this.#qe(),repaintStatus();return}switch(o.type){case`up`:case`down`:{let e=movePromptLine(u,o.type);e!==void 0&&(u=e,this.#qe(),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.#qe(),repaintStatus();break}c=`select`,u=EMPTY_LINE,this.#j=!1,this.#Ke(),repaintStatus();break}u=EMPTY_LINE,this.#qe(),repaintStatus();break;default:break}},this.#Re()})}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.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();return}this.#nt({id:subagentStepSectionId(e.callId,e.sectionKey),kind:`subagent-step`,depth:1,reasoning:t,body:n,live:!e.finalized}),this.#pt()}}upsertSubagentTool(e){if(this.#o===`hidden`)return;if(this.#tt(e.callId,e.subagentName),this.#o===`collapsed`){this.#pt();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.#nt(n),this.#pt()}markChildToolCallId(e){this.#_.add(e);let t=this.#v.get(e);t!==void 0&&(this.#rt(t),this.#v.delete(e),this.#pt())}#ge(e){let t=this.#m.get(toolSectionId(e));t!==void 0&&(t.status=`denied`,t.live=!1)}upsertConnectionAuth(e){if(this.#s===`hidden`)return;let t=connectionAuthTerminalMessage(e.state);this.#nt({id:connectionAuthSectionId(e.name),kind:`connection-auth`,title:`${stripTerminalControls(e.name)} · authorization · ${e.state}`,body:formatConnectionAuthContent(e,t),preformatted:!0,live:t===void 0}),this.#pt()}setConnectionAuthPendingCount(e){let t=Math.max(0,e);if(t===this.#T)return;let n=this.#T>0;this.#T=t,t>0?(this.#P=STATUS.connectionAuth,this.#pt()):n&&(this.#P=STATUS.processing,this.#pt())}setVercelStatus(e){this.#E=e,this.#pt()}setRemoteConnectionStatus(e){this.#D=e,this.#pt()}reset(){this.#p=[],this.#m.clear(),this.#h.clear(),this.#w=void 0,this.#C.length=0,this.#g.length=0,this.#x=!1,this.#S=void 0,this.#_.clear(),this.#v.clear(),this.#y.clear(),this.#ue=void 0,this.#ce=void 0,this.#T=0,this.#Q=void 0,this.#$=void 0,this.#te=void 0,this.#ne=void 0,this.#re=void 0,this.#I&&(this.#n.clearAll(),this.#pt())}renderNotice(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`notice`,body:t,live:!1}),this.#pt())}renderSandboxLog(e){let t=parseSandboxLogLine(stripTerminalControls(e));t!==void 0&&(this.#Ie(),this.#Ze({kind:`sandbox`,body:t,live:!1}),this.#pt())}renderSetupWarning(e){let t=stripTerminalControls(e);if(t.trim().length===0){this.#_e();return}this.#Ie(),this.#fe=t,this.#pt()}clearSetupWarning(){this.#_e()}#_e(){this.#fe!==void 0&&(this.#fe=void 0,this.#pt())}renderCommandInvocation(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;this.#Ie();let r={kind:`command`,body:n,live:!1};t===`failed`&&(r.status=`error`),this.#Ze(r),this.#pt()}renderCommandResult(e){let t=stripTerminalControls(e);t.trim().length!==0&&(this.#Ie(),this.#Ze({kind:`result`,body:t,live:!1}),this.#pt())}#ve(e,t=`spinner`){this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``;let n=t===`pulse`?{kind:`pulse`,startedAtMs:Date.now()}:{kind:`spinner`};this.#de={title:stripTerminalControls(e),indicator:n,lines:[],outputBuffer:[]},this.#Je(),this.#pt()}#ye(e){this.#pe=void 0,this.#Me();let t=this.#de;if(t!==void 0){if(this.#de=void 0,this.#Xe(),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.#Ze({kind:`flow`,title:`info`,body:e.join(`
|
|
3
3
|
`),live:!1}),this.#Ze({kind:`flow`,title:n.tone,body:n.text,live:!1})),e=[]}}this.#pt()}}async#be(e){let t=this.#Ee(),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.#pt()},loadSearch=async(e,t)=>{c=!0,s=void 0;let a=++l;this.#pt();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.#pt())}},u=e.notices;if(e.kind===`task-list`||e.kind===`search`&&e.layout===`task-list`){let n=t.taskListLineStart??t.lines.length,r=t.lines.slice(n).filter(e=>e.tone===`success`||e.tone===`warning`||e.tone===`error`).map(e=>({tone:e.tone,text:e.text}));u=[...e.notices??[],...r],t.taskListLineStart=t.lines.length,t.hideLinesWhileQuestion=!0}let panelState=()=>{let t={...e,options:i,select:o};return u!==void 0&&u.length>0&&(t.notices=u),s!==void 0&&(t.error=s),c&&(t.loadingFrame=this.#bt()),t};return t.question=e=>renderSelectQuestion(panelState(),this.#r,e),this.#pt(),await this.#ke((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.#pt();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.#pt();return;case`update`:o=d.select,s=void 0,this.#pt();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.#pt();return;case`ignore`:return}}).promise}#xe(e){this.#Ie();let t=this.#De();t.status={kind:`progress`,text:stripTerminalControls(e.status)};let n;t.question=t=>renderSelectQuestion({kind:`actions`,context:e.context,actions:e.actions,cursor:n},this.#r,t),this.#pt();let r=this.#ke((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.#pt();return;case`repaint`:this.#pt();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#Se(e){let t=this.#Ee(),n={options:e.options};e.initialValue!==void 0&&(n.defaultValue=e.initialValue);let r=initialSelectState(n),i=lineOf(``),a;t.question=t=>{let n={kind:`inline-edit`,layout:`task-list`,message:e.message,options:e.options,select:r,edit:{optionValue:e.editable.value,caretVisible:this.#R,editor:{kind:`rename`,editor:i,defaultValue:e.editable.defaultValue,formatHint:e.editable.formatHint}}};return a!==void 0&&(n.error=a),renderSelectQuestion(n,this.#r,t)};let onEditableRow=()=>selectValueAtCursor([...e.options],r.cursor)===e.editable.value,syncEditableRow=()=>{onEditableRow()?this.#Ge():(i=lineOf(``),this.#Ke())};return syncEditableRow(),this.#pt(),await this.#ke((t,n)=>{let applyEditor=e=>{i=e,a=void 0,this.#qe(),this.#pt()},applySelect=t=>{r=reduceSelect(r,t,{options:e.options}),a=void 0,syncEditableRow(),this.#pt()},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.#pt();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.#pt();return;case void 0:break}if(!onEditableRow())return;let s=applyLineEditorKey(i,t);s!==void 0&&applyEditor(s)},()=>this.#Ke()).promise}async#Ce(e){let t=this.#Ee(),n=initialProviderPickerState(e.options,e.initialValue),r;t.question=t=>renderSelectQuestion({kind:`inline-edit`,layout:`stacked`,message:e.message,options:e.options,select:n.select,edit:{optionValue:`own-key`,caretVisible:this.#R,editor:{kind:`key`,phase:n.phase}}},this.#r,t);let syncCaret=()=>{n.phase.kind===`editing`||n.phase.kind===`invalid`?this.#Ge():this.#Ke()};return syncCaret(),this.#pt(),await this.#ke((t,i,a)=>{let dispatch=t=>{let o=transitionProviderPicker(n,t,e.options);switch(o.kind){case`ignore`:return;case`clear`:r?.abort(),r=void 0,n=o.state,syncCaret(),this.#pt();return;case`cancel`:i(void 0);return;case`render`:n=o.state,syncCaret(),this.#pt();return;case`validate`:{n=o.state,syncCaret(),this.#pt();let t=new AbortController;r=t;let i;try{i=e.validateInlineKey(o.key,t.signal)}catch(e){a(e);return}i.then(e=>{r!==t||t.signal.aborted||(r=void 0,dispatch({type:`validated`,validation:e}))},e=>{r!==t||t.signal.aborted||(r=void 0,a(e))});return}case`settle`:i(o.result);return}},o=setupSelectionIntent(t);switch(o?.kind){case`cancel`:dispatch({type:`cancel`});return;case`move`:dispatch({type:`move`,direction:o.direction});return;case`submit`:dispatch({type:`submit`});return;case`repaint`:this.#pt();return;case void 0:break}if(n.phase.kind!==`editing`&&n.phase.kind!==`invalid`)return;let s=applyLineEditorKey(n.phase.editor,t);s!==void 0&&(this.#qe(),dispatch({type:`edit`,editor:s}))},()=>{r?.abort(),r=void 0,this.#Ke()}).promise}async#we(e){let t=this.#Ee(),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.#R)},this.#Ge(),this.#pt(),await this.#ke((t,i)=>{let apply=e=>{n=e,r=void 0,this.#qe(),this.#pt()},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.#pt();return;case`enter`:{let t=n.text.length>0?n.text:e.defaultValue??``,a=e.validate?.(t);if(a!==void 0){r=a,this.#pt();return}i(t);return}default:return}},()=>this.#Ke()).promise}async#Te(e){let t=this.#Ee();return t.question=t=>renderAcknowledgeQuestion({message:e.message,lines:e.lines},this.#r,t),this.#pt(),await this.#ke((e,t)=>{switch(e.type){case`enter`:case`escape`:case`ctrl-c`:t();return;case`ctrl-r`:this.#pt();return;default:return}}).promise}#Ee(){return this.#Ie(),this.#j=!1,this.#N={kind:`idle`},this.#P=``,this.#De()}#De(){return this.#de===void 0&&(this.#de={title:``,indicator:{kind:`spinner`},lines:[],outputBuffer:[]}),this.#de}#Oe(){this.#de!==void 0&&(this.#de.question=void 0,this.#de.hideLinesWhileQuestion=!1),this.#W=void 0,this.#ze(),this.#je(),this.#pt()}#ke(e,t){let n=!1,r,i,a=new Promise((e,t)=>{r=e,i=t}),settle=e=>{n||(n=!0,t?.(),this.#Oe(),r(e))},reject=e=>{n||(n=!0,t?.(),this.#Oe(),i(e))};return this.#W=t=>e(t,settle,reject),this.#Re(),{promise:a,settle}}#Ae(){let e,t=new Promise(t=>{e=t});return this.#pe=e,this.#je(),{promise:t,dispose:()=>{this.#pe===e&&(this.#pe=void 0,this.#Me())}}}#je(){if(this.#pe===void 0)return;let consumer=e=>{if(e.type===`ctrl-c`||e.type===`escape`){let e=this.#pe;this.#pe=void 0,this.#Me(),e?.();return}e.type===`ctrl-r`&&this.#pt()};this.#me=consumer,this.#W=consumer,this.#Re()}#Me(){this.#me!==void 0&&(this.#W===this.#me&&this.#ze(),this.#me=void 0)}#Ne(e){let t=e===void 0?void 0:typeof e==`string`?{kind:`progress`,text:stripTerminalControls(e)}:{kind:`external-action`,text:stripTerminalControls(e.text),emphasis:stripTerminalControls(e.emphasis)};if(this.#de!==void 0){this.#de.status=t,t===void 0&&(this.#de.preview=void 0),this.#pt();return}if(t===void 0){this.#N={kind:`idle`},this.#P=``,this.#Xe(),this.#pt();return}this.#Ie(),this.#Ye(),this.#P=t.text,this.#pt()}#Pe(e,t){let n=stripTerminalControls(e);if(n.trim().length===0)return;let r=this.#de;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.#pt();return}this.#Ie(),this.#Ze({kind:`flow`,title:t,body:n,live:!1}),this.#pt()}#Fe(e){let t=stripTerminalControls(e);if(t.trim().length===0)return;let n=this.#de;if(n===void 0){this.#Pe(t,`info`);return}n.preview=t,n.outputBuffer.push(t),n.outputBuffer.length>40&&n.outputBuffer.shift(),this.#pt()}shutdown(){this.#Le()}#Ie(e){this.#F=e?.title??this.#F,this.#ee=e?.contextSize??this.#l,!this.#I&&(this.#I=!0,this.#n.reset(),this.#n.hideCursor(),this.#kt(),this.#e.isTTY&&(this.#e.setRawMode?.(!0),this.#e.resume(),this.#n.emitBracketedPaste(!0)),this.#J=()=>this.#pt(),this.#t.on(`resize`,this.#J))}#Le(){this.#ze(),this.#Ke(),this.#Xe(),this.#H!==void 0&&(clearTimeout(this.#H),this.#H=void 0),this.#U=!1,this.#I&&=(this.#Lt(),this.#pt(),this.#n.clear(),this.#n.showCursor(),this.#At(),this.#n.newline(),this.#e.isTTY&&(this.#n.emitBracketedPaste(!1),this.#e.setRawMode?.(!1),this.#e.pause()),this.#J&&=(this.#t.off(`resize`,this.#J),void 0),!1)}#Re(){this.#e.off(`data`,this.#Be),this.#e.on(`data`,this.#Be)}#ze(){this.#e.off(`data`,this.#Be),this.#Ue(),this.#G=``,this.#K=new StringDecoder(`utf8`),this.#W=void 0}#Be=e=>{this.#Ue(),this.#G+=this.#K.write(e),this.#He(),this.#Ve()};#Ve(){if(this.#G===`\x1B`){this.#q=setTimeout(()=>{this.#G===`\x1B`&&(this.#G=``,this.#W?.({type:`escape`}))},30),this.#q.unref?.();return}if(isIncompletePaste(this.#G)){let e=this.#G;this.#q=setTimeout(()=>{if(this.#G!==e)return;let t=sanitizePastedText(stripPasteStart(e));this.#G=``,t.length>0&&this.#W?.({type:`text`,value:t,framing:`bracketed-paste`})},1e3),this.#q.unref?.()}}#He(){for(;this.#G.length>0;){let e=nextKey(this.#G);if(e.incomplete)return;this.#G=this.#G.slice(e.consumed),e.key&&e.key.type!==`ignore`&&this.#W?.(e.key)}}#Ue(){this.#q&&=(clearTimeout(this.#q),void 0)}#We(e){switch(e.type){case`ctrl-l`:case`ctrl-r`:this.#pt();break;case`ctrl-c`:this.#L||(this.#L=!0,this.#N={kind:`idle`},this.#P=`Interrupted`,this.#Y?.(),this.#pt());break;default:break}}#Ge(){this.#Ke(),this.#qe(),this.#B=setInterval(()=>{this.#R=!this.#R,this.#pt()},500),this.#B.unref?.()}#Ke(){this.#B&&=(clearInterval(this.#B),void 0),this.#R=!0}#qe(){this.#R=!0}#Je(){this.#Xe(),this.#V=setInterval(()=>{this.#z+=1,this.#pt()},90),this.#V.unref?.()}#Ye(){this.#N={kind:`waiting`,startedAtMs:Date.now()},this.#Je()}#Xe(){this.#V&&=(clearInterval(this.#V),void 0)}#Ze(e){e.id!==this.#ce?.id&&this.#Lt(),this.#p.push(e),e.id&&this.#m.set(e.id,e)}#Qe(e){this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1}),this.#pt()}#$e(e){if(e!=null){if(this.#ue===e){this.#ue=void 0;return}this.#Ze({kind:`user`,body:stripTerminalControls(e),live:!1})}}#et(e,t,n){let r={kind:`error`,title:stripTerminalControls(e),body:stripTerminalControls(t),live:!1};n!==void 0&&(r.detail=stripTerminalControls(n)),this.#Ze(r),this.#pt()}#tt(e,t){this.#y.has(e)||(this.#y.add(e),this.#Ze({id:subagentHeaderId(e),kind:`subagent`,title:stripTerminalControls(t),live:!1}))}#nt(e){if(e.id&&this.#h.has(e.id))return;let t=e.id?this.#m.get(e.id):void 0;if(t){Object.assign(t,e);return}this.#Ze(e)}#rt(e){this.#p=this.#p.filter(t=>t.id!==e),this.#m.delete(e)}#it(){for(let e of this.#p)e.status===`approval`||e.status===`running`||e.kind===`connection-auth`&&e.live||(e.live=!1)}#at(e,t,n){switch(e.type){case`step-start`:this.#ot(n.hasPendingToolResults?STATUS.toolResults:STATUS.processing),n.hasPendingToolResults=!1;break;case`step-finish`:this.#ft(e.usage),this.#pt();break;case`assistant-delta`:{let t=(n.text.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(t),this.#ot(STATUS.streaming),n.text.set(e.id,t),this.#ct(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.#st(r),n.text.set(e.id,r),this.#ct(e.id,r,!1);break}case`reasoning-delta`:{if(t.reasoning===`hidden`)break;let r=(n.reasoning.get(e.id)??``)+stripTerminalControls(e.delta);this.#st(r),this.#ot(STATUS.streaming),n.reasoning.set(e.id,r),this.#lt(e.id,r,!0,t);break}case`reasoning-complete`:{if(t.reasoning===`hidden`)break;let r=n.reasoning.get(e.id)??``;this.#st(r),this.#lt(e.id,r,!1,t);break}case`tool-call`:if(t.tools===`hidden`)break;this.#ot(STATUS.executingTools),this.#ut({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.#ut({...r,status:`approval`},t,n);break}case`tool-result`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,output:e.output,status:`done`},t,n);break}case`tool-error`:{if(t.tools===`hidden`)break;let r=this.#dt(e.toolCallId,n);if(r===void 0)break;n.hasPendingToolResults=!0,this.#ot(STATUS.toolResults),this.#ut({...r,errorText:e.errorText,status:`error`},t,n);break}case`error`:this.#et(`Error`,e.errorText,e.detail);break;case`finish`:this.#ft(e.usage),this.#pt();break}}#ot(e){let t=this.#T>0?STATUS.connectionAuth:e;this.#P!==t&&(this.#P=t,this.#pt())}#st(e){e.trim().length>0&&(this.#N={kind:`answering`})}#ct(e,t,n){let r=stripTerminalControls(t).trim();r.length!==0&&(this.#nt({id:e,kind:`assistant`,body:r,live:n}),this.#pt())}#lt(e,t,n,r){let i=stripTerminalControls(t).trim();i.length!==0&&(this.#nt({id:e,kind:`reasoning`,body:i,collapsed:collapseReasoning(r.reasoning,n),live:n}),this.#pt())}#ut(e,t,n){if(n.tools.set(e.toolCallId,e),this.#_.has(e.toolCallId))return;let r=toolSectionId(e.toolCallId);this.#v.set(e.toolCallId,r),this.#nt(renderNativeToolBlock(e,r,t.tools===`full`)),this.#pt()}#dt(e,t){let n=t.tools.get(e);if(n!==void 0)return n;let r=this.#v.get(e)??toolSectionId(e),i=this.#m.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`}}#ft(e){if(e===void 0)return;let{inputTokens:t,outputTokens:n}=e;if((t!=null||n!=null)&&(this.#Q=(t??0)+(n??0)),this.#$=t??this.#$,this.#te=n??this.#te,this.#te!=null&&this.#re!==void 0){let e=(Date.now()-this.#re)/1e3;e>0&&(this.#ne=this.#te/e)}}#pt(){if(this.#I){if(this.#X){this.#Z=!0;return}this.#X=!0;try{do this.#Z=!1,this.#mt();while(this.#Z)}finally{this.#X=!1}}}#mt(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=[],i=this.#w;for(;this.#p.length>0&&this.#p[0].live===!1;){let t=this.#p.shift();if(this.#g.push(t),t.id&&(this.#h.add(t.id),this.#m.delete(t.id)),this.#zt(t))continue;let n=this.#yt(t,e,i);i=previousBlockOf(t),this.#w=i,r.push(...n),this.#C.push(...n)}let a=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(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)}#ht(){if(!this.#I)return;let e=this.#Dt(),t=this.#Ct(e),n=Math.max(1,this.#Ot()-t.length),r=this.#w,i=[];for(let t of this.#p){if(this.#zt(t))continue;let n=this.#yt(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.#vt(),...this.#C],a)}logDisplayMode(){return this.#f}setLogDisplayMode(e){e!==this.#f&&(this.#f=e,e===`all`&&this.flushDelayedDevBuildErrors(),this.#_t(),this.#I&&this.#ht())}flushDelayedDevBuildErrors(){let e=this.#se;e!==void 0&&(this.#se=void 0,this.#Ze({kind:`log`,title:`stderr`,body:e,live:!1}),this.#pt())}#gt(){this.#U=!0,this.#H!==void 0&&clearTimeout(this.#H),this.#H=setTimeout(()=>{this.#U=!1,this.#H=void 0,this.#pt()},5e3),this.setLogDisplayMode(nextLogDisplayMode(this.#f)),this.#pt()}#_t(){let e=this.#Dt();this.#C.length=0;let t;for(let n of this.#g){if(this.#zt(n))continue;let r=this.#yt(n,e,t);t=previousBlockOf(n),this.#C.push(...r)}this.#w=t}#vt(){let e=this.#b;if(e===void 0)return[];let t={name:e.name,theme:this.#r,width:this.#Dt()};return e.info!==void 0&&(t.info=e.info),e.tip!==void 0&&(t.tip=e.tip),buildAgentHeader(t)}#yt(e,t,n){let r={spinner:this.#bt()};n!==void 0&&(r.previous=n);let i=renderBlockLines(e,t,this.#r,r);return(e.depth??0)===0&&leadsWithGap(e,n)?[``,...i]:i}#bt(){return this.#r.spinner[this.#z%this.#r.spinner.length]??``}#xt(e,t){return isProgressPulseVisible(Date.now()-e)?t:` `}#St(e,t){return e.indicator.kind===`spinner`?{glyph:this.#bt(),color:`yellow`}:{glyph:this.#xt(e.indicator.startedAtMs,this.#r.unicode?PROGRESS_PULSE_GLYPH:PROGRESS_PULSE_ASCII_GLYPH),color:t?.kind===`external-action`?`yellow`:`green`}}#Ct(e){let n=this.#r.colors,r=[``],i=this.#de;if(i!==void 0){let t=this.#St(i,i.status),n=i.status===void 0?void 0:{...i.status,indicator:t},a;if(i.question!==void 0){let t=i.question(e);a={kind:`question`,rows:t},n!==void 0&&(a={kind:`question`,rows:t,status:n})}else n===void 0?a=i.preview===void 0?{kind:`idle`,indicator:t}:{kind:`preview`,text:i.preview,indicator:t}:(a={kind:`status`,status:n},i.preview!==void 0&&(a={kind:`status`,status:n,preview:i.preview}));let o={title:i.title,lines:i.hideLinesWhileQuestion===!0?[]:i.lines,content:a};return r.push(...renderFlowPanel(o,this.#r,e)),this.#Tt(r,e),r}if(this.#fe!==void 0&&r.push(...renderAttentionRows(this.#fe,e,this.#r),``),this.#j){let i=this.#M===void 0?void 0:inlineCommandHint(this.#M);i===void 0&&this.#M!==void 0&&isTypeaheadOpen(this.#M)&&r.push(...renderCommandSuggestions(this.#M,this.#r,e));let a=isPromptControlCommand(this.#O),o=i?n.dim(` ${i}`):``,s=[];this.#wt(s,e);let c=Math.max(1,this.#Ot()-1-r.length-1-s.length);return r.push(...promptInputRows({text:this.#O,cursor:this.#k,width:e,theme:this.#r,caretVisible:this.#R,isCommand:a,ghost:o,maxRows:c})),r.push(...s),r}let a=this.#N;if(a.kind===`answering`)return this.#wt(r,e),r;let o=a.kind===`waiting`,s=o?n.green(this.#xt(a.startedAtMs,this.#r.unicode?`⊙`:`o`)):n.dim(this.#r.glyph.dot),c=this.#P.length>0?this.#P:`Ready`,l=o?n.dim(c):c,u=this.#Et(),f=o?` `:``,p=u?`${f}${s} ${l} ${n.dim(this.#r.glyph.dot)} ${u}`:`${f}${s} ${l}`;r.push(clip(p,e));let g=[];return this.#wt(g,e),o&&g.length>0&&r.push(``),r.push(...g),r}#wt(e,t){let n=this.#D===void 0?``:` `,r=Math.max(1,t-n.length),i={theme:this.#r,width:r};this.#U&&(i.logLevel=this.#f);let a=this.#b?.serverUrl;if(a!==void 0&&this.#D===void 0){let e=new URL(a).port;e.length>0&&(i.serverPort=e)}let o=this.#b?.info?.agent.model.id;o!==void 0&&(i.model=o);let s=this.#b?.info?.agent.model.endpoint;s!==void 0&&(i.endpoint=s);let c=this.#$??0,l=this.#te??0;if(c>0||l>0){let e={inputTokens:c,outputTokens:l};this.#ee!==void 0&&(e.contextSize=this.#ee),i.tokens=formatTokenFlow(e,this.#r.glyph)}this.#E!==void 0&&(i.vercel=this.#E),this.#D!==void 0&&(i.remote=this.#D);let u=buildStatusLine(i);u!==void 0&&e.push(clip(`${n}${u}`,t))}#Tt(e,t){if(this.#D===void 0)return;let n=Math.max(1,t-2),r=buildStatusLine({remote:this.#D,theme:this.#r,width:n});r!==void 0&&e.push(``,clip(` ${r}`,t))}#Et(){let e=this.#r.colors,t=[],n=formatAssistantResponseStats({totalTokens:this.#Q,outputTokens:this.#te,tokensPerSecond:this.#ne},this.#c);return n&&t.push(n),t.length>0?e.dim(t.join(` ${this.#r.glyph.dot} `)):``}#Dt(){return Math.max(20,this.#t.columns||80)}#Ot(){return Math.max(8,this.#t.rows||24)}#kt(){if(this.#ie!==void 0||!this.#u)return;this.#ae=``,this.#oe=``;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.#jt(t,chunkToString(e,i)),a?.(),!0}),()=>{e.write=n}},e=capture(process.stdout,`stdout`),t=capture(process.stderr,`stderr`);this.#ie=()=>{e(),t()}}#At(){let e=this.#ie;e!==void 0&&(this.#ie=void 0,e(),this.#ae.length>0&&(this.#Rt(`stdout`)&&process.stdout.write(`${this.#ae}\n`),this.#ae=``),this.#oe.length>0&&(this.#Rt(`stderr`)&&process.stderr.write(`${this.#oe}\n`),this.#oe=``))}#jt(e,t){let n=(e===`stdout`?this.#ae:this.#oe)+t,r=n.lastIndexOf(`
|
|
4
4
|
`),i=r===-1?n:n.slice(r+1);if(e===`stdout`?this.#ae=i:this.#oe=i,r===-1)return;let a=stripAnsi(n.slice(0,r)).replace(/\s+$/u,``);a.trim().length!==0&&(e===`stdout`?this.#Mt(a):this.#Nt(a),this.#pt())}#Mt(e){let t=[],flushPending=()=>{if(t.length===0)return;let e=t.join(`
|
|
5
5
|
`);t=[],e.trim().length!==0&&this.#Ze({kind:`log`,title:`stdout`,body:e,live:!1})};for(let n of e.split(`
|
|
@@ -18,6 +18,8 @@ export declare class MockUserInput extends EventEmitter implements TerminalInput
|
|
|
18
18
|
left(): void;
|
|
19
19
|
right(): void;
|
|
20
20
|
ctrlC(): void;
|
|
21
|
+
ctrlN(): void;
|
|
22
|
+
ctrlP(): void;
|
|
21
23
|
}
|
|
22
24
|
export declare class MockScreen extends EventEmitter implements TerminalOutput {
|
|
23
25
|
#private;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{EventEmitter}from"node:events";const ansiControlSequencePattern=RegExp(`^\x1B\\[([0-9?;]*)([ -/]*)([@-~])`);var MockUserInput=class extends EventEmitter{isTTY=!0;rawModes=[];resumeCalls=0;pauseCalls=0;setRawMode(e){return this.rawModes.push(e),this}resume(){return this.resumeCalls+=1,this}pause(){return this.pauseCalls+=1,this}type(e){this.emit(`data`,Buffer.from(e))}send(e){this.emit(`data`,Buffer.from(e))}enter(){this.send(`\r`)}backspace(){this.send(``)}up(){this.send(`\x1B[A`)}down(){this.send(`\x1B[B`)}left(){this.send(`\x1B[D`)}right(){this.send(`\x1B[C`)}ctrlC(){this.send(``)}},MockScreen=class extends EventEmitter{isTTY=!0;columns;rows;#e=``;#t=[];#n=0;#r=0;#i=[];constructor({columns:e,rows:t}){super(),this.columns=e,this.rows=t}write(e,t,n){let r=String(e);return this.#e+=r,this.#o(r),typeof t==`function`&&t(),n?.(),this.#a(),!0}resize(e,t){this.columns=e,this.rows=t,this.emit(`resize`)}snapshot(){return this.#t.join(`
|
|
1
|
+
import{EventEmitter}from"node:events";const ansiControlSequencePattern=RegExp(`^\x1B\\[([0-9?;]*)([ -/]*)([@-~])`);var MockUserInput=class extends EventEmitter{isTTY=!0;rawModes=[];resumeCalls=0;pauseCalls=0;setRawMode(e){return this.rawModes.push(e),this}resume(){return this.resumeCalls+=1,this}pause(){return this.pauseCalls+=1,this}type(e){this.emit(`data`,Buffer.from(e))}send(e){this.emit(`data`,Buffer.from(e))}enter(){this.send(`\r`)}backspace(){this.send(``)}up(){this.send(`\x1B[A`)}down(){this.send(`\x1B[B`)}left(){this.send(`\x1B[D`)}right(){this.send(`\x1B[C`)}ctrlC(){this.send(``)}ctrlN(){this.send(``)}ctrlP(){this.send(``)}},MockScreen=class extends EventEmitter{isTTY=!0;columns;rows;#e=``;#t=[];#n=0;#r=0;#i=[];constructor({columns:e,rows:t}){super(),this.columns=e,this.rows=t}write(e,t,n){let r=String(e);return this.#e+=r,this.#o(r),typeof t==`function`&&t(),n?.(),this.#a(),!0}resize(e,t){this.columns=e,this.rows=t,this.emit(`resize`)}snapshot(){return this.#t.join(`
|
|
2
2
|
`)}rawOutput(){return this.#e}async waitForText(e,t=1e3,n=()=>this.snapshot()){this.snapshot().includes(e)||await new Promise((r,i)=>{let a={text:e,resolve:r,reject:i,timeout:setTimeout(()=>{this.#i=this.#i.filter(e=>e!==a),i(Error(`Timed out waiting for screen text: ${e}\n\nScreen:\n${n()}`))},t)};this.#i.push(a)})}#a(){let e=this.snapshot();for(let t of this.#i.slice())e.includes(t.text)&&(clearTimeout(t.timeout),this.#i=this.#i.filter(e=>e!==t),t.resolve())}#o(e){let t=0;for(;t<e.length;){if(e[t]===`\x1B`){let n=this.#s(e,t);if(n>t){t=n;continue}}let n=e[t];if(t+=1,n!==void 0){if(n===`
|
|
3
3
|
`){this.#n+=1,this.#r=0;continue}if(n===`\r`){this.#r=0;continue}this.#u(n)}}}#s(e,n){let r=e.slice(n).match(ansiControlSequencePattern);if(!r)return n;let[i,a=``,,o]=r,s=a.startsWith(`?`),c=a&&!s?a.split(`;`):[],first=e=>c[0]===void 0||c[0]===``?e:Number(c[0]);if(s)return n+i.length;switch(o){case`H`:case`f`:this.#n=first(1)-1,this.#r=(c[1]?Number(c[1]):1)-1;break;case`A`:this.#n=Math.max(0,this.#n-first(1));break;case`B`:this.#n+=first(1);break;case`C`:this.#r+=first(1);break;case`D`:this.#r=Math.max(0,this.#r-first(1));break;case`E`:this.#n+=first(1),this.#r=0;break;case`F`:this.#n=Math.max(0,this.#n-first(1)),this.#r=0;break;case`G`:this.#r=first(1)-1;break;case`J`:this.#c(first(0));break;case`K`:this.#l(first(0));break;default:break}return n+i.length}#c(e){if(e===2||e===3){this.#t=[],this.#n=0,this.#r=0;return}if(e===1){for(let e=0;e<this.#n;e+=1)this.#t[e]=``;this.#l(1);return}this.#l(0),this.#t.length=Math.min(this.#t.length,this.#n+1)}#l(e){let t=this.#t[this.#n]??``;if(e===2){this.#t[this.#n]=``;return}if(e===1){this.#t[this.#n]=` `.repeat(this.#r)+t.slice(this.#r);return}this.#t[this.#n]=t.slice(0,this.#r)}#u(e){let t=(this.#t[this.#n]??``).padEnd(this.#r,` `),n=t.slice(0,this.#r)+e+t.slice(this.#r+e.length);this.#t[this.#n]=n,this.#r+=e.length}};export{MockScreen,MockUserInput};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
2
|
+
import type { ToolExecuteOptions } from "#shared/tool-definition.js";
|
|
3
|
+
/** Base context shared by tool executors. */
|
|
4
|
+
export type BaseToolContext = SessionContext & {
|
|
5
|
+
readonly abortSignal: AbortSignal;
|
|
6
|
+
readonly callId: string;
|
|
7
|
+
};
|
|
8
|
+
/** Builds the base context for one tool execution. */
|
|
9
|
+
export declare function buildBaseToolContext(options: Pick<ToolExecuteOptions, "abortSignal" | "toolCallId">): BaseToolContext;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{buildCallbackContext}from"#context/build-callback-context.js";import{bindSandboxAbortSignal}from"#execution/sandbox/abort-bound-session.js";function buildBaseToolContext(e){let t=buildCallbackContext(),n=e.abortSignal??new AbortController().signal;return{...t,abortSignal:n,callId:e.toolCallId,getSandbox:async()=>bindSandboxAbortSignal(await t.getSandbox(),n)}}export{buildBaseToolContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{jsonSchema}from"ai";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{jsonSchema}from"ai";import{buildBaseToolContext}from"#context/build-base-tool-context.js";const log=createLogger(`dynamic-tools`);function lookupStepFunction(e){try{let t=globalThis[Symbol.for(`@workflow/core//registeredSteps`)];return t===void 0?null:t.get(e)||null}catch{return null}}function replayTools(e){let t=[];for(let n of e){if(!n.executeStepFnName||!n.closureVars){log.warn(`Dynamic tool "${n.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(n.executeStepFnName);if(!e){log.warn(`Dynamic tool "${n.name}" references step function "${n.executeStepFnName}" which is not registered — skipping on this step.`);continue}t.push({description:n.description,execute:(t,r)=>e(n.closureVars,t,buildBaseToolContext(r)),inputSchema:jsonSchema(n.inputSchema),name:n.name,approval:buildReplayedApproval(n),outputSchema:n.outputSchema===void 0?void 0:jsonSchema(n.outputSchema)})}return t}function buildReplayedApproval(e){if(e.approvalStepFnName===void 0)return;let t=lookupStepFunction(e.approvalStepFnName);return t===null?(log.warn(`Dynamic tool "${e.name}" references approval function "${e.approvalStepFnName}" which is not registered — requiring approval by default.`),()=>`user-approval`):async n=>await t(e.closureVars??{},n)}function buildDynamicTools(e){let i=e.get(LiveStepToolsKey)??[],a=replayTools(e.get(TurnDynamicToolMetadataKey)??[]),o=replayTools(e.get(SessionDynamicToolMetadataKey)??[]);return[...i,...a,...o]}export{buildDynamicTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS,isBrandedToolEntry}from"#shared/dynamic-tool-definition.js";import{jsonSchema,zodSchema}from"ai";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{LiveStepToolsKey,SessionDynamicToolMetadataKey,TurnDynamicToolMetadataKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS,isBrandedToolEntry}from"#shared/dynamic-tool-definition.js";import{jsonSchema,zodSchema}from"ai";import{buildBaseToolContext}from"#context/build-base-tool-context.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{normalizeJsonSchemaDefinition}from"#internal/json-schema.js";const log=createLogger(`dynamic-tools`);function toHarnessToolDefinition(e,t){return{description:t.description,execute:(e,n)=>t.execute(e,buildBaseToolContext(n)),inputSchema:convertInputSchema(t.inputSchema),name:e,approval:t.approval,outputSchema:convertOptionalOutputSchema(t.outputSchema),...t.toModelOutput===void 0?{}:{toModelOutput:t.toModelOutput}}}function convertInputSchema(e){return typeof e==`object`&&e&&`~standard`in e?zodSchema(e):jsonSchema(e)}function convertOptionalOutputSchema(e){if(e!==void 0)return typeof e==`object`&&e&&`~standard`in e?zodSchema(e):jsonSchema(e)}function qualifyDynamicToolNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t)return i.push({name:e,entryKey:r[0],entry:n[r[0]]}),i;for(let e of r)i.push({name:e,entryKey:e,entry:n[e]});return i}function replayDynamicSessionTools(e,t){let n=[];for(let t of e){if(!t.executeStepFnName||!t.closureVars){log.warn(`Dynamic tool "${t.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(t.executeStepFnName);if(!e){log.warn(`Dynamic tool "${t.name}" references step function "${t.executeStepFnName}" which is not registered — skipping on this step.`);continue}n.push({description:t.description,execute:(n,r)=>e(t.closureVars,n,buildBaseToolContext(r)),inputSchema:jsonSchema(t.inputSchema),name:t.name,outputSchema:t.outputSchema===void 0?void 0:jsonSchema(t.outputSchema)})}return n}function getStepRegistry(){let e=Symbol.for(`@workflow/core//registeredSteps`),t=globalThis,n=t[e];return n===void 0&&(n=new Map,t[e]=n),n}function lookupStepFunction(e){try{return getStepRegistry().get(e)||null}catch{return null}}function registerStepFunction(e,t){getStepRegistry().set(e,t)}function safeSerialize(e){try{return JSON.parse(JSON.stringify(e))}catch{return{}}}function durableKeyForEvent(e){switch(e){case`session.started`:return SessionDynamicToolMetadataKey;case`turn.started`:return TurnDynamicToolMetadataKey;default:return}}async function resolveToolsFromEvent(e,t,n,r){let a=await Promise.allSettled(t.map(async t=>{let i=t.events[n.type];if(i===void 0)return null;let a=await i(n,buildResolveContext(e,r));if(a==null)return null;let s,c;return isBrandedToolEntry(a)?(s={_single:a},c=!0):(s=a,c=!1),{resolver:t,entries:s,isSingle:c}})),s=[],c=[],l=new Map;for(let e of a){if(e.status===`rejected`){log.error(`Dynamic tool resolver (${n.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}if(e.value===null)continue;let{resolver:t,entries:r,isSingle:a}=e.value,o=qualifyDynamicToolNames(t.slug,a,r);for(let{name:e,entryKey:r,entry:i}of o){let a=l.get(e);if(a!==void 0&&a!==t.slug)throw Error(`Dynamic tool "${e}" from resolver "${t.slug}" collides with dynamic resolver "${a}". Namespace the map key manually, e.g. "${t.slug}__${e}".`);if(l.set(e,t.slug),c.push(toHarnessToolDefinition(e,i)),n.type===`step.started`)continue;let o=`__executeStepFn`in i?i.__executeStepFn:void 0,u=`__closureVars`in i?i.__closureVars:void 0,f=o?.stepId,p=u===void 0?void 0:safeSerialize(u);if(f===void 0){let e=`eve:framework-dynamic:${t.slug}:${r}`,n=i.execute.bind(i);registerStepFunction(e,(e,t,r)=>n(t,r)),f=e,p={}}let m;if(i.approval!==void 0){m=`eve:dynamic-tool-approval:${t.slug}:${r}`;let e=i.approval.bind(i);registerStepFunction(m,(t,n)=>e(n))}s.push({name:e,description:i.description,inputSchema:normalizeJsonSchemaDefinition(i.inputSchema),outputSchema:i.outputSchema===void 0?void 0:normalizeJsonSchemaDefinition(i.outputSchema,`output`),resolverSlug:t.slug,entryKey:r,executeStepFnName:f,approvalStepFnName:m,closureVars:p})}}return{metadata:s,liveTools:c}}async function dispatchDynamicToolEvent(e){let{ctx:n,resolvers:r,event:i,messages:o}=e;if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(i.type))return;let s=r.filter(e=>e.eventNames.includes(i.type));if(s.length===0)return;let{metadata:c,liveTools:l}=await resolveToolsFromEvent(n,s,i,o);if(i.type===`step.started`){n.setVirtualContext(LiveStepToolsKey,l);return}let u=durableKeyForEvent(i.type);if(u===void 0)return;let d=new Set(s.map(e=>e.slug)),f=(n.get(u)??[]).filter(e=>!d.has(e.resolverSlug));n.set(u,[...f,...c])}export{dispatchDynamicToolEvent,replayDynamicSessionTools};
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{createDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{discoverAndImportEvals,discoverEvalConfig}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{ConsoleReporter}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n){let o=resolveApplicationRoot();loadDevelopmentEnvironmentFiles(o);let s=e.length>0?e:void 0,c=await discoverAndImportEvals(o,s);if(c.length===0){
|
|
1
|
+
import{basename,join}from"node:path";import{readFile}from"node:fs/promises";import{loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{resolveApplicationRoot}from"#internal/application/paths.js";import{createDevelopmentServer}from"#internal/nitro/host.js";import{createEvalClient}from"#evals/cli/eval-client.js";import{discoverAndImportEvals,discoverEvalConfig,findMisplacedEvalDirs}from"#evals/runner/discover.js";import{runEvals}from"#evals/runner/run-evals.js";import{ConsoleReporter}from"#evals/runner/reporters/console.js";import{JUnit}from"#evals/runner/reporters/junit.js";import{resolveEvalTargetHandle}from"#evals/target.js";async function runEvalCommand(e,t,n){let o=resolveApplicationRoot();loadDevelopmentEnvironmentFiles(o);let s=e.length>0?e:void 0,c=await discoverAndImportEvals(o,s);if(c.length===0){let e=await findMisplacedEvalDirs(o);e.length>0?n.error(`No evals found under evals/, but eval files are present inside agent/:
|
|
2
|
+
`+e.map(e=>` - ${e}`).join(`
|
|
3
|
+
`)+`
|
|
4
|
+
eve eval only scans the top-level evals/ directory (a sibling of agent/). Move these files there.`):s?n.error(`No evals found matching: ${s.join(`, `)}`):n.error(`No evals found. Create files under evals/ with the *.eval.ts extension.`),process.exitCode=2;return}let l=filterEvalsByTag(c,t.tag??[]);if(l.length===0){n.error(`No evals matched the provided tags (${(t.tag??[]).join(`, `)}).`),process.exitCode=2;return}let u,d;try{u=parsePositiveInteger(t.maxConcurrency,`--max-concurrency`),d=parseNonNegativeInteger(t.timeout,`--timeout`)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}if(t.list===!0){printEvalList(l,t.json===!0,n);return}let f;try{f=await discoverEvalConfig(o)}catch(e){n.error(e instanceof Error?e.message:String(e)),process.exitCode=2;return}let p,m,h;try{if(t.url)h=await createEvalClient({kind:`remote`,url:t.url},{workspaceRoot:o}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(o),kind:`remote`,url:t.url});else{p=createDevelopmentServer(o,{host:`127.0.0.1`,port:0});let e=await p.start();h=await createEvalClient({kind:`local`,url:e.url}),m=await resolveEvalTargetHandle({client:h,expectedAgentName:await readExpectedAgentName(o),kind:`local`,url:e.url})}let e=t.json===!0?[]:[new ConsoleReporter];t.junit!==void 0&&e.push(JUnit({filePath:t.junit}));let r=await runEvals({evaluations:l,config:f,target:m,client:h,appRoot:o,reporters:e,includeEvalReporters:t.skipReport!==!0,maxConcurrency:u,timeoutMs:d,onEvalLog:t.verbose===!0?(e,t)=>n.log(`[${e}] ${t}`):void 0});t.json&&n.log(JSON.stringify(r,null,2));let i=r.failed>0,a=t.strict===!0&&r.scored>0;(i||a)&&(process.exitCode=1)}finally{p&&await p.close()}let g=typeof process.exitCode==`number`?process.exitCode:0;process.exit(g)}function parsePositiveInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<1)throw Error(`${t} must be a positive integer; got "${e}".`);return n}function parseNonNegativeInteger(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw Error(`${t} must be a non-negative integer; got "${e}".`);return n}function filterEvalsByTag(e,t){return t.length===0?[...e]:e.filter(e=>e.tags?.some(e=>t.includes(e))??!1)}function printEvalList(e,t,n){if(t){let t=e.map(e=>({id:e.id,description:e.description,tags:e.tags}));n.log(JSON.stringify(t,null,2));return}for(let t of e){let e=t.description===void 0?``:` — ${t.description}`,r=t.tags!==void 0&&t.tags.length>0?` [${t.tags.join(`, `)}]`:``;n.log(`${t.id}${r}${e}`)}}async function readExpectedAgentName(r){try{let i=JSON.parse(await readFile(join(r,`package.json`),`utf8`));return typeof i.name==`string`&&i.name.length>0?i.name:basename(r)}catch{return basename(r)}}export{runEvalCommand};
|
|
@@ -6,6 +6,16 @@ import type { EveEval, EveEvalConfig } from "#evals/types.js";
|
|
|
6
6
|
* Returns absolute paths sorted alphabetically by relative path.
|
|
7
7
|
*/
|
|
8
8
|
export declare function discoverEvalFiles(appRoot: string): Promise<string[]>;
|
|
9
|
+
/**
|
|
10
|
+
* Finds directories under `<appRoot>/agent/` that directly contain
|
|
11
|
+
* `*.eval.ts` files. Used to produce a clear error when eval files are placed
|
|
12
|
+
* inside the agent tree instead of the top-level `evals/` directory that
|
|
13
|
+
* {@link discoverEvalFiles} scans.
|
|
14
|
+
*
|
|
15
|
+
* Returns app-root-relative, POSIX-normalized directory paths, sorted and
|
|
16
|
+
* de-duplicated. Returns `[]` when `agent/` is absent.
|
|
17
|
+
*/
|
|
18
|
+
export declare function findMisplacedEvalDirs(appRoot: string): Promise<string[]>;
|
|
9
19
|
/**
|
|
10
20
|
* Returns true when `evalId` matches one of the requested filters. A filter
|
|
11
21
|
* matches its exact eval id or any eval nested under it, so `"runtime"`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join,relative}from"node:path";import{access,readdir}from"node:fs/promises";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";const EVAL_FILE_SUFFIX=`.eval.ts`,EVAL_CONFIG_FILE=`evals.config.ts`;async function discoverEvalFiles(n){let r=join(n,`evals`),i=[];try{await collectEvalFiles(r,i)}catch(e){if(isNoEntryError(e))return[];throw e}return i.sort((e,n)=>relative(r,e).localeCompare(relative(r,n))),i}function deriveEvalId(n,r){let i=relative(join(n,`evals`),r).split(/[\\/]/u).join(`/`);return i.endsWith(EVAL_FILE_SUFFIX)?i.slice(0,-8):i}function matchesEvalFilter(e,t){return t.length===0?!0:t.some(t=>e===t||e.startsWith(`${t}/`))}async function importEvalFile(e,t){let n=(await loadAuthoredModuleNamespace(t)).default,r=deriveEvalId(e,t);if(isEveEvalDefinition(n))return[{...n,id:r}];if(Array.isArray(n))return n.map((e,n)=>{if(!isEveEvalDefinition(e))throw Error(`Eval file "${t}" exports an array whose entry at index ${n} is not a valid EveEval. Use defineEval() to create every entry.`);return{...e,id:`${r}/${String(n).padStart(4,`0`)}`}});throw Error(`Eval file "${t}" does not export a valid EveEval (or array of EveEvals) as its default export. Use defineEval() to create the eval.`)}async function discoverAndImportEvals(e,t){let n=await discoverEvalFiles(e);if(n.length===0)return[];let r=t??[],i=[],a=new Map;for(let t of n)for(let n of await importEvalFile(e,t)){let e=a.get(n.id);if(e!==void 0)throw Error(`Duplicate eval id "${n.id}" derived from both "${e}" and "${t}".`);a.set(n.id,t),matchesEvalFilter(n.id,r)&&i.push(n)}return i}async function discoverEvalConfig(t){let r=join(t,`evals`,EVAL_CONFIG_FILE);try{await access(r)}catch(e){throw isNoEntryError(e)?Error(`Missing required eval config at evals/${EVAL_CONFIG_FILE}. Create it with defineEvalConfig({}) (optionally \`{ judge: { model } }\` to set the default judge model for \`t.judge.*\` assertions).`):e}let a=(await loadAuthoredModuleNamespace(r)).default;if(!isEveEvalConfig(a))throw Error(`Eval config "evals/${EVAL_CONFIG_FILE}" must default-export a defineEvalConfig() value.`);return a}function isEveEvalConfig(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`EveEvalConfig`}function isEveEvalDefinition(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`EveEval`}async function collectEvalFiles(t,n){let i=await readdir(t,{withFileTypes:!0});for(let r of i){let i=join(t,r.name);r.isDirectory()?await collectEvalFiles(i,n):r.isFile()&&r.name.endsWith(EVAL_FILE_SUFFIX)&&n.push(i)}}function isNoEntryError(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}export{discoverAndImportEvals,discoverEvalConfig,discoverEvalFiles,importEvalFile,matchesEvalFilter};
|
|
1
|
+
import{join,relative}from"node:path";import{access,readdir}from"node:fs/promises";import{loadAuthoredModuleNamespace}from"#internal/authored-module-loader.js";const EVAL_FILE_SUFFIX=`.eval.ts`,EVAL_CONFIG_FILE=`evals.config.ts`;async function discoverEvalFiles(n){let r=join(n,`evals`),i=[];try{await collectEvalFiles(r,i)}catch(e){if(isNoEntryError(e))return[];throw e}return i.sort((e,n)=>relative(r,e).localeCompare(relative(r,n))),i}async function findMisplacedEvalDirs(t){let n=join(t,`agent`),r=new Set;try{await collectMisplacedEvalDirs(n,t,r)}catch(e){if(isNoEntryError(e))return[];throw e}return[...r].sort((e,t)=>e.localeCompare(t))}function deriveEvalId(n,r){let i=relative(join(n,`evals`),r).split(/[\\/]/u).join(`/`);return i.endsWith(EVAL_FILE_SUFFIX)?i.slice(0,-8):i}function matchesEvalFilter(e,t){return t.length===0?!0:t.some(t=>e===t||e.startsWith(`${t}/`))}async function importEvalFile(e,t){let n=(await loadAuthoredModuleNamespace(t)).default,r=deriveEvalId(e,t);if(isEveEvalDefinition(n))return[{...n,id:r}];if(Array.isArray(n))return n.map((e,n)=>{if(!isEveEvalDefinition(e))throw Error(`Eval file "${t}" exports an array whose entry at index ${n} is not a valid EveEval. Use defineEval() to create every entry.`);return{...e,id:`${r}/${String(n).padStart(4,`0`)}`}});throw Error(`Eval file "${t}" does not export a valid EveEval (or array of EveEvals) as its default export. Use defineEval() to create the eval.`)}async function discoverAndImportEvals(e,t){let n=await discoverEvalFiles(e);if(n.length===0)return[];let r=t??[],i=[],a=new Map;for(let t of n)for(let n of await importEvalFile(e,t)){let e=a.get(n.id);if(e!==void 0)throw Error(`Duplicate eval id "${n.id}" derived from both "${e}" and "${t}".`);a.set(n.id,t),matchesEvalFilter(n.id,r)&&i.push(n)}return i}async function discoverEvalConfig(t){let r=join(t,`evals`,EVAL_CONFIG_FILE);try{await access(r)}catch(e){throw isNoEntryError(e)?Error(`Missing required eval config at evals/${EVAL_CONFIG_FILE}. Create it with defineEvalConfig({}) (optionally \`{ judge: { model } }\` to set the default judge model for \`t.judge.*\` assertions).`):e}let a=(await loadAuthoredModuleNamespace(r)).default;if(!isEveEvalConfig(a))throw Error(`Eval config "evals/${EVAL_CONFIG_FILE}" must default-export a defineEvalConfig() value.`);return a}function isEveEvalConfig(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`EveEvalConfig`}function isEveEvalDefinition(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`EveEval`}async function collectEvalFiles(t,n){let i=await readdir(t,{withFileTypes:!0});for(let r of i){let i=join(t,r.name);r.isDirectory()?await collectEvalFiles(i,n):r.isFile()&&r.name.endsWith(EVAL_FILE_SUFFIX)&&n.push(i)}}async function collectMisplacedEvalDirs(n,i,o){let s=await readdir(n,{withFileTypes:!0});for(let r of s)r.isDirectory()?await collectMisplacedEvalDirs(join(n,r.name),i,o):r.isFile()&&r.name.endsWith(EVAL_FILE_SUFFIX)&&o.add(relative(i,n).split(/[\\/]/u).join(`/`))}function isNoEntryError(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}export{discoverAndImportEvals,discoverEvalConfig,discoverEvalFiles,findMisplacedEvalDirs,importEvalFile,matchesEvalFilter};
|
|
@@ -15,6 +15,8 @@ import type { DurableSessionState } from "#execution/durable-session-store.js";
|
|
|
15
15
|
import type { RunMode } from "#shared/run-mode.js";
|
|
16
16
|
export declare const TURN_WORKFLOW_INPUT_VERSION = 1;
|
|
17
17
|
export interface TurnStepInput {
|
|
18
|
+
/** Cancellation signal forwarded into the turn step. */
|
|
19
|
+
readonly abortSignal?: AbortSignal;
|
|
18
20
|
readonly input: HookPayload | undefined;
|
|
19
21
|
readonly parentWritable: WritableStream<Uint8Array>;
|
|
20
22
|
readonly serializedContext: Record<string, unknown>;
|
|
@@ -18,6 +18,8 @@ export type CreateRuntime = (config: {
|
|
|
18
18
|
* Input for building a harness step for one resolved runtime node.
|
|
19
19
|
*/
|
|
20
20
|
export interface CreateExecutionNodeStepInput {
|
|
21
|
+
/** Cancellation signal forwarded to the tool-loop harness. */
|
|
22
|
+
readonly abortSignal?: AbortSignal;
|
|
21
23
|
/**
|
|
22
24
|
* Session-level capabilities propagated from the runtime. The
|
|
23
25
|
* harness passes this through to `buildToolSet` so `ask_question`
|
|
@@ -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{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`),BUILT_IN_AGENT_TOOL_DESCRIPTION=[`Delegate a focused subtask to a fresh copy of yourself.`,`Use it to isolate complex work or split a large task into independent pieces.`,"Issue multiple `agent` calls in one response to run a small fixed set in parallel.","Each child has fresh history and state but shares your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes."].join(` `);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=createNodeHarnessTools({node:e.node});return createToolLoopHarness({capabilities:e.capabilities,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:BUILT_IN_AGENT_TOOL_DESCRIPTION,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:`),o=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({isFrameworkTool:i,rawExecute:o,scope:r.name}),inputSchema:r.inputStandardSchema??jsonSchema(r.inputSchema??{}),name:r.name,approval:r.approval,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};
|
|
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{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`),BUILT_IN_AGENT_TOOL_DESCRIPTION=[`Delegate a focused subtask to a fresh copy of yourself.`,`Use it to isolate complex work or split a large task into independent pieces.`,"Issue multiple `agent` calls in one response to run a small fixed set in parallel.","Each child has fresh history and state but shares your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes."].join(` `);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=createNodeHarnessTools({node:e.node});return createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,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:BUILT_IN_AGENT_TOOL_DESCRIPTION,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:`),o=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({isFrameworkTool:i,rawExecute:o,scope:r.name}),inputSchema:r.inputStandardSchema??jsonSchema(r.inputSchema??{}),name:r.name,approval:r.approval,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};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SandboxSession } from "#shared/sandbox-session.js";
|
|
2
|
+
/**
|
|
3
|
+
* Returns a sandbox session that applies `abortSignal` to every operation.
|
|
4
|
+
* Per-call signals are composed with the bound signal.
|
|
5
|
+
*/
|
|
6
|
+
export declare function bindSandboxAbortSignal(session: SandboxSession, abortSignal: AbortSignal): SandboxSession;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function bindSandboxAbortSignal(e,t){let compose=e=>e===void 0?t:AbortSignal.any([t,e]);return{...e,run:t=>e.run({...t,abortSignal:compose(t.abortSignal)}),spawn:t=>e.spawn({...t,abortSignal:compose(t.abortSignal)}),readFile:t=>e.readFile({...t,abortSignal:compose(t.abortSignal)}),readBinaryFile:t=>e.readBinaryFile({...t,abortSignal:compose(t.abortSignal)}),readTextFile:t=>e.readTextFile({...t,abortSignal:compose(t.abortSignal)}),writeFile:t=>e.writeFile({...t,abortSignal:compose(t.abortSignal)}),writeBinaryFile:t=>e.writeBinaryFile({...t,abortSignal:compose(t.abortSignal)}),writeTextFile:t=>e.writeTextFile({...t,abortSignal:compose(t.abortSignal)}),removePath:t=>e.removePath({...t,abortSignal:compose(t.abortSignal)})}}export{bindSandboxAbortSignal};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slice of `SandboxBackendHandle` the shutdown registry needs.
|
|
3
|
+
* Structural so handles of any session-options generic register without
|
|
4
|
+
* variance friction.
|
|
5
|
+
*/
|
|
6
|
+
export interface ShutdownCapableSandboxHandle {
|
|
7
|
+
shutdown(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Registers a live sandbox handle for shutdown tracking. A handle
|
|
11
|
+
* created later for the same backend and session key replaces the
|
|
12
|
+
* previous entry.
|
|
13
|
+
*/
|
|
14
|
+
export declare function trackActiveSandboxHandle(input: {
|
|
15
|
+
readonly backendName: string;
|
|
16
|
+
readonly handle: ShutdownCapableSandboxHandle;
|
|
17
|
+
readonly sessionKey: string;
|
|
18
|
+
}): void;
|
|
19
|
+
/**
|
|
20
|
+
* Stops every tracked sandbox by calling `shutdown()` on each handle in
|
|
21
|
+
* parallel, then clears the registry. Failures are logged and never
|
|
22
|
+
* thrown so one misbehaving sandbox cannot block server shutdown.
|
|
23
|
+
*/
|
|
24
|
+
export declare function shutdownActiveSandboxHandles(input?: {
|
|
25
|
+
readonly log?: (message: string) => void;
|
|
26
|
+
}): Promise<void>;
|
|
27
|
+
/** Returns the number of tracked handles. Exposed for tests and logging. */
|
|
28
|
+
export declare function countActiveSandboxHandles(): number;
|
|
29
|
+
export declare function clearActiveSandboxHandlesForTest(): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorMessage}from"#shared/errors.js";const activeSandboxHandles=new Map;function createActiveSandboxHandleKey(e,t){return`${e}\0${t}`}function trackActiveSandboxHandle(e){activeSandboxHandles.set(createActiveSandboxHandleKey(e.backendName,e.sessionKey),e.handle)}async function shutdownActiveSandboxHandles(n){let r=[...activeSandboxHandles.entries()];activeSandboxHandles.clear();let i=await Promise.allSettled(r.map(([,e])=>e.shutdown()));for(let[t,a]of i.entries())if(a.status===`rejected`){let i=r[t];n?.log?.(`failed to shut down sandbox "${i?.[0]??`unknown`}": ${toErrorMessage(a.reason)}`)}}function countActiveSandboxHandles(){return activeSandboxHandles.size}function clearActiveSandboxHandlesForTest(){activeSandboxHandles.clear()}export{clearActiveSandboxHandlesForTest,countActiveSandboxHandles,shutdownActiveSandboxHandles,trackActiveSandboxHandle};
|
|
@@ -27,7 +27,7 @@ export interface CreateDockerSandboxBackendInput {
|
|
|
27
27
|
* container into a reusable template image.
|
|
28
28
|
* - `create` starts (or restarts) one long-lived container per session
|
|
29
29
|
* key from the template image. The container's filesystem carries
|
|
30
|
-
* session state across reconnects
|
|
31
|
-
*
|
|
30
|
+
* session state across reconnects, so `shutdown` only stops the
|
|
31
|
+
* container and the next `create` restarts it with state intact.
|
|
32
32
|
*/
|
|
33
33
|
export declare function createDockerSandboxBackend(input?: CreateDockerSandboxBackendInput): SandboxBackend;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{expectDockerSuccess}from"#execution/sandbox/bindings/docker-utils.js";import{markDevelopmentSandboxBackendInitialized}from"#execution/sandbox/development-run.js";import{writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{assertDockerDaemonAvailable,createDockerCli}from"#execution/sandbox/bindings/docker-cli.js";import{DOCKER_SANDBOX_LABEL,runDockerBaseSetup,startDockerContainer}from"#execution/sandbox/bindings/docker-container.js";import{setDockerNetworkPolicy}from"#execution/sandbox/bindings/docker-network.js";import{createDockerSandboxOptionsHash,resolveDockerSandboxOptions}from"#execution/sandbox/bindings/docker-options.js";import{createDockerInternalSession}from"#execution/sandbox/bindings/docker-session.js";import{DOCKER_TEMPLATE_IMAGE_REPOSITORY,dockerImageExists,dockerTemplateImageReference,ensureDockerBaseImage,pruneDockerSandboxTemplates,resolveDockerTemplateMarkerPath,touchDockerTemplateMarker}from"#execution/sandbox/bindings/docker-templates.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";const DOCKER_BACKEND_NAME=`docker`;function createDockerSandboxBackend(c={}){let l=c.dockerCli??createDockerCli(),u=resolveDockerSandboxOptions(c.createOptions),d=createDockerSandboxOptionsHash(u),f;function ensureDaemon(){return f??=assertDockerDaemonAvailable(l).catch(e=>{throw f=void 0,e}),f}return{name:DOCKER_BACKEND_NAME,async prewarm(n){n.log?.(`checking Docker daemon`),await ensureDaemon();let i={optionsHash:d,templateKey:n.templateKey},a=dockerTemplateImageReference(i),o=resolveDockerTemplateMarkerPath(n.runtimeContext.appRoot,i);if(n.log?.(`checking cached template image "${a}"`),await dockerImageExists(l,a))return n.log?.(`reusing cached template image`),await touchDockerTemplateMarker(o,a),{reused:!0};n.log?.(`checking base image "${u.image}"`),await ensureDockerBaseImage(l,u);let s=`${n.templateKey}-build-${randomUUID().slice(0,8)}`;n.log?.(`starting template build container`),await startDockerContainer({cli:l,containerName:s,image:u.image,initialNetworkPolicy:`allow-all`,options:u,role:`template-build`});try{n.log?.(`preparing base runtime inside container`),await runDockerBaseSetup(l,s),u.networkPolicy!==`allow-all`&&(n.log?.(`applying network policy`),await setDockerNetworkPolicy(l,s,u.networkPolicy));let e=buildSandboxSession(createDockerInternalSession({cli:l,containerName:s,id:n.templateKey}),e=>setDockerNetworkPolicy(l,s,e));n.bootstrap!==void 0&&(n.log?.(`running sandbox bootstrap`),await n.bootstrap({use:async()=>createLoggingSandboxSession({log:n.log,session:e})})),n.seedFiles.length>0&&n.log?.(`writing ${n.seedFiles.length} seed file(s)`),await writeSandboxSeedFiles(e,n.seedFiles),n.log?.(`stopping template build container`),expectDockerSuccess(await l.run([`stop`,`-t`,`0`,s]),`stop template build container "${s}"`),n.log?.(`committing template image "${a}"`),expectDockerSuccess(await l.run([`commit`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}=1`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}.role=template`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}.template-key=${n.templateKey}`,s,a]),`commit sandbox template image "${a}"`),await touchDockerTemplateMarker(o,a)}finally{await l.run([`rm`,`-f`,s]).catch(()=>{})}return{reused:!1}},async create(e){await ensureDaemon(),markDevelopmentSandboxBackendInitialized(DOCKER_BACKEND_NAME);let r=getDockerContainerName(e.existingMetadata)??e.sessionKey,i=await l.run([`container`,`inspect`,`--format`,`{{.State.Running}}`,r]);if(i.exitCode===0)i.stdout.trim()!==`true`&&expectDockerSuccess(await l.run([`start`,r]),`restart sandbox session container "${r}"`);else{let t;if(e.templateKey===null)await ensureDockerBaseImage(l,u),t=u.image;else{let n={optionsHash:d,templateKey:e.templateKey};if(t=dockerTemplateImageReference(n),!await dockerImageExists(l,t))throw new SandboxTemplateNotProvisionedError({backendName:DOCKER_BACKEND_NAME,templateKey:e.templateKey});await touchDockerTemplateMarker(resolveDockerTemplateMarkerPath(e.runtimeContext.appRoot,n),t)}try{await startDockerContainer({cli:l,containerName:r,image:t,initialNetworkPolicy:e.templateKey===null?`allow-all`:u.networkPolicy,options:u,role:`session`,tags:e.tags})}catch(t){throw e.templateKey===null?t:new SandboxTemplateNotProvisionedError({backendName:DOCKER_BACKEND_NAME,templateKey:e.templateKey})}e.templateKey===null&&(await runDockerBaseSetup(l,r),u.networkPolicy!==`allow-all`&&await setDockerNetworkPolicy(l,r,u.networkPolicy))}let a=buildSandboxSession(createDockerInternalSession({cli:l,containerName:r,id:e.sessionKey}),e=>setDockerNetworkPolicy(l,r,e));return{session:a,useSessionFn:async()=>a,async captureState(){return{backendName:DOCKER_BACKEND_NAME,metadata:{containerName:r},sessionKey:e.sessionKey}},async
|
|
1
|
+
import{randomUUID}from"node:crypto";import{expectDockerSuccess}from"#execution/sandbox/bindings/docker-utils.js";import{markDevelopmentSandboxBackendInitialized}from"#execution/sandbox/development-run.js";import{writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{assertDockerDaemonAvailable,createDockerCli}from"#execution/sandbox/bindings/docker-cli.js";import{DOCKER_SANDBOX_LABEL,runDockerBaseSetup,startDockerContainer,stopDockerContainerIfRunning}from"#execution/sandbox/bindings/docker-container.js";import{setDockerNetworkPolicy}from"#execution/sandbox/bindings/docker-network.js";import{createDockerSandboxOptionsHash,resolveDockerSandboxOptions}from"#execution/sandbox/bindings/docker-options.js";import{createDockerInternalSession}from"#execution/sandbox/bindings/docker-session.js";import{DOCKER_TEMPLATE_IMAGE_REPOSITORY,dockerImageExists,dockerTemplateImageReference,ensureDockerBaseImage,pruneDockerSandboxTemplates,resolveDockerTemplateMarkerPath,touchDockerTemplateMarker}from"#execution/sandbox/bindings/docker-templates.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";const DOCKER_BACKEND_NAME=`docker`;function createDockerSandboxBackend(c={}){let l=c.dockerCli??createDockerCli(),u=resolveDockerSandboxOptions(c.createOptions),d=createDockerSandboxOptionsHash(u),f;function ensureDaemon(){return f??=assertDockerDaemonAvailable(l).catch(e=>{throw f=void 0,e}),f}return{name:DOCKER_BACKEND_NAME,async prewarm(n){n.log?.(`checking Docker daemon`),await ensureDaemon();let i={optionsHash:d,templateKey:n.templateKey},a=dockerTemplateImageReference(i),o=resolveDockerTemplateMarkerPath(n.runtimeContext.appRoot,i);if(n.log?.(`checking cached template image "${a}"`),await dockerImageExists(l,a))return n.log?.(`reusing cached template image`),await touchDockerTemplateMarker(o,a),{reused:!0};n.log?.(`checking base image "${u.image}"`),await ensureDockerBaseImage(l,u);let s=`${n.templateKey}-build-${randomUUID().slice(0,8)}`;n.log?.(`starting template build container`),await startDockerContainer({cli:l,containerName:s,image:u.image,initialNetworkPolicy:`allow-all`,options:u,role:`template-build`});try{n.log?.(`preparing base runtime inside container`),await runDockerBaseSetup(l,s),u.networkPolicy!==`allow-all`&&(n.log?.(`applying network policy`),await setDockerNetworkPolicy(l,s,u.networkPolicy));let e=buildSandboxSession(createDockerInternalSession({cli:l,containerName:s,id:n.templateKey}),e=>setDockerNetworkPolicy(l,s,e));n.bootstrap!==void 0&&(n.log?.(`running sandbox bootstrap`),await n.bootstrap({use:async()=>createLoggingSandboxSession({log:n.log,session:e})})),n.seedFiles.length>0&&n.log?.(`writing ${n.seedFiles.length} seed file(s)`),await writeSandboxSeedFiles(e,n.seedFiles),n.log?.(`stopping template build container`),expectDockerSuccess(await l.run([`stop`,`-t`,`0`,s]),`stop template build container "${s}"`),n.log?.(`committing template image "${a}"`),expectDockerSuccess(await l.run([`commit`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}=1`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}.role=template`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}.template-key=${n.templateKey}`,s,a]),`commit sandbox template image "${a}"`),await touchDockerTemplateMarker(o,a)}finally{await l.run([`rm`,`-f`,s]).catch(()=>{})}return{reused:!1}},async create(e){await ensureDaemon(),markDevelopmentSandboxBackendInitialized(DOCKER_BACKEND_NAME);let r=getDockerContainerName(e.existingMetadata)??e.sessionKey,i=await l.run([`container`,`inspect`,`--format`,`{{.State.Running}}`,r]);if(i.exitCode===0)i.stdout.trim()!==`true`&&expectDockerSuccess(await l.run([`start`,r]),`restart sandbox session container "${r}"`);else{let t;if(e.templateKey===null)await ensureDockerBaseImage(l,u),t=u.image;else{let n={optionsHash:d,templateKey:e.templateKey};if(t=dockerTemplateImageReference(n),!await dockerImageExists(l,t))throw new SandboxTemplateNotProvisionedError({backendName:DOCKER_BACKEND_NAME,templateKey:e.templateKey});await touchDockerTemplateMarker(resolveDockerTemplateMarkerPath(e.runtimeContext.appRoot,n),t)}try{await startDockerContainer({cli:l,containerName:r,image:t,initialNetworkPolicy:e.templateKey===null?`allow-all`:u.networkPolicy,options:u,role:`session`,tags:e.tags})}catch(t){throw e.templateKey===null?t:new SandboxTemplateNotProvisionedError({backendName:DOCKER_BACKEND_NAME,templateKey:e.templateKey})}e.templateKey===null&&(await runDockerBaseSetup(l,r),u.networkPolicy!==`allow-all`&&await setDockerNetworkPolicy(l,r,u.networkPolicy))}let a=buildSandboxSession(createDockerInternalSession({cli:l,containerName:r,id:e.sessionKey}),e=>setDockerNetworkPolicy(l,r,e));return{session:a,useSessionFn:async()=>a,async captureState(){return{backendName:DOCKER_BACKEND_NAME,metadata:{containerName:r},sessionKey:e.sessionKey}},async shutdown(){await stopDockerContainerIfRunning(l,r)}}}}}function getDockerContainerName(e){let t=e?.containerName;return typeof t==`string`?t:void 0}export{DOCKER_BACKEND_NAME,DOCKER_TEMPLATE_IMAGE_REPOSITORY,createDockerSandboxBackend,pruneDockerSandboxTemplates};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname}from"node:path";import{mkdir,readFile,writeFile}from"node:fs/promises";import{loadOptionalEnginePackage}from"#internal/application/optional-package-install.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{createFileBackedInternalSandboxSession,pathExists}from"#execution/sandbox/bindings/local-backend-utils.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{adaptMultiplexedCommandToSandboxProcess}from"#execution/sandbox/multiplexed-command.js";let justBashModulePromise;async function loadJustBashModule(e){return justBashModulePromise??=loadOptionalEnginePackage({appRoot:e.appRoot,autoInstall:e.autoInstall,importModule:async()=>await import(`just-bash`),missingMessage:"The just-bash sandbox backend requires the `just-bash` package, which is not bundled with eve. Install it in your application (for example `pnpm add -D just-bash`), or use docker() / defaultSandbox() instead.",packageName:`just-bash`}).catch(e=>{throw justBashModulePromise=void 0,e}),await justBashModulePromise}async function createBashSandbox(n){let{ReadWriteFs:r,Sandbox:i}=await loadJustBashModule({appRoot:n.appRoot,autoInstall:n.autoInstall}),a=resolveLocalSandboxFilesystemRootPath(n.rootPath),o=resolveLocalSandboxMetadataPath(n.rootPath),s=await readLocalMetadata(o);await mkdir(a,{recursive:!0});let c=new r({allowSymlinks:!0,maxFileReadSize:2**53-1,root:a});await ensureLocalSandboxDirectories(c);let l=await i.create({cwd:WORKSPACE_ROOT,env:s?.env,fs:c,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureState(){return await writeLocalMetadata(o,{env:{...l.bashEnvInstance.getEnv()},version:1}),{rootPath:n.rootPath}},async dispose(){await l.stop()},async readFileBytes(e){let t;try{t=await c.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async removePath(e){await c.rm(e.path,{force:e.force,recursive:e.recursive})},rootPath:n.rootPath,sessionKey:n.sessionKey,async spawn(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${shellQuote(e.workingDirectory)} && ${e.command} )`;return adaptMultiplexedCommandToSandboxProcess({command:await l.runCommand({args:[t],cmd:`eval`,detached:!0,env:e.env,signal:e.abortSignal}),getOutput:e=>e.type})},async writeFiles(t){for(let n of t){let t=dirname(n.path);await c.mkdir(t,{recursive:!0}),await c.writeFile(n.path,n.content)}}}}async function justBashSetNetworkPolicyUnsupported(){throw Error(`setNetworkPolicy() is not supported on the just-bash sandbox backend. just-bash applies its network policy only at sandbox creation (no run-time update) and does not run git or other binaries. Use docker() for coarse egress control or vercel() / microsandbox() for credential brokering.`)}function createJustBashHandle(e,t){let n=buildSandboxSession(createFileBackedInternalSandboxSession({id:e.sessionKey,sandbox:e}),justBashSetNetworkPolicyUnsupported);return{session:n,useSessionFn:async()=>n,async captureState(){return{backendName:t,metadata:await e.captureState()??{},sessionKey:e.sessionKey}},async
|
|
1
|
+
import{dirname}from"node:path";import{mkdir,readFile,writeFile}from"node:fs/promises";import{loadOptionalEnginePackage}from"#internal/application/optional-package-install.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{createFileBackedInternalSandboxSession,pathExists}from"#execution/sandbox/bindings/local-backend-utils.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{adaptMultiplexedCommandToSandboxProcess}from"#execution/sandbox/multiplexed-command.js";let justBashModulePromise;async function loadJustBashModule(e){return justBashModulePromise??=loadOptionalEnginePackage({appRoot:e.appRoot,autoInstall:e.autoInstall,importModule:async()=>await import(`just-bash`),missingMessage:"The just-bash sandbox backend requires the `just-bash` package, which is not bundled with eve. Install it in your application (for example `pnpm add -D just-bash`), or use docker() / defaultSandbox() instead.",packageName:`just-bash`}).catch(e=>{throw justBashModulePromise=void 0,e}),await justBashModulePromise}async function createBashSandbox(n){let{ReadWriteFs:r,Sandbox:i}=await loadJustBashModule({appRoot:n.appRoot,autoInstall:n.autoInstall}),a=resolveLocalSandboxFilesystemRootPath(n.rootPath),o=resolveLocalSandboxMetadataPath(n.rootPath),s=await readLocalMetadata(o);await mkdir(a,{recursive:!0});let c=new r({allowSymlinks:!0,maxFileReadSize:2**53-1,root:a});await ensureLocalSandboxDirectories(c);let l=await i.create({cwd:WORKSPACE_ROOT,env:s?.env,fs:c,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureState(){return await writeLocalMetadata(o,{env:{...l.bashEnvInstance.getEnv()},version:1}),{rootPath:n.rootPath}},async dispose(){await l.stop()},async readFileBytes(e){let t;try{t=await c.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async removePath(e){await c.rm(e.path,{force:e.force,recursive:e.recursive})},rootPath:n.rootPath,sessionKey:n.sessionKey,async spawn(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=e.workingDirectory===void 0?e.command:`( cd ${shellQuote(e.workingDirectory)} && ${e.command} )`;return adaptMultiplexedCommandToSandboxProcess({command:await l.runCommand({args:[t],cmd:`eval`,detached:!0,env:e.env,signal:e.abortSignal}),getOutput:e=>e.type})},async writeFiles(t){for(let n of t){let t=dirname(n.path);await c.mkdir(t,{recursive:!0}),await c.writeFile(n.path,n.content)}}}}async function justBashSetNetworkPolicyUnsupported(){throw Error(`setNetworkPolicy() is not supported on the just-bash sandbox backend. just-bash applies its network policy only at sandbox creation (no run-time update) and does not run git or other binaries. Use docker() for coarse egress control or vercel() / microsandbox() for credential brokering.`)}function createJustBashHandle(e,t){let n=buildSandboxSession(createFileBackedInternalSandboxSession({id:e.sessionKey,sandbox:e}),justBashSetNetworkPolicyUnsupported);return{session:n,useSessionFn:async()=>n,async captureState(){return{backendName:t,metadata:await e.captureState()??{},sessionKey:e.sessionKey}},async shutdown(){await e.dispose()}}}function resolveLocalSandboxFilesystemRootPath(e){return`${e}/fs`}function resolveLocalSandboxMetadataPath(e){return`${e}/metadata.json`}async function ensureLocalSandboxDirectories(e){await e.mkdir(WORKSPACE_ROOT,{recursive:!0})}async function readLocalMetadata(e){if(!await pathExists(e))return null;let t=JSON.parse(await readFile(e,`utf8`));return t.version!==1||!isStringRecord(t.env)?null:{env:t.env,version:1}}async function writeLocalMetadata(n,i){await mkdir(dirname(n),{recursive:!0}),await writeFile(n,`${JSON.stringify(i,null,2)}\n`)}function isStringRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`)}export{createBashSandbox,createJustBashHandle,justBashSetNetworkPolicyUnsupported};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname}from"node:path";import{mkdir,rename,rm}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{randomUUID}from"node:crypto";import{withDevelopmentSandboxMetadataPathTag}from"#execution/sandbox/development-run.js";import{createFileBackedInternalSandboxSession,touchDirectory,writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{MICROSANDBOX_METADATA_VERSION,readSessionMetadata,readSessionMetadataRecord,readTemplateMetadata,resolveMicrosandboxMetadataPath,writeTemplateMetadata}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{connectMicrosandbox,createPreparedMicrosandbox,createProviderName,doesPathExist,isMicrosandboxNotFoundError,loadMicrosandboxModule,removeSnapshotIfExists,sandboxExists,snapshotExists}from"#execution/sandbox/bindings/microsandbox-runtime.js";import{resolveMicrosandboxSessionRootPath,resolveMicrosandboxTemplateRootPath}from"#execution/sandbox/bindings/microsandbox-templates.js";const activeMicrosandboxSessionHandles=new Map;async function prewarmMicrosandboxTemplate(i){i.prewarmInput.log?.(`loading microsandbox runtime`);let a=await loadMicrosandboxModule({appRoot:i.prewarmInput.runtimeContext.appRoot,log:i.prewarmInput.log,options:i.options}),u=resolveMicrosandboxTemplateRootPath(resolveSandboxCacheDirectory(i.prewarmInput.runtimeContext.appRoot),i.prewarmInput.templateKey),f=resolveMicrosandboxMetadataPath(u);i.prewarmInput.log?.(`checking cached snapshot`);let p=await readTemplateMetadata(f);if(p?.optionsHash===i.optionsHash&&await snapshotExists(a,p.snapshotName))return i.prewarmInput.log?.(`reusing cached snapshot`),await touchDirectory(u),{reused:!0};let h=createProviderName(`eve-sbx-tpl`,i.prewarmInput.templateKey,i.optionsHash),_=`${u}.${randomUUID()}.tmp`,v=createProviderName(`eve-sbx-tpl-tmp`,`${i.prewarmInput.templateKey}:${randomUUID()}`);await removeSnapshotIfExists(a,h),await rm(_,{force:!0,recursive:!0}),await mkdir(_,{recursive:!0}),i.prewarmInput.log?.(`creating template VM from image "${i.options.image}"`);let y=await createPreparedMicrosandbox({log:i.prewarmInput.log,module:a,name:v,networkPolicy:i.options.networkPolicy,options:i.options,sessionKey:i.prewarmInput.templateKey,setupBaseRuntime:!0,tags:void 0}),b=buildSandboxSession(createMicrosandboxInternalSession(y),async e=>{await y.setNetworkPolicy(e)});try{i.prewarmInput.bootstrap!==void 0&&(i.prewarmInput.log?.(`running sandbox bootstrap`),await i.prewarmInput.bootstrap({use:async e=>(e?.networkPolicy!==void 0&&await y.setNetworkPolicy(e.networkPolicy),createLoggingSandboxSession({log:i.prewarmInput.log,session:b}))})),i.prewarmInput.seedFiles.length>0&&i.prewarmInput.log?.(`writing ${i.prewarmInput.seedFiles.length} seed file(s)`),await writeSandboxSeedFiles(b,i.prewarmInput.seedFiles),i.prewarmInput.log?.(`snapshotting template VM`),await y.stopAndSnapshot(h),await writeTemplateMetadata(resolveMicrosandboxMetadataPath(_),{optionsHash:i.optionsHash,snapshotName:h,version:MICROSANDBOX_METADATA_VERSION}),await mkdir(dirname(u),{recursive:!0}),await rm(u,{force:!0,recursive:!0});try{await rename(_,u)}catch(e){if(await doesPathExist(u))return{reused:!0};throw e}}finally{await y.removePersisted(),await rm(_,{force:!0,recursive:!0}).catch(()=>{})}return{reused:!1}}async function createMicrosandboxHandle(e){let t=await loadMicrosandboxModule({appRoot:e.createInput.runtimeContext.appRoot,options:e.options}),n=resolveSandboxCacheDirectory(e.createInput.runtimeContext.appRoot),r=resolveMicrosandboxSessionRootPath(n,e.createInput.sessionKey),a=createActiveMicrosandboxSessionKey(r,e.optionsHash),o=activeMicrosandboxSessionHandles.get(a);if(o!==void 0)return o;let s=resolveMicrosandboxMetadataPath(r),c=readSessionMetadataRecord(e.createInput.existingMetadata)??await readSessionMetadata(s),l=withDevelopmentSandboxMetadataPathTag(e.createInput.tags,s);if(c?.optionsHash===e.optionsHash&&(await sandboxExists(t,c.sandboxName)||c.stateSnapshotName!==void 0&&await snapshotExists(t,c.stateSnapshotName))){let n=await connectMicrosandbox({metadata:c,metadataPath:s,module:t,options:e.options,sessionKey:e.createInput.sessionKey,tags:l});if(n!==null)return cacheHandle(a,createHandle(n,e.backendName,e.optionsHash,()=>{activeMicrosandboxSessionHandles.delete(a)}))}let d=null;if(e.createInput.templateKey!==null){let r=await readTemplateMetadata(resolveMicrosandboxMetadataPath(resolveMicrosandboxTemplateRootPath(n,e.createInput.templateKey)));if(r===null||r.optionsHash!==e.optionsHash||!await snapshotExists(t,r.snapshotName))throw new SandboxTemplateNotProvisionedError({backendName:e.backendName,templateKey:e.createInput.templateKey});d=r.snapshotName}let m=createProviderName(`eve-sbx-ses`,`${e.createInput.sessionKey}:${randomUUID()}`),g;try{g=await createPreparedMicrosandbox({fromSnapshot:d??void 0,module:t,name:m,networkPolicy:e.options.networkPolicy,options:e.options,sessionKey:e.createInput.sessionKey,setupBaseRuntime:d===null,tags:l})}catch(t){throw d!==null&&e.createInput.templateKey!==null&&isMicrosandboxNotFoundError(t)?new SandboxTemplateNotProvisionedError({backendName:e.backendName,templateKey:e.createInput.templateKey}):t}return await g.writeMetadata(s,e.optionsHash),cacheHandle(a,createHandle(g,e.backendName,e.optionsHash,()=>{activeMicrosandboxSessionHandles.delete(a)}))}function createHandle(e,t,n,r){return{session:buildSandboxSession(createMicrosandboxInternalSession(e),async t=>{await e.setNetworkPolicy(t)}),useSessionFn:async t=>(t?.networkPolicy!==void 0&&await e.setNetworkPolicy(t.networkPolicy),buildSandboxSession(createMicrosandboxInternalSession(e),async t=>{await e.setNetworkPolicy(t)})),async captureState(){return{backendName:t,metadata:{...await e.captureState(n)},sessionKey:e.id}},async
|
|
1
|
+
import{dirname}from"node:path";import{mkdir,rename,rm}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{randomUUID}from"node:crypto";import{withDevelopmentSandboxMetadataPathTag}from"#execution/sandbox/development-run.js";import{createFileBackedInternalSandboxSession,touchDirectory,writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{MICROSANDBOX_METADATA_VERSION,readSessionMetadata,readSessionMetadataRecord,readTemplateMetadata,resolveMicrosandboxMetadataPath,writeTemplateMetadata}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{connectMicrosandbox,createPreparedMicrosandbox,createProviderName,doesPathExist,isMicrosandboxNotFoundError,loadMicrosandboxModule,removeSnapshotIfExists,sandboxExists,snapshotExists}from"#execution/sandbox/bindings/microsandbox-runtime.js";import{resolveMicrosandboxSessionRootPath,resolveMicrosandboxTemplateRootPath}from"#execution/sandbox/bindings/microsandbox-templates.js";const activeMicrosandboxSessionHandles=new Map;async function prewarmMicrosandboxTemplate(i){i.prewarmInput.log?.(`loading microsandbox runtime`);let a=await loadMicrosandboxModule({appRoot:i.prewarmInput.runtimeContext.appRoot,log:i.prewarmInput.log,options:i.options}),u=resolveMicrosandboxTemplateRootPath(resolveSandboxCacheDirectory(i.prewarmInput.runtimeContext.appRoot),i.prewarmInput.templateKey),f=resolveMicrosandboxMetadataPath(u);i.prewarmInput.log?.(`checking cached snapshot`);let p=await readTemplateMetadata(f);if(p?.optionsHash===i.optionsHash&&await snapshotExists(a,p.snapshotName))return i.prewarmInput.log?.(`reusing cached snapshot`),await touchDirectory(u),{reused:!0};let h=createProviderName(`eve-sbx-tpl`,i.prewarmInput.templateKey,i.optionsHash),_=`${u}.${randomUUID()}.tmp`,v=createProviderName(`eve-sbx-tpl-tmp`,`${i.prewarmInput.templateKey}:${randomUUID()}`);await removeSnapshotIfExists(a,h),await rm(_,{force:!0,recursive:!0}),await mkdir(_,{recursive:!0}),i.prewarmInput.log?.(`creating template VM from image "${i.options.image}"`);let y=await createPreparedMicrosandbox({log:i.prewarmInput.log,module:a,name:v,networkPolicy:i.options.networkPolicy,options:i.options,sessionKey:i.prewarmInput.templateKey,setupBaseRuntime:!0,tags:void 0}),b=buildSandboxSession(createMicrosandboxInternalSession(y),async e=>{await y.setNetworkPolicy(e)});try{i.prewarmInput.bootstrap!==void 0&&(i.prewarmInput.log?.(`running sandbox bootstrap`),await i.prewarmInput.bootstrap({use:async e=>(e?.networkPolicy!==void 0&&await y.setNetworkPolicy(e.networkPolicy),createLoggingSandboxSession({log:i.prewarmInput.log,session:b}))})),i.prewarmInput.seedFiles.length>0&&i.prewarmInput.log?.(`writing ${i.prewarmInput.seedFiles.length} seed file(s)`),await writeSandboxSeedFiles(b,i.prewarmInput.seedFiles),i.prewarmInput.log?.(`snapshotting template VM`),await y.stopAndSnapshot(h),await writeTemplateMetadata(resolveMicrosandboxMetadataPath(_),{optionsHash:i.optionsHash,snapshotName:h,version:MICROSANDBOX_METADATA_VERSION}),await mkdir(dirname(u),{recursive:!0}),await rm(u,{force:!0,recursive:!0});try{await rename(_,u)}catch(e){if(await doesPathExist(u))return{reused:!0};throw e}}finally{await y.removePersisted(),await rm(_,{force:!0,recursive:!0}).catch(()=>{})}return{reused:!1}}async function createMicrosandboxHandle(e){let t=await loadMicrosandboxModule({appRoot:e.createInput.runtimeContext.appRoot,options:e.options}),n=resolveSandboxCacheDirectory(e.createInput.runtimeContext.appRoot),r=resolveMicrosandboxSessionRootPath(n,e.createInput.sessionKey),a=createActiveMicrosandboxSessionKey(r,e.optionsHash),o=activeMicrosandboxSessionHandles.get(a);if(o!==void 0)return o;let s=resolveMicrosandboxMetadataPath(r),c=readSessionMetadataRecord(e.createInput.existingMetadata)??await readSessionMetadata(s),l=withDevelopmentSandboxMetadataPathTag(e.createInput.tags,s);if(c?.optionsHash===e.optionsHash&&(await sandboxExists(t,c.sandboxName)||c.stateSnapshotName!==void 0&&await snapshotExists(t,c.stateSnapshotName))){let n=await connectMicrosandbox({metadata:c,metadataPath:s,module:t,options:e.options,sessionKey:e.createInput.sessionKey,tags:l});if(n!==null)return cacheHandle(a,createHandle(n,e.backendName,e.optionsHash,()=>{activeMicrosandboxSessionHandles.delete(a)}))}let d=null;if(e.createInput.templateKey!==null){let r=await readTemplateMetadata(resolveMicrosandboxMetadataPath(resolveMicrosandboxTemplateRootPath(n,e.createInput.templateKey)));if(r===null||r.optionsHash!==e.optionsHash||!await snapshotExists(t,r.snapshotName))throw new SandboxTemplateNotProvisionedError({backendName:e.backendName,templateKey:e.createInput.templateKey});d=r.snapshotName}let m=createProviderName(`eve-sbx-ses`,`${e.createInput.sessionKey}:${randomUUID()}`),g;try{g=await createPreparedMicrosandbox({fromSnapshot:d??void 0,module:t,name:m,networkPolicy:e.options.networkPolicy,options:e.options,sessionKey:e.createInput.sessionKey,setupBaseRuntime:d===null,tags:l})}catch(t){throw d!==null&&e.createInput.templateKey!==null&&isMicrosandboxNotFoundError(t)?new SandboxTemplateNotProvisionedError({backendName:e.backendName,templateKey:e.createInput.templateKey}):t}return await g.writeMetadata(s,e.optionsHash),cacheHandle(a,createHandle(g,e.backendName,e.optionsHash,()=>{activeMicrosandboxSessionHandles.delete(a)}))}function createHandle(e,t,n,r){return{session:buildSandboxSession(createMicrosandboxInternalSession(e),async t=>{await e.setNetworkPolicy(t)}),useSessionFn:async t=>(t?.networkPolicy!==void 0&&await e.setNetworkPolicy(t.networkPolicy),buildSandboxSession(createMicrosandboxInternalSession(e),async t=>{await e.setNetworkPolicy(t)})),async captureState(){return{backendName:t,metadata:{...await e.captureState(n)},sessionKey:e.id}},async shutdown(){r?.(),await e.shutdown()}}}function createMicrosandboxInternalSession(e){return createFileBackedInternalSandboxSession({id:e.id,sandbox:e})}function createActiveMicrosandboxSessionKey(e,t){return`${e}\0${t}`}function cacheHandle(e,t){return activeMicrosandboxSessionHandles.set(e,t),t}function clearActiveMicrosandboxSessionHandlesForTest(){activeMicrosandboxSessionHandles.clear()}export{clearActiveMicrosandboxSessionHandlesForTest,createMicrosandboxHandle,prewarmMicrosandboxTemplate};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MicrosandboxModule } from "#execution/sandbox/bindings/microsandbox-runtime.js";
|
|
2
|
+
/**
|
|
3
|
+
* Classifies provider errors by message because the microsandbox SDK
|
|
4
|
+
* exposes no structured error codes for these conditions.
|
|
5
|
+
*/
|
|
6
|
+
export declare function isMicrosandboxNotFoundError(error: unknown): boolean;
|
|
7
|
+
export declare function isMicrosandboxStillRunningError(error: unknown): boolean;
|
|
8
|
+
export declare function isMicrosandboxSnapshotSourceRunningError(error: unknown): boolean;
|
|
9
|
+
export declare function snapshotExists(module: MicrosandboxModule, snapshotName: string): Promise<boolean>;
|
|
10
|
+
export declare function sandboxExists(module: MicrosandboxModule, sandboxName: string): Promise<boolean>;
|
|
11
|
+
export declare function removeSnapshotIfExists(module: MicrosandboxModule, snapshotName: string): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function isMicrosandboxNotFoundError(e){return e instanceof Error?/not found|not exist|no such/i.test(e.message):!1}function isMicrosandboxStillRunningError(e){return e instanceof Error?/still running/i.test(e.message):!1}function isMicrosandboxSnapshotSourceRunningError(e){return e instanceof Error?/snapshot source sandbox .*not stopped|SnapshotSandboxRunning/i.test(e.message):!1}async function snapshotExists(e,t){try{return await e.Snapshot.get(t),!0}catch{return!1}}async function sandboxExists(e,t){try{return await e.Sandbox.get(t),!0}catch(e){if(isMicrosandboxNotFoundError(e))return!1;throw e}}async function removeSnapshotIfExists(e,t){try{await e.Snapshot.remove(t,{force:!0})}catch(e){if(!isMicrosandboxNotFoundError(e))throw e}}export{isMicrosandboxNotFoundError,isMicrosandboxSnapshotSourceRunningError,isMicrosandboxStillRunningError,removeSnapshotIfExists,sandboxExists,snapshotExists};
|
|
@@ -4,6 +4,7 @@ import type { SandboxBackendTags } from "#public/definitions/sandbox-backend.js"
|
|
|
4
4
|
import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";
|
|
5
5
|
import type { SandboxProcess, SandboxRemovePathOptions, SandboxSpawnOptions } from "#shared/sandbox-session.js";
|
|
6
6
|
import type { Sandbox as MicrosandboxSandbox } from "microsandbox";
|
|
7
|
+
export { isMicrosandboxNotFoundError, removeSnapshotIfExists, sandboxExists, snapshotExists, } from "#execution/sandbox/bindings/microsandbox-provider-state.js";
|
|
7
8
|
export type MicrosandboxModule = typeof import("microsandbox");
|
|
8
9
|
export declare class MicrosandboxVm {
|
|
9
10
|
#private;
|
|
@@ -16,6 +17,12 @@ export declare class MicrosandboxVm {
|
|
|
16
17
|
get id(): string;
|
|
17
18
|
captureState(optionsHash: string): Promise<MicrosandboxSessionMetadata>;
|
|
18
19
|
detach(): Promise<void>;
|
|
20
|
+
/**
|
|
21
|
+
* Stops the VM and releases the SDK client for server shutdown. The
|
|
22
|
+
* stopped sandbox persists on disk, so a later `connect` restarts it
|
|
23
|
+
* (dev) or restores from the last captured snapshot (production).
|
|
24
|
+
*/
|
|
25
|
+
shutdown(): Promise<void>;
|
|
19
26
|
readFileBytes(path: string): Promise<Buffer | null>;
|
|
20
27
|
removePath(options: SandboxRemovePathOptions): Promise<void>;
|
|
21
28
|
removePersisted(): Promise<void>;
|
|
@@ -67,10 +74,6 @@ export declare function loadMicrosandboxModule(input: {
|
|
|
67
74
|
*/
|
|
68
75
|
export declare function loadMicrosandboxWithoutInstall(): Promise<MicrosandboxModule | null>;
|
|
69
76
|
export declare function stopAndSnapshotMicrosandboxSandbox(module: MicrosandboxModule, sandboxName: string, snapshotName: string): Promise<void>;
|
|
70
|
-
export declare function snapshotExists(module: MicrosandboxModule, snapshotName: string): Promise<boolean>;
|
|
71
|
-
export declare function sandboxExists(module: MicrosandboxModule, sandboxName: string): Promise<boolean>;
|
|
72
|
-
export declare function removeSnapshotIfExists(module: MicrosandboxModule, snapshotName: string): Promise<void>;
|
|
73
77
|
export declare function createProviderName(prefix: string, key: string, extra?: string): string;
|
|
74
78
|
export declare function createStableHash(value: string): string;
|
|
75
79
|
export declare function doesPathExist(path: string): Promise<boolean>;
|
|
76
|
-
export declare function isMicrosandboxNotFoundError(error: unknown): boolean;
|