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