@abyss-project/runtime 3.5.0 → 3.7.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 (59) 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/engine/run-in-isolate.js +5 -2
  6. package/dist/engine/run-in-isolate.js.map +1 -1
  7. package/dist/interpreter/interpreter.js +19 -4
  8. package/dist/interpreter/interpreter.js.map +1 -1
  9. package/dist/interpreter/interpreter.types.d.ts +3 -0
  10. package/dist/interpreter/interpreter.types.js.map +1 -1
  11. package/dist/runner-protocol/execution-protocol.types.d.ts +12 -0
  12. package/dist/runner-protocol/execution-protocol.types.js +2 -1
  13. package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
  14. package/jest.config.ts +11 -11
  15. package/package.json +15 -10
  16. package/scripts/build-engine.cjs +70 -70
  17. package/src/__tests__/engine-bundle.test.ts +121 -121
  18. package/src/__tests__/surface.test.ts +70 -66
  19. package/src/access/__tests__/host-match.test.ts +24 -24
  20. package/src/access/access.types.ts +25 -25
  21. package/src/access/host-match.ts +13 -13
  22. package/src/cost/__tests__/execution-cost.test.ts +196 -196
  23. package/src/cost/execution-cost.ts +186 -186
  24. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  25. package/src/definition/definition.limits.ts +9 -9
  26. package/src/definition/definition.schema.ts +172 -172
  27. package/src/definition/definition.types.ts +171 -171
  28. package/src/definition/validate-definition.ts +206 -206
  29. package/src/definition/walk-steps.ts +44 -44
  30. package/src/discord/__tests__/discord-event-input.test.ts +89 -89
  31. package/src/discord/discord.types.ts +639 -639
  32. package/src/engine/__tests__/run-in-isolate.test.ts +468 -468
  33. package/src/engine/engine-entry.ts +3 -3
  34. package/src/engine/engine-global.ts +2 -2
  35. package/src/engine/run-in-isolate.ts +419 -404
  36. package/src/errors/runtime-error-code.enum.ts +37 -37
  37. package/src/index.ts +32 -32
  38. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  39. package/src/interpreter/__tests__/log-respond-resume.test.ts +271 -223
  40. package/src/interpreter/interpreter-error.ts +12 -12
  41. package/src/interpreter/interpreter.ts +483 -461
  42. package/src/interpreter/interpreter.types.ts +204 -192
  43. package/src/interpreter/sequence-path.ts +67 -67
  44. package/src/interpreter/test-host.ts +85 -85
  45. package/src/runner-protocol/evaluation.types.ts +21 -21
  46. package/src/runner-protocol/execution-protocol.types.ts +260 -231
  47. package/src/schedule/schedule.types.ts +100 -100
  48. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  49. package/src/server/code-runner-error.ts +12 -12
  50. package/src/server/code-runner-session.ts +310 -310
  51. package/src/server/index.ts +11 -11
  52. package/src/steps/__tests__/global-references.test.ts +133 -133
  53. package/src/steps/execute-step.ts +186 -186
  54. package/src/steps/global-references.ts +48 -48
  55. package/src/steps/step-access.ts +56 -56
  56. package/src/steps/step-fields.ts +87 -87
  57. package/src/steps/value-source.ts +69 -69
  58. package/tsconfig.check.json +15 -15
  59. package/tsconfig.json +35 -35
@@ -1,404 +1,419 @@
1
- // The interpreter driver that runs INSIDE the execution's isolate (ADR-0243). It is bundled with
2
- // the interpreter into one self-contained script (`@abyss-project/runtime/engine`), so it and
3
- // everything it imports must stay free of Node, of web APIs absent from a bare V8 context
4
- // (`URL`, `TextEncoder`, timers...), and of Joi:
5
- // - the definition is validated by the host when it is published (`validateDefinition`), not here;
6
- // - a host action's input is validated by the host when it serves the call, against its catalog,
7
- // since a Joi schema cannot cross into the isolate;
8
- // - the runner only checks that a capability is exposed; the host re-checks each HTTP host and
9
- // each action against the run's grants (ADR-0228 §9), so no URL is parsed here.
10
-
11
- import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
12
- import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
13
- import { AccessKind } from '../access/access.types';
14
- import { MAX_WAIT_DURATION_MS } from '../definition/definition.limits';
15
- import { InterpreterError } from '../interpreter/interpreter-error';
16
- import { startRun, stepRun } from '../interpreter/interpreter';
17
- import type { RunPolicy, StepFinish, StepObserver } from '../interpreter/interpreter';
18
- import {
19
- CURRENT_STATE_VERSION,
20
- EffectType,
21
- RunEventType,
22
- RunStatus,
23
- } from '../interpreter/interpreter.types';
24
- import type {
25
- Effect,
26
- EvaluationContext,
27
- HttpResponse,
28
- RunEvent,
29
- RunState,
30
- StepResult,
31
- WaitEffect,
32
- } from '../interpreter/interpreter.types';
33
- import { StopStatus } from '../definition/definition.types';
34
- import { AccessVerdict } from '../steps/step-access';
35
- import type { EvaluationItem, EvaluationResult } from '../runner-protocol/evaluation.types';
36
- import {
37
- CoreCapability,
38
- ExecutionStatus,
39
- MAX_PROGRESS_OUTPUT_CHARS,
40
- StepPhase,
41
- StepStatus,
42
- } from '../runner-protocol/execution-protocol.types';
43
- import type {
44
- CallError,
45
- ExecuteMessage,
46
- ExecutionOutcome,
47
- ExecutionRejectionCode,
48
- JSONValue,
49
- ProgressMessage,
50
- } from '../runner-protocol/execution-protocol.types';
51
-
52
- /** The host's answer to one call, as the runner relays it from `callResult`. */
53
- export type HostCallAnswer =
54
- | { ok: true; value: unknown }
55
- | { ok: true; suspend: true }
56
- | { ok: false; error: CallError };
57
-
58
- /** A `progress` message without what only the runner measures. */
59
- export type EngineProgress = Omit<ProgressMessage, 'type' | 'metrics'>;
60
-
61
- /** What the runner provides to the engine. A rejected promise is an infrastructure failure. */
62
- export interface EngineHost {
63
- /**
64
- * Evaluates the JS items of one step, each in a fresh context. `globals` is the request's, as is
65
- * (absent when the host gave none): each of its keys is a read-only global of every context.
66
- */
67
- evaluate: (
68
- items: EvaluationItem[],
69
- context: EvaluationContext,
70
- stepId: string,
71
- globals?: Record<string, JSONValue>,
72
- ) => Promise<EvaluationResult[]>;
73
- /** Relays a host function call made by step `stepId`. */
74
- callHost: (stepId: string, capability: string, args: unknown) => Promise<HostCallAnswer>;
75
- onProgress: (progress: EngineProgress) => void;
76
- /** Milliseconds; only differences are used (step durations, `until` against the threshold). */
77
- now: () => number;
78
- }
79
-
80
- export type EngineRequest = Pick<
81
- ExecuteMessage,
82
- | 'definition'
83
- | 'input'
84
- | 'state'
85
- | 'resumeInput'
86
- | 'capabilities'
87
- | 'budget'
88
- | 'suspendWaitAboveMs'
89
- | 'globals'
90
- >;
91
-
92
- export enum EngineResultKind {
93
- FINISHED = 'FINISHED',
94
- REJECTED = 'REJECTED',
95
- }
96
-
97
- export type EngineResult =
98
- | { kind: EngineResultKind.FINISHED; outcome: ExecutionOutcome }
99
- | { kind: EngineResultKind.REJECTED; code: ExecutionRejectionCode; message: string };
100
-
101
- const RUNTIME_ERROR_CODES = new Set<string>(Object.values(RuntimeErrorCode));
102
-
103
- const rejected = (code: ExecutionRejectionCode, message: string): EngineResult => ({
104
- kind: EngineResultKind.REJECTED,
105
- code,
106
- message,
107
- });
108
-
109
- const finished = (outcome: ExecutionOutcome): EngineResult => ({
110
- kind: EngineResultKind.FINISHED,
111
- outcome,
112
- });
113
-
114
- /**
115
- * Runner-side policy. The capability list stands for the grants: an HTTP step needs
116
- * `http.fetch` exposed, a host action needs to be declared by the definition AND exposed. The
117
- * host re-checks the HTTP host and the action's input when it serves the call.
118
- */
119
- const isolatePolicy = (request: EngineRequest): RunPolicy => {
120
- const exposed = new Set(request.capabilities);
121
- const declared = (action: string): boolean =>
122
- request.definition.accesses.some(
123
- (access) => access.kind === AccessKind.HOST_ACTION && access.action === action,
124
- );
125
- return {
126
- // Waits above `suspendWaitAboveMs` suspend; the host bounds the others by the time left.
127
- budget: { ...request.budget, maxWaitMs: MAX_WAIT_DURATION_MS },
128
- httpAccess: () =>
129
- exposed.has(CoreCapability.HTTP_FETCH) ? AccessVerdict.ALLOWED : AccessVerdict.NOT_GRANTED,
130
- hostActionAccess: (action) => {
131
- if (!declared(action)) {
132
- return AccessVerdict.NOT_DECLARED;
133
- }
134
- return exposed.has(action) ? AccessVerdict.ALLOWED : AccessVerdict.NOT_GRANTED;
135
- },
136
- hostInput: (_action, input) => ({ input }),
137
- };
138
- };
139
-
140
- /** The progress view of an output: the value itself, or the beginning of its JSON. */
141
- const outputPreview = (output: unknown): Pick<EngineProgress, 'output' | 'outputTruncated'> => {
142
- let json: string | undefined;
143
- try {
144
- json = JSON.stringify(output);
145
- } catch {
146
- return { outputTruncated: true };
147
- }
148
- if (json === undefined) {
149
- return {};
150
- }
151
- if (json.length <= MAX_PROGRESS_OUTPUT_CHARS) {
152
- return { output };
153
- }
154
- return { output: json.slice(0, MAX_PROGRESS_OUTPUT_CHARS), outputTruncated: true };
155
- };
156
-
157
- /** Turns interpreter step notifications into `progress`, timing each step with `host.now`. */
158
- const progressObserver = (host: EngineHost) => {
159
- const startedAt = new Map<string, number>();
160
- const durationOf = (stepId: string): number => {
161
- const start = startedAt.get(stepId);
162
- startedAt.delete(stepId);
163
- return start === undefined ? 0 : Math.max(0, host.now() - start);
164
- };
165
- const observer: StepObserver = {
166
- stepStarted: (stepId) => {
167
- startedAt.set(stepId, host.now());
168
- host.onProgress({ stepId, phase: StepPhase.STARTED });
169
- },
170
- stepFinished: (stepId, finish: StepFinish) => {
171
- const durationMs = durationOf(stepId);
172
- host.onProgress(
173
- finish.ok
174
- ? {
175
- stepId,
176
- phase: StepPhase.FINISHED,
177
- status: StepStatus.SUCCEEDED,
178
- durationMs,
179
- ...outputPreview(finish.output),
180
- }
181
- : {
182
- stepId,
183
- phase: StepPhase.FINISHED,
184
- status: StepStatus.FAILED,
185
- durationMs,
186
- errorCode: finish.error.code,
187
- },
188
- );
189
- },
190
- };
191
- const suspended = (stepId: string): void =>
192
- host.onProgress({
193
- stepId,
194
- phase: StepPhase.FINISHED,
195
- status: StepStatus.SUSPENDED,
196
- durationMs: durationOf(stepId),
197
- });
198
- return { observer, suspended };
199
- };
200
-
201
- type CallEffect = Exclude<Effect, { type: EffectType.EVALUATE }>;
202
-
203
- const callOf = (effect: CallEffect): { capability: string; args: unknown } => {
204
- switch (effect.type) {
205
- case EffectType.HTTP:
206
- return { capability: CoreCapability.HTTP_FETCH, args: effect.request };
207
- case EffectType.HOST:
208
- return { capability: effect.action, args: effect.input };
209
- case EffectType.WAIT:
210
- return {
211
- capability: CoreCapability.WAIT,
212
- args:
213
- effect.durationMs !== undefined
214
- ? { durationMs: effect.durationMs }
215
- : { until: effect.until },
216
- };
217
- case EffectType.LOG: {
218
- const args: Record<string, unknown> = { level: effect.level, message: effect.message };
219
- if ('data' in effect) {
220
- args.data = effect.data;
221
- }
222
- return { capability: CoreCapability.LOG_WRITE, args };
223
- }
224
- case EffectType.RESPOND:
225
- return { capability: CoreCapability.HTTP_RESPOND, args: effect.response };
226
- }
227
- };
228
-
229
- const completionOf = (effect: CallEffect, value: unknown): RunEvent => {
230
- switch (effect.type) {
231
- case EffectType.HTTP:
232
- return { type: RunEventType.HTTP_COMPLETED, response: value as HttpResponse };
233
- case EffectType.HOST:
234
- return { type: RunEventType.HOST_COMPLETED, output: value };
235
- case EffectType.WAIT:
236
- return { type: RunEventType.WAIT_ELAPSED };
237
- case EffectType.LOG:
238
- return { type: RunEventType.LOG_WRITTEN };
239
- case EffectType.RESPOND:
240
- return { type: RunEventType.RESPONSE_SENT };
241
- }
242
- };
243
-
244
- const callFailure = (effect: CallEffect, error: CallError): RunEvent => {
245
- const fallback =
246
- effect.type === EffectType.HTTP ? RuntimeErrorCode.HTTP_ERROR : RuntimeErrorCode.HOST_ERROR;
247
- const detail: RuntimeErrorDetail = {
248
- code: error.code !== undefined && RUNTIME_ERROR_CODES.has(error.code) ? error.code : fallback,
249
- message: error.message,
250
- };
251
- return { type: RunEventType.EFFECT_FAILED, error: detail };
252
- };
253
-
254
- const waitsAboveThreshold = (effect: WaitEffect, request: EngineRequest, now: number): boolean => {
255
- const threshold = request.suspendWaitAboveMs;
256
- if (threshold === undefined) {
257
- return false;
258
- }
259
- if (effect.durationMs !== undefined) {
260
- return effect.durationMs > threshold;
261
- }
262
- return effect.until !== undefined && Date.parse(effect.until) - now > threshold;
263
- };
264
-
265
- const outcomeOf = (state: RunState): ExecutionOutcome => {
266
- const outcome = state.outcome;
267
- if (state.status === RunStatus.SUCCEEDED) {
268
- return outcome?.output === undefined
269
- ? { status: ExecutionStatus.SUCCEEDED }
270
- : { status: ExecutionStatus.SUCCEEDED, output: outcome.output };
271
- }
272
- if (outcome?.error) {
273
- const failure: ExecutionOutcome = {
274
- status: ExecutionStatus.FAILED,
275
- errorCode: outcome.error.code,
276
- errorMessage: outcome.error.message,
277
- };
278
- if (outcome.error.stepId !== undefined) {
279
- failure.stepId = outcome.error.stepId;
280
- }
281
- return failure;
282
- }
283
- // A STOP step that chose FAILED: no error, its output says why.
284
- return outcome?.status === StopStatus.FAILED && outcome.output !== undefined
285
- ? { status: ExecutionStatus.FAILED, output: outcome.output }
286
- : { status: ExecutionStatus.FAILED };
287
- };
288
-
289
- /** Why a state cannot be resumed, or null when it can. */
290
- const resumeRefusal = (state: RunState): EngineResult | null => {
291
- if (state.stateVersion !== CURRENT_STATE_VERSION) {
292
- return rejected(
293
- RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
294
- `Run state version ${String(state.stateVersion)} is not supported ` +
295
- `(this core reads version ${CURRENT_STATE_VERSION})`,
296
- );
297
- }
298
- if (state.status !== RunStatus.WAITING || !state.pending) {
299
- return rejected(RuntimeErrorCode.INVALID_REQUEST, 'The state to resume is not suspended');
300
- }
301
- if (state.pending.type === EffectType.EVALUATE) {
302
- return rejected(
303
- RuntimeErrorCode.INVALID_REQUEST,
304
- 'The state to resume waits for an evaluation, which never suspends',
305
- );
306
- }
307
- return null;
308
- };
309
-
310
- /**
311
- * Runs one execution, or one segment of it, from its start or from a suspended `state`.
312
- * Steps chain until the run ends, or until it suspends between two steps: on a WAIT above
313
- * `suspendWaitAboveMs`, or when the host answers a call with `suspend`. A resumed run gives
314
- * `resumeInput` (null when absent) to the step that suspended, as its output.
315
- */
316
- export const runInIsolate = async (
317
- request: EngineRequest,
318
- host: EngineHost,
319
- ): Promise<EngineResult> => {
320
- const { definition, state } = request;
321
- if (state !== undefined) {
322
- const refusal = resumeRefusal(state);
323
- if (refusal) {
324
- return refusal;
325
- }
326
- }
327
- const policy = isolatePolicy(request);
328
- const exposed = new Set(request.capabilities);
329
- const progress = progressObserver(host);
330
- const suspend = (stepId: string, suspendedState: RunState): EngineResult => {
331
- progress.suspended(stepId);
332
- return finished({ status: ExecutionStatus.SUSPENDED, state: suspendedState });
333
- };
334
-
335
- try {
336
- let result: StepResult;
337
- if (state === undefined) {
338
- result = startRun(definition, request.input, policy, progress.observer);
339
- } else {
340
- // `resumeRefusal` guarantees a pending call effect.
341
- progress.observer.stepStarted((state.pending as Effect).stepId);
342
- result = stepRun(
343
- definition,
344
- state,
345
- { type: RunEventType.RESUMED, output: request.resumeInput ?? null },
346
- policy,
347
- progress.observer,
348
- );
349
- }
350
- while (result.status === RunStatus.WAITING) {
351
- const effect = result.state.pending;
352
- if (!effect) {
353
- throw new InterpreterError(RuntimeErrorCode.INVALID_REQUEST, 'Run waits for no effect');
354
- }
355
- let event: RunEvent;
356
- if (effect.type === EffectType.EVALUATE) {
357
- const results = await host.evaluate(
358
- effect.items,
359
- effect.context,
360
- effect.stepId,
361
- request.globals,
362
- );
363
- event = { type: RunEventType.EVALUATED, results };
364
- } else if (
365
- effect.type === EffectType.WAIT &&
366
- waitsAboveThreshold(effect, request, host.now())
367
- ) {
368
- return suspend(effect.stepId, result.state);
369
- } else {
370
- const { capability, args } = callOf(effect);
371
- if (!exposed.has(capability)) {
372
- event = {
373
- type: RunEventType.EFFECT_FAILED,
374
- error: {
375
- code: RuntimeErrorCode.ACCESS_DENIED,
376
- message: `Capability "${capability}" is not granted to the execution`,
377
- },
378
- };
379
- } else {
380
- const answer = await host.callHost(effect.stepId, capability, args);
381
- if (!answer.ok) {
382
- event = callFailure(effect, answer.error);
383
- } else if ('suspend' in answer) {
384
- return suspend(effect.stepId, result.state);
385
- } else {
386
- event = completionOf(effect, answer.value);
387
- }
388
- }
389
- }
390
- result = stepRun(definition, result.state, event, policy, progress.observer);
391
- }
392
- return finished(outcomeOf(result.state));
393
- } catch (error) {
394
- // A misuse the interpreter detected (results that do not cover a step, corrupted state).
395
- if (error instanceof InterpreterError) {
396
- return finished({
397
- status: ExecutionStatus.FAILED,
398
- errorCode: error.code,
399
- errorMessage: error.message,
400
- });
401
- }
402
- throw error;
403
- }
404
- };
1
+ // The interpreter driver that runs INSIDE the execution's isolate (ADR-0243). It is bundled with
2
+ // the interpreter into one self-contained script (`@abyss-project/runtime/engine`), so it and
3
+ // everything it imports must stay free of Node, of web APIs absent from a bare V8 context
4
+ // (`URL`, `TextEncoder`, timers...), and of Joi:
5
+ // - the definition is validated by the host when it is published (`validateDefinition`), not here;
6
+ // - a host action's input is validated by the host when it serves the call, against its catalog,
7
+ // since a Joi schema cannot cross into the isolate;
8
+ // - the runner only checks that a capability is exposed; the host re-checks each HTTP host and
9
+ // each action against the run's grants (ADR-0228 §9), so no URL is parsed here.
10
+
11
+ import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
12
+ import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
13
+ import { AccessKind } from '../access/access.types';
14
+ import { MAX_WAIT_DURATION_MS } from '../definition/definition.limits';
15
+ import { InterpreterError } from '../interpreter/interpreter-error';
16
+ import { startRun, stepRun } from '../interpreter/interpreter';
17
+ import type { RunPolicy, StepFinish, StepObserver } from '../interpreter/interpreter';
18
+ import {
19
+ CURRENT_STATE_VERSION,
20
+ EffectType,
21
+ RunEventType,
22
+ RunStatus,
23
+ } from '../interpreter/interpreter.types';
24
+ import type {
25
+ Effect,
26
+ EvaluationContext,
27
+ HttpResponse,
28
+ RunEvent,
29
+ RunState,
30
+ StepResult,
31
+ WaitEffect,
32
+ } from '../interpreter/interpreter.types';
33
+ import { StopStatus } from '../definition/definition.types';
34
+ import { AccessVerdict } from '../steps/step-access';
35
+ import type { EvaluationItem, EvaluationResult } from '../runner-protocol/evaluation.types';
36
+ import {
37
+ CoreCapability,
38
+ ExecutionStatus,
39
+ MAX_PROGRESS_OUTPUT_CHARS,
40
+ StepPhase,
41
+ StepStatus,
42
+ } from '../runner-protocol/execution-protocol.types';
43
+ import type {
44
+ CallError,
45
+ ExecuteMessage,
46
+ ExecutionOutcome,
47
+ ExecutionRejectionCode,
48
+ JSONValue,
49
+ ProgressMessage,
50
+ } from '../runner-protocol/execution-protocol.types';
51
+
52
+ /** The host's answer to one call, as the runner relays it from `callResult`. */
53
+ export type HostCallAnswer =
54
+ | { ok: true; value: unknown }
55
+ | { ok: true; suspend: true }
56
+ | { ok: false; error: CallError };
57
+
58
+ /** A `progress` message without what only the runner measures. */
59
+ export type EngineProgress = Omit<ProgressMessage, 'type' | 'metrics'>;
60
+
61
+ /** What the runner provides to the engine. A rejected promise is an infrastructure failure. */
62
+ export interface EngineHost {
63
+ /**
64
+ * Evaluates the JS items of one step, each in a fresh context. `globals` is the request's, as is
65
+ * (absent when the host gave none): each of its keys is a read-only global of every context.
66
+ */
67
+ evaluate: (
68
+ items: EvaluationItem[],
69
+ context: EvaluationContext,
70
+ stepId: string,
71
+ globals?: Record<string, JSONValue>,
72
+ ) => Promise<EvaluationResult[]>;
73
+ /** Relays a host function call made by step `stepId`. */
74
+ callHost: (stepId: string, capability: string, args: unknown) => Promise<HostCallAnswer>;
75
+ onProgress: (progress: EngineProgress) => void;
76
+ /** Milliseconds; only differences are used (step durations, `until` against the threshold). */
77
+ now: () => number;
78
+ }
79
+
80
+ export type EngineRequest = Pick<
81
+ ExecuteMessage,
82
+ | 'definition'
83
+ | 'input'
84
+ | 'state'
85
+ | 'resumeInput'
86
+ | 'capabilities'
87
+ | 'budget'
88
+ | 'suspendWaitAboveMs'
89
+ | 'globals'
90
+ >;
91
+
92
+ export enum EngineResultKind {
93
+ FINISHED = 'FINISHED',
94
+ REJECTED = 'REJECTED',
95
+ }
96
+
97
+ export type EngineResult =
98
+ | { kind: EngineResultKind.FINISHED; outcome: ExecutionOutcome }
99
+ | { kind: EngineResultKind.REJECTED; code: ExecutionRejectionCode; message: string };
100
+
101
+ const RUNTIME_ERROR_CODES = new Set<string>(Object.values(RuntimeErrorCode));
102
+
103
+ const rejected = (code: ExecutionRejectionCode, message: string): EngineResult => ({
104
+ kind: EngineResultKind.REJECTED,
105
+ code,
106
+ message,
107
+ });
108
+
109
+ const finished = (outcome: ExecutionOutcome): EngineResult => ({
110
+ kind: EngineResultKind.FINISHED,
111
+ outcome,
112
+ });
113
+
114
+ /**
115
+ * Runner-side policy. The capability list stands for the grants: an HTTP step needs
116
+ * `http.fetch` exposed, a host action needs to be declared by the definition AND exposed. The
117
+ * host re-checks the HTTP host and the action's input when it serves the call.
118
+ */
119
+ const isolatePolicy = (request: EngineRequest): RunPolicy => {
120
+ const exposed = new Set(request.capabilities);
121
+ const declared = (action: string): boolean =>
122
+ request.definition.accesses.some(
123
+ (access) => access.kind === AccessKind.HOST_ACTION && access.action === action,
124
+ );
125
+ return {
126
+ // Waits above `suspendWaitAboveMs` suspend; the host bounds the others by the time left.
127
+ budget: { ...request.budget, maxWaitMs: MAX_WAIT_DURATION_MS },
128
+ httpAccess: () =>
129
+ exposed.has(CoreCapability.HTTP_FETCH) ? AccessVerdict.ALLOWED : AccessVerdict.NOT_GRANTED,
130
+ hostActionAccess: (action) => {
131
+ if (!declared(action)) {
132
+ return AccessVerdict.NOT_DECLARED;
133
+ }
134
+ return exposed.has(action) ? AccessVerdict.ALLOWED : AccessVerdict.NOT_GRANTED;
135
+ },
136
+ hostInput: (_action, input) => ({ input }),
137
+ };
138
+ };
139
+
140
+ /** The progress view of an output: the value itself, or the beginning of its JSON. */
141
+ const outputPreview = (output: unknown): Pick<EngineProgress, 'output' | 'outputTruncated'> => {
142
+ let json: string | undefined;
143
+ try {
144
+ json = JSON.stringify(output);
145
+ } catch {
146
+ return { outputTruncated: true };
147
+ }
148
+ if (json === undefined) {
149
+ return {};
150
+ }
151
+ if (json.length <= MAX_PROGRESS_OUTPUT_CHARS) {
152
+ return { output };
153
+ }
154
+ return { output: json.slice(0, MAX_PROGRESS_OUTPUT_CHARS), outputTruncated: true };
155
+ };
156
+
157
+ /** Turns interpreter step notifications into `progress`, timing each step with `host.now`. */
158
+ const progressObserver = (host: EngineHost) => {
159
+ const startedAt = new Map<string, number>();
160
+ const durationOf = (stepId: string): number => {
161
+ const start = startedAt.get(stepId);
162
+ startedAt.delete(stepId);
163
+ return start === undefined ? 0 : Math.max(0, host.now() - start);
164
+ };
165
+ const observer: StepObserver = {
166
+ stepStarted: (stepId) => {
167
+ startedAt.set(stepId, host.now());
168
+ host.onProgress({ stepId, phase: StepPhase.STARTED });
169
+ },
170
+ stepFinished: (stepId, finish: StepFinish) => {
171
+ const durationMs = durationOf(stepId);
172
+ host.onProgress(
173
+ finish.ok
174
+ ? {
175
+ stepId,
176
+ phase: StepPhase.FINISHED,
177
+ status: StepStatus.SUCCEEDED,
178
+ durationMs,
179
+ ...outputPreview(finish.output),
180
+ }
181
+ : {
182
+ stepId,
183
+ phase: StepPhase.FINISHED,
184
+ status: StepStatus.FAILED,
185
+ durationMs,
186
+ errorCode: finish.error.code,
187
+ },
188
+ );
189
+ },
190
+ };
191
+ const suspended = (stepId: string): void =>
192
+ host.onProgress({
193
+ stepId,
194
+ phase: StepPhase.FINISHED,
195
+ status: StepStatus.SUSPENDED,
196
+ durationMs: durationOf(stepId),
197
+ });
198
+ return { observer, suspended };
199
+ };
200
+
201
+ type CallEffect = Exclude<Effect, { type: EffectType.EVALUATE }>;
202
+
203
+ const callOf = (effect: CallEffect): { capability: string; args: unknown } => {
204
+ switch (effect.type) {
205
+ case EffectType.HTTP:
206
+ return { capability: CoreCapability.HTTP_FETCH, args: effect.request };
207
+ case EffectType.HOST:
208
+ return { capability: effect.action, args: effect.input };
209
+ case EffectType.WAIT:
210
+ return {
211
+ capability: CoreCapability.WAIT,
212
+ args:
213
+ effect.durationMs !== undefined
214
+ ? { durationMs: effect.durationMs }
215
+ : { until: effect.until },
216
+ };
217
+ case EffectType.LOG: {
218
+ const args: Record<string, unknown> = { level: effect.level, message: effect.message };
219
+ if ('data' in effect) {
220
+ args.data = effect.data;
221
+ }
222
+ return { capability: CoreCapability.LOG_WRITE, args };
223
+ }
224
+ case EffectType.RESPOND:
225
+ return { capability: CoreCapability.HTTP_RESPOND, args: effect.response };
226
+ }
227
+ };
228
+
229
+ const completionOf = (effect: CallEffect, value: unknown): RunEvent => {
230
+ switch (effect.type) {
231
+ case EffectType.HTTP:
232
+ return { type: RunEventType.HTTP_COMPLETED, response: value as HttpResponse };
233
+ case EffectType.HOST:
234
+ return { type: RunEventType.HOST_COMPLETED, output: value };
235
+ case EffectType.WAIT:
236
+ return { type: RunEventType.WAIT_ELAPSED };
237
+ case EffectType.LOG:
238
+ return { type: RunEventType.LOG_WRITTEN };
239
+ case EffectType.RESPOND:
240
+ return { type: RunEventType.RESPONSE_SENT };
241
+ }
242
+ };
243
+
244
+ const callFailure = (effect: CallEffect, error: CallError): RunEvent => {
245
+ const fallback =
246
+ effect.type === EffectType.HTTP ? RuntimeErrorCode.HTTP_ERROR : RuntimeErrorCode.HOST_ERROR;
247
+ const detail: RuntimeErrorDetail = {
248
+ code: error.code !== undefined && RUNTIME_ERROR_CODES.has(error.code) ? error.code : fallback,
249
+ message: error.message,
250
+ };
251
+ return { type: RunEventType.EFFECT_FAILED, error: detail };
252
+ };
253
+
254
+ const waitsAboveThreshold = (effect: WaitEffect, request: EngineRequest, now: number): boolean => {
255
+ const threshold = request.suspendWaitAboveMs;
256
+ if (threshold === undefined) {
257
+ return false;
258
+ }
259
+ if (effect.durationMs !== undefined) {
260
+ return effect.durationMs > threshold;
261
+ }
262
+ return effect.until !== undefined && Date.parse(effect.until) - now > threshold;
263
+ };
264
+
265
+ /** LOG steps the interpreter skipped during this segment (the counter is cumulative in the state). */
266
+ const droppedInSegment = (state: RunState, before: number): number =>
267
+ (state.counters.droppedLogLines ?? 0) - before;
268
+
269
+ const withDropped = (outcome: ExecutionOutcome, dropped: number): ExecutionOutcome =>
270
+ dropped > 0 ? { ...outcome, droppedLogLines: dropped } : outcome;
271
+
272
+ const outcomeOf = (state: RunState): ExecutionOutcome => {
273
+ const outcome = state.outcome;
274
+ if (state.status === RunStatus.SUCCEEDED) {
275
+ return outcome?.output === undefined
276
+ ? { status: ExecutionStatus.SUCCEEDED }
277
+ : { status: ExecutionStatus.SUCCEEDED, output: outcome.output };
278
+ }
279
+ if (outcome?.error) {
280
+ const failure: ExecutionOutcome = {
281
+ status: ExecutionStatus.FAILED,
282
+ errorCode: outcome.error.code,
283
+ errorMessage: outcome.error.message,
284
+ };
285
+ if (outcome.error.stepId !== undefined) {
286
+ failure.stepId = outcome.error.stepId;
287
+ }
288
+ return failure;
289
+ }
290
+ // A STOP step that chose FAILED: no error, its output says why.
291
+ return outcome?.status === StopStatus.FAILED && outcome.output !== undefined
292
+ ? { status: ExecutionStatus.FAILED, output: outcome.output }
293
+ : { status: ExecutionStatus.FAILED };
294
+ };
295
+
296
+ /** Why a state cannot be resumed, or null when it can. */
297
+ const resumeRefusal = (state: RunState): EngineResult | null => {
298
+ if (state.stateVersion !== CURRENT_STATE_VERSION) {
299
+ return rejected(
300
+ RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
301
+ `Run state version ${String(state.stateVersion)} is not supported ` +
302
+ `(this core reads version ${CURRENT_STATE_VERSION})`,
303
+ );
304
+ }
305
+ if (state.status !== RunStatus.WAITING || !state.pending) {
306
+ return rejected(RuntimeErrorCode.INVALID_REQUEST, 'The state to resume is not suspended');
307
+ }
308
+ if (state.pending.type === EffectType.EVALUATE) {
309
+ return rejected(
310
+ RuntimeErrorCode.INVALID_REQUEST,
311
+ 'The state to resume waits for an evaluation, which never suspends',
312
+ );
313
+ }
314
+ return null;
315
+ };
316
+
317
+ /**
318
+ * Runs one execution, or one segment of it, from its start or from a suspended `state`.
319
+ * Steps chain until the run ends, or until it suspends between two steps: on a WAIT above
320
+ * `suspendWaitAboveMs`, or when the host answers a call with `suspend`. A resumed run gives
321
+ * `resumeInput` (null when absent) to the step that suspended, as its output.
322
+ */
323
+ export const runInIsolate = async (
324
+ request: EngineRequest,
325
+ host: EngineHost,
326
+ ): Promise<EngineResult> => {
327
+ const { definition, state } = request;
328
+ if (state !== undefined) {
329
+ const refusal = resumeRefusal(state);
330
+ if (refusal) {
331
+ return refusal;
332
+ }
333
+ }
334
+ const policy = isolatePolicy(request);
335
+ const exposed = new Set(request.capabilities);
336
+ const progress = progressObserver(host);
337
+ const droppedBefore = state?.counters.droppedLogLines ?? 0;
338
+ const suspend = (stepId: string, suspendedState: RunState): EngineResult => {
339
+ progress.suspended(stepId);
340
+ return finished(
341
+ withDropped(
342
+ { status: ExecutionStatus.SUSPENDED, state: suspendedState },
343
+ droppedInSegment(suspendedState, droppedBefore),
344
+ ),
345
+ );
346
+ };
347
+
348
+ try {
349
+ let result: StepResult;
350
+ if (state === undefined) {
351
+ result = startRun(definition, request.input, policy, progress.observer);
352
+ } else {
353
+ // `resumeRefusal` guarantees a pending call effect.
354
+ progress.observer.stepStarted((state.pending as Effect).stepId);
355
+ result = stepRun(
356
+ definition,
357
+ state,
358
+ { type: RunEventType.RESUMED, output: request.resumeInput ?? null },
359
+ policy,
360
+ progress.observer,
361
+ );
362
+ }
363
+ while (result.status === RunStatus.WAITING) {
364
+ const effect = result.state.pending;
365
+ if (!effect) {
366
+ throw new InterpreterError(RuntimeErrorCode.INVALID_REQUEST, 'Run waits for no effect');
367
+ }
368
+ let event: RunEvent;
369
+ if (effect.type === EffectType.EVALUATE) {
370
+ const results = await host.evaluate(
371
+ effect.items,
372
+ effect.context,
373
+ effect.stepId,
374
+ request.globals,
375
+ );
376
+ event = { type: RunEventType.EVALUATED, results };
377
+ } else if (
378
+ effect.type === EffectType.WAIT &&
379
+ waitsAboveThreshold(effect, request, host.now())
380
+ ) {
381
+ return suspend(effect.stepId, result.state);
382
+ } else {
383
+ const { capability, args } = callOf(effect);
384
+ if (!exposed.has(capability)) {
385
+ event = {
386
+ type: RunEventType.EFFECT_FAILED,
387
+ error: {
388
+ code: RuntimeErrorCode.ACCESS_DENIED,
389
+ message: `Capability "${capability}" is not granted to the execution`,
390
+ },
391
+ };
392
+ } else {
393
+ const answer = await host.callHost(effect.stepId, capability, args);
394
+ if (!answer.ok) {
395
+ event = callFailure(effect, answer.error);
396
+ } else if ('suspend' in answer) {
397
+ return suspend(effect.stepId, result.state);
398
+ } else {
399
+ event = completionOf(effect, answer.value);
400
+ }
401
+ }
402
+ }
403
+ result = stepRun(definition, result.state, event, policy, progress.observer);
404
+ }
405
+ return finished(
406
+ withDropped(outcomeOf(result.state), droppedInSegment(result.state, droppedBefore)),
407
+ );
408
+ } catch (error) {
409
+ // A misuse the interpreter detected (results that do not cover a step, corrupted state).
410
+ if (error instanceof InterpreterError) {
411
+ return finished({
412
+ status: ExecutionStatus.FAILED,
413
+ errorCode: error.code,
414
+ errorMessage: error.message,
415
+ });
416
+ }
417
+ throw error;
418
+ }
419
+ };