@abyss-project/runtime 0.0.0-stage → 2.0.0

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 (132) hide show
  1. package/.eslintrc.js +32 -0
  2. package/.prettierrc +5 -0
  3. package/README.md +28 -3
  4. package/dist/access/access.types.d.ts +14 -0
  5. package/dist/access/access.types.js +9 -0
  6. package/dist/access/access.types.js.map +1 -0
  7. package/dist/access/host-match.d.ts +1 -0
  8. package/dist/access/host-match.js +14 -0
  9. package/dist/access/host-match.js.map +1 -0
  10. package/dist/cost/execution-cost.d.ts +45 -0
  11. package/dist/cost/execution-cost.js +114 -0
  12. package/dist/cost/execution-cost.js.map +1 -0
  13. package/dist/definition/definition.limits.d.ts +4 -0
  14. package/dist/definition/definition.limits.js +8 -0
  15. package/dist/definition/definition.limits.js.map +1 -0
  16. package/dist/definition/definition.schema.d.ts +8 -0
  17. package/dist/definition/definition.schema.js +123 -0
  18. package/dist/definition/definition.schema.js.map +1 -0
  19. package/dist/definition/definition.types.d.ts +117 -0
  20. package/dist/definition/definition.types.js +37 -0
  21. package/dist/definition/definition.types.js.map +1 -0
  22. package/dist/definition/validate-definition.d.ts +9 -0
  23. package/dist/definition/validate-definition.js +163 -0
  24. package/dist/definition/validate-definition.js.map +1 -0
  25. package/dist/definition/walk-steps.d.ts +5 -0
  26. package/dist/definition/walk-steps.js +31 -0
  27. package/dist/definition/walk-steps.js.map +1 -0
  28. package/dist/engine/engine-entry.d.ts +1 -0
  29. package/dist/engine/engine-entry.js +6 -0
  30. package/dist/engine/engine-entry.js.map +1 -0
  31. package/dist/engine/engine-global.d.ts +1 -0
  32. package/dist/engine/engine-global.js +5 -0
  33. package/dist/engine/engine-global.js.map +1 -0
  34. package/dist/engine/engine-source.d.ts +2 -0
  35. package/dist/engine/engine-source.js +3 -0
  36. package/dist/engine/run-in-isolate.d.ts +34 -0
  37. package/dist/engine/run-in-isolate.js +267 -0
  38. package/dist/engine/run-in-isolate.js.map +1 -0
  39. package/dist/errors/runtime-error-code.enum.d.ts +18 -0
  40. package/dist/errors/runtime-error-code.enum.js +19 -0
  41. package/dist/errors/runtime-error-code.enum.js.map +1 -0
  42. package/dist/index.d.ts +21 -0
  43. package/dist/index.js +47 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/interpreter/interpreter-error.d.ts +5 -0
  46. package/dist/interpreter/interpreter-error.js +12 -0
  47. package/dist/interpreter/interpreter-error.js.map +1 -0
  48. package/dist/interpreter/interpreter.d.ts +30 -0
  49. package/dist/interpreter/interpreter.js +313 -0
  50. package/dist/interpreter/interpreter.js.map +1 -0
  51. package/dist/interpreter/interpreter.types.d.ts +152 -0
  52. package/dist/interpreter/interpreter.types.js +31 -0
  53. package/dist/interpreter/interpreter.types.js.map +1 -0
  54. package/dist/interpreter/sequence-path.d.ts +6 -0
  55. package/dist/interpreter/sequence-path.js +53 -0
  56. package/dist/interpreter/sequence-path.js.map +1 -0
  57. package/dist/interpreter/test-host.d.ts +18 -0
  58. package/dist/interpreter/test-host.js +43 -0
  59. package/dist/interpreter/test-host.js.map +1 -0
  60. package/dist/runner-protocol/evaluation.types.d.ts +20 -0
  61. package/dist/runner-protocol/evaluation.types.js +10 -0
  62. package/dist/runner-protocol/evaluation.types.js.map +1 -0
  63. package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
  64. package/dist/runner-protocol/execution-protocol.types.js +48 -0
  65. package/dist/runner-protocol/execution-protocol.types.js.map +1 -0
  66. package/dist/server/code-runner-error.d.ts +5 -0
  67. package/dist/server/code-runner-error.js +12 -0
  68. package/dist/server/code-runner-error.js.map +1 -0
  69. package/dist/server/code-runner-session.d.ts +28 -0
  70. package/dist/server/code-runner-session.js +208 -0
  71. package/dist/server/code-runner-session.js.map +1 -0
  72. package/dist/server/index.d.ts +3 -0
  73. package/dist/server/index.js +10 -0
  74. package/dist/server/index.js.map +1 -0
  75. package/dist/steps/execute-step.d.ts +50 -0
  76. package/dist/steps/execute-step.js +136 -0
  77. package/dist/steps/execute-step.js.map +1 -0
  78. package/dist/steps/global-references.d.ts +2 -0
  79. package/dist/steps/global-references.js +28 -0
  80. package/dist/steps/global-references.js.map +1 -0
  81. package/dist/steps/step-access.d.ts +8 -0
  82. package/dist/steps/step-access.js +39 -0
  83. package/dist/steps/step-access.js.map +1 -0
  84. package/dist/steps/step-fields.d.ts +5 -0
  85. package/dist/steps/step-fields.js +68 -0
  86. package/dist/steps/step-fields.js.map +1 -0
  87. package/dist/steps/value-source.d.ts +6 -0
  88. package/dist/steps/value-source.js +58 -0
  89. package/dist/steps/value-source.js.map +1 -0
  90. package/jest.config.ts +11 -0
  91. package/package.json +68 -3
  92. package/scripts/build-engine.cjs +70 -0
  93. package/src/__tests__/engine-bundle.test.ts +121 -0
  94. package/src/__tests__/surface.test.ts +53 -0
  95. package/src/access/__tests__/host-match.test.ts +24 -0
  96. package/src/access/access.types.ts +25 -0
  97. package/src/access/host-match.ts +13 -0
  98. package/src/cost/__tests__/execution-cost.test.ts +200 -0
  99. package/src/cost/execution-cost.ts +192 -0
  100. package/src/definition/__tests__/validate-definition.test.ts +354 -0
  101. package/src/definition/definition.limits.ts +9 -0
  102. package/src/definition/definition.schema.ts +172 -0
  103. package/src/definition/definition.types.ts +171 -0
  104. package/src/definition/validate-definition.ts +206 -0
  105. package/src/definition/walk-steps.ts +44 -0
  106. package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
  107. package/src/engine/engine-entry.ts +3 -0
  108. package/src/engine/engine-global.ts +2 -0
  109. package/src/engine/run-in-isolate.ts +404 -0
  110. package/src/errors/runtime-error-code.enum.ts +37 -0
  111. package/src/index.ts +30 -0
  112. package/src/interpreter/__tests__/interpreter.test.ts +854 -0
  113. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
  114. package/src/interpreter/interpreter-error.ts +12 -0
  115. package/src/interpreter/interpreter.ts +461 -0
  116. package/src/interpreter/interpreter.types.ts +192 -0
  117. package/src/interpreter/sequence-path.ts +67 -0
  118. package/src/interpreter/test-host.ts +85 -0
  119. package/src/runner-protocol/evaluation.types.ts +21 -0
  120. package/src/runner-protocol/execution-protocol.types.ts +221 -0
  121. package/src/server/__tests__/code-runner-session.test.ts +311 -0
  122. package/src/server/code-runner-error.ts +12 -0
  123. package/src/server/code-runner-session.ts +310 -0
  124. package/src/server/index.ts +11 -0
  125. package/src/steps/__tests__/global-references.test.ts +113 -0
  126. package/src/steps/execute-step.ts +186 -0
  127. package/src/steps/global-references.ts +48 -0
  128. package/src/steps/step-access.ts +56 -0
  129. package/src/steps/step-fields.ts +87 -0
  130. package/src/steps/value-source.ts +69 -0
  131. package/tsconfig.check.json +15 -0
  132. package/tsconfig.json +35 -0
@@ -0,0 +1,854 @@
1
+ import Joi from 'joi';
2
+ import { AccessKind } from '../../access/access.types';
3
+ import type { AccessDeclaration } from '../../access/access.types';
4
+ import {
5
+ CURRENT_FORMAT_VERSION,
6
+ HttpMethod,
7
+ StepType,
8
+ StopStatus,
9
+ } from '../../definition/definition.types';
10
+ import { MAX_WAIT_DURATION_MS } from '../../definition/definition.schema';
11
+ import type { HostActionCatalog, RuntimeDefinition, Step } from '../../definition/definition.types';
12
+ import { RuntimeErrorCode } from '../../errors/runtime-error-code.enum';
13
+ import { EvaluationKind } from '../../runner-protocol/evaluation.types';
14
+ import type { EvaluationItem, EvaluationResult } from '../../runner-protocol/evaluation.types';
15
+ import { InterpreterError } from '../interpreter-error';
16
+ import { start, step } from '../interpreter';
17
+ import { EffectType, RunEventType, RunStatus } from '../interpreter.types';
18
+ import type { RunEvent, RunOptions, StepResult } from '../interpreter.types';
19
+ import { runToCompletion } from '../test-host';
20
+ import type { TestHostHandlers } from '../test-host';
21
+
22
+ const HTTP_ACCESS: AccessDeclaration = {
23
+ kind: AccessKind.HTTP,
24
+ hosts: ['api.example.com', '*.trusted.org'],
25
+ };
26
+ const SEND_ACCESS: AccessDeclaration = { kind: AccessKind.HOST_ACTION, action: 'send' };
27
+
28
+ const catalog: HostActionCatalog = new Map([
29
+ [
30
+ 'send',
31
+ { name: 'send', inputSchema: Joi.object({ to: Joi.string().required(), count: Joi.number() }) },
32
+ ],
33
+ ]);
34
+
35
+ const options = (overrides: Partial<RunOptions> = {}): RunOptions => ({
36
+ catalog,
37
+ grants: [HTTP_ACCESS, SEND_ACCESS],
38
+ budget: { maxSteps: 100, maxEffects: 100, maxWaitMs: 1_000_000 },
39
+ ...overrides,
40
+ });
41
+
42
+ const definitionOf = (
43
+ steps: Step[],
44
+ accesses: AccessDeclaration[] = [HTTP_ACCESS, SEND_ACCESS],
45
+ ): RuntimeDefinition => ({
46
+ formatVersion: CURRENT_FORMAT_VERSION,
47
+ accesses,
48
+ steps,
49
+ });
50
+
51
+ /** Understands prepared sources only: never evaluates anything. */
52
+ const tableEvaluator =
53
+ (table: Record<string, unknown>): TestHostHandlers['evaluate'] =>
54
+ (effect) =>
55
+ effect.items.map(
56
+ (item: EvaluationItem): EvaluationResult =>
57
+ item.source in table
58
+ ? { id: item.id, ok: true, value: table[item.source] }
59
+ : {
60
+ id: item.id,
61
+ ok: false,
62
+ error: { code: RuntimeErrorCode.EXPRESSION_ERROR, message: 'unknown source' },
63
+ },
64
+ );
65
+
66
+ const deepFreeze = <T>(value: T): T => {
67
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
68
+ Object.freeze(value);
69
+ Object.values(value).forEach(deepFreeze);
70
+ }
71
+ return value;
72
+ };
73
+
74
+ const evaluated = (results: EvaluationResult[]): RunEvent => ({
75
+ type: RunEventType.EVALUATED,
76
+ results,
77
+ });
78
+
79
+ const outputOf = (state: { outputs: Record<string, { output: unknown }> }, id: string): unknown =>
80
+ state.outputs[id]?.output;
81
+
82
+ const httpStep: Step = {
83
+ id: 'call',
84
+ type: StepType.HTTP,
85
+ method: HttpMethod.POST,
86
+ url: '{{ base }}',
87
+ headers: { Authorization: 'Bearer {{ token }}', 'X-Count': { $expression: 'count' } },
88
+ body: { user: { name: '{{ name }}' }, tags: ['a', '{{ tag }}'] },
89
+ timeoutMs: 1000,
90
+ };
91
+
92
+ describe('interpreter', () => {
93
+ describe('criterion 2: pure, deterministic, serializable', () => {
94
+ const definition = definitionOf([
95
+ { id: 'set', type: StepType.SET, variable: 'who', value: '{{ name }}' },
96
+ httpStep,
97
+ {
98
+ id: 'mail',
99
+ type: StepType.HOST,
100
+ action: 'send',
101
+ input: { to: { $expression: 'vars.who' } },
102
+ },
103
+ ]);
104
+ const table = {
105
+ '{{ name }}': 'Ada',
106
+ '{{ base }}': 'https://api.example.com',
107
+ 'Bearer {{ token }}': 'Bearer t0k',
108
+ count: 3,
109
+ '{{ tag }}': 'x',
110
+ 'vars.who': 'ada@example.com',
111
+ };
112
+
113
+ it('gives the same result for the same input', () => {
114
+ expect(start(definition, { a: 1 }, options())).toEqual(
115
+ start(definition, { a: 1 }, options()),
116
+ );
117
+ });
118
+
119
+ it('resumes identically from a JSON round-tripped state', async () => {
120
+ const first = start(definition, null, options());
121
+ const roundTripped = JSON.parse(JSON.stringify(first.state));
122
+ const results = await tableEvaluator(table)(first.effects[0] as never);
123
+ const direct = step(definition, first.state, evaluated(results), options());
124
+ const resumed = step(definition, roundTripped, evaluated(results), options());
125
+ expect(JSON.parse(JSON.stringify(resumed))).toEqual(JSON.parse(JSON.stringify(direct)));
126
+ });
127
+
128
+ it('does not mutate its arguments', async () => {
129
+ const frozenDefinition = deepFreeze(JSON.parse(JSON.stringify(definition)));
130
+ const frozenInput = deepFreeze({ nested: { a: 1 } });
131
+ const frozenOptions = { ...options(), grants: deepFreeze([HTTP_ACCESS, SEND_ACCESS]) };
132
+ let result: StepResult = start(frozenDefinition, frozenInput, frozenOptions);
133
+ while (result.effects.length > 0) {
134
+ const effect = result.effects[0];
135
+ const frozenState = deepFreeze(JSON.parse(JSON.stringify(result.state)));
136
+ const event: RunEvent =
137
+ effect.type === EffectType.EVALUATE
138
+ ? evaluated(await tableEvaluator(table)(effect))
139
+ : effect.type === EffectType.HTTP
140
+ ? { type: RunEventType.HTTP_COMPLETED, response: { status: 200, headers: {}, body: 1 } }
141
+ : { type: RunEventType.HOST_COMPLETED, output: 1 };
142
+ result = step(frozenDefinition, frozenState, deepFreeze(event), frozenOptions);
143
+ }
144
+ expect(result.status).toBe(RunStatus.SUCCEEDED);
145
+ });
146
+ });
147
+
148
+ describe('criterion 3: one evaluation lot per step', () => {
149
+ it('emits exactly one EVALUATE effect holding url, header and body items', () => {
150
+ const { effects, state } = start(
151
+ definitionOf([
152
+ {
153
+ id: 'call',
154
+ type: StepType.HTTP,
155
+ method: HttpMethod.GET,
156
+ url: 'https://api.example.com/{{ id }}',
157
+ headers: { Authorization: 'Bearer {{ token }}' },
158
+ body: { user: { name: { $expression: 'input.name' } } },
159
+ },
160
+ ]),
161
+ { name: 'Ada' },
162
+ options(),
163
+ );
164
+ expect(effects).toHaveLength(1);
165
+ expect(effects[0]).toMatchObject({ type: EffectType.EVALUATE, stepId: 'call' });
166
+ const evaluate = effects[0] as { items: EvaluationItem[]; context: unknown };
167
+ expect(evaluate.items).toEqual([
168
+ { id: 'url', kind: EvaluationKind.TEMPLATE, source: 'https://api.example.com/{{ id }}' },
169
+ {
170
+ id: 'headers.Authorization',
171
+ kind: EvaluationKind.TEMPLATE,
172
+ source: 'Bearer {{ token }}',
173
+ },
174
+ { id: 'body.user.name', kind: EvaluationKind.EXPRESSION, source: 'input.name' },
175
+ ]);
176
+ expect(evaluate.context).toEqual({ input: { name: 'Ada' }, steps: {}, vars: {} });
177
+ expect(state.pending).toEqual(effects[0]);
178
+ });
179
+
180
+ it('emits no EVALUATE effect for a step with literals only', () => {
181
+ const { effects } = start(
182
+ definitionOf([{ id: 'wait', type: StepType.WAIT, durationMs: 50 }]),
183
+ null,
184
+ options(),
185
+ );
186
+ expect(effects).toEqual([{ type: EffectType.WAIT, stepId: 'wait', durationMs: 50 }]);
187
+ });
188
+
189
+ it('builds the HTTP request from resolved values, headers as strings', async () => {
190
+ const { effects } = await runToCompletion(definitionOf([httpStep]), null, options(), {
191
+ evaluate: tableEvaluator({
192
+ '{{ base }}': 'https://api.example.com',
193
+ 'Bearer {{ token }}': 'Bearer t0k',
194
+ count: 3,
195
+ '{{ name }}': 'Ada',
196
+ '{{ tag }}': 'x',
197
+ }),
198
+ });
199
+ expect(effects[1]).toEqual({
200
+ type: EffectType.HTTP,
201
+ stepId: 'call',
202
+ request: {
203
+ method: HttpMethod.POST,
204
+ url: 'https://api.example.com',
205
+ headers: { Authorization: 'Bearer t0k', 'X-Count': '3' },
206
+ body: { user: { name: 'Ada' }, tags: ['a', 'x'] },
207
+ timeoutMs: 1000,
208
+ },
209
+ });
210
+ });
211
+ });
212
+
213
+ describe('criterion 4: every step type', () => {
214
+ const run = (
215
+ steps: Step[],
216
+ table: Record<string, unknown> = {},
217
+ handlers: Partial<TestHostHandlers> = {},
218
+ ) =>
219
+ runToCompletion(definitionOf(steps), { n: 1 }, options(), {
220
+ evaluate: tableEvaluator(table),
221
+ ...handlers,
222
+ });
223
+
224
+ const markers = (id: string): Step => ({ id, type: StepType.SET, variable: id, value: id });
225
+
226
+ it('CONDITION takes then when truthy', async () => {
227
+ const { state } = await run(
228
+ [
229
+ {
230
+ id: 'c',
231
+ type: StepType.CONDITION,
232
+ if: { $expression: 'ok' },
233
+ then: [markers('t')],
234
+ else: [markers('e')],
235
+ },
236
+ ],
237
+ { ok: 1 },
238
+ );
239
+ expect(state.vars).toEqual({ t: 't' });
240
+ expect(outputOf(state, 'c')).toBe('then');
241
+ });
242
+
243
+ it('CONDITION takes else when falsy, and nothing without else', async () => {
244
+ const branching: Step = {
245
+ id: 'c',
246
+ type: StepType.CONDITION,
247
+ if: { $expression: 'ok' },
248
+ then: [markers('t')],
249
+ else: [markers('e')],
250
+ };
251
+ const withElse = await run([branching], { ok: 0 });
252
+ expect(withElse.state.vars).toEqual({ e: 'e' });
253
+ const noElse: Step = {
254
+ ...(branching as Extract<Step, { type: StepType.CONDITION }>),
255
+ else: undefined,
256
+ };
257
+ const without = await run([noElse, markers('after')], { ok: 0 });
258
+ expect(without.state.vars).toEqual({ after: 'after' });
259
+ expect(without.state.status).toBe(RunStatus.SUCCEEDED);
260
+ });
261
+
262
+ const switchStep = (withDefault: boolean): Step => ({
263
+ id: 's',
264
+ type: StepType.SWITCH,
265
+ value: { $expression: 'kind' },
266
+ cases: [
267
+ { match: 'a', steps: [markers('ca')] },
268
+ { match: { $expression: 'bValue' }, steps: [markers('cb')] },
269
+ ],
270
+ ...(withDefault ? { default: [markers('d')] } : {}),
271
+ });
272
+
273
+ it('SWITCH takes the matching case, compared strictly', async () => {
274
+ const second = await run([switchStep(true)], { kind: 'b', bValue: 'b' });
275
+ expect(second.state.vars).toEqual({ cb: 'cb' });
276
+ expect(outputOf(second.state, 's')).toBe('cases[1]');
277
+ const strict = await run([switchStep(true)], { kind: 1, bValue: '1' });
278
+ expect(strict.state.vars).toEqual({ d: 'd' });
279
+ });
280
+
281
+ it('SWITCH falls back to default, or to nothing', async () => {
282
+ const table = { kind: 'zzz', bValue: 'b' };
283
+ const withDefault = await run([switchStep(true)], table);
284
+ expect(withDefault.state.vars).toEqual({ d: 'd' });
285
+ expect(outputOf(withDefault.state, 's')).toBe('default');
286
+ const without = await run([switchStep(false)], table);
287
+ expect(without.state.vars).toEqual({});
288
+ expect(outputOf(without.state, 's')).toBeNull();
289
+ expect(without.state.status).toBe(RunStatus.SUCCEEDED);
290
+ });
291
+
292
+ it('WAIT with a duration or a date emits a WaitEffect and outputs null', async () => {
293
+ const { state, effects } = await run(
294
+ [
295
+ { id: 'w1', type: StepType.WAIT, durationMs: 1500 },
296
+ { id: 'w2', type: StepType.WAIT, until: '2030-01-01T00:00:00.000Z' },
297
+ { id: 'w3', type: StepType.WAIT, durationMs: { $expression: 'delay' } },
298
+ ],
299
+ { delay: 20 },
300
+ );
301
+ expect(effects.filter((effect) => effect.type === EffectType.WAIT)).toEqual([
302
+ { type: EffectType.WAIT, stepId: 'w1', durationMs: 1500 },
303
+ { type: EffectType.WAIT, stepId: 'w2', until: '2030-01-01T00:00:00.000Z' },
304
+ { type: EffectType.WAIT, stepId: 'w3', durationMs: 20 },
305
+ ]);
306
+ expect(outputOf(state, 'w1')).toBeNull();
307
+ expect(state.status).toBe(RunStatus.SUCCEEDED);
308
+ });
309
+
310
+ it('WAIT with an unusable resolved duration fails the run', async () => {
311
+ const { state, effects } = await run(
312
+ [{ id: 'w', type: StepType.WAIT, durationMs: { $expression: 'delay' } }],
313
+ { delay: 'soon' },
314
+ );
315
+ expect(effects).toHaveLength(1);
316
+ expect(state.outcome?.error).toMatchObject({
317
+ code: RuntimeErrorCode.EXPRESSION_ERROR,
318
+ stepId: 'w',
319
+ });
320
+ });
321
+
322
+ it('WAIT with a resolved duration above the budget fails with BUDGET_EXCEEDED, no effect', async () => {
323
+ const { state, effects } = await run(
324
+ [{ id: 'w', type: StepType.WAIT, durationMs: { $expression: 'delay' } }],
325
+ { delay: 1_000_001 },
326
+ );
327
+ expect(effects.filter((effect) => effect.type === EffectType.WAIT)).toEqual([]);
328
+ expect(state.status).toBe(RunStatus.FAILED);
329
+ expect(state.outcome?.error).toMatchObject({
330
+ code: RuntimeErrorCode.BUDGET_EXCEEDED,
331
+ stepId: 'w',
332
+ });
333
+ });
334
+
335
+ it('WAIT above MAX_WAIT_DURATION_MS fails even when the host budget is larger', async () => {
336
+ const { state } = await runToCompletion(
337
+ definitionOf([{ id: 'w', type: StepType.WAIT, durationMs: { $expression: 'delay' } }]),
338
+ null,
339
+ options({
340
+ budget: { maxSteps: 100, maxEffects: 100, maxWaitMs: MAX_WAIT_DURATION_MS * 2 },
341
+ }),
342
+ { evaluate: tableEvaluator({ delay: MAX_WAIT_DURATION_MS + 1 }) },
343
+ );
344
+ expect(state.status).toBe(RunStatus.FAILED);
345
+ expect(state.outcome?.error).toMatchObject({
346
+ code: RuntimeErrorCode.BUDGET_EXCEEDED,
347
+ stepId: 'w',
348
+ });
349
+ });
350
+
351
+ it('WAIT accepts a duration equal to the budget', async () => {
352
+ const { state } = await run(
353
+ [{ id: 'w', type: StepType.WAIT, durationMs: { $expression: 'delay' } }],
354
+ { delay: 1_000_000 },
355
+ );
356
+ expect(state.status).toBe(RunStatus.SUCCEEDED);
357
+ });
358
+
359
+ it('WAIT with a negative or fractional resolved duration fails with EXPRESSION_ERROR', async () => {
360
+ for (const delay of [-1, 1.5]) {
361
+ const { state } = await run(
362
+ [{ id: 'w', type: StepType.WAIT, durationMs: { $expression: 'delay' } }],
363
+ { delay },
364
+ );
365
+ expect(state.outcome?.error).toMatchObject({
366
+ code: RuntimeErrorCode.EXPRESSION_ERROR,
367
+ stepId: 'w',
368
+ });
369
+ }
370
+ });
371
+
372
+ it('SET is read back by a following step', async () => {
373
+ const { state, effects } = await run(
374
+ [
375
+ { id: 'set', type: StepType.SET, variable: 'total', value: { $expression: 'compute' } },
376
+ {
377
+ id: 'next',
378
+ type: StepType.SET,
379
+ variable: 'copy',
380
+ value: { $expression: 'vars.total + 1' },
381
+ },
382
+ ],
383
+ { compute: 41, 'vars.total + 1': 42 },
384
+ );
385
+ const second = effects[1] as { context: { vars: unknown } };
386
+ expect(second.context.vars).toEqual({ total: 41 });
387
+ expect(state.vars).toEqual({ total: 41, copy: 42 });
388
+ expect(outputOf(state, 'set')).toBe(41);
389
+ });
390
+
391
+ it('CODE outputs the value of its return', async () => {
392
+ const { state, effects } = await run(
393
+ [{ id: 'code', type: StepType.CODE, source: 'return 7' }],
394
+ {
395
+ 'return 7': 7,
396
+ },
397
+ );
398
+ expect(effects[0]).toMatchObject({
399
+ items: [{ id: 'source', kind: EvaluationKind.CODE, source: 'return 7' }],
400
+ });
401
+ expect(outputOf(state, 'code')).toBe(7);
402
+ });
403
+
404
+ it('HTTP outputs the response', async () => {
405
+ const response = { status: 201, headers: { a: 'b' }, body: { id: 1 } };
406
+ const { state } = await run(
407
+ [
408
+ {
409
+ id: 'h',
410
+ type: StepType.HTTP,
411
+ method: HttpMethod.GET,
412
+ url: 'https://api.example.com/x',
413
+ },
414
+ ],
415
+ {},
416
+ { http: () => response },
417
+ );
418
+ expect(outputOf(state, 'h')).toEqual(response);
419
+ });
420
+
421
+ it('HOST emits the validated input and outputs the action result', async () => {
422
+ const { state, effects } = await run(
423
+ [{ id: 'h', type: StepType.HOST, action: 'send', input: { to: '{{ who }}', count: 2 } }],
424
+ { '{{ who }}': 'ada' },
425
+ { host: () => ({ sent: true }) },
426
+ );
427
+ expect(effects[1]).toEqual({
428
+ type: EffectType.HOST,
429
+ stepId: 'h',
430
+ action: 'send',
431
+ input: { to: 'ada', count: 2 },
432
+ });
433
+ expect(outputOf(state, 'h')).toEqual({ sent: true });
434
+ });
435
+
436
+ it('STOP ends the run with its status and output, skipping what follows', async () => {
437
+ const succeeded = await run(
438
+ [
439
+ {
440
+ id: 'x',
441
+ type: StepType.STOP,
442
+ status: StopStatus.SUCCEEDED,
443
+ output: { $expression: 'result' },
444
+ },
445
+ markers('after'),
446
+ ],
447
+ { result: { done: true } },
448
+ );
449
+ expect(succeeded.state.status).toBe(RunStatus.SUCCEEDED);
450
+ expect(succeeded.state.outcome).toEqual({
451
+ status: StopStatus.SUCCEEDED,
452
+ output: { done: true },
453
+ });
454
+ expect(succeeded.state.vars).toEqual({});
455
+ const failed = await run([
456
+ { id: 'x', type: StepType.STOP, status: StopStatus.FAILED, output: 'nope' },
457
+ ]);
458
+ expect(failed.state.status).toBe(RunStatus.FAILED);
459
+ expect(failed.state.outcome).toEqual({ status: StopStatus.FAILED, output: 'nope' });
460
+ });
461
+
462
+ it('ends SUCCEEDED with an undefined output when the root sequence ends without STOP', async () => {
463
+ const { state } = await run([markers('only')]);
464
+ expect(state.status).toBe(RunStatus.SUCCEEDED);
465
+ expect(state.outcome).toEqual({ status: StopStatus.SUCCEEDED });
466
+ expect(state.outcome?.output).toBeUndefined();
467
+ });
468
+
469
+ it('runs a definition nested on three levels and comes back up in order', async () => {
470
+ const definition = definitionOf([
471
+ markers('first'),
472
+ {
473
+ id: 'outer',
474
+ type: StepType.CONDITION,
475
+ if: { $expression: 'yes' },
476
+ then: [
477
+ markers('level1'),
478
+ {
479
+ id: 'middle',
480
+ type: StepType.SWITCH,
481
+ value: { $expression: 'kind' },
482
+ cases: [
483
+ {
484
+ match: 'deep',
485
+ steps: [
486
+ {
487
+ id: 'inner',
488
+ type: StepType.CONDITION,
489
+ if: { $expression: 'no' },
490
+ then: [markers('wrong')],
491
+ else: [markers('level3a'), markers('level3b')],
492
+ },
493
+ markers('level2end'),
494
+ ],
495
+ },
496
+ ],
497
+ },
498
+ markers('level1end'),
499
+ ],
500
+ },
501
+ markers('last'),
502
+ ]);
503
+ const { state, effects } = await runToCompletion(definition, null, options(), {
504
+ evaluate: tableEvaluator({ yes: true, kind: 'deep', no: false }),
505
+ });
506
+ expect(Object.keys(state.vars)).toEqual([
507
+ 'first',
508
+ 'level1',
509
+ 'level3a',
510
+ 'level3b',
511
+ 'level2end',
512
+ 'level1end',
513
+ 'last',
514
+ ]);
515
+ expect(Object.keys(state.outputs)).toEqual([
516
+ 'first',
517
+ 'outer',
518
+ 'level1',
519
+ 'middle',
520
+ 'inner',
521
+ 'level3a',
522
+ 'level3b',
523
+ 'level2end',
524
+ 'level1end',
525
+ 'last',
526
+ ]);
527
+ expect(effects.map((effect) => effect.stepId)).toEqual(['outer', 'middle', 'inner']);
528
+ expect(state.status).toBe(RunStatus.SUCCEEDED);
529
+ });
530
+ });
531
+
532
+ describe('criterion 5: access', () => {
533
+ const httpTo = (url: string): Step => ({
534
+ id: 'h',
535
+ type: StepType.HTTP,
536
+ method: HttpMethod.GET,
537
+ url,
538
+ });
539
+ const hostSend = (input: Record<string, never | string | number>): Step => ({
540
+ id: 'h',
541
+ type: StepType.HOST,
542
+ action: 'send',
543
+ input,
544
+ });
545
+
546
+ it('lets a covered host through, exact or wildcard', () => {
547
+ expect(
548
+ start(definitionOf([httpTo('https://api.example.com/x')]), null, options()).effects,
549
+ ).toHaveLength(1);
550
+ expect(
551
+ start(definitionOf([httpTo('https://a.trusted.org/x')]), null, options()).effects,
552
+ ).toHaveLength(1);
553
+ });
554
+
555
+ it('denies an HTTP host that is declared but not granted, with no effect', () => {
556
+ const result = start(
557
+ definitionOf([httpTo('https://api.example.com/x')]),
558
+ null,
559
+ options({ grants: [{ kind: AccessKind.HTTP, hosts: ['other.com'] }] }),
560
+ );
561
+ expect(result.effects).toEqual([]);
562
+ expect(result.status).toBe(RunStatus.FAILED);
563
+ expect(result.state.outcome?.error).toMatchObject({
564
+ code: RuntimeErrorCode.ACCESS_DENIED,
565
+ stepId: 'h',
566
+ });
567
+ expect(result.state.pending).toBeNull();
568
+ });
569
+
570
+ it('denies an HTTP host that is granted but not declared', () => {
571
+ const result = start(
572
+ definitionOf([httpTo('https://api.example.com/x')], []),
573
+ null,
574
+ options(),
575
+ );
576
+ expect(result.effects).toEqual([]);
577
+ expect(result.state.outcome?.error?.code).toBe(RuntimeErrorCode.ACCESS_DENIED);
578
+ });
579
+
580
+ it('denies a bare apex for a wildcard pattern and an unparsable url', () => {
581
+ for (const url of ['https://trusted.org/x', 'not a url']) {
582
+ const result = start(definitionOf([httpTo(url)]), null, options());
583
+ expect(result.effects).toEqual([]);
584
+ expect(result.state.outcome?.error?.code).toBe(RuntimeErrorCode.ACCESS_DENIED);
585
+ }
586
+ });
587
+
588
+ it('denies any scheme other than http(s) even when the host is declared and granted', () => {
589
+ for (const url of [
590
+ 'file://api.example.com/etc/passwd',
591
+ 'ftp://api.example.com/x',
592
+ 'ws://api.example.com/x',
593
+ 'data:text/plain,hello',
594
+ 'javascript:alert(1)',
595
+ ]) {
596
+ const result = start(definitionOf([httpTo(url)]), null, options());
597
+ expect(result.effects).toEqual([]);
598
+ expect(result.status).toBe(RunStatus.FAILED);
599
+ expect(result.state.outcome?.error?.code).toBe(RuntimeErrorCode.ACCESS_DENIED);
600
+ }
601
+ });
602
+
603
+ it('still allows an http: url on a declared and granted host', () => {
604
+ const result = start(definitionOf([httpTo('http://api.example.com/x')]), null, options());
605
+ expect(result.effects).toHaveLength(1);
606
+ });
607
+
608
+ it('denies a HOST action not granted, or not declared, with no effect', () => {
609
+ const notGranted = start(
610
+ definitionOf([hostSend({ to: 'a' })]),
611
+ null,
612
+ options({ grants: [HTTP_ACCESS] }),
613
+ );
614
+ expect(notGranted.effects).toEqual([]);
615
+ expect(notGranted.state.outcome?.error).toMatchObject({
616
+ code: RuntimeErrorCode.ACCESS_DENIED,
617
+ stepId: 'h',
618
+ });
619
+ const notDeclared = start(
620
+ definitionOf([hostSend({ to: 'a' })], [HTTP_ACCESS]),
621
+ null,
622
+ options(),
623
+ );
624
+ expect(notDeclared.effects).toEqual([]);
625
+ expect(notDeclared.state.outcome?.error?.code).toBe(RuntimeErrorCode.ACCESS_DENIED);
626
+ });
627
+
628
+ it('fails with HOST_ERROR when the resolved input is outside the action schema', () => {
629
+ const result = start(definitionOf([hostSend({ count: 3 })]), null, options());
630
+ expect(result.effects).toEqual([]);
631
+ expect(result.status).toBe(RunStatus.FAILED);
632
+ expect(result.state.outcome?.error).toMatchObject({
633
+ code: RuntimeErrorCode.HOST_ERROR,
634
+ stepId: 'h',
635
+ });
636
+ });
637
+
638
+ it('fails with HOST_ERROR when the action is not in the catalog', () => {
639
+ const result = start(
640
+ definitionOf([{ id: 'h', type: StepType.HOST, action: 'send', input: { to: 'a' } }]),
641
+ null,
642
+ options({ catalog: new Map() }),
643
+ );
644
+ expect(result.state.outcome?.error?.code).toBe(RuntimeErrorCode.HOST_ERROR);
645
+ });
646
+
647
+ it('checks access on the resolved url, after evaluation', async () => {
648
+ const { state, effects } = await runToCompletion(
649
+ definitionOf([httpTo('{{ target }}')]),
650
+ null,
651
+ options(),
652
+ { evaluate: tableEvaluator({ '{{ target }}': 'https://evil.net/x' }) },
653
+ );
654
+ expect(effects).toHaveLength(1);
655
+ expect(state.outcome?.error).toMatchObject({
656
+ code: RuntimeErrorCode.ACCESS_DENIED,
657
+ stepId: 'h',
658
+ });
659
+ });
660
+ });
661
+
662
+ describe('criterion 6: failures and budget', () => {
663
+ it('fails the run when an evaluation item is in error', () => {
664
+ const first = start(
665
+ definitionOf([{ id: 's', type: StepType.SET, variable: 'v', value: '{{ broken }}' }]),
666
+ null,
667
+ options(),
668
+ );
669
+ const result = step(
670
+ definitionOf([{ id: 's', type: StepType.SET, variable: 'v', value: '{{ broken }}' }]),
671
+ first.state,
672
+ evaluated([
673
+ {
674
+ id: 'value',
675
+ ok: false,
676
+ error: { code: RuntimeErrorCode.TIMEOUT, message: 'too slow' },
677
+ },
678
+ ]),
679
+ options(),
680
+ );
681
+ expect(result.status).toBe(RunStatus.FAILED);
682
+ expect(result.effects).toEqual([]);
683
+ expect(result.state.outcome).toEqual({
684
+ status: StopStatus.FAILED,
685
+ error: { code: RuntimeErrorCode.TIMEOUT, message: 'too slow', stepId: 's' },
686
+ });
687
+ });
688
+
689
+ it('fails the run on EFFECT_FAILED with the code received', () => {
690
+ const definition = definitionOf([{ id: 'w', type: StepType.WAIT, durationMs: 1 }]);
691
+ const first = start(definition, null, options());
692
+ const result = step(
693
+ definition,
694
+ first.state,
695
+ {
696
+ type: RunEventType.EFFECT_FAILED,
697
+ error: { code: RuntimeErrorCode.HTTP_ERROR, message: 'down' },
698
+ },
699
+ options(),
700
+ );
701
+ expect(result.status).toBe(RunStatus.FAILED);
702
+ expect(result.state.outcome?.error).toEqual({
703
+ code: RuntimeErrorCode.HTTP_ERROR,
704
+ message: 'down',
705
+ stepId: 'w',
706
+ });
707
+ });
708
+
709
+ const manySets = (count: number): Step[] =>
710
+ Array.from({ length: count }, (_, index) => ({
711
+ id: `s${index}`,
712
+ type: StepType.SET as const,
713
+ variable: `v${index}`,
714
+ value: index,
715
+ }));
716
+
717
+ it('fails with BUDGET_EXCEEDED when the step budget is exceeded', () => {
718
+ const result = start(
719
+ definitionOf(manySets(3)),
720
+ null,
721
+ options({ budget: { maxSteps: 2, maxEffects: 10, maxWaitMs: 1_000_000 } }),
722
+ );
723
+ expect(result.status).toBe(RunStatus.FAILED);
724
+ expect(result.state.outcome?.error).toMatchObject({
725
+ code: RuntimeErrorCode.BUDGET_EXCEEDED,
726
+ stepId: 's2',
727
+ });
728
+ expect(result.state.counters.steps).toBe(2);
729
+ });
730
+
731
+ it('lets a run use exactly its step budget', () => {
732
+ const result = start(
733
+ definitionOf(manySets(2)),
734
+ null,
735
+ options({ budget: { maxSteps: 2, maxEffects: 10, maxWaitMs: 1_000_000 } }),
736
+ );
737
+ expect(result.status).toBe(RunStatus.SUCCEEDED);
738
+ expect(result.state.counters.steps).toBe(2);
739
+ });
740
+
741
+ it('fails with BUDGET_EXCEEDED when the effect budget is exceeded', async () => {
742
+ const waits: Step[] = [
743
+ { id: 'w1', type: StepType.WAIT, durationMs: 1 },
744
+ { id: 'w2', type: StepType.WAIT, durationMs: 1 },
745
+ ];
746
+ const { state, effects } = await runToCompletion(
747
+ definitionOf(waits),
748
+ null,
749
+ options({ budget: { maxSteps: 10, maxEffects: 1, maxWaitMs: 1_000_000 } }),
750
+ {
751
+ evaluate: tableEvaluator({}),
752
+ },
753
+ );
754
+ expect(effects).toHaveLength(1);
755
+ expect(state.counters.effects).toBe(1);
756
+ expect(state.outcome?.error).toMatchObject({
757
+ code: RuntimeErrorCode.BUDGET_EXCEEDED,
758
+ stepId: 'w2',
759
+ });
760
+ });
761
+
762
+ it('counts the evaluation lot as an effect', () => {
763
+ const result = start(
764
+ definitionOf([{ id: 's', type: StepType.SET, variable: 'v', value: '{{ x }}' }]),
765
+ null,
766
+ options({ budget: { maxSteps: 10, maxEffects: 0, maxWaitMs: 1_000_000 } }),
767
+ );
768
+ expect(result.state.outcome?.error?.code).toBe(RuntimeErrorCode.BUDGET_EXCEEDED);
769
+ });
770
+ });
771
+
772
+ describe('unexpected events', () => {
773
+ const definition = definitionOf([{ id: 'w', type: StepType.WAIT, durationMs: 1 }]);
774
+
775
+ const thrownBy = (action: () => unknown): InterpreterError => {
776
+ try {
777
+ action();
778
+ } catch (error) {
779
+ return error as InterpreterError;
780
+ }
781
+ throw new Error('expected an exception');
782
+ };
783
+
784
+ it('throws INVALID_REQUEST when the event does not answer the pending effect', () => {
785
+ const { state } = start(definition, null, options());
786
+ const error = thrownBy(() =>
787
+ step(
788
+ definition,
789
+ state,
790
+ { type: RunEventType.HTTP_COMPLETED, response: { status: 200, headers: {}, body: null } },
791
+ options(),
792
+ ),
793
+ );
794
+ expect(error).toBeInstanceOf(InterpreterError);
795
+ expect(error.code).toBe(RuntimeErrorCode.INVALID_REQUEST);
796
+ });
797
+
798
+ it('throws INVALID_REQUEST when evaluation results miss an item', () => {
799
+ const evalDefinition = definitionOf([
800
+ { id: 's', type: StepType.SET, variable: 'v', value: '{{ x }}' },
801
+ ]);
802
+ const { state } = start(evalDefinition, null, options());
803
+ expect(thrownBy(() => step(evalDefinition, state, evaluated([]), options())).code).toBe(
804
+ RuntimeErrorCode.INVALID_REQUEST,
805
+ );
806
+ });
807
+
808
+ it('throws INVALID_REQUEST once the run is over', () => {
809
+ const finished = start(definitionOf([]), null, options());
810
+ expect(finished.status).toBe(RunStatus.SUCCEEDED);
811
+ const error = thrownBy(() =>
812
+ step(definition, finished.state, { type: RunEventType.WAIT_ELAPSED }, options()),
813
+ );
814
+ expect(error.code).toBe(RuntimeErrorCode.INVALID_REQUEST);
815
+ });
816
+ });
817
+
818
+ describe('reserved names', () => {
819
+ const roundTrip = <T>(value: T): T => JSON.parse(JSON.stringify(value));
820
+
821
+ it('keeps __proto__ as a plain own key for step outputs and variables', () => {
822
+ const result = start(
823
+ definitionOf([
824
+ { id: '__proto__', type: StepType.SET, variable: '__proto__', value: 7 },
825
+ { id: 'constructor', type: StepType.SET, variable: 'constructor', value: 8 },
826
+ ]),
827
+ null,
828
+ options(),
829
+ );
830
+ const { outputs, vars } = result.state;
831
+ expect(Object.getPrototypeOf(outputs)).toBe(Object.prototype);
832
+ expect(Object.getPrototypeOf(vars)).toBe(Object.prototype);
833
+ expect(Object.keys(outputs)).toEqual(['__proto__', 'constructor']);
834
+ expect(Object.keys(vars)).toEqual(['__proto__', 'constructor']);
835
+ expect(Object.getOwnPropertyDescriptor(outputs, '__proto__')?.value).toEqual({ output: 7 });
836
+ expect(Object.getOwnPropertyDescriptor(vars, '__proto__')?.value).toBe(7);
837
+ expect(roundTrip(result.state)).toEqual(result.state);
838
+ });
839
+
840
+ it('loses nothing when a hand-built state with these keys crosses a JSON round trip and a step', () => {
841
+ const waitDefinition = definitionOf([{ id: 'w', type: StepType.WAIT, durationMs: 1 }]);
842
+ const restored = roundTrip(start(waitDefinition, null, options()).state);
843
+ restored.outputs = JSON.parse('{"__proto__":{"output":1},"prototype":{"output":2}}');
844
+ restored.vars = JSON.parse('{"__proto__":3,"constructor":4}');
845
+ const next = step(waitDefinition, restored, { type: RunEventType.WAIT_ELAPSED }, options());
846
+ expect(Object.keys(next.state.outputs).sort()).toEqual(['__proto__', 'prototype', 'w']);
847
+ expect(Object.getOwnPropertyDescriptor(next.state.outputs, '__proto__')?.value).toEqual({
848
+ output: 1,
849
+ });
850
+ expect(Object.getOwnPropertyDescriptor(next.state.vars, '__proto__')?.value).toBe(3);
851
+ expect(roundTrip(next.state)).toEqual(next.state);
852
+ });
853
+ });
854
+ });