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.

refactor: use installed runtime endpoints directly

kashorin859a053f93cf
diff --git a/packages/driver-node/src/registry.ts b/packages/driver-node/src/registry.ts
index 119b011e..e85214b7 100644
--- a/packages/driver-node/src/registry.ts
+++ b/packages/driver-node/src/registry.ts
@@ -13,11 +13,7 @@ import type {
ProducerRef,
TypeRef,
} from "@narratage/protocol";
-import {
- RuntimeModuleRegistry,
- verifyCredentialRef,
-} from "@narratage/runtime";
-import type { ResolvedRuntimeEndpoint, RuntimeClosure } from "@narratage/runtime";
+import { verifyCredentialRef } from "@narratage/runtime";
import type {
ProducerHandler,
@@ -104,9 +100,6 @@ export class EndpointRegistry implements EndpointRegistrar {
readonly #registrations: EndpointRegistration[] = [];
readonly #registrationKeys = new Set<string>();
readonly #registrationsByCapability = new Map<string, EndpointRegistration[]>();
- readonly #offers = new Map<string, string>();
- readonly #runtimeScheduling = new Map<string, SchedulingHint>();
- #bound = false;
registerImmediateEndpoint(
id: string,
@@ -146,91 +139,11 @@ export class EndpointRegistry implements EndpointRegistrar {
this.#registrationsByCapability.set(endpointCapabilityKey(capability), registrations);
}
- /** Bind the Endpoint instances selected by one resolved Runtime profile. */
- applyRuntimeClosure(
- closure: RuntimeClosure,
- modules: RuntimeModuleRegistry,
- ): void {
- modules.verifyClosure(closure);
- if (this.#bound) throw new Error("Endpoint Registry is already bound");
- const endpoints = new Map(closure.instances
- .filter((instance) => instance.role === "capability-endpoint")
- .map((instance) => [instance.id, instance]));
- const registrations = new Map(this.#registrations.map((registration) => [
- `${registration.id}\n${endpointCapabilityKey(registration.capability)}\n${endpointReturnKey(registration.returns)}`,
- registration,
- ]));
- const lanes = new Map<string, ResolvedRuntimeEndpoint["lanes"][number]>();
- for (const endpoint of endpoints.values()) {
- for (const lane of endpoint.lanes) {
- lanes.set(`${endpoint.id}\n${endpointCapabilityKey(lane.capability)}\n${endpointReturnKey(lane.returns)}`, lane);
- }
- }
- const pending: { readonly key: string; readonly endpoint: string; readonly scheduling: SchedulingHint }[] = [];
- for (const offer of closure.endpoints) {
- const endpoint = endpoints.get(offer.endpoint);
- if (endpoint === undefined) throw new Error(`Runtime Endpoint ${offer.endpoint} is unavailable`);
- const exact = `${endpoint.id}\n${endpointCapabilityKey(offer.capability)}\n${endpointReturnKey(offer.returns)}`;
- const registration = registrations.get(exact);
- if (registration === undefined) {
- throw new Error(`Endpoint ${endpoint.id} is not registered for ${endpointCapabilityKey(offer.capability)}`);
- }
- const expectedKind = endpoint.lifecycle;
- if (registration.kind !== expectedKind) {
- throw new Error(`Endpoint ${endpoint.id} lifecycle does not match the Runtime Closure`);
- }
- const credentialSlots = Object.keys(registration.credentials ?? {}).sort();
- if (JSON.stringify(credentialSlots) !== JSON.stringify(endpoint.credentialSlots)) {
- throw new Error(`Endpoint ${endpoint.id} credential slots do not match the Runtime Closure`);
- }
- const lane = lanes.get(exact);
- if (lane === undefined) throw new Error(`Endpoint ${endpoint.id} has no locked scheduling lane`);
- const scheduling = {
- queue: { pool: endpoint.pool, lane: lane.lane },
- resources: [
- {
- id: `pool:${endpoint.pool}`,
- maxActive: endpoint.maxConcurrency,
- maxInFlight: endpoint.maxConcurrency,
- },
- {
- id: `lane:${endpoint.pool}/${lane.lane}`,
- maxActive: lane.maxConcurrency,
- maxInFlight: lane.maxConcurrency,
- },
- ],
- };
- pending.push({
- key: endpointCapabilityKey(offer.capability),
- endpoint: endpoint.id,
- scheduling,
- });
- }
- for (const item of pending) {
- this.#offers.set(item.key, item.endpoint);
- this.#runtimeScheduling.set(`${item.endpoint}\n${item.key}`, item.scheduling);
- }
- this.#bound = true;
- }
-
resolve(need: Need): EndpointResolution {
const key = endpointCapabilityKey(need.capability);
- const bound = this.#offers.get(key);
const registrations = (this.#registrationsByCapability.get(key) ?? []).filter((registration) =>
sameRef(registration.returns, need.returns)
&& (registration.supports?.(need) ?? true));
- if (bound !== undefined) {
- const registration = registrations.find((candidate) => candidate.id === bound);
- const scheduling = registration === undefined
- ? undefined
- : this.#runtimeScheduling.get(`${registration.id}\n${key}`) ?? registration.scheduling;
- return registration === undefined
- ? { status: "missing", endpointId: bound }
- : {
- status: "resolved",
- registration: scheduling === undefined ? registration : { ...registration, scheduling },
- };
- }
if (registrations.length === 0) return { status: "missing" };
if (registrations.length > 1) {
return {
@@ -238,12 +151,7 @@ export class EndpointRegistry implements EndpointRegistrar {
endpointIds: registrations.map((registration) => registration.id).sort(),
};
}
- const registration = registrations[0]!;
- const scheduling = this.#runtimeScheduling.get(`${registration.id}\n${key}`) ?? registration.scheduling;
- return {
- status: "resolved",
- registration: scheduling === undefined ? registration : { ...registration, scheduling },
- };
+ return { status: "resolved", registration: registrations[0]! };
}
}
diff --git a/packages/driver-node/test/scheduler.test.ts b/packages/driver-node/test/scheduler.test.ts
index 8c55fde8..bcc01e5e 100644
--- a/packages/driver-node/test/scheduler.test.ts
+++ b/packages/driver-node/test/scheduler.test.ts
@@ -10,15 +10,8 @@ import type { AsyncEndpoint } from "@narratage/endpoint-kit";
import {
LocalBuildScheduler,
MemoryOperationStore,
- RuntimeModuleRegistry,
- localSchedulerOptionsFromClosure,
- resolveRuntimeClosure,
- sealResolvedRuntimeProfile,
-} from "@narratage/runtime";
-import type {
- OperationStore,
- RuntimeModuleManifest,
} from "@narratage/runtime";
+import type { OperationStore } from "@narratage/runtime";
import {
createResolvedClosure,
link,
@@ -152,86 +145,9 @@ function registerGreetingProducers(producers: ProducerRegistry): void {
});
}
-const runtimeModule = { name: "example.scheduler-runtime", version: "1" } as const;
-const providerFacet = { module: runtimeModule, name: "generation-endpoint" } as const;
-function resolvedRuntime(laneLimit: number, lifecycle: "immediate" | "asynchronous" = "immediate") {
- const manifest: RuntimeModuleManifest = {
- format: "narratage.runtime-module@1",
- name: runtimeModule.name,
- version: runtimeModule.version,
- facets: [
- {
- name: "scheduler",
- role: "scheduler",
- },
- {
- name: "operations",
- role: "operation-store",
- },
- ...([
- ["worker", "worker"],
- ["builds", "build-store"],
- ["dispatch", "dispatch-store"],
- ["artifacts", "artifact-store"],
- ["credentials", "credential-store"],
- ] as const).map(([name, role]) => ({
- name,
- role,
- })),
- {
- name: providerFacet.name,
- role: "capability-endpoint",
- fulfills: [{ capability: capabilities.generation, returns: types.generated }],
- lifecycle,
- defaultConcurrency: 1,
- },
- ],
- };
- const modules = new RuntimeModuleRegistry();
- modules.register(manifest);
- const closure = resolveRuntimeClosure(modules, sealResolvedRuntimeProfile({
- instances: [
- { id: "scheduler.local", facet: { module: runtimeModule, name: "scheduler" } },
- { id: "worker.local", facet: { module: runtimeModule, name: "worker" } },
- { id: "builds.memory", facet: { module: runtimeModule, name: "builds" } },
- { id: "operations.memory", facet: { module: runtimeModule, name: "operations" } },
- { id: "dispatch.memory", facet: { module: runtimeModule, name: "dispatch" } },
- { id: "artifacts.memory", facet: { module: runtimeModule, name: "artifacts" } },
- { id: "credentials.memory", facet: { module: runtimeModule, name: "credentials" } },
- { id: "generation.local", facet: providerFacet, pool: "fixture.account" },
- ],
- scheduler: "scheduler.local",
- worker: "worker.local",
- stores: {
- build: "builds.memory",
- operations: "operations.memory",
- dispatch: "dispatch.memory",
- artifacts: "artifacts.memory",
- credentials: ["credentials.memory"],
- },
- endpoints: [{
- capability: capabilities.generation,
- returns: types.generated,
- endpoint: "generation.local",
- }],
- scheduling: {
- maxConcurrency: 8,
- resources: [
- { id: "pool:fixture.account", maxConcurrency: laneLimit },
- {
- id: `lane:fixture.account/${capabilities.generation.module.name}@${capabilities.generation.module.version}#${capabilities.generation.name}`,
- maxConcurrency: laneLimit,
- },
- ],
- },
- }));
- return { closure, modules };
-}
-
function asyncExecutor(
endpoint: AsyncEndpoint,
operations: OperationStore,
- runtime = resolvedRuntime(1, "asynchronous"),
) {
const producers = new ProducerRegistry();
registerGreetingProducers(producers);
@@ -241,12 +157,17 @@ function asyncExecutor(
capabilities.generation,
types.generated,
endpoint,
+ {
+ scheduling: {
+ queue: { pool: "fixture.account", lane: "generation" },
+ resources: [
+ { id: "pool:fixture.account", maxActive: 1, maxInFlight: 1 },
+ { id: "lane:fixture.account/generation", maxActive: 1, maxInFlight: 1 },
+ ],
+ },
+ },
);
- endpoints.applyRuntimeClosure(runtime.closure, runtime.modules);
- return {
- executor: new NodeDriver({ producers, endpoints, operations }),
- runtime,
- };
+ return new NodeDriver({ producers, endpoints, operations });
}
test("one local Scheduler shares an Endpoint resource across multiple Builds", async () => {
@@ -318,46 +239,8 @@ test("independent paid commands inside one Build may fill the same resource with
record.type.name === types.generated.name).length, 2);
});
-test("a resolved Runtime selects an Endpoint and Scheduler policy without manual bind", async () => {
- let maximumActive = 0;
- const { closure, modules } = resolvedRuntime(2);
- const { executor, endpoints } = configuredExecutor({
- resource: "pool:ignored-registration",
- defaultConcurrency: 1,
- endpointId: "generation.local",
- observe(active) {
- maximumActive = Math.max(maximumActive, active);
- },
- });
- endpoints.applyRuntimeClosure(closure, modules);
- const results = await new LocalBuildScheduler(
- executor,
- localSchedulerOptionsFromClosure(closure),
- ).run([
- { id: "video-a", state: createGreetingBuild() },
- { id: "video-b", state: createGreetingBuild() },
- ]);
-
- assert.deepEqual(results.map((result) => result.status), ["complete", "complete"]);
- assert.equal(maximumActive, 2, "the selected Profile override owns the resource");
- assert.equal(results.every((result) =>
- result.state.records.some((record) => record.id === "generated:root")), true);
-});
-
-test("a asynchronous Runtime facet cannot be activated by a one-shot Handler", () => {
- const { closure, modules } = resolvedRuntime(1, "asynchronous");
- const { endpoints } = configuredExecutor({
- resource: "pool:fixture.account",
- defaultConcurrency: 1,
- endpointId: "generation.local",
- observe() {},
- });
- assert.throws(() => endpoints.applyRuntimeClosure(closure, modules), /lifecycle does not match/u);
-});
-
test("a asynchronous Endpoint starts once and is polled until complete", async () => {
const operations = new MemoryOperationStore();
- const runtime = resolvedRuntime(1, "asynchronous");
let starts = 0;
let resumes = 0;
let operationId: string | undefined;
@@ -380,11 +263,9 @@ test("a asynchronous Endpoint starts once and is polled until complete", async (
},
};
- const firstExecutor = asyncExecutor(endpoint, operations, runtime).executor;
- const [first] = await new LocalBuildScheduler(
- firstExecutor,
- localSchedulerOptionsFromClosure(runtime.closure),
- ).run([{ id: "video", state: createGreetingBuild() }]);
+ const firstExecutor = asyncExecutor(endpoint, operations);
+ const [first] = await new LocalBuildScheduler(firstExecutor, { maxConcurrency: 8 })
+ .run([{ id: "video", state: createGreetingBuild() }]);
assert.equal(first?.status, "paused");
assert.equal(starts, 1);
assert.equal(resumes, 0);
@@ -393,11 +274,9 @@ test("a asynchronous Endpoint starts once and is polled until complete", async (
assert.ok(pending?.operation);
assert.equal((await operations.read(pending.operation))?.status, "pending");
- const secondExecutor = asyncExecutor(endpoint, operations, runtime).executor;
- const [second] = await new LocalBuildScheduler(
- secondExecutor,
- localSchedulerOptionsFromClosure(runtime.closure),
- ).run([{ id: "video", state: createGreetingBuild() }]);
+ const secondExecutor = asyncExecutor(endpoint, operations);
+ const [second] = await new LocalBuildScheduler(secondExecutor, { maxConcurrency: 8 })
+ .run([{ id: "video", state: createGreetingBuild() }]);
assert.equal(second?.status, "complete");
assert.equal(starts, 1);
@@ -407,7 +286,6 @@ test("a asynchronous Endpoint starts once and is polled until complete", async (
test("wakeAt prevents early polling and Runtime cancellation becomes a terminal Core failure", async () => {
const operations = new MemoryOperationStore();
- const runtime = resolvedRuntime(1, "asynchronous");
let resumes = 0;
let cancels = 0;
const wakeAt = Date.now() + 60_000;
@@ -425,8 +303,8 @@ test("wakeAt prevents early polling and Runtime cancellation becomes a terminal
return { status: "confirmed" };
},
};
- const executor = asyncExecutor(endpoint, operations, runtime).executor;
- const scheduler = new LocalBuildScheduler(executor, localSchedulerOptionsFromClosure(runtime.closure));
+ const executor = asyncExecutor(endpoint, operations);
+ const scheduler = new LocalBuildScheduler(executor, { maxConcurrency: 8 });
const [first] = await scheduler.run([{ id: "cancel-video", state: createGreetingBuild() }]);
const operationId = first?.outcomes.find((item) => item.status === "pending")?.operation;
assert.ok(operationId);
diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.ts
index f4d66db2..a95804cd 100644
--- a/packages/endpoint-kit/src/index.ts
+++ b/packages/endpoint-kit/src/index.ts
@@ -13,10 +13,6 @@ import type {
CredentialValue,
OperationFailure,
OperationProgress,
- EndpointOffer,
- RuntimeFacetRef,
- RuntimeModuleManifest,
- RuntimeFacetInstance,
} from "@narratage/runtime";
import { verifyCredentialRef } from "@narratage/runtime";
@@ -113,14 +109,22 @@ export interface EndpointRegistrar {
}
export type EndpointPackage = {
- readonly manifest: RuntimeModuleManifest;
- readonly instance: RuntimeFacetInstance;
+ readonly instance: {
+ readonly id: string;
+ readonly pool: string;
+ };
readonly offers: readonly EndpointOffer[];
/** Host-facing login material declared by this exact configured Endpoint instance. */
readonly credentials: readonly EndpointCredentialDescription[];
install(registry: EndpointRegistrar): Awaitable<void>;
};
+export type EndpointOffer = {
+ readonly capability: CapabilityRef;
+ readonly returns: TypeRef;
+ readonly endpoint: string;
+};
+
export type EndpointCredentialDescription = {
readonly endpoint: string;
readonly slot: string;
@@ -232,37 +236,12 @@ export function defineEndpointPackage(options: DefineEndpointPackageOptions): En
ref: structuredClone(ref),
} satisfies EndpointCredentialDescription;
});
- const module = { ...options.module };
- const facet = { module, name: options.facet };
const fulfills = options.capabilities.map((item) => ({
capability: structuredClone(item.capability),
returns: structuredClone(item.returns),
}));
- const manifest: RuntimeModuleManifest = {
- format: "narratage.runtime-module@1",
- name: module.name,
- version: module.version,
- facets: [{
- name: options.facet,
- role: "capability-endpoint",
- fulfills,
- lifecycle,
- defaultConcurrency: positiveInteger(options.defaultConcurrency ?? 1, "defaultConcurrency"),
- lanes: options.capabilities.map((capability) => ({
- capability: structuredClone(capability.capability),
- returns: structuredClone(capability.returns),
- lane: capability.lane ?? capability.capability.name,
- maxConcurrency: positiveInteger(
- capability.maxConcurrency ?? options.defaultConcurrency ?? 1,
- `${capability.capability.name} maxConcurrency`,
- ),
- })),
- credentialSlots: Object.keys(credentials),
- }],
- };
- const instance: RuntimeFacetInstance = {
+ const instance = {
id: options.instance,
- facet,
pool: options.pool,
};
const offers: readonly EndpointOffer[] = fulfills.map((item) => ({
@@ -270,7 +249,6 @@ export function defineEndpointPackage(options: DefineEndpointPackageOptions): En
endpoint: options.instance,
}));
return {
- manifest,
instance,
offers,
credentials: credentialDescriptions,
diff --git a/packages/endpoint-kit/test/endpoint.test.ts b/packages/endpoint-kit/test/endpoint.test.ts
index 52b15bd2..8524e97d 100644
--- a/packages/endpoint-kit/test/endpoint.test.ts
+++ b/packages/endpoint-kit/test/endpoint.test.ts
@@ -40,7 +40,7 @@ function capturingRegistrar(registrations: CapturedRegistration[]): EndpointRegi
};
}
-test("one Endpoint definition generates Manifest, instance, offers and host-neutral registration", async () => {
+test("one Endpoint definition generates one configured instance and host-neutral registration", async () => {
const endpoint = defineEndpointPackage({
module: { name: "example.provider", version: "1" },
facet: "http-json",
@@ -59,10 +59,8 @@ test("one Endpoint definition generates Manifest, instance, offers and host-neut
}),
}],
});
- assert.equal(endpoint.manifest.facets[0]?.role, "capability-endpoint");
- assert.equal(endpoint.manifest.facets[0]?.defaultConcurrency, 3);
- assert.deepEqual(endpoint.manifest.facets[0]?.credentialSlots, ["apiKey"]);
assert.equal(endpoint.instance.id, "example.personal");
+ assert.equal(endpoint.instance.pool, "example.personal");
assert.deepEqual(endpoint.offers, [{
capability: capabilities.generation,
returns: types.generated,
diff --git a/packages/provider-google-vertex/test/provider.test.ts b/packages/provider-google-vertex/test/provider.test.ts
index 237f92d5..92b25648 100644
--- a/packages/provider-google-vertex/test/provider.test.ts
+++ b/packages/provider-google-vertex/test/provider.test.ts
@@ -101,11 +101,6 @@ test("Vertex transports the exact model request while the model package validate
test("Vertex configuration exposes credential/queue policy without changing the model request", () => {
const provider = createGoogleVertexCaptionProvider({ project: "narratage-test-project", defaultConcurrency: 3 });
assert.equal(provider.instance.id, "google-vertex.caption");
- const facet = provider.manifest.facets[0];
- assert.equal(facet?.role, "capability-endpoint");
- assert(facet?.role === "capability-endpoint");
- assert.equal(facet.defaultConcurrency, 3);
- assert.deepEqual(facet.credentialSlots, ["googleCredentials"]);
assert.deepEqual(provider.offers, [{
capability: captionGeminiCapabilities.plan,
returns: captionTypes.plan,
diff --git a/packages/provider-hyperframes-local/test/provider.test.ts b/packages/provider-hyperframes-local/test/provider.test.ts
index 7d06a165..e9d712bf 100644
--- a/packages/provider-hyperframes-local/test/provider.test.ts
+++ b/packages/provider-hyperframes-local/test/provider.test.ts
@@ -97,10 +97,6 @@ async function handlerFor(request: Need): Promise<{
test("local HyperFrames Provider exposes one exact visual capability and two separate concurrency levels", async () => {
const provider = createLocalHyperframesProvider({ workers: 4, defaultConcurrency: 2 });
assert.equal(provider.instance.id, "hyperframes.local");
- const facet = provider.manifest.facets[0];
- assert.equal(facet?.role, "capability-endpoint");
- assert(facet?.role === "capability-endpoint");
- assert.equal(facet.defaultConcurrency, 2);
assert.deepEqual(provider.offers, [{
capability: renderHyperframesCapabilities.renderVisual,
returns: mediaTypes.renderedVisual,
diff --git a/packages/provider-image-opencv-local/test/provider.test.ts b/packages/provider-image-opencv-local/test/provider.test.ts
index 89e20968..5f66d04d 100644
--- a/packages/provider-image-opencv-local/test/provider.test.ts
+++ b/packages/provider-image-opencv-local/test/provider.test.ts
@@ -59,15 +59,11 @@ function composeNeed(source: BlobRef): Need {
test("the OpenCV package is one replaceable Endpoint with no second queue", async () => {
const provider = createLocalOpenCvImageProvider({ defaultConcurrency: 3 });
assert.equal(provider.instance.id, "image.opencv.local");
- const facet = provider.manifest.facets[0];
- assert(facet?.role === "capability-endpoint");
- assert.equal(facet.defaultConcurrency, 3);
assert.deepEqual(provider.offers, [{
capability: rasterCapabilities.execute,
returns: artifactTypes.blob,
endpoint: "image.opencv.local",
}]);
- assert.equal(provider.manifest.name, localOpenCvImageProviderModuleRef.name);
});
test("managed and external OpenCV deployments never mix their interpreters", () => {
diff --git a/packages/provider-whisperx-local/test/provider.test.ts b/packages/provider-whisperx-local/test/provider.test.ts
index de41f92a..f9c3c159 100644
--- a/packages/provider-whisperx-local/test/provider.test.ts
+++ b/packages/provider-whisperx-local/test/provider.test.ts
@@ -41,10 +41,6 @@ function wav(sampleFrames: number): Uint8Array {
test("local WhisperX Provider pins the complete service runtime and is independently queued", () => {
const provider = createLocalWhisperXProvider({ expectedModel: "small", defaultConcurrency: 2 });
assert.equal(provider.instance.id, "whisperx.local");
- const facet = provider.manifest.facets[0];
- assert.equal(facet?.role, "capability-endpoint");
- assert(facet?.role === "capability-endpoint");
- assert.equal(facet.defaultConcurrency, 2);
assert.throws(
() => createLocalWhisperXProvider({ baseUrl: "https://whisper.example.com" }),
/loopback/u,
diff --git a/packages/provider-xiaomi-mimo/test/provider.test.ts b/packages/provider-xiaomi-mimo/test/provider.test.ts
index 1873fbd7..82a72ee5 100644
--- a/packages/provider-xiaomi-mimo/test/provider.test.ts
+++ b/packages/provider-xiaomi-mimo/test/provider.test.ts
@@ -107,11 +107,6 @@ test("the official Provider maps all three model contracts without owning them",
test("Provider configuration owns credentials and queue policy, not model semantics", () => {
const provider = createXiaomiMimoProvider({ defaultConcurrency: 3 });
- const facet = provider.manifest.facets[0];
- assert(facet?.role === "capability-endpoint");
- assert.equal(facet.defaultConcurrency, 3);
- assert.deepEqual(facet.credentialSlots, ["apiKey"]);
assert.equal(provider.offers.length, 3);
assert.ok(provider.offers.every((binding) => binding.returns.name === generationTypes.audioSet.name));
- assert.equal(JSON.stringify(provider.manifest).includes("voiceDescription"), false);
});
diff --git a/packages/runtime-local/src/runtime.ts b/packages/runtime-local/src/runtime.ts
index 986f6e47..b7c5b6d3 100644
--- a/packages/runtime-local/src/runtime.ts
+++ b/packages/runtime-local/src/runtime.ts
@@ -10,21 +10,16 @@ import {
EndpointRegistry,
} from "@narratage/driver-node";
import {
- RuntimeModuleRegistry,
+ LocalBuildScheduler,
createBuildDispatchIdentity,
isStreamingArtifactStore,
- resolveRuntimeClosure,
- sealResolvedRuntimeProfile,
} from "@narratage/runtime";
import { TypeValidatorRegistry } from "@narratage/validation";
-import type {
- RuntimeModuleManifest,
- RuntimeFacetInstance,
-} from "@narratage/runtime";
import { createProjectRuntimeInfrastructure } from "./project-infrastructure.js";
import { createLocalRuntimeControl } from "./control.js";
import { createLocalCredentialControl } from "./credentials.js";
+import { createDurableLocalWorker } from "./worker.js";
import type {
CreateLocalRuntimeOptions,
LocalBuildOptions,
@@ -39,14 +34,6 @@ function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
-function moduleKey(manifest: RuntimeModuleManifest): string {
- return `${manifest.name}@${manifest.version}`;
-}
-
-function facetKey(instance: RuntimeFacetInstance): string {
- return `${instance.facet.module.name}@${instance.facet.module.version}#${instance.facet.name}`;
-}
-
function nonNegativeInteger(value: number, subject: string): number {
assert(Number.isSafeInteger(value) && value >= 0, `${subject} must be a non-negative safe integer`);
return value;
@@ -69,33 +56,12 @@ async function wait(delayMs: number, signal: AbortSignal | undefined): Promise<v
});
}
-function registerManifests(
- registry: RuntimeModuleRegistry,
- manifests: readonly RuntimeModuleManifest[],
-): void {
- const seen = new Map<string, string>();
- for (const manifest of manifests) {
- const key = moduleKey(manifest);
- const declaration = JSON.stringify(manifest);
- const existing = seen.get(key);
- if (existing !== undefined) {
- assert(existing === declaration, `Runtime package ${key} was configured with conflicting Manifests`);
- continue;
- }
- seen.set(key, declaration);
- registry.register(manifest);
- }
-}
-
function verifyEndpointPackages(packages: readonly EndpointPackage[]): void {
const instances = new Set<string>();
for (const item of packages) {
assert(item.instance.id.trim().length > 0, "Endpoint instance id is empty");
assert(!instances.has(item.instance.id), `Endpoint instance ${item.instance.id} is configured twice`);
instances.add(item.instance.id);
- assert(item.manifest.name === item.instance.facet.module.name
- && item.manifest.version === item.instance.facet.module.version,
- `${item.instance.id} instance ${facetKey(item.instance)} is outside its Runtime Manifest`);
assert(item.offers.length > 0, `${item.instance.id} binds no exact capability`);
for (const offer of item.offers) {
assert(offer.endpoint === item.instance.id,
@@ -108,9 +74,6 @@ export async function createLocalRuntime(
options: CreateLocalRuntimeOptions,
): Promise<LocalRuntime> {
const buildCatalog = options.buildCatalog;
- if (options.scheduling?.maxConcurrency !== undefined || options.scheduling?.resourceLimits !== undefined) {
- throw new Error("the selected Runtime profile owns maxConcurrency and resource limits");
- }
const producers = new ProducerRegistry();
const endpoints = new EndpointRegistry();
const validators = options.validators ?? new TypeValidatorRegistry();
@@ -119,7 +82,6 @@ export async function createLocalRuntime(
registerProducerFacets(producers, component.producers ?? []);
}
for (const endpoint of options.endpoints ?? []) await endpoint.install(endpoints);
- endpoints.applyRuntimeClosure(options.closure.value, options.closure.modules);
const driver = new NodeDriver({
producers,
endpoints,
@@ -128,12 +90,13 @@ export async function createLocalRuntime(
operations: options.operationStore,
validators,
});
- const scheduling = {
- maxConcurrency: options.closure.value.scheduling.maxConcurrency,
- resourceLimits: Object.fromEntries(options.closure.value.scheduling.resources.map((resource) => [resource.id, resource.maxConcurrency])),
- };
- const worker = options.worker.create(driver, {
- scheduler: options.scheduler,
+ const scheduling = options.scheduling;
+ const worker = createDurableLocalWorker(driver, {
+ scheduler: {
+ create(executor, schedulerOptions) {
+ return new LocalBuildScheduler(executor, schedulerOptions);
+ },
+ },
stores: {
builds: options.buildStore,
operations: options.operationStore,
@@ -141,7 +104,6 @@ export async function createLocalRuntime(
artifacts: options.artifactStore,
},
scheduling,
- runtimeClosure: options.closure.value,
});
const credentialControl = createLocalCredentialControl({
credentialStore: options.credentialStore,
@@ -153,6 +115,7 @@ export async function createLocalRuntime(
operationStore: options.operationStore,
dispatchStore: options.dispatchStore,
artifactStore: options.artifactStore,
+ ...(options.close === undefined ? {} : { close: options.close }),
});
const stageAttachments = async (request: LocalBuildRequest): Promise<void> => {
for (const item of request.attachments ?? []) {
@@ -261,42 +224,10 @@ export async function createProjectLocalRuntime(
const configuredComponents = options.components ?? [];
const projectInfrastructure = await createProjectRuntimeInfrastructure(root, options);
const infrastructure = projectInfrastructure.assembly;
- const selection = projectInfrastructure.selection;
- const partId = (reference: { readonly from: string; readonly part: string }) =>
- `${reference.from}.${reference.part}`;
const endpointPackages = options.endpoints ?? [];
try {
verifyEndpointPackages(endpointPackages);
- const modules = new RuntimeModuleRegistry();
- registerManifests(modules, [
- ...infrastructure.manifests,
- ...endpointPackages.map((item) => item.manifest),
- ]);
- const profile = sealResolvedRuntimeProfile({
- instances: [
- ...infrastructure.instances,
- ...endpointPackages.map((item) => item.instance),
- ],
- scheduler: partId(selection.scheduler),
- worker: partId(selection.worker),
- stores: {
- build: partId(selection.buildStore),
- operations: partId(selection.operationStore),
- dispatch: partId(selection.dispatchStore),
- artifacts: partId(selection.artifactStore),
- credentials: selection.credentialStores.map(partId),
- },
- endpoints: endpointPackages.flatMap((item) => item.offers),
- scheduling: {
- maxConcurrency: options.scheduling.maxConcurrency,
- resources: Object.entries(options.scheduling.resources ?? {}).map(([id, maxConcurrency]) => ({
- id,
- maxConcurrency,
- })),
- },
- });
- const closure = resolveRuntimeClosure(modules, profile);
const runtime = await createLocalRuntime({
buildStore: infrastructure.buildStore,
...(projectInfrastructure.catalog === undefined ? {} : { buildCatalog: projectInfrastructure.catalog }),
@@ -304,13 +235,17 @@ export async function createProjectLocalRuntime(
dispatchStore: infrastructure.dispatchStore,
artifactStore: infrastructure.artifactStore,
credentialStore: infrastructure.credentialStore,
- scheduler: infrastructure.scheduler,
- worker: infrastructure.worker,
...(configuredComponents.length === 0
? {}
: { components: configuredComponents }),
endpoints: endpointPackages,
- closure: { modules, value: closure },
+ scheduling: {
+ maxConcurrency: options.scheduling.maxConcurrency,
+ ...(options.scheduling.resources === undefined ? {} : {
+ resourceLimits: options.scheduling.resources,
+ }),
+ },
+ close: projectInfrastructure.close,
...(options.validators === undefined ? {} : { validators: options.validators }),
});
return {
@@ -330,9 +265,7 @@ export async function createProjectLocalRuntime(
readArtifact: runtime.readArtifact,
openArtifact: runtime.openArtifact,
garbageCollectArtifacts: runtime.garbageCollectArtifacts,
- close() {
- return projectInfrastructure.close();
- },
+ close: runtime.close,
};
} catch (error) {
await projectInfrastructure.close();
diff --git a/packages/runtime-local/src/scheduler-package.ts b/packages/runtime-local/src/scheduler-package.ts
index ed90e586..0069523b 100644
--- a/packages/runtime-local/src/scheduler-package.ts
+++ b/packages/runtime-local/src/scheduler-package.ts
@@ -4,7 +4,7 @@ import {
} from "@narratage/runtime";
import type { RuntimeInfrastructurePackage } from "@narratage/runtime";
-import { durableLocalWorkerFactory } from "./worker.js";
+import { createDurableLocalWorker } from "./worker.js";
const localRuntimeModuleRef = {
name: "@narratage/runtime-local",
@@ -32,7 +32,7 @@ export function createLocalExecutionPackage(
role: "worker",
part: "worker",
facet: "worker",
- port: durableLocalWorkerFactory,
+ port: { create: createDurableLocalWorker },
},
],
});
diff --git a/packages/runtime-local/src/types.ts b/packages/runtime-local/src/types.ts
index 32f024d4..d3158694 100644
--- a/packages/runtime-local/src/types.ts
+++ b/packages/runtime-local/src/types.ts
@@ -8,7 +8,6 @@ import type {
BuildCatalog,
BuildCatalogDescriptor,
BuildCatalogEntry,
- BuildSchedulerFactory,
BuildSchedulerOptions,
BuildSnapshot,
BuildStore,
@@ -17,10 +16,8 @@ import type {
CredentialStore,
OperationStore,
OperationSnapshot,
- RuntimeModuleRegistry,
RuntimeInfrastructurePackage,
RuntimeRoleSelection,
- RuntimeWorkerFactory,
} from "@narratage/runtime";
import type { TypeValidatorRegistrar, TypeValidatorRegistryLike } from "@narratage/validation";
@@ -31,11 +28,6 @@ export type LocalTypeValidatorRegistry = TypeValidatorRegistryLike & TypeValidat
export type { EndpointPackage } from "@narratage/endpoint-kit";
export type { RuntimeInfrastructurePackage } from "@narratage/runtime";
-export type LocalRuntimeClosureOptions = {
- readonly modules: RuntimeModuleRegistry;
- readonly value: import("@narratage/runtime").RuntimeClosure;
-};
-
export type CreateLocalRuntimeOptions = {
readonly buildStore: BuildStore;
/** Host presentation metadata only; never part of Runtime Closure or Core state. */
@@ -44,13 +36,11 @@ export type CreateLocalRuntimeOptions = {
readonly dispatchStore: import("@narratage/runtime").BuildDispatchStore;
readonly artifactStore: ArtifactStore;
readonly credentialStore: CredentialStore;
- readonly scheduler: BuildSchedulerFactory;
- readonly worker: RuntimeWorkerFactory;
readonly components?: readonly ComponentPackage[];
readonly endpoints?: readonly EndpointPackage[];
- readonly closure: LocalRuntimeClosureOptions;
- readonly scheduling?: Omit<BuildSchedulerOptions, "buildStore" | "runtimeClosure">;
+ readonly scheduling: Omit<BuildSchedulerOptions, "buildStore">;
readonly validators?: LocalTypeValidatorRegistry;
+ readonly close?: () => Awaitable<void>;
};
export type CreateLocalRuntimeArchiveControlOptions = {
diff --git a/packages/runtime-local/src/worker.ts b/packages/runtime-local/src/worker.ts
index 33bffc24..19441c49 100644
--- a/packages/runtime-local/src/worker.ts
+++ b/packages/runtime-local/src/worker.ts
@@ -7,7 +7,6 @@ import type {
RuntimePreparation,
RuntimeRunnableCommand,
RuntimeWorker,
- RuntimeWorkerFactory,
RuntimeWorkerFactoryOptions,
RuntimeWorkerRunOptions,
} from "@narratage/runtime";
@@ -215,7 +214,6 @@ class DurableLocalWorker implements RuntimeWorker {
const scheduler = this.#options.scheduler.create(this.#executorWithCapacity, {
...this.#options.scheduling,
buildStore: this.#options.stores.builds,
- runtimeClosure: this.#options.runtimeClosure,
});
try {
const [result] = await scheduler.run([{ id: dispatch.build, state: stored.state, snapshot: stored }]);
@@ -298,8 +296,9 @@ class DurableLocalWorker implements RuntimeWorker {
}
}
-export const durableLocalWorkerFactory: RuntimeWorkerFactory = {
- create(executor, options) {
- return new DurableLocalWorker(executor, options);
- },
-};
+export function createDurableLocalWorker(
+ executor: RuntimeCommandExecutor,
+ options: RuntimeWorkerFactoryOptions,
+): RuntimeWorker {
+ return new DurableLocalWorker(executor, options);
+}
diff --git a/packages/runtime-local/test/local.test.ts b/packages/runtime-local/test/local.test.ts
index b615eb27..de5594c9 100644
--- a/packages/runtime-local/test/local.test.ts
+++ b/packages/runtime-local/test/local.test.ts
@@ -26,9 +26,8 @@ import {
collectNodePackageComponents,
loadNodePackageSelection,
} from "@narratage/package-loader-node";
-import { LocalBuildScheduler, credentialRef, defineRuntimeInfrastructurePackage } from "@narratage/runtime";
+import { credentialRef, defineRuntimeInfrastructurePackage } from "@narratage/runtime";
import type { CredentialValue, WritableCredentialStore } from "@narratage/runtime";
-import type { RuntimeModuleManifest } from "@narratage/runtime";
import { createSqliteRuntimeInfrastructurePackage } from "@narratage/store-sqlite";
import {
@@ -40,19 +39,6 @@ import {
} from "../../core/test/greeting-fixture.js";
const providerModule = { name: "example.local-endpoint", version: "1" } as const;
-const providerFacet = { module: providerModule, name: "generation" } as const;
-const providerManifest: RuntimeModuleManifest = {
- format: "narratage.runtime-module@1",
- name: providerModule.name,
- version: providerModule.version,
- facets: [{
- name: providerFacet.name,
- role: "capability-endpoint",
- fulfills: [{ capability: capabilities.generation, returns: types.generated }],
- lifecycle: "asynchronous",
- defaultConcurrency: 1,
- }],
-};
function projectRuntimeFixture(directory: string) {
const execution = createLocalExecutionPackage("execution");
@@ -238,28 +224,18 @@ test("project local runtime queues, polls and cancels work with replaceable pack
return { status: "confirmed" };
},
};
- const endpointPackage: EndpointPackage = {
- manifest: providerManifest,
- instance: {
- id: "generation.personal",
- facet: providerFacet,
- pool: "generation.personal",
- },
- offers: [{
+ const endpointPackage: EndpointPackage = defineEndpointPackage({
+ module: providerModule,
+ facet: "generation",
+ instance: "generation.personal",
+ pool: "generation.personal",
+ capabilities: [{
+ lifecycle: "asynchronous",
capability: capabilities.generation,
returns: types.generated,
- endpoint: "generation.personal",
+ endpoint: asyncEndpoint,
}],
- credentials: [],
- install(registry) {
- registry.registerAsyncEndpoint(
- "generation.personal",
- capabilities.generation,
- types.generated,
- asyncEndpoint,
- );
- },
- };
+ });
try {
const firstRuntime = await createProjectLocalRuntime({
@@ -452,79 +428,6 @@ test("project local runtime accepts components loaded from an installed package"
}
});
-test("project local runtime uses only the explicitly selected Scheduler", async () => {
- const directory = await mkdtemp(join(tmpdir(), "narratage-local-scheduler-service-"));
- let creates = 0;
- const scheduler = defineRuntimeInfrastructurePackage({
- module: { name: "example.scheduler", version: "1" },
- instance: "custom-scheduler",
- parts: [{
- role: "scheduler",
- facet: "scheduler",
- part: "scheduler",
- port: {
- create(executor, options) {
- creates += 1;
- return new LocalBuildScheduler(executor, options);
- },
- },
- }],
- });
- try {
- const base = projectRuntimeFixture(directory);
- const runtime = await createProjectLocalRuntime({
- dataRoot: directory,
- ...base,
- infrastructure: [...base.infrastructure, scheduler],
- roles: { ...base.roles, scheduler: { from: "custom-scheduler", part: "scheduler" } },
- });
- await runtime.build({ id: "scheduler-selection", definition: buildDefinition(createGreetingBuild()) });
- await runtime.workOnce();
- assert.equal(creates, 1);
- await runtime.close();
- } finally {
- await rm(directory, { recursive: true, force: true });
- }
-});
-
-test("two installed Schedulers are unambiguous because the Profile selects one", async () => {
- const directory = await mkdtemp(join(tmpdir(), "narratage-local-scheduler-selection-"));
- const creates = { one: 0, two: 0 };
- const closes = { one: 0, two: 0 };
- const scheduler = (name: "one" | "two") => defineRuntimeInfrastructurePackage({
- module: { name: `example.scheduler.${name}`, version: "1" },
- instance: `scheduler-${name}`,
- parts: [{
- role: "scheduler",
- facet: "scheduler",
- part: "scheduler",
- port: {
- create(executor, options) {
- creates[name] += 1;
- return new LocalBuildScheduler(executor, options);
- },
- },
- }],
- close() { closes[name] += 1; },
- });
- try {
- const base = projectRuntimeFixture(directory);
- const runtime = await createProjectLocalRuntime({
- dataRoot: directory,
- ...base,
- infrastructure: [...base.infrastructure, scheduler("one"), scheduler("two")],
- roles: { ...base.roles, scheduler: { from: "scheduler-two", part: "scheduler" } },
- });
- await runtime.build({ id: "scheduler-two", definition: buildDefinition(createGreetingBuild()) });
- await runtime.workOnce();
- assert.deepEqual(creates, { one: 0, two: 1 });
- await runtime.close();
- assert.deepEqual(closes, { one: 1, two: 1 });
- } finally {
- await rm(directory, { recursive: true, force: true });
- }
-});
-
test("project local runtime accepts an explicitly selected replacement ArtifactStore package", async () => {
const directory = await mkdtemp(join(tmpdir(), "narratage-local-artifacts-"));
const module = { name: "example.remote-artifacts", version: "1" } as const;
@@ -564,8 +467,7 @@ test("project local runtime accepts an explicitly selected replacement ArtifactS
attachments: [{ artifact: sourceArtifact, open: async () => (async function* () { yield bytes; })() }],
});
const blocked = await runtime.workOnce();
- assert.equal(blocked?.terminal, "failed");
- assert.match(blocked?.reason ?? "", /does not bind demanded capability/u);
+ assert.equal(blocked?.phase, "blocked");
assert.deepEqual(await artifactStore.get(sourceArtifact.digest), bytes);
let reopened = false;
await runtime.build({
diff --git a/packages/runtime/src/scheduler.ts b/packages/runtime/src/scheduler.ts
index e36d764f..e4c69f1f 100644
--- a/packages/runtime/src/scheduler.ts
+++ b/packages/runtime/src/scheduler.ts
@@ -1,7 +1,5 @@
import { BuildMachine, buildDefinition, reduce } from "@narratage/core";
import type { BuildState } from "@narratage/protocol";
-import { verifyRuntimeCoverage } from "./profile.js";
-import type { RuntimeClosure } from "./profile.js";
import type {
BuildScheduler,
@@ -55,15 +53,11 @@ export class LocalBuildScheduler implements BuildScheduler {
readonly #executor: RuntimeCommandExecutor;
readonly #maxConcurrency: number;
readonly #resourceLimits: Readonly<Record<string, number>>;
- readonly #runtimeClosure: RuntimeClosure | undefined;
readonly #buildStore: BuildSchedulerOptions["buildStore"];
constructor(executor: RuntimeCommandExecutor, options: BuildSchedulerOptions = {}) {
this.#executor = executor;
this.#maxConcurrency = positiveInteger(options.maxConcurrency ?? 4, "maxConcurrency");
- this.#runtimeClosure = options.runtimeClosure === undefined
- ? undefined
- : structuredClone(options.runtimeClosure);
this.#buildStore = options.buildStore;
for (const [resource, limit] of Object.entries(options.resourceLimits ?? {})) {
if (resource.trim().length === 0) throw new Error("resource override name must not be empty");
@@ -97,7 +91,6 @@ export class LocalBuildScheduler implements BuildScheduler {
state = snapshot.state;
machine = new BuildMachine(snapshot.definition, snapshot.facts);
}
- if (this.#runtimeClosure !== undefined) verifyRuntimeCoverage(this.#runtimeClosure, state);
builds.push({
id: request.id,
state,
diff --git a/packages/runtime/src/types.ts b/packages/runtime/src/types.ts
index 8accdab2..e7b843f2 100644
--- a/packages/runtime/src/types.ts
+++ b/packages/runtime/src/types.ts
@@ -7,7 +7,6 @@ import type {
CoreCommand,
Digest,
} from "@narratage/protocol";
-import type { RuntimeClosure } from "./profile.js";
import type { BuildDispatchSnapshot, BuildDispatchStore } from "./dispatch.js";
import type { OperationSnapshot } from "./operations.js";
@@ -60,7 +59,6 @@ export type RuntimeWorkerFactoryOptions = {
readonly scheduler: BuildSchedulerFactory;
readonly stores: RuntimeExecutionStores;
readonly scheduling: BuildSchedulerOptions;
- readonly runtimeClosure: RuntimeClosure;
};
/** Selected execution strategy. Process supervision remains a generic Host concern. */
@@ -183,7 +181,6 @@ export type ScheduledBuildResult = {
export type BuildSchedulerOptions = {
readonly maxConcurrency?: number;
readonly resourceLimits?: Readonly<Record<string, number>>;
- readonly runtimeClosure?: RuntimeClosure;
/** Optional durable authority. When present, every admitted Core Fact is appended. */
readonly buildStore?: BuildStore;
};