eve 0.44.3 → 0.44.4
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 +15 -0
- package/dist/src/channel/adapter.d.ts +2 -2
- package/dist/src/chunks/{use-eve-agent-DpUEwS23.js → use-eve-agent-BJwaMe5k.js} +6 -2
- package/dist/src/chunks/{use-eve-agent-BsLJiIbc.js → use-eve-agent-BtsOXv3s.js} +6 -2
- package/dist/src/cli/dev/tui/prompt-command-handler.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/setup-commands.d.ts +2 -0
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +2 -2
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.d.ts +1 -0
- package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
- package/dist/src/execution/web-fetch/request.js +1 -1
- package/dist/src/execution/web-fetch/tool.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/harness/attachment-staging.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/public/channels/chat-sdk/authorization.d.ts +3 -0
- package/dist/src/public/channels/chat-sdk/authorization.js +3 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +2 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
- package/dist/src/public/channels/linq/index.d.ts +1 -1
- package/dist/src/public/channels/linq/index.js +1 -1
- package/dist/src/public/channels/linq/linqChannel.d.ts +3 -1
- package/dist/src/public/channels/linq/linqChannel.js +1 -1
- package/dist/src/public/channels/photon/index.d.ts +1 -1
- package/dist/src/public/channels/photon/index.js +1 -1
- package/dist/src/public/channels/photon/photonIMessageChannel.d.ts +3 -1
- package/dist/src/public/channels/photon/photonIMessageChannel.js +1 -1
- package/dist/src/public/channels/slack/api.d.ts +15 -5
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/slack/attachments.d.ts +2 -2
- package/dist/src/public/channels/slack/attachments.js +1 -1
- package/dist/src/public/channels/slack/hitl.d.ts +2 -0
- package/dist/src/public/channels/slack/inbound-content.d.ts +4 -0
- package/dist/src/public/channels/slack/inbound-content.js +4 -0
- package/dist/src/public/channels/slack/inbound.d.ts +8 -1
- package/dist/src/public/channels/slack/inbound.js +1 -1
- package/dist/src/public/channels/slack/index.d.ts +1 -1
- package/dist/src/public/channels/slack/input-response.d.ts +1 -0
- package/dist/src/public/channels/slack/input-response.js +1 -1
- package/dist/src/public/channels/slack/interaction-cards.d.ts +10 -0
- package/dist/src/public/channels/slack/interaction-cards.js +1 -0
- package/dist/src/public/channels/slack/interactions.d.ts +1 -0
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +6 -1
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/sandbox/just-bash-sandbox.d.ts +12 -1
- package/dist/src/setup/flows/registry.d.ts +7 -1
- package/dist/src/setup/flows/registry.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +39 -2
- package/dist/src/shared/channel-definition.d.ts +5 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/linq.mdx +1 -1
- package/docs/channels/photon.mdx +4 -4
- package/docs/channels/slack.mdx +18 -3
- package/docs/concepts/built-in-tools.md +1 -0
- package/docs/getting-started.mdx +1 -0
- package/docs/guides/dev-tui.md +26 -15
- package/docs/meta.json +1 -1
- package/docs/sandbox.mdx +20 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.44.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- dbfa01c: New standalone projects created by `eve init` now include a `README.md` with templated project and development instructions.
|
|
8
|
+
- 5a029d9: Allow `justbash({ customCommands })` to register trusted host application commands in live just-bash sandbox sessions.
|
|
9
|
+
- 2bbb775: Pass the app installation workspace id to function-form Slack bot token providers across events, interactions, proactive sends, and private file downloads.
|
|
10
|
+
- 2a34f75: Chat SDK direct-message channels now support HITL authorization challenges.
|
|
11
|
+
- 1b1f2dd: Resume an existing Web Chat session's active response even when its durable history still ends at the previous turn boundary.
|
|
12
|
+
- 8f2bf7a: Add `eval` and `deploy` scripts to newly scaffolded eve projects.
|
|
13
|
+
- bca1304: Linq and Photon inbound messages now derive user auth from their message authors, allowing user-scoped connections to request authorization by default.
|
|
14
|
+
- 50488a1: `/add` in the dev terminal UI now accepts a registry item address. `/add channel/slack` skips the category and search screens and opens that item's details and confirmation directly, then runs the same installation, setup, add-more, and deployment flow as bare `/add`, which still opens the registry browser.
|
|
15
|
+
- 94a0952: Follow up to ten `web_fetch` redirects while rechecking each destination for SSRF safety. Non-success HTTP responses now return a plain-text failure result with the response body when available instead of failing the tool call.
|
|
16
|
+
- 4464e4d: Slack inbound messages now derive their text from Block Kit blocks and legacy attachments when the top-level `text` field is empty or a short fallback. Alert-style bot posts (sections, fields, headers, markdown blocks, tables, cards, carousels, containers, rich text, legacy attachments) previously reached the model as an empty message body; they now carry the visible message content, and fetched thread replies get the same treatment.
|
|
17
|
+
|
|
3
18
|
## 0.44.3
|
|
4
19
|
|
|
5
20
|
### Patch Changes
|
|
@@ -3,7 +3,7 @@ import type { StepInput } from "#harness/types.js";
|
|
|
3
3
|
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
4
4
|
import type { SessionHandle } from "#channel/session.js";
|
|
5
5
|
import type { DeliverPayload } from "#channel/types.js";
|
|
6
|
-
import type { FetchFileResult, FetchFileFunction } from "#shared/channel-definition.js";
|
|
6
|
+
import type { FetchFileContext, FetchFileResult, FetchFileFunction } from "#shared/channel-definition.js";
|
|
7
7
|
import type { ChannelAudienceMetadata } from "#shared/channel-audience.js";
|
|
8
8
|
/**
|
|
9
9
|
* Context available to every adapter handler (`deliver` and event handlers).
|
|
@@ -72,7 +72,7 @@ export type ChannelEventHandlers<TCtx extends ChannelAdapterContext<any> = Chann
|
|
|
72
72
|
* When fields are provided, staging prefers them over the values the
|
|
73
73
|
* channel populated at ingestion time.
|
|
74
74
|
*/
|
|
75
|
-
export type { FetchFileResult };
|
|
75
|
+
export type { FetchFileContext, FetchFileResult };
|
|
76
76
|
export type ChannelInstrumentationMetadata = Readonly<Record<string, unknown> & ChannelAudienceMetadata>;
|
|
77
77
|
export type ChannelInstrumentationMetadataProjector = (state: Record<string, unknown> | undefined) => ChannelInstrumentationMetadata;
|
|
78
78
|
/**
|
|
@@ -1537,9 +1537,13 @@ var EveAgentStore = class {
|
|
|
1537
1537
|
}
|
|
1538
1538
|
if (!this.#isActiveTurn(turn)) return;
|
|
1539
1539
|
this.#publish();
|
|
1540
|
-
|
|
1540
|
+
const replaySettled = isSettledSessionTail(replayed);
|
|
1541
|
+
if (!replaySettled || replayed.at(-1)?.type === "session.waiting") {
|
|
1541
1542
|
const pendingAuthorizations = collectPendingAuthorizations(replayed);
|
|
1542
|
-
for await (const event of session.stream({
|
|
1543
|
+
for await (const event of session.stream({
|
|
1544
|
+
signal: turn.abortController.signal,
|
|
1545
|
+
streamReconnectPolicy: replaySettled ? { reconnect: false } : void 0
|
|
1546
|
+
})) {
|
|
1543
1547
|
if (!this.#isActiveTurn(turn)) return;
|
|
1544
1548
|
this.#acceptServerEvent(event);
|
|
1545
1549
|
updatePendingAuthorizations(pendingAuthorizations, event);
|
|
@@ -1537,9 +1537,13 @@ var EveAgentStore = class {
|
|
|
1537
1537
|
}
|
|
1538
1538
|
if (!this.#isActiveTurn(turn)) return;
|
|
1539
1539
|
this.#publish();
|
|
1540
|
-
|
|
1540
|
+
const replaySettled = isSettledSessionTail(replayed);
|
|
1541
|
+
if (!replaySettled || replayed.at(-1)?.type === "session.waiting") {
|
|
1541
1542
|
const pendingAuthorizations = collectPendingAuthorizations(replayed);
|
|
1542
|
-
for await (const event of session.stream({
|
|
1543
|
+
for await (const event of session.stream({
|
|
1544
|
+
signal: turn.abortController.signal,
|
|
1545
|
+
streamReconnectPolicy: replaySettled ? { reconnect: false } : void 0
|
|
1546
|
+
})) {
|
|
1543
1547
|
if (!this.#isActiveTurn(turn)) return;
|
|
1544
1548
|
this.#acceptServerEvent(event);
|
|
1545
1549
|
updatePendingAuthorizations(pendingAuthorizations, event);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isPromptCommandAvailableFor}from"./prompt-commands.js";import{toErrorMessage}from"#shared/errors.js";function createPromptCommandHandler(n){return{async handle(r,i){let{target:a}=n;if(a.kind===`remote`&&!isPromptCommandAvailableFor(r.name,`remote`))return{message:`/${r.name} needs eve dev running the local server (it is not available with --url).`};if(r.name===`model`&&r.argument.length>0){if(a.kind!==`local`)return{message:`/model needs eve dev running the local server (it is not available with --url).`};let e=a.workspaceRoot;try{let{modelChangeRefusalForUneditableModel:t}=await import(`#setup/flows/model.js`),{changeAgentModel:i,formatApplyModelOutcome:a}=await import(`#setup/flows/model-source-change.js`),o=await(n.modelChangeRefusal??t)(e);return o===null?{message:a(await(n.applyModel??i)({appRoot:e,slug:r.argument}))}:{message:o}}catch(e){return{message:`Couldn't change the model: ${toErrorMessage(e)}`}}}let o=i.renderer.setupFlow;if(o===void 0)return{message:`/${r.name} is not supported by this renderer.`};if(r.name===`vc:login`&&a.kind===`remote`){if(i.remoteConnection===void 0)return{message:`/vc:login is not available in this session.`};let e;try{({runRemoteAuthCommand:e}=await import(`./remote-auth-command.js`))}catch(e){return{message:`/vc:login failed: ${toErrorMessage(e)}`}}return{message:await e({connection:i.remoteConnection,flow:n.remoteAuthFlow,renderer:o})}}let s;try{s=await import(`./setup-commands.js`)}catch(e){return{message:`/${r.name} failed: ${toErrorMessage(e)}`}}let{runTuiSetupCommand:c,SETUP_FLOW_CONFIG:l}=s,u=l[r.name];o.begin(u.title,u.indicator);let d=!0;try{let e={command:r.name,appRoot:a.workspaceRoot,renderer:o,withExclusiveTerminal:i.withExclusiveTerminal,chatGptAccountLabel:i.chatGptAccountLabel};i.initialModelStep!==void 0&&(e.initialModelStep=i.initialModelStep),n.flows!==void 0&&(e.flows=n.flows);let t=await c(e);d=t.preserveFlowDiagnostics;let s={message:t.message};return t.tone!==void 0&&(s.tone=t.tone),t.effect!==void 0&&(s.effect=t.effect),s}finally{i.keepSetupFlowOpen!==!0&&o.end({preserveDiagnostics:d})}}}}export{createPromptCommandHandler};
|
|
1
|
+
import{isPromptCommandAvailableFor}from"./prompt-commands.js";import{toErrorMessage}from"#shared/errors.js";function createPromptCommandHandler(n){return{async handle(r,i){let{target:a}=n;if(a.kind===`remote`&&!isPromptCommandAvailableFor(r.name,`remote`))return{message:`/${r.name} needs eve dev running the local server (it is not available with --url).`};if(r.name===`model`&&r.argument.length>0){if(a.kind!==`local`)return{message:`/model needs eve dev running the local server (it is not available with --url).`};let e=a.workspaceRoot;try{let{modelChangeRefusalForUneditableModel:t}=await import(`#setup/flows/model.js`),{changeAgentModel:i,formatApplyModelOutcome:a}=await import(`#setup/flows/model-source-change.js`),o=await(n.modelChangeRefusal??t)(e);return o===null?{message:a(await(n.applyModel??i)({appRoot:e,slug:r.argument}))}:{message:o}}catch(e){return{message:`Couldn't change the model: ${toErrorMessage(e)}`}}}let o=i.renderer.setupFlow;if(o===void 0)return{message:`/${r.name} is not supported by this renderer.`};if(r.name===`vc:login`&&a.kind===`remote`){if(i.remoteConnection===void 0)return{message:`/vc:login is not available in this session.`};let e;try{({runRemoteAuthCommand:e}=await import(`./remote-auth-command.js`))}catch(e){return{message:`/vc:login failed: ${toErrorMessage(e)}`}}return{message:await e({connection:i.remoteConnection,flow:n.remoteAuthFlow,renderer:o})}}let s;try{s=await import(`./setup-commands.js`)}catch(e){return{message:`/${r.name} failed: ${toErrorMessage(e)}`}}let{runTuiSetupCommand:c,SETUP_FLOW_CONFIG:l}=s,u=l[r.name];o.begin(u.title,u.indicator);let d=!0;try{let e={command:r.name,appRoot:a.workspaceRoot,renderer:o,withExclusiveTerminal:i.withExclusiveTerminal,chatGptAccountLabel:i.chatGptAccountLabel};i.initialModelStep!==void 0&&(e.initialModelStep=i.initialModelStep),r.name===`add`&&r.argument.length>0&&(e.initialRegistryAddress=r.argument),n.flows!==void 0&&(e.flows=n.flows);let t=await c(e);d=t.preserveFlowDiagnostics;let s={message:t.message};return t.tone!==void 0&&(s.tone=t.tone),t.effect!==void 0&&(s.effect=t.effect),s}finally{i.keepSetupFlowOpen!==!0&&o.end({preserveDiagnostics:d})}}}}export{createPromptCommandHandler};
|
|
@@ -35,7 +35,7 @@ export interface PromptCommandSpec {
|
|
|
35
35
|
readonly aliases: readonly string[];
|
|
36
36
|
/** One-line discovery copy shown by the typeahead. */
|
|
37
37
|
readonly description: string;
|
|
38
|
-
/**
|
|
38
|
+
/** Optional argument shape shown dim after the name, e.g. "[provider/model]". */
|
|
39
39
|
readonly argumentHint?: string;
|
|
40
40
|
/** Accepts a trailing argument (enables `/name <arg>` parsing). */
|
|
41
41
|
readonly takesArgument: boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const PROMPT_COMMAND_DEFINITIONS=[{name:`help`,aliases:[],description:`Show available commands`,takesArgument:!1,build:()=>({type:`help`}),targets:[`local`,`remote`]},{name:`reset`,aliases:[],description:`Start a fresh session`,takesArgument:!1,build:()=>({type:`reset`}),targets:[`local`,`remote`]},{name:`cancel`,aliases:[],description:`Cancel the running turn`,takesArgument:!1,build:()=>({type:`cancel`}),targets:[`local`,`remote`]},{name:`clear`,aliases:[`new`],description:`Clear the current session context`,takesArgument:!1,build:()=>({type:`clear`}),targets:[`local`,`remote`]},{name:`compact`,aliases:[],description:`Compact the current session context`,takesArgument:!1,build:()=>({type:`compact`}),targets:[`local`,`remote`]},{name:`vc:install`,aliases:[],description:`Install the Vercel CLI`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:install`,argument:``}),targets:[`local`,`remote`]},{name:`vc:login`,aliases:[],description:`Authenticate with Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:login`,argument:``}),targets:[`local`,`remote`]},{name:`model`,aliases:[],description:`Configure the agent's model and provider`,argumentHint:`[provider/model]`,takesArgument:!0,build:e=>({type:`extension`,name:`model`,argument:e}),targets:[`local`]},{name:`loglevel`,aliases:[],description:`Show or hide captured stdout/stderr/sandbox logs`,argumentHint:`[all|stderr|sandbox|none]`,takesArgument:!0,build:e=>({type:`loglevel`,argument:e}),targets:[`local`,`remote`]},{name:`traces`,aliases:[],description:`Open the local trace viewer`,argumentHint:`[trace]`,takesArgument:!0,build:e=>({type:`traces`,argument:e}),targets:[`local`]},{name:`add`,aliases:[],description:`Add an integration from the registry`,takesArgument:!
|
|
1
|
+
const PROMPT_COMMAND_DEFINITIONS=[{name:`help`,aliases:[],description:`Show available commands`,takesArgument:!1,build:()=>({type:`help`}),targets:[`local`,`remote`]},{name:`reset`,aliases:[],description:`Start a fresh session`,takesArgument:!1,build:()=>({type:`reset`}),targets:[`local`,`remote`]},{name:`cancel`,aliases:[],description:`Cancel the running turn`,takesArgument:!1,build:()=>({type:`cancel`}),targets:[`local`,`remote`]},{name:`clear`,aliases:[`new`],description:`Clear the current session context`,takesArgument:!1,build:()=>({type:`clear`}),targets:[`local`,`remote`]},{name:`compact`,aliases:[],description:`Compact the current session context`,takesArgument:!1,build:()=>({type:`compact`}),targets:[`local`,`remote`]},{name:`vc:install`,aliases:[],description:`Install the Vercel CLI`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:install`,argument:``}),targets:[`local`,`remote`]},{name:`vc:login`,aliases:[],description:`Authenticate with Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`vc:login`,argument:``}),targets:[`local`,`remote`]},{name:`model`,aliases:[],description:`Configure the agent's model and provider`,argumentHint:`[provider/model]`,takesArgument:!0,build:e=>({type:`extension`,name:`model`,argument:e}),targets:[`local`]},{name:`loglevel`,aliases:[],description:`Show or hide captured stdout/stderr/sandbox logs`,argumentHint:`[all|stderr|sandbox|none]`,takesArgument:!0,build:e=>({type:`loglevel`,argument:e}),targets:[`local`,`remote`]},{name:`traces`,aliases:[],description:`Open the local trace viewer`,argumentHint:`[trace]`,takesArgument:!0,build:e=>({type:`traces`,argument:e}),targets:[`local`]},{name:`add`,aliases:[],description:`Add an integration from the registry`,takesArgument:!0,build:e=>({type:`extension`,name:`add`,argument:e}),targets:[`local`]},{name:`deploy`,aliases:[],description:`Deploy the agent to Vercel`,takesArgument:!1,build:()=>({type:`extension`,name:`deploy`,argument:``}),targets:[`local`]},{name:`exit`,aliases:[`quit`],description:`Quit the TUI`,takesArgument:!1,build:()=>({type:`exit`}),targets:[`local`,`remote`]}],PROMPT_COMMANDS=PROMPT_COMMAND_DEFINITIONS;function promptCommandsFor(t){return PROMPT_COMMAND_DEFINITIONS.filter(e=>e.targets.some(e=>e===t))}function isPromptCommandAvailableFor(t,n){return(PROMPT_COMMAND_DEFINITIONS.find(e=>e.name===t)?.targets)?.includes(n)??!1}function parsePromptCommand(e){let n=e.trim();if(!n.startsWith(`/`))return null;for(let e of PROMPT_COMMANDS)for(let t of[e.name,...e.aliases]){let r=`/${t}`;if(n===r)return e.build(``);if(e.takesArgument&&n.startsWith(`${r} `))return e.build(n.slice(r.length).trim())}return null}function isPromptControlCommand(e){return parsePromptCommand(e)!==null}function formatPromptCommandHelp(e=PROMPT_COMMANDS){let n=e.map(e=>{let t=e.argumentHint===void 0?``:` ${e.argumentHint}`,n=e.aliases.map(e=>` (/${e})`).join(``);return{invocation:`/${e.name}${t}${n}`,description:e.description}}),r=Math.max(...n.map(e=>e.invocation.length))+2;return n.map(e=>e.invocation.padEnd(r)+e.description).join(`
|
|
2
2
|
`)}export{PROMPT_COMMANDS,formatPromptCommandHelp,isPromptCommandAvailableFor,isPromptControlCommand,parsePromptCommand,promptCommandsFor};
|
|
@@ -46,6 +46,8 @@ export interface TuiSetupCommandInput {
|
|
|
46
46
|
renderer: TuiSetupCommandRenderer;
|
|
47
47
|
/** Initial model-flow step authorized by the runner's boot evidence. */
|
|
48
48
|
initialModelStep?: "provider";
|
|
49
|
+
/** Registry address from `/add <item>`, opening that item instead of the browser. */
|
|
50
|
+
initialRegistryAddress?: string;
|
|
49
51
|
/** Live ChatGPT identity shown only inside model configuration UI. */
|
|
50
52
|
chatGptAccountLabel?: string;
|
|
51
53
|
/** Suspends development runtime artifacts while registry installation and setup mutate them. */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{createTuiPrompter}from"./tui-prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";import{WizardCancelledError}from"#setup/step.js";import{runLoginFlow}from"#setup/flows/login.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runInstallVercelCliFlow}from"#setup/flows/install-vercel-cli.js";import{runModelFlow}from"#setup/flows/model.js";import{runProviderFlow}from"#setup/flows/provider.js";import{RegistryFlowFailedError,runRegistryFlow}from"#setup/flows/registry.js";const SETUP_FLOW_CONFIG={"vc:install":{title:`Install the Vercel CLI`,indicator:`pulse`},"vc:login":{title:`Log in to Vercel`,indicator:`pulse`},model:{title:`Configure the agent model`,indicator:`pulse`},add:{title:`Add to your agent`,indicator:`pulse`},deploy:{title:`Deploy to Vercel`,indicator:`spinner`}};function joinedTitles(e){return e.length===0?``:e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(`, `)}, and ${e.at(-1)}`}function registryResultMessage(e){let t=[`Added ${joinedTitles(e.items.map(e=>e.title))}`];for(let n of e.items){if(n.facts.length===0&&n.output.length===0)continue;t.push(``,n.title);let e=Math.max(0,...n.facts.map(e=>e.label.length));for(let r of n.facts)t.push(` ${r.label.padEnd(e)} ${r.value}`);for(let e of n.output)t.push(` ${e}`)}return t.join(`
|
|
2
2
|
`)}function muteableRenderer(e,t,n){return{readSelect:n=>t()?Promise.resolve(void 0):e.readSelect(n),readEditableSelect:n=>t()?Promise.resolve(void 0):e.readEditableSelect(n),readProviderPicker:n=>t()?Promise.resolve(void 0):e.readProviderPicker(n),readModelEditor:n=>t()?Promise.resolve(void 0):e.readModelEditor(n),readText:n=>t()?Promise.resolve(void 0):e.readText(n),readAcknowledge:n=>t()?Promise.resolve():e.readAcknowledge(n),readChoice:n=>t()?{choice:Promise.resolve(void 0),close:()=>{}}:e.readChoice(n),setStatus:n=>{t()||e.setStatus(n)},renderLine:(n,r)=>{(!t()||r===`warning`||r===`error`)&&e.renderLine(n,r)},replaceContent:n=>{t()||e.replaceContent?.(n)},renderOutput:n=>{t()||e.renderOutput(n)},withInheritedStdio:t=>e.withInheritedStdio(t),withExclusiveTerminal:e=>n?.(e)??e()}}async function runTuiSetupCommand(t){let{command:r}=t,i=!1,a=new AbortController,o=muteableRenderer(t.renderer,()=>i,t.withExclusiveTerminal),s=(t.createPrompter??createTuiPrompter)(o),c=t.renderer.waitForInterrupt(),l=Symbol(`interrupted`),u=executeSetupCommand(t,s,o,a.signal);try{let e=await Promise.race([u,c.promise.then(()=>l)]);return e===l?(i=!0,a.abort(new WizardCancelledError),{...await u,message:`/${r} interrupted.`,tone:`error`,preserveFlowDiagnostics:!0}):e}finally{c.dispose(),t.renderer.setStatus(void 0)}}async function executeSetupCommand(e,i,u,d){let{command:f,appRoot:p}=e,m={runInstallVercelCliFlow,runLoginFlow,runModelFlow,runRegistryFlow,runDeployFlow,...e.flows};try{switch(f){case`vc:install`:return installVercelCliResultMessage(await m.runInstallVercelCliFlow({appRoot:p,prompter:i,signal:d}));case`vc:login`:return loginResultMessage(await m.runLoginFlow({appRoot:p,prompter:i,signal:d}));case`model`:{let pickProvider=e=>u.readProviderPicker(e),t={appRoot:p,prompter:i,signal:d,chatGptAccountLabel:e.chatGptAccountLabel,deps:{pickModelSettings:e=>u.readModelEditor(e),runProviderFlow:e=>runProviderFlow({...e,picker:pickProvider})}};e.initialModelStep!==void 0&&(t.initialStep=e.initialModelStep),t.withExclusiveTerminal=t=>u.withInheritedStdio(()=>e.withExclusiveTerminal?.(t)??t());let n=await m.runModelFlow(t);if(n.kind===`cancelled`)return{message:n.discardedDraft===!0?`/model dismissed. Drafted changes were discarded; Done commits them.`:`/model dismissed.`,preserveFlowDiagnostics:!1};let r=[];n.modelMessage!==void 0&&r.push(n.modelMessage),n.providerSelection!==void 0&&r.push(providerSelectionMessage(n.providerSelection));let a={message:r.join(`
|
|
3
|
-
`),preserveFlowDiagnostics:!1};return n.accessChanged&&(a.effect={kind:`model-access-changed`}),a}case`add`:{let
|
|
3
|
+
`),preserveFlowDiagnostics:!1};return n.accessChanged&&(a.effect={kind:`model-access-changed`}),a}case`add`:{let t={appRoot:p,prompter:i,signal:d};e.initialRegistryAddress!==void 0&&(t.initialAddress=e.initialRegistryAddress);let n=await m.runRegistryFlow(t);if(n.kind===`cancelled`)return{message:`/add dismissed.`,preserveFlowDiagnostics:!0};let r={message:n.addedItems.length>0?registryResultMessage(n):`No registry items added.`,preserveFlowDiagnostics:!0};return n.addedItems.length>0&&(r.tone=`success`),n.deployed===`production`&&(r.effect={kind:`deployed`}),r}case`deploy`:{let e=await m.runDeployFlow({appRoot:p,prompter:i,interactive:!0,signal:d});return e.kind===`cancelled`?{message:`/deploy dismissed.`,preserveFlowDiagnostics:!0}:e.kind===`needs-link`?{message:`Not linked to a Vercel project — run /model to connect one first.`,preserveFlowDiagnostics:!0}:e.kind===`local-model`?{message:`ChatGPT subscription models are local-only. Switch to an AI Gateway or server-authenticated model before deploying.`,preserveFlowDiagnostics:!0}:{message:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}}}catch(e){let t=await vercelCliUpgradeOutcome(e instanceof RegistryFlowFailedError?e.cause:e,f,m,{appRoot:p,prompter:i,signal:d});if(t!==void 0)return t;if(e instanceof RegistryFlowFailedError){let t=e.completed;return{message:`${registryResultMessage(t)}\n\n${e.message}`,tone:`error`,preserveFlowDiagnostics:!0}}if(e instanceof WizardCancelledError)return{message:`/${f} dismissed.`,preserveFlowDiagnostics:f!==`model`};let r=vercelActionOutcome(e,f);return r===void 0?{message:`/${f} failed: ${e instanceof Error?e.message:String(e)}`,tone:`error`,preserveFlowDiagnostics:!0}:r}}async function vercelCliUpgradeOutcome(e,t,n,r){if(!(e instanceof HumanActionRequiredError)||e.action.kind!==`vercel-cli-upgrade`)return;let a;try{a=await r.prompter.select({message:`Your Vercel CLI needs an update to continue setup. Upgrade now?`,options:[{value:`upgrade`,label:`Upgrade Vercel CLI`,description:`Run the Vercel CLI's native upgrader`},{value:`later`,label:`Not now`}],initialValue:`upgrade`})}catch{a=`later`}if(a===`later`)return{message:`The Vercel CLI needs an update — run \`vercel upgrade\`, then retry /${t}.`,preserveFlowDiagnostics:!0};let o;try{o=await n.runInstallVercelCliFlow({appRoot:r.appRoot,prompter:r.prompter,signal:r.signal,upgrade:!0})}catch(e){return{message:vercelCliUpgradeFailureMessage(t,errorMessage(e)),preserveFlowDiagnostics:!0}}switch(o.kind){case`installed`:return{message:`Upgraded the Vercel CLI. Retry /${t}.`,preserveFlowDiagnostics:!1};case`failed`:return{message:vercelCliUpgradeFailureMessage(t,o.reason),preserveFlowDiagnostics:!0};case`cancelled`:return{message:`Vercel CLI upgrade cancelled — run \`vercel upgrade\`, then retry /${t}.`,preserveFlowDiagnostics:!0};case`already`:return{message:`The Vercel CLI is already up to date. Retry /${t}.`,preserveFlowDiagnostics:!1}}}function errorMessage(e){let t=(e instanceof Error?e.message:String(e)).replace(/\s+/gu,` `).trim();return t.length<=240?t:`${t.slice(0,239)}…`}function vercelCliUpgradeFailureMessage(e,t){return`Couldn't upgrade the Vercel CLI${t===void 0||t===``?``:` (${t})`} — run \`vercel upgrade\`, then retry /${e}.`}function vercelActionOutcome(e,t){if(!(e instanceof HumanActionRequiredError))return;let n=vercelActionMessage(e.action.kind,t);return n===void 0?void 0:{message:n,preserveFlowDiagnostics:!0}}function vercelActionMessage(e,t){switch(e){case`vercel-login`:return`You're not logged in to Vercel — run /vc:login, then retry /${t}.`;case`vercel-forbidden`:return`Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${t}.`;case`vercel-cli-missing`:return`The Vercel CLI isn't installed — run /vc:install to install it, then retry /${t}.`;case`vercel-cli-upgrade`:return`The Vercel CLI needs an update — run \`vercel upgrade\`, then retry /${t}.`;default:return}}function installVercelCliResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:install dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`The Vercel CLI is already installed.`,preserveFlowDiagnostics:!1};case`failed`:return{message:"Couldn't install the Vercel CLI — install it manually with `npm i -g vercel@latest`.",preserveFlowDiagnostics:!0};case`installed`:return{message:`Installed the Vercel CLI. Run /vc:login next.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}}}}function loginResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:login dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`You're already logged in to Vercel.`,preserveFlowDiagnostics:!1};case`cli-missing`:return{message:`The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.`,preserveFlowDiagnostics:!0};case`failed`:return{message:`Vercel login didn't complete — run /vc:login to try again.`,preserveFlowDiagnostics:!0};case`logged-in`:return{message:`Logged in to Vercel.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}};case`unavailable`:return{message:`Couldn't reach Vercel — check your connection, then retry /vc:login.`,preserveFlowDiagnostics:!0}}}function providerSelectionMessage(e){return e===`chatgpt`?`ChatGPT subscription selected.`:e===`ai-gateway-project`?`AI Gateway via Project selected.`:`AI Gateway via API key selected.`}export{SETUP_FLOW_CONFIG,runTuiSetupCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{Client}from"#client/client.js";import{assertExclusiveTurnInput,collectPendingAuthorizations,createAbortSignal,createSubmissionId,isAbortError,isSettledSessionTail,summarizeUserContent,toTerminalStreamFailureError,updatePendingAuthorizations}from"#client/eve-agent-store-helpers.js";const detachStore=Symbol(`detachEveAgentStore`);var EveAgentStore=class{#e;#t;#n;#r;#i=new Set;#a=createEventDeduper();#o;#s={};#c;#l;#u;#d=[];#f;#p;#m;#h;#g=`ready`;constructor(e){this.#t=e.session!==void 0,this.#e=this.#t?void 0:new Client({auth:e.auth,headers:e.headers,host:e.host??``});let t=[];for(let n of e.initialEvents??[])this.#a.admit(n)&&t.push(n);this.#u=t,this.#f=[...this.#u],this.#n=e.optimistic??!0,this.#r=e.reducer,this.#m=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#c=this.#j(this.#f),this.#h=this.#M()}get snapshot(){return this.#h}setCallbacks(e){this.#s=e}subscribe(e){return this.#i.add(e),()=>{this.#i.delete(e)}}async send(t){if(this.#o!==void 0)return await this.#v(this.#o,t);let n=Promise.withResolvers(),r=Promise.withResolvers(),a={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>a.acceptedFollowUps>0&&this.#m!==void 0?this.#m.cancel():n.promise.then(e=>e===void 0?{status:`no_active_turn`}:e.cancel()),completion:r.promise,followUpDispatches:new Set,receivedFollowUps:0,resolveCompletion:r.resolve,response:n.promise,resolveResponse:n.resolve};this.#o=a,this.#l=void 0,this.#g=`submitted`,this.#N();try{let e=await this.#s.prepareSend?.(t)??t;if(assertExclusiveTurnInput(e),!this.#S(a))return;this.#C(e),this.#w(e),this.#N();let n={...e,signal:createAbortSignal(e.signal,a.abortController.signal)},r=await this.#x(n);if(!this.#S(a))return;a.resolveResponse(r);for await(let e of r){if(!this.#S(a))return;this.#T(e)}if(!this.#S(a)||(await this.#y(a),!this.#S(a)))return;this.#g=this.#l===void 0?`ready`:`error`}catch(t){if(!this.#S(a))return;isAbortError(t)?(this.#g=`ready`,this.#O(toError(t))):(this.#l=toError(t),this.#g=`error`,this.#O(this.#l),this.#s.onError?.(this.#l))}finally{this.#S(a)&&(a.resolveResponse(void 0),this.#o=void 0,this.#s.onSessionChange?.(this.#m?.state),this.#N(),this.#s.onFinish?.(this.#h),a.resolveCompletion())}}resume(){if(this.#p!==void 0)return this.#p;let e=this.#_();this.#p=e;let clear=()=>{this.#p===e&&(this.#p=void 0)};return e.then(clear,clear),e}async#_(){if(this.#g===`streaming`||this.#g===`submitted`)throw Error(`eve session is already processing a turn.`);if(this.#m===void 0)throw Error(`An eve session is required before resuming.`);let t=Promise.withResolvers(),r=Promise.withResolvers(),i=this.#m,o={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>i.cancel(),completion:r.promise,followUpDispatches:new Set,receivedFollowUps:0,resolveCompletion:r.resolve,response:t.promise,resolveResponse:t.resolve};this.#o=o,o.resolveResponse(void 0),this.#l=void 0,this.#g=`submitted`,this.#N();try{let e=[];for await(let t of i.stream({follow:!1,signal:o.abortController.signal,startIndex:0})){if(!this.#S(o))return;e.push(t),this.#T(t,!1)}if(!this.#S(o))return;
|
|
1
|
+
import{toError}from"#shared/errors.js";import{createEventDeduper}from"#protocol/event-dedupe.js";import{isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{Client}from"#client/client.js";import{assertExclusiveTurnInput,collectPendingAuthorizations,createAbortSignal,createSubmissionId,isAbortError,isSettledSessionTail,summarizeUserContent,toTerminalStreamFailureError,updatePendingAuthorizations}from"#client/eve-agent-store-helpers.js";const detachStore=Symbol(`detachEveAgentStore`);var EveAgentStore=class{#e;#t;#n;#r;#i=new Set;#a=createEventDeduper();#o;#s={};#c;#l;#u;#d=[];#f;#p;#m;#h;#g=`ready`;constructor(e){this.#t=e.session!==void 0,this.#e=this.#t?void 0:new Client({auth:e.auth,headers:e.headers,host:e.host??``});let t=[];for(let n of e.initialEvents??[])this.#a.admit(n)&&t.push(n);this.#u=t,this.#f=[...this.#u],this.#n=e.optimistic??!0,this.#r=e.reducer,this.#m=e.session??(e.initialSession===void 0?void 0:this.#e?.sessions.attach(e.initialSession.sessionId,{streamIndex:e.initialSession.streamIndex})),this.#c=this.#j(this.#f),this.#h=this.#M()}get snapshot(){return this.#h}setCallbacks(e){this.#s=e}subscribe(e){return this.#i.add(e),()=>{this.#i.delete(e)}}async send(t){if(this.#o!==void 0)return await this.#v(this.#o,t);let n=Promise.withResolvers(),r=Promise.withResolvers(),a={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>a.acceptedFollowUps>0&&this.#m!==void 0?this.#m.cancel():n.promise.then(e=>e===void 0?{status:`no_active_turn`}:e.cancel()),completion:r.promise,followUpDispatches:new Set,receivedFollowUps:0,resolveCompletion:r.resolve,response:n.promise,resolveResponse:n.resolve};this.#o=a,this.#l=void 0,this.#g=`submitted`,this.#N();try{let e=await this.#s.prepareSend?.(t)??t;if(assertExclusiveTurnInput(e),!this.#S(a))return;this.#C(e),this.#w(e),this.#N();let n={...e,signal:createAbortSignal(e.signal,a.abortController.signal)},r=await this.#x(n);if(!this.#S(a))return;a.resolveResponse(r);for await(let e of r){if(!this.#S(a))return;this.#T(e)}if(!this.#S(a)||(await this.#y(a),!this.#S(a)))return;this.#g=this.#l===void 0?`ready`:`error`}catch(t){if(!this.#S(a))return;isAbortError(t)?(this.#g=`ready`,this.#O(toError(t))):(this.#l=toError(t),this.#g=`error`,this.#O(this.#l),this.#s.onError?.(this.#l))}finally{this.#S(a)&&(a.resolveResponse(void 0),this.#o=void 0,this.#s.onSessionChange?.(this.#m?.state),this.#N(),this.#s.onFinish?.(this.#h),a.resolveCompletion())}}resume(){if(this.#p!==void 0)return this.#p;let e=this.#_();this.#p=e;let clear=()=>{this.#p===e&&(this.#p=void 0)};return e.then(clear,clear),e}async#_(){if(this.#g===`streaming`||this.#g===`submitted`)throw Error(`eve session is already processing a turn.`);if(this.#m===void 0)throw Error(`An eve session is required before resuming.`);let t=Promise.withResolvers(),r=Promise.withResolvers(),i=this.#m,o={abortController:new AbortController,acceptedFollowUps:0,cancel:()=>i.cancel(),completion:r.promise,followUpDispatches:new Set,receivedFollowUps:0,resolveCompletion:r.resolve,response:t.promise,resolveResponse:t.resolve};this.#o=o,o.resolveResponse(void 0),this.#l=void 0,this.#g=`submitted`,this.#N();try{let e=[];for await(let t of i.stream({follow:!1,signal:o.abortController.signal,startIndex:0})){if(!this.#S(o))return;e.push(t),this.#T(t,!1)}if(!this.#S(o))return;this.#N();let t=isSettledSessionTail(e);if(!t||e.at(-1)?.type===`session.waiting`){let r=collectPendingAuthorizations(e);for await(let e of i.stream({signal:o.abortController.signal,streamReconnectPolicy:t?{reconnect:!1}:void 0})){if(!this.#S(o))return;if(this.#T(e),updatePendingAuthorizations(r,e),isCurrentTurnBoundaryEvent(e)&&(e.type!==`session.waiting`||r.size===0))break}}await this.#y(o),this.#S(o)&&(this.#g=this.#l===void 0?`ready`:`error`)}catch(t){if(!this.#S(o))return;isAbortError(t)?this.#g=`ready`:(this.#l=toError(t),this.#g=`error`,this.#s.onError?.(this.#l))}finally{this.#S(o)&&(o.resolveResponse(void 0),this.#o=void 0,this.#s.onSessionChange?.(i.state),this.#N(),this.#s.onFinish?.(this.#h),o.resolveCompletion())}}cancel(){let e=this.#o;return e===void 0?Promise.resolve({status:`no_active_turn`}):e.cancel()}[detachStore](){this.#o?.abortController.abort()}reset(){let e=this.#o;this.#o=void 0,e?.resolveResponse(void 0),e?.resolveCompletion(),e?.abortController.abort(),this.#t||(this.#m=void 0),this.#u=[],this.#a=createEventDeduper(),this.#d=[],this.#f=[],this.#c=this.#r.initial(),this.#l=void 0,this.#g=`ready`,this.#s.onSessionChange?.(this.#m?.state),this.#N()}async#v(t,n){if(n.message===void 0||n.turnPolicy!==`steer`)throw Error(`eve session is already processing a turn. Send a message with turnPolicy: "steer" to replace it.`);let r=await this.#s.prepareSend?.(n)??n;if(assertExclusiveTurnInput(r),r.message===void 0||r.turnPolicy!==`steer`)throw Error(`An in-flight follow-up requires a message with turnPolicy: "steer".`);if(!this.#S(t))return await this.send(r);let a=this.#C(r);this.#N();let o;o=(async()=>{try{if(await t.response,!this.#S(t)||this.#m===void 0)throw Error(`The active eve turn ended before the follow-up could be sent.`);let{message:e,...n}=r;await this.#m.send(e,n),t.acceptedFollowUps+=1}catch(t){throw this.#O(toError(t),a),this.#N(),t}finally{t.followUpDispatches.delete(o)}})(),t.followUpDispatches.add(o),await o,await t.completion}async#y(e){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(!(e.receivedFollowUps>=e.acceptedFollowUps||this.#m===void 0))for await(let t of this.#m.stream({signal:e.abortController.signal})){if(!this.#S(e))return;if(t.type===`message.received`&&(e.receivedFollowUps+=1),this.#T(t),isCurrentTurnBoundaryEvent(t)){for(;e.followUpDispatches.size>0;)await Promise.allSettled(e.followUpDispatches);if(e.receivedFollowUps>=e.acceptedFollowUps)return}}}async#b(e){if(this.#e===void 0)throw Error(`An external eve session is required before sending.`);if(e.message===void 0)throw Error(`Cannot answer an input request before the session starts.`);let t=await this.#e.sessions.create({...e,message:e.message});return this.#m=t.session,this.#s.onSessionChange?.(t.session.state),this.#N(),t.response}async#x(e){if(this.#m===void 0)return await this.#b(e);if(e.inputResponses===void 0){let{message:t,...n}=e;return await this.#m.send(t,n)}let{inputResponses:t,...n}=e;return await this.#m.respond(t,n)}#S(e){return this.#o===e}#C(e){if(!this.#n||e.message===void 0)return;let t=createSubmissionId(),n={createdAt:Date.now(),id:t,message:summarizeUserContent(e.message)};return this.#d=[...this.#d,n],this.#k({data:{createdAt:n.createdAt,message:n.message,submissionId:n.id},type:`client.message.submitted`}),t}#w(e){e.inputResponses===void 0||e.inputResponses.length===0||this.#k({data:{createdAt:Date.now(),responses:e.inputResponses},type:`client.input.responded`})}#T(e,t=!0){this.#a.admit(e)&&(this.#u=[...this.#u,e],this.#E(e),this.#s.onEvent?.(e),this.#g=`streaming`,this.#D(e),t&&this.#N())}#E(e){let t=this.#d[0];if(e.type===`message.received`&&t!==void 0){let n=t.id;this.#d=this.#d.slice(1),this.#A(e=>e.type===`client.message.submitted`&&e.data.submissionId===n,e);return}this.#k(e)}#D(e){let t=toTerminalStreamFailureError(e);t!==void 0&&(this.#g=`error`,this.#O(t),this.#l===void 0&&(this.#l=t,this.#s.onError?.(t)))}#O(e,t){let n=t===void 0?this.#d[0]:this.#d.find(e=>e.id===t);n!==void 0&&(this.#d=this.#d.filter(e=>e.id!==n.id),this.#A(e=>e.type===`client.message.submitted`&&e.data.submissionId===n.id,{data:{createdAt:n.createdAt,error:{message:e.message},message:n.message,submissionId:n.id},type:`client.message.failed`}))}#k(e){this.#f=[...this.#f,e],this.#c=this.#r.reduce(this.#c,e)}#A(e,t){let n=!1;this.#f=this.#f.map(r=>!n&&e(r)?(n=!0,t):r),n||(this.#f=[...this.#f,t]),this.#c=this.#j(this.#f)}#j(e){let t=this.#r.initial();for(let n of e)t=this.#r.reduce(t,n);return t}#M(){return{data:this.#c,error:this.#l,events:this.#u,session:this.#m?.state,status:this.#g}}#N(){this.#h=this.#M();for(let e of this.#i)e()}};function detachEveAgentStore(e){e[detachStore]()}export{EveAgentStore,detachEveAgentStore};
|
|
@@ -23,8 +23,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
23
23
|
readonly dropped: {};
|
|
24
24
|
};
|
|
25
25
|
readonly channel: {
|
|
26
|
-
readonly current:
|
|
27
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
|
|
26
|
+
readonly current: 8;
|
|
27
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8];
|
|
28
28
|
readonly dropped: {};
|
|
29
29
|
};
|
|
30
30
|
readonly schedule: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:17,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17],dropped:{15:`TaskExec replaces stageEffect with send`}},dynamicTool:{current:18,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],dropped:{}},channel:{current:
|
|
1
|
+
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:17,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17],dropped:{15:`TaskExec replaces stageEffect with send`}},dynamicTool:{current:18,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],dropped:{}},channel:{current:8,supported:[1,2,3,4,5,6,7,8],dropped:{}},schedule:{current:3,supported:[1,2,3],dropped:{}},subagent:{current:2,supported:[1,2],dropped:{}},connection:{current:5,supported:[1,2,3,4,5],dropped:{}},hook:{current:14,supported:[10,11,12,13,14],dropped:{1:`Model identity moved from session.started runtime metadata to step.started call attribution.`,2:`Model identity moved from session.started runtime metadata to step.started call attribution.`,3:`Model identity moved from session.started runtime metadata to step.started call attribution.`,4:`Model identity moved from session.started runtime metadata to step.started call attribution.`,5:`Model identity moved from session.started runtime metadata to step.started call attribution.`,6:`Model identity moved from session.started runtime metadata to step.started call attribution.`,7:`Model identity moved from session.started runtime metadata to step.started call attribution.`,8:`Model identity moved from session.started runtime metadata to step.started call attribution.`,9:`Model identity moved from session.started runtime metadata to step.started call attribution.`}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:12,supported:[1,2,3,4,5,6,7,8,9,10,11,12],dropped:{}},instructions:{current:2,supported:[1,2],dropped:{}},dynamicInstructions:{current:13,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:3,supported:[1,2,3],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestV1Schema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict(),extensionCompatibilityManifestV2Schema=extensionCompatibilityManifestV1Schema.extend({formatVersion:z.literal(2),build:z.object({externalDependencies:z.array(z.string().min(1)).readonly()}).strict().optional()}),extensionCompatibilityManifestSchema=z.union([extensionCompatibilityManifestV1Schema,extensionCompatibilityManifestV2Schema]);function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(t){return parseExtensionCompatibilityManifest(await readFile(t,`utf8`),t)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
|
|
@@ -17,6 +17,7 @@ export interface BashSandbox {
|
|
|
17
17
|
export declare function createBashSandbox(input: {
|
|
18
18
|
readonly appRoot: string;
|
|
19
19
|
readonly autoInstall: boolean;
|
|
20
|
+
readonly customCommands?: JustBashSandboxCreateOptions["customCommands"];
|
|
20
21
|
readonly filesystem?: JustBashSandboxCreateOptions["filesystem"];
|
|
21
22
|
readonly rootPath: string;
|
|
22
23
|
readonly sessionKey: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname}from"node:path";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(t){let n=await loadJustBashModule({appRoot:t.appRoot,autoInstall:t.autoInstall}),{ReadWriteFs:r,Sandbox:i}=n,a=resolveLocalSandboxFilesystemRootPath(t.rootPath),o=resolveLocalSandboxMetadataPath(t.rootPath),s=await readLocalMetadata(o);await mkdir(a,{recursive:!0});let c=new r({allowSymlinks:!0,maxFileReadSize:2**53-1,root:a}),l=c;if(t.filesystem!==void 0)try{l=await t.filesystem({appRoot:t.appRoot,defaultFilesystem:c,justBash:n})}catch(e){throw Error(`Failed to create the custom just-bash filesystem.`,{cause:e})}await ensureLocalSandboxDirectories(l);let u=await i.create({cwd:WORKSPACE_ROOT,env:s?.env,fs:l,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureState(){return await writeLocalMetadata(o,{env:{...u.bashEnvInstance.getEnv()},version:1}),{rootPath:t.rootPath}},async dispose(){await u.stop()},async readFileBytes(e){let t;try{t=await l.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async removePath(e){await l.rm(e.path,{force:e.force,recursive:e.recursive})},rootPath:t.rootPath,sessionKey:t.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 u.runCommand({args:[t],cmd:`eval`,detached:!0,env:e.env,signal:e.abortSignal}),getOutput:e=>e.type})},async writeFiles(e){for(let t of e){let e=dirname(t.path);await l.mkdir(e,{recursive:!0}),await l.writeFile(t.path,t.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 stop(){await e.dispose()},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 n=JSON.parse(await readFile(e,`utf8`));return n.version!==1||!isStringRecord(n.env)?null:{env:n.env,version:1}}async function writeLocalMetadata(t,r){await mkdir(dirname(t),{recursive:!0}),await writeFile(t,`${JSON.stringify(r,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
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{dirname}from"node:path";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(t){let n=await loadJustBashModule({appRoot:t.appRoot,autoInstall:t.autoInstall}),{ReadWriteFs:r,Sandbox:i}=n,a=resolveLocalSandboxFilesystemRootPath(t.rootPath),o=resolveLocalSandboxMetadataPath(t.rootPath),s=await readLocalMetadata(o);await mkdir(a,{recursive:!0});let c=new r({allowSymlinks:!0,maxFileReadSize:2**53-1,root:a}),l=c;if(t.filesystem!==void 0)try{l=await t.filesystem({appRoot:t.appRoot,defaultFilesystem:c,justBash:n})}catch(e){throw Error(`Failed to create the custom just-bash filesystem.`,{cause:e})}await ensureLocalSandboxDirectories(l);let u=await i.create({cwd:WORKSPACE_ROOT,customCommands:t.customCommands===void 0?void 0:[...t.customCommands],env:s?.env,fs:l,network:{dangerouslyAllowFullInternetAccess:!0}});return{async captureState(){return await writeLocalMetadata(o,{env:{...u.bashEnvInstance.getEnv()},version:1}),{rootPath:t.rootPath}},async dispose(){await u.stop()},async readFileBytes(e){let t;try{t=await l.readFileBuffer(e)}catch{return null}return Buffer.from(t)},async removePath(e){await l.rm(e.path,{force:e.force,recursive:e.recursive})},rootPath:t.rootPath,sessionKey:t.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 u.runCommand({args:[t],cmd:`eval`,detached:!0,env:e.env,signal:e.abortSignal}),getOutput:e=>e.type})},async writeFiles(e){for(let t of e){let e=dirname(t.path);await l.mkdir(e,{recursive:!0}),await l.writeFile(t.path,t.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 stop(){await e.dispose()},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 n=JSON.parse(await readFile(e,`utf8`));return n.version!==1||!isStringRecord(n.env)?null:{env:n.env,version:1}}async function writeLocalMetadata(t,r){await mkdir(dirname(t),{recursive:!0}),await writeFile(t,`${JSON.stringify(r,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{randomUUID}from"node:crypto";import{mkdir,readdir,rename,rm,stat}from"node:fs/promises";import{dirname,join}from"node:path";import"node:fs";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{copyDirectoryAtomically,createFileBackedInternalSandboxSession,pathExists,resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory,touchDirectory,writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,selectStaleTemplateEntries}from"#execution/sandbox/bindings/local-template-prune.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{createBashSandbox,createJustBashHandle,justBashSetNetworkPolicyUnsupported}from"#execution/sandbox/bindings/just-bash-runtime.js";const JUST_BASH_CACHE_DIRECTORY_NAME=`just-bash`,JUST_BASH_BACKEND_NAME=`just-bash`;function createJustBashSandboxBackend(n={}){let i=n.createOptions?.autoInstall??!0,o=n.createOptions?.filesystem;return{name:JUST_BASH_BACKEND_NAME,async prewarm(n){let o=resolveTemplateRootPath(resolveSandboxCacheDirectory(n.runtimeContext.appRoot),n.templateKey);if(await pathExists(o))return await touchDirectory(o),{reused:!0};let s=`${o}.${randomUUID()}.tmp`,u=!1,d=await createBashSandbox({appRoot:n.runtimeContext.appRoot,autoInstall:i,rootPath:s,sessionKey:n.templateKey}),f=buildSandboxSession(createFileBackedInternalSandboxSession({id:d.sessionKey,sandbox:d}),justBashSetNetworkPolicyUnsupported);try{if(await writeSandboxSeedFiles(f,n.seedFiles),n.bootstrap!==void 0&&(n.log?.(`running sandbox bootstrap`),await n.bootstrap({use:async()=>createLoggingSandboxSession({log:n.log,session:f})})),await d.captureState()===null)throw Error(`Failed to capture local sandbox template state for "${n.templateKey}".`);await mkdir(dirname(o),{recursive:!0});try{await rename(s,o),u=!0}catch(e){if(await pathExists(o))return{reused:!0};throw e}}finally{await d.dispose(),u||await rm(s,{force:!0,recursive:!0}).catch(()=>{})}return{reused:!1}},async create(e){let n=resolveSandboxCacheDirectory(e.runtimeContext.appRoot),r=getLocalRootPath(e.existingMetadata)??resolveSessionRootPath(n,e.sessionKey);if(!await pathExists(r))if(e.templateKey===null)await mkdir(r,{recursive:!0});else{let t=resolveTemplateRootPath(n,e.templateKey);if(!await pathExists(t))throw new SandboxTemplateNotProvisionedError({backendName:JUST_BASH_BACKEND_NAME,templateKey:e.templateKey});await copyDirectoryAtomically(t,r)}return createJustBashHandle(await createBashSandbox({appRoot:e.runtimeContext.appRoot,autoInstall:i,
|
|
1
|
+
import{randomUUID}from"node:crypto";import{mkdir,readdir,rename,rm,stat}from"node:fs/promises";import{dirname,join}from"node:path";import"node:fs";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{copyDirectoryAtomically,createFileBackedInternalSandboxSession,pathExists,resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory,touchDirectory,writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,selectStaleTemplateEntries}from"#execution/sandbox/bindings/local-template-prune.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{createBashSandbox,createJustBashHandle,justBashSetNetworkPolicyUnsupported}from"#execution/sandbox/bindings/just-bash-runtime.js";const JUST_BASH_CACHE_DIRECTORY_NAME=`just-bash`,JUST_BASH_BACKEND_NAME=`just-bash`;function createJustBashSandboxBackend(n={}){let i=n.createOptions?.autoInstall??!0,o=n.createOptions?.customCommands,u=n.createOptions?.filesystem;return{name:JUST_BASH_BACKEND_NAME,async prewarm(n){let o=resolveTemplateRootPath(resolveSandboxCacheDirectory(n.runtimeContext.appRoot),n.templateKey);if(await pathExists(o))return await touchDirectory(o),{reused:!0};let s=`${o}.${randomUUID()}.tmp`,u=!1,d=await createBashSandbox({appRoot:n.runtimeContext.appRoot,autoInstall:i,rootPath:s,sessionKey:n.templateKey}),f=buildSandboxSession(createFileBackedInternalSandboxSession({id:d.sessionKey,sandbox:d}),justBashSetNetworkPolicyUnsupported);try{if(await writeSandboxSeedFiles(f,n.seedFiles),n.bootstrap!==void 0&&(n.log?.(`running sandbox bootstrap`),await n.bootstrap({use:async()=>createLoggingSandboxSession({log:n.log,session:f})})),await d.captureState()===null)throw Error(`Failed to capture local sandbox template state for "${n.templateKey}".`);await mkdir(dirname(o),{recursive:!0});try{await rename(s,o),u=!0}catch(e){if(await pathExists(o))return{reused:!0};throw e}}finally{await d.dispose(),u||await rm(s,{force:!0,recursive:!0}).catch(()=>{})}return{reused:!1}},async create(e){let n=resolveSandboxCacheDirectory(e.runtimeContext.appRoot),r=getLocalRootPath(e.existingMetadata)??resolveSessionRootPath(n,e.sessionKey);if(!await pathExists(r))if(e.templateKey===null)await mkdir(r,{recursive:!0});else{let t=resolveTemplateRootPath(n,e.templateKey);if(!await pathExists(t))throw new SandboxTemplateNotProvisionedError({backendName:JUST_BASH_BACKEND_NAME,templateKey:e.templateKey});await copyDirectoryAtomically(t,r)}return createJustBashHandle(await createBashSandbox({appRoot:e.runtimeContext.appRoot,autoInstall:i,customCommands:o,filesystem:u,rootPath:r,sessionKey:e.sessionKey}),JUST_BASH_BACKEND_NAME)}}}async function pruneJustBashSandboxTemplates(e){let t=resolveLocalBackendTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot),JUST_BASH_CACHE_DIRECTORY_NAME),r=e.now??Date.now(),a=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,s=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,c;try{c=await readdir(t,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let l=await Promise.all(c.filter(e=>e.isDirectory()).map(async e=>{let n=join(t,e.name);return{isTemporary:e.name.endsWith(`.tmp`),mtimeMs:(await stat(n)).mtimeMs,path:n}})),u=selectStaleTemplateEntries(l.filter(e=>!e.isTemporary),{now:r,recentWindowMs:a,retainCount:s}),d=selectStaleTemplateEntries(l.filter(e=>e.isTemporary),{now:r,recentWindowMs:a,retainCount:0});await Promise.all([...u,...d].map(async e=>await rm(e.path,{force:!0,recursive:!0})))}function resolveTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function resolveSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,JUST_BASH_CACHE_DIRECTORY_NAME,t)}function getLocalRootPath(e){let t=e?.rootPath;return typeof t==`string`?t:void 0}export{JUST_BASH_BACKEND_NAME,createJustBashSandboxBackend,pruneJustBashSandboxTemplates};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLoopbackHostname,isPrivateOrReservedIpAddress}from"#shared/network-address.js";import{lookup}from"node:dns";import{isIP}from"node:net";const REDIRECT_STATUSES=new Set([301,302,303,307,308]),UNSAFE_DESTINATION_ERROR=`URL must not target localhost, private, link-local, or reserved IP addresses.`;async function requestPublicUrl(e,t){let n=parseHttpsUrl(e)
|
|
1
|
+
import{isLoopbackHostname,isPrivateOrReservedIpAddress}from"#shared/network-address.js";import{lookup}from"node:dns";import{isIP}from"node:net";const REDIRECT_STATUSES=new Set([301,302,303,307,308]),UNSAFE_DESTINATION_ERROR=`URL must not target localhost, private, link-local, or reserved IP addresses.`;async function requestPublicUrl(e,t){let n=parseHttpsUrl(e);for(let e=0;;e++){let{dispatcher:r,response:a}=await requestOnce(n,t);try{let r=a.headers.get(`location`);if(r!==null&&REDIRECT_STATUSES.has(a.status)&&e<10){await cancelResponseBody(a),n=parseHttpsUrl(new URL(r,n).toString());continue}return await consumeResponse(a,t.maxResponseSize)}finally{await r.close()}}}function parseHttpsUrl(e){let t;try{t=new URL(e)}catch{throw Error(`URL must be a valid absolute https:// URL.`)}if(t.protocol!==`https:`)throw Error(`URL must start with https://`);return t}async function requestOnce(e,t){assertPublicHostname(e.hostname);let{Agent:n,Dispatcher1Wrapper:r}=await import(`undici`),i=new r(new n({connect:{lookup:createPublicLookup()}}));try{return{dispatcher:i,response:await fetchWithDispatcher(e,{dispatcher:i,headers:t.headers,redirect:`manual`,signal:t.signal})}}catch(e){throw await i.close(),e}}function fetchWithDispatcher(e,t){return fetch(e,t)}function assertPublicHostname(t){let n=t.replace(/^\[(.*)\]$/u,`$1`);if(isIP(n)!==0){assertPublicAddress(n);return}if(isLoopbackHostname(n))throw Error(UNSAFE_DESTINATION_ERROR)}function assertPublicAddress(e){if(isPrivateOrReservedIpAddress(e))throw Error(UNSAFE_DESTINATION_ERROR)}function createPublicLookup(){return(e,t,r)=>{lookup(e,{all:!0,verbatim:!0},(n,i)=>{if(n!==null){r(n,``,0);return}try{for(let{address:e}of i)assertPublicAddress(e)}catch(e){r(e,``,0);return}let a=t.family===void 0||t.family===0?i:i.filter(({family:e})=>e===t.family);if(a.length===0){let t=Error(`Unable to resolve URL hostname "${e}" in the requested IP family.`);Object.assign(t,{code:`ENOTFOUND`}),r(t,``,0);return}if(t.all===!0){r(null,a);return}let o=a[0];r(null,o.address,o.family)})}}async function consumeResponse(e,t){let n=parseContentLength(e.headers.get(`content-length`));if(n!==void 0&&n>t)throw await cancelResponseBody(e),createResponseTooLargeError();let r=await readBoundedBody(e,t),i=r.byteLength===0?null:Uint8Array.from(r).buffer;return new Response(i,{headers:e.headers,status:e.status,statusText:e.statusText})}function parseContentLength(e){if(e===null)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>=0?t:void 0}async function readBoundedBody(e,t){if(e.body===null)return new Uint8Array;let n=e.body.getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.byteLength,i>t)throw await n.cancel(),createResponseTooLargeError();r.push(a)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a}async function cancelResponseBody(e){try{await e.body?.cancel()}catch{}}function createResponseTooLargeError(){return Error(`Response too large (exceeds 5 MB limit).`)}export{requestPublicUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{truncateHead}from"#execution/sandbox/truncate-output.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{convertHtmlToMarkdown,extractTextFromHtml}from"#execution/web-fetch/html.js";import{requestPublicUrl}from"#execution/web-fetch/request.js";const MAX_RESPONSE_SIZE=5*1024*1024;async function executeWebFetchTool(n,r){let{url:i,format:a=`markdown`,timeout:o}=n,s=Math.min(o===void 0?3e4:o*1e3,12e4),c=AbortSignal.timeout(s),l=r?.abortSignal===void 0?c:AbortSignal.any([r.abortSignal,c]),u=buildHeaders(a),d=await requestPublicUrl(i,{headers:u,maxResponseSize:MAX_RESPONSE_SIZE,signal:l}),f=d.status===403&&d.headers.get(`cf-mitigated`)===`challenge`?await requestPublicUrl(i,{headers:{...u,"User-Agent":EVE_PACKAGE_NAME},maxResponseSize:MAX_RESPONSE_SIZE,signal:l}):d
|
|
1
|
+
import{truncateHead}from"#execution/sandbox/truncate-output.js";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{convertHtmlToMarkdown,extractTextFromHtml}from"#execution/web-fetch/html.js";import{requestPublicUrl}from"#execution/web-fetch/request.js";const MAX_RESPONSE_SIZE=5*1024*1024;async function executeWebFetchTool(n,r){let{url:i,format:a=`markdown`,timeout:o}=n,s=Math.min(o===void 0?3e4:o*1e3,12e4),c=AbortSignal.timeout(s),l=r?.abortSignal===void 0?c:AbortSignal.any([r.abortSignal,c]),u=buildHeaders(a),d=await requestPublicUrl(i,{headers:u,maxResponseSize:MAX_RESPONSE_SIZE,signal:l}),f=d.status===403&&d.headers.get(`cf-mitigated`)===`challenge`?await requestPublicUrl(i,{headers:{...u,"User-Agent":EVE_PACKAGE_NAME},maxResponseSize:MAX_RESPONSE_SIZE,signal:l}):d,p=await f.arrayBuffer(),m=f.headers.get(`content-type`)??``,h=m.includes(`text/html`),g=new TextDecoder().decode(p),_;if(_=a===`markdown`&&h?convertHtmlToMarkdown(g):a===`text`&&h?extractTextFromHtml(g):g,!f.ok){let e=`Request failed with status code: ${f.status}`;_=_.length===0?e:`${e}\n\n${_}`}let{output:v,truncated:y}=truncateHead(_);return{content:v,contentType:m,truncated:y,url:i}}function buildHeaders(e){let t;return t=e===`markdown`?`text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1`:e===`text`?`text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1`:`text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1`,{Accept:t,"Accept-Language":`en-US,en;q=0.9`,"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36`}}export{executeWebFetchTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,start}from"#internal/workflow/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{RuntimeSessionOwnershipConflictError}from"#execution/runtime-errors.js";import{sessionCommandHookToken}from"#execution/session-command-token.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{walkCauseChain}from"#shared/errors.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{serializeContext}from"#context/serialize.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{EntityConflictError,HookNotFoundError,RunExpiredError,WorkflowRunNotFoundError}from"#compiled/@workflow/errors/index.js";import{getHookByToken,getRun,start}from"#internal/workflow/runtime.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{resumeSessionInbox}from"#execution/wire/session-inbox-resume.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";import{buildInvocationAttributes}from"#internal/invocation/metadata.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,TASK_RUN_WORKFLOW_NAME=`taskRunWorkflow`,EVE_PACKAGE_INFO=resolveInstalledPackageInfo(),COMMAND_HOOK_READY_TIMEOUT_MS=3e4,LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE=`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`,STABLE_WORKFLOW_NAMES=new Set([WORKFLOW_ENTRY_NAME,TURN_WORKFLOW_NAME,SESSION_TIMEOUT_WORKFLOW_NAME,TASK_RUN_WORKFLOW_NAME]),STABLE_ID_BASE=EVE_PACKAGE_INFO.name,log=createLogger(`execution.workflow-runtime`),workflowEntryReference={workflowId:`workflow//${STABLE_ID_BASE}//${WORKFLOW_ENTRY_NAME}`},turnWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TURN_WORKFLOW_NAME}`},sessionTimeoutWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`},taskRunWorkflowReference={workflowId:`workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`};function createWorkflowRuntime(e){return{async createSession(i){let a=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),o=buildRunContext({bundle:a,dynamicSubagentAgentConfig:e.dynamicSubagentAgentConfig,run:i}),s=resolveEffectiveAgentRuntime(a,o),c=serializeContext(o),l=readParentLineage(c),u=s.limits?.sessionTimeoutMs,d={input:i.input,limits:i.limits,serializedContext:c};u!==void 0&&(d.sessionTimeoutMs=u);let f={...l.sessionId===void 0?buildSessionAttributes({inputMessage:i.title??i.input.message,serializedContext:c}):buildSubagentRootAttributes({identity:{nodeId:a.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},parentCallId:l.callId,parentSessionId:l.sessionId,parentTurnId:l.turnId,rootSessionId:l.rootSessionId??l.sessionId,serializedContext:c}),...i.externalInvocation===void 0?{}:buildInvocationAttributes(i.externalInvocation)},p;try{p=await startWorkflowPreferLatest(workflowEntryReference,[d],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(f)})}catch(e){throw logError(log,`failed to start workflow run`,e,{continuationToken:i.continuationToken}),e}if(i.continuationToken){let e=await waitForCommandHookOwner(i.continuationToken);if(e.runId!==p.runId)throw new RuntimeSessionOwnershipConflictError({continuationToken:i.continuationToken,ownerSessionId:e.runId,sessionId:p.runId})}await waitForOwnedCommandHook(sessionCommandHookToken(p.runId),p.runId);let m,getEvents=()=>(m??=parseNdjsonStream(()=>getRun(p.runId).getReadable()),m);return{get events(){return getEvents()},sessionId:p.runId}},async dispatchContinuation(e){return await dispatchWorkflowCommand(e.continuationToken,e.command)},async dispatchSession(e){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),e.command)},async getEventStream(e,t){return parseNdjsonStream(()=>getRun(e).getReadable({startIndex:t?.startIndex}))},async getStreamTailIndex(e){let t=getRun(e).getReadable();try{return await t.getTailIndex()}finally{await t.cancel().catch(()=>{})}},async resolveContinuation(e){try{return{sessionId:(await getHookByToken(e)).runId}}catch(n){if(HookNotFoundError.is(n))return;throw logError(log,`failed to resolve session by continuation token`,n,{continuationToken:e}),n}}}}async function dispatchWorkflowCommand(e,n){let i;try{i=normalizeWorkflowHook(await resumeSessionInbox(e,n))}catch(r){if(isInactiveCommandTarget(r))return inactiveCommandResult(n);throw logError(log,`failed to dispatch session command`,r,{command:n.kind,token:e}),r}return n.kind===`reset`&&await waitForCommandHookRelease(sessionCommandHookToken(i.runId),i.runId),activeCommandResult(n,i.runId)}function activeCommandResult(e,t){return e.kind===`reset`?{previousSessionId:t,status:`reset`}:(e.kind,{sessionId:t,status:`accepted`})}function inactiveCommandResult(e){return e.kind===`send`?{status:`session_not_active`}:e.kind===`cancel`?{status:`no_active_turn`}:{status:`no_active_session`}}async function requestWorkflowTurnCancellation(e){let t={kind:`cancel`};return e.taskId!==void 0&&(t.taskId=e.taskId),e.turnId!==void 0&&(t.turnId=e.turnId),await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),t)}function isInactiveCommandTarget(e){if(HookNotFoundError.is(e))return!0;for(let t of walkCauseChain(e))if(WorkflowRunNotFoundError.is(t)||RunExpiredError.is(t)||EntityConflictError.is(t))return!0;return!1}async function waitForOwnedCommandHook(e,t){let r=await waitForCommandHookOwner(e);if(r.runId!==t)throw new RuntimeSessionOwnershipConflictError({continuationToken:e,ownerSessionId:r.runId,sessionId:t})}async function waitForCommandHookOwner(e){let t=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;)try{return normalizeWorkflowHook(await getHookByToken(e))}catch(e){if(!HookNotFoundError.is(e)||Date.now()>=t)throw e;await new Promise(e=>setTimeout(e,20))}}async function waitForCommandHookRelease(e,t){let n=Date.now()+COMMAND_HOOK_READY_TIMEOUT_MS;for(;;){try{if(normalizeWorkflowHook(await getHookByToken(e)).runId!==t)return}catch(e){if(HookNotFoundError.is(e))return;throw e}if(Date.now()>=n)throw Error(`Timed out waiting for session "${t}" to release its command inbox.`);await new Promise(e=>setTimeout(e,20))}}async function startWorkflowPreferLatest(e,t,n){if(!shouldRouteToLatestDeployment())return n===void 0?await start(e,t):await start(e,t,n);try{return await start(e,t,{...n,deploymentId:`latest`})}catch(r){if(!isLatestDeploymentUnsupportedError(r))throw r;return n===void 0?await start(e,t):await start(e,t,n)}}function shouldRouteToLatestDeployment(){return process.env.VERCEL_ENV===`production`||isEveDevEnvironment()}function isLatestDeploymentUnsupportedError(e){return e instanceof Error&&e.message.includes(`deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()`)}function normalizeWorkflowHook(e){if(typeof e!=`object`||!e||!(`runId`in e))throw Error(`Workflow hook did not include a run id.`);let t=e.runId;if(typeof t!=`string`||t.length===0)throw Error(`Workflow hook did not include a run id.`);return{runId:t}}export{LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,STABLE_WORKFLOW_NAMES,createWorkflowRuntime,requestWorkflowTurnCancellation,sessionTimeoutWorkflowReference,startWorkflowPreferLatest,taskRunWorkflowReference,turnWorkflowReference,waitForCommandHookOwner,workflowEntryReference};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{buildSessionHandle}from"#channel/session.js";import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{deserializeUrlFilePart,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{SandboxKey}from"#context/keys.js";import{basename}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{fileDataToBytes}from"#internal/attachments/data.js";import{EveAttachmentError}from"#internal/attachments/errors.js";import{decodeSandboxRef,encodeSandboxRef,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";const ATTACHMENTS_ROOT=`/workspace/attachments`,log=createLogger(`harness.attachment-staging`),UNSAFE_FILENAME_CHARS=/[^\w.-]+/g;async function stageAttachmentsForAdapter(e,t,n){if(typeof e==`string`)return e;let r=reconstitueFilePartUrls(e);return Promise.all(r.map(async e=>e.type===`file`?stageFilePart(e,t,n):e))}async function stageAttachmentsToSandbox(e){if(typeof e==`string`||!Array.isArray(e)||!hasFileParts(e))return e;let n=loadContext(),r=n.get(SandboxKey);if(r===void 0)return e;let i=await r.get();if(i===null)return e;let a=n.get(ChannelKey);return stageAttachmentsForAdapter(e,i,a?buildAdapterContext(a,n):{ctx:n,state:{},session:buildSessionHandle(n)})}async function hydrateSandboxAttachments(e){if(!messagesContainSandboxRef(e))return e;let t=loadContext().get(SandboxKey);if(t===void 0)throw Error(`Cannot hydrate sandbox-ref FilePart: no SandboxKey is bound on the active eve context. Hydration must run inside a step scope with the framework sandbox provider installed.`);let n=await t.get();if(n===null)throw Error(`Cannot hydrate sandbox-ref FilePart: SandboxKey is bound but no active sandbox session is available.`);return Promise.all(e.map(async e=>{if(!messageContainsSandboxRef(e))return e;let t=await hydrateMessageContent(e.content,n);return{...e,content:t}}))}function hasFileParts(e){for(let t of e)if(t.type===`file`)return!0;return!1}function messagesContainSandboxRef(e){for(let t of e)if(messageContainsSandboxRef(t))return!0;return!1}function messageContainsSandboxRef(e){let t=e.content;if(!Array.isArray(t))return!1;for(let e of t)if(isSandboxRefFilePart(e))return!0;return!1}function isSandboxRefFilePart(e){return typeof e==`object`&&!!e&&e.type===`file`&&isSandboxRefUrl(e.data)}async function hydrateMessageContent(e,t){return Array.isArray(e)?Promise.all(e.map(async e=>{if(!isSandboxRefFilePart(e))return e;let n=e,r=decodeSandboxRef(n.data);if(!shouldInlineSandboxRefAsBytes(r))return renderSandboxRefAsTextPart(r);let i=await t.readBinaryFile({path:r.path});return i===null?(log.warn(`sandbox-ref attachment bytes missing on hydration — degrading to text reference`,{mediaType:r.mediaType,path:r.path,size:r.size}),{text:`FileNotFound: Current snapshot may be newer and does not contain ${r.path}.`,type:`text`}):{...n,data:i,mediaType:r.mediaType}})):e}function shouldInlineSandboxRefAsBytes(e){return e.mediaType.startsWith(`image/`)?e.size<=3145728:e.mediaType===`application/pdf`&&e.size<=20971520}function renderSandboxRefAsTextPart(e){return{text:`Attached file ${e.path} (${e.mediaType})`,type:`text`}}async function stageFilePart(e,t,n){if(isSandboxRefUrl(e.data))return e;if(e.data instanceof URL&&e.data.protocol!==`data:`){let r=await tryFetchFile(e.data.href,n);return r===null?e:stageResolvedBytes(e,r,t)}let r=await fileDataToBytes(e.data);return r===null?e:stageResolvedBytes(e,{bytes:r},t)}async function stageResolvedBytes(e,t,n){let r=t.bytes,i=sha256Prefix(r),a=t.mediaType??e.mediaType??`application/octet-stream`,o=safeFilename(t.filename??e.filename,i),s=`${ATTACHMENTS_ROOT}/${i}/${o}`;await n.writeBinaryFile({content:r,path:s});let c=n.resolvePath(s);return{...e,data:encodeSandboxRef({mediaType:a,path:c,size:r.byteLength}),filename:c,mediaType:a}}async function tryFetchFile(e,t){let n=t.ctx.get(ChannelKey);if(n?.fetchFile===void 0)return null;let i=getAdapterKind(n);try{let
|
|
1
|
+
import{createHash}from"node:crypto";import{buildSessionHandle}from"#channel/session.js";import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{deserializeUrlFilePart,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{SandboxKey}from"#context/keys.js";import{basename}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{fileDataToBytes}from"#internal/attachments/data.js";import{EveAttachmentError}from"#internal/attachments/errors.js";import{decodeSandboxRef,encodeSandboxRef,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";const ATTACHMENTS_ROOT=`/workspace/attachments`,log=createLogger(`harness.attachment-staging`),UNSAFE_FILENAME_CHARS=/[^\w.-]+/g;async function stageAttachmentsForAdapter(e,t,n){if(typeof e==`string`)return e;let r=reconstitueFilePartUrls(e);return Promise.all(r.map(async e=>e.type===`file`?stageFilePart(e,t,n):e))}async function stageAttachmentsToSandbox(e){if(typeof e==`string`||!Array.isArray(e)||!hasFileParts(e))return e;let n=loadContext(),r=n.get(SandboxKey);if(r===void 0)return e;let i=await r.get();if(i===null)return e;let a=n.get(ChannelKey);return stageAttachmentsForAdapter(e,i,a?buildAdapterContext(a,n):{ctx:n,state:{},session:buildSessionHandle(n)})}async function hydrateSandboxAttachments(e){if(!messagesContainSandboxRef(e))return e;let t=loadContext().get(SandboxKey);if(t===void 0)throw Error(`Cannot hydrate sandbox-ref FilePart: no SandboxKey is bound on the active eve context. Hydration must run inside a step scope with the framework sandbox provider installed.`);let n=await t.get();if(n===null)throw Error(`Cannot hydrate sandbox-ref FilePart: SandboxKey is bound but no active sandbox session is available.`);return Promise.all(e.map(async e=>{if(!messageContainsSandboxRef(e))return e;let t=await hydrateMessageContent(e.content,n);return{...e,content:t}}))}function hasFileParts(e){for(let t of e)if(t.type===`file`)return!0;return!1}function messagesContainSandboxRef(e){for(let t of e)if(messageContainsSandboxRef(t))return!0;return!1}function messageContainsSandboxRef(e){let t=e.content;if(!Array.isArray(t))return!1;for(let e of t)if(isSandboxRefFilePart(e))return!0;return!1}function isSandboxRefFilePart(e){return typeof e==`object`&&!!e&&e.type===`file`&&isSandboxRefUrl(e.data)}async function hydrateMessageContent(e,t){return Array.isArray(e)?Promise.all(e.map(async e=>{if(!isSandboxRefFilePart(e))return e;let n=e,r=decodeSandboxRef(n.data);if(!shouldInlineSandboxRefAsBytes(r))return renderSandboxRefAsTextPart(r);let i=await t.readBinaryFile({path:r.path});return i===null?(log.warn(`sandbox-ref attachment bytes missing on hydration — degrading to text reference`,{mediaType:r.mediaType,path:r.path,size:r.size}),{text:`FileNotFound: Current snapshot may be newer and does not contain ${r.path}.`,type:`text`}):{...n,data:i,mediaType:r.mediaType}})):e}function shouldInlineSandboxRefAsBytes(e){return e.mediaType.startsWith(`image/`)?e.size<=3145728:e.mediaType===`application/pdf`&&e.size<=20971520}function renderSandboxRefAsTextPart(e){return{text:`Attached file ${e.path} (${e.mediaType})`,type:`text`}}async function stageFilePart(e,t,n){if(isSandboxRefUrl(e.data))return e;if(e.data instanceof URL&&e.data.protocol!==`data:`){let r=await tryFetchFile(e.data.href,n);return r===null?e:stageResolvedBytes(e,r,t)}let r=await fileDataToBytes(e.data);return r===null?e:stageResolvedBytes(e,{bytes:r},t)}async function stageResolvedBytes(e,t,n){let r=t.bytes,i=sha256Prefix(r),a=t.mediaType??e.mediaType??`application/octet-stream`,o=safeFilename(t.filename??e.filename,i),s=`${ATTACHMENTS_ROOT}/${i}/${o}`;await n.writeBinaryFile({content:r,path:s});let c=n.resolvePath(s);return{...e,data:encodeSandboxRef({mediaType:a,path:c,size:r.byteLength}),filename:c,mediaType:a}}async function tryFetchFile(e,t){let n=t.ctx.get(ChannelKey);if(n?.fetchFile===void 0)return null;let i=getAdapterKind(n);try{let r=await n.fetchFile(e,t);return r===null?null:Buffer.isBuffer(r)?{bytes:r}:r}catch(e){throw e instanceof EveAttachmentError?e:new EveAttachmentError({adapterKind:i,cause:e,kind:`resolver-threw`,message:`fetchFile for adapter kind="${i}" threw: ${toErrorMessage(e)}`})}}function reconstitueFilePartUrls(e){let t=!1,n=e.map(e=>e.type===`file`&&isSerializedUrlFilePart(e.data)?(t=!0,{...e,data:deserializeUrlFilePart(e.data)}):e);return t?n:e}function sha256Prefix(t){return createHash(`sha256`).update(t).digest(`hex`).slice(0,16)}function safeFilename(e,t){if(e===void 0)return`file-${t}`;let n=basename(e).replace(UNSAFE_FILENAME_CHARS,`_`);return n.length>0?n:`file-${t}`}export{ATTACHMENTS_ROOT,hydrateSandboxAttachments,stageAttachmentsForAdapter,stageAttachmentsToSandbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.44.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.44.4`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { ChatSdkChannelEvents } from "#public/channels/chat-sdk/chatSdkChannel.js";
|
|
2
|
+
/** Built-in connection authorization handlers for Chat SDK threads. */
|
|
3
|
+
export declare function defaultAuthorizationEvents(): Pick<ChatSdkChannelEvents, "authorization.completed" | "authorization.required">;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{isNotImplemented}from"#public/channels/chat-sdk/notImplemented.js";function defaultAuthorizationEvents(){return{async"authorization.required"(e,t,n){if(!t.thread||e.candidateId!==void 0)return;let r=t.state.pendingAuthMessageIds??{};if(r[e.name]!==void 0)return;let i=authorizationDisplayName(e.name,e.authorization?.displayName),a=t.thread.isDM?authorizationPrompt({displayName:i,instructions:e.authorization?.instructions,url:e.authorization?.url,userCode:e.authorization?.userCode}):`Authorization required for ${i}. Continue in a direct message with this agent.`,o=await t.thread.post({markdown:a});o.id&&(t.state.pendingAuthMessageIds={...r,[e.name]:o.id})},async"authorization.completed"(t,n,r){if(!n.thread||t.candidateId!==void 0)return;let i=n.state.pendingAuthMessageIds??{},a=i[t.name];if(a===void 0)return;let o=authorizationCompleted({displayName:authorizationDisplayName(t.name,t.authorization?.displayName),outcome:t.outcome,reason:t.reason});try{await editMessage(n.thread,a,o)}catch(t){if(!isNotImplemented(t))throw t;n.state.editSupported=!1,await n.thread.post({markdown:o})}let s={...i};delete s[t.name],n.state.pendingAuthMessageIds=s,t.outcome===`authorized`&&await safeStartTyping(n.thread,`Connected. Resuming...`)}}}async function safeStartTyping(t,n){try{await t.startTyping(n)}catch(t){if(!isNotImplemented(t))throw t}}async function editMessage(e,t,n){await e.adapter.editMessage(e.id,t,{markdown:n})}function authorizationDisplayName(e,t){return t===void 0?e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1):t}function authorizationPrompt(e){return[`Authorization required for ${e.displayName}.`,e.instructions,e.userCode===void 0?void 0:`Code: ${e.userCode}`,e.url].filter(e=>e!==void 0&&e.length>0).join(`
|
|
2
|
+
|
|
3
|
+
`)}function authorizationCompleted(e){if(e.outcome===`authorized`)return`${e.displayName} connected.`;let t=e.reason===void 0?``:` (${e.reason})`,n=e.outcome===`timed-out`?`timed out`:e.outcome;return`${e.displayName} authorization ${n}${t}.`}export{defaultAuthorizationEvents};
|
|
@@ -23,6 +23,8 @@ export interface ChatSdkChannelState extends Record<string, unknown> {
|
|
|
23
23
|
lastEditAtMs?: number | null;
|
|
24
24
|
/** Buffered first line of a tool-call message, surfaced as typing status. */
|
|
25
25
|
pendingToolCallMessage?: string | null;
|
|
26
|
+
/** Authorization status messages, keyed by connection name. */
|
|
27
|
+
pendingAuthMessageIds?: Record<string, string>;
|
|
26
28
|
/** Step index the current stream anchor belongs to (resets per step). */
|
|
27
29
|
streamStepIndex?: number | null;
|
|
28
30
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{normalizeSendInput}from"#channel/send-input.js";import{INTERNAL_CHANNEL_DELIVER}from"#channel/channel-operations.js";import{GET,POST,defineChannel}from"#public/definitions/channel.js";import{ContextContainer,contextStorage}from"#context/container.js";import{ContextKey}from"#context/key.js";import{Actions,Button,Card,CardText,Chat,Message,ThreadImpl}from"#compiled/chat/index.js";import{
|
|
1
|
+
import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{normalizeSendInput}from"#channel/send-input.js";import{INTERNAL_CHANNEL_DELIVER}from"#channel/channel-operations.js";import{GET,POST,defineChannel}from"#public/definitions/channel.js";import{ContextContainer,contextStorage}from"#context/container.js";import{ContextKey}from"#context/key.js";import{isNotImplemented}from"#public/channels/chat-sdk/notImplemented.js";import{Actions,Button,Card,CardText,Chat,Message,ThreadImpl}from"#compiled/chat/index.js";import{defaultAuthorizationEvents}from"#public/channels/chat-sdk/authorization.js";import{chatSdkInstrumentationMetadata}from"#public/channels/chat-sdk/audience.js";const log=createLogger(`chat-sdk.channel`),ActiveWebhookKey=new ContextKey(`chat-sdk.active-webhook`);function chatSdkChannel(e){let t=new Chat(e),n=e.inputActionPrefix??`eve_input:`,r=e.streaming??!0,i=e.streamingEditIntervalMs??1e3,l={...defaultEvents(n),...e.events};return t.onAction(async r=>{let i=decodeInputAction(r.actionId,n,r.value);if(i){if(!r.thread)throw Error(`chatSdkChannel input actions require a thread on the Chat SDK action event.`);await bridgeSend(t,{inputResponses:[i]},{auth:e.resolveInputAuth?await e.resolveInputAuth(r):null,thread:r.thread})}}),{bot:t,channel:defineChannel({kindHint:`chat-sdk`,turnPolicy:e.turnPolicy,state:initialState(),metadata:chatSdkInstrumentationMetadata,context(e){return{bot:t,state:e,streaming:r,streamingEditIntervalMs:i,thread:threadFromState(t,e)}},routes:adapterNames(e.adapters).flatMap(n=>{let r=routeForAdapter(n,e),handler=async(r,i)=>{let a=t.webhooks[n],o=new ContextContainer;return o.setVirtualContext(ActiveWebhookKey,{from:i.from}),contextStorage.run(o,()=>a(r,{...e.webhook,waitUntil(e){i.waitUntil(e)}}))};return[GET(r,handler),POST(r,handler)]}),async receive(e,{from:n}){let r=serializeReceiveTarget(t,e.target);return n(r.id).send(e.message,{auth:e.auth,state:{thread:r}})},events:l}),send(e,n){return bridgeSend(t,e,n)}}}function defaultEvents(e){return{...defaultAuthorizationEvents(),async"turn.started"(e,t,n){t.state.pendingToolCallMessage=null,clearStream(t.state),await safeStartTyping(t.thread,`Working...`)},async"actions.requested"(e,t,n){let r=t.state.pendingToolCallMessage;if(t.state.pendingToolCallMessage=null,r){await safeStartTyping(t.thread,truncate(r));return}let i=e.actions.map(e=>e.kind===`tool-call`?e.toolName:e.kind);await safeStartTyping(t.thread,truncate(`Running ${i.join(`, `)}...`))},async"message.appended"(e,t,n){if(!t.thread||!e.messageSoFar||!canStream(t))return;let r=t.state.anchorMessageId;if(!r||t.state.streamStepIndex!==e.stepIndex){let n=await t.thread.post({markdown:e.messageSoFar});t.state.anchorMessageId=n.id,t.state.streamStepIndex=e.stepIndex,t.state.lastEditAtMs=Date.now();return}let i=t.state.lastEditAtMs??0;if(!(Date.now()-i<t.streamingEditIntervalMs))try{await editMessage(t.thread,r,e.messageSoFar),t.state.lastEditAtMs=Date.now()}catch(e){if(!isNotImplemented(e))throw e;t.state.editSupported=!1,clearStream(t.state)}},async"input.requested"(t,n,r){!n.thread||t.requests.length===0||await n.thread.post(renderInputRequests(t.requests,e))},async"message.completed"(e,t,n){if(e.finishReason===`tool-calls`){t.state.pendingToolCallMessage=e.message?firstNonEmptyLine(e.message)??null:null,e.message?await finalizeStreamedMessage(t,e.message,!1):clearStream(t.state);return}if(t.state.pendingToolCallMessage=null,!e.message){clearStream(t.state);return}await finalizeStreamedMessage(t,e.message,!0)},async"turn.failed"(e,t,n){await postFailure(t.thread,`I hit an error while handling your request`,e)},async"session.failed"(e,t){await postFailure(t.thread,`This session could not recover from an error`,e)}}}async function safeStartTyping(e,t){if(e)try{await e.startTyping(t)}catch(e){if(!isNotImplemented(e))throw e}}async function editMessage(e,t,n){await e.adapter.editMessage(e.id,t,{markdown:n})}async function finalizeStreamedMessage(e,t,n){let r=e.thread;if(!r){clearStream(e.state);return}let i=e.state.anchorMessageId;if(canStream(e)&&i)try{await editMessage(r,i,t)}catch(i){if(!isNotImplemented(i))throw i;e.state.editSupported=!1,n&&await r.post({markdown:t})}else n&&await r.post({markdown:t});clearStream(e.state)}function canStream(e){return e.streaming&&e.state.editSupported!==!1}function clearStream(e){e.anchorMessageId=null,e.lastEditAtMs=null,e.streamStepIndex=null}function firstNonEmptyLine(e){for(let t of e.split(/\r?\n/u)){let e=t.trim();if(e.length>0)return e}}function truncate(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function renderInputRequests(e,t){return Card({children:e.flatMap(e=>renderInputRequest(e,t))})}function renderInputRequest(e,t){let n=[CardText(e.prompt)];return e.options&&e.options.length>0?(n.push(Actions(e.options.map(n=>Button({id:encodeInputAction(t,e.requestId,n.id),label:n.label,style:n.style,value:n.id})))),n):(n.push(CardText(`This request needs a freeform answer. Continue from the eve session UI.`)),n)}async function postFailure(e,r,i){if(!e)return;let a=formatErrorHint(i),o=extractErrorId(i.details);await e.post([`${r}${a}.`,`Please try again, rephrase, or reach out if it keeps failing.`,...o?[`Error id: ${o}`]:[]].join(`
|
|
2
2
|
|
|
3
|
-
`))}async function bridgeSend(e,t,n){let a=contextStorage.getStore()?.get(ActiveWebhookKey);if(!a)throw Error(`chatSdkChannel().send can only run during a Chat SDK webhook handler for this bridge.`);let o=serializeThread(e,n.thread,n.adapterName),s=normalizeSendInput(t),c={auth:n.auth??null,state:{thread:o}};return n.callback!==void 0&&(c.callback=n.callback),n.mode!==void 0&&(c.mode=n.mode),n.title!==void 0&&(c.title=n.title),n.turnPolicy!==void 0&&(c.turnPolicy=n.turnPolicy),a.from(o.id)[INTERNAL_CHANNEL_DELIVER](s,c)}function initialState(){return{thread:null}}function threadFromState(e,t){if(!t.thread)return null;try{let n=t.thread;return new ThreadImpl({adapter:e.getAdapter(n.adapterName),channelId:n.channelId,channelVisibility:n.channelVisibility,currentMessage:n.currentMessage?Message.fromJSON(n.currentMessage):void 0,id:n.id,isDM:n.isDM,stateAdapter:e.getState()})}catch(e){return log.warn(`failed to rebuild Chat SDK thread from channel state`,{error:e}),null}}function serializeReceiveTarget(e,t){if(t.thread)return t.thread;if(!t.threadId)throw Error(`chatSdkChannel().receive requires target.thread or target.threadId.`);return serializeThread(e,t.threadId,t.adapterName)}function serializeThread(e,t,n){if(typeof t==`string`){let r=n??inferAdapterName(t),i=e.getAdapter(r);return{_type:`chat:Thread`,adapterName:r,channelId:i.channelIdFromThreadId(t),channelVisibility:i.getChannelVisibility?.(t),id:t,isDM:!1}}return isSerializedThread(t)?t:t.toJSON()}function isSerializedThread(e){return`_type`in e&&e._type===`chat:Thread`}function inferAdapterName(e){let t=e.indexOf(`:`);if(t<=0)throw Error(`chatSdkChannel string thread references require options.adapterName.`);return e.slice(0,t)}function adapterNames(e){return Object.keys(e)}function routeForAdapter(e,t){return t.routes?.[e]||`${(t.route??`/eve/v1`).replace(/\/$/u,``)}/${e}`}function encodeInputAction(e,t,n){return`${e}${encodeURIComponent(t)}:${encodeURIComponent(n)}`}function decodeInputAction(e,t,n){if(!e.startsWith(t))return null;let r=e.slice(t.length),i=r.indexOf(`:`);if(i<=0)return null;try{let e=decodeURIComponent(r.slice(0,i));return{optionId:n??decodeURIComponent(r.slice(i+1)),requestId:e}}catch{return null}}export{chatSdkChannel};
|
|
3
|
+
`))}async function bridgeSend(e,t,n){let a=contextStorage.getStore()?.get(ActiveWebhookKey);if(!a)throw Error(`chatSdkChannel().send can only run during a Chat SDK webhook handler for this bridge.`);let o=serializeThread(e,n.thread,n.adapterName),s=normalizeSendInput(t),c={auth:n.auth??null,state:{thread:o}};return n.callback!==void 0&&(c.callback=n.callback),n.mode!==void 0&&(c.mode=n.mode),n.title!==void 0&&(c.title=n.title),n.turnPolicy!==void 0&&(c.turnPolicy=n.turnPolicy),a.from(o.id)[INTERNAL_CHANNEL_DELIVER](s,c)}function initialState(){return{pendingAuthMessageIds:{},thread:null}}function threadFromState(e,t){if(!t.thread)return null;try{let n=t.thread;return new ThreadImpl({adapter:e.getAdapter(n.adapterName),channelId:n.channelId,channelVisibility:n.channelVisibility,currentMessage:n.currentMessage?Message.fromJSON(n.currentMessage):void 0,id:n.id,isDM:n.isDM,stateAdapter:e.getState()})}catch(e){return log.warn(`failed to rebuild Chat SDK thread from channel state`,{error:e}),null}}function serializeReceiveTarget(e,t){if(t.thread)return t.thread;if(!t.threadId)throw Error(`chatSdkChannel().receive requires target.thread or target.threadId.`);return serializeThread(e,t.threadId,t.adapterName)}function serializeThread(e,t,n){if(typeof t==`string`){let r=n??inferAdapterName(t),i=e.getAdapter(r);return{_type:`chat:Thread`,adapterName:r,channelId:i.channelIdFromThreadId(t),channelVisibility:i.getChannelVisibility?.(t),id:t,isDM:!1}}return isSerializedThread(t)?t:t.toJSON()}function isSerializedThread(e){return`_type`in e&&e._type===`chat:Thread`}function inferAdapterName(e){let t=e.indexOf(`:`);if(t<=0)throw Error(`chatSdkChannel string thread references require options.adapterName.`);return e.slice(0,t)}function adapterNames(e){return Object.keys(e)}function routeForAdapter(e,t){return t.routes?.[e]||`${(t.route??`/eve/v1`).replace(/\/$/u,``)}/${e}`}function encodeInputAction(e,t,n){return`${e}${encodeURIComponent(t)}:${encodeURIComponent(n)}`}function decodeInputAction(e,t,n){if(!e.startsWith(t))return null;let r=e.slice(t.length),i=r.indexOf(`:`);if(i<=0)return null;try{let e=decodeURIComponent(r.slice(0,i));return{optionId:n??decodeURIComponent(r.slice(i+1)),requestId:e}}catch{return null}}export{chatSdkChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { linqChannel, type LinqChannel, type LinqChannelConfig, type LinqChannelCredentials, type LinqCredentialValue, type LinqInboundMessageContext, type LinqInboundResult, type LinqInboundResultOrPromise, } from "#public/channels/linq/linqChannel.js";
|
|
1
|
+
export { defaultLinqAuth, linqChannel, type LinqChannel, type LinqChannelConfig, type LinqChannelCredentials, type LinqCredentialValue, type LinqInboundMessageContext, type LinqInboundResult, type LinqInboundResultOrPromise, } from "#public/channels/linq/linqChannel.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{linqChannel}from"#public/channels/linq/linqChannel.js";export{linqChannel};
|
|
1
|
+
import{defaultLinqAuth,linqChannel}from"#public/channels/linq/linqChannel.js";export{defaultLinqAuth,linqChannel};
|
|
@@ -38,7 +38,7 @@ export interface LinqChannelConfig {
|
|
|
38
38
|
readonly events?: ChatSdkChannelEvents<{
|
|
39
39
|
linq: ReturnType<typeof createLinqAdapter>;
|
|
40
40
|
}>;
|
|
41
|
-
/** Inbound message policy. Defaults to dispatching
|
|
41
|
+
/** Inbound message policy. Defaults to dispatching with the Linq message author's user auth. */
|
|
42
42
|
readonly onMessage?: (ctx: LinqInboundMessageContext, message: Message) => LinqInboundResultOrPromise;
|
|
43
43
|
/** Override the default webhook route (`/eve/v1/linq`). */
|
|
44
44
|
readonly route?: string;
|
|
@@ -64,3 +64,5 @@ export interface LinqChannel extends Channel<ChatSdkChannelState, ChatSdkReceive
|
|
|
64
64
|
* ```
|
|
65
65
|
*/
|
|
66
66
|
export declare function linqChannel(config: LinqChannelConfig): LinqChannel;
|
|
67
|
+
/** Default Linq auth projection for inbound Chat SDK message authors. */
|
|
68
|
+
export declare function defaultLinqAuth(message: Message): SessionAuthContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{vercelOidc}from"#public/channels/auth.js";import{chatSdkChannel}from"#public/channels/chat-sdk/index.js";import{createMemoryState}from"#compiled/@chat-adapter/state-memory/index.js";import{createLinqAdapter}from"#compiled/@linqapp/chat-sdk-adapter/index.js";import{linqInboundContent}from"#public/channels/linq/inboundContent.js";function linqChannel(e){let i=normalizeCredentials(e.credentials);e.baseURL!==void 0&&(i.baseURL=e.baseURL);let a=chatSdkChannel({adapters:{linq:createLinqAdapter(i)},concurrency:`concurrent`,events:e.events,routes:{linq:e.route??`/eve/v1/linq`},state:createMemoryState(),streaming:!1,turnPolicy:e.turnPolicy,userName:e.userName??`eve`}),o=e.onMessage??defaultOnMessage;return a.bot.onDirectMessage(async(e,t)=>{await dispatchMessage(a,o,e,t)}),a.bot.onNewMessage(/[\s\S]*/,async(e,t)=>{await dispatchMessage(a,o,e,t)}),a.channel}function normalizeCredentials(t){let{apiKey:n,signingSecret:r,webhookVerifier:i}=t??{},a={};return n!==void 0&&(a.credentials=createCredentialProvider(n,r)),i===void 0?r===void 0&&(a.webhookVerifier=vercelOidc()):a.webhookVerifier=i,a}function createCredentialProvider(e,t){return async()=>{let n={apiKey:await resolveCredentialValue(e)};return t!==void 0&&(n.signingSecret=await resolveCredentialValue(t)),n}}async function resolveCredentialValue(e){return typeof e==`function`?await e():e}async function defaultOnMessage(){return{auth:
|
|
1
|
+
import{vercelOidc}from"#public/channels/auth.js";import{chatSdkChannel}from"#public/channels/chat-sdk/index.js";import{createMemoryState}from"#compiled/@chat-adapter/state-memory/index.js";import{createLinqAdapter}from"#compiled/@linqapp/chat-sdk-adapter/index.js";import{linqInboundContent}from"#public/channels/linq/inboundContent.js";function linqChannel(e){let i=normalizeCredentials(e.credentials);e.baseURL!==void 0&&(i.baseURL=e.baseURL);let a=chatSdkChannel({adapters:{linq:createLinqAdapter(i)},concurrency:`concurrent`,events:e.events,routes:{linq:e.route??`/eve/v1/linq`},state:createMemoryState(),streaming:!1,turnPolicy:e.turnPolicy,userName:e.userName??`eve`}),o=e.onMessage??defaultOnMessage;return a.bot.onDirectMessage(async(e,t)=>{await dispatchMessage(a,o,e,t)}),a.bot.onNewMessage(/[\s\S]*/,async(e,t)=>{await dispatchMessage(a,o,e,t)}),a.channel}function normalizeCredentials(t){let{apiKey:n,signingSecret:r,webhookVerifier:i}=t??{},a={};return n!==void 0&&(a.credentials=createCredentialProvider(n,r)),i===void 0?r===void 0&&(a.webhookVerifier=vercelOidc()):a.webhookVerifier=i,a}function createCredentialProvider(e,t){return async()=>{let n={apiKey:await resolveCredentialValue(e)};return t!==void 0&&(n.signingSecret=await resolveCredentialValue(t)),n}}async function resolveCredentialValue(e){return typeof e==`function`?await e():e}function defaultLinqAuth(e){let t={};return e.author.userName!==void 0&&(t.user_name=e.author.userName),{attributes:t,authenticator:`linq-message`,issuer:`linq`,principalId:`linq:${e.author.userId}`,principalType:e.author.isBot?`service`:`user`,subject:e.author.userId}}async function defaultOnMessage(e,t){return{auth:defaultLinqAuth(t)}}async function dispatchMessage(e,t,n,r){let a=await t({thread:n},r);if(a===null)return;await markReadBestEffort(e.bot.getAdapter(`linq`),n,r);let o=linqInboundContent(r);o!==void 0&&await e.send({context:[...a.context??[]],message:o},{auth:a.auth,thread:n,title:a.title})}async function markReadBestEffort(e,t,n){try{await e.markRead(t.id,n.id)}catch{}}export{defaultLinqAuth,linqChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { photonIMessageChannel, type PhotonIMessageChannel, type PhotonIMessageChannelConfig, type PhotonIMessageChannelCredentials, type PhotonInboundMessageContext, type PhotonInboundResult, type PhotonInboundResultOrPromise, } from "#public/channels/photon/photonIMessageChannel.js";
|
|
1
|
+
export { defaultPhotonAuth, photonIMessageChannel, type PhotonIMessageChannel, type PhotonIMessageChannelConfig, type PhotonIMessageChannelCredentials, type PhotonInboundMessageContext, type PhotonInboundResult, type PhotonInboundResultOrPromise, } from "#public/channels/photon/photonIMessageChannel.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{photonIMessageChannel}from"#public/channels/photon/photonIMessageChannel.js";export{photonIMessageChannel};
|
|
1
|
+
import{defaultPhotonAuth,photonIMessageChannel}from"#public/channels/photon/photonIMessageChannel.js";export{defaultPhotonAuth,photonIMessageChannel};
|
|
@@ -26,7 +26,7 @@ export interface PhotonIMessageChannelConfig {
|
|
|
26
26
|
readonly events?: ChatSdkChannelEvents<{
|
|
27
27
|
imessage: iMessageAdapter;
|
|
28
28
|
}>;
|
|
29
|
-
/** Inbound message policy. Defaults to dispatching
|
|
29
|
+
/** Inbound message policy. Defaults to dispatching with the Photon message author's user auth. */
|
|
30
30
|
readonly onMessage?: (ctx: PhotonInboundMessageContext, message: Message) => PhotonInboundResultOrPromise;
|
|
31
31
|
/** Override the default webhook route (`/eve/v1/photon`). */
|
|
32
32
|
readonly route?: string;
|
|
@@ -56,3 +56,5 @@ export interface PhotonIMessageChannel extends ChatSdkChannel {
|
|
|
56
56
|
* ```
|
|
57
57
|
*/
|
|
58
58
|
export declare function photonIMessageChannel(config: PhotonIMessageChannelConfig): PhotonIMessageChannel;
|
|
59
|
+
/** Default Photon auth projection for inbound Chat SDK message authors. */
|
|
60
|
+
export declare function defaultPhotonAuth(message: Message): SessionAuthContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{vercelOidc}from"#public/channels/auth.js";import{chatSdkChannel}from"#public/channels/chat-sdk/index.js";import{createMemoryState}from"#compiled/@chat-adapter/state-memory/index.js";import{createiMessageAdapter}from"#compiled/@photon-ai/chat-adapter-imessage/index.js";import{photonInboundContent}from"#public/channels/photon/inboundContent.js";function photonIMessageChannel(i){let a=i.webhookSecret??process.env.IMESSAGE_WEBHOOK_SECRET,o=chatSdkChannel({adapters:{imessage:createiMessageAdapter({credentials:i.credentials,...i.webhookVerifier?{webhookVerifier:i.webhookVerifier}:a?{webhookSecret:a}:{webhookVerifier:vercelOidc()}})},concurrency:`concurrent`,events:i.events,routes:{imessage:i.route??`/eve/v1/photon`},state:createMemoryState(),streaming:!1,turnPolicy:i.turnPolicy,userName:i.userName??`eve`}),s=i.onMessage??defaultOnMessage;return o.bot.onDirectMessage(async(e,t)=>{await dispatchMessage(o,s,e,t)}),o.bot.onNewMessage(/[\s\S]*/,async(e,t)=>{await dispatchMessage(o,s,e,t)}),o.channel}async function defaultOnMessage(){return{auth:
|
|
1
|
+
import{vercelOidc}from"#public/channels/auth.js";import{chatSdkChannel}from"#public/channels/chat-sdk/index.js";import{createMemoryState}from"#compiled/@chat-adapter/state-memory/index.js";import{createiMessageAdapter}from"#compiled/@photon-ai/chat-adapter-imessage/index.js";import{photonInboundContent}from"#public/channels/photon/inboundContent.js";function photonIMessageChannel(i){let a=i.webhookSecret??process.env.IMESSAGE_WEBHOOK_SECRET,o=chatSdkChannel({adapters:{imessage:createiMessageAdapter({credentials:i.credentials,...i.webhookVerifier?{webhookVerifier:i.webhookVerifier}:a?{webhookSecret:a}:{webhookVerifier:vercelOidc()}})},concurrency:`concurrent`,events:i.events,routes:{imessage:i.route??`/eve/v1/photon`},state:createMemoryState(),streaming:!1,turnPolicy:i.turnPolicy,userName:i.userName??`eve`}),s=i.onMessage??defaultOnMessage;return o.bot.onDirectMessage(async(e,t)=>{await dispatchMessage(o,s,e,t)}),o.bot.onNewMessage(/[\s\S]*/,async(e,t)=>{await dispatchMessage(o,s,e,t)}),o.channel}function defaultPhotonAuth(e){let t={};return e.author.userName!==void 0&&(t.user_name=e.author.userName),{attributes:t,authenticator:`photon-imessage`,issuer:`photon`,principalId:`photon:${e.author.userId}`,principalType:e.author.isBot?`service`:`user`,subject:e.author.userId}}async function defaultOnMessage(e,t){return{auth:defaultPhotonAuth(t)}}async function dispatchMessage(e,t,n,r){let a=await t({thread:n},r);if(a===null)return;await markReadBestEffort(e.bot.getAdapter(`imessage`),n,r);let o=photonInboundContent(r);o!==void 0&&await e.send({context:[...a.context??[]],message:o},{auth:a.auth,thread:n,title:a.title})}async function markReadBestEffort(e,t,n){try{await e.markRead(t.id,n.id)}catch{}}export{defaultPhotonAuth,photonIMessageChannel};
|