@elie-laloum/outpost 7.0.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +2 -0
- package/dist/adapters/agents/antigravity-adapter.js +3 -0
- package/dist/adapters/agents/antigravity-adapter.js.map +1 -1
- package/dist/adapters/agents/claude-adapter.js +3 -0
- package/dist/adapters/agents/claude-adapter.js.map +1 -1
- package/dist/adapters/agents/claude-events.js +25 -1
- package/dist/adapters/agents/claude-events.js.map +1 -1
- package/dist/adapters/agents/codex-adapter.js +3 -0
- package/dist/adapters/agents/codex-adapter.js.map +1 -1
- package/dist/adapters/agents/copilot-adapter.js +3 -0
- package/dist/adapters/agents/copilot-adapter.js.map +1 -1
- package/dist/adapters/agents/copilot-events.js +7 -3
- package/dist/adapters/agents/copilot-events.js.map +1 -1
- package/dist/adapters/agents/kimi-adapter.js +3 -0
- package/dist/adapters/agents/kimi-adapter.js.map +1 -1
- package/dist/adapters/agents/quota.constants.d.ts +7 -0
- package/dist/adapters/agents/quota.constants.js +31 -0
- package/dist/adapters/agents/quota.constants.js.map +1 -0
- package/dist/adapters/agents/quota.d.ts +1 -0
- package/dist/adapters/agents/quota.js +4 -0
- package/dist/adapters/agents/quota.js.map +1 -0
- package/dist/adapters/models/http-provider.js +8 -2
- package/dist/adapters/models/http-provider.js.map +1 -1
- package/dist/adapters/models/model.constants.d.ts +2 -0
- package/dist/adapters/models/model.constants.js +6 -0
- package/dist/adapters/models/model.constants.js.map +1 -1
- package/dist/adapters/models/stream-events.js +11 -7
- package/dist/adapters/models/stream-events.js.map +1 -1
- package/dist/application/agent-output.js +10 -1
- package/dist/application/agent-output.js.map +1 -1
- package/dist/application/agent-quota.d.ts +7 -0
- package/dist/application/agent-quota.js +33 -0
- package/dist/application/agent-quota.js.map +1 -0
- package/dist/application/agent-turn.js +25 -9
- package/dist/application/agent-turn.js.map +1 -1
- package/dist/application/dispatch-observation.js +10 -1
- package/dist/application/dispatch-observation.js.map +1 -1
- package/dist/application/execution.types.d.ts +2 -0
- package/dist/application/execution.types.js.map +1 -1
- package/dist/application/interactive-task-execution.d.ts +3 -0
- package/dist/application/interactive-task-execution.js +76 -0
- package/dist/application/interactive-task-execution.js.map +1 -0
- package/dist/application/interactive-task-protocol.d.ts +4 -0
- package/dist/application/interactive-task-protocol.js +56 -0
- package/dist/application/interactive-task-protocol.js.map +1 -0
- package/dist/application/interactive-task.constants.d.ts +4 -0
- package/dist/application/interactive-task.constants.js +7 -0
- package/dist/application/interactive-task.constants.js.map +1 -0
- package/dist/application/interactive-task.d.ts +3 -0
- package/dist/application/interactive-task.js +84 -0
- package/dist/application/interactive-task.js.map +1 -0
- package/dist/application/interactive-task.types.d.ts +44 -0
- package/dist/application/interactive-task.types.js +2 -0
- package/dist/application/interactive-task.types.js.map +1 -0
- package/dist/application/queue-worker.js +19 -1
- package/dist/application/queue-worker.js.map +1 -1
- package/dist/application/queued-task.js +17 -2
- package/dist/application/queued-task.js.map +1 -1
- package/dist/application/quota-resume.constants.d.ts +1 -0
- package/dist/application/quota-resume.constants.js +2 -0
- package/dist/application/quota-resume.constants.js.map +1 -0
- package/dist/application/quota-resume.d.ts +9 -0
- package/dist/application/quota-resume.js +34 -0
- package/dist/application/quota-resume.js.map +1 -0
- package/dist/application/quota-resume.types.d.ts +1 -0
- package/dist/application/quota-resume.types.js +2 -0
- package/dist/application/quota-resume.types.js.map +1 -0
- package/dist/application/recovery-retention-policy.js +1 -1
- package/dist/application/recovery-retention-policy.js.map +1 -1
- package/dist/application/recovery-retention.js +3 -3
- package/dist/application/recovery-retention.js.map +1 -1
- package/dist/application/recovery-retention.types.d.ts +1 -1
- package/dist/application/recovery-retention.types.js.map +1 -1
- package/dist/application/remote-workspace.js +2 -1
- package/dist/application/remote-workspace.js.map +1 -1
- package/dist/application/replay-recording.d.ts +2 -0
- package/dist/application/replay-recording.js +22 -0
- package/dist/application/replay-recording.js.map +1 -0
- package/dist/application/replay-turn.d.ts +4 -0
- package/dist/application/replay-turn.js +47 -0
- package/dist/application/replay-turn.js.map +1 -0
- package/dist/application/replay-workspace.d.ts +4 -0
- package/dist/application/replay-workspace.js +71 -0
- package/dist/application/replay-workspace.js.map +1 -0
- package/dist/application/replay-workspace.types.d.ts +6 -0
- package/dist/application/replay-workspace.types.js +2 -0
- package/dist/application/replay-workspace.types.js.map +1 -0
- package/dist/application/repository-fingerprint.d.ts +1 -0
- package/dist/application/repository-fingerprint.js +18 -0
- package/dist/application/repository-fingerprint.js.map +1 -0
- package/dist/application/sandbox-dispatch.js +2 -0
- package/dist/application/sandbox-dispatch.js.map +1 -1
- package/dist/application/speculation-checkpoint.js +19 -2
- package/dist/application/speculation-checkpoint.js.map +1 -1
- package/dist/application/speculation-checkpoint.types.d.ts +1 -1
- package/dist/application/speculation-checkpoint.types.js.map +1 -1
- package/dist/application/speculation-resume.js +21 -0
- package/dist/application/speculation-resume.js.map +1 -1
- package/dist/application/speculation-run.js +18 -1
- package/dist/application/speculation-run.js.map +1 -1
- package/dist/application/speculation.types.d.ts +7 -2
- package/dist/application/speculation.types.js.map +1 -1
- package/dist/application/tasks.d.ts +2 -2
- package/dist/application/tasks.js +11 -4
- package/dist/application/tasks.js.map +1 -1
- package/dist/application/tasks.types.d.ts +5 -0
- package/dist/application/tasks.types.js.map +1 -1
- package/dist/application/transport-inspection.constants.js +1 -0
- package/dist/application/transport-inspection.constants.js.map +1 -1
- package/dist/application/transport-retention.js +33 -1
- package/dist/application/transport-retention.js.map +1 -1
- package/dist/domain/agent-observation.js +1 -0
- package/dist/domain/agent-observation.js.map +1 -1
- package/dist/domain/agent.types.d.ts +8 -1
- package/dist/domain/agent.types.js.map +1 -1
- package/dist/domain/errors.types.d.ts +1 -1
- package/dist/domain/errors.types.js.map +1 -1
- package/dist/domain/observation.types.d.ts +6 -1
- package/dist/domain/observation.types.js.map +1 -1
- package/dist/domain/quota.constants.d.ts +1 -0
- package/dist/domain/quota.constants.js +2 -0
- package/dist/domain/quota.constants.js.map +1 -0
- package/dist/domain/quota.d.ts +4 -0
- package/dist/domain/quota.js +28 -0
- package/dist/domain/quota.js.map +1 -0
- package/dist/domain/quota.types.d.ts +7 -0
- package/dist/domain/quota.types.js +2 -0
- package/dist/domain/quota.types.js.map +1 -0
- package/dist/domain/replay.constants.d.ts +11 -0
- package/dist/domain/replay.constants.js +42 -0
- package/dist/domain/replay.constants.js.map +1 -0
- package/dist/domain/replay.d.ts +11 -0
- package/dist/domain/replay.js +231 -0
- package/dist/domain/replay.js.map +1 -0
- package/dist/domain/replay.types.d.ts +84 -0
- package/dist/domain/replay.types.js +2 -0
- package/dist/domain/replay.types.js.map +1 -0
- package/dist/domain/task-queue.js +18 -0
- package/dist/domain/task-queue.js.map +1 -1
- package/dist/domain/task-queue.types.d.ts +9 -0
- package/dist/domain/task-queue.types.js.map +1 -1
- package/dist/domain/workflow/checkpoint-validation.js +14 -1
- package/dist/domain/workflow/checkpoint-validation.js.map +1 -1
- package/dist/domain/workflow/checkpoint.js +13 -2
- package/dist/domain/workflow/checkpoint.js.map +1 -1
- package/dist/domain/workflow/gate-validation.js +2 -1
- package/dist/domain/workflow/gate-validation.js.map +1 -1
- package/dist/domain/workflow/input-validation.d.ts +7 -0
- package/dist/domain/workflow/input-validation.js +82 -0
- package/dist/domain/workflow/input-validation.js.map +1 -0
- package/dist/domain/workflow/input.d.ts +10 -0
- package/dist/domain/workflow/input.js +93 -0
- package/dist/domain/workflow/input.js.map +1 -0
- package/dist/domain/workflow/input.types.d.ts +37 -0
- package/dist/domain/workflow/input.types.js +2 -0
- package/dist/domain/workflow/input.types.js.map +1 -0
- package/dist/domain/workflow/loop-runner.d.ts +3 -0
- package/dist/domain/workflow/loop-runner.js +91 -0
- package/dist/domain/workflow/loop-runner.js.map +1 -0
- package/dist/domain/workflow/loop-task.d.ts +10 -0
- package/dist/domain/workflow/loop-task.js +39 -0
- package/dist/domain/workflow/loop-task.js.map +1 -0
- package/dist/domain/workflow/loop-task.types.d.ts +28 -0
- package/dist/domain/workflow/loop-task.types.js +2 -0
- package/dist/domain/workflow/loop-task.types.js.map +1 -0
- package/dist/domain/workflow/loop-validation.d.ts +4 -0
- package/dist/domain/workflow/loop-validation.js +62 -0
- package/dist/domain/workflow/loop-validation.js.map +1 -0
- package/dist/domain/workflow/quota-pause.d.ts +7 -0
- package/dist/domain/workflow/quota-pause.js +83 -0
- package/dist/domain/workflow/quota-pause.js.map +1 -0
- package/dist/domain/workflow/quota-pause.types.d.ts +14 -0
- package/dist/domain/workflow/quota-pause.types.js +2 -0
- package/dist/domain/workflow/quota-pause.types.js.map +1 -0
- package/dist/domain/workflow/quota-validation.d.ts +2 -0
- package/dist/domain/workflow/quota-validation.js +30 -0
- package/dist/domain/workflow/quota-validation.js.map +1 -0
- package/dist/domain/workflow/task-cache-entry.d.ts +3 -0
- package/dist/domain/workflow/task-cache-entry.js +57 -0
- package/dist/domain/workflow/task-cache-entry.js.map +1 -0
- package/dist/domain/workflow/task-cache.constants.d.ts +3 -0
- package/dist/domain/workflow/task-cache.constants.js +3 -0
- package/dist/domain/workflow/task-cache.constants.js.map +1 -0
- package/dist/domain/workflow/task-cache.d.ts +6 -0
- package/dist/domain/workflow/task-cache.js +92 -0
- package/dist/domain/workflow/task-cache.js.map +1 -0
- package/dist/domain/workflow/task-cache.types.d.ts +35 -0
- package/dist/domain/workflow/task-cache.types.js +2 -0
- package/dist/domain/workflow/task-cache.types.js.map +1 -0
- package/dist/domain/workflow/task-runner.js +100 -34
- package/dist/domain/workflow/task-runner.js.map +1 -1
- package/dist/domain/workflow/task.js +21 -0
- package/dist/domain/workflow/task.js.map +1 -1
- package/dist/domain/workflow/validation.js +13 -2
- package/dist/domain/workflow/validation.js.map +1 -1
- package/dist/domain/workflow/workflow-scheduler.js +27 -2
- package/dist/domain/workflow/workflow-scheduler.js.map +1 -1
- package/dist/domain/workflow/workflow-state.js +20 -3
- package/dist/domain/workflow/workflow-state.js.map +1 -1
- package/dist/domain/workflow.types.d.ts +26 -3
- package/dist/domain/workflow.types.js.map +1 -1
- package/dist/index.d.ts +16 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/git/command.d.ts +2 -1
- package/dist/infrastructure/git/command.js +2 -2
- package/dist/infrastructure/git/command.js.map +1 -1
- package/dist/infrastructure/git/replay-commits.constants.d.ts +5 -0
- package/dist/infrastructure/git/replay-commits.constants.js +6 -0
- package/dist/infrastructure/git/replay-commits.constants.js.map +1 -0
- package/dist/infrastructure/git/replay-commits.d.ts +2 -0
- package/dist/infrastructure/git/replay-commits.js +92 -0
- package/dist/infrastructure/git/replay-commits.js.map +1 -0
- package/dist/infrastructure/journal.types.d.ts +1 -0
- package/dist/infrastructure/journal.types.js.map +1 -1
- package/dist/infrastructure/reporter.js +3 -0
- package/dist/infrastructure/reporter.js.map +1 -1
- package/dist/infrastructure/storage-inventory.types.d.ts +1 -1
- package/dist/infrastructure/storage-inventory.types.js.map +1 -1
- package/dist/infrastructure/transport-task-cache.constants.d.ts +2 -0
- package/dist/infrastructure/transport-task-cache.constants.js +3 -0
- package/dist/infrastructure/transport-task-cache.constants.js.map +1 -0
- package/dist/infrastructure/transport-task-cache.d.ts +3 -0
- package/dist/infrastructure/transport-task-cache.js +56 -0
- package/dist/infrastructure/transport-task-cache.js.map +1 -0
- package/dist/infrastructure/transport-task-cache.types.d.ts +4 -0
- package/dist/infrastructure/transport-task-cache.types.js +2 -0
- package/dist/infrastructure/transport-task-cache.types.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task-cache.types.js","sourceRoot":"","sources":["../../../src/domain/workflow/task-cache.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TaskContext } from \"../workflow.types.ts\";\nimport type {\n WorkflowCheckpointValue,\n WorkflowJson,\n} from \"./checkpoint.types.ts\";\n\nexport type TaskCacheMode = \"reuse\" | \"refresh\";\n\nexport type TaskCacheOutcome = \"hit\" | \"miss\" | \"stored\" | \"failed\";\n\nexport interface TaskCacheEntry {\n readonly format: 1;\n readonly fingerprint: string;\n readonly workflow: string;\n readonly task: string;\n readonly version: string;\n readonly createdAt: string;\n readonly value: WorkflowCheckpointValue;\n}\n\nexport interface TaskCacheAccessOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface TaskCacheStore {\n read(\n fingerprint: string,\n options?: TaskCacheAccessOptions,\n ): Promise<TaskCacheEntry | undefined>;\n write(entry: TaskCacheEntry, options?: TaskCacheAccessOptions): Promise<void>;\n}\n\nexport interface TaskCacheOptions {\n readonly store: TaskCacheStore;\n /** Change when the task implementation, agent or output contract changes. */\n readonly version: string;\n readonly key: (context: TaskContext) => WorkflowJson | Promise<WorkflowJson>;\n readonly maxAgeMs?: number;\n readonly mode?: TaskCacheMode;\n}\n\nexport type TaskCacheLookup =\n | { readonly hit: true; readonly value: unknown }\n | { readonly hit: false; readonly fingerprint: string };\n"]}
|
|
@@ -1,12 +1,21 @@
|
|
|
1
|
+
import { InputSuspension } from "./input.js";
|
|
2
|
+
import { loopDefinition } from "./loop-task.js";
|
|
3
|
+
import { runLoopTask } from "./loop-runner.js";
|
|
1
4
|
import { checkpointValue } from "./checkpoint-value.js";
|
|
2
5
|
import { WorkflowBudgetExceeded, WorkflowUsageUnavailable } from "./budget.js";
|
|
6
|
+
import { awaitQuotaReset, pauseForQuota } from "./quota-pause.js";
|
|
3
7
|
import { retryDelay, waitForRetry } from "./retry.js";
|
|
8
|
+
import { lookupTaskCache, storeTaskCache } from "./task-cache.js";
|
|
9
|
+
import { quotaFault } from "../quota.js";
|
|
4
10
|
export async function runTask(item, runtime) {
|
|
5
|
-
const { record, signal, context, emit, finish,
|
|
11
|
+
const { record, signal, context, emit, finish, errors, options, stop, values, } = runtime;
|
|
6
12
|
const state = record(item);
|
|
13
|
+
if (state.quota && !(await awaitQuotaReset(item, runtime, true)))
|
|
14
|
+
return;
|
|
7
15
|
state.status = "active";
|
|
8
16
|
delete state.error;
|
|
9
17
|
delete state.finishedAt;
|
|
18
|
+
delete state.cacheHit;
|
|
10
19
|
state.startedAt = new Date().toISOString();
|
|
11
20
|
emit({ type: "task", key: item.key, status: "active", attempt: 0 });
|
|
12
21
|
try {
|
|
@@ -17,45 +26,30 @@ export async function runTask(item, runtime) {
|
|
|
17
26
|
finish(item, "skipped");
|
|
18
27
|
return;
|
|
19
28
|
}
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const deadline = new AbortController();
|
|
31
|
-
const timer = item.timeoutMs === undefined
|
|
32
|
-
? undefined
|
|
33
|
-
: setTimeout(() => deadline.abort(new Error(`${item.key} timed out`)), item.timeoutMs);
|
|
34
|
-
const taskSignal = AbortSignal.any([signal, deadline.signal]);
|
|
29
|
+
const cache = item.cache
|
|
30
|
+
? await lookupTaskCache(item, item.cache, runtime)
|
|
31
|
+
: undefined;
|
|
32
|
+
if (cache?.hit) {
|
|
33
|
+
values.set(item, cache.value);
|
|
34
|
+
state.cacheHit = true;
|
|
35
|
+
finish(item, "done");
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
while (true) {
|
|
35
39
|
try {
|
|
36
|
-
|
|
37
|
-
const value = await item.perform(context(item, attempt, taskSignal));
|
|
38
|
-
taskSignal.throwIfAborted();
|
|
39
|
-
if (options.checkpoint)
|
|
40
|
-
checkpointValue(value);
|
|
41
|
-
values.set(item, value);
|
|
42
|
-
finish(item, "done");
|
|
40
|
+
await perform(item, runtime, cache);
|
|
43
41
|
return;
|
|
44
42
|
}
|
|
45
43
|
catch (error) {
|
|
46
|
-
|
|
47
|
-
if (signal.aborted ||
|
|
48
|
-
cycle === limit ||
|
|
49
|
-
item.retry?.accepts?.(error, attempt) === false)
|
|
44
|
+
if (!(await pauseForQuota(item, runtime, error)))
|
|
50
45
|
throw error;
|
|
51
|
-
|
|
52
|
-
|
|
46
|
+
if (!(await awaitQuotaReset(item, runtime, false)))
|
|
47
|
+
return;
|
|
48
|
+
state.status = "active";
|
|
49
|
+
delete state.finishedAt;
|
|
50
|
+
emit({ type: "task", key: item.key, status: "active", attempt: 0 });
|
|
51
|
+
await runtime.persist();
|
|
53
52
|
}
|
|
54
|
-
finally {
|
|
55
|
-
runtime.closeAttempt(item);
|
|
56
|
-
clearTimeout(timer);
|
|
57
|
-
}
|
|
58
|
-
await waitForRetry(delayMs, signal);
|
|
59
53
|
}
|
|
60
54
|
}
|
|
61
55
|
catch (error) {
|
|
@@ -76,4 +70,76 @@ export async function runTask(item, runtime) {
|
|
|
76
70
|
await runtime.persist();
|
|
77
71
|
}
|
|
78
72
|
}
|
|
73
|
+
async function complete(item, runtime, cache, value) {
|
|
74
|
+
if (item.cache && cache && !cache.hit)
|
|
75
|
+
await storeTaskCache(item, item.cache, runtime, cache.fingerprint, value);
|
|
76
|
+
runtime.values.set(item, value);
|
|
77
|
+
runtime.finish(item, "done");
|
|
78
|
+
}
|
|
79
|
+
async function perform(item, runtime, cache) {
|
|
80
|
+
const { record, signal, context, emit, finish, options } = runtime;
|
|
81
|
+
const state = record(item);
|
|
82
|
+
const loop = loopDefinition(item);
|
|
83
|
+
if (loop) {
|
|
84
|
+
const value = await runLoopTask(item, loop, runtime);
|
|
85
|
+
signal.throwIfAborted();
|
|
86
|
+
await complete(item, runtime, cache, value);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const limit = item.retry?.attempts ?? 1;
|
|
90
|
+
const priorAttempts = state.attempts;
|
|
91
|
+
for (let cycle = 1; cycle <= limit; cycle++) {
|
|
92
|
+
const attempt = priorAttempts + cycle;
|
|
93
|
+
signal.throwIfAborted();
|
|
94
|
+
runtime.accounting.admit();
|
|
95
|
+
state.attempts = attempt;
|
|
96
|
+
emit({ type: "attempt", key: item.key, attempt });
|
|
97
|
+
await runtime.persist();
|
|
98
|
+
let delayMs = 0;
|
|
99
|
+
let completed = false;
|
|
100
|
+
let value;
|
|
101
|
+
const deadline = new AbortController();
|
|
102
|
+
const timer = item.timeoutMs === undefined
|
|
103
|
+
? undefined
|
|
104
|
+
: setTimeout(() => deadline.abort(new Error(`${item.key} timed out`)), item.timeoutMs);
|
|
105
|
+
const taskSignal = AbortSignal.any([signal, deadline.signal]);
|
|
106
|
+
try {
|
|
107
|
+
taskSignal.throwIfAborted();
|
|
108
|
+
value = await item.perform(context(item, attempt, taskSignal));
|
|
109
|
+
taskSignal.throwIfAborted();
|
|
110
|
+
if (options.checkpoint)
|
|
111
|
+
checkpointValue(value);
|
|
112
|
+
completed = true;
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
runtime.closeAttempt(item);
|
|
116
|
+
if (error instanceof InputSuspension && item.interaction) {
|
|
117
|
+
state.interaction = error.interaction;
|
|
118
|
+
finish(item, "waiting-input");
|
|
119
|
+
emit({
|
|
120
|
+
type: "input-request",
|
|
121
|
+
key: item.key,
|
|
122
|
+
status: "waiting-input",
|
|
123
|
+
});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (signal.aborted ||
|
|
127
|
+
cycle === limit ||
|
|
128
|
+
(options.onQuota && quotaFault(error)) ||
|
|
129
|
+
item.retry?.accepts?.(error, attempt) === false)
|
|
130
|
+
throw error;
|
|
131
|
+
delayMs = retryDelay(item.retry, cycle, error);
|
|
132
|
+
emit({ type: "retry", key: item.key, attempt, delayMs });
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
runtime.closeAttempt(item);
|
|
136
|
+
clearTimeout(timer);
|
|
137
|
+
}
|
|
138
|
+
if (completed) {
|
|
139
|
+
await complete(item, runtime, cache, value);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
await waitForRetry(delayMs, signal);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
79
145
|
//# sourceMappingURL=task-runner.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-run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AAO,CAAC,WAAW,KAAK,KAAK;gBAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;AACH,CAAC","sourcesContent":["import { checkpointValue } from \"./checkpoint-value.ts\";\nimport { WorkflowBudgetExceeded, WorkflowUsageUnavailable } from \"./budget.ts\";\nimport { retryDelay, waitForRetry } from \"./retry.ts\";\nimport type { Task, WorkflowExecutionState } from \"../workflow.types.ts\";\n\nexport async function runTask(\n item: Task,\n runtime: WorkflowExecutionState,\n): Promise<void> {\n const {\n record,\n signal,\n context,\n emit,\n finish,\n values,\n errors,\n options,\n stop,\n } = runtime;\n const state = record(item);\n state.status = \"active\";\n delete state.error;\n delete state.finishedAt;\n state.startedAt = new Date().toISOString();\n emit({ type: \"task\", key: item.key, status: \"active\", attempt: 0 });\n try {\n await runtime.persist();\n signal.throwIfAborted();\n if (item.condition && !(await item.condition(context(item, 0, signal)))) {\n signal.throwIfAborted();\n finish(item, \"skipped\");\n return;\n }\n const limit = item.retry?.attempts ?? 1;\n const priorAttempts = state.attempts;\n for (let cycle = 1; cycle <= limit; cycle++) {\n const attempt = priorAttempts + cycle;\n signal.throwIfAborted();\n runtime.accounting.admit();\n state.attempts = attempt;\n emit({ type: \"attempt\", key: item.key, attempt });\n await runtime.persist();\n let delayMs = 0;\n const deadline = new AbortController();\n const timer =\n item.timeoutMs === undefined\n ? undefined\n : setTimeout(\n () => deadline.abort(new Error(`${item.key} timed out`)),\n item.timeoutMs,\n );\n const taskSignal = AbortSignal.any([signal, deadline.signal]);\n try {\n taskSignal.throwIfAborted();\n const value = await item.perform(context(item, attempt, taskSignal));\n taskSignal.throwIfAborted();\n if (options.checkpoint) checkpointValue(value);\n values.set(item, value);\n finish(item, \"done\");\n return;\n } catch (error) {\n runtime.closeAttempt(item);\n if (\n signal.aborted ||\n cycle === limit ||\n item.retry?.accepts?.(error, attempt) === false\n )\n throw error;\n delayMs = retryDelay(item.retry, cycle, error);\n emit({ type: \"retry\", key: item.key, attempt, delayMs });\n } finally {\n runtime.closeAttempt(item);\n clearTimeout(timer);\n }\n await waitForRetry(delayMs, signal);\n }\n } catch (error) {\n state.error = error instanceof Error ? error.message : String(error);\n if (\n signal.aborted ||\n ((error instanceof WorkflowBudgetExceeded ||\n error instanceof WorkflowUsageUnavailable) &&\n runtime.accounting.exhausted)\n )\n finish(item, \"cancelled\");\n else {\n errors.push(error);\n finish(item, \"failed\");\n if (options.stopOnError !== false) stop.abort(error);\n }\n } finally {\n await runtime.persist();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"task-runner.js","sourceRoot":"","sources":["../../../src/domain/workflow/task-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,IAAU,EACV,OAA+B;IAE/B,MAAM,EACJ,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,MAAM,GACP,GAAG,OAAO,CAAC;IACZ,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,C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,CAAC,CAAC;YAC3B,IAAI,KAAK,YAAY,eAAe,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;gBACzD,KAAK,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;gBACtC,MAAM,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;gBAC9B,IAAI,CAAC;oBACH,IAAI,EAAE,eAAe;oBACrB,GAAG,EAAE,IAAI,CAAC,GAAG;oBACb,MAAM,EAAE,eAAe;iBACxB,CAAC,CAAC;gBACH,OAAO;YACT,CAAC;YACD,IACE,MAAM,CAAC,OAAO;gBACd,KAAK,KAAK,KAAK;gBACf,CAAC,OAAO,CAAC,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;gBACtC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,KAAK;gBAE/C,MAAM,KAAK,CAAC;YACd,OAAO,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;YAC/C,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;QAC3D,CAAC;gBAAS,CAAC;YACT,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;YAC3B,YAAY,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,IAAI,SAAS,EAAE,CAAC;YACd,MAAM,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO;QACT,CAAC;QACD,MAAM,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACtC,CAAC;AACH,CAAC","sourcesContent":["import { InputSuspension } from \"./input.ts\";\nimport { loopDefinition } from \"./loop-task.ts\";\nimport { runLoopTask } from \"./loop-runner.ts\";\nimport { checkpointValue } from \"./checkpoint-value.ts\";\nimport { WorkflowBudgetExceeded, WorkflowUsageUnavailable } from \"./budget.ts\";\nimport { awaitQuotaReset, pauseForQuota } from \"./quota-pause.ts\";\nimport { retryDelay, waitForRetry } from \"./retry.ts\";\nimport { lookupTaskCache, storeTaskCache } from \"./task-cache.ts\";\nimport { quotaFault } from \"../quota.ts\";\nimport type { Task, WorkflowExecutionState } from \"../workflow.types.ts\";\nimport type { TaskCacheLookup } from \"./task-cache.types.ts\";\n\nexport async function runTask(\n item: Task,\n runtime: WorkflowExecutionState,\n): Promise<void> {\n const {\n record,\n signal,\n context,\n emit,\n finish,\n errors,\n options,\n stop,\n values,\n } = runtime;\n const state = record(item);\n if (state.quota && !(await awaitQuotaReset(item, runtime, true))) return;\n state.status = \"active\";\n delete state.error;\n delete state.finishedAt;\n delete state.cacheHit;\n state.startedAt = new Date().toISOString();\n emit({ type: \"task\", key: item.key, status: \"active\", attempt: 0 });\n try {\n await runtime.persist();\n signal.throwIfAborted();\n if (item.condition && !(await item.condition(context(item, 0, signal)))) {\n signal.throwIfAborted();\n finish(item, \"skipped\");\n return;\n }\n const cache = item.cache\n ? await lookupTaskCache(item, item.cache, runtime)\n : undefined;\n if (cache?.hit) {\n values.set(item, cache.value);\n state.cacheHit = true;\n finish(item, \"done\");\n return;\n }\n while (true) {\n try {\n await perform(item, runtime, cache);\n return;\n } catch (error) {\n if (!(await pauseForQuota(item, runtime, error))) throw error;\n if (!(await awaitQuotaReset(item, runtime, false))) return;\n state.status = \"active\";\n delete state.finishedAt;\n emit({ type: \"task\", key: item.key, status: \"active\", attempt: 0 });\n await runtime.persist();\n }\n }\n } catch (error) {\n state.error = error instanceof Error ? error.message : String(error);\n if (\n signal.aborted ||\n ((error instanceof WorkflowBudgetExceeded ||\n error instanceof WorkflowUsageUnavailable) &&\n runtime.accounting.exhausted)\n )\n finish(item, \"cancelled\");\n else {\n errors.push(error);\n finish(item, \"failed\");\n if (options.stopOnError !== false) stop.abort(error);\n }\n } finally {\n await runtime.persist();\n }\n}\n\nasync function complete(\n item: Task,\n runtime: WorkflowExecutionState,\n cache: TaskCacheLookup | undefined,\n value: unknown,\n): Promise<void> {\n if (item.cache && cache && !cache.hit)\n await storeTaskCache(item, item.cache, runtime, cache.fingerprint, value);\n runtime.values.set(item, value);\n runtime.finish(item, \"done\");\n}\n\nasync function perform(\n item: Task,\n runtime: WorkflowExecutionState,\n cache: TaskCacheLookup | undefined,\n): Promise<void> {\n const { record, signal, context, emit, finish, options } = runtime;\n const state = record(item);\n const loop = loopDefinition(item);\n if (loop) {\n const value = await runLoopTask(item, loop, runtime);\n signal.throwIfAborted();\n await complete(item, runtime, cache, value);\n return;\n }\n const limit = item.retry?.attempts ?? 1;\n const priorAttempts = state.attempts;\n for (let cycle = 1; cycle <= limit; cycle++) {\n const attempt = priorAttempts + cycle;\n signal.throwIfAborted();\n runtime.accounting.admit();\n state.attempts = attempt;\n emit({ type: \"attempt\", key: item.key, attempt });\n await runtime.persist();\n let delayMs = 0;\n let completed = false;\n let value: unknown;\n const deadline = new AbortController();\n const timer =\n item.timeoutMs === undefined\n ? undefined\n : setTimeout(\n () => deadline.abort(new Error(`${item.key} timed out`)),\n item.timeoutMs,\n );\n const taskSignal = AbortSignal.any([signal, deadline.signal]);\n try {\n taskSignal.throwIfAborted();\n value = await item.perform(context(item, attempt, taskSignal));\n taskSignal.throwIfAborted();\n if (options.checkpoint) checkpointValue(value);\n completed = true;\n } catch (error) {\n runtime.closeAttempt(item);\n if (error instanceof InputSuspension && item.interaction) {\n state.interaction = error.interaction;\n finish(item, \"waiting-input\");\n emit({\n type: \"input-request\",\n key: item.key,\n status: \"waiting-input\",\n });\n return;\n }\n if (\n signal.aborted ||\n cycle === limit ||\n (options.onQuota && quotaFault(error)) ||\n item.retry?.accepts?.(error, attempt) === false\n )\n throw error;\n delayMs = retryDelay(item.retry, cycle, error);\n emit({ type: \"retry\", key: item.key, attempt, delayMs });\n } finally {\n runtime.closeAttempt(item);\n clearTimeout(timer);\n }\n if (completed) {\n await complete(item, runtime, cache, value);\n return;\n }\n await waitForRetry(delayMs, signal);\n }\n}\n"]}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { validateInteraction } from "./input-validation.js";
|
|
1
2
|
import { validateRetry } from "./retry.js";
|
|
2
3
|
import { maxTimerMs } from "./retry.constants.js";
|
|
3
4
|
import { positive } from "./validation.js";
|
|
5
|
+
import { validateTaskCache } from "./task-cache.js";
|
|
4
6
|
export function task(options) {
|
|
5
7
|
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(options.key))
|
|
6
8
|
throw new Error(`Invalid task key: ${options.key}`);
|
|
@@ -8,11 +10,30 @@ export function task(options) {
|
|
|
8
10
|
positive(options.timeoutMs, "timeoutMs");
|
|
9
11
|
if (options.timeoutMs !== undefined && options.timeoutMs > maxTimerMs)
|
|
10
12
|
throw new Error("timeoutMs exceeds the supported timer range");
|
|
13
|
+
if (options.interaction) {
|
|
14
|
+
validateInteraction(options.interaction);
|
|
15
|
+
if (options.gate)
|
|
16
|
+
throw new Error("A task cannot be both an interaction and a gate");
|
|
17
|
+
}
|
|
11
18
|
if (options.retry)
|
|
12
19
|
validateRetry(options.retry);
|
|
20
|
+
if (options.cache !== undefined) {
|
|
21
|
+
validateTaskCache(options.cache);
|
|
22
|
+
if (options.interaction || options.gate)
|
|
23
|
+
throw new Error("Interactions and gates cannot use a task cache");
|
|
24
|
+
}
|
|
13
25
|
return Object.freeze({
|
|
14
26
|
...options,
|
|
27
|
+
...(options.interaction
|
|
28
|
+
? {
|
|
29
|
+
interaction: Object.freeze({
|
|
30
|
+
...options.interaction,
|
|
31
|
+
actors: Object.freeze([...options.interaction.actors]),
|
|
32
|
+
}),
|
|
33
|
+
}
|
|
34
|
+
: {}),
|
|
15
35
|
...(options.retry ? { retry: Object.freeze({ ...options.retry }) } : {}),
|
|
36
|
+
...(options.cache ? { cache: Object.freeze({ ...options.cache }) } : {}),
|
|
16
37
|
after: Object.freeze([...(options.after ?? [])]),
|
|
17
38
|
});
|
|
18
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task.js","sourceRoot":"","sources":["../../../src/domain/workflow/task.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"task.js","sourceRoot":"","sources":["../../../src/domain/workflow/task.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,UAAU,IAAI,CAAI,OAAuB;IAC7C,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC;QACnD,MAAM,IAAI,KAAK,CAAC,qBAAqB,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IACtD,IAAI,OAAO,CAAC,SAAS,KAAK,SAAS;QAAE,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IAC9E,IAAI,OAAO,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,CAAC,SAAS,GAAG,UAAU;QACnE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;IACjE,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;QACxB,mBAAmB,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACzC,IAAI,OAAO,CAAC,IAAI;YACd,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACvE,CAAC;IACD,IAAI,OAAO,CAAC,KAAK;QAAE,aAAa,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,OAAO,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;QAChC,iBAAiB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACjC,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,IAAI;YACrC,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,GAAG,OAAO;QACV,GAAG,CAAC,OAAO,CAAC,WAAW;YACrB,CAAC,CAAC;gBACE,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC;oBACzB,GAAG,OAAO,CAAC,WAAW;oBACtB,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;iBACvD,CAAC;aACH;YACH,CAAC,CAAC,EAAE,CAAC;QACP,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACxE,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACxE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { validateInteraction } from \"./input-validation.ts\";\nimport { validateRetry } from \"./retry.ts\";\nimport { maxTimerMs } from \"./retry.constants.ts\";\nimport type { Task, TaskOptions } from \"../workflow.types.ts\";\nimport { positive } from \"./validation.ts\";\nimport { validateTaskCache } from \"./task-cache.ts\";\n\nexport function task<T>(options: TaskOptions<T>): Task<T> {\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(options.key))\n throw new Error(`Invalid task key: ${options.key}`);\n if (options.timeoutMs !== undefined) positive(options.timeoutMs, \"timeoutMs\");\n if (options.timeoutMs !== undefined && options.timeoutMs > maxTimerMs)\n throw new Error(\"timeoutMs exceeds the supported timer range\");\n if (options.interaction) {\n validateInteraction(options.interaction);\n if (options.gate)\n throw new Error(\"A task cannot be both an interaction and a gate\");\n }\n if (options.retry) validateRetry(options.retry);\n if (options.cache !== undefined) {\n validateTaskCache(options.cache);\n if (options.interaction || options.gate)\n throw new Error(\"Interactions and gates cannot use a task cache\");\n }\n return Object.freeze({\n ...options,\n ...(options.interaction\n ? {\n interaction: Object.freeze({\n ...options.interaction,\n actors: Object.freeze([...options.interaction.actors]),\n }),\n }\n : {}),\n ...(options.retry ? { retry: Object.freeze({ ...options.retry }) } : {}),\n ...(options.cache ? { cache: Object.freeze({ ...options.cache }) } : {}),\n after: Object.freeze([...(options.after ?? [])]),\n });\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { validateInteraction } from "./input-validation.js";
|
|
1
2
|
import { validateGate } from "./gate-validation.js";
|
|
2
3
|
export function positive(value, label) {
|
|
3
4
|
if (!Number.isSafeInteger(value) || value < 1)
|
|
@@ -9,10 +10,20 @@ export function validate(tasks) {
|
|
|
9
10
|
const visiting = new Set();
|
|
10
11
|
const visited = new Set();
|
|
11
12
|
for (const item of tasks) {
|
|
13
|
+
if (item.interaction) {
|
|
14
|
+
validateInteraction(item.interaction);
|
|
15
|
+
if (item.cache)
|
|
16
|
+
throw new Error("Interactions and gates cannot use a task cache");
|
|
17
|
+
if (item.gate)
|
|
18
|
+
throw new Error("A task cannot be both an interaction and a gate");
|
|
19
|
+
}
|
|
12
20
|
if (item.gate) {
|
|
13
21
|
validateGate(item.gate);
|
|
14
|
-
if (item.condition ||
|
|
15
|
-
|
|
22
|
+
if (item.condition ||
|
|
23
|
+
item.retry ||
|
|
24
|
+
item.timeoutMs !== undefined ||
|
|
25
|
+
item.cache)
|
|
26
|
+
throw new Error("Workflow gates cannot have conditions, retries, timeouts or caches");
|
|
16
27
|
}
|
|
17
28
|
if (keys.has(item.key))
|
|
18
29
|
throw new Error(`Duplicate task: ${item.key}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../../src/domain/workflow/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGpD,MAAM,UAAU,QAAQ,CAAC,KAAa,EAAE,KAAa;IACnD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC;QAC3C,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,6BAA6B,CAAC,CAAC;AAC3D,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,KAAsB;IAC7C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC/B,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAQ,CAAC;IACjC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAQ,CAAC;IAChC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACxB,
|
|
1
|
+
{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../../src/domain/workflow/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGpD,MAAM,UAAU,QAAQ,CAAC,KAAa,EAAE,KAAa;I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AAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;gBAC1B,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,GAAG,wBAAwB,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC;IAC3E,CAAC;IACD,SAAS,KAAK,CAAC,IAAU;QACvB,IAAI,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QAC3E,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,OAAO;QAC9B,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACnB,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAC1B,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACpB,CAAC;IACD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import { validateInteraction } from \"./input-validation.ts\";\nimport { validateGate } from \"./gate-validation.ts\";\nimport type { Task } from \"../workflow.types.ts\";\n\nexport function positive(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value < 1)\n throw new Error(`${label} must be a positive integer`);\n}\n\nexport function validate(tasks: readonly Task[]): void {\n const keys = new Set<string>();\n const members = new Set(tasks);\n const visiting = new Set<Task>();\n const visited = new Set<Task>();\n for (const item of tasks) {\n if (item.interaction) {\n validateInteraction(item.interaction);\n if (item.cache)\n throw new Error(\"Interactions and gates cannot use a task cache\");\n if (item.gate)\n throw new Error(\"A task cannot be both an interaction and a gate\");\n }\n if (item.gate) {\n validateGate(item.gate);\n if (\n item.condition ||\n item.retry ||\n item.timeoutMs !== undefined ||\n item.cache\n )\n throw new Error(\n \"Workflow gates cannot have conditions, retries, timeouts or caches\",\n );\n }\n if (keys.has(item.key)) throw new Error(`Duplicate task: ${item.key}`);\n keys.add(item.key);\n for (const dependency of item.after)\n if (!members.has(dependency))\n throw new Error(`${item.key}: missing dependency ${dependency.key}`);\n }\n function visit(item: Task): void {\n if (visiting.has(item)) throw new Error(`Dependency cycle at ${item.key}`);\n if (visited.has(item)) return;\n visiting.add(item);\n item.after.forEach(visit);\n visiting.delete(item);\n visited.add(item);\n }\n tasks.forEach(visit);\n}\n"]}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { prepareAnswers, applyAnswers } from "./input.js";
|
|
1
2
|
import { OutpostError } from "../errors.js";
|
|
3
|
+
import { quotaResumes, validateQuotaPolicy } from "./quota-pause.js";
|
|
2
4
|
import { maxTimerMs } from "./retry.constants.js";
|
|
3
5
|
import { applyDecisions, pauseGate, prepareDecisions } from "./gates.js";
|
|
4
6
|
import { openCheckpoint } from "./checkpoint.js";
|
|
@@ -7,6 +9,16 @@ import { runTask } from "./task-runner.js";
|
|
|
7
9
|
import { positive } from "./validation.js";
|
|
8
10
|
import { workflowState } from "./workflow-state.js";
|
|
9
11
|
export async function schedule(name, tasks, options) {
|
|
12
|
+
if (!options.checkpoint &&
|
|
13
|
+
(tasks.some((item) => item.interaction) || options.answers?.length))
|
|
14
|
+
throw new Error("Workflow interactions and answers require a checkpoint");
|
|
15
|
+
if (options.answers && !options.answers.length)
|
|
16
|
+
throw new Error("Workflow answers cannot be empty");
|
|
17
|
+
if (options.onQuota) {
|
|
18
|
+
if (!options.checkpoint)
|
|
19
|
+
throw new Error("Workflow quota pauses require a checkpoint");
|
|
20
|
+
validateQuotaPolicy(options.onQuota);
|
|
21
|
+
}
|
|
10
22
|
if (!options.checkpoint &&
|
|
11
23
|
(tasks.some((item) => item.gate) || options.decisions?.length))
|
|
12
24
|
throw new Error("Workflow gates and decisions require a checkpoint");
|
|
@@ -46,20 +58,27 @@ async function scheduleRun(name, tasks, options, checkpoint, deadline) {
|
|
|
46
58
|
const { executionId, signal, values, records, errors, observerErrors, record, emit, finish, } = state;
|
|
47
59
|
const active = new Map();
|
|
48
60
|
const started = Date.now();
|
|
61
|
+
const answers = prepareAnswers(state);
|
|
49
62
|
const decisions = await prepareDecisions(state);
|
|
50
63
|
emit({ type: "start" });
|
|
51
64
|
if (checkpoint?.initial)
|
|
52
65
|
emit({ type: "resume" });
|
|
53
|
-
if (!signal.aborted)
|
|
66
|
+
if (!signal.aborted) {
|
|
54
67
|
applyDecisions(state, decisions);
|
|
68
|
+
applyAnswers(state, answers);
|
|
69
|
+
}
|
|
55
70
|
await state.persist();
|
|
71
|
+
const resumes = quotaResumes(state);
|
|
56
72
|
try {
|
|
57
73
|
while (true) {
|
|
58
74
|
let changed = false;
|
|
59
75
|
for (const item of tasks) {
|
|
60
|
-
|
|
76
|
+
const resumed = resumes.has(item);
|
|
77
|
+
if (record(item).status !== "waiting" && !resumed)
|
|
61
78
|
continue;
|
|
62
79
|
if (signal.aborted || state.accounting.exhausted) {
|
|
80
|
+
if (resumes.delete(item))
|
|
81
|
+
continue;
|
|
63
82
|
finish(item, "cancelled");
|
|
64
83
|
changed = true;
|
|
65
84
|
continue;
|
|
@@ -74,6 +93,7 @@ async function scheduleRun(name, tasks, options, checkpoint, deadline) {
|
|
|
74
93
|
item.after.some((dependency) => active.has(dependency)) ||
|
|
75
94
|
!dependencies.every((status) => status === "done"))
|
|
76
95
|
continue;
|
|
96
|
+
resumes.delete(item);
|
|
77
97
|
const running = (item.gate ? pauseGate(item, state) : runTask(item, state)).finally(() => {
|
|
78
98
|
active.delete(item);
|
|
79
99
|
});
|
|
@@ -100,6 +120,8 @@ async function scheduleRun(name, tasks, options, checkpoint, deadline) {
|
|
|
100
120
|
let status = "done";
|
|
101
121
|
if (paused)
|
|
102
122
|
status = "paused";
|
|
123
|
+
if ([...records.values()].some((entry) => entry.status === "waiting-input"))
|
|
124
|
+
status = "waiting-input";
|
|
103
125
|
if (errors.length)
|
|
104
126
|
status = "failed";
|
|
105
127
|
if (options.signal?.aborted)
|
|
@@ -110,6 +132,9 @@ async function scheduleRun(name, tasks, options, checkpoint, deadline) {
|
|
|
110
132
|
const result = Object.freeze({
|
|
111
133
|
executionId,
|
|
112
134
|
name,
|
|
135
|
+
inputRequests: Object.freeze([...records.values()].flatMap((record) => record.status === "waiting-input" && record.interaction?.request
|
|
136
|
+
? [record.interaction.request]
|
|
137
|
+
: [])),
|
|
113
138
|
status,
|
|
114
139
|
usage: state.accounting.snapshot(),
|
|
115
140
|
tasks: Object.freeze([...records.values()].map((value) => Object.freeze({ ...value }))),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-scheduler.js","sourceRoot":"","sources":["../../../src/domain/workflow/workflow-scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOjD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,IAAY,EACZ,KAAsB,EACtB,OAAwB;IAExB,IACE,CAAC,OAAO,CAAC,UAAU;QACnB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC;QAE9D,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,IAAI,OAAO,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,MAAM;QAChD,MA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,CAAC;AACxE,CAAC","sourcesContent":["import { OutpostError } from \"../errors.ts\";\nimport { maxTimerMs } from \"./retry.constants.ts\";\nimport { applyDecisions, pauseGate, prepareDecisions } from \"./gates.ts\";\nimport { openCheckpoint } from \"./checkpoint.ts\";\nimport type { WorkflowCheckpointSession } from \"./checkpoint.types.ts\";\nimport type {\n Task,\n WorkflowOptions,\n WorkflowResult,\n} from \"../workflow.types.ts\";\nimport { WorkflowFailure } from \"./failure.ts\";\nimport { runTask } from \"./task-runner.ts\";\nimport { positive } from \"./validation.ts\";\nimport { workflowState } from \"./workflow-state.ts\";\n\nexport async function schedule(\n name: string,\n tasks: readonly Task[],\n options: WorkflowOptions,\n): Promise<WorkflowResult> {\n if (\n !options.checkpoint &&\n (tasks.some((item) => item.gate) || options.decisions?.length)\n )\n throw new Error(\"Workflow gates and decisions require a checkpoint\");\n if (options.decisions && !options.decisions.length)\n throw new Error(\"Workflow decisions cannot be empty\");\n if (options.timeoutMs !== undefined) {\n positive(options.timeoutMs, \"Workflow timeoutMs\");\n if (options.timeoutMs > maxTimerMs)\n throw new Error(\"Workflow timeoutMs exceeds the supported timer range\");\n }\n const deadline = new AbortController();\n const timer =\n options.timeoutMs === undefined\n ? undefined\n : setTimeout(\n () =>\n deadline.abort(\n new OutpostError(\"timeout\", `Workflow ${name} timed out`, {\n timeoutMs: options.timeoutMs,\n }),\n ),\n options.timeoutMs,\n );\n const signal = options.signal\n ? AbortSignal.any([options.signal, deadline.signal])\n : deadline.signal;\n let checkpoint: WorkflowCheckpointSession | undefined;\n try {\n checkpoint = options.checkpoint\n ? await openCheckpoint(name, tasks, options.checkpoint)\n : undefined;\n return await scheduleRun(\n name,\n tasks,\n { ...options, signal },\n checkpoint,\n deadline.signal,\n );\n } finally {\n clearTimeout(timer);\n await checkpoint?.release();\n }\n}\n\nasync function scheduleRun(\n name: string,\n tasks: readonly Task[],\n options: WorkflowOptions,\n checkpoint: WorkflowCheckpointSession | undefined,\n deadline: AbortSignal,\n): Promise<WorkflowResult> {\n const concurrency = options.concurrency ?? 1;\n positive(concurrency, \"concurrency\");\n const state = workflowState(name, tasks, options, checkpoint);\n try {\n const {\n executionId,\n signal,\n values,\n records,\n errors,\n observerErrors,\n record,\n emit,\n finish,\n } = state;\n const active = new Map<Task, Promise<void>>();\n const started = Date.now();\n const decisions = await prepareDecisions(state);\n emit({ type: \"start\" });\n if (checkpoint?.initial) emit({ type: \"resume\" });\n if (!signal.aborted) applyDecisions(state, decisions);\n await state.persist();\n try {\n while (true) {\n let changed = false;\n for (const item of tasks) {\n if (record(item).status !== \"waiting\") continue;\n if (signal.aborted || state.accounting.exhausted) {\n finish(item, \"cancelled\");\n changed = true;\n continue;\n }\n const dependencies = item.after.map(\n (dependency) => record(dependency).status,\n );\n if (\n dependencies.some((status) =>\n [\"failed\", \"skipped\", \"cancelled\", \"rejected\"].includes(status),\n )\n ) {\n finish(item, \"skipped\");\n changed = true;\n continue;\n }\n if (\n active.size >= concurrency ||\n item.after.some((dependency) => active.has(dependency)) ||\n !dependencies.every((status) => status === \"done\")\n )\n continue;\n const running = (\n item.gate ? pauseGate(item, state) : runTask(item, state)\n ).finally(() => {\n active.delete(item);\n });\n active.set(item, running);\n changed = true;\n }\n if (active.size) {\n await Promise.race(active.values());\n continue;\n }\n if (!changed) break;\n }\n } catch (error) {\n state.stop.abort(error);\n await Promise.allSettled(active.values());\n throw error;\n }\n await state.persist();\n if (options.signal?.aborted) errors.push(options.signal.reason);\n const paused = [...records.values()].some(\n (entry) => entry.status === \"paused\",\n );\n let status: WorkflowResult[\"status\"] = \"done\";\n if (paused) status = \"paused\";\n if (errors.length) status = \"failed\";\n if (options.signal?.aborted)\n status = timedOut(options, deadline) ? \"failed\" : \"cancelled\";\n emit({ type: \"finish\", status, durationMs: Date.now() - started });\n await state.observation.close();\n observerErrors.push(...state.observation.errors);\n const result: WorkflowResult = Object.freeze({\n executionId,\n name,\n status,\n usage: state.accounting.snapshot(),\n tasks: Object.freeze(\n [...records.values()].map((value) => Object.freeze({ ...value })),\n ),\n errors: Object.freeze(errors),\n observerErrors: Object.freeze(observerErrors),\n value<T>(item: Task<T>): T {\n if (!values.has(item))\n throw new Error(\n `${item.key} has no successful value in this execution`,\n );\n return values.get(item) as T;\n },\n unwrap() {\n if (status !== \"done\") throw new WorkflowFailure(result);\n },\n });\n return result;\n } catch (error) {\n state.emit({\n type: \"finish\",\n status:\n options.signal?.aborted && !timedOut(options, deadline)\n ? \"cancelled\"\n : \"failed\",\n });\n await state.observation.close();\n throw error;\n }\n}\n\nfunction timedOut(options: WorkflowOptions, deadline: AbortSignal): boolean {\n return deadline.aborted && options.signal?.reason === deadline.reason;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workflow-scheduler.js","sourceRoot":"","sources":["../../../src/domain/workflow/workflow-scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOjD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,IAAY,EACZ,KAAsB,EACtB,OAAwB;IAExB,IACE,CAAC,OAAO,CAAC,UAAU;QACnB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI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EAAE,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;gBACrD,CAAC,CAAC,WAAW;gBACb,CAAC,CAAC,QAAQ;SACf,CAAC,CAAC;QACH,MAAM,KAAK,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QAChC,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,OAAwB,EAAE,QAAqB;IAC/D,OAAO,QAAQ,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,EAAE,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC;AACxE,CAAC","sourcesContent":["import { prepareAnswers, applyAnswers } from \"./input.ts\";\nimport { OutpostError } from \"../errors.ts\";\nimport { quotaResumes, validateQuotaPolicy } from \"./quota-pause.ts\";\nimport { maxTimerMs } from \"./retry.constants.ts\";\nimport { applyDecisions, pauseGate, prepareDecisions } from \"./gates.ts\";\nimport { openCheckpoint } from \"./checkpoint.ts\";\nimport type { WorkflowCheckpointSession } from \"./checkpoint.types.ts\";\nimport type {\n Task,\n WorkflowOptions,\n WorkflowResult,\n} from \"../workflow.types.ts\";\nimport { WorkflowFailure } from \"./failure.ts\";\nimport { runTask } from \"./task-runner.ts\";\nimport { positive } from \"./validation.ts\";\nimport { workflowState } from \"./workflow-state.ts\";\n\nexport async function schedule(\n name: string,\n tasks: readonly Task[],\n options: WorkflowOptions,\n): Promise<WorkflowResult> {\n if (\n !options.checkpoint &&\n (tasks.some((item) => item.interaction) || options.answers?.length)\n )\n throw new Error(\"Workflow interactions and answers require a checkpoint\");\n if (options.answers && !options.answers.length)\n throw new Error(\"Workflow answers cannot be empty\");\n if (options.onQuota) {\n if (!options.checkpoint)\n throw new Error(\"Workflow quota pauses require a checkpoint\");\n validateQuotaPolicy(options.onQuota);\n }\n if (\n !options.checkpoint &&\n (tasks.some((item) => item.gate) || options.decisions?.length)\n )\n throw new Error(\"Workflow gates and decisions require a checkpoint\");\n if (options.decisions && !options.decisions.length)\n throw new Error(\"Workflow decisions cannot be empty\");\n if (options.timeoutMs !== undefined) {\n positive(options.timeoutMs, \"Workflow timeoutMs\");\n if (options.timeoutMs > maxTimerMs)\n throw new Error(\"Workflow timeoutMs exceeds the supported timer range\");\n }\n const deadline = new AbortController();\n const timer =\n options.timeoutMs === undefined\n ? undefined\n : setTimeout(\n () =>\n deadline.abort(\n new OutpostError(\"timeout\", `Workflow ${name} timed out`, {\n timeoutMs: options.timeoutMs,\n }),\n ),\n options.timeoutMs,\n );\n const signal = options.signal\n ? AbortSignal.any([options.signal, deadline.signal])\n : deadline.signal;\n let checkpoint: WorkflowCheckpointSession | undefined;\n try {\n checkpoint = options.checkpoint\n ? await openCheckpoint(name, tasks, options.checkpoint)\n : undefined;\n return await scheduleRun(\n name,\n tasks,\n { ...options, signal },\n checkpoint,\n deadline.signal,\n );\n } finally {\n clearTimeout(timer);\n await checkpoint?.release();\n }\n}\n\nasync function scheduleRun(\n name: string,\n tasks: readonly Task[],\n options: WorkflowOptions,\n checkpoint: WorkflowCheckpointSession | undefined,\n deadline: AbortSignal,\n): Promise<WorkflowResult> {\n const concurrency = options.concurrency ?? 1;\n positive(concurrency, \"concurrency\");\n const state = workflowState(name, tasks, options, checkpoint);\n try {\n const {\n executionId,\n signal,\n values,\n records,\n errors,\n observerErrors,\n record,\n emit,\n finish,\n } = state;\n const active = new Map<Task, Promise<void>>();\n const started = Date.now();\n const answers = prepareAnswers(state);\n const decisions = await prepareDecisions(state);\n emit({ type: \"start\" });\n if (checkpoint?.initial) emit({ type: \"resume\" });\n if (!signal.aborted) {\n applyDecisions(state, decisions);\n applyAnswers(state, answers);\n }\n await state.persist();\n const resumes = quotaResumes(state);\n try {\n while (true) {\n let changed = false;\n for (const item of tasks) {\n const resumed = resumes.has(item);\n if (record(item).status !== \"waiting\" && !resumed) continue;\n if (signal.aborted || state.accounting.exhausted) {\n if (resumes.delete(item)) continue;\n finish(item, \"cancelled\");\n changed = true;\n continue;\n }\n const dependencies = item.after.map(\n (dependency) => record(dependency).status,\n );\n if (\n dependencies.some((status) =>\n [\"failed\", \"skipped\", \"cancelled\", \"rejected\"].includes(status),\n )\n ) {\n finish(item, \"skipped\");\n changed = true;\n continue;\n }\n if (\n active.size >= concurrency ||\n item.after.some((dependency) => active.has(dependency)) ||\n !dependencies.every((status) => status === \"done\")\n )\n continue;\n resumes.delete(item);\n const running = (\n item.gate ? pauseGate(item, state) : runTask(item, state)\n ).finally(() => {\n active.delete(item);\n });\n active.set(item, running);\n changed = true;\n }\n if (active.size) {\n await Promise.race(active.values());\n continue;\n }\n if (!changed) break;\n }\n } catch (error) {\n state.stop.abort(error);\n await Promise.allSettled(active.values());\n throw error;\n }\n await state.persist();\n if (options.signal?.aborted) errors.push(options.signal.reason);\n const paused = [...records.values()].some(\n (entry) => entry.status === \"paused\",\n );\n let status: WorkflowResult[\"status\"] = \"done\";\n if (paused) status = \"paused\";\n if ([...records.values()].some((entry) => entry.status === \"waiting-input\"))\n status = \"waiting-input\";\n if (errors.length) status = \"failed\";\n if (options.signal?.aborted)\n status = timedOut(options, deadline) ? \"failed\" : \"cancelled\";\n emit({ type: \"finish\", status, durationMs: Date.now() - started });\n await state.observation.close();\n observerErrors.push(...state.observation.errors);\n const result: WorkflowResult = Object.freeze({\n executionId,\n name,\n inputRequests: Object.freeze(\n [...records.values()].flatMap((record) =>\n record.status === \"waiting-input\" && record.interaction?.request\n ? [record.interaction.request]\n : [],\n ),\n ),\n status,\n usage: state.accounting.snapshot(),\n tasks: Object.freeze(\n [...records.values()].map((value) => Object.freeze({ ...value })),\n ),\n errors: Object.freeze(errors),\n observerErrors: Object.freeze(observerErrors),\n value<T>(item: Task<T>): T {\n if (!values.has(item))\n throw new Error(\n `${item.key} has no successful value in this execution`,\n );\n return values.get(item) as T;\n },\n unwrap() {\n if (status !== \"done\") throw new WorkflowFailure(result);\n },\n });\n return result;\n } catch (error) {\n state.emit({\n type: \"finish\",\n status:\n options.signal?.aborted && !timedOut(options, deadline)\n ? \"cancelled\"\n : \"failed\",\n });\n await state.observation.close();\n throw error;\n }\n}\n\nfunction timedOut(options: WorkflowOptions, deadline: AbortSignal): boolean {\n return deadline.aborted && options.signal?.reason === deadline.reason;\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { interactionContext, immutableInput } from "./input.js";
|
|
1
2
|
import { taskIdempotencyKey } from "./idempotency.js";
|
|
2
3
|
import { createObservationHub } from "../observation.js";
|
|
3
4
|
import { maxUsageReceiptsPerTask } from "./usage-receipt.constants.js";
|
|
@@ -26,6 +27,7 @@ export function workflowState(name, tasks, options, checkpoint) {
|
|
|
26
27
|
: stop.signal;
|
|
27
28
|
const values = new Map();
|
|
28
29
|
const activeAttempts = new Map();
|
|
30
|
+
const quotaResumes = new Map();
|
|
29
31
|
const records = new Map(tasks.map((item) => [
|
|
30
32
|
item,
|
|
31
33
|
{ key: item.key, status: "waiting", attempts: 0 },
|
|
@@ -33,13 +35,16 @@ export function workflowState(name, tasks, options, checkpoint) {
|
|
|
33
35
|
const saved = checkpoint?.initial;
|
|
34
36
|
if (saved) {
|
|
35
37
|
const complete = saved.records.every((entry) => ["done", "skipped"].includes(entry.status));
|
|
36
|
-
const settledPause = saved.records.some((entry) => ["paused", "rejected"].includes(entry.status)) &&
|
|
37
|
-
saved.records.every((entry) => ["done", "skipped", "paused", "rejected"].includes(entry.status) ||
|
|
38
|
+
const settledPause = saved.records.some((entry) => ["paused", "rejected", "waiting-input"].includes(entry.status)) &&
|
|
39
|
+
saved.records.every((entry) => ["done", "skipped", "paused", "rejected", "waiting-input"].includes(entry.status) ||
|
|
38
40
|
(entry.status === "waiting" && entry.attempts === 0));
|
|
39
41
|
for (const item of tasks) {
|
|
40
42
|
const entry = saved.records.find((entry) => entry.key === item.key);
|
|
41
43
|
records.set(item, {
|
|
42
44
|
...entry,
|
|
45
|
+
...(entry.interaction
|
|
46
|
+
? { interaction: immutableInput(entry.interaction) }
|
|
47
|
+
: {}),
|
|
43
48
|
...(entry.usageReceipts
|
|
44
49
|
? { usageReceipts: Object.freeze([...entry.usageReceipts]) }
|
|
45
50
|
: {}),
|
|
@@ -54,7 +59,8 @@ export function workflowState(name, tasks, options, checkpoint) {
|
|
|
54
59
|
...(entry.decision
|
|
55
60
|
? { decision: Object.freeze({ ...entry.decision }) }
|
|
56
61
|
: {}),
|
|
57
|
-
|
|
62
|
+
...(entry.quota ? { quota: Object.freeze({ ...entry.quota }) } : {}),
|
|
63
|
+
status: ["done", "paused", "rejected", "waiting-input"].includes(entry.status) ||
|
|
58
64
|
complete ||
|
|
59
65
|
(settledPause && entry.status === "skipped")
|
|
60
66
|
? entry.status
|
|
@@ -147,6 +153,14 @@ export function workflowState(name, tasks, options, checkpoint) {
|
|
|
147
153
|
});
|
|
148
154
|
}
|
|
149
155
|
return {
|
|
156
|
+
...(item.interaction
|
|
157
|
+
? {
|
|
158
|
+
interaction: interactionContext(item, runtime, attempt, taskSignal, () => activeAttempts.get(item) === attempt),
|
|
159
|
+
}
|
|
160
|
+
: {}),
|
|
161
|
+
...(attempt > 0 && quotaResumes.has(item)
|
|
162
|
+
? { quota: quotaResumes.get(item) }
|
|
163
|
+
: {}),
|
|
150
164
|
observation: observation.child({ taskKey: item.key, attempt }),
|
|
151
165
|
signal: taskSignal,
|
|
152
166
|
attempt,
|
|
@@ -168,6 +182,7 @@ export function workflowState(name, tasks, options, checkpoint) {
|
|
|
168
182
|
};
|
|
169
183
|
}
|
|
170
184
|
const runtime = {
|
|
185
|
+
workflow: name,
|
|
171
186
|
observation,
|
|
172
187
|
async persist() {
|
|
173
188
|
await checkpoint?.save(runtime);
|
|
@@ -178,7 +193,9 @@ export function workflowState(name, tasks, options, checkpoint) {
|
|
|
178
193
|
accounting,
|
|
179
194
|
closeAttempt(item) {
|
|
180
195
|
activeAttempts.delete(item);
|
|
196
|
+
quotaResumes.delete(item);
|
|
181
197
|
},
|
|
198
|
+
quotaResumes,
|
|
182
199
|
stop,
|
|
183
200
|
signal,
|
|
184
201
|
values,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-state.js","sourceRoot":"","sources":["../../../src/domain/workflow/workflow-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAWzC,MAAM,UAAU,aAAa,CAC3B,IAAY,EACZ,KAAsB,EACtB,OAAwB,EACxB,UAAsC;IAEtC,MAAM,WAAW,GAAG,UAAU,EAAE,OAAO,EAAE,WAAW,IAAI,UAAU,EAAE,CAAC;IACrE,MAAM,WAAW,GAAG,CAAC,OAAO,CAAC,WAAW,IAAI,oBAAoB,EAAE,CAAC,CAAC,KAAK,CACvE,EAAE,WAAW,EAAE,EACf;QACE;YACE,OAAO,CAAC,KAAK;gBACX,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,KAAK,UAAU;oBACjC,OAAO,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACzD,CAAC;SACF;QACD;YACE,OAAO,CAAC,KAAK;gBACX,IAAI,KAAK,CAAC,KAAK,CAAC,IAAI,KAAK,UAAU;oBACjC,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAChD,CAAC;SACF;KACF,CACF,CAAC;IACF,MAAM,IAAI,GAAG,IAAI,eAAe,EAAE,CAAC;IACnC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM;QAC3B,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,OA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EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;YACnC,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC;YACrC,eAAe,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;gBAClC,oBAAoB,CAAC,OAAO,CAAC,CAAC;gBAC9B,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YACzB,CAAC;YACD,KAAK,CAAI,UAAmB;gBAC1B,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC;oBAClC,MAAM,IAAI,KAAK,CACb,GAAG,IAAI,CAAC,GAAG,2BAA2B,UAAU,CAAC,GAAG,EAAE,CACvD,CAAC;gBACJ,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC;oBACzB,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,CAAC,GAAG,0BAA0B,CAAC,CAAC;gBAC/D,OAAO,MAAM,CAAC,GAAG,CAAC,UAAU,CAAM,CAAC;YACrC,CAAC;SACF,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAA2B;QACtC,WAAW;QACX,KAAK,CAAC,OAAO;YACX,MAAM,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YAChC,IAAI,UAAU;gBAAE,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QAC/C,CAAC;QACD,WAAW;QACX,UAAU;QACV,YAAY,CAAC,IAAI;YACf,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC;QACD,IAAI;QACJ,MAAM;QACN,MAAM;QACN,OAAO;QACP,MAAM;QACN,cAAc;QACd,MAAM;QACN,IAAI;QACJ,MAAM;QACN,OAAO;QACP,OAAO;KACR,CAAC;IACF,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { taskIdempotencyKey } from \"./idempotency.ts\";\nimport { createObservationHub } from \"../observation.ts\";\nimport { maxUsageReceiptsPerTask } from \"./usage-receipt.constants.ts\";\nimport { validateUsageReceipt } from \"./usage-receipt.ts\";\nimport type { Usage } from \"../agent.types.ts\";\nimport type { WorkflowCheckpointSession } from \"./checkpoint.types.ts\";\nimport { workflowAccounting } from \"./budget.ts\";\nimport { randomUUID } from \"node:crypto\";\nimport type {\n Task,\n TaskContext,\n TaskRecord,\n TaskStatus,\n WorkflowEvent,\n WorkflowExecutionState,\n WorkflowOptions,\n} from \"../workflow.types.ts\";\n\nexport function workflowState(\n name: string,\n tasks: readonly Task[],\n options: WorkflowOptions,\n checkpoint?: WorkflowCheckpointSession,\n): WorkflowExecutionState {\n const executionId = checkpoint?.initial?.executionId ?? randomUUID();\n const observation = (options.observation ?? createObservationHub()).child(\n { executionId },\n [\n {\n observe(value) {\n if (value.event.kind === \"workflow\")\n return options.telemetry?.observe(value.event.event);\n },\n },\n {\n observe(value) {\n if (value.event.kind === \"workflow\")\n return options.observe?.(value.event.event);\n },\n },\n ],\n );\n const stop = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([options.signal, stop.signal])\n : stop.signal;\n const values = new Map<Task, unknown>();\n const activeAttempts = new Map<Task, number>();\n const records = new Map<Task, TaskRecord>(\n tasks.map((item) => [\n item,\n { key: item.key, status: \"waiting\", attempts: 0 },\n ]),\n );\n const saved = checkpoint?.initial;\n if (saved) {\n const complete = saved.records.every((entry) =>\n [\"done\", \"skipped\"].includes(entry.status),\n );\n const settledPause =\n saved.records.some((entry) =>\n [\"paused\", \"rejected\"].includes(entry.status),\n ) &&\n saved.records.every(\n (entry) =>\n [\"done\", \"skipped\", \"paused\", \"rejected\"].includes(entry.status) ||\n (entry.status === \"waiting\" && entry.attempts === 0),\n );\n for (const item of tasks) {\n const entry = saved.records.find((entry) => entry.key === item.key)!;\n records.set(item, {\n ...entry,\n ...(entry.usageReceipts\n ? { usageReceipts: Object.freeze([...entry.usageReceipts]) }\n : {}),\n ...(entry.pause\n ? {\n pause: Object.freeze({\n ...entry.pause,\n actors: Object.freeze([...entry.pause.actors]),\n }),\n }\n : {}),\n ...(entry.decision\n ? { decision: Object.freeze({ ...entry.decision }) }\n : {}),\n status:\n [\"done\", \"paused\", \"rejected\"].includes(entry.status) ||\n complete ||\n (settledPause && entry.status === \"skipped\")\n ? entry.status\n : \"waiting\",\n });\n if (entry.status === \"done\") {\n const output = saved.values[item.key]!;\n values.set(item, output.kind === \"json\" ? output.value : undefined);\n }\n }\n }\n const errors: unknown[] = [],\n observerErrors: unknown[] = [];\n for (const entry of records.values())\n if (entry.status === \"rejected\") errors.push(new Error(entry.error));\n const accounting = workflowAccounting(\n options.budget,\n (error) => {\n errors.push(error);\n emit({ type: \"budget-exceeded\" });\n if (error.dimension !== \"attempts\") stop.abort(error);\n },\n saved?.usage,\n );\n const record = (item: Task) => records.get(item)!;\n function emit(\n event: Omit<WorkflowEvent, \"executionId\" | \"workflow\" | \"timestamp\">,\n ): void {\n const notification: WorkflowEvent = {\n ...event,\n executionId,\n workflow: name,\n timestamp: new Date().toISOString(),\n };\n observation\n .child({\n ...(event.key ? { taskKey: event.key } : {}),\n ...(event.attempt === undefined ? {} : { attempt: event.attempt }),\n })\n .emit(\"workflow\", { kind: \"workflow\", event: notification });\n }\n function finish(item: Task, status: TaskStatus): void {\n Object.assign(record(item), {\n status,\n finishedAt: new Date().toISOString(),\n });\n emit({\n type: \"task\",\n key: item.key,\n status,\n attempt: record(item).attempts,\n ...(record(item).startedAt\n ? { durationMs: Date.now() - Date.parse(record(item).startedAt!) }\n : {}),\n });\n }\n function context(\n item: Task,\n attempt: number,\n taskSignal: AbortSignal,\n ): TaskContext {\n if (attempt > 0) activeAttempts.set(item, attempt);\n function report(usage: Usage, receipt?: string): void {\n const current = record(item);\n if (\n attempt === 0 ||\n current.status !== \"active\" ||\n activeAttempts.get(item) !== attempt\n )\n throw new Error(\n \"Usage must be reported during its active task attempt\",\n );\n if (receipt !== undefined) {\n validateUsageReceipt(receipt);\n if (current.usageReceipts?.includes(receipt)) return;\n if ((current.usageReceipts?.length ?? 0) >= maxUsageReceiptsPerTask)\n throw new Error(\"Workflow usage receipt limit exceeded\");\n }\n const previousReceipts = current.usageReceipts;\n if (receipt !== undefined)\n current.usageReceipts = Object.freeze([\n ...(previousReceipts ?? []),\n receipt,\n ]);\n try {\n accounting.report(usage);\n } catch (error) {\n if (previousReceipts) current.usageReceipts = previousReceipts;\n else delete current.usageReceipts;\n throw error;\n }\n void runtime.persist().catch((error: unknown) => stop.abort(error));\n emit({\n type: \"usage\",\n key: item.key,\n attempt,\n usage: Object.freeze({ ...usage }),\n });\n }\n\n return {\n observation: observation.child({ taskKey: item.key, attempt }),\n signal: taskSignal,\n attempt,\n executionId,\n idempotencyKey: taskIdempotencyKey(executionId, item.key),\n checkpoint: () => runtime.persist(),\n reportUsage: (usage) => report(usage),\n reportUsageOnce: (receipt, usage) => {\n validateUsageReceipt(receipt);\n report(usage, receipt);\n },\n value<T>(dependency: Task<T>): T {\n if (!item.after.includes(dependency))\n throw new Error(\n `${item.key}: undeclared dependency ${dependency.key}`,\n );\n if (!values.has(dependency))\n throw new Error(`${dependency.key} has no successful value`);\n return values.get(dependency) as T;\n },\n };\n }\n\n const runtime: WorkflowExecutionState = {\n observation,\n async persist() {\n await checkpoint?.save(runtime);\n if (checkpoint) emit({ type: \"checkpoint\" });\n },\n executionId,\n accounting,\n closeAttempt(item) {\n activeAttempts.delete(item);\n },\n stop,\n signal,\n values,\n records,\n errors,\n observerErrors,\n record,\n emit,\n finish,\n context,\n options,\n };\n return runtime;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workflow-state.js","sourceRoot":"","sources":["../../../src/domain/workflow/workflow-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,O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AG,CAAC,UAAU,CAAM,CAAC;YACrC,CAAC;SACF,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAA2B;QACtC,QAAQ,EAAE,IAAI;QACd,WAAW;QACX,KAAK,CAAC,OAAO;YACX,MAAM,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YAChC,IAAI,UAAU;gBAAE,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QAC/C,CAAC;QACD,WAAW;QACX,UAAU;QACV,YAAY,CAAC,IAAI;YACf,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YAC5B,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC5B,CAAC;QACD,YAAY;QACZ,IAAI;QACJ,MAAM;QACN,MAAM;QACN,OAAO;QACP,MAAM;QACN,cAAc;QACd,MAAM;QACN,IAAI;QACJ,MAAM;QACN,OAAO;QACP,OAAO;KACR,CAAC;IACF,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { interactionContext, immutableInput } from \"./input.ts\";\nimport { taskIdempotencyKey } from \"./idempotency.ts\";\nimport { createObservationHub } from \"../observation.ts\";\nimport { maxUsageReceiptsPerTask } from \"./usage-receipt.constants.ts\";\nimport { validateUsageReceipt } from \"./usage-receipt.ts\";\nimport type { Usage } from \"../agent.types.ts\";\nimport type { WorkflowCheckpointSession } from \"./checkpoint.types.ts\";\nimport type { WorkflowQuotaPause } from \"./quota-pause.types.ts\";\nimport { workflowAccounting } from \"./budget.ts\";\nimport { randomUUID } from \"node:crypto\";\nimport type {\n Task,\n TaskContext,\n TaskRecord,\n TaskStatus,\n WorkflowEvent,\n WorkflowExecutionState,\n WorkflowOptions,\n} from \"../workflow.types.ts\";\n\nexport function workflowState(\n name: string,\n tasks: readonly Task[],\n options: WorkflowOptions,\n checkpoint?: WorkflowCheckpointSession,\n): WorkflowExecutionState {\n const executionId = checkpoint?.initial?.executionId ?? randomUUID();\n const observation = (options.observation ?? createObservationHub()).child(\n { executionId },\n [\n {\n observe(value) {\n if (value.event.kind === \"workflow\")\n return options.telemetry?.observe(value.event.event);\n },\n },\n {\n observe(value) {\n if (value.event.kind === \"workflow\")\n return options.observe?.(value.event.event);\n },\n },\n ],\n );\n const stop = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([options.signal, stop.signal])\n : stop.signal;\n const values = new Map<Task, unknown>();\n const activeAttempts = new Map<Task, number>();\n const quotaResumes = new Map<Task, WorkflowQuotaPause>();\n const records = new Map<Task, TaskRecord>(\n tasks.map((item) => [\n item,\n { key: item.key, status: \"waiting\", attempts: 0 },\n ]),\n );\n const saved = checkpoint?.initial;\n if (saved) {\n const complete = saved.records.every((entry) =>\n [\"done\", \"skipped\"].includes(entry.status),\n );\n const settledPause =\n saved.records.some((entry) =>\n [\"paused\", \"rejected\", \"waiting-input\"].includes(entry.status),\n ) &&\n saved.records.every(\n (entry) =>\n [\"done\", \"skipped\", \"paused\", \"rejected\", \"waiting-input\"].includes(\n entry.status,\n ) ||\n (entry.status === \"waiting\" && entry.attempts === 0),\n );\n for (const item of tasks) {\n const entry = saved.records.find((entry) => entry.key === item.key)!;\n records.set(item, {\n ...entry,\n ...(entry.interaction\n ? { interaction: immutableInput(entry.interaction) }\n : {}),\n ...(entry.usageReceipts\n ? { usageReceipts: Object.freeze([...entry.usageReceipts]) }\n : {}),\n ...(entry.pause\n ? {\n pause: Object.freeze({\n ...entry.pause,\n actors: Object.freeze([...entry.pause.actors]),\n }),\n }\n : {}),\n ...(entry.decision\n ? { decision: Object.freeze({ ...entry.decision }) }\n : {}),\n ...(entry.quota ? { quota: Object.freeze({ ...entry.quota }) } : {}),\n status:\n [\"done\", \"paused\", \"rejected\", \"waiting-input\"].includes(\n entry.status,\n ) ||\n complete ||\n (settledPause && entry.status === \"skipped\")\n ? entry.status\n : \"waiting\",\n });\n if (entry.status === \"done\") {\n const output = saved.values[item.key]!;\n values.set(item, output.kind === \"json\" ? output.value : undefined);\n }\n }\n }\n const errors: unknown[] = [],\n observerErrors: unknown[] = [];\n for (const entry of records.values())\n if (entry.status === \"rejected\") errors.push(new Error(entry.error));\n const accounting = workflowAccounting(\n options.budget,\n (error) => {\n errors.push(error);\n emit({ type: \"budget-exceeded\" });\n if (error.dimension !== \"attempts\") stop.abort(error);\n },\n saved?.usage,\n );\n const record = (item: Task) => records.get(item)!;\n function emit(\n event: Omit<WorkflowEvent, \"executionId\" | \"workflow\" | \"timestamp\">,\n ): void {\n const notification: WorkflowEvent = {\n ...event,\n executionId,\n workflow: name,\n timestamp: new Date().toISOString(),\n };\n observation\n .child({\n ...(event.key ? { taskKey: event.key } : {}),\n ...(event.attempt === undefined ? {} : { attempt: event.attempt }),\n })\n .emit(\"workflow\", { kind: \"workflow\", event: notification });\n }\n function finish(item: Task, status: TaskStatus): void {\n Object.assign(record(item), {\n status,\n finishedAt: new Date().toISOString(),\n });\n emit({\n type: \"task\",\n key: item.key,\n status,\n attempt: record(item).attempts,\n ...(record(item).startedAt\n ? { durationMs: Date.now() - Date.parse(record(item).startedAt!) }\n : {}),\n });\n }\n function context(\n item: Task,\n attempt: number,\n taskSignal: AbortSignal,\n ): TaskContext {\n if (attempt > 0) activeAttempts.set(item, attempt);\n function report(usage: Usage, receipt?: string): void {\n const current = record(item);\n if (\n attempt === 0 ||\n current.status !== \"active\" ||\n activeAttempts.get(item) !== attempt\n )\n throw new Error(\n \"Usage must be reported during its active task attempt\",\n );\n if (receipt !== undefined) {\n validateUsageReceipt(receipt);\n if (current.usageReceipts?.includes(receipt)) return;\n if ((current.usageReceipts?.length ?? 0) >= maxUsageReceiptsPerTask)\n throw new Error(\"Workflow usage receipt limit exceeded\");\n }\n const previousReceipts = current.usageReceipts;\n if (receipt !== undefined)\n current.usageReceipts = Object.freeze([\n ...(previousReceipts ?? []),\n receipt,\n ]);\n try {\n accounting.report(usage);\n } catch (error) {\n if (previousReceipts) current.usageReceipts = previousReceipts;\n else delete current.usageReceipts;\n throw error;\n }\n void runtime.persist().catch((error: unknown) => stop.abort(error));\n emit({\n type: \"usage\",\n key: item.key,\n attempt,\n usage: Object.freeze({ ...usage }),\n });\n }\n\n return {\n ...(item.interaction\n ? {\n interaction: interactionContext(\n item,\n runtime,\n attempt,\n taskSignal,\n () => activeAttempts.get(item) === attempt,\n ),\n }\n : {}),\n ...(attempt > 0 && quotaResumes.has(item)\n ? { quota: quotaResumes.get(item)! }\n : {}),\n observation: observation.child({ taskKey: item.key, attempt }),\n signal: taskSignal,\n attempt,\n executionId,\n idempotencyKey: taskIdempotencyKey(executionId, item.key),\n checkpoint: () => runtime.persist(),\n reportUsage: (usage) => report(usage),\n reportUsageOnce: (receipt, usage) => {\n validateUsageReceipt(receipt);\n report(usage, receipt);\n },\n value<T>(dependency: Task<T>): T {\n if (!item.after.includes(dependency))\n throw new Error(\n `${item.key}: undeclared dependency ${dependency.key}`,\n );\n if (!values.has(dependency))\n throw new Error(`${dependency.key} has no successful value`);\n return values.get(dependency) as T;\n },\n };\n }\n\n const runtime: WorkflowExecutionState = {\n workflow: name,\n observation,\n async persist() {\n await checkpoint?.save(runtime);\n if (checkpoint) emit({ type: \"checkpoint\" });\n },\n executionId,\n accounting,\n closeAttempt(item) {\n activeAttempts.delete(item);\n quotaResumes.delete(item);\n },\n quotaResumes,\n stop,\n signal,\n values,\n records,\n errors,\n observerErrors,\n record,\n emit,\n finish,\n context,\n options,\n };\n return runtime;\n}\n"]}
|