@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,858 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.run = exports.messageAdapter = void 0;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const logger_js_1 = __importDefault(require("../logger.js"));
|
|
9
|
+
const runtimeContext_js_1 = require("../runtimeContext.js");
|
|
10
|
+
const bookkeeping_js_1 = require("./bookkeeping.js");
|
|
11
|
+
const platformTransport_js_1 = require("./platformTransport.js");
|
|
12
|
+
const retrying_js_1 = require("./retrying.js");
|
|
13
|
+
const journal_js_1 = require("../durable/journal.js");
|
|
14
|
+
const pause_js_1 = require("../durable/pause.js");
|
|
15
|
+
const resume_js_1 = require("../durable/resume.js");
|
|
16
|
+
const DECISIONS = ["run", "ignore", "reopen", "create", "delete"];
|
|
17
|
+
// ── The input adapter ────────────────────────────────────────────────────
|
|
18
|
+
const TRIGGER = { RESUME: "RESUME", INBOX: "INBOX", INTERACTIVE: "INTERACTIVE" };
|
|
19
|
+
/**
|
|
20
|
+
* The run's own input from its run message (runner spec §3 "How it plugs
|
|
21
|
+
* in"): `params.data` is the run record's `steps[0].data` as backend-core's
|
|
22
|
+
* `getExecutionEnvelope` builds it, the same for a SERVICE and a JOB run.
|
|
23
|
+
* `trigger: "RESUME"` is a resume run, bound from its creation; its input (the
|
|
24
|
+
* wait's outcome) is not in the message and comes from the lease. `trigger:
|
|
25
|
+
* "INBOX"` is a queued-input run, with no input of its own. `trigger:
|
|
26
|
+
* "INTERACTIVE"` (or `params.contentType` "INTERACTIVE") is a synchronous
|
|
27
|
+
* agent call made a run (I1): its input is `{ type: "interactive", id: <run
|
|
28
|
+
* id>, payload: params.data.payload }`, what the caller asked for. Anything
|
|
29
|
+
* else is a platform event (a scheduled run's included). Before the lease an
|
|
30
|
+
* event has no inbox entry, so its `id` is the run's own; the turn is handed
|
|
31
|
+
* the platform's input, whose `id` is its entry.
|
|
32
|
+
*
|
|
33
|
+
* An INTERACTIVE run arrives claimed by the platform, as every run reaches
|
|
34
|
+
* `main` claimed (by `serve()`'s caller or by `runOnce()`): the runner never
|
|
35
|
+
* claims.
|
|
36
|
+
*/
|
|
37
|
+
const messageAdapter = (params, _request) => {
|
|
38
|
+
const data = params?.data ?? {};
|
|
39
|
+
const batchJobId = data.batchJobId ? String(data.batchJobId) : null;
|
|
40
|
+
if (data.trigger === TRIGGER.INBOX)
|
|
41
|
+
return { kind: "inbox", batchJobId, bound: true, input: null };
|
|
42
|
+
if (data.trigger === TRIGGER.RESUME)
|
|
43
|
+
return { kind: "resume", batchJobId, bound: true, input: null };
|
|
44
|
+
if (data.trigger === TRIGGER.INTERACTIVE || params?.contentType === TRIGGER.INTERACTIVE) {
|
|
45
|
+
return {
|
|
46
|
+
kind: "interactive",
|
|
47
|
+
batchJobId,
|
|
48
|
+
bound: Boolean(data.workflowId),
|
|
49
|
+
input: { type: "interactive", id: batchJobId, payload: data.payload ?? null },
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const payload = data.data !== undefined ? data.data : data.schedule !== undefined ? { schedule: data.schedule } : null;
|
|
53
|
+
return {
|
|
54
|
+
kind: "event",
|
|
55
|
+
batchJobId,
|
|
56
|
+
bound: Boolean(data.workflowId),
|
|
57
|
+
input: {
|
|
58
|
+
type: "event",
|
|
59
|
+
id: batchJobId,
|
|
60
|
+
eventType: data.eventType ?? params?.contentType ?? null,
|
|
61
|
+
elementType: data.elementType ?? null,
|
|
62
|
+
elementId: data.elementId !== undefined && data.elementId !== null ? String(data.elementId) : null,
|
|
63
|
+
data: payload,
|
|
64
|
+
userId: data.userId !== undefined && data.userId !== null ? String(data.userId) : null,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
exports.messageAdapter = messageAdapter;
|
|
69
|
+
// ── Internals ────────────────────────────────────────────────────────────
|
|
70
|
+
const LINGER_POLL_MS = 5000;
|
|
71
|
+
/** The wait stops this long before the lease's `until` (§4). */
|
|
72
|
+
const UNTIL_MARGIN_MS = 30_000;
|
|
73
|
+
/** Release or end answered `inbox: true` this many times in a row with nothing to take: the platform is not making sense. */
|
|
74
|
+
const EMPTY_INBOX_ANSWERS_MAX = 3;
|
|
75
|
+
/** An administrator deleted the workflow (a 404 once bound, §6.2): the run ends successfully. */
|
|
76
|
+
class WorkflowGone extends Error {
|
|
77
|
+
}
|
|
78
|
+
/** The platform's 409 not holder: another run took the lease past `until`. */
|
|
79
|
+
class NotHolder extends Error {
|
|
80
|
+
failure;
|
|
81
|
+
constructor(failure) {
|
|
82
|
+
super("workflow: this run no longer holds the lease");
|
|
83
|
+
this.failure = failure;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** A turn that failed: its handler, its send, or its saves threw. */
|
|
87
|
+
class TurnFailed extends Error {
|
|
88
|
+
failure;
|
|
89
|
+
input;
|
|
90
|
+
constructor(failure, input) {
|
|
91
|
+
super("workflow: a turn failed");
|
|
92
|
+
this.failure = failure;
|
|
93
|
+
this.input = input;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const messageOf = (error) => String(error?.message ?? error);
|
|
97
|
+
/** A body with its undefined fields left out, so a call sends only what it means. */
|
|
98
|
+
const defined = (fields) => Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
|
|
99
|
+
/** A wait as `openWaits` lists it (core's `openWaitView`), from its declaration and the id its save answered. */
|
|
100
|
+
const viewOf = (waitId, decl) => ({
|
|
101
|
+
waitId,
|
|
102
|
+
kind: decl?.kind,
|
|
103
|
+
tag: decl?.tag ?? null,
|
|
104
|
+
deadline: decl?.kind === "timer" ? decl.at : (decl?.deadline ?? null),
|
|
105
|
+
...(decl?.prompt?.title !== undefined ? { title: decl.prompt.title } : {}),
|
|
106
|
+
...(decl?.addressees ? { addressees: [...decl.addressees] } : {}),
|
|
107
|
+
...(decl?.runId ? { runId: decl.runId } : {}),
|
|
108
|
+
...(decl?.event ? { event: { ...decl.event } } : {}),
|
|
109
|
+
...(decl?.kind === "signal" ? { signal: { name: decl.name, correlation: decl.correlation } } : {}),
|
|
110
|
+
...(decl?.kind === "timer" ? { at: decl.at } : {}),
|
|
111
|
+
});
|
|
112
|
+
const systemClock = {
|
|
113
|
+
now: () => Date.now(),
|
|
114
|
+
sleep: (ms, signal) => new Promise((resolve) => {
|
|
115
|
+
if (signal?.aborted) {
|
|
116
|
+
resolve();
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const done = () => {
|
|
120
|
+
clearTimeout(timer);
|
|
121
|
+
signal?.removeEventListener("abort", done);
|
|
122
|
+
resolve();
|
|
123
|
+
};
|
|
124
|
+
const timer = setTimeout(done, ms);
|
|
125
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
126
|
+
}),
|
|
127
|
+
};
|
|
128
|
+
/** One run of `workflow.run`'s loop (runner spec §3): lease, turns, linger, let go. */
|
|
129
|
+
class WorkflowRun {
|
|
130
|
+
handlers;
|
|
131
|
+
transport;
|
|
132
|
+
start;
|
|
133
|
+
signal;
|
|
134
|
+
workflowId = null;
|
|
135
|
+
version = null;
|
|
136
|
+
agent = null;
|
|
137
|
+
book = { outbox: [], turns: [], lastWrite: null };
|
|
138
|
+
openWaits = [];
|
|
139
|
+
until = null;
|
|
140
|
+
turns = 0;
|
|
141
|
+
/** The waits this run declared in a turn whose choice was to wait (§4). */
|
|
142
|
+
lingerFor = new Set();
|
|
143
|
+
last = null;
|
|
144
|
+
lastTurnEndedAt = 0;
|
|
145
|
+
lingered = null;
|
|
146
|
+
halted = false;
|
|
147
|
+
/**
|
|
148
|
+
* Whether the run's outcome is a caller's answer (Ruling 22): an INTERACTIVE
|
|
149
|
+
* run's own, or any round of a workflow an interactive call created, which
|
|
150
|
+
* the lease answer says (core e2f1ae12). Set before the lease from the run's
|
|
151
|
+
* kind, and by the lease once taken.
|
|
152
|
+
*/
|
|
153
|
+
interactive;
|
|
154
|
+
maxMs;
|
|
155
|
+
pollMs;
|
|
156
|
+
clock;
|
|
157
|
+
constructor(handlers, transport, start, options, signal) {
|
|
158
|
+
this.handlers = handlers;
|
|
159
|
+
this.transport = transport;
|
|
160
|
+
this.start = start;
|
|
161
|
+
this.signal = signal;
|
|
162
|
+
this.maxMs = Math.max(0, options.linger?.maxMs ?? 0);
|
|
163
|
+
this.pollMs = Math.max(1, options.linger?.pollMs ?? LINGER_POLL_MS);
|
|
164
|
+
this.clock = options.clock ?? systemClock;
|
|
165
|
+
this.interactive = start.kind === "interactive";
|
|
166
|
+
}
|
|
167
|
+
/** The run, start to end: its summary, and whether its outcome is a caller's answer. */
|
|
168
|
+
async go() {
|
|
169
|
+
const summary = await this.drive();
|
|
170
|
+
return { summary, interactive: this.interactive };
|
|
171
|
+
}
|
|
172
|
+
async drive() {
|
|
173
|
+
// 1. Before the lease: `open` and `decide`, for a run with an input of its own.
|
|
174
|
+
let decision = null;
|
|
175
|
+
const body = {};
|
|
176
|
+
if (this.start.kind === "event" || this.start.kind === "interactive") {
|
|
177
|
+
const input = this.start.input;
|
|
178
|
+
const opened = this.start.bound ? null : await this.open(input);
|
|
179
|
+
const read = this.handlers.decide ? await this.transport.get(opened?.key) : null;
|
|
180
|
+
if (read)
|
|
181
|
+
this.workflowId = read.workflowId;
|
|
182
|
+
decision = await this.decide(input, read);
|
|
183
|
+
if (decision === "ignore")
|
|
184
|
+
return this.summary("ignored");
|
|
185
|
+
if (decision === "delete") {
|
|
186
|
+
// DELETE /workflow takes no key (§6.2): before the lease it reaches the
|
|
187
|
+
// bound workflow, or for an unbound run its element's default-key one.
|
|
188
|
+
// That is the workflow decide was shown only for a bound run or the
|
|
189
|
+
// default key of an event run; any other is leased by its key first and
|
|
190
|
+
// deleted by its holder, whose DELETE reaches the workflow it holds.
|
|
191
|
+
const shown = !opened || (opened.key === "" && this.start.kind === "event");
|
|
192
|
+
return shown ? await this.deleteBeforeLease() : await this.deleteUnderLease(opened.key);
|
|
193
|
+
}
|
|
194
|
+
if (opened) {
|
|
195
|
+
if (opened.key !== undefined)
|
|
196
|
+
body.key = opened.key;
|
|
197
|
+
if (opened.create || decision === "create")
|
|
198
|
+
body.create = true;
|
|
199
|
+
}
|
|
200
|
+
if (decision === "reopen")
|
|
201
|
+
body.reopen = true;
|
|
202
|
+
}
|
|
203
|
+
// 2. The lease. A run that does not take it ends successfully with the answer.
|
|
204
|
+
const lease = await this.transport.lease(body);
|
|
205
|
+
if (!lease?.taken)
|
|
206
|
+
return await this.refused(lease);
|
|
207
|
+
this.workflowId = lease.workflowId;
|
|
208
|
+
try {
|
|
209
|
+
this.leased(lease);
|
|
210
|
+
// 3. The turn on the run's own input (a queued-input run has none).
|
|
211
|
+
if (lease.input) {
|
|
212
|
+
await this.runTurn(this.ownInput(lease.input), this.start.kind === "resume" ? null : decision, lease.input.id);
|
|
213
|
+
}
|
|
214
|
+
// 4 to 6. The inbox, the wait for a quick resolution, and letting go.
|
|
215
|
+
return await this.loop();
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
return await this.failed(error);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// ── Before the lease ──────────────────────────────────────────────────
|
|
222
|
+
async open(input) {
|
|
223
|
+
// An interactive request is one piece of work, not its element's
|
|
224
|
+
// lifecycle: its own workflow, keyed by its run id (I5). With no id known,
|
|
225
|
+
// no key is sent and the platform keys it by the run's id itself.
|
|
226
|
+
const defaults = this.start.kind === "interactive"
|
|
227
|
+
? { key: this.start.batchJobId ?? undefined, create: true }
|
|
228
|
+
: { key: "", create: false };
|
|
229
|
+
if (!this.handlers.open)
|
|
230
|
+
return defaults;
|
|
231
|
+
const opened = (await this.handlers.open(input)) ?? {};
|
|
232
|
+
return { key: opened.key ?? defaults.key, create: opened.create ?? defaults.create };
|
|
233
|
+
}
|
|
234
|
+
async decide(input, read) {
|
|
235
|
+
if (!this.handlers.decide)
|
|
236
|
+
return "run";
|
|
237
|
+
const workflow = read ? { ...read, state: (0, bookkeeping_js_1.agentOf)(read.state) } : null;
|
|
238
|
+
try {
|
|
239
|
+
const answer = await this.handlers.decide({ input, workflow });
|
|
240
|
+
if (DECISIONS.includes(answer))
|
|
241
|
+
return answer;
|
|
242
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.warn, `workflow decide answered ${typeof answer === "string" ? `"${answer.slice(0, 32)}"` : typeof answer}, which is not a decision; taken as "run"`);
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
// decide must be total: an input lost before the lease is never re-run,
|
|
246
|
+
// so it is decided under the lease instead, where a failed turn is (W4).
|
|
247
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.error, `workflow decide threw, which it must never do; taken as "run" so the input is decided under the lease: ${messageOf(error)}`);
|
|
248
|
+
}
|
|
249
|
+
return "run";
|
|
250
|
+
}
|
|
251
|
+
async deleteBeforeLease() {
|
|
252
|
+
const answer = await this.transport.delete();
|
|
253
|
+
if (answer?.deleted)
|
|
254
|
+
return this.summary("deleted");
|
|
255
|
+
// Held by another run: this run's input is queued for its holder, whose turn deletes it.
|
|
256
|
+
if (answer?.held)
|
|
257
|
+
return this.summary("deferred");
|
|
258
|
+
if (answer?.gone)
|
|
259
|
+
return this.summary("gone");
|
|
260
|
+
throw new Error("workflow: the platform's delete answered neither deleted nor held");
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* decide's delete of a workflow named by a key: lease it by that key (never
|
|
264
|
+
* creating one), then delete it as its holder. A lease refused deletes
|
|
265
|
+
* nothing and the run ends with the lease's answer: deferred queues the input
|
|
266
|
+
* for the holder, whose turn decides, as a delete answered `held` does.
|
|
267
|
+
*/
|
|
268
|
+
async deleteUnderLease(key) {
|
|
269
|
+
const lease = await this.transport.lease(defined({ key }));
|
|
270
|
+
if (!lease?.taken) {
|
|
271
|
+
const outcome = (await this.refused(lease)).outcome;
|
|
272
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `workflow decide answered delete for key "${key ?? ""}" in run ${this.start.batchJobId}; the lease answered ${outcome}, so nothing was deleted`);
|
|
273
|
+
return this.summary(outcome);
|
|
274
|
+
}
|
|
275
|
+
this.workflowId = lease.workflowId;
|
|
276
|
+
try {
|
|
277
|
+
this.leased(lease);
|
|
278
|
+
return this.summary(await this.deleteHeld());
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
return await this.failed(error);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** The holder deletes the workflow it holds. */
|
|
285
|
+
async deleteHeld() {
|
|
286
|
+
const answer = await this.held(() => this.transport.delete());
|
|
287
|
+
if (answer?.gone)
|
|
288
|
+
throw new WorkflowGone();
|
|
289
|
+
if (answer?.deleted)
|
|
290
|
+
return "deleted";
|
|
291
|
+
throw new Error("workflow: the platform refused the holder's delete");
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* A lease that was not taken ends the run successfully with the answer. For
|
|
295
|
+
* a BOUND run that is a later round of a workflow, whose RESUME/INBOX
|
|
296
|
+
* envelope and the platform's refusal answers carry no `interactive` flag:
|
|
297
|
+
* core settles any non-null `main` return of an interactive call's round as
|
|
298
|
+
* `completed` with it as the result, but a refused round must answer
|
|
299
|
+
* `queued` (spec §5 W12), which only a null return does. So the workflow is
|
|
300
|
+
* read once, best effort: interactive, or gone (404), returns nothing. A
|
|
301
|
+
* failed read fails toward `queued` for a RESUME/INBOX run, never toward a
|
|
302
|
+
* bogus `completed`; a bound event run keeps its summary.
|
|
303
|
+
*/
|
|
304
|
+
async refused(lease) {
|
|
305
|
+
const outcome = this.leaseOutcome(lease);
|
|
306
|
+
if (lease?.interactive === true)
|
|
307
|
+
this.interactive = true;
|
|
308
|
+
if (this.start.bound && !this.interactive) {
|
|
309
|
+
try {
|
|
310
|
+
const read = await this.transport.get();
|
|
311
|
+
if (read === null || read?.interactive === true)
|
|
312
|
+
this.interactive = true;
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
if (this.start.kind === "resume" || this.start.kind === "inbox")
|
|
316
|
+
this.interactive = true;
|
|
317
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.warn, `workflow ${this.workflowId ?? ""}: could not read the workflow after a refused lease: ${messageOf(error)}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return this.summary(outcome);
|
|
321
|
+
}
|
|
322
|
+
leaseOutcome(lease) {
|
|
323
|
+
if (lease?.deferred)
|
|
324
|
+
return "deferred";
|
|
325
|
+
if (lease?.handled)
|
|
326
|
+
return "handled";
|
|
327
|
+
// A bound run's workflow missing was deleted under it.
|
|
328
|
+
if (lease?.missing)
|
|
329
|
+
return this.start.bound ? "gone" : "missing";
|
|
330
|
+
if (lease?.ended)
|
|
331
|
+
return "already-ended";
|
|
332
|
+
if (lease?.halted)
|
|
333
|
+
return "halted";
|
|
334
|
+
throw new Error("workflow: the platform's lease answered none of its answers");
|
|
335
|
+
}
|
|
336
|
+
// ── Under the lease ───────────────────────────────────────────────────
|
|
337
|
+
leased(lease) {
|
|
338
|
+
const { agent, runner } = (0, bookkeeping_js_1.readState)(lease.state);
|
|
339
|
+
this.agent = agent;
|
|
340
|
+
this.book = runner;
|
|
341
|
+
this.version = String(lease.version);
|
|
342
|
+
this.openWaits = (lease.openWaits ?? []).map((wait) => ({ ...wait }));
|
|
343
|
+
const until = lease.until ? Date.parse(lease.until) : NaN;
|
|
344
|
+
this.until = Number.isNaN(until) ? null : until;
|
|
345
|
+
if (lease.interactive === true)
|
|
346
|
+
this.interactive = true;
|
|
347
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `workflow ${this.workflowId}: lease taken by run ${this.start.batchJobId}${lease.until ? ` until ${lease.until}` : ""}, ${this.openWaits.length} open waits`);
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* The run's own input as its turn receives it: the platform's, except an
|
|
351
|
+
* INTERACTIVE run's, which is the caller's request as its message carries
|
|
352
|
+
* it, whole (the platform's copy of it is capped like an event's data, and
|
|
353
|
+
* an older platform hands it as a bare event). Its entry is still named by
|
|
354
|
+
* `done`.
|
|
355
|
+
*/
|
|
356
|
+
ownInput(input) {
|
|
357
|
+
return this.start.kind === "interactive" ? this.start.input : input;
|
|
358
|
+
}
|
|
359
|
+
/** A transport call under the lease: the platform's 409 not holder becomes {@link NotHolder}. */
|
|
360
|
+
async held(call) {
|
|
361
|
+
try {
|
|
362
|
+
return await call();
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
if (error?.response?.status === 409)
|
|
366
|
+
throw new NotHolder(error);
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
async loop() {
|
|
371
|
+
let empty = 0;
|
|
372
|
+
for (;;) {
|
|
373
|
+
const before = this.turns;
|
|
374
|
+
await this.drainInbox();
|
|
375
|
+
if (!this.halted && this.shouldLinger())
|
|
376
|
+
await this.linger();
|
|
377
|
+
const outcome = await this.letWorkflowGo();
|
|
378
|
+
if (outcome)
|
|
379
|
+
return this.summary(outcome);
|
|
380
|
+
// Answered inbox: true: entries were queued after the last take. Take them.
|
|
381
|
+
empty = this.turns === before ? empty + 1 : 0;
|
|
382
|
+
if (empty >= EMPTY_INBOX_ANSWERS_MAX) {
|
|
383
|
+
throw new Error(`workflow: the platform answered inbox: true ${empty} times with nothing in the inbox to take`);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/** Step 4: one entry per take, its turn, until a take answers none (or halted). */
|
|
388
|
+
async drainInbox() {
|
|
389
|
+
while (!this.halted) {
|
|
390
|
+
const take = await this.held(() => this.transport.take());
|
|
391
|
+
if (take?.gone)
|
|
392
|
+
throw new WorkflowGone();
|
|
393
|
+
if (take?.halted) {
|
|
394
|
+
this.halted = true;
|
|
395
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.warn, `workflow ${this.workflowId}: the platform halted it (turn budget or rate, W12); releasing what this run has`);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (!take?.entry)
|
|
399
|
+
return;
|
|
400
|
+
await this.runTurn(take.entry, null, take.entry.id);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** Step 6: release, end or delete, by the last turn. Null when the platform answered inbox: true. */
|
|
404
|
+
async letWorkflowGo() {
|
|
405
|
+
const next = this.last?.next ?? {};
|
|
406
|
+
if (next.delete)
|
|
407
|
+
return await this.deleteHeld();
|
|
408
|
+
if (next.end && !this.halted) {
|
|
409
|
+
const answer = await this.write("end");
|
|
410
|
+
if (answer.ended)
|
|
411
|
+
return "ended";
|
|
412
|
+
if (answer.inbox)
|
|
413
|
+
return null;
|
|
414
|
+
if (!answer.halted)
|
|
415
|
+
throw new Error("workflow: the platform's end answered neither ended, inbox nor halted");
|
|
416
|
+
// Entries queued on a halted workflow: an end would strand them, so release (W4).
|
|
417
|
+
this.halted = true;
|
|
418
|
+
}
|
|
419
|
+
const answer = await this.write("release");
|
|
420
|
+
if (answer.released)
|
|
421
|
+
return this.halted ? "halted" : "released";
|
|
422
|
+
if (answer.inbox)
|
|
423
|
+
return null;
|
|
424
|
+
throw new Error("workflow: the platform's release answered neither released nor inbox");
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* One turn and its end-of-turn save (§3): the outbox saved, sent under the
|
|
428
|
+
* lease, then one save with the sent entries removed, `done` naming the
|
|
429
|
+
* input and the turn's waits, cancellations and contacts. A turn that
|
|
430
|
+
* queued nothing needs only that last save.
|
|
431
|
+
*/
|
|
432
|
+
async runTurn(input, decision, entryId) {
|
|
433
|
+
const added = [];
|
|
434
|
+
const declared = [];
|
|
435
|
+
let declaredInput = false;
|
|
436
|
+
// The resume this run takes settles its wait out of openWaits.
|
|
437
|
+
if (input?.type === "resume")
|
|
438
|
+
this.dropWait(input.waitId);
|
|
439
|
+
const outbox = {
|
|
440
|
+
add: (entries) => {
|
|
441
|
+
if (!this.handlers.send) {
|
|
442
|
+
throw new Error("workflow.run: outbox.add needs a send handler: workflow.run({ turn, send })");
|
|
443
|
+
}
|
|
444
|
+
for (const entry of Array.isArray(entries) ? entries : [entries]) {
|
|
445
|
+
if (!entry || typeof entry.key !== "string" || entry.key.length === 0) {
|
|
446
|
+
throw new TypeError("workflow.run: an outbox entry needs a stable, non-empty key");
|
|
447
|
+
}
|
|
448
|
+
added.push(entry);
|
|
449
|
+
}
|
|
450
|
+
},
|
|
451
|
+
};
|
|
452
|
+
const checkpoint = async (state, options = {}) => {
|
|
453
|
+
this.agent = state;
|
|
454
|
+
const declarations = { waits: options.waits, cancel: options.cancel, contacts: options.contacts };
|
|
455
|
+
let answer;
|
|
456
|
+
if (options.send) {
|
|
457
|
+
this.book.outbox = (0, bookkeeping_js_1.mergeOutbox)(this.book.outbox, added.splice(0));
|
|
458
|
+
answer = await this.write("save", declarations);
|
|
459
|
+
await this.sendOutbox();
|
|
460
|
+
this.book.outbox = [];
|
|
461
|
+
await this.write("save");
|
|
462
|
+
}
|
|
463
|
+
else {
|
|
464
|
+
answer = await this.write("save", declarations);
|
|
465
|
+
}
|
|
466
|
+
for (const wait of answer.waits)
|
|
467
|
+
declared.push(wait.waitId);
|
|
468
|
+
if ((options.waits ?? []).some((decl) => decl?.kind === "input"))
|
|
469
|
+
declaredInput = true;
|
|
470
|
+
return { waits: answer.waits, cancelled: answer.cancelled };
|
|
471
|
+
};
|
|
472
|
+
try {
|
|
473
|
+
// The answers to a paused turn's wait run that turn again, on its own
|
|
474
|
+
// input, with its journal (design #964 §10.2); any other input is a turn
|
|
475
|
+
// of its own, journaled in case it pauses.
|
|
476
|
+
const creator = this.creator();
|
|
477
|
+
const restored = (0, resume_js_1.isPausedResume)(input) ? await this.restorePaused(input, creator) : null;
|
|
478
|
+
const turnInput = restored ? restored.input : input;
|
|
479
|
+
const turnDecision = restored ? restored.decision : decision;
|
|
480
|
+
const durableTurn = restored?.turn ?? new journal_js_1.DurableTurn({ creator, now: () => this.clock.now() });
|
|
481
|
+
durableTurn.event = turnInput?.type === "event";
|
|
482
|
+
let result;
|
|
483
|
+
try {
|
|
484
|
+
result = await durableTurn.run(() => this.handlers.turn({
|
|
485
|
+
input: turnInput,
|
|
486
|
+
decision: turnDecision,
|
|
487
|
+
state: this.agent,
|
|
488
|
+
checkpoint,
|
|
489
|
+
outbox,
|
|
490
|
+
openWaits: this.openWaits.map((wait) => ({ ...wait })),
|
|
491
|
+
}));
|
|
492
|
+
}
|
|
493
|
+
catch (error) {
|
|
494
|
+
if (!durableTurn.pausing)
|
|
495
|
+
throw error;
|
|
496
|
+
result = null;
|
|
497
|
+
}
|
|
498
|
+
if (restored) {
|
|
499
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `durable: resumed a paused turn on workflow ${this.workflowId} from checkpoint step ${restored.step}: ${durableTurn.hits} journal hits`);
|
|
500
|
+
}
|
|
501
|
+
if (durableTurn.pausing) {
|
|
502
|
+
if (result) {
|
|
503
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.warn, `durable: the turn on input ${entryId} caught the pause and returned; it is paused all the same, and what it returned is dropped`);
|
|
504
|
+
}
|
|
505
|
+
// The turn did not finish: it runs again on its resume, so nothing it queued is sent now.
|
|
506
|
+
//
|
|
507
|
+
// Crash window: `pause()` PUTs the checkpoint, which REPLACES the
|
|
508
|
+
// workflow's only one, and the save below declares the wait that names
|
|
509
|
+
// it. On a resumed round, a crash between the two leaves the re-queued
|
|
510
|
+
// resume pointing at a replaced checkpoint step: it fails (restore's
|
|
511
|
+
// step check) and, after INPUT_MAX_ATTEMPTS, the input is dropped. Not
|
|
512
|
+
// closed here: it needs the platform to keep two checkpoints.
|
|
513
|
+
added.length = 0;
|
|
514
|
+
result = { state: this.agent, next: { wait: [await this.pause(durableTurn, turnInput, turnDecision)] } };
|
|
515
|
+
}
|
|
516
|
+
if (!result || typeof result !== "object" || !("state" in result)) {
|
|
517
|
+
throw new TypeError("workflow.run: a turn returns { state, next }");
|
|
518
|
+
}
|
|
519
|
+
const next = result.next ?? {};
|
|
520
|
+
this.agent = result.state;
|
|
521
|
+
const pending = (0, bookkeeping_js_1.mergeOutbox)(this.book.outbox, added);
|
|
522
|
+
if (pending.length > 0) {
|
|
523
|
+
this.book.outbox = pending;
|
|
524
|
+
await this.write("save");
|
|
525
|
+
await this.sendOutbox();
|
|
526
|
+
}
|
|
527
|
+
this.book.outbox = [];
|
|
528
|
+
this.book.turns = (0, bookkeeping_js_1.withTurn)(this.book.turns, {
|
|
529
|
+
turn: entryId,
|
|
530
|
+
eventType: input?.type === "event" ? String(input.eventType) : String(input?.type),
|
|
531
|
+
batchJobId: this.start.batchJobId,
|
|
532
|
+
at: new Date(this.clock.now()).toISOString(),
|
|
533
|
+
outcome: next.end ? "end" : next.delete ? "delete" : "release",
|
|
534
|
+
...(next.end ? { terminal: true } : {}),
|
|
535
|
+
});
|
|
536
|
+
const answer = await this.write("save", {
|
|
537
|
+
done: entryId,
|
|
538
|
+
waits: next.wait,
|
|
539
|
+
cancel: next.cancel,
|
|
540
|
+
contacts: next.contacts,
|
|
541
|
+
});
|
|
542
|
+
for (const wait of answer.waits)
|
|
543
|
+
declared.push(wait.waitId);
|
|
544
|
+
if ((next.wait ?? []).some((decl) => decl?.kind === "input"))
|
|
545
|
+
declaredInput = true;
|
|
546
|
+
if (next.linger ?? declaredInput)
|
|
547
|
+
for (const waitId of declared)
|
|
548
|
+
this.lingerFor.add(waitId);
|
|
549
|
+
this.turns += 1;
|
|
550
|
+
this.last = { next, result: result.result, hasResult: Object.prototype.hasOwnProperty.call(result, "result") };
|
|
551
|
+
this.lastTurnEndedAt = this.clock.now();
|
|
552
|
+
}
|
|
553
|
+
catch (error) {
|
|
554
|
+
if (error instanceof WorkflowGone || error instanceof NotHolder)
|
|
555
|
+
throw error;
|
|
556
|
+
throw new TurnFailed(error, input);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
// ── The conversation checkpoint (design #964 W10, §10.2) ──────────────
|
|
560
|
+
/**
|
|
561
|
+
* The workflow's creator, whom a pause asks by default: a resume, inbox or
|
|
562
|
+
* interactive run acts as the workflow's creator (W7), and its run message
|
|
563
|
+
* names them as `userId`. An event's run names the event's user instead,
|
|
564
|
+
* so a pause on an event's turn must name its addressees (planPause).
|
|
565
|
+
*/
|
|
566
|
+
creator() {
|
|
567
|
+
const userId = (0, runtimeContext_js_1.getContext)()?.params?.data?.userId;
|
|
568
|
+
return userId === undefined || userId === null ? null : String(userId);
|
|
569
|
+
}
|
|
570
|
+
/** The paused turn a resume answers, rebuilt from the checkpoint its wait was declared for. */
|
|
571
|
+
async restorePaused(input, creator) {
|
|
572
|
+
const checkpoint = await this.held(() => this.transport.getCheckpoint());
|
|
573
|
+
if (checkpoint?.gone)
|
|
574
|
+
throw new WorkflowGone();
|
|
575
|
+
return (0, resume_js_1.restore)(input, checkpoint, { creator, now: () => this.clock.now() });
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* A turn stopped inside an LLM tool loop: the units still running are
|
|
579
|
+
* waited for, the conversation checkpoint is saved, and the wait its
|
|
580
|
+
* questions make is what the turn declares. Saving comes first: a turn
|
|
581
|
+
* whose checkpoint cannot be saved fails rather than wait on nothing (§12).
|
|
582
|
+
*/
|
|
583
|
+
async pause(turn, input, decision) {
|
|
584
|
+
if (this.openWaits.some((wait) => typeof wait.tag === "string" && wait.tag.startsWith(pause_js_1.PAUSE_TAG_PREFIX))) {
|
|
585
|
+
throw new Error(`durable: workflow ${this.workflowId} has a paused conversation already waiting for its answers; a second pause would replace its checkpoint`);
|
|
586
|
+
}
|
|
587
|
+
await turn.drain(pause_js_1.AGENT_PAUSE_DRAIN_MS, pause_js_1.drainSleep);
|
|
588
|
+
const plan = (0, pause_js_1.planPause)(turn, { event: input?.type === "event" });
|
|
589
|
+
const snapshot = await (0, pause_js_1.snapshotOf)(turn, plan, { input, decision });
|
|
590
|
+
(0, pause_js_1.checkCheckpointSize)(snapshot.bytes);
|
|
591
|
+
const sha256 = (0, node_crypto_1.createHash)("sha256").update(snapshot.bytes).digest("hex");
|
|
592
|
+
let saved;
|
|
593
|
+
try {
|
|
594
|
+
saved = await this.held(() => this.transport.saveCheckpoint(snapshot.bytes));
|
|
595
|
+
}
|
|
596
|
+
catch (error) {
|
|
597
|
+
if (error?.response?.status !== 413)
|
|
598
|
+
throw error;
|
|
599
|
+
const code = error.response.data?.error;
|
|
600
|
+
throw new Error(`workflow ${this.workflowId}: the platform refused the conversation checkpoint as too large (${code ? `413 ${code}` : "413"}): ${snapshot.bytes.length} bytes gzipped`);
|
|
601
|
+
}
|
|
602
|
+
if (saved?.gone)
|
|
603
|
+
throw new WorkflowGone();
|
|
604
|
+
if (!saved?.saved)
|
|
605
|
+
throw new Error(`workflow ${this.workflowId}: the platform did not save the conversation checkpoint`);
|
|
606
|
+
// The wait names the checkpoint by its step, and its resume checks the
|
|
607
|
+
// bytes against the sha256: both must be the ones of what was sent.
|
|
608
|
+
if (!Number.isInteger(saved.step)) {
|
|
609
|
+
throw new Error(`workflow ${this.workflowId}: the platform saved the conversation checkpoint without saying its step`);
|
|
610
|
+
}
|
|
611
|
+
if (saved.sha256 !== sha256) {
|
|
612
|
+
throw new Error(`workflow ${this.workflowId}: the platform saved a checkpoint whose sha256 ${saved.sha256} is not that of the bytes sent (${sha256})`);
|
|
613
|
+
}
|
|
614
|
+
const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
615
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `durable: turn paused on workflow ${this.workflowId}: ${count(plan.questions.length, "question", "questions")}, snapshot ${snapshot.size} bytes, ${snapshot.bytes.length} gzipped, ${count(snapshot.entries, "journal entry", "journal entries")}, ${count(snapshot.threads, "thread", "threads")}; checkpoint step ${saved.step}`);
|
|
616
|
+
// Its deadline counts from now, after the upload, as the platform counts it.
|
|
617
|
+
return (0, pause_js_1.waitOf)(plan, saved.step, this.clock.now());
|
|
618
|
+
}
|
|
619
|
+
async sendOutbox() {
|
|
620
|
+
const entries = this.book.outbox;
|
|
621
|
+
if (entries.length === 0)
|
|
622
|
+
return;
|
|
623
|
+
if (!this.handlers.send) {
|
|
624
|
+
throw new Error("workflow.run: the outbox has entries and no send handler to send them");
|
|
625
|
+
}
|
|
626
|
+
for (const entry of entries)
|
|
627
|
+
await this.handlers.send(entry);
|
|
628
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.debug, `workflow ${this.workflowId}: ${entries.length} outbox entries sent under the lease`);
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* A save, release or end under the lease, stamped with a fresh last-write
|
|
632
|
+
* id (§7). A version mismatch, or for a release or end a not-holder, may be
|
|
633
|
+
* this call's own write landing with its answer lost and retried: the
|
|
634
|
+
* workflow is read again, and if its stamp is this call's, the write
|
|
635
|
+
* landed and the run goes on from the version read.
|
|
636
|
+
*/
|
|
637
|
+
async write(kind, fields = {}) {
|
|
638
|
+
const id = (0, node_crypto_1.randomUUID)();
|
|
639
|
+
this.book.lastWrite = { batchJobId: this.start.batchJobId, id };
|
|
640
|
+
const body = { state: (0, bookkeeping_js_1.storedState)(this.agent, this.book), version: this.version, ...defined(fields) };
|
|
641
|
+
let answer;
|
|
642
|
+
try {
|
|
643
|
+
answer = await this.held(() => this.transport[kind](body));
|
|
644
|
+
}
|
|
645
|
+
catch (error) {
|
|
646
|
+
if (error instanceof NotHolder && kind !== "save") {
|
|
647
|
+
const landed = await this.landed(id);
|
|
648
|
+
if (landed)
|
|
649
|
+
return this.landedAnswer(kind, landed, fields);
|
|
650
|
+
}
|
|
651
|
+
throw error;
|
|
652
|
+
}
|
|
653
|
+
if (answer?.gone)
|
|
654
|
+
throw new WorkflowGone();
|
|
655
|
+
if (answer?.versionMismatch) {
|
|
656
|
+
const landed = await this.landed(id);
|
|
657
|
+
if (landed)
|
|
658
|
+
return this.landedAnswer(kind, landed, fields);
|
|
659
|
+
throw new Error(`workflow: the workflow's version moved under this run's ${kind}: a write it did not make landed`);
|
|
660
|
+
}
|
|
661
|
+
// A save answers saved, a version mismatch, gone or (rejected) not holder:
|
|
662
|
+
// anything else fails here, at the save that got it. A release's and an
|
|
663
|
+
// end's answers are read by their caller.
|
|
664
|
+
if (kind === "save" && !answer?.saved) {
|
|
665
|
+
throw new Error("workflow: the platform's save answered neither saved nor a version mismatch");
|
|
666
|
+
}
|
|
667
|
+
if (answer?.saved || answer?.released) {
|
|
668
|
+
// Every caller reads `waits` and `cancelled` off a save or a release.
|
|
669
|
+
answer = { ...answer, waits: answer.waits ?? [], cancelled: answer.cancelled ?? [] };
|
|
670
|
+
this.version = String(answer.version);
|
|
671
|
+
answer.waits.forEach((wait, index) => {
|
|
672
|
+
this.openWaits.push(viewOf(wait.waitId, fields.waits?.[index]));
|
|
673
|
+
});
|
|
674
|
+
for (const waitId of answer.cancelled)
|
|
675
|
+
this.dropWait(waitId);
|
|
676
|
+
}
|
|
677
|
+
return answer;
|
|
678
|
+
}
|
|
679
|
+
/** The workflow as read, when its last write is the one stamped `id`; else null. */
|
|
680
|
+
async landed(id) {
|
|
681
|
+
const read = await this.held(() => this.transport.get());
|
|
682
|
+
if (!read)
|
|
683
|
+
throw new WorkflowGone();
|
|
684
|
+
if ((0, bookkeeping_js_1.readState)(read.state).runner.lastWrite?.id !== id)
|
|
685
|
+
return null;
|
|
686
|
+
this.version = String(read.version);
|
|
687
|
+
return read;
|
|
688
|
+
}
|
|
689
|
+
landedAnswer(kind, read, fields) {
|
|
690
|
+
const known = new Set(this.openWaits.map((wait) => wait.waitId));
|
|
691
|
+
const open = read.openWaits;
|
|
692
|
+
const waits = open.filter((wait) => !known.has(wait.waitId)).map((wait) => ({ waitId: wait.waitId }));
|
|
693
|
+
const cancelled = (fields.cancel ?? []).filter((waitId) => known.has(waitId) && !open.some((wait) => wait.waitId === waitId));
|
|
694
|
+
this.openWaits = open.map((wait) => ({ ...wait }));
|
|
695
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `workflow ${this.workflowId}: the answer to this run's ${kind} was lost; its last-write stamp shows it landed`);
|
|
696
|
+
if (kind === "end")
|
|
697
|
+
return { ended: true };
|
|
698
|
+
const version = String(read.version);
|
|
699
|
+
return kind === "save"
|
|
700
|
+
? { saved: true, version, waits, cancelled }
|
|
701
|
+
: { released: true, version, waits, cancelled };
|
|
702
|
+
}
|
|
703
|
+
dropWait(waitId) {
|
|
704
|
+
this.openWaits = this.openWaits.filter((wait) => wait.waitId !== waitId);
|
|
705
|
+
}
|
|
706
|
+
// ── Waiting for a quick resolution (§4, pools §13) ────────────────────
|
|
707
|
+
waitingFor() {
|
|
708
|
+
return this.openWaits.filter((wait) => this.lingerFor.has(wait.waitId));
|
|
709
|
+
}
|
|
710
|
+
shouldLinger() {
|
|
711
|
+
if (this.maxMs <= 0 || this.until === null || this.signal?.aborted)
|
|
712
|
+
return false;
|
|
713
|
+
const next = this.last?.next;
|
|
714
|
+
if (next?.end || next?.delete)
|
|
715
|
+
return false;
|
|
716
|
+
return this.waitingFor().length > 0;
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Step 5: take the inbox every `pollMs` while a wait this run chose to wait
|
|
720
|
+
* on is open, each entry run as in step 4. The window runs `maxMs` from the
|
|
721
|
+
* last turn's end, and never past 30 s before the lease's `until`.
|
|
722
|
+
*/
|
|
723
|
+
async linger() {
|
|
724
|
+
const startedAt = this.clock.now();
|
|
725
|
+
const deadline = () => Math.min(this.lastTurnEndedAt + this.maxMs, this.until - UNTIL_MARGIN_MS);
|
|
726
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `workflow linger started on workflow ${this.workflowId}: up to ${Math.max(0, deadline() - startedAt)} ms, for waits ${this.waitingFor()
|
|
727
|
+
.map((wait) => wait.waitId)
|
|
728
|
+
.join(", ")}`);
|
|
729
|
+
let resolved = false;
|
|
730
|
+
let stopped = null;
|
|
731
|
+
for (;;) {
|
|
732
|
+
const next = this.last?.next;
|
|
733
|
+
if (this.waitingFor().length === 0 || next?.end || next?.delete) {
|
|
734
|
+
resolved = true;
|
|
735
|
+
break;
|
|
736
|
+
}
|
|
737
|
+
const left = deadline() - this.clock.now();
|
|
738
|
+
if (left <= 0)
|
|
739
|
+
break;
|
|
740
|
+
await this.clock.sleep(Math.min(this.pollMs, left), this.signal);
|
|
741
|
+
if (this.signal?.aborted) {
|
|
742
|
+
stopped = "the run was aborted";
|
|
743
|
+
break;
|
|
744
|
+
}
|
|
745
|
+
await this.drainInbox();
|
|
746
|
+
if (this.halted) {
|
|
747
|
+
stopped = "the workflow halted";
|
|
748
|
+
break;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
const ms = this.clock.now() - startedAt;
|
|
752
|
+
this.lingered = { ms: (this.lingered?.ms ?? 0) + ms, resolved };
|
|
753
|
+
const seconds = Math.round(ms / 1000);
|
|
754
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, resolved
|
|
755
|
+
? `workflow linger resolved after ${seconds} s`
|
|
756
|
+
: stopped
|
|
757
|
+
? `workflow linger stopped after ${seconds} s: ${stopped}`
|
|
758
|
+
: `workflow linger timed out after ${seconds} s`);
|
|
759
|
+
}
|
|
760
|
+
// ── Endings ───────────────────────────────────────────────────────────
|
|
761
|
+
async failed(error) {
|
|
762
|
+
if (error instanceof WorkflowGone) {
|
|
763
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `workflow ${this.workflowId} was deleted under run ${this.start.batchJobId}; nothing to let go`);
|
|
764
|
+
return this.summary("gone");
|
|
765
|
+
}
|
|
766
|
+
if (error instanceof NotHolder) {
|
|
767
|
+
// Another run took the lease past `until` and re-queued this run's input:
|
|
768
|
+
// no release, no let-go, nothing more written.
|
|
769
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.error, `workflow ${this.workflowId}: run ${this.start.batchJobId} no longer holds the lease (taken over past its until); stopping without a release`);
|
|
770
|
+
throw error.failure;
|
|
771
|
+
}
|
|
772
|
+
if (error instanceof TurnFailed) {
|
|
773
|
+
await this.turnFailed(error);
|
|
774
|
+
throw error.failure;
|
|
775
|
+
}
|
|
776
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.error, `workflow ${this.workflowId}: run ${this.start.batchJobId} failed under the lease (${(0, retrying_js_1.failureOf)(error)}): ${messageOf(error)}; letting go`);
|
|
777
|
+
await this.letGo();
|
|
778
|
+
throw error;
|
|
779
|
+
}
|
|
780
|
+
async turnFailed(failed) {
|
|
781
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.error, `workflow ${this.workflowId}: turn failed on input ${failed.input?.id} (${failed.input?.type}): ${messageOf(failed.failure)}`);
|
|
782
|
+
const letGo = () => this.letGo();
|
|
783
|
+
try {
|
|
784
|
+
if (this.handlers.onError) {
|
|
785
|
+
await this.handlers.onError({ input: failed.input, error: failed.failure, state: this.agent, letGo });
|
|
786
|
+
}
|
|
787
|
+
else {
|
|
788
|
+
await letGo();
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
catch (error) {
|
|
792
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.error, `workflow ${this.workflowId}: onError threw: ${messageOf(error)}`);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
/** Gives the lease up: the input being run goes back to the queue (W4, Recovery). */
|
|
796
|
+
async letGo() {
|
|
797
|
+
try {
|
|
798
|
+
const answer = await this.transport.letGo();
|
|
799
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `workflow ${this.workflowId}: let go by run ${this.start.batchJobId}, ${answer?.requeued ?? 0} input re-queued`);
|
|
800
|
+
}
|
|
801
|
+
catch (error) {
|
|
802
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.warn, `workflow ${this.workflowId}: let-go failed (${(0, retrying_js_1.failureOf)(error)}); the platform frees the lease when this run ends`);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
summary(outcome) {
|
|
806
|
+
const summary = {
|
|
807
|
+
workflowId: this.workflowId,
|
|
808
|
+
outcome,
|
|
809
|
+
turns: this.turns,
|
|
810
|
+
lingered: this.lingered,
|
|
811
|
+
};
|
|
812
|
+
// I6: the ending turn's result is the run's outcome, through whatever
|
|
813
|
+
// settles the run with what `main` returns. The runner does not log it;
|
|
814
|
+
// runOnce logs the first 500 characters of what `main` returns.
|
|
815
|
+
if (this.last?.next?.end && this.last.hasResult && (outcome === "ended" || outcome === "halted")) {
|
|
816
|
+
summary.result = this.last.result;
|
|
817
|
+
}
|
|
818
|
+
logger_js_1.default.log(null, logger_js_1.default.levels.info, `workflow run ${this.start.batchJobId} finished: ${outcome}, ${this.turns} turns${this.workflowId ? `, workflow ${this.workflowId}` : ""}${this.lingered ? `, lingered ${this.lingered.ms} ms (${this.lingered.resolved ? "resolved" : "not resolved"})` : ""}`);
|
|
819
|
+
return summary;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
const defaultTransport = (request) => {
|
|
823
|
+
const token = request?.authToken ?? request?.authorization;
|
|
824
|
+
if (!token) {
|
|
825
|
+
throw new Error("workflow.run: the run carries no token (request.authToken), so it cannot reach the platform; pass options.transport to run without one");
|
|
826
|
+
}
|
|
827
|
+
return (0, retrying_js_1.retrying)((0, platformTransport_js_1.platformTransport)(token));
|
|
828
|
+
};
|
|
829
|
+
/**
|
|
830
|
+
* `workflow.run(handlers, options)` (runner spec §3): an ordinary agent
|
|
831
|
+
* `main`, so `serve()` (SERVICE) and `runOnce()` (JOB) run it as they run any
|
|
832
|
+
* agent, and settle the run with what it returns. The agent writes `decide`
|
|
833
|
+
* and `turn`; the runner owns the lease, the inbox loop one entry per take,
|
|
834
|
+
* the end-of-turn saves with the outbox sent under the lease, release, end
|
|
835
|
+
* and delete, let-go on a failed turn, the last-write stamp, and the wait
|
|
836
|
+
* for a quick resolution (off unless `linger.maxMs` is set, and never past
|
|
837
|
+
* the lease's `until`). The runner never claims the run: `serve()` and
|
|
838
|
+
* `runOnce()` own its lifecycle.
|
|
839
|
+
*/
|
|
840
|
+
const run = (handlers, options = {}) => {
|
|
841
|
+
if (!handlers || typeof handlers.turn !== "function") {
|
|
842
|
+
throw new TypeError("workflow.run needs a turn handler: workflow.run({ turn })");
|
|
843
|
+
}
|
|
844
|
+
return async (signal) => {
|
|
845
|
+
const context = (0, runtimeContext_js_1.getContext)();
|
|
846
|
+
const start = (options.adapter ?? exports.messageAdapter)(context?.params, context?.request);
|
|
847
|
+
const transport = options.transport ?? defaultTransport(context?.request);
|
|
848
|
+
const { summary, interactive } = await new WorkflowRun(handlers, transport, start, options, signal ?? context?.signal ?? null).go();
|
|
849
|
+
// Ruling 22: core's interactiveRuns settles what `main` returns as the
|
|
850
|
+
// run's outcome, InteractiveAnswer.result, for the call's first round and
|
|
851
|
+
// for every round after it (a resume or queued-input run of the workflow
|
|
852
|
+
// the call created, invoked inline, I3). Such a run returns the ending
|
|
853
|
+
// turn's result itself, or nothing (the platform then reads its open tool
|
|
854
|
+
// wait, or no answer). The summary was logged at info.
|
|
855
|
+
return interactive ? summary.result : summary;
|
|
856
|
+
};
|
|
857
|
+
};
|
|
858
|
+
exports.run = run;
|