@composable-os/sdk 0.0.0-stage → 0.1.0-beta.11

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.
Files changed (81) hide show
  1. package/LICENSE +109 -0
  2. package/dist/allowance.d.ts +198 -0
  3. package/dist/allowance.js +374 -0
  4. package/dist/automation-check.d.ts +38 -0
  5. package/dist/automation-check.js +454 -0
  6. package/dist/automation.d.ts +767 -0
  7. package/dist/automation.js +303 -0
  8. package/dist/behaviour.d.ts +3 -0
  9. package/dist/behaviour.js +153 -0
  10. package/dist/capacity.d.ts +146 -0
  11. package/dist/capacity.js +189 -0
  12. package/dist/contract.d.ts +851 -0
  13. package/dist/contract.js +42 -0
  14. package/dist/document.d.ts +211 -0
  15. package/dist/document.js +726 -0
  16. package/dist/field-types.d.ts +11 -0
  17. package/dist/field-types.js +98 -0
  18. package/dist/formula/ast.d.ts +67 -0
  19. package/dist/formula/ast.js +22 -0
  20. package/dist/formula/compile.d.ts +37 -0
  21. package/dist/formula/compile.js +379 -0
  22. package/dist/formula/index.d.ts +3 -0
  23. package/dist/formula/index.js +4 -0
  24. package/dist/formula/parser.d.ts +13 -0
  25. package/dist/formula/parser.js +365 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.js +24 -0
  28. package/dist/manifest.d.ts +1708 -0
  29. package/dist/manifest.js +1494 -0
  30. package/dist/media.d.ts +41 -0
  31. package/dist/media.js +90 -0
  32. package/dist/permissions.d.ts +17 -0
  33. package/dist/permissions.js +44 -0
  34. package/dist/recurring.d.ts +114 -0
  35. package/dist/recurring.js +173 -0
  36. package/dist/renamed.d.ts +16 -0
  37. package/dist/renamed.js +59 -0
  38. package/dist/rich-text-fixture.d.ts +121 -0
  39. package/dist/rich-text-fixture.js +67 -0
  40. package/dist/rich-text.d.ts +48 -0
  41. package/dist/rich-text.js +184 -0
  42. package/dist/runtime.d.ts +95 -0
  43. package/dist/runtime.js +312 -0
  44. package/dist/sellable.d.ts +331 -0
  45. package/dist/sellable.js +746 -0
  46. package/dist/slug.d.ts +11 -0
  47. package/dist/slug.js +23 -0
  48. package/dist/states.d.ts +292 -0
  49. package/dist/states.js +383 -0
  50. package/dist/testing.d.ts +151 -0
  51. package/dist/testing.js +679 -0
  52. package/dist/unique.d.ts +20 -0
  53. package/dist/unique.js +58 -0
  54. package/package.json +34 -4
  55. package/src/allowance.ts +522 -0
  56. package/src/automation-check.ts +534 -0
  57. package/src/automation.ts +743 -0
  58. package/src/behaviour.ts +215 -0
  59. package/src/capacity.ts +303 -0
  60. package/src/contract.ts +909 -0
  61. package/src/document.ts +935 -0
  62. package/src/field-types.ts +111 -0
  63. package/src/formula/ast.ts +72 -0
  64. package/src/formula/compile.ts +454 -0
  65. package/src/formula/index.ts +4 -0
  66. package/src/formula/parser.ts +417 -0
  67. package/src/index.ts +36 -0
  68. package/src/manifest.ts +1785 -0
  69. package/src/media.ts +108 -0
  70. package/src/permissions.ts +60 -0
  71. package/src/recurring.ts +321 -0
  72. package/src/renamed.ts +63 -0
  73. package/src/rich-text-fixture.ts +68 -0
  74. package/src/rich-text.ts +221 -0
  75. package/src/runtime.ts +410 -0
  76. package/src/sellable.ts +1138 -0
  77. package/src/slug.ts +25 -0
  78. package/src/states.ts +598 -0
  79. package/src/testing.ts +847 -0
  80. package/src/unique.ts +81 -0
  81. package/README.md +0 -3
@@ -0,0 +1,221 @@
1
+ // The `richText` field type (stage 28, ADR 0440): a document field (ADR 0445) with one fixed
2
+ // schema the platform owns. A post's body is one; a client renders it with its own components,
3
+ // block by block, and never as HTML.
4
+ //
5
+ // body: { type: "richText", label: "Body" }
6
+ //
7
+ // The value is `{ blocks: [...] }`. A block is one of paragraph, heading, list, quote, image,
8
+ // divider, embed, callout and button, told apart by `type`. Text sits in inline runs: a run of
9
+ // text with its marks (bold, italic, code, a link) or a line break. Every text is `noMarkup` and
10
+ // every link is checked by scheme, so no HTML, script or `javascript:` address can be stored, by
11
+ // any actor. A block type, mark or key the schema does not name is refused like any other fault.
12
+ //
13
+ // The schema is data like any declared document schema: the host, `cos ext check`, the SDK's test
14
+ // host and both renderers read this one declaration. Changing it changes what every product
15
+ // stores; a block type added here must be added to both renderers (stage 28, step 6).
16
+ import type { DocumentNode, DocumentObjectNode, DocumentSchema } from "./document.ts";
17
+
18
+ /** The block types, in the order a renderer lists them. */
19
+ export const RICH_TEXT_BLOCKS = [
20
+ "paragraph",
21
+ "heading",
22
+ "list",
23
+ "quote",
24
+ "image",
25
+ "divider",
26
+ "embed",
27
+ "callout",
28
+ "button",
29
+ ] as const;
30
+ export type RichTextBlockType = (typeof RICH_TEXT_BLOCKS)[number];
31
+
32
+ /** The marks a run of text may carry. A link is `href`. */
33
+ export const RICH_TEXT_MARKS = ["bold", "italic", "code", "href"] as const;
34
+
35
+ /** A richText field that declares no `maxBytes`. At most DOCUMENT_MAX_BYTES. */
36
+ export const RICH_TEXT_DEFAULT_BYTES = 131_072;
37
+
38
+ /** The object a picture's `media` names: the media library's (stage 28, step 4). */
39
+ export const RICH_TEXT_MEDIA_OBJECT = "media";
40
+
41
+ const prose = (max: number, extra: Partial<DocumentNode> = {}): DocumentNode =>
42
+ ({ type: "text", max, noMarkup: true, ...extra }) as DocumentNode;
43
+ const optional = (node: DocumentNode): DocumentNode => ({ ...node, optional: true });
44
+ const inlines: DocumentNode = { type: "use", def: "inlines" };
45
+ const object = (fields: Record<string, DocumentNode>): DocumentObjectNode => ({
46
+ type: "object",
47
+ fields,
48
+ });
49
+
50
+ const listShape = (): DocumentObjectNode =>
51
+ object({
52
+ style: { type: "choice", options: ["bullet", "ordered"] },
53
+ items: { type: "array", min: 1, max: 200, of: { type: "use", def: "listItem" } },
54
+ });
55
+
56
+ const blocks: Record<RichTextBlockType, DocumentObjectNode> = {
57
+ paragraph: object({ content: inlines }),
58
+ heading: object({
59
+ level: { type: "number", integer: true, min: 1, max: 6 },
60
+ content: inlines,
61
+ }),
62
+ list: listShape(),
63
+ quote: object({ content: inlines, attribution: optional(prose(300)) }),
64
+ image: object({
65
+ media: {
66
+ type: "ref",
67
+ to: RICH_TEXT_MEDIA_OBJECT,
68
+ media: "image",
69
+ description: "The picture, from media",
70
+ },
71
+ alt: prose(500, { description: "What the picture shows, for people who cannot see it" }),
72
+ caption: optional(inlines),
73
+ }),
74
+ divider: object({}),
75
+ embed: object({
76
+ url: {
77
+ type: "text",
78
+ max: 2000,
79
+ href: "web",
80
+ description: "A video or post to show (YouTube, Vimeo): the client decides how",
81
+ },
82
+ caption: optional(prose(500)),
83
+ }),
84
+ callout: object({
85
+ tone: { type: "choice", options: ["info", "note", "success", "warning"] },
86
+ content: inlines,
87
+ }),
88
+ button: object({
89
+ label: prose(80, { min: 1 }),
90
+ href: { type: "text", max: 2000, href: "link" },
91
+ }),
92
+ };
93
+
94
+ /** The one schema of every richText field. */
95
+ export const RICH_TEXT_SCHEMA: DocumentSchema = {
96
+ root: object({
97
+ blocks: {
98
+ type: "array",
99
+ max: 1000,
100
+ of: {
101
+ type: "union",
102
+ tag: "type",
103
+ variants: blocks,
104
+ },
105
+ },
106
+ }),
107
+ defs: {
108
+ inlines: {
109
+ type: "array",
110
+ max: 500,
111
+ of: {
112
+ type: "union",
113
+ tag: "type",
114
+ variants: {
115
+ text: object({
116
+ text: prose(5000, { min: 1 }),
117
+ bold: optional({ type: "boolean" }),
118
+ italic: optional({ type: "boolean" }),
119
+ code: optional({ type: "boolean" }),
120
+ href: optional({ type: "text", max: 2000, href: "link" }),
121
+ }),
122
+ break: object({}),
123
+ },
124
+ },
125
+ },
126
+ listItem: object({ content: inlines, list: optional({ type: "use", def: "list" }) }),
127
+ list: listShape(),
128
+ },
129
+ };
130
+
131
+ /**
132
+ * The `image` field type (stage 28, ADR 0444): a picture from the media library, with its alt
133
+ * text and the point to keep in view when a client crops it (0 to 1 from the left and the top).
134
+ */
135
+ export const IMAGE_SCHEMA: DocumentSchema = {
136
+ root: object({
137
+ media: {
138
+ type: "ref",
139
+ to: RICH_TEXT_MEDIA_OBJECT,
140
+ media: "image",
141
+ description: "The picture, from media",
142
+ },
143
+ alt: prose(500, { description: "What the picture shows, for people who cannot see it" }),
144
+ focal: optional(
145
+ object({
146
+ x: { type: "number", min: 0, max: 1 },
147
+ y: { type: "number", min: 0, max: 1 },
148
+ }),
149
+ ),
150
+ }),
151
+ };
152
+
153
+ /** The most an image field's value may be, in bytes of its JSON. */
154
+ export const IMAGE_MAX_BYTES = 2048;
155
+
156
+ /**
157
+ * A video from the media library (stage 42, ADR 0475), as a node a declared document may use: the
158
+ * video (a ready one, checked on write) and, optionally, a picture to show before it plays.
159
+ */
160
+ export const VIDEO_NODE: DocumentObjectNode = object({
161
+ media: {
162
+ type: "ref",
163
+ to: RICH_TEXT_MEDIA_OBJECT,
164
+ media: "video",
165
+ description: "The video, from media (a ready one)",
166
+ },
167
+ poster: optional({
168
+ type: "ref",
169
+ to: RICH_TEXT_MEDIA_OBJECT,
170
+ media: "image",
171
+ description: "A picture shown before it plays",
172
+ }),
173
+ });
174
+
175
+ /** A downloadable file from the media library (a PDF), as a node a declared document may use. */
176
+ export const FILE_NODE: DocumentNode = {
177
+ type: "ref",
178
+ to: RICH_TEXT_MEDIA_OBJECT,
179
+ media: "file",
180
+ description: "The file, from media",
181
+ };
182
+
183
+ /** The `video` field type (stage 42, ADR 0475): `{ media, poster? }`. */
184
+ export const VIDEO_SCHEMA: DocumentSchema = { root: VIDEO_NODE };
185
+
186
+ /** The most a video field's value may be, in bytes of its JSON. */
187
+ export const VIDEO_MAX_BYTES = 1024;
188
+
189
+ /**
190
+ * The field types whose value is a document (ADR 0445): `document`, `richText`, `image` and
191
+ * `video`.
192
+ */
193
+ export function isDocumentType(type: string | undefined): boolean {
194
+ return type === "document" || type === "richText" || type === "image" || type === "video";
195
+ }
196
+
197
+ /**
198
+ * The schema a document-valued field is checked against: its declared one, or richText's. Not a
199
+ * document type: undefined.
200
+ */
201
+ export function documentSchemaOf(field: {
202
+ type?: string | undefined;
203
+ schema?: unknown;
204
+ }): DocumentSchema | undefined {
205
+ if (field.type === "richText") return RICH_TEXT_SCHEMA;
206
+ if (field.type === "image") return IMAGE_SCHEMA;
207
+ if (field.type === "video") return VIDEO_SCHEMA;
208
+ if (field.type === "document") return field.schema as DocumentSchema | undefined;
209
+ return undefined;
210
+ }
211
+
212
+ /** The size limit of a document-valued field: its declared one, or its type's default. */
213
+ export function documentMaxBytesOf(field: {
214
+ type?: string | undefined;
215
+ maxBytes?: number | undefined;
216
+ }): number | undefined {
217
+ if (field.type === "image") return IMAGE_MAX_BYTES;
218
+ if (field.type === "video") return VIDEO_MAX_BYTES;
219
+ if (field.maxBytes !== undefined) return field.maxBytes;
220
+ return field.type === "richText" ? RICH_TEXT_DEFAULT_BYTES : undefined;
221
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,410 @@
1
+ // The sandbox side of the runtime. The host generates a small entry module per run that imports
2
+ // the extension and the host modules it declared, and calls `runExtension`. Tool handlers get a
3
+ // `ctx` built from those modules; a module the extension did not declare is absent, and using it
4
+ // throws.
5
+ import {
6
+ type AutomationAdvance,
7
+ type AutomationContext,
8
+ type AutomationEvent,
9
+ type AutomationJournalEntry,
10
+ type AutomationRunRequest,
11
+ type AutomationSpec,
12
+ type AutomationStep,
13
+ type AutomationStepApi,
14
+ type AutomationTestStep,
15
+ type Duration,
16
+ durationMs,
17
+ notificationInput,
18
+ } from "./automation.ts";
19
+ import type {
20
+ AiModule,
21
+ Extension,
22
+ ExtensionContext,
23
+ GatekeeperModule,
24
+ LogModule,
25
+ OpsModule,
26
+ StartedBy,
27
+ StorageModule,
28
+ } from "./contract.ts";
29
+ import { toManifest } from "./manifest.ts";
30
+
31
+ type HostFn = (...args: unknown[]) => Promise<unknown>;
32
+
33
+ /** The raw `codemode:*` modules, as imported in the entry module. */
34
+ export interface RawHostModules {
35
+ ops?: { call: HostFn };
36
+ storage?: { get: HostFn; set: HostFn; del: HostFn; list: HostFn };
37
+ log?: { write: HostFn };
38
+ ai?: { summarise: HostFn; extract: HostFn; classify: HostFn };
39
+ /** `codemode:<gatekeeper>` modules, by gatekeeper name. */
40
+ [gatekeeper: string]: Record<string, HostFn> | undefined;
41
+ }
42
+
43
+ export type RunRequest =
44
+ | { kind: "manifest" }
45
+ | {
46
+ kind: "tool";
47
+ tool: string;
48
+ input: unknown;
49
+ version?: string;
50
+ /** Who started the tool, from the host (ADR 0436). */
51
+ caller?: StartedBy;
52
+ };
53
+
54
+ export type RunResponse =
55
+ | { ok: true; value: unknown }
56
+ | { ok: false; error: { code: string; message: string; details?: unknown } };
57
+
58
+ /** What `codemode:ops`'s `call` returns. */
59
+ export type OpsReply =
60
+ | { ok: true; value: unknown }
61
+ | { ok: false; error: { code: string; message: string; details?: unknown } };
62
+
63
+ /** Thrown by `ctx.ops.call` when the operation fails; `code` is the pipeline's error code. */
64
+ export class OpsCallError extends Error {
65
+ override name = "OpsCallError";
66
+ constructor(
67
+ readonly code: string,
68
+ message: string,
69
+ readonly details?: unknown,
70
+ ) {
71
+ super(message);
72
+ }
73
+ }
74
+
75
+ function missing(name: string): never {
76
+ throw new Error(
77
+ `Host module "${name}" is not declared. Add "${name}" to permissions.modules in defineExtension.`,
78
+ );
79
+ }
80
+
81
+ function absent<T extends object>(name: string): T {
82
+ return new Proxy({} as T, {
83
+ get(_target, prop) {
84
+ if (prop === "then") return undefined;
85
+ return () => missing(name);
86
+ },
87
+ });
88
+ }
89
+
90
+ /** Builds the `ctx` tools receive from raw host modules. Exported for the testing harness. */
91
+ export function buildContext(
92
+ extension: { id: string; version: string },
93
+ raw: RawHostModules,
94
+ pending: Promise<unknown>[] = [],
95
+ caller?: StartedBy,
96
+ ): ExtensionContext {
97
+ const ops: OpsModule = raw.ops
98
+ ? {
99
+ call: async (operation, input) => {
100
+ // The host answers with an envelope so error codes survive the isolate boundary.
101
+ const reply = (await raw.ops?.call(operation, input ?? {})) as OpsReply;
102
+ if (reply.ok) return reply.value as never;
103
+ throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
104
+ },
105
+ }
106
+ : absent("ops");
107
+ const storage: StorageModule = raw.storage
108
+ ? {
109
+ get: (key) => raw.storage?.get(key) as Promise<never>,
110
+ set: async (key, value) => {
111
+ await raw.storage?.set(key, value);
112
+ },
113
+ delete: async (key) => {
114
+ await raw.storage?.del(key);
115
+ },
116
+ list: (prefix) => raw.storage?.list(prefix ?? "") as Promise<never>,
117
+ }
118
+ : absent("storage");
119
+ const write = (level: string) => (message: string, data?: unknown) => {
120
+ const call = raw.log?.write(level, String(message), data ?? null);
121
+ if (call) pending.push(call.catch(() => undefined));
122
+ };
123
+ const log: LogModule = raw.log
124
+ ? { info: write("info"), warn: write("warn"), error: write("error") }
125
+ : absent("log");
126
+ const ai: AiModule = raw.ai
127
+ ? {
128
+ summarise: (text, options) => raw.ai?.summarise(text, options ?? {}) as Promise<string>,
129
+ extract: (text, fields) => raw.ai?.extract(text, fields) as Promise<never>,
130
+ classify: (text, labels) => raw.ai?.classify(text, labels) as Promise<never>,
131
+ }
132
+ : absent("ai");
133
+ const gatekeeper = (name: string): GatekeeperModule => {
134
+ const mod = raw[name] as Record<string, HostFn> | undefined;
135
+ if (!mod?.call) return absent<GatekeeperModule>(name);
136
+ return {
137
+ connections: () => mod.connections?.() as Promise<never>,
138
+ call: async (connectionId, resource, method, ...args) => {
139
+ const reply = (await mod.call?.(connectionId, resource, method, args)) as OpsReply;
140
+ if (reply.ok) return reply.value as never;
141
+ throw new OpsCallError(reply.error.code, reply.error.message, reply.error.details);
142
+ },
143
+ types: (connectionId, resource) => mod.types?.(connectionId, resource) as Promise<string>,
144
+ };
145
+ };
146
+ return {
147
+ extension: { id: extension.id, version: extension.version },
148
+ ops,
149
+ storage,
150
+ log,
151
+ ai,
152
+ gatekeeper: gatekeeper as ExtensionContext["gatekeeper"],
153
+ ...(caller ? { caller: Object.freeze({ ...caller }) as StartedBy } : {}),
154
+ };
155
+ }
156
+
157
+ function toError(error: unknown): { code: string; message: string; details?: unknown } {
158
+ if (error && typeof error === "object") {
159
+ const e = error as { code?: unknown; message?: unknown; details?: unknown };
160
+ return {
161
+ code: typeof e.code === "string" ? e.code : "extension_error",
162
+ message: typeof e.message === "string" ? e.message : String(error),
163
+ ...(e.details === undefined ? {} : { details: e.details }),
164
+ };
165
+ }
166
+ return { code: "extension_error", message: String(error) };
167
+ }
168
+
169
+ /** Plain JSON only crosses back to the host. */
170
+ function plain(value: unknown): unknown {
171
+ return value === undefined ? null : JSON.parse(JSON.stringify(value));
172
+ }
173
+
174
+ /** Dispatches one run request inside the sandbox. */
175
+ export async function runExtension(
176
+ extension: Extension,
177
+ request: RunRequest,
178
+ raw: RawHostModules,
179
+ ): Promise<RunResponse> {
180
+ const pending: Promise<unknown>[] = [];
181
+ try {
182
+ if (request.kind === "manifest") return { ok: true, value: plain(toManifest(extension)) };
183
+ const tool = extension.tools?.[request.tool];
184
+ if (!tool) {
185
+ return {
186
+ ok: false,
187
+ error: { code: "unknown_tool", message: `No tool named ${request.tool}` },
188
+ };
189
+ }
190
+ const parsed = tool.input.safeParse(request.input);
191
+ if (!parsed.success) {
192
+ return {
193
+ ok: false,
194
+ error: {
195
+ code: "invalid_input",
196
+ message: `Invalid input for ${request.tool}`,
197
+ details: plain(parsed.error.issues),
198
+ },
199
+ };
200
+ }
201
+ const ctx = buildContext(extension, raw, pending, request.caller);
202
+ const result = await tool.handler(parsed.data, ctx);
203
+ const checked = tool.output.safeParse(result);
204
+ await Promise.all(pending);
205
+ if (!checked.success) {
206
+ return {
207
+ ok: false,
208
+ error: {
209
+ code: "invalid_output",
210
+ message: `${request.tool} returned an invalid result`,
211
+ details: plain(checked.error.issues),
212
+ },
213
+ };
214
+ }
215
+ return { ok: true, value: plain(checked.data) };
216
+ } catch (error) {
217
+ await Promise.all(pending);
218
+ return { ok: false, error: toError(error) };
219
+ }
220
+ }
221
+
222
+ // ---------------------------------------------------------------------------------------------
223
+ // Automations (ADR 0130): the replay protocol. The host replays `run` with the journal of steps
224
+ // already done on every advance: journaled steps return their stored results, the first new
225
+ // `step.do` runs and the advance stops there, and a new sleep or wait stops without running
226
+ // anything. Test mode (ADR 0133) runs to the end, skipping waits.
227
+
228
+ /** What `runAutomation` returns in `value`: an advance, or (test mode) every step. */
229
+ export type AutomationRunValue =
230
+ | AutomationAdvance
231
+ | { kind: "test"; steps: AutomationTestStep[]; value: unknown };
232
+
233
+ /** Thrown to unwind `run` once the advance has done its one step. Never reaches the host. */
234
+ class AdvanceStop extends Error {
235
+ override name = "AdvanceStop";
236
+ }
237
+
238
+ /** A step call that does not match the declarations (the declarations are the contract). */
239
+ export class AutomationStepError extends Error {
240
+ override name = "AutomationStepError";
241
+ readonly code = "undeclared_step";
242
+ }
243
+
244
+ /**
245
+ * Builds the automation `ctx`: the extension context plus `notify`, which calls
246
+ * `notification.send` with `notificationInput`. Its dedupe key is `<step>:<n>` (the n-th notify
247
+ * of that step), so a step retried or replayed never notifies twice.
248
+ */
249
+ export function buildAutomationContext(
250
+ extension: { id: string; version: string },
251
+ raw: RawHostModules,
252
+ event: AutomationEvent,
253
+ pending: Promise<unknown>[] = [],
254
+ currentStep: () => string | null = () => null,
255
+ ): AutomationContext {
256
+ const base = buildContext(extension, raw, pending);
257
+ const counts = new Map<string, number>();
258
+ return {
259
+ ...base,
260
+ async notify(to, message) {
261
+ const step = currentStep() ?? "run";
262
+ const n = (counts.get(step) ?? 0) + 1;
263
+ counts.set(step, n);
264
+ const input = notificationInput(event, to, message, `${step}:${n}`);
265
+ const out = (await base.ops.call("notification.send" as never, input as never)) as {
266
+ sent?: number;
267
+ } | null;
268
+ return { sent: typeof out?.sent === "number" ? out.sent : 0 };
269
+ },
270
+ };
271
+ }
272
+
273
+ /** Runs one advance (or a whole test run) of an automation inside the sandbox. */
274
+ export async function runAutomation(
275
+ extension: Extension,
276
+ request: AutomationRunRequest,
277
+ raw: RawHostModules,
278
+ ): Promise<RunResponse> {
279
+ const spec = extension.automations?.[request.automation] as AutomationSpec | undefined;
280
+ if (!spec) {
281
+ return {
282
+ ok: false,
283
+ error: { code: "unknown_automation", message: `No automation named ${request.automation}` },
284
+ };
285
+ }
286
+ const test = request.mode === "test";
287
+ const journal = request.journal ?? [];
288
+ const declared = new Map(spec.steps.map((s) => [s.name, s] as const));
289
+ const testSteps: AutomationTestStep[] = [];
290
+ let cursor = 0;
291
+ let stop: AutomationAdvance | null = null;
292
+
293
+ const declaredStep = (name: string, kind: "do" | "sleep" | "waitForEvent"): AutomationStep => {
294
+ const step = declared.get(name);
295
+ if (!step) {
296
+ throw new AutomationStepError(
297
+ `step.${kind}("${name}") is not a declared step of ${request.automation}; add it to steps`,
298
+ );
299
+ }
300
+ const declaredKind = step.kind ?? "do";
301
+ if (declaredKind !== kind) {
302
+ throw new AutomationStepError(
303
+ `"${name}" is declared as a ${declaredKind} step but was called with step.${kind}`,
304
+ );
305
+ }
306
+ return step;
307
+ };
308
+ /** The journaled result of the next step, or undefined when it is new. */
309
+ const replayed = (name: string, kind: AutomationJournalEntry["kind"]) => {
310
+ if (stop) throw new AdvanceStop();
311
+ const entry = journal[cursor];
312
+ if (!entry) return undefined;
313
+ if (entry.name !== name || entry.kind !== kind) {
314
+ throw new AutomationStepError(
315
+ `The run took a different path on replay: step ${cursor + 1} was "${entry.name}" ` +
316
+ `(${entry.kind}) and is now "${name}" (${kind}). Steps must run in the same order ` +
317
+ "every time; base branches on step results, not on the clock or randomness.",
318
+ );
319
+ }
320
+ cursor += 1;
321
+ return { value: entry.value };
322
+ };
323
+ const halt = (advance: AutomationAdvance): never => {
324
+ stop = advance;
325
+ throw new AdvanceStop();
326
+ };
327
+
328
+ const pending: Promise<unknown>[] = [];
329
+ // Every ops call carries the step it ran in, so the host can file it under that step (and
330
+ // flag writes the step did not declare).
331
+ let current: string | null = null;
332
+ const ops = raw.ops;
333
+ const tagged: RawHostModules = ops
334
+ ? { ...raw, ops: { call: (operation, input) => ops.call(operation, input, { step: current }) } }
335
+ : raw;
336
+ const ctx = buildAutomationContext(extension, tagged, request.event, pending, () => current);
337
+ const step = {
338
+ async do(name: string, a: unknown, b?: unknown): Promise<unknown> {
339
+ const fn = (typeof a === "function" ? a : b) as () => unknown;
340
+ const declaredDo = declaredStep(name, "do") as { writes?: readonly { object: string }[] };
341
+ if (a && typeof a === "object") {
342
+ const intent = a as { writes?: readonly { object: string }[] };
343
+ const allowed = new Set((declaredDo.writes ?? []).map((w) => w.object));
344
+ const extra = (intent.writes ?? []).find((w) => !allowed.has(w.object));
345
+ if (extra) {
346
+ throw new AutomationStepError(
347
+ `step.do("${name}") writes ${extra.object}, which its declaration does not list`,
348
+ );
349
+ }
350
+ }
351
+ const r = replayed(name, "do");
352
+ if (r) return r.value;
353
+ current = name;
354
+ let value: unknown;
355
+ try {
356
+ value = plain(await fn());
357
+ } finally {
358
+ current = null;
359
+ }
360
+ if (test) {
361
+ testSteps.push({ name, kind: "do", value });
362
+ return value;
363
+ }
364
+ return halt({ kind: "do", name, value });
365
+ },
366
+ async sleep(name: string, duration: Duration): Promise<void> {
367
+ declaredStep(name, "sleep");
368
+ if (replayed(name, "sleep")) return;
369
+ const ms = durationMs(duration);
370
+ if (test) {
371
+ testSteps.push({ name, kind: "sleep", skippedMs: ms });
372
+ return;
373
+ }
374
+ halt({ kind: "sleep", name, ms });
375
+ },
376
+ async waitForEvent(name: string): Promise<unknown> {
377
+ const declaredWait = declaredStep(name, "waitForEvent") as {
378
+ event: string;
379
+ timeout?: Duration;
380
+ };
381
+ const r = replayed(name, "waitForEvent");
382
+ if (r) return r.value ?? null;
383
+ const timeoutMs = durationMs(declaredWait.timeout ?? "7 days");
384
+ if (test) {
385
+ testSteps.push({ name, kind: "waitForEvent", skippedMs: timeoutMs });
386
+ return null;
387
+ }
388
+ return halt({ kind: "waitForEvent", name, event: declaredWait.event, timeoutMs });
389
+ },
390
+ } as AutomationStepApi;
391
+
392
+ try {
393
+ const value = await spec.run(request.event, step, ctx);
394
+ await Promise.all(pending);
395
+ if (stop) return { ok: true, value: plain(stop) };
396
+ const done: AutomationRunValue = test
397
+ ? { kind: "test", steps: testSteps, value: plain(value) }
398
+ : { kind: "done", value: plain(value) };
399
+ return { ok: true, value: plain(done) };
400
+ } catch (error) {
401
+ await Promise.all(pending);
402
+ // The stop unwinds `run` by throwing; code that catches and rethrows it changes nothing.
403
+ if (stop) return { ok: true, value: plain(stop) };
404
+ // Test mode keeps the steps that ran before the failure, for the report.
405
+ if (test) {
406
+ return { ok: false, error: { ...toError(error), details: { steps: plain(testSteps) } } };
407
+ }
408
+ return { ok: false, error: toError(error) };
409
+ }
410
+ }