@backendkit-labs/agent-core 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +2 -1
  2. package/dist/flow/adapter.d.ts +20 -0
  3. package/dist/flow/adapter.d.ts.map +1 -0
  4. package/dist/flow/adapter.js +81 -0
  5. package/dist/flow/adapter.js.map +1 -0
  6. package/dist/flow/approval-handler.d.ts +59 -0
  7. package/dist/flow/approval-handler.d.ts.map +1 -0
  8. package/dist/flow/approval-handler.js +79 -0
  9. package/dist/flow/approval-handler.js.map +1 -0
  10. package/dist/flow/approval.d.ts +39 -0
  11. package/dist/flow/approval.d.ts.map +1 -0
  12. package/dist/flow/approval.js +58 -0
  13. package/dist/flow/approval.js.map +1 -0
  14. package/dist/flow/convert.d.ts +44 -0
  15. package/dist/flow/convert.d.ts.map +1 -0
  16. package/dist/flow/convert.js +34 -0
  17. package/dist/flow/convert.js.map +1 -0
  18. package/dist/flow/file-journal.d.ts +34 -0
  19. package/dist/flow/file-journal.d.ts.map +1 -0
  20. package/dist/flow/file-journal.js +176 -0
  21. package/dist/flow/file-journal.js.map +1 -0
  22. package/dist/flow/handler.d.ts +35 -0
  23. package/dist/flow/handler.d.ts.map +1 -0
  24. package/dist/flow/handler.js +51 -0
  25. package/dist/flow/handler.js.map +1 -0
  26. package/dist/flow/host.d.ts +79 -0
  27. package/dist/flow/host.d.ts.map +1 -0
  28. package/dist/flow/host.js +148 -0
  29. package/dist/flow/host.js.map +1 -0
  30. package/dist/flow/index.d.ts +27 -0
  31. package/dist/flow/index.d.ts.map +1 -0
  32. package/dist/flow/index.js +55 -0
  33. package/dist/flow/index.js.map +1 -0
  34. package/dist/flow/interpolate.d.ts +6 -0
  35. package/dist/flow/interpolate.d.ts.map +1 -0
  36. package/dist/flow/interpolate.js +18 -0
  37. package/dist/flow/interpolate.js.map +1 -0
  38. package/dist/flow/journal.d.ts +105 -0
  39. package/dist/flow/journal.d.ts.map +1 -0
  40. package/dist/flow/journal.js +89 -0
  41. package/dist/flow/journal.js.map +1 -0
  42. package/dist/flow/limiter.d.ts +21 -0
  43. package/dist/flow/limiter.d.ts.map +1 -0
  44. package/dist/flow/limiter.js +45 -0
  45. package/dist/flow/limiter.js.map +1 -0
  46. package/dist/flow/loader.d.ts +24 -0
  47. package/dist/flow/loader.d.ts.map +1 -0
  48. package/dist/flow/loader.js +172 -0
  49. package/dist/flow/loader.js.map +1 -0
  50. package/dist/flow/planner.d.ts +50 -0
  51. package/dist/flow/planner.d.ts.map +1 -0
  52. package/dist/flow/planner.js +131 -0
  53. package/dist/flow/planner.js.map +1 -0
  54. package/dist/flow/run.d.ts +106 -0
  55. package/dist/flow/run.d.ts.map +1 -0
  56. package/dist/flow/run.js +354 -0
  57. package/dist/flow/run.js.map +1 -0
  58. package/dist/flow/tools.d.ts +27 -0
  59. package/dist/flow/tools.d.ts.map +1 -0
  60. package/dist/flow/tools.js +71 -0
  61. package/dist/flow/tools.js.map +1 -0
  62. package/dist/flow/types.d.ts +112 -0
  63. package/dist/flow/types.d.ts.map +1 -0
  64. package/dist/flow/types.js +63 -0
  65. package/dist/flow/types.js.map +1 -0
  66. package/dist/index.d.ts +17 -1
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +46 -2
  69. package/dist/index.js.map +1 -1
  70. package/dist/learning/index.d.ts +1 -1
  71. package/dist/learning/index.d.ts.map +1 -1
  72. package/dist/learning/index.js +104 -42
  73. package/dist/learning/index.js.map +1 -1
  74. package/dist/learning/signal.d.ts +32 -14
  75. package/dist/learning/signal.d.ts.map +1 -1
  76. package/dist/learning/signal.js +95 -30
  77. package/dist/learning/signal.js.map +1 -1
  78. package/dist/learning/types.d.ts +60 -0
  79. package/dist/learning/types.d.ts.map +1 -1
  80. package/package.json +6 -1
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PLANNER_SYSTEM = exports.UNRESOLVED_AGENT = void 0;
4
+ exports.planFlow = planFlow;
5
+ const zod_1 = require("zod");
6
+ const generateObject_1 = require("../structured/generateObject");
7
+ const convert_1 = require("./convert");
8
+ /** The marker for a needed capability no agent covers. The step stays in the flow and is reported in `unresolved`. */
9
+ exports.UNRESOLVED_AGENT = 'unresolved';
10
+ exports.PLANNER_SYSTEM = `You are a task decomposition expert.
11
+ Given a task and a list of available specialist agents, produce a JSON execution plan.
12
+
13
+ Rules:
14
+ - Use only agent IDs from the provided list.
15
+ - depends_on: [] means the sub-task can start immediately; ["t1"] waits for t1 to finish.
16
+ - If no agent matches a needed capability, use agent_id="unresolved" and note the gap in the task.
17
+ - Keep each task description focused and self-contained.
18
+ - gate: set to true when a MANDATORY GATES section is present and the step's agent domain matches a governed domain. Always false otherwise.
19
+ - gate_criteria: when gate is true, copy the suggested criteria from the MANDATORY GATES section verbatim and add any task-specific criteria that the human approver should verify.`;
20
+ /** First dependency cycle as a path (a -> b -> a), or undefined. */
21
+ function findCycle(steps) {
22
+ const deps = new Map(steps.map(s => [s.id, s.depends_on]));
23
+ const state = new Map();
24
+ const path = [];
25
+ const visit = (id) => {
26
+ if (state.get(id) === 'done')
27
+ return undefined;
28
+ if (state.get(id) === 'visiting')
29
+ return [...path.slice(path.indexOf(id)), id];
30
+ state.set(id, 'visiting');
31
+ path.push(id);
32
+ for (const dep of deps.get(id) ?? []) {
33
+ const found = visit(dep);
34
+ if (found)
35
+ return found;
36
+ }
37
+ path.pop();
38
+ state.set(id, 'done');
39
+ return undefined;
40
+ };
41
+ for (const s of steps) {
42
+ const found = visit(s.id);
43
+ if (found)
44
+ return found;
45
+ }
46
+ return undefined;
47
+ }
48
+ function planSchema(agentIds) {
49
+ return zod_1.z.object({
50
+ summary: zod_1.z.string().min(1).describe('one-line description of the overall plan'),
51
+ subtasks: zod_1.z.array(zod_1.z.object({
52
+ id: zod_1.z.string().min(1),
53
+ agent_id: zod_1.z.string().min(1).describe('id from the list of available agents, or "unresolved"'),
54
+ task: zod_1.z.string().min(1).describe('specific, actionable instruction for this specialist'),
55
+ depends_on: zod_1.z.array(zod_1.z.string()).default([]),
56
+ gate: zod_1.z.boolean().optional(),
57
+ gate_criteria: zod_1.z.array(zod_1.z.string()).optional(),
58
+ })).min(1),
59
+ }).superRefine((plan, ctx) => {
60
+ const ids = new Set();
61
+ for (const st of plan.subtasks) {
62
+ if (ids.has(st.id))
63
+ ctx.addIssue({ code: 'custom', message: `duplicate sub-task id: ${st.id}` });
64
+ ids.add(st.id);
65
+ }
66
+ for (const st of plan.subtasks) {
67
+ for (const dep of st.depends_on) {
68
+ if (!ids.has(dep))
69
+ ctx.addIssue({ code: 'custom', message: `sub-task ${st.id} depends on unknown id: ${dep}` });
70
+ }
71
+ if (st.agent_id !== exports.UNRESOLVED_AGENT && !agentIds.has(st.agent_id)) {
72
+ ctx.addIssue({ code: 'custom', message: `sub-task ${st.id} uses unknown agent_id: ${st.agent_id}` });
73
+ }
74
+ }
75
+ const cycle = findCycle(plan.subtasks);
76
+ if (cycle)
77
+ ctx.addIssue({ code: 'custom', message: `dependency cycle: ${cycle.join(' -> ')}` });
78
+ });
79
+ }
80
+ async function planFlow(task, opts) {
81
+ if (!opts.provider && !opts.chat)
82
+ throw new Error('planFlow needs a provider or a chat function');
83
+ if (opts.agents.length === 0)
84
+ throw new Error('planFlow needs at least one agent');
85
+ const agentList = opts.agents.map(a => {
86
+ const lines = [`- id: ${a.id}`];
87
+ if (a.name)
88
+ lines.push(` name: ${a.name}`);
89
+ if (a.description)
90
+ lines.push(` description: ${a.description}`);
91
+ if (a.capabilities?.length)
92
+ lines.push(` capabilities: [${a.capabilities.join(', ')}]`);
93
+ if (a.domain)
94
+ lines.push(` domain: ${a.domain}`);
95
+ return lines.join('\n');
96
+ }).join('\n');
97
+ const prompt = [
98
+ `Task: ${task}`,
99
+ opts.context ? `\nKnowledge base context (use to inform the plan):\n${opts.context}\n` : '',
100
+ opts.policyContext ? `\n${opts.policyContext}\n` : '',
101
+ 'Available agents:',
102
+ agentList,
103
+ '',
104
+ 'Produce the execution plan.',
105
+ ].filter(Boolean).join('\n');
106
+ const schema = planSchema(new Set(opts.agents.map(a => a.id)));
107
+ const genOpts = {
108
+ system: exports.PLANNER_SYSTEM, name: 'plan', retries: opts.retries ?? 1,
109
+ ...(opts.signal ? { signal: opts.signal } : {}), ...(opts.onMetrics ? { onMetrics: opts.onMetrics } : {}),
110
+ };
111
+ const plan = opts.chat
112
+ ? await (0, generateObject_1.generateObjectWith)(opts.chat, prompt, schema, genOpts)
113
+ : await (0, generateObject_1.generateObject)(opts.provider, prompt, schema, genOpts);
114
+ // An agent configured as gated gets its gate whatever the model said (as the executor did: `subtask.gate ?? agent.gate`).
115
+ const byId = new Map(opts.agents.map(a => [a.id, a]));
116
+ const subtasks = plan.subtasks.map(st => {
117
+ const agent = byId.get(st.agent_id);
118
+ const gated = st.gate === true || agent?.gate === true;
119
+ return {
120
+ ...st,
121
+ gate: gated,
122
+ gate_criteria: gated ? [...(agent?.gateCriteria ?? []), ...(st.gate_criteria ?? [])] : [],
123
+ };
124
+ });
125
+ return {
126
+ flow: (0, convert_1.flowFromTaskPlan)({ summary: plan.summary, subtasks }, opts.flow ? { flow: opts.flow } : {}),
127
+ summary: plan.summary,
128
+ unresolved: subtasks.filter(s => s.agent_id === exports.UNRESOLVED_AGENT).map(s => s.id),
129
+ };
130
+ }
131
+ //# sourceMappingURL=planner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"planner.js","sourceRoot":"","sources":["../../src/flow/planner.ts"],"names":[],"mappings":";;;AA2HA,4BAiDC;AA5KD,6BAAwB;AACxB,iEAAkF;AAGlF,uCAA6C;AA0B7C,sHAAsH;AACzG,QAAA,gBAAgB,GAAG,YAAY,CAAC;AA0BhC,QAAA,cAAc,GAAG;;;;;;;;;oLASsJ,CAAC;AAErL,oEAAoE;AACpE,SAAS,SAAS,CAAC,KAAkD;IACjE,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,KA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IACN,CAAC,CAAC,CAAC;IAEH,OAAO;QACH,IAAI,EAAE,IAAA,0BAAgB,EAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACjG,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,wBAAgB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACnF,CAAC;AACN,CAAC"}
@@ -0,0 +1,106 @@
1
+ import type { Transport } from '../transport/Transport';
2
+ import type { FlowDefinition, FlowStep, FlowTransition } from './types';
3
+ import type { ConcurrencyLimiter } from './limiter';
4
+ import type { FlowApprovals } from './approval';
5
+ import type { RunJournal } from './journal';
6
+ /**
7
+ * The flow engine (SPEC-0023 F2): runs a `FlowDefinition` in waves (steps whose `after` are done run together, up to
8
+ * `maxConcurrency`), skips what depends on a failure, then runs the compensations. How a step is executed is not its
9
+ * concern: that is the `StepExecutor` (one agent, a remote worker, a queue).
10
+ */
11
+ export interface StepOutput {
12
+ content: string;
13
+ costUsd?: number;
14
+ }
15
+ export interface StepInput {
16
+ prompt: string;
17
+ /** Outputs of the steps this one waits for, as `[id]:\n<output>` blocks. */
18
+ context?: string;
19
+ /** `runId:stepId:attempt`: a step with an external effect uses it to be safe when run again (at-least-once). */
20
+ idempotencyKey: string;
21
+ signal: AbortSignal;
22
+ }
23
+ export interface StepExecutor {
24
+ run(step: FlowStep, input: StepInput): Promise<StepOutput>;
25
+ }
26
+ /** `awaiting_approval`: a step waits for a person; resolve the approval and run again with the same `runId` to continue. */
27
+ export type FlowRunStatus = 'completed' | 'failed' | 'rejected' | 'cancelled' | 'awaiting_approval';
28
+ export interface FlowStepResult {
29
+ stepId: string;
30
+ agentId: string;
31
+ content: string;
32
+ status: 'completed' | 'failed' | 'skipped' | 'rejected';
33
+ error?: string;
34
+ costUsd?: number;
35
+ }
36
+ export interface FlowCompensationResult {
37
+ on: string;
38
+ agent: string;
39
+ status: 'completed' | 'failed';
40
+ content?: string;
41
+ error?: string;
42
+ }
43
+ export interface FlowResult {
44
+ runId: string;
45
+ flow: string;
46
+ version: number;
47
+ status: FlowRunStatus;
48
+ steps: Record<string, FlowStepResult>;
49
+ transitions: FlowTransition[];
50
+ compensations: FlowCompensationResult[];
51
+ }
52
+ export interface GateContext {
53
+ runId: string;
54
+ flow: string;
55
+ /** Appends to the transition log (`gate_passed`, `gate_failed`...). */
56
+ record(event: FlowTransition['event'], detail?: string): void;
57
+ }
58
+ export interface RunFlowOptions {
59
+ executor: StepExecutor;
60
+ /** Trigger payload, interpolated into prompts as `{{payload.x}}`. */
61
+ payload?: unknown;
62
+ runId?: string;
63
+ /** Most steps of one wave at the same time. Default 8. */
64
+ maxConcurrency?: number;
65
+ /** Caps per `step.agent` (and per `tenantId`, if given) across every flow that shares the limiter. */
66
+ limiter?: ConcurrencyLimiter;
67
+ tenantId?: string;
68
+ /** Abort to stop: running steps get the signal, steps not started are not started, the result is `cancelled`. */
69
+ signal?: AbortSignal;
70
+ /** Awaited before each step starts: a supervisor holds it while the flow is paused (`FlowControl.checkpoint`). */
71
+ checkpoint?: () => Promise<void>;
72
+ /** Transport for `workflow_*` events, as `WorkflowRunner` emits. */
73
+ transport?: Transport;
74
+ /** Approval through the `ApprovalStore` (F5); replaces `approve`. A step can stop the run as `awaiting_approval`. */
75
+ approvals?: FlowApprovals;
76
+ /** Asks a person for a step with `gate.approval: human`. Default: approve. False rejects the step and what depends on it. */
77
+ approve?: (step: FlowStep, previousOutputs: Record<string, string>) => Promise<boolean>;
78
+ /** After a step succeeds and has a `gate`: throw to fail the step (a gate is never skipped silently). */
79
+ gate?: (step: FlowStep, output: string, ctx: GateContext) => Promise<void>;
80
+ onTransition?: (t: FlowTransition) => void;
81
+ /** What a failed step means for the steps that wait for it: `skip` (default) skips them; `continue` runs them without its output. The run still ends `failed`. */
82
+ onStepFailure?: 'skip' | 'continue';
83
+ /** Deadline for every step that has no `timeoutMs` of its own. A step that exceeds it fails (and its signal aborts) without holding up the others. Default: none. */
84
+ stepTimeoutMs?: number;
85
+ /**
86
+ * Durable state (SPEC-0023 F3). With a journal the run is claimed (one process per run), each step is written before and
87
+ * after it runs, and a `runId` that already has a record is RESUMED: steps that are `done` are not run again and their
88
+ * output feeds the next ones. The payload is not stored: pass it again when resuming.
89
+ */
90
+ journal?: RunJournal;
91
+ /** Who holds the claim. Default: a random id per call. */
92
+ owner?: string;
93
+ /** How long the claim lasts without being renewed. Default 10 minutes. */
94
+ claimTtlMs?: number;
95
+ /** A step the journal shows as `running` (the process died in it): run it again (default, at least once; the idempotency key carries the attempt) or fail it. */
96
+ onInterrupted?: 'retry' | 'fail';
97
+ /** Applied to the input preview and error texts written to the journal. Outputs are stored as they are. */
98
+ redact?: (text: string) => string;
99
+ }
100
+ /** Another process holds the claim of the run. */
101
+ export declare class FlowClaimError extends Error {
102
+ readonly runId: string;
103
+ constructor(runId: string);
104
+ }
105
+ export declare function runFlow(def: FlowDefinition, opts: RunFlowOptions): Promise<FlowResult>;
106
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/flow/run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAGpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,KAAK,EAAE,UAAU,EAAc,MAAM,W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aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,OAAO,CAAC,EAAE,UAAU,CAAC;IACrB,0DAA0D;IAC1D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iKAAiK;IACjK,aAAa,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IACjC,2GAA2G;IAC3G,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;CACrC;AAED,kDAAkD;AAClD,qBAAa,cAAe,SAAQ,KAAK;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM;gBAAb,KAAK,EAAE,MAAM;CACrC;AAOD,wBAAsB,OAAO,CAAC,GAAG,EAAE,cAAc,EAAE,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,UAAU,CAAC,CAsB5F"}
@@ -0,0 +1,354 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FlowClaimError = void 0;
4
+ exports.runFlow = runFlow;
5
+ const interpolate_1 = require("./interpolate");
6
+ const approval_1 = require("./approval");
7
+ /** Another process holds the claim of the run. */
8
+ class FlowClaimError extends Error {
9
+ runId;
10
+ constructor(runId) {
11
+ super(`run "${runId}" is held by another owner`);
12
+ this.runId = runId;
13
+ this.name = 'FlowClaimError';
14
+ }
15
+ }
16
+ exports.FlowClaimError = FlowClaimError;
17
+ const DEFAULT_MAX_CONCURRENCY = 8;
18
+ const DEFAULT_CLAIM_TTL_MS = 10 * 60_000;
19
+ const PREVIEW_CHARS = 200;
20
+ async function runFlow(def, opts) {
21
+ const runId = opts.runId ?? `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
22
+ const journal = opts.journal;
23
+ if (!journal)
24
+ return execute(def, opts, runId, undefined);
25
+ const release = await journal.claim(runId, opts.owner ?? `owner-${Math.random().toString(36).slice(2, 10)}`, opts.claimTtlMs ?? DEFAULT_CLAIM_TTL_MS);
26
+ if (!release)
27
+ throw new FlowClaimError(runId);
28
+ try {
29
+ const prior = await journal.get(runId);
30
+ if (prior && prior.flow !== def.flow)
31
+ throw new Error(`run "${runId}" belongs to flow "${prior.flow}", not "${def.flow}"`);
32
+ if (prior && (prior.status === 'done' || prior.status === 'cancelled'))
33
+ return fromJournal(prior, def);
34
+ if (!prior) {
35
+ const raw = opts.payload === undefined ? '' : (typeof opts.payload === 'string' ? opts.payload : JSON.stringify(opts.payload));
36
+ const cut = raw.length > PREVIEW_CHARS ? `${raw.slice(0, PREVIEW_CHARS)}…` : raw;
37
+ await journal.begin({ runId, flow: def.flow, inputPreview: opts.redact ? opts.redact(cut) : cut, ...(opts.tenantId ? { tenantId: opts.tenantId } : {}) });
38
+ }
39
+ else {
40
+ await journal.update(runId, { status: 'running' });
41
+ }
42
+ return await execute(def, opts, runId, prior);
43
+ }
44
+ finally {
45
+ await release().catch(() => undefined);
46
+ }
47
+ }
48
+ /** A run that already finished, as the result `runFlow` would have returned. */
49
+ function fromJournal(run, def) {
50
+ const steps = {};
51
+ for (const s of def.steps) {
52
+ const j = run.steps[s.id];
53
+ if (!j)
54
+ continue;
55
+ steps[s.id] = {
56
+ stepId: s.id, agentId: s.agent, content: j.output ?? '',
57
+ status: j.status === 'done' ? 'completed' : j.status === 'skipped' ? 'skipped' : 'failed',
58
+ ...(j.error !== undefined ? { error: j.error } : {}),
59
+ ...(j.costUsd !== undefined ? { costUsd: j.costUsd } : {}),
60
+ };
61
+ }
62
+ return {
63
+ runId: run.runId, flow: run.flow, version: def.version,
64
+ status: run.status === 'done' ? 'completed' : run.status === 'cancelled' ? 'cancelled' : 'failed',
65
+ steps, transitions: run.transitions, compensations: [],
66
+ };
67
+ }
68
+ async function execute(def, opts, runId, prior) {
69
+ const journal = opts.journal;
70
+ const redact = (s) => (opts.redact ? opts.redact(s) : s);
71
+ const transitions = [];
72
+ let pending = [];
73
+ /** Transitions not yet written travel with the next journal write. */
74
+ const flush = () => { const p = pending; pending = []; return p.length ? p : undefined; };
75
+ const record = (stepId, event, detail) => {
76
+ const t = { at: new Date().toISOString(), stepId, event, ...(detail !== undefined ? { detail } : {}) };
77
+ transitions.push(t);
78
+ pending.push(t);
79
+ opts.onTransition?.(t);
80
+ };
81
+ const controller = new AbortController();
82
+ const onAbort = () => controller.abort();
83
+ if (opts.signal?.aborted)
84
+ controller.abort();
85
+ else
86
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
87
+ const results = {};
88
+ const completed = new Set();
89
+ const failed = new Set();
90
+ const remaining = new Set(def.steps.map(s => s.id));
91
+ /** Steps that stopped for approval: the run is suspended, not failed. */
92
+ const awaiting = new Map();
93
+ // Resume: what the journal shows as done is not run again; its output feeds the steps that follow.
94
+ if (prior) {
95
+ for (const s of def.steps) {
96
+ const j = prior.steps[s.id];
97
+ if (j?.status === 'done') {
98
+ results[s.id] = {
99
+ stepId: s.id, agentId: s.agent, content: j.output ?? '', status: 'completed',
100
+ ...(j.costUsd !== undefined ? { costUsd: j.costUsd } : {}),
101
+ };
102
+ completed.add(s.id);
103
+ remaining.delete(s.id);
104
+ }
105
+ else if (j?.status === 'running' && opts.onInterrupted === 'fail') {
106
+ const error = 'interrupted: the process stopped while this step was running';
107
+ results[s.id] = { stepId: s.id, agentId: s.agent, content: '', status: 'failed', error };
108
+ failed.add(s.id);
109
+ remaining.delete(s.id);
110
+ record(s.id, 'failed', error);
111
+ await journal?.step(runId, s.id, { status: 'interrupted', error, transitions: flush() });
112
+ }
113
+ }
114
+ }
115
+ opts.transport?.emit({ type: 'workflow_start', name: def.flow });
116
+ const approvalsWhen = opts.approvals?.when ?? 'before';
117
+ /**
118
+ * Asks for approval of a step through the `ApprovalStore`. Returns true to go on. On false the step has been settled here
119
+ * (rejected, denied) or left waiting (`awaiting_approval`, with `output` kept in the journal when the review is after the step).
120
+ */
121
+ const settleApproval = async (step, prev, output) => {
122
+ let verdict;
123
+ try {
124
+ verdict = await (0, approval_1.decideStepApproval)(opts.approvals, def.flow, runId, step, prev, output);
125
+ }
126
+ catch (err) {
127
+ verdict = { kind: 'denied', reason: err instanceof Error ? err.message : String(err) };
128
+ }
129
+ if (verdict.kind === 'proceed')
130
+ return true;
131
+ if (verdict.kind === 'pending') {
132
+ opts.transport?.emit({ type: 'workflow_approval_required', step: step.id });
133
+ record(step.id, 'approval_requested', verdict.approvalId);
134
+ awaiting.set(step.id, verdict.approvalId);
135
+ await journal?.step(runId, step.id, {
136
+ status: 'awaiting_approval', ...(output !== undefined ? { output } : {}), transitions: flush(),
137
+ }).catch(() => undefined);
138
+ return false;
139
+ }
140
+ const rejected = verdict.kind === 'rejected';
141
+ record(step.id, rejected ? 'rejected' : 'failed', verdict.reason);
142
+ await journal?.step(runId, step.id, { status: 'failed', error: redact(verdict.reason), transitions: flush() }).catch(() => undefined);
143
+ results[step.id] = {
144
+ stepId: step.id, agentId: step.agent, content: '', status: rejected ? 'rejected' : 'failed',
145
+ ...(rejected ? {} : { error: verdict.reason }),
146
+ };
147
+ failed.add(step.id);
148
+ return false;
149
+ };
150
+ const executeOne = async (step) => {
151
+ const prev = {};
152
+ for (const dep of step.after)
153
+ if (results[dep]?.status === 'completed')
154
+ prev[dep] = results[dep].content;
155
+ if (opts.approvals) {
156
+ if (approvalsWhen === 'before' && !(await settleApproval(step, prev)))
157
+ return;
158
+ }
159
+ else if (step.gate?.approval === 'human') {
160
+ opts.transport?.emit({ type: 'workflow_approval_required', step: step.id });
161
+ record(step.id, 'approval_requested');
162
+ const ok = await (opts.approve?.(step, prev) ?? Promise.resolve(true));
163
+ if (!ok) {
164
+ record(step.id, 'rejected');
165
+ await journal?.step(runId, step.id, { status: 'failed', error: 'rejected', transitions: flush() }).catch(() => undefined);
166
+ results[step.id] = { stepId: step.id, agentId: step.agent, content: '', status: 'rejected' };
167
+ failed.add(step.id);
168
+ return;
169
+ }
170
+ }
171
+ // A step whose output was already produced and is only waiting for its review is not run again.
172
+ const reviewed = opts.approvals && approvalsWhen === 'after' && prior?.steps[step.id]?.status === 'awaiting_approval'
173
+ ? prior.steps[step.id].output : undefined;
174
+ let attempt = prior?.steps[step.id]?.attempt ?? 0;
175
+ const releases = [];
176
+ let timer;
177
+ let unlink;
178
+ try {
179
+ await opts.checkpoint?.();
180
+ if (controller.signal.aborted)
181
+ return; // not started: left out of the results, the run is cancelled
182
+ let out;
183
+ if (reviewed !== undefined) {
184
+ out = { content: reviewed };
185
+ }
186
+ else {
187
+ if (opts.limiter) {
188
+ releases.push(await opts.limiter.acquire(step.agent, controller.signal));
189
+ if (opts.tenantId)
190
+ releases.push(await opts.limiter.acquire(`tenant:${opts.tenantId}`, controller.signal));
191
+ }
192
+ opts.transport?.emit({ type: 'workflow_step_start', step: step.id, agent: step.agent });
193
+ record(step.id, 'started');
194
+ attempt += 1;
195
+ // Written BEFORE the step runs; if the journal cannot write, the step does not run (fails closed).
196
+ await journal?.step(runId, step.id, { status: 'running', attempt, transitions: flush() });
197
+ const context = Object.keys(prev).length > 0
198
+ ? Object.entries(prev).map(([id, o]) => `[${id}]:\n${o}`).join('\n\n')
199
+ : undefined;
200
+ // The step's own signal: aborted by the run or by the step's deadline, so a timeout stops only this step.
201
+ const stepCtl = new AbortController();
202
+ const link = () => stepCtl.abort();
203
+ controller.signal.addEventListener('abort', link, { once: true });
204
+ unlink = () => controller.signal.removeEventListener('abort', link);
205
+ const pendingRun = opts.executor.run(step, {
206
+ prompt: (0, interpolate_1.interpolate)(step.prompt, opts.payload),
207
+ context,
208
+ idempotencyKey: `${runId}:${step.id}:${attempt}`,
209
+ signal: stepCtl.signal,
210
+ });
211
+ const limitMs = step.timeoutMs ?? opts.stepTimeoutMs;
212
+ if (limitMs === undefined) {
213
+ out = await pendingRun;
214
+ }
215
+ else {
216
+ pendingRun.catch(() => undefined); // a late rejection after the deadline is already accounted for
217
+ const deadline = new Promise((_, reject) => {
218
+ timer = setTimeout(() => { stepCtl.abort(); reject(new Error(`timed out after ${limitMs}ms`)); }, limitMs);
219
+ });
220
+ out = await Promise.race([pendingRun, deadline]);
221
+ }
222
+ if (step.gate && opts.gate) {
223
+ await opts.gate(step, out.content, { runId, flow: def.flow, record: (e, d) => record(step.id, e, d) });
224
+ }
225
+ if (opts.approvals && approvalsWhen === 'after') {
226
+ // The output is produced and kept; the review decides whether the steps that follow may use it.
227
+ await journal?.step(runId, step.id, { status: 'running', attempt, output: out.content });
228
+ }
229
+ }
230
+ if (opts.approvals && approvalsWhen === 'after' && !(await settleApproval(step, prev, out.content)))
231
+ return;
232
+ record(step.id, 'completed');
233
+ await journal?.step(runId, step.id, {
234
+ status: 'done', output: out.content, attempt,
235
+ ...(out.costUsd !== undefined ? { costUsd: out.costUsd } : {}), transitions: flush(),
236
+ });
237
+ results[step.id] = {
238
+ stepId: step.id, agentId: step.agent, content: out.content, status: 'completed',
239
+ ...(out.costUsd !== undefined ? { costUsd: out.costUsd } : {}),
240
+ };
241
+ completed.add(step.id);
242
+ opts.transport?.emit({ type: 'workflow_step_complete', step: step.id, success: true });
243
+ }
244
+ catch (err) {
245
+ // Cancelled while running or waiting for a slot: the step did not fail, the run was stopped.
246
+ if (controller.signal.aborted)
247
+ return;
248
+ const error = err instanceof Error ? err.message : String(err);
249
+ results[step.id] = { stepId: step.id, agentId: step.agent, content: '', status: 'failed', error };
250
+ // `continue`: the steps that follow still run (they get no output from this one).
251
+ if (opts.onStepFailure === 'continue')
252
+ completed.add(step.id);
253
+ else
254
+ failed.add(step.id);
255
+ record(step.id, 'failed', error);
256
+ await journal?.step(runId, step.id, { status: 'failed', error: redact(error), transitions: flush() }).catch(() => undefined);
257
+ opts.transport?.emit({ type: 'workflow_step_complete', step: step.id, success: false });
258
+ }
259
+ finally {
260
+ if (timer)
261
+ clearTimeout(timer);
262
+ unlink?.();
263
+ for (const r of releases.reverse())
264
+ r();
265
+ }
266
+ };
267
+ const runLimited = async (items) => {
268
+ const limit = Math.max(1, opts.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY);
269
+ let next = 0;
270
+ const worker = async () => {
271
+ while (next < items.length)
272
+ await executeOne(items[next++]);
273
+ };
274
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
275
+ };
276
+ try {
277
+ while (remaining.size > 0 && !controller.signal.aborted) {
278
+ const runnable = def.steps.filter(s => remaining.has(s.id) && s.after.every(d => completed.has(d)) && !s.after.some(d => failed.has(d)));
279
+ const blocked = def.steps.filter(s => remaining.has(s.id) && s.after.some(d => failed.has(d)));
280
+ for (const step of blocked) {
281
+ results[step.id] = { stepId: step.id, agentId: step.agent, content: '', status: 'skipped' };
282
+ remaining.delete(step.id);
283
+ failed.add(step.id); // transitive
284
+ record(step.id, 'skipped');
285
+ await journal?.step(runId, step.id, { status: 'skipped', transitions: flush() }).catch(() => undefined);
286
+ }
287
+ if (runnable.length === 0) {
288
+ if (blocked.length > 0)
289
+ continue;
290
+ break;
291
+ }
292
+ for (const step of runnable)
293
+ remaining.delete(step.id);
294
+ // Human-approval steps go one at a time after the parallel ones of the wave, as WorkflowRunner does.
295
+ await runLimited(runnable.filter(s => s.gate?.approval !== 'human'));
296
+ for (const step of runnable.filter(s => s.gate?.approval === 'human'))
297
+ await executeOne(step);
298
+ }
299
+ }
300
+ finally {
301
+ opts.signal?.removeEventListener('abort', onAbort);
302
+ }
303
+ const cancelled = controller.signal.aborted;
304
+ const suspended = !cancelled && awaiting.size > 0;
305
+ if (!cancelled && !suspended) {
306
+ // Unsatisfiable (cycle or unknown step in a definition that skipped validation): report it, do not drop it.
307
+ for (const id of remaining) {
308
+ const step = def.steps.find(s => s.id === id);
309
+ const error = 'Unsatisfiable dependencies (cycle or unknown step)';
310
+ results[id] = { stepId: id, agentId: step.agent, content: '', status: 'failed', error };
311
+ record(id, 'failed', error);
312
+ }
313
+ }
314
+ const compensations = [];
315
+ if (!cancelled && !suspended) {
316
+ for (const comp of def.compensation) {
317
+ const stepId = comp.on.replace(/\.failed$/, '');
318
+ if (results[stepId]?.status !== 'failed')
319
+ continue;
320
+ record(stepId, 'compensation_started', `agent: ${comp.agent}`);
321
+ try {
322
+ const out = await opts.executor.run({ id: `${stepId}:compensation`, agent: comp.agent, prompt: comp.prompt, after: [] }, {
323
+ prompt: (0, interpolate_1.interpolate)(comp.prompt, opts.payload),
324
+ context: `Failed step "${stepId}": ${results[stepId].error ?? 'unknown error'}`,
325
+ idempotencyKey: `${runId}:${stepId}:compensation:1`,
326
+ signal: controller.signal,
327
+ });
328
+ compensations.push({ on: comp.on, agent: comp.agent, status: 'completed', content: out.content });
329
+ record(stepId, 'compensation_completed');
330
+ }
331
+ catch (err) {
332
+ const error = err instanceof Error ? err.message : String(err);
333
+ compensations.push({ on: comp.on, agent: comp.agent, status: 'failed', error });
334
+ record(stepId, 'compensation_failed', error);
335
+ }
336
+ }
337
+ }
338
+ const vals = Object.values(results);
339
+ const status = cancelled ? 'cancelled'
340
+ : suspended ? 'awaiting_approval'
341
+ : vals.some(r => r.status === 'rejected') ? 'rejected'
342
+ : vals.some(r => r.status === 'failed') ? 'failed'
343
+ : 'completed';
344
+ await journal?.update(runId, {
345
+ status: status === 'completed' ? 'done' : status === 'cancelled' ? 'cancelled' : status === 'awaiting_approval' ? 'awaiting_approval' : 'failed',
346
+ ...(suspended ? { waiting: { stepId: [...awaiting.keys()][0], approvalId: [...awaiting.values()][0] } } : { waiting: null }),
347
+ ...(status === 'rejected' ? { error: 'rejected' } : {}),
348
+ ...(vals.some(r => r.costUsd !== undefined) ? { costUsd: vals.reduce((a, r) => a + (r.costUsd ?? 0), 0) } : {}),
349
+ transitions: flush(),
350
+ });
351
+ opts.transport?.emit({ type: 'workflow_complete', name: def.flow, status: status === 'completed' ? 'completed' : status === 'rejected' ? 'rejected' : 'failed' });
352
+ return { runId, flow: def.flow, version: def.version, status, steps: results, transitions, compensations };
353
+ }
354
+ //# sourceMappingURL=run.js.map