@abyss-project/runtime 2.0.0 → 3.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.
- package/dist/cost/execution-cost.d.ts +0 -2
- package/dist/cost/execution-cost.js +2 -6
- package/dist/cost/execution-cost.js.map +1 -1
- package/dist/definition/definition.limits.d.ts +1 -1
- package/dist/definition/definition.limits.js +1 -1
- package/dist/engine/engine-source.js +1 -1
- package/dist/runner-protocol/execution-protocol.types.d.ts +0 -1
- package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
- package/package.json +1 -1
- package/src/cost/__tests__/execution-cost.test.ts +6 -10
- package/src/cost/execution-cost.ts +10 -16
- package/src/definition/__tests__/validate-definition.test.ts +3 -3
- package/src/definition/definition.limits.ts +1 -1
- package/src/engine/run-in-isolate.ts +1 -1
- package/src/runner-protocol/execution-protocol.types.ts +7 -3
- package/src/server/__tests__/code-runner-session.test.ts +1 -1
|
@@ -13,7 +13,6 @@ export declare const RESOURCE_PROFILES: Readonly<Record<ResourceProfile, Resourc
|
|
|
13
13
|
export declare const COST_RATES: {
|
|
14
14
|
readonly executionMillicredits: 10;
|
|
15
15
|
readonly cpuMillicreditsPerSecond: 500;
|
|
16
|
-
readonly guaranteedCpuCoefficient: 1.5;
|
|
17
16
|
readonly memoryMillicreditsPerGbSecond: 100;
|
|
18
17
|
readonly networkOutMillicreditsPerMb: 1000;
|
|
19
18
|
readonly httpCallMillicredits: 10;
|
|
@@ -34,7 +33,6 @@ export interface StepUsage {
|
|
|
34
33
|
export interface ExecutionCostInput extends StepUsage {
|
|
35
34
|
status: CostedExecutionStatus;
|
|
36
35
|
profile: ResourceProfile;
|
|
37
|
-
guaranteedCpu: boolean;
|
|
38
36
|
resumedSegment?: boolean;
|
|
39
37
|
}
|
|
40
38
|
export interface StepCostInput {
|
|
@@ -19,7 +19,6 @@ exports.RESOURCE_PROFILES = {
|
|
|
19
19
|
exports.COST_RATES = {
|
|
20
20
|
executionMillicredits: 10,
|
|
21
21
|
cpuMillicreditsPerSecond: 500,
|
|
22
|
-
guaranteedCpuCoefficient: 1.5,
|
|
23
22
|
memoryMillicreditsPerGbSecond: 100,
|
|
24
23
|
networkOutMillicreditsPerMb: 1000,
|
|
25
24
|
httpCallMillicredits: 10,
|
|
@@ -32,10 +31,10 @@ var CostedExecutionStatus;
|
|
|
32
31
|
CostedExecutionStatus["REFUSED"] = "REFUSED";
|
|
33
32
|
})(CostedExecutionStatus || (exports.CostedExecutionStatus = CostedExecutionStatus = {}));
|
|
34
33
|
const MICROS_PER_SECOND = BigInt(1_000_000);
|
|
35
|
-
const CPU_DENOMINATOR = MICROS_PER_SECOND * BigInt(100)
|
|
34
|
+
const CPU_DENOMINATOR = MICROS_PER_SECOND * BigInt(100);
|
|
36
35
|
const MEMORY_DENOMINATOR = BigInt(1024) * MICROS_PER_SECOND;
|
|
37
36
|
const NETWORK_DENOMINATOR = BigInt(1024 * 1024);
|
|
38
|
-
const UNITS_PER_MILLICREDIT = BigInt(1_048_576) * BigInt(
|
|
37
|
+
const UNITS_PER_MILLICREDIT = BigInt(1_048_576) * BigInt(390_625);
|
|
39
38
|
const ZERO = BigInt(0);
|
|
40
39
|
const ONE = BigInt(1);
|
|
41
40
|
const TWO = BigInt(2);
|
|
@@ -50,14 +49,11 @@ const assertUsage = (usage, subject) => {
|
|
|
50
49
|
const micros = (ms) => BigInt(Math.round(ms * 1000));
|
|
51
50
|
const whole = (count) => BigInt(Math.round(count));
|
|
52
51
|
const hundredths = (coefficient) => BigInt(Math.round(coefficient * 100));
|
|
53
|
-
const thousandths = (coefficient) => BigInt(Math.round(coefficient * 1000));
|
|
54
52
|
const variableUnits = (usage, execution) => {
|
|
55
53
|
const profile = exports.RESOURCE_PROFILES[execution.profile];
|
|
56
|
-
const guaranteed = execution.guaranteedCpu ? exports.COST_RATES.guaranteedCpuCoefficient : 1;
|
|
57
54
|
const cpu = (micros(usage.cpuMs) *
|
|
58
55
|
BigInt(exports.COST_RATES.cpuMillicreditsPerSecond) *
|
|
59
56
|
hundredths(profile.cpuCoefficient) *
|
|
60
|
-
thousandths(guaranteed) *
|
|
61
57
|
UNITS_PER_MILLICREDIT) /
|
|
62
58
|
CPU_DENOMINATOR;
|
|
63
59
|
const memory = (BigInt(profile.memoryMb) *
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution-cost.js","sourceRoot":"","sources":["../../src/cost/execution-cost.ts"],"names":[],"mappings":";;;AAIA,IAAY,eAMX;AAND,WAAY,eAAe;IACzB,0BAAO,CAAA;IACP,0BAAO,CAAA;IACP,0BAAO,CAAA;IACP,4BAAS,CAAA;IACT,8BAAW,CAAA;AACb,CAAC,EANW,eAAe,+BAAf,eAAe,QAM1B;AASY,QAAA,iBAAiB,GAA2D;IACvF,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,cAAc,EAAE,CAAC,EAAE;IACzD,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,cAAc,EAAE,IAAI,EAAE;IAC5D,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE;IAC3D,CAAC,eAAe,CAAC,EAAE,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,EAAE;IAC7D,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,EAAE;CAChE,CAAC;AAGW,QAAA,UAAU,GAAG;IAExB,qBAAqB,EAAE,EAAE;IACzB,wBAAwB,EAAE,GAAG;IAE7B,
|
|
1
|
+
{"version":3,"file":"execution-cost.js","sourceRoot":"","sources":["../../src/cost/execution-cost.ts"],"names":[],"mappings":"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"}
|
|
@@ -3,6 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.MAX_RESPONSE_STATUS = exports.MIN_RESPONSE_STATUS = exports.MAX_WAIT_DURATION_MS = exports.MAX_HTTP_TIMEOUT_MS = void 0;
|
|
4
4
|
exports.MAX_HTTP_TIMEOUT_MS = 30_000;
|
|
5
5
|
exports.MAX_WAIT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
6
|
-
exports.MIN_RESPONSE_STATUS =
|
|
6
|
+
exports.MIN_RESPONSE_STATUS = 200;
|
|
7
7
|
exports.MAX_RESPONSE_STATUS = 599;
|
|
8
8
|
//# sourceMappingURL=definition.limits.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ENGINE_SOURCE = "\"use strict\";\nvar AbyssRuntimeEngine = (() => {\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n };\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n // src/engine/engine-entry.ts\n var engine_entry_exports = {};\n __export(engine_entry_exports, {\n runInIsolate: () => runInIsolate\n });\n\n // src/errors/runtime-error-code.enum.ts\n var RuntimeErrorCode = /* @__PURE__ */ ((RuntimeErrorCode2) => {\n RuntimeErrorCode2[\"EXPRESSION_ERROR\"] = \"EXPRESSION_ERROR\";\n RuntimeErrorCode2[\"CODE_ERROR\"] = \"CODE_ERROR\";\n RuntimeErrorCode2[\"TIMEOUT\"] = \"TIMEOUT\";\n RuntimeErrorCode2[\"MEMORY_LIMIT\"] = \"MEMORY_LIMIT\";\n RuntimeErrorCode2[\"ACCESS_DENIED\"] = \"ACCESS_DENIED\";\n RuntimeErrorCode2[\"BUDGET_EXCEEDED\"] = \"BUDGET_EXCEEDED\";\n RuntimeErrorCode2[\"HOST_ERROR\"] = \"HOST_ERROR\";\n RuntimeErrorCode2[\"HTTP_ERROR\"] = \"HTTP_ERROR\";\n RuntimeErrorCode2[\"RUNNER_UNAVAILABLE\"] = \"RUNNER_UNAVAILABLE\";\n RuntimeErrorCode2[\"RUNNER_SATURATED\"] = \"RUNNER_SATURATED\";\n RuntimeErrorCode2[\"INVALID_REQUEST\"] = \"INVALID_REQUEST\";\n RuntimeErrorCode2[\"STATE_VERSION_UNSUPPORTED\"] = \"STATE_VERSION_UNSUPPORTED\";\n return RuntimeErrorCode2;\n })(RuntimeErrorCode || {});\n\n // src/definition/definition.limits.ts\n var MAX_WAIT_DURATION_MS = 30 * 24 * 60 * 60 * 1e3;\n var MIN_RESPONSE_STATUS = 100;\n var MAX_RESPONSE_STATUS = 599;\n\n // src/interpreter/interpreter-error.ts\n var InterpreterError = class extends Error {\n constructor(code, message) {\n super(message);\n this.name = \"InterpreterError\";\n this.code = code;\n }\n };\n\n // src/definition/definition.types.ts\n var CURRENT_FORMAT_VERSION = 1;\n\n // src/steps/value-source.ts\n var TEMPLATE_PATTERN = /\\{\\{[\\s\\S]*?\\}\\}/;\n var IDENTIFIER_KEY = /^[A-Za-z_$][\\w$-]*$/;\n var isExpressionValue = (value) => typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && typeof value.$expression === \"string\";\n var propertyPath = (base, key) => IDENTIFIER_KEY.test(key) ? `${base}.${key}` : `${base}[${JSON.stringify(key)}]`;\n var indexPath = (base, index) => `${base}[${index}]`;\n var collectItems = (path, source, items) => {\n if (typeof source === \"string\") {\n if (TEMPLATE_PATTERN.test(source)) {\n items.push({ id: path, kind: \"TEMPLATE\" /* TEMPLATE */, source });\n }\n return;\n }\n if (source === null || typeof source !== \"object\") {\n return;\n }\n if (isExpressionValue(source)) {\n items.push({ id: path, kind: \"EXPRESSION\" /* EXPRESSION */, source: source.$expression });\n return;\n }\n if (Array.isArray(source)) {\n source.forEach((entry, index) => collectItems(indexPath(path, index), entry, items));\n return;\n }\n for (const [key, entry] of Object.entries(source)) {\n collectItems(propertyPath(path, key), entry, items);\n }\n };\n var resolveValue = (path, source, results) => {\n if (typeof source === \"string\") {\n return TEMPLATE_PATTERN.test(source) ? results.get(path) : source;\n }\n if (source === null || typeof source !== \"object\") {\n return source;\n }\n if (isExpressionValue(source)) {\n return results.get(path);\n }\n if (Array.isArray(source)) {\n return source.map((entry, index) => resolveValue(indexPath(path, index), entry, results));\n }\n return Object.fromEntries(\n Object.entries(source).map(([key, entry]) => [\n key,\n resolveValue(propertyPath(path, key), entry, results)\n ])\n );\n };\n\n // src/steps/execute-step.ts\n var fail = (message) => ({\n kind: \"FAIL\" /* FAIL */,\n error: { code: \"EXPRESSION_ERROR\" /* EXPRESSION_ERROR */, message }\n });\n var headerValue = (value) => typeof value === \"string\" ? value : JSON.stringify(value) ?? \"\";\n var resolvedRecord = (base, keys, fields) => Object.fromEntries(keys.map((key) => [key, fields.get(propertyPath(base, key))]));\n var executeWait = (step, fields) => {\n if (step.durationMs !== void 0) {\n const durationMs = fields.get(\"durationMs\");\n if (typeof durationMs !== \"number\" || !Number.isInteger(durationMs) || durationMs < 0) {\n return fail(\"Wait duration must resolve to a non-negative integer number of milliseconds\");\n }\n return { kind: \"WAIT\" /* WAIT */, durationMs };\n }\n const until = fields.get(\"until\");\n if (typeof until !== \"string\" || Number.isNaN(Date.parse(until))) {\n return fail(\"Wait date must resolve to an ISO 8601 date\");\n }\n return { kind: \"WAIT\" /* WAIT */, until };\n };\n var executeLog = (step, fields) => {\n const message = fields.get(\"message\");\n const action = {\n kind: \"LOG\" /* LOG */,\n level: step.level,\n message: typeof message === \"string\" ? message : JSON.stringify(message) ?? \"\"\n };\n if (step.data !== void 0) {\n action.data = fields.get(\"data\");\n }\n return action;\n };\n var executeRespond = (step, fields) => {\n const status = fields.get(\"status\");\n if (typeof status !== \"number\" || !Number.isInteger(status) || status < MIN_RESPONSE_STATUS || status > MAX_RESPONSE_STATUS) {\n return fail(\n `Response status must resolve to an integer from ${MIN_RESPONSE_STATUS} to ${MAX_RESPONSE_STATUS}`\n );\n }\n const headers = resolvedRecord(\"headers\", Object.keys(step.headers ?? {}), fields);\n const response = {\n status,\n headers: Object.fromEntries(\n Object.entries(headers).map(([key, value]) => [key, headerValue(value)])\n )\n };\n if (step.body !== void 0) {\n response.body = fields.get(\"body\");\n }\n return { kind: \"RESPOND\" /* RESPOND */, response };\n };\n var executeStep = (step, fields) => {\n switch (step.type) {\n case \"CONDITION\" /* CONDITION */: {\n if (fields.get(\"if\")) {\n return { kind: \"DONE\" /* DONE */, output: \"then\", branch: \"then\" };\n }\n return step.else ? { kind: \"DONE\" /* DONE */, output: \"else\", branch: \"else\" } : { kind: \"DONE\" /* DONE */, output: \"else\" };\n }\n case \"SWITCH\" /* SWITCH */: {\n const value = fields.get(\"value\");\n const index = step.cases.findIndex(\n (_, caseIndex) => fields.get(`cases[${caseIndex}].match`) === value\n );\n if (index >= 0) {\n const branch = `cases[${index}].steps`;\n return { kind: \"DONE\" /* DONE */, output: `cases[${index}]`, branch };\n }\n return step.default ? { kind: \"DONE\" /* DONE */, output: \"default\", branch: \"default\" } : { kind: \"DONE\" /* DONE */, output: null };\n }\n case \"WAIT\" /* WAIT */:\n return executeWait(step, fields);\n case \"SET\" /* SET */: {\n const value = fields.get(\"value\");\n return {\n kind: \"DONE\" /* DONE */,\n output: value,\n variable: { name: step.variable, value }\n };\n }\n case \"CODE\" /* CODE */:\n return { kind: \"DONE\" /* DONE */, output: fields.get(\"source\") };\n case \"HTTP\" /* HTTP */: {\n const url = fields.get(\"url\");\n if (typeof url !== \"string\") {\n return fail(\"HTTP url must resolve to a string\");\n }\n const headers = resolvedRecord(\"headers\", Object.keys(step.headers ?? {}), fields);\n const request = {\n method: step.method,\n url,\n headers: Object.fromEntries(\n Object.entries(headers).map(([key, value]) => [key, headerValue(value)])\n )\n };\n if (step.body !== void 0) {\n request.body = fields.get(\"body\");\n }\n if (step.timeoutMs !== void 0) {\n request.timeoutMs = step.timeoutMs;\n }\n return { kind: \"HTTP\" /* HTTP */, request };\n }\n case \"HOST\" /* HOST */:\n return {\n kind: \"HOST\" /* HOST */,\n action: step.action,\n input: resolvedRecord(\"input\", Object.keys(step.input), fields)\n };\n case \"LOG\" /* LOG */:\n return executeLog(step, fields);\n case \"RESPOND\" /* RESPOND */:\n return executeRespond(step, fields);\n case \"STOP\" /* STOP */:\n return { kind: \"STOP\" /* STOP */, status: step.status, output: fields.get(\"output\") };\n }\n };\n\n // src/steps/step-fields.ts\n var recordFields = (base, record) => Object.entries(record ?? {}).map(([key, source]) => ({ path: propertyPath(base, key), source }));\n var optionalField = (path, source) => source === void 0 ? [] : [{ path, source }];\n var stepFields = (step) => {\n switch (step.type) {\n case \"CONDITION\" /* CONDITION */:\n return [{ path: \"if\", source: step.if }];\n case \"SWITCH\" /* SWITCH */:\n return [\n { path: \"value\", source: step.value },\n ...step.cases.map((switchCase, index) => ({\n path: `cases[${index}].match`,\n source: switchCase.match\n }))\n ];\n case \"WAIT\" /* WAIT */:\n return [\n ...optionalField(\"durationMs\", step.durationMs),\n ...optionalField(\"until\", step.until)\n ];\n case \"SET\" /* SET */:\n return [{ path: \"value\", source: step.value }];\n case \"CODE\" /* CODE */:\n return [];\n case \"HTTP\" /* HTTP */:\n return [\n { path: \"url\", source: step.url },\n ...recordFields(\"headers\", step.headers),\n ...optionalField(\"body\", step.body)\n ];\n case \"HOST\" /* HOST */:\n return recordFields(\"input\", step.input);\n case \"LOG\" /* LOG */:\n return [{ path: \"message\", source: step.message }, ...optionalField(\"data\", step.data)];\n case \"RESPOND\" /* RESPOND */:\n return [\n { path: \"status\", source: step.status },\n ...recordFields(\"headers\", step.headers),\n ...optionalField(\"body\", step.body)\n ];\n case \"STOP\" /* STOP */:\n return optionalField(\"output\", step.output);\n }\n };\n var collectStepItems = (step) => {\n if (step.type === \"CODE\" /* CODE */) {\n return [{ id: \"source\", kind: \"CODE\" /* CODE */, source: step.source }];\n }\n const items = [];\n for (const field of stepFields(step)) {\n collectItems(field.path, field.source, items);\n }\n return items;\n };\n var resolveStepFields = (step, results) => {\n if (step.type === \"CODE\" /* CODE */) {\n return /* @__PURE__ */ new Map([[\"source\", results.get(\"source\")]]);\n }\n return new Map(\n stepFields(step).map((field) => [field.path, resolveValue(field.path, field.source, results)])\n );\n };\n\n // src/interpreter/interpreter.types.ts\n var CURRENT_STATE_VERSION = 1;\n\n // src/interpreter/sequence-path.ts\n var ROOT = \"steps\";\n var SEGMENT = /\\[(\\d+)\\]\\.(?:(then|else|default)|cases\\[(\\d+)\\]\\.steps)/y;\n var corrupted = (path) => new InterpreterError(\n \"INVALID_REQUEST\" /* INVALID_REQUEST */,\n `Run state points outside the definition: ${path}`\n );\n var branchOf = (step, name, caseIndex) => {\n if (step.type === \"CONDITION\" /* CONDITION */) {\n return name === \"then\" ? step.then : name === \"else\" ? step.else : void 0;\n }\n if (step.type === \"SWITCH\" /* SWITCH */) {\n return name === \"default\" ? step.default : caseIndex === void 0 ? void 0 : step.cases[Number(caseIndex)]?.steps;\n }\n return void 0;\n };\n var resolveSequence = (definition, path) => {\n if (!path.startsWith(ROOT)) {\n throw corrupted(path);\n }\n let sequence = definition.steps;\n let position = ROOT.length;\n while (position < path.length) {\n SEGMENT.lastIndex = position;\n const match = SEGMENT.exec(path);\n const next = match ? branchOf(sequence[Number(match[1])], match[2], match[3]) : void 0;\n if (!match || !next) {\n throw corrupted(path);\n }\n sequence = next;\n position = SEGMENT.lastIndex;\n }\n return sequence;\n };\n var resolveStep = (definition, frame) => {\n const step = resolveSequence(definition, frame.sequencePath)[frame.index];\n if (!step) {\n throw corrupted(frame.sequencePath);\n }\n return step;\n };\n var branchPath = (frame, branch) => `${frame.sequencePath}[${frame.index}].${branch}`;\n var ROOT_SEQUENCE_PATH = ROOT;\n\n // src/interpreter/interpreter.ts\n var NO_RESULTS = /* @__PURE__ */ new Map();\n var SILENT_OBSERVER = {\n stepStarted: () => void 0,\n stepFinished: () => void 0\n };\n var invalidRequest = (message) => new InterpreterError(\"INVALID_REQUEST\" /* INVALID_REQUEST */, message);\n var draftOf = (state) => ({\n ...state,\n stack: state.stack.map((frame) => ({ ...frame })),\n outputs: { ...state.outputs },\n vars: { ...state.vars },\n counters: { ...state.counters }\n });\n var setOwn = (target, key, value) => {\n Object.defineProperty(target, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n };\n var topFrame = (draft) => draft.stack[draft.stack.length - 1];\n var advance = (draft) => {\n topFrame(draft).index += 1;\n };\n var settle = (draft, status) => {\n draft.status = status;\n draft.pending = null;\n return { state: draft, effects: [], status };\n };\n var failRun = (context, draft, error, stepId) => {\n draft.outcome = { status: \"FAILED\" /* FAILED */, error: { ...error, stepId } };\n context.observer.stepFinished(stepId, { ok: false, error });\n return settle(draft, \"FAILED\" /* FAILED */);\n };\n var emit = (context, draft, effect) => {\n if (draft.counters.effects + 1 > context.policy.budget.maxEffects) {\n return failRun(\n context,\n draft,\n { code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */, message: \"Effect budget exceeded\" },\n effect.stepId\n );\n }\n draft.counters.effects += 1;\n draft.pending = effect;\n draft.status = \"WAITING\" /* WAITING */;\n return { state: draft, effects: [effect], status: \"WAITING\" /* WAITING */ };\n };\n var accessDenied = (verdict, subject) => ({\n code: \"ACCESS_DENIED\" /* ACCESS_DENIED */,\n message: verdict === \"NOT_DECLARED\" /* NOT_DECLARED */ ? `${subject} is not declared by the definition` : `${subject} is not granted to the run`\n });\n var applyAction = (context, draft, step, action) => {\n const { policy, observer } = context;\n switch (action.kind) {\n case \"FAIL\" /* FAIL */:\n return failRun(context, draft, action.error, step.id);\n case \"STOP\" /* STOP */:\n draft.outcome = { status: action.status, output: action.output };\n observer.stepFinished(step.id, { ok: true, output: action.output });\n return settle(\n draft,\n action.status === \"SUCCEEDED\" /* SUCCEEDED */ ? \"SUCCEEDED\" /* SUCCEEDED */ : \"FAILED\" /* FAILED */\n );\n case \"DONE\" /* DONE */: {\n setOwn(draft.outputs, step.id, { output: action.output });\n observer.stepFinished(step.id, { ok: true, output: action.output });\n if (action.variable) {\n setOwn(draft.vars, action.variable.name, action.variable.value);\n }\n if (action.branch === void 0) {\n advance(draft);\n } else {\n draft.stack.push({ sequencePath: branchPath(topFrame(draft), action.branch), index: 0 });\n }\n return null;\n }\n case \"WAIT\" /* WAIT */: {\n const maxWaitMs = Math.min(policy.budget.maxWaitMs, MAX_WAIT_DURATION_MS);\n if (action.durationMs !== void 0 && action.durationMs > maxWaitMs) {\n return failRun(\n context,\n draft,\n {\n code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */,\n message: `Wait duration exceeds the budget of ${maxWaitMs} ms`\n },\n step.id\n );\n }\n const effect = { type: \"WAIT\" /* WAIT */, stepId: step.id };\n if (action.durationMs !== void 0) {\n effect.durationMs = action.durationMs;\n }\n if (action.until !== void 0) {\n effect.until = action.until;\n }\n return emit(context, draft, effect);\n }\n case \"HTTP\" /* HTTP */: {\n const verdict = policy.httpAccess(action.request.url);\n if (verdict !== \"ALLOWED\" /* ALLOWED */) {\n return failRun(context, draft, accessDenied(verdict, \"HTTP request host\"), step.id);\n }\n return emit(context, draft, {\n type: \"HTTP\" /* HTTP */,\n stepId: step.id,\n request: action.request\n });\n }\n case \"HOST\" /* HOST */: {\n const verdict = policy.hostActionAccess(action.action);\n if (verdict !== \"ALLOWED\" /* ALLOWED */) {\n return failRun(context, draft, accessDenied(verdict, \"Host action\"), step.id);\n }\n const validated = policy.hostInput(action.action, action.input);\n if (\"error\" in validated) {\n return failRun(context, draft, validated.error, step.id);\n }\n return emit(context, draft, {\n type: \"HOST\" /* HOST */,\n stepId: step.id,\n action: action.action,\n input: validated.input\n });\n }\n // Logging and responding are granted to every run; the host bounds them (one response).\n case \"LOG\" /* LOG */: {\n const effect = {\n type: \"LOG\" /* LOG */,\n stepId: step.id,\n level: action.level,\n message: action.message\n };\n if (\"data\" in action) {\n effect.data = action.data;\n }\n return emit(context, draft, effect);\n }\n case \"RESPOND\" /* RESPOND */:\n return emit(context, draft, {\n type: \"RESPOND\" /* RESPOND */,\n stepId: step.id,\n response: action.response\n });\n }\n };\n var runStep = (context, draft, step, results) => {\n if (results === void 0) {\n const items = collectStepItems(step);\n if (items.length > 0) {\n return emit(context, draft, {\n type: \"EVALUATE\" /* EVALUATE */,\n stepId: step.id,\n items,\n context: { input: draft.input, steps: draft.outputs, vars: draft.vars }\n });\n }\n }\n const fields = resolveStepFields(step, results ?? NO_RESULTS);\n return applyAction(context, draft, step, executeStep(step, fields));\n };\n var drive = (context, draft) => {\n for (; ; ) {\n const frame = topFrame(draft);\n if (!frame) {\n draft.outcome = { status: \"SUCCEEDED\" /* SUCCEEDED */ };\n return settle(draft, \"SUCCEEDED\" /* SUCCEEDED */);\n }\n const sequence = resolveSequence(context.definition, frame.sequencePath);\n if (frame.index >= sequence.length) {\n draft.stack.pop();\n if (draft.stack.length > 0) {\n advance(draft);\n }\n continue;\n }\n const step = sequence[frame.index];\n context.observer.stepStarted(step.id);\n if (draft.counters.steps + 1 > context.policy.budget.maxSteps) {\n return failRun(\n context,\n draft,\n { code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */, message: \"Step budget exceeded\" },\n step.id\n );\n }\n draft.counters.steps += 1;\n const result = runStep(context, draft, step, void 0);\n if (result) {\n return result;\n }\n }\n };\n var startRun = (definition, input, policy, observer = SILENT_OBSERVER) => drive(\n { definition, policy, observer },\n {\n stateVersion: CURRENT_STATE_VERSION,\n formatVersion: CURRENT_FORMAT_VERSION,\n status: \"WAITING\" /* WAITING */,\n input,\n stack: [{ sequencePath: ROOT_SEQUENCE_PATH, index: 0 }],\n outputs: {},\n vars: {},\n pending: null,\n counters: { steps: 0, effects: 0 }\n }\n );\n var unexpected = (event, pending) => invalidRequest(`Event ${event.type} does not answer the pending ${pending.type} effect`);\n var readEvaluation = (pending, results) => {\n if (pending.type !== \"EVALUATE\" /* EVALUATE */) {\n throw invalidRequest(\n `Event ${\"EVALUATED\" /* EVALUATED */} does not answer the pending ${pending.type} effect`\n );\n }\n const values = /* @__PURE__ */ new Map();\n for (const item of pending.items) {\n const result = results.find((candidate) => candidate.id === item.id);\n if (!result) {\n throw invalidRequest(\"Evaluation results do not cover every item of the lot\");\n }\n if (!result.ok) {\n return result.error;\n }\n values.set(item.id, result.value);\n }\n return values;\n };\n var complete = (context, draft, step, output) => {\n setOwn(draft.outputs, step.id, { output });\n context.observer.stepFinished(step.id, { ok: true, output });\n advance(draft);\n return drive(context, draft);\n };\n var stepRun = (definition, state, event, policy, observer = SILENT_OBSERVER) => {\n if (state.stateVersion !== CURRENT_STATE_VERSION) {\n throw new InterpreterError(\n \"STATE_VERSION_UNSUPPORTED\" /* STATE_VERSION_UNSUPPORTED */,\n `Run state version ${String(state.stateVersion)} is not supported (this core reads version ${CURRENT_STATE_VERSION})`\n );\n }\n const pending = state.pending;\n if (state.status !== \"WAITING\" /* WAITING */ || !pending) {\n throw invalidRequest(`Event ${event.type} received by a run that waits for nothing`);\n }\n const context = { definition, policy, observer };\n const draft = draftOf(state);\n draft.pending = null;\n const current = resolveStep(definition, topFrame(draft));\n switch (event.type) {\n case \"EVALUATED\" /* EVALUATED */: {\n const values = readEvaluation(pending, event.results);\n if (!(values instanceof Map)) {\n return failRun(context, draft, values, current.id);\n }\n return runStep(context, draft, current, values) ?? drive(context, draft);\n }\n case \"HTTP_COMPLETED\" /* HTTP_COMPLETED */:\n if (pending.type !== \"HTTP\" /* HTTP */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.response);\n case \"HOST_COMPLETED\" /* HOST_COMPLETED */:\n if (pending.type !== \"HOST\" /* HOST */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.output);\n case \"WAIT_ELAPSED\" /* WAIT_ELAPSED */:\n if (pending.type !== \"WAIT\" /* WAIT */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"LOG_WRITTEN\" /* LOG_WRITTEN */:\n if (pending.type !== \"LOG\" /* LOG */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"RESPONSE_SENT\" /* RESPONSE_SENT */:\n if (pending.type !== \"RESPOND\" /* RESPOND */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"RESUMED\" /* RESUMED */:\n if (pending.type === \"EVALUATE\" /* EVALUATE */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.output);\n case \"EFFECT_FAILED\" /* EFFECT_FAILED */:\n return failRun(context, draft, event.error, current.id);\n }\n };\n\n // src/runner-protocol/execution-protocol.types.ts\n var MAX_PROGRESS_OUTPUT_CHARS = 4096;\n\n // src/engine/run-in-isolate.ts\n var RUNTIME_ERROR_CODES = new Set(Object.values(RuntimeErrorCode));\n var rejected = (code, message) => ({\n kind: \"REJECTED\" /* REJECTED */,\n code,\n message\n });\n var finished = (outcome) => ({\n kind: \"FINISHED\" /* FINISHED */,\n outcome\n });\n var isolatePolicy = (request) => {\n const exposed = new Set(request.capabilities);\n const declared = (action) => request.definition.accesses.some(\n (access) => access.kind === \"HOST_ACTION\" /* HOST_ACTION */ && access.action === action\n );\n return {\n // Waits above `suspendWaitAboveMs` suspend; the host bounds the others by the time left.\n budget: { ...request.budget, maxWaitMs: MAX_WAIT_DURATION_MS },\n httpAccess: () => exposed.has(\"http.fetch\" /* HTTP_FETCH */) ? \"ALLOWED\" /* ALLOWED */ : \"NOT_GRANTED\" /* NOT_GRANTED */,\n hostActionAccess: (action) => {\n if (!declared(action)) {\n return \"NOT_DECLARED\" /* NOT_DECLARED */;\n }\n return exposed.has(action) ? \"ALLOWED\" /* ALLOWED */ : \"NOT_GRANTED\" /* NOT_GRANTED */;\n },\n hostInput: (_action, input) => ({ input })\n };\n };\n var outputPreview = (output) => {\n let json;\n try {\n json = JSON.stringify(output);\n } catch {\n return { outputTruncated: true };\n }\n if (json === void 0) {\n return {};\n }\n if (json.length <= MAX_PROGRESS_OUTPUT_CHARS) {\n return { output };\n }\n return { output: json.slice(0, MAX_PROGRESS_OUTPUT_CHARS), outputTruncated: true };\n };\n var progressObserver = (host) => {\n const startedAt = /* @__PURE__ */ new Map();\n const durationOf = (stepId) => {\n const start = startedAt.get(stepId);\n startedAt.delete(stepId);\n return start === void 0 ? 0 : Math.max(0, host.now() - start);\n };\n const observer = {\n stepStarted: (stepId) => {\n startedAt.set(stepId, host.now());\n host.onProgress({ stepId, phase: \"started\" /* STARTED */ });\n },\n stepFinished: (stepId, finish) => {\n const durationMs = durationOf(stepId);\n host.onProgress(\n finish.ok ? {\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"SUCCEEDED\" /* SUCCEEDED */,\n durationMs,\n ...outputPreview(finish.output)\n } : {\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"FAILED\" /* FAILED */,\n durationMs,\n errorCode: finish.error.code\n }\n );\n }\n };\n const suspended = (stepId) => host.onProgress({\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"SUSPENDED\" /* SUSPENDED */,\n durationMs: durationOf(stepId)\n });\n return { observer, suspended };\n };\n var callOf = (effect) => {\n switch (effect.type) {\n case \"HTTP\" /* HTTP */:\n return { capability: \"http.fetch\" /* HTTP_FETCH */, args: effect.request };\n case \"HOST\" /* HOST */:\n return { capability: effect.action, args: effect.input };\n case \"WAIT\" /* WAIT */:\n return {\n capability: \"wait\" /* WAIT */,\n args: effect.durationMs !== void 0 ? { durationMs: effect.durationMs } : { until: effect.until }\n };\n case \"LOG\" /* LOG */: {\n const args = { level: effect.level, message: effect.message };\n if (\"data\" in effect) {\n args.data = effect.data;\n }\n return { capability: \"log.write\" /* LOG_WRITE */, args };\n }\n case \"RESPOND\" /* RESPOND */:\n return { capability: \"http.respond\" /* HTTP_RESPOND */, args: effect.response };\n }\n };\n var completionOf = (effect, value) => {\n switch (effect.type) {\n case \"HTTP\" /* HTTP */:\n return { type: \"HTTP_COMPLETED\" /* HTTP_COMPLETED */, response: value };\n case \"HOST\" /* HOST */:\n return { type: \"HOST_COMPLETED\" /* HOST_COMPLETED */, output: value };\n case \"WAIT\" /* WAIT */:\n return { type: \"WAIT_ELAPSED\" /* WAIT_ELAPSED */ };\n case \"LOG\" /* LOG */:\n return { type: \"LOG_WRITTEN\" /* LOG_WRITTEN */ };\n case \"RESPOND\" /* RESPOND */:\n return { type: \"RESPONSE_SENT\" /* RESPONSE_SENT */ };\n }\n };\n var callFailure = (effect, error) => {\n const fallback = effect.type === \"HTTP\" /* HTTP */ ? \"HTTP_ERROR\" /* HTTP_ERROR */ : \"HOST_ERROR\" /* HOST_ERROR */;\n const detail = {\n code: error.code !== void 0 && RUNTIME_ERROR_CODES.has(error.code) ? error.code : fallback,\n message: error.message\n };\n return { type: \"EFFECT_FAILED\" /* EFFECT_FAILED */, error: detail };\n };\n var waitsAboveThreshold = (effect, request, now) => {\n const threshold = request.suspendWaitAboveMs;\n if (threshold === void 0) {\n return false;\n }\n if (effect.durationMs !== void 0) {\n return effect.durationMs > threshold;\n }\n return effect.until !== void 0 && Date.parse(effect.until) - now > threshold;\n };\n var outcomeOf = (state) => {\n const outcome = state.outcome;\n if (state.status === \"SUCCEEDED\" /* SUCCEEDED */) {\n return outcome?.output === void 0 ? { status: \"SUCCEEDED\" /* SUCCEEDED */ } : { status: \"SUCCEEDED\" /* SUCCEEDED */, output: outcome.output };\n }\n if (outcome?.error) {\n const failure = {\n status: \"FAILED\" /* FAILED */,\n errorCode: outcome.error.code,\n errorMessage: outcome.error.message\n };\n if (outcome.error.stepId !== void 0) {\n failure.stepId = outcome.error.stepId;\n }\n return failure;\n }\n return outcome?.status === \"FAILED\" /* FAILED */ && outcome.output !== void 0 ? { status: \"FAILED\" /* FAILED */, output: outcome.output } : { status: \"FAILED\" /* FAILED */ };\n };\n var resumeRefusal = (state) => {\n if (state.stateVersion !== CURRENT_STATE_VERSION) {\n return rejected(\n \"STATE_VERSION_UNSUPPORTED\" /* STATE_VERSION_UNSUPPORTED */,\n `Run state version ${String(state.stateVersion)} is not supported (this core reads version ${CURRENT_STATE_VERSION})`\n );\n }\n if (state.status !== \"WAITING\" /* WAITING */ || !state.pending) {\n return rejected(\"INVALID_REQUEST\" /* INVALID_REQUEST */, \"The state to resume is not suspended\");\n }\n if (state.pending.type === \"EVALUATE\" /* EVALUATE */) {\n return rejected(\n \"INVALID_REQUEST\" /* INVALID_REQUEST */,\n \"The state to resume waits for an evaluation, which never suspends\"\n );\n }\n return null;\n };\n var runInIsolate = async (request, host) => {\n const { definition, state } = request;\n if (state !== void 0) {\n const refusal = resumeRefusal(state);\n if (refusal) {\n return refusal;\n }\n }\n const policy = isolatePolicy(request);\n const exposed = new Set(request.capabilities);\n const progress = progressObserver(host);\n const suspend = (stepId, suspendedState) => {\n progress.suspended(stepId);\n return finished({ status: \"SUSPENDED\" /* SUSPENDED */, state: suspendedState });\n };\n try {\n let result;\n if (state === void 0) {\n result = startRun(definition, request.input, policy, progress.observer);\n } else {\n progress.observer.stepStarted(state.pending.stepId);\n result = stepRun(\n definition,\n state,\n { type: \"RESUMED\" /* RESUMED */, output: request.resumeInput ?? null },\n policy,\n progress.observer\n );\n }\n while (result.status === \"WAITING\" /* WAITING */) {\n const effect = result.state.pending;\n if (!effect) {\n throw new InterpreterError(\"INVALID_REQUEST\" /* INVALID_REQUEST */, \"Run waits for no effect\");\n }\n let event;\n if (effect.type === \"EVALUATE\" /* EVALUATE */) {\n const results = await host.evaluate(\n effect.items,\n effect.context,\n effect.stepId,\n request.globals\n );\n event = { type: \"EVALUATED\" /* EVALUATED */, results };\n } else if (effect.type === \"WAIT\" /* WAIT */ && waitsAboveThreshold(effect, request, host.now())) {\n return suspend(effect.stepId, result.state);\n } else {\n const { capability, args } = callOf(effect);\n if (!exposed.has(capability)) {\n event = {\n type: \"EFFECT_FAILED\" /* EFFECT_FAILED */,\n error: {\n code: \"ACCESS_DENIED\" /* ACCESS_DENIED */,\n message: `Capability \"${capability}\" is not granted to the execution`\n }\n };\n } else {\n const answer = await host.callHost(effect.stepId, capability, args);\n if (!answer.ok) {\n event = callFailure(effect, answer.error);\n } else if (\"suspend\" in answer) {\n return suspend(effect.stepId, result.state);\n } else {\n event = completionOf(effect, answer.value);\n }\n }\n }\n result = stepRun(definition, result.state, event, policy, progress.observer);\n }\n return finished(outcomeOf(result.state));\n } catch (error) {\n if (error instanceof InterpreterError) {\n return finished({\n status: \"FAILED\" /* FAILED */,\n errorCode: error.code,\n errorMessage: error.message\n });\n }\n throw error;\n }\n };\n return __toCommonJS(engine_entry_exports);\n})();\n";
|
|
3
|
+
exports.ENGINE_SOURCE = "\"use strict\";\nvar AbyssRuntimeEngine = (() => {\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n };\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n // src/engine/engine-entry.ts\n var engine_entry_exports = {};\n __export(engine_entry_exports, {\n runInIsolate: () => runInIsolate\n });\n\n // src/errors/runtime-error-code.enum.ts\n var RuntimeErrorCode = /* @__PURE__ */ ((RuntimeErrorCode2) => {\n RuntimeErrorCode2[\"EXPRESSION_ERROR\"] = \"EXPRESSION_ERROR\";\n RuntimeErrorCode2[\"CODE_ERROR\"] = \"CODE_ERROR\";\n RuntimeErrorCode2[\"TIMEOUT\"] = \"TIMEOUT\";\n RuntimeErrorCode2[\"MEMORY_LIMIT\"] = \"MEMORY_LIMIT\";\n RuntimeErrorCode2[\"ACCESS_DENIED\"] = \"ACCESS_DENIED\";\n RuntimeErrorCode2[\"BUDGET_EXCEEDED\"] = \"BUDGET_EXCEEDED\";\n RuntimeErrorCode2[\"HOST_ERROR\"] = \"HOST_ERROR\";\n RuntimeErrorCode2[\"HTTP_ERROR\"] = \"HTTP_ERROR\";\n RuntimeErrorCode2[\"RUNNER_UNAVAILABLE\"] = \"RUNNER_UNAVAILABLE\";\n RuntimeErrorCode2[\"RUNNER_SATURATED\"] = \"RUNNER_SATURATED\";\n RuntimeErrorCode2[\"INVALID_REQUEST\"] = \"INVALID_REQUEST\";\n RuntimeErrorCode2[\"STATE_VERSION_UNSUPPORTED\"] = \"STATE_VERSION_UNSUPPORTED\";\n return RuntimeErrorCode2;\n })(RuntimeErrorCode || {});\n\n // src/definition/definition.limits.ts\n var MAX_WAIT_DURATION_MS = 30 * 24 * 60 * 60 * 1e3;\n var MIN_RESPONSE_STATUS = 200;\n var MAX_RESPONSE_STATUS = 599;\n\n // src/interpreter/interpreter-error.ts\n var InterpreterError = class extends Error {\n constructor(code, message) {\n super(message);\n this.name = \"InterpreterError\";\n this.code = code;\n }\n };\n\n // src/definition/definition.types.ts\n var CURRENT_FORMAT_VERSION = 1;\n\n // src/steps/value-source.ts\n var TEMPLATE_PATTERN = /\\{\\{[\\s\\S]*?\\}\\}/;\n var IDENTIFIER_KEY = /^[A-Za-z_$][\\w$-]*$/;\n var isExpressionValue = (value) => typeof value === \"object\" && value !== null && !Array.isArray(value) && Object.keys(value).length === 1 && typeof value.$expression === \"string\";\n var propertyPath = (base, key) => IDENTIFIER_KEY.test(key) ? `${base}.${key}` : `${base}[${JSON.stringify(key)}]`;\n var indexPath = (base, index) => `${base}[${index}]`;\n var collectItems = (path, source, items) => {\n if (typeof source === \"string\") {\n if (TEMPLATE_PATTERN.test(source)) {\n items.push({ id: path, kind: \"TEMPLATE\" /* TEMPLATE */, source });\n }\n return;\n }\n if (source === null || typeof source !== \"object\") {\n return;\n }\n if (isExpressionValue(source)) {\n items.push({ id: path, kind: \"EXPRESSION\" /* EXPRESSION */, source: source.$expression });\n return;\n }\n if (Array.isArray(source)) {\n source.forEach((entry, index) => collectItems(indexPath(path, index), entry, items));\n return;\n }\n for (const [key, entry] of Object.entries(source)) {\n collectItems(propertyPath(path, key), entry, items);\n }\n };\n var resolveValue = (path, source, results) => {\n if (typeof source === \"string\") {\n return TEMPLATE_PATTERN.test(source) ? results.get(path) : source;\n }\n if (source === null || typeof source !== \"object\") {\n return source;\n }\n if (isExpressionValue(source)) {\n return results.get(path);\n }\n if (Array.isArray(source)) {\n return source.map((entry, index) => resolveValue(indexPath(path, index), entry, results));\n }\n return Object.fromEntries(\n Object.entries(source).map(([key, entry]) => [\n key,\n resolveValue(propertyPath(path, key), entry, results)\n ])\n );\n };\n\n // src/steps/execute-step.ts\n var fail = (message) => ({\n kind: \"FAIL\" /* FAIL */,\n error: { code: \"EXPRESSION_ERROR\" /* EXPRESSION_ERROR */, message }\n });\n var headerValue = (value) => typeof value === \"string\" ? value : JSON.stringify(value) ?? \"\";\n var resolvedRecord = (base, keys, fields) => Object.fromEntries(keys.map((key) => [key, fields.get(propertyPath(base, key))]));\n var executeWait = (step, fields) => {\n if (step.durationMs !== void 0) {\n const durationMs = fields.get(\"durationMs\");\n if (typeof durationMs !== \"number\" || !Number.isInteger(durationMs) || durationMs < 0) {\n return fail(\"Wait duration must resolve to a non-negative integer number of milliseconds\");\n }\n return { kind: \"WAIT\" /* WAIT */, durationMs };\n }\n const until = fields.get(\"until\");\n if (typeof until !== \"string\" || Number.isNaN(Date.parse(until))) {\n return fail(\"Wait date must resolve to an ISO 8601 date\");\n }\n return { kind: \"WAIT\" /* WAIT */, until };\n };\n var executeLog = (step, fields) => {\n const message = fields.get(\"message\");\n const action = {\n kind: \"LOG\" /* LOG */,\n level: step.level,\n message: typeof message === \"string\" ? message : JSON.stringify(message) ?? \"\"\n };\n if (step.data !== void 0) {\n action.data = fields.get(\"data\");\n }\n return action;\n };\n var executeRespond = (step, fields) => {\n const status = fields.get(\"status\");\n if (typeof status !== \"number\" || !Number.isInteger(status) || status < MIN_RESPONSE_STATUS || status > MAX_RESPONSE_STATUS) {\n return fail(\n `Response status must resolve to an integer from ${MIN_RESPONSE_STATUS} to ${MAX_RESPONSE_STATUS}`\n );\n }\n const headers = resolvedRecord(\"headers\", Object.keys(step.headers ?? {}), fields);\n const response = {\n status,\n headers: Object.fromEntries(\n Object.entries(headers).map(([key, value]) => [key, headerValue(value)])\n )\n };\n if (step.body !== void 0) {\n response.body = fields.get(\"body\");\n }\n return { kind: \"RESPOND\" /* RESPOND */, response };\n };\n var executeStep = (step, fields) => {\n switch (step.type) {\n case \"CONDITION\" /* CONDITION */: {\n if (fields.get(\"if\")) {\n return { kind: \"DONE\" /* DONE */, output: \"then\", branch: \"then\" };\n }\n return step.else ? { kind: \"DONE\" /* DONE */, output: \"else\", branch: \"else\" } : { kind: \"DONE\" /* DONE */, output: \"else\" };\n }\n case \"SWITCH\" /* SWITCH */: {\n const value = fields.get(\"value\");\n const index = step.cases.findIndex(\n (_, caseIndex) => fields.get(`cases[${caseIndex}].match`) === value\n );\n if (index >= 0) {\n const branch = `cases[${index}].steps`;\n return { kind: \"DONE\" /* DONE */, output: `cases[${index}]`, branch };\n }\n return step.default ? { kind: \"DONE\" /* DONE */, output: \"default\", branch: \"default\" } : { kind: \"DONE\" /* DONE */, output: null };\n }\n case \"WAIT\" /* WAIT */:\n return executeWait(step, fields);\n case \"SET\" /* SET */: {\n const value = fields.get(\"value\");\n return {\n kind: \"DONE\" /* DONE */,\n output: value,\n variable: { name: step.variable, value }\n };\n }\n case \"CODE\" /* CODE */:\n return { kind: \"DONE\" /* DONE */, output: fields.get(\"source\") };\n case \"HTTP\" /* HTTP */: {\n const url = fields.get(\"url\");\n if (typeof url !== \"string\") {\n return fail(\"HTTP url must resolve to a string\");\n }\n const headers = resolvedRecord(\"headers\", Object.keys(step.headers ?? {}), fields);\n const request = {\n method: step.method,\n url,\n headers: Object.fromEntries(\n Object.entries(headers).map(([key, value]) => [key, headerValue(value)])\n )\n };\n if (step.body !== void 0) {\n request.body = fields.get(\"body\");\n }\n if (step.timeoutMs !== void 0) {\n request.timeoutMs = step.timeoutMs;\n }\n return { kind: \"HTTP\" /* HTTP */, request };\n }\n case \"HOST\" /* HOST */:\n return {\n kind: \"HOST\" /* HOST */,\n action: step.action,\n input: resolvedRecord(\"input\", Object.keys(step.input), fields)\n };\n case \"LOG\" /* LOG */:\n return executeLog(step, fields);\n case \"RESPOND\" /* RESPOND */:\n return executeRespond(step, fields);\n case \"STOP\" /* STOP */:\n return { kind: \"STOP\" /* STOP */, status: step.status, output: fields.get(\"output\") };\n }\n };\n\n // src/steps/step-fields.ts\n var recordFields = (base, record) => Object.entries(record ?? {}).map(([key, source]) => ({ path: propertyPath(base, key), source }));\n var optionalField = (path, source) => source === void 0 ? [] : [{ path, source }];\n var stepFields = (step) => {\n switch (step.type) {\n case \"CONDITION\" /* CONDITION */:\n return [{ path: \"if\", source: step.if }];\n case \"SWITCH\" /* SWITCH */:\n return [\n { path: \"value\", source: step.value },\n ...step.cases.map((switchCase, index) => ({\n path: `cases[${index}].match`,\n source: switchCase.match\n }))\n ];\n case \"WAIT\" /* WAIT */:\n return [\n ...optionalField(\"durationMs\", step.durationMs),\n ...optionalField(\"until\", step.until)\n ];\n case \"SET\" /* SET */:\n return [{ path: \"value\", source: step.value }];\n case \"CODE\" /* CODE */:\n return [];\n case \"HTTP\" /* HTTP */:\n return [\n { path: \"url\", source: step.url },\n ...recordFields(\"headers\", step.headers),\n ...optionalField(\"body\", step.body)\n ];\n case \"HOST\" /* HOST */:\n return recordFields(\"input\", step.input);\n case \"LOG\" /* LOG */:\n return [{ path: \"message\", source: step.message }, ...optionalField(\"data\", step.data)];\n case \"RESPOND\" /* RESPOND */:\n return [\n { path: \"status\", source: step.status },\n ...recordFields(\"headers\", step.headers),\n ...optionalField(\"body\", step.body)\n ];\n case \"STOP\" /* STOP */:\n return optionalField(\"output\", step.output);\n }\n };\n var collectStepItems = (step) => {\n if (step.type === \"CODE\" /* CODE */) {\n return [{ id: \"source\", kind: \"CODE\" /* CODE */, source: step.source }];\n }\n const items = [];\n for (const field of stepFields(step)) {\n collectItems(field.path, field.source, items);\n }\n return items;\n };\n var resolveStepFields = (step, results) => {\n if (step.type === \"CODE\" /* CODE */) {\n return /* @__PURE__ */ new Map([[\"source\", results.get(\"source\")]]);\n }\n return new Map(\n stepFields(step).map((field) => [field.path, resolveValue(field.path, field.source, results)])\n );\n };\n\n // src/interpreter/interpreter.types.ts\n var CURRENT_STATE_VERSION = 1;\n\n // src/interpreter/sequence-path.ts\n var ROOT = \"steps\";\n var SEGMENT = /\\[(\\d+)\\]\\.(?:(then|else|default)|cases\\[(\\d+)\\]\\.steps)/y;\n var corrupted = (path) => new InterpreterError(\n \"INVALID_REQUEST\" /* INVALID_REQUEST */,\n `Run state points outside the definition: ${path}`\n );\n var branchOf = (step, name, caseIndex) => {\n if (step.type === \"CONDITION\" /* CONDITION */) {\n return name === \"then\" ? step.then : name === \"else\" ? step.else : void 0;\n }\n if (step.type === \"SWITCH\" /* SWITCH */) {\n return name === \"default\" ? step.default : caseIndex === void 0 ? void 0 : step.cases[Number(caseIndex)]?.steps;\n }\n return void 0;\n };\n var resolveSequence = (definition, path) => {\n if (!path.startsWith(ROOT)) {\n throw corrupted(path);\n }\n let sequence = definition.steps;\n let position = ROOT.length;\n while (position < path.length) {\n SEGMENT.lastIndex = position;\n const match = SEGMENT.exec(path);\n const next = match ? branchOf(sequence[Number(match[1])], match[2], match[3]) : void 0;\n if (!match || !next) {\n throw corrupted(path);\n }\n sequence = next;\n position = SEGMENT.lastIndex;\n }\n return sequence;\n };\n var resolveStep = (definition, frame) => {\n const step = resolveSequence(definition, frame.sequencePath)[frame.index];\n if (!step) {\n throw corrupted(frame.sequencePath);\n }\n return step;\n };\n var branchPath = (frame, branch) => `${frame.sequencePath}[${frame.index}].${branch}`;\n var ROOT_SEQUENCE_PATH = ROOT;\n\n // src/interpreter/interpreter.ts\n var NO_RESULTS = /* @__PURE__ */ new Map();\n var SILENT_OBSERVER = {\n stepStarted: () => void 0,\n stepFinished: () => void 0\n };\n var invalidRequest = (message) => new InterpreterError(\"INVALID_REQUEST\" /* INVALID_REQUEST */, message);\n var draftOf = (state) => ({\n ...state,\n stack: state.stack.map((frame) => ({ ...frame })),\n outputs: { ...state.outputs },\n vars: { ...state.vars },\n counters: { ...state.counters }\n });\n var setOwn = (target, key, value) => {\n Object.defineProperty(target, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n };\n var topFrame = (draft) => draft.stack[draft.stack.length - 1];\n var advance = (draft) => {\n topFrame(draft).index += 1;\n };\n var settle = (draft, status) => {\n draft.status = status;\n draft.pending = null;\n return { state: draft, effects: [], status };\n };\n var failRun = (context, draft, error, stepId) => {\n draft.outcome = { status: \"FAILED\" /* FAILED */, error: { ...error, stepId } };\n context.observer.stepFinished(stepId, { ok: false, error });\n return settle(draft, \"FAILED\" /* FAILED */);\n };\n var emit = (context, draft, effect) => {\n if (draft.counters.effects + 1 > context.policy.budget.maxEffects) {\n return failRun(\n context,\n draft,\n { code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */, message: \"Effect budget exceeded\" },\n effect.stepId\n );\n }\n draft.counters.effects += 1;\n draft.pending = effect;\n draft.status = \"WAITING\" /* WAITING */;\n return { state: draft, effects: [effect], status: \"WAITING\" /* WAITING */ };\n };\n var accessDenied = (verdict, subject) => ({\n code: \"ACCESS_DENIED\" /* ACCESS_DENIED */,\n message: verdict === \"NOT_DECLARED\" /* NOT_DECLARED */ ? `${subject} is not declared by the definition` : `${subject} is not granted to the run`\n });\n var applyAction = (context, draft, step, action) => {\n const { policy, observer } = context;\n switch (action.kind) {\n case \"FAIL\" /* FAIL */:\n return failRun(context, draft, action.error, step.id);\n case \"STOP\" /* STOP */:\n draft.outcome = { status: action.status, output: action.output };\n observer.stepFinished(step.id, { ok: true, output: action.output });\n return settle(\n draft,\n action.status === \"SUCCEEDED\" /* SUCCEEDED */ ? \"SUCCEEDED\" /* SUCCEEDED */ : \"FAILED\" /* FAILED */\n );\n case \"DONE\" /* DONE */: {\n setOwn(draft.outputs, step.id, { output: action.output });\n observer.stepFinished(step.id, { ok: true, output: action.output });\n if (action.variable) {\n setOwn(draft.vars, action.variable.name, action.variable.value);\n }\n if (action.branch === void 0) {\n advance(draft);\n } else {\n draft.stack.push({ sequencePath: branchPath(topFrame(draft), action.branch), index: 0 });\n }\n return null;\n }\n case \"WAIT\" /* WAIT */: {\n const maxWaitMs = Math.min(policy.budget.maxWaitMs, MAX_WAIT_DURATION_MS);\n if (action.durationMs !== void 0 && action.durationMs > maxWaitMs) {\n return failRun(\n context,\n draft,\n {\n code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */,\n message: `Wait duration exceeds the budget of ${maxWaitMs} ms`\n },\n step.id\n );\n }\n const effect = { type: \"WAIT\" /* WAIT */, stepId: step.id };\n if (action.durationMs !== void 0) {\n effect.durationMs = action.durationMs;\n }\n if (action.until !== void 0) {\n effect.until = action.until;\n }\n return emit(context, draft, effect);\n }\n case \"HTTP\" /* HTTP */: {\n const verdict = policy.httpAccess(action.request.url);\n if (verdict !== \"ALLOWED\" /* ALLOWED */) {\n return failRun(context, draft, accessDenied(verdict, \"HTTP request host\"), step.id);\n }\n return emit(context, draft, {\n type: \"HTTP\" /* HTTP */,\n stepId: step.id,\n request: action.request\n });\n }\n case \"HOST\" /* HOST */: {\n const verdict = policy.hostActionAccess(action.action);\n if (verdict !== \"ALLOWED\" /* ALLOWED */) {\n return failRun(context, draft, accessDenied(verdict, \"Host action\"), step.id);\n }\n const validated = policy.hostInput(action.action, action.input);\n if (\"error\" in validated) {\n return failRun(context, draft, validated.error, step.id);\n }\n return emit(context, draft, {\n type: \"HOST\" /* HOST */,\n stepId: step.id,\n action: action.action,\n input: validated.input\n });\n }\n // Logging and responding are granted to every run; the host bounds them (one response).\n case \"LOG\" /* LOG */: {\n const effect = {\n type: \"LOG\" /* LOG */,\n stepId: step.id,\n level: action.level,\n message: action.message\n };\n if (\"data\" in action) {\n effect.data = action.data;\n }\n return emit(context, draft, effect);\n }\n case \"RESPOND\" /* RESPOND */:\n return emit(context, draft, {\n type: \"RESPOND\" /* RESPOND */,\n stepId: step.id,\n response: action.response\n });\n }\n };\n var runStep = (context, draft, step, results) => {\n if (results === void 0) {\n const items = collectStepItems(step);\n if (items.length > 0) {\n return emit(context, draft, {\n type: \"EVALUATE\" /* EVALUATE */,\n stepId: step.id,\n items,\n context: { input: draft.input, steps: draft.outputs, vars: draft.vars }\n });\n }\n }\n const fields = resolveStepFields(step, results ?? NO_RESULTS);\n return applyAction(context, draft, step, executeStep(step, fields));\n };\n var drive = (context, draft) => {\n for (; ; ) {\n const frame = topFrame(draft);\n if (!frame) {\n draft.outcome = { status: \"SUCCEEDED\" /* SUCCEEDED */ };\n return settle(draft, \"SUCCEEDED\" /* SUCCEEDED */);\n }\n const sequence = resolveSequence(context.definition, frame.sequencePath);\n if (frame.index >= sequence.length) {\n draft.stack.pop();\n if (draft.stack.length > 0) {\n advance(draft);\n }\n continue;\n }\n const step = sequence[frame.index];\n context.observer.stepStarted(step.id);\n if (draft.counters.steps + 1 > context.policy.budget.maxSteps) {\n return failRun(\n context,\n draft,\n { code: \"BUDGET_EXCEEDED\" /* BUDGET_EXCEEDED */, message: \"Step budget exceeded\" },\n step.id\n );\n }\n draft.counters.steps += 1;\n const result = runStep(context, draft, step, void 0);\n if (result) {\n return result;\n }\n }\n };\n var startRun = (definition, input, policy, observer = SILENT_OBSERVER) => drive(\n { definition, policy, observer },\n {\n stateVersion: CURRENT_STATE_VERSION,\n formatVersion: CURRENT_FORMAT_VERSION,\n status: \"WAITING\" /* WAITING */,\n input,\n stack: [{ sequencePath: ROOT_SEQUENCE_PATH, index: 0 }],\n outputs: {},\n vars: {},\n pending: null,\n counters: { steps: 0, effects: 0 }\n }\n );\n var unexpected = (event, pending) => invalidRequest(`Event ${event.type} does not answer the pending ${pending.type} effect`);\n var readEvaluation = (pending, results) => {\n if (pending.type !== \"EVALUATE\" /* EVALUATE */) {\n throw invalidRequest(\n `Event ${\"EVALUATED\" /* EVALUATED */} does not answer the pending ${pending.type} effect`\n );\n }\n const values = /* @__PURE__ */ new Map();\n for (const item of pending.items) {\n const result = results.find((candidate) => candidate.id === item.id);\n if (!result) {\n throw invalidRequest(\"Evaluation results do not cover every item of the lot\");\n }\n if (!result.ok) {\n return result.error;\n }\n values.set(item.id, result.value);\n }\n return values;\n };\n var complete = (context, draft, step, output) => {\n setOwn(draft.outputs, step.id, { output });\n context.observer.stepFinished(step.id, { ok: true, output });\n advance(draft);\n return drive(context, draft);\n };\n var stepRun = (definition, state, event, policy, observer = SILENT_OBSERVER) => {\n if (state.stateVersion !== CURRENT_STATE_VERSION) {\n throw new InterpreterError(\n \"STATE_VERSION_UNSUPPORTED\" /* STATE_VERSION_UNSUPPORTED */,\n `Run state version ${String(state.stateVersion)} is not supported (this core reads version ${CURRENT_STATE_VERSION})`\n );\n }\n const pending = state.pending;\n if (state.status !== \"WAITING\" /* WAITING */ || !pending) {\n throw invalidRequest(`Event ${event.type} received by a run that waits for nothing`);\n }\n const context = { definition, policy, observer };\n const draft = draftOf(state);\n draft.pending = null;\n const current = resolveStep(definition, topFrame(draft));\n switch (event.type) {\n case \"EVALUATED\" /* EVALUATED */: {\n const values = readEvaluation(pending, event.results);\n if (!(values instanceof Map)) {\n return failRun(context, draft, values, current.id);\n }\n return runStep(context, draft, current, values) ?? drive(context, draft);\n }\n case \"HTTP_COMPLETED\" /* HTTP_COMPLETED */:\n if (pending.type !== \"HTTP\" /* HTTP */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.response);\n case \"HOST_COMPLETED\" /* HOST_COMPLETED */:\n if (pending.type !== \"HOST\" /* HOST */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.output);\n case \"WAIT_ELAPSED\" /* WAIT_ELAPSED */:\n if (pending.type !== \"WAIT\" /* WAIT */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"LOG_WRITTEN\" /* LOG_WRITTEN */:\n if (pending.type !== \"LOG\" /* LOG */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"RESPONSE_SENT\" /* RESPONSE_SENT */:\n if (pending.type !== \"RESPOND\" /* RESPOND */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, null);\n case \"RESUMED\" /* RESUMED */:\n if (pending.type === \"EVALUATE\" /* EVALUATE */) {\n throw unexpected(event, pending);\n }\n return complete(context, draft, current, event.output);\n case \"EFFECT_FAILED\" /* EFFECT_FAILED */:\n return failRun(context, draft, event.error, current.id);\n }\n };\n\n // src/runner-protocol/execution-protocol.types.ts\n var MAX_PROGRESS_OUTPUT_CHARS = 4096;\n\n // src/engine/run-in-isolate.ts\n var RUNTIME_ERROR_CODES = new Set(Object.values(RuntimeErrorCode));\n var rejected = (code, message) => ({\n kind: \"REJECTED\" /* REJECTED */,\n code,\n message\n });\n var finished = (outcome) => ({\n kind: \"FINISHED\" /* FINISHED */,\n outcome\n });\n var isolatePolicy = (request) => {\n const exposed = new Set(request.capabilities);\n const declared = (action) => request.definition.accesses.some(\n (access) => access.kind === \"HOST_ACTION\" /* HOST_ACTION */ && access.action === action\n );\n return {\n // Waits above `suspendWaitAboveMs` suspend; the host bounds the others by the time left.\n budget: { ...request.budget, maxWaitMs: MAX_WAIT_DURATION_MS },\n httpAccess: () => exposed.has(\"http.fetch\" /* HTTP_FETCH */) ? \"ALLOWED\" /* ALLOWED */ : \"NOT_GRANTED\" /* NOT_GRANTED */,\n hostActionAccess: (action) => {\n if (!declared(action)) {\n return \"NOT_DECLARED\" /* NOT_DECLARED */;\n }\n return exposed.has(action) ? \"ALLOWED\" /* ALLOWED */ : \"NOT_GRANTED\" /* NOT_GRANTED */;\n },\n hostInput: (_action, input) => ({ input })\n };\n };\n var outputPreview = (output) => {\n let json;\n try {\n json = JSON.stringify(output);\n } catch {\n return { outputTruncated: true };\n }\n if (json === void 0) {\n return {};\n }\n if (json.length <= MAX_PROGRESS_OUTPUT_CHARS) {\n return { output };\n }\n return { output: json.slice(0, MAX_PROGRESS_OUTPUT_CHARS), outputTruncated: true };\n };\n var progressObserver = (host) => {\n const startedAt = /* @__PURE__ */ new Map();\n const durationOf = (stepId) => {\n const start = startedAt.get(stepId);\n startedAt.delete(stepId);\n return start === void 0 ? 0 : Math.max(0, host.now() - start);\n };\n const observer = {\n stepStarted: (stepId) => {\n startedAt.set(stepId, host.now());\n host.onProgress({ stepId, phase: \"started\" /* STARTED */ });\n },\n stepFinished: (stepId, finish) => {\n const durationMs = durationOf(stepId);\n host.onProgress(\n finish.ok ? {\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"SUCCEEDED\" /* SUCCEEDED */,\n durationMs,\n ...outputPreview(finish.output)\n } : {\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"FAILED\" /* FAILED */,\n durationMs,\n errorCode: finish.error.code\n }\n );\n }\n };\n const suspended = (stepId) => host.onProgress({\n stepId,\n phase: \"finished\" /* FINISHED */,\n status: \"SUSPENDED\" /* SUSPENDED */,\n durationMs: durationOf(stepId)\n });\n return { observer, suspended };\n };\n var callOf = (effect) => {\n switch (effect.type) {\n case \"HTTP\" /* HTTP */:\n return { capability: \"http.fetch\" /* HTTP_FETCH */, args: effect.request };\n case \"HOST\" /* HOST */:\n return { capability: effect.action, args: effect.input };\n case \"WAIT\" /* WAIT */:\n return {\n capability: \"wait\" /* WAIT */,\n args: effect.durationMs !== void 0 ? { durationMs: effect.durationMs } : { until: effect.until }\n };\n case \"LOG\" /* LOG */: {\n const args = { level: effect.level, message: effect.message };\n if (\"data\" in effect) {\n args.data = effect.data;\n }\n return { capability: \"log.write\" /* LOG_WRITE */, args };\n }\n case \"RESPOND\" /* RESPOND */:\n return { capability: \"http.respond\" /* HTTP_RESPOND */, args: effect.response };\n }\n };\n var completionOf = (effect, value) => {\n switch (effect.type) {\n case \"HTTP\" /* HTTP */:\n return { type: \"HTTP_COMPLETED\" /* HTTP_COMPLETED */, response: value };\n case \"HOST\" /* HOST */:\n return { type: \"HOST_COMPLETED\" /* HOST_COMPLETED */, output: value };\n case \"WAIT\" /* WAIT */:\n return { type: \"WAIT_ELAPSED\" /* WAIT_ELAPSED */ };\n case \"LOG\" /* LOG */:\n return { type: \"LOG_WRITTEN\" /* LOG_WRITTEN */ };\n case \"RESPOND\" /* RESPOND */:\n return { type: \"RESPONSE_SENT\" /* RESPONSE_SENT */ };\n }\n };\n var callFailure = (effect, error) => {\n const fallback = effect.type === \"HTTP\" /* HTTP */ ? \"HTTP_ERROR\" /* HTTP_ERROR */ : \"HOST_ERROR\" /* HOST_ERROR */;\n const detail = {\n code: error.code !== void 0 && RUNTIME_ERROR_CODES.has(error.code) ? error.code : fallback,\n message: error.message\n };\n return { type: \"EFFECT_FAILED\" /* EFFECT_FAILED */, error: detail };\n };\n var waitsAboveThreshold = (effect, request, now) => {\n const threshold = request.suspendWaitAboveMs;\n if (threshold === void 0) {\n return false;\n }\n if (effect.durationMs !== void 0) {\n return effect.durationMs > threshold;\n }\n return effect.until !== void 0 && Date.parse(effect.until) - now > threshold;\n };\n var outcomeOf = (state) => {\n const outcome = state.outcome;\n if (state.status === \"SUCCEEDED\" /* SUCCEEDED */) {\n return outcome?.output === void 0 ? { status: \"SUCCEEDED\" /* SUCCEEDED */ } : { status: \"SUCCEEDED\" /* SUCCEEDED */, output: outcome.output };\n }\n if (outcome?.error) {\n const failure = {\n status: \"FAILED\" /* FAILED */,\n errorCode: outcome.error.code,\n errorMessage: outcome.error.message\n };\n if (outcome.error.stepId !== void 0) {\n failure.stepId = outcome.error.stepId;\n }\n return failure;\n }\n return outcome?.status === \"FAILED\" /* FAILED */ && outcome.output !== void 0 ? { status: \"FAILED\" /* FAILED */, output: outcome.output } : { status: \"FAILED\" /* FAILED */ };\n };\n var resumeRefusal = (state) => {\n if (state.stateVersion !== CURRENT_STATE_VERSION) {\n return rejected(\n \"STATE_VERSION_UNSUPPORTED\" /* STATE_VERSION_UNSUPPORTED */,\n `Run state version ${String(state.stateVersion)} is not supported (this core reads version ${CURRENT_STATE_VERSION})`\n );\n }\n if (state.status !== \"WAITING\" /* WAITING */ || !state.pending) {\n return rejected(\"INVALID_REQUEST\" /* INVALID_REQUEST */, \"The state to resume is not suspended\");\n }\n if (state.pending.type === \"EVALUATE\" /* EVALUATE */) {\n return rejected(\n \"INVALID_REQUEST\" /* INVALID_REQUEST */,\n \"The state to resume waits for an evaluation, which never suspends\"\n );\n }\n return null;\n };\n var runInIsolate = async (request, host) => {\n const { definition, state } = request;\n if (state !== void 0) {\n const refusal = resumeRefusal(state);\n if (refusal) {\n return refusal;\n }\n }\n const policy = isolatePolicy(request);\n const exposed = new Set(request.capabilities);\n const progress = progressObserver(host);\n const suspend = (stepId, suspendedState) => {\n progress.suspended(stepId);\n return finished({ status: \"SUSPENDED\" /* SUSPENDED */, state: suspendedState });\n };\n try {\n let result;\n if (state === void 0) {\n result = startRun(definition, request.input, policy, progress.observer);\n } else {\n progress.observer.stepStarted(state.pending.stepId);\n result = stepRun(\n definition,\n state,\n { type: \"RESUMED\" /* RESUMED */, output: request.resumeInput ?? null },\n policy,\n progress.observer\n );\n }\n while (result.status === \"WAITING\" /* WAITING */) {\n const effect = result.state.pending;\n if (!effect) {\n throw new InterpreterError(\"INVALID_REQUEST\" /* INVALID_REQUEST */, \"Run waits for no effect\");\n }\n let event;\n if (effect.type === \"EVALUATE\" /* EVALUATE */) {\n const results = await host.evaluate(\n effect.items,\n effect.context,\n effect.stepId,\n request.globals\n );\n event = { type: \"EVALUATED\" /* EVALUATED */, results };\n } else if (effect.type === \"WAIT\" /* WAIT */ && waitsAboveThreshold(effect, request, host.now())) {\n return suspend(effect.stepId, result.state);\n } else {\n const { capability, args } = callOf(effect);\n if (!exposed.has(capability)) {\n event = {\n type: \"EFFECT_FAILED\" /* EFFECT_FAILED */,\n error: {\n code: \"ACCESS_DENIED\" /* ACCESS_DENIED */,\n message: `Capability \"${capability}\" is not granted to the execution`\n }\n };\n } else {\n const answer = await host.callHost(effect.stepId, capability, args);\n if (!answer.ok) {\n event = callFailure(effect, answer.error);\n } else if (\"suspend\" in answer) {\n return suspend(effect.stepId, result.state);\n } else {\n event = completionOf(effect, answer.value);\n }\n }\n }\n result = stepRun(definition, result.state, event, policy, progress.observer);\n }\n return finished(outcomeOf(result.state));\n } catch (error) {\n if (error instanceof InterpreterError) {\n return finished({\n status: \"FAILED\" /* FAILED */,\n errorCode: error.code,\n errorMessage: error.message\n });\n }\n throw error;\n }\n };\n return __toCommonJS(engine_entry_exports);\n})();\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution-protocol.types.js","sourceRoot":"","sources":["../../src/runner-protocol/execution-protocol.types.ts"],"names":[],"mappings":";;;AAQa,QAAA,kBAAkB,GAAG,kBAAkB,CAAC;AAGxC,QAAA,sBAAsB,GAAG,SAAS,CAAC;AAGnC,QAAA,yBAAyB,GAAG,KAAK,CAAC;AAM/C,IAAY,cASX;AATD,WAAY,cAAc;IAExB,2CAAyB,CAAA;IAEzB,+BAAa,CAAA;IAEb,yCAAuB,CAAA;IAEvB,+CAA6B,CAAA;AAC/B,CAAC,EATW,cAAc,8BAAd,cAAc,QASzB;AAED,IAAY,oBAOX;AAPD,WAAY,oBAAoB;IAC9B,2CAAmB,CAAA;IACnB,qCAAa,CAAA;IACb,kDAA0B,CAAA;IAC1B,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;AACvB,CAAC,EAPW,oBAAoB,oCAApB,oBAAoB,QAO/B;AAcY,QAAA,qBAAqB,GAAsB;IACtD,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,SAAS;CACV,CAAC;
|
|
1
|
+
{"version":3,"file":"execution-protocol.types.js","sourceRoot":"","sources":["../../src/runner-protocol/execution-protocol.types.ts"],"names":[],"mappings":";;;AAQa,QAAA,kBAAkB,GAAG,kBAAkB,CAAC;AAGxC,QAAA,sBAAsB,GAAG,SAAS,CAAC;AAGnC,QAAA,yBAAyB,GAAG,KAAK,CAAC;AAM/C,IAAY,cASX;AATD,WAAY,cAAc;IAExB,2CAAyB,CAAA;IAEzB,+BAAa,CAAA;IAEb,yCAAuB,CAAA;IAEvB,+CAA6B,CAAA;AAC/B,CAAC,EATW,cAAc,8BAAd,cAAc,QASzB;AAED,IAAY,oBAOX;AAPD,WAAY,oBAAoB;IAC9B,2CAAmB,CAAA;IACnB,qCAAa,CAAA;IACb,kDAA0B,CAAA;IAC1B,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;AACvB,CAAC,EAPW,oBAAoB,oCAApB,oBAAoB,QAO/B;AAcY,QAAA,qBAAqB,GAAsB;IACtD,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,SAAS;CACV,CAAC;AAyFF,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,gCAAmB,CAAA;IACnB,kCAAqB,CAAA;AACvB,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAED,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,qCAAuB,CAAA;IACvB,+BAAiB,CAAA;IAEjB,qCAAuB,CAAA;AACzB,CAAC,EALW,UAAU,0BAAV,UAAU,QAKrB;AAuBD,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,0CAAuB,CAAA;IACvB,oCAAiB,CAAA;IACjB,0CAAuB,CAAA;AACzB,CAAC,EAJW,eAAe,+BAAf,eAAe,QAI1B"}
|
package/package.json
CHANGED
|
@@ -14,7 +14,6 @@ const execution = (overrides: Partial<ExecutionCostInput> = {}): ExecutionCostIn
|
|
|
14
14
|
...NO_USAGE,
|
|
15
15
|
status: CostedExecutionStatus.RAN,
|
|
16
16
|
profile: ResourceProfile.S,
|
|
17
|
-
guaranteedCpu: false,
|
|
18
17
|
...overrides,
|
|
19
18
|
});
|
|
20
19
|
|
|
@@ -23,7 +22,7 @@ const usage = (overrides: Partial<StepUsage>): StepUsage => ({ ...NO_USAGE, ...o
|
|
|
23
22
|
const sum = (values: number[]): number => values.reduce((total, value) => total + value, 0);
|
|
24
23
|
|
|
25
24
|
describe('resource profiles and rates', () => {
|
|
26
|
-
it('follow ADR-
|
|
25
|
+
it('follow ADR-0240', () => {
|
|
27
26
|
expect(RESOURCE_PROFILES).toEqual({
|
|
28
27
|
S: { memoryMb: 128, cpuCoefficient: 1 },
|
|
29
28
|
M: { memoryMb: 256, cpuCoefficient: 1.05 },
|
|
@@ -34,7 +33,6 @@ describe('resource profiles and rates', () => {
|
|
|
34
33
|
expect(COST_RATES).toEqual({
|
|
35
34
|
executionMillicredits: 10,
|
|
36
35
|
cpuMillicreditsPerSecond: 500,
|
|
37
|
-
guaranteedCpuCoefficient: 1.5,
|
|
38
36
|
memoryMillicreditsPerGbSecond: 100,
|
|
39
37
|
networkOutMillicreditsPerMb: 1000,
|
|
40
38
|
httpCallMillicredits: 10,
|
|
@@ -68,16 +66,15 @@ describe('computeExecutionCost', () => {
|
|
|
68
66
|
);
|
|
69
67
|
});
|
|
70
68
|
|
|
71
|
-
it('applies the profile coefficient
|
|
69
|
+
it('applies the profile coefficient to the CPU part', () => {
|
|
72
70
|
const cpu = { cpuMs: 1_000 };
|
|
73
71
|
expect(computeExecutionCost(execution(cpu))).toBe(10 + 500);
|
|
74
|
-
expect(computeExecutionCost(execution({ ...cpu,
|
|
72
|
+
expect(computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.M }))).toBe(10 + 525);
|
|
75
73
|
expect(computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.XXL }))).toBe(
|
|
76
74
|
10 + 675,
|
|
77
75
|
);
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
).toBe(10 + 788); // 500 × 1.05 × 1.5 = 787.5
|
|
76
|
+
// 500 × 1.05 × 0.001 = 0.525: rounded half-up once, at the end.
|
|
77
|
+
expect(computeExecutionCost(execution({ cpuMs: 1, profile: ResourceProfile.M }))).toBe(10 + 1);
|
|
81
78
|
});
|
|
82
79
|
|
|
83
80
|
it('prices the allocated memory, the network out and the effects', () => {
|
|
@@ -126,7 +123,6 @@ describe('computeStepCost', () => {
|
|
|
126
123
|
];
|
|
127
124
|
const total = execution({
|
|
128
125
|
profile: ResourceProfile.M,
|
|
129
|
-
guaranteedCpu: true,
|
|
130
126
|
// The engine between the steps adds CPU and time measured at the execution level only.
|
|
131
127
|
cpuMs: 140,
|
|
132
128
|
wallMs: 3_500,
|
|
@@ -155,7 +151,7 @@ describe('computeStepCost', () => {
|
|
|
155
151
|
{ cpuMs: 0.37 * n, wallMs: 1.9 * n, httpCalls: 0 },
|
|
156
152
|
);
|
|
157
153
|
for (const profile of Object.values(ResourceProfile)) {
|
|
158
|
-
const total = execution({ ...totals, profile
|
|
154
|
+
const total = execution({ ...totals, profile });
|
|
159
155
|
const costs = computeStepCost({ execution: total, steps });
|
|
160
156
|
expect(sum(costs) + COST_RATES.executionMillicredits).toBe(computeExecutionCost(total));
|
|
161
157
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Metered cost of an execution, shared by Flow and Reflex (ADR-
|
|
1
|
+
// Metered cost of an execution, shared by Flow and Reflex (ADR-0240). Prices are in
|
|
2
2
|
// millicredits (thousandths of a credit). Every part is computed exactly, in integer
|
|
3
3
|
// sub-millicredit units, and rounded half-up once, at the end.
|
|
4
4
|
|
|
@@ -25,13 +25,11 @@ export const RESOURCE_PROFILES: Readonly<Record<ResourceProfile, ResourceProfile
|
|
|
25
25
|
[ResourceProfile.XXL]: { memoryMb: 2048, cpuCoefficient: 1.35 },
|
|
26
26
|
};
|
|
27
27
|
|
|
28
|
-
/** The ADR-
|
|
28
|
+
/** The ADR-0240 price list, in millicredits. */
|
|
29
29
|
export const COST_RATES = {
|
|
30
30
|
/** Once per execution, whatever its number of segments. */
|
|
31
31
|
executionMillicredits: 10,
|
|
32
32
|
cpuMillicreditsPerSecond: 500,
|
|
33
|
-
/** Multiplies the CPU part of an execution with a guaranteed core. */
|
|
34
|
-
guaranteedCpuCoefficient: 1.5,
|
|
35
33
|
/** Per GB-second of ALLOCATED memory (the profile's), GB = 1024 MB. */
|
|
36
34
|
memoryMillicreditsPerGbSecond: 100,
|
|
37
35
|
/** Per MB sent out, MB = 1024 × 1024 bytes. */
|
|
@@ -43,7 +41,7 @@ export const COST_RATES = {
|
|
|
43
41
|
export enum CostedExecutionStatus {
|
|
44
42
|
/** Ran (succeeded, failed or suspended): billed at the measure. */
|
|
45
43
|
RAN = 'RAN',
|
|
46
|
-
/** Stopped by a pod shutdown: free (ADR-
|
|
44
|
+
/** Stopped by a pod shutdown: free (ADR-0240 §6). */
|
|
47
45
|
INTERRUPTED = 'INTERRUPTED',
|
|
48
46
|
/** Refused before any step (401, 404, 429, paused, invalid input): free. */
|
|
49
47
|
REFUSED = 'REFUSED',
|
|
@@ -61,7 +59,6 @@ export interface StepUsage {
|
|
|
61
59
|
export interface ExecutionCostInput extends StepUsage {
|
|
62
60
|
status: CostedExecutionStatus;
|
|
63
61
|
profile: ResourceProfile;
|
|
64
|
-
guaranteedCpu: boolean;
|
|
65
62
|
/**
|
|
66
63
|
* True for the second and later segments of a suspended execution: they add their measure
|
|
67
64
|
* but not the execution price, paid once by the first segment.
|
|
@@ -77,14 +74,14 @@ export interface StepCostInput {
|
|
|
77
74
|
}
|
|
78
75
|
|
|
79
76
|
// Exact unit: 1 / UNITS_PER_MILLICREDIT of a millicredit. Durations are taken in microseconds
|
|
80
|
-
// (cpuMs and wallMs may carry fractions of a millisecond), coefficients in hundredths
|
|
81
|
-
//
|
|
82
|
-
//
|
|
77
|
+
// (cpuMs and wallMs may carry fractions of a millisecond), coefficients in hundredths. Each part
|
|
78
|
+
// is a product divided by a fixed denominator; UNITS_PER_MILLICREDIT is their least common
|
|
79
|
+
// multiple, 2^20 × 5^8, so that every part is an exact integer of units.
|
|
83
80
|
const MICROS_PER_SECOND = BigInt(1_000_000);
|
|
84
|
-
const CPU_DENOMINATOR = MICROS_PER_SECOND * BigInt(100)
|
|
81
|
+
const CPU_DENOMINATOR = MICROS_PER_SECOND * BigInt(100);
|
|
85
82
|
const MEMORY_DENOMINATOR = BigInt(1024) * MICROS_PER_SECOND;
|
|
86
83
|
const NETWORK_DENOMINATOR = BigInt(1024 * 1024);
|
|
87
|
-
const UNITS_PER_MILLICREDIT = BigInt(1_048_576) * BigInt(
|
|
84
|
+
const UNITS_PER_MILLICREDIT = BigInt(1_048_576) * BigInt(390_625);
|
|
88
85
|
const ZERO = BigInt(0);
|
|
89
86
|
const ONE = BigInt(1);
|
|
90
87
|
const TWO = BigInt(2);
|
|
@@ -100,20 +97,17 @@ const assertUsage = (usage: StepUsage, subject: string): void => {
|
|
|
100
97
|
|
|
101
98
|
const micros = (ms: number): bigint => BigInt(Math.round(ms * 1000));
|
|
102
99
|
const whole = (count: number): bigint => BigInt(Math.round(count));
|
|
103
|
-
/**
|
|
100
|
+
/** Profile coefficients have at most two decimals (1.05): exact as integers. */
|
|
104
101
|
const hundredths = (coefficient: number): bigint => BigInt(Math.round(coefficient * 100));
|
|
105
|
-
const thousandths = (coefficient: number): bigint => BigInt(Math.round(coefficient * 1000));
|
|
106
102
|
|
|
107
103
|
/** Variable cost (everything but the execution price) of a usage, in exact units. */
|
|
108
104
|
const variableUnits = (usage: StepUsage, execution: ExecutionCostInput): bigint => {
|
|
109
105
|
const profile = RESOURCE_PROFILES[execution.profile];
|
|
110
|
-
|
|
111
|
-
// cpuUs / 10^6 s × rate × coefficient% / 100 × guaranteed‰ / 1000
|
|
106
|
+
// cpuUs / 10^6 s × rate × coefficient% / 100
|
|
112
107
|
const cpu =
|
|
113
108
|
(micros(usage.cpuMs) *
|
|
114
109
|
BigInt(COST_RATES.cpuMillicreditsPerSecond) *
|
|
115
110
|
hundredths(profile.cpuCoefficient) *
|
|
116
|
-
thousandths(guaranteed) *
|
|
117
111
|
UNITS_PER_MILLICREDIT) /
|
|
118
112
|
CPU_DENOMINATOR;
|
|
119
113
|
// memoryMb / 1024 GB × wallUs / 10^6 s × rate
|
|
@@ -181,15 +181,15 @@ describe('validateDefinition', () => {
|
|
|
181
181
|
expect(pathsOf(at({ level: 'error' }))).toEqual(['steps[0].message']);
|
|
182
182
|
});
|
|
183
183
|
|
|
184
|
-
it('requires a RESPOND status, a literal one
|
|
184
|
+
it('requires a RESPOND status, a literal one from 200 to 599', () => {
|
|
185
185
|
const at = (status: unknown) => ({
|
|
186
186
|
...validDefinition(),
|
|
187
187
|
steps: [{ id: 'r', type: StepType.RESPOND, status }],
|
|
188
188
|
});
|
|
189
|
-
for (const good of [
|
|
189
|
+
for (const good of [200, 201, 599, '{{ input.status }}', { $expression: 'input.status' }]) {
|
|
190
190
|
expect(validateDefinition(at(good), catalog).ok).toBe(true);
|
|
191
191
|
}
|
|
192
|
-
for (const bad of [
|
|
192
|
+
for (const bad of [100, 199, 600, 200.5, 'ok']) {
|
|
193
193
|
expect(pathsOf(at(bad))).toEqual(['steps[0].status']);
|
|
194
194
|
}
|
|
195
195
|
const missing = { ...validDefinition(), steps: [{ id: 'r', type: StepType.RESPOND }] };
|
|
@@ -5,5 +5,5 @@ export const MAX_HTTP_TIMEOUT_MS = 30_000;
|
|
|
5
5
|
export const MAX_WAIT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
|
|
6
6
|
|
|
7
7
|
/** HTTP status range a RESPOND step may send. */
|
|
8
|
-
export const MIN_RESPONSE_STATUS =
|
|
8
|
+
export const MIN_RESPONSE_STATUS = 200;
|
|
9
9
|
export const MAX_RESPONSE_STATUS = 599;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// The interpreter driver that runs INSIDE the execution's isolate (ADR-
|
|
1
|
+
// The interpreter driver that runs INSIDE the execution's isolate (ADR-0239). It is bundled with
|
|
2
2
|
// the interpreter into one self-contained script (`@abyss-project/runtime/engine`), so it and
|
|
3
3
|
// everything it imports must stay free of Node, of web APIs absent from a bare V8 context
|
|
4
4
|
// (`URL`, `TextEncoder`, timers...), and of Joi:
|
|
@@ -3,7 +3,7 @@ import type { RuntimeDefinition } from '../definition/definition.types';
|
|
|
3
3
|
import type { RunState } from '../interpreter/interpreter.types';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* WebSocket sub-protocol of an execution (ADR-
|
|
6
|
+
* WebSocket sub-protocol of an execution (ADR-0239): one connection, one `execute`, one isolate
|
|
7
7
|
* running the whole definition. A new version is a new name, never a silent change.
|
|
8
8
|
*/
|
|
9
9
|
export const EXECUTION_PROTOCOL = 'abyss-runtime.v2';
|
|
@@ -66,8 +66,6 @@ export interface ExecutionLimits {
|
|
|
66
66
|
cpuTimeMs: number;
|
|
67
67
|
/** Wall-clock time of the whole execution (one segment when it suspends). */
|
|
68
68
|
wallTimeMs: number;
|
|
69
|
-
/** Whether the execution holds a core of the runner for itself. */
|
|
70
|
-
guaranteedCpu: boolean;
|
|
71
69
|
}
|
|
72
70
|
|
|
73
71
|
export interface ExecutionBudget {
|
|
@@ -130,6 +128,12 @@ export type ExecutionCallResultMessage =
|
|
|
130
128
|
|
|
131
129
|
export interface StepMetrics {
|
|
132
130
|
cpuMs: number;
|
|
131
|
+
/**
|
|
132
|
+
* What the step itself grew the heap by: the highest reading during the step minus the reading
|
|
133
|
+
* at its start, never below 0. An estimate that can err both ways (a late sample misses a short
|
|
134
|
+
* peak, a delayed GC keeps freed memory), and blind to the isolate's base heap and to what earlier
|
|
135
|
+
* steps left.
|
|
136
|
+
*/
|
|
133
137
|
heapPeakBytes: number;
|
|
134
138
|
wallMs: number;
|
|
135
139
|
}
|
|
@@ -21,7 +21,7 @@ const request: ExecutionRequest = {
|
|
|
21
21
|
executionId: 'exec-1',
|
|
22
22
|
definition: { formatVersion: CURRENT_FORMAT_VERSION, accesses: [], steps: [] },
|
|
23
23
|
input: { a: 1 },
|
|
24
|
-
limits: { memoryMb: 128, cpuTimeMs: 1_000, wallTimeMs: 300
|
|
24
|
+
limits: { memoryMb: 128, cpuTimeMs: 1_000, wallTimeMs: 300 },
|
|
25
25
|
budget: { maxSteps: 10, maxEffects: 10 },
|
|
26
26
|
};
|
|
27
27
|
|