@effect-agent/workflow 0.1.0-beta.46
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/dist/AgentWorkflow.d.mts +30 -0
- package/dist/AgentWorkflow.mjs +52 -0
- package/dist/AgentWorkflow.mjs.map +1 -0
- package/dist/WorkflowAgentHost-DOGuS1cg.mjs +298 -0
- package/dist/WorkflowAgentHost-DOGuS1cg.mjs.map +1 -0
- package/dist/WorkflowAgentHost.d.mts +58 -0
- package/dist/WorkflowAgentHost.mjs +4 -0
- package/dist/WorkflowDispatch.d.mts +81 -0
- package/dist/WorkflowDispatch.mjs +91 -0
- package/dist/WorkflowDispatch.mjs.map +1 -0
- package/dist/WorkflowExecution.d.mts +30 -0
- package/dist/WorkflowExecution.mjs +23 -0
- package/dist/WorkflowExecution.mjs.map +1 -0
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +5 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +1 -0
- package/src/AgentWorkflow.ts +65 -0
- package/src/WorkflowAgentHost.ts +614 -0
- package/src/WorkflowDispatch.ts +118 -0
- package/src/WorkflowExecution.ts +33 -0
- package/src/index.ts +4 -0
- package/src/internal/completion.ts +7 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { WorkflowDispatchError } from "./WorkflowDispatch.mjs";
|
|
2
|
+
import { WorkflowAgent, WorkflowExecuteOptions, WorkflowExecutionFailure } from "./WorkflowExecution.mjs";
|
|
3
|
+
import { WorkflowAdmissionClosed, WorkflowAgentHost } from "./WorkflowAgentHost.mjs";
|
|
4
|
+
import { AgentInputError, AgentOutputError } from "@effect-agent/core/AgentError";
|
|
5
|
+
import { BindingUnavailable } from "@effect-agent/thread/AgentRegistration";
|
|
6
|
+
import { DigestError } from "@effect-agent/thread/Digest";
|
|
7
|
+
import { DurableRuntimeFailpointError } from "@effect-agent/thread/DurableFailpoint";
|
|
8
|
+
import { OperationDenied } from "@effect-agent/thread/OperationAuthorizer";
|
|
9
|
+
import { AdmissionConflict, LedgerError, SettlementConflict } from "@effect-agent/thread/SubmissionLedger";
|
|
10
|
+
import { AppendConflict, FenceRejected, ThreadNotMaterialized, ThreadStoreError } from "@effect-agent/thread/ThreadStore";
|
|
11
|
+
import { Effect, Schema } from "effect";
|
|
12
|
+
declare namespace AgentWorkflow_d_exports {
|
|
13
|
+
export { Error, execute };
|
|
14
|
+
}
|
|
15
|
+
/** Schema for the exact typed failure channel of execute, suitable for Workflow.make({ error }). */
|
|
16
|
+
declare const Error: Schema.Union<readonly [typeof AgentInputError, typeof AgentOutputError, typeof AdmissionConflict, typeof AppendConflict, typeof BindingUnavailable, typeof DigestError, typeof DurableRuntimeFailpointError, typeof FenceRejected, typeof LedgerError, typeof OperationDenied, typeof SettlementConflict, typeof ThreadNotMaterialized, typeof ThreadStoreError, typeof WorkflowDispatchError, typeof WorkflowAdmissionClosed, typeof WorkflowExecutionFailure]>;
|
|
17
|
+
type Error = typeof Error.Type;
|
|
18
|
+
/**
|
|
19
|
+
* Run a registered agent inside a native Workflow.toLayer handler. One stable name identifies
|
|
20
|
+
* one submission in that parent execution. Replays verify admission identity and decode the
|
|
21
|
+
* canonical output again. Pending work suspends through Effect DurableDeferred; neither
|
|
22
|
+
* suspension nor parent interruption aborts accepted agent work. Use the host's authorized abort.
|
|
23
|
+
* Provide WorkflowAgentHost at the application boundary, sharing the parent's WorkflowEngine.
|
|
24
|
+
* Pass the exact Agent Definition instance used in runtime registration; a same-ID copy fails
|
|
25
|
+
* with BindingUnavailable before input encoding or admission.
|
|
26
|
+
*/
|
|
27
|
+
declare const execute: <Input extends Schema.Top, Output extends Schema.Top>(agent: WorkflowAgent<Input, Output>, input: Input["Type"], options: WorkflowExecuteOptions) => Effect.Effect<Output["Type"], AdmissionConflict | AgentInputError | AgentOutputError | AppendConflict | BindingUnavailable | DigestError | DurableRuntimeFailpointError | FenceRejected | LedgerError | OperationDenied | SettlementConflict | ThreadNotMaterialized | ThreadStoreError | WorkflowAdmissionClosed | WorkflowDispatchError | WorkflowExecutionFailure, WorkflowAgentHost | import("effect/unstable/workflow/WorkflowEngine").WorkflowEngine | import("effect/unstable/workflow/WorkflowEngine").WorkflowInstance | Input["EncodingServices"] | Output["DecodingServices"]>;
|
|
28
|
+
//#endregion
|
|
29
|
+
export { Error, execute, AgentWorkflow_d_exports as t };
|
|
30
|
+
//# sourceMappingURL=AgentWorkflow.d.mts.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
+
import { WorkflowDispatchError } from "./WorkflowDispatch.mjs";
|
|
3
|
+
import { n as WorkflowAgentHost, t as WorkflowAdmissionClosed } from "./WorkflowAgentHost-DOGuS1cg.mjs";
|
|
4
|
+
import { WorkflowExecutionFailure } from "./WorkflowExecution.mjs";
|
|
5
|
+
import { AgentInputError, AgentOutputError } from "@effect-agent/core/AgentError";
|
|
6
|
+
import { BindingUnavailable } from "@effect-agent/thread/AgentRegistration";
|
|
7
|
+
import { DigestError } from "@effect-agent/thread/Digest";
|
|
8
|
+
import { DurableRuntimeFailpointError } from "@effect-agent/thread/DurableFailpoint";
|
|
9
|
+
import { OperationDenied } from "@effect-agent/thread/OperationAuthorizer";
|
|
10
|
+
import { AdmissionConflict, LedgerError, SettlementConflict } from "@effect-agent/thread/SubmissionLedger";
|
|
11
|
+
import { AppendConflict, FenceRejected, ThreadNotMaterialized, ThreadStoreError } from "@effect-agent/thread/ThreadStore";
|
|
12
|
+
import { Effect, Schema } from "effect";
|
|
13
|
+
//#region src/AgentWorkflow.ts
|
|
14
|
+
var AgentWorkflow_exports = /* @__PURE__ */ __exportAll({
|
|
15
|
+
Error: () => Error,
|
|
16
|
+
execute: () => execute
|
|
17
|
+
});
|
|
18
|
+
/** Schema for the exact typed failure channel of execute, suitable for Workflow.make({ error }). */
|
|
19
|
+
const Error = Schema.Union([
|
|
20
|
+
AgentInputError,
|
|
21
|
+
AgentOutputError,
|
|
22
|
+
AdmissionConflict,
|
|
23
|
+
AppendConflict,
|
|
24
|
+
BindingUnavailable,
|
|
25
|
+
DigestError,
|
|
26
|
+
DurableRuntimeFailpointError,
|
|
27
|
+
FenceRejected,
|
|
28
|
+
LedgerError,
|
|
29
|
+
OperationDenied,
|
|
30
|
+
SettlementConflict,
|
|
31
|
+
ThreadNotMaterialized,
|
|
32
|
+
ThreadStoreError,
|
|
33
|
+
WorkflowDispatchError,
|
|
34
|
+
WorkflowAdmissionClosed,
|
|
35
|
+
WorkflowExecutionFailure
|
|
36
|
+
]);
|
|
37
|
+
/**
|
|
38
|
+
* Run a registered agent inside a native Workflow.toLayer handler. One stable name identifies
|
|
39
|
+
* one submission in that parent execution. Replays verify admission identity and decode the
|
|
40
|
+
* canonical output again. Pending work suspends through Effect DurableDeferred; neither
|
|
41
|
+
* suspension nor parent interruption aborts accepted agent work. Use the host's authorized abort.
|
|
42
|
+
* Provide WorkflowAgentHost at the application boundary, sharing the parent's WorkflowEngine.
|
|
43
|
+
* Pass the exact Agent Definition instance used in runtime registration; a same-ID copy fails
|
|
44
|
+
* with BindingUnavailable before input encoding or admission.
|
|
45
|
+
*/
|
|
46
|
+
const execute = Effect.fn("AgentWorkflow.execute")(function* (agent, input, options) {
|
|
47
|
+
return yield* (yield* WorkflowAgentHost).execute(agent, input, options);
|
|
48
|
+
});
|
|
49
|
+
//#endregion
|
|
50
|
+
export { Error, execute, AgentWorkflow_exports as t };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=AgentWorkflow.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AgentWorkflow.mjs","names":[],"sources":["../src/AgentWorkflow.ts"],"sourcesContent":["import { AgentInputError, AgentOutputError } from \"@effect-agent/core/AgentError\";\nimport { BindingUnavailable } from \"@effect-agent/thread/AgentRegistration\";\nimport { DigestError } from \"@effect-agent/thread/Digest\";\nimport { DurableRuntimeFailpointError } from \"@effect-agent/thread/DurableFailpoint\";\nimport { OperationDenied } from \"@effect-agent/thread/OperationAuthorizer\";\nimport {\n AdmissionConflict,\n LedgerError,\n SettlementConflict,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n AppendConflict,\n FenceRejected,\n ThreadNotMaterialized,\n ThreadStoreError,\n} from \"@effect-agent/thread/ThreadStore\";\nimport { Effect, Schema } from \"effect\";\n\nimport { WorkflowAdmissionClosed, WorkflowAgentHost } from \"./WorkflowAgentHost.ts\";\nimport { WorkflowDispatchError } from \"./WorkflowDispatch.ts\";\nimport {\n WorkflowExecutionFailure,\n type WorkflowAgent,\n type WorkflowExecuteOptions,\n} from \"./WorkflowExecution.ts\";\n\n/** Schema for the exact typed failure channel of execute, suitable for Workflow.make({ error }). */\nexport const Error = Schema.Union([\n AgentInputError,\n AgentOutputError,\n AdmissionConflict,\n AppendConflict,\n BindingUnavailable,\n DigestError,\n DurableRuntimeFailpointError,\n FenceRejected,\n LedgerError,\n OperationDenied,\n SettlementConflict,\n ThreadNotMaterialized,\n ThreadStoreError,\n WorkflowDispatchError,\n WorkflowAdmissionClosed,\n WorkflowExecutionFailure,\n]);\n\nexport type Error = typeof Error.Type;\n\n/**\n * Run a registered agent inside a native Workflow.toLayer handler. One stable name identifies\n * one submission in that parent execution. Replays verify admission identity and decode the\n * canonical output again. Pending work suspends through Effect DurableDeferred; neither\n * suspension nor parent interruption aborts accepted agent work. Use the host's authorized abort.\n * Provide WorkflowAgentHost at the application boundary, sharing the parent's WorkflowEngine.\n * Pass the exact Agent Definition instance used in runtime registration; a same-ID copy fails\n * with BindingUnavailable before input encoding or admission.\n */\nexport const execute = Effect.fn(\"AgentWorkflow.execute\")(function* <\n Input extends Schema.Top,\n Output extends Schema.Top,\n>(agent: WorkflowAgent<Input, Output>, input: Input[\"Type\"], options: WorkflowExecuteOptions) {\n const host = yield* WorkflowAgentHost;\n\n return yield* host.execute(agent, input, options);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,MAAa,QAAQ,OAAO,MAAM;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAaD,MAAa,UAAU,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAGxD,OAAqC,OAAsB,SAAiC;CAG5F,OAAO,QAAO,OAFM,kBAAA,CAED,QAAQ,OAAO,OAAO,OAAO;AAClD,CAAC"}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
+
import { WorkflowDispatchError, WorkflowDispatchFailpoint, WorkflowDispatchIntent, WorkflowDispatchScan, WorkflowDispatchStore, WorkflowRepairReport, WorkflowRepairTrigger, WorkflowSettlementReference, WorkflowSubmission } from "./WorkflowDispatch.mjs";
|
|
3
|
+
import { WorkflowExecutionFailure } from "./WorkflowExecution.mjs";
|
|
4
|
+
import { AgentOutputError } from "@effect-agent/core/AgentError";
|
|
5
|
+
import "@effect-agent/thread/AgentRegistration";
|
|
6
|
+
import { digestJson } from "@effect-agent/thread/Digest";
|
|
7
|
+
import { IdempotencyKey, Principal, SubmissionLedger, SubmissionLookupById } from "@effect-agent/thread/SubmissionLedger";
|
|
8
|
+
import { Cause, Context, Crypto, Effect, Exit, Layer, Option, RcMap, Ref, Result, Schema, Semaphore, Stream } from "effect";
|
|
9
|
+
import { ThreadId } from "@effect-agent/core/Identifiers";
|
|
10
|
+
import { DurableAgentRuntime, DurableRuntimeConfig, Receipt } from "@effect-agent/thread/DurableAgentRuntime";
|
|
11
|
+
import { DeploymentId } from "@effect-agent/thread/Records";
|
|
12
|
+
import { DurableDeferred, Workflow, WorkflowEngine } from "effect/unstable/workflow";
|
|
13
|
+
//#region src/internal/completion.ts
|
|
14
|
+
/** Native deferred results contain only canonical identities, never a second agent result. */
|
|
15
|
+
const workflowCompletion = (name) => DurableDeferred.make(name, { success: WorkflowSettlementReference });
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/WorkflowAgentHost.ts
|
|
18
|
+
var WorkflowAgentHost_exports = /* @__PURE__ */ __exportAll({
|
|
19
|
+
WorkflowAdmissionClosed: () => WorkflowAdmissionClosed,
|
|
20
|
+
WorkflowAgentHost: () => WorkflowAgentHost,
|
|
21
|
+
WorkflowHostConfigError: () => WorkflowHostConfigError
|
|
22
|
+
});
|
|
23
|
+
const WorkflowHostConfig = Schema.Struct({
|
|
24
|
+
deploymentId: DeploymentId,
|
|
25
|
+
principal: Principal,
|
|
26
|
+
workflowName: Schema.NonEmptyString,
|
|
27
|
+
executionConcurrency: Schema.Int.check(Schema.isBetween({
|
|
28
|
+
minimum: 1,
|
|
29
|
+
maximum: 64
|
|
30
|
+
})),
|
|
31
|
+
repairBatchSize: Schema.Int.check(Schema.isBetween({
|
|
32
|
+
minimum: 1,
|
|
33
|
+
maximum: 1e3
|
|
34
|
+
})),
|
|
35
|
+
dispatchTimeoutMillis: Schema.Int.check(Schema.isBetween({
|
|
36
|
+
minimum: 1,
|
|
37
|
+
maximum: 3e5
|
|
38
|
+
}))
|
|
39
|
+
});
|
|
40
|
+
var WorkflowHostConfigError = class extends Schema.TaggedError()("WorkflowHostConfigError", { message: Schema.String }) {};
|
|
41
|
+
var WorkflowAdmissionClosed = class extends Schema.TaggedError()("WorkflowAdmissionClosed", { message: Schema.String }) {};
|
|
42
|
+
const nativeOperation = (operation, effect) => effect.pipe(Effect.catchDefect((cause) => Effect.fail(new WorkflowDispatchError({
|
|
43
|
+
operation,
|
|
44
|
+
message: "Workflow engine operation failed",
|
|
45
|
+
cause
|
|
46
|
+
}))));
|
|
47
|
+
const makeHost = Effect.fn("WorkflowAgentHost.make")(function* (options) {
|
|
48
|
+
const config = yield* Schema.decodeUnknownEffect(WorkflowHostConfig)({
|
|
49
|
+
deploymentId: options.deploymentId,
|
|
50
|
+
principal: options.principal,
|
|
51
|
+
workflowName: options.workflowName ?? "effect-agent/Submission/v1",
|
|
52
|
+
executionConcurrency: options.executionConcurrency ?? 1,
|
|
53
|
+
repairBatchSize: options.repairBatchSize ?? 32,
|
|
54
|
+
dispatchTimeoutMillis: options.dispatchTimeoutMillis ?? 1e4
|
|
55
|
+
}).pipe(Effect.mapError((error) => new WorkflowHostConfigError({ message: error.message })));
|
|
56
|
+
const runtime = yield* DurableAgentRuntime;
|
|
57
|
+
const crypto = yield* Crypto.Crypto;
|
|
58
|
+
const runtimeConfig = yield* DurableRuntimeConfig;
|
|
59
|
+
const ledger = yield* SubmissionLedger;
|
|
60
|
+
const engine = yield* WorkflowEngine.WorkflowEngine;
|
|
61
|
+
const dispatch = yield* WorkflowDispatchStore;
|
|
62
|
+
const trigger = yield* WorkflowRepairTrigger;
|
|
63
|
+
const failpoint = yield* WorkflowDispatchFailpoint;
|
|
64
|
+
if (runtimeConfig.deploymentId !== config.deploymentId) return yield* new WorkflowHostConfigError({ message: "Workflow and durable runtime deploymentId must match" });
|
|
65
|
+
const permits = yield* Semaphore.make(config.executionConcurrency);
|
|
66
|
+
const lanes = yield* RcMap.make({ lookup: (_threadId) => Semaphore.make(1) });
|
|
67
|
+
const repairPermit = yield* Semaphore.make(1);
|
|
68
|
+
const admission = yield* Ref.make(true);
|
|
69
|
+
const nativeName = `${config.workflowName}/deployment/${config.deploymentId.length}:${config.deploymentId}`;
|
|
70
|
+
const workflow = Workflow.make(nativeName, {
|
|
71
|
+
payload: WorkflowSubmission,
|
|
72
|
+
success: WorkflowSettlementReference,
|
|
73
|
+
idempotencyKey: ({ deploymentId, receipt }) => `v1/${deploymentId.length}:${deploymentId}/${receipt.submissionId}`
|
|
74
|
+
}).annotate(Workflow.SuspendOnFailure, true);
|
|
75
|
+
const bounded = (operation, effect) => nativeOperation(operation, effect).pipe(Effect.timeout(config.dispatchTimeoutMillis), Effect.catchTag("TimeoutError", () => Effect.fail(WorkflowDispatchError.make({
|
|
76
|
+
operation,
|
|
77
|
+
message: "Workflow dispatch operation timed out; accepted work remains recoverable"
|
|
78
|
+
}))));
|
|
79
|
+
const validateReceipt = Effect.fn("WorkflowAgentHost.validateReceipt")(function* (receipt) {
|
|
80
|
+
const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId: receipt.submissionId }));
|
|
81
|
+
if (Option.isNone(found) || found.value.deploymentId !== config.deploymentId || found.value.threadId !== receipt.threadId || found.value.receiptId !== receipt.receiptId || found.value.queueSequence !== receipt.queueSequence) return yield* WorkflowDispatchError.make({
|
|
82
|
+
operation: "identity",
|
|
83
|
+
message: "Workflow Receipt does not match its authoritative deployment and Submission"
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
yield* engine.register(workflow, Effect.fn("WorkflowAgentHost.execute")(function* (payload, executionId) {
|
|
87
|
+
yield* Effect.annotateCurrentSpan({
|
|
88
|
+
"workflow.execution.id": executionId,
|
|
89
|
+
"agent.submission.id": payload.receipt.submissionId,
|
|
90
|
+
"agent.thread.id": payload.receipt.threadId
|
|
91
|
+
});
|
|
92
|
+
if (payload.deploymentId !== config.deploymentId) return yield* Effect.die("Workflow payload belongs to another deployment");
|
|
93
|
+
if (executionId !== (yield* workflow.executionId(payload))) return yield* Effect.die("Workflow execution identity does not match its Submission");
|
|
94
|
+
yield* validateReceipt(payload.receipt).pipe(Effect.orDie);
|
|
95
|
+
const initial = yield* runtime.inspectSubmissionStatus(payload.receipt).pipe(Effect.orDie);
|
|
96
|
+
if (initial._tag === "settled") return new WorkflowSettlementReference({
|
|
97
|
+
version: 1,
|
|
98
|
+
submissionId: initial.settlement.submissionId,
|
|
99
|
+
threadId: payload.receipt.threadId,
|
|
100
|
+
settlementId: initial.settlement.settlementId
|
|
101
|
+
});
|
|
102
|
+
const status = yield* Effect.scoped(Effect.gen(function* () {
|
|
103
|
+
return yield* (yield* RcMap.get(lanes, payload.receipt.threadId)).withPermit(permits.withPermit(Effect.scoped(Effect.gen(function* () {
|
|
104
|
+
yield* runtime.recoverSubmission(payload.receipt.submissionId);
|
|
105
|
+
const recovered = yield* runtime.inspectSubmissionStatus(payload.receipt);
|
|
106
|
+
if (recovered._tag === "settled") return recovered;
|
|
107
|
+
yield* runtime.processThreadHead(payload.receipt.threadId);
|
|
108
|
+
return yield* runtime.inspectSubmissionStatus(payload.receipt);
|
|
109
|
+
}))));
|
|
110
|
+
})).pipe(Effect.orDie);
|
|
111
|
+
if (status._tag === "settled") return new WorkflowSettlementReference({
|
|
112
|
+
version: 1,
|
|
113
|
+
submissionId: status.settlement.submissionId,
|
|
114
|
+
threadId: payload.receipt.threadId,
|
|
115
|
+
settlementId: status.settlement.settlementId
|
|
116
|
+
});
|
|
117
|
+
const instance = yield* WorkflowEngine.WorkflowInstance;
|
|
118
|
+
return yield* Workflow.suspend(instance);
|
|
119
|
+
}));
|
|
120
|
+
const intentFor = Effect.fn("WorkflowAgentHost.intentFor")(function* (receipt) {
|
|
121
|
+
const payload = new WorkflowSubmission({
|
|
122
|
+
version: 1,
|
|
123
|
+
deploymentId: config.deploymentId,
|
|
124
|
+
receipt
|
|
125
|
+
});
|
|
126
|
+
const executionId = yield* workflow.executionId(payload);
|
|
127
|
+
return new WorkflowDispatchIntent({
|
|
128
|
+
...payload,
|
|
129
|
+
workflowName: nativeName,
|
|
130
|
+
executionId
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
const dispatchIntent = Effect.fn("WorkflowAgentHost.dispatch")(function* (requested) {
|
|
134
|
+
let intent = requested;
|
|
135
|
+
const expected = yield* intentFor(intent.receipt);
|
|
136
|
+
if (intent.executionId !== expected.executionId || intent.deploymentId !== expected.deploymentId || intent.workflowName !== expected.workflowName) return yield* new WorkflowDispatchError({
|
|
137
|
+
operation: "dispatch",
|
|
138
|
+
message: "Dispatch identity does not match the configured Workflow"
|
|
139
|
+
});
|
|
140
|
+
yield* validateReceipt(intent.receipt);
|
|
141
|
+
yield* failpoint.hit("intent:before-persist", intent);
|
|
142
|
+
intent = yield* dispatch.put(intent);
|
|
143
|
+
yield* failpoint.hit("intent:after-persist", intent);
|
|
144
|
+
yield* failpoint.hit("launch:before", intent);
|
|
145
|
+
yield* nativeOperation("execute", engine.execute(workflow, {
|
|
146
|
+
executionId: intent.executionId,
|
|
147
|
+
payload: new WorkflowSubmission(intent),
|
|
148
|
+
discard: true
|
|
149
|
+
}).pipe(Effect.updateContext((context) => Context.omit(WorkflowEngine.WorkflowInstance)(context))));
|
|
150
|
+
yield* failpoint.hit("launch:after", intent);
|
|
151
|
+
yield* nativeOperation("resume", engine.resume(workflow, intent.executionId));
|
|
152
|
+
yield* failpoint.hit("completion:before-observe", intent);
|
|
153
|
+
const result = yield* nativeOperation("poll", engine.poll(workflow, intent.executionId));
|
|
154
|
+
yield* failpoint.hit("completion:after-observe", intent);
|
|
155
|
+
if (Option.isNone(result) || result.value._tag !== "Complete") return false;
|
|
156
|
+
if (Exit.isFailure(result.value.exit)) return yield* new WorkflowDispatchError({
|
|
157
|
+
operation: "completion",
|
|
158
|
+
message: "Native Workflow completed without a Settlement reference; intent retained",
|
|
159
|
+
cause: result.value.exit.cause
|
|
160
|
+
});
|
|
161
|
+
const status = yield* runtime.inspectSubmissionStatus(intent.receipt);
|
|
162
|
+
const reference = result.value.exit.value;
|
|
163
|
+
if (status._tag !== "settled" || reference.version !== 1 || reference.submissionId !== intent.receipt.submissionId || reference.threadId !== intent.receipt.threadId || reference.settlementId !== status.settlement.settlementId) return yield* new WorkflowDispatchError({
|
|
164
|
+
operation: "completion",
|
|
165
|
+
message: "Native completion disagrees with canonical Settlement; intent retained"
|
|
166
|
+
});
|
|
167
|
+
if (intent.completionToken !== void 0) {
|
|
168
|
+
yield* failpoint.hit("completion:before-notify", intent);
|
|
169
|
+
yield* nativeOperation("notify", DurableDeferred.succeed(workflowCompletion("settlement"), {
|
|
170
|
+
token: intent.completionToken,
|
|
171
|
+
value: reference
|
|
172
|
+
}).pipe(Effect.provideService(WorkflowEngine.WorkflowEngine, engine)));
|
|
173
|
+
yield* failpoint.hit("completion:after-notify", intent);
|
|
174
|
+
}
|
|
175
|
+
yield* failpoint.hit("cleanup:before", intent);
|
|
176
|
+
yield* dispatch.remove(intent);
|
|
177
|
+
yield* failpoint.hit("cleanup:after", intent);
|
|
178
|
+
return true;
|
|
179
|
+
}, (effect) => bounded("dispatch", effect));
|
|
180
|
+
let submissionOffset = 0;
|
|
181
|
+
let intentCursor;
|
|
182
|
+
const repair = repairPermit.withPermit(Effect.gen(function* () {
|
|
183
|
+
const discovery = yield* bounded("scanSubmissions", ledger.scanNonterminal.pipe(Stream.filter((row) => row.deploymentId === config.deploymentId), Stream.drop(submissionOffset), Stream.take(config.repairBatchSize), Stream.runCollect)).pipe(Effect.result);
|
|
184
|
+
const submissions = Result.isSuccess(discovery) ? discovery.success : [];
|
|
185
|
+
if (Result.isSuccess(discovery)) submissionOffset = submissions.length < config.repairBatchSize ? 0 : submissionOffset + submissions.length;
|
|
186
|
+
const discovered = yield* Effect.forEach(submissions, (row) => Effect.flatMap(intentFor(new Receipt(row)), dispatchIntent).pipe(Effect.result));
|
|
187
|
+
const outstanding = yield* bounded("scanIntents", dispatch.scan(new WorkflowDispatchScan({
|
|
188
|
+
deploymentId: config.deploymentId,
|
|
189
|
+
workflowName: nativeName,
|
|
190
|
+
...intentCursor === void 0 ? {} : { after: intentCursor },
|
|
191
|
+
limit: config.repairBatchSize
|
|
192
|
+
}))).pipe(Effect.result);
|
|
193
|
+
const intents = Result.isSuccess(outstanding) ? outstanding.success : [];
|
|
194
|
+
if (Result.isSuccess(outstanding)) intentCursor = intents.length < config.repairBatchSize ? void 0 : intents[intents.length - 1]?.executionId;
|
|
195
|
+
const inspected = yield* Effect.forEach(intents, (intent) => dispatchIntent(intent).pipe(Effect.result));
|
|
196
|
+
const results = [...discovered, ...inspected];
|
|
197
|
+
if (Result.isFailure(discovery)) return yield* discovery.failure;
|
|
198
|
+
if (Result.isFailure(outstanding)) return yield* outstanding.failure;
|
|
199
|
+
const failure = results.find(Result.isFailure);
|
|
200
|
+
if (failure !== void 0) return yield* Effect.fail(failure.failure);
|
|
201
|
+
return new WorkflowRepairReport({
|
|
202
|
+
discovered: submissions.length,
|
|
203
|
+
inspected: intents.length,
|
|
204
|
+
completed: results.filter((result) => Result.isSuccess(result) && result.success).length
|
|
205
|
+
});
|
|
206
|
+
}));
|
|
207
|
+
yield* trigger.register(repair.pipe(Effect.asVoid, Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.logError("Workflow dispatch repair failed; durable obligations remain", cause))));
|
|
208
|
+
yield* Effect.addFinalizer(() => Ref.set(admission, false));
|
|
209
|
+
const submit = Effect.fn("WorkflowAgentHost.submit")(function* (agent, input, options) {
|
|
210
|
+
if (!(yield* Ref.get(admission))) return yield* new WorkflowAdmissionClosed({ message: "The Workflow host is shutting down" });
|
|
211
|
+
const receipt = yield* runtime.submit(agent, input, options);
|
|
212
|
+
yield* dispatchIntent(yield* intentFor(receipt));
|
|
213
|
+
return receipt;
|
|
214
|
+
});
|
|
215
|
+
const execute = Effect.fn("AgentWorkflow.execute")(function* (agent, input, options) {
|
|
216
|
+
if ((yield* WorkflowEngine.WorkflowEngine) !== engine) return yield* new WorkflowExecutionFailure({
|
|
217
|
+
reason: "engine-mismatch",
|
|
218
|
+
message: "Agent host and parent workflow must share one WorkflowEngine Layer"
|
|
219
|
+
});
|
|
220
|
+
const name = yield* Schema.decodeUnknownEffect(Schema.NonEmptyString)(options.name).pipe(Effect.mapError(() => new WorkflowExecutionFailure({
|
|
221
|
+
reason: "invalid-name",
|
|
222
|
+
message: "Workflow agent steps need a nonempty stable name"
|
|
223
|
+
})));
|
|
224
|
+
const completion = workflowCompletion(`effect-agent/${name}`);
|
|
225
|
+
const completionToken = yield* DurableDeferred.token(completion);
|
|
226
|
+
const identity = yield* digestJson([
|
|
227
|
+
config.deploymentId,
|
|
228
|
+
config.principal,
|
|
229
|
+
completionToken
|
|
230
|
+
]).pipe(Effect.provideService(Crypto.Crypto, crypto));
|
|
231
|
+
if (!(yield* Ref.get(admission))) return yield* new WorkflowAdmissionClosed({ message: "The Workflow host is shutting down" });
|
|
232
|
+
const receipt = yield* runtime.submitRegistered({ definition: agent }, input, {
|
|
233
|
+
threadId: ThreadId.make(`workflow/${identity}`),
|
|
234
|
+
idempotencyKey: IdempotencyKey.make(identity),
|
|
235
|
+
principal: config.principal
|
|
236
|
+
});
|
|
237
|
+
yield* Effect.annotateCurrentSpan({
|
|
238
|
+
"agent.submission.id": receipt.submissionId,
|
|
239
|
+
"agent.workflow.step": name
|
|
240
|
+
});
|
|
241
|
+
yield* runtime.submissionStatus(receipt);
|
|
242
|
+
yield* dispatchIntent(new WorkflowDispatchIntent({
|
|
243
|
+
...yield* intentFor(receipt),
|
|
244
|
+
completionToken
|
|
245
|
+
}));
|
|
246
|
+
const reference = yield* DurableDeferred.await(completion);
|
|
247
|
+
const record = yield* runtime.settlementRecord(receipt);
|
|
248
|
+
if (reference.submissionId !== receipt.submissionId || reference.threadId !== receipt.threadId || reference.settlementId !== record.settlementId) return yield* new WorkflowDispatchError({
|
|
249
|
+
operation: "result",
|
|
250
|
+
message: "Workflow completion disagrees with canonical Settlement"
|
|
251
|
+
});
|
|
252
|
+
if (record.outcome === "failed") return yield* new WorkflowExecutionFailure({
|
|
253
|
+
reason: "failed",
|
|
254
|
+
message: "Agent submission failed",
|
|
255
|
+
receipt,
|
|
256
|
+
failure: record.result
|
|
257
|
+
});
|
|
258
|
+
if (record.outcome === "aborted") return yield* new WorkflowExecutionFailure({
|
|
259
|
+
reason: "aborted",
|
|
260
|
+
message: "Agent submission was aborted",
|
|
261
|
+
receipt
|
|
262
|
+
});
|
|
263
|
+
if (record.result === void 0) return yield* new WorkflowExecutionFailure({
|
|
264
|
+
reason: "missing-output",
|
|
265
|
+
message: "Completed submission has no independent output",
|
|
266
|
+
receipt
|
|
267
|
+
});
|
|
268
|
+
return yield* Schema.decodeUnknownEffect(agent.output)(record.result).pipe(Effect.mapError((cause) => new AgentOutputError({ message: `Cannot decode canonical agent output: ${cause.message}` })));
|
|
269
|
+
});
|
|
270
|
+
return WorkflowAgentHost.of({
|
|
271
|
+
execute,
|
|
272
|
+
submit,
|
|
273
|
+
awaitSettlement: runtime.awaitSettlement,
|
|
274
|
+
observe: runtime.observe,
|
|
275
|
+
abort: runtime.abort,
|
|
276
|
+
resolveApproval: runtime.resolveApproval,
|
|
277
|
+
resolveUnknown: runtime.resolveUnknown,
|
|
278
|
+
submissionStatus: runtime.submissionStatus,
|
|
279
|
+
repair,
|
|
280
|
+
executionId: Effect.fn("WorkflowAgentHost.executionId")((receipt) => intentFor(receipt).pipe(Effect.map((intent) => intent.executionId)))
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
/**
|
|
284
|
+
* Optional engine-independent host. Supply the upstream WorkflowEngine, the existing
|
|
285
|
+
* durable runtime and ledger, durable dispatch storage, and a host-owned repair trigger.
|
|
286
|
+
* Do not also start the ordinary Node worker loop. Waiter interruption only detaches;
|
|
287
|
+
* abort and resolutions retain the runtime's authorization and durable intent protocol.
|
|
288
|
+
*/
|
|
289
|
+
var WorkflowAgentHost = class WorkflowAgentHost extends Context.Service()("@effect-agent/workflow/WorkflowAgentHost") {
|
|
290
|
+
/** Drive the injected runtime, whose Layer owns executable registrations and their services. */
|
|
291
|
+
static layer(options) {
|
|
292
|
+
return Layer.effect(WorkflowAgentHost)(makeHost(options));
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
//#endregion
|
|
296
|
+
export { WorkflowHostConfigError as i, WorkflowAgentHost as n, WorkflowAgentHost_exports as r, WorkflowAdmissionClosed as t };
|
|
297
|
+
|
|
298
|
+
//# sourceMappingURL=WorkflowAgentHost-DOGuS1cg.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WorkflowAgentHost-DOGuS1cg.mjs","names":[],"sources":["../src/internal/completion.ts","../src/WorkflowAgentHost.ts"],"sourcesContent":["import { DurableDeferred } from \"effect/unstable/workflow\";\n\nimport { WorkflowSettlementReference } from \"../WorkflowDispatch.ts\";\n\n/** Native deferred results contain only canonical identities, never a second agent result. */\nexport const workflowCompletion = (name: string) =>\n DurableDeferred.make(name, { success: WorkflowSettlementReference });\n","import { AgentOutputError } from \"@effect-agent/core/AgentError\";\nimport { ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { type BindingUnavailable } from \"@effect-agent/thread/AgentRegistration\";\nimport { digestJson } from \"@effect-agent/thread/Digest\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n Receipt,\n type DurableAwaitFailure,\n type DurableSubmitAgent,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n} from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { DeploymentId } from \"@effect-agent/thread/Records\";\nimport {\n IdempotencyKey,\n Principal,\n SubmissionLedger,\n SubmissionLookupById,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n Cause,\n Context,\n Crypto,\n Effect,\n Exit,\n Layer,\n Option,\n RcMap,\n Ref,\n Result,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\nimport { DurableDeferred, Workflow, WorkflowEngine } from \"effect/unstable/workflow\";\n\nimport { workflowCompletion } from \"./internal/completion.ts\";\nimport {\n WorkflowDispatchError,\n WorkflowDispatchFailpoint,\n WorkflowDispatchIntent,\n WorkflowDispatchScan,\n WorkflowDispatchStore,\n WorkflowRepairReport,\n WorkflowRepairTrigger,\n WorkflowSettlementReference,\n WorkflowSubmission,\n} from \"./WorkflowDispatch.ts\";\nimport {\n WorkflowExecutionFailure,\n type WorkflowAgent,\n type WorkflowExecuteOptions,\n} from \"./WorkflowExecution.ts\";\n\nconst WorkflowHostConfig = Schema.Struct({\n deploymentId: DeploymentId,\n principal: Principal,\n workflowName: Schema.NonEmptyString,\n executionConcurrency: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 64 })),\n repairBatchSize: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1000 })),\n dispatchTimeoutMillis: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 300_000 })),\n});\n\nexport class WorkflowHostConfigError extends Schema.TaggedError<WorkflowHostConfigError>()(\n \"WorkflowHostConfigError\",\n { message: Schema.String },\n) {}\n\nexport class WorkflowAdmissionClosed extends Schema.TaggedError<WorkflowAdmissionClosed>()(\n \"WorkflowAdmissionClosed\",\n { message: Schema.String },\n) {}\n\nexport interface WorkflowAgentHostOptions {\n readonly deploymentId: string;\n /** Application-owned identity for submissions from AgentWorkflow.execute. */\n readonly principal: string;\n /** Stable versioned name prefix. The native name also includes deploymentId. */\n readonly workflowName?: string;\n /** Concurrent Attempts within this host Layer instance, not a fleet-wide limit. Default 1. */\n readonly executionConcurrency?: number;\n /** Maximum entries per scan per repair invocation. Default 32. */\n readonly repairBatchSize?: number;\n /** Bound each dispatch or scan, including a retrying native engine. Default 10000 ms. */\n readonly dispatchTimeoutMillis?: number;\n}\n\nexport type WorkflowRepairFailure = WorkflowDispatchError | DurableAwaitFailure;\n\nconst nativeOperation = <A, E, R>(operation: string, effect: Effect.Effect<A, E, R>) =>\n effect.pipe(\n Effect.catchDefect((cause) =>\n Effect.fail(\n new WorkflowDispatchError({\n operation,\n message: \"Workflow engine operation failed\",\n cause,\n }),\n ),\n ),\n );\n\nconst makeHost = Effect.fn(\"WorkflowAgentHost.make\")(function* (options: WorkflowAgentHostOptions) {\n const config = yield* Schema.decodeUnknownEffect(WorkflowHostConfig)({\n deploymentId: options.deploymentId,\n principal: options.principal,\n workflowName: options.workflowName ?? \"effect-agent/Submission/v1\",\n executionConcurrency: options.executionConcurrency ?? 1,\n repairBatchSize: options.repairBatchSize ?? 32,\n dispatchTimeoutMillis: options.dispatchTimeoutMillis ?? 10_000,\n }).pipe(Effect.mapError((error) => new WorkflowHostConfigError({ message: error.message })));\n\n const runtime = yield* DurableAgentRuntime;\n const crypto = yield* Crypto.Crypto;\n const runtimeConfig = yield* DurableRuntimeConfig;\n const ledger = yield* SubmissionLedger;\n const engine = yield* WorkflowEngine.WorkflowEngine;\n const dispatch = yield* WorkflowDispatchStore;\n const trigger = yield* WorkflowRepairTrigger;\n const failpoint = yield* WorkflowDispatchFailpoint;\n\n if (runtimeConfig.deploymentId !== config.deploymentId) {\n return yield* new WorkflowHostConfigError({\n message: \"Workflow and durable runtime deploymentId must match\",\n });\n }\n const permits = yield* Semaphore.make(config.executionConcurrency);\n const lanes = yield* RcMap.make({ lookup: (_threadId: ThreadId) => Semaphore.make(1) });\n const repairPermit = yield* Semaphore.make(1);\n const admission = yield* Ref.make(true);\n const nativeName = `${config.workflowName}/deployment/${config.deploymentId.length}:${config.deploymentId}`;\n\n const workflow = Workflow.make(nativeName, {\n payload: WorkflowSubmission,\n success: WorkflowSettlementReference,\n idempotencyKey: ({ deploymentId, receipt }) =>\n `v1/${deploymentId.length}:${deploymentId}/${receipt.submissionId}`,\n }).annotate(Workflow.SuspendOnFailure, true);\n\n const bounded = <A, E, R>(operation: string, effect: Effect.Effect<A, E, R>) =>\n nativeOperation(operation, effect).pipe(\n Effect.timeout(config.dispatchTimeoutMillis),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n WorkflowDispatchError.make({\n operation,\n message: \"Workflow dispatch operation timed out; accepted work remains recoverable\",\n }),\n ),\n ),\n );\n\n const validateReceipt = Effect.fn(\"WorkflowAgentHost.validateReceipt\")(function* (\n receipt: Receipt,\n ) {\n const found = yield* ledger.lookup(\n SubmissionLookupById.make({ submissionId: receipt.submissionId }),\n );\n\n if (\n Option.isNone(found) ||\n found.value.deploymentId !== config.deploymentId ||\n found.value.threadId !== receipt.threadId ||\n found.value.receiptId !== receipt.receiptId ||\n found.value.queueSequence !== receipt.queueSequence\n ) {\n return yield* WorkflowDispatchError.make({\n operation: \"identity\",\n message: \"Workflow Receipt does not match its authoritative deployment and Submission\",\n });\n }\n });\n\n // No Activities: rerun journal recovery directly on every native resume. The upstream\n // failure annotation suspends infrastructure failures and defects instead of settling them.\n yield* engine.register(\n workflow,\n Effect.fn(\"WorkflowAgentHost.execute\")(function* (payload, executionId) {\n yield* Effect.annotateCurrentSpan({\n \"workflow.execution.id\": executionId,\n \"agent.submission.id\": payload.receipt.submissionId,\n \"agent.thread.id\": payload.receipt.threadId,\n });\n if (payload.deploymentId !== config.deploymentId) {\n return yield* Effect.die(\"Workflow payload belongs to another deployment\");\n }\n if (executionId !== (yield* workflow.executionId(payload))) {\n return yield* Effect.die(\"Workflow execution identity does not match its Submission\");\n }\n yield* validateReceipt(payload.receipt).pipe(Effect.orDie);\n const initial = yield* runtime.inspectSubmissionStatus(payload.receipt).pipe(Effect.orDie);\n\n if (initial._tag === \"settled\") {\n return new WorkflowSettlementReference({\n version: 1,\n submissionId: initial.settlement.submissionId,\n threadId: payload.receipt.threadId,\n settlementId: initial.settlement.settlementId,\n });\n }\n\n const status = yield* Effect.scoped(\n Effect.gen(function* () {\n // Serialize recovery and processing for one Thread even when a ledger allows\n // same-producer takeover. Followers wait without consuming a global permit.\n const lane = yield* RcMap.get(lanes, payload.receipt.threadId);\n\n return yield* lane.withPermit(\n permits.withPermit(\n Effect.scoped(\n Effect.gen(function* () {\n yield* runtime.recoverSubmission(payload.receipt.submissionId);\n const recovered = yield* runtime.inspectSubmissionStatus(payload.receipt);\n\n if (recovered._tag === \"settled\") return recovered;\n yield* runtime.processThreadHead(payload.receipt.threadId);\n\n return yield* runtime.inspectSubmissionStatus(payload.receipt);\n }),\n ),\n ),\n );\n }),\n ).pipe(Effect.orDie);\n\n if (status._tag === \"settled\") {\n return new WorkflowSettlementReference({\n version: 1,\n submissionId: status.settlement.submissionId,\n threadId: payload.receipt.threadId,\n settlementId: status.settlement.settlementId,\n });\n }\n // Release the permit and Attempt Scope before native suspension, whose lifetime may\n // outlast this process. Completion is never inferred from an empty processing result.\n const instance = yield* WorkflowEngine.WorkflowInstance;\n\n return yield* Workflow.suspend(instance);\n }),\n );\n\n const intentFor = Effect.fn(\"WorkflowAgentHost.intentFor\")(function* (receipt: Receipt) {\n const payload = new WorkflowSubmission({\n version: 1,\n deploymentId: config.deploymentId,\n receipt,\n });\n\n const executionId = yield* workflow.executionId(payload);\n\n return new WorkflowDispatchIntent({\n ...payload,\n workflowName: nativeName,\n executionId,\n });\n });\n\n const dispatchIntent = Effect.fn(\"WorkflowAgentHost.dispatch\")(\n function* (\n requested: WorkflowDispatchIntent,\n ): Effect.fn.Return<boolean, WorkflowRepairFailure> {\n let intent = requested;\n const expected = yield* intentFor(intent.receipt);\n\n if (\n intent.executionId !== expected.executionId ||\n intent.deploymentId !== expected.deploymentId ||\n intent.workflowName !== expected.workflowName\n ) {\n return yield* new WorkflowDispatchError({\n operation: \"dispatch\",\n message: \"Dispatch identity does not match the configured Workflow\",\n });\n }\n yield* validateReceipt(intent.receipt);\n yield* failpoint.hit(\"intent:before-persist\", intent);\n intent = yield* dispatch.put(intent);\n yield* failpoint.hit(\"intent:after-persist\", intent);\n yield* failpoint.hit(\"launch:before\", intent);\n // Submission lifetime belongs to the durable host. Strip the optional parent\n // instance so upstream child interruption cannot cancel this recovery workflow.\n yield* nativeOperation(\n \"execute\",\n engine\n .execute(workflow, {\n executionId: intent.executionId,\n payload: new WorkflowSubmission(intent),\n discard: true,\n })\n .pipe(\n Effect.updateContext((context: Context.Context<never>) =>\n Context.omit(WorkflowEngine.WorkflowInstance)(context),\n ),\n ),\n );\n yield* failpoint.hit(\"launch:after\", intent);\n // Resume before suspension may be a no-op. Keep the intent and retry on a later trigger.\n yield* nativeOperation(\"resume\", engine.resume(workflow, intent.executionId));\n yield* failpoint.hit(\"completion:before-observe\", intent);\n const result = yield* nativeOperation(\"poll\", engine.poll(workflow, intent.executionId));\n\n yield* failpoint.hit(\"completion:after-observe\", intent);\n if (Option.isNone(result) || result.value._tag !== \"Complete\") return false;\n if (Exit.isFailure(result.value.exit)) {\n return yield* new WorkflowDispatchError({\n operation: \"completion\",\n message: \"Native Workflow completed without a Settlement reference; intent retained\",\n cause: result.value.exit.cause,\n });\n }\n const status = yield* runtime.inspectSubmissionStatus(intent.receipt);\n const reference = result.value.exit.value;\n\n if (\n status._tag !== \"settled\" ||\n reference.version !== 1 ||\n reference.submissionId !== intent.receipt.submissionId ||\n reference.threadId !== intent.receipt.threadId ||\n reference.settlementId !== status.settlement.settlementId\n ) {\n return yield* new WorkflowDispatchError({\n operation: \"completion\",\n message: \"Native completion disagrees with canonical Settlement; intent retained\",\n });\n }\n if (intent.completionToken !== undefined) {\n yield* failpoint.hit(\"completion:before-notify\", intent);\n yield* nativeOperation(\n \"notify\",\n DurableDeferred.succeed(workflowCompletion(\"settlement\"), {\n token: intent.completionToken,\n value: reference,\n }).pipe(Effect.provideService(WorkflowEngine.WorkflowEngine, engine)),\n );\n yield* failpoint.hit(\"completion:after-notify\", intent);\n }\n yield* failpoint.hit(\"cleanup:before\", intent);\n yield* dispatch.remove(intent);\n yield* failpoint.hit(\"cleanup:after\", intent);\n\n return true;\n },\n (effect) => bounded(\"dispatch\", effect),\n );\n\n let submissionOffset = 0;\n let intentCursor: string | undefined;\n\n const repair = repairPermit.withPermit(\n Effect.gen(function* () {\n // Respect adapter ordering, which may differ from JavaScript string comparison.\n // Deletions may defer a row until the next wrap; restarts repeat idempotent work.\n const discovery = yield* bounded(\n \"scanSubmissions\",\n ledger.scanNonterminal.pipe(\n Stream.filter((row) => row.deploymentId === config.deploymentId),\n Stream.drop(submissionOffset),\n Stream.take(config.repairBatchSize),\n Stream.runCollect,\n ),\n ).pipe(Effect.result);\n\n const submissions = Result.isSuccess(discovery) ? discovery.success : [];\n\n if (Result.isSuccess(discovery)) {\n submissionOffset =\n submissions.length < config.repairBatchSize ? 0 : submissionOffset + submissions.length;\n }\n\n const discovered = yield* Effect.forEach(submissions, (row) =>\n Effect.flatMap(intentFor(new Receipt(row)), dispatchIntent).pipe(Effect.result),\n );\n\n const outstanding = yield* bounded(\n \"scanIntents\",\n dispatch.scan(\n new WorkflowDispatchScan({\n deploymentId: config.deploymentId,\n workflowName: nativeName,\n ...(intentCursor === undefined ? {} : { after: intentCursor }),\n limit: config.repairBatchSize,\n }),\n ),\n ).pipe(Effect.result);\n\n const intents = Result.isSuccess(outstanding) ? outstanding.success : [];\n\n if (Result.isSuccess(outstanding))\n intentCursor =\n intents.length < config.repairBatchSize\n ? undefined\n : intents[intents.length - 1]?.executionId;\n\n const inspected = yield* Effect.forEach(intents, (intent) =>\n dispatchIntent(intent).pipe(Effect.result),\n );\n\n const results = [...discovered, ...inspected];\n\n if (Result.isFailure(discovery)) return yield* discovery.failure;\n if (Result.isFailure(outstanding)) return yield* outstanding.failure;\n const failure = results.find(Result.isFailure);\n\n if (failure !== undefined) return yield* Effect.fail(failure.failure);\n\n return new WorkflowRepairReport({\n discovered: submissions.length,\n inspected: intents.length,\n completed: results.filter((result) => Result.isSuccess(result) && result.success).length,\n });\n }),\n );\n\n yield* trigger.register(\n repair.pipe(\n Effect.asVoid,\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logError(\"Workflow dispatch repair failed; durable obligations remain\", cause),\n ),\n ),\n );\n yield* Effect.addFinalizer(() => Ref.set(admission, false));\n\n const submit = Effect.fn(\"WorkflowAgentHost.submit\")(function* <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ): Effect.fn.Return<\n Receipt,\n DurableSubmitFailure | WorkflowRepairFailure | WorkflowAdmissionClosed,\n InputSchema[\"EncodingServices\"]\n > {\n if (!(yield* Ref.get(admission))) {\n return yield* new WorkflowAdmissionClosed({ message: \"The Workflow host is shutting down\" });\n }\n const receipt = yield* runtime.submit(agent, input, options);\n\n yield* dispatchIntent(yield* intentFor(receipt));\n\n return receipt;\n });\n\n const execute = Effect.fn(\"AgentWorkflow.execute\")(function* <\n Input extends Schema.Top,\n Output extends Schema.Top,\n >(agent: WorkflowAgent<Input, Output>, input: Input[\"Type\"], options: WorkflowExecuteOptions) {\n const parentEngine = yield* WorkflowEngine.WorkflowEngine;\n\n if (parentEngine !== engine) {\n return yield* new WorkflowExecutionFailure({\n reason: \"engine-mismatch\",\n message: \"Agent host and parent workflow must share one WorkflowEngine Layer\",\n });\n }\n\n const name = yield* Schema.decodeUnknownEffect(Schema.NonEmptyString)(options.name).pipe(\n Effect.mapError(\n () =>\n new WorkflowExecutionFailure({\n reason: \"invalid-name\",\n message: \"Workflow agent steps need a nonempty stable name\",\n }),\n ),\n );\n\n const completion = workflowCompletion(`effect-agent/${name}`);\n const completionToken = yield* DurableDeferred.token(completion);\n\n // Agent identity and input deliberately do not participate: changing either on replay\n // must conflict with the original admission rather than launch new external work.\n const identity = yield* digestJson([\n config.deploymentId,\n config.principal,\n completionToken,\n ]).pipe(Effect.provideService(Crypto.Crypto, crypto));\n\n if (!(yield* Ref.get(admission))) {\n return yield* new WorkflowAdmissionClosed({ message: \"The Workflow host is shutting down\" });\n }\n\n const receipt = yield* runtime.submitRegistered({ definition: agent }, input, {\n threadId: ThreadId.make(`workflow/${identity}`),\n idempotencyKey: IdempotencyKey.make(identity),\n principal: config.principal,\n });\n\n yield* Effect.annotateCurrentSpan({\n \"agent.submission.id\": receipt.submissionId,\n \"agent.workflow.step\": name,\n });\n yield* runtime.submissionStatus(receipt);\n yield* dispatchIntent(\n new WorkflowDispatchIntent({ ...(yield* intentFor(receipt)), completionToken }),\n );\n\n // The deferred stores only a reference. Always reauthorize and read canonical data,\n // including on replay after the workflow engine has cached the notification.\n const reference = yield* DurableDeferred.await(completion);\n\n const record = yield* runtime.settlementRecord(receipt);\n\n if (\n reference.submissionId !== receipt.submissionId ||\n reference.threadId !== receipt.threadId ||\n reference.settlementId !== record.settlementId\n ) {\n return yield* new WorkflowDispatchError({\n operation: \"result\",\n message: \"Workflow completion disagrees with canonical Settlement\",\n });\n }\n if (record.outcome === \"failed\") {\n return yield* new WorkflowExecutionFailure({\n reason: \"failed\",\n message: \"Agent submission failed\",\n receipt,\n failure: record.result,\n });\n }\n if (record.outcome === \"aborted\") {\n return yield* new WorkflowExecutionFailure({\n reason: \"aborted\",\n message: \"Agent submission was aborted\",\n receipt,\n });\n }\n if (record.result === undefined) {\n return yield* new WorkflowExecutionFailure({\n reason: \"missing-output\",\n message: \"Completed submission has no independent output\",\n receipt,\n });\n }\n\n return yield* Schema.decodeUnknownEffect(agent.output)(record.result).pipe(\n Effect.mapError(\n (cause) =>\n new AgentOutputError({\n message: `Cannot decode canonical agent output: ${cause.message}`,\n }),\n ),\n );\n });\n\n return WorkflowAgentHost.of({\n execute,\n submit,\n awaitSettlement: runtime.awaitSettlement,\n observe: runtime.observe,\n abort: runtime.abort,\n resolveApproval: runtime.resolveApproval,\n resolveUnknown: runtime.resolveUnknown,\n submissionStatus: runtime.submissionStatus,\n repair,\n executionId: Effect.fn(\"WorkflowAgentHost.executionId\")((receipt: Receipt) =>\n intentFor(receipt).pipe(Effect.map((intent) => intent.executionId)),\n ),\n });\n});\n\n/**\n * Optional engine-independent host. Supply the upstream WorkflowEngine, the existing\n * durable runtime and ledger, durable dispatch storage, and a host-owned repair trigger.\n * Do not also start the ordinary Node worker loop. Waiter interruption only detaches;\n * abort and resolutions retain the runtime's authorization and durable intent protocol.\n */\nexport class WorkflowAgentHost extends Context.Service<\n WorkflowAgentHost,\n {\n readonly execute: <Input extends Schema.Top, Output extends Schema.Top>(\n agent: WorkflowAgent<Input, Output>,\n input: Input[\"Type\"],\n options: WorkflowExecuteOptions,\n ) => Effect.Effect<\n Output[\"Type\"],\n | DurableSubmitFailure\n | BindingUnavailable\n | DurableAwaitFailure\n | WorkflowDispatchError\n | WorkflowAdmissionClosed\n | WorkflowExecutionFailure\n | AgentOutputError,\n | Input[\"EncodingServices\"]\n | Output[\"DecodingServices\"]\n | WorkflowEngine.WorkflowInstance\n | WorkflowEngine.WorkflowEngine\n >;\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) => Effect.Effect<\n Receipt,\n DurableSubmitFailure | WorkflowRepairFailure | WorkflowAdmissionClosed,\n InputSchema[\"EncodingServices\"]\n >;\n readonly awaitSettlement: DurableAgentRuntime[\"Service\"][\"awaitSettlement\"];\n readonly observe: DurableAgentRuntime[\"Service\"][\"observe\"];\n readonly abort: DurableAgentRuntime[\"Service\"][\"abort\"];\n readonly resolveApproval: DurableAgentRuntime[\"Service\"][\"resolveApproval\"];\n readonly resolveUnknown: DurableAgentRuntime[\"Service\"][\"resolveUnknown\"];\n readonly submissionStatus: DurableAgentRuntime[\"Service\"][\"submissionStatus\"];\n readonly repair: Effect.Effect<WorkflowRepairReport, WorkflowRepairFailure>;\n readonly executionId: (receipt: Receipt) => Effect.Effect<string>;\n }\n>()(\"@effect-agent/workflow/WorkflowAgentHost\") {\n /** Drive the injected runtime, whose Layer owns executable registrations and their services. */\n static layer(options: WorkflowAgentHostOptions) {\n return Layer.effect(WorkflowAgentHost)(makeHost(options));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAKA,MAAa,sBAAsB,SACjC,gBAAgB,KAAK,MAAM,EAAE,SAAS,4BAA4B,CAAC;;;;;;;;ACiDrE,MAAM,qBAAqB,OAAO,OAAO;CACvC,cAAc;CACd,WAAW;CACX,cAAc,OAAO;CACrB,sBAAsB,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAG,CAAC,CAAC;CACpF,iBAAiB,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAK,CAAC,CAAC;CACjF,uBAAuB,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAQ,CAAC,CAAC;AAC5F,CAAC;AAED,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CACxF,2BACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;AAEH,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CACxF,2BACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;AAkBH,MAAM,mBAA4B,WAAmB,WACnD,OAAO,KACL,OAAO,a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ACtC,WAAW;GACX,SAAS;EACX,CAAC;EAEH,IAAI,OAAO,YAAY,UACrB,OAAO,OAAO,IAAI,yBAAyB;GACzC,QAAQ;GACR,SAAS;GACT;GACA,SAAS,OAAO;EAClB,CAAC;EAEH,IAAI,OAAO,YAAY,WACrB,OAAO,OAAO,IAAI,yBAAyB;GACzC,QAAQ;GACR,SAAS;GACT;EACF,CAAC;EAEH,IAAI,OAAO,WAAW,KAAA,GACpB,OAAO,OAAO,IAAI,yBAAyB;GACzC,QAAQ;GACR,SAAS;GACT;EACF,CAAC;EAGH,OAAO,OAAO,OAAO,oBAAoB,MAAM,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,KACpE,OAAO,UACJ,UACC,IAAI,iBAAiB,EACnB,SAAS,yCAAyC,MAAM,UAC1D,CAAC,CACL,CACF;CACF,CAAC;CAED,OAAO,kBAAkB,GAAG;EAC1B;EACA;EACA,iBAAiB,QAAQ;EACzB,SAAS,QAAQ;EACjB,OAAO,QAAQ;EACf,iBAAiB,QAAQ;EACzB,gBAAgB,QAAQ;EACxB,kBAAkB,QAAQ;EAC1B;EACA,aAAa,OAAO,GAAG,+BAA+B,CAAC,EAAE,YACvD,UAAU,OAAO,CAAC,CAAC,KAAK,OAAO,KAAK,WAAW,OAAO,WAAW,CAAC,CACpE;CACF,CAAC;AACH,CAAC;;;;;;;AAQD,IAAa,oBAAb,MAAa,0BAA0B,QAAQ,QAuC7C,CAAC,CAAC,0CAA0C,CAAC,CAAC;;CAE9C,OAAO,MAAM,SAAmC;EAC9C,OAAO,MAAM,OAAO,iBAAiB,CAAC,CAAC,SAAS,OAAO,CAAC;CAC1D;AACF"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { WorkflowDispatchError, WorkflowDispatchStore, WorkflowRepairReport, WorkflowRepairTrigger } from "./WorkflowDispatch.mjs";
|
|
2
|
+
import { WorkflowAgent, WorkflowExecuteOptions, WorkflowExecutionFailure } from "./WorkflowExecution.mjs";
|
|
3
|
+
import { AgentOutputError } from "@effect-agent/core/AgentError";
|
|
4
|
+
import { BindingUnavailable } from "@effect-agent/thread/AgentRegistration";
|
|
5
|
+
import { SubmissionLedger } from "@effect-agent/thread/SubmissionLedger";
|
|
6
|
+
import { Cause, Context, Crypto, Effect, Layer, Schema } from "effect";
|
|
7
|
+
import { DurableAgentRuntime, DurableAwaitFailure, DurableRuntimeConfig, DurableSubmitAgent, DurableSubmitFailure, DurableSubmitOptions, Receipt } from "@effect-agent/thread/DurableAgentRuntime";
|
|
8
|
+
import { WorkflowEngine } from "effect/unstable/workflow";
|
|
9
|
+
declare namespace WorkflowAgentHost_d_exports {
|
|
10
|
+
export { WorkflowAdmissionClosed, WorkflowAgentHost, WorkflowAgentHostOptions, WorkflowHostConfigError, WorkflowRepairFailure };
|
|
11
|
+
}
|
|
12
|
+
declare const WorkflowHostConfigError_base: Schema.Class<WorkflowHostConfigError, Schema.TaggedStruct<"WorkflowHostConfigError", {
|
|
13
|
+
readonly message: Schema.String;
|
|
14
|
+
}>, Cause.YieldableError>;
|
|
15
|
+
declare class WorkflowHostConfigError extends WorkflowHostConfigError_base {}
|
|
16
|
+
declare const WorkflowAdmissionClosed_base: Schema.Class<WorkflowAdmissionClosed, Schema.TaggedStruct<"WorkflowAdmissionClosed", {
|
|
17
|
+
readonly message: Schema.String;
|
|
18
|
+
}>, Cause.YieldableError>;
|
|
19
|
+
declare class WorkflowAdmissionClosed extends WorkflowAdmissionClosed_base {}
|
|
20
|
+
interface WorkflowAgentHostOptions {
|
|
21
|
+
readonly deploymentId: string;
|
|
22
|
+
/** Application-owned identity for submissions from AgentWorkflow.execute. */
|
|
23
|
+
readonly principal: string;
|
|
24
|
+
/** Stable versioned name prefix. The native name also includes deploymentId. */
|
|
25
|
+
readonly workflowName?: string;
|
|
26
|
+
/** Concurrent Attempts within this host Layer instance, not a fleet-wide limit. Default 1. */
|
|
27
|
+
readonly executionConcurrency?: number;
|
|
28
|
+
/** Maximum entries per scan per repair invocation. Default 32. */
|
|
29
|
+
readonly repairBatchSize?: number;
|
|
30
|
+
/** Bound each dispatch or scan, including a retrying native engine. Default 10000 ms. */
|
|
31
|
+
readonly dispatchTimeoutMillis?: number;
|
|
32
|
+
}
|
|
33
|
+
type WorkflowRepairFailure = WorkflowDispatchError | DurableAwaitFailure;
|
|
34
|
+
declare const WorkflowAgentHost_base: Context.ServiceClass<WorkflowAgentHost, "@effect-agent/workflow/WorkflowAgentHost", {
|
|
35
|
+
readonly execute: <Input extends Schema.Top, Output extends Schema.Top>(agent: WorkflowAgent<Input, Output>, input: Input["Type"], options: WorkflowExecuteOptions) => Effect.Effect<Output["Type"], DurableSubmitFailure | BindingUnavailable | DurableAwaitFailure | WorkflowDispatchError | WorkflowAdmissionClosed | WorkflowExecutionFailure | AgentOutputError, Input["EncodingServices"] | Output["DecodingServices"] | WorkflowEngine.WorkflowInstance | WorkflowEngine.WorkflowEngine>;
|
|
36
|
+
readonly submit: <InputSchema extends Schema.Top>(agent: DurableSubmitAgent<InputSchema>, input: InputSchema["Type"], options: DurableSubmitOptions) => Effect.Effect<Receipt, DurableSubmitFailure | WorkflowRepairFailure | WorkflowAdmissionClosed, InputSchema["EncodingServices"]>;
|
|
37
|
+
readonly awaitSettlement: DurableAgentRuntime["Service"]["awaitSettlement"];
|
|
38
|
+
readonly observe: DurableAgentRuntime["Service"]["observe"];
|
|
39
|
+
readonly abort: DurableAgentRuntime["Service"]["abort"];
|
|
40
|
+
readonly resolveApproval: DurableAgentRuntime["Service"]["resolveApproval"];
|
|
41
|
+
readonly resolveUnknown: DurableAgentRuntime["Service"]["resolveUnknown"];
|
|
42
|
+
readonly submissionStatus: DurableAgentRuntime["Service"]["submissionStatus"];
|
|
43
|
+
readonly repair: Effect.Effect<WorkflowRepairReport, WorkflowRepairFailure>;
|
|
44
|
+
readonly executionId: (receipt: Receipt) => Effect.Effect<string>;
|
|
45
|
+
}>;
|
|
46
|
+
/**
|
|
47
|
+
* Optional engine-independent host. Supply the upstream WorkflowEngine, the existing
|
|
48
|
+
* durable runtime and ledger, durable dispatch storage, and a host-owned repair trigger.
|
|
49
|
+
* Do not also start the ordinary Node worker loop. Waiter interruption only detaches;
|
|
50
|
+
* abort and resolutions retain the runtime's authorization and durable intent protocol.
|
|
51
|
+
*/
|
|
52
|
+
declare class WorkflowAgentHost extends WorkflowAgentHost_base {
|
|
53
|
+
/** Drive the injected runtime, whose Layer owns executable registrations and their services. */
|
|
54
|
+
static layer(options: WorkflowAgentHostOptions): Layer.Layer<WorkflowAgentHost, WorkflowHostConfigError, Crypto.Crypto | DurableAgentRuntime | DurableRuntimeConfig | SubmissionLedger | WorkflowDispatchStore | WorkflowEngine.WorkflowEngine | WorkflowRepairTrigger>;
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { WorkflowAdmissionClosed, WorkflowAgentHost, WorkflowAgentHostOptions, WorkflowHostConfigError, WorkflowRepairFailure, WorkflowAgentHost_d_exports as t };
|
|
58
|
+
//# sourceMappingURL=WorkflowAgentHost.d.mts.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import "./WorkflowDispatch.mjs";
|
|
2
|
+
import { i as WorkflowHostConfigError, n as WorkflowAgentHost, t as WorkflowAdmissionClosed } from "./WorkflowAgentHost-DOGuS1cg.mjs";
|
|
3
|
+
import "./WorkflowExecution.mjs";
|
|
4
|
+
export { WorkflowAdmissionClosed, WorkflowAgentHost, WorkflowHostConfigError };
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { Context, Effect, Schema, Scope } from "effect";
|
|
2
|
+
import { Receipt } from "@effect-agent/thread/DurableAgentRuntime";
|
|
3
|
+
declare namespace WorkflowDispatch_d_exports {
|
|
4
|
+
export { WorkflowDispatchError, WorkflowDispatchFailpoint, WorkflowDispatchFailpointLocation, WorkflowDispatchIntent, WorkflowDispatchScan, WorkflowDispatchStore, WorkflowRepairReport, WorkflowRepairTrigger, WorkflowSettlementReference, WorkflowSubmission };
|
|
5
|
+
}
|
|
6
|
+
declare const WorkflowSubmission_base: Schema.Class<WorkflowSubmission, Schema.Struct<{
|
|
7
|
+
readonly version: Schema.Literal<1>;
|
|
8
|
+
readonly deploymentId: Schema.brand<Schema.NonEmptyString, "@effect-agent/thread/DeploymentId">;
|
|
9
|
+
readonly receipt: typeof Receipt;
|
|
10
|
+
}>, {}>;
|
|
11
|
+
/** Only identities cross the Workflow boundary; the agent journal owns the outcome. */
|
|
12
|
+
declare class WorkflowSubmission extends WorkflowSubmission_base {}
|
|
13
|
+
declare const WorkflowSettlementReference_base: Schema.Class<WorkflowSettlementReference, Schema.Struct<{
|
|
14
|
+
readonly version: Schema.Literal<1>;
|
|
15
|
+
readonly submissionId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/SubmissionId">;
|
|
16
|
+
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
17
|
+
readonly settlementId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/SettlementId">;
|
|
18
|
+
}>, {}>;
|
|
19
|
+
declare class WorkflowSettlementReference extends WorkflowSettlementReference_base {}
|
|
20
|
+
declare const WorkflowDispatchIntent_base: Schema.Class<WorkflowDispatchIntent, Schema.Struct<{
|
|
21
|
+
readonly version: Schema.Literal<1>;
|
|
22
|
+
readonly deploymentId: Schema.brand<Schema.NonEmptyString, "@effect-agent/thread/DeploymentId">;
|
|
23
|
+
readonly receipt: typeof Receipt;
|
|
24
|
+
readonly workflowName: Schema.NonEmptyString;
|
|
25
|
+
readonly executionId: Schema.NonEmptyString;
|
|
26
|
+
/** One workflow step owns this submission. Repair must notify it before removing the intent. */
|
|
27
|
+
readonly completionToken: Schema.optionalKey<Schema.brand<Schema.String, "~effect/workflow/DurableDeferred/Token">>;
|
|
28
|
+
}>, {}>;
|
|
29
|
+
/** Retained until native success has been checked against the canonical Settlement. */
|
|
30
|
+
declare class WorkflowDispatchIntent extends WorkflowDispatchIntent_base {}
|
|
31
|
+
declare const WorkflowDispatchError_base: Schema.Class<WorkflowDispatchError, Schema.TaggedStruct<"WorkflowDispatchError", {
|
|
32
|
+
readonly operation: Schema.String;
|
|
33
|
+
readonly message: Schema.String;
|
|
34
|
+
readonly cause: Schema.optionalKey<Schema.Defect>;
|
|
35
|
+
}>, import("effect/Cause").YieldableError>;
|
|
36
|
+
declare class WorkflowDispatchError extends WorkflowDispatchError_base {}
|
|
37
|
+
declare const WorkflowDispatchScan_base: Schema.Class<WorkflowDispatchScan, Schema.Struct<{
|
|
38
|
+
readonly deploymentId: Schema.brand<Schema.NonEmptyString, "@effect-agent/thread/DeploymentId">;
|
|
39
|
+
readonly workflowName: Schema.NonEmptyString;
|
|
40
|
+
readonly after: Schema.optionalKey<Schema.String>;
|
|
41
|
+
readonly limit: Schema.Int;
|
|
42
|
+
}>, {}>;
|
|
43
|
+
declare class WorkflowDispatchScan extends WorkflowDispatchScan_base {}
|
|
44
|
+
declare const WorkflowDispatchStore_base: Context.ServiceClass<WorkflowDispatchStore, "@effect-agent/workflow/WorkflowDispatchStore", {
|
|
45
|
+
readonly put: (intent: WorkflowDispatchIntent) => Effect.Effect<WorkflowDispatchIntent, WorkflowDispatchError>;
|
|
46
|
+
readonly scan: (request: WorkflowDispatchScan) => Effect.Effect<ReadonlyArray<WorkflowDispatchIntent>, WorkflowDispatchError>;
|
|
47
|
+
readonly remove: (intent: WorkflowDispatchIntent) => Effect.Effect<void, WorkflowDispatchError>;
|
|
48
|
+
}>;
|
|
49
|
+
/**
|
|
50
|
+
* Adapter-private outbox. `put` returns the stored intent, preserving an existing completion
|
|
51
|
+
* token when omitted and allowing its one-time attachment. Different identities or tokens
|
|
52
|
+
* conflict. `remove` must compare the entire intent, so a concurrent token attachment cannot
|
|
53
|
+
* be lost. `scan` returns at most limit rows in executionId order, after
|
|
54
|
+
* the exclusive cursor, filtered by deployment and workflow. All writes are durable
|
|
55
|
+
* before returning. No transcript, outcome, or native engine storage belongs here.
|
|
56
|
+
*/
|
|
57
|
+
declare class WorkflowDispatchStore extends WorkflowDispatchStore_base {}
|
|
58
|
+
declare const WorkflowRepairTrigger_base: Context.ServiceClass<WorkflowRepairTrigger, "@effect-agent/workflow/WorkflowRepairTrigger", {
|
|
59
|
+
readonly register: (repair: Effect.Effect<void>) => Effect.Effect<void, never, Scope.Scope>;
|
|
60
|
+
}>;
|
|
61
|
+
/**
|
|
62
|
+
* Host-owned durable repair trigger. Register before admission opens. The host must
|
|
63
|
+
* invoke repair at startup and repeatedly after lost hints or process loss. A Node
|
|
64
|
+
* deployment may use a scoped poller; other hosts may use alarms or durable jobs.
|
|
65
|
+
* Stop invoking the callback when this Scope closes. The shared driver starts no loop.
|
|
66
|
+
*/
|
|
67
|
+
declare class WorkflowRepairTrigger extends WorkflowRepairTrigger_base {}
|
|
68
|
+
declare const WorkflowDispatchFailpointLocation: Schema.Literals<readonly ["intent:before-persist", "intent:after-persist", "launch:before", "launch:after", "completion:before-observe", "completion:after-observe", "completion:before-notify", "completion:after-notify", "cleanup:before", "cleanup:after"]>;
|
|
69
|
+
type WorkflowDispatchFailpointLocation = typeof WorkflowDispatchFailpointLocation.Type;
|
|
70
|
+
declare const WorkflowDispatchFailpoint: Context.Reference<{
|
|
71
|
+
readonly hit: (location: WorkflowDispatchFailpointLocation, intent: WorkflowDispatchIntent) => Effect.Effect<void, WorkflowDispatchError>;
|
|
72
|
+
}>;
|
|
73
|
+
declare const WorkflowRepairReport_base: Schema.Class<WorkflowRepairReport, Schema.Struct<{
|
|
74
|
+
readonly discovered: Schema.Int;
|
|
75
|
+
readonly inspected: Schema.Int;
|
|
76
|
+
readonly completed: Schema.Int;
|
|
77
|
+
}>, {}>;
|
|
78
|
+
declare class WorkflowRepairReport extends WorkflowRepairReport_base {}
|
|
79
|
+
//#endregion
|
|
80
|
+
export { WorkflowDispatchError, WorkflowDispatchFailpoint, WorkflowDispatchFailpointLocation, WorkflowDispatchIntent, WorkflowDispatchScan, WorkflowDispatchStore, WorkflowRepairReport, WorkflowRepairTrigger, WorkflowSettlementReference, WorkflowSubmission, WorkflowDispatch_d_exports as t };
|
|
81
|
+
//# sourceMappingURL=WorkflowDispatch.d.mts.map
|