@abyss-project/runtime 3.0.0 → 3.1.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.
- package/README.md +27 -0
- package/dist/discord/discord.types.d.ts +123 -0
- package/dist/discord/discord.types.js +53 -0
- package/dist/discord/discord.types.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
- package/package.json +1 -1
- package/scripts/build-engine.cjs +70 -70
- package/src/__tests__/engine-bundle.test.ts +121 -121
- package/src/cost/__tests__/execution-cost.test.ts +196 -196
- package/src/cost/execution-cost.ts +186 -186
- package/src/definition/__tests__/validate-definition.test.ts +354 -354
- package/src/definition/definition.limits.ts +9 -9
- package/src/definition/definition.schema.ts +172 -172
- package/src/definition/definition.types.ts +171 -171
- package/src/discord/discord.types.ts +155 -0
- package/src/engine/__tests__/run-in-isolate.test.ts +468 -468
- package/src/engine/engine-entry.ts +3 -3
- package/src/engine/engine-global.ts +2 -2
- package/src/engine/run-in-isolate.ts +404 -404
- package/src/errors/runtime-error-code.enum.ts +37 -37
- package/src/index.ts +31 -30
- package/src/interpreter/__tests__/interpreter.test.ts +854 -854
- package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -223
- package/src/interpreter/interpreter.ts +461 -461
- package/src/interpreter/interpreter.types.ts +192 -192
- package/src/interpreter/test-host.ts +85 -85
- package/src/runner-protocol/evaluation.types.ts +21 -21
- package/src/runner-protocol/execution-protocol.types.ts +231 -225
- package/src/server/__tests__/code-runner-session.test.ts +311 -311
- package/src/server/code-runner-error.ts +12 -12
- package/src/server/code-runner-session.ts +310 -310
- package/src/server/index.ts +11 -11
- package/src/steps/__tests__/global-references.test.ts +133 -113
- package/src/steps/execute-step.ts +186 -186
- package/src/steps/global-references.ts +48 -48
- package/src/steps/step-access.ts +56 -56
- package/src/steps/step-fields.ts +87 -87
- package/src/steps/value-source.ts +69 -69
|
@@ -1,404 +1,404 @@
|
|
|
1
|
-
// The interpreter driver that runs INSIDE the execution's isolate (ADR-
|
|
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
|
+
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
|
+
};
|