eve 0.24.6 → 0.25.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 +21 -0
- package/dist/src/chunks/{use-eve-agent-6BO9gFVq.js → use-eve-agent-CQIeqmKc.js} +69 -64
- package/dist/src/chunks/{use-eve-agent-B1MJNRE-.js → use-eve-agent-Cy73lgA6.js} +69 -64
- package/dist/src/cli/commands/agent-instructions.js +1 -1
- package/dist/src/cli/commands/channels.js +1 -1
- package/dist/src/cli/commands/extension-build.d.ts +1 -1
- package/dist/src/cli/commands/extension-build.js +1 -1
- package/dist/src/client/output-schema.d.ts +0 -7
- package/dist/src/client/output-schema.js +1 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +56 -0
- package/dist/src/compiler/extension-compatibility.js +1 -0
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/context/build-dynamic-tools.js +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.d.ts +1 -1
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/discover/discover-agent.d.ts +29 -7
- package/dist/src/discover/discover-agent.js +1 -1
- package/dist/src/discover/extensions.d.ts +43 -8
- package/dist/src/discover/extensions.js +1 -1
- package/dist/src/discover/filesystem.d.ts +3 -1
- package/dist/src/discover/filesystem.js +1 -1
- package/dist/src/discover/named-source-directory.js +1 -1
- package/dist/src/discover/skills.js +1 -1
- package/dist/src/evals/autoevals-client.js +2 -2
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/sandbox/bindings/docker.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
- package/dist/src/execution/sandbox/bindings/microsandbox-templates.js +1 -1
- package/dist/src/execution/sandbox/development-cleanup.d.ts +1 -1
- package/dist/src/execution/sandbox/development-cleanup.js +1 -1
- package/dist/src/execution/sandbox/development-run.d.ts +0 -3
- package/dist/src/execution/sandbox/development-run.js +1 -1
- package/dist/src/execution/sandbox/ensure.js +1 -1
- package/dist/src/execution/subagent-tool.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/input-extraction.d.ts +10 -1
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/input-requests.d.ts +12 -2
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/messages.d.ts +8 -1
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/stale-input-responses.d.ts +26 -0
- package/dist/src/harness/stale-input-responses.js +3 -0
- package/dist/src/harness/step-hooks.d.ts +1 -12
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-call-input-errors.d.ts +11 -0
- package/dist/src/harness/tool-call-input-errors.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/workflow-sandbox.d.ts +1 -1
- package/dist/src/harness/workflow-sandbox.js +1 -1
- package/dist/src/internal/application/optional-package-install.d.ts +5 -0
- package/dist/src/internal/application/optional-package-install.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/schema-backed.js +1 -1
- package/dist/src/internal/authored-module-loader.d.ts +17 -0
- package/dist/src/internal/authored-module-loader.js +2 -2
- package/dist/src/internal/authored-module-map-loader.js +1 -1
- package/dist/src/internal/authored-package-boundary.d.ts +8 -0
- package/dist/src/internal/authored-package-boundary.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.d.ts +4 -0
- package/dist/src/internal/nitro/dev-runtime-source-snapshot.js +1 -1
- package/dist/src/internal/nitro/host/build-extension.d.ts +6 -21
- package/dist/src/internal/nitro/host/build-extension.js +2 -4
- package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/host/dev-workspace-extensions.d.ts +18 -0
- package/dist/src/internal/nitro/host/dev-workspace-extensions.js +1 -0
- package/dist/src/internal/nitro/host/extension-build-config.d.ts +18 -0
- package/dist/src/internal/nitro/host/extension-build-config.js +1 -0
- package/dist/src/internal/nitro/host/extension-capability-requirements.d.ts +10 -0
- package/dist/src/internal/nitro/host/extension-capability-requirements.js +1 -0
- package/dist/src/internal/nitro/host/extension-declarations.d.ts +10 -0
- package/dist/src/internal/nitro/host/extension-declarations.js +2 -0
- package/dist/src/internal/nitro/host/extension-distribution.d.ts +32 -0
- package/dist/src/internal/nitro/host/extension-distribution.js +3 -0
- package/dist/src/internal/nitro/host/extension-state-usage.d.ts +7 -0
- package/dist/src/internal/nitro/host/extension-state-usage.js +1 -0
- package/dist/src/internal/nitro/host/prepare-application-host.d.ts +5 -1
- package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
- package/dist/src/internal/nitro/host/start-development-server.js +2 -2
- package/dist/src/internal/nitro/host/types.d.ts +2 -0
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +63 -12
- package/dist/src/public/definitions/tool.d.ts +2 -2
- package/dist/src/public/hooks/index.d.ts +1 -1
- package/dist/src/public/tools/internal.js +1 -1
- package/dist/src/runtime/agent/mock-model-fixtures.js +2 -2
- package/dist/src/runtime/connections/openapi-client.js +1 -1
- package/dist/src/runtime/framework-tools/ask-question.d.ts +23 -9
- package/dist/src/runtime/framework-tools/ask-question.js +1 -1
- package/dist/src/runtime/framework-tools/bash.d.ts +10 -3
- package/dist/src/runtime/framework-tools/bash.js +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -1
- package/dist/src/runtime/framework-tools/final-output.d.ts +1 -1
- package/dist/src/runtime/framework-tools/final-output.js +1 -1
- package/dist/src/runtime/framework-tools/glob.d.ts +12 -3
- package/dist/src/runtime/framework-tools/glob.js +1 -1
- package/dist/src/runtime/framework-tools/grep.d.ts +16 -3
- package/dist/src/runtime/framework-tools/grep.js +1 -1
- package/dist/src/runtime/framework-tools/read-file.d.ts +13 -3
- package/dist/src/runtime/framework-tools/read-file.js +1 -1
- package/dist/src/runtime/framework-tools/skill.d.ts +5 -2
- package/dist/src/runtime/framework-tools/skill.js +1 -1
- package/dist/src/runtime/framework-tools/todo.d.ts +57 -10
- package/dist/src/runtime/framework-tools/todo.js +3 -3
- package/dist/src/runtime/framework-tools/web-fetch.d.ts +16 -3
- package/dist/src/runtime/framework-tools/web-fetch.js +1 -1
- package/dist/src/runtime/framework-tools/write-file.d.ts +9 -3
- package/dist/src/runtime/framework-tools/write-file.js +1 -1
- package/dist/src/runtime/loaders/compile-metadata.js +1 -1
- package/dist/src/runtime/loaders/manifest.js +1 -1
- package/dist/src/runtime/loaders/module-map.js +1 -1
- package/dist/src/runtime/resolve-tool.d.ts +4 -5
- package/dist/src/runtime/resolve-tool.js +1 -1
- package/dist/src/runtime/subagents/registry.d.ts +6 -3
- package/dist/src/runtime/subagents/registry.js +1 -1
- package/dist/src/runtime/tools/registry.js +1 -1
- package/dist/src/runtime/types.d.ts +7 -9
- package/dist/src/setup/boxes/deploy-project.d.ts +11 -1
- package/dist/src/setup/boxes/deploy-project.js +1 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/extension.js +2 -2
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/update/channels.js +1 -1
- package/dist/src/setup/scaffold/update/connections.js +1 -1
- package/dist/src/setup/vercel-project-framework.d.ts +4 -2
- package/dist/src/shared/extension-package-contract.d.ts +11 -0
- package/dist/src/shared/extension-package-contract.js +1 -0
- package/dist/src/shared/json.d.ts +4 -0
- package/dist/src/shared/json.js +1 -1
- package/dist/src/shared/tool-schema.d.ts +52 -0
- package/dist/src/shared/tool-schema.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +6 -0
- package/docs/extensions.md +22 -6
- package/docs/reference/cli.md +2 -2
- package/package.json +1 -1
- package/dist/src/internal/json-schema.d.ts +0 -1
- package/dist/src/internal/json-schema.js +0 -1
- package/dist/src/setup/boxes/reconcile-host-framework-preset.d.ts +0 -26
- package/dist/src/setup/boxes/reconcile-host-framework-preset.js +0 -1
- package/dist/src/shared/hook-definition.d.ts +0 -36
- package/dist/src/shared/hook-definition.js +0 -1
- package/dist/src/shared/json-schema.d.ts +0 -9
- package/dist/src/shared/json-schema.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DiscoverDiagnostic } from "#discover/diagnostics.js";
|
|
2
|
-
import { type AgentSourceManifest } from "#discover/manifest.js";
|
|
2
|
+
import { type AgentSourceManifest, type ExtensionSourceRef } from "#discover/manifest.js";
|
|
3
3
|
import { type ProjectSource } from "#discover/project-source.js";
|
|
4
4
|
/**
|
|
5
5
|
* Input for discovering the authored agent source graph from resolved roots.
|
|
@@ -21,12 +21,6 @@ interface DiscoverAgentInput {
|
|
|
21
21
|
* not resolve further extensions (transitive mounting is a non-goal).
|
|
22
22
|
*/
|
|
23
23
|
role?: "agent" | "extension";
|
|
24
|
-
/**
|
|
25
|
-
* The app's eve version, checked against each mounted extension's
|
|
26
|
-
* `peerDependencies.eve`. Defaults to the running eve's version; injectable
|
|
27
|
-
* for tests.
|
|
28
|
-
*/
|
|
29
|
-
eveVersion?: string;
|
|
30
24
|
}
|
|
31
25
|
/**
|
|
32
26
|
* Result of discovering one authored agent source graph.
|
|
@@ -40,4 +34,32 @@ interface DiscoverAgentResult {
|
|
|
40
34
|
* modules.
|
|
41
35
|
*/
|
|
42
36
|
export declare function discoverAgent(input: DiscoverAgentInput): Promise<DiscoverAgentResult>;
|
|
37
|
+
/**
|
|
38
|
+
* One extension mount discovered under `agent/extensions/`, in either the flat
|
|
39
|
+
* file form (`extensions/crm.ts`) or the directory form
|
|
40
|
+
* (`extensions/crm/extension.ts` with optional override slots).
|
|
41
|
+
*/
|
|
42
|
+
export interface ExtensionMountDescriptor {
|
|
43
|
+
/** Mount namespace prefixed onto every composed contribution. */
|
|
44
|
+
readonly namespace: string;
|
|
45
|
+
/** Module ref for the mount declaration the package specifier is read from. */
|
|
46
|
+
readonly mountRef: ExtensionSourceRef;
|
|
47
|
+
/**
|
|
48
|
+
* Absolute path to the mount directory when this is the directory form.
|
|
49
|
+
* Its override slots are discovered as an agent-shaped source. Absent for
|
|
50
|
+
* the flat file form.
|
|
51
|
+
*/
|
|
52
|
+
readonly overridesRoot?: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Discovers extension mount declarations without resolving or inspecting their
|
|
56
|
+
* package distributions. Development uses this before building local mounts.
|
|
57
|
+
*/
|
|
58
|
+
export declare function discoverExtensionMountDeclarations(input: {
|
|
59
|
+
readonly agentRoot: string;
|
|
60
|
+
readonly source?: ProjectSource;
|
|
61
|
+
}): Promise<{
|
|
62
|
+
diagnostics: DiscoverDiagnostic[];
|
|
63
|
+
mounts: ExtensionMountDescriptor[];
|
|
64
|
+
}>;
|
|
43
65
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{join,resolve}from"node:path";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS,classifyAgentRootEntry,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,DISCOVER_EXTENSION_SCHEDULE_UNSUPPORTED,locateExtensionMount,mountNamespace}from"#discover/extensions.js";import{createAgentSourceManifest,createModuleSourceRef}from"#discover/manifest.js";import{DISCOVER_CHANNELS_DIRECTORY_INVALID,DISCOVER_EXTENSIONS_DIRECTORY_INVALID,DISCOVER_HOOKS_DIRECTORY_INVALID,DISCOVER_TOOLS_DIRECTORY_INVALID,createChannelNameDiagnostic,createExtensionNameDiagnostic,createHookNameDiagnostic,createToolNameDiagnostic,createUnsupportedRootDirectoryDiagnostics,discoverFlatModuleSource,discoverInstructionsSource,discoverNamedSourceDirectory,readSortedDirectoryEntries}from"#discover/grammar.js";import{discoverConnectionSources}from"#discover/connections.js";import{discoverSubagents}from"#discover/discover-subagent.js";import{discoverLibSources}from"#discover/lib.js";import{discoverSandboxSource}from"#discover/sandbox.js";import{discoverScheduleSources}from"#discover/schedules.js";import{discoverSkills}from"#discover/skills.js";import{stripNpmPackageScope}from"#shared/package-name.js";async function discoverAgent(r){let a=r.source??createDiskProjectSource(),c=resolve(r.appRoot),l=resolve(r.agentRoot),d=r.role??`agent`,h=[],g=await tryReadPackageJsonName(a,c),_=await readSortedDirectoryEntries(a,l);h.push(...createUnsupportedRootDirectoryDiagnostics({classifyEntry:classifyAgentRootEntry,createUnsupportedDirectoryMessage(e){return`Ignoring unsupported directory "${e}/" in the agent root.`},rootEntries:_,rootPath:l}));let v=await discoverInstructionsSource({rootEntries:_,rootPath:l,source:a,required:d!==`extension`});h.push(...v.diagnostics);let y=discoverFlatModuleSource({rootEntries:_,rootPath:l,slotName:`agent`});h.push(...y.diagnostics);let b=await discoverNamedSourceDirectory({directoryName:`channels`,invalidDirectoryCode:DISCOVER_CHANNELS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(l,`channels`)}" to be a directory of authored channels.`,recursive:!0,rootEntries:_,rootPath:l,source:a,validateSegment:createChannelNameDiagnostic});h.push(...b.diagnostics);let x=await discoverLibSources({agentRoot:l,rootEntries:_,source:a});h.push(...x.diagnostics);let S=await discoverScheduleSources({agentRoot:l,rootEntries:_,source:a});h.push(...S.diagnostics);let C=await discoverConnectionSources({rootEntries:_,rootPath:l,source:a});h.push(...C.diagnostics);let w=await discoverSandboxSource({rootEntries:_,rootPath:l,source:a});if(h.push(...w.diagnostics),d===`extension`){y.module!==void 0&&h.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,message:`An extension may not declare agent config (agent.ts) — model, limits, and sandbox are the consuming agent's to own.`,sourcePath:join(l,y.module.logicalPath)})),w.sandbox!==null&&h.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,message:`An extension may not declare a sandbox — it is the consuming agent's to own.`,sourcePath:join(l,w.sandbox.logicalPath)}));let[t]=S.schedules;t!==void 0&&h.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_SCHEDULE_UNSUPPORTED,message:`An extension may not declare schedules — background scheduling runs on the consuming agent's deployment under its limits, so it is the consuming agent's to own.`,sourcePath:join(l,t.logicalPath)}))}let T=await discoverNamedSourceDirectory({directoryName:`tools`,invalidDirectoryCode:DISCOVER_TOOLS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(l,`tools`)}" to be a directory of authored tools.`,recursive:!0,rootEntries:_,rootPath:l,source:a,validateSegment:createToolNameDiagnostic});h.push(...T.diagnostics);let E=await discoverNamedSourceDirectory({directoryName:`hooks`,invalidDirectoryCode:DISCOVER_HOOKS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(l,`hooks`)}" to be a directory of authored hooks.`,recursive:!0,rootEntries:_,rootPath:l,source:a,validateSegment:createHookNameDiagnostic});h.push(...E.diagnostics);let D=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(l,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:_,rootPath:l,source:a,validateSegment:createExtensionNameDiagnostic});h.push(...D.diagnostics);let O=await discoverSkills({agentRoot:l,source:a});h.push(...O.diagnostics);let k=await discoverSubagents({agentRoot:l,appRoot:c,source:a});h.push(...k.diagnostics);let A=await collectExtensionMounts({agentRoot:l,fileMounts:D.sources,rootEntries:_,source:a});h.push(...A.diagnostics),h.push(...detectRootNamespaceCollisions({agentRoot:l,namespaces:A.mounts.map(e=>e.namespace),sources:[...T.sources,...C.connections,...O.skills,...S.schedules]}));let j=[];if(d!==`agent`)for(let t of A.mounts)h.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,message:`"${t.mountRef.logicalPath}" mounts an extension from inside an extension, which is not supported yet. Extensions cannot mount other extensions; remove the "extensions/" slot.`,sourcePath:join(l,t.mountRef.logicalPath)}));else for(let e of A.mounts){let t=await locateExtensionMount({source:a,agentRoot:l,appRoot:c,mount:e.mountRef,namespace:e.namespace});if(h.push(...t.diagnostics),t.location===void 0)continue;let n=await discoverAgent({agentRoot:t.location.sourceRoot,appRoot:t.location.packageRoot,source:a,role:`extension`});h.push(...n.diagnostics);let r;if(e.overridesRoot!==void 0){let t=await discoverAgent({agentRoot:e.overridesRoot,appRoot:c,source:a,role:`extension`});h.push(...t.diagnostics),r=t.manifest}let i={namespace:t.location.namespace,specifier:t.location.specifier,packageName:t.location.packageName,packageRoot:t.location.packageRoot,sourceRoot:t.location.sourceRoot,manifest:n.manifest};r!==void 0&&(i.overrides=r),j.push(i)}let M={agentRoot:l,appRoot:c,channels:b.sources,connections:C.connections,packageName:g,diagnostics:h,extensions:A.mounts.map(e=>e.mountRef),resolvedExtensions:j,hooks:E.sources,lib:x.lib,instructions:v.instructions,sandbox:w.sandbox,sandboxWorkspaces:w.sandboxWorkspace===null?[]:[w.sandboxWorkspace],schedules:S.schedules,skills:O.skills,tools:T.sources,subagents:k.subagents};return y.module!==void 0&&(M.configModule=y.module),{diagnostics:h,manifest:createAgentSourceManifest(M)}}async function discoverExtensionMountDeclarations(n){let r=n.source??createDiskProjectSource(),i=resolve(n.agentRoot),a=await readSortedDirectoryEntries(r,i),s=await discoverNamedSourceDirectory({directoryName:`extensions`,invalidDirectoryCode:DISCOVER_EXTENSIONS_DIRECTORY_INVALID,invalidDirectoryMessage:`Expected "${join(i,`extensions`)}" to be a directory of extension mounts.`,recursive:!1,rootEntries:a,rootPath:i,source:r,validateSegment:createExtensionNameDiagnostic}),c=await collectExtensionMounts({agentRoot:i,fileMounts:s.sources,rootEntries:a,source:r});return{diagnostics:[...s.diagnostics,...c.diagnostics],mounts:c.mounts}}async function collectExtensionMounts(t){let r=[],i=join(t.agentRoot,`extensions`),o=t.fileMounts.map(e=>({namespace:mountNamespace(e.logicalPath),mountRef:e})),s=new Set(o.map(e=>e.namespace)),u=t.rootEntries.find(e=>e.name===`extensions`),d=[],f=new Set;if(u?.isDirectory()===!0){let o=await readSortedDirectoryEntries(t.source,i);for(let c of o){if(!c.isDirectory())continue;let o=c.name,u=join(i,o),p=createExtensionNameDiagnostic(o,u);if(p!==null){r.push(p);continue}let m=discoverFlatModuleSource({rootEntries:await readSortedDirectoryEntries(t.source,u),rootPath:u,slotName:`extension`});if(r.push(...m.diagnostics),m.module===void 0){r.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,message:`Extension mount directory "extensions/${o}/" must declare its mount in "extension.ts" (or another supported module extension).`,sourcePath:u}));continue}s.has(o)&&f.add(o),d.push({namespace:o,mountRef:createModuleSourceRef({logicalPath:normalizeLogicalPath(join(`extensions`,o,m.module.logicalPath))}),overridesRoot:u})}}for(let e of f)r.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,message:`Extension namespace "${e}" is claimed by both a file mount ("extensions/${e}.ts") and a directory mount ("extensions/${e}/"). Keep only one.`,sourcePath:i}));return{diagnostics:r,mounts:[...o,...d].filter(e=>!f.has(e.namespace))}}function detectRootNamespaceCollisions(t){if(t.namespaces.length===0)return[];let r=[];for(let i of t.sources){let a=rootContributionName(i.logicalPath),o=t.namespaces.find(e=>a.startsWith(`${e}__`));o!==void 0&&r.push(createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,message:`"${i.logicalPath}" uses the "${o}__" prefix reserved for the mounted extension "${o}". Override an extension's contributions inside its mount directory ("extensions/${o}/…"), not at the agent root.`,sourcePath:join(t.agentRoot,i.logicalPath)}))}return r}function rootContributionName(e){let t=e.slice(e.indexOf(`/`)+1),n=t.split(`/`)[0]??t;for(let e of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(n.toLowerCase().endsWith(e))return n.slice(0,n.length-e.length);return n}async function tryReadPackageJsonName(t,n){try{let r=join(n,`package.json`),i=JSON.parse(await t.readTextFile(r)).name;return typeof i!=`string`||i.length===0?void 0:stripNpmPackageScope(i)}catch{return}}export{discoverAgent,discoverExtensionMountDeclarations};
|
|
@@ -32,11 +32,15 @@ export declare const DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT = "discover/exten
|
|
|
32
32
|
*/
|
|
33
33
|
export declare const DISCOVER_EXTENSION_PACKAGE_INVALID = "discover/extension-package-invalid";
|
|
34
34
|
/**
|
|
35
|
-
* Emitted when
|
|
36
|
-
*
|
|
37
|
-
* built for.
|
|
35
|
+
* Emitted when an extension distribution's compatibility manifest is missing
|
|
36
|
+
* or malformed.
|
|
38
37
|
*/
|
|
39
|
-
export declare const
|
|
38
|
+
export declare const DISCOVER_EXTENSION_COMPATIBILITY_INVALID = "discover/extension-compatibility-invalid";
|
|
39
|
+
/**
|
|
40
|
+
* Emitted when this eve cannot consume one of the extension capabilities the
|
|
41
|
+
* distribution requires.
|
|
42
|
+
*/
|
|
43
|
+
export declare const DISCOVER_EXTENSION_CAPABILITY_INCOMPATIBLE = "discover/extension-capability-incompatible";
|
|
40
44
|
/**
|
|
41
45
|
* Emitted when an extension source tree declares agent-level config (`agent.ts`),
|
|
42
46
|
* which is the consuming agent's to own.
|
|
@@ -65,9 +69,28 @@ export interface ExtensionMountLocation {
|
|
|
65
69
|
readonly packageName: string;
|
|
66
70
|
/** Absolute path to the resolved package root. */
|
|
67
71
|
readonly packageRoot: string;
|
|
68
|
-
/** Absolute path to the extension's agent-shaped
|
|
72
|
+
/** Absolute path to the extension's agent-shaped distribution root. */
|
|
69
73
|
readonly sourceRoot: string;
|
|
70
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Package roots resolved from one extension mount before its distribution is
|
|
77
|
+
* inspected. Development uses this to build a mounted workspace extension
|
|
78
|
+
* before the consumer requires its dist tree to exist.
|
|
79
|
+
*/
|
|
80
|
+
export interface ExtensionMountPackageLocation {
|
|
81
|
+
/** Mount namespace derived from the mount filename. */
|
|
82
|
+
readonly namespace: string;
|
|
83
|
+
/** Package specifier read from the mount declaration. */
|
|
84
|
+
readonly specifier: string;
|
|
85
|
+
/** Package name from the resolved package manifest. */
|
|
86
|
+
readonly packageName: string;
|
|
87
|
+
/** Absolute path to the resolved package root. */
|
|
88
|
+
readonly packageRoot: string;
|
|
89
|
+
/** Absolute authoring root when the package publishes a source-backed contract. */
|
|
90
|
+
readonly authoredSourceRoot?: string;
|
|
91
|
+
/** Absolute path to the agent-shaped distribution root. */
|
|
92
|
+
readonly distRoot: string;
|
|
93
|
+
}
|
|
71
94
|
/**
|
|
72
95
|
* Derives the mount namespace from an `extensions/<name>.<ext>` logical path.
|
|
73
96
|
*/
|
|
@@ -89,7 +112,7 @@ export declare function packageStateNamespace(packageName: string): string;
|
|
|
89
112
|
* Resolves one extension mount to its package and agent-shaped source root
|
|
90
113
|
* without importing the mount module. Reads the mount source text to extract
|
|
91
114
|
* the package specifier, resolves the package, and reads
|
|
92
|
-
* `package.json#eve.extension` for the
|
|
115
|
+
* `package.json#eve.extension.dist` for the agent-shaped distribution root.
|
|
93
116
|
*/
|
|
94
117
|
export declare function locateExtensionMount(input: {
|
|
95
118
|
readonly source: ProjectSource;
|
|
@@ -101,9 +124,21 @@ export declare function locateExtensionMount(input: {
|
|
|
101
124
|
* the file and directory mount forms name it at different path positions.
|
|
102
125
|
*/
|
|
103
126
|
readonly namespace: string;
|
|
104
|
-
/** The app's eve version, checked against the extension's `peerDependencies.eve`. */
|
|
105
|
-
readonly eveVersion: string;
|
|
106
127
|
}): Promise<{
|
|
107
128
|
location?: ExtensionMountLocation;
|
|
108
129
|
diagnostics: DiscoverDiagnostic[];
|
|
109
130
|
}>;
|
|
131
|
+
/**
|
|
132
|
+
* Resolves one extension mount through its package manifest without requiring
|
|
133
|
+
* a built distribution or compatibility manifest.
|
|
134
|
+
*/
|
|
135
|
+
export declare function locateExtensionMountPackage(input: {
|
|
136
|
+
readonly source: ProjectSource;
|
|
137
|
+
readonly agentRoot: string;
|
|
138
|
+
readonly appRoot: string;
|
|
139
|
+
readonly mount: ExtensionSourceRef;
|
|
140
|
+
readonly namespace: string;
|
|
141
|
+
}): Promise<{
|
|
142
|
+
location?: ExtensionMountPackageLocation;
|
|
143
|
+
diagnostics: DiscoverDiagnostic[];
|
|
144
|
+
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,isAbsolute,join,resolve}from"node:path";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";import
|
|
1
|
+
import{dirname,isAbsolute,join,resolve}from"node:path";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS}from"#discover/filesystem.js";import{EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest}from"#compiler/extension-compatibility.js";import{parseExtensionMountSpecifier}from"#discover/extension-specifier.js";import{parseExtensionPackageRoots}from"#shared/extension-package-contract.js";const DISCOVER_EXTENSION_MOUNT_UNRESOLVED=`discover/extension-mount-unresolved`,DISCOVER_EXTENSION_MOUNT_AMBIGUOUS=`discover/extension-mount-ambiguous`,DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION=`discover/extension-mount-missing-declaration`,DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED=`discover/extension-nested-mount-unsupported`,DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT=`discover/extension-override-outside-mount`,DISCOVER_EXTENSION_PACKAGE_INVALID=`discover/extension-package-invalid`,DISCOVER_EXTENSION_COMPATIBILITY_INVALID=`discover/extension-compatibility-invalid`,DISCOVER_EXTENSION_CAPABILITY_INCOMPATIBLE=`discover/extension-capability-incompatible`,DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED=`discover/extension-agent-config-unsupported`,DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED=`discover/extension-sandbox-unsupported`,DISCOVER_EXTENSION_SCHEDULE_UNSUPPORTED=`discover/extension-schedule-unsupported`;function mountNamespace(e){let t=e.slice(e.lastIndexOf(`/`)+1);for(let e of SUPPORTED_AUTHORED_MODULE_FILE_EXTENSIONS)if(t.toLowerCase().endsWith(e))return t.slice(0,t.length-e.length);return t}function mountRefNamespace(e){let t=e.replace(/^extensions\//,``),n=t.indexOf(`/`);return n===-1?mountNamespace(e):t.slice(0,n)}function packageStateNamespace(e){return e.replace(/^@/,``).replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`extension`}async function locateExtensionMount(e){let t=await locateExtensionMountPackage(e);if(t.location===void 0)return{diagnostics:t.diagnostics};let{location:r}=t,a=join(r.distRoot,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),l;try{l=parseExtensionCompatibilityManifest(await e.source.readTextFile(a),a)}catch(e){return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_COMPATIBILITY_INVALID,message:`Extension "${r.packageName}" has no valid compatibility manifest at "${a}". Rebuild or reinstall the extension. ${e instanceof Error?e.message:String(e)}`,sourcePath:a})]}}let u=findUnsupportedExtensionCapabilities(l);return u.length>0?{diagnostics:u.map(e=>createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_CAPABILITY_INCOMPATIBLE,message:`Extension "${r.packageName}" requires ${e.capability} contract v${e.requiredVersion}, but this eve supports ${e.capability} contract ${formatSupportedVersions(e.supportedVersions)}. Upgrade eve or install an extension release that requires a supported ${e.capability} contract.`,sourcePath:a}))}:{location:{namespace:r.namespace,specifier:r.specifier,packageName:r.packageName,packageRoot:r.packageRoot,sourceRoot:r.distRoot},diagnostics:[]}}async function locateExtensionMountPackage(t){let a=join(t.agentRoot,t.mount.logicalPath),{namespace:o}=t,s;try{s=await t.source.readTextFile(a)}catch{return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_UNRESOLVED,message:`Could not read extension mount "${t.mount.logicalPath}".`,sourcePath:a})]}}let c=parseExtensionMountSpecifier(s);if(c===null)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_UNRESOLVED,message:`Extension mount "${t.mount.logicalPath}" must default-export a mounted extension, e.g. \`export default crm({ ... })\` or \`export { default } from "@acme/crm"\`.`,sourcePath:a})]};let d=await resolvePackageRoot({source:t.source,appRoot:t.appRoot,mountDirectory:dirname(a),specifier:c});if(d===null)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_MOUNT_UNRESOLVED,message:`Could not resolve extension package "${c}" mounted by "${t.mount.logicalPath}".`,sourcePath:a})]};let f=join(d,`package.json`),p;try{p=JSON.parse(await t.source.readTextFile(f))}catch{return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_PACKAGE_INVALID,message:`Extension package "${c}" has no readable package.json at "${f}".`,sourcePath:f})]}}let m=parseExtensionPackageRoots(p.eve?.extension);return m===null?{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_EXTENSION_PACKAGE_INVALID,message:`Package "${c}" is not an eve extension: its package.json must declare \`eve.extension.dist\`.`,sourcePath:f})]}:{location:{namespace:o,specifier:c,packageName:typeof p.name==`string`&&p.name.length>0?p.name:c,packageRoot:d,...m.source===void 0?{}:{authoredSourceRoot:resolve(d,m.source)},distRoot:resolve(d,m.dist)},diagnostics:[]}}function formatSupportedVersions(e){return e.length===0?`versions: none`:`versions: ${e.map(e=>`v${e}`).join(`, `)}`}async function resolvePackageRoot(i){if(i.specifier.startsWith(`.`)){let e=resolve(i.mountDirectory,i.specifier);return await hasPackageJson(i.source,e)?e:null}if(isAbsolute(i.specifier))return await hasPackageJson(i.source,i.specifier)?i.specifier:null;let a=bareSpecifierPackagePath(i.specifier),o=resolve(i.appRoot);for(;;){let t=join(o,`node_modules`,a);if(await hasPackageJson(i.source,t))return t;let r=dirname(o);if(r===o)return null;o=r}}function bareSpecifierPackagePath(e){let t=e.split(`/`);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]??e}async function hasPackageJson(e,t){return await e.stat(join(t,`package.json`))===`file`}export{DISCOVER_EXTENSION_AGENT_CONFIG_UNSUPPORTED,DISCOVER_EXTENSION_CAPABILITY_INCOMPATIBLE,DISCOVER_EXTENSION_COMPATIBILITY_INVALID,DISCOVER_EXTENSION_MOUNT_AMBIGUOUS,DISCOVER_EXTENSION_MOUNT_MISSING_DECLARATION,DISCOVER_EXTENSION_MOUNT_UNRESOLVED,DISCOVER_EXTENSION_NESTED_MOUNT_UNSUPPORTED,DISCOVER_EXTENSION_OVERRIDE_OUTSIDE_MOUNT,DISCOVER_EXTENSION_PACKAGE_INVALID,DISCOVER_EXTENSION_SANDBOX_UNSUPPORTED,DISCOVER_EXTENSION_SCHEDULE_UNSUPPORTED,locateExtensionMount,locateExtensionMountPackage,mountNamespace,mountRefNamespace,packageStateNamespace};
|
|
@@ -27,7 +27,7 @@ export type SkillPackageEntryKind = "skill-assets-directory" | "skill-markdown"
|
|
|
27
27
|
/**
|
|
28
28
|
* Classified top-level entry inside `skills/`.
|
|
29
29
|
*/
|
|
30
|
-
export type SkillsDirectoryEntryKind = "flat-skill-markdown" | "flat-skill-module" | "skill-package-directory" | "unknown";
|
|
30
|
+
export type SkillsDirectoryEntryKind = "flat-skill-markdown" | "flat-skill-module" | "ignored-declaration" | "skill-package-directory" | "unknown";
|
|
31
31
|
/**
|
|
32
32
|
* Returns the normalized entry type for a Node filesystem dirent.
|
|
33
33
|
*/
|
|
@@ -61,6 +61,8 @@ export declare function normalizeLogicalPath(input: string): string;
|
|
|
61
61
|
* extension.
|
|
62
62
|
*/
|
|
63
63
|
export declare function getSupportedModuleBaseName(name: string): string | null;
|
|
64
|
+
/** Returns whether a filename is a TypeScript declaration module. */
|
|
65
|
+
export declare function isTypeScriptDeclarationFileName(name: string): boolean;
|
|
64
66
|
/**
|
|
65
67
|
* Returns whether the file name matches one supported authored module basename.
|
|
66
68
|
*/
|
|
@@ -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===`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(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){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 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,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([`.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===`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{join}from"node:path";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{getDirectoryEntryType,getSupportedModuleBaseName,normalizeLogicalPath}from"#discover/filesystem.js";import{createModuleSourceRef}from"#discover/manifest.js";import{createModuleSlotCollisionDiagnostic,createSlotCollisionDiagnostic,readSortedDirectoryEntries}from"#discover/grammar.js";import{collectNamedSlotCandidates}from"#discover/slots.js";import{discoverMarkdownSource}from"#discover/markdown.js";async function discoverNamedSourceDirectory(n){let r=join(n.rootPath,n.directoryName),i=n.rootEntries.find(e=>e.name===n.directoryName);if(i===void 0)return{diagnostics:[],sources:[]};if(!i.isDirectory())return{diagnostics:[createDiscoverErrorDiagnostic({code:n.invalidDirectoryCode,message:n.invalidDirectoryMessage,sourcePath:r})],sources:[]};let a=[],o=[];return await walkNamedSourceDirectory({allowMarkdown:n.allowMarkdown===!0,diagnostics:a,markdownLowerer:n.allowMarkdown===!0?n.markdownLowerer:void 0,projectSource:n.source,recursive:n.recursive,relativeDirectory:n.directoryName,rootDirectoryPath:r,sources:o,subdirectoryRelative:``,unsupportedEntryCode:n.unsupportedEntryCode,unsupportedEntryMessage:n.unsupportedEntryMessage,unsupportedFileCode:n.unsupportedFileCode,unsupportedFileMessage:n.unsupportedFileMessage,validateSegment:n.validateSegment}),{diagnostics:a,sources:o}}async function walkNamedSourceDirectory(t){let n=t.subdirectoryRelative===``?t.rootDirectoryPath:join(t.rootDirectoryPath,t.subdirectoryRelative),r=await readSortedDirectoryEntries(t.projectSource,n);t.recursive&&await walkSubdirectories(t,r,n),(t.unsupportedFileCode!==void 0||t.unsupportedEntryCode!==void 0)&&emitUnsupportedLeafDiagnostics(t,r,n),await collectLeafSources(t,r,n)}async function walkSubdirectories(t,n,r){for(let i of n){if(!i.isDirectory())continue;let n=join(r,i.name);if(t.validateSegment!==void 0){let e=t.validateSegment(i.name,n);if(e!==null){t.diagnostics.push(e);continue}}await walkNamedSourceDirectory({allowMarkdown:t.allowMarkdown,diagnostics:t.diagnostics,markdownLowerer:t.markdownLowerer,projectSource:t.projectSource,recursive:t.recursive,relativeDirectory:t.relativeDirectory,rootDirectoryPath:t.rootDirectoryPath,sources:t.sources,subdirectoryRelative:t.subdirectoryRelative===``?i.name:join(t.subdirectoryRelative,i.name),unsupportedEntryCode:t.unsupportedEntryCode,unsupportedEntryMessage:t.unsupportedEntryMessage,unsupportedFileCode:t.unsupportedFileCode,unsupportedFileMessage:t.unsupportedFileMessage,validateSegment:t.validateSegment})}}function emitUnsupportedLeafDiagnostics(
|
|
1
|
+
import{join}from"node:path";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{getDirectoryEntryType,getSupportedModuleBaseName,isTypeScriptDeclarationFileName,normalizeLogicalPath}from"#discover/filesystem.js";import{createModuleSourceRef}from"#discover/manifest.js";import{createModuleSlotCollisionDiagnostic,createSlotCollisionDiagnostic,readSortedDirectoryEntries}from"#discover/grammar.js";import{collectNamedSlotCandidates}from"#discover/slots.js";import{discoverMarkdownSource}from"#discover/markdown.js";async function discoverNamedSourceDirectory(n){let r=join(n.rootPath,n.directoryName),i=n.rootEntries.find(e=>e.name===n.directoryName);if(i===void 0)return{diagnostics:[],sources:[]};if(!i.isDirectory())return{diagnostics:[createDiscoverErrorDiagnostic({code:n.invalidDirectoryCode,message:n.invalidDirectoryMessage,sourcePath:r})],sources:[]};let a=[],o=[];return await walkNamedSourceDirectory({allowMarkdown:n.allowMarkdown===!0,diagnostics:a,markdownLowerer:n.allowMarkdown===!0?n.markdownLowerer:void 0,projectSource:n.source,recursive:n.recursive,relativeDirectory:n.directoryName,rootDirectoryPath:r,sources:o,subdirectoryRelative:``,unsupportedEntryCode:n.unsupportedEntryCode,unsupportedEntryMessage:n.unsupportedEntryMessage,unsupportedFileCode:n.unsupportedFileCode,unsupportedFileMessage:n.unsupportedFileMessage,validateSegment:n.validateSegment}),{diagnostics:a,sources:o}}async function walkNamedSourceDirectory(t){let n=t.subdirectoryRelative===``?t.rootDirectoryPath:join(t.rootDirectoryPath,t.subdirectoryRelative),r=await readSortedDirectoryEntries(t.projectSource,n);t.recursive&&await walkSubdirectories(t,r,n),(t.unsupportedFileCode!==void 0||t.unsupportedEntryCode!==void 0)&&emitUnsupportedLeafDiagnostics(t,r,n),await collectLeafSources(t,r,n)}async function walkSubdirectories(t,n,r){for(let i of n){if(!i.isDirectory())continue;let n=join(r,i.name);if(t.validateSegment!==void 0){let e=t.validateSegment(i.name,n);if(e!==null){t.diagnostics.push(e);continue}}await walkNamedSourceDirectory({allowMarkdown:t.allowMarkdown,diagnostics:t.diagnostics,markdownLowerer:t.markdownLowerer,projectSource:t.projectSource,recursive:t.recursive,relativeDirectory:t.relativeDirectory,rootDirectoryPath:t.rootDirectoryPath,sources:t.sources,subdirectoryRelative:t.subdirectoryRelative===``?i.name:join(t.subdirectoryRelative,i.name),unsupportedEntryCode:t.unsupportedEntryCode,unsupportedEntryMessage:t.unsupportedEntryMessage,unsupportedFileCode:t.unsupportedFileCode,unsupportedFileMessage:t.unsupportedFileMessage,validateSegment:t.validateSegment})}}function emitUnsupportedLeafDiagnostics(a,o,s){for(let c of o){let o=getDirectoryEntryType(c),l=join(s,c.name);if(o===`directory`)continue;if(o===`other`){a.unsupportedEntryCode!==void 0&&a.diagnostics.push(createDiscoverErrorDiagnostic({code:a.unsupportedEntryCode,message:a.unsupportedEntryMessage?.(l,a.relativeDirectory)??`Expected "${l}" to be a regular file or directory within "${a.relativeDirectory}/".`,sourcePath:l}));continue}if(a.unsupportedFileCode===void 0||isTypeScriptDeclarationFileName(c.name))continue;let u=getSupportedModuleBaseName(c.name)!==null,d=a.allowMarkdown&&c.name.endsWith(`.md`);u||d||a.diagnostics.push(createDiscoverErrorDiagnostic({code:a.unsupportedFileCode,message:a.unsupportedFileMessage?.(l,a.relativeDirectory)??`Expected "${l}" to be a supported authored source within "${a.relativeDirectory}/".`,sourcePath:l}))}}async function collectLeafSources(t,n,r){for(let i of collectNamedSlotCandidates(n,{allowMarkdown:t.allowMarkdown,allowModules:!0})){let n=t.subdirectoryRelative===``?i.slotName:join(t.subdirectoryRelative,i.slotName),l=normalizeLogicalPath(join(t.relativeDirectory,n));if(t.validateSegment!==void 0){let n=i.markdownFileName??i.moduleFileNames[0]??i.slotName,a=t.validateSegment(i.slotName,join(r,n));if(a!==null){t.diagnostics.push(a);continue}}if(i.markdownFileName!==void 0&&i.moduleFileNames.length>0){t.diagnostics.push(createSlotCollisionDiagnostic(r,l,[i.markdownFileName,...i.moduleFileNames]));continue}if(i.moduleFileNames.length>1){t.diagnostics.push(createModuleSlotCollisionDiagnostic(r,l,i.moduleFileNames));continue}if(i.markdownFileName!==void 0){let n=t.subdirectoryRelative===``?i.markdownFileName:join(t.subdirectoryRelative,i.markdownFileName),r=normalizeLogicalPath(join(t.relativeDirectory,n));if(t.markdownLowerer===void 0)continue;let o=await discoverMarkdownSource({logicalPath:r,lower:t.markdownLowerer,source:t.projectSource,sourcePath:join(t.rootDirectoryPath,n)});t.sources.push(o);continue}let[u]=i.moduleFileNames;if(u===void 0)continue;let f=t.subdirectoryRelative===``?u:join(t.subdirectoryRelative,u);t.sources.push(createModuleSourceRef({logicalPath:normalizeLogicalPath(join(t.relativeDirectory,f))}))}}export{discoverNamedSourceDirectory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{classifySkillPackageEntry,classifySkillsDirectoryEntry,getDirectoryEntryType,getSupportedModuleBaseName,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{createModuleSourceRef,createPathDerivedSourceId,createSkillPackageSourceRef}from"#discover/manifest.js";import{readSortedDirectoryEntries}from"#discover/grammar.js";import{lowerSkillMarkdown}from"#internal/helpers/markdown.js";const DISCOVER_SKILLS_DIRECTORY_INVALID=`discover/skills-directory-invalid`,DISCOVER_SKILL_COLLISION=`discover/skill-collision`,DISCOVER_SKILL_ENTRY_NOT_DIRECTORY=`discover/skill-entry-not-directory`,DISCOVER_SKILL_FRONTMATTER_INVALID=`discover/skill-frontmatter-invalid`,DISCOVER_SKILL_MARKDOWN_MISSING=`discover/skill-markdown-missing`;async function discoverSkills(r){let a=r.source??createDiskProjectSource(),o=resolve(r.agentRoot),c=resolve(r.skillsDirectoryPath??join(o,`skills`)),l=normalizeLogicalPath(r.skillsLogicalPath??relative(o,c)),u=await a.stat(c);if(u===`missing`)return{diagnostics:[],skills:[]};if(u!==`directory`)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILLS_DIRECTORY_INVALID,message:`Expected "${c}" to be a directory of authored skills.`,sourcePath:c})],skills:[]};let d=[],f=new Set,p=new Map,m=await readSortedDirectoryEntries(a,c);for(let t of m){let n=await discoverOneSkill({entryName:t.name,entryType:getDirectoryEntryType(t),skillsDirectoryPath:c,skillsLogicalPath:l,source:a});if(d.push(...n.diagnostics),n.skill===null||n.skillId===null||f.has(n.skillId))continue;let r=p.get(n.skillId);if(r!==void 0){d.push(createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_COLLISION,message:`Found conflicting authored skill sources for "${n.skillId}": "${r.logicalPath}" and "${n.logicalPath}".`,sourcePath:join(c,n.skillId)})),f.add(n.skillId),p.delete(n.skillId);continue}p.set(n.skillId,{logicalPath:n.logicalPath,skill:n.skill})}return{diagnostics:d,skills:[...p.values()].map(e=>e.skill)}}async function discoverOneSkill(t){let n=join(t.skillsDirectoryPath,t.entryName);switch(classifySkillsDirectoryEntry(t.entryName,t.entryType)){case`skill-package-directory`:return discoverPackagedSkill({logicalSkillsPath:t.skillsLogicalPath,skillId:t.entryName,skillRootPath:n,source:t.source});case`flat-skill-markdown`:return discoverFlatMarkdownSkill({logicalSkillsPath:t.skillsLogicalPath,skillFileName:t.entryName,skillFilePath:n,source:t.source});case`flat-skill-module`:return discoverFlatModuleSkill({logicalSkillsPath:t.skillsLogicalPath,skillFileName:t.entryName});default:return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_ENTRY_NOT_DIRECTORY,message:`Expected "${n}" to be a skill directory containing SKILL.md or a flat ".md", ".ts", ".cts", ".mts", ".js", ".cjs", or ".mjs" skill file.`,sourcePath:n})],logicalPath:normalizeLogicalPath(join(t.skillsLogicalPath,t.entryName)),skill:null,skillId:null}}}async function discoverPackagedSkill(t){let n=(await readSortedDirectoryEntries(t.source,t.skillRootPath)).find(e=>e.isFile()&&e.name.toLowerCase()===`skill.md`)?.name,r=join(t.skillRootPath,n??`SKILL.md`),a=normalizeLogicalPath(join(t.logicalSkillsPath,t.skillId,n??`SKILL.md`));if(n===void 0)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_MARKDOWN_MISSING,message:`Expected "${r}" to exist for the "${t.skillId}" skill.`,sourcePath:t.skillRootPath})],logicalPath:a,skill:null,skillId:null};let o;try{o=lowerSkillMarkdown(await t.source.readTextFile(r))}catch(e){return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_FRONTMATTER_INVALID,message:formatSkillDiscoveryError(r,e),sourcePath:r})],logicalPath:a,skill:null,skillId:null}}let s=await discoverSkillPackagePaths(t.source,t.skillRootPath),c={description:o.description,logicalPath:a,markdown:o.markdown,name:t.skillId,rootPath:t.skillRootPath,skillFilePath:r,skillId:t.skillId,sourceId:createPathDerivedSourceId(a)};return s.assetsPath!==void 0&&(c.assetsPath=s.assetsPath),o.license!==void 0&&(c.license=o.license),o.metadata!==void 0&&(c.metadata=o.metadata),s.referencesPath!==void 0&&(c.referencesPath=s.referencesPath),s.scriptsPath!==void 0&&(c.scriptsPath=s.scriptsPath),{diagnostics:[],logicalPath:a,skill:createSkillPackageSourceRef(c),skillId:t.skillId}}async function discoverFlatMarkdownSkill(t){let n=stripMarkdownExtension(t.skillFileName),r=normalizeLogicalPath(join(t.logicalSkillsPath,t.skillFileName)),a;try{a=lowerSkillMarkdown(await t.source.readTextFile(t.skillFilePath),{slug:n})}catch(e){return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_FRONTMATTER_INVALID,message:formatSkillDiscoveryError(t.skillFilePath,e),sourcePath:t.skillFilePath})],logicalPath:r,skill:null,skillId:null}}return{diagnostics:[],logicalPath:r,skill:{definition:a,sourceKind:`markdown`,logicalPath:r,sourceId:createPathDerivedSourceId(r)},skillId:n}}async function discoverFlatModuleSkill(t){let n=getSupportedModuleBaseName(t.skillFileName),r=normalizeLogicalPath(join(t.logicalSkillsPath,t.skillFileName));return n===null?{diagnostics:[],logicalPath:r,skill:null,skillId:null}:{diagnostics:[],logicalPath:r,skill:createModuleSourceRef({logicalPath:r}),skillId:n}}async function discoverSkillPackagePaths(t,n){let r=await t.readDirectory(n),i={};for(let t of r)if(t.isDirectory())switch(classifySkillPackageEntry(t.name,getDirectoryEntryType(t))){case`skill-assets-directory`:i.assetsPath=join(n,t.name);break;case`skill-references-directory`:i.referencesPath=join(n,t.name);break;case`skill-scripts-directory`:i.scriptsPath=join(n,t.name);break;default:break}return i}function formatSkillDiscoveryError(e,t){return`Invalid authored skill frontmatter in "${e}": ${toErrorMessage(t)}`}function stripMarkdownExtension(e){return e.toLowerCase().endsWith(`.md`)?e.slice(0,-3):e}export{DISCOVER_SKILLS_DIRECTORY_INVALID,DISCOVER_SKILL_COLLISION,DISCOVER_SKILL_ENTRY_NOT_DIRECTORY,DISCOVER_SKILL_FRONTMATTER_INVALID,DISCOVER_SKILL_MARKDOWN_MISSING,discoverSkills};
|
|
1
|
+
import{join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{createDiscoverErrorDiagnostic}from"#discover/diagnostics.js";import{classifySkillPackageEntry,classifySkillsDirectoryEntry,getDirectoryEntryType,getSupportedModuleBaseName,normalizeLogicalPath}from"#discover/filesystem.js";import{createDiskProjectSource}from"#discover/project-source.js";import{createModuleSourceRef,createPathDerivedSourceId,createSkillPackageSourceRef}from"#discover/manifest.js";import{readSortedDirectoryEntries}from"#discover/grammar.js";import{lowerSkillMarkdown}from"#internal/helpers/markdown.js";const DISCOVER_SKILLS_DIRECTORY_INVALID=`discover/skills-directory-invalid`,DISCOVER_SKILL_COLLISION=`discover/skill-collision`,DISCOVER_SKILL_ENTRY_NOT_DIRECTORY=`discover/skill-entry-not-directory`,DISCOVER_SKILL_FRONTMATTER_INVALID=`discover/skill-frontmatter-invalid`,DISCOVER_SKILL_MARKDOWN_MISSING=`discover/skill-markdown-missing`;async function discoverSkills(r){let a=r.source??createDiskProjectSource(),o=resolve(r.agentRoot),c=resolve(r.skillsDirectoryPath??join(o,`skills`)),l=normalizeLogicalPath(r.skillsLogicalPath??relative(o,c)),u=await a.stat(c);if(u===`missing`)return{diagnostics:[],skills:[]};if(u!==`directory`)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILLS_DIRECTORY_INVALID,message:`Expected "${c}" to be a directory of authored skills.`,sourcePath:c})],skills:[]};let d=[],f=new Set,p=new Map,m=await readSortedDirectoryEntries(a,c);for(let t of m){let n=await discoverOneSkill({entryName:t.name,entryType:getDirectoryEntryType(t),skillsDirectoryPath:c,skillsLogicalPath:l,source:a});if(d.push(...n.diagnostics),n.skill===null||n.skillId===null||f.has(n.skillId))continue;let r=p.get(n.skillId);if(r!==void 0){d.push(createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_COLLISION,message:`Found conflicting authored skill sources for "${n.skillId}": "${r.logicalPath}" and "${n.logicalPath}".`,sourcePath:join(c,n.skillId)})),f.add(n.skillId),p.delete(n.skillId);continue}p.set(n.skillId,{logicalPath:n.logicalPath,skill:n.skill})}return{diagnostics:d,skills:[...p.values()].map(e=>e.skill)}}async function discoverOneSkill(t){let n=join(t.skillsDirectoryPath,t.entryName);switch(classifySkillsDirectoryEntry(t.entryName,t.entryType)){case`skill-package-directory`:return discoverPackagedSkill({logicalSkillsPath:t.skillsLogicalPath,skillId:t.entryName,skillRootPath:n,source:t.source});case`flat-skill-markdown`:return discoverFlatMarkdownSkill({logicalSkillsPath:t.skillsLogicalPath,skillFileName:t.entryName,skillFilePath:n,source:t.source});case`flat-skill-module`:return discoverFlatModuleSkill({logicalSkillsPath:t.skillsLogicalPath,skillFileName:t.entryName});case`ignored-declaration`:return{diagnostics:[],logicalPath:normalizeLogicalPath(join(t.skillsLogicalPath,t.entryName)),skill:null,skillId:null};default:return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_ENTRY_NOT_DIRECTORY,message:`Expected "${n}" to be a skill directory containing SKILL.md or a flat ".md", ".ts", ".cts", ".mts", ".js", ".cjs", or ".mjs" skill file.`,sourcePath:n})],logicalPath:normalizeLogicalPath(join(t.skillsLogicalPath,t.entryName)),skill:null,skillId:null}}}async function discoverPackagedSkill(t){let n=(await readSortedDirectoryEntries(t.source,t.skillRootPath)).find(e=>e.isFile()&&e.name.toLowerCase()===`skill.md`)?.name,r=join(t.skillRootPath,n??`SKILL.md`),a=normalizeLogicalPath(join(t.logicalSkillsPath,t.skillId,n??`SKILL.md`));if(n===void 0)return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_MARKDOWN_MISSING,message:`Expected "${r}" to exist for the "${t.skillId}" skill.`,sourcePath:t.skillRootPath})],logicalPath:a,skill:null,skillId:null};let o;try{o=lowerSkillMarkdown(await t.source.readTextFile(r))}catch(e){return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_FRONTMATTER_INVALID,message:formatSkillDiscoveryError(r,e),sourcePath:r})],logicalPath:a,skill:null,skillId:null}}let s=await discoverSkillPackagePaths(t.source,t.skillRootPath),c={description:o.description,logicalPath:a,markdown:o.markdown,name:t.skillId,rootPath:t.skillRootPath,skillFilePath:r,skillId:t.skillId,sourceId:createPathDerivedSourceId(a)};return s.assetsPath!==void 0&&(c.assetsPath=s.assetsPath),o.license!==void 0&&(c.license=o.license),o.metadata!==void 0&&(c.metadata=o.metadata),s.referencesPath!==void 0&&(c.referencesPath=s.referencesPath),s.scriptsPath!==void 0&&(c.scriptsPath=s.scriptsPath),{diagnostics:[],logicalPath:a,skill:createSkillPackageSourceRef(c),skillId:t.skillId}}async function discoverFlatMarkdownSkill(t){let n=stripMarkdownExtension(t.skillFileName),r=normalizeLogicalPath(join(t.logicalSkillsPath,t.skillFileName)),a;try{a=lowerSkillMarkdown(await t.source.readTextFile(t.skillFilePath),{slug:n})}catch(e){return{diagnostics:[createDiscoverErrorDiagnostic({code:DISCOVER_SKILL_FRONTMATTER_INVALID,message:formatSkillDiscoveryError(t.skillFilePath,e),sourcePath:t.skillFilePath})],logicalPath:r,skill:null,skillId:null}}return{diagnostics:[],logicalPath:r,skill:{definition:a,sourceKind:`markdown`,logicalPath:r,sourceId:createPathDerivedSourceId(r)},skillId:n}}async function discoverFlatModuleSkill(t){let n=getSupportedModuleBaseName(t.skillFileName),r=normalizeLogicalPath(join(t.logicalSkillsPath,t.skillFileName));return n===null?{diagnostics:[],logicalPath:r,skill:null,skillId:null}:{diagnostics:[],logicalPath:r,skill:createModuleSourceRef({logicalPath:r}),skillId:n}}async function discoverSkillPackagePaths(t,n){let r=await t.readDirectory(n),i={};for(let t of r)if(t.isDirectory())switch(classifySkillPackageEntry(t.name,getDirectoryEntryType(t))){case`skill-assets-directory`:i.assetsPath=join(n,t.name);break;case`skill-references-directory`:i.referencesPath=join(n,t.name);break;case`skill-scripts-directory`:i.scriptsPath=join(n,t.name);break;default:break}return i}function formatSkillDiscoveryError(e,t){return`Invalid authored skill frontmatter in "${e}": ${toErrorMessage(t)}`}function stripMarkdownExtension(e){return e.toLowerCase().endsWith(`.md`)?e.slice(0,-3):e}export{DISCOVER_SKILLS_DIRECTORY_INVALID,DISCOVER_SKILL_COLLISION,DISCOVER_SKILL_ENTRY_NOT_DIRECTORY,DISCOVER_SKILL_FRONTMATTER_INVALID,DISCOVER_SKILL_MARKDOWN_MISSING,discoverSkills};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"../node_modules/.pnpm/autoevals@0.0.132_ws@8.21.0/node_modules/autoevals/jsdist/index.js";import{generateText
|
|
2
|
-
`)}function convertTools(
|
|
1
|
+
import"../node_modules/.pnpm/autoevals@0.0.132_ws@8.21.0/node_modules/autoevals/jsdist/index.js";import{toInputSchema}from"#shared/tool-schema.js";import{generateText}from"ai";function createAutoevalsClient(e){return{chat:{completions:{create:t=>createChatCompletion(t,e)}}}}async function createChatCompletion(e,n){let r=convertTools(e.tools),i=await generateText({model:n.languageModel,messages:convertMessages(e.messages??[]),tools:Object.keys(r).length>0?r:void 0,toolChoice:convertToolChoice(e.tool_choice),providerOptions:n.providerOptions}),a=i.toolCalls.map(e=>({id:e.toolCallId,type:`function`,function:{name:e.toolName,arguments:JSON.stringify(e.input??{})}}));return{choices:[{index:0,finish_reason:a.length>0?`tool_calls`:`stop`,message:{role:`assistant`,content:i.text||null,tool_calls:a.length>0?a:void 0}}]}}function convertMessages(e){return e.map(e=>{let t=contentToText(e.content);switch(e.role){case`assistant`:return{role:`assistant`,content:t};case`developer`:case`system`:return{role:`system`,content:t};default:return{role:`user`,content:t}}})}function contentToText(e){return e==null?``:typeof e==`string`?e:e.map(e=>e.text??``).filter(Boolean).join(`
|
|
2
|
+
`)}function convertTools(t){let n={};for(let r of t??[])r.type!==`function`||r.function?.name===void 0||(n[r.function.name]={description:r.function.description,inputSchema:toInputSchema(r.function.parameters??{})});return n}function convertToolChoice(e){if(e!==void 0)return typeof e==`string`?e:{type:`tool`,toolName:e.function.name}}export{createAutoevalsClient};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{
|
|
1
|
+
import{createLogger}from"#internal/logging.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{UNSPECIFIED_INPUT_SCHEMA,toInputSchema,toOutputSchema}from"#shared/tool-schema.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{AGENT_TOOL_DESCRIPTION,AGENT_TOOL_NAME}from"#runtime/framework-tools/agent.js";import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{preserveFrameworkStateOnCompaction}from"#execution/compaction.js";import{createToolExecuteWithAuth}from"#execution/tool-auth.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.modelResolutionScope),n=e.node.turnAgent.dynamicModel===void 0?void 0:createRuntimeDynamicModelEventDispatcher(e.modelResolutionScope,e.node.turnAgent.dynamicModel),r=createNodeHarnessTools({node:e.node});return createToolLoopHarness({abortSignal:e.abortSignal,capabilities:e.capabilities,workflow:e.node.agent.workflowTool!==void 0,workflowMaxSubagents:e.workflowMaxSubagents,handleEvent:e.handleEvent,mode:e.mode,onCompaction:preserveFrameworkStateOnCompaction,dispatchDynamicModelEvent:n,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:r})}function buildRuntimeIdentity(e){let n=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,eveVersion:n.version,modelId:e.turnAgent.dynamicModel===void 0?e.turnAgent.model.id:`dynamic:${e.turnAgent.model.id}`},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,e)}function createRuntimeDynamicModelEventDispatcher(e,t){return n=>dispatchDynamicModelEvent({ctx:n.ctx,dynamicModel:t,event:n.event,fallback:n.fallback,messages:n.messages,scope:e})}function createNodeHarnessTools(e){let t=new Map;for(let n of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:n});r!==null&&t.set(n.name,r)}return e.node.nodeId===ROOT_RUNTIME_AGENT_NODE_ID&&!e.node.agent.disabledFrameworkTools.includes(AGENT_TOOL_NAME)&&!t.has(AGENT_TOOL_NAME)&&t.set(AGENT_TOOL_NAME,{description:AGENT_TOOL_DESCRIPTION,inputSchema:SUBAGENT_TOOL_INPUT_SCHEMA,name:AGENT_TOOL_NAME,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:AGENT_TOOL_NAME}}),t}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`||e.tool.kind===`remote`){let t=e.tool.kind===`remote`?{kind:`remote-agent-call`,nodeId:e.tool.nodeId,remoteAgentName:e.tool.name,subagentName:e.tool.name}:{kind:`subagent-call`,nodeId:e.tool.nodeId,subagentName:e.tool.name};return{description:e.tool.description??``,inputSchema:toInputSchema(e.tool.inputSchema)??UNSPECIFIED_INPUT_SCHEMA,name:e.tool.name,outputSchema:toOutputSchema(e.tool.outputSchema),runtimeAction:t}}let t=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(t===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let a=t.definition,o=a.sourceId.startsWith(`eve:`),s=a.execute;return{approvalKey:a.approvalKey,description:a.description,execute:resolveAuthoredExecute({isFrameworkTool:o,rawExecute:s,scope:a.name}),inputSchema:a.inputSchema??UNSPECIFIED_INPUT_SCHEMA,name:a.name,approval:a.approval,outputSchema:a.outputSchema,toModelOutput:a.toModelOutput}}function resolveAuthoredExecute(e){let{isFrameworkTool:t,rawExecute:n,scope:r}=e;return n===void 0?void 0:t?n:createToolExecuteWithAuth({execute:n,scope:r})}export{createExecutionNodeStep,createNodeHarnessTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{expectDockerSuccess}from"#execution/sandbox/bindings/docker-utils.js";import{
|
|
1
|
+
import{randomUUID}from"node:crypto";import{expectDockerSuccess}from"#execution/sandbox/bindings/docker-utils.js";import{writeSandboxSeedFiles}from"#execution/sandbox/bindings/local-backend-utils.js";import{assertDockerDaemonAvailable,createDockerCli}from"#execution/sandbox/bindings/docker-cli.js";import{DOCKER_SANDBOX_LABEL,runDockerBaseSetup,startDockerContainer,stopDockerContainerIfRunning}from"#execution/sandbox/bindings/docker-container.js";import{setDockerNetworkPolicy}from"#execution/sandbox/bindings/docker-network.js";import{createDockerSandboxOptionsHash,resolveDockerSandboxOptions}from"#execution/sandbox/bindings/docker-options.js";import{createDockerInternalSession}from"#execution/sandbox/bindings/docker-session.js";import{DOCKER_TEMPLATE_IMAGE_REPOSITORY,dockerImageExists,dockerTemplateImageReference,ensureDockerBaseImage,pruneDockerSandboxTemplates,resolveDockerTemplateMarkerPath,touchDockerTemplateMarker}from"#execution/sandbox/bindings/docker-templates.js";import{createLoggingSandboxSession}from"#execution/sandbox/logging-session.js";import{buildSandboxSession}from"#execution/sandbox/session.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";const DOCKER_BACKEND_NAME=`docker`;function createDockerSandboxBackend(c={}){let l=c.dockerCli??createDockerCli(),u=resolveDockerSandboxOptions(c.createOptions),d=createDockerSandboxOptionsHash(u),f;function ensureDaemon(){return f??=assertDockerDaemonAvailable(l).catch(e=>{throw f=void 0,e}),f}return{name:DOCKER_BACKEND_NAME,async prewarm(r){r.log?.(`checking Docker daemon`),await ensureDaemon();let i={optionsHash:d,templateKey:r.templateKey},a=dockerTemplateImageReference(i),o=resolveDockerTemplateMarkerPath(r.runtimeContext.appRoot,i);if(r.log?.(`checking cached template image "${a}"`),await dockerImageExists(l,a))return r.log?.(`reusing cached template image`),await touchDockerTemplateMarker(o,a),{reused:!0};r.log?.(`checking base image "${u.image}"`),await ensureDockerBaseImage(l,u);let s=`${r.templateKey}-build-${randomUUID().slice(0,8)}`;r.log?.(`starting template build container`),await startDockerContainer({cli:l,containerName:s,image:u.image,initialNetworkPolicy:`allow-all`,options:u,role:`template-build`});try{r.log?.(`preparing base runtime inside container`),await runDockerBaseSetup(l,s),u.networkPolicy!==`allow-all`&&(r.log?.(`applying network policy`),await setDockerNetworkPolicy(l,s,u.networkPolicy));let e=buildSandboxSession(createDockerInternalSession({cli:l,containerName:s,id:r.templateKey}),e=>setDockerNetworkPolicy(l,s,e));r.bootstrap!==void 0&&(r.log?.(`running sandbox bootstrap`),await r.bootstrap({use:async()=>createLoggingSandboxSession({log:r.log,session:e})})),r.seedFiles.length>0&&r.log?.(`writing ${r.seedFiles.length} seed file(s)`),await writeSandboxSeedFiles(e,r.seedFiles),r.log?.(`stopping template build container`),expectDockerSuccess(await l.run([`stop`,`-t`,`0`,s]),`stop template build container "${s}"`),r.log?.(`committing template image "${a}"`),expectDockerSuccess(await l.run([`commit`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}=1`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}.role=template`,`--change`,`LABEL ${DOCKER_SANDBOX_LABEL}.template-key=${r.templateKey}`,s,a]),`commit sandbox template image "${a}"`),await touchDockerTemplateMarker(o,a)}finally{await l.run([`rm`,`-f`,s]).catch(()=>{})}return{reused:!1}},async create(e){await ensureDaemon();let n=getDockerContainerName(e.existingMetadata)??e.sessionKey,r=await l.run([`container`,`inspect`,`--format`,`{{.State.Running}}`,n]);if(r.exitCode===0)r.stdout.trim()!==`true`&&expectDockerSuccess(await l.run([`start`,n]),`restart sandbox session container "${n}"`);else{let t;if(e.templateKey===null)await ensureDockerBaseImage(l,u),t=u.image;else{let n={optionsHash:d,templateKey:e.templateKey};if(t=dockerTemplateImageReference(n),!await dockerImageExists(l,t))throw new SandboxTemplateNotProvisionedError({backendName:DOCKER_BACKEND_NAME,templateKey:e.templateKey});await touchDockerTemplateMarker(resolveDockerTemplateMarkerPath(e.runtimeContext.appRoot,n),t)}try{await startDockerContainer({cli:l,containerName:n,image:t,initialNetworkPolicy:e.templateKey===null?`allow-all`:u.networkPolicy,options:u,role:`session`,tags:e.tags})}catch(t){throw e.templateKey===null?t:new SandboxTemplateNotProvisionedError({backendName:DOCKER_BACKEND_NAME,templateKey:e.templateKey})}e.templateKey===null&&(await runDockerBaseSetup(l,n),u.networkPolicy!==`allow-all`&&await setDockerNetworkPolicy(l,n,u.networkPolicy))}let i=buildSandboxSession(createDockerInternalSession({cli:l,containerName:n,id:e.sessionKey}),e=>setDockerNetworkPolicy(l,n,e));return{session:i,useSessionFn:async()=>i,async captureState(){return{backendName:DOCKER_BACKEND_NAME,metadata:{containerName:n},sessionKey:e.sessionKey}},async shutdown(){await stopDockerContainerIfRunning(l,n)}}}}}function getDockerContainerName(e){let t=e?.containerName;return typeof t==`string`?t:void 0}export{DOCKER_BACKEND_NAME,DOCKER_TEMPLATE_IMAGE_REPOSITORY,createDockerSandboxBackend,pruneDockerSandboxTemplates};
|
|
@@ -72,7 +72,7 @@ export declare function loadMicrosandboxModule(input: {
|
|
|
72
72
|
* Loads microsandbox only when its package and runtime are already
|
|
73
73
|
* present — used by cleanup paths that must never trigger installs.
|
|
74
74
|
*/
|
|
75
|
-
export declare function loadMicrosandboxWithoutInstall(): Promise<MicrosandboxModule | null>;
|
|
75
|
+
export declare function loadMicrosandboxWithoutInstall(appRoot: string): Promise<MicrosandboxModule | null>;
|
|
76
76
|
export declare function stopAndSnapshotMicrosandboxSandbox(module: MicrosandboxModule, sandboxName: string, snapshotName: string): Promise<void>;
|
|
77
77
|
export declare function createProviderName(prefix: string, key: string, extra?: string): string;
|
|
78
78
|
export declare function createStableHash(value: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{posix}from"node:path";import{access}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{isEveDevEnvironment,loadOptionalEnginePackage}from"#internal/application/optional-package-install.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{withDevelopmentSandboxTags}from"#execution/sandbox/development-run.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{assertMicrosandboxPlatformCandidate,ensureMicrosandboxBaseRuntime}from"#execution/sandbox/bindings/microsandbox-platform.js";import{MICROSANDBOX_METADATA_VERSION,writeSessionMetadata}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{MICROSANDBOX_USER}from"#execution/sandbox/bindings/microsandbox-options.js";import{createMicrosandboxWithProgress}from"#execution/sandbox/bindings/microsandbox-create.js";import{applyMicrosandboxNetwork,createMicrosandboxNetworkPlan,createTransformBrokerEnvironment}from"#execution/sandbox/bindings/microsandbox-network.js";import{adaptMicrosandboxExecToSandboxProcess}from"#execution/sandbox/bindings/microsandbox-process.js";import{isMicrosandboxNotFoundError,isMicrosandboxNotFoundError as isMicrosandboxNotFoundError$1,isMicrosandboxSnapshotSourceRunningError,isMicrosandboxStillRunningError,removeSnapshotIfExists,removeSnapshotIfExists as removeSnapshotIfExists$1,sandboxExists,snapshotExists,snapshotExists as snapshotExists$1}from"#execution/sandbox/bindings/microsandbox-provider-state.js";const MICROSANDBOX_STOP_TIMEOUT_MS=1e4;var MicrosandboxVm=class{#e;#t;#n;#r;#i;#a;#o;constructor(e,t,n,r,i,a,o){this.#e=e,this.#i=t,this.#a=n,this.#n=r,this.#t=i,this.#r=a,this.#o=o}get id(){return this.#e.sessionKey}async captureState(e){if(this.#r=e,isEveDevEnvironment())return this.#t!==void 0&&await this.writeMetadata(this.#t,e),{networkPolicy:this.#n,optionsHash:e,sandboxName:this.#a,stateSnapshotName:this.#o,version:MICROSANDBOX_METADATA_VERSION};let t=this.#o,n=createProviderName(`eve-sbx-state`,`${this.#e.sessionKey}:${randomUUID()}`);return await this.stopAndSnapshot(n),this.#o=n,this.#t!==void 0&&await this.writeMetadata(this.#t,e),t!==void 0&&await removeSnapshotIfExists$1(this.#e.module,t),{networkPolicy:this.#n,optionsHash:e,sandboxName:this.#a,stateSnapshotName:n,version:MICROSANDBOX_METADATA_VERSION}}async detach(){await this.#i.detach().catch(()=>{})}async shutdown(){await this.#i.stop().catch(()=>{}),await this.detach()}async readFileBytes(e){try{let t=this.#i.fs();return await t.exists(e)?Buffer.from(await t.read(e)):null}catch{return null}}async removePath(e){let t=`${e.force===!0?`f`:``}${e.recursive===!0?`r`:``}`,n=`${t.length>0?`rm -${t}`:`rm`} -- ${shellQuote(e.path)}`;await this.runInternalCommand({abortSignal:e.abortSignal,command:n,user:MICROSANDBOX_USER})}async removePersisted(){await removeSandboxIfExists(this.#e.module,this.#a),this.#o!==void 0&&await removeSnapshotIfExists$1(this.#e.module,this.#o)}async setNetworkPolicy(e){let t=this.#o,n=createProviderName(`eve-sbx-state`,`${this.#e.sessionKey}:${randomUUID()}`),i=this.#a;await this.stopAndSnapshot(n),await removeSandboxIfExists(this.#e.module,i);let a=createProviderName(`eve-sbx-ses`,`${this.#e.sessionKey}:${randomUUID()}`);this.#i=await createMicrosandbox({fromSnapshot:n,module:this.#e.module,name:a,networkPolicy:e,options:this.#e.options,tags:this.#e.tags,user:MICROSANDBOX_USER,workdir:WORKSPACE_ROOT}),this.#a=a,this.#n=e,this.#o=void 0,this.#t!==void 0&&this.#r!==void 0&&await this.writeMetadata(this.#t,this.#r),await removeSnapshotIfExists$1(this.#e.module,n),t!==void 0&&await removeSnapshotIfExists$1(this.#e.module,t)}async spawn(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t={...this.#e.options.env,...createTransformBrokerEnvironment(createMicrosandboxNetworkPlan(this.#n)),...e.env},n=await this.#i.execStreamWith(`bash`,n=>n.args([`-lc`,e.command]).cwd(e.workingDirectory??WORKSPACE_ROOT).envs(t).user(MICROSANDBOX_USER));return e.abortSignal!==void 0&&e.abortSignal.addEventListener(`abort`,()=>{n.kill().catch(()=>{})},{once:!0}),adaptMicrosandboxExecToSandboxProcess(n)}async stopAndSnapshot(e){await this.#i.stop().catch(()=>{}),await stopAndSnapshotMicrosandboxSandbox(this.#e.module,this.#a,e)}async writeFiles(t){let n=this.#i.fs();for(let r of t){let t=posix.dirname(r.path);await this.runInternalCommand({command:`mkdir -p ${shellQuote(t)}`,user:MICROSANDBOX_USER}),await n.write(r.path,r.content),await this.runInternalCommand({command:`chown ${MICROSANDBOX_USER}:${MICROSANDBOX_USER} ${shellQuote(r.path)}`,user:`root`})}}async writeMetadata(e,t){this.#t=e,this.#r=t,await writeSessionMetadata(e,{networkPolicy:this.#n,optionsHash:t,sandboxName:this.#a,stateSnapshotName:this.#o,version:MICROSANDBOX_METADATA_VERSION})}async runInternalCommand(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=await this.#i.execWith(`bash`,t=>t.args([`-lc`,e.command]).cwd(WORKSPACE_ROOT).user(e.user));if(t.code!==0){let n=e.failureMessage??`Microsandbox command failed.`;throw Error(`${n} ${t.stderr()}`.trim())}}};async function createPreparedMicrosandbox(e){let t=e.setupBaseRuntime?`allow-all`:e.networkPolicy,n=await createMicrosandbox({fromSnapshot:e.fromSnapshot,log:e.log,module:e.module,name:e.name,networkPolicy:t,options:e.options,tags:e.tags,user:e.setupBaseRuntime?void 0:MICROSANDBOX_USER,workdir:e.setupBaseRuntime?`/`:WORKSPACE_ROOT}),r=new MicrosandboxVm({module:e.module,options:e.options,sessionKey:e.sessionKey,tags:e.tags},n,e.name,t);return e.setupBaseRuntime&&(await withProgressHeartbeat(`preparing base runtime inside VM`,e.log,async()=>{await ensureMicrosandboxBaseRuntime(n,{log:e.log})}),e.networkPolicy!==void 0&&e.networkPolicy!==`allow-all`&&(e.log?.(`applying network policy`),await r.setNetworkPolicy(e.networkPolicy))),r}async function connectMicrosandbox(e){let t;try{t=await e.module.Sandbox.get(e.metadata.sandboxName)}catch(t){if(!isMicrosandboxNotFoundError$1(t))throw t;return e.metadata.stateSnapshotName===void 0?null:await restoreMicrosandboxSessionSnapshot(e)}if(t.status!==`running`&&t.status!==`draining`&&e.metadata.stateSnapshotName!==void 0)return await restoreMicrosandboxSessionSnapshot(e);let n=t.status===`running`||t.status===`draining`?await t.connectWithTimeout(1e4):await t.startDetached();return new MicrosandboxVm({module:e.module,options:e.options,sessionKey:e.sessionKey,tags:e.tags},n,e.metadata.sandboxName,e.metadata.networkPolicy,e.metadataPath,e.metadata.optionsHash,e.metadata.stateSnapshotName)}async function restoreMicrosandboxSessionSnapshot(e){if(e.metadata.stateSnapshotName===void 0||!await snapshotExists$1(e.module,e.metadata.stateSnapshotName))return null;let t=createProviderName(`eve-sbx-ses`,`${e.sessionKey}:${randomUUID()}`),n=await createMicrosandbox({fromSnapshot:e.metadata.stateSnapshotName,module:e.module,name:t,networkPolicy:e.metadata.networkPolicy,options:e.options,tags:e.tags,user:MICROSANDBOX_USER,workdir:WORKSPACE_ROOT});await removeSandboxIfExists(e.module,e.metadata.sandboxName);let i=new MicrosandboxVm({module:e.module,options:e.options,sessionKey:e.sessionKey,tags:e.tags},n,t,e.metadata.networkPolicy,e.metadataPath,e.metadata.optionsHash,e.metadata.stateSnapshotName);return await i.writeMetadata(e.metadataPath,e.metadata.optionsHash),i}async function loadMicrosandboxModule(e){e.log?.(`checking microsandbox platform support`),await assertMicrosandboxPlatformCandidate();let t=await withProgressHeartbeat(`loading microsandbox npm package`,e.log,()=>loadOptionalEnginePackage({appRoot:e.appRoot,autoInstall:e.options.setup.autoInstall,importModule:async()=>await import(`microsandbox`),missingMessage:"The microsandbox sandbox backend requires the `microsandbox` package, which is not bundled with eve. Install it in your application (for example `pnpm add -D microsandbox`), or use docker() / vercel() instead.",packageName:`microsandbox`}));if(e.log?.(`checking microsandbox VM runtime`),!t.isInstalled()){if(!e.options.setup.autoInstall||!isEveDevEnvironment())throw Error("The microsandbox VM runtime is not installed. Run `npx microsandbox install`, set MSB_PATH for a custom install, or let `eve dev` install it automatically with microsandbox({ setup: { autoInstall: true } }).");await withProgressHeartbeat(`installing microsandbox VM runtime`,e.log,async()=>{await t.setup().skipVerify(e.options.setup.skipVerify).install()})}return e.log?.(`microsandbox runtime ready`),t}async function withProgressHeartbeat(e,t,n){if(t?.(e),t===void 0)return await n();let r=Date.now(),i=setInterval(()=>{t(`${e} (${Math.round((Date.now()-r)/1e3)}s elapsed)`)},1e4);i.unref?.();try{return await n()}finally{clearInterval(i)}}async function loadMicrosandboxWithoutInstall(){try{let e=await import(`microsandbox`);return e.isInstalled()?e:null}catch{return null}}async function stopAndSnapshotMicrosandboxSandbox(e,t,n){for(let r=0;r<3;r+=1){let i=await e.Sandbox.get(t);await i.stopWithTimeout(r===0?MICROSANDBOX_STOP_TIMEOUT_MS:0).catch(()=>{});try{await i.snapshot(n);return}catch(e){if(!isMicrosandboxSnapshotSourceRunningError(e)||r===2)throw e;await i.kill().catch(()=>{}),await new Promise(e=>setTimeout(e,250))}}}function createProviderName(e,t,n=``){return`${e}-${createStableHash(`${t}:${n}`).slice(0,32)}`}function createStableHash(e){return createHash(`sha256`).update(e).digest(`hex`)}async function doesPathExist(e){try{return await access(e),!0}catch{return!1}}async function createMicrosandbox(e){let t=e.module.Sandbox.builder(e.name).cpus(e.options.cpus).detached(!0).envs(e.options.env).labels(resolveMicrosandboxLabels(e.tags)).memory(e.options.memoryMiB).pullPolicy(e.options.pullPolicy).replace().workdir(e.workdir);t=e.fromSnapshot===void 0?t.image(e.options.image):t.fromSnapshot(e.fromSnapshot),e.user!==void 0&&(t=t.user(e.user));let n=e.fromSnapshot===void 0?`image "${e.options.image}"`:`snapshot "${e.fromSnapshot}"`;return await createMicrosandboxWithProgress({builder:applyMicrosandboxNetwork(t,e.networkPolicy),errorType:e.module.MicrosandboxError,log:e.log,source:n})}async function removeSandboxIfExists(e,t){for(let n=0;n<3;n+=1)try{let r=await e.Sandbox.get(t);await r.stopWithTimeout(n===0?MICROSANDBOX_STOP_TIMEOUT_MS:0).catch(()=>{}),await r.remove();return}catch(r){if(isMicrosandboxNotFoundError$1(r))return;if(isMicrosandboxStillRunningError(r)&&n<2){await(await e.Sandbox.get(t).catch(()=>null))?.kill().catch(()=>{}),await new Promise(e=>setTimeout(e,250));continue}throw r}}function resolveMicrosandboxLabels(e){return{"eve.backend":`microsandbox`,...withDevelopmentSandboxTags(e)}}export{MicrosandboxVm,connectMicrosandbox,createPreparedMicrosandbox,createProviderName,createStableHash,doesPathExist,isMicrosandboxNotFoundError,loadMicrosandboxModule,loadMicrosandboxWithoutInstall,removeSnapshotIfExists,sandboxExists,snapshotExists,stopAndSnapshotMicrosandboxSandbox};
|
|
1
|
+
import{posix}from"node:path";import{access}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{importInstalledEnginePackage,isEveDevEnvironment,loadOptionalEnginePackage}from"#internal/application/optional-package-install.js";import{WORKSPACE_ROOT}from"#runtime/workspace/types.js";import{withDevelopmentSandboxTags}from"#execution/sandbox/development-run.js";import{shellQuote}from"#execution/sandbox/shell-quote.js";import{assertMicrosandboxPlatformCandidate,ensureMicrosandboxBaseRuntime}from"#execution/sandbox/bindings/microsandbox-platform.js";import{MICROSANDBOX_METADATA_VERSION,writeSessionMetadata}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{MICROSANDBOX_USER}from"#execution/sandbox/bindings/microsandbox-options.js";import{createMicrosandboxWithProgress}from"#execution/sandbox/bindings/microsandbox-create.js";import{applyMicrosandboxNetwork,createMicrosandboxNetworkPlan,createTransformBrokerEnvironment}from"#execution/sandbox/bindings/microsandbox-network.js";import{adaptMicrosandboxExecToSandboxProcess}from"#execution/sandbox/bindings/microsandbox-process.js";import{isMicrosandboxNotFoundError,isMicrosandboxNotFoundError as isMicrosandboxNotFoundError$1,isMicrosandboxSnapshotSourceRunningError,isMicrosandboxStillRunningError,removeSnapshotIfExists,removeSnapshotIfExists as removeSnapshotIfExists$1,sandboxExists,snapshotExists,snapshotExists as snapshotExists$1}from"#execution/sandbox/bindings/microsandbox-provider-state.js";const MICROSANDBOX_PACKAGE_NAME=`microsandbox`,MICROSANDBOX_STOP_TIMEOUT_MS=1e4;var MicrosandboxVm=class{#e;#t;#n;#r;#i;#a;#o;constructor(e,t,n,r,i,a,o){this.#e=e,this.#i=t,this.#a=n,this.#n=r,this.#t=i,this.#r=a,this.#o=o}get id(){return this.#e.sessionKey}async captureState(e){if(this.#r=e,isEveDevEnvironment())return this.#t!==void 0&&await this.writeMetadata(this.#t,e),{networkPolicy:this.#n,optionsHash:e,sandboxName:this.#a,stateSnapshotName:this.#o,version:MICROSANDBOX_METADATA_VERSION};let t=this.#o,n=createProviderName(`eve-sbx-state`,`${this.#e.sessionKey}:${randomUUID()}`);return await this.stopAndSnapshot(n),this.#o=n,this.#t!==void 0&&await this.writeMetadata(this.#t,e),t!==void 0&&await removeSnapshotIfExists$1(this.#e.module,t),{networkPolicy:this.#n,optionsHash:e,sandboxName:this.#a,stateSnapshotName:n,version:MICROSANDBOX_METADATA_VERSION}}async detach(){await this.#i.detach().catch(()=>{})}async shutdown(){await this.#i.stop().catch(()=>{}),await this.detach()}async readFileBytes(e){try{let t=this.#i.fs();return await t.exists(e)?Buffer.from(await t.read(e)):null}catch{return null}}async removePath(e){let t=`${e.force===!0?`f`:``}${e.recursive===!0?`r`:``}`,n=`${t.length>0?`rm -${t}`:`rm`} -- ${shellQuote(e.path)}`;await this.runInternalCommand({abortSignal:e.abortSignal,command:n,user:MICROSANDBOX_USER})}async removePersisted(){await removeSandboxIfExists(this.#e.module,this.#a),this.#o!==void 0&&await removeSnapshotIfExists$1(this.#e.module,this.#o)}async setNetworkPolicy(e){let t=this.#o,n=createProviderName(`eve-sbx-state`,`${this.#e.sessionKey}:${randomUUID()}`),i=this.#a;await this.stopAndSnapshot(n),await removeSandboxIfExists(this.#e.module,i);let a=createProviderName(`eve-sbx-ses`,`${this.#e.sessionKey}:${randomUUID()}`);this.#i=await createMicrosandbox({fromSnapshot:n,module:this.#e.module,name:a,networkPolicy:e,options:this.#e.options,tags:this.#e.tags,user:MICROSANDBOX_USER,workdir:WORKSPACE_ROOT}),this.#a=a,this.#n=e,this.#o=void 0,this.#t!==void 0&&this.#r!==void 0&&await this.writeMetadata(this.#t,this.#r),await removeSnapshotIfExists$1(this.#e.module,n),t!==void 0&&await removeSnapshotIfExists$1(this.#e.module,t)}async spawn(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t={...this.#e.options.env,...createTransformBrokerEnvironment(createMicrosandboxNetworkPlan(this.#n)),...e.env},n=await this.#i.execStreamWith(`bash`,n=>n.args([`-lc`,e.command]).cwd(e.workingDirectory??WORKSPACE_ROOT).envs(t).user(MICROSANDBOX_USER));return e.abortSignal!==void 0&&e.abortSignal.addEventListener(`abort`,()=>{n.kill().catch(()=>{})},{once:!0}),adaptMicrosandboxExecToSandboxProcess(n)}async stopAndSnapshot(e){await this.#i.stop().catch(()=>{}),await stopAndSnapshotMicrosandboxSandbox(this.#e.module,this.#a,e)}async writeFiles(t){let n=this.#i.fs();for(let r of t){let t=posix.dirname(r.path);await this.runInternalCommand({command:`mkdir -p ${shellQuote(t)}`,user:MICROSANDBOX_USER}),await n.write(r.path,r.content),await this.runInternalCommand({command:`chown ${MICROSANDBOX_USER}:${MICROSANDBOX_USER} ${shellQuote(r.path)}`,user:`root`})}}async writeMetadata(e,t){this.#t=e,this.#r=t,await writeSessionMetadata(e,{networkPolicy:this.#n,optionsHash:t,sandboxName:this.#a,stateSnapshotName:this.#o,version:MICROSANDBOX_METADATA_VERSION})}async runInternalCommand(e){if(e.abortSignal?.aborted)throw new DOMException(`The operation was aborted.`,`AbortError`);let t=await this.#i.execWith(`bash`,t=>t.args([`-lc`,e.command]).cwd(WORKSPACE_ROOT).user(e.user));if(t.code!==0){let n=e.failureMessage??`Microsandbox command failed.`;throw Error(`${n} ${t.stderr()}`.trim())}}};async function createPreparedMicrosandbox(e){let t=e.setupBaseRuntime?`allow-all`:e.networkPolicy,n=await createMicrosandbox({fromSnapshot:e.fromSnapshot,log:e.log,module:e.module,name:e.name,networkPolicy:t,options:e.options,tags:e.tags,user:e.setupBaseRuntime?void 0:MICROSANDBOX_USER,workdir:e.setupBaseRuntime?`/`:WORKSPACE_ROOT}),r=new MicrosandboxVm({module:e.module,options:e.options,sessionKey:e.sessionKey,tags:e.tags},n,e.name,t);return e.setupBaseRuntime&&(await withProgressHeartbeat(`preparing base runtime inside VM`,e.log,async()=>{await ensureMicrosandboxBaseRuntime(n,{log:e.log})}),e.networkPolicy!==void 0&&e.networkPolicy!==`allow-all`&&(e.log?.(`applying network policy`),await r.setNetworkPolicy(e.networkPolicy))),r}async function connectMicrosandbox(e){let t;try{t=await e.module.Sandbox.get(e.metadata.sandboxName)}catch(t){if(!isMicrosandboxNotFoundError$1(t))throw t;return e.metadata.stateSnapshotName===void 0?null:await restoreMicrosandboxSessionSnapshot(e)}if(t.status!==`running`&&t.status!==`draining`&&e.metadata.stateSnapshotName!==void 0)return await restoreMicrosandboxSessionSnapshot(e);let n=t.status===`running`||t.status===`draining`?await t.connectWithTimeout(1e4):await t.startDetached();return new MicrosandboxVm({module:e.module,options:e.options,sessionKey:e.sessionKey,tags:e.tags},n,e.metadata.sandboxName,e.metadata.networkPolicy,e.metadataPath,e.metadata.optionsHash,e.metadata.stateSnapshotName)}async function restoreMicrosandboxSessionSnapshot(e){if(e.metadata.stateSnapshotName===void 0||!await snapshotExists$1(e.module,e.metadata.stateSnapshotName))return null;let t=createProviderName(`eve-sbx-ses`,`${e.sessionKey}:${randomUUID()}`),n=await createMicrosandbox({fromSnapshot:e.metadata.stateSnapshotName,module:e.module,name:t,networkPolicy:e.metadata.networkPolicy,options:e.options,tags:e.tags,user:MICROSANDBOX_USER,workdir:WORKSPACE_ROOT});await removeSandboxIfExists(e.module,e.metadata.sandboxName);let i=new MicrosandboxVm({module:e.module,options:e.options,sessionKey:e.sessionKey,tags:e.tags},n,t,e.metadata.networkPolicy,e.metadataPath,e.metadata.optionsHash,e.metadata.stateSnapshotName);return await i.writeMetadata(e.metadataPath,e.metadata.optionsHash),i}async function loadMicrosandboxModule(e){e.log?.(`checking microsandbox platform support`),await assertMicrosandboxPlatformCandidate();let t=await withProgressHeartbeat(`loading microsandbox npm package`,e.log,()=>loadOptionalEnginePackage({appRoot:e.appRoot,autoInstall:e.options.setup.autoInstall,importModule:async()=>await import(`microsandbox`),missingMessage:"The microsandbox sandbox backend requires the `microsandbox` package, which is not bundled with eve. Install it in your application (for example `pnpm add -D microsandbox`), or use docker() / vercel() instead.",packageName:MICROSANDBOX_PACKAGE_NAME}));if(e.log?.(`checking microsandbox VM runtime`),!t.isInstalled()){if(!e.options.setup.autoInstall||!isEveDevEnvironment())throw Error("The microsandbox VM runtime is not installed. Run `npx microsandbox install`, set MSB_PATH for a custom install, or let `eve dev` install it automatically with microsandbox({ setup: { autoInstall: true } }).");await withProgressHeartbeat(`installing microsandbox VM runtime`,e.log,async()=>{await t.setup().skipVerify(e.options.setup.skipVerify).install()})}return e.log?.(`microsandbox runtime ready`),t}async function withProgressHeartbeat(e,t,n){if(t?.(e),t===void 0)return await n();let r=Date.now(),i=setInterval(()=>{t(`${e} (${Math.round((Date.now()-r)/1e3)}s elapsed)`)},1e4);i.unref?.();try{return await n()}finally{clearInterval(i)}}async function loadMicrosandboxWithoutInstall(e){try{let t=await importInstalledEnginePackage({appRoot:e,packageName:MICROSANDBOX_PACKAGE_NAME});return t.isInstalled()?t:null}catch{return null}}async function stopAndSnapshotMicrosandboxSandbox(e,t,n){for(let r=0;r<3;r+=1){let i=await e.Sandbox.get(t);await i.stopWithTimeout(r===0?MICROSANDBOX_STOP_TIMEOUT_MS:0).catch(()=>{});try{await i.snapshot(n);return}catch(e){if(!isMicrosandboxSnapshotSourceRunningError(e)||r===2)throw e;await i.kill().catch(()=>{}),await new Promise(e=>setTimeout(e,250))}}}function createProviderName(e,t,n=``){return`${e}-${createStableHash(`${t}:${n}`).slice(0,32)}`}function createStableHash(e){return createHash(`sha256`).update(e).digest(`hex`)}async function doesPathExist(e){try{return await access(e),!0}catch{return!1}}async function createMicrosandbox(e){let t=e.module.Sandbox.builder(e.name).cpus(e.options.cpus).detached(!0).envs(e.options.env).labels(resolveMicrosandboxLabels(e.tags)).memory(e.options.memoryMiB).pullPolicy(e.options.pullPolicy).replace().workdir(e.workdir);t=e.fromSnapshot===void 0?t.image(e.options.image):t.fromSnapshot(e.fromSnapshot),e.user!==void 0&&(t=t.user(e.user));let n=e.fromSnapshot===void 0?`image "${e.options.image}"`:`snapshot "${e.fromSnapshot}"`;return await createMicrosandboxWithProgress({builder:applyMicrosandboxNetwork(t,e.networkPolicy),errorType:e.module.MicrosandboxError,log:e.log,source:n})}async function removeSandboxIfExists(e,t){for(let n=0;n<3;n+=1)try{let r=await e.Sandbox.get(t);await r.stopWithTimeout(n===0?MICROSANDBOX_STOP_TIMEOUT_MS:0).catch(()=>{}),await r.remove();return}catch(r){if(isMicrosandboxNotFoundError$1(r))return;if(isMicrosandboxStillRunningError(r)&&n<2){await(await e.Sandbox.get(t).catch(()=>null))?.kill().catch(()=>{}),await new Promise(e=>setTimeout(e,250));continue}throw r}}function resolveMicrosandboxLabels(e){return{"eve.backend":`microsandbox`,...withDevelopmentSandboxTags(e)}}export{MicrosandboxVm,connectMicrosandbox,createPreparedMicrosandbox,createProviderName,createStableHash,doesPathExist,isMicrosandboxNotFoundError,loadMicrosandboxModule,loadMicrosandboxWithoutInstall,removeSnapshotIfExists,sandboxExists,snapshotExists,stopAndSnapshotMicrosandboxSandbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:fs";import{join}from"node:path";import{readdir,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT}from"#execution/sandbox/bindings/local-template-prune.js";import{readTemplateMetadata,resolveMicrosandboxMetadataPath}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{loadMicrosandboxWithoutInstall,removeSnapshotIfExists}from"#execution/sandbox/bindings/microsandbox-runtime.js";const MICROSANDBOX_CACHE_DIRECTORY_NAME=`microsandbox`;async function pruneMicrosandboxTemplates(e){let t=resolveMicrosandboxTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot)),n=e.now??Date.now(),r=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,a=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,o=await readMicrosandboxTemplateDirectories(t),s=o.filter(e=>!e.isTemporary);await Promise.all([...s.map(async(
|
|
1
|
+
import"node:fs";import{join}from"node:path";import{readdir,rm,stat}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";import{resolveLocalBackendSessionRootPath,resolveLocalBackendTemplateRootPath,resolveLocalBackendTemplatesDirectory}from"#execution/sandbox/bindings/local-backend-utils.js";import{LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT}from"#execution/sandbox/bindings/local-template-prune.js";import{readTemplateMetadata,resolveMicrosandboxMetadataPath}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{loadMicrosandboxWithoutInstall,removeSnapshotIfExists}from"#execution/sandbox/bindings/microsandbox-runtime.js";const MICROSANDBOX_CACHE_DIRECTORY_NAME=`microsandbox`;async function pruneMicrosandboxTemplates(e){let t=resolveMicrosandboxTemplatesDirectory(resolveSandboxCacheDirectory(e.appRoot)),n=e.now??Date.now(),r=e.recentWindowMs??LOCAL_SANDBOX_TEMPLATE_RECENT_WINDOW_MS,a=e.retainCount??LOCAL_SANDBOX_TEMPLATE_RETAIN_COUNT,o=await readMicrosandboxTemplateDirectories(t),s=o.filter(e=>!e.isTemporary);await Promise.all([...s.map(async(t,i)=>{i<a||n-t.mtimeMs<=r||await removeTemplateDirectory(e.appRoot,t.path,t.metadata)}),...o.filter(e=>e.isTemporary).map(async t=>{n-t.mtimeMs<=r||await removeTemplateDirectory(e.appRoot,t.path,t.metadata)})])}function resolveMicrosandboxTemplateRootPath(e,t){return resolveLocalBackendTemplateRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}function resolveMicrosandboxTemplatesDirectory(e){return resolveLocalBackendTemplatesDirectory(e,MICROSANDBOX_CACHE_DIRECTORY_NAME)}function resolveMicrosandboxSessionRootPath(e,t){return resolveLocalBackendSessionRootPath(e,MICROSANDBOX_CACHE_DIRECTORY_NAME,t)}async function readMicrosandboxTemplateDirectories(n){let i;try{i=await readdir(n,{withFileTypes:!0})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return[];throw e}return(await Promise.all(i.filter(e=>e.isDirectory()).map(async t=>{let i=join(n,t.name);return{isTemporary:t.name.endsWith(`.tmp`),metadata:await readTemplateMetadata(resolveMicrosandboxMetadataPath(i)),mtimeMs:(await stat(i)).mtimeMs,path:i}}))).sort((e,t)=>t.mtimeMs-e.mtimeMs)}async function removeTemplateDirectory(e,t,r){if(await rm(t,{force:!0,recursive:!0}),r===null)return;let i=await loadMicrosandboxWithoutInstall(e);i!==null&&await removeSnapshotIfExists(i,r.snapshotName)}export{pruneMicrosandboxTemplates,resolveMicrosandboxSessionRootPath,resolveMicrosandboxTemplateRootPath,resolveMicrosandboxTemplatesDirectory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorMessage}from"#shared/errors.js";import{randomUUID}from"node:crypto";import{EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG,EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG}from"#execution/sandbox/development-run.js";import{createDockerCli}from"#execution/sandbox/bindings/docker-cli.js";import{DOCKER_SANDBOX_LABEL,stopDockerContainerIfRunning}from"#execution/sandbox/bindings/docker-container.js";import{
|
|
1
|
+
import{toErrorMessage}from"#shared/errors.js";import{randomUUID}from"node:crypto";import{EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG,EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG}from"#execution/sandbox/development-run.js";import{DockerUnavailableError,createDockerCli}from"#execution/sandbox/bindings/docker-cli.js";import{DOCKER_SANDBOX_LABEL,stopDockerContainerIfRunning}from"#execution/sandbox/bindings/docker-container.js";import{MICROSANDBOX_METADATA_VERSION,readSessionMetadata,writeSessionMetadata}from"#execution/sandbox/bindings/microsandbox-metadata.js";import{createProviderName,loadMicrosandboxWithoutInstall,removeSnapshotIfExists,stopAndSnapshotMicrosandboxSandbox}from"#execution/sandbox/bindings/microsandbox-runtime.js";async function stopDevelopmentSandboxResources(t){let n=await Promise.allSettled([stopDevelopmentDockerResources(t.devRunId),stopDevelopmentMicrosandboxResources(t.appRoot,t.devRunId,t.log)]);for(let r of n)r.status===`rejected`&&t.log?.(`failed to stop development sandbox resources: ${toErrorMessage(r.reason)}`)}async function stopDevelopmentDockerResources(e){let t=createDockerCli(),n=[`label=${DOCKER_SANDBOX_LABEL}=1`,`label=${DOCKER_SANDBOX_LABEL}.tag.${EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG}=${e}`],c;try{c=await t.run([`ps`,`-q`,...n.flatMap(e=>[`--filter`,e])])}catch(e){if(e instanceof DockerUnavailableError)return;throw e}if(c.exitCode!==0)return;let l=c.stdout.trim().split(/\s+/u).filter(Boolean);await Promise.all(l.map(e=>stopDockerContainerIfRunning(t,e)))}async function stopDevelopmentMicrosandboxResources(e,i,a){let o=await loadMicrosandboxWithoutInstall(e);if(o===null)return;let s=await o.Sandbox.listWith({labels:{"eve.backend":`microsandbox`,[EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG]:i}});await Promise.all(s.filter(e=>e.status===`running`||e.status===`draining`).map(async e=>{let r=getMicrosandboxLabel(e.configJson,EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG);if(r===void 0){await(await o.Sandbox.get(e.name)).stopWithTimeout(1e4).catch(()=>{});return}let i=await readSessionMetadata(r);if(i===null||i.sandboxName!==e.name){await(await o.Sandbox.get(e.name)).stopWithTimeout(1e4).catch(()=>{});return}a?.(`snapshotting development microsandbox session "${e.name}" before shutdown`);let s=i.stateSnapshotName,u=createProviderName(`eve-sbx-state`,`${i.sandboxName}:${randomUUID()}`);await stopAndSnapshotMicrosandboxSandbox(o,e.name,u),await writeSessionMetadata(r,{networkPolicy:i.networkPolicy,optionsHash:i.optionsHash,sandboxName:i.sandboxName,stateSnapshotName:u,version:MICROSANDBOX_METADATA_VERSION}),s!==void 0&&await removeSnapshotIfExists(o,s)}))}function getMicrosandboxLabel(e,t){let n;try{n=JSON.parse(e)}catch{return}return findLabel(n,t)}function findLabel(e,t){if(!isRecord(e))return;let n=e[t];if(typeof n==`string`)return n;let r=e.labels;if(isRecord(r)&&typeof r[t]==`string`)return r[t];if(typeof e.labelsJson==`string`){let n=parseJsonRecord(e.labelsJson);if(n!==null&&typeof n[t]==`string`)return n[t]}for(let n of Object.values(e)){let e=findLabel(n,t);if(e!==void 0)return e}}function parseJsonRecord(e){try{let t=JSON.parse(e);return isRecord(t)?t:null}catch{return null}}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{stopDevelopmentSandboxResources};
|
|
@@ -6,6 +6,3 @@ export declare function createDevelopmentSandboxRunId(): string;
|
|
|
6
6
|
export declare function getDevelopmentSandboxRunId(): string | undefined;
|
|
7
7
|
export declare function withDevelopmentSandboxTags(tags: SandboxBackendTags | undefined): SandboxBackendTags | undefined;
|
|
8
8
|
export declare function withDevelopmentSandboxMetadataPathTag(tags: SandboxBackendTags | undefined, metadataPath: string): SandboxBackendTags | undefined;
|
|
9
|
-
export declare function markDevelopmentSandboxBackendInitialized(backendName: string): void;
|
|
10
|
-
export declare function getInitializedDevelopmentSandboxBackendNames(runId: string): readonly string[];
|
|
11
|
-
export declare function clearInitializedDevelopmentSandboxBackendNames(runId: string): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";const EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV=`EVE_DEVELOPMENT_SANDBOX_RUN_ID`,EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG=`eve.metadataPath`,EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG=`devRunId
|
|
1
|
+
import{randomUUID}from"node:crypto";const EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV=`EVE_DEVELOPMENT_SANDBOX_RUN_ID`,EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG=`eve.metadataPath`,EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG=`devRunId`;function createDevelopmentSandboxRunId(){return randomUUID()}function getDevelopmentSandboxRunId(){let e=process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];return e===void 0||e.trim()===``?void 0:e}function withDevelopmentSandboxTags(e){let t=getDevelopmentSandboxRunId();return t===void 0?e:{...e,[EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG]:t}}function withDevelopmentSandboxMetadataPathTag(e,t){return getDevelopmentSandboxRunId()===void 0?e:{...e,[EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG]:t}}export{EVE_DEVELOPMENT_SANDBOX_METADATA_PATH_TAG,EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV,EVE_DEVELOPMENT_SANDBOX_RUN_ID_TAG,createDevelopmentSandboxRunId,getDevelopmentSandboxRunId,withDevelopmentSandboxMetadataPathTag,withDevelopmentSandboxTags};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{waitForDevelopmentSandboxPrewarm}from"#execution/sandbox/development-prewarm.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{trackActiveSandboxHandle}from"#execution/sandbox/active-handles.js";import{isEveDevEnvironment}from"#internal/application/optional-package-install.js";import{
|
|
1
|
+
import{waitForDevelopmentSandboxPrewarm}from"#execution/sandbox/development-prewarm.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{trackActiveSandboxHandle}from"#execution/sandbox/active-handles.js";import{isEveDevEnvironment}from"#internal/application/optional-package-install.js";import{SandboxTemplateNotProvisionedError}from"#public/definitions/sandbox-backend.js";import{getRuntimeCompiledArtifactsSandboxAppRoot}from"#runtime/compiled-artifacts-source.js";import{createRuntimeSandboxKeys}from"#runtime/sandbox/keys.js";import{createRuntimeSandboxTemplatePlan}from"#runtime/sandbox/template-plan.js";import{prewarmAppSandboxes}from"#execution/sandbox/prewarm.js";import{waitForSandboxTemplatePrewarmLock}from"#execution/sandbox/template-prewarm-lock.js";async function ensureSandboxAccess(r){let i=r.state?.initialized??!1,o=r.state?.session??null,s=getRuntimeCompiledArtifactsSandboxAppRoot(r.compiledArtifactsSource)??process.cwd(),c=r.registry.sandbox,l;function getHandle(){return l===void 0&&(l=createHandle().catch(e=>{throw l=void 0,e})),l}async function createHandle(){if(c===null)return null;let a=c.definition,l=a.backend,u=createRuntimeSandboxTemplatePlan({definition:a,workspaceResourceRoot:c.workspaceResourceRoot}),d=await createRuntimeSandboxKeys({backendName:l.name,compiledArtifactsSource:r.compiledArtifactsSource,nodeId:r.nodeId,sessionId:r.sessionId,sourceId:a.sourceId,templatePlan:u});d.templateKey!==null&&(await waitForDevelopmentSandboxPrewarm({appRoot:s,compiledArtifactsSource:r.compiledArtifactsSource,log:e=>logDevelopmentSandbox(`eve: sandbox template "${formatNodeLabel(r.nodeId)}" (${l.name}): ${e}`)}),await waitForSandboxTemplatePrewarmLock({appRoot:s,backendName:l.name,log:e=>logDevelopmentSandbox(`eve: sandbox template "${formatNodeLabel(r.nodeId)}" (${l.name}): ${e}`),templateKey:d.templateKey}));let f=o!==null&&o.backendName===l.name&&o.sessionKey===d.sessionKey?o:null;f===null&&(i=!1);let p={existingMetadata:f?.metadata,runtimeContext:{appRoot:s},sessionKey:d.sessionKey,tags:r.tags,templateKey:d.templateKey},m=await withDevelopmentSandboxProgress(`eve: opening sandbox session "${formatNodeLabel(r.nodeId)}" on backend "${l.name}"...`,`eve: opening sandbox session "${formatNodeLabel(r.nodeId)}" on backend "${l.name}"`,async()=>await createBackendHandleWithPrewarmRetry({appRoot:s,backend:l,compiledArtifactsSource:r.compiledArtifactsSource,createInput:p}));return trackActiveSandboxHandle({backendName:l.name,handle:m,sessionKey:d.sessionKey}),i||=(await runOnSession(async()=>{await a.onSession?.({ctx:buildCallbackContext(),use:m.useSessionFn})}),!0),m}async function runOnSession(e){if(r.runOnSession!==void 0){await r.runOnSession(e);return}await e()}return{async captureState(){if(l!==void 0){let e=await l;e!==null&&(o=await e.captureState())}return{initialized:i,session:o}},async get(){return(await getHandle())?.session??null}}}async function createBackendHandleWithPrewarmRetry(e){try{return await e.backend.create(e.createInput)}catch(t){if(e.createInput.templateKey===null||e.compiledArtifactsSource.kind!==`disk`||!SandboxTemplateNotProvisionedError.is(t))throw t;return await prewarmAppSandboxes({appRoot:e.appRoot,compiledArtifactsSource:e.compiledArtifactsSource,log:e=>logDevelopmentSandbox(e)}),await waitForSandboxTemplatePrewarmLock({appRoot:e.appRoot,backendName:e.backend.name,log:e=>logDevelopmentSandbox(`eve: ${e}`),templateKey:e.createInput.templateKey}),logDevelopmentSandbox(`eve: sandbox template is ready; retrying sandbox creation...`),await e.backend.create(e.createInput)}}function logDevelopmentSandbox(e){isEveDevEnvironment()&&console.log(e)}async function withDevelopmentSandboxProgress(e,t,n){if(logDevelopmentSandbox(e),!isEveDevEnvironment())return await n();let i=Date.now(),a=setInterval(()=>{logDevelopmentSandbox(`${t} (${Math.round((Date.now()-i)/1e3)}s elapsed)...`)},5e3);a.unref?.();try{return await n()}finally{clearInterval(a)}}function formatNodeLabel(e){return e===`__root__`?`root`:e}export{ensureSandboxAccess};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{formatSubagentInput}from"#execution/subagent-invocation.js";import{resolveRemainingSessionTokenLimits}from"#harness/subagent-token-budget.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l,source:u}=n,d=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),f=l.rootSessionId??l.sessionId,p=resolveSubagentDepth(l),m=resolveRemainingSessionTokenLimits(l,n.fanoutSize);return{childContinuationToken:d,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:d,initiatorAuth:c,input:{message:formatSubagentCallInputMessage({action:r,source:u}),outputSchema:
|
|
1
|
+
import{isJsonObjectValue}from"#shared/json.js";import{mintSubagentContinuationToken}from"#execution/session.js";import{SUBAGENT_ADAPTER_KIND}from"#execution/subagent-adapter.js";import{resolveSubagentDepth}from"#harness/subagent-depth.js";import{formatSubagentInput}from"#execution/subagent-invocation.js";import{resolveRemainingSessionTokenLimits}from"#harness/subagent-token-budget.js";function buildSubagentRunInput(n){let{action:r,auth:i,batchEvent:a,capabilities:o,channelMetadata:s,initiatorAuth:c,session:l,source:u}=n,d=mintSubagentContinuationToken(`${l.sessionId}:${r.callId}`),f=l.rootSessionId??l.sessionId,p=resolveSubagentDepth(l),m=resolveRemainingSessionTokenLimits(l,n.fanoutSize),h=r.input.outputSchema,g=isJsonObjectValue(h)&&Object.keys(h).length>0?h:void 0;return{childContinuationToken:d,runInput:{adapter:{kind:SUBAGENT_ADAPTER_KIND,state:{callId:r.callId,parentContinuationToken:n.parentContinuationToken??l.continuationToken,parentSessionId:l.sessionId,subagentName:r.subagentName,...r.subagentName===`agent`&&l.sandboxState?{parentSandboxState:l.sandboxState,sandboxSessionId:l.sessionId}:{}}},auth:i,capabilities:o,channelMetadata:s,continuationToken:d,initiatorAuth:c,input:{message:formatSubagentCallInputMessage({action:r,source:u}),outputSchema:g},limits:m,mode:`task`,parent:{callId:r.callId,rootSessionId:f,sessionId:l.sessionId,turn:{id:a.turnId,sequence:a.sequence}},subagentDepth:p.nextChildDepth}}}function formatSubagentCallInputMessage(e){let{message:t}=e.action.input;switch(e.source.type){case`local`:return formatSubagentInput({description:e.source.description,message:t,name:e.action.subagentName,type:`local`}).message;case`runtime`:return formatSubagentInput({message:t,name:e.action.subagentName,type:`runtime`}).message;default:return e.source}}export{buildSubagentRunInput};
|