Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat(v2): add run documents and declarative runtime profiles
kashorinabbda6284994
diff --git a/README.md b/README.mdindex 450c37b6..f5387c19 100644--- a/README.md+++ b/README.md@@ -103,12 +103,12 @@ pnpm svml:v2 plan examples/talking-film-graph-check/main.svml \--target final.video```-The live example uses explicit local Runtime assembly and external credentials:+The live example uses an explicit Run Graph, declarative local Runtime Profile and external+credentials:```bash-pnpm svml:v2 build examples/talking-film-live/main.svml \- --target final.video \- --runtime examples/talking-film-live/svml.runtime.ts \+pnpm svml:v2 build examples/talking-film-live/build.svrun \+ --runtime examples/talking-film-live/svml.runtime.json \--follow \--out examples/talking-film-live/output/final.mp4```@@ -124,8 +124,8 @@ These inputs are separate by design:|---|---|| `.svml` | author meaning, explicit model/component choices and graph references || `.svs` | reusable package-defined Recipe values |-| planned `.svrun` | Targets, Candidates and explicit Satisfaction edges for one reusable Run |-| Runtime Profile / `svml.runtime.ts` | Scheduler, Stores, credentials, Endpoints and concurrency |+| `.svrun` | Targets, Candidates and explicit Satisfaction edges for one reusable Run |+| `svml.runtime.json` / `svml.runtime.ts` | Scheduler, Stores, credential references, Endpoints and concurrency |Source imports activate author vocabulary only. They never authorize network, filesystem, process,credential or queue access.@@ -155,6 +155,7 @@ packages/protocol immutable wire contractspackages/core domain-neutral Demand compiler and Build state machinepackages/elaborator author declarations and hygienic Fragment expansionpackages/compiler-node reference Node compiler Host+packages/run official human-readable Run Graph frontendpackages/runtime environment-neutral scheduling and Store portspackages/driver-node trusted Node command executionpackages/local zero-service SQLite/filesystem developer assembly@@ -185,7 +186,7 @@ rewritten under `packages/`. They are not the public v2 package taxonomy or sourWork is intentionally focused on two layers:-1. domain-neutral `.svrun`, Runtime Profile usability, package lifecycle and inspection;+1. Run/Runtime diagnostics, package lifecycle and developer inspection;2. repeatable live acceptance and replaceable local/cloud Endpoint environments.Broader Text, Caption, B-roll and Ranking visual behavior is deferred until those foundations arediff --git a/examples/talking-film-live/README.md b/examples/talking-film-live/README.mdindex 74d93790..780efa45 100644--- a/examples/talking-film-live/README.md+++ b/examples/talking-film-live/README.md@@ -13,31 +13,35 @@ Both English lines resolve to five seconds with `pace="normal"`, `padding="0.3"`minimum and `ceil` rounding. The generated presenter image is intentionally ignored by Git under`assets/`; supply or regenerate `assets/presenter.png` before checking or building.-Run the complete graph with the explicitly trusted local Runtime:+Run the complete graph through the explicit Run Graph and declarative local Runtime Profile:```bash-pnpm svml:v2 build examples/talking-film-live/main.svml \- --target final.video \- --runtime examples/talking-film-live/svml.runtime.ts \+pnpm svml:v2 build examples/talking-film-live/build.svrun \+ --runtime examples/talking-film-live/svml.runtime.json \--follow \--out examples/talking-film-live/output/final.mp4```-Reuse the paid shot outputs from a verified earlier Build while rebuilding every reachable-downstream result:--```bash-pnpm svml:v2 build examples/talking-film-live/main.svml \- --target final.video \- --runtime examples/talking-film-live/svml.runtime.ts \- --pin opening-take=<prior-build-id> \- --pin answer-take=<prior-build-id> \- --accept-substitute \- --follow \- --out examples/talking-film-live/output/final-pinned.mp4+`build.svrun` owns the selected Target and fidelity. `svml.runtime.json` owns Provider instances,+permissions and concurrency. The existing `svml.runtime.ts` shows the advanced executable embedding+API and remains supported.++To reuse the paid shot outputs from a verified earlier Build, add two zero-input Build Record+Candidates and their explicit Satisfaction edges to another `.svrun`:++```xml+<svrun version="1" source="./main.svml" targets="delivery">+ <target-set id="delivery">+ <target output="final.video" accepts="substitute"/>+ </target-set>+ <build-record id="opening" build="prior-build-id" output="opening-take"/>+ <build-record id="answer" build="prior-build-id" output="answer-take"/>+ <satisfy output="opening-take" candidate="opening" fidelity="substitute"/>+ <satisfy output="answer-take" candidate="answer" fidelity="substitute"/>+</svrun>```-The second command compiles a new Build whose two shot outputs are explicitly selected substitute+The second Run compiles a new Build whose two shot outputs are explicitly selected substituteExisting values. It therefore contains no Seedance Operations or KIE Needs. Substitute fidelitypropagates through the rebuilt media normalization, WhisperX, SemanticMap, Tracks, Film andHyperFrames path instead of being washed back to exact.diff --git a/examples/talking-film-live/build.svrun b/examples/talking-film-live/build.svrunnew file mode 100644index 00000000..17b0c2c1--- /dev/null+++ b/examples/talking-film-live/build.svrun@@ -0,0 +1,5 @@+<svrun version="1" source="./main.svml" targets="delivery">+ <target-set id="delivery">+ <target output="final.video" accepts="exact"/>+ </target-set>+</svrun>diff --git a/examples/talking-film-live/svml.runtime.json b/examples/talking-film-live/svml.runtime.jsonnew file mode 100644index 00000000..62cdbd00--- /dev/null+++ b/examples/talking-film-live/svml.runtime.json@@ -0,0 +1,70 @@+{+ "format": "svml.runtime-config@1",+ "services": [],+ "endpoints": [+ {+ "use": "@svml/provider-kie",+ "instance": "kie.talking-film",+ "lane": "generation",+ "config": {+ "apiKeyEnv": "KIE_API_KEY",+ "defaultConcurrency": 2+ }+ },+ {+ "use": "@svml/provider-media-local",+ "instance": "media.talking-film",+ "lane": "media",+ "config": {+ "defaultConcurrency": 2+ }+ },+ {+ "use": "@svml/provider-whisperx-local",+ "instance": "whisperx.talking-film",+ "lane": "alignment",+ "config": {+ "defaultConcurrency": 1+ }+ },+ {+ "use": "@svml/provider-google-vertex",+ "instance": "vertex.talking-film",+ "lane": "planning",+ "config": {+ "projectEnv": "GOOGLE_CLOUD_PROJECT",+ "credentialsEnv": "GOOGLE_APPLICATION_CREDENTIALS_JSON",+ "defaultConcurrency": 1+ }+ },+ {+ "use": "@svml/provider-hyperframes-local",+ "instance": "hyperframes.talking-film",+ "lane": "render",+ "config": {+ "workers": 2,+ "quality": "standard",+ "defaultConcurrency": 1+ }+ }+ ],+ "permissions": [+ "filesystem:whisperx-staging",+ "network:aiplatform.googleapis.com",+ "network:api.kie.ai",+ "network:kieai.redpandaai.co",+ "network:whisperx-loopback",+ "process:hyperframes",+ "process:media"+ ],+ "scheduling": {+ "maxConcurrency": 4,+ "lanes": {+ "generation": 2,+ "media": 2,+ "alignment": 1,+ "planning": 1,+ "render": 1+ }+ }+}diff --git a/packages/cli/README.md b/packages/cli/README.mdindex a6e4df14..77b67b55 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -22,12 +22,12 @@ pnpm svml:v2 check path/to/main.svmlpnpm svml:v2 lock-packages ./svml.packages.lock --package @example/cards --root .pnpm svml:v2 check path/to/main.svml --package-lock ./svml.packages.lock --root .pnpm svml:v2 plan path/to/main.svml --target component.result-pnpm svml:v2 build path/to/main.svml --target component.result --runtime ./svml.runtime.ts-pnpm svml:v2 build path/to/main.svml --target component.result --runtime ./svml.runtime.ts --follow-pnpm svml:v2 build path/to/main.svml --target final.video --runtime ./svml.runtime.ts --follow --out ./final.mp4+pnpm svml:v2 check path/to/build.svrun+pnpm svml:v2 plan path/to/build.svrun+pnpm svml:v2 build path/to/build.svrun --runtime ./svml.runtime.json --follow --out ./final.mp4pnpm svml:v2 build path/to/main.svml --target final.video --runtime ./svml.runtime.ts --pin shot=<prior-build-id> --accept-substitute --follow --out ./variant.mp4-pnpm svml:v2 status <build-id> --runtime ./svml.runtime.ts-pnpm svml:v2 cancel <build-id> --runtime ./svml.runtime.ts+pnpm svml:v2 status <build-id> --runtime ./svml.runtime.json+pnpm svml:v2 cancel <build-id> --runtime ./svml.runtime.json````check` is usable for the complete provider-free author graph in@@ -35,10 +35,11 @@ pnpm svml:v2 cancel <build-id> --runtime ./svml.runtime.tslive example now executes the explicit Vertex Gemini Caption package and real local/remoteEndpoints; the CLI never fabricates missing facts.-`build` compiles the same locked BuildState and passes it to a trusted local Runtime config module.+`build` compiles the same locked BuildState and passes it to a trusted local Runtime Profile.The default Build identity is content-derived, so the same invocation resumes durable local state;-`--build-id take-02` names an explicit take. The config module is deployment code with normal Node-authority. It is never discovered from a source import and should not be used for untrusted code.+`--build-id take-02` names an explicit take. JSON Profiles resolve only adapters registered by the+Host and contain no executable callback. A TypeScript config module remains trusted deployment code+with normal Node authority. Neither form is discovered from a source import.Without `--follow`, a pending remote job returns `paused` and a later identical command resumes it.With `--follow`, the CLI stays attached and follows endpoint `wakeAt` hints until completion, a@@ -57,8 +58,8 @@ prove that the old Graph, prompt or semantic meaning matches the current output.command requires `--accept-substitute`. Upstream work behind that selected Candidate is notdemanded, while every unbound reachable output follows the ordinary graph. The prior artifact muststill exist in the ArtifactStore selected by the Runtime. This is a new Build with a new identity;-it never resumes or copies the prior Build's outstanding Commands. The planned `.svrun` Frontend-will replace this narrow flag with the general Run Graph, Target and Satisfaction language.+it never resumes or copies the prior Build's outstanding Commands. `.svrun` is now the general Run+Graph, Target and Satisfaction language; this narrow flag remains only migration compatibility.`@svml/package-loader-node` supports explicitly trusted installed implementation packages. Itverifies the complete physical dependency closure before executing an activation entry, then checksdiff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 060e8198..dfdc26f6 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -8,10 +8,18 @@},"dependencies": {"@svml/compiler-node": "workspace:*",+ "@svml/artifact-store-s3": "workspace:*","@svml/local": "workspace:*","@svml/package-loader-node": "workspace:*","@svml/prelude-video": "workspace:*",+ "@svml/provider-google-vertex": "workspace:*",+ "@svml/provider-hyperframes-local": "workspace:*",+ "@svml/provider-kie": "workspace:*",+ "@svml/provider-media-local": "workspace:*",+ "@svml/provider-whisperx-local": "workspace:*","@svml/protocol": "workspace:*",- "@svml/realization": "workspace:*"+ "@svml/realization": "workspace:*",+ "@svml/run": "workspace:*",+ "@svml/runtime": "workspace:*"}}diff --git a/packages/cli/src/host.ts b/packages/cli/src/host.tsindex 9ffec6b6..674c2b23 100644--- a/packages/cli/src/host.ts+++ b/packages/cli/src/host.ts@@ -11,9 +11,15 @@ export type OfficialCompilerOptions = {readonly packages?: readonly NodePackageActivation[];};+export function officialNodePackages(+ packages?: readonly NodePackageActivation[],+): readonly NodePackageActivation[] {+ return packages ?? [videoPrelude];+}+/** The CLI names only an ordinary replaceable prelude; no domain package is registered here. */export function createOfficialNodeCompiler(options: OfficialCompilerOptions = {}): NodeCompiler {- return createActivatedNodeCompiler(options.packages ?? [videoPrelude], {+ return createActivatedNodeCompiler(officialNodePackages(options.packages), {...(options.root === undefined ? {} : { root: options.root }),});}diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex 535c2493..a6dda297 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -1,5 +1,5 @@import { mkdir, writeFile } from "node:fs/promises";-import { dirname, resolve } from "node:path";+import { dirname, extname, resolve } from "node:path";import { pathToFileURL } from "node:url";import type { LocalRuntime } from "@svml/local";@@ -14,7 +14,9 @@ import {writeNodePackageLock,} from "@svml/package-loader-node";-import { createOfficialNodeCompiler } from "./host.js";+import { createOfficialNodeCompiler, officialNodePackages } from "./host.js";+import { loadRunFile } from "./run-file.js";+import { createOfficialRuntimeFromConfig } from "./runtime-config.js";type CliIo = {readonly write: (text: string) => void;@@ -85,7 +87,7 @@ function parseArgs(argv: readonly string[]): ParsedArgs {}if (item === "--runtime") {const value = rest[index + 1];- if (value === undefined || value.startsWith("--")) throw new Error("--runtime requires a trusted config module");+ if (value === undefined || value.startsWith("--")) throw new Error("--runtime requires a Runtime Profile or trusted config module");runtime = resolve(value);index += 1;continue;@@ -150,11 +152,13 @@ function usage(): string {return ["usage:"," svml-v2 lock-packages <svml.packages.lock> --package installed-name [--package installed-name] [--root directory]",- " svml-v2 check <file.svml> [--package-lock file] [--root directory]",+ " svml-v2 check <file.svml|file.svrun> [--runtime profile.json] [--package-lock file] [--root directory]"," svml-v2 plan <file.svml> --target export [--target export] [--accept-substitute] [--package-lock file]",+ " svml-v2 plan <file.svrun> [--runtime profile.json] [--package-lock file]"," svml-v2 build <file.svml> --target export --runtime ./svml.runtime.ts [--pin output=prior-build --accept-substitute] [--follow] [--out video.mp4]",- " svml-v2 status <build-id> --runtime ./svml.runtime.ts",- " svml-v2 cancel <build-id> --runtime ./svml.runtime.ts",+ " svml-v2 build <file.svrun> --runtime profile.json [--follow] [--out video.mp4]",+ " svml-v2 status <build-id> --runtime profile.json|./svml.runtime.ts",+ " svml-v2 cancel <build-id> --runtime profile.json|./svml.runtime.ts",].join("\n");}@@ -170,6 +174,7 @@ function isLocalRuntime(value: unknown): value is LocalRuntime {}async function loadLocalRuntime(path: string): Promise<LocalRuntime> {+ if (extname(path) === ".json") return await createOfficialRuntimeFromConfig(path);// A Runtime config is trusted executable deployment code, never an Author Frontend or .svml import.const imported = await import(pathToFileURL(path).href) as {readonly default?: unknown;@@ -272,29 +277,67 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<void>return;}if (args.packages.length > 0) throw new Error("--package is only valid for lock-packages");+ const runMode = extname(args.file) === ".svrun";+ if (runMode && (args.targets.length > 0 || args.substitute || args.pins.length > 0)) {+ throw new Error(".svrun owns Targets, Candidate selections and fidelity; do not combine it with --target, --pin or --accept-substitute");+ }const activated = args.packageLock === undefined? undefined: await loadNodePackageSet(args.packageLock, args.root ?? dirname(args.packageLock));+ const packages = officialNodePackages(activated?.packages);const compiler = createOfficialNodeCompiler({...(args.root === undefined ? {} : { root: args.root }),- ...(activated === undefined ? {} : { packages: activated.packages }),+ packages,});if (args.command === "check") {- const result = await compiler.compileFile(args.file);- io.write(`${JSON.stringify({- ok: true,- sourceClosure: result.closure.id,- moduleClosure: result.program.closure.digest,- graph: result.elaboration.graph.id,- units: result.closure.units.length,- sourceAssets: result.attachments.map((item) => item.artifact),- modules: result.program.closure.modules.map((item) => `${item.ref.name}@${item.ref.version}`),- exports: result.exports.map((item) => ({ name: item.name, type: item.type, kind: item.ref.kind })),- }, null, 2)}\n`);- return;+ let runtime: LocalRuntime | undefined;+ try {+ runtime = args.runtime === undefined ? undefined : await loadLocalRuntime(args.runtime);+ if (runMode) {+ const loaded = await loadRunFile({+ path: args.file,+ compiler,+ packages,+ ...(runtime === undefined ? {} : { runtime }),+ });+ const planned = compiler.planCompilation(loaded.compilation, {+ targets: loaded.run.targets,+ satisfactions: loaded.run.satisfactions,+ realizations: loaded.run.graphs,+ ...(activated === undefined ? {} : { implementationClosure: activated.lock.digest }),+ });+ io.write(`${JSON.stringify({+ ok: true,+ run: loaded.path,+ source: loaded.source,+ sourceClosure: loaded.compilation.closure.id,+ graph: planned.request.graph,+ targetSet: loaded.document.selectedTargets,+ targets: loaded.run.targets,+ candidates: loaded.run.candidates,+ satisfactions: loaded.run.satisfactions,+ steps: planned.plan.steps.length,+ }, null, 2)}\n`);+ return;+ }+ const result = await compiler.compileFile(args.file);+ io.write(`${JSON.stringify({+ ok: true,+ sourceClosure: result.closure.id,+ moduleClosure: result.program.closure.digest,+ graph: result.elaboration.graph.id,+ units: result.closure.units.length,+ sourceAssets: result.attachments.map((item) => item.artifact),+ modules: result.program.closure.modules.map((item) => `${item.ref.name}@${item.ref.version}`),+ exports: result.exports.map((item) => ({ name: item.name, type: item.type, kind: item.ref.kind })),+ }, null, 2)}\n`);+ return;+ } finally {+ await runtime?.close();+ }}if (args.command === "build") {- if (args.runtime === undefined) throw new Error("build requires --runtime with a trusted local config module");+ if (args.runtime === undefined) throw new Error("build requires --runtime with a Runtime Profile or trusted local config module");const runtime = await loadLocalRuntime(args.runtime);try {const planOptions = {@@ -303,9 +346,19 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<void>...(activated === undefined ? {} : { implementationClosure: activated.lock.digest }),};let pinSummary: readonly { readonly output: string; readonly build: string; readonly candidate: string }[] = [];- const result = args.pins.length === 0- ? await compiler.planFile(args.file, planOptions)- : await (async () => {+ const loadedRun = runMode+ ? await loadRunFile({ path: args.file, compiler, packages, runtime })+ : undefined;+ const result = loadedRun !== undefined+ ? compiler.planCompilation(loadedRun.compilation, {+ targets: loadedRun.run.targets,+ satisfactions: loadedRun.run.satisfactions,+ realizations: loadedRun.run.graphs,+ ...(activated === undefined ? {} : { implementationClosure: activated.lock.digest }),+ })+ : args.pins.length === 0+ ? await compiler.planFile(args.file, planOptions)+ : await (async () => {const compilation = await compiler.compileFile(args.file!);const seen = new Set<string>();const candidates = [];@@ -377,10 +430,31 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<void>}return;}- const result = await compiler.planFile(args.file, {- targets: args.targets,- accepts: args.substitute ? "substitute" : "exact",- ...(activated === undefined ? {} : { implementationClosure: activated.lock.digest }),- });- io.write(`${JSON.stringify(result.plan, null, 2)}\n`);+ let runtime: LocalRuntime | undefined;+ try {+ runtime = args.runtime === undefined ? undefined : await loadLocalRuntime(args.runtime);+ const result = runMode+ ? await (async () => {+ const loaded = await loadRunFile({+ path: args.file!,+ compiler,+ packages,+ ...(runtime === undefined ? {} : { runtime }),+ });+ return compiler.planCompilation(loaded.compilation, {+ targets: loaded.run.targets,+ satisfactions: loaded.run.satisfactions,+ realizations: loaded.run.graphs,+ ...(activated === undefined ? {} : { implementationClosure: activated.lock.digest }),+ });+ })()+ : await compiler.planFile(args.file, {+ targets: args.targets,+ accepts: args.substitute ? "substitute" : "exact",+ ...(activated === undefined ? {} : { implementationClosure: activated.lock.digest }),+ });+ io.write(`${JSON.stringify(result.plan, null, 2)}\n`);+ } finally {+ await runtime?.close();+ }}diff --git a/packages/cli/src/run-file.ts b/packages/cli/src/run-file.tsnew file mode 100644index 00000000..463f9963--- /dev/null+++ b/packages/cli/src/run-file.ts@@ -0,0 +1,52 @@+import { readFile } from "node:fs/promises";+import { dirname, resolve } from "node:path";++import type { NodeCompiler, NodeCompiledSourceClosure } from "@svml/compiler-node";+import type { LocalRuntime } from "@svml/local";+import type { NodePackageActivation } from "@svml/package-loader-node";+import {+ parseRunDocument,+ resolveRunDocument,+ RunFragmentRegistry,+} from "@svml/run";+import type { ResolvedRunDocument, RunDocument } from "@svml/run";++export type LoadedRunFile = {+ readonly path: string;+ readonly source: string;+ readonly document: RunDocument;+ readonly compilation: NodeCompiledSourceClosure;+ readonly run: ResolvedRunDocument;+};++export async function loadRunFile(options: {+ readonly path: string;+ readonly compiler: NodeCompiler;+ readonly packages: readonly NodePackageActivation[];+ readonly runtime?: Pick<LocalRuntime, "status">;+}): Promise<LoadedRunFile> {+ const path = resolve(options.path);+ const directory = dirname(path);+ const document = parseRunDocument(path, await readFile(path, "utf8"));+ const source = resolve(directory, document.source);+ const compilation = await options.compiler.compileFile(source);+ const fragments = new RunFragmentRegistry();+ for (const item of options.packages) {+ if (item.runFragments === undefined || Object.keys(item.runFragments).length === 0) continue;+ fragments.register({ name: item.name, fragments: item.runFragments });+ }+ const run = await resolveRunDocument(document, {+ compilation,+ fragments,+ async readStoredValue(from) {+ return JSON.parse(await readFile(resolve(directory, from), "utf8"));+ },+ async readBuild(id) {+ if (options.runtime === undefined) {+ throw new Error(`Run Candidate uses Build ${id}; select a Runtime Profile so it can be resolved`);+ }+ return (await options.runtime.status(id)).build?.state;+ },+ });+ return { path, source, document, compilation, run };+}diff --git a/packages/cli/src/runtime-config.ts b/packages/cli/src/runtime-config.tsnew file mode 100644index 00000000..1471d0da--- /dev/null+++ b/packages/cli/src/runtime-config.ts@@ -0,0 +1,172 @@+import { createS3ArtifactStorePackage } from "@svml/artifact-store-s3";+import {+ RuntimeConfigRegistry,+ createRuntimeFromConfig,+} from "@svml/local";+import type { RuntimeConfigFactoryContext } from "@svml/local";+import { createGoogleVertexCaptionProvider } from "@svml/provider-google-vertex";+import { createLocalHyperframesProvider } from "@svml/provider-hyperframes-local";+import { createKieProvider } from "@svml/provider-kie";+import { createLocalMediaProvider } from "@svml/provider-media-local";+import { createLocalWhisperXProvider } from "@svml/provider-whisperx-local";+import { svmlPackage as videoPrelude } from "@svml/prelude-video";+import type { CanonicalValue } from "@svml/protocol";+import { credentialRef } from "@svml/runtime";++function object(value: CanonicalValue, subject: string): Record<string, CanonicalValue> {+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${subject} config must be an object`);+ return value as Record<string, CanonicalValue>;+}++function exact(value: Record<string, CanonicalValue>, allowed: readonly string[], subject: string): void {+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));+ if (unknown.length > 0) throw new Error(`${subject} config does not accept ${unknown[0]}`);+}++function string(value: CanonicalValue | undefined, subject: string): string | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${subject} must be a non-empty string`);+ return value;+}++function number(value: CanonicalValue | undefined, subject: string): number | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) throw new Error(`${subject} must be a positive integer`);+ return value;+}++function boolean(value: CanonicalValue | undefined, subject: string): boolean | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== "boolean") throw new Error(`${subject} must be a boolean`);+ return value;+}++function common(context: RuntimeConfigFactoryContext): { readonly instance: string; readonly lane?: string } {+ return { instance: context.instance, ...(context.lane === undefined ? {} : { lane: context.lane }) };+}++export function createOfficialRuntimeConfigRegistry(): RuntimeConfigRegistry {+ const registry = new RuntimeConfigRegistry();+ registry.registerEndpoint("@svml/provider-kie", (context) => {+ const config = object(context.config, "KIE");+ exact(config, [+ "apiBaseUrl", "uploadBaseUrl", "apiKeyEnv", "defaultConcurrency", "pollIntervalMs",+ "submissionIntervalMs", "requestTimeoutMs", "maxOperationMs", "maxArtifactBytes",+ ], "KIE");+ const apiKeyEnv = string(config.apiKeyEnv, "KIE apiKeyEnv");+ return createKieProvider({+ ...common(context),+ ...(string(config.apiBaseUrl, "KIE apiBaseUrl") === undefined ? {} : { apiBaseUrl: config.apiBaseUrl as string }),+ ...(string(config.uploadBaseUrl, "KIE uploadBaseUrl") === undefined ? {} : { uploadBaseUrl: config.uploadBaseUrl as string }),+ ...(apiKeyEnv === undefined ? {} : { apiKey: credentialRef("env", apiKeyEnv) }),+ ...(number(config.defaultConcurrency, "KIE defaultConcurrency") === undefined ? {} : { defaultConcurrency: config.defaultConcurrency as number }),+ ...(number(config.pollIntervalMs, "KIE pollIntervalMs") === undefined ? {} : { pollIntervalMs: config.pollIntervalMs as number }),+ ...(number(config.submissionIntervalMs, "KIE submissionIntervalMs") === undefined ? {} : { submissionIntervalMs: config.submissionIntervalMs as number }),+ ...(number(config.requestTimeoutMs, "KIE requestTimeoutMs") === undefined ? {} : { requestTimeoutMs: config.requestTimeoutMs as number }),+ ...(number(config.maxOperationMs, "KIE maxOperationMs") === undefined ? {} : { maxOperationMs: config.maxOperationMs as number }),+ ...(number(config.maxArtifactBytes, "KIE maxArtifactBytes") === undefined ? {} : { maxArtifactBytes: config.maxArtifactBytes as number }),+ });+ });+ registry.registerEndpoint("@svml/provider-media-local", (context) => {+ const config = object(context.config, "local media");+ exact(config, ["ffmpegPath", "ffprobePath", "defaultConcurrency", "processTimeoutMs", "maxProbeOutputBytes"], "local media");+ return createLocalMediaProvider({+ ...common(context),+ ...(string(config.ffmpegPath, "media ffmpegPath") === undefined ? {} : { ffmpegPath: config.ffmpegPath as string }),+ ...(string(config.ffprobePath, "media ffprobePath") === undefined ? {} : { ffprobePath: config.ffprobePath as string }),+ ...(number(config.defaultConcurrency, "media defaultConcurrency") === undefined ? {} : { defaultConcurrency: config.defaultConcurrency as number }),+ ...(number(config.processTimeoutMs, "media processTimeoutMs") === undefined ? {} : { processTimeoutMs: config.processTimeoutMs as number }),+ ...(number(config.maxProbeOutputBytes, "media maxProbeOutputBytes") === undefined ? {} : { maxProbeOutputBytes: config.maxProbeOutputBytes as number }),+ });+ });+ registry.registerEndpoint("@svml/provider-whisperx-local", (context) => {+ const config = object(context.config, "local WhisperX");+ exact(config, [+ "baseUrl", "expectedModel", "expectedDevice", "expectedCompute", "expectedBatchSize",+ "expectedServiceVersion", "expectedWhisperXVersion", "expectedPunktTabDigest",+ "defaultConcurrency", "requestTimeoutMs", "maxResponseBytes",+ ], "local WhisperX");+ return createLocalWhisperXProvider({+ ...common(context),+ ...(string(config.baseUrl, "WhisperX baseUrl") === undefined ? {} : { baseUrl: config.baseUrl as string }),+ ...(string(config.expectedModel, "WhisperX expectedModel") === undefined ? {} : { expectedModel: config.expectedModel as string }),+ ...(string(config.expectedDevice, "WhisperX expectedDevice") === undefined ? {} : { expectedDevice: config.expectedDevice as string }),+ ...(string(config.expectedCompute, "WhisperX expectedCompute") === undefined ? {} : { expectedCompute: config.expectedCompute as string }),+ ...(number(config.expectedBatchSize, "WhisperX expectedBatchSize") === undefined ? {} : { expectedBatchSize: config.expectedBatchSize as number }),+ ...(string(config.expectedServiceVersion, "WhisperX expectedServiceVersion") === undefined ? {} : { expectedServiceVersion: config.expectedServiceVersion as string }),+ ...(string(config.expectedWhisperXVersion, "WhisperX expectedWhisperXVersion") === undefined ? {} : { expectedWhisperXVersion: config.expectedWhisperXVersion as string }),+ ...(string(config.expectedPunktTabDigest, "WhisperX expectedPunktTabDigest") === undefined ? {} : { expectedPunktTabDigest: config.expectedPunktTabDigest as string }),+ ...(number(config.defaultConcurrency, "WhisperX defaultConcurrency") === undefined ? {} : { defaultConcurrency: config.defaultConcurrency as number }),+ ...(number(config.requestTimeoutMs, "WhisperX requestTimeoutMs") === undefined ? {} : { requestTimeoutMs: config.requestTimeoutMs as number }),+ ...(number(config.maxResponseBytes, "WhisperX maxResponseBytes") === undefined ? {} : { maxResponseBytes: config.maxResponseBytes as number }),+ });+ });+ registry.registerEndpoint("@svml/provider-hyperframes-local", (context) => {+ const config = object(context.config, "local HyperFrames");+ exact(config, [+ "nodePath", "hyperframesCliPath", "ffprobePath", "workers", "quality", "browserGpu",+ "defaultConcurrency", "processTimeoutMs", "maxProcessOutputBytes", "maxRenderedBytes",+ ], "local HyperFrames");+ const workers = config.workers;+ if (workers !== undefined && workers !== "auto") number(workers, "HyperFrames workers");+ const quality = string(config.quality, "HyperFrames quality");+ if (quality !== undefined && quality !== "draft" && quality !== "standard" && quality !== "high") throw new Error("HyperFrames quality is invalid");+ const browserGpu = string(config.browserGpu, "HyperFrames browserGpu");+ if (browserGpu !== undefined && browserGpu !== "auto" && browserGpu !== "software" && browserGpu !== "hardware") throw new Error("HyperFrames browserGpu is invalid");+ return createLocalHyperframesProvider({+ ...common(context),+ ...(string(config.nodePath, "HyperFrames nodePath") === undefined ? {} : { nodePath: config.nodePath as string }),+ ...(string(config.hyperframesCliPath, "HyperFrames hyperframesCliPath") === undefined ? {} : { hyperframesCliPath: config.hyperframesCliPath as string }),+ ...(string(config.ffprobePath, "HyperFrames ffprobePath") === undefined ? {} : { ffprobePath: config.ffprobePath as string }),+ ...(workers === undefined ? {} : { workers: workers as number | "auto" }),+ ...(quality === undefined ? {} : { quality }),+ ...(browserGpu === undefined ? {} : { browserGpu }),+ ...(number(config.defaultConcurrency, "HyperFrames defaultConcurrency") === undefined ? {} : { defaultConcurrency: config.defaultConcurrency as number }),+ ...(number(config.processTimeoutMs, "HyperFrames processTimeoutMs") === undefined ? {} : { processTimeoutMs: config.processTimeoutMs as number }),+ ...(number(config.maxProcessOutputBytes, "HyperFrames maxProcessOutputBytes") === undefined ? {} : { maxProcessOutputBytes: config.maxProcessOutputBytes as number }),+ ...(number(config.maxRenderedBytes, "HyperFrames maxRenderedBytes") === undefined ? {} : { maxRenderedBytes: config.maxRenderedBytes as number }),+ });+ });+ registry.registerEndpoint("@svml/provider-google-vertex", (context) => {+ const config = object(context.config, "Google Vertex");+ exact(config, ["project", "projectEnv", "location", "credentialsEnv", "defaultConcurrency", "requestTimeoutMs", "maxResponseBytes"], "Google Vertex");+ const projectValue = string(config.project, "Google Vertex project");+ const projectEnv = string(config.projectEnv, "Google Vertex projectEnv");+ if (projectValue !== undefined && projectEnv !== undefined) throw new Error("Google Vertex accepts project or projectEnv, not both");+ const project = projectValue ?? (projectEnv === undefined ? undefined : process.env[projectEnv]?.trim());+ if (project === undefined || project.length === 0) throw new Error("Google Vertex project is required");+ const credentialsEnv = string(config.credentialsEnv, "Google Vertex credentialsEnv");+ return createGoogleVertexCaptionProvider({+ project,+ ...common(context),+ ...(string(config.location, "Google Vertex location") === undefined ? {} : { location: config.location as string }),+ ...(credentialsEnv === undefined ? {} : { credentialsJson: credentialRef("env", credentialsEnv) }),+ ...(number(config.defaultConcurrency, "Google Vertex defaultConcurrency") === undefined ? {} : { defaultConcurrency: config.defaultConcurrency as number }),+ ...(number(config.requestTimeoutMs, "Google Vertex requestTimeoutMs") === undefined ? {} : { requestTimeoutMs: config.requestTimeoutMs as number }),+ ...(number(config.maxResponseBytes, "Google Vertex maxResponseBytes") === undefined ? {} : { maxResponseBytes: config.maxResponseBytes as number }),+ });+ });+ registry.registerService("@svml/artifact-store-s3", (context) => {+ const config = object(context.config, "S3 ArtifactStore");+ exact(config, ["bucket", "prefix", "expectedBucketOwner", "region", "endpoint", "forcePathStyle"], "S3 ArtifactStore");+ const bucket = string(config.bucket, "S3 bucket");+ if (bucket === undefined) throw new Error("S3 bucket is required");+ return createS3ArtifactStorePackage({+ instance: context.instance,+ bucket,+ ...(string(config.prefix, "S3 prefix") === undefined ? {} : { prefix: config.prefix as string }),+ ...(string(config.expectedBucketOwner, "S3 expectedBucketOwner") === undefined ? {} : { expectedBucketOwner: config.expectedBucketOwner as string }),+ ...(string(config.region, "S3 region") === undefined ? {} : { region: config.region as string }),+ ...(string(config.endpoint, "S3 endpoint") === undefined ? {} : { endpoint: config.endpoint as string }),+ ...(boolean(config.forcePathStyle, "S3 forcePathStyle") === undefined ? {} : { forcePathStyle: config.forcePathStyle as boolean }),+ });+ });+ return registry;+}++export async function createOfficialRuntimeFromConfig(path: string) {+ return await createRuntimeFromConfig(path, {+ registry: createOfficialRuntimeConfigRegistry(),+ components: videoPrelude.components ?? [],+ });+}diff --git a/packages/cli/test/cli.test.ts b/packages/cli/test/cli.test.tsindex cf3ad0fd..e4768ffd 100644--- a/packages/cli/test/cli.test.ts+++ b/packages/cli/test/cli.test.ts@@ -141,6 +141,61 @@ test("official media and Seedance Surfaces lower author intent into exact genera);});+test(".svrun is the complete human-readable Target graph used by plan", async () => {+ const root = await mkdtemp(join(tmpdir(), "svml-cli-run-"));+ const source = join(root, "main.svml");+ const run = join(root, "preview.svrun");+ await writeFile(source, `<svml>+ <import as="seedance" from="@svml/seedance@1"/>+ <seedance:Prompt id="direction">A quiet locked-off studio shot.</seedance:Prompt>+ <seedance:Video id="motion" model="mini" prompt={direction} duration="4"/>+ </svml>`, "utf8");+ await writeFile(run, `<svrun version="1" source="./main.svml" targets="preview">+ <target-set id="preview">+ <target output="motion.video" accepts="exact"/>+ </target-set>+ </svrun>`, "utf8");++ let output = "";+ await runCli(["plan", run], { write: (text) => { output += text; } });+ const plan = JSON.parse(output) as {+ readonly goals: readonly unknown[];+ readonly steps: readonly { readonly producer: { readonly name: string } }[];+ };+ assert.equal(plan.goals.length, 1);+ assert.deepEqual(plan.steps.map((item) => item.producer.name), [+ "request-seedance-2-mini",+ "select-primary-video",+ ]);+ await assert.rejects(+ async () => await runCli(["plan", run, "--target", "motion.video"], { write() {} }),+ /.svrun owns Targets/u,+ );+});++test("CLI accepts a declarative Runtime Profile without an executable config module", async () => {+ const root = await mkdtemp(join(tmpdir(), "svml-cli-runtime-profile-"));+ const profile = join(root, "svml.runtime.json");+ await writeFile(profile, JSON.stringify({+ format: "svml.runtime-config@1",+ services: [],+ endpoints: [{+ use: "@svml/provider-kie",+ instance: "kie.cli-test",+ lane: "generation",+ config: { apiKeyEnv: "KIE_API_KEY", defaultConcurrency: 2 },+ }],+ permissions: ["network:api.kie.ai", "network:kieai.redpandaai.co"],+ scheduling: { lanes: { generation: 2 } },+ }), "utf8");+ let output = "";+ await runCli(["status", "missing-build", "--runtime", profile], {+ write: (text) => { output += text; },+ });+ const status = JSON.parse(output) as { readonly operations: readonly unknown[] };+ assert.deepEqual(status.operations, []);+});+test("official prelude lowers Speech Spine and explicit WhisperX alignment without provider calls", async () => {const root = await mkdtemp(join(tmpdir(), "svml-cli-speech-spine-"));const file = join(root, "main.svml");diff --git a/packages/compiler-node/src/compiler.ts b/packages/compiler-node/src/compiler.tsindex b089ae55..92d1dff2 100644--- a/packages/compiler-node/src/compiler.ts+++ b/packages/compiler-node/src/compiler.ts@@ -86,7 +86,10 @@ export type NodeCompilerOptions = {};export type PlanFileOptions = {- readonly targets: readonly string[];+ readonly targets: readonly (string | {+ readonly name: string;+ readonly accepts: NeedAcceptance;+ })[];readonly accepts?: NeedAcceptance;readonly satisfactions?: readonly Satisfaction[];readonly implementationClosure?: import("@svml/protocol").Digest;@@ -176,7 +179,8 @@ export class NodeCompiler {compilation.elaboration.graph,options.realizations,).graph;- const targets = options.targets.map((name) => {+ const targets = options.targets.map((target) => {+ const name = typeof target === "string" ? target : target.name;const exported = resolveCompiledSourceExport(compilation, name);if (exported.ref.kind !== "logical-output") {throw new NodeCompilerError(@@ -185,7 +189,10 @@ export class NodeCompiler {name,);}- return { output: exported.ref.id, accepts: options.accepts ?? "exact" } as const;+ return {+ output: exported.ref.id,+ accepts: typeof target === "string" ? options.accepts ?? "exact" : target.accepts,+ } as const;});const request = sealBuildRequest({graph: graph.id,diff --git a/packages/local/README.md b/packages/local/README.mdindex 85c12848..045272d7 100644--- a/packages/local/README.md+++ b/packages/local/README.md@@ -14,6 +14,33 @@ The convenience assembly uses:- an exact implementation package lock for deterministic component packages;- separately selected external Endpoint packages.+Normal CLI projects may express the same assembly as closed data:++```json+{+ "format": "svml.runtime-config@1",+ "services": [],+ "endpoints": [+ {+ "use": "@svml/provider-kie",+ "instance": "kie.project",+ "lane": "generation",+ "config": { "apiKeyEnv": "KIE_API_KEY", "defaultConcurrency": 2 }+ }+ ],+ "permissions": [+ "network:api.kie.ai",+ "network:kieai.redpandaai.co"+ ],+ "scheduling": { "maxConcurrency": 4, "lanes": { "generation": 2 } }+}+```++`RuntimeConfigRegistry` maps each exact `use` name to a trusted package factory. The data file can+choose instances, non-secret configuration, permissions and concurrency, but it cannot embed code+or secrets. Unknown adapters fail rather than being guessed. `createProjectLocalRuntime(...)`+remains the advanced TypeScript embedding API.+Deterministic packages implement the host-neutral `@svml/component-kit` contract. `@svml/local`adapts them to `ProducerRegistry`; the component never imports the Node Driver or receives Runtimeservices.diff --git a/packages/local/src/config.ts b/packages/local/src/config.tsnew file mode 100644index 00000000..c7ff21f5--- /dev/null+++ b/packages/local/src/config.ts@@ -0,0 +1,248 @@+import { readFile } from "node:fs/promises";+import { dirname, resolve } from "node:path";++import type { ComponentPackage } from "@svml/component-kit";+import type { EndpointPackage } from "@svml/endpoint-kit";+import { canonicalize } from "@svml/protocol";+import type { CanonicalValue } from "@svml/protocol";+import type { RuntimeServicePackage } from "@svml/runtime";++import { createProjectLocalRuntime } from "./runtime.js";+import type { LocalRuntime } from "./types.js";++export type RuntimeConfigEntry = {+ readonly use: string;+ readonly instance: string;+ readonly lane?: string;+ readonly config?: CanonicalValue;+};++export type RuntimeConfigDocument = {+ readonly format: "svml.runtime-config@1";+ /** Resolved relative to the configuration file. Defaults to its directory. */+ readonly root?: string;+ readonly statePath?: string;+ readonly artifactPath?: string;+ readonly packageLock?: string;+ readonly services: readonly RuntimeConfigEntry[];+ readonly endpoints: readonly RuntimeConfigEntry[];+ readonly selection?: {+ readonly scheduler?: string;+ readonly stores?: {+ readonly build?: string;+ readonly operations?: string;+ readonly artifacts?: string;+ readonly credentials?: string;+ };+ };+ readonly permissions: readonly string[];+ readonly scheduling?: {+ readonly maxConcurrency?: number;+ readonly lanes?: Readonly<Record<string, number>>;+ readonly maxEventsPerBuild?: number;+ };+};++export type RuntimeConfigFactoryContext = {+ readonly root: string;+ readonly instance: string;+ readonly lane?: string;+ readonly config: CanonicalValue;+};++export type RuntimeEndpointFactory = (+ context: RuntimeConfigFactoryContext,+) => Promise<EndpointPackage> | EndpointPackage;++export type RuntimeServiceFactory = (+ context: RuntimeConfigFactoryContext,+) => Promise<RuntimeServicePackage> | RuntimeServicePackage;++export class RuntimeConfigRegistry {+ readonly #endpoints = new Map<string, RuntimeEndpointFactory>();+ readonly #services = new Map<string, RuntimeServiceFactory>();++ registerEndpoint(use: string, factory: RuntimeEndpointFactory): void {+ if (use.trim().length === 0) throw new Error("Runtime Endpoint adapter name must not be empty");+ if (this.#endpoints.has(use) || this.#services.has(use)) throw new Error(`Runtime adapter ${use} is already registered`);+ this.#endpoints.set(use, factory);+ }++ registerService(use: string, factory: RuntimeServiceFactory): void {+ if (use.trim().length === 0) throw new Error("Runtime service adapter name must not be empty");+ if (this.#endpoints.has(use) || this.#services.has(use)) throw new Error(`Runtime adapter ${use} is already registered`);+ this.#services.set(use, factory);+ }++ endpoint(use: string): RuntimeEndpointFactory | undefined {+ return this.#endpoints.get(use);+ }++ service(use: string): RuntimeServiceFactory | undefined {+ return this.#services.get(use);+ }+}++function object(value: unknown, subject: string): Record<string, unknown> {+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${subject} must be an object`);+ return value as Record<string, unknown>;+}++function exactKeys(value: Record<string, unknown>, allowed: readonly string[], subject: string): void {+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));+ if (unknown.length > 0) throw new Error(`${subject} does not accept ${unknown[0]}`);+}++function optionalString(value: unknown, subject: string): string | undefined {+ if (value === undefined) return undefined;+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${subject} must be a non-empty string`);+ return value;+}++function requiredString(value: unknown, subject: string): string {+ const result = optionalString(value, subject);+ if (result === undefined) throw new Error(`${subject} is required`);+ return result;+}++function positiveInteger(value: unknown, subject: string): number | undefined {+ if (value === undefined) return undefined;+ if (!Number.isSafeInteger(value) || (value as number) <= 0) throw new Error(`${subject} must be a positive integer`);+ return value as number;+}++function stringList(value: unknown, subject: string): readonly string[] {+ if (value === undefined) return [];+ if (!Array.isArray(value)) throw new Error(`${subject} must be an array`);+ const items = value.map((item, index) => optionalString(item, `${subject}[${index}]`)!);+ if (new Set(items).size !== items.length) throw new Error(`${subject} contains duplicates`);+ return items;+}++function entry(value: unknown, subject: string, laneAllowed: boolean): RuntimeConfigEntry {+ const item = object(value, subject);+ exactKeys(item, laneAllowed ? ["use", "instance", "lane", "config"] : ["use", "instance", "config"], subject);+ const lane = laneAllowed ? optionalString(item.lane, `${subject}.lane`) : undefined;+ return {+ use: requiredString(item.use, `${subject}.use`),+ instance: requiredString(item.instance, `${subject}.instance`),+ ...(lane === undefined ? {} : { lane }),+ ...(item.config === undefined ? {} : { config: canonicalize(item.config) }),+ };+}++function selection(value: unknown): RuntimeConfigDocument["selection"] {+ if (value === undefined) return undefined;+ const item = object(value, "$runtime.selection");+ exactKeys(item, ["scheduler", "stores"], "$runtime.selection");+ const stores = item.stores === undefined ? undefined : object(item.stores, "$runtime.selection.stores");+ if (stores !== undefined) exactKeys(stores, ["build", "operations", "artifacts", "credentials"], "$runtime.selection.stores");+ const scheduler = optionalString(item.scheduler, "$runtime.selection.scheduler");+ return {+ ...(scheduler === undefined ? {} : { scheduler }),+ ...(stores === undefined ? {} : { stores: {+ ...(optionalString(stores.build, "$runtime.selection.stores.build") === undefined ? {} : { build: stores.build as string }),+ ...(optionalString(stores.operations, "$runtime.selection.stores.operations") === undefined ? {} : { operations: stores.operations as string }),+ ...(optionalString(stores.artifacts, "$runtime.selection.stores.artifacts") === undefined ? {} : { artifacts: stores.artifacts as string }),+ ...(optionalString(stores.credentials, "$runtime.selection.stores.credentials") === undefined ? {} : { credentials: stores.credentials as string }),+ } }),+ };+}++function scheduling(value: unknown): RuntimeConfigDocument["scheduling"] {+ if (value === undefined) return undefined;+ const item = object(value, "$runtime.scheduling");+ exactKeys(item, ["maxConcurrency", "lanes", "maxEventsPerBuild"], "$runtime.scheduling");+ const lanes = item.lanes === undefined ? undefined : object(item.lanes, "$runtime.scheduling.lanes");+ const normalizedLanes = lanes === undefined ? undefined : Object.fromEntries(Object.entries(lanes).map(([name, limit]) => {+ if (name.trim().length === 0) throw new Error("Runtime lane name must not be empty");+ return [name, positiveInteger(limit, `$runtime.scheduling.lanes.${name}`)!];+ }));+ return {+ ...(positiveInteger(item.maxConcurrency, "$runtime.scheduling.maxConcurrency") === undefined+ ? {}+ : { maxConcurrency: item.maxConcurrency as number }),+ ...(normalizedLanes === undefined ? {} : { lanes: normalizedLanes }),+ ...(positiveInteger(item.maxEventsPerBuild, "$runtime.scheduling.maxEventsPerBuild") === undefined+ ? {}+ : { maxEventsPerBuild: item.maxEventsPerBuild as number }),+ };+}++export function parseRuntimeConfig(value: unknown): RuntimeConfigDocument {+ const item = object(value, "$runtime");+ exactKeys(item, [+ "format", "root", "statePath", "artifactPath", "packageLock", "services", "endpoints",+ "selection", "permissions", "scheduling",+ ], "$runtime");+ if (item.format !== "svml.runtime-config@1") throw new Error("$runtime.format must be svml.runtime-config@1");+ const services = item.services === undefined ? [] : (() => {+ if (!Array.isArray(item.services)) throw new Error("$runtime.services must be an array");+ return item.services.map((value, index) => entry(value, `$runtime.services[${index}]`, false));+ })();+ const endpoints = item.endpoints === undefined ? [] : (() => {+ if (!Array.isArray(item.endpoints)) throw new Error("$runtime.endpoints must be an array");+ return item.endpoints.map((value, index) => entry(value, `$runtime.endpoints[${index}]`, true));+ })();+ const instances = [...services, ...endpoints].map((value) => value.instance);+ if (new Set(instances).size !== instances.length) throw new Error("$runtime repeats a Runtime instance id");+ const selected = selection(item.selection);+ const scheduled = scheduling(item.scheduling);+ return {+ format: "svml.runtime-config@1",+ ...(optionalString(item.root, "$runtime.root") === undefined ? {} : { root: item.root as string }),+ ...(optionalString(item.statePath, "$runtime.statePath") === undefined ? {} : { statePath: item.statePath as string }),+ ...(optionalString(item.artifactPath, "$runtime.artifactPath") === undefined ? {} : { artifactPath: item.artifactPath as string }),+ ...(optionalString(item.packageLock, "$runtime.packageLock") === undefined ? {} : { packageLock: item.packageLock as string }),+ services,+ endpoints,+ ...(selected === undefined ? {} : { selection: selected }),+ permissions: stringList(item.permissions, "$runtime.permissions"),+ ...(scheduled === undefined ? {} : { scheduling: scheduled }),+ };+}++export type LoadRuntimeConfigOptions = {+ readonly registry: RuntimeConfigRegistry;+ readonly components?: readonly ComponentPackage[];+};++export async function createRuntimeFromConfig(+ path: string,+ options: LoadRuntimeConfigOptions,+): Promise<LocalRuntime> {+ const absolute = resolve(path);+ const document = parseRuntimeConfig(JSON.parse(await readFile(absolute, "utf8")));+ const root = resolve(dirname(absolute), document.root ?? ".");+ const services = await Promise.all(document.services.map(async (item) => {+ const factory = options.registry.service(item.use);+ if (factory === undefined) throw new Error(`Runtime service adapter ${item.use} is not registered`);+ return await factory({+ root,+ instance: item.instance,+ config: item.config ?? {},+ });+ }));+ const endpoints = await Promise.all(document.endpoints.map(async (item) => {+ const factory = options.registry.endpoint(item.use);+ if (factory === undefined) throw new Error(`Runtime Endpoint adapter ${item.use} is not registered`);+ return await factory({+ root,+ instance: item.instance,+ ...(item.lane === undefined ? {} : { lane: item.lane }),+ config: item.config ?? {},+ });+ }));+ return await createProjectLocalRuntime({+ root,+ ...(document.statePath === undefined ? {} : { statePath: document.statePath }),+ ...(document.artifactPath === undefined ? {} : { artifactPath: document.artifactPath }),+ ...(document.packageLock === undefined ? {} : { packageLock: document.packageLock }),+ runtimeServices: services,+ ...(document.selection === undefined ? {} : { runtimeSelection: document.selection }),+ components: options.components ?? [],+ endpoints,+ allowedPermissions: document.permissions,+ ...(document.scheduling === undefined ? {} : { scheduling: document.scheduling }),+ });+}diff --git a/packages/local/src/index.ts b/packages/local/src/index.tsindex 751a6d87..8bfd3846 100644--- a/packages/local/src/index.ts+++ b/packages/local/src/index.ts@@ -7,4 +7,10 @@ export {createLocalRuntime,createProjectLocalRuntime,} from "./runtime.js";+export {+ createRuntimeFromConfig,+ parseRuntimeConfig,+ RuntimeConfigRegistry,+} from "./config.js";export type * from "./types.js";+export type * from "./config.js";diff --git a/packages/local/test/config.test.ts b/packages/local/test/config.test.tsnew file mode 100644index 00000000..c2e19d96--- /dev/null+++ b/packages/local/test/config.test.ts@@ -0,0 +1,54 @@+import assert from "node:assert/strict";+import { mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import {+ createRuntimeFromConfig,+ parseRuntimeConfig,+ RuntimeConfigRegistry,+} from "@svml/local";++test("declarative Runtime config starts the domain-neutral local defaults", async () => {+ const root = await mkdtemp(join(tmpdir(), "svml-runtime-config-"));+ const path = join(root, "svml.runtime.json");+ await writeFile(path, JSON.stringify({+ format: "svml.runtime-config@1",+ services: [],+ endpoints: [],+ permissions: [],+ scheduling: { maxConcurrency: 3, lanes: { generation: 2 } },+ }));+ const runtime = await createRuntimeFromConfig(path, { registry: new RuntimeConfigRegistry() });+ try {+ assert.equal((await runtime.status("absent")).build, undefined);+ } finally {+ await runtime.close();+ }+});++test("Runtime config is closed data and rejects unknown environment authority", () => {+ assert.throws(() => parseRuntimeConfig({+ format: "svml.runtime-config@1",+ services: [],+ endpoints: [],+ permissions: [],+ apiKey: "must-not-live-here",+ }), /does not accept apiKey/u);+});++test("declarative adapters are explicit and never guessed", async () => {+ const root = await mkdtemp(join(tmpdir(), "svml-runtime-adapter-"));+ const path = join(root, "svml.runtime.json");+ await writeFile(path, JSON.stringify({+ format: "svml.runtime-config@1",+ services: [],+ endpoints: [{ use: "example.missing", instance: "missing", config: {} }],+ permissions: [],+ }));+ await assert.rejects(+ async () => await createRuntimeFromConfig(path, { registry: new RuntimeConfigRegistry() }),+ /adapter example\.missing is not registered/u,+ );+});diff --git a/packages/package-loader-node/src/lock.ts b/packages/package-loader-node/src/lock.tsindex 46810b20..5efdd5f3 100644--- a/packages/package-loader-node/src/lock.ts+++ b/packages/package-loader-node/src/lock.ts@@ -220,6 +220,9 @@ function activationMetadata(value: NodePackageActivation): unknown {.localeCompare(`${right.type.module.name}@${right.type.module.version}#${right.type.name}`),),})).sort((left, right) => left.name.localeCompare(right.name)),+ runFragments: Object.entries(value.runFragments ?? {})+ .map(([name, fragment]) => ({ name, digest: fragment.id }))+ .sort((left, right) => left.name.localeCompare(right.name)),};}diff --git a/packages/package-loader-node/src/types.ts b/packages/package-loader-node/src/types.tsindex 1bed7b4f..beca91ea 100644--- a/packages/package-loader-node/src/types.ts+++ b/packages/package-loader-node/src/types.ts@@ -1,6 +1,7 @@import type { RegisteredModulePackage } from "@svml/compiler-node";import type { ComponentPackage } from "@svml/component-kit";import type { AuthorFrontend } from "@svml/elaborator";+import type { GraphFragment } from "@svml/elaborator";import type { Digest, ModuleRef } from "@svml/protocol";import type {RawSurfaceHandler,@@ -35,6 +36,8 @@ export type NodePackageActivation = {readonly frontends?: readonly AuthorFrontend[];readonly textSurfaces?: readonly NodeTextSurfaceFacet[];readonly components?: readonly ComponentPackage[];+ /** Trusted Run-Graph Fragments, addressable from `.svrun` imports by package and export name. */+ readonly runFragments?: Readonly<Record<string, GraphFragment>>;};export type LockedPackageArtifact = {diff --git a/packages/run/README.md b/packages/run/README.mdnew file mode 100644index 00000000..8ab87e17--- /dev/null+++ b/packages/run/README.md@@ -0,0 +1,48 @@+# `@svml/run`++The official human-readable frontend for one execution intention. It compiles a `.svrun` file into+three ordinary domain-neutral facts before Core starts:++```text+Run Graph[] + Satisfaction[] + Target[]+```++It is deliberately separate from both author source and deployment configuration:++- `.svml` says what the author means;+- `.svrun` says what this run demands and which explicit Candidates satisfy which outputs;+- `svml.runtime.json` says where and under which permissions the frozen plan executes.++```xml+<svrun version="1" source="./main.svml" targets="delivery">+ <target-set id="delivery">+ <target output="final.video" accepts="substitute"/>+ </target-set>++ <build-record id="opening" build="prior-build-id" output="opening-take"/>+ <satisfy output="opening-take" candidate="opening" fidelity="substitute"/>+</svrun>+```++`<value>` attaches a typed zero-input `StoredValue` from JSON. `<build-record>` extracts one typed+Record from a verified prior Build by its prior Logical Output id; it is independent of the current+output later named by `<satisfy>`. Neither is a Core Pin primitive. `<fragment>` instantiates a+trusted package-exported Run Fragment and may expose several Candidates backed by one shared+Operation:++```xml+<import from="@acme/preview" as="preview"/>+<fragment id="one-black-frame" using="preview:black-video">+ <input name="duration" from="opening.duration"/>+</fragment>+<satisfy output="opening.visual"+ candidate="one-black-frame.video"+ fidelity="substitute"/>+```++Two `<fragment>` declarations are two instances and therefore may execute twice. One declaration+with several exports is one instance and shares its internal Operations. Imports must form the+opening prologue and can resolve only Fragments exposed by explicitly activated trusted packages.++`.svrun` cannot declare credentials, Providers, Store paths, queues, Endpoint bindings or inline+execution callbacks.diff --git a/packages/run/package.json b/packages/run/package.jsonnew file mode 100644index 00000000..d6db07d5--- /dev/null+++ b/packages/run/package.json@@ -0,0 +1,18 @@+{+ "name": "@svml/run",+ "version": "0.0.0-dev",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "dependencies": {+ "@svml/elaborator": "workspace:*",+ "@svml/protocol": "workspace:*",+ "@svml/realization": "workspace:*",+ "@svml/text": "workspace:*"+ },+ "devDependencies": {+ "@svml/core": "workspace:*"+ }+}diff --git a/packages/run/src/index.ts b/packages/run/src/index.tsnew file mode 100644index 00000000..165ca200--- /dev/null+++ b/packages/run/src/index.ts@@ -0,0 +1,4 @@+export { RunFragmentRegistry } from "./registry.js";+export { resolveRunDocument } from "./resolve.js";+export { parseRunDocument, parseTypeRef, RunSyntaxError } from "./syntax.js";+export type * from "./types.js";diff --git a/packages/run/src/registry.ts b/packages/run/src/registry.tsnew file mode 100644index 00000000..e5fb879f--- /dev/null+++ b/packages/run/src/registry.ts@@ -0,0 +1,24 @@+import type { GraphFragment } from "@svml/elaborator";++import type { RunFragmentPackage, RunFragmentRegistryLike } from "./types.js";++export class RunFragmentRegistry implements RunFragmentRegistryLike {+ readonly #packages = new Map<string, ReadonlyMap<string, GraphFragment>>();++ register(item: RunFragmentPackage): void {+ if (item.name.trim().length === 0) throw new Error("Run Fragment package name must not be empty");+ if (this.#packages.has(item.name)) throw new Error(`Run Fragment package ${item.name} is already registered`);+ const fragments = new Map<string, GraphFragment>();+ for (const [name, fragment] of Object.entries(item.fragments)) {+ if (name.trim().length === 0) throw new Error(`${item.name} has an empty Run Fragment name`);+ if (fragments.has(name)) throw new Error(`${item.name} repeats Run Fragment ${name}`);+ fragments.set(name, fragment);+ }+ if (fragments.size === 0) throw new Error(`Run Fragment package ${item.name} exports no Fragments`);+ this.#packages.set(item.name, fragments);+ }++ resolve(packageName: string, fragmentName: string): GraphFragment | undefined {+ return this.#packages.get(packageName)?.get(fragmentName);+ }+}diff --git a/packages/run/src/resolve.ts b/packages/run/src/resolve.tsnew file mode 100644index 00000000..a9f6518c--- /dev/null+++ b/packages/run/src/resolve.ts@@ -0,0 +1,120 @@+import {+ elaborateGraphFragment,+ exportRunFragment,+ resolveCompiledSourceExport,+} from "@svml/elaborator";+import type { GraphValueRef, StoredValue } from "@svml/protocol";+import {+ createBuildRecordCandidate,+ createProvidedCandidate,+ sealRunGraph,+} from "@svml/realization";++import type {+ ResolveRunDocumentContext,+ ResolvedRunDocument,+ RunDocument,+} from "./types.js";++function authorRef(context: ResolveRunDocumentContext, name: string): GraphValueRef {+ const exported = resolveCompiledSourceExport(context.compilation, name);+ return exported.ref;+}++function logicalOutput(context: ResolveRunDocumentContext, name: string): string {+ const exported = resolveCompiledSourceExport(context.compilation, name);+ if (exported.ref.kind !== "logical-output") {+ throw new Error(`${name} is an authored Record, not a realizable Logical Output`);+ }+ return exported.ref.id;+}++function assertStoredValue(value: unknown, subject: string): asserts value is StoredValue {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ throw new Error(`${subject} must contain one StoredValue object`);+ }+ const item = value as Record<string, unknown>;+ if (item.kind === "inline" && Object.hasOwn(item, "value")) return;+ if (item.kind === "blob"+ && typeof item.digest === "string"+ && Number.isSafeInteger(item.size)+ && typeof item.mediaType === "string") return;+ throw new Error(`${subject} is not an inline or blob StoredValue`);+}++/** Resolve both source graphs completely before Core derives a finite BuildPlan. */+export async function resolveRunDocument(+ document: RunDocument,+ context: ResolveRunDocumentContext,+): Promise<ResolvedRunDocument> {+ const imports = new Map(document.imports.map((item) => [item.as, item.from]));+ const candidates = [];+ const operations = [];+ const candidateNames = new Map<string, string>();+ const bindCandidateName = (name: string, candidate: string): void => {+ if (candidateNames.has(name)) throw new Error(`Run Candidate reference ${name} is declared twice`);+ candidateNames.set(name, candidate);+ };++ for (const declaration of document.candidates) {+ if (declaration.kind === "provided") {+ const value = await context.readStoredValue(declaration.from);+ assertStoredValue(value, declaration.from);+ const candidate = createProvidedCandidate({ type: declaration.type, value });+ candidates.push(candidate);+ bindCandidateName(declaration.id, candidate.id);+ continue;+ }+ if (declaration.kind === "build-record") {+ const build = await context.readBuild(declaration.build);+ if (build === undefined) throw new Error(`Build ${declaration.build} does not exist`);+ const candidate = createBuildRecordCandidate({+ build,+ sourceOutput: declaration.output,+ });+ candidates.push(candidate);+ bindCandidateName(declaration.id, candidate.id);+ continue;+ }+ const packageName = imports.get(declaration.using.alias);+ if (packageName === undefined) throw new Error(`Run Fragment alias ${declaration.using.alias} is not imported`);+ const fragment = context.fragments.resolve(packageName, declaration.using.name);+ if (fragment === undefined) {+ throw new Error(`${packageName} exports no Run Fragment ${declaration.using.name}`);+ }+ const instance = elaborateGraphFragment(context.compilation.program, fragment, {+ id: declaration.id,+ fragment: fragment.id,+ inputs: Object.fromEntries(declaration.inputs.map((item) => [item.name, authorRef(context, item.from)])),+ });+ const contribution = exportRunFragment(instance, declaration.exports);+ candidates.push(...contribution.candidates);+ operations.push(...contribution.operations);+ for (const item of contribution.exports) bindCandidateName(`${declaration.id}.${item.name}`, item.candidate);+ }++ const satisfactions = document.satisfactions.map((item) => {+ const candidate = candidateNames.get(item.candidate);+ if (candidate === undefined) throw new Error(`Unknown Run Candidate ${item.candidate}`);+ return {+ output: logicalOutput(context, item.output),+ candidate,+ fidelity: item.fidelity,+ } as const;+ });+ const selected = document.targetSets.find((item) => item.id === document.selectedTargets)!;+ const graphs = candidates.length === 0+ ? []+ : [sealRunGraph({+ sourceGraph: context.compilation.elaboration.graph.id,+ candidates,+ operations,+ })];+ return {+ source: document.source,+ targets: selected.targets.map((item) => ({ name: item.output, accepts: item.accepts })),+ graphs,+ satisfactions,+ candidates: Object.fromEntries([...candidateNames.entries()].sort(([left], [right]) => left.localeCompare(right))),+ };+}diff --git a/packages/run/src/syntax.ts b/packages/run/src/syntax.tsnew file mode 100644index 00000000..902ec6d9--- /dev/null+++ b/packages/run/src/syntax.ts@@ -0,0 +1,241 @@+import type { CanonicalValue, TypeRef } from "@svml/protocol";+import {+ parseStructuredElement,+ skipTextTrivia,+} from "@svml/text";+import type {+ SourceUnit,+ StructuredElement,+ StructuredNode,+ TextAttributeValue,+} from "@svml/text";++import type {+ RunBuildRecord,+ RunCandidateDeclaration,+ RunDocument,+ RunFragmentInstance,+ RunImport,+ RunProvidedValue,+ RunSatisfaction,+ RunTargetSet,+} from "./types.js";++export class RunSyntaxError extends Error {+ readonly code: string;+ readonly offset: number;++ constructor(code: string, message: string, offset: number) {+ super(message);+ this.name = "RunSyntaxError";+ this.code = code;+ this.offset = offset;+ }+}++function fail(element: StructuredElement, code: string, message: string): never {+ throw new RunSyntaxError(code, message, element.range.start);+}++function elements(element: StructuredElement): readonly StructuredElement[] {+ const result: StructuredElement[] = [];+ for (const child of element.children) {+ if (child.kind === "text") {+ if (child.value.trim().length > 0) fail(element, "RUN_TEXT", `<${element.name}> only accepts elements`);+ continue;+ }+ result.push(child);+ }+ return result;+}++function exactAttributes(element: StructuredElement, allowed: readonly string[]): void {+ const unknown = Object.keys(element.attributes).filter((name) => !allowed.includes(name));+ if (unknown.length > 0) fail(element, "RUN_ATTRIBUTE", `<${element.name}> does not accept ${unknown[0]}`);+}++function stringAttribute(element: StructuredElement, name: string, required = true): string | undefined {+ const value = element.attributes[name];+ if (value === undefined) {+ if (required) fail(element, "RUN_ATTRIBUTE", `<${element.name}> requires ${name}`);+ return undefined;+ }+ if (typeof value !== "string") fail(element, "RUN_ATTRIBUTE", `<${element.name}> ${name} must be a string`);+ const normalized = value.trim();+ if (normalized.length === 0) fail(element, "RUN_ATTRIBUTE", `<${element.name}> ${name} must not be empty`);+ return normalized;+}++function empty(element: StructuredElement): void {+ if (elements(element).length > 0) fail(element, "RUN_CHILD", `<${element.name}> must be empty`);+}++function conformance(element: StructuredElement, name: string): "exact" | "substitute" {+ const value = stringAttribute(element, name);+ if (value !== "exact" && value !== "substitute") {+ fail(element, "RUN_CONFORMANCE", `<${element.name}> ${name} must be exact or substitute`);+ }+ return value;+}++export function parseTypeRef(value: string): TypeRef {+ const hash = value.lastIndexOf("#");+ const version = hash <= 0 ? -1 : value.lastIndexOf("@", hash);+ if (hash <= 0 || version <= 0 || version === hash - 1 || hash === value.length - 1) {+ throw new Error(`Type ${value} must use package@version#Type`);+ }+ return {+ module: { name: value.slice(0, version), version: value.slice(version + 1, hash) },+ name: value.slice(hash + 1),+ };+}++function importDeclaration(element: StructuredElement): RunImport {+ exactAttributes(element, ["from", "as"]);+ empty(element);+ return { from: stringAttribute(element, "from")!, as: stringAttribute(element, "as")! };+}++function targetSet(element: StructuredElement): RunTargetSet {+ exactAttributes(element, ["id"]);+ const targets = elements(element).map((child) => {+ if (child.name !== "target") fail(child, "RUN_CHILD", `<target-set> does not accept <${child.name}>`);+ exactAttributes(child, ["output", "accepts"]);+ empty(child);+ return { output: stringAttribute(child, "output")!, accepts: conformance(child, "accepts") };+ });+ if (targets.length === 0) fail(element, "RUN_TARGETS", `<target-set> must contain at least one target`);+ return { id: stringAttribute(element, "id")!, targets };+}++function provided(element: StructuredElement): RunProvidedValue {+ exactAttributes(element, ["id", "type", "from"]);+ empty(element);+ let type: TypeRef;+ try {+ type = parseTypeRef(stringAttribute(element, "type")!);+ } catch (error) {+ fail(element, "RUN_TYPE", error instanceof Error ? error.message : String(error));+ }+ return {+ kind: "provided",+ id: stringAttribute(element, "id")!,+ type,+ from: stringAttribute(element, "from")!,+ };+}++function buildRecord(element: StructuredElement): RunBuildRecord {+ exactAttributes(element, ["id", "build", "output"]);+ empty(element);+ return {+ kind: "build-record",+ id: stringAttribute(element, "id")!,+ build: stringAttribute(element, "build")!,+ output: stringAttribute(element, "output")!,+ };+}++function fragment(element: StructuredElement): RunFragmentInstance {+ exactAttributes(element, ["id", "using"]);+ const using = stringAttribute(element, "using")!;+ const separator = using.indexOf(":");+ if (separator <= 0 || separator === using.length - 1) {+ fail(element, "RUN_FRAGMENT_REF", `<fragment> using must be alias:fragment`);+ }+ const inputs: { readonly name: string; readonly from: string }[] = [];+ const exports: string[] = [];+ for (const child of elements(element)) {+ if (child.name === "input") {+ exactAttributes(child, ["name", "from"]);+ empty(child);+ inputs.push({ name: stringAttribute(child, "name")!, from: stringAttribute(child, "from")! });+ continue;+ }+ if (child.name === "export") {+ exactAttributes(child, ["name"]);+ empty(child);+ exports.push(stringAttribute(child, "name")!);+ continue;+ }+ fail(child, "RUN_CHILD", `<fragment> does not accept <${child.name}>`);+ }+ unique(inputs.map((item) => item.name), `${stringAttribute(element, "id")} Fragment input`, element);+ unique(exports, `${stringAttribute(element, "id")} Fragment export`, element);+ return {+ kind: "fragment",+ id: stringAttribute(element, "id")!,+ using: { alias: using.slice(0, separator), name: using.slice(separator + 1) },+ inputs,+ ...(exports.length === 0 ? {} : { exports }),+ };+}++function satisfaction(element: StructuredElement): RunSatisfaction {+ exactAttributes(element, ["output", "candidate", "fidelity"]);+ empty(element);+ return {+ output: stringAttribute(element, "output")!,+ candidate: stringAttribute(element, "candidate")!,+ fidelity: conformance(element, "fidelity"),+ };+}++function unique(values: readonly string[], subject: string, element: StructuredElement): void {+ const seen = new Set<string>();+ for (const value of values) {+ if (seen.has(value)) fail(element, "RUN_DUPLICATE", `${subject} repeats ${value}`);+ seen.add(value);+ }+}++/** Parse only the public Run language. No package code, Runtime or Provider executes here. */+export function parseRunDocument(name: string, text: string): RunDocument {+ const source: SourceUnit = { name, text };+ const start = skipTextTrivia(source, 0);+ const parsed = parseStructuredElement(source, start);+ const end = skipTextTrivia(source, parsed.nextOffset);+ if (end !== text.length) throw new RunSyntaxError("RUN_TRAILING", "Only trivia may follow </svrun>", end);+ const root = parsed.element;+ if (root.name !== "svrun") fail(root, "RUN_ROOT", "Run document root must be <svrun>");+ exactAttributes(root, ["version", "source", "targets"]);+ if (stringAttribute(root, "version") !== "1") fail(root, "RUN_VERSION", "Only .svrun version 1 is supported");++ const imports: RunImport[] = [];+ const targetSets: RunTargetSet[] = [];+ const candidates: RunCandidateDeclaration[] = [];+ const satisfactions: RunSatisfaction[] = [];+ let bodyStarted = false;+ for (const child of elements(root)) {+ if (child.name === "import") {+ if (bodyStarted) fail(child, "RUN_IMPORT_ORDER", "Run imports must form the opening prologue");+ imports.push(importDeclaration(child));+ continue;+ }+ bodyStarted = true;+ if (child.name === "target-set") targetSets.push(targetSet(child));+ else if (child.name === "value") candidates.push(provided(child));+ else if (child.name === "build-record") candidates.push(buildRecord(child));+ else if (child.name === "fragment") candidates.push(fragment(child));+ else if (child.name === "satisfy") satisfactions.push(satisfaction(child));+ else fail(child, "RUN_CHILD", `<svrun> does not accept <${child.name}>`);+ }++ unique(imports.map((item) => item.as), "Run import alias", root);+ unique(targetSets.map((item) => item.id), "Target set", root);+ unique(candidates.map((item) => item.id), "Candidate declaration", root);+ for (const set of targetSets) unique(set.targets.map((item) => item.output), `${set.id} target`, root);+ const selectedTargets = stringAttribute(root, "targets")!;+ if (!targetSets.some((item) => item.id === selectedTargets)) {+ fail(root, "RUN_TARGET_SET", `Selected target set ${selectedTargets} is not declared`);+ }+ return {+ format: "svml.run-document@1",+ source: stringAttribute(root, "source")!,+ selectedTargets,+ imports,+ targetSets,+ candidates,+ satisfactions,+ };+}diff --git a/packages/run/src/types.ts b/packages/run/src/types.tsnew file mode 100644index 00000000..07295fd1--- /dev/null+++ b/packages/run/src/types.ts@@ -0,0 +1,106 @@+import type {+ CompiledSourceClosure,+ GraphFragment,+} from "@svml/elaborator";+import type {+ BuildState,+ CanonicalValue,+ NeedAcceptance,+ Satisfaction,+ StoredValue,+ TypeRef,+} from "@svml/protocol";+import type { RunGraph } from "@svml/realization";++export type RunImport = {+ readonly from: string;+ readonly as: string;+};++export type RunTarget = {+ readonly output: string;+ readonly accepts: NeedAcceptance;+};++export type RunTargetSet = {+ readonly id: string;+ readonly targets: readonly RunTarget[];+};++export type RunProvidedValue = {+ readonly kind: "provided";+ readonly id: string;+ readonly type: TypeRef;+ /** File containing one StoredValue JSON object. */+ readonly from: string;+ readonly provenance?: CanonicalValue;+};++export type RunBuildRecord = {+ readonly kind: "build-record";+ readonly id: string;+ readonly build: string;+ /** Logical Output id selected by the prior Build; independent of the current author graph. */+ readonly output: string;+};++export type RunFragmentInput = {+ readonly name: string;+ /** Public author-source export. */+ readonly from: string;+};++export type RunFragmentInstance = {+ readonly kind: "fragment";+ readonly id: string;+ readonly using: {+ readonly alias: string;+ readonly name: string;+ };+ readonly inputs: readonly RunFragmentInput[];+ /** Omitted means every Fragment export. */+ readonly exports?: readonly string[];+};++export type RunCandidateDeclaration = RunProvidedValue | RunBuildRecord | RunFragmentInstance;++export type RunSatisfaction = {+ readonly output: string;+ /** Candidate id, or `fragment-instance.export`. */+ readonly candidate: string;+ readonly fidelity: "exact" | "substitute";+};++export type RunDocument = {+ readonly format: "svml.run-document@1";+ readonly source: string;+ readonly selectedTargets: string;+ readonly imports: readonly RunImport[];+ readonly targetSets: readonly RunTargetSet[];+ readonly candidates: readonly RunCandidateDeclaration[];+ readonly satisfactions: readonly RunSatisfaction[];+};++export type RunFragmentPackage = {+ readonly name: string;+ readonly fragments: Readonly<Record<string, GraphFragment>>;+};++export interface RunFragmentRegistryLike {+ resolve(packageName: string, fragmentName: string): GraphFragment | undefined;+}++export type ResolveRunDocumentContext = {+ readonly compilation: CompiledSourceClosure;+ readonly fragments: RunFragmentRegistryLike;+ readonly readStoredValue: (from: string) => Promise<StoredValue> | StoredValue;+ readonly readBuild: (id: string) => Promise<BuildState | undefined> | BuildState | undefined;+};++export type ResolvedRunDocument = {+ readonly source: string;+ readonly targets: readonly { readonly name: string; readonly accepts: NeedAcceptance }[];+ readonly graphs: readonly RunGraph[];+ readonly satisfactions: readonly Satisfaction[];+ readonly candidates: Readonly<Record<string, string>>;+};diff --git a/packages/run/test/run.test.ts b/packages/run/test/run.test.tsnew file mode 100644index 00000000..cf8b066f--- /dev/null+++ b/packages/run/test/run.test.ts@@ -0,0 +1,230 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ createResolvedClosure,+ digestOf,+ link,+ sealBuildRequest,+ sealCompiledGraph,+ sealRecord,+ sealTypedModule,+ start,+} from "@svml/core";+import {+ sealGraphFragment,+} from "@svml/elaborator";+import type { CompiledSourceClosure } from "@svml/elaborator";+import type { ModuleManifest, ProducerRef, TypeRef } from "@svml/protocol";+import { resolveRealization } from "@svml/realization";+import {+ parseRunDocument,+ resolveRunDocument,+ RunFragmentRegistry,+} from "@svml/run";++const moduleRef = { name: "example.run", version: "1" } as const;+const promptType = { module: moduleRef, name: "Prompt" } satisfies TypeRef;+const mediaType = { module: moduleRef, name: "Media" } satisfies TypeRef;+const defaultProducer = { module: moduleRef, name: "default" } satisfies ProducerRef;+const previewProducer = { module: moduleRef, name: "preview" } satisfies ProducerRef;++const manifest: ModuleManifest = {+ format: "svml.module@0",+ name: moduleRef.name,+ version: moduleRef.version,+ dependencies: [],+ types: [+ { name: promptType.name, schema: { kind: "string" } },+ { name: mediaType.name, schema: { kind: "string" } },+ ],+ capabilities: [],+ surfaces: [],+ producers: [defaultProducer, previewProducer].map((producer) => ({+ name: producer.name,+ inputs: [{ name: "prompt", type: promptType }],+ outputs: [{ name: "media", type: mediaType }],+ needs: [],+ implementation: {+ kind: "registered" as const,+ locator: `example.run/${producer.name}`,+ digest: digestOf(`example.run/${producer.name}@1`),+ },+ })),+};++function fixture(): CompiledSourceClosure {+ const closure = createResolvedClosure([manifest]);+ const prompt = sealRecord({+ id: "prompt:root",+ type: promptType,+ value: { kind: "inline", value: "A deliberate preview." },+ conformance: "exact",+ origin: {+ kind: "authored",+ sourceDigest: digestOf("run-source"),+ frontendClosureDigest: digestOf("run-frontend"),+ },+ });+ const program = link(closure, [sealTypedModule({+ id: "author:run",+ closureDigest: closure.digest,+ records: [prompt],+ })]);+ const graph = sealCompiledGraph({+ program: program.semanticDigest,+ outputs: ["left", "right"].map((id) => ({+ id,+ type: mediaType,+ primary: "default:candidate",+ semanticInputs: [{ kind: "record" as const, id: prompt.id }],+ })),+ candidates: [{+ id: "default:candidate",+ type: mediaType,+ root: { kind: "operation", result: { kind: "operation-result", operation: "default:operation" } },+ }],+ operations: [{+ id: "default:operation",+ producer: defaultProducer,+ inputs: { prompt: { kind: "record", id: prompt.id } },+ result: { kind: "output", name: "media", record: "default:record" },+ }],+ });+ return {+ program,+ elaboration: { graph },+ exports: [+ { name: "prompt", type: promptType, ref: { kind: "record", id: prompt.id } },+ { name: "left", type: mediaType, ref: { kind: "logical-output", id: "left" } },+ { name: "right", type: mediaType, ref: { kind: "logical-output", id: "right" } },+ ],+ } as unknown as CompiledSourceClosure;+}++function previewFragment() {+ const input = { kind: "fragment-input" as const, name: "prompt" };+ const operation = { kind: "fragment-operation" as const, operation: "preview" };+ return sealGraphFragment({+ name: "shared-preview",+ inputs: [{ name: "prompt", type: promptType }],+ operations: [{+ id: "preview",+ producer: previewProducer,+ inputs: { prompt: input },+ result: { kind: "output", name: "media" },+ }],+ exports: ["first", "second"].map((name) => ({+ name,+ type: mediaType,+ root: operation,+ semanticInputs: ["prompt"],+ fidelity: "substitute" as const,+ })),+ });+}++test(".svrun compiles one multi-export Fragment instance before execution", async () => {+ const document = parseRunDocument("preview.svrun", `<svrun version="1" source="./main.svml" targets="preview">+ <import from="@example/run-preview" as="preview"/>+ <target-set id="preview">+ <target output="left" accepts="substitute"/>+ <target output="right" accepts="substitute"/>+ </target-set>+ <fragment id="one-call" using="preview:shared">+ <input name="prompt" from="prompt"/>+ </fragment>+ <satisfy output="left" candidate="one-call.first" fidelity="substitute"/>+ <satisfy output="right" candidate="one-call.second" fidelity="substitute"/>+ </svrun>`);+ const compilation = fixture();+ const fragments = new RunFragmentRegistry();+ fragments.register({ name: "@example/run-preview", fragments: { shared: previewFragment() } });+ const run = await resolveRunDocument(document, {+ compilation,+ fragments,+ readStoredValue() { throw new Error("not used"); },+ readBuild() { throw new Error("not used"); },+ });+ assert.equal(run.graphs.length, 1);+ assert.equal(run.graphs[0]!.operations.length, 1);+ assert.equal(Object.keys(run.candidates).length, 2);+ const realized = resolveRealization(+ compilation.program,+ compilation.elaboration.graph,+ run.graphs,+ );+ const request = sealBuildRequest({+ graph: realized.graph.id,+ targets: run.targets.map((item) => ({ output: item.name, accepts: item.accepts })),+ satisfactions: run.satisfactions,+ });+ const state = start(compilation.program, realized.graph, request);+ assert.equal(state.plan.steps.length, 1);+ assert.equal(state.plan.steps[0]!.producer.name, "preview");+});++test("separate Fragment declarations remain separate executions", async () => {+ const document = parseRunDocument("preview.svrun", `<svrun version="1" source="./main.svml" targets="preview">+ <import from="@example/run-preview" as="preview"/>+ <target-set id="preview"><target output="left" accepts="substitute"/><target output="right" accepts="substitute"/></target-set>+ <fragment id="left-call" using="preview:shared"><input name="prompt" from="prompt"/><export name="first"/></fragment>+ <fragment id="right-call" using="preview:shared"><input name="prompt" from="prompt"/><export name="second"/></fragment>+ <satisfy output="left" candidate="left-call.first" fidelity="substitute"/>+ <satisfy output="right" candidate="right-call.second" fidelity="substitute"/>+ </svrun>`);+ const compilation = fixture();+ const fragments = new RunFragmentRegistry();+ fragments.register({ name: "@example/run-preview", fragments: { shared: previewFragment() } });+ const run = await resolveRunDocument(document, {+ compilation,+ fragments,+ readStoredValue() { throw new Error("not used"); },+ readBuild() { throw new Error("not used"); },+ });+ assert.equal(run.graphs[0]!.operations.length, 2);+ assert.equal(new Set(run.graphs[0]!.operations.map((item) => item.id)).size, 2);+});++test("a Provided Value is an ordinary zero-input Candidate selected by Satisfaction", async () => {+ const document = parseRunDocument("fixed.svrun", `<svrun version="1" source="./main.svml" targets="preview">+ <target-set id="preview"><target output="left" accepts="substitute"/></target-set>+ <value id="fixed" type="example.run@1#Media" from="./fixed.json"/>+ <satisfy output="left" candidate="fixed" fidelity="substitute"/>+ </svrun>`);+ const compilation = fixture();+ const run = await resolveRunDocument(document, {+ compilation,+ fragments: new RunFragmentRegistry(),+ readStoredValue(from) {+ assert.equal(from, "./fixed.json");+ return { kind: "inline", value: "already rendered" };+ },+ readBuild() { throw new Error("not used"); },+ });+ const realized = resolveRealization(compilation.program, compilation.elaboration.graph, run.graphs);+ const state = start(compilation.program, realized.graph, sealBuildRequest({+ graph: realized.graph.id,+ targets: run.targets.map((item) => ({ output: item.name, accepts: item.accepts })),+ satisfactions: run.satisfactions,+ }));+ assert.equal(state.plan.steps.length, 0);+ assert.equal(state.records.find((item) => item.id === state.plan.goals[0]!.record)?.value.kind, "inline");+});++test("Run imports are a prologue and Runtime settings are not language elements", () => {+ assert.throws(+ () => parseRunDocument("bad.svrun", `<svrun version="1" source="main.svml" targets="x">+ <target-set id="x"><target output="film" accepts="exact"/></target-set>+ <import from="@example/run" as="run"/>+ </svrun>`),+ /opening prologue/u,+ );+ assert.throws(+ () => parseRunDocument("bad.svrun", `<svrun version="1" source="main.svml" targets="x">+ <target-set id="x"><target output="film" accepts="exact"/></target-set>+ <provider name="kie"/>+ </svrun>`),+ /does not accept <provider>/u,+ );+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6dbb9afc..9bf5cda4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -147,6 +147,9 @@ importers:packages/cli:dependencies:+ '@svml/artifact-store-s3':+ specifier: workspace:*+ version: link:../artifact-store-s3'@svml/compiler-node':specifier: workspace:*version: link:../compiler-node@@ -162,9 +165,30 @@ importers:'@svml/protocol':specifier: workspace:*version: link:../protocol+ '@svml/provider-google-vertex':+ specifier: workspace:*+ version: link:../provider-google-vertex+ '@svml/provider-hyperframes-local':+ specifier: workspace:*+ version: link:../provider-hyperframes-local+ '@svml/provider-kie':+ specifier: workspace:*+ version: link:../provider-kie+ '@svml/provider-media-local':+ specifier: workspace:*+ version: link:../provider-media-local+ '@svml/provider-whisperx-local':+ specifier: workspace:*+ version: link:../provider-whisperx-local'@svml/realization':specifier: workspace:*version: link:../realization+ '@svml/run':+ specifier: workspace:*+ version: link:../run+ '@svml/runtime':+ specifier: workspace:*+ version: link:../runtimepackages/compiler-node:dependencies:@@ -847,6 +871,25 @@ importers:specifier: workspace:*version: link:../validation+ packages/run:+ dependencies:+ '@svml/elaborator':+ specifier: workspace:*+ version: link:../elaborator+ '@svml/protocol':+ specifier: workspace:*+ version: link:../protocol+ '@svml/realization':+ specifier: workspace:*+ version: link:../realization+ '@svml/text':+ specifier: workspace:*+ version: link:../text+ devDependencies:+ '@svml/core':+ specifier: workspace:*+ version: link:../core+packages/runtime:dependencies:'@svml/core':diff --git a/tsconfig.v2.json b/tsconfig.v2.jsonindex 2dbbdeb4..dfe262d8 100644--- a/tsconfig.v2.json+++ b/tsconfig.v2.json@@ -20,6 +20,7 @@"@svml/speech-take": ["packages/speech-take/src/index.ts"],"@svml/elaborator": ["packages/elaborator/src/index.ts"],"@svml/realization": ["packages/realization/src/index.ts"],+ "@svml/run": ["packages/run/src/index.ts"],"@svml/runtime": ["packages/runtime/src/index.ts"],"@svml/store-sqlite": ["packages/store-sqlite/src/index.ts"],"@svml/artifact-store-fs": ["packages/artifact-store-fs/src/index.ts"],