@abyss-project/runtime 3.7.0 → 3.8.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 (55) hide show
  1. package/.eslintrc.js +32 -32
  2. package/.prettierrc +5 -5
  3. package/README.md +88 -88
  4. package/dist/engine/engine-source.js +1 -1
  5. package/dist/engine/run-in-isolate.js +32 -2
  6. package/dist/engine/run-in-isolate.js.map +1 -1
  7. package/dist/runner-protocol/execution-protocol.types.d.ts +2 -0
  8. package/dist/runner-protocol/execution-protocol.types.js +2 -1
  9. package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
  10. package/jest.config.ts +11 -11
  11. package/package.json +10 -15
  12. package/scripts/build-engine.cjs +70 -70
  13. package/src/__tests__/engine-bundle.test.ts +121 -121
  14. package/src/__tests__/surface.test.ts +12 -1
  15. package/src/access/__tests__/host-match.test.ts +24 -24
  16. package/src/access/access.types.ts +25 -25
  17. package/src/access/host-match.ts +13 -13
  18. package/src/cost/__tests__/execution-cost.test.ts +196 -196
  19. package/src/cost/execution-cost.ts +186 -186
  20. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  21. package/src/definition/definition.limits.ts +9 -9
  22. package/src/definition/definition.schema.ts +172 -172
  23. package/src/definition/definition.types.ts +171 -171
  24. package/src/definition/validate-definition.ts +206 -206
  25. package/src/definition/walk-steps.ts +44 -44
  26. package/src/discord/__tests__/discord-event-input.test.ts +89 -89
  27. package/src/discord/discord.types.ts +639 -639
  28. package/src/engine/__tests__/run-in-isolate.test.ts +56 -5
  29. package/src/engine/engine-entry.ts +3 -3
  30. package/src/engine/engine-global.ts +2 -2
  31. package/src/engine/run-in-isolate.ts +47 -4
  32. package/src/errors/runtime-error-code.enum.ts +37 -37
  33. package/src/index.ts +32 -32
  34. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  35. package/src/interpreter/__tests__/log-respond-resume.test.ts +271 -271
  36. package/src/interpreter/interpreter-error.ts +12 -12
  37. package/src/interpreter/interpreter.ts +483 -483
  38. package/src/interpreter/interpreter.types.ts +204 -204
  39. package/src/interpreter/sequence-path.ts +67 -67
  40. package/src/interpreter/test-host.ts +85 -85
  41. package/src/runner-protocol/evaluation.types.ts +21 -21
  42. package/src/runner-protocol/execution-protocol.types.ts +20 -3
  43. package/src/schedule/schedule.types.ts +100 -100
  44. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  45. package/src/server/code-runner-error.ts +12 -12
  46. package/src/server/code-runner-session.ts +310 -310
  47. package/src/server/index.ts +11 -11
  48. package/src/steps/__tests__/global-references.test.ts +133 -133
  49. package/src/steps/execute-step.ts +186 -186
  50. package/src/steps/global-references.ts +48 -48
  51. package/src/steps/step-access.ts +56 -56
  52. package/src/steps/step-fields.ts +87 -87
  53. package/src/steps/value-source.ts +69 -69
  54. package/tsconfig.check.json +15 -15
  55. package/tsconfig.json +35 -35
@@ -1,310 +1,310 @@
1
- import { WebSocket } from 'ws';
2
- import type { RawData } from 'ws';
3
- import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
4
- import {
5
- EXECUTION_PROTOCOL,
6
- ExecutionMessageType,
7
- ExecutionStatus,
8
- StepPhase,
9
- } from '../runner-protocol/execution-protocol.types';
10
- import type {
11
- CallError,
12
- ExecuteMessage,
13
- ExecutionCallMessage,
14
- ExecutionCallResultMessage,
15
- ExecutionRejectedMessage,
16
- ExecutionRunnerMessage,
17
- FinishedMessage,
18
- ProgressMessage,
19
- } from '../runner-protocol/execution-protocol.types';
20
- import { CodeRunnerError } from './code-runner-error';
21
-
22
- export interface CodeRunnerSessionOptions {
23
- /** `ws://` or `wss://` URL of the code runner. */
24
- url: string;
25
- /** Bearer token the runner knows by fingerprint. */
26
- token: string;
27
- /** Maximum time to open the connection; past it the execution fails with RUNNER_UNAVAILABLE. */
28
- connectTimeoutMs: number;
29
- /**
30
- * Added to `limits.wallTimeMs` once the connection is open: time the runner may spend
31
- * queueing the execution and reporting its end. Past the sum, the execution fails with
32
- * TIMEOUT and the connection is closed, which stops the execution in the runner.
33
- */
34
- wallTimeGraceMs: number;
35
- }
36
-
37
- export interface CapabilityContext {
38
- /** The step that made the call. */
39
- stepId: string;
40
- }
41
-
42
- /**
43
- * One handler per capability the execution may call; their names are the `capabilities` sent
44
- * to the runner. A handler resolves the call's value, resolves `SUSPEND_EXECUTION` to suspend
45
- * the execution after this step, or throws (a `CapabilityError` to choose the error code).
46
- */
47
- export type CapabilityHandlers = Record<
48
- string,
49
- (args: unknown, context: CapabilityContext) => Promise<unknown>
50
- >;
51
-
52
- /** Resolved by a capability handler: the runner finishes SUSPENDED after the calling step. */
53
- export const SUSPEND_EXECUTION: unique symbol = Symbol('abyss-runtime.suspend-execution');
54
-
55
- /** Thrown by a capability handler to fail the call with a given code (ACCESS_DENIED...). */
56
- export class CapabilityError extends Error {
57
- public readonly code: RuntimeErrorCode;
58
-
59
- constructor(code: RuntimeErrorCode, message: string) {
60
- super(message);
61
- this.name = 'CapabilityError';
62
- this.code = code;
63
- }
64
- }
65
-
66
- /** What the host sends; `capabilities` is derived from the handlers. */
67
- export type ExecutionRequest = Omit<ExecuteMessage, 'type' | 'capabilities'>;
68
-
69
- export interface ExecuteOptions {
70
- onProgress?: (progress: Omit<ProgressMessage, 'type'>) => void;
71
- /** Aborting closes the connection, which stops the execution; the promise rejects with the signal's reason. */
72
- signal?: AbortSignal;
73
- }
74
-
75
- export type ExecutionResult = Omit<FinishedMessage, 'type'>;
76
-
77
- const REJECTION_CODES = new Set<string>([
78
- RuntimeErrorCode.RUNNER_SATURATED,
79
- RuntimeErrorCode.INVALID_REQUEST,
80
- RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
81
- ]);
82
- const EXECUTION_STATUSES = new Set<string>(Object.values(ExecutionStatus));
83
- const STEP_PHASES = new Set<string>(Object.values(StepPhase));
84
-
85
- const isRecord = (value: unknown): value is Record<string, unknown> =>
86
- typeof value === 'object' && value !== null && !Array.isArray(value);
87
-
88
- const malformed = (type: string): Error =>
89
- new Error(`Code runner sent a malformed "${type}" message`);
90
-
91
- const parseRunnerMessage = (raw: RawData): ExecutionRunnerMessage => {
92
- let parsed: unknown;
93
- try {
94
- parsed = JSON.parse(raw.toString());
95
- } catch {
96
- throw new Error('Code runner sent a message that is not valid JSON');
97
- }
98
- if (!isRecord(parsed)) {
99
- throw new Error('Code runner sent a message that is not an object');
100
- }
101
- switch (parsed.type) {
102
- case ExecutionMessageType.CALL:
103
- if (
104
- typeof parsed.callId !== 'string' ||
105
- typeof parsed.stepId !== 'string' ||
106
- typeof parsed.capability !== 'string'
107
- ) {
108
- throw malformed(parsed.type);
109
- }
110
- return parsed as unknown as ExecutionCallMessage;
111
- case ExecutionMessageType.PROGRESS:
112
- if (typeof parsed.stepId !== 'string' || !STEP_PHASES.has(parsed.phase as string)) {
113
- throw malformed(parsed.type);
114
- }
115
- return parsed as unknown as ProgressMessage;
116
- case ExecutionMessageType.FINISHED:
117
- if (
118
- !isRecord(parsed.outcome) ||
119
- !EXECUTION_STATUSES.has(parsed.outcome.status as string) ||
120
- !isRecord(parsed.metrics)
121
- ) {
122
- throw malformed(parsed.type);
123
- }
124
- return parsed as unknown as FinishedMessage;
125
- case ExecutionMessageType.REJECTED:
126
- if (!REJECTION_CODES.has(parsed.code as string) || typeof parsed.message !== 'string') {
127
- throw malformed(parsed.type);
128
- }
129
- return parsed as unknown as ExecutionRejectedMessage;
130
- default:
131
- throw new Error('Code runner sent a message of unknown type');
132
- }
133
- };
134
-
135
- const errorMessage = (error: unknown): string =>
136
- error instanceof Error ? error.message : String(error);
137
-
138
- const callErrorOf = (error: unknown): CallError =>
139
- error instanceof CapabilityError
140
- ? { code: error.code, message: error.message }
141
- : { message: errorMessage(error) };
142
-
143
- const abortReason = (signal: AbortSignal): unknown =>
144
- signal.reason ?? new Error('The execution was aborted');
145
-
146
- /**
147
- * Node client of the code runner for `abyss-runtime.v2`: one WebSocket connection per
148
- * execution, one `execute`, the runner's calls served by the host's capability handlers.
149
- */
150
- export class CodeRunnerSession {
151
- private readonly options: CodeRunnerSessionOptions;
152
-
153
- constructor(options: CodeRunnerSessionOptions) {
154
- this.options = options;
155
- }
156
-
157
- public execute(
158
- request: ExecutionRequest,
159
- handlers: CapabilityHandlers,
160
- executeOptions: ExecuteOptions = {},
161
- ): Promise<ExecutionResult> {
162
- const { url, token, connectTimeoutMs, wallTimeGraceMs } = this.options;
163
- const { onProgress, signal } = executeOptions;
164
- if (signal?.aborted) {
165
- return Promise.reject(abortReason(signal));
166
- }
167
-
168
- return new Promise<ExecutionResult>((resolve, reject) => {
169
- let settled = false;
170
- let wallTimer: ReturnType<typeof setTimeout> | undefined;
171
- const ws = new WebSocket(url, EXECUTION_PROTOCOL, {
172
- headers: { Authorization: `Bearer ${token}` },
173
- handshakeTimeout: connectTimeoutMs,
174
- });
175
-
176
- const onAbort = (): void => finish(() => reject(abortReason(signal as AbortSignal)));
177
-
178
- function finish(outcome: () => void): void {
179
- if (settled) {
180
- return;
181
- }
182
- settled = true;
183
- clearTimeout(connectTimer);
184
- clearTimeout(wallTimer);
185
- signal?.removeEventListener('abort', onAbort);
186
- if (ws.readyState === WebSocket.OPEN) {
187
- ws.close();
188
- } else {
189
- ws.terminate();
190
- }
191
- outcome();
192
- }
193
- const fail = (code: RuntimeErrorCode, message: string): void =>
194
- finish(() => reject(new CodeRunnerError(code, message)));
195
- const unavailable = (message: string): void =>
196
- fail(RuntimeErrorCode.RUNNER_UNAVAILABLE, message);
197
-
198
- const connectTimer = setTimeout(
199
- () =>
200
- unavailable(`Code runner did not accept the connection within ${connectTimeoutMs} ms`),
201
- connectTimeoutMs,
202
- );
203
- signal?.addEventListener('abort', onAbort, { once: true });
204
-
205
- const send = (message: ExecuteMessage | ExecutionCallResultMessage): void => {
206
- if (!settled && ws.readyState === WebSocket.OPEN) {
207
- ws.send(JSON.stringify(message));
208
- }
209
- };
210
-
211
- const serveCall = async (call: ExecutionCallMessage): Promise<void> => {
212
- const handler = Object.prototype.hasOwnProperty.call(handlers, call.capability)
213
- ? handlers[call.capability]
214
- : undefined;
215
- if (!handler) {
216
- send({
217
- type: ExecutionMessageType.CALL_RESULT,
218
- callId: call.callId,
219
- ok: false,
220
- error: {
221
- code: RuntimeErrorCode.ACCESS_DENIED,
222
- message: `Capability "${call.capability}" is not granted to the execution`,
223
- },
224
- });
225
- return;
226
- }
227
- try {
228
- const value = await handler(call.args, { stepId: call.stepId });
229
- send(
230
- value === SUSPEND_EXECUTION
231
- ? {
232
- type: ExecutionMessageType.CALL_RESULT,
233
- callId: call.callId,
234
- ok: true,
235
- suspend: true,
236
- }
237
- : { type: ExecutionMessageType.CALL_RESULT, callId: call.callId, ok: true, value },
238
- );
239
- } catch (error) {
240
- send({
241
- type: ExecutionMessageType.CALL_RESULT,
242
- callId: call.callId,
243
- ok: false,
244
- error: callErrorOf(error),
245
- });
246
- }
247
- };
248
-
249
- ws.on('unexpected-response', (_request, response) => {
250
- const status = response.statusCode;
251
- unavailable(
252
- status === 401
253
- ? 'Code runner refused the token (401 Unauthorized)'
254
- : `Code runner refused the connection (HTTP ${status})`,
255
- );
256
- });
257
- ws.on('error', (error) => unavailable(`Code runner unreachable: ${error.message}`));
258
- ws.on('close', () => unavailable('Code runner connection closed before the end'));
259
-
260
- ws.on('open', () => {
261
- clearTimeout(connectTimer);
262
- const wallLimitMs = request.limits.wallTimeMs + wallTimeGraceMs;
263
- wallTimer = setTimeout(
264
- () => fail(RuntimeErrorCode.TIMEOUT, `Execution did not finish within ${wallLimitMs} ms`),
265
- wallLimitMs,
266
- );
267
- send({
268
- ...request,
269
- type: ExecutionMessageType.EXECUTE,
270
- capabilities: Object.keys(handlers),
271
- });
272
- });
273
-
274
- ws.on('message', (raw) => {
275
- if (settled) {
276
- return;
277
- }
278
- let message: ExecutionRunnerMessage;
279
- try {
280
- message = parseRunnerMessage(raw);
281
- } catch (error) {
282
- unavailable(errorMessage(error));
283
- return;
284
- }
285
- switch (message.type) {
286
- case ExecutionMessageType.CALL:
287
- void serveCall(message);
288
- break;
289
- case ExecutionMessageType.PROGRESS: {
290
- if (!onProgress) {
291
- break;
292
- }
293
- try {
294
- onProgress(message);
295
- } catch (error) {
296
- finish(() => reject(error));
297
- }
298
- break;
299
- }
300
- case ExecutionMessageType.FINISHED:
301
- finish(() => resolve({ outcome: message.outcome, metrics: message.metrics }));
302
- break;
303
- case ExecutionMessageType.REJECTED:
304
- fail(message.code, message.message);
305
- break;
306
- }
307
- });
308
- });
309
- }
310
- }
1
+ import { WebSocket } from 'ws';
2
+ import type { RawData } from 'ws';
3
+ import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
4
+ import {
5
+ EXECUTION_PROTOCOL,
6
+ ExecutionMessageType,
7
+ ExecutionStatus,
8
+ StepPhase,
9
+ } from '../runner-protocol/execution-protocol.types';
10
+ import type {
11
+ CallError,
12
+ ExecuteMessage,
13
+ ExecutionCallMessage,
14
+ ExecutionCallResultMessage,
15
+ ExecutionRejectedMessage,
16
+ ExecutionRunnerMessage,
17
+ FinishedMessage,
18
+ ProgressMessage,
19
+ } from '../runner-protocol/execution-protocol.types';
20
+ import { CodeRunnerError } from './code-runner-error';
21
+
22
+ export interface CodeRunnerSessionOptions {
23
+ /** `ws://` or `wss://` URL of the code runner. */
24
+ url: string;
25
+ /** Bearer token the runner knows by fingerprint. */
26
+ token: string;
27
+ /** Maximum time to open the connection; past it the execution fails with RUNNER_UNAVAILABLE. */
28
+ connectTimeoutMs: number;
29
+ /**
30
+ * Added to `limits.wallTimeMs` once the connection is open: time the runner may spend
31
+ * queueing the execution and reporting its end. Past the sum, the execution fails with
32
+ * TIMEOUT and the connection is closed, which stops the execution in the runner.
33
+ */
34
+ wallTimeGraceMs: number;
35
+ }
36
+
37
+ export interface CapabilityContext {
38
+ /** The step that made the call. */
39
+ stepId: string;
40
+ }
41
+
42
+ /**
43
+ * One handler per capability the execution may call; their names are the `capabilities` sent
44
+ * to the runner. A handler resolves the call's value, resolves `SUSPEND_EXECUTION` to suspend
45
+ * the execution after this step, or throws (a `CapabilityError` to choose the error code).
46
+ */
47
+ export type CapabilityHandlers = Record<
48
+ string,
49
+ (args: unknown, context: CapabilityContext) => Promise<unknown>
50
+ >;
51
+
52
+ /** Resolved by a capability handler: the runner finishes SUSPENDED after the calling step. */
53
+ export const SUSPEND_EXECUTION: unique symbol = Symbol('abyss-runtime.suspend-execution');
54
+
55
+ /** Thrown by a capability handler to fail the call with a given code (ACCESS_DENIED...). */
56
+ export class CapabilityError extends Error {
57
+ public readonly code: RuntimeErrorCode;
58
+
59
+ constructor(code: RuntimeErrorCode, message: string) {
60
+ super(message);
61
+ this.name = 'CapabilityError';
62
+ this.code = code;
63
+ }
64
+ }
65
+
66
+ /** What the host sends; `capabilities` is derived from the handlers. */
67
+ export type ExecutionRequest = Omit<ExecuteMessage, 'type' | 'capabilities'>;
68
+
69
+ export interface ExecuteOptions {
70
+ onProgress?: (progress: Omit<ProgressMessage, 'type'>) => void;
71
+ /** Aborting closes the connection, which stops the execution; the promise rejects with the signal's reason. */
72
+ signal?: AbortSignal;
73
+ }
74
+
75
+ export type ExecutionResult = Omit<FinishedMessage, 'type'>;
76
+
77
+ const REJECTION_CODES = new Set<string>([
78
+ RuntimeErrorCode.RUNNER_SATURATED,
79
+ RuntimeErrorCode.INVALID_REQUEST,
80
+ RuntimeErrorCode.STATE_VERSION_UNSUPPORTED,
81
+ ]);
82
+ const EXECUTION_STATUSES = new Set<string>(Object.values(ExecutionStatus));
83
+ const STEP_PHASES = new Set<string>(Object.values(StepPhase));
84
+
85
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
86
+ typeof value === 'object' && value !== null && !Array.isArray(value);
87
+
88
+ const malformed = (type: string): Error =>
89
+ new Error(`Code runner sent a malformed "${type}" message`);
90
+
91
+ const parseRunnerMessage = (raw: RawData): ExecutionRunnerMessage => {
92
+ let parsed: unknown;
93
+ try {
94
+ parsed = JSON.parse(raw.toString());
95
+ } catch {
96
+ throw new Error('Code runner sent a message that is not valid JSON');
97
+ }
98
+ if (!isRecord(parsed)) {
99
+ throw new Error('Code runner sent a message that is not an object');
100
+ }
101
+ switch (parsed.type) {
102
+ case ExecutionMessageType.CALL:
103
+ if (
104
+ typeof parsed.callId !== 'string' ||
105
+ typeof parsed.stepId !== 'string' ||
106
+ typeof parsed.capability !== 'string'
107
+ ) {
108
+ throw malformed(parsed.type);
109
+ }
110
+ return parsed as unknown as ExecutionCallMessage;
111
+ case ExecutionMessageType.PROGRESS:
112
+ if (typeof parsed.stepId !== 'string' || !STEP_PHASES.has(parsed.phase as string)) {
113
+ throw malformed(parsed.type);
114
+ }
115
+ return parsed as unknown as ProgressMessage;
116
+ case ExecutionMessageType.FINISHED:
117
+ if (
118
+ !isRecord(parsed.outcome) ||
119
+ !EXECUTION_STATUSES.has(parsed.outcome.status as string) ||
120
+ !isRecord(parsed.metrics)
121
+ ) {
122
+ throw malformed(parsed.type);
123
+ }
124
+ return parsed as unknown as FinishedMessage;
125
+ case ExecutionMessageType.REJECTED:
126
+ if (!REJECTION_CODES.has(parsed.code as string) || typeof parsed.message !== 'string') {
127
+ throw malformed(parsed.type);
128
+ }
129
+ return parsed as unknown as ExecutionRejectedMessage;
130
+ default:
131
+ throw new Error('Code runner sent a message of unknown type');
132
+ }
133
+ };
134
+
135
+ const errorMessage = (error: unknown): string =>
136
+ error instanceof Error ? error.message : String(error);
137
+
138
+ const callErrorOf = (error: unknown): CallError =>
139
+ error instanceof CapabilityError
140
+ ? { code: error.code, message: error.message }
141
+ : { message: errorMessage(error) };
142
+
143
+ const abortReason = (signal: AbortSignal): unknown =>
144
+ signal.reason ?? new Error('The execution was aborted');
145
+
146
+ /**
147
+ * Node client of the code runner for `abyss-runtime.v2`: one WebSocket connection per
148
+ * execution, one `execute`, the runner's calls served by the host's capability handlers.
149
+ */
150
+ export class CodeRunnerSession {
151
+ private readonly options: CodeRunnerSessionOptions;
152
+
153
+ constructor(options: CodeRunnerSessionOptions) {
154
+ this.options = options;
155
+ }
156
+
157
+ public execute(
158
+ request: ExecutionRequest,
159
+ handlers: CapabilityHandlers,
160
+ executeOptions: ExecuteOptions = {},
161
+ ): Promise<ExecutionResult> {
162
+ const { url, token, connectTimeoutMs, wallTimeGraceMs } = this.options;
163
+ const { onProgress, signal } = executeOptions;
164
+ if (signal?.aborted) {
165
+ return Promise.reject(abortReason(signal));
166
+ }
167
+
168
+ return new Promise<ExecutionResult>((resolve, reject) => {
169
+ let settled = false;
170
+ let wallTimer: ReturnType<typeof setTimeout> | undefined;
171
+ const ws = new WebSocket(url, EXECUTION_PROTOCOL, {
172
+ headers: { Authorization: `Bearer ${token}` },
173
+ handshakeTimeout: connectTimeoutMs,
174
+ });
175
+
176
+ const onAbort = (): void => finish(() => reject(abortReason(signal as AbortSignal)));
177
+
178
+ function finish(outcome: () => void): void {
179
+ if (settled) {
180
+ return;
181
+ }
182
+ settled = true;
183
+ clearTimeout(connectTimer);
184
+ clearTimeout(wallTimer);
185
+ signal?.removeEventListener('abort', onAbort);
186
+ if (ws.readyState === WebSocket.OPEN) {
187
+ ws.close();
188
+ } else {
189
+ ws.terminate();
190
+ }
191
+ outcome();
192
+ }
193
+ const fail = (code: RuntimeErrorCode, message: string): void =>
194
+ finish(() => reject(new CodeRunnerError(code, message)));
195
+ const unavailable = (message: string): void =>
196
+ fail(RuntimeErrorCode.RUNNER_UNAVAILABLE, message);
197
+
198
+ const connectTimer = setTimeout(
199
+ () =>
200
+ unavailable(`Code runner did not accept the connection within ${connectTimeoutMs} ms`),
201
+ connectTimeoutMs,
202
+ );
203
+ signal?.addEventListener('abort', onAbort, { once: true });
204
+
205
+ const send = (message: ExecuteMessage | ExecutionCallResultMessage): void => {
206
+ if (!settled && ws.readyState === WebSocket.OPEN) {
207
+ ws.send(JSON.stringify(message));
208
+ }
209
+ };
210
+
211
+ const serveCall = async (call: ExecutionCallMessage): Promise<void> => {
212
+ const handler = Object.prototype.hasOwnProperty.call(handlers, call.capability)
213
+ ? handlers[call.capability]
214
+ : undefined;
215
+ if (!handler) {
216
+ send({
217
+ type: ExecutionMessageType.CALL_RESULT,
218
+ callId: call.callId,
219
+ ok: false,
220
+ error: {
221
+ code: RuntimeErrorCode.ACCESS_DENIED,
222
+ message: `Capability "${call.capability}" is not granted to the execution`,
223
+ },
224
+ });
225
+ return;
226
+ }
227
+ try {
228
+ const value = await handler(call.args, { stepId: call.stepId });
229
+ send(
230
+ value === SUSPEND_EXECUTION
231
+ ? {
232
+ type: ExecutionMessageType.CALL_RESULT,
233
+ callId: call.callId,
234
+ ok: true,
235
+ suspend: true,
236
+ }
237
+ : { type: ExecutionMessageType.CALL_RESULT, callId: call.callId, ok: true, value },
238
+ );
239
+ } catch (error) {
240
+ send({
241
+ type: ExecutionMessageType.CALL_RESULT,
242
+ callId: call.callId,
243
+ ok: false,
244
+ error: callErrorOf(error),
245
+ });
246
+ }
247
+ };
248
+
249
+ ws.on('unexpected-response', (_request, response) => {
250
+ const status = response.statusCode;
251
+ unavailable(
252
+ status === 401
253
+ ? 'Code runner refused the token (401 Unauthorized)'
254
+ : `Code runner refused the connection (HTTP ${status})`,
255
+ );
256
+ });
257
+ ws.on('error', (error) => unavailable(`Code runner unreachable: ${error.message}`));
258
+ ws.on('close', () => unavailable('Code runner connection closed before the end'));
259
+
260
+ ws.on('open', () => {
261
+ clearTimeout(connectTimer);
262
+ const wallLimitMs = request.limits.wallTimeMs + wallTimeGraceMs;
263
+ wallTimer = setTimeout(
264
+ () => fail(RuntimeErrorCode.TIMEOUT, `Execution did not finish within ${wallLimitMs} ms`),
265
+ wallLimitMs,
266
+ );
267
+ send({
268
+ ...request,
269
+ type: ExecutionMessageType.EXECUTE,
270
+ capabilities: Object.keys(handlers),
271
+ });
272
+ });
273
+
274
+ ws.on('message', (raw) => {
275
+ if (settled) {
276
+ return;
277
+ }
278
+ let message: ExecutionRunnerMessage;
279
+ try {
280
+ message = parseRunnerMessage(raw);
281
+ } catch (error) {
282
+ unavailable(errorMessage(error));
283
+ return;
284
+ }
285
+ switch (message.type) {
286
+ case ExecutionMessageType.CALL:
287
+ void serveCall(message);
288
+ break;
289
+ case ExecutionMessageType.PROGRESS: {
290
+ if (!onProgress) {
291
+ break;
292
+ }
293
+ try {
294
+ onProgress(message);
295
+ } catch (error) {
296
+ finish(() => reject(error));
297
+ }
298
+ break;
299
+ }
300
+ case ExecutionMessageType.FINISHED:
301
+ finish(() => resolve({ outcome: message.outcome, metrics: message.metrics }));
302
+ break;
303
+ case ExecutionMessageType.REJECTED:
304
+ fail(message.code, message.message);
305
+ break;
306
+ }
307
+ });
308
+ });
309
+ }
310
+ }
@@ -1,11 +1,11 @@
1
- // Entry point `@abyss-project/runtime/server`: the only place where `ws` and Node modules are allowed.
2
- export { CodeRunnerError } from './code-runner-error';
3
- export { CapabilityError, CodeRunnerSession, SUSPEND_EXECUTION } from './code-runner-session';
4
- export type {
5
- CapabilityContext,
6
- CapabilityHandlers,
7
- CodeRunnerSessionOptions,
8
- ExecuteOptions,
9
- ExecutionRequest,
10
- ExecutionResult,
11
- } from './code-runner-session';
1
+ // Entry point `@abyss-project/runtime/server`: the only place where `ws` and Node modules are allowed.
2
+ export { CodeRunnerError } from './code-runner-error';
3
+ export { CapabilityError, CodeRunnerSession, SUSPEND_EXECUTION } from './code-runner-session';
4
+ export type {
5
+ CapabilityContext,
6
+ CapabilityHandlers,
7
+ CodeRunnerSessionOptions,
8
+ ExecuteOptions,
9
+ ExecutionRequest,
10
+ ExecutionResult,
11
+ } from './code-runner-session';