@backendkit-labs/agent-core 0.42.0 → 0.44.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 (84) hide show
  1. package/README.md +60 -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/condition.d.ts +6 -0
  15. package/dist/flow/condition.d.ts.map +1 -0
  16. package/dist/flow/condition.js +30 -0
  17. package/dist/flow/condition.js.map +1 -0
  18. package/dist/flow/convert.d.ts +44 -0
  19. package/dist/flow/convert.d.ts.map +1 -0
  20. package/dist/flow/convert.js +34 -0
  21. package/dist/flow/convert.js.map +1 -0
  22. package/dist/flow/file-journal.d.ts +34 -0
  23. package/dist/flow/file-journal.d.ts.map +1 -0
  24. package/dist/flow/file-journal.js +176 -0
  25. package/dist/flow/file-journal.js.map +1 -0
  26. package/dist/flow/handler.d.ts +35 -0
  27. package/dist/flow/handler.d.ts.map +1 -0
  28. package/dist/flow/handler.js +51 -0
  29. package/dist/flow/handler.js.map +1 -0
  30. package/dist/flow/host.d.ts +79 -0
  31. package/dist/flow/host.d.ts.map +1 -0
  32. package/dist/flow/host.js +148 -0
  33. package/dist/flow/host.js.map +1 -0
  34. package/dist/flow/index.d.ts +27 -0
  35. package/dist/flow/index.d.ts.map +1 -0
  36. package/dist/flow/index.js +55 -0
  37. package/dist/flow/index.js.map +1 -0
  38. package/dist/flow/interpolate.d.ts +6 -0
  39. package/dist/flow/interpolate.d.ts.map +1 -0
  40. package/dist/flow/interpolate.js +18 -0
  41. package/dist/flow/interpolate.js.map +1 -0
  42. package/dist/flow/journal.d.ts +105 -0
  43. package/dist/flow/journal.d.ts.map +1 -0
  44. package/dist/flow/journal.js +89 -0
  45. package/dist/flow/journal.js.map +1 -0
  46. package/dist/flow/limiter.d.ts +21 -0
  47. package/dist/flow/limiter.d.ts.map +1 -0
  48. package/dist/flow/limiter.js +45 -0
  49. package/dist/flow/limiter.js.map +1 -0
  50. package/dist/flow/loader.d.ts +24 -0
  51. package/dist/flow/loader.d.ts.map +1 -0
  52. package/dist/flow/loader.js +185 -0
  53. package/dist/flow/loader.js.map +1 -0
  54. package/dist/flow/planner.d.ts +50 -0
  55. package/dist/flow/planner.d.ts.map +1 -0
  56. package/dist/flow/planner.js +131 -0
  57. package/dist/flow/planner.js.map +1 -0
  58. package/dist/flow/run.d.ts +115 -0
  59. package/dist/flow/run.d.ts.map +1 -0
  60. package/dist/flow/run.js +417 -0
  61. package/dist/flow/run.js.map +1 -0
  62. package/dist/flow/tools.d.ts +27 -0
  63. package/dist/flow/tools.d.ts.map +1 -0
  64. package/dist/flow/tools.js +71 -0
  65. package/dist/flow/tools.js.map +1 -0
  66. package/dist/flow/types.d.ts +139 -0
  67. package/dist/flow/types.d.ts.map +1 -0
  68. package/dist/flow/types.js +80 -0
  69. package/dist/flow/types.js.map +1 -0
  70. package/dist/index.d.ts +17 -1
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +46 -2
  73. package/dist/index.js.map +1 -1
  74. package/dist/learning/index.d.ts +1 -1
  75. package/dist/learning/index.d.ts.map +1 -1
  76. package/dist/learning/index.js +104 -42
  77. package/dist/learning/index.js.map +1 -1
  78. package/dist/learning/signal.d.ts +32 -14
  79. package/dist/learning/signal.d.ts.map +1 -1
  80. package/dist/learning/signal.js +95 -30
  81. package/dist/learning/signal.js.map +1 -1
  82. package/dist/learning/types.d.ts +60 -0
  83. package/dist/learning/types.d.ts.map +1 -1
  84. package/package.json +6 -1
@@ -0,0 +1,50 @@
1
+ import type { StructuredChat, GenerateObjectOptions } from '../structured/generateObject';
2
+ import type { LLMProvider } from '../types';
3
+ import type { FlowDefinition } from './types';
4
+ export type { StructuredChat };
5
+ /**
6
+ * The planner (SPEC-0023 F6b): from a task and the agents available, a model produces a plan that becomes a `FlowDefinition`,
7
+ * ready for `runFlow`. A plan a model writes and a flow written in YAML are then the same object.
8
+ *
9
+ * The plan is validated before anything runs: duplicate ids, a dependency on an unknown step, an agent that does not exist
10
+ * and cycles are rejected, and the model is told what was wrong and asked again (`retries`). An agent id invented by the
11
+ * model would otherwise run as a no-op and look like success.
12
+ */
13
+ export interface PlannerAgent {
14
+ id: string;
15
+ name?: string;
16
+ description?: string;
17
+ capabilities?: string[];
18
+ domain?: string;
19
+ /** Every step of this agent needs a person to review its output (`gate.approval: human`), whatever the model says. */
20
+ gate?: boolean;
21
+ /** Criteria the reviewer checks; added to those the model proposes. Only count when the step is gated. */
22
+ gateCriteria?: string[];
23
+ }
24
+ /** The marker for a needed capability no agent covers. The step stays in the flow and is reported in `unresolved`. */
25
+ export declare const UNRESOLVED_AGENT = "unresolved";
26
+ export interface PlanFlowOptions {
27
+ agents: PlannerAgent[];
28
+ /** The model: a provider, or any chat function (`StructuredChat`). One of the two. */
29
+ provider?: LLMProvider;
30
+ chat?: StructuredChat;
31
+ /** Knowledge the plan should take into account (retrieved by the caller). */
32
+ context?: string;
33
+ /** Policy text for the planner, e.g. a MANDATORY GATES section: which domains need a gate and with what criteria. */
34
+ policyContext?: string;
35
+ /** Name of the flow. Default: the summary the model wrote. */
36
+ flow?: string;
37
+ /** Extra attempts after an invalid plan, each told what was wrong. Default 1. */
38
+ retries?: number;
39
+ signal?: AbortSignal;
40
+ onMetrics?: GenerateObjectOptions['onMetrics'];
41
+ }
42
+ export interface PlannedFlow {
43
+ flow: FlowDefinition;
44
+ summary: string;
45
+ /** Steps the model could not assign to any agent (`agent_id: "unresolved"`). Empty when the plan is complete. */
46
+ unresolved: string[];
47
+ }
48
+ export declare const PLANNER_SYSTEM = "You are a task decomposition expert.\nGiven a task and a list of available specialist agents, produce a JSON execution plan.\n\nRules:\n- Use only agent IDs from the provided list.\n- depends_on: [] means the sub-task can start immediately; [\"t1\"] waits for t1 to finish.\n- If no agent matches a needed capability, use agent_id=\"unresolved\" and note the gap in the task.\n- Keep each task description focused and self-contained.\n- gate: set to true when a MANDATORY GATES section is present and the step's agent domain matches a governed domain. Always false otherwise.\n- 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.";
49
+ export declare function planFlow(task: string, opts: PlanFlowOptions): Promise<PlannedFlow>;
50
+ //# sourceMappingURL=planner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"planner.d.ts","sourceRoot":"","sources":["../../src/flow/planner.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC1F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B;;;;;;;GAOG;AAEH,MAAM,WAAW,YAAY;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sHAAsH;IACtH,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,0GAA0G;IAC1G,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B;AAED,sHAAsH;AACtH,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAE7C,MAAM,WAAW,eAAe;IAC5B,MAAM,EAAE,YAAY,EAAE,CAAC;IACvB,sFAAsF;IACtF,QAAQ,CAAC,EAAE,WAAW,CAAC;IACvB,IAAI,CAAC,EAAE,cAAc,CAAC;IACtB,6EAA6E;IAC7E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qHAAqH;IACrH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,8DAA8D;IAC9D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,iFAAiF;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,SAAS,CAAC,EAAE,qBAAqB,CAAC,WAAW,CAAC,CAAC;CAClD;AAED,MAAM,WAAW,WAAW;IACxB,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,iHAAiH;IACjH,UAAU,EAAE,MAAM,EAAE,CAAC;CACxB;AAED,eAAO,MAAM,cAAc,yvBASyJ,CAAC;AAyDrL,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,WAAW,CAAC,CAiDxF"}
@@ -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,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC3D,MAAM,KAAK,GAAG,IAAI,GAAG,EAA+B,CAAC;IACrD,MAAM,IAAI,GAAa,EAAE,CAAC;IAC1B,MAAM,KAAK,GAAG,CAAC,EAAU,EAAwB,EAAE;QAC/C,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,MAAM;YAAE,OAAO,SAAS,CAAC;QAC/C,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,UAAU;YAAE,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CA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AC"}
@@ -0,0 +1,115 @@
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
+ /** Sum of the `costUsd` the steps reported. Absent when none did. */
50
+ costUsd?: number;
51
+ transitions: FlowTransition[];
52
+ compensations: FlowCompensationResult[];
53
+ }
54
+ export interface GateContext {
55
+ runId: string;
56
+ flow: string;
57
+ /** Appends to the transition log (`gate_passed`, `gate_failed`...). */
58
+ record(event: FlowTransition['event'], detail?: string): void;
59
+ }
60
+ export interface RunFlowOptions {
61
+ executor: StepExecutor;
62
+ /** Trigger payload, interpolated into prompts as `{{payload.x}}`. */
63
+ payload?: unknown;
64
+ runId?: string;
65
+ /** Most steps of one wave at the same time. Default 8. */
66
+ maxConcurrency?: number;
67
+ /** Caps per `step.agent` (and per `tenantId`, if given) across every flow that shares the limiter. */
68
+ limiter?: ConcurrencyLimiter;
69
+ tenantId?: string;
70
+ /** Abort to stop: running steps get the signal, steps not started are not started, the result is `cancelled`. */
71
+ signal?: AbortSignal;
72
+ /** Awaited before each step starts: a supervisor holds it while the flow is paused (`FlowControl.checkpoint`). */
73
+ checkpoint?: () => Promise<void>;
74
+ /** Transport for `workflow_*` events, as `WorkflowRunner` emits. */
75
+ transport?: Transport;
76
+ /** Approval through the `ApprovalStore` (F5); replaces `approve`. A step can stop the run as `awaiting_approval`. */
77
+ approvals?: FlowApprovals;
78
+ /** Asks a person for a step with `gate.approval: human`. Default: approve. False rejects the step and what depends on it. */
79
+ approve?: (step: FlowStep, previousOutputs: Record<string, string>) => Promise<boolean>;
80
+ /** After a step succeeds and has a `gate`: throw to fail the step (a gate is never skipped silently). */
81
+ gate?: (step: FlowStep, output: string, ctx: GateContext) => Promise<void>;
82
+ onTransition?: (t: FlowTransition) => void;
83
+ /** 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`. */
84
+ onStepFailure?: 'skip' | 'continue';
85
+ /** 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. */
86
+ stepTimeoutMs?: number;
87
+ /**
88
+ * Durable state (SPEC-0023 F3). With a journal the run is claimed (one process per run), each step is written before and
89
+ * after it runs, and a `runId` that already has a record is RESUMED: steps that are `done` are not run again and their
90
+ * output feeds the next ones. The payload is not stored: pass it again when resuming.
91
+ */
92
+ journal?: RunJournal;
93
+ /** Who holds the claim. Default: a random id per call. */
94
+ owner?: string;
95
+ /** How long the claim lasts without being renewed. Default 10 minutes. */
96
+ claimTtlMs?: number;
97
+ /**
98
+ * How often the run renews its claim while it goes on, so that a run longer than `claimTtlMs` is not taken over by another
99
+ * process while it is alive: the claim then only expires when this process stops (dies, stalls). Default a third of the TTL;
100
+ * 0 turns renewal off (tests that simulate a process that died). If a renewal finds the claim taken by someone else, the run is
101
+ * stopped and `runFlow` throws `FlowClaimError`; the journal is left as the new owner found it.
102
+ */
103
+ claimRenewMs?: number;
104
+ /** 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. */
105
+ onInterrupted?: 'retry' | 'fail';
106
+ /** Applied to the input preview and error texts written to the journal. Outputs are stored as they are. */
107
+ redact?: (text: string) => string;
108
+ }
109
+ /** Another process holds the claim of the run. */
110
+ export declare class FlowClaimError extends Error {
111
+ readonly runId: string;
112
+ constructor(runId: string);
113
+ }
114
+ export declare function runFlow(def: FlowDefinition, opts: RunFlowOptions): Promise<FlowResult>;
115
+ //# 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;AAIpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,KAAK,EAAE,UAAU,EAAc,MAAM,WAAW,CAAC;AAExD;;;;GAIG;AAEH,MAAM,WAAW,UAAU;IAAG,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE;AAEjE,MAAM,WAAW,SAAS;IACtB,MAAM,EAAE,MAAM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