@stackfactor/agent-utils 1.13.4 → 1.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +667 -23
- package/dist/cjs/agentProto.d.ts +13 -3
- package/dist/cjs/agentProto.d.ts.map +1 -1
- package/dist/cjs/agentProto.js +25 -4
- package/dist/cjs/backoff.d.ts +17 -0
- package/dist/cjs/backoff.d.ts.map +1 -0
- package/dist/cjs/backoff.js +26 -0
- package/dist/cjs/cancellation.d.ts +22 -0
- package/dist/cjs/cancellation.d.ts.map +1 -0
- package/dist/cjs/cancellation.js +36 -0
- package/dist/cjs/cli.d.ts +3 -0
- package/dist/cjs/cli.d.ts.map +1 -0
- package/dist/cjs/cli.js +85 -0
- package/dist/cjs/client.d.ts +11 -0
- package/dist/cjs/client.d.ts.map +1 -1
- package/dist/cjs/client.js +27 -0
- package/dist/cjs/const.d.ts +23 -0
- package/dist/cjs/const.d.ts.map +1 -1
- package/dist/cjs/const.js +23 -0
- package/dist/cjs/daemon.d.ts +94 -0
- package/dist/cjs/daemon.d.ts.map +1 -0
- package/dist/cjs/daemon.js +507 -0
- package/dist/cjs/daemonConfig.d.ts +45 -0
- package/dist/cjs/daemonConfig.d.ts.map +1 -0
- package/dist/cjs/daemonConfig.js +148 -0
- package/dist/cjs/daemonEnv.d.ts +10 -0
- package/dist/cjs/daemonEnv.d.ts.map +1 -0
- package/dist/cjs/daemonEnv.js +12 -0
- package/dist/cjs/durable/clientTool.d.ts +39 -0
- package/dist/cjs/durable/clientTool.d.ts.map +1 -0
- package/dist/cjs/durable/clientTool.js +90 -0
- package/dist/cjs/durable/index.d.ts +9 -0
- package/dist/cjs/durable/index.d.ts.map +1 -0
- package/dist/cjs/durable/index.js +16 -0
- package/dist/cjs/durable/journal.d.ts +218 -0
- package/dist/cjs/durable/journal.d.ts.map +1 -0
- package/dist/cjs/durable/journal.js +392 -0
- package/dist/cjs/durable/pause.d.ts +84 -0
- package/dist/cjs/durable/pause.d.ts.map +1 -0
- package/dist/cjs/durable/pause.js +241 -0
- package/dist/cjs/durable/resume.d.ts +27 -0
- package/dist/cjs/durable/resume.d.ts.map +1 -0
- package/dist/cjs/durable/resume.js +80 -0
- package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
- package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
- package/dist/cjs/durable/snapshotSaver.js +81 -0
- package/dist/cjs/durable/step.d.ts +28 -0
- package/dist/cjs/durable/step.d.ts.map +1 -0
- package/dist/cjs/durable/step.js +43 -0
- package/dist/cjs/index.d.ts +30 -7
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +28 -1
- package/dist/cjs/infrastructure.d.ts +50 -0
- package/dist/cjs/infrastructure.d.ts.map +1 -0
- package/dist/cjs/infrastructure.js +163 -0
- package/dist/cjs/langChain.d.ts +15 -3
- package/dist/cjs/langChain.d.ts.map +1 -1
- package/dist/cjs/langChain.js +986 -180
- package/dist/cjs/learningActivityMedia.d.ts +196 -0
- package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
- package/dist/cjs/learningActivityMedia.js +861 -0
- package/dist/cjs/learningContentPlan.d.ts +105 -0
- package/dist/cjs/learningContentPlan.d.ts.map +1 -0
- package/dist/cjs/learningContentPlan.js +305 -0
- package/dist/cjs/learningContentThread.d.ts +184 -0
- package/dist/cjs/learningContentThread.d.ts.map +1 -0
- package/dist/cjs/learningContentThread.js +407 -0
- package/dist/cjs/logger.d.ts +1 -0
- package/dist/cjs/logger.d.ts.map +1 -1
- package/dist/cjs/logger.js +17 -3
- package/dist/cjs/modelRates.d.ts +40 -0
- package/dist/cjs/modelRates.d.ts.map +1 -0
- package/dist/cjs/modelRates.js +76 -0
- package/dist/cjs/referenceContext.d.ts +4 -145
- package/dist/cjs/referenceContext.d.ts.map +1 -1
- package/dist/cjs/referenceContext.js +16 -251
- package/dist/cjs/retry.d.ts +64 -0
- package/dist/cjs/retry.d.ts.map +1 -0
- package/dist/cjs/retry.js +138 -0
- package/dist/cjs/runtimeContext.d.ts +8 -1
- package/dist/cjs/runtimeContext.d.ts.map +1 -1
- package/dist/cjs/runtimeContext.js +3 -1
- package/dist/cjs/serve.d.ts +3 -2
- package/dist/cjs/serve.d.ts.map +1 -1
- package/dist/cjs/serve.js +32 -2
- package/dist/cjs/sourceStore.d.ts +378 -0
- package/dist/cjs/sourceStore.d.ts.map +1 -0
- package/dist/cjs/sourceStore.js +872 -0
- package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
- package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
- package/dist/cjs/stackfactorKnowledge.js +108 -44
- package/dist/cjs/tavily.d.ts +108 -4
- package/dist/cjs/tavily.d.ts.map +1 -1
- package/dist/cjs/tavily.js +242 -21
- package/dist/cjs/usage.d.ts.map +1 -1
- package/dist/cjs/usage.js +9 -15
- package/dist/cjs/version.d.ts +3 -0
- package/dist/cjs/version.d.ts.map +1 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
- package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
- package/dist/cjs/workflow/bookkeeping.js +75 -0
- package/dist/cjs/workflow/index.d.ts +13 -0
- package/dist/cjs/workflow/index.d.ts.map +1 -0
- package/dist/cjs/workflow/index.js +51 -0
- package/dist/cjs/workflow/limits.d.ts +52 -0
- package/dist/cjs/workflow/limits.d.ts.map +1 -0
- package/dist/cjs/workflow/limits.js +62 -0
- package/dist/cjs/workflow/platformTransport.d.ts +39 -0
- package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
- package/dist/cjs/workflow/platformTransport.js +115 -0
- package/dist/cjs/workflow/retrying.d.ts +44 -0
- package/dist/cjs/workflow/retrying.d.ts.map +1 -0
- package/dist/cjs/workflow/retrying.js +82 -0
- package/dist/cjs/workflow/run.d.ts +195 -0
- package/dist/cjs/workflow/run.d.ts.map +1 -0
- package/dist/cjs/workflow/run.js +858 -0
- package/dist/cjs/workflow/testing/index.d.ts +3 -0
- package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
- package/dist/cjs/workflow/testing/index.js +6 -0
- package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
- package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
- package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
- package/dist/cjs/workflow/transport.d.ts +219 -0
- package/dist/cjs/workflow/transport.d.ts.map +1 -0
- package/dist/cjs/workflow/transport.js +19 -0
- package/dist/esm/agentProto.d.ts +13 -3
- package/dist/esm/agentProto.d.ts.map +1 -1
- package/dist/esm/agentProto.js +23 -3
- package/dist/esm/backoff.d.ts +17 -0
- package/dist/esm/backoff.d.ts.map +1 -0
- package/dist/esm/backoff.js +22 -0
- package/dist/esm/cancellation.d.ts +22 -0
- package/dist/esm/cancellation.d.ts.map +1 -0
- package/dist/esm/cancellation.js +27 -0
- package/dist/esm/cli.d.ts +3 -0
- package/dist/esm/cli.d.ts.map +1 -0
- package/dist/esm/cli.js +80 -0
- package/dist/esm/client.d.ts +11 -0
- package/dist/esm/client.d.ts.map +1 -1
- package/dist/esm/client.js +25 -1
- package/dist/esm/const.d.ts +23 -0
- package/dist/esm/const.d.ts.map +1 -1
- package/dist/esm/const.js +23 -0
- package/dist/esm/daemon.d.ts +94 -0
- package/dist/esm/daemon.d.ts.map +1 -0
- package/dist/esm/daemon.js +499 -0
- package/dist/esm/daemonConfig.d.ts +45 -0
- package/dist/esm/daemonConfig.d.ts.map +1 -0
- package/dist/esm/daemonConfig.js +142 -0
- package/dist/esm/daemonEnv.d.ts +10 -0
- package/dist/esm/daemonEnv.d.ts.map +1 -0
- package/dist/esm/daemonEnv.js +9 -0
- package/dist/esm/durable/clientTool.d.ts +39 -0
- package/dist/esm/durable/clientTool.d.ts.map +1 -0
- package/dist/esm/durable/clientTool.js +82 -0
- package/dist/esm/durable/index.d.ts +9 -0
- package/dist/esm/durable/index.d.ts.map +1 -0
- package/dist/esm/durable/index.js +8 -0
- package/dist/esm/durable/journal.d.ts +218 -0
- package/dist/esm/durable/journal.d.ts.map +1 -0
- package/dist/esm/durable/journal.js +374 -0
- package/dist/esm/durable/pause.d.ts +84 -0
- package/dist/esm/durable/pause.d.ts.map +1 -0
- package/dist/esm/durable/pause.js +226 -0
- package/dist/esm/durable/resume.d.ts +27 -0
- package/dist/esm/durable/resume.d.ts.map +1 -0
- package/dist/esm/durable/resume.js +72 -0
- package/dist/esm/durable/snapshotSaver.d.ts +38 -0
- package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
- package/dist/esm/durable/snapshotSaver.js +77 -0
- package/dist/esm/durable/step.d.ts +28 -0
- package/dist/esm/durable/step.d.ts.map +1 -0
- package/dist/esm/durable/step.js +36 -0
- package/dist/esm/index.d.ts +30 -7
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +20 -4
- package/dist/esm/infrastructure.d.ts +50 -0
- package/dist/esm/infrastructure.d.ts.map +1 -0
- package/dist/esm/infrastructure.js +156 -0
- package/dist/esm/langChain.d.ts +15 -3
- package/dist/esm/langChain.d.ts.map +1 -1
- package/dist/esm/langChain.js +984 -179
- package/dist/esm/learningActivityMedia.d.ts +196 -0
- package/dist/esm/learningActivityMedia.d.ts.map +1 -0
- package/dist/esm/learningActivityMedia.js +807 -0
- package/dist/esm/learningContentPlan.d.ts +105 -0
- package/dist/esm/learningContentPlan.d.ts.map +1 -0
- package/dist/esm/learningContentPlan.js +299 -0
- package/dist/esm/learningContentThread.d.ts +184 -0
- package/dist/esm/learningContentThread.d.ts.map +1 -0
- package/dist/esm/learningContentThread.js +364 -0
- package/dist/esm/logger.d.ts +1 -0
- package/dist/esm/logger.d.ts.map +1 -1
- package/dist/esm/logger.js +17 -3
- package/dist/esm/modelRates.d.ts +40 -0
- package/dist/esm/modelRates.d.ts.map +1 -0
- package/dist/esm/modelRates.js +68 -0
- package/dist/esm/referenceContext.d.ts +4 -145
- package/dist/esm/referenceContext.d.ts.map +1 -1
- package/dist/esm/referenceContext.js +16 -243
- package/dist/esm/retry.d.ts +64 -0
- package/dist/esm/retry.d.ts.map +1 -0
- package/dist/esm/retry.js +127 -0
- package/dist/esm/runtimeContext.d.ts +8 -1
- package/dist/esm/runtimeContext.d.ts.map +1 -1
- package/dist/esm/runtimeContext.js +3 -1
- package/dist/esm/serve.d.ts +3 -2
- package/dist/esm/serve.d.ts.map +1 -1
- package/dist/esm/serve.js +33 -3
- package/dist/esm/sourceStore.d.ts +378 -0
- package/dist/esm/sourceStore.d.ts.map +1 -0
- package/dist/esm/sourceStore.js +855 -0
- package/dist/esm/stackfactorKnowledge.d.ts +91 -7
- package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
- package/dist/esm/stackfactorKnowledge.js +101 -41
- package/dist/esm/tavily.d.ts +108 -4
- package/dist/esm/tavily.d.ts.map +1 -1
- package/dist/esm/tavily.js +237 -20
- package/dist/esm/usage.d.ts.map +1 -1
- package/dist/esm/usage.js +9 -15
- package/dist/esm/version.d.ts +3 -0
- package/dist/esm/version.d.ts.map +1 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/workflow/bookkeeping.d.ts +78 -0
- package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
- package/dist/esm/workflow/bookkeeping.js +67 -0
- package/dist/esm/workflow/index.d.ts +13 -0
- package/dist/esm/workflow/index.d.ts.map +1 -0
- package/dist/esm/workflow/index.js +10 -0
- package/dist/esm/workflow/limits.d.ts +52 -0
- package/dist/esm/workflow/limits.d.ts.map +1 -0
- package/dist/esm/workflow/limits.js +59 -0
- package/dist/esm/workflow/platformTransport.d.ts +39 -0
- package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
- package/dist/esm/workflow/platformTransport.js +110 -0
- package/dist/esm/workflow/retrying.d.ts +44 -0
- package/dist/esm/workflow/retrying.d.ts.map +1 -0
- package/dist/esm/workflow/retrying.js +73 -0
- package/dist/esm/workflow/run.d.ts +195 -0
- package/dist/esm/workflow/run.d.ts.map +1 -0
- package/dist/esm/workflow/run.js +850 -0
- package/dist/esm/workflow/testing/index.d.ts +3 -0
- package/dist/esm/workflow/testing/index.d.ts.map +1 -0
- package/dist/esm/workflow/testing/index.js +2 -0
- package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
- package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
- package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
- package/dist/esm/workflow/transport.d.ts +219 -0
- package/dist/esm/workflow/transport.d.ts.map +1 -0
- package/dist/esm/workflow/transport.js +16 -0
- package/package.json +8 -7
|
@@ -0,0 +1,1171 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.memoryTransport = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const runtimeContext_js_1 = require("../../runtimeContext.js");
|
|
6
|
+
const limits_js_1 = require("../limits.js");
|
|
7
|
+
// ── The platform's vocabulary (design §5.1), as core's INTEGRATIONS.WORKFLOW states it ──
|
|
8
|
+
const LIVE = "live";
|
|
9
|
+
const ENDED = "ended";
|
|
10
|
+
const HALTED = "halted";
|
|
11
|
+
const QUEUED = "queued";
|
|
12
|
+
const TAKEN = "taken";
|
|
13
|
+
const DONE = "done";
|
|
14
|
+
const FAILED = "failed";
|
|
15
|
+
const RESUME = "RESUME";
|
|
16
|
+
const INBOX = "INBOX";
|
|
17
|
+
const INTERACTIVE = "INTERACTIVE";
|
|
18
|
+
const HOUR_MS = 3_600_000;
|
|
19
|
+
/** Tool names, as core validates them (interactive tool calls, I2). */
|
|
20
|
+
const TOOL_NAME = /^[A-Za-z0-9_.-]+$/;
|
|
21
|
+
const TOOL_DESCRIPTION_MAX_CHARS = 2000;
|
|
22
|
+
/** The fields each wait kind is declared with (§6.2); `kind` and `tag` go with every one. */
|
|
23
|
+
const WAIT_FIELDS = {
|
|
24
|
+
input: ["prompt", "addressees", "deadline"],
|
|
25
|
+
run: ["runId", "deadline"],
|
|
26
|
+
event: ["event", "deadline"],
|
|
27
|
+
signal: ["name", "correlation", "deadline"],
|
|
28
|
+
timer: ["at"],
|
|
29
|
+
};
|
|
30
|
+
/** A refusal shaped as the platform's are: an error with `response.status` and `response.data`. */
|
|
31
|
+
const refusal = (status, error, detail) => {
|
|
32
|
+
const failure = new Error(`memoryTransport: ${status} ${error}${detail ? `: ${detail}` : ""}`);
|
|
33
|
+
failure.response = { status, data: { error, ...(detail ? { detail } : {}) } };
|
|
34
|
+
return failure;
|
|
35
|
+
};
|
|
36
|
+
const invalidWait = (detail) => refusal(422, "AGENT_WAIT_INVALID", detail);
|
|
37
|
+
/** The JSON the platform would store and answer: a copy, undefined as null. */
|
|
38
|
+
const wire = (value) => value === undefined ? null : JSON.parse(JSON.stringify(value));
|
|
39
|
+
const byteSize = (value) => value === undefined ? 0 : Buffer.byteLength(JSON.stringify(value) ?? "", "utf8");
|
|
40
|
+
const iso = (ms) => ms === null || ms === undefined ? null : new Date(ms).toISOString();
|
|
41
|
+
/** An event's data as kept: over INBOX_EVENT_DATA_MAX_BYTES it is null and flagged (§6.3). */
|
|
42
|
+
const capped = (data) => byteSize(data) > limits_js_1.LIMITS.INBOX_EVENT_DATA_MAX_BYTES
|
|
43
|
+
? { data: null, dataTruncated: true }
|
|
44
|
+
: { data: wire(data) };
|
|
45
|
+
const timeOf = (value, what) => {
|
|
46
|
+
const ms = typeof value === "string" || value instanceof Date ? Date.parse(String(value instanceof Date ? value.toISOString() : value)) : NaN;
|
|
47
|
+
if (Number.isNaN(ms))
|
|
48
|
+
throw invalidWait(`${what} is not a time`);
|
|
49
|
+
return ms;
|
|
50
|
+
};
|
|
51
|
+
const isString = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
|
|
52
|
+
/**
|
|
53
|
+
* `workflow.testing.memoryTransport()`: the agent routes of design §6.2 with
|
|
54
|
+
* core's rules (runner spec §8), so an agent's tests run every turn offline:
|
|
55
|
+
* one entry per take, `done`, release and end refused while entries are
|
|
56
|
+
* queued on a live workflow, deferral of a run that finds the lease held, the
|
|
57
|
+
* handled answer, halting by the turn budget and rate (W12), the wait caps,
|
|
58
|
+
* the timer floor and `until`.
|
|
59
|
+
*
|
|
60
|
+
* The platform knows a run by its token; this transport knows it by the run
|
|
61
|
+
* message bound as `params.data` (its `batchJobId`, `trigger`, `workflowId`,
|
|
62
|
+
* element), which is what `execute` and `asRun` bind, and what `serve()` and
|
|
63
|
+
* `runOnce()` bind for a real run. One transport serves every run of a test,
|
|
64
|
+
* as one platform does.
|
|
65
|
+
*/
|
|
66
|
+
const memoryTransport = (options = {}) => {
|
|
67
|
+
const base = options.now ?? (() => Date.now());
|
|
68
|
+
let offset = 0;
|
|
69
|
+
const now = () => base() + offset;
|
|
70
|
+
const leaseMs = (options.leaseSeconds ?? limits_js_1.LIMITS.TASK_LEASE_DEFAULT_SECONDS) * 1000;
|
|
71
|
+
let counter = 0;
|
|
72
|
+
const newId = () => (++counter).toString(16).padStart(24, "0");
|
|
73
|
+
const workflows = new Map();
|
|
74
|
+
const bindings = new Map();
|
|
75
|
+
const runs = new Map();
|
|
76
|
+
const started = [];
|
|
77
|
+
const drops = new Set();
|
|
78
|
+
// ── The run a call is made for ──────────────────────────────────────────
|
|
79
|
+
const register = (message) => {
|
|
80
|
+
const runId = String(message.batchJobId);
|
|
81
|
+
if (!runs.has(runId))
|
|
82
|
+
runs.set(runId, { message, status: "running" });
|
|
83
|
+
return runId;
|
|
84
|
+
};
|
|
85
|
+
const subjectOf = (data) => data.elementType !== undefined && data.elementType !== null &&
|
|
86
|
+
data.elementId !== undefined && data.elementId !== null
|
|
87
|
+
? { elementType: data.elementType, elementId: String(data.elementId) }
|
|
88
|
+
: null;
|
|
89
|
+
const runOf = () => {
|
|
90
|
+
const data = (0, runtimeContext_js_1.getContext)()?.params?.data;
|
|
91
|
+
if (!data?.batchJobId) {
|
|
92
|
+
throw new Error("memoryTransport: the call is not made inside a run (make it through execute() or asRun(), or bind a run message as params.data)");
|
|
93
|
+
}
|
|
94
|
+
const runId = register(data);
|
|
95
|
+
return {
|
|
96
|
+
runId,
|
|
97
|
+
data,
|
|
98
|
+
boundId: bindings.get(runId) ?? (data.workflowId ? String(data.workflowId) : null),
|
|
99
|
+
subject: subjectOf(data),
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
const sameSubject = (a, b) => Boolean(a && b && a.elementType === b.elementType && a.elementId === b.elementId);
|
|
103
|
+
/** The workflow a bound run reaches, or the one an unbound run's element has under `key`. */
|
|
104
|
+
const workflowOfRun = (ctx, key) => {
|
|
105
|
+
if (ctx.boundId)
|
|
106
|
+
return workflows.get(ctx.boundId) ?? null;
|
|
107
|
+
if (!ctx.subject)
|
|
108
|
+
return null;
|
|
109
|
+
for (const workflow of workflows.values()) {
|
|
110
|
+
if (sameSubject(workflow.subject, ctx.subject) && workflow.key === key)
|
|
111
|
+
return workflow;
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
};
|
|
115
|
+
const isHolder = (workflow, runId) => workflow.lease?.batchJobId === runId;
|
|
116
|
+
const notHolder = () => refusal(409, "AGENT_WORKFLOW_NOT_HOLDER");
|
|
117
|
+
/** A holder-only route's workflow; an unbound run holds nothing. Null when it was deleted. */
|
|
118
|
+
const holderWorkflowOf = (ctx) => {
|
|
119
|
+
if (!ctx.boundId)
|
|
120
|
+
throw notHolder();
|
|
121
|
+
const workflow = workflows.get(ctx.boundId) ?? null;
|
|
122
|
+
if (workflow && !isHolder(workflow, ctx.runId))
|
|
123
|
+
throw notHolder();
|
|
124
|
+
return workflow;
|
|
125
|
+
};
|
|
126
|
+
// ── Inputs (§6.3) ──────────────────────────────────────────────────────
|
|
127
|
+
/** The run's own input (W4): its wait's resume, none for a queued-input run, else its event. */
|
|
128
|
+
const ownInputOf = (ctx) => {
|
|
129
|
+
const { data } = ctx;
|
|
130
|
+
if (data.trigger === INBOX)
|
|
131
|
+
return null;
|
|
132
|
+
if (data.trigger === RESUME) {
|
|
133
|
+
return data.resume?.waitId ? { type: "resume", waitId: String(data.resume.waitId) } : null;
|
|
134
|
+
}
|
|
135
|
+
const payload = data.data !== undefined ? data.data : data.schedule !== undefined ? { schedule: data.schedule } : null;
|
|
136
|
+
return {
|
|
137
|
+
type: "event",
|
|
138
|
+
event: {
|
|
139
|
+
eventType: data.eventType ?? "PROCESS",
|
|
140
|
+
elementType: data.elementType ?? null,
|
|
141
|
+
elementId: data.elementId !== undefined && data.elementId !== null ? String(data.elementId) : null,
|
|
142
|
+
category: data.category ?? null,
|
|
143
|
+
...capped(payload),
|
|
144
|
+
userId: data.userId ?? null,
|
|
145
|
+
...(data.trigger === INTERACTIVE ? { contentType: data.contentType ?? data.payload?.contentType ?? null } : {}),
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* The key a run reaches its element's workflow by when it names none: `""`,
|
|
151
|
+
* but an INTERACTIVE run's own id (I5), for the lease, read, reopen and
|
|
152
|
+
* delete alike (core 82e723e0).
|
|
153
|
+
*/
|
|
154
|
+
const defaultKeyOf = (ctx) => (ctx.data.trigger === INTERACTIVE ? ctx.runId : "");
|
|
155
|
+
const findWait = (workflow, waitId) => workflow.waits.find((wait) => wait.id === waitId);
|
|
156
|
+
/** Where the run's own input stands: run already, taken by it, queued, or not there. */
|
|
157
|
+
const ownStateOf = (workflow, ctx, input) => {
|
|
158
|
+
if (!input)
|
|
159
|
+
return "none";
|
|
160
|
+
const mine = workflow.inbox.find((entry) => entry.sourceBatchJobId === ctx.runId) ??
|
|
161
|
+
(input.type === "resume"
|
|
162
|
+
? workflow.inbox.find((entry) => entry.type === "resume" && entry.waitId === input.waitId)
|
|
163
|
+
: undefined);
|
|
164
|
+
if (mine?.status === DONE || mine?.status === FAILED)
|
|
165
|
+
return "handled";
|
|
166
|
+
if (mine?.status === TAKEN && mine.takenBy === ctx.runId)
|
|
167
|
+
return "taken";
|
|
168
|
+
if (mine)
|
|
169
|
+
return "queued";
|
|
170
|
+
if (input.type === "resume") {
|
|
171
|
+
const wait = findWait(workflow, input.waitId);
|
|
172
|
+
if (!wait?.outcome || wait.outcome.delivered)
|
|
173
|
+
return "handled";
|
|
174
|
+
}
|
|
175
|
+
return "none";
|
|
176
|
+
};
|
|
177
|
+
const inputOf = (workflow, entry) => {
|
|
178
|
+
if (!entry)
|
|
179
|
+
return null;
|
|
180
|
+
if (entry.type === "event") {
|
|
181
|
+
const event = entry.event;
|
|
182
|
+
if (event.contentType !== undefined) {
|
|
183
|
+
return {
|
|
184
|
+
type: "interactive",
|
|
185
|
+
id: entry.id,
|
|
186
|
+
payload: {
|
|
187
|
+
contentType: event.contentType,
|
|
188
|
+
data: wire(event.data),
|
|
189
|
+
...(event.dataTruncated ? { dataTruncated: true } : {}),
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
type: "event",
|
|
195
|
+
id: entry.id,
|
|
196
|
+
eventType: event.eventType,
|
|
197
|
+
elementType: event.elementType,
|
|
198
|
+
elementId: event.elementId,
|
|
199
|
+
data: wire(event.data),
|
|
200
|
+
...(event.dataTruncated ? { dataTruncated: true } : {}),
|
|
201
|
+
userId: event.userId,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
// A resume entry names a settled wait: one is pushed only once its wait
|
|
205
|
+
// settles, and an outstanding wait is never pruned.
|
|
206
|
+
const wait = findWait(workflow, entry.waitId);
|
|
207
|
+
const outcome = wait.outcome;
|
|
208
|
+
return {
|
|
209
|
+
type: "resume",
|
|
210
|
+
id: entry.id,
|
|
211
|
+
waitId: entry.waitId,
|
|
212
|
+
kind: wait.kind,
|
|
213
|
+
tag: wait.tag,
|
|
214
|
+
outcome: outcome.status,
|
|
215
|
+
reason: outcome.reason,
|
|
216
|
+
input: wire(outcome.input),
|
|
217
|
+
...(outcome.inputTruncated ? { truncated: true } : {}),
|
|
218
|
+
by: outcome.by ? wire(outcome.by) : null,
|
|
219
|
+
};
|
|
220
|
+
};
|
|
221
|
+
const openWaitView = (wait) => ({
|
|
222
|
+
waitId: wait.id,
|
|
223
|
+
kind: wait.kind,
|
|
224
|
+
tag: wait.tag,
|
|
225
|
+
deadline: iso(wait.deadline),
|
|
226
|
+
declaredAt: iso(wait.declaredAt),
|
|
227
|
+
...(wait.prompt ? { title: wait.prompt.title } : {}),
|
|
228
|
+
...(wait.addressees ? { addressees: [...wait.addressees] } : {}),
|
|
229
|
+
...(wait.runId ? { runId: wait.runId } : {}),
|
|
230
|
+
...(wait.event ? { event: { ...wait.event } } : {}),
|
|
231
|
+
...(wait.signal ? { signal: { ...wait.signal } } : {}),
|
|
232
|
+
...(wait.at !== undefined ? { at: iso(wait.at) } : {}),
|
|
233
|
+
});
|
|
234
|
+
const openWaitsOf = (workflow) => workflow.waits.filter((wait) => !wait.outcome).map(openWaitView);
|
|
235
|
+
const hasQueued = (workflow) => workflow.inbox.some((entry) => entry.status === QUEUED);
|
|
236
|
+
const queuedEvents = (workflow) => workflow.inbox.filter((entry) => entry.type === "event" && entry.status === QUEUED).length;
|
|
237
|
+
const takenAnswer = (workflow, entry) => ({
|
|
238
|
+
taken: true,
|
|
239
|
+
workflowId: workflow.workflowId,
|
|
240
|
+
until: iso(workflow.lease.until),
|
|
241
|
+
state: wire(workflow.state),
|
|
242
|
+
version: String(workflow.version),
|
|
243
|
+
input: inputOf(workflow, entry),
|
|
244
|
+
openWaits: openWaitsOf(workflow),
|
|
245
|
+
interactive: workflow.interactive,
|
|
246
|
+
});
|
|
247
|
+
// ── Turns (W12) ────────────────────────────────────────────────────────
|
|
248
|
+
const turnLimitReached = (workflow, at) => {
|
|
249
|
+
const { turns } = workflow;
|
|
250
|
+
if (!(turns.total < turns.allowance))
|
|
251
|
+
return "TURN_BUDGET";
|
|
252
|
+
const max = limits_js_1.LIMITS.MAX_TURNS_PER_HOUR;
|
|
253
|
+
if (turns.recent.length >= max && !(turns.recent[turns.recent.length - max] < at - HOUR_MS)) {
|
|
254
|
+
return "TURN_RATE";
|
|
255
|
+
}
|
|
256
|
+
return null;
|
|
257
|
+
};
|
|
258
|
+
const countTurn = (workflow, at) => {
|
|
259
|
+
workflow.turns.total += 1;
|
|
260
|
+
workflow.turns.recent = [...workflow.turns.recent, at].slice(-limits_js_1.LIMITS.MAX_TURNS_PER_HOUR);
|
|
261
|
+
};
|
|
262
|
+
const halt = (workflow, reason, at) => {
|
|
263
|
+
workflow.status = HALTED;
|
|
264
|
+
workflow.halted = { at, reason, turns: workflow.turns.total };
|
|
265
|
+
};
|
|
266
|
+
// ── Inbox entries (W4) ─────────────────────────────────────────────────
|
|
267
|
+
const entryOf = (input, runId, status, at) => ({
|
|
268
|
+
id: newId(),
|
|
269
|
+
type: input.type,
|
|
270
|
+
...(input.event ? { event: input.event } : {}),
|
|
271
|
+
...(input.waitId ? { waitId: input.waitId } : {}),
|
|
272
|
+
sourceBatchJobId: runId,
|
|
273
|
+
status,
|
|
274
|
+
takenBy: status === TAKEN ? runId : null,
|
|
275
|
+
attempts: 0,
|
|
276
|
+
queuedAt: at,
|
|
277
|
+
});
|
|
278
|
+
/** An entry finished (done) or given up on (failed): an event's data dropped, a resume's wait delivered. */
|
|
279
|
+
const settleEntry = (workflow, entry, status) => {
|
|
280
|
+
entry.status = status;
|
|
281
|
+
entry.takenBy = null;
|
|
282
|
+
if (entry.event)
|
|
283
|
+
entry.event.data = null;
|
|
284
|
+
if (entry.type === "resume") {
|
|
285
|
+
const wait = findWait(workflow, entry.waitId);
|
|
286
|
+
if (wait?.outcome) {
|
|
287
|
+
wait.outcome.delivered = true;
|
|
288
|
+
wait.outcome.input = null;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
/** Done and failed entries go at the next save that ends a turn, release, end, let-go or takeover (§5.1). */
|
|
293
|
+
const prune = (workflow) => {
|
|
294
|
+
workflow.inbox = workflow.inbox.filter((entry) => entry.status !== DONE && entry.status !== FAILED);
|
|
295
|
+
const settled = workflow.waits.filter((wait) => wait.outcome?.delivered);
|
|
296
|
+
if (settled.length > limits_js_1.LIMITS.SETTLED_WAITS_KEPT) {
|
|
297
|
+
const drop = new Set(settled.slice(0, settled.length - limits_js_1.LIMITS.SETTLED_WAITS_KEPT));
|
|
298
|
+
workflow.waits = workflow.waits.filter((wait) => !drop.has(wait));
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
/** Recovery (W4): the entry the holder had taken back to the queue, attempts + 1, failed at the cap. */
|
|
302
|
+
const requeueTaken = (workflow, holderId) => {
|
|
303
|
+
let requeued = 0;
|
|
304
|
+
for (const entry of workflow.inbox) {
|
|
305
|
+
if (entry.status !== TAKEN || entry.takenBy !== holderId)
|
|
306
|
+
continue;
|
|
307
|
+
entry.attempts += 1;
|
|
308
|
+
if (entry.attempts >= limits_js_1.LIMITS.INPUT_MAX_ATTEMPTS) {
|
|
309
|
+
settleEntry(workflow, entry, FAILED);
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
entry.status = QUEUED;
|
|
313
|
+
entry.takenBy = null;
|
|
314
|
+
requeued += 1;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return requeued;
|
|
318
|
+
};
|
|
319
|
+
const markTakenDone = (workflow, runId) => {
|
|
320
|
+
for (const entry of workflow.inbox) {
|
|
321
|
+
if (entry.status === TAKEN && entry.takenBy === runId)
|
|
322
|
+
settleEntry(workflow, entry, DONE);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
/** Queues the run's own input for the holder or a person's resume; an event only under INBOX_MAX. */
|
|
326
|
+
const queueOwn = (workflow, ctx, input, at) => {
|
|
327
|
+
if (!input || ownStateOf(workflow, ctx, input) !== "none")
|
|
328
|
+
return;
|
|
329
|
+
if (input.type === "event" && queuedEvents(workflow) >= limits_js_1.LIMITS.INBOX_MAX)
|
|
330
|
+
return;
|
|
331
|
+
workflow.inbox.push(entryOf(input, ctx.runId, QUEUED, at));
|
|
332
|
+
};
|
|
333
|
+
// ── Runs the platform starts (W4, W6) ──────────────────────────────────
|
|
334
|
+
const subjectFields = (workflow) => workflow.subject
|
|
335
|
+
? { elementType: workflow.subject.elementType, elementId: workflow.subject.elementId }
|
|
336
|
+
: {};
|
|
337
|
+
const startRun = (fields) => {
|
|
338
|
+
const message = { batchJobId: newId(), ...fields };
|
|
339
|
+
runs.set(message.batchJobId, { message, status: "pending" });
|
|
340
|
+
started.push(message);
|
|
341
|
+
return message;
|
|
342
|
+
};
|
|
343
|
+
const isActive = (runId) => {
|
|
344
|
+
const status = runId ? runs.get(runId)?.status : undefined;
|
|
345
|
+
return status === "pending" || status === "running";
|
|
346
|
+
};
|
|
347
|
+
/** One queued-input run for a live workflow with queued input and a free lease (W4). */
|
|
348
|
+
const startQueuedRun = (workflow) => {
|
|
349
|
+
if (workflow.status !== LIVE || !hasQueued(workflow))
|
|
350
|
+
return null;
|
|
351
|
+
if (workflow.lease && workflow.lease.until > now())
|
|
352
|
+
return null;
|
|
353
|
+
if (isActive(workflow.queuedRun?.batchJobId))
|
|
354
|
+
return null;
|
|
355
|
+
const message = startRun({
|
|
356
|
+
trigger: INBOX,
|
|
357
|
+
eventType: INBOX,
|
|
358
|
+
workflowId: workflow.workflowId,
|
|
359
|
+
...subjectFields(workflow),
|
|
360
|
+
userId: workflow.createdBy,
|
|
361
|
+
});
|
|
362
|
+
workflow.queuedRun = { batchJobId: message.batchJobId, at: now() };
|
|
363
|
+
return message;
|
|
364
|
+
};
|
|
365
|
+
/** Queues a settled wait's resume, at most once (W6); whether it pushed one. */
|
|
366
|
+
const pushResume = (workflow, wait) => {
|
|
367
|
+
if (workflow.inbox.some((entry) => entry.type === "resume" && entry.waitId === wait.id))
|
|
368
|
+
return false;
|
|
369
|
+
workflow.inbox.push(entryOf({ type: "resume", waitId: wait.id }, null, QUEUED, now()));
|
|
370
|
+
return true;
|
|
371
|
+
};
|
|
372
|
+
/** A settled wait's resume (W6): into the inbox while halted or leased, else a resume run. */
|
|
373
|
+
const resume = (workflow, wait) => {
|
|
374
|
+
if (workflow.status === HALTED || (workflow.lease && workflow.lease.until > now())) {
|
|
375
|
+
pushResume(workflow, wait);
|
|
376
|
+
return { queued: true, run: null };
|
|
377
|
+
}
|
|
378
|
+
const run = startRun({
|
|
379
|
+
trigger: RESUME,
|
|
380
|
+
eventType: RESUME,
|
|
381
|
+
workflowId: workflow.workflowId,
|
|
382
|
+
resume: { waitId: wait.id, kind: wait.kind, outcome: { status: wait.outcome.status, reason: wait.outcome.reason } },
|
|
383
|
+
...subjectFields(workflow),
|
|
384
|
+
category: 1,
|
|
385
|
+
userId: workflow.createdBy,
|
|
386
|
+
});
|
|
387
|
+
return { queued: false, run };
|
|
388
|
+
};
|
|
389
|
+
/** What a settled wait hands its resume (§6.3): an event's data, or a run's outcome, capped. */
|
|
390
|
+
const outcomeInput = (wait, input) => {
|
|
391
|
+
if (wait.kind === "event") {
|
|
392
|
+
const event = input ?? {};
|
|
393
|
+
const kept = capped(event.data);
|
|
394
|
+
return {
|
|
395
|
+
input: { ...wire(event), data: kept.data },
|
|
396
|
+
...(kept.dataTruncated ? { inputTruncated: true } : {}),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
if (wait.kind === "run" && byteSize(input?.outcome) > limits_js_1.LIMITS.INBOX_EVENT_DATA_MAX_BYTES) {
|
|
400
|
+
return { input: { ...wire(input), outcome: null }, inputTruncated: true };
|
|
401
|
+
}
|
|
402
|
+
return { input: wire(input) };
|
|
403
|
+
};
|
|
404
|
+
const settleWait = (wait, status, reason, input, by, delivered = false) => {
|
|
405
|
+
wait.outcome = {
|
|
406
|
+
status,
|
|
407
|
+
reason,
|
|
408
|
+
at: now(),
|
|
409
|
+
by: by ?? null,
|
|
410
|
+
...(delivered ? { input: null } : outcomeInput(wait, input)),
|
|
411
|
+
delivered,
|
|
412
|
+
};
|
|
413
|
+
};
|
|
414
|
+
const findOpenWaitAnywhere = (waitId) => {
|
|
415
|
+
for (const workflow of workflows.values()) {
|
|
416
|
+
const wait = findWait(workflow, waitId);
|
|
417
|
+
if (wait)
|
|
418
|
+
return wait.outcome ? null : { workflow, wait };
|
|
419
|
+
}
|
|
420
|
+
return null;
|
|
421
|
+
};
|
|
422
|
+
/** The platform's sweep at this time: deadlines expire, timers fire (§7.3). */
|
|
423
|
+
const sweep = () => {
|
|
424
|
+
const at = now();
|
|
425
|
+
for (const workflow of workflows.values()) {
|
|
426
|
+
if (workflow.status === ENDED)
|
|
427
|
+
continue;
|
|
428
|
+
for (const wait of workflow.waits) {
|
|
429
|
+
if (wait.outcome)
|
|
430
|
+
continue;
|
|
431
|
+
if (wait.kind === "timer" && wait.at <= at) {
|
|
432
|
+
settleWait(wait, "resolved", "RESOLVED", null, null);
|
|
433
|
+
resume(workflow, wait);
|
|
434
|
+
}
|
|
435
|
+
else if (wait.deadline !== null && wait.deadline <= at) {
|
|
436
|
+
settleWait(wait, "expired", "DEADLINE", null, null);
|
|
437
|
+
resume(workflow, wait);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
// ── Declarations (§6.2) ────────────────────────────────────────────────
|
|
443
|
+
const checkQuestions = (prompt) => {
|
|
444
|
+
if (!prompt || typeof prompt !== "object")
|
|
445
|
+
throw invalidWait("an input wait needs a prompt");
|
|
446
|
+
for (const field of Object.keys(prompt)) {
|
|
447
|
+
if (!["title", "body", "questions"].includes(field))
|
|
448
|
+
throw invalidWait(`a prompt carries no ${field}`);
|
|
449
|
+
}
|
|
450
|
+
if (!isString(prompt.title, limits_js_1.LIMITS.TITLE_MAX_CHARS))
|
|
451
|
+
throw invalidWait("prompt.title");
|
|
452
|
+
if (prompt.body !== undefined && !(typeof prompt.body === "string" && prompt.body.length <= limits_js_1.LIMITS.DETAILS_MAX_CHARS)) {
|
|
453
|
+
throw invalidWait("prompt.body");
|
|
454
|
+
}
|
|
455
|
+
const questions = prompt.questions;
|
|
456
|
+
if (!Array.isArray(questions) || questions.length < 1 || questions.length > limits_js_1.LIMITS.MAX_QUESTIONS_PER_WAIT) {
|
|
457
|
+
throw invalidWait(`a wait has 1 to ${limits_js_1.LIMITS.MAX_QUESTIONS_PER_WAIT} questions`);
|
|
458
|
+
}
|
|
459
|
+
if (new Set(questions.map((question) => question?.id)).size !== questions.length) {
|
|
460
|
+
throw invalidWait("question ids are not distinct");
|
|
461
|
+
}
|
|
462
|
+
if (byteSize(questions) > limits_js_1.LIMITS.QUESTIONS_MAX_BYTES)
|
|
463
|
+
throw invalidWait("QUESTIONS_MAX_BYTES");
|
|
464
|
+
const tools = questions.filter((question) => question?.kind === "tool").length;
|
|
465
|
+
if (tools > 0 && tools < questions.length) {
|
|
466
|
+
throw invalidWait("a wait mixes tool questions with questions for a person");
|
|
467
|
+
}
|
|
468
|
+
for (const question of questions) {
|
|
469
|
+
if (!["question", "approval", "tool"].includes(question?.kind))
|
|
470
|
+
throw invalidWait(`question ${question?.id}`);
|
|
471
|
+
if (question.kind !== "tool")
|
|
472
|
+
continue;
|
|
473
|
+
const value = question.value ?? {};
|
|
474
|
+
if (!(isString(value.name, limits_js_1.LIMITS.TOOL_NAME_MAX_CHARS) && TOOL_NAME.test(value.name))) {
|
|
475
|
+
throw invalidWait(`question ${question.id}: tool name`);
|
|
476
|
+
}
|
|
477
|
+
if (value.description !== undefined && !(typeof value.description === "string" && value.description.length <= TOOL_DESCRIPTION_MAX_CHARS)) {
|
|
478
|
+
throw invalidWait(`question ${question.id}: description`);
|
|
479
|
+
}
|
|
480
|
+
if (!value.args || typeof value.args !== "object" || Array.isArray(value.args)) {
|
|
481
|
+
throw invalidWait(`question ${question.id}: args`);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
const declared = (decl, ctx, at) => {
|
|
486
|
+
const fields = decl && typeof decl === "object" ? WAIT_FIELDS[decl.kind] : undefined;
|
|
487
|
+
if (!fields)
|
|
488
|
+
throw invalidWait(`unknown wait kind ${decl?.kind}`);
|
|
489
|
+
for (const field of Object.keys(decl)) {
|
|
490
|
+
if (field !== "kind" && field !== "tag" && !fields.includes(field)) {
|
|
491
|
+
throw invalidWait(`a ${decl.kind} wait carries no ${field}`);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (decl.tag !== undefined && decl.tag !== null && !(typeof decl.tag === "string" && limits_js_1.LIMITS.WAIT_TAG_PATTERN.test(decl.tag))) {
|
|
495
|
+
throw invalidWait("tag");
|
|
496
|
+
}
|
|
497
|
+
const floor = at + limits_js_1.LIMITS.MIN_TIMER_SECONDS * 1000;
|
|
498
|
+
let deadline = null;
|
|
499
|
+
if (decl.deadline !== undefined && decl.deadline !== null) {
|
|
500
|
+
deadline = timeOf(decl.deadline, "deadline");
|
|
501
|
+
if (deadline < floor)
|
|
502
|
+
throw invalidWait(`a deadline is at least ${limits_js_1.LIMITS.MIN_TIMER_SECONDS} s away`);
|
|
503
|
+
}
|
|
504
|
+
const wait = {
|
|
505
|
+
id: null,
|
|
506
|
+
kind: decl.kind,
|
|
507
|
+
tag: decl.tag ?? null,
|
|
508
|
+
deadline,
|
|
509
|
+
declaredBy: ctx.runId,
|
|
510
|
+
declaredAt: at,
|
|
511
|
+
outcome: null,
|
|
512
|
+
};
|
|
513
|
+
if (decl.kind === "input") {
|
|
514
|
+
checkQuestions(decl.prompt);
|
|
515
|
+
const addressees = Array.isArray(decl.addressees)
|
|
516
|
+
? [...new Set(decl.addressees.map(String))]
|
|
517
|
+
: [];
|
|
518
|
+
if (addressees.length < 1 || addressees.length > limits_js_1.LIMITS.ADDRESSEES_MAX) {
|
|
519
|
+
throw invalidWait(`addressees are 1 to ${limits_js_1.LIMITS.ADDRESSEES_MAX} users`);
|
|
520
|
+
}
|
|
521
|
+
wait.prompt = wire(decl.prompt);
|
|
522
|
+
wait.addressees = addressees;
|
|
523
|
+
const tools = decl.prompt.questions.every((question) => question.kind === "tool");
|
|
524
|
+
if (tools && deadline === null)
|
|
525
|
+
wait.deadline = at + limits_js_1.LIMITS.TOOL_WAIT_DEFAULT_DEADLINE_SECONDS * 1000;
|
|
526
|
+
}
|
|
527
|
+
else if (decl.kind === "run") {
|
|
528
|
+
if (!isString(decl.runId, 64))
|
|
529
|
+
throw invalidWait("runId");
|
|
530
|
+
wait.runId = decl.runId;
|
|
531
|
+
}
|
|
532
|
+
else if (decl.kind === "event") {
|
|
533
|
+
const event = decl.event;
|
|
534
|
+
if (!event || typeof event !== "object")
|
|
535
|
+
throw invalidWait("event");
|
|
536
|
+
for (const field of Object.keys(event)) {
|
|
537
|
+
if (!["eventType", "elementType", "elementId"].includes(field))
|
|
538
|
+
throw invalidWait(`an event carries no ${field}`);
|
|
539
|
+
}
|
|
540
|
+
if (event.eventType === undefined || typeof event.elementType !== "number" || !isString(event.elementId, limits_js_1.LIMITS.WAIT_FIELD_MAX_CHARS)) {
|
|
541
|
+
throw invalidWait("event");
|
|
542
|
+
}
|
|
543
|
+
wait.event = { eventType: event.eventType, elementType: event.elementType, elementId: event.elementId };
|
|
544
|
+
}
|
|
545
|
+
else if (decl.kind === "signal") {
|
|
546
|
+
if (!isString(decl.name, limits_js_1.LIMITS.WAIT_FIELD_MAX_CHARS) || !isString(decl.correlation, limits_js_1.LIMITS.WAIT_FIELD_MAX_CHARS)) {
|
|
547
|
+
throw invalidWait("signal name and correlation");
|
|
548
|
+
}
|
|
549
|
+
wait.signal = { name: decl.name, correlation: decl.correlation };
|
|
550
|
+
}
|
|
551
|
+
else {
|
|
552
|
+
wait.at = timeOf(decl.at, "at");
|
|
553
|
+
if (wait.at < floor)
|
|
554
|
+
throw invalidWait(`a timer is at least ${limits_js_1.LIMITS.MIN_TIMER_SECONDS} s away`);
|
|
555
|
+
wait.deadline = null;
|
|
556
|
+
}
|
|
557
|
+
return wait;
|
|
558
|
+
};
|
|
559
|
+
const isOutstanding = (wait) => !wait.outcome || !wait.outcome.delivered;
|
|
560
|
+
const declarationsOf = (workflow, ctx, body, at) => {
|
|
561
|
+
const waits = body.waits ?? [];
|
|
562
|
+
const cancel = body.cancel ?? [];
|
|
563
|
+
if (!Array.isArray(waits) || !Array.isArray(cancel))
|
|
564
|
+
throw refusal(400, "INVALID_VALUE", "waits and cancel are lists");
|
|
565
|
+
if (waits.length > limits_js_1.LIMITS.OPEN_WAITS_MAX)
|
|
566
|
+
throw invalidWait(`more than OPEN_WAITS_MAX (${limits_js_1.LIMITS.OPEN_WAITS_MAX}) waits at once`);
|
|
567
|
+
const adding = waits.map((decl) => declared(decl, ctx, at));
|
|
568
|
+
let contacts;
|
|
569
|
+
if (body.contacts !== undefined && body.contacts !== null) {
|
|
570
|
+
if (!Array.isArray(body.contacts) || body.contacts.some((id) => !isString(id, 64))) {
|
|
571
|
+
throw refusal(422, "AGENT_WAIT_CONTACTS_INVALID");
|
|
572
|
+
}
|
|
573
|
+
contacts = [...new Set(body.contacts)];
|
|
574
|
+
if (contacts.length > limits_js_1.LIMITS.CONTACTS_MAX)
|
|
575
|
+
throw refusal(422, "AGENT_WAIT_CONTACTS_INVALID");
|
|
576
|
+
}
|
|
577
|
+
if (adding.length > 0) {
|
|
578
|
+
const cancelling = new Set(cancel.map(String));
|
|
579
|
+
const outstanding = [
|
|
580
|
+
...workflow.waits.filter((wait) => isOutstanding(wait) && !(cancelling.has(wait.id) && !wait.outcome)),
|
|
581
|
+
...adding,
|
|
582
|
+
];
|
|
583
|
+
if (outstanding.length > limits_js_1.LIMITS.OPEN_WAITS_MAX)
|
|
584
|
+
throw invalidWait("OPEN_WAITS_MAX");
|
|
585
|
+
if (outstanding.filter((wait) => wait.kind === "input").length > limits_js_1.LIMITS.OPEN_INPUT_WAITS_MAX) {
|
|
586
|
+
throw invalidWait("OPEN_INPUT_WAITS_MAX");
|
|
587
|
+
}
|
|
588
|
+
const bytes = outstanding.reduce((sum, wait) => sum + byteSize(wait.prompt) + (wait.outcome && !wait.outcome.delivered ? byteSize(wait.outcome.input) : 0), 0);
|
|
589
|
+
if (bytes > limits_js_1.LIMITS.OPEN_WAITS_MAX_BYTES)
|
|
590
|
+
throw invalidWait("OPEN_WAITS_MAX_BYTES");
|
|
591
|
+
}
|
|
592
|
+
return { adding, cancel: cancel.map(String), ...(contacts ? { contacts } : {}) };
|
|
593
|
+
};
|
|
594
|
+
/** Applies checked declarations; a `run` wait on a run already settled here resolves at once (§6.2). */
|
|
595
|
+
const applyDeclarations = (workflow, decl) => {
|
|
596
|
+
const cancelled = [];
|
|
597
|
+
for (const waitId of decl.cancel) {
|
|
598
|
+
const wait = workflow.waits.find((candidate) => candidate.id === waitId && !candidate.outcome);
|
|
599
|
+
if (!wait)
|
|
600
|
+
continue;
|
|
601
|
+
settleWait(wait, "cancelled", "CANCELLED_BY_AGENT", null, null, true);
|
|
602
|
+
cancelled.push(waitId);
|
|
603
|
+
}
|
|
604
|
+
const added = decl.adding.map((wait) => ({ ...wait, id: newId() }));
|
|
605
|
+
workflow.waits.push(...added);
|
|
606
|
+
if (decl.contacts)
|
|
607
|
+
workflow.contacts = decl.contacts;
|
|
608
|
+
return { added, cancelled };
|
|
609
|
+
};
|
|
610
|
+
const resolveEndedRunWaits = (workflow, added) => {
|
|
611
|
+
for (const wait of added) {
|
|
612
|
+
const run = wait.kind === "run" ? runs.get(wait.runId) : undefined;
|
|
613
|
+
if (run?.status !== "completed" && run?.status !== "failed")
|
|
614
|
+
continue;
|
|
615
|
+
settleWait(wait, "resolved", "RESOLVED", { status: run.status === "completed" ? 2 : 3, outcome: run.outcome ?? null }, { runId: wait.runId });
|
|
616
|
+
resume(workflow, wait);
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
const checkState = (state) => {
|
|
620
|
+
if (byteSize(state) > limits_js_1.LIMITS.STATE_MAX_BYTES)
|
|
621
|
+
throw refusal(413, "AGENT_WORKFLOW_STATE_TOO_LARGE");
|
|
622
|
+
};
|
|
623
|
+
const checkCode = (code) => {
|
|
624
|
+
if (code !== undefined && code !== null && !isString(code, limits_js_1.LIMITS.CODE_MAX_CHARS)) {
|
|
625
|
+
throw refusal(400, "INVALID_VALUE", "code");
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
const checkKey = (key) => {
|
|
629
|
+
if (key !== undefined && !(typeof key === "string" && limits_js_1.LIMITS.KEY_PATTERN.test(key))) {
|
|
630
|
+
throw refusal(400, "INVALID_VALUE", "key");
|
|
631
|
+
}
|
|
632
|
+
};
|
|
633
|
+
// ── The routes (§6.2) ──────────────────────────────────────────────────
|
|
634
|
+
const create = (ctx, input, key, code) => {
|
|
635
|
+
const at = now();
|
|
636
|
+
const createdBy = ctx.data.userId ? String(ctx.data.userId) : null;
|
|
637
|
+
const workflow = {
|
|
638
|
+
workflowId: newId(),
|
|
639
|
+
subject: ctx.subject,
|
|
640
|
+
key,
|
|
641
|
+
code: code ?? ctx.data.code ?? null,
|
|
642
|
+
createdBy,
|
|
643
|
+
createdByRun: ctx.runId,
|
|
644
|
+
interactive: ctx.data.trigger === INTERACTIVE,
|
|
645
|
+
contacts: createdBy ? [createdBy] : [],
|
|
646
|
+
version: 1,
|
|
647
|
+
status: LIVE,
|
|
648
|
+
turns: { total: 1, allowance: limits_js_1.LIMITS.MAX_TURNS, recent: [at] },
|
|
649
|
+
halted: null,
|
|
650
|
+
state: null,
|
|
651
|
+
lease: { batchJobId: ctx.runId, until: at + leaseMs },
|
|
652
|
+
lastTurnBy: ctx.runId,
|
|
653
|
+
queuedRun: null,
|
|
654
|
+
inbox: [],
|
|
655
|
+
waits: [],
|
|
656
|
+
checkpoint: null,
|
|
657
|
+
endedAt: null,
|
|
658
|
+
createdAt: at,
|
|
659
|
+
};
|
|
660
|
+
const entry = entryOf(input, ctx.runId, TAKEN, at);
|
|
661
|
+
workflow.inbox.push(entry);
|
|
662
|
+
workflows.set(workflow.workflowId, workflow);
|
|
663
|
+
bindings.set(ctx.runId, workflow.workflowId);
|
|
664
|
+
return takenAnswer(workflow, entry);
|
|
665
|
+
};
|
|
666
|
+
const leaseExisting = (workflow, ctx, input, reopen, code) => {
|
|
667
|
+
const at = now();
|
|
668
|
+
const own = ownStateOf(workflow, ctx, input);
|
|
669
|
+
if (own === "handled")
|
|
670
|
+
return { taken: false, handled: true };
|
|
671
|
+
if (isHolder(workflow, ctx.runId)) {
|
|
672
|
+
// A lease answered and asked again (its answer was lost): the same answer.
|
|
673
|
+
const mine = workflow.inbox.find((entry) => entry.sourceBatchJobId === ctx.runId && entry.status === TAKEN);
|
|
674
|
+
return takenAnswer(workflow, mine ?? null);
|
|
675
|
+
}
|
|
676
|
+
if (workflow.status === HALTED) {
|
|
677
|
+
queueOwn(workflow, ctx, input, at);
|
|
678
|
+
return { taken: false, halted: true };
|
|
679
|
+
}
|
|
680
|
+
if (workflow.status === ENDED && !reopen)
|
|
681
|
+
return { taken: false, ended: true };
|
|
682
|
+
if (workflow.lease && workflow.lease.until > at) {
|
|
683
|
+
queueOwn(workflow, ctx, input, at);
|
|
684
|
+
return { taken: false, deferred: true };
|
|
685
|
+
}
|
|
686
|
+
// The own input is handed out with the lease and counted as a turn,
|
|
687
|
+
// unless an earlier deferral already queued it.
|
|
688
|
+
const handing = input !== null && own === "none";
|
|
689
|
+
const reason = handing ? turnLimitReached(workflow, at) : null;
|
|
690
|
+
if (reason) {
|
|
691
|
+
// A reopening lease that halts leaves the workflow live-but-halted, with
|
|
692
|
+
// neither an end date nor a finished turn's checkpoint (W12).
|
|
693
|
+
if (reopen) {
|
|
694
|
+
workflow.endedAt = null;
|
|
695
|
+
workflow.checkpoint = null;
|
|
696
|
+
}
|
|
697
|
+
halt(workflow, reason, at);
|
|
698
|
+
queueOwn(workflow, ctx, input, at);
|
|
699
|
+
return { taken: false, halted: true };
|
|
700
|
+
}
|
|
701
|
+
const previous = workflow.lease?.batchJobId ?? null;
|
|
702
|
+
if (previous) {
|
|
703
|
+
// Taken over past `until`: the old holder's taken entry back to the queue.
|
|
704
|
+
prune(workflow);
|
|
705
|
+
requeueTaken(workflow, previous);
|
|
706
|
+
}
|
|
707
|
+
let entry = null;
|
|
708
|
+
if (handing) {
|
|
709
|
+
entry = entryOf(input, ctx.runId, TAKEN, at);
|
|
710
|
+
workflow.inbox.push(entry);
|
|
711
|
+
countTurn(workflow, at);
|
|
712
|
+
workflow.lastTurnBy = ctx.runId;
|
|
713
|
+
}
|
|
714
|
+
if (reopen && workflow.status === ENDED) {
|
|
715
|
+
workflow.status = LIVE;
|
|
716
|
+
workflow.endedAt = null;
|
|
717
|
+
workflow.checkpoint = null;
|
|
718
|
+
}
|
|
719
|
+
workflow.lease = { batchJobId: ctx.runId, until: at + leaseMs };
|
|
720
|
+
if (code !== undefined)
|
|
721
|
+
workflow.code = code;
|
|
722
|
+
if (!ctx.boundId)
|
|
723
|
+
bindings.set(ctx.runId, workflow.workflowId);
|
|
724
|
+
return takenAnswer(workflow, entry);
|
|
725
|
+
};
|
|
726
|
+
const routes = {
|
|
727
|
+
get: async (key) => {
|
|
728
|
+
const ctx = runOf();
|
|
729
|
+
checkKey(key);
|
|
730
|
+
const workflow = workflowOfRun(ctx, key ?? defaultKeyOf(ctx));
|
|
731
|
+
if (!workflow)
|
|
732
|
+
return null;
|
|
733
|
+
if (ctx.boundId && key !== undefined && key !== workflow.key) {
|
|
734
|
+
throw refusal(422, "AGENT_WORKFLOW_SUBJECT_MISMATCH");
|
|
735
|
+
}
|
|
736
|
+
return {
|
|
737
|
+
workflowId: workflow.workflowId,
|
|
738
|
+
status: workflow.status,
|
|
739
|
+
state: wire(workflow.state),
|
|
740
|
+
version: String(workflow.version),
|
|
741
|
+
lease: workflow.lease ? { batchJobId: workflow.lease.batchJobId, until: iso(workflow.lease.until) } : null,
|
|
742
|
+
openWaits: openWaitsOf(workflow),
|
|
743
|
+
queued: workflow.inbox.filter((entry) => entry.status === QUEUED).length,
|
|
744
|
+
interactive: workflow.interactive,
|
|
745
|
+
};
|
|
746
|
+
},
|
|
747
|
+
lease: async (body = {}) => {
|
|
748
|
+
const ctx = runOf();
|
|
749
|
+
checkKey(body.key);
|
|
750
|
+
checkCode(body.code);
|
|
751
|
+
const named = body.key;
|
|
752
|
+
const key = named ?? defaultKeyOf(ctx);
|
|
753
|
+
const workflow = workflowOfRun(ctx, key);
|
|
754
|
+
if (ctx.boundId) {
|
|
755
|
+
if (!workflow)
|
|
756
|
+
return { taken: false, missing: true };
|
|
757
|
+
if (named !== undefined && named !== workflow.key)
|
|
758
|
+
throw refusal(422, "AGENT_WORKFLOW_SUBJECT_MISMATCH");
|
|
759
|
+
}
|
|
760
|
+
const input = ownInputOf(ctx);
|
|
761
|
+
// A subject-less workflow is found only by the run bound to it. Core
|
|
762
|
+
// also looks one up by its creating run, for a create retried after its
|
|
763
|
+
// bind failed (W2); a bind cannot fail here, so a retry finds it bound.
|
|
764
|
+
if (!workflow) {
|
|
765
|
+
if (body.create !== true || !input)
|
|
766
|
+
return { taken: false, missing: true };
|
|
767
|
+
return create(ctx, input, key, body.code);
|
|
768
|
+
}
|
|
769
|
+
return leaseExisting(workflow, ctx, input, body.reopen === true, body.code);
|
|
770
|
+
},
|
|
771
|
+
take: async () => {
|
|
772
|
+
const ctx = runOf();
|
|
773
|
+
const workflow = holderWorkflowOf(ctx);
|
|
774
|
+
if (!workflow)
|
|
775
|
+
return { gone: true };
|
|
776
|
+
const at = now();
|
|
777
|
+
if (workflow.status === HALTED)
|
|
778
|
+
return { entry: null, halted: true };
|
|
779
|
+
const held = workflow.inbox.find((entry) => entry.status === TAKEN && entry.takenBy === ctx.runId);
|
|
780
|
+
if (held)
|
|
781
|
+
return { entry: inputOf(workflow, held), version: String(workflow.version) };
|
|
782
|
+
const queued = workflow.inbox.find((entry) => entry.status === QUEUED);
|
|
783
|
+
if (!queued)
|
|
784
|
+
return { entry: null, version: String(workflow.version) };
|
|
785
|
+
const reason = turnLimitReached(workflow, at);
|
|
786
|
+
if (reason) {
|
|
787
|
+
halt(workflow, reason, at);
|
|
788
|
+
return { entry: null, halted: true };
|
|
789
|
+
}
|
|
790
|
+
queued.status = TAKEN;
|
|
791
|
+
queued.takenBy = ctx.runId;
|
|
792
|
+
countTurn(workflow, at);
|
|
793
|
+
workflow.lastTurnBy = ctx.runId;
|
|
794
|
+
return { entry: inputOf(workflow, queued), version: String(workflow.version) };
|
|
795
|
+
},
|
|
796
|
+
save: async (body) => {
|
|
797
|
+
const ctx = runOf();
|
|
798
|
+
const workflow = holderWorkflowOf(ctx);
|
|
799
|
+
if (!workflow)
|
|
800
|
+
return { gone: true };
|
|
801
|
+
if (String(body?.version) !== String(workflow.version))
|
|
802
|
+
return { saved: false, versionMismatch: true };
|
|
803
|
+
checkState(body.state);
|
|
804
|
+
const done = body.done ?? null;
|
|
805
|
+
const entry = done
|
|
806
|
+
? workflow.inbox.find((candidate) => candidate.id === done && candidate.status === TAKEN && candidate.takenBy === ctx.runId)
|
|
807
|
+
: null;
|
|
808
|
+
if (done && !entry)
|
|
809
|
+
throw refusal(400, "INVALID_VALUE", "done names no entry this run has taken");
|
|
810
|
+
const decl = declarationsOf(workflow, ctx, body, now());
|
|
811
|
+
if (entry) {
|
|
812
|
+
prune(workflow);
|
|
813
|
+
settleEntry(workflow, entry, DONE);
|
|
814
|
+
}
|
|
815
|
+
workflow.state = wire(body.state);
|
|
816
|
+
workflow.version += 1;
|
|
817
|
+
const { added, cancelled } = applyDeclarations(workflow, decl);
|
|
818
|
+
resolveEndedRunWaits(workflow, added);
|
|
819
|
+
return {
|
|
820
|
+
saved: true,
|
|
821
|
+
version: String(workflow.version),
|
|
822
|
+
waits: added.map((wait) => ({ waitId: wait.id })),
|
|
823
|
+
cancelled,
|
|
824
|
+
};
|
|
825
|
+
},
|
|
826
|
+
release: async (body) => {
|
|
827
|
+
const ctx = runOf();
|
|
828
|
+
const workflow = holderWorkflowOf(ctx);
|
|
829
|
+
if (!workflow)
|
|
830
|
+
return { gone: true };
|
|
831
|
+
if (String(body?.version) !== String(workflow.version))
|
|
832
|
+
return { released: false, versionMismatch: true };
|
|
833
|
+
if (workflow.status !== HALTED && hasQueued(workflow))
|
|
834
|
+
return { released: false, inbox: true };
|
|
835
|
+
checkState(body.state);
|
|
836
|
+
checkCode(body.code);
|
|
837
|
+
const decl = declarationsOf(workflow, ctx, body, now());
|
|
838
|
+
prune(workflow);
|
|
839
|
+
markTakenDone(workflow, ctx.runId);
|
|
840
|
+
workflow.state = wire(body.state);
|
|
841
|
+
workflow.version += 1;
|
|
842
|
+
const { added, cancelled } = applyDeclarations(workflow, decl);
|
|
843
|
+
workflow.lease = null;
|
|
844
|
+
if (body.code !== undefined && body.code !== null)
|
|
845
|
+
workflow.code = body.code;
|
|
846
|
+
resolveEndedRunWaits(workflow, added);
|
|
847
|
+
return {
|
|
848
|
+
released: true,
|
|
849
|
+
version: String(workflow.version),
|
|
850
|
+
waits: added.map((wait) => ({ waitId: wait.id })),
|
|
851
|
+
cancelled,
|
|
852
|
+
};
|
|
853
|
+
},
|
|
854
|
+
end: async (body) => {
|
|
855
|
+
const ctx = runOf();
|
|
856
|
+
const workflow = holderWorkflowOf(ctx);
|
|
857
|
+
if (!workflow)
|
|
858
|
+
return { gone: true };
|
|
859
|
+
if (String(body?.version) !== String(workflow.version))
|
|
860
|
+
return { ended: false, versionMismatch: true };
|
|
861
|
+
if (hasQueued(workflow)) {
|
|
862
|
+
return workflow.status === HALTED ? { ended: false, halted: true } : { ended: false, inbox: true };
|
|
863
|
+
}
|
|
864
|
+
if (body.state !== undefined) {
|
|
865
|
+
checkState(body.state);
|
|
866
|
+
workflow.state = wire(body.state);
|
|
867
|
+
}
|
|
868
|
+
prune(workflow);
|
|
869
|
+
markTakenDone(workflow, ctx.runId);
|
|
870
|
+
for (const wait of workflow.waits) {
|
|
871
|
+
if (!wait.outcome)
|
|
872
|
+
settleWait(wait, "cancelled", "WORKFLOW_ENDED", null, null, true);
|
|
873
|
+
}
|
|
874
|
+
workflow.version += 1;
|
|
875
|
+
workflow.status = ENDED;
|
|
876
|
+
workflow.endedAt = now();
|
|
877
|
+
workflow.lease = null;
|
|
878
|
+
workflow.checkpoint = null;
|
|
879
|
+
return { ended: true };
|
|
880
|
+
},
|
|
881
|
+
letGo: async () => {
|
|
882
|
+
const ctx = runOf();
|
|
883
|
+
if (!ctx.boundId)
|
|
884
|
+
return { letGo: false };
|
|
885
|
+
const workflow = workflows.get(ctx.boundId);
|
|
886
|
+
if (!workflow)
|
|
887
|
+
return { gone: true };
|
|
888
|
+
if (!isHolder(workflow, ctx.runId))
|
|
889
|
+
return { letGo: false };
|
|
890
|
+
prune(workflow);
|
|
891
|
+
const requeued = requeueTaken(workflow, ctx.runId);
|
|
892
|
+
workflow.lease = null;
|
|
893
|
+
return { letGo: true, requeued };
|
|
894
|
+
},
|
|
895
|
+
reopen: async () => {
|
|
896
|
+
const ctx = runOf();
|
|
897
|
+
const workflow = workflowOfRun(ctx, defaultKeyOf(ctx));
|
|
898
|
+
if (!workflow)
|
|
899
|
+
return { reopened: false, missing: true };
|
|
900
|
+
if (workflow.status === HALTED)
|
|
901
|
+
return { reopened: false, halted: true };
|
|
902
|
+
if (workflow.status === ENDED) {
|
|
903
|
+
workflow.status = LIVE;
|
|
904
|
+
workflow.endedAt = null;
|
|
905
|
+
workflow.checkpoint = null;
|
|
906
|
+
}
|
|
907
|
+
return { reopened: true };
|
|
908
|
+
},
|
|
909
|
+
delete: async () => {
|
|
910
|
+
const ctx = runOf();
|
|
911
|
+
const workflow = workflowOfRun(ctx, defaultKeyOf(ctx));
|
|
912
|
+
if (!workflow)
|
|
913
|
+
return ctx.boundId ? { gone: true } : { deleted: true };
|
|
914
|
+
const at = now();
|
|
915
|
+
if (!isHolder(workflow, ctx.runId) && workflow.lease && workflow.lease.until > at) {
|
|
916
|
+
queueOwn(workflow, ctx, ownInputOf(ctx), at);
|
|
917
|
+
return { deleted: false, held: true };
|
|
918
|
+
}
|
|
919
|
+
workflows.delete(workflow.workflowId);
|
|
920
|
+
return { deleted: true };
|
|
921
|
+
},
|
|
922
|
+
cancelWait: async (waitId) => {
|
|
923
|
+
const ctx = runOf();
|
|
924
|
+
const workflow = holderWorkflowOf(ctx);
|
|
925
|
+
if (!workflow)
|
|
926
|
+
return { gone: true };
|
|
927
|
+
const wait = workflow.waits.find((candidate) => candidate.id === waitId && !candidate.outcome);
|
|
928
|
+
if (!wait)
|
|
929
|
+
return { cancelled: false };
|
|
930
|
+
settleWait(wait, "cancelled", "CANCELLED_BY_AGENT", null, null, true);
|
|
931
|
+
return { cancelled: true };
|
|
932
|
+
},
|
|
933
|
+
signal: async (body) => {
|
|
934
|
+
const ctx = runOf();
|
|
935
|
+
if (!isString(body?.name, limits_js_1.LIMITS.WAIT_FIELD_MAX_CHARS) || !isString(body?.correlation, limits_js_1.LIMITS.WAIT_FIELD_MAX_CHARS)) {
|
|
936
|
+
throw refusal(400, "INVALID_VALUE", "name and correlation");
|
|
937
|
+
}
|
|
938
|
+
if (byteSize(body.input) > limits_js_1.LIMITS.SIGNAL_INPUT_MAX_BYTES)
|
|
939
|
+
throw refusal(413, "AGENT_WORKFLOW_SIGNAL_TOO_LARGE");
|
|
940
|
+
let resolved = 0;
|
|
941
|
+
for (const workflow of workflows.values()) {
|
|
942
|
+
for (const wait of workflow.waits) {
|
|
943
|
+
if (wait.outcome || wait.kind !== "signal")
|
|
944
|
+
continue;
|
|
945
|
+
if (wait.signal.name !== body.name || wait.signal.correlation !== body.correlation)
|
|
946
|
+
continue;
|
|
947
|
+
settleWait(wait, "resolved", "RESOLVED", body.input, { runId: ctx.runId });
|
|
948
|
+
resume(workflow, wait);
|
|
949
|
+
resolved += 1;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return { resolved };
|
|
953
|
+
},
|
|
954
|
+
saveCheckpoint: async (bytes) => {
|
|
955
|
+
const ctx = runOf();
|
|
956
|
+
const workflow = holderWorkflowOf(ctx);
|
|
957
|
+
if (!workflow)
|
|
958
|
+
return { gone: true };
|
|
959
|
+
const data = Buffer.from(bytes);
|
|
960
|
+
if (data.length > limits_js_1.LIMITS.CHECKPOINT_MAX_BYTES)
|
|
961
|
+
throw refusal(413, "AGENT_WORKFLOW_CHECKPOINT_TOO_LARGE");
|
|
962
|
+
const sha256 = (0, node_crypto_1.createHash)("sha256").update(data).digest("hex");
|
|
963
|
+
const step = (workflow.checkpoint?.step ?? 0) + 1;
|
|
964
|
+
workflow.checkpoint = { step, sha256, bytes: data.length, savedAt: now(), data };
|
|
965
|
+
return { saved: true, bytes: data.length, sha256, step };
|
|
966
|
+
},
|
|
967
|
+
getCheckpoint: async () => {
|
|
968
|
+
const ctx = runOf();
|
|
969
|
+
if (!ctx.boundId)
|
|
970
|
+
return null;
|
|
971
|
+
const workflow = workflows.get(ctx.boundId);
|
|
972
|
+
if (!workflow)
|
|
973
|
+
return { gone: true };
|
|
974
|
+
if (!workflow.checkpoint)
|
|
975
|
+
return null;
|
|
976
|
+
return {
|
|
977
|
+
bytes: Buffer.from(workflow.checkpoint.data),
|
|
978
|
+
sha256: workflow.checkpoint.sha256,
|
|
979
|
+
step: workflow.checkpoint.step,
|
|
980
|
+
};
|
|
981
|
+
},
|
|
982
|
+
};
|
|
983
|
+
// Each route, its answer lost once when the test asked (dropNextAnswer):
|
|
984
|
+
// applied, then failed as a network error with no response, which `retrying`
|
|
985
|
+
// retries and which is never an answer.
|
|
986
|
+
const transport = {};
|
|
987
|
+
for (const name of Object.keys(routes)) {
|
|
988
|
+
const route = routes[name];
|
|
989
|
+
transport[name] = async (...args) => {
|
|
990
|
+
const answer = await route(...args);
|
|
991
|
+
if (drops.delete(name)) {
|
|
992
|
+
const lost = new Error(`memoryTransport: the answer to ${name} was lost`);
|
|
993
|
+
lost.code = "ECONNRESET";
|
|
994
|
+
throw lost;
|
|
995
|
+
}
|
|
996
|
+
return answer;
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
// ── Hooks ──────────────────────────────────────────────────────────────
|
|
1000
|
+
const resolution = (resolved, done) => ({
|
|
1001
|
+
resolved,
|
|
1002
|
+
queued: done.queued,
|
|
1003
|
+
run: done.run,
|
|
1004
|
+
});
|
|
1005
|
+
const settle = (waitId, status, reason, input, by) => {
|
|
1006
|
+
const found = findOpenWaitAnywhere(waitId);
|
|
1007
|
+
if (!found)
|
|
1008
|
+
return { resolved: false, queued: false, run: null };
|
|
1009
|
+
if (found.wait.kind === "input" && byteSize(input) > limits_js_1.LIMITS.ANSWERS_MAX_BYTES) {
|
|
1010
|
+
throw refusal(422, "INVALID_VALUE", "ANSWERS_MAX_BYTES");
|
|
1011
|
+
}
|
|
1012
|
+
settleWait(found.wait, status, reason, input, by);
|
|
1013
|
+
return resolution(true, resume(found.workflow, found.wait));
|
|
1014
|
+
};
|
|
1015
|
+
/** finalizeRun (§7.5), for a run `execute` ran: frees a lease left held, queues a lost resume, starts the queued-input run. */
|
|
1016
|
+
const finalize = (runId) => {
|
|
1017
|
+
const message = runs.get(runId).message;
|
|
1018
|
+
for (const workflow of [...workflows.values()]) {
|
|
1019
|
+
let trigger = workflow.lastTurnBy === runId;
|
|
1020
|
+
if (workflow.lease?.batchJobId === runId) {
|
|
1021
|
+
prune(workflow);
|
|
1022
|
+
requeueTaken(workflow, runId);
|
|
1023
|
+
workflow.lease = null;
|
|
1024
|
+
trigger = true;
|
|
1025
|
+
}
|
|
1026
|
+
if (message.trigger === RESUME && String(message.workflowId) === workflow.workflowId) {
|
|
1027
|
+
// A resume run that ended before its lease took its resume with it (W6).
|
|
1028
|
+
const wait = findWait(workflow, String(message.resume?.waitId));
|
|
1029
|
+
if (wait?.outcome && !wait.outcome.delivered && pushResume(workflow, wait))
|
|
1030
|
+
trigger = true;
|
|
1031
|
+
}
|
|
1032
|
+
if (message.trigger === INBOX && workflow.queuedRun?.batchJobId === runId) {
|
|
1033
|
+
workflow.queuedRun.batchJobId = null;
|
|
1034
|
+
}
|
|
1035
|
+
if (trigger)
|
|
1036
|
+
startQueuedRun(workflow);
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
const contextFor = (message, signal, config = {}) => ({
|
|
1040
|
+
config,
|
|
1041
|
+
params: { contentType: message.eventType ?? message.trigger, data: message },
|
|
1042
|
+
request: { authToken: `memory-token:${message.batchJobId}` },
|
|
1043
|
+
event: 0,
|
|
1044
|
+
onProgress: null,
|
|
1045
|
+
onPartialResult: null,
|
|
1046
|
+
signal,
|
|
1047
|
+
session: null,
|
|
1048
|
+
});
|
|
1049
|
+
const advance = (ms) => {
|
|
1050
|
+
offset += ms;
|
|
1051
|
+
sweep();
|
|
1052
|
+
};
|
|
1053
|
+
const memory = {
|
|
1054
|
+
...transport,
|
|
1055
|
+
resolveWait: (waitId, input, by = null) => settle(waitId, "resolved", "RESOLVED", input, by),
|
|
1056
|
+
expireWait: (waitId) => settle(waitId, "expired", "DEADLINE", null, null),
|
|
1057
|
+
emit: (event) => {
|
|
1058
|
+
const data = event.data ?? null;
|
|
1059
|
+
const ev = {
|
|
1060
|
+
eventType: event.eventType,
|
|
1061
|
+
elementType: event.elementType,
|
|
1062
|
+
elementId: String(event.elementId),
|
|
1063
|
+
category: event.category ?? 1,
|
|
1064
|
+
data,
|
|
1065
|
+
userId: event.userId ?? null,
|
|
1066
|
+
};
|
|
1067
|
+
let resolved = 0;
|
|
1068
|
+
let queued = false;
|
|
1069
|
+
let run = null;
|
|
1070
|
+
const resolvedOn = new Set();
|
|
1071
|
+
for (const workflow of workflows.values()) {
|
|
1072
|
+
for (const wait of workflow.waits) {
|
|
1073
|
+
if (wait.outcome || wait.kind !== "event")
|
|
1074
|
+
continue;
|
|
1075
|
+
const target = wait.event;
|
|
1076
|
+
if (target.eventType !== ev.eventType || target.elementType !== ev.elementType || target.elementId !== ev.elementId)
|
|
1077
|
+
continue;
|
|
1078
|
+
settleWait(wait, "resolved", "RESOLVED", { eventType: ev.eventType, elementType: ev.elementType, elementId: ev.elementId, data, userId: ev.userId }, null);
|
|
1079
|
+
const done = resume(workflow, wait);
|
|
1080
|
+
queued = queued || done.queued;
|
|
1081
|
+
run = done.run ?? run;
|
|
1082
|
+
resolved += 1;
|
|
1083
|
+
resolvedOn.add(workflow.workflowId);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const subject = { elementType: ev.elementType, elementId: ev.elementId };
|
|
1087
|
+
const recipient = [...workflows.values()].find((workflow) => sameSubject(workflow.subject, subject) && workflow.key === "");
|
|
1088
|
+
// One input per workflow (W11): an event that resolved its wait is not also delivered.
|
|
1089
|
+
if (recipient && resolvedOn.has(recipient.workflowId))
|
|
1090
|
+
return { resolved, queued, run };
|
|
1091
|
+
if (recipient && (recipient.status === HALTED || (recipient.lease && recipient.lease.until > now()))) {
|
|
1092
|
+
if (queuedEvents(recipient) < limits_js_1.LIMITS.INBOX_MAX) {
|
|
1093
|
+
recipient.inbox.push(entryOf({ type: "event", event: { ...ev, ...capped(data) } }, null, QUEUED, now()));
|
|
1094
|
+
queued = true;
|
|
1095
|
+
}
|
|
1096
|
+
return { resolved, queued, run };
|
|
1097
|
+
}
|
|
1098
|
+
run = startRun({ ...ev, data: wire(data) });
|
|
1099
|
+
return { resolved, queued, run };
|
|
1100
|
+
},
|
|
1101
|
+
advance,
|
|
1102
|
+
dropNextAnswer: (operation) => {
|
|
1103
|
+
drops.add(operation);
|
|
1104
|
+
},
|
|
1105
|
+
snapshot: (workflowId) => {
|
|
1106
|
+
const workflow = workflowId ? workflows.get(workflowId) : [...workflows.values()].pop();
|
|
1107
|
+
if (!workflow)
|
|
1108
|
+
return null;
|
|
1109
|
+
const { checkpoint, ...rest } = workflow;
|
|
1110
|
+
return {
|
|
1111
|
+
...wire(rest),
|
|
1112
|
+
checkpoint: checkpoint ? { step: checkpoint.step, sha256: checkpoint.sha256, bytes: checkpoint.bytes, savedAt: checkpoint.savedAt } : null,
|
|
1113
|
+
};
|
|
1114
|
+
},
|
|
1115
|
+
get started() {
|
|
1116
|
+
return started;
|
|
1117
|
+
},
|
|
1118
|
+
execute: async (main, message, runOptions = {}) => {
|
|
1119
|
+
(0, runtimeContext_js_1.installGlobals)();
|
|
1120
|
+
const runId = register(message);
|
|
1121
|
+
const record = runs.get(runId);
|
|
1122
|
+
record.status = "running";
|
|
1123
|
+
const signal = runOptions.signal ?? null;
|
|
1124
|
+
try {
|
|
1125
|
+
const result = await (0, runtimeContext_js_1.runWithContext)(contextFor(message, signal, runOptions.config), () => main(signal ?? undefined));
|
|
1126
|
+
record.status = "completed";
|
|
1127
|
+
record.outcome = wire(result);
|
|
1128
|
+
return result;
|
|
1129
|
+
}
|
|
1130
|
+
catch (error) {
|
|
1131
|
+
record.status = "failed";
|
|
1132
|
+
record.outcome = { message: String(error?.message ?? error) };
|
|
1133
|
+
throw error;
|
|
1134
|
+
}
|
|
1135
|
+
finally {
|
|
1136
|
+
finalize(runId);
|
|
1137
|
+
}
|
|
1138
|
+
},
|
|
1139
|
+
asRun: async (message, fn) => {
|
|
1140
|
+
register(message);
|
|
1141
|
+
return await (0, runtimeContext_js_1.runWithContext)(contextFor(message, null), fn);
|
|
1142
|
+
},
|
|
1143
|
+
settled: (batchJobId) => {
|
|
1144
|
+
const record = runs.get(batchJobId);
|
|
1145
|
+
if (record?.status !== "completed" && record?.status !== "failed")
|
|
1146
|
+
return null;
|
|
1147
|
+
return { status: record.status, outcome: record.outcome };
|
|
1148
|
+
},
|
|
1149
|
+
deleteAsAdmin: (workflowId) => workflows.delete(workflowId),
|
|
1150
|
+
resumeHalted: (workflowId) => {
|
|
1151
|
+
const workflow = workflows.get(workflowId);
|
|
1152
|
+
if (workflow?.status !== HALTED)
|
|
1153
|
+
return null;
|
|
1154
|
+
workflow.status = LIVE;
|
|
1155
|
+
workflow.turns.recent = [];
|
|
1156
|
+
workflow.turns.allowance += limits_js_1.LIMITS.MAX_TURNS;
|
|
1157
|
+
return startQueuedRun(workflow);
|
|
1158
|
+
},
|
|
1159
|
+
clock: {
|
|
1160
|
+
now,
|
|
1161
|
+
sleep: async (ms, signal) => {
|
|
1162
|
+
if (signal?.aborted)
|
|
1163
|
+
return;
|
|
1164
|
+
advance(ms);
|
|
1165
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
1166
|
+
},
|
|
1167
|
+
},
|
|
1168
|
+
};
|
|
1169
|
+
return memory;
|
|
1170
|
+
};
|
|
1171
|
+
exports.memoryTransport = memoryTransport;
|