@abyss-project/runtime 3.5.0 → 3.6.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 (57) hide show
  1. package/.eslintrc.js +32 -32
  2. package/.prettierrc +5 -5
  3. package/README.md +88 -88
  4. package/dist/engine/engine-source.js +1 -1
  5. package/dist/interpreter/interpreter.js +18 -4
  6. package/dist/interpreter/interpreter.js.map +1 -1
  7. package/dist/interpreter/interpreter.types.d.ts +2 -0
  8. package/dist/interpreter/interpreter.types.js.map +1 -1
  9. package/dist/runner-protocol/execution-protocol.types.d.ts +11 -0
  10. package/dist/runner-protocol/execution-protocol.types.js +2 -1
  11. package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
  12. package/jest.config.ts +11 -11
  13. package/package.json +15 -10
  14. package/scripts/build-engine.cjs +70 -70
  15. package/src/__tests__/engine-bundle.test.ts +121 -121
  16. package/src/__tests__/surface.test.ts +70 -66
  17. package/src/access/__tests__/host-match.test.ts +24 -24
  18. package/src/access/access.types.ts +25 -25
  19. package/src/access/host-match.ts +13 -13
  20. package/src/cost/__tests__/execution-cost.test.ts +196 -196
  21. package/src/cost/execution-cost.ts +186 -186
  22. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  23. package/src/definition/definition.limits.ts +9 -9
  24. package/src/definition/definition.schema.ts +172 -172
  25. package/src/definition/definition.types.ts +171 -171
  26. package/src/definition/validate-definition.ts +206 -206
  27. package/src/definition/walk-steps.ts +44 -44
  28. package/src/discord/__tests__/discord-event-input.test.ts +89 -89
  29. package/src/discord/discord.types.ts +639 -639
  30. package/src/engine/__tests__/run-in-isolate.test.ts +468 -468
  31. package/src/engine/engine-entry.ts +3 -3
  32. package/src/engine/engine-global.ts +2 -2
  33. package/src/engine/run-in-isolate.ts +404 -404
  34. package/src/errors/runtime-error-code.enum.ts +37 -37
  35. package/src/index.ts +32 -32
  36. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  37. package/src/interpreter/__tests__/log-respond-resume.test.ts +270 -223
  38. package/src/interpreter/interpreter-error.ts +12 -12
  39. package/src/interpreter/interpreter.ts +482 -461
  40. package/src/interpreter/interpreter.types.ts +202 -192
  41. package/src/interpreter/sequence-path.ts +67 -67
  42. package/src/interpreter/test-host.ts +85 -85
  43. package/src/runner-protocol/evaluation.types.ts +21 -21
  44. package/src/runner-protocol/execution-protocol.types.ts +254 -231
  45. package/src/schedule/schedule.types.ts +100 -100
  46. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  47. package/src/server/code-runner-error.ts +12 -12
  48. package/src/server/code-runner-session.ts +310 -310
  49. package/src/server/index.ts +11 -11
  50. package/src/steps/__tests__/global-references.test.ts +133 -133
  51. package/src/steps/execute-step.ts +186 -186
  52. package/src/steps/global-references.ts +48 -48
  53. package/src/steps/step-access.ts +56 -56
  54. package/src/steps/step-fields.ts +87 -87
  55. package/src/steps/value-source.ts +69 -69
  56. package/tsconfig.check.json +15 -15
  57. package/tsconfig.json +35 -35
@@ -1,468 +1,468 @@
1
- import { AccessKind } from '../../access/access.types';
2
- import {
3
- CURRENT_FORMAT_VERSION,
4
- HttpMethod,
5
- LogLevel,
6
- StepType,
7
- StopStatus,
8
- } from '../../definition/definition.types';
9
- import type { RuntimeDefinition } from '../../definition/definition.types';
10
- import { RuntimeErrorCode } from '../../errors/runtime-error-code.enum';
11
- import { CURRENT_STATE_VERSION, RunStatus } from '../../interpreter/interpreter.types';
12
- import type { RunState } from '../../interpreter/interpreter.types';
13
- import type { EvaluationItem, EvaluationResult } from '../../runner-protocol/evaluation.types';
14
- import {
15
- CoreCapability,
16
- ExecutionStatus,
17
- MAX_PROGRESS_OUTPUT_CHARS,
18
- StepPhase,
19
- StepStatus,
20
- } from '../../runner-protocol/execution-protocol.types';
21
- import type { ExecutionOutcome, JSONValue } from '../../runner-protocol/execution-protocol.types';
22
- import { EngineResultKind, runInIsolate } from '../run-in-isolate';
23
- import type {
24
- EngineHost,
25
- EngineProgress,
26
- EngineRequest,
27
- EngineResult,
28
- HostCallAnswer,
29
- } from '../run-in-isolate';
30
-
31
- const ALL_CAPABILITIES = [
32
- CoreCapability.HTTP_FETCH,
33
- CoreCapability.WAIT,
34
- CoreCapability.LOG_WRITE,
35
- CoreCapability.HTTP_RESPOND,
36
- 'store.set',
37
- ];
38
-
39
- const definition: RuntimeDefinition = {
40
- formatVersion: CURRENT_FORMAT_VERSION,
41
- accesses: [
42
- { kind: AccessKind.HTTP, hosts: ['api.example.com'] },
43
- { kind: AccessKind.HOST_ACTION, action: 'store.set' },
44
- ],
45
- steps: [
46
- { id: 'name', type: StepType.SET, variable: 'name', value: { $expression: 'input.name' } },
47
- { id: 'fetch', type: StepType.HTTP, method: HttpMethod.GET, url: 'https://api.example.com/x' },
48
- { id: 'save', type: StepType.HOST, action: 'store.set', input: { key: 'k', value: 1 } },
49
- { id: 'note', type: StepType.LOG, level: LogLevel.INFO, message: 'hello' },
50
- { id: 'reply', type: StepType.RESPOND, status: 200, body: 'ok' },
51
- { id: 'pause', type: StepType.WAIT, durationMs: 50 },
52
- { id: 'end', type: StepType.STOP, status: StopStatus.SUCCEEDED, output: { done: true } },
53
- ],
54
- };
55
-
56
- interface Call {
57
- stepId: string;
58
- capability: string;
59
- args: unknown;
60
- }
61
-
62
- interface FakeHost extends EngineHost {
63
- calls: Call[];
64
- progress: EngineProgress[];
65
- evaluations: EvaluationItem[][];
66
- globalsSeen: Array<Record<string, JSONValue> | undefined>;
67
- }
68
-
69
- const fakeHost = (
70
- answer: (call: Call) => HostCallAnswer = () => ({ ok: true, value: null }),
71
- values: Record<string, unknown> = { 'input.name': 'Ada' },
72
- ): FakeHost => {
73
- let clock = 1_000;
74
- const host: FakeHost = {
75
- calls: [],
76
- progress: [],
77
- evaluations: [],
78
- globalsSeen: [],
79
- evaluate: async (items, _context, _stepId, globals) => {
80
- host.evaluations.push(items);
81
- host.globalsSeen.push(globals);
82
- return items.map(
83
- (item): EvaluationResult =>
84
- item.source in values
85
- ? { id: item.id, ok: true, value: values[item.source] }
86
- : {
87
- id: item.id,
88
- ok: false,
89
- error: { code: RuntimeErrorCode.EXPRESSION_ERROR, message: 'unknown' },
90
- },
91
- );
92
- },
93
- callHost: async (stepId, capability, args) => {
94
- const call = { stepId, capability, args };
95
- host.calls.push(call);
96
- return answer(call);
97
- },
98
- onProgress: (progress) => host.progress.push(progress),
99
- now: () => (clock += 5),
100
- };
101
- return host;
102
- };
103
-
104
- const request = (overrides: Partial<EngineRequest> = {}): EngineRequest => ({
105
- definition,
106
- input: { name: 'Ada' },
107
- capabilities: ALL_CAPABILITIES,
108
- budget: { maxSteps: 50, maxEffects: 50 },
109
- ...overrides,
110
- });
111
-
112
- const outcomeOf = (result: EngineResult): ExecutionOutcome => {
113
- if (result.kind !== EngineResultKind.FINISHED) {
114
- throw new Error(`expected a finished execution, got ${result.kind}`);
115
- }
116
- return result.outcome;
117
- };
118
-
119
- const roundTrip = (state: RunState | undefined): RunState => JSON.parse(JSON.stringify(state));
120
-
121
- describe('runInIsolate', () => {
122
- it('runs every step, relaying each effect as a call of its capability', async () => {
123
- const host = fakeHost(({ capability }) =>
124
- capability === CoreCapability.HTTP_FETCH
125
- ? { ok: true, value: { status: 200, headers: {}, body: 'x' } }
126
- : { ok: true, value: null },
127
- );
128
- const outcome = outcomeOf(await runInIsolate(request(), host));
129
- expect(outcome).toEqual({ status: ExecutionStatus.SUCCEEDED, output: { done: true } });
130
- expect(host.calls).toEqual([
131
- {
132
- stepId: 'fetch',
133
- capability: CoreCapability.HTTP_FETCH,
134
- args: { method: HttpMethod.GET, url: 'https://api.example.com/x', headers: {} },
135
- },
136
- { stepId: 'save', capability: 'store.set', args: { key: 'k', value: 1 } },
137
- {
138
- stepId: 'note',
139
- capability: CoreCapability.LOG_WRITE,
140
- args: { level: LogLevel.INFO, message: 'hello' },
141
- },
142
- {
143
- stepId: 'reply',
144
- capability: CoreCapability.HTTP_RESPOND,
145
- args: { status: 200, headers: {}, body: 'ok' },
146
- },
147
- { stepId: 'pause', capability: CoreCapability.WAIT, args: { durationMs: 50 } },
148
- ]);
149
- });
150
-
151
- it('passes the request globals to every evaluation, and nothing when there are none', async () => {
152
- const globals = { secrets: { API_KEY: 'k' } };
153
- const withGlobals = fakeHost();
154
- await runInIsolate(request({ globals }), withGlobals);
155
- expect(withGlobals.globalsSeen).toEqual([globals]);
156
- const without = fakeHost();
157
- await runInIsolate(request(), without);
158
- expect(without.globalsSeen).toEqual([undefined]);
159
- });
160
-
161
- it('reports the start and the end of each step, with its duration and output', async () => {
162
- const host = fakeHost();
163
- await runInIsolate(request(), host);
164
- const ids = definition.steps.map((step) => step.id);
165
- expect(host.progress.map((p) => `${p.stepId}:${p.phase}`)).toEqual(
166
- ids.flatMap((id) => [`${id}:${StepPhase.STARTED}`, `${id}:${StepPhase.FINISHED}`]),
167
- );
168
- const finishedName = host.progress.find(
169
- (p) => p.stepId === 'name' && p.phase === StepPhase.FINISHED,
170
- );
171
- expect(finishedName).toEqual({
172
- stepId: 'name',
173
- phase: StepPhase.FINISHED,
174
- status: StepStatus.SUCCEEDED,
175
- durationMs: expect.any(Number),
176
- output: 'Ada',
177
- });
178
- expect(finishedName?.durationMs).toBeGreaterThan(0);
179
- });
180
-
181
- it('truncates a large output in the progress, never in the run', async () => {
182
- const big = 'x'.repeat(MAX_PROGRESS_OUTPUT_CHARS * 2);
183
- const host = fakeHost(undefined, { 'input.name': big });
184
- const outcome = outcomeOf(
185
- await runInIsolate(
186
- request({ definition: { ...definition, steps: [definition.steps[0]] } }),
187
- host,
188
- ),
189
- );
190
- expect(outcome.status).toBe(ExecutionStatus.SUCCEEDED);
191
- const finished = host.progress.find((p) => p.phase === StepPhase.FINISHED);
192
- expect(finished?.outputTruncated).toBe(true);
193
- expect((finished?.output as string).length).toBe(MAX_PROGRESS_OUTPUT_CHARS);
194
- });
195
-
196
- it('refuses a capability the host did not expose, without calling it', async () => {
197
- const host = fakeHost();
198
- const outcome = outcomeOf(
199
- await runInIsolate(
200
- request({ capabilities: ALL_CAPABILITIES.filter((c) => c !== CoreCapability.LOG_WRITE) }),
201
- host,
202
- ),
203
- );
204
- expect(outcome).toEqual({
205
- status: ExecutionStatus.FAILED,
206
- errorCode: RuntimeErrorCode.ACCESS_DENIED,
207
- errorMessage: expect.stringContaining('log.write'),
208
- stepId: 'note',
209
- });
210
- expect(host.calls.map((c) => c.capability)).not.toContain(CoreCapability.LOG_WRITE);
211
- expect(host.progress).toContainEqual({
212
- stepId: 'note',
213
- phase: StepPhase.FINISHED,
214
- status: StepStatus.FAILED,
215
- durationMs: expect.any(Number),
216
- errorCode: RuntimeErrorCode.ACCESS_DENIED,
217
- });
218
- });
219
-
220
- it('refuses a host action that is declared but not exposed, and one not declared', async () => {
221
- const notExposed = outcomeOf(
222
- await runInIsolate(
223
- request({ capabilities: ALL_CAPABILITIES.filter((c) => c !== 'store.set') }),
224
- fakeHost(),
225
- ),
226
- );
227
- expect(notExposed).toEqual(
228
- expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'save' }),
229
- );
230
- const undeclared = outcomeOf(
231
- await runInIsolate(
232
- request({
233
- definition: {
234
- ...definition,
235
- accesses: definition.accesses.filter((a) => a.kind === AccessKind.HTTP),
236
- },
237
- }),
238
- fakeHost(),
239
- ),
240
- );
241
- expect(undeclared).toEqual(
242
- expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'save' }),
243
- );
244
- });
245
-
246
- it('refuses an HTTP step when http.fetch is not exposed', async () => {
247
- const host = fakeHost();
248
- const outcome = outcomeOf(
249
- await runInIsolate(
250
- request({ capabilities: ALL_CAPABILITIES.filter((c) => c !== CoreCapability.HTTP_FETCH) }),
251
- host,
252
- ),
253
- );
254
- expect(outcome).toEqual(
255
- expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'fetch' }),
256
- );
257
- expect(host.calls).toEqual([]);
258
- });
259
-
260
- it('fails the step with the code the host gives, or the capability default', async () => {
261
- const coded = outcomeOf(
262
- await runInIsolate(
263
- request(),
264
- fakeHost(({ capability }) =>
265
- capability === 'store.set'
266
- ? { ok: false, error: { code: RuntimeErrorCode.ACCESS_DENIED, message: 'no' } }
267
- : { ok: true, value: null },
268
- ),
269
- ),
270
- );
271
- expect(coded).toEqual(
272
- expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'save' }),
273
- );
274
- const uncoded = outcomeOf(
275
- await runInIsolate(
276
- request(),
277
- fakeHost(() => ({ ok: false, error: { message: 'network down' } })),
278
- ),
279
- );
280
- expect(uncoded).toEqual({
281
- status: ExecutionStatus.FAILED,
282
- errorCode: RuntimeErrorCode.HTTP_ERROR,
283
- errorMessage: 'network down',
284
- stepId: 'fetch',
285
- });
286
- });
287
-
288
- it('reports a STOP that chose FAILED with its output and no error code', async () => {
289
- const outcome = outcomeOf(
290
- await runInIsolate(
291
- request({
292
- definition: {
293
- ...definition,
294
- steps: [{ id: 'stop', type: StepType.STOP, status: StopStatus.FAILED, output: 'no' }],
295
- },
296
- }),
297
- fakeHost(),
298
- ),
299
- );
300
- expect(outcome).toEqual({ status: ExecutionStatus.FAILED, output: 'no' });
301
- });
302
-
303
- it('fails with INVALID_REQUEST when the evaluation does not cover the step', async () => {
304
- const host = fakeHost();
305
- host.evaluate = async () => [];
306
- const outcome = outcomeOf(await runInIsolate(request(), host));
307
- expect(outcome).toEqual(
308
- expect.objectContaining({
309
- status: ExecutionStatus.FAILED,
310
- errorCode: RuntimeErrorCode.INVALID_REQUEST,
311
- }),
312
- );
313
- });
314
-
315
- describe('suspension', () => {
316
- const longWait: RuntimeDefinition = {
317
- ...definition,
318
- steps: [
319
- { id: 'pause', type: StepType.WAIT, durationMs: 60_000 },
320
- { id: 'after', type: StepType.SET, variable: 'v', value: { $expression: 'input.name' } },
321
- { id: 'end', type: StepType.STOP, status: StopStatus.SUCCEEDED, output: 'finished' },
322
- ],
323
- };
324
-
325
- it('suspends on a WAIT above the threshold without calling wait, then resumes', async () => {
326
- const host = fakeHost();
327
- const first = outcomeOf(
328
- await runInIsolate(request({ definition: longWait, suspendWaitAboveMs: 1_000 }), host),
329
- );
330
- expect(first.status).toBe(ExecutionStatus.SUSPENDED);
331
- expect(first.state?.stateVersion).toBe(CURRENT_STATE_VERSION);
332
- expect(host.calls).toEqual([]);
333
- expect(host.progress[host.progress.length - 1]).toEqual({
334
- stepId: 'pause',
335
- phase: StepPhase.FINISHED,
336
- status: StepStatus.SUSPENDED,
337
- durationMs: expect.any(Number),
338
- });
339
-
340
- const resumedHost = fakeHost();
341
- const resumed = outcomeOf(
342
- await runInIsolate(
343
- request({
344
- definition: longWait,
345
- state: roundTrip(first.state),
346
- suspendWaitAboveMs: 1_000,
347
- }),
348
- resumedHost,
349
- ),
350
- );
351
- expect(resumed).toEqual({ status: ExecutionStatus.SUCCEEDED, output: 'finished' });
352
- expect(resumedHost.progress.slice(0, 2)).toEqual([
353
- { stepId: 'pause', phase: StepPhase.STARTED },
354
- expect.objectContaining({ stepId: 'pause', status: StepStatus.SUCCEEDED, output: null }),
355
- ]);
356
-
357
- // Same outcome as a run in one go, where the host serves the wait.
358
- const inOneGo = outcomeOf(await runInIsolate(request({ definition: longWait }), fakeHost()));
359
- expect(inOneGo).toEqual(resumed);
360
- });
361
-
362
- it('suspends on a WAIT until a date further than the threshold', async () => {
363
- const host = fakeHost();
364
- const farUntil = new Date(Date.now() + 3_600_000).toISOString();
365
- const outcome = outcomeOf(
366
- await runInIsolate(
367
- request({
368
- definition: {
369
- ...definition,
370
- steps: [{ id: 'later', type: StepType.WAIT, until: farUntil }],
371
- },
372
- suspendWaitAboveMs: 1_000,
373
- }),
374
- { ...host, now: () => Date.now() },
375
- ),
376
- );
377
- expect(outcome.status).toBe(ExecutionStatus.SUSPENDED);
378
- });
379
-
380
- it('suspends when the host answers suspend, and gives resumeInput to that step', async () => {
381
- const approval: RuntimeDefinition = {
382
- ...definition,
383
- steps: [
384
- { id: 'save', type: StepType.HOST, action: 'store.set', input: { key: 'k' } },
385
- {
386
- id: 'end',
387
- type: StepType.STOP,
388
- status: StopStatus.SUCCEEDED,
389
- output: { $expression: 'steps.save.output' },
390
- },
391
- ],
392
- };
393
- const first = outcomeOf(
394
- await runInIsolate(
395
- request({ definition: approval }),
396
- fakeHost(() => ({ ok: true, suspend: true })),
397
- ),
398
- );
399
- expect(first.status).toBe(ExecutionStatus.SUSPENDED);
400
-
401
- const resumedHost = fakeHost();
402
- resumedHost.evaluate = async (items, context) =>
403
- items.map((item) => ({ id: item.id, ok: true, value: context.steps.save.output }));
404
- const resumed = outcomeOf(
405
- await runInIsolate(
406
- request({
407
- definition: approval,
408
- state: roundTrip(first.state),
409
- resumeInput: { approved: true },
410
- }),
411
- resumedHost,
412
- ),
413
- );
414
- expect(resumed).toEqual({ status: ExecutionStatus.SUCCEEDED, output: { approved: true } });
415
- expect(resumedHost.calls).toEqual([]);
416
- });
417
-
418
- it('refuses a state of an unknown version before running anything', async () => {
419
- const host = fakeHost();
420
- const first = outcomeOf(
421
- await runInIsolate(
422
- request({ definition: longWait, suspendWaitAboveMs: 1_000 }),
423
- fakeHost(),
424
- ),
425
- );
426
- const result = await runInIsolate(
427
- request({
428
- definition: longWait,
429
- state: { ...roundTrip(first.state), stateVersion: CURRENT_STATE_VERSION + 1 },
430
- }),
431
- host,
432
- );
433
- expect(result).toEqual({
434
- kind: EngineResultKind.REJECTED,
435
- code: RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
436
- message: expect.any(String),
437
- });
438
- expect(host.progress).toEqual([]);
439
- expect(host.calls).toEqual([]);
440
- });
441
-
442
- it('refuses to resume a state that is not suspended', async () => {
443
- const done = outcomeOf(await runInIsolate(request({ definition: longWait }), fakeHost()));
444
- expect(done.status).toBe(ExecutionStatus.SUCCEEDED);
445
- const ended: RunState = {
446
- stateVersion: CURRENT_STATE_VERSION,
447
- formatVersion: CURRENT_FORMAT_VERSION,
448
- status: RunStatus.SUCCEEDED,
449
- input: null,
450
- stack: [],
451
- outputs: {},
452
- vars: {},
453
- pending: null,
454
- counters: { steps: 1, effects: 0 },
455
- };
456
- const result = await runInIsolate(
457
- request({ definition: longWait, state: ended }),
458
- fakeHost(),
459
- );
460
- expect(result).toEqual(
461
- expect.objectContaining({
462
- kind: EngineResultKind.REJECTED,
463
- code: RuntimeErrorCode.INVALID_REQUEST,
464
- }),
465
- );
466
- });
467
- });
468
- });
1
+ import { AccessKind } from '../../access/access.types';
2
+ import {
3
+ CURRENT_FORMAT_VERSION,
4
+ HttpMethod,
5
+ LogLevel,
6
+ StepType,
7
+ StopStatus,
8
+ } from '../../definition/definition.types';
9
+ import type { RuntimeDefinition } from '../../definition/definition.types';
10
+ import { RuntimeErrorCode } from '../../errors/runtime-error-code.enum';
11
+ import { CURRENT_STATE_VERSION, RunStatus } from '../../interpreter/interpreter.types';
12
+ import type { RunState } from '../../interpreter/interpreter.types';
13
+ import type { EvaluationItem, EvaluationResult } from '../../runner-protocol/evaluation.types';
14
+ import {
15
+ CoreCapability,
16
+ ExecutionStatus,
17
+ MAX_PROGRESS_OUTPUT_CHARS,
18
+ StepPhase,
19
+ StepStatus,
20
+ } from '../../runner-protocol/execution-protocol.types';
21
+ import type { ExecutionOutcome, JSONValue } from '../../runner-protocol/execution-protocol.types';
22
+ import { EngineResultKind, runInIsolate } from '../run-in-isolate';
23
+ import type {
24
+ EngineHost,
25
+ EngineProgress,
26
+ EngineRequest,
27
+ EngineResult,
28
+ HostCallAnswer,
29
+ } from '../run-in-isolate';
30
+
31
+ const ALL_CAPABILITIES = [
32
+ CoreCapability.HTTP_FETCH,
33
+ CoreCapability.WAIT,
34
+ CoreCapability.LOG_WRITE,
35
+ CoreCapability.HTTP_RESPOND,
36
+ 'store.set',
37
+ ];
38
+
39
+ const definition: RuntimeDefinition = {
40
+ formatVersion: CURRENT_FORMAT_VERSION,
41
+ accesses: [
42
+ { kind: AccessKind.HTTP, hosts: ['api.example.com'] },
43
+ { kind: AccessKind.HOST_ACTION, action: 'store.set' },
44
+ ],
45
+ steps: [
46
+ { id: 'name', type: StepType.SET, variable: 'name', value: { $expression: 'input.name' } },
47
+ { id: 'fetch', type: StepType.HTTP, method: HttpMethod.GET, url: 'https://api.example.com/x' },
48
+ { id: 'save', type: StepType.HOST, action: 'store.set', input: { key: 'k', value: 1 } },
49
+ { id: 'note', type: StepType.LOG, level: LogLevel.INFO, message: 'hello' },
50
+ { id: 'reply', type: StepType.RESPOND, status: 200, body: 'ok' },
51
+ { id: 'pause', type: StepType.WAIT, durationMs: 50 },
52
+ { id: 'end', type: StepType.STOP, status: StopStatus.SUCCEEDED, output: { done: true } },
53
+ ],
54
+ };
55
+
56
+ interface Call {
57
+ stepId: string;
58
+ capability: string;
59
+ args: unknown;
60
+ }
61
+
62
+ interface FakeHost extends EngineHost {
63
+ calls: Call[];
64
+ progress: EngineProgress[];
65
+ evaluations: EvaluationItem[][];
66
+ globalsSeen: Array<Record<string, JSONValue> | undefined>;
67
+ }
68
+
69
+ const fakeHost = (
70
+ answer: (call: Call) => HostCallAnswer = () => ({ ok: true, value: null }),
71
+ values: Record<string, unknown> = { 'input.name': 'Ada' },
72
+ ): FakeHost => {
73
+ let clock = 1_000;
74
+ const host: FakeHost = {
75
+ calls: [],
76
+ progress: [],
77
+ evaluations: [],
78
+ globalsSeen: [],
79
+ evaluate: async (items, _context, _stepId, globals) => {
80
+ host.evaluations.push(items);
81
+ host.globalsSeen.push(globals);
82
+ return items.map(
83
+ (item): EvaluationResult =>
84
+ item.source in values
85
+ ? { id: item.id, ok: true, value: values[item.source] }
86
+ : {
87
+ id: item.id,
88
+ ok: false,
89
+ error: { code: RuntimeErrorCode.EXPRESSION_ERROR, message: 'unknown' },
90
+ },
91
+ );
92
+ },
93
+ callHost: async (stepId, capability, args) => {
94
+ const call = { stepId, capability, args };
95
+ host.calls.push(call);
96
+ return answer(call);
97
+ },
98
+ onProgress: (progress) => host.progress.push(progress),
99
+ now: () => (clock += 5),
100
+ };
101
+ return host;
102
+ };
103
+
104
+ const request = (overrides: Partial<EngineRequest> = {}): EngineRequest => ({
105
+ definition,
106
+ input: { name: 'Ada' },
107
+ capabilities: ALL_CAPABILITIES,
108
+ budget: { maxSteps: 50, maxEffects: 50 },
109
+ ...overrides,
110
+ });
111
+
112
+ const outcomeOf = (result: EngineResult): ExecutionOutcome => {
113
+ if (result.kind !== EngineResultKind.FINISHED) {
114
+ throw new Error(`expected a finished execution, got ${result.kind}`);
115
+ }
116
+ return result.outcome;
117
+ };
118
+
119
+ const roundTrip = (state: RunState | undefined): RunState => JSON.parse(JSON.stringify(state));
120
+
121
+ describe('runInIsolate', () => {
122
+ it('runs every step, relaying each effect as a call of its capability', async () => {
123
+ const host = fakeHost(({ capability }) =>
124
+ capability === CoreCapability.HTTP_FETCH
125
+ ? { ok: true, value: { status: 200, headers: {}, body: 'x' } }
126
+ : { ok: true, value: null },
127
+ );
128
+ const outcome = outcomeOf(await runInIsolate(request(), host));
129
+ expect(outcome).toEqual({ status: ExecutionStatus.SUCCEEDED, output: { done: true } });
130
+ expect(host.calls).toEqual([
131
+ {
132
+ stepId: 'fetch',
133
+ capability: CoreCapability.HTTP_FETCH,
134
+ args: { method: HttpMethod.GET, url: 'https://api.example.com/x', headers: {} },
135
+ },
136
+ { stepId: 'save', capability: 'store.set', args: { key: 'k', value: 1 } },
137
+ {
138
+ stepId: 'note',
139
+ capability: CoreCapability.LOG_WRITE,
140
+ args: { level: LogLevel.INFO, message: 'hello' },
141
+ },
142
+ {
143
+ stepId: 'reply',
144
+ capability: CoreCapability.HTTP_RESPOND,
145
+ args: { status: 200, headers: {}, body: 'ok' },
146
+ },
147
+ { stepId: 'pause', capability: CoreCapability.WAIT, args: { durationMs: 50 } },
148
+ ]);
149
+ });
150
+
151
+ it('passes the request globals to every evaluation, and nothing when there are none', async () => {
152
+ const globals = { secrets: { API_KEY: 'k' } };
153
+ const withGlobals = fakeHost();
154
+ await runInIsolate(request({ globals }), withGlobals);
155
+ expect(withGlobals.globalsSeen).toEqual([globals]);
156
+ const without = fakeHost();
157
+ await runInIsolate(request(), without);
158
+ expect(without.globalsSeen).toEqual([undefined]);
159
+ });
160
+
161
+ it('reports the start and the end of each step, with its duration and output', async () => {
162
+ const host = fakeHost();
163
+ await runInIsolate(request(), host);
164
+ const ids = definition.steps.map((step) => step.id);
165
+ expect(host.progress.map((p) => `${p.stepId}:${p.phase}`)).toEqual(
166
+ ids.flatMap((id) => [`${id}:${StepPhase.STARTED}`, `${id}:${StepPhase.FINISHED}`]),
167
+ );
168
+ const finishedName = host.progress.find(
169
+ (p) => p.stepId === 'name' && p.phase === StepPhase.FINISHED,
170
+ );
171
+ expect(finishedName).toEqual({
172
+ stepId: 'name',
173
+ phase: StepPhase.FINISHED,
174
+ status: StepStatus.SUCCEEDED,
175
+ durationMs: expect.any(Number),
176
+ output: 'Ada',
177
+ });
178
+ expect(finishedName?.durationMs).toBeGreaterThan(0);
179
+ });
180
+
181
+ it('truncates a large output in the progress, never in the run', async () => {
182
+ const big = 'x'.repeat(MAX_PROGRESS_OUTPUT_CHARS * 2);
183
+ const host = fakeHost(undefined, { 'input.name': big });
184
+ const outcome = outcomeOf(
185
+ await runInIsolate(
186
+ request({ definition: { ...definition, steps: [definition.steps[0]] } }),
187
+ host,
188
+ ),
189
+ );
190
+ expect(outcome.status).toBe(ExecutionStatus.SUCCEEDED);
191
+ const finished = host.progress.find((p) => p.phase === StepPhase.FINISHED);
192
+ expect(finished?.outputTruncated).toBe(true);
193
+ expect((finished?.output as string).length).toBe(MAX_PROGRESS_OUTPUT_CHARS);
194
+ });
195
+
196
+ it('refuses a capability the host did not expose, without calling it', async () => {
197
+ const host = fakeHost();
198
+ const outcome = outcomeOf(
199
+ await runInIsolate(
200
+ request({ capabilities: ALL_CAPABILITIES.filter((c) => c !== CoreCapability.LOG_WRITE) }),
201
+ host,
202
+ ),
203
+ );
204
+ expect(outcome).toEqual({
205
+ status: ExecutionStatus.FAILED,
206
+ errorCode: RuntimeErrorCode.ACCESS_DENIED,
207
+ errorMessage: expect.stringContaining('log.write'),
208
+ stepId: 'note',
209
+ });
210
+ expect(host.calls.map((c) => c.capability)).not.toContain(CoreCapability.LOG_WRITE);
211
+ expect(host.progress).toContainEqual({
212
+ stepId: 'note',
213
+ phase: StepPhase.FINISHED,
214
+ status: StepStatus.FAILED,
215
+ durationMs: expect.any(Number),
216
+ errorCode: RuntimeErrorCode.ACCESS_DENIED,
217
+ });
218
+ });
219
+
220
+ it('refuses a host action that is declared but not exposed, and one not declared', async () => {
221
+ const notExposed = outcomeOf(
222
+ await runInIsolate(
223
+ request({ capabilities: ALL_CAPABILITIES.filter((c) => c !== 'store.set') }),
224
+ fakeHost(),
225
+ ),
226
+ );
227
+ expect(notExposed).toEqual(
228
+ expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'save' }),
229
+ );
230
+ const undeclared = outcomeOf(
231
+ await runInIsolate(
232
+ request({
233
+ definition: {
234
+ ...definition,
235
+ accesses: definition.accesses.filter((a) => a.kind === AccessKind.HTTP),
236
+ },
237
+ }),
238
+ fakeHost(),
239
+ ),
240
+ );
241
+ expect(undeclared).toEqual(
242
+ expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'save' }),
243
+ );
244
+ });
245
+
246
+ it('refuses an HTTP step when http.fetch is not exposed', async () => {
247
+ const host = fakeHost();
248
+ const outcome = outcomeOf(
249
+ await runInIsolate(
250
+ request({ capabilities: ALL_CAPABILITIES.filter((c) => c !== CoreCapability.HTTP_FETCH) }),
251
+ host,
252
+ ),
253
+ );
254
+ expect(outcome).toEqual(
255
+ expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'fetch' }),
256
+ );
257
+ expect(host.calls).toEqual([]);
258
+ });
259
+
260
+ it('fails the step with the code the host gives, or the capability default', async () => {
261
+ const coded = outcomeOf(
262
+ await runInIsolate(
263
+ request(),
264
+ fakeHost(({ capability }) =>
265
+ capability === 'store.set'
266
+ ? { ok: false, error: { code: RuntimeErrorCode.ACCESS_DENIED, message: 'no' } }
267
+ : { ok: true, value: null },
268
+ ),
269
+ ),
270
+ );
271
+ expect(coded).toEqual(
272
+ expect.objectContaining({ errorCode: RuntimeErrorCode.ACCESS_DENIED, stepId: 'save' }),
273
+ );
274
+ const uncoded = outcomeOf(
275
+ await runInIsolate(
276
+ request(),
277
+ fakeHost(() => ({ ok: false, error: { message: 'network down' } })),
278
+ ),
279
+ );
280
+ expect(uncoded).toEqual({
281
+ status: ExecutionStatus.FAILED,
282
+ errorCode: RuntimeErrorCode.HTTP_ERROR,
283
+ errorMessage: 'network down',
284
+ stepId: 'fetch',
285
+ });
286
+ });
287
+
288
+ it('reports a STOP that chose FAILED with its output and no error code', async () => {
289
+ const outcome = outcomeOf(
290
+ await runInIsolate(
291
+ request({
292
+ definition: {
293
+ ...definition,
294
+ steps: [{ id: 'stop', type: StepType.STOP, status: StopStatus.FAILED, output: 'no' }],
295
+ },
296
+ }),
297
+ fakeHost(),
298
+ ),
299
+ );
300
+ expect(outcome).toEqual({ status: ExecutionStatus.FAILED, output: 'no' });
301
+ });
302
+
303
+ it('fails with INVALID_REQUEST when the evaluation does not cover the step', async () => {
304
+ const host = fakeHost();
305
+ host.evaluate = async () => [];
306
+ const outcome = outcomeOf(await runInIsolate(request(), host));
307
+ expect(outcome).toEqual(
308
+ expect.objectContaining({
309
+ status: ExecutionStatus.FAILED,
310
+ errorCode: RuntimeErrorCode.INVALID_REQUEST,
311
+ }),
312
+ );
313
+ });
314
+
315
+ describe('suspension', () => {
316
+ const longWait: RuntimeDefinition = {
317
+ ...definition,
318
+ steps: [
319
+ { id: 'pause', type: StepType.WAIT, durationMs: 60_000 },
320
+ { id: 'after', type: StepType.SET, variable: 'v', value: { $expression: 'input.name' } },
321
+ { id: 'end', type: StepType.STOP, status: StopStatus.SUCCEEDED, output: 'finished' },
322
+ ],
323
+ };
324
+
325
+ it('suspends on a WAIT above the threshold without calling wait, then resumes', async () => {
326
+ const host = fakeHost();
327
+ const first = outcomeOf(
328
+ await runInIsolate(request({ definition: longWait, suspendWaitAboveMs: 1_000 }), host),
329
+ );
330
+ expect(first.status).toBe(ExecutionStatus.SUSPENDED);
331
+ expect(first.state?.stateVersion).toBe(CURRENT_STATE_VERSION);
332
+ expect(host.calls).toEqual([]);
333
+ expect(host.progress[host.progress.length - 1]).toEqual({
334
+ stepId: 'pause',
335
+ phase: StepPhase.FINISHED,
336
+ status: StepStatus.SUSPENDED,
337
+ durationMs: expect.any(Number),
338
+ });
339
+
340
+ const resumedHost = fakeHost();
341
+ const resumed = outcomeOf(
342
+ await runInIsolate(
343
+ request({
344
+ definition: longWait,
345
+ state: roundTrip(first.state),
346
+ suspendWaitAboveMs: 1_000,
347
+ }),
348
+ resumedHost,
349
+ ),
350
+ );
351
+ expect(resumed).toEqual({ status: ExecutionStatus.SUCCEEDED, output: 'finished' });
352
+ expect(resumedHost.progress.slice(0, 2)).toEqual([
353
+ { stepId: 'pause', phase: StepPhase.STARTED },
354
+ expect.objectContaining({ stepId: 'pause', status: StepStatus.SUCCEEDED, output: null }),
355
+ ]);
356
+
357
+ // Same outcome as a run in one go, where the host serves the wait.
358
+ const inOneGo = outcomeOf(await runInIsolate(request({ definition: longWait }), fakeHost()));
359
+ expect(inOneGo).toEqual(resumed);
360
+ });
361
+
362
+ it('suspends on a WAIT until a date further than the threshold', async () => {
363
+ const host = fakeHost();
364
+ const farUntil = new Date(Date.now() + 3_600_000).toISOString();
365
+ const outcome = outcomeOf(
366
+ await runInIsolate(
367
+ request({
368
+ definition: {
369
+ ...definition,
370
+ steps: [{ id: 'later', type: StepType.WAIT, until: farUntil }],
371
+ },
372
+ suspendWaitAboveMs: 1_000,
373
+ }),
374
+ { ...host, now: () => Date.now() },
375
+ ),
376
+ );
377
+ expect(outcome.status).toBe(ExecutionStatus.SUSPENDED);
378
+ });
379
+
380
+ it('suspends when the host answers suspend, and gives resumeInput to that step', async () => {
381
+ const approval: RuntimeDefinition = {
382
+ ...definition,
383
+ steps: [
384
+ { id: 'save', type: StepType.HOST, action: 'store.set', input: { key: 'k' } },
385
+ {
386
+ id: 'end',
387
+ type: StepType.STOP,
388
+ status: StopStatus.SUCCEEDED,
389
+ output: { $expression: 'steps.save.output' },
390
+ },
391
+ ],
392
+ };
393
+ const first = outcomeOf(
394
+ await runInIsolate(
395
+ request({ definition: approval }),
396
+ fakeHost(() => ({ ok: true, suspend: true })),
397
+ ),
398
+ );
399
+ expect(first.status).toBe(ExecutionStatus.SUSPENDED);
400
+
401
+ const resumedHost = fakeHost();
402
+ resumedHost.evaluate = async (items, context) =>
403
+ items.map((item) => ({ id: item.id, ok: true, value: context.steps.save.output }));
404
+ const resumed = outcomeOf(
405
+ await runInIsolate(
406
+ request({
407
+ definition: approval,
408
+ state: roundTrip(first.state),
409
+ resumeInput: { approved: true },
410
+ }),
411
+ resumedHost,
412
+ ),
413
+ );
414
+ expect(resumed).toEqual({ status: ExecutionStatus.SUCCEEDED, output: { approved: true } });
415
+ expect(resumedHost.calls).toEqual([]);
416
+ });
417
+
418
+ it('refuses a state of an unknown version before running anything', async () => {
419
+ const host = fakeHost();
420
+ const first = outcomeOf(
421
+ await runInIsolate(
422
+ request({ definition: longWait, suspendWaitAboveMs: 1_000 }),
423
+ fakeHost(),
424
+ ),
425
+ );
426
+ const result = await runInIsolate(
427
+ request({
428
+ definition: longWait,
429
+ state: { ...roundTrip(first.state), stateVersion: CURRENT_STATE_VERSION + 1 },
430
+ }),
431
+ host,
432
+ );
433
+ expect(result).toEqual({
434
+ kind: EngineResultKind.REJECTED,
435
+ code: RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
436
+ message: expect.any(String),
437
+ });
438
+ expect(host.progress).toEqual([]);
439
+ expect(host.calls).toEqual([]);
440
+ });
441
+
442
+ it('refuses to resume a state that is not suspended', async () => {
443
+ const done = outcomeOf(await runInIsolate(request({ definition: longWait }), fakeHost()));
444
+ expect(done.status).toBe(ExecutionStatus.SUCCEEDED);
445
+ const ended: RunState = {
446
+ stateVersion: CURRENT_STATE_VERSION,
447
+ formatVersion: CURRENT_FORMAT_VERSION,
448
+ status: RunStatus.SUCCEEDED,
449
+ input: null,
450
+ stack: [],
451
+ outputs: {},
452
+ vars: {},
453
+ pending: null,
454
+ counters: { steps: 1, effects: 0 },
455
+ };
456
+ const result = await runInIsolate(
457
+ request({ definition: longWait, state: ended }),
458
+ fakeHost(),
459
+ );
460
+ expect(result).toEqual(
461
+ expect.objectContaining({
462
+ kind: EngineResultKind.REJECTED,
463
+ code: RuntimeErrorCode.INVALID_REQUEST,
464
+ }),
465
+ );
466
+ });
467
+ });
468
+ });