Skip to content

armgit / hypit

Public Imported from GitHub
0

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.

feat: let a Provider declare the external program it needs

kashorin90acd445ddaa
diff --git a/examples/echo-pro-aroll/svml.runtime-packages.lock b/examples/echo-pro-aroll/svml.runtime-packages.lock
index fb0b624f..cba08eb5 100644
--- a/examples/echo-pro-aroll/svml.runtime-packages.lock
+++ b/examples/echo-pro-aroll/svml.runtime-packages.lock
@@ -129,7 +129,7 @@
{
"name": "@narratage/provider-whisperx-local",
"version": "0.0.0-dev",
- "digest": "sha256:fcea064388755c71c7d178900bf77488cf9dbe57c2746b2969dca751f73940de"
+ "digest": "sha256:f1abef0bb16d172d2d013b1e44cedcd77bc1beeaa46590b90774892fd948514f"
},
{
"name": "@narratage/render-hyperframes",
@@ -144,7 +144,7 @@
{
"name": "@narratage/runtime-adapter",
"version": "0.0.0-dev",
- "digest": "sha256:c8871a16a909ec7259180ca2f8db03abb38977675f545dd2b8ec7389b8c8a0ed"
+ "digest": "sha256:532f529daa0334c393c94faa99268e9f216b1e3fb760440e8d4f9b9b1e3ce324"
},
{
"name": "@narratage/runtime",
@@ -850,7 +850,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:b2636492ab0b0b500d674899ab2ff14fc61c7f2b22ef44eb8f816f141b21ec4d",
- "closureDigest": "sha256:ff3178552036273ca7397ed62e58ebe5184fd0e324f97c2540b7cce0f0503c13"
+ "closureDigest": "sha256:e56b87f20fc177aebaf4f99c374f7c97363384c2ad9c98f6548342fa5b465c45"
},
{
"specifier": "@narratage/provider-hyperframes-local",
@@ -859,7 +859,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:b14b721bdc0c9d5d9ced1c345107c92a3a5878f3383dea2ecd3e310442c2a40c",
- "closureDigest": "sha256:3a02162d681f5dca81f341d7580b220b4ebe3b02a3728ad3aae6923c621705f5"
+ "closureDigest": "sha256:b86d3e37edbdbc3d64cb494897b02697a35e5098e80ce99cf19a87b1f22a6f4b"
},
{
"specifier": "@narratage/provider-kie",
@@ -868,7 +868,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:e61ebb911a33d4c5d0e4e4ee4fb69cdb790f4ced050ef35f7472bfbd72013d9b",
- "closureDigest": "sha256:d2444554de53333f48b4516aae6c8a0dd6632d524aeacefa79897c322028112e"
+ "closureDigest": "sha256:fca0be1ad55d4f5cd6c871d7004865bb6339213d7678ac3b6e795adf0a77c978"
},
{
"specifier": "@narratage/provider-media-local",
@@ -877,7 +877,7 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:701abcc923bf8a711c20b6e308d8cc8be27bf560f249b8c5a801e1dbd9cb3979",
- "closureDigest": "sha256:655a1d9f5a823639202005364821ab0e91a69f4cb1c0c38c543fb547b5b42646"
+ "closureDigest": "sha256:2b8ffcc53158623170425aa94442671e58c167e210e7413e158fce2cdac87db5"
},
{
"specifier": "@narratage/provider-whisperx-local",
@@ -886,8 +886,8 @@
"version": "0.0.0-dev"
},
"facetsDigest": "sha256:3686b84c42cc2b1bcaccf57cbdcda25a15c7d9d3778fb92d25437f9880ed8f5d",
- "closureDigest": "sha256:621f941c2c8c4d65de7ebaaacf9a589de8b85154e04667f04c6e82049e37cfd5"
+ "closureDigest": "sha256:a9a75710e062f02bb8ba55cd5eac6ef2c8622fcddd8908547f336503b1f188ca"
}
],
- "digest": "sha256:ec400ea8518f373094428bf4c4181ba539b5ae726626a3418d8d68e9e4955466"
+ "digest": "sha256:f0cf55a93a5bbc7e9500b20a3c09d49624b5b3fdc49cb5c9d8e4d0fe0e436e83"
}
diff --git a/packages/local/src/config.ts b/packages/local/src/config.ts
index 69558975..583237a8 100644
--- a/packages/local/src/config.ts
+++ b/packages/local/src/config.ts
@@ -9,7 +9,11 @@ import {
isRuntimeAdapterHostFacet,
RuntimeAdapterRegistry,
} from "@narratage/runtime-adapter";
-import type { RuntimeDoctorDiagnostic } from "@narratage/runtime-adapter";
+import type {
+ RuntimeDoctorDiagnostic,
+ RuntimeExternalService,
+ RuntimeServiceState,
+} from "@narratage/runtime-adapter";
import { createProjectLocalRuntime } from "./runtime.js";
import type { LocalRuntime } from "./types.js";
@@ -224,11 +228,11 @@ export async function doctorRuntimeConfig(
for (const item of document.runtimeServices) {
const context = { root, instance: item.instance, config: item.config ?? {} };
try {
- diagnostics.push(...await registry.doctor(item.use, "service", context));
+ diagnostics.push(...await registry.doctor(item.use, "runtime-service", context));
} catch (error) {
diagnostics.push(diagnostic(error, "RUNTIME_ADAPTER_DOCTOR_FAILED", item.instance));
}
- if (!registry.has(item.use, "service")) continue;
+ if (!registry.has(item.use, "runtime-service")) continue;
try {
await registry.createService(item.use, context);
} catch (error) {
@@ -253,6 +257,42 @@ export async function doctorRuntimeConfig(
} catch (error) {
diagnostics.push(diagnostic(error, "RUNTIME_ENDPOINT_CONFIG_INVALID", item.instance));
}
+ // An external program is a prerequisite a Build cannot supply for itself, so
+ // name the command that supplies it here rather than failing mid-Build on a
+ // socket. `RUNTIME_SERVICE_` above is the Runtime's own part; this is the
+ // separate program a deployment must have installed or running.
+ let service: RuntimeExternalService | undefined;
+ try {
+ service = registry.service(item.use, context);
+ } catch (error) {
+ diagnostics.push(diagnostic(error, "EXTERNAL_SERVICE_INVALID", item.instance));
+ }
+ if (service === undefined) continue;
+ let state: RuntimeServiceState;
+ try {
+ state = await service.probe();
+ } catch (error) {
+ diagnostics.push(diagnostic(error, "EXTERNAL_SERVICE_PROBE_FAILED", service.id));
+ continue;
+ }
+ if (state.state === "down") {
+ diagnostics.push({
+ severity: "error",
+ code: "EXTERNAL_SERVICE_DOWN",
+ message: `${service.id} is not usable: ${state.detail}.${
+ service.start === undefined && service.prepare === undefined
+ ? ""
+ : " Bring it up with: narratage services up"}`,
+ subject: service.id,
+ });
+ } else if (state.state === "mismatch") {
+ diagnostics.push({
+ severity: "error",
+ code: "EXTERNAL_SERVICE_MISMATCH",
+ message: `${service.id} is running but differs from this Runtime Profile: ${state.detail}`,
+ subject: service.id,
+ });
+ }
}
return { root, diagnostics };
}
diff --git a/packages/local/test/config.test.ts b/packages/local/test/config.test.ts
index f1d21372..a86e1e7f 100644
--- a/packages/local/test/config.test.ts
+++ b/packages/local/test/config.test.ts
@@ -4,8 +4,11 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
+import { createRuntimeEndpointAdapterFacet } from "@narratage/runtime-adapter";
+
import {
createRuntimeFromConfig,
+ doctorRuntimeConfig,
parseRuntimeConfig,
RuntimeConfigRegistry,
} from "@narratage/local";
@@ -81,3 +84,52 @@ test("runtimeServices names the Runtime's own replaceable parts, apart from exte
);
await rm(root, { recursive: true, force: true });
});
+
+test("doctor names the external program a Provider needs, and the command that supplies it", async () => {
+ const root = await mkdtemp(join(tmpdir(), "svml-external-service-"));
+ const path = join(root, "svml.runtime.json");
+ await writeFile(path, JSON.stringify({
+ format: "svml.runtime-config@1",
+ endpoints: [
+ { use: "example.absent", instance: "absent", config: {} },
+ { use: "example.wrong", instance: "wrong", config: {} },
+ { use: "example.exploding", instance: "exploding", config: {} },
+ ],
+ permissions: [],
+ }));
+
+ const registry = new RuntimeConfigRegistry();
+ const declare = (use: string, service: unknown) =>
+ registry.registerFacet(createRuntimeEndpointAdapterFacet({
+ use,
+ create: () => ({}) as never,
+ service: () => service as never,
+ }));
+ declare("example.absent", {
+ id: "absent-one",
+ start: { command: "uv", args: ["run", "serve"] },
+ probe: async () => ({ state: "down", detail: "nothing is answering at http://127.0.0.1:1" }),
+ });
+ declare("example.wrong", {
+ id: "wrong-one",
+ probe: async () => ({ state: "mismatch", detail: "model is large-v3, expected small" }),
+ });
+ declare("example.exploding", {
+ id: "exploding-one",
+ probe: async () => { throw new Error("the probe itself is broken"); },
+ });
+
+ const { diagnostics } = await doctorRuntimeConfig(path, { registry });
+ const seen = diagnostics.map((item) => `${item.code}: ${item.message}`);
+
+ assert.deepEqual(seen, [
+ "EXTERNAL_SERVICE_DOWN: absent-one is not usable: nothing is answering at http://127.0.0.1:1."
+ + " Bring it up with: narratage services up",
+ // Nothing to prepare and nothing to start: report the difference, name no command.
+ "EXTERNAL_SERVICE_MISMATCH: wrong-one is running but differs from this Runtime Profile:"
+ + " model is large-v3, expected small",
+ // A broken probe is a broken Provider, never a silently healthy service.
+ "EXTERNAL_SERVICE_PROBE_FAILED: the probe itself is broken",
+ ]);
+ await rm(root, { recursive: true, force: true });
+});
diff --git a/packages/provider-image-opencv-local/src/activation.ts b/packages/provider-image-opencv-local/src/activation.ts
index 9a5a16ff..ac9c4c29 100644
--- a/packages/provider-image-opencv-local/src/activation.ts
+++ b/packages/provider-image-opencv-local/src/activation.ts
@@ -11,6 +11,7 @@ import {
} from "@narratage/runtime-adapter-node";
import { createLocalOpenCvImageProvider } from "./provider.js";
+import { localOpenCvService } from "./service.js";
const localOpenCvRuntimeAdapter = createRuntimeEndpointAdapterFacet({
use: "@narratage/provider-image-opencv-local",
@@ -46,6 +47,7 @@ const localOpenCvRuntimeAdapter = createRuntimeEndpointAdapterFacet({
subject: "OpenCV Python",
});
},
+ service: localOpenCvService,
});
export const svmlPackage = {
diff --git a/packages/provider-image-opencv-local/src/service.ts b/packages/provider-image-opencv-local/src/service.ts
new file mode 100644
index 00000000..070fc185
--- /dev/null
+++ b/packages/provider-image-opencv-local/src/service.ts
@@ -0,0 +1,59 @@
+import { execFile } from "node:child_process";
+
+import { runtimeConfigObject, runtimeConfigString } from "@narratage/runtime-adapter";
+import type { RuntimeAdapterFactoryContext, RuntimeExternalService, RuntimeServiceState } from "@narratage/runtime-adapter";
+import { resolveRuntimeExecutable } from "@narratage/runtime-adapter-node";
+
+/**
+ * OpenCV runs as one bounded process per Need, so there is nothing to keep
+ * warm and this service declares no `start`. What it does declare is the
+ * interpreter's identity: a Python without `cv2`, or with a `cv2` from before
+ * the APIs this Provider calls, fails in the middle of a Build with a
+ * subprocess error. Probing says so at `doctor` time instead.
+ */
+const DEFAULT_PREPARE = {
+ command: "uv",
+ args: ["sync", "--project", "services/image-opencv", "--frozen"],
+} as const;
+
+/** Kept equal to `services/image-opencv/pyproject.toml` by a test in this package. */
+const REQUIRED_MAJOR = { cv2: 4, numpy: 2 } as const;
+
+const PROBE_PROGRAM =
+ "import cv2, numpy, json; print(json.dumps({'cv2': cv2.__version__, 'numpy': numpy.__version__}))";
+
+function run(executable: string, args: readonly string[]): Promise<{ ok: boolean; output: string }> {
+ return new Promise((resolve) => {
+ execFile(executable, [...args], { timeout: 15_000, shell: false }, (error, stdout, stderr) => {
+ resolve(error === null
+ ? { ok: true, output: stdout.trim() }
+ : { ok: false, output: (stderr.trim() || error.message).split("\n").at(-1) ?? "" });
+ });
+ });
+}
+
+export function localOpenCvService(context: RuntimeAdapterFactoryContext): RuntimeExternalService {
+ const config = runtimeConfigObject(context.config, "local OpenCV image");
+ const configured = runtimeConfigString(config.pythonExecutable, "OpenCV pythonExecutable");
+ const python = configured === undefined ? "python3" : resolveRuntimeExecutable(context.root, configured);
+ return {
+ id: "image-opencv",
+ prepare: DEFAULT_PREPARE,
+ async probe(): Promise<RuntimeServiceState> {
+ const result = await run(python, ["-c", PROBE_PROGRAM]);
+ if (!result.ok) return { state: "down", detail: `${python} cannot import cv2 and numpy: ${result.output}` };
+ let found: Record<string, string>;
+ try {
+ found = JSON.parse(result.output) as Record<string, string>;
+ } catch {
+ return { state: "down", detail: `${python} answered something other than a version report` };
+ }
+ const differs = Object.entries(REQUIRED_MAJOR)
+ .filter(([name, major]) => Number.parseInt(found[name] ?? "", 10) !== major)
+ .map(([name, major]) => `${name} is ${found[name] ?? "absent"}, expected ${major}.x`);
+ return differs.length === 0
+ ? { state: "ready" }
+ : { state: "mismatch", detail: `${python} carries ${differs.join("; ")}` };
+ },
+ };
+}
diff --git a/packages/provider-image-opencv-local/test/service.test.ts b/packages/provider-image-opencv-local/test/service.test.ts
new file mode 100644
index 00000000..8b6e1bd9
--- /dev/null
+++ b/packages/provider-image-opencv-local/test/service.test.ts
@@ -0,0 +1,49 @@
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { localOpenCvService } from "../src/service.js";
+
+const context = (config: Record<string, unknown> = {}) => ({
+ root: process.cwd(), instance: "opencv.test", config: config as never,
+});
+
+test("OpenCV declares how to install its interpreter and nothing to keep running", () => {
+ const service = localOpenCvService(context());
+ assert.equal(service.id, "image-opencv");
+ assert.equal(service.start, undefined, "OpenCV runs per Need; there is no daemon to start");
+ assert.deepEqual(service.prepare, {
+ command: "uv",
+ args: ["sync", "--project", "services/image-opencv", "--frozen"],
+ });
+});
+
+test("an interpreter without cv2 is reported here, not mid-Build", async () => {
+ // `false` exits non-zero without printing a version report.
+ const state = await localOpenCvService(context({ pythonExecutable: "/usr/bin/false" })).probe();
+ assert.equal(state.state, "down");
+ assert.match(state.state === "down" ? state.detail : "", /cannot import cv2 and numpy/u);
+});
+
+test("an interpreter carrying another OpenCV major is a mismatch, not a failure", async () => {
+ // A stand-in interpreter that answers truthfully about an environment this
+ // Provider cannot drive: cv2 3.x predates the APIs it calls.
+ const directory = await mkdtemp(join(tmpdir(), "svml-opencv-probe-"));
+ const fake = join(directory, "python");
+ await writeFile(fake, "#!/bin/sh\necho '{\"cv2\": \"3.4.18\", \"numpy\": \"2.1.0\"}'\n", { mode: 0o755 });
+ try {
+ const state = await localOpenCvService(context({ pythonExecutable: fake })).probe();
+ assert.equal(state.state, "mismatch");
+ assert.match(state.state === "mismatch" ? state.detail : "", /cv2 is 3\.4\.18, expected 4\.x/u);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test("the major versions the probe demands are the ones the locked project installs", async () => {
+ const pyproject = await readFile(new URL("../../../services/image-opencv/pyproject.toml", import.meta.url), "utf8");
+ assert.match(pyproject, /"opencv-python-headless>=4\./u, "probe expects cv2 4.x");
+ assert.match(pyproject, /"numpy>=2\./u, "probe expects numpy 2.x");
+});
diff --git a/packages/provider-whisperx-local/src/activation.ts b/packages/provider-whisperx-local/src/activation.ts
index c8be63ab..6bccb770 100644
--- a/packages/provider-whisperx-local/src/activation.ts
+++ b/packages/provider-whisperx-local/src/activation.ts
@@ -7,6 +7,7 @@ import {
} from "@narratage/runtime-adapter";
import { createLocalWhisperXProvider } from "./provider.js";
+import { localWhisperXService } from "./service.js";
const localWhisperXRuntimeAdapter = createRuntimeEndpointAdapterFacet({
use: "@narratage/provider-whisperx-local",
@@ -16,6 +17,7 @@ const localWhisperXRuntimeAdapter = createRuntimeEndpointAdapterFacet({
"baseUrl", "expectedModel", "expectedDevice", "expectedCompute", "expectedBatchSize",
"expectedServiceVersion", "expectedWhisperXVersion", "expectedPunktTabDigest",
"defaultConcurrency", "requestTimeoutMs", "maxResponseBytes",
+ "serviceCommand", "servicePrepareCommand",
], "local WhisperX");
return createLocalWhisperXProvider({
instance: context.instance,
@@ -44,6 +46,7 @@ const localWhisperXRuntimeAdapter = createRuntimeEndpointAdapterFacet({
? {} : { maxResponseBytes: config.maxResponseBytes as number }),
});
},
+ service: localWhisperXService,
});
export const svmlPackage = {
diff --git a/packages/provider-whisperx-local/src/service.ts b/packages/provider-whisperx-local/src/service.ts
new file mode 100644
index 00000000..69d963c4
--- /dev/null
+++ b/packages/provider-whisperx-local/src/service.ts
@@ -0,0 +1,64 @@
+import { runtimeConfigObject, runtimeConfigString } from "@narratage/runtime-adapter";
+import type { RuntimeAdapterFactoryContext, RuntimeExternalService, RuntimeServiceState } from "@narratage/runtime-adapter";
+
+import { localWhisperXPunktTabDigest } from "./provider.js";
+
+/**
+ * WhisperX loads multi-gigabyte weights before it can answer, so it is a warm
+ * program a developer keeps running, not a process spawned for each Need. The
+ * Provider declares how to bring it up; the Runtime Profile may override the
+ * command for an environment that installs WhisperX differently.
+ */
+const DEFAULT_START = {
+ command: "uv",
+ args: ["run", "--project", "services/whisperx", "--frozen", "svml-whisperx-service"],
+} as const;
+
+const DEFAULT_PREPARE = {
+ command: "uv",
+ args: ["run", "--project", "services/whisperx", "--frozen", "svml-whisperx-prepare"],
+} as const;
+
+function command(value: unknown, fallback: { readonly command: string; readonly args: readonly string[] }) {
+ if (value === undefined) return fallback;
+ if (!Array.isArray(value) || value.length === 0 || value.some((item) => typeof item !== "string")) {
+ throw new Error("WhisperX serviceCommand must be a non-empty array of strings");
+ }
+ return { command: value[0] as string, args: (value as string[]).slice(1) };
+}
+
+export function localWhisperXService(context: RuntimeAdapterFactoryContext): RuntimeExternalService {
+ const config = runtimeConfigObject(context.config, "local WhisperX");
+ const baseUrl = (runtimeConfigString(config.baseUrl, "WhisperX baseUrl") ?? "http://127.0.0.1:8765")
+ .replace(/\/+$/u, "");
+ const expected = {
+ protocol: "svml.whisperx-service@1",
+ serviceVersion: runtimeConfigString(config.expectedServiceVersion, "WhisperX expectedServiceVersion") ?? "0.1.0",
+ whisperxVersion: runtimeConfigString(config.expectedWhisperXVersion, "WhisperX expectedWhisperXVersion") ?? "3.8.6",
+ model: runtimeConfigString(config.expectedModel, "WhisperX expectedModel") ?? "small",
+ device: runtimeConfigString(config.expectedDevice, "WhisperX expectedDevice") ?? "cpu",
+ punktTabDigest: runtimeConfigString(config.expectedPunktTabDigest, "WhisperX expectedPunktTabDigest") ?? localWhisperXPunktTabDigest,
+ };
+ return {
+ id: "whisperx",
+ prepare: command(config.servicePrepareCommand, DEFAULT_PREPARE),
+ start: command(config.serviceCommand, DEFAULT_START),
+ async probe(): Promise<RuntimeServiceState> {
+ let health: Record<string, unknown>;
+ try {
+ const response = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(2000) });
+ if (!response.ok) return { state: "down", detail: `${baseUrl}/health answered ${response.status}` };
+ health = await response.json() as Record<string, unknown>;
+ } catch {
+ return { state: "down", detail: `nothing is answering at ${baseUrl}` };
+ }
+ const differs = Object.entries(expected)
+ .filter(([key, want]) => health[key] !== want)
+ .map(([key, want]) => `${key} is ${String(health[key])}, expected ${String(want)}`);
+ if (health.ok !== true) differs.push("the service reports itself unhealthy");
+ return differs.length === 0
+ ? { state: "ready" }
+ : { state: "mismatch", detail: differs.join("; ") };
+ },
+ };
+}
diff --git a/packages/provider-whisperx-local/test/service.test.ts b/packages/provider-whisperx-local/test/service.test.ts
new file mode 100644
index 00000000..4e12de1c
--- /dev/null
+++ b/packages/provider-whisperx-local/test/service.test.ts
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { localWhisperXService } from "../src/service.js";
+
+const context = (config: Record<string, unknown> = {}) => ({
+ root: "/tmp", instance: "whisperx.test", config: config as never,
+});
+
+test("the Provider declares how to bring WhisperX up and how to recognise it", () => {
+ const service = localWhisperXService(context());
+ assert.equal(service.id, "whisperx");
+ assert.deepEqual(service.start, {
+ command: "uv",
+ args: ["run", "--project", "services/whisperx", "--frozen", "svml-whisperx-service"],
+ });
+ assert.equal(service.prepare?.args.at(-1), "svml-whisperx-prepare");
+});
+
+test("a deployment that installs WhisperX elsewhere overrides the command", () => {
+ const service = localWhisperXService(context({ serviceCommand: ["conda", "run", "whisperx-serve"] }));
+ assert.deepEqual(service.start, { command: "conda", args: ["run", "whisperx-serve"] });
+});
+
+test("a program answering with another identity is reported, never used", async () => {
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => new Response(JSON.stringify({
+ ok: true,
+ protocol: "svml.whisperx-service@1",
+ serviceVersion: "0.1.0",
+ whisperxVersion: "3.8.6",
+ model: "large-v3",
+ device: "cpu",
+ punktTabDigest: "sha256:" + "0".repeat(64),
+ }), { status: 200 })) as typeof fetch;
+ try {
+ const state = await localWhisperXService(context()).probe();
+ assert.equal(state.state, "mismatch");
+ assert.match(state.state === "mismatch" ? state.detail : "", /model is large-v3, expected small/u);
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("nothing answering is down, not a mismatch", async () => {
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => { throw new Error("ECONNREFUSED"); }) as typeof fetch;
+ try {
+ const state = await localWhisperXService(context({ baseUrl: "http://127.0.0.1:9" })).probe();
+ assert.equal(state.state, "down");
+ } finally {
+ globalThis.fetch = original;
+ }
+});
diff --git a/packages/runtime-adapter/src/index.ts b/packages/runtime-adapter/src/index.ts
index 13bf9cce..ed33411d 100644
--- a/packages/runtime-adapter/src/index.ts
+++ b/packages/runtime-adapter/src/index.ts
@@ -10,7 +10,7 @@ import type { RuntimeServicePackage } from "@narratage/runtime";
export const runtimeAdapterHostAbi = "svml.runtime-adapter-host@1";
-export type RuntimeAdapterKind = "endpoint" | "service";
+export type RuntimeAdapterKind = "endpoint" | "runtime-service";
export type RuntimeAdapterIdentity = {
readonly contract: "svml.runtime-adapter-facet@1";
@@ -33,9 +33,37 @@ export type RuntimeDoctorDiagnostic = {
readonly subject?: string;
};
+/** One command this deployment may run on the developer's machine. */
+export type RuntimeServiceCommand = {
+ readonly command: string;
+ readonly args: readonly string[];
+};
+
+export type RuntimeServiceState =
+ | { readonly state: "ready" }
+ | { readonly state: "down"; readonly detail: string }
+ /** Something answers, but not as the configured deployment expects. */
+ | { readonly state: "mismatch"; readonly detail: string };
+
+/**
+ * A separate program that must already be running for this Endpoint to work.
+ *
+ * An Endpoint that spawns a bounded process per Need declares nothing here; this
+ * is for a program whose cost is its warm state, which therefore outlives one
+ * Need and one Build. `start` is absent when the deployment does not own the
+ * program's lifetime, as with a remote host, leaving `probe` to report on it.
+ */
+export type RuntimeExternalService = {
+ readonly id: string;
+ probe(): Promise<RuntimeServiceState>;
+ readonly prepare?: RuntimeServiceCommand;
+ readonly start?: RuntimeServiceCommand;
+};
+
export type RuntimeEndpointAdapterImplementation = {
create(context: RuntimeAdapterFactoryContext): EndpointPackage | Promise<EndpointPackage>;
doctor?(context: RuntimeAdapterFactoryContext): readonly RuntimeDoctorDiagnostic[] | Promise<readonly RuntimeDoctorDiagnostic[]>;
+ service?(context: RuntimeAdapterFactoryContext): RuntimeExternalService | undefined;
};
export type RuntimeServiceAdapterImplementation = {
@@ -72,7 +100,7 @@ function identity(value: CanonicalValue): RuntimeAdapterIdentity {
const item = value as unknown as RuntimeAdapterIdentity;
assert(item.contract === "svml.runtime-adapter-facet@1", "Runtime Adapter identity contract is unsupported");
assert(item.use.trim().length > 0, "Runtime Adapter use name is empty");
- assert(item.kind === "endpoint" || item.kind === "service", "Runtime Adapter kind is invalid");
+ assert(item.kind === "endpoint" || item.kind === "runtime-service", "Runtime Adapter kind is invalid");
return canonicalize(item) as unknown as RuntimeAdapterIdentity;
}
@@ -88,6 +116,7 @@ export function createRuntimeEndpointAdapterFacet(options: {
readonly use: string;
readonly create: RuntimeEndpointAdapterImplementation["create"];
readonly doctor?: RuntimeEndpointAdapterImplementation["doctor"];
+ readonly service?: RuntimeEndpointAdapterImplementation["service"];
}): RuntimeAdapterHostFacet {
const facet: RuntimeAdapterHostFacet = {
abi: runtimeAdapterHostAbi,
@@ -99,6 +128,7 @@ export function createRuntimeEndpointAdapterFacet(options: {
implementation: {
create: options.create,
...(options.doctor === undefined ? {} : { doctor: options.doctor }),
+ ...(options.service === undefined ? {} : { service: options.service }),
},
};
return facet;
@@ -114,7 +144,7 @@ export function createRuntimeServiceAdapterFacet(options: {
identity: identity(canonicalize({
contract: "svml.runtime-adapter-facet@1",
use: options.use,
- kind: "service",
+ kind: "runtime-service",
})),
implementation: {
create: options.create,
@@ -270,11 +300,19 @@ export class RuntimeAdapterRegistry {
async createService(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeServicePackage> {
const value = this.#registrations.get(use);
assert(value !== undefined, `Runtime service adapter ${use} is not registered`);
- assert(value.facet.identity.kind === "service", `Runtime Adapter ${use} is not a service adapter`);
+ assert(value.facet.identity.kind === "runtime-service", `Runtime Adapter ${use} is not a Runtime service adapter`);
const created = await (value.facet.implementation as RuntimeServiceAdapterImplementation).create(context);
return bindServicePackage(created, value.facet.identity, value.binding);
}
+ /** The external program this Endpoint adapter needs running, when it declares one. */
+ service(use: string, context: RuntimeAdapterFactoryContext): RuntimeExternalService | undefined {
+ const value = this.#registrations.get(use);
+ if (value === undefined || value.facet.identity.kind !== "endpoint") return undefined;
+ const declare = (value.facet.implementation as RuntimeEndpointAdapterImplementation).service;
+ return declare === undefined ? undefined : declare(context);
+ }
+
async doctor(use: string, kind: RuntimeAdapterKind, context: RuntimeAdapterFactoryContext): Promise<readonly RuntimeDoctorDiagnostic[]> {
const value = this.#registrations.get(use);
if (value === undefined) return [{ severity: "error", code: "RUNTIME_ADAPTER_MISSING", message: `Runtime Adapter ${use} is not registered`, subject: use }];