@oona/vlo 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,74 @@
1
+ // src/config/define.ts
2
+ /**
3
+ * Refers to an environment variable by name so a secret never sits in `vlo.config.ts`.
4
+ *
5
+ * The value is read when the profile is loaded, not when `env` is called. An unset or empty
6
+ * variable fails the load with a message naming the variable, unless `optional` is `true`,
7
+ * in which case the field is simply absent.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { defineConfig, env } from "@oona/vlo";
12
+ *
13
+ * export default defineConfig({
14
+ * workflows: ["*.workflow.ts"],
15
+ * profiles: {
16
+ * prod: {
17
+ * journal: env("DATABASE_URL"),
18
+ * auth: { token: env("VLO_TOKEN"), pushSecret: env("VLO_PUSH_SECRET", { optional: true }) },
19
+ * },
20
+ * },
21
+ * });
22
+ * ```
23
+ */
24
+ function env(name, options = {}) {
25
+ return {
26
+ __env: name,
27
+ ...options.optional !== void 0 ? { optional: options.optional } : {}
28
+ };
29
+ }
30
+ /** Whether `value` is an {@link EnvRef} rather than a literal. */
31
+ function isEnvRef(value) {
32
+ return typeof value === "object" && value !== null && "__env" in value;
33
+ }
34
+ /**
35
+ * Types and checks a `vlo.config.ts` and returns it unchanged for `export default`.
36
+ *
37
+ * Throws a `TypeError` when `profiles` is empty. Values wrapped with {@link env} are
38
+ * resolved later, when the CLI loads the profile.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * import { defineConfig, env } from "@oona/vlo";
43
+ *
44
+ * export default defineConfig({
45
+ * workflows: ["./workflows/*.workflow.ts"],
46
+ * workers: ["./workers/*.worker.ts"],
47
+ * profiles: {
48
+ * local: { journal: "sqlite://.vlo/dev.db", blob: "file://.vlo/blobs" },
49
+ * prod: {
50
+ * journal: env("DATABASE_URL"),
51
+ * auth: { token: env("VLO_TOKEN") },
52
+ * roles: ["orchestrator", "api"],
53
+ * queues: { media: { mode: "pull" } },
54
+ * dispatcher: { mode: "manual" },
55
+ * deploy: { target: "vercel", cron: "* * * * *" },
56
+ * },
57
+ * },
58
+ * });
59
+ * ```
60
+ */
61
+ function defineConfig(config) {
62
+ if (Object.keys(config.profiles).length === 0) throw new TypeError("defineConfig: at least one profile is required");
63
+ return config;
64
+ }
65
+ /** Used when there is no `vlo.config.ts`: SQLite and a file blob store under `.vlo/`. */
66
+ const DEFAULT_CONFIG = {
67
+ workflows: ["**/*.workflow.{ts,js,mjs}"],
68
+ workers: ["**/*.worker.{ts,js,mjs}"],
69
+ profiles: { local: {
70
+ journal: "sqlite://.vlo/dev.db",
71
+ blob: "file://.vlo/blobs"
72
+ } }
73
+ };
74
+ export { isEnvRef as i, defineConfig as n, env as r, DEFAULT_CONFIG as t };
@@ -0,0 +1,338 @@
1
+ import { z } from "zod";
2
+ import { createHash } from "node:crypto";
3
+ /**
4
+ * Deterministic JSON: object keys sorted recursively, arrays in order, no whitespace.
5
+ * Throws on anything JSON cannot represent losslessly (undefined, NaN, Infinity, bigint,
6
+ * function, symbol) rather than silently dropping it, because a dropped field would make
7
+ * two different schemas hash the same.
8
+ */
9
+ function canonicalJson(value) {
10
+ switch (typeof value) {
11
+ case "string": return JSON.stringify(value);
12
+ case "boolean": return value ? "true" : "false";
13
+ case "number":
14
+ if (!Number.isFinite(value)) throw new TypeError(`canonicalJson: non-finite number (${String(value)})`);
15
+ return JSON.stringify(value);
16
+ case "object": {
17
+ if (value === null) return "null";
18
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
19
+ const record = value;
20
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
21
+ }
22
+ default: throw new TypeError(`canonicalJson: unsupported value of type ${typeof value}`);
23
+ }
24
+ }
25
+ /** Full SHA-256 of `data` as 64 lowercase hex characters; strings are hashed as UTF-8. */
26
+ function sha256Hex(data) {
27
+ return createHash("sha256").update(data).digest("hex");
28
+ }
29
+ /** SHA-256 of the canonical encoding, truncated to `HASH_CHARS`. */
30
+ function contentHash(value) {
31
+ return sha256Hex(canonicalJson(value)).slice(0, 16);
32
+ }
33
+ // src/core/schema-projection.ts
34
+ /** Version tag folded into every activity and signal hash. Bump when the projection changes. */
35
+ const SCHEMA_HASH_VERSION = 1;
36
+ /** Keywords removed from every schema object before hashing, at any depth. */
37
+ const ANNOTATION_KEYWORDS = [
38
+ "$schema",
39
+ "$id",
40
+ "$comment",
41
+ "title",
42
+ "description",
43
+ "examples",
44
+ "default",
45
+ "deprecated",
46
+ "readOnly",
47
+ "writeOnly"
48
+ ];
49
+ /**
50
+ * Keywords whose value is a map from a user-chosen name to a schema. The names are opaque
51
+ * (a property may be called `default`), only the values are schemas.
52
+ */
53
+ const NAMED_SCHEMA_MAPS = [
54
+ "properties",
55
+ "patternProperties",
56
+ "dependentSchemas",
57
+ "$defs",
58
+ "definitions"
59
+ ];
60
+ const STRIPPED = new Set(ANNOTATION_KEYWORDS);
61
+ const NAMED_MAPS = new Set(NAMED_SCHEMA_MAPS);
62
+ /**
63
+ * Returns a copy of `schema` with every annotation keyword removed from every schema
64
+ * object in it. Arrays are walked (`anyOf`, `prefixItems`, …) in order; the entries of a
65
+ * name-keyed map (`properties`, `$defs`, …) keep their names and have their values
66
+ * projected; scalars pass through. The input is never mutated.
67
+ */
68
+ function projectSchema(schema) {
69
+ if (Array.isArray(schema)) return schema.map(projectSchema);
70
+ if (schema === null || typeof schema !== "object") return schema;
71
+ const projected = {};
72
+ for (const [key, value] of Object.entries(schema)) {
73
+ if (STRIPPED.has(key)) continue;
74
+ projected[key] = NAMED_MAPS.has(key) ? projectNamedMap(value) : projectSchema(value);
75
+ }
76
+ return projected;
77
+ }
78
+ function projectNamedMap(map) {
79
+ if (map === null || typeof map !== "object" || Array.isArray(map)) return map;
80
+ const projected = {};
81
+ for (const [name, schema] of Object.entries(map)) projected[name] = projectSchema(schema);
82
+ return projected;
83
+ }
84
+ // src/core/activity.ts
85
+ /**
86
+ * Activity and signal definitions: a name, Zod schemas, a retry policy, and a content hash
87
+ * derived from all three. The hash is the version: `name@hash` is the `schema_ref` carried
88
+ * on every event, so a run can span a schema upgrade.
89
+ */
90
+ /**
91
+ * Retry policy an activity gets when {@link ActivityOptions.retry} is omitted: three
92
+ * attempts, exponential backoff from 1 s to a 10 min cap, factor 2, full jitter. Each
93
+ * field is also the fallback for any {@link RetryOptions} field left unset.
94
+ */
95
+ const DEFAULT_RETRY = {
96
+ max_attempts: 3,
97
+ backoff: "exponential",
98
+ initial_ms: 1e3,
99
+ max_ms: 6e5,
100
+ factor: 2,
101
+ jitter: "full"
102
+ };
103
+ /**
104
+ * Queue an activity is dispatched on when {@link ActivityOptions.queue} is omitted, and the
105
+ * queue a worker serves when {@link WorkerOptions.queues} is omitted.
106
+ */
107
+ const DEFAULT_QUEUE = "default";
108
+ /** Lease a worker holds before it must heartbeat. Long tasks heartbeat, they do not raise this. */
109
+ const DEFAULT_LEASE_MS = 6e4;
110
+ function toRetryPolicy(options) {
111
+ const o = options ?? {};
112
+ return {
113
+ max_attempts: o.maxAttempts ?? DEFAULT_RETRY.max_attempts,
114
+ backoff: o.backoff ?? DEFAULT_RETRY.backoff,
115
+ initial_ms: o.initialMs ?? DEFAULT_RETRY.initial_ms,
116
+ max_ms: o.maxMs ?? DEFAULT_RETRY.max_ms,
117
+ factor: o.factor ?? DEFAULT_RETRY.factor,
118
+ jitter: o.jitter ?? DEFAULT_RETRY.jitter
119
+ };
120
+ }
121
+ /**
122
+ * Defines an activity: a named unit of work a worker implements and a reducer requests
123
+ * with `cmd.task`.
124
+ *
125
+ * The content hash covers `name`, both schemas (as JSON Schema, projected by
126
+ * {@link projectSchema} so annotations such as `description` and `default` are
127
+ * hash-neutral) and the resolved retry policy, so changing any of them yields a new
128
+ * `schemaRef`; `queue`, `leaseMs` and `timeoutMs` are operational and hash-neutral. Runs
129
+ * pin the `schemaRef` per event, so old and new versions coexist.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { z } from "zod";
134
+ * import { activity } from "@oona/vlo";
135
+ *
136
+ * export const work = activity("example.work", {
137
+ * input: z.object({ item: z.string() }),
138
+ * output: z.object({ upper: z.string() }),
139
+ * retry: { maxAttempts: 3 },
140
+ * queue: "default",
141
+ * timeoutMs: 30_000,
142
+ * });
143
+ * ```
144
+ */
145
+ function activity(name, options) {
146
+ const retry = toRetryPolicy(options.retry);
147
+ const jsonSchema = {
148
+ input: toJsonSchema(options.input),
149
+ output: toJsonSchema(options.output)
150
+ };
151
+ const hash = contentHash({
152
+ v: 1,
153
+ name,
154
+ input: projectSchema(jsonSchema.input),
155
+ output: projectSchema(jsonSchema.output),
156
+ retry
157
+ });
158
+ return {
159
+ kind: "activity",
160
+ name,
161
+ hash,
162
+ schemaRef: `${name}@${hash}`,
163
+ input: options.input,
164
+ output: options.output,
165
+ retry,
166
+ queue: options.queue ?? "default",
167
+ leaseMs: options.leaseMs ?? 6e4,
168
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
169
+ jsonSchema
170
+ };
171
+ }
172
+ /**
173
+ * Defines a signal: a named, typed message a run can park on with `cmd.awaitSignal`,
174
+ * `cmd.awaitHuman` or {@link waitFor}, delivered from outside through the host's API.
175
+ *
176
+ * The content hash covers `name` and the schema as JSON Schema, projected the same way as
177
+ * an activity's. A host that has the definition registered rejects an inbound payload the
178
+ * schema does not accept.
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * import { z } from "zod";
183
+ * import { signal } from "@oona/vlo";
184
+ *
185
+ * export const approve = signal("example.approve", z.object({ by: z.string() }));
186
+ * ```
187
+ */
188
+ function signal(name, schema) {
189
+ const jsonSchema = toJsonSchema(schema);
190
+ const hash = contentHash({
191
+ v: 1,
192
+ name,
193
+ schema: projectSchema(jsonSchema)
194
+ });
195
+ return {
196
+ kind: "signal",
197
+ name,
198
+ hash,
199
+ schemaRef: `${name}@${hash}`,
200
+ schema,
201
+ jsonSchema
202
+ };
203
+ }
204
+ function toJsonSchema(schema) {
205
+ return z.toJSONSchema(schema);
206
+ }
207
+ // src/core/run-status.ts
208
+ /** The statuses a run never leaves: `completed`, `failed`, `cancelled`, `continued`. */
209
+ const TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set([
210
+ "completed",
211
+ "failed",
212
+ "cancelled",
213
+ "continued"
214
+ ]);
215
+ /** True when the run accepts no further events. */
216
+ function isTerminalRunStatus(status) {
217
+ return TERMINAL_RUN_STATUSES.has(status);
218
+ }
219
+ // src/host/worker/registry.ts
220
+ /**
221
+ * Defines a worker: a map from activity name to {@link ActivityHandler} plus the queues it
222
+ * serves. Passed to `createHost({ workers })` for in-process execution, `runPullWorker` for
223
+ * long-polling, or found by the config loader's `workers` globs.
224
+ *
225
+ * The worker holds no schemas; validation happens in the reducer (input) and on the host
226
+ * (output). Throws a `TypeError` when `impls` is empty.
227
+ *
228
+ * @example
229
+ * ```ts
230
+ * import { defineWorker } from "@oona/vlo";
231
+ *
232
+ * export default defineWorker(
233
+ * {
234
+ * "example.plan": (input: { n: number }) => ({
235
+ * items: Array.from({ length: input.n }, (_, i) => `item-${i}`),
236
+ * }),
237
+ * "example.work": async (input: { item: string }, ctx) => {
238
+ * await ctx.heartbeat();
239
+ * ctx.reportUsage({ tokens: 12 });
240
+ * return { upper: input.item.toUpperCase() };
241
+ * },
242
+ * },
243
+ * { queues: ["default"] },
244
+ * );
245
+ * ```
246
+ */
247
+ function defineWorker(impls, options = {}) {
248
+ const handlers = /* @__PURE__ */ new Map();
249
+ for (const [name, handler] of Object.entries(impls)) handlers.set(name, handler);
250
+ if (handlers.size === 0) throw new TypeError("defineWorker: no activity implementations given");
251
+ return {
252
+ kind: "worker",
253
+ queues: options.queues ?? ["default"],
254
+ handlers
255
+ };
256
+ }
257
+ /**
258
+ * Wraps a handler so attempts after the first receive `shape(input, attempt)` instead of the
259
+ * journaled input. Use it when repeating the same ask would fail the same way — a model
260
+ * looping on a long prompt, say — and a smaller or different ask has a chance.
261
+ *
262
+ * The journaled task input is untouched; only this process's view of it changes, and
263
+ * `attempt` is journaled, so the same attempt always sees the same input. `shape` must be
264
+ * pure. The shaped input is not re-validated against the activity's input schema.
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * defineWorker({
269
+ * "brand.synthesize": withRetryInput(synthesize, (input) => ({ ...input, compact: true })),
270
+ * });
271
+ * ```
272
+ */
273
+ function withRetryInput(handler, shape) {
274
+ return (input, ctx) => handler(ctx.attempt > 1 ? shape(input, ctx.attempt) : input, ctx);
275
+ }
276
+ /** The first worker in this process that serves both the queue and the activity. */
277
+ function findWorker(workers, queue, activity) {
278
+ return workers.find((w) => w.queues.includes(queue) && w.handlers.has(activity));
279
+ }
280
+ // src/host/domain.ts
281
+ /**
282
+ * Groups one area's workflows, workers, activities and signals under a name, for
283
+ * `createHost({ domains: [...] })`.
284
+ *
285
+ * @example
286
+ * ```ts
287
+ * import { defineDomain } from "@oona/vlo";
288
+ * import { brandActivities } from "./activities.ts";
289
+ * import { brandResearch, brandWeekly } from "./workflows.ts";
290
+ * import { brandWorker } from "./worker.ts";
291
+ *
292
+ * export const brandDomain = defineDomain({
293
+ * name: "brand",
294
+ * workflows: [brandResearch, brandWeekly],
295
+ * workers: [brandWorker],
296
+ * activities: brandActivities,
297
+ * });
298
+ * ```
299
+ */
300
+ function defineDomain(def) {
301
+ return {
302
+ kind: "domain",
303
+ name: def.name,
304
+ workflows: def.workflows ?? [],
305
+ workers: def.workers ?? [],
306
+ activities: def.activities ?? [],
307
+ signals: def.signals ?? []
308
+ };
309
+ }
310
+ /**
311
+ * Flattens `domains` onto the flat registries. Throws a `TypeError` when two domains share
312
+ * a name, or when two different workflow or activity values are registered under one name;
313
+ * the same value registered twice is fine.
314
+ */
315
+ function mergeDomains(options) {
316
+ const seen = /* @__PURE__ */ new Set();
317
+ for (const domain of options.domains ?? []) {
318
+ if (seen.has(domain.name)) throw new TypeError(`defineDomain: two domains are named "${domain.name}"`);
319
+ seen.add(domain.name);
320
+ }
321
+ const domains = options.domains ?? [];
322
+ return {
323
+ workflows: unique("workflow", [...options.workflows ?? [], ...domains.flatMap((d) => d.workflows)]),
324
+ workers: [.../* @__PURE__ */ new Set([...options.workers ?? [], ...domains.flatMap((d) => d.workers)])],
325
+ activities: unique("activity", [...options.activities ?? [], ...domains.flatMap((d) => d.activities)]),
326
+ signals: unique("signal", [...options.signals ?? [], ...domains.flatMap((d) => d.signals)])
327
+ };
328
+ }
329
+ function unique(what, items) {
330
+ const byName = /* @__PURE__ */ new Map();
331
+ for (const item of items) {
332
+ const prior = byName.get(item.name);
333
+ if (prior !== void 0 && prior !== item) throw new TypeError(`createHost: two different ${what} definitions are named "${item.name}"`);
334
+ byName.set(item.name, item);
335
+ }
336
+ return [...byName.values()];
337
+ }
338
+ export { canonicalJson as _, withRetryInput as a, DEFAULT_LEASE_MS as c, activity as d, signal as f, projectSchema as g, SCHEMA_HASH_VERSION as h, findWorker as i, DEFAULT_QUEUE as l, NAMED_SCHEMA_MAPS as m, mergeDomains as n, TERMINAL_RUN_STATUSES as o, ANNOTATION_KEYWORDS as p, defineWorker as r, isTerminalRunStatus as s, defineDomain as t, DEFAULT_RETRY as u, contentHash as v, sha256Hex as y };