@smithers-orchestrator/engine 0.16.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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +50 -0
  3. package/src/AlertHumanRequestOptions.ts +8 -0
  4. package/src/AlertRuntimeServices.ts +10 -0
  5. package/src/ChildWorkflowDefinition.ts +5 -0
  6. package/src/ChildWorkflowExecuteOptions.ts +14 -0
  7. package/src/ContinuationRequest.ts +3 -0
  8. package/src/HijackState.ts +19 -0
  9. package/src/HumanRequestKind.ts +1 -0
  10. package/src/HumanRequestStatus.ts +1 -0
  11. package/src/PlanNode.ts +29 -0
  12. package/src/RalphMeta.ts +7 -0
  13. package/src/RalphState.ts +4 -0
  14. package/src/RalphStateMap.ts +3 -0
  15. package/src/ScheduleResult.ts +15 -0
  16. package/src/SignalRunOptions.ts +5 -0
  17. package/src/alert-runtime.js +22 -0
  18. package/src/approvals.js +220 -0
  19. package/src/child-workflow.js +163 -0
  20. package/src/effect/ApprovalDeferredResolution.ts +13 -0
  21. package/src/effect/ApprovalDurableDeferredResolution.ts +11 -0
  22. package/src/effect/ApprovalPayload.ts +7 -0
  23. package/src/effect/ApprovalResult.ts +6 -0
  24. package/src/effect/BuilderNode.ts +52 -0
  25. package/src/effect/BuilderStepHandle.ts +47 -0
  26. package/src/effect/CancelPayload.ts +3 -0
  27. package/src/effect/CancelResult.ts +4 -0
  28. package/src/effect/DeferredResolution.ts +7 -0
  29. package/src/effect/DiffBundle.ts +7 -0
  30. package/src/effect/ExecuteTaskActivityOptions.ts +7 -0
  31. package/src/effect/FilePatch.ts +6 -0
  32. package/src/effect/GetRunPayload.ts +3 -0
  33. package/src/effect/GetRunResult.ts +3 -0
  34. package/src/effect/LegacyExecuteTaskFn.ts +24 -0
  35. package/src/effect/ListRunsPayload.ts +6 -0
  36. package/src/effect/RunStatusSchema.ts +9 -0
  37. package/src/effect/RunSummary.ts +23 -0
  38. package/src/effect/SignalPayload.ts +7 -0
  39. package/src/effect/SignalResult.ts +6 -0
  40. package/src/effect/SmithersSqliteOptions.ts +3 -0
  41. package/src/effect/SqlMessageStorageEventHistoryQuery.ts +7 -0
  42. package/src/effect/TaggedWorkerError.ts +46 -0
  43. package/src/effect/TaskActivityContext.ts +4 -0
  44. package/src/effect/TaskActivityRetryOptions.ts +4 -0
  45. package/src/effect/TaskBridgeToolConfig.ts +6 -0
  46. package/src/effect/TaskFailure.ts +3 -0
  47. package/src/effect/TaskResult.ts +5 -0
  48. package/src/effect/UnknownWorkerError.ts +5 -0
  49. package/src/effect/WaitForEventDurableDeferredResolution.ts +11 -0
  50. package/src/effect/WorkerDispatchKind.ts +1 -0
  51. package/src/effect/WorkerTask.ts +14 -0
  52. package/src/effect/WorkerTaskError.ts +4 -0
  53. package/src/effect/WorkerTaskKind.ts +1 -0
  54. package/src/effect/WorkflowPatchDecisionRecord.ts +4 -0
  55. package/src/effect/WorkflowPatchDecisions.ts +1 -0
  56. package/src/effect/WorkflowVersioningRuntime.ts +7 -0
  57. package/src/effect/activity-bridge.js +131 -0
  58. package/src/effect/bridge-utils.js +45 -0
  59. package/src/effect/builder.js +837 -0
  60. package/src/effect/compute-task-bridge.js +734 -0
  61. package/src/effect/deferred-bridge.js +63 -0
  62. package/src/effect/deferred-state-bridge.js +1343 -0
  63. package/src/effect/diff-bundle.js +352 -0
  64. package/src/effect/durable-deferred-bridge.js +282 -0
  65. package/src/effect/entity-worker.js +154 -0
  66. package/src/effect/http-runner.js +86 -0
  67. package/src/effect/rpc-schema.js +101 -0
  68. package/src/effect/single-runner.js +189 -0
  69. package/src/effect/sql-message-storage.js +817 -0
  70. package/src/effect/static-task-bridge.js +308 -0
  71. package/src/effect/versioning.js +123 -0
  72. package/src/effect/workflow-bridge.js +260 -0
  73. package/src/effect/workflow-make-bridge.js +233 -0
  74. package/src/engine.js +6933 -0
  75. package/src/events.js +237 -0
  76. package/src/external/json-schema-to-zod.js +214 -0
  77. package/src/getDefinedToolMetadata.js +10 -0
  78. package/src/hot/HotReloadEvent.ts +21 -0
  79. package/src/hot/HotWorkflowController.js +220 -0
  80. package/src/hot/OverlayOptions.ts +4 -0
  81. package/src/hot/WatchTreeOptions.ts +6 -0
  82. package/src/hot/index.js +9 -0
  83. package/src/hot/overlay.js +177 -0
  84. package/src/hot/watch.js +174 -0
  85. package/src/human-requests.js +120 -0
  86. package/src/index.d.ts +1597 -0
  87. package/src/index.js +41 -0
  88. package/src/runtime-owner.js +36 -0
  89. package/src/scheduler.js +31 -0
  90. package/src/signals.js +82 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 William Cory
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@smithers-orchestrator/engine",
3
+ "version": "0.16.0",
4
+ "description": "Concrete Smithers workflow execution engine",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "exports": {
8
+ ".": {
9
+ "types": "./src/index.d.ts",
10
+ "import": "./src/index.js",
11
+ "default": "./src/index.js"
12
+ },
13
+ "./*": {
14
+ "types": "./src/index.d.ts",
15
+ "import": "./src/*.js",
16
+ "default": "./src/*.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "src/"
21
+ ],
22
+ "dependencies": {
23
+ "@effect/platform-bun": "^0.89.0",
24
+ "effect": "^3.21.0",
25
+ "@smithers-orchestrator/agents": "0.16.0",
26
+ "@smithers-orchestrator/db": "0.16.0",
27
+ "@smithers-orchestrator/driver": "0.16.0",
28
+ "@smithers-orchestrator/graph": "0.16.0",
29
+ "@smithers-orchestrator/memory": "0.16.0",
30
+ "@smithers-orchestrator/errors": "0.16.0",
31
+ "@smithers-orchestrator/observability": "0.16.0",
32
+ "@smithers-orchestrator/react-reconciler": "0.16.0",
33
+ "@smithers-orchestrator/scheduler": "0.16.0",
34
+ "@smithers-orchestrator/components": "0.16.0",
35
+ "@smithers-orchestrator/sandbox": "0.16.0",
36
+ "@smithers-orchestrator/time-travel": "0.16.0",
37
+ "@smithers-orchestrator/vcs": "0.16.0",
38
+ "@smithers-orchestrator/scorers": "0.16.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/bun": "latest",
42
+ "react": "^18.3.0 || ^19.0.0",
43
+ "typescript": "~5.9.3"
44
+ },
45
+ "scripts": {
46
+ "build": "tsup --dts-only",
47
+ "test": "bun test tests",
48
+ "typecheck": "tsc -p tsconfig.json --noEmit"
49
+ }
50
+ }
@@ -0,0 +1,8 @@
1
+ export type AlertHumanRequestOptions = {
2
+ runId: string;
3
+ nodeId: string;
4
+ iteration: number;
5
+ kind: "ask" | "confirm" | "select" | "json";
6
+ prompt: string;
7
+ linkedAlertId?: string;
8
+ };
@@ -0,0 +1,10 @@
1
+ import type { AlertHumanRequestOptions } from "./AlertHumanRequestOptions.ts";
2
+
3
+ export type AlertRuntimeServices = {
4
+ runId: string;
5
+ adapter: unknown;
6
+ eventBus: unknown;
7
+ requestCancel: () => void;
8
+ createHumanRequest: (options: AlertHumanRequestOptions) => Promise<void>;
9
+ pauseScheduler: (reason: string) => void;
10
+ };
@@ -0,0 +1,5 @@
1
+ import type { SmithersWorkflow } from "@smithers-orchestrator/components/SmithersWorkflow";
2
+
3
+ export type ChildWorkflowDefinition =
4
+ | SmithersWorkflow<unknown>
5
+ | (() => SmithersWorkflow<unknown> | unknown);
@@ -0,0 +1,14 @@
1
+ import type { ChildWorkflowDefinition } from "./ChildWorkflowDefinition.ts";
2
+
3
+ export type ChildWorkflowExecuteOptions = {
4
+ workflow: ChildWorkflowDefinition;
5
+ input?: unknown;
6
+ runId?: string;
7
+ parentRunId?: string;
8
+ rootDir?: string;
9
+ allowNetwork?: boolean;
10
+ maxOutputBytes?: number;
11
+ toolTimeoutMs?: number;
12
+ workflowPath?: string;
13
+ signal?: AbortSignal;
14
+ };
@@ -0,0 +1,3 @@
1
+ export type ContinuationRequest = {
2
+ stateJson?: string;
3
+ };
@@ -0,0 +1,19 @@
1
+ type HijackCompletion = {
2
+ requestedAtMs: number;
3
+ nodeId: string;
4
+ iteration: number;
5
+ attempt: number;
6
+ engine: string;
7
+ mode: "native-cli" | "conversation";
8
+ resume?: string;
9
+ messages?: unknown[];
10
+ cwd: string;
11
+ };
12
+
13
+ export type HijackState = {
14
+ request: {
15
+ requestedAtMs: number;
16
+ target?: string | null;
17
+ } | null;
18
+ completion: HijackCompletion | null;
19
+ };
@@ -0,0 +1 @@
1
+ export type HumanRequestKind = "ask" | "confirm" | "select" | "json";
@@ -0,0 +1 @@
1
+ export type HumanRequestStatus = "pending" | "answered" | "cancelled" | "expired";
@@ -0,0 +1,29 @@
1
+ export type PlanNode =
2
+ | { kind: "task"; nodeId: string }
3
+ | { kind: "sequence"; children: PlanNode[] }
4
+ | { kind: "parallel"; children: PlanNode[] }
5
+ | {
6
+ kind: "ralph";
7
+ id: string;
8
+ children: PlanNode[];
9
+ until: boolean;
10
+ maxIterations: number;
11
+ onMaxReached: "fail" | "return-last";
12
+ continueAsNewEvery?: number;
13
+ }
14
+ | { kind: "continue-as-new"; stateJson?: string }
15
+ | { kind: "group"; children: PlanNode[] }
16
+ | {
17
+ kind: "saga";
18
+ id: string;
19
+ actionChildren: PlanNode[];
20
+ compensationChildren: PlanNode[];
21
+ onFailure: "compensate" | "compensate-and-fail" | "fail";
22
+ }
23
+ | {
24
+ kind: "try-catch-finally";
25
+ id: string;
26
+ tryChildren: PlanNode[];
27
+ catchChildren: PlanNode[];
28
+ finallyChildren: PlanNode[];
29
+ };
@@ -0,0 +1,7 @@
1
+ export type RalphMeta = {
2
+ id: string;
3
+ until: boolean;
4
+ maxIterations: number;
5
+ onMaxReached: "fail" | "return-last";
6
+ continueAsNewEvery?: number;
7
+ };
@@ -0,0 +1,4 @@
1
+ export type RalphState = {
2
+ iteration: number;
3
+ done: boolean;
4
+ };
@@ -0,0 +1,3 @@
1
+ import type { RalphState } from "./RalphState.ts";
2
+
3
+ export type RalphStateMap = Map<string, RalphState>;
@@ -0,0 +1,15 @@
1
+ import type { TaskDescriptor } from "@smithers-orchestrator/graph/TaskDescriptor";
2
+ import type { RalphMeta } from "./RalphMeta.ts";
3
+ import type { ContinuationRequest } from "./ContinuationRequest.ts";
4
+
5
+ export type ScheduleResult = {
6
+ runnable: TaskDescriptor[];
7
+ pendingExists: boolean;
8
+ waitingApprovalExists: boolean;
9
+ waitingEventExists: boolean;
10
+ waitingTimerExists: boolean;
11
+ readyRalphs: RalphMeta[];
12
+ continuation?: ContinuationRequest;
13
+ nextRetryAtMs?: number;
14
+ fatalError?: string;
15
+ };
@@ -0,0 +1,5 @@
1
+ export type SignalRunOptions = {
2
+ correlationId?: string | null;
3
+ receivedBy?: string | null;
4
+ timestampMs?: number;
5
+ };
@@ -0,0 +1,22 @@
1
+ // @smithers-type-exports-begin
2
+ /** @typedef {import("./AlertHumanRequestOptions.ts").AlertHumanRequestOptions} AlertHumanRequestOptions */
3
+ /** @typedef {import("./AlertRuntimeServices.ts").AlertRuntimeServices} AlertRuntimeServices */
4
+ // @smithers-type-exports-end
5
+
6
+ /** @typedef {import("@smithers-orchestrator/scheduler/SmithersWorkflowOptions").SmithersAlertPolicy} SmithersAlertPolicy */
7
+ export class AlertRuntime {
8
+ /** @type {SmithersAlertPolicy} */
9
+ policy;
10
+ /** @type {AlertRuntimeServices} */
11
+ services;
12
+ /**
13
+ * @param {SmithersAlertPolicy} policy
14
+ * @param {AlertRuntimeServices} services
15
+ */
16
+ constructor(policy, services) {
17
+ this.policy = policy;
18
+ this.services = services;
19
+ }
20
+ start() { }
21
+ stop() { }
22
+ }
@@ -0,0 +1,220 @@
1
+ import { Effect, Metric } from "effect";
2
+ import { nowMs } from "@smithers-orchestrator/scheduler/nowMs";
3
+ import { SmithersDb } from "@smithers-orchestrator/db/adapter";
4
+ import { approvalWaitDuration, trackEvent, updateAsyncExternalWaitPending, } from "@smithers-orchestrator/observability/metrics";
5
+ import { bridgeApprovalResolve } from "./effect/durable-deferred-bridge.js";
6
+ import { SmithersError } from "@smithers-orchestrator/errors/SmithersError";
7
+ /**
8
+ * @param {string | null | undefined} currentStatus
9
+ * @param {number} pendingApprovals
10
+ * @returns {"waiting-approval" | "waiting-event" | null}
11
+ */
12
+ function nextRunStatusForApproval(currentStatus, pendingApprovals) {
13
+ if (currentStatus !== "waiting-approval" &&
14
+ currentStatus !== "waiting-event") {
15
+ return null;
16
+ }
17
+ return pendingApprovals > 0 ? "waiting-approval" : "waiting-event";
18
+ }
19
+ /**
20
+ * @param {unknown} decision
21
+ */
22
+ function serializeDecision(decision) {
23
+ return decision === undefined ? null : JSON.stringify(decision);
24
+ }
25
+ /**
26
+ * @param {string | null} [requestJson]
27
+ */
28
+ function isAsyncApprovalRequest(requestJson) {
29
+ if (!requestJson)
30
+ return false;
31
+ try {
32
+ return JSON.parse(requestJson)?.waitAsync === true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /**
39
+ * @param {string} runId
40
+ * @param {string} nodeId
41
+ * @param {number} iteration
42
+ * @param {string | null | undefined} state
43
+ * @returns {Effect.Effect<void, SmithersError>}
44
+ */
45
+ function validateNodeWaitingForApproval(runId, nodeId, iteration, state) {
46
+ if (state === "waiting-approval" || state === "waiting_approval") {
47
+ return Effect.void;
48
+ }
49
+ return Effect.fail(new SmithersError("INVALID_INPUT", `Node ${nodeId} is not waiting for approval.`, { runId, nodeId, iteration, state: state ?? null }));
50
+ }
51
+ /**
52
+ * @param {SmithersDb} adapter
53
+ * @param {string} runId
54
+ * @param {string} nodeId
55
+ * @param {number} iteration
56
+ * @param {string} [note]
57
+ * @param {string} [decidedBy]
58
+ * @param {unknown} [decision]
59
+ * @param {boolean} [autoApproved]
60
+ * @returns {Effect.Effect<void, SmithersError, never>}
61
+ */
62
+ export function approveNode(adapter, runId, nodeId, iteration, note, decidedBy, decision, autoApproved = false) {
63
+ const ts = nowMs();
64
+ const event = {
65
+ type: autoApproved ? "ApprovalAutoApproved" : "ApprovalGranted",
66
+ runId,
67
+ nodeId,
68
+ iteration,
69
+ timestampMs: ts,
70
+ };
71
+ return Effect.gen(function* () {
72
+ const existing = yield* adapter.getApproval(runId, nodeId, iteration);
73
+ const currentNode = yield* adapter.getNode(runId, nodeId, iteration);
74
+ yield* validateNodeWaitingForApproval(runId, nodeId, iteration, currentNode?.state);
75
+ yield* adapter.withTransactionEffect("approval", Effect.gen(function* () {
76
+ yield* adapter.insertOrUpdateApproval({
77
+ runId,
78
+ nodeId,
79
+ iteration,
80
+ status: "approved",
81
+ requestedAtMs: null,
82
+ decidedAtMs: ts,
83
+ note: note ?? null,
84
+ decidedBy: decidedBy ?? null,
85
+ requestJson: existing?.requestJson ?? null,
86
+ decisionJson: serializeDecision(decision) ?? existing?.decisionJson ?? null,
87
+ autoApproved,
88
+ });
89
+ yield* adapter.insertNode({
90
+ runId,
91
+ nodeId,
92
+ iteration,
93
+ state: "pending",
94
+ lastAttempt: currentNode?.lastAttempt ?? null,
95
+ updatedAtMs: nowMs(),
96
+ outputTable: currentNode?.outputTable ?? "",
97
+ label: currentNode?.label ?? null,
98
+ });
99
+ const run = yield* adapter.getRun(runId);
100
+ if (run) {
101
+ const pending = yield* adapter.listPendingApprovals(runId);
102
+ const nextStatus = nextRunStatusForApproval(run.status, pending.length);
103
+ if (nextStatus && run.status !== nextStatus) {
104
+ yield* adapter.updateRun(runId, { status: nextStatus });
105
+ }
106
+ }
107
+ }));
108
+ if (existing?.requestedAtMs) {
109
+ yield* Metric.update(approvalWaitDuration, ts - existing.requestedAtMs);
110
+ }
111
+ if (existing?.status === "requested" && isAsyncApprovalRequest(existing.requestJson)) {
112
+ yield* updateAsyncExternalWaitPending("approval", -1);
113
+ }
114
+ yield* adapter.insertEventWithNextSeq({
115
+ runId,
116
+ timestampMs: ts,
117
+ type: event.type,
118
+ payloadJson: JSON.stringify(event),
119
+ });
120
+ yield* trackEvent(event);
121
+ yield* Effect.logInfo(autoApproved ? "approval auto-approved" : "approval granted");
122
+ yield* Effect.promise(() => bridgeApprovalResolve(adapter, runId, nodeId, iteration, {
123
+ approved: true,
124
+ note: note ?? null,
125
+ decidedBy: decidedBy ?? null,
126
+ decisionJson: serializeDecision(decision),
127
+ autoApproved,
128
+ }));
129
+ }).pipe(Effect.annotateLogs({
130
+ runId,
131
+ nodeId,
132
+ iteration,
133
+ approvalStatus: autoApproved ? "auto-approved" : "approved",
134
+ approvalDecidedBy: decidedBy ?? null,
135
+ }), Effect.withLogSpan("approval:grant"));
136
+ }
137
+ /**
138
+ * @param {SmithersDb} adapter
139
+ * @param {string} runId
140
+ * @param {string} nodeId
141
+ * @param {number} iteration
142
+ * @param {string} [note]
143
+ * @param {string} [decidedBy]
144
+ * @param {unknown} [decision]
145
+ * @returns {Effect.Effect<void, SmithersError, never>}
146
+ */
147
+ export function denyNode(adapter, runId, nodeId, iteration, note, decidedBy, decision) {
148
+ const ts = nowMs();
149
+ const event = {
150
+ type: "ApprovalDenied",
151
+ runId,
152
+ nodeId,
153
+ iteration,
154
+ timestampMs: ts,
155
+ };
156
+ return Effect.gen(function* () {
157
+ const existing = yield* adapter.getApproval(runId, nodeId, iteration);
158
+ const currentNode = yield* adapter.getNode(runId, nodeId, iteration);
159
+ yield* validateNodeWaitingForApproval(runId, nodeId, iteration, currentNode?.state);
160
+ yield* adapter.withTransactionEffect("approval", Effect.gen(function* () {
161
+ yield* adapter.insertOrUpdateApproval({
162
+ runId,
163
+ nodeId,
164
+ iteration,
165
+ status: "denied",
166
+ requestedAtMs: null,
167
+ decidedAtMs: ts,
168
+ note: note ?? null,
169
+ decidedBy: decidedBy ?? null,
170
+ requestJson: existing?.requestJson ?? null,
171
+ decisionJson: serializeDecision(decision) ?? existing?.decisionJson ?? null,
172
+ autoApproved: false,
173
+ });
174
+ yield* adapter.insertNode({
175
+ runId,
176
+ nodeId,
177
+ iteration,
178
+ state: "failed",
179
+ lastAttempt: currentNode?.lastAttempt ?? null,
180
+ updatedAtMs: nowMs(),
181
+ outputTable: currentNode?.outputTable ?? "",
182
+ label: currentNode?.label ?? null,
183
+ });
184
+ const run = yield* adapter.getRun(runId);
185
+ if (run) {
186
+ const pending = yield* adapter.listPendingApprovals(runId);
187
+ const nextStatus = nextRunStatusForApproval(run.status, pending.length);
188
+ if (nextStatus && run.status !== nextStatus) {
189
+ yield* adapter.updateRun(runId, { status: nextStatus });
190
+ }
191
+ }
192
+ }));
193
+ if (existing?.requestedAtMs) {
194
+ yield* Metric.update(approvalWaitDuration, ts - existing.requestedAtMs);
195
+ }
196
+ if (existing?.status === "requested" && isAsyncApprovalRequest(existing.requestJson)) {
197
+ yield* updateAsyncExternalWaitPending("approval", -1);
198
+ }
199
+ yield* adapter.insertEventWithNextSeq({
200
+ runId,
201
+ timestampMs: ts,
202
+ type: "ApprovalDenied",
203
+ payloadJson: JSON.stringify(event),
204
+ });
205
+ yield* trackEvent(event);
206
+ yield* Effect.logInfo("approval denied");
207
+ yield* Effect.promise(() => bridgeApprovalResolve(adapter, runId, nodeId, iteration, {
208
+ approved: false,
209
+ note: note ?? null,
210
+ decidedBy: decidedBy ?? null,
211
+ decisionJson: serializeDecision(decision),
212
+ }));
213
+ }).pipe(Effect.annotateLogs({
214
+ runId,
215
+ nodeId,
216
+ iteration,
217
+ approvalStatus: "denied",
218
+ approvalDecidedBy: decidedBy ?? null,
219
+ }), Effect.withLogSpan("approval:deny"));
220
+ }
@@ -0,0 +1,163 @@
1
+ import { Effect } from "effect";
2
+ import { SmithersError } from "@smithers-orchestrator/errors/SmithersError";
3
+ import { SmithersDb } from "@smithers-orchestrator/db/adapter";
4
+ import { requireTaskRuntime } from "@smithers-orchestrator/driver/task-runtime";
5
+ import { getWorkflowMakeBridgeRuntime } from "./effect/workflow-make-bridge.js";
6
+ /** @typedef {import("./ChildWorkflowDefinition.ts").ChildWorkflowDefinition} ChildWorkflowDefinition */
7
+ /** @typedef {import("./ChildWorkflowExecuteOptions.ts").ChildWorkflowExecuteOptions} ChildWorkflowExecuteOptions */
8
+ /** @typedef {import("@smithers-orchestrator/driver/RunResult").RunResult} RunResult */
9
+
10
+ /**
11
+ * @param {unknown} value
12
+ * @returns {value is import("@smithers-orchestrator/components/SmithersWorkflow").SmithersWorkflow<any>}
13
+ */
14
+ function isWorkflowLike(value) {
15
+ return Boolean(value &&
16
+ typeof value === "object" &&
17
+ "build" in value &&
18
+ typeof value.build === "function");
19
+ }
20
+ /**
21
+ * @param {unknown} input
22
+ * @returns {Record<string, unknown>}
23
+ */
24
+ function normalizeChildInput(input) {
25
+ if (!input)
26
+ return {};
27
+ if (typeof input === "object" && !Array.isArray(input)) {
28
+ return input;
29
+ }
30
+ return { value: input };
31
+ }
32
+ /**
33
+ * @param {unknown} value
34
+ * @returns {unknown}
35
+ */
36
+ function stripSystemColumns(value) {
37
+ if (!value || typeof value !== "object")
38
+ return value;
39
+ if (Array.isArray(value)) {
40
+ return value.map(stripSystemColumns);
41
+ }
42
+ const obj = value;
43
+ const out = {};
44
+ for (const [key, val] of Object.entries(obj)) {
45
+ if (key === "runId" || key === "nodeId" || key === "iteration")
46
+ continue;
47
+ out[key] = val;
48
+ }
49
+ return out;
50
+ }
51
+ /**
52
+ * @param {RunResult} runResult
53
+ * @returns {unknown}
54
+ */
55
+ function normalizeChildOutput(runResult) {
56
+ const output = runResult.output;
57
+ if (!Array.isArray(output))
58
+ return stripSystemColumns(output);
59
+ const rows = output.map((row) => stripSystemColumns(row));
60
+ if (rows.length === 0)
61
+ return null;
62
+ if (rows.length === 1)
63
+ return rows[0];
64
+ return rows;
65
+ }
66
+ /**
67
+ * @param {string} parentRunId
68
+ * @param {string} stepId
69
+ * @param {number} iteration
70
+ * @returns {string}
71
+ */
72
+ function buildChildWorkflowRunId(parentRunId, stepId, iteration) {
73
+ return [
74
+ parentRunId,
75
+ "child",
76
+ stepId,
77
+ String(iteration),
78
+ ].join(":");
79
+ }
80
+ /**
81
+ * @param {ChildWorkflowDefinition} definition
82
+ * @param {import("@smithers-orchestrator/components/SmithersWorkflow").SmithersWorkflow<any>} [parentWorkflow]
83
+ * @returns {import("@smithers-orchestrator/components/SmithersWorkflow").SmithersWorkflow<any>}
84
+ */
85
+ function resolveChildWorkflow(definition, parentWorkflow) {
86
+ const resolved = typeof definition === "function" ? definition() : definition;
87
+ if (isWorkflowLike(resolved)) {
88
+ return {
89
+ db: resolved.db ?? parentWorkflow?.db,
90
+ build: resolved.build,
91
+ opts: resolved.opts ?? {},
92
+ schemaRegistry: resolved.schemaRegistry ?? parentWorkflow?.schemaRegistry,
93
+ zodToKeyName: resolved.zodToKeyName ?? parentWorkflow?.zodToKeyName,
94
+ };
95
+ }
96
+ if (typeof resolved === "function") {
97
+ if (!parentWorkflow) {
98
+ throw new SmithersError("INVALID_INPUT", "Child workflow function requires a parent workflow context.");
99
+ }
100
+ const render = resolved;
101
+ return {
102
+ db: parentWorkflow.db,
103
+ build: (ctx) => render(ctx),
104
+ opts: {},
105
+ schemaRegistry: parentWorkflow.schemaRegistry,
106
+ zodToKeyName: parentWorkflow.zodToKeyName,
107
+ };
108
+ }
109
+ throw new SmithersError("INVALID_INPUT", "Child workflow must be a Smithers workflow object or function.");
110
+ }
111
+ /**
112
+ * @param {import("@smithers-orchestrator/components/SmithersWorkflow").SmithersWorkflow<any> | undefined} parentWorkflow
113
+ * @param {ChildWorkflowExecuteOptions} options
114
+ * @returns {Promise<{ runId: string; status: RunResult["status"]; output: unknown; }>}
115
+ */
116
+ export async function executeChildWorkflow(parentWorkflow, options) {
117
+ const runtime = requireTaskRuntime();
118
+ const childWorkflow = resolveChildWorkflow(options.workflow, parentWorkflow);
119
+ const input = normalizeChildInput(options.input);
120
+ const childRunId = options.runId ??
121
+ buildChildWorkflowRunId(options.parentRunId ?? runtime.runId, runtime.stepId, runtime.iteration);
122
+ const adapter = new SmithersDb(childWorkflow.db);
123
+ const existingChildRun = await adapter.getRun(childRunId);
124
+ const resume = Boolean(existingChildRun);
125
+ const bridgeRuntime = getWorkflowMakeBridgeRuntime();
126
+ if (bridgeRuntime) {
127
+ const result = await bridgeRuntime.executeChildWorkflow(childWorkflow, {
128
+ input,
129
+ runId: childRunId,
130
+ resume,
131
+ parentRunId: options.parentRunId ?? runtime.runId,
132
+ rootDir: options.rootDir,
133
+ workflowPath: options.workflowPath,
134
+ allowNetwork: options.allowNetwork,
135
+ maxOutputBytes: options.maxOutputBytes,
136
+ toolTimeoutMs: options.toolTimeoutMs,
137
+ signal: options.signal ?? runtime.signal,
138
+ });
139
+ return {
140
+ runId: result.runId,
141
+ status: result.status,
142
+ output: normalizeChildOutput(result),
143
+ };
144
+ }
145
+ const { runWorkflow } = await import("./engine.js");
146
+ const result = await Effect.runPromise(runWorkflow(childWorkflow, {
147
+ input,
148
+ runId: childRunId,
149
+ resume,
150
+ parentRunId: options.parentRunId ?? runtime.runId,
151
+ rootDir: options.rootDir,
152
+ workflowPath: options.workflowPath,
153
+ allowNetwork: options.allowNetwork,
154
+ maxOutputBytes: options.maxOutputBytes,
155
+ toolTimeoutMs: options.toolTimeoutMs,
156
+ signal: options.signal ?? runtime.signal,
157
+ }));
158
+ return {
159
+ runId: result.runId,
160
+ status: result.status,
161
+ output: normalizeChildOutput(result),
162
+ };
163
+ }
@@ -0,0 +1,13 @@
1
+ import type { Schema } from "effect";
2
+
3
+ /**
4
+ * Mirrors the shape of the approvalDeferredSuccessSchema defined in
5
+ * deferred-bridge.js. Kept in sync with the runtime schema.
6
+ */
7
+ export type ApprovalDeferredResolution = Schema.Schema.Type<
8
+ Schema.Struct<{
9
+ approved: typeof Schema.Boolean;
10
+ note: Schema.NullOr<typeof Schema.String>;
11
+ decidedBy: Schema.NullOr<typeof Schema.String>;
12
+ }>
13
+ >;
@@ -0,0 +1,11 @@
1
+ import type { Schema } from "effect";
2
+
3
+ export type ApprovalDurableDeferredResolution = Schema.Schema.Type<
4
+ Schema.Struct<{
5
+ approved: typeof Schema.Boolean;
6
+ note: Schema.NullOr<typeof Schema.String>;
7
+ decidedBy: Schema.NullOr<typeof Schema.String>;
8
+ decisionJson: Schema.NullOr<typeof Schema.String>;
9
+ autoApproved: typeof Schema.Boolean;
10
+ }>
11
+ >;
@@ -0,0 +1,7 @@
1
+ export type ApprovalPayload = {
2
+ runId: string;
3
+ nodeId: string;
4
+ iteration?: number;
5
+ note?: string;
6
+ decidedBy?: string;
7
+ };
@@ -0,0 +1,6 @@
1
+ export type ApprovalResult = {
2
+ runId: string;
3
+ nodeId: string;
4
+ iteration: number;
5
+ approved: boolean;
6
+ };