@abyss-project/runtime 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/.eslintrc.js +32 -0
  2. package/.prettierrc +5 -0
  3. package/README.md +28 -3
  4. package/dist/access/access.types.d.ts +14 -0
  5. package/dist/access/access.types.js +9 -0
  6. package/dist/access/access.types.js.map +1 -0
  7. package/dist/access/host-match.d.ts +1 -0
  8. package/dist/access/host-match.js +14 -0
  9. package/dist/access/host-match.js.map +1 -0
  10. package/dist/cost/execution-cost.d.ts +45 -0
  11. package/dist/cost/execution-cost.js +114 -0
  12. package/dist/cost/execution-cost.js.map +1 -0
  13. package/dist/definition/definition.limits.d.ts +4 -0
  14. package/dist/definition/definition.limits.js +8 -0
  15. package/dist/definition/definition.limits.js.map +1 -0
  16. package/dist/definition/definition.schema.d.ts +8 -0
  17. package/dist/definition/definition.schema.js +123 -0
  18. package/dist/definition/definition.schema.js.map +1 -0
  19. package/dist/definition/definition.types.d.ts +117 -0
  20. package/dist/definition/definition.types.js +37 -0
  21. package/dist/definition/definition.types.js.map +1 -0
  22. package/dist/definition/validate-definition.d.ts +9 -0
  23. package/dist/definition/validate-definition.js +163 -0
  24. package/dist/definition/validate-definition.js.map +1 -0
  25. package/dist/definition/walk-steps.d.ts +5 -0
  26. package/dist/definition/walk-steps.js +31 -0
  27. package/dist/definition/walk-steps.js.map +1 -0
  28. package/dist/engine/engine-entry.d.ts +1 -0
  29. package/dist/engine/engine-entry.js +6 -0
  30. package/dist/engine/engine-entry.js.map +1 -0
  31. package/dist/engine/engine-global.d.ts +1 -0
  32. package/dist/engine/engine-global.js +5 -0
  33. package/dist/engine/engine-global.js.map +1 -0
  34. package/dist/engine/engine-source.d.ts +2 -0
  35. package/dist/engine/engine-source.js +3 -0
  36. package/dist/engine/run-in-isolate.d.ts +34 -0
  37. package/dist/engine/run-in-isolate.js +267 -0
  38. package/dist/engine/run-in-isolate.js.map +1 -0
  39. package/dist/errors/runtime-error-code.enum.d.ts +18 -0
  40. package/dist/errors/runtime-error-code.enum.js +19 -0
  41. package/dist/errors/runtime-error-code.enum.js.map +1 -0
  42. package/dist/index.d.ts +21 -0
  43. package/dist/index.js +47 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/interpreter/interpreter-error.d.ts +5 -0
  46. package/dist/interpreter/interpreter-error.js +12 -0
  47. package/dist/interpreter/interpreter-error.js.map +1 -0
  48. package/dist/interpreter/interpreter.d.ts +30 -0
  49. package/dist/interpreter/interpreter.js +313 -0
  50. package/dist/interpreter/interpreter.js.map +1 -0
  51. package/dist/interpreter/interpreter.types.d.ts +152 -0
  52. package/dist/interpreter/interpreter.types.js +31 -0
  53. package/dist/interpreter/interpreter.types.js.map +1 -0
  54. package/dist/interpreter/sequence-path.d.ts +6 -0
  55. package/dist/interpreter/sequence-path.js +53 -0
  56. package/dist/interpreter/sequence-path.js.map +1 -0
  57. package/dist/interpreter/test-host.d.ts +18 -0
  58. package/dist/interpreter/test-host.js +43 -0
  59. package/dist/interpreter/test-host.js.map +1 -0
  60. package/dist/runner-protocol/evaluation.types.d.ts +20 -0
  61. package/dist/runner-protocol/evaluation.types.js +10 -0
  62. package/dist/runner-protocol/evaluation.types.js.map +1 -0
  63. package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
  64. package/dist/runner-protocol/execution-protocol.types.js +48 -0
  65. package/dist/runner-protocol/execution-protocol.types.js.map +1 -0
  66. package/dist/server/code-runner-error.d.ts +5 -0
  67. package/dist/server/code-runner-error.js +12 -0
  68. package/dist/server/code-runner-error.js.map +1 -0
  69. package/dist/server/code-runner-session.d.ts +28 -0
  70. package/dist/server/code-runner-session.js +208 -0
  71. package/dist/server/code-runner-session.js.map +1 -0
  72. package/dist/server/index.d.ts +3 -0
  73. package/dist/server/index.js +10 -0
  74. package/dist/server/index.js.map +1 -0
  75. package/dist/steps/execute-step.d.ts +50 -0
  76. package/dist/steps/execute-step.js +136 -0
  77. package/dist/steps/execute-step.js.map +1 -0
  78. package/dist/steps/global-references.d.ts +2 -0
  79. package/dist/steps/global-references.js +28 -0
  80. package/dist/steps/global-references.js.map +1 -0
  81. package/dist/steps/step-access.d.ts +8 -0
  82. package/dist/steps/step-access.js +39 -0
  83. package/dist/steps/step-access.js.map +1 -0
  84. package/dist/steps/step-fields.d.ts +5 -0
  85. package/dist/steps/step-fields.js +68 -0
  86. package/dist/steps/step-fields.js.map +1 -0
  87. package/dist/steps/value-source.d.ts +6 -0
  88. package/dist/steps/value-source.js +58 -0
  89. package/dist/steps/value-source.js.map +1 -0
  90. package/jest.config.ts +11 -0
  91. package/package.json +68 -3
  92. package/scripts/build-engine.cjs +70 -0
  93. package/src/__tests__/engine-bundle.test.ts +121 -0
  94. package/src/__tests__/surface.test.ts +53 -0
  95. package/src/access/__tests__/host-match.test.ts +24 -0
  96. package/src/access/access.types.ts +25 -0
  97. package/src/access/host-match.ts +13 -0
  98. package/src/cost/__tests__/execution-cost.test.ts +200 -0
  99. package/src/cost/execution-cost.ts +192 -0
  100. package/src/definition/__tests__/validate-definition.test.ts +354 -0
  101. package/src/definition/definition.limits.ts +9 -0
  102. package/src/definition/definition.schema.ts +172 -0
  103. package/src/definition/definition.types.ts +171 -0
  104. package/src/definition/validate-definition.ts +206 -0
  105. package/src/definition/walk-steps.ts +44 -0
  106. package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
  107. package/src/engine/engine-entry.ts +3 -0
  108. package/src/engine/engine-global.ts +2 -0
  109. package/src/engine/run-in-isolate.ts +404 -0
  110. package/src/errors/runtime-error-code.enum.ts +37 -0
  111. package/src/index.ts +30 -0
  112. package/src/interpreter/__tests__/interpreter.test.ts +854 -0
  113. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
  114. package/src/interpreter/interpreter-error.ts +12 -0
  115. package/src/interpreter/interpreter.ts +461 -0
  116. package/src/interpreter/interpreter.types.ts +192 -0
  117. package/src/interpreter/sequence-path.ts +67 -0
  118. package/src/interpreter/test-host.ts +85 -0
  119. package/src/runner-protocol/evaluation.types.ts +21 -0
  120. package/src/runner-protocol/execution-protocol.types.ts +221 -0
  121. package/src/server/__tests__/code-runner-session.test.ts +311 -0
  122. package/src/server/code-runner-error.ts +12 -0
  123. package/src/server/code-runner-session.ts +310 -0
  124. package/src/server/index.ts +11 -0
  125. package/src/steps/__tests__/global-references.test.ts +113 -0
  126. package/src/steps/execute-step.ts +186 -0
  127. package/src/steps/global-references.ts +48 -0
  128. package/src/steps/step-access.ts +56 -0
  129. package/src/steps/step-fields.ts +87 -0
  130. package/src/steps/value-source.ts +69 -0
  131. package/tsconfig.check.json +15 -0
  132. package/tsconfig.json +35 -0
@@ -0,0 +1,223 @@
1
+ import { CURRENT_FORMAT_VERSION, LogLevel, StepType } from '../../definition/definition.types';
2
+ import type { RuntimeDefinition, Step } from '../../definition/definition.types';
3
+ import { RuntimeErrorCode } from '../../errors/runtime-error-code.enum';
4
+ import { EvaluationKind } from '../../runner-protocol/evaluation.types';
5
+ import { InterpreterError } from '../interpreter-error';
6
+ import { start, step } from '../interpreter';
7
+ import { CURRENT_STATE_VERSION, EffectType, RunEventType, RunStatus } from '../interpreter.types';
8
+ import type { RunOptions, RunState } from '../interpreter.types';
9
+ import { runToCompletion } from '../test-host';
10
+
11
+ const options = (overrides: Partial<RunOptions['budget']> = {}): RunOptions => ({
12
+ catalog: new Map(),
13
+ grants: [],
14
+ budget: { maxSteps: 100, maxEffects: 100, maxWaitMs: 1_000_000, ...overrides },
15
+ });
16
+
17
+ const definitionOf = (steps: Step[]): RuntimeDefinition => ({
18
+ formatVersion: CURRENT_FORMAT_VERSION,
19
+ accesses: [],
20
+ steps,
21
+ });
22
+
23
+ const thrownBy = (fn: () => unknown): unknown => {
24
+ try {
25
+ fn();
26
+ } catch (error) {
27
+ return error;
28
+ }
29
+ throw new Error('expected a throw');
30
+ };
31
+
32
+ describe('LOG step', () => {
33
+ const log: Step = {
34
+ id: 'log',
35
+ type: StepType.LOG,
36
+ level: LogLevel.WARN,
37
+ message: 'order {{ input.id }}',
38
+ data: { total: { $expression: 'input.total' }, fixed: 1 },
39
+ };
40
+
41
+ it('evaluates its message and data, then emits a LOG effect', () => {
42
+ const definition = definitionOf([log]);
43
+ const first = start(definition, { id: 7, total: 12 }, options());
44
+ expect(first.effects).toEqual([
45
+ expect.objectContaining({
46
+ type: EffectType.EVALUATE,
47
+ items: [
48
+ { id: 'message', kind: EvaluationKind.TEMPLATE, source: 'order {{ input.id }}' },
49
+ { id: 'data.total', kind: EvaluationKind.EXPRESSION, source: 'input.total' },
50
+ ],
51
+ }),
52
+ ]);
53
+ const second = step(
54
+ definition,
55
+ first.state,
56
+ {
57
+ type: RunEventType.EVALUATED,
58
+ results: [
59
+ { id: 'message', ok: true, value: 'order 7' },
60
+ { id: 'data.total', ok: true, value: 12 },
61
+ ],
62
+ },
63
+ options(),
64
+ );
65
+ expect(second.effects).toEqual([
66
+ {
67
+ type: EffectType.LOG,
68
+ stepId: 'log',
69
+ level: LogLevel.WARN,
70
+ message: 'order 7',
71
+ data: { total: 12, fixed: 1 },
72
+ },
73
+ ]);
74
+ const done = step(definition, second.state, { type: RunEventType.LOG_WRITTEN }, options());
75
+ expect(done.status).toBe(RunStatus.SUCCEEDED);
76
+ expect(done.state.outputs.log).toEqual({ output: null });
77
+ });
78
+
79
+ it('writes a non-string message as its JSON and omits absent data', () => {
80
+ const definition = definitionOf([
81
+ { id: 'log', type: StepType.LOG, level: LogLevel.INFO, message: { $expression: 'input' } },
82
+ ]);
83
+ const first = start(definition, null, options());
84
+ const second = step(
85
+ definition,
86
+ first.state,
87
+ { type: RunEventType.EVALUATED, results: [{ id: 'message', ok: true, value: { a: 1 } }] },
88
+ options(),
89
+ );
90
+ expect(second.effects).toEqual([
91
+ { type: EffectType.LOG, stepId: 'log', level: LogLevel.INFO, message: '{"a":1}' },
92
+ ]);
93
+ });
94
+
95
+ it('counts against the effect budget', () => {
96
+ const definition = definitionOf([
97
+ { id: 'a', type: StepType.LOG, level: LogLevel.INFO, message: 'a' },
98
+ { id: 'b', type: StepType.LOG, level: LogLevel.INFO, message: 'b' },
99
+ ]);
100
+ const first = start(definition, null, options({ maxEffects: 1 }));
101
+ const second = step(
102
+ definition,
103
+ first.state,
104
+ { type: RunEventType.LOG_WRITTEN },
105
+ options({ maxEffects: 1 }),
106
+ );
107
+ expect(second.status).toBe(RunStatus.FAILED);
108
+ expect(second.state.outcome?.error).toEqual(
109
+ expect.objectContaining({ code: RuntimeErrorCode.BUDGET_EXCEEDED, stepId: 'b' }),
110
+ );
111
+ });
112
+ });
113
+
114
+ describe('RESPOND step', () => {
115
+ it('emits the response with string headers, and the run goes on after it', async () => {
116
+ const definition = definitionOf([
117
+ {
118
+ id: 'reply',
119
+ type: StepType.RESPOND,
120
+ status: 201,
121
+ headers: { 'X-Count': 3, 'Content-Type': 'application/json' },
122
+ body: { ok: true },
123
+ },
124
+ { id: 'after', type: StepType.SET, variable: 'x', value: 1 },
125
+ ]);
126
+ const responses: unknown[] = [];
127
+ const { state, effects } = await runToCompletion(definition, null, options(), {
128
+ evaluate: () => [],
129
+ respond: (effect) => {
130
+ responses.push(effect.response);
131
+ },
132
+ });
133
+ expect(effects.map((effect) => effect.type)).toEqual([EffectType.RESPOND]);
134
+ expect(responses).toEqual([
135
+ {
136
+ status: 201,
137
+ headers: { 'X-Count': '3', 'Content-Type': 'application/json' },
138
+ body: { ok: true },
139
+ },
140
+ ]);
141
+ expect(state.status).toBe(RunStatus.SUCCEEDED);
142
+ expect(state.outputs.reply).toEqual({ output: null });
143
+ expect(state.vars.x).toBe(1);
144
+ });
145
+
146
+ it('fails the step when the status does not resolve to an HTTP status', () => {
147
+ const definition = definitionOf([
148
+ { id: 'reply', type: StepType.RESPOND, status: { $expression: 'input.status' } },
149
+ ]);
150
+ const first = start(definition, null, options());
151
+ const second = step(
152
+ definition,
153
+ first.state,
154
+ { type: RunEventType.EVALUATED, results: [{ id: 'status', ok: true, value: 700 }] },
155
+ options(),
156
+ );
157
+ expect(second.status).toBe(RunStatus.FAILED);
158
+ expect(second.state.outcome?.error).toEqual(
159
+ expect.objectContaining({ code: RuntimeErrorCode.EXPRESSION_ERROR, stepId: 'reply' }),
160
+ );
161
+ });
162
+
163
+ it('refuses a RESPONSE_SENT event for another pending effect', () => {
164
+ const definition = definitionOf([{ id: 'w', type: StepType.WAIT, durationMs: 10 }]);
165
+ const first = start(definition, null, options());
166
+ const error = thrownBy(() =>
167
+ step(definition, first.state, { type: RunEventType.RESPONSE_SENT }, options()),
168
+ );
169
+ expect(error).toBeInstanceOf(InterpreterError);
170
+ });
171
+ });
172
+
173
+ describe('resume and state version', () => {
174
+ const definition = definitionOf([
175
+ { id: 'approve', type: StepType.WAIT, durationMs: 500 },
176
+ {
177
+ id: 'after',
178
+ type: StepType.SET,
179
+ variable: 'v',
180
+ value: { $expression: 'steps.approve.output' },
181
+ },
182
+ ]);
183
+
184
+ it('stamps every new state with the current state version', () => {
185
+ expect(CURRENT_STATE_VERSION).toBe(1);
186
+ expect(start(definition, null, options()).state.stateVersion).toBe(CURRENT_STATE_VERSION);
187
+ });
188
+
189
+ it('gives a RESUMED output to the step that suspended', () => {
190
+ const first = start(definition, null, options());
191
+ const persisted = JSON.parse(JSON.stringify(first.state)) as RunState;
192
+ const resumed = step(
193
+ definition,
194
+ persisted,
195
+ { type: RunEventType.RESUMED, output: { approved: true } },
196
+ options(),
197
+ );
198
+ expect(resumed.state.outputs.approve).toEqual({ output: { approved: true } });
199
+ expect(resumed.effects).toEqual([
200
+ expect.objectContaining({ type: EffectType.EVALUATE, stepId: 'after' }),
201
+ ]);
202
+ });
203
+
204
+ it('refuses RESUMED while an evaluation is pending', () => {
205
+ const evaluating = definitionOf([{ id: 'c', type: StepType.CODE, source: 'return 1;' }]);
206
+ const first = start(evaluating, null, options());
207
+ const error = thrownBy(() =>
208
+ step(evaluating, first.state, { type: RunEventType.RESUMED, output: 1 }, options()),
209
+ );
210
+ expect(error).toBeInstanceOf(InterpreterError);
211
+ expect((error as InterpreterError).code).toBe(RuntimeErrorCode.INVALID_REQUEST);
212
+ });
213
+
214
+ it('refuses a state of an unknown version', () => {
215
+ const first = start(definition, null, options());
216
+ const future = { ...first.state, stateVersion: CURRENT_STATE_VERSION + 1 };
217
+ const error = thrownBy(() =>
218
+ step(definition, future, { type: RunEventType.WAIT_ELAPSED }, options()),
219
+ );
220
+ expect(error).toBeInstanceOf(InterpreterError);
221
+ expect((error as InterpreterError).code).toBe(RuntimeErrorCode.STATE_VERSION_UNSUPPORTED);
222
+ });
223
+ });
@@ -0,0 +1,12 @@
1
+ import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
+
3
+ /** Thrown for a misuse of the interpreter (unexpected event, corrupted state), never for a run failure. */
4
+ export class InterpreterError extends Error {
5
+ readonly code: RuntimeErrorCode;
6
+
7
+ constructor(code: RuntimeErrorCode, message: string) {
8
+ super(message);
9
+ this.name = 'InterpreterError';
10
+ this.code = code;
11
+ }
12
+ }
@@ -0,0 +1,461 @@
1
+ import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
+ import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
3
+ import { MAX_WAIT_DURATION_MS } from '../definition/definition.limits';
4
+ import { CURRENT_FORMAT_VERSION, StopStatus } from '../definition/definition.types';
5
+ import type { RuntimeDefinition, Step } from '../definition/definition.types';
6
+ import { StepActionKind, executeStep } from '../steps/execute-step';
7
+ import type { StepAction } from '../steps/execute-step';
8
+ import { collectStepItems, resolveStepFields } from '../steps/step-fields';
9
+ import { AccessVerdict, checkHostActionAccess, checkHttpAccess } from '../steps/step-access';
10
+ import { InterpreterError } from './interpreter-error';
11
+ import { CURRENT_STATE_VERSION, EffectType, RunEventType, RunStatus } from './interpreter.types';
12
+ import type {
13
+ Effect,
14
+ LogEffect,
15
+ RunBudget,
16
+ RunEvent,
17
+ RunOptions,
18
+ RunState,
19
+ StepResult,
20
+ WaitEffect,
21
+ } from './interpreter.types';
22
+ import { ROOT_SEQUENCE_PATH, branchPath, resolveSequence, resolveStep } from './sequence-path';
23
+
24
+ const NO_RESULTS: ReadonlyMap<string, unknown> = new Map();
25
+
26
+ export type HostInputCheck = { input: Record<string, unknown> } | { error: RuntimeErrorDetail };
27
+
28
+ /**
29
+ * What the interpreter asks about a run. `start`/`step` build it from `RunOptions` (declarations,
30
+ * grants and catalog, on the host); the isolate engine builds it from the capabilities the host
31
+ * exposed (`engine/run-in-isolate.ts`).
32
+ */
33
+ export interface RunPolicy {
34
+ budget: RunBudget;
35
+ httpAccess: (url: string) => AccessVerdict;
36
+ hostActionAccess: (action: string) => AccessVerdict;
37
+ /** Validates the resolved input of a host action; may normalize it. */
38
+ hostInput: (action: string, input: Record<string, unknown>) => HostInputCheck;
39
+ }
40
+
41
+ export type StepFinish = { ok: true; output: unknown } | { ok: false; error: RuntimeErrorDetail };
42
+
43
+ /** Told when a step starts and when it ends; a step that emitted an effect ends with its answer. */
44
+ export interface StepObserver {
45
+ stepStarted: (stepId: string) => void;
46
+ stepFinished: (stepId: string, finish: StepFinish) => void;
47
+ }
48
+
49
+ const SILENT_OBSERVER: StepObserver = {
50
+ stepStarted: () => undefined,
51
+ stepFinished: () => undefined,
52
+ };
53
+
54
+ interface RunContext {
55
+ definition: RuntimeDefinition;
56
+ policy: RunPolicy;
57
+ observer: StepObserver;
58
+ }
59
+
60
+ const invalidRequest = (message: string): InterpreterError =>
61
+ new InterpreterError(RuntimeErrorCode.INVALID_REQUEST, message);
62
+
63
+ /** A copy whose containers can be changed freely; the caller's state is never touched. */
64
+ const draftOf = (state: RunState): RunState => ({
65
+ ...state,
66
+ stack: state.stack.map((frame) => ({ ...frame })),
67
+ outputs: { ...state.outputs },
68
+ vars: { ...state.vars },
69
+ counters: { ...state.counters },
70
+ });
71
+
72
+ /** Own, enumerable data property: unlike `target[key] = value`, a key such as `__proto__` stays a key. */
73
+ const setOwn = <T>(target: Record<string, T>, key: string, value: T): void => {
74
+ Object.defineProperty(target, key, {
75
+ value,
76
+ writable: true,
77
+ enumerable: true,
78
+ configurable: true,
79
+ });
80
+ };
81
+
82
+ const topFrame = (draft: RunState) => draft.stack[draft.stack.length - 1];
83
+
84
+ const advance = (draft: RunState): void => {
85
+ topFrame(draft).index += 1;
86
+ };
87
+
88
+ const settle = (draft: RunState, status: RunStatus): StepResult => {
89
+ draft.status = status;
90
+ draft.pending = null;
91
+ return { state: draft, effects: [], status };
92
+ };
93
+
94
+ const failRun = (
95
+ context: RunContext,
96
+ draft: RunState,
97
+ error: RuntimeErrorDetail,
98
+ stepId: string,
99
+ ): StepResult => {
100
+ draft.outcome = { status: StopStatus.FAILED, error: { ...error, stepId } };
101
+ context.observer.stepFinished(stepId, { ok: false, error });
102
+ return settle(draft, RunStatus.FAILED);
103
+ };
104
+
105
+ const emit = (context: RunContext, draft: RunState, effect: Effect): StepResult => {
106
+ if (draft.counters.effects + 1 > context.policy.budget.maxEffects) {
107
+ return failRun(
108
+ context,
109
+ draft,
110
+ { code: RuntimeErrorCode.BUDGET_EXCEEDED, message: 'Effect budget exceeded' },
111
+ effect.stepId,
112
+ );
113
+ }
114
+ draft.counters.effects += 1;
115
+ draft.pending = effect;
116
+ draft.status = RunStatus.WAITING;
117
+ return { state: draft, effects: [effect], status: RunStatus.WAITING };
118
+ };
119
+
120
+ const accessDenied = (verdict: AccessVerdict, subject: string): RuntimeErrorDetail => ({
121
+ code: RuntimeErrorCode.ACCESS_DENIED,
122
+ message:
123
+ verdict === AccessVerdict.NOT_DECLARED
124
+ ? `${subject} is not declared by the definition`
125
+ : `${subject} is not granted to the run`,
126
+ });
127
+
128
+ const validateHostInput = (
129
+ options: RunOptions,
130
+ action: string,
131
+ input: Record<string, unknown>,
132
+ ): HostInputCheck => {
133
+ const definition = options.catalog.get(action);
134
+ if (!definition) {
135
+ return {
136
+ error: { code: RuntimeErrorCode.HOST_ERROR, message: 'Host action is not in the catalog' },
137
+ };
138
+ }
139
+ const { error, value } = definition.inputSchema.validate(input, { abortEarly: false });
140
+ if (error) {
141
+ const reasons = error.details.map((detail) => detail.message).join('; ');
142
+ return {
143
+ error: {
144
+ code: RuntimeErrorCode.HOST_ERROR,
145
+ message: `Invalid host action input: ${reasons}`,
146
+ },
147
+ };
148
+ }
149
+ return { input: value as Record<string, unknown> };
150
+ };
151
+
152
+ /** Host-side policy: the definition's declarations AND the run's grants, the product's catalog. */
153
+ const hostPolicy = (definition: RuntimeDefinition, options: RunOptions): RunPolicy => ({
154
+ budget: options.budget,
155
+ httpAccess: (url) => checkHttpAccess(url, definition.accesses, options.grants),
156
+ hostActionAccess: (action) => checkHostActionAccess(action, definition.accesses, options.grants),
157
+ hostInput: (action, input) => validateHostInput(options, action, input),
158
+ });
159
+
160
+ const applyAction = (
161
+ context: RunContext,
162
+ draft: RunState,
163
+ step: Step,
164
+ action: StepAction,
165
+ ): StepResult | null => {
166
+ const { policy, observer } = context;
167
+ switch (action.kind) {
168
+ case StepActionKind.FAIL:
169
+ return failRun(context, draft, action.error, step.id);
170
+ case StepActionKind.STOP:
171
+ draft.outcome = { status: action.status, output: action.output };
172
+ observer.stepFinished(step.id, { ok: true, output: action.output });
173
+ return settle(
174
+ draft,
175
+ action.status === StopStatus.SUCCEEDED ? RunStatus.SUCCEEDED : RunStatus.FAILED,
176
+ );
177
+ case StepActionKind.DONE: {
178
+ setOwn(draft.outputs, step.id, { output: action.output });
179
+ observer.stepFinished(step.id, { ok: true, output: action.output });
180
+ if (action.variable) {
181
+ setOwn(draft.vars, action.variable.name, action.variable.value);
182
+ }
183
+ if (action.branch === undefined) {
184
+ advance(draft);
185
+ } else {
186
+ draft.stack.push({ sequencePath: branchPath(topFrame(draft), action.branch), index: 0 });
187
+ }
188
+ return null;
189
+ }
190
+ case StepActionKind.WAIT: {
191
+ // A host budget never loosens the bound the validation applies to a literal duration.
192
+ const maxWaitMs = Math.min(policy.budget.maxWaitMs, MAX_WAIT_DURATION_MS);
193
+ if (action.durationMs !== undefined && action.durationMs > maxWaitMs) {
194
+ return failRun(
195
+ context,
196
+ draft,
197
+ {
198
+ code: RuntimeErrorCode.BUDGET_EXCEEDED,
199
+ message: `Wait duration exceeds the budget of ${maxWaitMs} ms`,
200
+ },
201
+ step.id,
202
+ );
203
+ }
204
+ const effect: WaitEffect = { type: EffectType.WAIT, stepId: step.id };
205
+ if (action.durationMs !== undefined) {
206
+ effect.durationMs = action.durationMs;
207
+ }
208
+ if (action.until !== undefined) {
209
+ effect.until = action.until;
210
+ }
211
+ return emit(context, draft, effect);
212
+ }
213
+ case StepActionKind.HTTP: {
214
+ const verdict = policy.httpAccess(action.request.url);
215
+ if (verdict !== AccessVerdict.ALLOWED) {
216
+ return failRun(context, draft, accessDenied(verdict, 'HTTP request host'), step.id);
217
+ }
218
+ return emit(context, draft, {
219
+ type: EffectType.HTTP,
220
+ stepId: step.id,
221
+ request: action.request,
222
+ });
223
+ }
224
+ case StepActionKind.HOST: {
225
+ const verdict = policy.hostActionAccess(action.action);
226
+ if (verdict !== AccessVerdict.ALLOWED) {
227
+ return failRun(context, draft, accessDenied(verdict, 'Host action'), step.id);
228
+ }
229
+ const validated = policy.hostInput(action.action, action.input);
230
+ if ('error' in validated) {
231
+ return failRun(context, draft, validated.error, step.id);
232
+ }
233
+ return emit(context, draft, {
234
+ type: EffectType.HOST,
235
+ stepId: step.id,
236
+ action: action.action,
237
+ input: validated.input,
238
+ });
239
+ }
240
+ // Logging and responding are granted to every run; the host bounds them (one response).
241
+ case StepActionKind.LOG: {
242
+ const effect: LogEffect = {
243
+ type: EffectType.LOG,
244
+ stepId: step.id,
245
+ level: action.level,
246
+ message: action.message,
247
+ };
248
+ if ('data' in action) {
249
+ effect.data = action.data;
250
+ }
251
+ return emit(context, draft, effect);
252
+ }
253
+ case StepActionKind.RESPOND:
254
+ return emit(context, draft, {
255
+ type: EffectType.RESPOND,
256
+ stepId: step.id,
257
+ response: action.response,
258
+ });
259
+ }
260
+ };
261
+
262
+ /**
263
+ * Runs the current step: evaluates it first when it has non-literal values (`results` undefined),
264
+ * then applies it. Returns null when the step finished and the run goes on.
265
+ */
266
+ const runStep = (
267
+ context: RunContext,
268
+ draft: RunState,
269
+ step: Step,
270
+ results: ReadonlyMap<string, unknown> | undefined,
271
+ ): StepResult | null => {
272
+ if (results === undefined) {
273
+ const items = collectStepItems(step);
274
+ if (items.length > 0) {
275
+ return emit(context, draft, {
276
+ type: EffectType.EVALUATE,
277
+ stepId: step.id,
278
+ items,
279
+ context: { input: draft.input, steps: draft.outputs, vars: draft.vars },
280
+ });
281
+ }
282
+ }
283
+ const fields = resolveStepFields(step, results ?? NO_RESULTS);
284
+ return applyAction(context, draft, step, executeStep(step, fields));
285
+ };
286
+
287
+ /** Enters steps one after the other until an effect is emitted or the run ends. */
288
+ const drive = (context: RunContext, draft: RunState): StepResult => {
289
+ for (;;) {
290
+ const frame = topFrame(draft);
291
+ if (!frame) {
292
+ draft.outcome = { status: StopStatus.SUCCEEDED };
293
+ return settle(draft, RunStatus.SUCCEEDED);
294
+ }
295
+ const sequence = resolveSequence(context.definition, frame.sequencePath);
296
+ if (frame.index >= sequence.length) {
297
+ draft.stack.pop();
298
+ if (draft.stack.length > 0) {
299
+ advance(draft);
300
+ }
301
+ continue;
302
+ }
303
+ const step = sequence[frame.index];
304
+ context.observer.stepStarted(step.id);
305
+ if (draft.counters.steps + 1 > context.policy.budget.maxSteps) {
306
+ return failRun(
307
+ context,
308
+ draft,
309
+ { code: RuntimeErrorCode.BUDGET_EXCEEDED, message: 'Step budget exceeded' },
310
+ step.id,
311
+ );
312
+ }
313
+ draft.counters.steps += 1;
314
+ const result = runStep(context, draft, step, undefined);
315
+ if (result) {
316
+ return result;
317
+ }
318
+ }
319
+ };
320
+
321
+ /** `start` with an explicit policy and observer: the entry of the isolate engine. */
322
+ export const startRun = (
323
+ definition: RuntimeDefinition,
324
+ input: unknown,
325
+ policy: RunPolicy,
326
+ observer: StepObserver = SILENT_OBSERVER,
327
+ ): StepResult =>
328
+ drive(
329
+ { definition, policy, observer },
330
+ {
331
+ stateVersion: CURRENT_STATE_VERSION,
332
+ formatVersion: CURRENT_FORMAT_VERSION,
333
+ status: RunStatus.WAITING,
334
+ input,
335
+ stack: [{ sequencePath: ROOT_SEQUENCE_PATH, index: 0 }],
336
+ outputs: {},
337
+ vars: {},
338
+ pending: null,
339
+ counters: { steps: 0, effects: 0 },
340
+ },
341
+ );
342
+
343
+ export const start = (
344
+ definition: RuntimeDefinition,
345
+ input: unknown,
346
+ options: RunOptions,
347
+ ): StepResult => startRun(definition, input, hostPolicy(definition, options));
348
+
349
+ const unexpected = (event: RunEvent, pending: Effect): InterpreterError =>
350
+ invalidRequest(`Event ${event.type} does not answer the pending ${pending.type} effect`);
351
+
352
+ /** Maps each item id to its value, or returns the first failing item's error. */
353
+ const readEvaluation = (
354
+ pending: Effect,
355
+ results: Extract<RunEvent, { type: RunEventType.EVALUATED }>['results'],
356
+ ): ReadonlyMap<string, unknown> | RuntimeErrorDetail => {
357
+ if (pending.type !== EffectType.EVALUATE) {
358
+ throw invalidRequest(
359
+ `Event ${RunEventType.EVALUATED} does not answer the pending ${pending.type} effect`,
360
+ );
361
+ }
362
+ const values = new Map<string, unknown>();
363
+ for (const item of pending.items) {
364
+ const result = results.find((candidate) => candidate.id === item.id);
365
+ if (!result) {
366
+ throw invalidRequest('Evaluation results do not cover every item of the lot');
367
+ }
368
+ if (!result.ok) {
369
+ return result.error;
370
+ }
371
+ values.set(item.id, result.value);
372
+ }
373
+ return values;
374
+ };
375
+
376
+ const complete = (
377
+ context: RunContext,
378
+ draft: RunState,
379
+ step: Step,
380
+ output: unknown,
381
+ ): StepResult => {
382
+ setOwn(draft.outputs, step.id, { output });
383
+ context.observer.stepFinished(step.id, { ok: true, output });
384
+ advance(draft);
385
+ return drive(context, draft);
386
+ };
387
+
388
+ /** `step` with an explicit policy and observer: the entry of the isolate engine. */
389
+ export const stepRun = (
390
+ definition: RuntimeDefinition,
391
+ state: RunState,
392
+ event: RunEvent,
393
+ policy: RunPolicy,
394
+ observer: StepObserver = SILENT_OBSERVER,
395
+ ): StepResult => {
396
+ if (state.stateVersion !== CURRENT_STATE_VERSION) {
397
+ throw new InterpreterError(
398
+ RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
399
+ `Run state version ${String(state.stateVersion)} is not supported ` +
400
+ `(this core reads version ${CURRENT_STATE_VERSION})`,
401
+ );
402
+ }
403
+ const pending = state.pending;
404
+ if (state.status !== RunStatus.WAITING || !pending) {
405
+ throw invalidRequest(`Event ${event.type} received by a run that waits for nothing`);
406
+ }
407
+ const context: RunContext = { definition, policy, observer };
408
+ const draft = draftOf(state);
409
+ draft.pending = null;
410
+ const current = resolveStep(definition, topFrame(draft));
411
+
412
+ switch (event.type) {
413
+ case RunEventType.EVALUATED: {
414
+ const values = readEvaluation(pending, event.results);
415
+ if (!(values instanceof Map)) {
416
+ return failRun(context, draft, values as RuntimeErrorDetail, current.id);
417
+ }
418
+ return runStep(context, draft, current, values) ?? drive(context, draft);
419
+ }
420
+ case RunEventType.HTTP_COMPLETED:
421
+ if (pending.type !== EffectType.HTTP) {
422
+ throw unexpected(event, pending);
423
+ }
424
+ return complete(context, draft, current, event.response);
425
+ case RunEventType.HOST_COMPLETED:
426
+ if (pending.type !== EffectType.HOST) {
427
+ throw unexpected(event, pending);
428
+ }
429
+ return complete(context, draft, current, event.output);
430
+ case RunEventType.WAIT_ELAPSED:
431
+ if (pending.type !== EffectType.WAIT) {
432
+ throw unexpected(event, pending);
433
+ }
434
+ return complete(context, draft, current, null);
435
+ case RunEventType.LOG_WRITTEN:
436
+ if (pending.type !== EffectType.LOG) {
437
+ throw unexpected(event, pending);
438
+ }
439
+ return complete(context, draft, current, null);
440
+ case RunEventType.RESPONSE_SENT:
441
+ if (pending.type !== EffectType.RESPOND) {
442
+ throw unexpected(event, pending);
443
+ }
444
+ return complete(context, draft, current, null);
445
+ case RunEventType.RESUMED:
446
+ // A run suspends between steps, never while an evaluation is in flight.
447
+ if (pending.type === EffectType.EVALUATE) {
448
+ throw unexpected(event, pending);
449
+ }
450
+ return complete(context, draft, current, event.output);
451
+ case RunEventType.EFFECT_FAILED:
452
+ return failRun(context, draft, event.error, current.id);
453
+ }
454
+ };
455
+
456
+ export const step = (
457
+ definition: RuntimeDefinition,
458
+ state: RunState,
459
+ event: RunEvent,
460
+ options: RunOptions,
461
+ ): StepResult => stepRun(definition, state, event, hostPolicy(definition, options));