@effect-agent/platform-node 0.1.0-beta.6 → 0.1.0-beta.60

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 (37) hide show
  1. package/dist/NodeDurableAgentRuntime-CFElFzNF.d.mts +179 -0
  2. package/dist/NodeDurableAgentRuntime.d.mts +2 -0
  3. package/dist/NodeDurableAgentRuntime.mjs +221 -0
  4. package/dist/NodeDurableAgentRuntime.mjs.map +1 -0
  5. package/dist/NodeDurableHost-BMSajuQn.mjs +194 -0
  6. package/dist/NodeDurableHost-BMSajuQn.mjs.map +1 -0
  7. package/dist/NodeDurableHost.d.mts +168 -0
  8. package/dist/NodeDurableHost.mjs +2 -0
  9. package/dist/NodeScheduling.d.mts +22 -0
  10. package/dist/NodeScheduling.mjs +59 -0
  11. package/dist/NodeScheduling.mjs.map +1 -0
  12. package/dist/NodeSubscriptions.d.mts +27 -0
  13. package/dist/NodeSubscriptions.mjs +74 -0
  14. package/dist/NodeSubscriptions.mjs.map +1 -0
  15. package/dist/NodeWakeScheduler-4ZeXYwPu.d.mts +27 -0
  16. package/dist/NodeWakeScheduler.d.mts +2 -0
  17. package/dist/NodeWakeScheduler.mjs +65 -0
  18. package/dist/NodeWakeScheduler.mjs.map +1 -0
  19. package/dist/NodeWorkflow.d.mts +27 -0
  20. package/dist/NodeWorkflow.mjs +159 -0
  21. package/dist/NodeWorkflow.mjs.map +1 -0
  22. package/dist/index.d.mts +6 -214
  23. package/dist/index.mjs +6 -286
  24. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  25. package/package.json +1 -45
  26. package/src/NodeDurableAgentRuntime.ts +596 -0
  27. package/src/NodeDurableHost.ts +361 -0
  28. package/src/NodeScheduling.ts +121 -0
  29. package/src/NodeSubscriptions.ts +162 -0
  30. package/src/{wake-scheduler.ts → NodeWakeScheduler.ts} +32 -17
  31. package/src/NodeWorkflow.ts +258 -0
  32. package/src/index.ts +5 -3
  33. package/src/internal/message-delivery.ts +53 -0
  34. package/src/internal/prepared-admission.ts +81 -0
  35. package/dist/index.mjs.map +0 -1
  36. package/src/host.ts +0 -215
  37. package/src/layers.ts +0 -381
@@ -0,0 +1,74 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { n as NodeDurableHost, o as NodeAdmission, s as makeNodePreparedInputAdmission } from "./NodeDurableHost-BMSajuQn.mjs";
3
+ import { ScheduledInputAdmission } from "@effect-agent/thread/Schedule";
4
+ import { NodeCrypto } from "@effect/platform-node";
5
+ import { Cause, Duration, Effect, Exit, Layer, Option } from "effect";
6
+ import { PreparedInputAdmission } from "@effect-agent/thread/PreparedInputAdmission";
7
+ import "@effect-agent/thread/EventSource";
8
+ import { SubscriptionStore, defaultSubscriptionLimits } from "@effect-agent/thread/Subscription";
9
+ import "@effect-agent/thread/SubscriptionInput";
10
+ import { SubscriptionDriver, SubscriptionIntake, Subscriptions } from "@effect-agent/thread/Subscriptions";
11
+ //#region src/NodeSubscriptions.ts
12
+ var NodeSubscriptions_exports = /* @__PURE__ */ __exportAll({
13
+ NodeSubscriptions: () => NodeSubscriptions,
14
+ nodePreparedInputAdmissionLayer: () => nodePreparedInputAdmissionLayer,
15
+ nodeScheduledInputAdmissionLayer: () => nodeScheduledInputAdmissionLayer
16
+ });
17
+ /** Ordinary prepared admission through the Scope-owned Node host gate. */
18
+ const nodePreparedInputAdmissionLayer = Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(Layer.provide(Layer.effect(NodeAdmission, NodeDurableHost)));
19
+ const preparedFromSchedule = (envelope) => ({
20
+ schemaVersion: 1,
21
+ threadId: envelope.threadId,
22
+ deliveryPrincipal: envelope.deliveryPrincipal,
23
+ ...envelope.admissionGroup === void 0 ? {} : { admissionGroup: envelope.admissionGroup },
24
+ ...envelope.admissionFence === void 0 ? {} : { admissionFence: envelope.admissionFence },
25
+ agentId: envelope.agentId,
26
+ definitions: envelope.definitions,
27
+ input: envelope.input,
28
+ inputDigest: envelope.inputDigest,
29
+ admissionKey: envelope.admissionKey,
30
+ authorization: envelope.authorization
31
+ });
32
+ const nodeScheduledInputAdmissionLayer = Layer.effect(ScheduledInputAdmission, Effect.map(PreparedInputAdmission, (admission) => ScheduledInputAdmission.of({ submit: (envelope) => admission.submit(preparedFromSchedule(envelope)) }))).pipe(Layer.provide(nodePreparedInputAdmissionLayer));
33
+ const reportPassFailure = (cause) => Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.logWarning("Node subscription pass failed").pipe(Effect.annotateLogs({ failureTag: Option.match(Cause.findErrorOption(cause), {
34
+ onNone: () => "Defect",
35
+ onSome: (error) => error._tag
36
+ }) }), Effect.as(false));
37
+ const nodeSubscriptionDriverLayer = (limits) => Layer.effectDiscard(Effect.gen(function* () {
38
+ const driver = yield* SubscriptionDriver;
39
+ const store = yield* SubscriptionStore;
40
+ const run = Effect.gen(function* () {
41
+ while (true) {
42
+ if (!(yield* driver.runDue.pipe(Effect.map((pass) => pass.failed === 0), Effect.catchCause(reportPassFailure)))) {
43
+ yield* Effect.sleep(Duration.millis(limits.retryMillis));
44
+ continue;
45
+ }
46
+ const deadline = yield* store.nextDeadline.pipe(Effect.exit);
47
+ if (Exit.isFailure(deadline)) {
48
+ yield* reportPassFailure(deadline.cause);
49
+ yield* Effect.sleep(Duration.millis(limits.retryMillis));
50
+ continue;
51
+ }
52
+ const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
53
+ const delay = deadline.value === null ? limits.retryMillis : Math.max(1, Math.min(deadline.value - nowMillis, limits.retryMillis));
54
+ yield* Effect.sleep(Duration.millis(delay));
55
+ }
56
+ });
57
+ yield* Effect.forkScoped(run);
58
+ }));
59
+ /**
60
+ * One Scope-owned subscription partition in the sole process owning its SQLite database.
61
+ * Indexed polling repairs restart and lost wake state; closing the Scope interrupts the driver.
62
+ */
63
+ var NodeSubscriptions = class {
64
+ static layer(options = {}) {
65
+ const limits = options.limits ?? defaultSubscriptionLimits;
66
+ const publicServices = Layer.merge(Subscriptions.layer(limits), SubscriptionIntake.layer(limits));
67
+ const driver = nodeSubscriptionDriverLayer(limits).pipe(Layer.provide(SubscriptionDriver.layer(limits)));
68
+ return Layer.merge(publicServices, driver).pipe(Layer.provide(nodePreparedInputAdmissionLayer), Layer.provide(NodeCrypto.layer));
69
+ }
70
+ };
71
+ //#endregion
72
+ export { NodeSubscriptions, nodePreparedInputAdmissionLayer, nodeScheduledInputAdmissionLayer, NodeSubscriptions_exports as t };
73
+
74
+ //# sourceMappingURL=NodeSubscriptions.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NodeSubscriptions.mjs","names":[],"sources":["../src/NodeSubscriptions.ts"],"sourcesContent":["import { type EventSources } from \"@effect-agent/thread/EventSource\";\nimport { PreparedInputAdmission } from \"@effect-agent/thread/PreparedInputAdmission\";\nimport { type ScheduledEnvelope, ScheduledInputAdmission } from \"@effect-agent/thread/Schedule\";\nimport {\n type PreparedInput,\n type SubscriptionAuthorizer,\n type SubscriptionError,\n type SubscriptionLimits,\n type SubscriptionStoreFailure,\n SubscriptionStore,\n defaultSubscriptionLimits,\n} from \"@effect-agent/thread/Subscription\";\nimport { type SubscriptionInputBindings } from \"@effect-agent/thread/SubscriptionInput\";\nimport {\n SubscriptionDriver,\n SubscriptionIntake,\n Subscriptions,\n} from \"@effect-agent/thread/Subscriptions\";\nimport { NodeCrypto } from \"@effect/platform-node\";\nimport { Cause, Duration, Effect, Exit, Layer, Option } from \"effect\";\n\nimport { makeNodePreparedInputAdmission, NodeAdmission } from \"./internal/prepared-admission.ts\";\nimport { NodeDurableHost } from \"./NodeDurableHost.ts\";\n\n/** Ordinary prepared admission through the Scope-owned Node host gate. */\nexport const nodePreparedInputAdmissionLayer: Layer.Layer<\n PreparedInputAdmission,\n never,\n NodeDurableHost\n> = Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(\n Layer.provide(Layer.effect(NodeAdmission, NodeDurableHost)),\n);\n\nconst preparedFromSchedule = (envelope: ScheduledEnvelope): PreparedInput => ({\n schemaVersion: 1,\n threadId: envelope.threadId,\n deliveryPrincipal: envelope.deliveryPrincipal,\n ...(envelope.admissionGroup === undefined ? {} : { admissionGroup: envelope.admissionGroup }),\n ...(envelope.admissionFence === undefined ? {} : { admissionFence: envelope.admissionFence }),\n agentId: envelope.agentId,\n definitions: envelope.definitions,\n input: envelope.input,\n inputDigest: envelope.inputDigest,\n admissionKey: envelope.admissionKey,\n authorization: envelope.authorization,\n});\n\n/** Compatibility adapter retaining the public scheduling admission port. */\nconst nodeScheduledInputAdmissionFromPreparedLayer: Layer.Layer<\n ScheduledInputAdmission,\n never,\n PreparedInputAdmission\n> = Layer.effect(\n ScheduledInputAdmission,\n Effect.map(PreparedInputAdmission, (admission) =>\n ScheduledInputAdmission.of({\n submit: (envelope) => admission.submit(preparedFromSchedule(envelope)),\n }),\n ),\n);\n\nexport const nodeScheduledInputAdmissionLayer: Layer.Layer<\n ScheduledInputAdmission,\n never,\n NodeDurableHost\n> = nodeScheduledInputAdmissionFromPreparedLayer.pipe(\n Layer.provide(nodePreparedInputAdmissionLayer),\n);\n\nconst reportPassFailure = (cause: Cause.Cause<SubscriptionStoreFailure>): Effect.Effect<boolean> =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logWarning(\"Node subscription pass failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n Effect.as(false),\n );\n\nconst nodeSubscriptionDriverLayer = (\n limits: SubscriptionLimits,\n): Layer.Layer<never, never, SubscriptionDriver | SubscriptionStore> =>\n Layer.effectDiscard(\n Effect.gen(function* () {\n const driver = yield* SubscriptionDriver;\n const store = yield* SubscriptionStore;\n\n const run = Effect.gen(function* () {\n while (true) {\n const passSucceeded = yield* driver.runDue.pipe(\n Effect.map((pass) => pass.failed === 0),\n Effect.catchCause(reportPassFailure),\n );\n\n if (!passSucceeded) {\n yield* Effect.sleep(Duration.millis(limits.retryMillis));\n continue;\n }\n\n const deadline = yield* store.nextDeadline.pipe(Effect.exit);\n\n if (Exit.isFailure(deadline)) {\n yield* reportPassFailure(deadline.cause);\n yield* Effect.sleep(Duration.millis(limits.retryMillis));\n continue;\n }\n\n const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\n const delay =\n deadline.value === null\n ? limits.retryMillis\n : Math.max(1, Math.min(deadline.value - nowMillis, limits.retryMillis));\n\n yield* Effect.sleep(Duration.millis(delay));\n }\n });\n\n yield* Effect.forkScoped(run);\n }),\n );\n\nexport interface NodeSubscriptionsOptions {\n readonly limits?: SubscriptionLimits | undefined;\n}\n\n/**\n * One Scope-owned subscription partition in the sole process owning its SQLite database.\n * Indexed polling repairs restart and lost wake state; closing the Scope interrupts the driver.\n */\nexport class NodeSubscriptions {\n static layer(\n options: NodeSubscriptionsOptions = {},\n ): Layer.Layer<\n Subscriptions | SubscriptionIntake,\n SubscriptionError,\n | NodeDurableHost\n | SubscriptionStore\n | SubscriptionAuthorizer\n | EventSources\n | SubscriptionInputBindings\n > {\n const limits = options.limits ?? defaultSubscriptionLimits;\n\n const publicServices = Layer.merge(\n Subscriptions.layer(limits),\n SubscriptionIntake.layer(limits),\n );\n\n const driver = nodeSubscriptionDriverLayer(limits).pipe(\n Layer.provide(SubscriptionDriver.layer(limits)),\n );\n\n return Layer.merge(publicServices, driver).pipe(\n Layer.provide(nodePreparedInputAdmissionLayer),\n Layer.provide(NodeCrypto.layer),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,MAAa,kCAIT,MAAM,OAAO,wBAAwB,8BAA8B,CAAC,CAAC,KACvE,MAAM,QAAQ,MAAM,OAAO,eAAe,eAAe,CAAC,CAC5D;AAEA,MAAM,wBAAwB,cAAgD;CAC5E,eAAe;CACf,UAAU,SAAS;CACnB,mBAAmB,SAAS;CAC5B,GAAI,SAAS,mBAAmB,KAAA,IAAY,C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AAY,OAAO,OAAO,WAAW,UAAU,MAAM,iBAAiB;GAE5E,MAAM,QACJ,SAAS,UAAU,OACf,OAAO,cACP,KAAK,IAAI,GAAG,KAAK,IAAI,SAAS,QAAQ,WAAW,OAAO,WAAW,CAAC;GAE1E,OAAO,OAAO,MAAM,SAAS,OAAO,KAAK,CAAC;EAC5C;CACF,CAAC;CAED,OAAO,OAAO,WAAW,GAAG;AAC9B,CAAC,CACH;;;;;AAUF,IAAa,oBAAb,MAA+B;CAC7B,OAAO,MACL,UAAoC,CAAC,GASrC;EACA,MAAM,SAAS,QAAQ,UAAU;EAEjC,MAAM,iBAAiB,MAAM,MAC3B,cAAc,MAAM,MAAM,GAC1B,mBAAmB,MAAM,MAAM,CACjC;EAEA,MAAM,SAAS,4BAA4B,MAAM,CAAC,CAAC,KACjD,MAAM,QAAQ,mBAAmB,MAAM,MAAM,CAAC,CAChD;EAEA,OAAO,MAAM,MAAM,gBAAgB,MAAM,CAAC,CAAC,KACzC,MAAM,QAAQ,+BAA+B,GAC7C,MAAM,QAAQ,WAAW,KAAK,CAChC;CACF;AACF"}
@@ -0,0 +1,27 @@
1
+ import { SubmissionLedger } from "@effect-agent/thread/SubmissionLedger";
2
+ import { WakeScheduler } from "@effect-agent/thread/WakeScheduler";
3
+ import { Context, Duration, Layer } from "effect";
4
+ declare namespace NodeWakeScheduler_d_exports {
5
+ export { NodeWakeSchedulerConfig, nodeWakeSchedulerLayer };
6
+ }
7
+ declare const NodeWakeSchedulerConfig_base: Context.ServiceClass<NodeWakeSchedulerConfig, "@effect-agent/platform-node/NodeWakeSchedulerConfig", {
8
+ /** Interval between ledger scans that re-emit every nonterminal Thread lane. */
9
+ readonly scanInterval: Duration.Duration;
10
+ }>;
11
+ /** Cadence authority for the Node wake scheduler's ledger-scan fallback loop. */
12
+ declare class NodeWakeSchedulerConfig extends NodeWakeSchedulerConfig_base {
13
+ static layer(options: {
14
+ readonly scanInterval: Duration.Duration;
15
+ }): Layer.Layer<NodeWakeSchedulerConfig>;
16
+ }
17
+ /**
18
+ * In-process Node `WakeScheduler`: `notify` publishes to a bounded sliding PubSub for prompt
19
+ * same-process wakeups, and active `wakes` subscriptions share one periodic
20
+ * `SubmissionLedger.scanNonterminal` fallback so a dropped, coalesced, or never-sent notification
21
+ * can never strand accepted work (persistence §14). Delivery may duplicate; consumers already
22
+ * treat wakes as pure liveness hints.
23
+ */
24
+ declare const nodeWakeSchedulerLayer: Layer.Layer<WakeScheduler, never, SubmissionLedger | NodeWakeSchedulerConfig>;
25
+ //#endregion
26
+ export { NodeWakeScheduler_d_exports as n, nodeWakeSchedulerLayer as r, NodeWakeSchedulerConfig as t };
27
+ //# sourceMappingURL=NodeWakeScheduler-4ZeXYwPu.d.mts.map
@@ -0,0 +1,2 @@
1
+ import { r as nodeWakeSchedulerLayer, t as NodeWakeSchedulerConfig } from "./NodeWakeScheduler-4ZeXYwPu.mjs";
2
+ export { NodeWakeSchedulerConfig, nodeWakeSchedulerLayer };
@@ -0,0 +1,65 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import "@effect-agent/core/Identifiers";
3
+ import { SubmissionLedger } from "@effect-agent/thread/SubmissionLedger";
4
+ import { WakeScheduler, makeWakeSubscriptionHub } from "@effect-agent/thread/WakeScheduler";
5
+ import { Context, Effect, Layer, PubSub, Stream } from "effect";
6
+ //#region src/NodeWakeScheduler.ts
7
+ var NodeWakeScheduler_exports = /* @__PURE__ */ __exportAll({
8
+ NodeWakeSchedulerConfig: () => NodeWakeSchedulerConfig,
9
+ nodeWakeSchedulerLayer: () => nodeWakeSchedulerLayer
10
+ });
11
+ /**
12
+ * Bounded in-process wake buffer. Wake hints are droppable by contract (the ledger-scan fallback
13
+ * keeps liveness), so a full buffer slides out the oldest hint instead of growing without bound.
14
+ */
15
+ const WAKE_BUFFER_CAPACITY = 1024;
16
+ /** Cadence authority for the Node wake scheduler's ledger-scan fallback loop. */
17
+ var NodeWakeSchedulerConfig = class NodeWakeSchedulerConfig extends Context.Service()("@effect-agent/platform-node/NodeWakeSchedulerConfig") {
18
+ static layer(options) {
19
+ return Layer.succeed(NodeWakeSchedulerConfig)({ scanInterval: options.scanInterval });
20
+ }
21
+ };
22
+ const makeWakeScheduler = Effect.gen(function* () {
23
+ const ledger = yield* SubmissionLedger;
24
+ const config = yield* NodeWakeSchedulerConfig;
25
+ const hints = yield* PubSub.sliding(WAKE_BUFFER_CAPACITY);
26
+ const progress = yield* makeWakeSubscriptionHub;
27
+ yield* Effect.addFinalizer(() => PubSub.shutdown(hints));
28
+ /**
29
+ * One fallback scan: every Thread lane with nonterminal work, deduplicated. A scan
30
+ * failure degrades to "no hints this round" — the wake channel has no error contract and the
31
+ * next round retries — but is logged so a persistently failing ledger stays visible.
32
+ */
33
+ const scanOnce = Stream.runCollect(ledger.scanNonterminal).pipe(Effect.map((snapshots) => {
34
+ const lanes = /* @__PURE__ */ new Set();
35
+ for (const snapshot of snapshots) lanes.add(snapshot.threadId);
36
+ return [...lanes];
37
+ }), Effect.catch((error) => Effect.logWarning("NodeWakeScheduler fallback scan failed", error).pipe(Effect.as([]))));
38
+ /**
39
+ * Deployment §3: correctness must not depend on in-memory notifications, so every `wakes` run
40
+ * merges its PubSub subscription with shared Clock-driven ledger scans. Share whole snapshots:
41
+ * sliding individual lanes would strand the beginning of scans larger than the hint buffer.
42
+ * The scan starts with the first subscriber and stops when the last subscriber leaves.
43
+ */
44
+ const fallbackScans = yield* Stream.share(Stream.fromEffectRepeat(Effect.sleep(config.scanInterval).pipe(Effect.andThen(scanOnce))), {
45
+ capacity: 1,
46
+ strategy: "sliding"
47
+ });
48
+ return WakeScheduler.of({
49
+ notify: (threadId) => progress.notify(threadId).pipe(Effect.andThen(PubSub.publish(hints, threadId)), Effect.asVoid),
50
+ subscribe: progress.subscribe,
51
+ wakes: Stream.merge(Stream.fromPubSub(hints), fallbackScans.pipe(Stream.flatMap(Stream.fromIterable)))
52
+ });
53
+ });
54
+ /**
55
+ * In-process Node `WakeScheduler`: `notify` publishes to a bounded sliding PubSub for prompt
56
+ * same-process wakeups, and active `wakes` subscriptions share one periodic
57
+ * `SubmissionLedger.scanNonterminal` fallback so a dropped, coalesced, or never-sent notification
58
+ * can never strand accepted work (persistence §14). Delivery may duplicate; consumers already
59
+ * treat wakes as pure liveness hints.
60
+ */
61
+ const nodeWakeSchedulerLayer = Layer.effect(WakeScheduler)(makeWakeScheduler);
62
+ //#endregion
63
+ export { NodeWakeSchedulerConfig, nodeWakeSchedulerLayer, NodeWakeScheduler_exports as t };
64
+
65
+ //# sourceMappingURL=NodeWakeScheduler.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NodeWakeScheduler.mjs","names":[],"sources":["../src/NodeWakeScheduler.ts"],"sourcesContent":["import { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { SubmissionLedger } from \"@effect-agent/thread/SubmissionLedger\";\nimport { makeWakeSubscriptionHub, WakeScheduler } from \"@effect-agent/thread/WakeScheduler\";\nimport type { Duration } from \"effect\";\nimport { Context, Effect, Layer, PubSub, Stream } from \"effect\";\n\n/**\n * Bounded in-process wake buffer. Wake hints are droppable by contract (the ledger-scan fallback\n * keeps liveness), so a full buffer slides out the oldest hint instead of growing without bound.\n */\nconst WAKE_BUFFER_CAPACITY = 1_024;\n\n/** Cadence authority for the Node wake scheduler's ledger-scan fallback loop. */\nexport class NodeWakeSchedulerConfig extends Context.Service<\n NodeWakeSchedulerConfig,\n {\n /** Interval between ledger scans that re-emit every nonterminal Thread lane. */\n readonly scanInterval: Duration.Duration;\n }\n>()(\"@effect-agent/platform-node/NodeWakeSchedulerConfig\") {\n static layer(options: {\n readonly scanInterval: Duration.Duration;\n }): Layer.Layer<NodeWakeSchedulerConfig> {\n return Layer.succeed(NodeWakeSchedulerConfig)({ scanInterval: options.scanInterval });\n }\n}\n\nconst makeWakeScheduler = Effect.gen(function* () {\n const ledger = yield* SubmissionLedger;\n const config = yield* NodeWakeSchedulerConfig;\n const hints = yield* PubSub.sliding<ThreadId>(WAKE_BUFFER_CAPACITY);\n const progress = yield* makeWakeSubscriptionHub;\n\n yield* Effect.addFinalizer(() => PubSub.shutdown(hints));\n\n /**\n * One fallback scan: every Thread lane with nonterminal work, deduplicated. A scan\n * failure degrades to \"no hints this round\" — the wake channel has no error contract and the\n * next round retries — but is logged so a persistently failing ledger stays visible.\n */\n const scanOnce: Effect.Effect<ReadonlyArray<ThreadId>> = Stream.runCollect(\n ledger.scanNonterminal,\n ).pipe(\n Effect.map((snapshots) => {\n const lanes = new Set<ThreadId>();\n\n for (const snapshot of snapshots) {\n lanes.add(snapshot.threadId);\n }\n\n return [...lanes];\n }),\n Effect.catch((error) =>\n Effect.logWarning(\"NodeWakeScheduler fallback scan failed\", error).pipe(\n Effect.as([] as ReadonlyArray<ThreadId>),\n ),\n ),\n );\n\n /**\n * Deployment §3: correctness must not depend on in-memory notifications, so every `wakes` run\n * merges its PubSub subscription with shared Clock-driven ledger scans. Share whole snapshots:\n * sliding individual lanes would strand the beginning of scans larger than the hint buffer.\n * The scan starts with the first subscriber and stops when the last subscriber leaves.\n */\n const fallbackScans = yield* Stream.share(\n Stream.fromEffectRepeat(Effect.sleep(config.scanInterval).pipe(Effect.andThen(scanOnce))),\n { capacity: 1, strategy: \"sliding\" },\n );\n\n return WakeScheduler.of({\n notify: (threadId) =>\n progress\n .notify(threadId)\n .pipe(Effect.andThen(PubSub.publish(hints, threadId)), Effect.asVoid),\n subscribe: progress.subscribe,\n wakes: Stream.merge(\n Stream.fromPubSub(hints),\n fallbackScans.pipe(Stream.flatMap(Stream.fromIterable)),\n ),\n });\n});\n\n/**\n * In-process Node `WakeScheduler`: `notify` publishes to a bounded sliding PubSub for prompt\n * same-process wakeups, and active `wakes` subscriptions share one periodic\n * `SubmissionLedger.scanNonterminal` fallback so a dropped, coalesced, or never-sent notification\n * can never strand accepted work (persistence §14). Delivery may duplicate; consumers already\n * treat wakes as pure liveness hints.\n */\nexport const nodeWakeSchedulerLayer: Layer.Layer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W,KAAK,GACvB,cAAc,KAAK,OAAO,QAAQ,OAAO,YAAY,CAAC,CACxD;CACF,CAAC;AACH,CAAC;;;;;;;;AASD,MAAa,yBAIT,MAAM,OAAO,aAAa,CAAC,CAAC,iBAAiB"}
@@ -0,0 +1,27 @@
1
+ import { Cause, Duration, Layer, Schema } from "effect";
2
+ import { WorkflowDispatchError, WorkflowDispatchStore, WorkflowRepairTrigger } from "@effect-agent/workflow/WorkflowDispatch";
3
+ import { SqlClient } from "effect/unstable/sql";
4
+ //#region src/NodeWorkflow.d.ts
5
+ /**
6
+ * Durable dispatch outbox over an application-supplied SqlClient. This adapter uses
7
+ * SQLite/PostgreSQL SQL syntax and is certified with SQLite. It does not own an engine
8
+ * or a database connection. Agent admission, dispatch persistence, and native Workflow
9
+ * storage are separate commits; the registered repair trigger closes those gaps.
10
+ * Stored version or shape mismatches fail typed and require an explicit data reset.
11
+ */
12
+ declare class SqlWorkflowDispatchStore {
13
+ static readonly layer: Layer.Layer<WorkflowDispatchStore, WorkflowDispatchError, SqlClient.SqlClient>;
14
+ }
15
+ declare const NodeWorkflowRepairConfigError_base: Schema.Class<NodeWorkflowRepairConfigError, Schema.TaggedStruct<"NodeWorkflowRepairConfigError", {
16
+ readonly message: Schema.String;
17
+ }>, Cause.YieldableError>;
18
+ declare class NodeWorkflowRepairConfigError extends NodeWorkflowRepairConfigError_base {}
19
+ /** A host-scoped startup and polling trigger. No ordinary Node agent worker is started. */
20
+ declare class NodeWorkflowRepairTrigger {
21
+ static layer(options?: {
22
+ readonly interval?: Duration.Input;
23
+ }): Layer.Layer<WorkflowRepairTrigger, NodeWorkflowRepairConfigError>;
24
+ }
25
+ //#endregion
26
+ export { NodeWorkflowRepairConfigError, NodeWorkflowRepairTrigger, SqlWorkflowDispatchStore };
27
+ //# sourceMappingURL=NodeWorkflow.d.mts.map
@@ -0,0 +1,159 @@
1
+ import { Cause, Duration, Effect, Layer, Option, Schema } from "effect";
2
+ import { WorkflowDispatchError, WorkflowDispatchIntent, WorkflowDispatchScan, WorkflowDispatchStore, WorkflowRepairTrigger } from "@effect-agent/workflow/WorkflowDispatch";
3
+ import { SqlClient } from "effect/unstable/sql";
4
+ //#region src/NodeWorkflow.ts
5
+ const StoredIntent = Schema.Struct({
6
+ deployment_id: Schema.String,
7
+ workflow_name: Schema.String,
8
+ execution_id: Schema.String,
9
+ intent_json: Schema.String
10
+ });
11
+ const IntentJson = Schema.fromJsonString(WorkflowDispatchIntent);
12
+ const decodeIntent = Schema.decodeUnknownEffect(IntentJson, { onExcessProperty: "error" });
13
+ const encodeIntent = Schema.encodeEffect(IntentJson);
14
+ const dispatchError = (operation) => (cause) => Schema.is(WorkflowDispatchError)(cause) ? cause : new WorkflowDispatchError({
15
+ operation,
16
+ message: "Workflow dispatch storage failed or contains incompatible data",
17
+ cause
18
+ });
19
+ const decodeRow = Effect.fn("SqlWorkflowDispatchStore.decodeRow")(function* (value) {
20
+ const row = yield* Schema.decodeUnknownEffect(StoredIntent, { onExcessProperty: "error" })(value);
21
+ const intent = yield* decodeIntent(row.intent_json);
22
+ if (row.deployment_id !== intent.deploymentId || row.workflow_name !== intent.workflowName || row.execution_id !== intent.executionId) return yield* new WorkflowDispatchError({
23
+ operation: "decode",
24
+ message: "Stored Workflow dispatch identity disagrees with its intent"
25
+ });
26
+ return intent;
27
+ });
28
+ /**
29
+ * Durable dispatch outbox over an application-supplied SqlClient. This adapter uses
30
+ * SQLite/PostgreSQL SQL syntax and is certified with SQLite. It does not own an engine
31
+ * or a database connection. Agent admission, dispatch persistence, and native Workflow
32
+ * storage are separate commits; the registered repair trigger closes those gaps.
33
+ * Stored version or shape mismatches fail typed and require an explicit data reset.
34
+ */
35
+ var SqlWorkflowDispatchStore = class {
36
+ static layer = Layer.effect(WorkflowDispatchStore)(Effect.gen(function* () {
37
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
38
+ yield* sql`
39
+ CREATE TABLE IF NOT EXISTS effect_agent_workflow_dispatch (
40
+ workflow_name TEXT NOT NULL,
41
+ execution_id TEXT NOT NULL,
42
+ deployment_id TEXT NOT NULL,
43
+ intent_json TEXT NOT NULL,
44
+ PRIMARY KEY (workflow_name, execution_id)
45
+ )
46
+ `;
47
+ yield* sql`
48
+ CREATE INDEX IF NOT EXISTS effect_agent_workflow_dispatch_scan
49
+ ON effect_agent_workflow_dispatch (deployment_id, workflow_name, execution_id)
50
+ `;
51
+ const put = Effect.fn("SqlWorkflowDispatchStore.put")(function* (input) {
52
+ const intent = yield* Schema.decodeUnknownEffect(WorkflowDispatchIntent)(input);
53
+ const encoded = yield* encodeIntent(intent);
54
+ yield* sql`
55
+ INSERT INTO effect_agent_workflow_dispatch
56
+ (workflow_name, execution_id, deployment_id, intent_json)
57
+ VALUES (${intent.workflowName}, ${intent.executionId}, ${intent.deploymentId}, ${encoded})
58
+ ON CONFLICT (workflow_name, execution_id) DO NOTHING
59
+ `;
60
+ const rows = yield* sql`
61
+ SELECT deployment_id, workflow_name, execution_id, intent_json
62
+ FROM effect_agent_workflow_dispatch
63
+ WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}
64
+ `;
65
+ const existing = yield* decodeRow(rows[0]);
66
+ const merged = new WorkflowDispatchIntent({
67
+ ...intent,
68
+ ...existing.completionToken === void 0 ? {} : { completionToken: existing.completionToken }
69
+ });
70
+ if ((yield* encodeIntent(new WorkflowDispatchIntent({
71
+ ...existing,
72
+ ...merged.completionToken === void 0 ? {} : { completionToken: merged.completionToken }
73
+ }))) !== (yield* encodeIntent(merged)) || intent.completionToken !== void 0 && existing.completionToken !== void 0 && intent.completionToken !== existing.completionToken) return yield* new WorkflowDispatchError({
74
+ operation: "put",
75
+ message: "Workflow dispatch identity already belongs to a different immutable intent"
76
+ });
77
+ const retained = yield* encodeIntent(merged);
78
+ const previous = yield* encodeIntent(existing);
79
+ if (retained !== previous) {
80
+ if ((yield* sql`
81
+ UPDATE effect_agent_workflow_dispatch SET intent_json = ${retained}
82
+ WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}
83
+ AND intent_json = ${previous}
84
+ RETURNING execution_id
85
+ `).length !== 1) return yield* new WorkflowDispatchError({
86
+ operation: "put",
87
+ message: "Dispatch intent changed while attaching its completion token"
88
+ });
89
+ }
90
+ return merged;
91
+ }, sql.withTransaction, Effect.mapError(dispatchError("put")));
92
+ const scan = Effect.fn("SqlWorkflowDispatchStore.scan")(function* (input) {
93
+ const request = yield* Schema.decodeUnknownEffect(WorkflowDispatchScan)(input);
94
+ const rows = yield* sql`
95
+ SELECT deployment_id, workflow_name, execution_id, intent_json
96
+ FROM effect_agent_workflow_dispatch
97
+ WHERE deployment_id = ${request.deploymentId}
98
+ AND workflow_name = ${request.workflowName}
99
+ AND execution_id > ${request.after ?? ""}
100
+ ORDER BY execution_id ASC
101
+ LIMIT ${request.limit}
102
+ `;
103
+ return yield* Effect.forEach(rows, decodeRow);
104
+ }, Effect.mapError(dispatchError("scan")));
105
+ const remove = Effect.fn("SqlWorkflowDispatchStore.remove")(function* (input) {
106
+ const intent = yield* Schema.decodeUnknownEffect(WorkflowDispatchIntent)(input);
107
+ const rows = yield* sql`
108
+ SELECT deployment_id, workflow_name, execution_id, intent_json
109
+ FROM effect_agent_workflow_dispatch
110
+ WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}
111
+ `;
112
+ if (rows.length === 0) return;
113
+ const existing = yield* decodeRow(rows[0]);
114
+ if ((yield* encodeIntent(existing)) !== (yield* encodeIntent(intent))) return yield* new WorkflowDispatchError({
115
+ operation: "remove",
116
+ message: "Cannot remove a different immutable Workflow dispatch intent"
117
+ });
118
+ if ((yield* sql`
119
+ DELETE FROM effect_agent_workflow_dispatch
120
+ WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}
121
+ AND intent_json = ${yield* encodeIntent(intent)}
122
+ RETURNING execution_id
123
+ `).length !== 1) return yield* new WorkflowDispatchError({
124
+ operation: "remove",
125
+ message: "Dispatch intent changed before cleanup"
126
+ });
127
+ }, sql.withTransaction, Effect.mapError(dispatchError("remove")));
128
+ return WorkflowDispatchStore.of({
129
+ put,
130
+ scan,
131
+ remove
132
+ });
133
+ }).pipe(Effect.mapError(dispatchError("initialize"))));
134
+ };
135
+ var NodeWorkflowRepairConfigError = class extends Schema.TaggedError()("NodeWorkflowRepairConfigError", { message: Schema.String }) {};
136
+ /** A host-scoped startup and polling trigger. No ordinary Node agent worker is started. */
137
+ var NodeWorkflowRepairTrigger = class {
138
+ static layer(options = {}) {
139
+ return Layer.effect(WorkflowRepairTrigger)(Effect.gen(function* () {
140
+ const interval = Duration.fromInput(options.interval ?? "1 second");
141
+ if (Option.isNone(interval) || !Duration.isFinite(interval.value) || !Duration.isPositive(interval.value)) return yield* new NodeWorkflowRepairConfigError({ message: "Workflow repair interval must be finite and greater than zero" });
142
+ const delay = interval.value;
143
+ return WorkflowRepairTrigger.of({ register: Effect.fn("NodeWorkflowRepairTrigger.register")(function* (repair) {
144
+ const attempt = repair.pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logError("Workflow repair trigger failed; next poll will retry", cause)));
145
+ yield* attempt;
146
+ yield* Effect.gen(function* () {
147
+ while (true) {
148
+ yield* Effect.sleep(delay);
149
+ yield* attempt;
150
+ }
151
+ }).pipe(Effect.forkScoped);
152
+ }) });
153
+ }));
154
+ }
155
+ };
156
+ //#endregion
157
+ export { NodeWorkflowRepairConfigError, NodeWorkflowRepairTrigger, SqlWorkflowDispatchStore };
158
+
159
+ //# sourceMappingURL=NodeWorkflow.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NodeWorkflow.mjs","names":[],"sources":["../src/NodeWorkflow.ts"],"sourcesContent":["import {\n WorkflowDispatchError,\n WorkflowDispatchIntent,\n WorkflowDispatchScan,\n WorkflowDispatchStore,\n WorkflowRepairTrigger,\n} from \"@effect-agent/workflow/WorkflowDispatch\";\nimport { Cause, Duration, Effect, Layer, Option, Schema } from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql\";\n\nconst StoredIntent = Schema.Struct({\n deployment_id: Schema.String,\n workflow_name: Schema.String,\n execution_id: Schema.String,\n intent_json: Schema.String,\n});\n\nconst IntentJson = Schema.fromJsonString(WorkflowDispatchIntent);\nconst decodeIntent = Schema.decodeUnknownEffect(IntentJson, { onExcessProperty: \"error\" });\nconst encodeIntent = Schema.encodeEffect(IntentJson);\n\nconst dispatchError = (operation: string) => (cause: unknown) =>\n Schema.is(WorkflowDispatchError)(cause)\n ? cause\n : new WorkflowDispatchError({\n operation,\n message: \"Workflow dispatch storage failed or contains incompatible data\",\n cause,\n });\n\nconst decodeRow = Effect.fn(\"SqlWorkflowDispatchStore.decodeRow\")(function* (value: unknown) {\n const row = yield* Schema.decodeUnknownEffect(StoredIntent, { onExcessProperty: \"error\" })(value);\n const intent = yield* decodeIntent(row.intent_json);\n\n if (\n row.deployment_id !== intent.deploymentId ||\n row.workflow_name !== intent.workflowName ||\n row.execution_id !== intent.executionId\n ) {\n return yield* new WorkflowDispatchError({\n operation: \"decode\",\n message: \"Stored Workflow dispatch identity disagrees with its intent\",\n });\n }\n\n return intent;\n});\n\n/**\n * Durable dispatch outbox over an application-supplied SqlClient. This adapter uses\n * SQLite/PostgreSQL SQL syntax and is certified with SQLite. It does not own an engine\n * or a database connection. Agent admission, dispatch persistence, and native Workflow\n * storage are separate commits; the registered repair trigger closes those gaps.\n * Stored version or shape mismatches fail typed and require an explicit data reset.\n */\nexport class SqlWorkflowDispatchStore {\n static readonly layer: Layer.Layer<\n WorkflowDispatchStore,\n WorkflowDispatchError,\n SqlClient.SqlClient\n > = Layer.effect(WorkflowDispatchStore)(\n Effect.gen(function* () {\n const sql = (yield* SqlClient.SqlClient).withoutTransforms();\n\n yield* sql`\n CREATE TABLE IF NOT EXISTS effect_agent_workflow_dispatch (\n workflow_name TEXT NOT NULL,\n execution_id TEXT NOT NULL,\n deployment_id TEXT NOT NULL,\n intent_json TEXT NOT NULL,\n PRIMARY KEY (workflow_name, execution_id)\n )\n `;\n yield* sql`\n CREATE INDEX IF NOT EXISTS effect_agent_workflow_dispatch_scan\n ON effect_agent_workflow_dispatch (deployment_id, workflow_name, execution_id)\n `;\n\n const put = Effect.fn(\"SqlWorkflowDispatchStore.put\")(\n function* (input: WorkflowDispatchIntent) {\n const intent = yield* Schema.decodeUnknownEffect(WorkflowDispatchIntent)(input);\n const encoded = yield* encodeIntent(intent);\n\n yield* sql`\n INSERT INTO effect_agent_workflow_dispatch\n (workflow_name, execution_id, deployment_id, intent_json)\n VALUES (${intent.workflowName}, ${intent.executionId}, ${intent.deploymentId}, ${encoded})\n ON CONFLICT (workflow_name, execution_id) DO NOTHING\n `;\n\n const rows = yield* sql`\n SELECT deployment_id, workflow_name, execution_id, intent_json\n FROM effect_agent_workflow_dispatch\n WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}\n `;\n\n const existing = yield* decodeRow(rows[0]);\n\n const merged = new WorkflowDispatchIntent({\n ...intent,\n ...(existing.completionToken === undefined\n ? {}\n : { completionToken: existing.completionToken }),\n });\n\n if (\n (yield* encodeIntent(\n new WorkflowDispatchIntent({\n ...existing,\n ...(merged.completionToken === undefined\n ? {}\n : { completionToken: merged.completionToken }),\n }),\n )) !== (yield* encodeIntent(merged)) ||\n (intent.completionToken !== undefined &&\n existing.completionToken !== undefined &&\n intent.completionToken !== existing.completionToken)\n ) {\n return yield* new WorkflowDispatchError({\n operation: \"put\",\n message: \"Workflow dispatch identity already belongs to a different immutable intent\",\n });\n }\n const retained = yield* encodeIntent(merged);\n const previous = yield* encodeIntent(existing);\n\n if (retained !== previous) {\n const updated = yield* sql`\n UPDATE effect_agent_workflow_dispatch SET intent_json = ${retained}\n WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}\n AND intent_json = ${previous}\n RETURNING execution_id\n `;\n\n if (updated.length !== 1) {\n return yield* new WorkflowDispatchError({\n operation: \"put\",\n message: \"Dispatch intent changed while attaching its completion token\",\n });\n }\n }\n\n return merged;\n },\n sql.withTransaction,\n Effect.mapError(dispatchError(\"put\")),\n );\n\n const scan = Effect.fn(\"SqlWorkflowDispatchStore.scan\")(\n function* (input: WorkflowDispatchScan) {\n const request = yield* Schema.decodeUnknownEffect(WorkflowDispatchScan)(input);\n\n const rows = yield* sql`\n SELECT deployment_id, workflow_name, execution_id, intent_json\n FROM effect_agent_workflow_dispatch\n WHERE deployment_id = ${request.deploymentId}\n AND workflow_name = ${request.workflowName}\n AND execution_id > ${request.after ?? \"\"}\n ORDER BY execution_id ASC\n LIMIT ${request.limit}\n `;\n\n return yield* Effect.forEach(rows, decodeRow);\n },\n Effect.mapError(dispatchError(\"scan\")),\n );\n\n const remove = Effect.fn(\"SqlWorkflowDispatchStore.remove\")(\n function* (input: WorkflowDispatchIntent) {\n const intent = yield* Schema.decodeUnknownEffect(WorkflowDispatchIntent)(input);\n\n const rows = yield* sql`\n SELECT deployment_id, workflow_name, execution_id, intent_json\n FROM effect_agent_workflow_dispatch\n WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}\n `;\n\n if (rows.length === 0) return;\n const existing = yield* decodeRow(rows[0]);\n\n if ((yield* encodeIntent(existing)) !== (yield* encodeIntent(intent))) {\n return yield* new WorkflowDispatchError({\n operation: \"remove\",\n message: \"Cannot remove a different immutable Workflow dispatch intent\",\n });\n }\n\n const removed = yield* sql`\n DELETE FROM effect_agent_workflow_dispatch\n WHERE workflow_name = ${intent.workflowName} AND execution_id = ${intent.executionId}\n AND intent_json = ${yield* encodeIntent(intent)}\n RETURNING execution_id\n `;\n\n if (removed.length !== 1) {\n return yield* new WorkflowDispatchError({\n operation: \"remove\",\n message: \"Dispatch intent changed before cleanup\",\n });\n }\n },\n sql.withTransaction,\n Effect.mapError(dispatchError(\"remove\")),\n );\n\n return WorkflowDispatchStore.of({ put, scan, remove });\n }).pipe(Effect.mapError(dispatchError(\"initialize\"))),\n );\n}\n\nexport class NodeWorkflowRepairConfigError extends Schema.TaggedError<NodeWorkflowRepairConfigError>()(\n \"NodeWorkflowRepairConfigError\",\n { message: Schema.String },\n) {}\n\n/** A host-scoped startup and polling trigger. No ordinary Node agent worker is started. */\nexport class NodeWorkflowRepairTrigger {\n static layer(\n options: { readonly interval?: Duration.Input } = {},\n ): Layer.Layer<WorkflowRepairTrigger, NodeWorkflowRepairConfigError> {\n return Layer.effect(WorkflowRepairTrigger)(\n Effect.gen(function* () {\n const interval = Duration.fromInput(options.interval ?? \"1 second\");\n\n if (\n Option.isNone(interval) ||\n !Duration.isFinite(interval.value) ||\n !Duration.isPositive(interval.value)\n ) {\n return yield* new NodeWorkflowRepairConfigError({\n message: \"Workflow repair interval must be finite and greater than zero\",\n });\n }\n const delay = interval.value;\n\n return WorkflowRepairTrigger.of({\n register: Effect.fn(\"NodeWorkflowRepairTrigger.register\")(function* (repair) {\n const attempt = repair.pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"Workflow repair trigger failed; next poll will retry\", cause),\n ),\n );\n\n yield* attempt;\n yield* Effect.gen(function* () {\n while (true) {\n yield* Effect.sleep(delay);\n yield* attempt;\n }\n }).pipe(Effect.forkScoped);\n }),\n });\n }),\n );\n }\n}\n"],"mappings":";;;;AAUA,MAAM,eAAe,OAAO,OAAO;CACjC,eAAe,OAAO;CACtB,eAAe,OAAO;CACtB,cAAc,OAAO;CACrB,aAAa,OAAO;AACtB,CAAC;AAED,MAAM,aAAa,OAAO,eAAe,sBAAsB;AAC/D,MAAM,eAAe,OAAO,oBAAoB,YAAY,EAAE,kBAAkB,QAAQ,CAAC;AACzF,MAAM,eAAe,OAAO,aAAa,UAAU;AAEnD,MAAM,iBAAiB,eAAuB,UAC5C,OAAO,GAAG,qBAAqB,CAAC,CAAC,KAAK,IAClC,QACA,IAAI,sBAAsB;CACxB;CACA,SAAS;CACT;AACF,CAAC;AAEP,MAAM,YAAY,OAAO,GAAG,oCAAoC,CAAC,CAAC,WAAW,OAAgB;CAC3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