eve 0.31.0 → 0.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/src/channel/cross-channel-receive.d.ts +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +2 -2
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/context/container.d.ts +3 -0
- package/dist/src/context/container.js +1 -1
- package/dist/src/discover/filesystem.js +1 -1
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/session-command-inbox.d.ts +11 -3
- package/dist/src/execution/session-command-wire.d.ts +24 -0
- package/dist/src/execution/session-command-wire.js +1 -0
- package/dist/src/execution/turn-control-receiver.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/authorization.d.ts +8 -0
- package/dist/src/harness/authorization.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/public/definitions/tool.d.ts +18 -14
- package/dist/src/runtime/connections/scoped-authorization.js +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/docs/guides/meta.json +2 -1
- package/docs/guides/remote-agents.md +6 -4
- package/docs/guides/ucp.mdx +181 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.31.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 2a141f0: Keep sessions resumable across eve deployment upgrades: sends now cross durable session hooks as the established `deliver` envelope (with a transitional single-payload mirror for sessions pinned to 0.30.3–0.30.8), and consumers keep accepting payloads persisted by those versions.
|
|
8
|
+
- 99982f7: Treat AI SDK `.devtools` like other generated directories: ignore it in `eve dev` watching, agent discovery, and source snapshots so generation writes do not recompile or warn.
|
|
9
|
+
- a497e8d: Preserve each tool executor's concrete return type through `defineTool`, so non-streaming tools no longer appear to return an async iterable. Allow `ctx.to()` to infer closed receive-target interfaces such as Slack's without requiring an index signature.
|
|
10
|
+
- fe9e7ef: Consume interactive authorization callback results once and keep targeted connection searches from replaying callbacks for unrelated connections.
|
|
11
|
+
|
|
3
12
|
## 0.31.0
|
|
4
13
|
|
|
5
14
|
### Minor Changes
|
|
@@ -16,7 +16,7 @@ export interface CrossChannelTargetHandle {
|
|
|
16
16
|
send(message: string | UserContent, options: CrossChannelSendOptions): Promise<Session>;
|
|
17
17
|
}
|
|
18
18
|
/** Selects another authored channel and one of its proactive targets. */
|
|
19
|
-
export type CrossChannelToFn = <TChannel extends ChannelReference
|
|
19
|
+
export type CrossChannelToFn = <TChannel extends ChannelReference<unknown>>(channel: TChannel, target: InferReceiveTarget<TChannel>) => CrossChannelTargetHandle;
|
|
20
20
|
/**
|
|
21
21
|
* Channel record consumed by the receiver — keeps the public-facing
|
|
22
22
|
* `definition` reference so callers can identify a target by value
|
|
@@ -11,8 +11,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
11
11
|
readonly dropped: {};
|
|
12
12
|
};
|
|
13
13
|
readonly tool: {
|
|
14
|
-
readonly current:
|
|
15
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7];
|
|
14
|
+
readonly current: 8;
|
|
15
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8];
|
|
16
16
|
readonly dropped: {};
|
|
17
17
|
};
|
|
18
18
|
readonly dynamicTool: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:
|
|
1
|
+
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:8,supported:[1,2,3,4,5,6,7,8],dropped:{}},dynamicTool:{current:10,supported:[1,2,3,4,5,6,7,8,9,10],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:8,supported:[1,2,3,4,5,6,7,8],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:7,supported:[1,2,3,4,5,6,7],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:2,supported:[1,2],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(t){return parseExtensionCompatibilityManifest(await readFile(t,`utf8`),t)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
|
|
@@ -11,6 +11,8 @@ import { type ContextAccessor, type ContextKey } from "#context/key.js";
|
|
|
11
11
|
* the serialization layer.
|
|
12
12
|
*/
|
|
13
13
|
export interface AlsContext extends ContextAccessor {
|
|
14
|
+
/** Removes a durable or step-local value from the context. */
|
|
15
|
+
delete<T>(key: ContextKey<T>): boolean;
|
|
14
16
|
/**
|
|
15
17
|
* Iterates all durable key/value pairs currently stored in the context.
|
|
16
18
|
* Used by the serialization layer to persist context at step boundaries.
|
|
@@ -30,6 +32,7 @@ export declare class ContextContainer implements AlsContext {
|
|
|
30
32
|
has<T>(key: ContextKey<T>): boolean;
|
|
31
33
|
set<T>(key: ContextKey<T>, valueOrUpdater: T | ((current: T | undefined) => T)): T;
|
|
32
34
|
ensure<T>(key: ContextKey<T>, create: () => T): T;
|
|
35
|
+
delete<T>(key: ContextKey<T>): boolean;
|
|
33
36
|
/**
|
|
34
37
|
* Clears all step-local provider values from the context.
|
|
35
38
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage}from"node:async_hooks";import{resolveKey}from"#context/key.js";const EVE_CONTEXT_STORAGE_KEY=Symbol.for(`eve.context-storage`);var ContextContainer=class{_durableValues=new Map;_virtualValues=new Map;get(e){return this._virtualValues.has(e.name)?this._virtualValues.get(e.name):this._durableValues.get(e.name)}require(e){if(!this.has(e))throw Error(`Context key "${e.name}" is not set.`);return this.get(e)}has(e){return this._virtualValues.has(e.name)||this._durableValues.has(e.name)}set(e,t){let n=typeof t==`function`?t(this.get(e)):t;return this._durableValues.set(e.name,n),n}ensure(e,t){return this.has(e)?this.require(e):this.set(e,t())}clearVirtualContext(){this._virtualValues.clear()}setVirtualContext(e,t){this._virtualValues.set(e.name,t)}*entries(){for(let[e,n]of this._durableValues){let r=resolveKey(e);r!==void 0&&(yield[r,n])}}};const globalContextStorage=globalThis;globalContextStorage[EVE_CONTEXT_STORAGE_KEY]===void 0&&(globalContextStorage[EVE_CONTEXT_STORAGE_KEY]=new AsyncLocalStorage);const contextStorage=globalContextStorage[EVE_CONTEXT_STORAGE_KEY];function loadContext(){let e=contextStorage.getStore();if(e===void 0)throw Error(`No active eve context. Call this function only from authored runtime code such as tools, steps, and model callbacks.`);return e}export{ContextContainer,contextStorage,loadContext};
|
|
1
|
+
import{AsyncLocalStorage}from"node:async_hooks";import{resolveKey}from"#context/key.js";const EVE_CONTEXT_STORAGE_KEY=Symbol.for(`eve.context-storage`);var ContextContainer=class{_durableValues=new Map;_virtualValues=new Map;get(e){return this._virtualValues.has(e.name)?this._virtualValues.get(e.name):this._durableValues.get(e.name)}require(e){if(!this.has(e))throw Error(`Context key "${e.name}" is not set.`);return this.get(e)}has(e){return this._virtualValues.has(e.name)||this._durableValues.has(e.name)}set(e,t){let n=typeof t==`function`?t(this.get(e)):t;return this._durableValues.set(e.name,n),n}ensure(e,t){return this.has(e)?this.require(e):this.set(e,t())}delete(e){let t=this._durableValues.delete(e.name),n=this._virtualValues.delete(e.name);return t||n}clearVirtualContext(){this._virtualValues.clear()}setVirtualContext(e,t){this._virtualValues.set(e.name,t)}*entries(){for(let[e,n]of this._durableValues){let r=resolveKey(e);r!==void 0&&(yield[r,n])}}};const globalContextStorage=globalThis;globalContextStorage[EVE_CONTEXT_STORAGE_KEY]===void 0&&(globalContextStorage[EVE_CONTEXT_STORAGE_KEY]=new AsyncLocalStorage);const contextStorage=globalContextStorage[EVE_CONTEXT_STORAGE_KEY];function loadContext(){let e=contextStorage.getStore();if(e===void 0)throw Error(`No active eve context. Call this function only from authored runtime code such as tools, steps, and model callbacks.`);return e}export{ContextContainer,contextStorage,loadContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sep}from"node:path";const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],PROJECT_MARKER_FILE_NAMES=[`package.json`,`vercel.json`],PROJECT_MARKER_FILE_NAME_SET=new Set(PROJECT_MARKER_FILE_NAMES),GENERATED_AGENT_DIRECTORY_NAMES=new Set([`.eve`,`.next`,`.output`,`.vercel`,`node_modules`]);function getDirectoryEntryType(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function isProjectMarkerEntry(e,t){return t===`file`&&PROJECT_MARKER_FILE_NAME_SET.has(e)}function classifyAgentRootEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function classifyLocalSubagentEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function classifySkillPackageEntry(e,t){if(t===`file`)return e.toLowerCase()===`skill.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function classifySkillsDirectoryEntry(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(isTypeScriptDeclarationFileName(e))return`ignored-declaration`;if(e.toLowerCase().endsWith(`.md`))return`flat-skill-markdown`;if(getSupportedModuleBaseName(e)!==null)return`flat-skill-module`}return`unknown`}function normalizeLogicalPath(t){return t.replaceAll(sep,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function getSupportedModuleBaseName(e){if(isTypeScriptDeclarationFileName(e))return null;for(let n of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(e.endsWith(n)&&e.length>n.length)return e.slice(0,-n.length);return null}function isTypeScriptDeclarationFileName(e){return/\.d\.(?:cts|mts|ts)$/.test(e)}function matchesSupportedModuleBaseName(e,t){return getSupportedModuleBaseName(e)===t}function stripLogicalPathExtension(e){let t=normalizeLogicalPath(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}export{PROJECT_MARKER_FILE_NAMES,SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,classifyLocalSubagentEntry,classifySkillPackageEntry,classifySkillsDirectoryEntry,getDirectoryEntryType,getSupportedModuleBaseName,isProjectMarkerEntry,isTypeScriptDeclarationFileName,matchesSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension};
|
|
1
|
+
import{sep}from"node:path";const SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS=[`.cts`,`.mts`,`.cjs`,`.mjs`,`.ts`,`.js`],PROJECT_MARKER_FILE_NAMES=[`package.json`,`vercel.json`],PROJECT_MARKER_FILE_NAME_SET=new Set(PROJECT_MARKER_FILE_NAMES),GENERATED_AGENT_DIRECTORY_NAMES=new Set([`.devtools`,`.eve`,`.next`,`.output`,`.vercel`,`node_modules`]);function getDirectoryEntryType(e){return e.isDirectory()?`directory`:e.isFile()?`file`:`other`}function isProjectMarkerEntry(e,t){return t===`file`&&PROJECT_MARKER_FILE_NAME_SET.has(e)}function classifyAgentRootEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`channels`)return`channels-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`skills`)return`skills-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`tools`)return`tools-directory`;if(e===`schedules`)return`schedules-directory`;if(e===`subagents`)return`subagents-directory`}return`unknown`}function classifyLocalSubagentEntry(e,t){if(t===`file`)return matchesSupportedModuleBaseName(e,`agent`)?`agent-config-module`:e.toLowerCase()===`instructions.md`?`instructions-markdown`:matchesSupportedModuleBaseName(e,`instructions`)?`instructions-module`:e.toLowerCase()===`system.md`?`system-markdown`:matchesSupportedModuleBaseName(e,`system`)?`system-module`:`unknown`;if(t===`directory`){if(GENERATED_AGENT_DIRECTORY_NAMES.has(e))return`ignored-directory`;if(e===`connections`)return`connections-directory`;if(e===`extensions`)return`extensions-directory`;if(e===`hooks`)return`hooks-directory`;if(e===`instructions`)return`instructions-directory`;if(e===`lib`)return`lib-directory`;if(e===`sandbox`)return`sandbox-directory`;if(e===`skills`)return`skills-directory`;if(e===`tools`)return`tools-directory`;if(e===`subagents`)return`subagents-directory`;if(e===`schedules`)return`invalid-schedules-directory`}return`unknown`}function classifySkillPackageEntry(e,t){if(t===`file`)return e.toLowerCase()===`skill.md`?`skill-markdown`:`skill-resource`;if(t===`directory`){if(e===`scripts`)return`skill-scripts-directory`;if(e===`references`)return`skill-references-directory`;if(e===`assets`)return`skill-assets-directory`}return`skill-resource`}function classifySkillsDirectoryEntry(e,t){if(t===`directory`)return`skill-package-directory`;if(t===`file`){if(isTypeScriptDeclarationFileName(e))return`ignored-declaration`;if(e.toLowerCase().endsWith(`.md`))return`flat-skill-markdown`;if(getSupportedModuleBaseName(e)!==null)return`flat-skill-module`}return`unknown`}function normalizeLogicalPath(t){return t.replaceAll(sep,`/`).replace(/^\.\//,``).replace(/^\/+/,``)}function getSupportedModuleBaseName(e){if(isTypeScriptDeclarationFileName(e))return null;for(let n of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(e.endsWith(n)&&e.length>n.length)return e.slice(0,-n.length);return null}function isTypeScriptDeclarationFileName(e){return/\.d\.(?:cts|mts|ts)$/.test(e)}function matchesSupportedModuleBaseName(e,t){return getSupportedModuleBaseName(e)===t}function stripLogicalPathExtension(e){let t=normalizeLogicalPath(e),n=t.lastIndexOf(`/`),r=t.lastIndexOf(`.`);return r===-1||r<n?t:t.slice(0,r)}export{PROJECT_MARKER_FILE_NAMES,SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,classifyLocalSubagentEntry,classifySkillPackageEntry,classifySkillsDirectoryEntry,getDirectoryEntryType,getSupportedModuleBaseName,isProjectMarkerEntry,isTypeScriptDeclarationFileName,matchesSupportedModuleBaseName,normalizeLogicalPath,stripLogicalPathExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{coalesceDeliveries}from"#harness/messages.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";async function nextTurnDelivery(e){for(;;){let n=await waitForNextSessionAction({bufferedDeliveries:e.bufferedDeliveries,bufferedSessionControls:e.bufferedSessionControls,commandInbox:e.commandInbox});if(n.kind!==`delivery`)return{kind:n.kind};let r=n.delivery;if(r===null)return{kind:`closed`};let i=await routeDeliverToChildren({auth:r.auth,parentWritable:e.driverWritable,payloads:r.payloads,sessionState:e.sessionState});if(i.kind===`cancel-turn`)return{kind:`cancel-turn`};if(i.remainder!==void 0)return{deliver:r,kind:`turn`,remainder:i.remainder}}}async function waitForNextSessionAction(e){let t=e.bufferedSessionControls.shift();if(t!==void 0)return{kind:t};if(e.bufferedDeliveries.length>0)return{delivery:takeBufferedTurnDelivery(e.bufferedDeliveries),kind:`delivery`};for(;;){let t=await e.commandInbox.next();if(e.commandInbox.consumeNext(),t.done)return{delivery:null,kind:`delivery`};if(t.value.kind===`session-timeout`)return{kind:`expired`};if(t.value.kind===`clear`||t.value.kind===`compact`||t.value.kind===`reset`)return{kind:t.value.kind};if(t.value.kind!==`cancel`)return{delivery:
|
|
1
|
+
import{coalesceDeliveries}from"#harness/messages.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";async function nextTurnDelivery(e){for(;;){let n=await waitForNextSessionAction({bufferedDeliveries:e.bufferedDeliveries,bufferedSessionControls:e.bufferedSessionControls,commandInbox:e.commandInbox});if(n.kind!==`delivery`)return{kind:n.kind};let r=n.delivery;if(r===null)return{kind:`closed`};let i=await routeDeliverToChildren({auth:r.auth,parentWritable:e.driverWritable,payloads:r.payloads,sessionState:e.sessionState});if(i.kind===`cancel-turn`)return{kind:`cancel-turn`};if(i.remainder!==void 0)return{deliver:r,kind:`turn`,remainder:i.remainder}}}async function waitForNextSessionAction(e){let t=e.bufferedSessionControls.shift();if(t!==void 0)return{kind:t};if(e.bufferedDeliveries.length>0)return{delivery:takeBufferedTurnDelivery(e.bufferedDeliveries),kind:`delivery`};for(;;){let t=await e.commandInbox.next();if(e.commandInbox.consumeNext(),t.done)return{delivery:null,kind:`delivery`};if(t.value.kind===`session-timeout`)return{kind:`expired`};if(t.value.kind===`clear`||t.value.kind===`compact`||t.value.kind===`reset`)return{kind:t.value.kind};if(t.value.kind!==`cancel`)return t.value.kind===`deliver`?{delivery:t.value,kind:`delivery`}:{delivery:sendCommandToDelivery(t.value),kind:`delivery`}}}function takeBufferedTurnDelivery(t){let n=t.shift();if(n===void 0)throw Error(`Cannot take a turn delivery from an empty buffer.`);let r=[n],i=n.caller;for(;t.length>0;){let e=t[0];if(e===void 0||i!==void 0&&e.caller!==void 0)break;let n=t.shift();if(n===void 0)throw Error(`Buffered turn delivery disappeared while partitioning.`);r.push(n),i??=n.caller}return coalesceDeliveries(r)}export{nextTurnDelivery};
|
|
@@ -1,6 +1,14 @@
|
|
|
1
|
-
import type { SessionCommand, SessionTimeoutHookPayload } from "#channel/types.js";
|
|
2
|
-
/**
|
|
3
|
-
|
|
1
|
+
import type { DeliverHookPayload, SessionCommand, SessionTimeoutHookPayload } from "#channel/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Payloads accepted by a session driver's stable and channel aliases.
|
|
4
|
+
*
|
|
5
|
+
* `DeliverHookPayload` is the only delivery format producers persist. The
|
|
6
|
+
* `send` member of `SessionCommand` stays accepted solely for payloads
|
|
7
|
+
* persisted by eve 0.30.3–0.30.8, which wrote the command shape directly;
|
|
8
|
+
* sessions are bounded by the 30-day default timeout, so the decode can be
|
|
9
|
+
* dropped once runs created on those versions have aged out.
|
|
10
|
+
*/
|
|
11
|
+
export type SessionInboxPayload = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;
|
|
4
12
|
/** Multiplexes one stable session hook and one rekeyable channel alias. */
|
|
5
13
|
export interface SessionCommandInbox {
|
|
6
14
|
claimStable(token: string): Promise<void>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { DeliverHookPayload, DeliverPayload, SessionCommand } from "#channel/types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The durable delivery envelope plus a transitional single-payload mirror.
|
|
4
|
+
*
|
|
5
|
+
* Consumers pinned to eve 0.30.3–0.30.8 cast any non-control inbox payload to
|
|
6
|
+
* a `send` command and read its `payload` field, so the mirror is what keeps
|
|
7
|
+
* their parked sessions receiving messages. Sessions are bounded by the
|
|
8
|
+
* 30-day default timeout; once runs created on those versions have aged out,
|
|
9
|
+
* drop the mirror and return plain `DeliverHookPayload`.
|
|
10
|
+
*/
|
|
11
|
+
export interface WireDeliverHookPayload extends DeliverHookPayload {
|
|
12
|
+
readonly payload: DeliverPayload;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Encodes a caller-side `send` command as the durable delivery envelope.
|
|
16
|
+
*
|
|
17
|
+
* `DeliverHookPayload` is the only wire format persisted to session hooks.
|
|
18
|
+
* Hooks outlive deployments, so every producer must emit this envelope and
|
|
19
|
+
* every consumer must keep accepting it; `send` never crosses the durable
|
|
20
|
+
* boundary itself.
|
|
21
|
+
*/
|
|
22
|
+
export declare function sendCommandToDelivery(command: Extract<SessionCommand, {
|
|
23
|
+
readonly kind: "send";
|
|
24
|
+
}>): WireDeliverHookPayload;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function sendCommandToDelivery(e){return{auth:e.auth,caller:e.caller,kind:`deliver`,payload:e.payload,payloads:[e.payload],requestId:e.requestId}}export{sendCommandToDelivery};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHook}from"#compiled/@workflow/core/index.js";import{closeHookIterator,disposeHook}from"#execution/hook-ownership.js";import{turnCancellationHookToken}from"#execution/turn-cancellation-token.js";import{forwardTurnCancellationStep}from"#execution/forward-turn-cancellation-step.js";import{forwardTurnDeliveryStep}from"#execution/forward-turn-delivery-step.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";var TurnControlReceiver=class{bufferedDeliveries;bufferedSessionControls;commandInbox;control;controlIterator;pendingControl=null;constructor(
|
|
1
|
+
import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{createHook}from"#compiled/@workflow/core/index.js";import{closeHookIterator,disposeHook}from"#execution/hook-ownership.js";import{turnCancellationHookToken}from"#execution/turn-cancellation-token.js";import{forwardTurnCancellationStep}from"#execution/forward-turn-cancellation-step.js";import{forwardTurnDeliveryStep}from"#execution/forward-turn-delivery-step.js";import{rebuildSerializableError}from"#execution/workflow-errors.js";var TurnControlReceiver=class{bufferedDeliveries;bufferedSessionControls;commandInbox;control;controlIterator;pendingControl=null;constructor(e){this.bufferedDeliveries=e.bufferedDeliveries,this.bufferedSessionControls=e.bufferedSessionControls,this.commandInbox=e.commandInbox,this.control=createHook({token:e.token}),this.controlIterator=this.control[Symbol.asyncIterator]()}get token(){return this.control.token}async dispose(){await closeHookIterator(this.controlIterator),await disposeHook(this.control)}async waitForAction(){for(;;){let e=await this.nextControlOrCommand();if(e.kind===`command`){let t=await this.handleSessionCommand(e.command);if(t!==void 0)return t;continue}let t=e.payload,n=this.readTerminalControl(t);if(n!==void 0)return n;if(t.kind===`turn-delivery-request`){let e=await this.serviceDeliveryRequest(t);if(e!==void 0)return e}}}async handleSessionCommand(t){if(t.kind===`deliver`){this.bufferedDeliveries.push(t);return}if(t.kind===`send`){this.bufferedDeliveries.push(sendCommandToDelivery(t));return}if(t.kind===`clear`||t.kind===`compact`){this.bufferedSessionControls.push(t.kind);return}if(t.kind===`session-timeout`){this.bufferedSessionControls.push(`expired`);return}if(t.kind===`cancel`){await forwardTurnCancellationStep({payload:t.turnId===void 0?{}:{turnId:t.turnId},token:turnCancellationHookToken(this.control.token)});return}if(t.kind===`reset`){await forwardTurnCancellationStep({payload:{},token:turnCancellationHookToken(this.control.token)}),this.bufferedSessionControls.push(`reset`);return}return unsupportedSessionCommand(t)}bufferTurnDeliveries(e){e.bufferedDeliveries!==void 0&&this.bufferedDeliveries.unshift(...e.bufferedDeliveries)}consumeControl(){this.pendingControl=null}getControlPromise(){return this.pendingControl??=this.controlIterator.next(),this.pendingControl}async nextControlOrCommand(){let e=await Promise.race([this.getControlPromise().then(e=>({kind:`control`,value:e})),this.commandInbox.next().then(e=>({kind:`command`,value:e}))]);if(e.kind===`command`){if(e.value.done)throw Error(`Session command inbox closed before the active turn settled.`);return this.commandInbox.consumeNext(),{command:e.value.value,kind:`command`}}if(this.consumeControl(),e.value.done)throw Error(`Turn control hook closed before delivering a result.`);let t=e.value.value;if(t.kind===`turn-error`)throw rebuildSerializableError(t.error);return t.kind===`turn-continuation-token`?(await this.commandInbox.rekeyContinuation(t.continuationToken),await this.nextControlOrCommand()):{kind:`control`,payload:t}}readTerminalControl(e){if(e.kind===`turn-error`)throw rebuildSerializableError(e.error);if(e.kind===`turn-result`)return this.bufferTurnDeliveries(e),e.action}async serviceDeliveryRequest(t){await this.commandInbox.rekeyContinuation(t.continuationToken);let n=this.bufferedDeliveries.shift();for(;n===void 0;){let r=await Promise.race([this.getControlPromise().then(e=>({kind:`control`,value:e})),this.commandInbox.next().then(e=>({kind:`command`,value:e}))]);if(r.kind===`control`){if(this.consumeControl(),r.value.done)throw Error(`Turn control hook closed during a delivery request.`);if(r.value.value.kind===`turn-continuation-token`){await this.commandInbox.rekeyContinuation(r.value.value.continuationToken);continue}let e=this.readTerminalControl(r.value.value);if(e!==void 0)return e;if(r.value.value.kind===`turn-delivery-cancelled`&&r.value.value.requestId===t.requestId)return;continue}if(r.value.done)throw Error(`Session command inbox closed during a turn delivery request.`);if(this.commandInbox.consumeNext(),r.value.value.kind===`deliver`){n=r.value.value;continue}if(r.value.value.kind===`send`){n=sendCommandToDelivery(r.value.value);continue}let i=await this.handleSessionCommand(r.value.value);if(i!==void 0)return i}try{await forwardTurnDeliveryStep({inboxToken:t.inboxToken,payload:{delivery:n,kind:`driver-delivery`,requestId:t.requestId}})}catch(e){if(!(e instanceof Error&&e.name===`HookNotFoundError`))throw e}return await this.awaitForwardedDelivery(t.requestId,n)}async awaitForwardedDelivery(e,t){for(;;){let n=await this.nextControlOrCommand();if(n.kind===`command`){let e=await this.handleSessionCommand(n.command);if(e!==void 0)return this.bufferedDeliveries.unshift(t),e;continue}let r=n.payload;if(r.kind===`turn-delivery-accepted`){if(r.requestId===e)return;continue}if(r.kind===`turn-delivery-cancelled`&&r.requestId===e){this.bufferedDeliveries.unshift(t);return}r.kind===`turn-result`&&this.bufferedDeliveries.unshift(t);let i=this.readTerminalControl(r);if(i!==void 0)return i}}};function unsupportedSessionCommand(e){throw Error(`Unsupported session command: ${JSON.stringify(e)}`)}export{TurnControlReceiver};
|
|
@@ -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{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,resumeHook,start}from"#internal/workflow/runtime.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,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]),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}`};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}),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(await waitForOwnedCommandHook(sessionCommandHookToken(p.runId),p.runId),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})}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 resumeHook(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){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),{kind:`cancel`,turnId:e.turnId})}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,turnWorkflowReference,workflowEntryReference};
|
|
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{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,resumeHook,start}from"#internal/workflow/runtime.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentLineage}from"#execution/eve-workflow-attributes.js";import{isEveDevEnvironment}from"#internal/application/dev-environment.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{buildRunContext}from"#execution/runtime-context.js";import{parseNdjsonStream}from"#execution/ndjson-stream.js";const WORKFLOW_ENTRY_NAME=`workflowEntry`,TURN_WORKFLOW_NAME=`turnWorkflow`,SESSION_TIMEOUT_WORKFLOW_NAME=`sessionTimeoutWorkflow`,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]),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}`};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}),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(await waitForOwnedCommandHook(sessionCommandHookToken(p.runId),p.runId),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})}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 resumeHook(e,sessionHookPayload(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 sessionHookPayload(e){return e.kind===`send`?sendCommandToDelivery(e):e}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){return await dispatchWorkflowCommand(sessionCommandHookToken(e.sessionId),{kind:`cancel`,turnId:e.turnId})}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,turnWorkflowReference,workflowEntryReference};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let f=getPendingAuthorization(s.state),p;if(f&&o.input?.kind===`deliver`){let e=[],t=[],n=[];for(let r of o.input.payloads){let i=r.authorizationCallback;if(i){let n=f.challenges.find(e=>e.name===i.connectionName);n&&(e.push({name:n.name,resume:n.resume,callback:i.callback,hookUrl:n.hookUrl}),t.push({name:n.name,authorization:n.challenge}))}else n.push(r)}e.length>0&&(c.set(PendingAuthorizationResultKey,e),s={...s,state:clearPendingAuthorization(s.state,e.map(e=>e.name))},p=t,o=n.length>0?{...o,input:{...o.input,payloads:n}}:{...o,input:void 0})}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let m=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:s,turnAgent:d.turnAgent}),h=buildAdapterContext(l,c),g;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,h):defaultDeliverResult(n);r!=null&&e.push(r)}g=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),g={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...h.state}}),o.input?.kind===`deliver`&&g===void 0){let e=reconcileSessionContinuationToken(c,m),t=serializeContext(c),n=e===m?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let _=u.hookRegistry,v=u.resolvedAgent.dynamicInstructionsResolvers??[],y=u.resolvedAgent.dynamicSkillResolvers??[],b=u.subagentRegistry.dynamicResolvers??[],x=u.resolvedAgent.config.experimental?.subagentPersistentSessions===!0,S=u.resolvedAgent.dynamicToolResolvers??[],C={...u.graph.root,turnAgent:d.turnAgent},w=buildRuntimeIdentity(C),T=process.env.VERCEL_DEPLOYMENT_ID?.trim(),E=T?`deployment:${T}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!getHarnessEmissionState(m.state).sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,E),c.set(SessionDynamicToolRuntimeRevisionKey,E);else{let e=createSessionStartedEvent({runtime:w});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:b,event:e,messages:m.history,persistentSessions:x,runtimeRevision:E}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,runtimeRevision:E})])}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,h);setChannelContext(c,{...l,state:{...h.state}});let r=stampMessageStreamEvent(n);return await D.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:_,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:d.turnAgent.dynamicModel,event:n,fallback:d.turnAgent.model,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:b,event:n,messages:t??[],persistentSessions:x}),await dispatchDynamicToolEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:v,event:n,messages:t??[]})},O=c.require(ModeKey),k;try{throwIfTurnAborted(o.abortSignal),k=await runStep(c,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:d.turnAgent.outputSchema,input:g,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of p)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:d.thresholdPercent},session:e,turnAgent:d.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:O,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:C,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,g)})}catch(e){if(!isTurnCancellation(e))throw e;return D.releaseLock(),{action:`cancelled`,serializedContext:preserveSerializedAgentTraceState(o.serializedContext,serializeContext(c)),sessionState:o.sessionState}}let A=reconcileSessionContinuationToken(c,k.session),j=serializeContext(c);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=readTurnSleepDurationMs(c),P=N===void 0?{}:{sleepDurationMs:N};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,output:k.next.output,isError:k.next.isError,...P,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...P,serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(!t.hasPendingAuthorization&&!t.hasPendingInputBatch&&(t.pendingRuntimeActionKeys?.length??0)===0&&k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...t,...P,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...t,...P,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...P,serializedContext:j,sessionState:M}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren){let n={auth:e.auth,kind:`send`,payload:t.payload};await resumeHook(t.childContinuationToken,n)}return n.parentAction??{kind:`continue`,remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicToolRuntimeRevisionKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionStartedEvent,encodeMessageStreamEvent,stampMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{dispatchDynamicSubagentEvent,refreshDynamicSessionSubagentsForRuntimeRevision}from"#context/dynamic-subagent-lifecycle.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resolveEffectiveAgentRuntime}from"#execution/effective-agent-config.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{preserveSerializedAgentTraceState}from"#tracing/agent-trace-context-store.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{sendCommandToDelivery}from"#execution/session-command-wire.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent,refreshDynamicSessionToolsForRuntimeRevision}from"#context/dynamic-tool-lifecycle.js";import{readTurnSleepDurationMs}from"#harness/turn-sleep.js";import{getTurnUsageState,takeSessionUsageDelta,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{buildRuntimeIdentity,createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";import{resolveRuntimeCompiledArtifactsVersionedCacheKey}from"#runtime/cache-key.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey),d=resolveEffectiveAgentRuntime(u,c);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let f=getPendingAuthorization(s.state),p;if(f&&o.input?.kind===`deliver`){let e=[],t=[],n=[];for(let r of o.input.payloads){let i=r.authorizationCallback;if(i){let n=f.challenges.find(e=>e.name===i.connectionName);n&&(e.push({name:n.name,resume:n.resume,callback:i.callback,hookUrl:n.hookUrl}),t.push({name:n.name,authorization:n.challenge}))}else n.push(r)}e.length>0&&(c.set(PendingAuthorizationResultKey,e),s={...s,state:clearPendingAuthorization(s.state,e.map(e=>e.name))},p=t,o=n.length>0?{...o,input:{...o.input,payloads:n}}:{...o,input:void 0})}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let m=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.thresholdPercent},durable:s,turnAgent:d.turnAgent}),h=buildAdapterContext(l,c),g;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,h):defaultDeliverResult(n);r!=null&&e.push(r)}g=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),g={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...h.state}}),o.input?.kind===`deliver`&&g===void 0){let e=reconcileSessionContinuationToken(c,m),t=serializeContext(c),n=e===m?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let _=u.hookRegistry,v=u.resolvedAgent.dynamicInstructionsResolvers??[],y=u.resolvedAgent.dynamicSkillResolvers??[],b=u.subagentRegistry.dynamicResolvers??[],x=u.resolvedAgent.config.experimental?.subagentPersistentSessions===!0,S=u.resolvedAgent.dynamicToolResolvers??[],C={...u.graph.root,turnAgent:d.turnAgent},w=buildRuntimeIdentity(C),T=process.env.VERCEL_DEPLOYMENT_ID?.trim(),E=T?`deployment:${T}`:await resolveRuntimeCompiledArtifactsVersionedCacheKey(u.compiledArtifactsSource);if(!getHarnessEmissionState(m.state).sessionStarted)c.set(SessionDynamicSubagentRuntimeRevisionKey,E),c.set(SessionDynamicToolRuntimeRevisionKey,E);else{let e=createSessionStartedEvent({runtime:w});await Promise.all([refreshDynamicSessionSubagentsForRuntimeRevision({ctx:c,resolvers:b,event:e,messages:m.history,persistentSessions:x,runtimeRevision:E}),refreshDynamicSessionToolsForRuntimeRevision({ctx:c,resolvers:S,event:e,messages:m.history,runtimeRevision:E})])}let D=o.parentWritable.getWriter(),emit=async t=>{let n=await callAdapterEventHandler(l,t,h);setChannelContext(c,{...l,state:{...h.state}});let r=stampMessageStreamEvent(n);return await D.write(encodeMessageStreamEvent(r)),r},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:_,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:d.turnAgent.dynamicModel,event:n,fallback:d.turnAgent.model,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicSubagentEvent({ctx:c,resolvers:b,event:n,messages:t??[],persistentSessions:x}),await dispatchDynamicToolEvent({ctx:c,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:v,event:n,messages:t??[]})},O=c.require(ModeKey),k;try{throwIfTurnAborted(o.abortSignal),k=await runStep(c,m,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:d.turnAgent.outputSchema,input:g,mode:O,session:e});if(p){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of p)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:d.thresholdPercent},session:e,turnAgent:d.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,clearOnly:o.input?.kind===`clear`,compactOnly:o.input?.kind===`compact`,createRuntime:createWorkflowRuntime,handleEvent,mode:O,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:C,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,g)})}catch(e){if(!isTurnCancellation(e))throw e;return D.releaseLock(),{action:`cancelled`,serializedContext:preserveSerializedAgentTraceState(o.serializedContext,serializeContext(c)),sessionState:o.sessionState}}let A=reconcileSessionContinuationToken(c,k.session),j=serializeContext(c);k={...k,session:A};let M=createDurableSessionState({session:k.session}),N=readTurnSleepDurationMs(c),P=N===void 0?{}:{sleepDurationMs:N};if(k.next!==null&&typeof k.next==`object`&&`done`in k.next){await D.close();let e=getTurnUsageState(k.session.state)?.session;return{action:`done`,output:k.next.output,isError:k.next.isError,...P,serializedContext:j,sessionState:M,usage:e===void 0?void 0:toUsage(e),usageDelta:takeSessionUsageDelta(k.session).delta}}if(k.next===null){D.releaseLock();let e=getPendingWorkflowInterrupt(k.session.state);if(e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt))return{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),...P,serializedContext:j,sessionState:M};let t=derivePendingState(k.session);if(!t.hasPendingAuthorization&&!t.hasPendingInputBatch&&(t.pendingRuntimeActionKeys?.length??0)===0&&k.settledTurn!==void 0){let{delta:e,session:n}=takeSessionUsageDelta(k.session);return{action:`park`,...t,...P,serializedContext:j,sessionState:createDurableSessionState({session:n}),settled:{output:k.settledTurn.output,isError:k.settledTurn.isError,usage:e}}}return{action:`park`,...t,...P,serializedContext:j,sessionState:M}}return D.releaseLock(),{action:`continue`,...P,serializedContext:j,sessionState:M}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,sendCommandToDelivery({auth:e.auth,kind:`send`,payload:t.payload}));return n.parentAction??{kind:`continue`,remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
|
|
@@ -87,6 +87,14 @@ export declare function redactSignalResume(signal: AuthorizationSignal): Authori
|
|
|
87
87
|
* single-challenge tools).
|
|
88
88
|
*/
|
|
89
89
|
export declare function getAuthorizationResult(name?: string): AuthorizationResult | undefined;
|
|
90
|
+
/**
|
|
91
|
+
* Removes and returns one authorization callback result.
|
|
92
|
+
*
|
|
93
|
+
* Callback results are one-shot inputs to `completeAuthorization`. Consuming
|
|
94
|
+
* before completion prevents a failed or replayed callback from poisoning
|
|
95
|
+
* every later tool call in the same step.
|
|
96
|
+
*/
|
|
97
|
+
export declare function consumeAuthorizationResult(name: string): AuthorizationResult | undefined;
|
|
90
98
|
/**
|
|
91
99
|
* Builds a callback URL for external systems. `name` identifies the
|
|
92
100
|
* callback in the URL path (e.g. a connection name or custom label).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function getHookUrl(r){let i=loadContext(),a=i.get(SessionIdKey),o=i.get(CallbackBaseUrlKey);return!a||!o?void 0:`${o}${createEveConnectionCallbackRoutePath(r,authHookToken(a))}`}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){return{...e,[PENDING_AUTHORIZATION_KEY]:t}}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(!(typeof t!=`object`||!t))return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,getAuthorizationResult,getHookUrl,getPendingAuthorization,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
|
|
1
|
+
import{createEveConnectionCallbackRoutePath}from"#protocol/routes.js";import{SessionIdKey}from"#context/keys.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";const AUTHORIZATION_BRAND=`__eveAuthorization`,AUTHORIZATION_PENDING_BRAND=`__eveAuthorizationPending`;function requestAuthorization(e){return{[AUTHORIZATION_BRAND]:!0,challenges:e}}function redactSignalResume(e){return requestAuthorization(e.challenges.map(e=>({name:e.name,challenge:e.challenge,hookUrl:e.hookUrl})))}function getAuthorizationResult(e){let t=loadContext().get(PendingAuthorizationResultKey);if(!(!t||t.length===0))return e===void 0?t[0]:t.find(t=>t.name===e)}function consumeAuthorizationResult(e){let t=loadContext(),r=t.get(PendingAuthorizationResultKey);if(!r||r.length===0)return;let i=r.findIndex(t=>t.name===e);if(i===-1)return;let a=r[i],s=r.filter((e,t)=>t!==i);return t.delete(PendingAuthorizationResultKey),s.length>0&&t.set(PendingAuthorizationResultKey,s),a}function getHookUrl(r){let i=loadContext(),a=i.get(SessionIdKey),o=i.get(CallbackBaseUrlKey);return!a||!o?void 0:`${o}${createEveConnectionCallbackRoutePath(r,authHookToken(a))}`}function isAuthorizationSignal(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_BRAND]===!0}function isAuthorizationPendingModelOutput(e){return typeof e!=`object`||!e?!1:e[AUTHORIZATION_PENDING_BRAND]===!0}function authorizationPendingAsJsonObject(e){return{[AUTHORIZATION_PENDING_BRAND]:!0,connections:[...e.connections]}}function modelFacingAuthorizationOutput(e){return authorizationPendingAsJsonObject({connections:e.challenges.map(e=>e.name)})}function authorizationPendingModelText(e){return e.length===0?`Authorization required. Waiting for the user to sign in.`:e.length===1?`Authorization required for ${e[0]}. Waiting for the user to sign in.`:`Authorization required for ${e.join(`, `)}. Waiting for the user to sign in.`}function isPendingAuthorizationToolOutput(e){return isAuthorizationPendingModelOutput(e)||isAuthorizationSignal(e)}function authHookToken(e){return`${e}:auth`}const PendingAuthorizationResultKey=new ContextKey(`eve.pendingAuthorizationResult`),CallbackBaseUrlKey=new ContextKey(`eve.callbackBaseUrl`),PENDING_AUTHORIZATION_KEY=`eve.runtime.pendingAuthorization`;function setPendingAuthorization(e,t){return{...e,[PENDING_AUTHORIZATION_KEY]:t}}function clearPendingAuthorization(e,t){if(e===void 0||e[PENDING_AUTHORIZATION_KEY]===void 0)return e;if(t!==void 0){if(t.length===0)return e;let n=getPendingAuthorization(e);if(n!==void 0){let r=new Set(t),i=n.challenges.filter(e=>!r.has(e.name));if(i.length>0)return{...e,[PENDING_AUTHORIZATION_KEY]:{challenges:i}}}}let n={...e};return delete n[PENDING_AUTHORIZATION_KEY],Object.keys(n).length>0?n:void 0}function getPendingAuthorization(e){if(!e)return;let t=e[PENDING_AUTHORIZATION_KEY];if(!(typeof t!=`object`||!t))return t}function hasPendingAuthorization(e){return getPendingAuthorization(e)!==void 0}export{CallbackBaseUrlKey,PendingAuthorizationResultKey,authHookToken,authorizationPendingAsJsonObject,authorizationPendingModelText,clearPendingAuthorization,consumeAuthorizationResult,getAuthorizationResult,getHookUrl,getPendingAuthorization,hasPendingAuthorization,isAuthorizationPendingModelOutput,isAuthorizationSignal,isPendingAuthorizationToolOutput,modelFacingAuthorizationOutput,redactSignalResume,requestAuthorization,setPendingAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.31.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.31.1`,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 n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=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 n=join(e,`dist`);if(existsSync(n))return{packageBuildRoot:n,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),i=tryResolveDirectBuildLocation(n);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(n));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}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 r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let t of e.copyFiles)existsSync(t)&&await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotDependencyMounts(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(r){try{if((await lstat(r.sourcePath)).isDirectory()){await copySnapshotDirectory(r);return}await mkdir(dirname(r.targetPath),{recursive:!0}),await cp(r.sourcePath,r.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(e){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${r.sourcePath}" to "${r.targetPath}": ${formatErrorMessage(e)}`)}}async function copySnapshotDirectory(t){await mkdir(t.targetPath,{recursive:!0});for(let n of await readdir(t.sourcePath,{withFileTypes:!0})){let r=join(t.sourcePath,n.name);shouldSkipSnapshotSource(t.plan,r)||await cp(r,join(t.targetPath,n.name),{filter:e=>!shouldSkipSnapshotSource(t.plan,e),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,t){let n=relative(e.sourceRoot,t);return n.length===0?!1:n.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(t,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:t})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotDependencyMounts(e){for(let t of e.dependencyMounts){let r=toSnapshotPathForPlan(e,t.mountPath),i=t.copied?toSnapshotPathForPlan(e,t.sourcePath):t.sourcePath,a=t.copied?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let t=join(e.runtimeAppRoot,`package.json`);existsSync(t)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(t,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let t=join(e.runtimeAppRoot,`package.json`);if(!existsSync(t))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${t}".`);for(let t of e.tsconfigPaths){let n=toSnapshotPathForPlan(e,t);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${n}".`);await validateSnapshotTsConfigExtends(n)}}async function validateSnapshotTsConfigExtends(e){let t=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let n of t)if(!(!isTsConfigFilePath(n)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:n}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${n}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
|
|
1
|
+
import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.devtools`,`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`.workflow-vitest`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let t of e.copyFiles)existsSync(t)&&await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotDependencyMounts(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(r){try{if((await lstat(r.sourcePath)).isDirectory()){await copySnapshotDirectory(r);return}await mkdir(dirname(r.targetPath),{recursive:!0}),await cp(r.sourcePath,r.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(e){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${r.sourcePath}" to "${r.targetPath}": ${formatErrorMessage(e)}`)}}async function copySnapshotDirectory(t){await mkdir(t.targetPath,{recursive:!0});for(let n of await readdir(t.sourcePath,{withFileTypes:!0})){let r=join(t.sourcePath,n.name);shouldSkipSnapshotSource(t.plan,r)||await cp(r,join(t.targetPath,n.name),{filter:e=>!shouldSkipSnapshotSource(t.plan,e),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,t){let n=relative(e.sourceRoot,t);return n.length===0?!1:n.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))||existsSync(join(t,`.git`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:t})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotDependencyMounts(e){for(let t of e.dependencyMounts){let r=toSnapshotPathForPlan(e,t.mountPath),i=t.copied?toSnapshotPathForPlan(e,t.sourcePath):t.sourcePath,a=t.copied?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let t=join(e.runtimeAppRoot,`package.json`);existsSync(t)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(t,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let t=join(e.runtimeAppRoot,`package.json`);if(!existsSync(t))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${t}".`);for(let t of e.tsconfigPaths){let n=toSnapshotPathForPlan(e,t);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${n}".`);await validateSnapshotTsConfigExtends(n)}}async function validateSnapshotTsConfigExtends(e){let t=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let n of t)if(!(!isTsConfigFilePath(n)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:n}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${n}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{existsSync}from"node:fs";import{dirname,join,normalize,resolve,sep}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=0,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch$1(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:e=>shouldIgnoreWatcherPath(e,t.workspaceExtensions)}),p=waitForWatcherReady(f),rebuild=async(i,a=!1)=>{n||o>0||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t;!a&&r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:o});t=n.host,a||(n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE)),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)},forceRebuild=async(e=!1)=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0,e)};return f.on(`all`,(e,t)=>{n||!a||e===`addDir`||e===`unlinkDir`||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:forceRebuild,async suspend(){o+=1,i!==void 0&&(clearTimeout(i),i=void 0),await r},async resume(e){o!==0&&(--o,o===0&&await forceRebuild(e?.silent))}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(t){let n=new Set([t.compileResult.project.agentRoot,join(t.appRoot,`package.json`),join(t.appRoot,`jsconfig.json`),join(t.appRoot,`tsconfig.json`),join(t.appRoot,`tsconfig.*.json`)]),i=await resolveTsConfigWatchPaths(t.appRoot),a=await resolveDevelopmentSourceSnapshotWatchPaths(t.appRoot);for(let e of t.workspaceExtensions){n.add(e.config.sourceRoot);for(let t of e.buildConfigPaths)n.add(t)}for(let r of getDevelopmentEnvironmentFilePaths(t.appRoot))n.add(r);for(let e of a)n.add(e);for(let e of i)n.add(e);for(let e of resolveLockfileSearchDirectories(t.appRoot))for(let t of WATCHED_LOCKFILE_NAMES)n.add(join(e,t));return[...n].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let t=resolve(e),r=[t],i=t;for(;;){if(hasWatchRootMarker(i))return r;let e=dirname(i);if(e===i)return[t];i=e,r.push(i)}}function hasWatchRootMarker(e){return WATCH_ROOT_MARKER_NAMES.some(n=>existsSync(join(e,n)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e,t){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))||t.some(t=>isPathInsideOrEqual(e,t.config.outDir))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{startAuthoredSourceWatcher};
|
|
1
|
+
import{getDevelopmentEnvironmentFilePaths}from"#cli/dev/environment.js";import{existsSync}from"node:fs";import{dirname,join,normalize,resolve,sep}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{watch as watch$1}from"#compiled/chokidar/index.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.devtools`,`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,a=!1,o=0,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch$1(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:e=>shouldIgnoreWatcherPath(e,t.workspaceExtensions)}),p=waitForWatcherReady(f),rebuild=async(i,a=!1)=>{n||o>0||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t;!a&&r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{let n=await e.coordinator.rebuild({changedPaths:o});t=n.host,a||(n.kind===`structural`?console.log(STRUCTURAL_RELOAD_LOG_LINE):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE)),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(t),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)},forceRebuild=async(e=!1)=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0,e)};return f.on(`all`,(e,t)=>{n||!a||e===`addDir`||e===`unlinkDir`||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,a=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:forceRebuild,async suspend(){o+=1,i!==void 0&&(clearTimeout(i),i=void 0),await r},async resume(e){o!==0&&(--o,o===0&&await forceRebuild(e?.silent))}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(t){let n=new Set([t.compileResult.project.agentRoot,join(t.appRoot,`package.json`),join(t.appRoot,`jsconfig.json`),join(t.appRoot,`tsconfig.json`),join(t.appRoot,`tsconfig.*.json`)]),i=await resolveTsConfigWatchPaths(t.appRoot),a=await resolveDevelopmentSourceSnapshotWatchPaths(t.appRoot);for(let e of t.workspaceExtensions){n.add(e.config.sourceRoot);for(let t of e.buildConfigPaths)n.add(t)}for(let r of getDevelopmentEnvironmentFilePaths(t.appRoot))n.add(r);for(let e of a)n.add(e);for(let e of i)n.add(e);for(let e of resolveLockfileSearchDirectories(t.appRoot))for(let t of WATCHED_LOCKFILE_NAMES)n.add(join(e,t));return[...n].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return normalize(resolve(e))}function resolveLockfileSearchDirectories(e){let t=resolve(e),r=[t],i=t;for(;;){if(hasWatchRootMarker(i))return r;let e=dirname(i);if(e===i)return[t];i=e,r.push(i)}}function hasWatchRootMarker(e){return WATCH_ROOT_MARKER_NAMES.some(n=>existsSync(join(e,n)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e,t){return normalize(e).split(sep).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))||t.some(t=>isPathInsideOrEqual(e,t.config.outDir))}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}export{startAuthoredSourceWatcher};
|
|
@@ -110,6 +110,10 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends Pub
|
|
|
110
110
|
*/
|
|
111
111
|
toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
|
|
112
112
|
}
|
|
113
|
+
type ToolOutputFromExecuteReturn<TReturn> = TReturn extends Promise<infer TOutput> ? TOutput : TReturn extends AsyncIterable<infer TOutput> ? TOutput : TReturn;
|
|
114
|
+
type ToolDefinitionWithExecuteReturn<TInput, TOutput, TReturn> = ToolDefinition<TInput, TOutput> & {
|
|
115
|
+
execute(input: TInput, ctx: ToolContext): TReturn;
|
|
116
|
+
};
|
|
113
117
|
/**
|
|
114
118
|
* Defines a tool configuration, used both for static tools (default export
|
|
115
119
|
* from `agent/tools/*.ts`) and as the entry wrapper inside `defineDynamic`
|
|
@@ -118,38 +122,38 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends Pub
|
|
|
118
122
|
* For static tools, the runtime tool name is the filename slug. `defineTool`
|
|
119
123
|
* stamps a brand that lifecycle code validates; it rejects raw object literals.
|
|
120
124
|
*/
|
|
121
|
-
export declare function defineTool<TInputSchema extends StandardJSONSchemaV1<unknown, unknown>, TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>>(definition: {
|
|
125
|
+
export declare function defineTool<TInputSchema extends StandardJSONSchemaV1<unknown, unknown>, TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn extends Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>>(definition: {
|
|
122
126
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
123
127
|
inputSchema: TInputSchema;
|
|
124
128
|
outputSchema: TOutputSchema;
|
|
125
|
-
execute(input: StandardJSONSchemaV1.InferOutput<TInputSchema>, ctx: ToolContext):
|
|
129
|
+
execute(input: StandardJSONSchemaV1.InferOutput<TInputSchema>, ctx: ToolContext): TReturn;
|
|
126
130
|
approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TInputSchema>, unknown>["approval"];
|
|
127
131
|
toModelOutput?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["toModelOutput"];
|
|
128
|
-
}):
|
|
129
|
-
export declare function defineTool<TSchema extends StandardJSONSchemaV1<unknown, unknown>,
|
|
132
|
+
}): ToolDefinitionWithExecuteReturn<StandardJSONSchemaV1.InferOutput<TInputSchema>, StandardJSONSchemaV1.InferOutput<TOutputSchema>, TReturn>;
|
|
133
|
+
export declare function defineTool<TSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn>(definition: {
|
|
130
134
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
131
135
|
inputSchema: TSchema;
|
|
132
136
|
outputSchema?: JsonObject;
|
|
133
|
-
execute(input: StandardJSONSchemaV1.InferOutput<TSchema>, ctx: ToolContext):
|
|
137
|
+
execute(input: StandardJSONSchemaV1.InferOutput<TSchema>, ctx: ToolContext): TReturn;
|
|
134
138
|
approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, unknown>["approval"];
|
|
135
|
-
toModelOutput?: ToolDefinition<unknown,
|
|
136
|
-
}):
|
|
137
|
-
export declare function defineTool<TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>>(definition: {
|
|
139
|
+
toModelOutput?: ToolDefinition<unknown, ToolOutputFromExecuteReturn<TReturn>>["toModelOutput"];
|
|
140
|
+
}): ToolDefinitionWithExecuteReturn<StandardJSONSchemaV1.InferOutput<TSchema>, ToolOutputFromExecuteReturn<TReturn>, TReturn>;
|
|
141
|
+
export declare function defineTool<TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>, TReturn extends Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>> | StandardJSONSchemaV1.InferOutput<TOutputSchema> | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>>(definition: {
|
|
138
142
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
139
143
|
inputSchema: JsonObject;
|
|
140
144
|
outputSchema: TOutputSchema;
|
|
141
|
-
execute(input: Record<string, unknown>, ctx: ToolContext):
|
|
145
|
+
execute(input: Record<string, unknown>, ctx: ToolContext): TReturn;
|
|
142
146
|
approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];
|
|
143
147
|
toModelOutput?: ToolDefinition<unknown, StandardJSONSchemaV1.InferOutput<TOutputSchema>>["toModelOutput"];
|
|
144
|
-
}):
|
|
145
|
-
export declare function defineTool<
|
|
148
|
+
}): ToolDefinitionWithExecuteReturn<Record<string, unknown>, StandardJSONSchemaV1.InferOutput<TOutputSchema>, TReturn>;
|
|
149
|
+
export declare function defineTool<TReturn>(definition: {
|
|
146
150
|
description: ToolDefinition<unknown, unknown>["description"];
|
|
147
151
|
inputSchema: JsonObject;
|
|
148
152
|
outputSchema?: JsonObject;
|
|
149
|
-
execute(input: Record<string, unknown>, ctx: ToolContext):
|
|
153
|
+
execute(input: Record<string, unknown>, ctx: ToolContext): TReturn;
|
|
150
154
|
approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];
|
|
151
|
-
toModelOutput?: ToolDefinition<unknown,
|
|
152
|
-
}):
|
|
155
|
+
toModelOutput?: ToolDefinition<unknown, ToolOutputFromExecuteReturn<TReturn>>["toModelOutput"];
|
|
156
|
+
}): ToolDefinitionWithExecuteReturn<Record<string, unknown>, ToolOutputFromExecuteReturn<TReturn>, TReturn>;
|
|
153
157
|
export declare function defineTool<TInput = unknown, TOutput = unknown>(definition: ToolDefinition<TInput, TOutput>): ToolDefinition<TInput, TOutput>;
|
|
154
158
|
/**
|
|
155
159
|
* Defines a dynamic resolver evaluated at runtime from stream-event
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage,loadContext}from"#context/container.js";import{
|
|
1
|
+
import{contextStorage,loadContext}from"#context/container.js";import{consumeAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{evictCachedToken,readCachedToken,writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";const LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES=new Set([`127.0.0.1`,`[::1]`]);async function resolveScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore(),o=resolveConnectionPrincipal(n,r,a);if(a===void 0)return await r.getToken({connection:i,principal:o});let u=principalKey(o),d=readCachedToken(a,n,u);if(d!==void 0)return d;let f=await r.getToken({connection:i,principal:o});return writeCachedToken(a,n,u,f),f}async function evictScopedToken(t){let{scope:n,authorization:r,connection:i}=t,a=contextStorage.getStore();if(a===void 0)return;let s;try{s=resolveConnectionPrincipal(n,r,a),evictCachedToken(a,n,principalKey(s))}catch{return}try{await r.evict?.({connection:i,principal:s})}catch{}}async function completeScopedAuthorization(e){let{scope:r,authorization:i,connection:o}=e;if(!supportsInteractiveAuthorization(i))return!1;let s=consumeAuthorizationResult(r);if(s===void 0)return!1;let u=i,d=loadContext(),f=resolveConnectionPrincipal(r,u,d),p=await u.completeAuthorization({callbackUrl:s.hookUrl,connection:o,principal:f,resume:s.resume,callback:s.callback});return writeCachedToken(d,r,principalKey(f),p),!0}async function startScopedAuthorization(e){let{scope:t,authorization:n,connection:o}=e;if(!supportsInteractiveAuthorization(n))return;let s=getHookUrl(t);if(s===void 0)return;let c=n,l=resolveConnectionPrincipal(t,c),u=resolveAuthorizationCallbackUrl({authorization:n,callbackUrl:s}),{challenge:d,resume:f}=await c.startAuthorization({callbackUrl:u,connection:o,principal:l});return requestAuthorization([{challenge:stampChallengeDisplayName(d,n),hookUrl:u,name:t,resume:f}])}function resolveAuthorizationCallbackUrl(e){if(e.authorization.vercelConnect===void 0)return e.callbackUrl;let t;try{t=new URL(e.callbackUrl)}catch{return e.callbackUrl}return t.protocol!==`http:`||!LOCAL_HTTP_VERCEL_CONNECT_HOSTNAMES.has(t.hostname)?e.callbackUrl:(t.hostname=`localhost`,t.toString())}function stampChallengeDisplayName(e,t){let n=t.displayName??e.displayName;return n===e.displayName?e:{...e,displayName:n}}export{completeScopedAuthorization,evictScopedToken,resolveAuthorizationCallbackUrl,resolveScopedToken,stampChallengeDisplayName,startScopedAuthorization};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{
|
|
2
|
-
`));
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{z}from"#compiled/zod/index.js";import{toError}from"#shared/errors.js";import{loadContext}from"#context/container.js";import{ContextKey}from"#context/key.js";import{ConnectionRegistryKey}from"#context/providers/connection-key.js";import{ConnectionAuthorizationFailedError,isConnectionAuthorizationFailedError,isConnectionAuthorizationRequiredError}from"#public/connections/errors.js";import{consumeAuthorizationResult,getHookUrl,requestAuthorization}from"#harness/authorization.js";import{supportsInteractiveAuthorization}from"#runtime/connections/types.js";import{resolveAuthorizationCallbackUrl,stampChallengeDisplayName}from"#runtime/connections/scoped-authorization.js";import{defineDynamic,defineTool}from"#public/definitions/tool.js";import{resolveConnectionAuthorization}from"#runtime/connections/resolve-authorization.js";import{writeCachedToken}from"#runtime/connections/authorization-tokens.js";import{principalKey,resolveConnectionPrincipal}from"#runtime/connections/principal.js";var __eveStepRegistrySym=Symbol.for(`@workflow/core//registeredSteps`);globalThis[__eveStepRegistrySym]||(globalThis[__eveStepRegistrySym]=new Map);var __eveStepRegistry=globalThis[__eveStepRegistrySym];const logger=createLogger(`framework.connection-search-dynamic`),CONNECTION_SEARCH_INPUT_SCHEMA=z.strictObject({connection:z.string().describe(`Optional: limit search to a specific connection name.`).optional(),keywords:z.string().describe(`Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.`),limit:z.number().describe(`Max results to return. Default 10.`).optional()}),connectionSchema=z.looseObject({}),CONNECTION_SEARCH_RESULT_ITEM_SCHEMA=z.strictObject({connection:z.string(),description:z.string(),error:z.string().optional(),inputSchema:connectionSchema.optional(),needsAuthorization:z.boolean().optional(),outputSchema:connectionSchema.optional(),qualifiedName:z.string().optional(),tool:z.string().optional()}),CONNECTION_SEARCH_OUTPUT_SCHEMA=z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA),ConnectionSearchResultsKey=new ContextKey(`eve.connectionSearchResults`);function qualifiedConnectionToolName(e,t){return`${e}__${t}`}function tokenize(e){return e.toLowerCase().split(/[\s_\-./]+/).filter(e=>e.length>1)}function scoreMatch(e,t){let n=tokenize(t.name),r=tokenize(t.description),i=0;for(let t of e){for(let e of n)(e.includes(t)||t.includes(e))&&(i+=3);for(let e of r)(e.includes(t)||t.includes(e))&&(i+=1)}return i}async function resolveInteractiveAuth(e,t){let n=e.getConnections().find(e=>e.connectionName===t);if(n===void 0)return;let r=await resolveConnectionAuthorization(n);if(supportsInteractiveAuthorization(r))return r}async function completePendingAuthorizations(e,t){let n=loadContext(),i=new Set;for(let r of t){let t=consumeAuthorizationResult(r.connectionName);if(!t)continue;let a=await resolveInteractiveAuth(e,r.connectionName);if(!a)continue;let o=resolveConnectionPrincipal(r.connectionName,a),s=await a.completeAuthorization({callbackUrl:t.hookUrl,connection:{url:r.url??``},principal:o,resume:t.resume,callback:t.callback});writeCachedToken(n,r.connectionName,principalKey(o),s),i.add(r.connectionName)}return i}async function executeConnectionSearch(e){let t=loadContext(),i=t.get(ConnectionRegistryKey);if(i===void 0)return[];let o=e.limit??10,l=tokenize(e.keywords),d=[],f=[],p=e.connection!==void 0&&e.connection!==``?i.getConnections().filter(t=>t.connectionName===e.connection):i.getConnections();if(e.connection&&p.length===0)throw Error(`Connection "${e.connection}" is not registered. Available connections: ${i.getConnectionNames().join(`, `)}.`);let m=await completePendingAuthorizations(i,p),h=[];for(let e of p){let t;try{t=await i.getClient(e.connectionName).getToolMetadata()}catch(t){if(isConnectionAuthorizationRequiredError(t)){if(m.has(e.connectionName)){logger.warn(`connection still unauthorized after authorization`,{connection:e.connectionName}),f.push({connection:e.connectionName,description:e.description,error:`Authorization for "${e.connectionName}" did not take effect; the token was rejected after sign-in.`});continue}let t=await resolveInteractiveAuth(i,e.connectionName);if(t){let r=getHookUrl(e.connectionName);if(r){let i=resolveConnectionPrincipal(e.connectionName,t),a=resolveAuthorizationCallbackUrl({authorization:t,callbackUrl:r});try{let{challenge:n,resume:r}=await t.startAuthorization({callbackUrl:a,connection:{url:e.url??``},principal:i});h.push({name:e.connectionName,challenge:stampChallengeDisplayName(n,t),hookUrl:a,resume:r})}catch(t){let r=toError(t);logger.warn(`startAuthorization failed`,{connection:e.connectionName,error:r}),f.push({connection:e.connectionName,description:e.description,error:`Failed to start authorization for "${e.connectionName}": ${r.message}`});continue}}}f.push({connection:e.connectionName,description:e.description,needsAuthorization:!0});continue}if(isConnectionAuthorizationFailedError(t)){logger.warn(`connection authorization failed`,{connection:e.connectionName,reason:t.reason,retryable:t.retryable,error:t}),f.push({connection:e.connectionName,description:e.description,error:`Authorization failed for ${e.connectionName}: ${t.message}`});continue}let r=toError(t);logger.warn(`failed to load connection tools`,{connection:e.connectionName,error:r}),f.push({connection:e.connectionName,description:e.description,error:`Failed to load tools for "${e.connectionName}": ${r.message}`});continue}for(let n of t){let t=scoreMatch(l,n);t>0&&d.push({item:{connection:e.connectionName,description:n.description,inputSchema:n.inputSchema,outputSchema:n.outputSchema,qualifiedName:qualifiedConnectionToolName(e.connectionName,n.name),tool:n.name},score:t})}}if(h.length>0)return requestAuthorization(h);let g=f.filter(e=>e.error!==void 0);if(p.length>0&&g.length===p.length)throw Error(g.map(e=>e.error).join(`
|
|
2
|
+
`));d.sort((e,t)=>t.score-e.score);let _=d.slice(0,o).map(e=>e.item);if(_.length>0){let e=[..._,...f],n=t.get(ConnectionSearchResultsKey)??[],r=new Map(n.map(e=>[e.qualifiedName,e]));for(let e of _)e.qualifiedName&&r.set(e.qualifiedName,e);return t.set(ConnectionSearchResultsKey,[...r.values()]),e}return p.map(e=>f.find(t=>t.connection===e.connectionName)||{connection:e.connectionName,description:e.description})}function extractDiscoveredTools(e){let t=new Map;for(let n of e){if(n.role!==`tool`)continue;let e=n.content;for(let n of e){if(n.type!==`tool-result`||n.toolName!==`connection_search`)continue;let e=n.output;if(e==null)continue;let r=typeof e==`object`&&`type`in e&&`value`in e?e.value:e;if(Array.isArray(r))for(let e of r)e.tool&&e.qualifiedName&&t.set(e.qualifiedName,e)}}return[...t.values()]}const connectionSearchDynamicDefinition=defineDynamic({events:{"step.started":async(e,t)=>{let n=loadContext().get(ConnectionRegistryKey);if(!n||n.getConnections().length===0)return null;let i=n.getConnections().map(e=>e.connectionName),o=extractDiscoveredTools(t.messages),s=loadContext().get(ConnectionSearchResultsKey)??[],c=new Map;for(let e of s)e.qualifiedName&&c.set(e.qualifiedName,e);for(let e of o)e.qualifiedName&&c.set(e.qualifiedName,e);let l=[...c.values()],u={};u.connection_search=defineTool({description:`Search for tools across your connections. Discovered tools become directly callable by their qualified name (e.g. \`linear__list_issues\`) in your next response. Available connections: ${i.join(`, `)}.`,inputSchema:CONNECTION_SEARCH_INPUT_SCHEMA,execute:async e=>await __eve_dynamic_exec_0({},e),__executeStepFn:__eve_dynamic_exec_0,__closureVars:{},outputSchema:CONNECTION_SEARCH_OUTPUT_SCHEMA});for(let e of l){let r=e.connection,i=e.tool,a=n.getConnectionApproval(r);u[qualifiedConnectionToolName(r,i)]=defineTool({description:e.description,inputSchema:e.inputSchema??{type:`object`},approval:a,outputSchema:e.outputSchema,execute:async(e,n)=>await __eve_dynamic_exec_1({ctx:t,connectionName:r,toolName:i},e,n),__executeStepFn:__eve_dynamic_exec_1,__closureVars:{ctx:t,connectionName:r,toolName:i}})}return u}}});async function __eve_dynamic_exec_0(e,t){return executeConnectionSearch(t)}async function __eve_dynamic_exec_1(e,t,n){let{ctx:i,connectionName:s,toolName:d}=e,f=loadContext().get(ConnectionRegistryKey),p=f.getConnections().find(e=>e.connectionName===s),m=await resolveInteractiveAuth(f,s),_=!1;if(m){let e=consumeAuthorizationResult(s);if(e){_=!0;let t=loadContext(),n=resolveConnectionPrincipal(s,m),i=await m.completeAuthorization({callbackUrl:e.hookUrl,connection:{url:p?.url??``},principal:n,resume:e.resume,callback:e.callback});writeCachedToken(t,s,principalKey(n),i)}}try{return await f.getClient(s).executeTool(d,t,{abortSignal:n.abortSignal})}catch(e){if(!isConnectionAuthorizationRequiredError(e)||!m)throw e;if(_)throw new ConnectionAuthorizationFailedError(s,{retryable:!1,reason:`token_rejected_after_authorization`,message:`Connection "${s}" rejected the token immediately after authorization.`});let t=getHookUrl(s);if(!t)throw e;let n=resolveConnectionPrincipal(s,m),r=resolveAuthorizationCallbackUrl({authorization:m,callbackUrl:t}),{challenge:i,resume:a}=await m.startAuthorization({callbackUrl:r,connection:{url:p?.url??``},principal:n});return requestAuthorization([{name:s,challenge:stampChallengeDisplayName(i,m),hookUrl:r,resume:a}])}}__eve_dynamic_exec_0.stepId=`eve:dynamic-tool//__eve_dynamic_exec_0`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_0`,__eve_dynamic_exec_0),__eve_dynamic_exec_1.stepId=`eve:dynamic-tool//__eve_dynamic_exec_1`,__eveStepRegistry.set(`eve:dynamic-tool//__eve_dynamic_exec_1`,__eve_dynamic_exec_1);export{connectionSearchDynamicDefinition as default,extractDiscoveredTools};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.38`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.31.
|
|
1
|
+
import{pinnedNodeEngineMajor}from"../../node-engine.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"../update/module-files.js";import{pathExists,writeTextFile}from"../files.js";import{blockingCreateInPlaceEntries}from"../create-in-place.js";import{resolveVersionToken}from"../version-tokens.js";import{applyPackageManagerWorkspaceConfiguration,isPackageManagerWorkspaceMember,patchWorkspaceRootPackageJson}from"../workspace-root.js";import{WEB_APP_TEMPLATE_FILES}from"./web-template.js";import{mkdir,readdir,stat}from"node:fs/promises";import{basename,join,resolve}from"node:path";const CURRENT_DIRECTORY_PROJECT_NAME=`.`,DEFAULT_AI_PACKAGE_VERSION=`^7.0.38`,DEFAULT_CONNECT_PACKAGE_VERSION=`0.4.3`,DEFAULT_ZOD_PACKAGE_VERSION=`4.4.3`,DEFAULT_EVE_PACKAGE_CONTRACT={version:`0.31.1`,nodeEngine:`>=24`};function resolveEvePackageContract(e=DEFAULT_EVE_PACKAGE_CONTRACT){return{version:resolveVersionToken(`evePackage.version`,e.version),nodeEngine:resolveVersionToken(`evePackage.nodeEngine`,e.nodeEngine)}}function modelProviderSlug(e){let t=(e.split(`/`)[0]??``).replaceAll(/[^A-Za-z0-9._-]/gu,``);return t.length>0?t:`anthropic`}function byokProviderEnvVar(e){let t=modelProviderSlug(e).toUpperCase().replaceAll(/[^A-Z0-9]/gu,`_`);return`${/^[0-9]/.test(t)?`_`:``}${t}_API_KEY`}function agentTemplateFiles(e){return{"agent/agent.ts":BASE_AGENT_TEMPLATE.replaceAll(`__EVE_INIT_MODEL__`,e),"agent/channels/eve.ts":WEB_APP_TEMPLATE_FILES[`agent/channels/eve.ts`],"agent/instructions.md":AGENT_INSTRUCTIONS_TEMPLATE}}function renderTemplate(e,t){return e.replaceAll(`__EVE_INIT_APP_NAME__`,t.appName).replaceAll(`__EVE_INIT_MODEL__`,t.model).replaceAll(`__EVE_INIT_BYOK_PROVIDER__`,modelProviderSlug(t.model)).replaceAll(`__EVE_INIT_BYOK_ENV_VAR__`,byokProviderEnvVar(t.model)).replaceAll(`__EVE_INIT_PACKAGE_VERSION__`,formatEveDependencySpecifier(t.eveVersion)).replaceAll(`__EVE_INIT_AI_SDK_VERSION__`,t.aiPackageVersion).replaceAll(`__EVE_INIT_CONNECT_VERSION__`,t.connectPackageVersion).replaceAll(`__EVE_INIT_ZOD_VERSION__`,t.zodPackageVersion).replaceAll(`__EVE_INIT_TYPESCRIPT_VERSION__`,t.typescriptPackageVersion).replaceAll(`__EVE_INIT_TYPES_NODE_VERSION__`,t.nodeTypesVersion).replaceAll(`__EVE_INIT_NODE_ENGINE__`,t.nodeEngine)}function formatEveDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}const BASE_AGENT_TEMPLATE=`import { defineAgent } from "eve";
|
|
2
2
|
|
|
3
3
|
export default defineAgent({
|
|
4
4
|
model: "__EVE_INIT_MODEL__",
|
package/docs/guides/meta.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: "Remote Agents"
|
|
3
|
-
description: "Call another eve deployment as a subagent with defineRemoteAgent: same
|
|
3
|
+
description: "Call another eve deployment as a subagent with defineRemoteAgent: same tool call as a local subagent, outbound auth, durable callback dispatch."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
`defineRemoteAgent` calls a separately deployed eve agent as if it were a local subagent. Reach for it when the specialist you delegate to is a separately owned agent behind its own URL rather than a directory in your repo.
|
|
@@ -28,7 +28,7 @@ export default defineRemoteAgent({
|
|
|
28
28
|
| `forwardPrincipal` | `boolean` | No | `false` | Forward the dispatching turn's session principal to the remote deployment (see [Forwarding the caller identity](#forwarding-the-caller-identity)). |
|
|
29
29
|
| `headers` | `HeadersValue` | No | none | Static or lazily resolved request headers. |
|
|
30
30
|
| `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |
|
|
31
|
-
| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires.
|
|
31
|
+
| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Enforced by the remote agent like any task-mode output schema. Set it on the definition to apply to every call, or override it per call. |
|
|
32
32
|
|
|
33
33
|
## Dynamic remote agents
|
|
34
34
|
|
|
@@ -78,9 +78,11 @@ export default defineRemoteAgent({
|
|
|
78
78
|
|
|
79
79
|
The function may be async and must return a non-empty string. `auth` and `headers` are resolved at runtime the same way.
|
|
80
80
|
|
|
81
|
-
##
|
|
81
|
+
## Calling a remote agent
|
|
82
82
|
|
|
83
|
-
|
|
83
|
+
To the model, a remote agent is another subagent tool. You call it the same way you call a local subagent, with a `message` and an optional `outputSchema`. The message must carry the full task, including any context the remote agent needs, because it never receives the parent's conversation history.
|
|
84
|
+
|
|
85
|
+
To get one structured result back instead of an open-ended reply, set an `outputSchema` on the agent definition or on an individual call. The remote agent then runs in task mode, a single-shot delegation that returns structured output as the tool result. See [Subagents](../subagents) for how task mode works.
|
|
84
86
|
|
|
85
87
|
## Outbound auth
|
|
86
88
|
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Universal Commerce Protocol (UCP)"
|
|
3
|
+
description: "Serve a UCP profile at /.well-known/ucp from a custom eve channel."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
The [Universal Commerce Protocol](https://ucp.dev/) (UCP) is an open standard for agentic commerce. A business declares its UCP support by serving a JSON **profile** from the `/.well-known/ucp` path. This is a document listing the spec versions it supports, its services and capabilities, its payment handlers, and the public keys agents use to verify signed responses.
|
|
7
|
+
|
|
8
|
+
With eve, you can support UCP in three steps:
|
|
9
|
+
|
|
10
|
+
1. [Author the profile](#author-the-profile)
|
|
11
|
+
2. [Serve it from a channel](#serve-it-from-a-channel)
|
|
12
|
+
3. [Add your commerce endpoints](#add-your-commerce-endpoints)
|
|
13
|
+
|
|
14
|
+
## Author the profile
|
|
15
|
+
|
|
16
|
+
Your profile is a plain JSON object that follows the [UCP spec](https://ucp.dev/). This spec outlines the `version`, `services`, `payment_handlers` and `capabilities` of your business. It also includes `signing_keys`, the public keys agents use to verify your business's signed messages.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
// agent/ucp-profile.ts
|
|
20
|
+
export const profile = {
|
|
21
|
+
ucp: {
|
|
22
|
+
version: "2026-04-08",
|
|
23
|
+
services: {
|
|
24
|
+
"dev.ucp.shopping": [
|
|
25
|
+
{
|
|
26
|
+
version: "2026-04-08",
|
|
27
|
+
spec: "https://ucp.dev/2026-04-08/specification/overview",
|
|
28
|
+
transport: "rest",
|
|
29
|
+
schema: "https://ucp.dev/2026-04-08/services/shopping/rest.openapi.json",
|
|
30
|
+
endpoint: "https://your_deployment_url_here/ucp/shopping",
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
},
|
|
34
|
+
capabilities: {
|
|
35
|
+
"dev.ucp.shopping.checkout": [
|
|
36
|
+
{
|
|
37
|
+
version: "2026-04-08",
|
|
38
|
+
spec: "https://ucp.dev/2026-04-08/specification/checkout",
|
|
39
|
+
schema: "https://ucp.dev/2026-04-08/schemas/shopping/checkout.json",
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
},
|
|
43
|
+
payment_handlers: {
|
|
44
|
+
"dev.shopify.shop_pay": [
|
|
45
|
+
{
|
|
46
|
+
id: "shop_pay_1234",
|
|
47
|
+
version: "2026-04-08",
|
|
48
|
+
spec: "https://shopify.dev/ucp/shop-pay-handler",
|
|
49
|
+
schema: "https://shopify.dev/ucp/schemas/shop-pay-config.json",
|
|
50
|
+
available_instruments: [
|
|
51
|
+
{
|
|
52
|
+
type: "shop_pay",
|
|
53
|
+
},
|
|
54
|
+
],
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
"com.example.processor_tokenizer": [
|
|
58
|
+
{
|
|
59
|
+
id: "processor_tokenizer",
|
|
60
|
+
version: "2026-04-08",
|
|
61
|
+
spec: "https://example.com/specs/payments/processor_tokenizer-payment",
|
|
62
|
+
schema: "https://example.com/schemas/payments/delegate-payment.json",
|
|
63
|
+
available_instruments: [
|
|
64
|
+
{
|
|
65
|
+
type: "card",
|
|
66
|
+
constraints: {
|
|
67
|
+
brands: ["visa", "mastercard"],
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
},
|
|
72
|
+
],
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
signing_keys: [
|
|
76
|
+
{
|
|
77
|
+
kid: "business_2025",
|
|
78
|
+
kty: "EC",
|
|
79
|
+
crv: "P-256",
|
|
80
|
+
x: "...",
|
|
81
|
+
y: "...",
|
|
82
|
+
use: "sig",
|
|
83
|
+
alg: "ES256",
|
|
84
|
+
},
|
|
85
|
+
],
|
|
86
|
+
};
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Serve it from a channel
|
|
90
|
+
|
|
91
|
+
Use a custom channel to serve the profile from the `/.well-known/ucp` endpoint.
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
// agent/channels/ucp.ts
|
|
95
|
+
import { defineChannel, GET } from "eve/channels";
|
|
96
|
+
import { profile } from "../ucp-profile";
|
|
97
|
+
|
|
98
|
+
const body = JSON.stringify(profile);
|
|
99
|
+
|
|
100
|
+
export default defineChannel({
|
|
101
|
+
cors: true,
|
|
102
|
+
routes: [
|
|
103
|
+
GET("/.well-known/ucp", async () => {
|
|
104
|
+
return new Response(body, {
|
|
105
|
+
headers: {
|
|
106
|
+
"content-type": "application/json",
|
|
107
|
+
"cache-control": "public, max-age=300",
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
}),
|
|
111
|
+
],
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
- **Caching**: The spec requires `public` and a `max-age` of at least 60 seconds, and forbids `private`, `no-store`, and `no-cache`. See [Profile Requirements](https://ucp.dev/2026-04-08/specification/overview#hosting).
|
|
116
|
+
- **CORS**: `cors: true` suits public discovery metadata. Pass a `cors` options object to narrow origins. See [CORS](../channels/custom#cors).
|
|
117
|
+
- **HTTPS, no redirects**: The spec requires HTTPS and forbids 3xx responses on the profile endpoint.
|
|
118
|
+
|
|
119
|
+
## Add your commerce endpoints
|
|
120
|
+
|
|
121
|
+
The URLs in `services[].endpoint` must point at endpoints you serve. You can use a custom channel for these endpoints:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
// agent/channels/ucp-shopping.ts
|
|
125
|
+
import { defineChannel, POST } from "eve/channels";
|
|
126
|
+
|
|
127
|
+
export default defineChannel({
|
|
128
|
+
routes: [
|
|
129
|
+
POST("/ucp/shopping/checkout-sessions", async (req) => {
|
|
130
|
+
const request = await req.json();
|
|
131
|
+
// Create a checkout session per your published schema. Every UCP
|
|
132
|
+
// response must carry the `ucp` envelope with the negotiated
|
|
133
|
+
// version and the capabilities active for this response.
|
|
134
|
+
return Response.json({
|
|
135
|
+
ucp: {
|
|
136
|
+
version: "2026-04-08",
|
|
137
|
+
capabilities: {
|
|
138
|
+
"dev.ucp.shopping.checkout": [{ version: "2026-04-08" }],
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
id: "checkout_123",
|
|
142
|
+
status: "incomplete",
|
|
143
|
+
// ...other checkout fields per the checkout schema
|
|
144
|
+
});
|
|
145
|
+
}),
|
|
146
|
+
],
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Routes are relative to the `endpoint` base in your profile, per the service's OpenAPI schema. Keep them in sync with the paths you mount here.
|
|
151
|
+
|
|
152
|
+
## Verify
|
|
153
|
+
|
|
154
|
+
Start the dev server with `eve dev` and fetch the well-known document locally:
|
|
155
|
+
|
|
156
|
+
```sh
|
|
157
|
+
curl -i http://localhost:2000/.well-known/ucp
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Then fetch it from your deployment:
|
|
161
|
+
|
|
162
|
+
```sh
|
|
163
|
+
curl -i https://your_deployment_url_here/.well-known/ucp
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Expect a `200` with the profile JSON:
|
|
167
|
+
|
|
168
|
+
```http
|
|
169
|
+
HTTP/2 200
|
|
170
|
+
content-type: application/json
|
|
171
|
+
cache-control: public, max-age=300
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## What's not covered
|
|
175
|
+
|
|
176
|
+
Commerce operation semantics are author-owned: the checkout, cart, and order state machines; payment-handler execution; and request signing and verification.
|
|
177
|
+
|
|
178
|
+
## Read next
|
|
179
|
+
|
|
180
|
+
- [Channels overview](../channels/overview): The channel contract this builds on.
|
|
181
|
+
- [Custom channels](../channels/custom): The route helpers, CORS, and metadata this page uses.
|