@systemfsoftware/agent-platform-cloudflare 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/Alarm-CbhflIzz.mjs +1931 -0
  3. package/dist/Alarm-CbhflIzz.mjs.map +1 -0
  4. package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
  5. package/dist/Alarm.d.mts +3 -0
  6. package/dist/Alarm.mjs +3 -0
  7. package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
  8. package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
  9. package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
  10. package/dist/BrowserCredentials.d.mts +2 -0
  11. package/dist/BrowserCredentials.mjs +1 -0
  12. package/dist/BrowserRestCapture.d.mts +14 -0
  13. package/dist/BrowserRestCapture.mjs +195 -0
  14. package/dist/BrowserRestCapture.mjs.map +1 -0
  15. package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
  16. package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
  17. package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
  18. package/dist/BrowserSession.d.mts +3 -0
  19. package/dist/BrowserSession.mjs +4 -0
  20. package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
  21. package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
  22. package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
  23. package/dist/BrowserUse.d.mts +2 -0
  24. package/dist/BrowserUse.mjs +1 -0
  25. package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
  26. package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
  27. package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
  28. package/dist/CloudflareAiGateway.d.mts +2 -0
  29. package/dist/CloudflareAiGateway.mjs +1 -0
  30. package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
  31. package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
  32. package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
  33. package/dist/CloudflareBindings.d.mts +2 -0
  34. package/dist/CloudflareBindings.mjs +1 -0
  35. package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
  36. package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
  37. package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
  38. package/dist/CloudflareBrowser.d.mts +3 -0
  39. package/dist/CloudflareBrowser.mjs +1 -0
  40. package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
  41. package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
  42. package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
  43. package/dist/CloudflareCodeMode.d.mts +2 -0
  44. package/dist/CloudflareCodeMode.mjs +1 -0
  45. package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
  46. package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
  47. package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
  48. package/dist/CloudflareConfig.d.mts +2 -0
  49. package/dist/CloudflareConfig.mjs +1 -0
  50. package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
  51. package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
  52. package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
  53. package/dist/CloudflareMemory.d.mts +2 -0
  54. package/dist/CloudflareMemory.mjs +1 -0
  55. package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
  56. package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
  57. package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
  58. package/dist/CloudflareScheduling.d.mts +2 -0
  59. package/dist/CloudflareScheduling.mjs +1 -0
  60. package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
  61. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
  62. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
  63. package/dist/CloudflareSubscriptions.d.mts +2 -0
  64. package/dist/CloudflareSubscriptions.mjs +1 -0
  65. package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
  66. package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
  67. package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
  68. package/dist/CloudflareThreadClient.d.mts +3 -0
  69. package/dist/CloudflareThreadClient.mjs +3 -0
  70. package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
  71. package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
  72. package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
  73. package/dist/InteractiveBrowser.d.mts +2 -0
  74. package/dist/InteractiveBrowser.mjs +1 -0
  75. package/dist/LiveText-CfpcZaGb.d.mts +91 -0
  76. package/dist/LiveText-DaF0tN_p.mjs +148 -0
  77. package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
  78. package/dist/LiveText.d.mts +2 -0
  79. package/dist/LiveText.mjs +1 -0
  80. package/dist/R2ToolResultStorage.d.mts +27 -0
  81. package/dist/R2ToolResultStorage.mjs +84 -0
  82. package/dist/R2ToolResultStorage.mjs.map +1 -0
  83. package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
  84. package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
  85. package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
  86. package/dist/ThreadObject.d.mts +2 -0
  87. package/dist/ThreadObject.mjs +1 -0
  88. package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
  89. package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
  90. package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
  91. package/dist/WakeScheduler.d.mts +2 -0
  92. package/dist/WakeScheduler.mjs +1 -0
  93. package/dist/boundary-YrOnE2zO.mjs +41 -0
  94. package/dist/boundary-YrOnE2zO.mjs.map +1 -0
  95. package/dist/browser-failure-CWBBnf1j.mjs +70 -0
  96. package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
  97. package/dist/index.d.mts +17 -0
  98. package/dist/index.mjs +17 -0
  99. package/dist/prepared-admission-DngoYN74.mjs +57 -0
  100. package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
  101. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  102. package/package.json +134 -3
  103. package/src/Alarm.ts +3402 -0
  104. package/src/BrowserCredentials.ts +181 -0
  105. package/src/BrowserRestCapture.ts +383 -0
  106. package/src/BrowserSession.ts +993 -0
  107. package/src/BrowserUse.ts +438 -0
  108. package/src/CloudflareAiGateway.ts +176 -0
  109. package/src/CloudflareBindings.ts +225 -0
  110. package/src/CloudflareBrowser.ts +9 -0
  111. package/src/CloudflareCodeMode.ts +896 -0
  112. package/src/CloudflareConfig.ts +142 -0
  113. package/src/CloudflareMemory.ts +418 -0
  114. package/src/CloudflareScheduling.ts +736 -0
  115. package/src/CloudflareSubscriptions.ts +1032 -0
  116. package/src/CloudflareThreadClient.ts +980 -0
  117. package/src/InteractiveBrowser.ts +3300 -0
  118. package/src/LiveText.ts +145 -0
  119. package/src/R2ToolResultStorage.ts +131 -0
  120. package/src/ThreadObject.ts +1348 -0
  121. package/src/WakeScheduler.ts +102 -0
  122. package/src/index.ts +16 -0
  123. package/src/internal/boundary.ts +53 -0
  124. package/src/internal/browser-binding.ts +483 -0
  125. package/src/internal/browser-credentials.ts +481 -0
  126. package/src/internal/browser-failure.ts +145 -0
  127. package/src/internal/browser-file-selection.ts +146 -0
  128. package/src/internal/browser-quick-action.ts +666 -0
  129. package/src/internal/browser-readonly-live-view.ts +121 -0
  130. package/src/internal/browser-session-lifecycle.ts +200 -0
  131. package/src/internal/crypto.ts +44 -0
  132. package/src/internal/due-queue.ts +452 -0
  133. package/src/internal/host-protocol-error.ts +23 -0
  134. package/src/internal/layers.ts +1181 -0
  135. package/src/internal/live-text-observation.ts +8 -0
  136. package/src/internal/live-text-protocol.ts +59 -0
  137. package/src/internal/live-text.ts +339 -0
  138. package/src/internal/message-delivery.ts +149 -0
  139. package/src/internal/page-function.ts +12 -0
  140. package/src/internal/prepared-admission.ts +83 -0
  141. package/src/internal/progress-wait.ts +121 -0
  142. package/src/internal/transport.ts +53 -0
  143. package/README.md +0 -3
@@ -0,0 +1,1225 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
+ import { LedgerLookupResult, PortFailed, PortProtocolError, PortSucceeded, decodePortRequest, encodePortResponse } from "@systemfsoftware/agent-storage-cloudflare/port-protocol";
3
+ import { IntegrityReport, ObligationReport, ObligationThresholds, RecoveryExplanation, RetryCommand, RetryRefused } from "@systemfsoftware/agent/admin";
4
+ import { DigestError } from "@systemfsoftware/agent/digest";
5
+ import { ApprovalSuspensionError, DurableAgentRuntime, DurableRuntimeConfig, RecoveryBlocked, RecoveryReport } from "@systemfsoftware/agent/durable-agent-runtime";
6
+ import { DurableRuntimeFailpoint, DurableRuntimeFailpointError } from "@systemfsoftware/agent/durable-failpoint";
7
+ import { SubmissionId, ThreadId } from "@systemfsoftware/agent/identifiers";
8
+ import { OperationAuthorizationRequest, OperationAuthorizer, OperationDenied, operationAuthorizerLayer } from "@systemfsoftware/agent/operation-authorizer";
9
+ import { PersistedJson, ProducerId } from "@systemfsoftware/agent/records";
10
+ import { RunJournalError } from "@systemfsoftware/agent/run-journal";
11
+ import { AdmissionPolicyError, LedgerError, OwnershipLost, SettlementConflict, SubmissionLedger, SubmissionLookupByKey } from "@systemfsoftware/agent/submission-ledger";
12
+ import { AppendConflict, AppendResult, PreparedAppend, ThreadNotMaterialized, ThreadRead, ThreadStore, ThreadStoreError } from "@systemfsoftware/agent/thread-store";
13
+ import { WorkDiscoveryUnavailable } from "@systemfsoftware/agent/thread-work";
14
+ import { WakeScheduler } from "@systemfsoftware/agent/wake-scheduler";
15
+ import { DurableObject, DurableObjectAlarm, DurableObjectState, RpcTracing, WorkerEnvironment } from "effect-cf";
16
+ import * as Context from "effect/Context";
17
+ import * as Effect from "effect/Effect";
18
+ import * as Layer from "effect/Layer";
19
+ import * as Option from "effect/Option";
20
+ import * as Schema from "effect/Schema";
21
+ import * as Stream from "effect/Stream";
22
+ import { _ as Messages, a as ThreadMaintenance, b as Publication, c as ThreadMessageDelivery, d as ThreadPublication, g as Lifecycle, h as HostLaneId, l as ThreadMutationGate, m as publishCommitted, n as DurableAlarmService, o as ThreadMaintenanceAlarm, s as ThreadMaintenanceFailpoint, u as ThreadNativeMaintenance, v as Native, y as Projection } from "./Alarm-CbhflIzz.mjs";
23
+ import { a as ThreadObjectIdentity, c as callThreadObject, i as DurableObjectContext, l as threadNamespaceFromEnv, o as ThreadObjectNamespace, r as DurableAlarmError, s as ThreadObjectPlacement } from "./CloudflareBindings-Dylkir84.mjs";
24
+ import { c as CloudflareDurableRuntimeConfigValue, i as CLOUDFLARE_RUNTIME_DEFAULTS, l as CloudflarePlatformConfigError, s as CloudflareDurableRuntimeConfig, t as AdmissionLimitExceeded } from "./CloudflareConfig-rBlbPSIZ.mjs";
25
+ import { A as decodeSubmitRequest, C as decodeApprovalDecisionCommand, E as decodeCancelProgressRequest, H as Observation, L as encodeHostResponse, O as decodeObservePageRequest, S as decodeAbortCommand, T as decodeAwaitSettlementRequest, U as cloudflareCryptoLayer, _ as SubmissionStatusResponse, c as HostFailed, f as ObservedPage, g as SettlementRecordReached, h as SettlementReached, j as decodeUnknownResolutionCommand, k as decodeReceipt, m as ProgressObserved, n as ApprovalRecorded, o as CloudflareThreadClient, p as ProgressCancelled, t as AbortRecorded, w as decodeAwaitProgressRequest, x as UnknownResolutionRecorded, y as SubmitSucceeded } from "./CloudflareThreadClient-K7QJHYpK.mjs";
26
+ import * as SqliteClient from "@effect/sql-sqlite-do/SqliteClient";
27
+ import { doMessageDeliveryStoreLayer } from "@systemfsoftware/agent-storage-cloudflare/do-message-delivery-store";
28
+ import "@systemfsoftware/agent-storage-cloudflare/do-storage-failpoint";
29
+ import { submissionLedgerLayer } from "@systemfsoftware/agent-storage-cloudflare/do-submission-ledger";
30
+ import { journalLayer, sqlOwnerLayer, storageConfigLayer, storageFailpointLayer, threadStoreLayer } from "@systemfsoftware/agent-storage-cloudflare/do-thread-store";
31
+ import { ThreadPortTransport, executePortRequest, makeLocalSubmissionLookup, portTransportFailure, routedMessageDeliveryStoreLayer, routedSettlementPublisherLayer, routedSubmissionLedgerLayer, routedThreadStoreLayer, routedWorkerAdmissionLayer } from "@systemfsoftware/agent-storage-cloudflare/port-routing";
32
+ import { SqlStorageProgress, SqlStorageProgressError } from "@systemfsoftware/agent-storage-sql/sql-storage-progress";
33
+ import { compileRegistrations } from "@systemfsoftware/agent/agent-registration";
34
+ import { LifecyclePublicationError, LifecyclePublicationFact, drainLifecyclePublications, lifecyclePublicationLayer } from "@systemfsoftware/agent/lifecycle-publication";
35
+ import { MessageDeliveryDriver, MessageDeliveryError, MessageDeliveryStore } from "@systemfsoftware/agent/message-delivery";
36
+ import { CurrentToolFailureObserver, RunContextPreparationPassthrough, RunToolAuthorization, toolFailureObserverLayer } from "@systemfsoftware/agent/run-options";
37
+ import { StorageOwner, layer as layer$1 } from "@systemfsoftware/agent/run-storage";
38
+ import { SettlementPublisher, validatePublication } from "@systemfsoftware/agent/settlement-publisher";
39
+ import { SqlStorageOwner } from "@systemfsoftware/agent/sql-storage-owner";
40
+ import { ThreadProjectionMaintenance } from "@systemfsoftware/agent/thread-projection-maintenance";
41
+ import { ToolReconciler } from "@systemfsoftware/agent/tool-reconciler";
42
+ import * as Cause from "effect/Cause";
43
+ import * as Clock from "effect/Clock";
44
+ import * as Duration from "effect/Duration";
45
+ import * as ErrorReporter from "effect/ErrorReporter";
46
+ import * as Exit from "effect/Exit";
47
+ import * as Match from "effect/Match";
48
+ import * as Semaphore from "effect/Semaphore";
49
+ import * as SqlClient from "effect/sql/SqlClient";
50
+ import { n as cloudflareWakeSchedulerLayer } from "./WakeScheduler-DV4J4TRe.mjs";
51
+ import { Publisher } from "@systemfsoftware/agent/provisional-text";
52
+ import { RpcTarget } from "cloudflare:workers";
53
+ import * as Response from "effect/ai/Response";
54
+ import { c as isBoundedEvent, d as boundHostDiagnostic, i as MAX_DELTA_LENGTH, r as Frame, s as Request, u as HostProtocolError } from "./LiveText-DaF0tN_p.mjs";
55
+ import { t as cloudflarePreparedInputAdmissionLayer } from "./prepared-admission-DngoYN74.mjs";
56
+ import * as Deferred from "effect/Deferred";
57
+ import * as Ref from "effect/Ref";
58
+ // src/internal/live-text.ts
59
+ var ObservationLifetime = class extends RpcTarget {
60
+ #close;
61
+ constructor(close) {
62
+ super();
63
+ this.#close = close;
64
+ }
65
+ [Symbol.dispose]() {
66
+ this.#close();
67
+ }
68
+ };
69
+ const encode = Schema.encodeSync(Frame);
70
+ /** One Object incarnation; owns drafts and subscriptions independently of RPC event scopes. */
71
+ var LiveTextHub = class LiveTextHub extends Context.Service()("@effect-agent/platform-cloudflare/LiveTextHub") {
72
+ static layer = Layer.effectContext(Effect.gen(function* () {
73
+ const observers = /* @__PURE__ */ new Set();
74
+ const drafts = /* @__PURE__ */ new Map();
75
+ let length = 0;
76
+ let stopped = false;
77
+ let unavailable;
78
+ const encoder = new TextEncoder();
79
+ yield* Effect.addFinalizer(() => Effect.sync(() => {
80
+ stopped = true;
81
+ drafts.clear();
82
+ for (const observer of observers) observer.close();
83
+ }));
84
+ const fail = (attemptId) => {
85
+ const error = HostProtocolError.make({ message: "Provisional text exceeds its draft bounds or is invalid; read canonical records" });
86
+ unavailable = {
87
+ error,
88
+ attemptId
89
+ };
90
+ drafts.clear();
91
+ length = 0;
92
+ for (const observer of observers) observer.close(error);
93
+ return false;
94
+ };
95
+ const offerUnsafe = (event) => {
96
+ if (stopped) return false;
97
+ if (event._tag === "AttemptEnded" && event.attemptId === unavailable?.attemptId) unavailable = void 0;
98
+ if (unavailable !== void 0) return false;
99
+ if (!isBoundedEvent(event)) return event._tag === "AttemptEnded" ? false : fail(event.attemptId);
100
+ if (event._tag === "Text") {
101
+ const key = JSON.stringify([
102
+ event.threadId,
103
+ event.submissionId,
104
+ event.attemptId,
105
+ event.runId,
106
+ event.turnId,
107
+ event.generation,
108
+ event.part.type.startsWith("reasoning-") ? "reasoning" : "text",
109
+ event.part.id
110
+ ]);
111
+ const draft = drafts.get(key);
112
+ if (event.part.type === "text-start" || event.part.type === "reasoning-start") {
113
+ if (draft !== void 0 || drafts.size >= 32) return fail(event.attemptId);
114
+ drafts.set(key, {
115
+ start: event,
116
+ text: "",
117
+ ended: false
118
+ });
119
+ } else {
120
+ if (draft === void 0) return false;
121
+ if (draft.ended) return fail(event.attemptId);
122
+ if (event.part.type === "text-delta" || event.part.type === "reasoning-delta") {
123
+ if (length + event.part.delta.length > 2097152) return fail(event.attemptId);
124
+ draft.text += event.part.delta;
125
+ length += event.part.delta.length;
126
+ } else draft.ended = true;
127
+ }
128
+ } else for (const [key, draft] of drafts) {
129
+ const start = draft.start;
130
+ if (start.threadId === event.threadId && start.submissionId === event.submissionId && start.attemptId === event.attemptId && (event._tag === "AttemptEnded" || start.runId === event.runId && start.turnId === event.turnId && start.generation === event.generation)) {
131
+ drafts.delete(key);
132
+ length -= draft.text.length;
133
+ }
134
+ }
135
+ for (const observer of observers) if (observer.threadId === event.threadId) observer.offer(event);
136
+ return true;
137
+ };
138
+ const open = Effect.fnUntraced(function* (threadId) {
139
+ if (stopped) return yield* HostProtocolError.make({ message: "Provisional text owner is closed" });
140
+ if (unavailable !== void 0) return yield* unavailable.error;
141
+ if (threadId.length > 256 || observers.size >= 8) return yield* HostProtocolError.make({ message: "Provisional text observation capacity exceeded" });
142
+ const buffer = [];
143
+ let controller;
144
+ let pending;
145
+ let snapshotNeeded = true;
146
+ let streamId = "";
147
+ let sequence = 0;
148
+ let closed = false;
149
+ let keepalive;
150
+ const dispose = () => {
151
+ closed = true;
152
+ clearInterval(keepalive);
153
+ buffer.length = 0;
154
+ pending = void 0;
155
+ observers.delete(observer);
156
+ };
157
+ const observer = {
158
+ threadId,
159
+ offer(event) {
160
+ if (buffer.length === 32) snapshotNeeded = true;
161
+ else buffer.push(event);
162
+ flush();
163
+ },
164
+ close(error) {
165
+ if (closed) return;
166
+ dispose();
167
+ if (error === void 0) controller?.close();
168
+ else controller?.error(error);
169
+ }
170
+ };
171
+ const frame = (event) => ({
172
+ _tag: "Event",
173
+ schemaVersion: 1,
174
+ streamId,
175
+ sequence: ++sequence,
176
+ event
177
+ });
178
+ const snapshot = function* () {
179
+ buffer.length = 0;
180
+ const current = Array.from(drafts.values()).filter((draft) => draft.start.threadId === threadId).map((draft) => ({ ...draft }));
181
+ snapshotNeeded = false;
182
+ streamId = crypto.randomUUID();
183
+ sequence = 0;
184
+ yield {
185
+ _tag: "Reset",
186
+ schemaVersion: 1,
187
+ streamId,
188
+ threadId,
189
+ sequence: 0
190
+ };
191
+ for (const draft of current) {
192
+ yield frame(draft.start);
193
+ for (let offset = 0; offset < draft.text.length; offset += MAX_DELTA_LENGTH) yield frame({
194
+ ...draft.start,
195
+ part: Response.makePart(draft.start.part.type === "reasoning-start" ? "reasoning-delta" : "text-delta", {
196
+ id: draft.start.part.id,
197
+ delta: draft.text.slice(offset, offset + MAX_DELTA_LENGTH)
198
+ })
199
+ });
200
+ if (draft.ended) yield frame({
201
+ ...draft.start,
202
+ part: Response.makePart(draft.start.part.type === "reasoning-start" ? "reasoning-end" : "text-end", { id: draft.start.part.id })
203
+ });
204
+ }
205
+ };
206
+ const flush = () => {
207
+ if (closed || controller === void 0) return;
208
+ while (controller.desiredSize !== null && controller.desiredSize > 0) {
209
+ if (snapshotNeeded) pending = snapshot();
210
+ let value;
211
+ if (pending !== void 0) {
212
+ const next = pending.next();
213
+ if (next.done) {
214
+ pending = void 0;
215
+ continue;
216
+ }
217
+ value = next.value;
218
+ } else {
219
+ const event = buffer.shift();
220
+ if (event === void 0) return;
221
+ value = frame(event);
222
+ }
223
+ let json;
224
+ try {
225
+ json = JSON.stringify(encode(value));
226
+ } catch {
227
+ observer.close(HostProtocolError.make({ message: "Provisional text frame is invalid" }));
228
+ return;
229
+ }
230
+ const bytes = encoder.encode(json + "\n");
231
+ if (bytes.byteLength > 32768) {
232
+ observer.close(HostProtocolError.make({ message: "Provisional text frame exceeds its wire bound" }));
233
+ return;
234
+ }
235
+ controller.enqueue(bytes);
236
+ }
237
+ };
238
+ const stream = new ReadableStream({
239
+ start(value) {
240
+ controller = value;
241
+ observers.add(observer);
242
+ keepalive = setInterval(() => {
243
+ if (closed || value.desiredSize === null || value.desiredSize <= 0) return;
244
+ value.enqueue(new Uint8Array([10]));
245
+ }, 15e3);
246
+ flush();
247
+ },
248
+ pull: flush,
249
+ cancel: dispose
250
+ });
251
+ return Observation.make({
252
+ stream,
253
+ lifetime: new ObservationLifetime(() => observer.close())
254
+ });
255
+ });
256
+ return Context.make(LiveTextHub, { open }).pipe(Context.add(Publisher, { offerUnsafe }));
257
+ }));
258
+ };
259
+ // src/internal/message-delivery.ts
260
+ /** Every write prearms its owner; the delivery due index owns its recovery deadline. */
261
+ const guardedMessageDeliveryStoreLayer = Layer.effect(MessageDeliveryStore, Effect.gen(function* () {
262
+ const store = yield* MessageDeliveryStore;
263
+ const mutations = yield* ThreadMutationGate;
264
+ const wakes = yield* WakeScheduler;
265
+ const { ownsThread } = yield* ThreadObjectPlacement;
266
+ const local = (owner, body) => owner === void 0 || ownsThread(owner) ? body : Effect.fail(MessageDeliveryError.make({
267
+ reason: "validation",
268
+ operation: "message owner"
269
+ }));
270
+ const mutate = (body) => mutations.withMutation(body, {
271
+ invalidatesRecovery: false,
272
+ lanes: [Messages, ...store.lifecyclePublications === void 0 ? [] : [Lifecycle]]
273
+ }).pipe(Effect.catchTag("DurableAlarmError", (cause) => MessageDeliveryError.make({
274
+ reason: "storage",
275
+ operation: "prearm message delivery",
276
+ cause
277
+ })));
278
+ return MessageDeliveryStore.of({
279
+ limits: store.limits,
280
+ maxStoredValueBytes: store.maxStoredValueBytes,
281
+ insert: (record) => local(record.key.ownerThreadId, mutate(store.insert(record)).pipe(Effect.tap(() => wakes.notify(record.key.ownerThreadId)))),
282
+ get: (key) => local(key.ownerThreadId, store.get(key)),
283
+ list: (request) => local(request.ownerThreadId, store.list(request)),
284
+ change: (key, change) => local(key.ownerThreadId, mutate(store.change(key, change))),
285
+ due: (nowMillis, limit, owner) => local(owner, store.due(nowMillis, limit, owner)).pipe(Effect.filterOrFail((keys) => keys.every((key) => ownsThread(key.ownerThreadId)), () => MessageDeliveryError.make({
286
+ reason: "validation",
287
+ operation: "message owner"
288
+ }))),
289
+ nextDeadline: (owner) => local(owner, store.nextDeadline(owner))
290
+ });
291
+ }));
292
+ /** Build the driver in the Object's Scope only when retained delivery work is due. */
293
+ const lazyThreadMessageDeliveryLayer = (driver) => Layer.fromBuildMemo((memoMap, scope) => Effect.gen(function* () {
294
+ const context = yield* Effect.context();
295
+ const store = yield* MessageDeliveryStore;
296
+ const service = yield* Effect.cachedWithTTL(Layer.buildWithMemoMap(driver, memoMap, scope).pipe(Effect.provide(context), Effect.map(Context.get(MessageDeliveryDriver)), Effect.mapError((cause) => DurableAlarmError.make({
297
+ operation: "prepare message delivery",
298
+ message: "Durable message recovery remains pending",
299
+ cause
300
+ }))), (exit) => Exit.isSuccess(exit) ? Duration.infinity : Duration.zero);
301
+ const failure = (operation) => () => DurableAlarmError.make({
302
+ operation,
303
+ message: "Durable message recovery remains pending"
304
+ });
305
+ const prepare = Effect.gen(function* () {
306
+ const deadline = yield* store.nextDeadline();
307
+ if (deadline === null || deadline > (yield* Clock.currentTimeMillis)) return {
308
+ timeoutMillis: 1,
309
+ run: Effect.succeed(Option.fromNullishOr(deadline))
310
+ };
311
+ const keys = yield* store.due(yield* Clock.currentTimeMillis, 4);
312
+ const records = yield* Effect.forEach(keys, (key) => store.get(key));
313
+ return {
314
+ timeoutMillis: Math.max(1, ...records.map((record) => record?.policy.attemptTimeoutMillis ?? 1)),
315
+ run: Effect.flatMap(service, (driver) => Effect.forEach(keys, (key) => driver.process(key), {
316
+ concurrency: 4,
317
+ discard: true
318
+ })).pipe(Effect.andThen(store.nextDeadline()), Effect.map(Option.fromNullishOr), Effect.mapError(failure("dispatch message delivery")))
319
+ };
320
+ }).pipe(Effect.mapError(failure("prepare message delivery")));
321
+ return Context.make(ThreadMessageDelivery, { prepare });
322
+ }));
323
+ lazyThreadMessageDeliveryLayer(Layer.effect(MessageDeliveryDriver, MessageDeliveryDriver));
324
+ // src/internal/progress-wait.ts
325
+ /** Cancellation tombstones are bounded hints, never durable authority. */
326
+ const MAX_CANCELLATION_TOMBSTONES = 1024;
327
+ /**
328
+ * Per-incarnation cancellation registry for long-lived progress and settlement RPCs. The runtime owns
329
+ * the actual wake registration; this host-only registry lets an interrupted Worker Effect ask
330
+ * the Object to interrupt its scoped wait before the Worker execution context itself ends.
331
+ */
332
+ var ProgressWaitRegistry = class ProgressWaitRegistry extends Context.Service()("@effect-agent/platform-cloudflare/ProgressWaitRegistry") {
333
+ static layer = Layer.effect(ProgressWaitRegistry, Effect.gen(function* () {
334
+ const registrations = yield* Ref.make(/* @__PURE__ */ new Map());
335
+ const remove = (waiterId, deferred) => Ref.update(registrations, (current) => {
336
+ const existing = current.get(waiterId);
337
+ if (existing === void 0 || existing === "cancelled" || !existing.has(deferred)) return current;
338
+ const next = new Map(current);
339
+ const active = new Set(existing);
340
+ active.delete(deferred);
341
+ if (active.size === 0) next.delete(waiterId);
342
+ else next.set(waiterId, active);
343
+ return next;
344
+ });
345
+ const subscribe = Effect.fnUntraced(function* (waiterId) {
346
+ const deferred = yield* Deferred.make();
347
+ yield* Effect.addFinalizer(() => remove(waiterId, deferred));
348
+ const cancelled = yield* Ref.modify(registrations, (current) => {
349
+ const existing = current.get(waiterId);
350
+ const next = new Map(current);
351
+ if (existing === "cancelled") return [true, current];
352
+ const active = new Set(existing ?? []);
353
+ active.add(deferred);
354
+ next.set(waiterId, active);
355
+ return [false, next];
356
+ });
357
+ return yield* Effect.succeed(cancelled ? Effect.void : Deferred.await(deferred));
358
+ });
359
+ const cancel = Effect.fnUntraced(function* (waiterId) {
360
+ const waiters = yield* Ref.modify(registrations, (current) => {
361
+ const existing = current.get(waiterId);
362
+ if (existing === "cancelled") return [[], current];
363
+ const next = new Map(current);
364
+ next.delete(waiterId);
365
+ next.set(waiterId, "cancelled");
366
+ let tombstones = 0;
367
+ for (const registration of next.values()) if (registration === "cancelled") tombstones += 1;
368
+ if (tombstones > MAX_CANCELLATION_TOMBSTONES) for (const [id, registration] of next) {
369
+ if (registration !== "cancelled") continue;
370
+ next.delete(id);
371
+ break;
372
+ }
373
+ return [existing === void 0 ? [] : [...existing], next];
374
+ });
375
+ yield* Effect.forEach(waiters, (waiter) => Deferred.succeed(waiter, void 0), { discard: true });
376
+ }, Effect.uninterruptible);
377
+ return ProgressWaitRegistry.of({
378
+ subscribe,
379
+ cancel
380
+ });
381
+ }));
382
+ };
383
+ // src/internal/transport.ts
384
+ /**
385
+ * `ThreadPortTransport` over native Durable Object JS RPC (decision D-P6-3): one
386
+ * `portCall(envelope)` on the stub of the Object that owns the addressed Thread
387
+ * (`namespace.idFromName(threadId)` — the identity rule, plan §1.2). The envelopes are
388
+ * already Schema-encoded JSON, so the RPC boundary carries only structured-cloneable values;
389
+ * the protocol module stays transport-agnostic and fetch-with-JSON remains the documented
390
+ * fallback carrier.
391
+ * The namespace's optional `rpcTracing` setting uses the same transient trailing context
392
+ * as host calls; it never changes the encoded port envelope.
393
+ *
394
+ * Every delivery problem — stub construction, RPC rejection, overload, deploy-in-progress —
395
+ * surfaces as `PortTransportError` (preserving the platform stub's own `retryable` signal
396
+ * when present) and NEVER as a fabricated answer: on `resolveAdmission` the routing layer
397
+ * turns exactly this error into `AdmissionIndeterminate` (SUB-031).
398
+ */
399
+ const threadPortTransportLayer = Layer.effect(ThreadPortTransport)(Effect.gen(function* () {
400
+ const namespace = yield* ThreadObjectNamespace;
401
+ const { rpcTracing } = namespace;
402
+ return ThreadPortTransport.of({ call: Effect.fnUntraced(function* (threadId, request) {
403
+ const traceArgs = rpcTracing === void 0 ? [] : yield* RpcTracing.withRpcTraceContext([]);
404
+ return yield* callThreadObject(threadId, (target) => target.portCall(request, ...traceArgs), (cause) => portTransportFailure(threadId, cause)).pipe(Effect.provideService(ThreadObjectNamespace, namespace));
405
+ }, (effect, threadId) => rpcTracing === void 0 ? Effect.withSpan(effect, "CloudflarePortTransport.call", { attributes: { threadId } }) : RpcTracing.withRpcClientSpan(effect, rpcTracing, "portCall")) });
406
+ }));
407
+ // src/internal/layers.ts
408
+ /**
409
+ * Owner-side execution port for a `portCall` request the wire endpoint has already decoded.
410
+ * It executes against THIS Object's LOCAL port facets — never the routed decorators, so a
411
+ * request cannot bounce between Objects — and returns the typed response for the endpoint to
412
+ * encode.
413
+ */
414
+ var ThreadObjectPorts = class extends Context.Service()("@effect-agent/platform-cloudflare/ThreadObjectPorts") {};
415
+ const decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);
416
+ const decodeThreadId = Schema.decodeUnknownEffect(ThreadId);
417
+ const decodeProducerId = Schema.decodeUnknownEffect(ProducerId);
418
+ const configFromOptions = (options) => decodeConfigValue({
419
+ deploymentId: options.deploymentId,
420
+ producerPrefix: options.producerPrefix,
421
+ recoveryWindowMillis: options.recoveryWindowMillis ?? CLOUDFLARE_RUNTIME_DEFAULTS.recoveryWindowMillis,
422
+ alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,
423
+ alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,
424
+ settlementPollInterval: options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,
425
+ abortPollInterval: options.abortPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.abortPollInterval,
426
+ observationPollInterval: options.observationPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.observationPollInterval,
427
+ projectionDispatchTimeoutMillis: options.projectionDispatchTimeoutMillis ?? CLOUDFLARE_RUNTIME_DEFAULTS.projectionDispatchTimeoutMillis,
428
+ maxStoredValueBytes: options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,
429
+ verifyOnOpen: options.verifyOnOpen ?? CLOUDFLARE_RUNTIME_DEFAULTS.verifyOnOpen,
430
+ limits: {
431
+ maxQueueDepthPerLane: options.maxQueueDepthPerLane ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxQueueDepthPerLane,
432
+ maxInputBytes: Math.min(options.maxInputBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxInputBytes, options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes),
433
+ maxDatabaseBytes: options.maxDatabaseBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxDatabaseBytes
434
+ }
435
+ }).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
436
+ message: `Invalid Cloudflare durable runtime configuration: ${error.message}`,
437
+ cause: error
438
+ })));
439
+ /**
440
+ * The Thread this Object owns, from the Object identity rule (plan §1.2): Thread
441
+ * Objects are addressed exclusively by `idFromName(threadId)`, so `ctx.id.name` IS the
442
+ * Thread ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.
443
+ */
444
+ const threadIdFromState = (ctx) => ctx.id.name === void 0 ? Effect.fail(CloudflarePlatformConfigError.make({ message: "This Durable Object was not created via idFromName(threadId); Thread Objects must be addressed by their Thread identity (plan §1.2)." })) : decodeThreadId(ctx.id.name).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
445
+ message: `The Durable Object name is not a valid ThreadId: ${error.message}`,
446
+ cause: error
447
+ })));
448
+ /**
449
+ * Validate deployment settings and derive services before building application dependencies.
450
+ * The native class factory builds this Layer inside its constructor gate. Custom Effect hosts
451
+ * can provide it around the complete application Layer with the native context already supplied.
452
+ */
453
+ const runtimeConfigLayer = (options, producerId) => Layer.unwrap(Effect.gen(function* () {
454
+ const { ctx } = yield* DurableObjectContext;
455
+ const config = yield* configFromOptions(options);
456
+ return Layer.mergeAll(Layer.succeed(CloudflareDurableRuntimeConfig, config), DurableRuntimeConfig.layer({
457
+ deploymentId: config.deploymentId,
458
+ producerId,
459
+ settlementPollInterval: Duration.millis(config.settlementPollInterval),
460
+ abortPollInterval: Duration.millis(config.abortPollInterval),
461
+ ...options.estimateCostMicrousd === void 0 ? {} : { estimateCostMicrousd: options.estimateCostMicrousd }
462
+ }), cloudflareCryptoLayer, LiveTextHub.layer, storageFailpointLayer({
463
+ storage: ctx.storage,
464
+ failpoint: options.storageFailpoint?.(ctx)
465
+ }), options.runtimeFailpoint === void 0 ? DurableRuntimeFailpoint.layer : Layer.succeed(DurableRuntimeFailpoint, { hit: options.runtimeFailpoint(ctx) }), options.maintenanceFailpoint === void 0 ? ThreadMaintenanceFailpoint.layer : Layer.succeed(ThreadMaintenanceFailpoint, { hit: options.maintenanceFailpoint(ctx) }), options.toolReconciler ?? ToolReconciler.uncertain, options.operationAuthorizer === void 0 ? Layer.empty : operationAuthorizerLayer(options.operationAuthorizer), options.toolFailureObserver === void 0 ? Layer.succeed(CurrentToolFailureObserver, void 0) : toolFailureObserverLayer(options.toolFailureObserver), RunContextPreparationPassthrough, RunToolAuthorization.allowAll);
466
+ }));
467
+ const producerIdentity = (prefix, owner) => decodeProducerId(`${prefix}:${owner}`).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
468
+ message: `The minted producer identity is invalid: ${error.message}`,
469
+ cause: error
470
+ })));
471
+ /** Native one-Thread configuration; retains its existing producer and logical identities. */
472
+ const layerConfig = (options) => Layer.unwrap(Effect.gen(function* () {
473
+ const { ctx } = yield* DurableObjectContext;
474
+ const threadId = yield* threadIdFromState(ctx);
475
+ const producerId = yield* producerIdentity(options.producerPrefix, threadId);
476
+ return Layer.mergeAll(runtimeConfigLayer(options, producerId), Layer.succeed(ThreadObjectIdentity, {
477
+ threadId,
478
+ producerId
479
+ }), Layer.succeed(ThreadObjectPlacement, {
480
+ threadId,
481
+ ownsThread: (target) => target === threadId
482
+ }));
483
+ }));
484
+ /**
485
+ * Configuration for an application Object owning several logical Threads. The producer is
486
+ * the stable physical Object. No logical identity is installed globally: handleRpc binds and
487
+ * validates it per request using the placement guard and this actual runtime producer.
488
+ */
489
+ const layerHostConfig = (options, ownsThread) => Layer.unwrap(Effect.gen(function* () {
490
+ const { ctx } = yield* DurableObjectContext;
491
+ const producerId = yield* producerIdentity(options.producerPrefix, ctx.id.toString());
492
+ return Layer.merge(runtimeConfigLayer(options, producerId), Layer.succeed(ThreadObjectPlacement, { ownsThread }));
493
+ }));
494
+ /**
495
+ * Register typed Agents and version declarations. Hashing and dependency capture happen in
496
+ * this Layer's Scope, after application Layers have been provided. Every Agent's instruction,
497
+ * Tool, Schema, and model requirements remain visible until satisfied by Layer composition.
498
+ * Use Layer.unwrap for registration values that need effectful application setup.
499
+ */
500
+ const registeredLayer = (registrations, options = {}) => Layer.unwrap(Effect.map(compileRegistrations(registrations), (bindings) => boundLayer(bindings, options)));
501
+ function layer(registrations, options = {}) {
502
+ return registeredLayer(registrations, options);
503
+ }
504
+ /**
505
+ * Assemble the durable runtime from already-resolved Agent Bindings.
506
+ * Use `ThreadObject.layer` to compile typed Agent registrations instead.
507
+ * Supply host services through `ThreadObject.make` or `ThreadObject.layerConfig` and
508
+ * the Durable Object context and namespace Layers when composing a custom host.
509
+ */
510
+ const boundLayer = (bindings, options = {}) => Layer.unwrap(Effect.map(DurableObjectContext, ({ ctx }) => sharedLayer(DurableAgentRuntime.layerWithBindings(bindings), options).pipe(Layer.provideMerge(SqliteClient.layer({ storage: ctx.storage })))));
511
+ function layerInHost(application, options = {}) {
512
+ return sharedLayer(application, options);
513
+ }
514
+ const sharedLayer = (application, options = {}) => Layer.unwrap(Effect.gen(function* () {
515
+ const { ctx } = yield* DurableObjectContext;
516
+ const config = yield* CloudflareDurableRuntimeConfig;
517
+ const placement = yield* ThreadObjectPlacement;
518
+ const scheduling = yield* DurableObjectAlarm.ScheduleConfiguration;
519
+ const { ownsThread } = placement;
520
+ const storageOptions = {
521
+ storage: ctx.storage,
522
+ observationPollInterval: config.observationPollInterval,
523
+ maxStoredValueBytes: config.maxStoredValueBytes,
524
+ verifyOnOpen: config.verifyOnOpen
525
+ };
526
+ const infrastructure = Layer.suspend(() => Layer.mergeAll(options.lifecyclePublication === void 0 ? Layer.empty : lifecyclePublicationLayer, storageConfigLayer(storageOptions), Layer.effect(SqlClient.SqlClient)(SqlClient.SqlClient)));
527
+ const sourceOwner = Layer.effect(SqlStorageOwner)(Effect.gen(function* () {
528
+ const owner = yield* SqlStorageOwner;
529
+ const mutations = yield* ThreadMutationGate;
530
+ if (owner === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("SQL owner unavailable"));
531
+ return {
532
+ identity: owner.identity ?? owner,
533
+ read: owner.read,
534
+ invalidators: owner.invalidators,
535
+ transaction: (body) => owner.read(mutations.withTransaction(body).pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Effect.sync(() => {
536
+ for (const invalidate of owner.invalidators) invalidate();
537
+ }) : Effect.void)))
538
+ };
539
+ })).pipe(Layer.provide(sqlOwnerLayer));
540
+ const localInfrastructure = Layer.suspend(() => Layer.mergeAll(infrastructure, sourceOwner));
541
+ const sourceProgress = Layer.effect(SqlStorageProgress)(Effect.gen(function* () {
542
+ const mutations = yield* ThreadMutationGate;
543
+ return { committed: (kind) => {
544
+ const lanes = Match.value(kind).pipe(Match.when("canonical", () => [
545
+ Native,
546
+ Publication,
547
+ ...options.projection === void 0 ? [] : [Projection]
548
+ ]), Match.whenOr("submission", "control", () => [Native, Publication]), Match.when("work-index", () => [Native]), Match.when("delivery", () => [Messages, ...options.lifecyclePublication === void 0 ? [] : [Lifecycle]]), Match.whenOr("lifecycle", "lifecycle-ack", () => options.lifecyclePublication === void 0 ? [] : [Lifecycle]), Match.exhaustive);
549
+ return mutations.recordProgress(lanes).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (failure) => SqlStorageProgressError.make({
550
+ operation: "record maintenance progress",
551
+ message: "Committed source work could not enroll maintenance",
552
+ cause: failure
553
+ })))));
554
+ } };
555
+ }));
556
+ const rawLocalPorts = Layer.suspend(() => Layer.mergeAll(threadStoreLayer, submissionLedgerLayer).pipe(Layer.provide(journalLayer), Layer.provide(localInfrastructure), Layer.provide(sourceProgress)));
557
+ const base = Layer.suspend(() => Layer.mergeAll(DurableAlarmService.layer, ProgressWaitRegistry.layer));
558
+ const wakes = cloudflareWakeSchedulerLayer.pipe(Layer.provide(base));
559
+ const messageStore = Layer.suspend(() => guardedMessageDeliveryStoreLayer.pipe(Layer.provide(doMessageDeliveryStoreLayer().pipe(Layer.provide(localInfrastructure), Layer.provide(sourceProgress))), Layer.provide(wakes)));
560
+ const messageRecovery = Layer.suspend(() => lazyThreadMessageDeliveryLayer(MessageDeliveryDriver.layer({
561
+ batchSize: 4,
562
+ concurrency: 4
563
+ }).pipe(Layer.provide(cloudflarePreparedInputAdmissionLayer), Layer.provide(CloudflareThreadClient.layer), Layer.provide(messageStore), Layer.provide(wakes))).pipe(Layer.provide(messageStore)));
564
+ const publication = options.publication === void 0 ? ThreadPublication.layer : options.publication.pipe(Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient.SqlClient)(SqlClient.SqlClient))));
565
+ const projection = options.projection === void 0 ? ThreadProjectionMaintenance.layer : options.projection.pipe(Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient.SqlClient)(SqlClient.SqlClient))));
566
+ const localPorts = options.publication === void 0 && options.projection === void 0 && options.hostLanesForMutation === void 0 && options.lifecyclePublication === void 0 ? rawLocalPorts : Layer.effectContext(Effect.gen(function* () {
567
+ const store = yield* ThreadStore;
568
+ const ledger = yield* SubmissionLedger;
569
+ const storageOwner = yield* StorageOwner;
570
+ const settlementPublisher = yield* SettlementPublisher;
571
+ const mutations = yield* ThreadMutationGate;
572
+ const index = yield* ThreadProjectionMaintenance;
573
+ const publish = yield* Effect.context();
574
+ const afterCommit = publishCommitted.pipe(Effect.provide(publish));
575
+ const sourceCommits = yield* Semaphore.make(1);
576
+ const observeAppend = (request, body) => mutations.withMutation(sourceCommits.withPermit(body.pipe(Effect.tap((result) => index.applyCommitted(request, result).pipe(Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.logError("Thread projection deferred after source commit", cause)))))).pipe(Effect.tap(() => afterCommit)), { lanes: [...options.projection === void 0 ? [] : [Projection], ...options.lifecyclePublication === void 0 || !request.batch.records.some((record) => Schema.is(Schema.toType(LifecyclePublicationFact))(record.payload)) ? [] : [Lifecycle]] }).pipe(Effect.catchTag("DurableAlarmError", (cause) => ThreadStoreError.make({
577
+ operation: "prearm publication append",
578
+ message: cause.message,
579
+ cause
580
+ })));
581
+ const observedStore = ThreadStore.of({
582
+ ...store,
583
+ ...store.lifecyclePublications === void 0 ? {} : { lifecyclePublications: {
584
+ ...store.lifecyclePublications,
585
+ retryParked: (ownerThreadId, nowMillis) => mutations.withMutation(store.lifecyclePublications.retryParked(ownerThreadId, nowMillis), {
586
+ invalidatesRecovery: false,
587
+ lanes: [Lifecycle]
588
+ }).pipe(Effect.catchTag("DurableAlarmError", (cause) => LifecyclePublicationError.make({
589
+ reason: "unavailable",
590
+ cause
591
+ })))
592
+ } },
593
+ append: (request) => observeAppend(request, store.append(request))
594
+ });
595
+ const observeIntent = (body, invalidatesRecovery = true, hostLanes = []) => mutations.withMutation(body.pipe(Effect.tap(() => invalidatesRecovery ? afterCommit : Effect.void)), {
596
+ invalidatesRecovery,
597
+ lanes: [...hostLanes, ...options.lifecyclePublication === void 0 ? [] : [Lifecycle]]
598
+ }).pipe(Effect.catchTag("DurableAlarmError", (cause) => LedgerError.make({
599
+ operation: "prearm publication intent",
600
+ message: "The publication generation could not be armed",
601
+ cause
602
+ })));
603
+ const observeMutation = (mutation, body, invalidatesRecovery) => Effect.suspend(() => Schema.decodeEffect(Schema.Array(HostLaneId))([...new Set(options.hostLanesForMutation?.(mutation) ?? [])])).pipe(Effect.mapError((cause) => LedgerError.make({
604
+ operation: "select host maintenance lanes",
605
+ message: "Native mutation selected an invalid host lane ID",
606
+ cause
607
+ })), Effect.flatMap((lanes) => observeIntent(body, invalidatesRecovery, lanes)));
608
+ const stopWorker = ledger.stopWorker;
609
+ const appendInput = ledger.appendInput;
610
+ return Context.make(ThreadStore, observedStore).pipe(Context.add(StorageOwner, storageOwner), Context.add(SettlementPublisher, { publish: Effect.fnUntraced(function* (input) {
611
+ const { request } = yield* validatePublication(input);
612
+ return yield* mutations.withMutation(sourceCommits.withPermit(settlementPublisher.publish(request).pipe(Effect.tap((result) => result.replayed ? Effect.void : index.applyCommitted(request.append, AppendResult.make({
613
+ firstSequence: result.tailSequence,
614
+ lastSequence: result.tailSequence,
615
+ replayed: false
616
+ })).pipe(Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.logError("Thread projection deferred after settlement publication", cause)))))).pipe(Effect.tap(() => afterCommit)), { lanes: [...options.projection === void 0 ? [] : [Projection], ...options.lifecyclePublication === void 0 ? [] : [Lifecycle]] }).pipe(Effect.catchTag("DurableAlarmError", (cause) => ThreadStoreError.make({
617
+ operation: "prearm settlement publication",
618
+ message: cause.message,
619
+ cause
620
+ })));
621
+ }) }), Context.add(SubmissionLedger, {
622
+ ...ledger,
623
+ ...appendInput === void 0 ? {} : { appendInput: (submissionId, input) => Effect.flatMap(PreparedAppend.capture(input), (request) => observeAppend(request, appendInput(submissionId, request))) },
624
+ ...options.hostLanesForMutation === void 0 && options.lifecyclePublication === void 0 ? {} : { admit: (...args) => observeMutation({
625
+ _tag: "Admission",
626
+ request: args[0]
627
+ }, ledger.admit(...args), false) },
628
+ ...options.lifecyclePublication === void 0 ? {} : {
629
+ markReady: (request) => observeIntent(ledger.markReady(request), false),
630
+ suspend: (request) => observeIntent(ledger.suspend(request), false),
631
+ markUnknown: (request) => observeIntent(ledger.markUnknown(request), false),
632
+ recordChildSettled: (request) => observeIntent(ledger.recordChildSettled(request), false)
633
+ },
634
+ ...options.lifecyclePublication === void 0 && options.hostLanesForMutation === void 0 ? {} : { finalizeSettlement: (request) => observeMutation({
635
+ _tag: "Settlement",
636
+ request
637
+ }, ledger.finalizeSettlement(request), false) },
638
+ recordApprovalDecision: (request) => observeIntent(ledger.recordApprovalDecision(request)),
639
+ ...stopWorker === void 0 ? {} : { stopWorker: (request) => observeMutation({
640
+ _tag: "WorkerStop",
641
+ request
642
+ }, stopWorker(request), true) },
643
+ requestAbort: (request) => observeIntent(ledger.requestAbort(request)),
644
+ recordUnknownResolution: (request) => observeIntent(ledger.recordUnknownResolution(request))
645
+ }));
646
+ })).pipe(Layer.provide(rawLocalPorts));
647
+ const portsEndpointLayer = Layer.effect(ThreadObjectPorts)(Effect.gen(function* () {
648
+ const local = yield* Effect.context().pipe(Effect.map(Context.omit(DurableObjectAlarm.ScheduleConfiguration)));
649
+ const lookupSubmission = makeLocalSubmissionLookup({ ownsThread });
650
+ return ThreadObjectPorts.of({
651
+ handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),
652
+ lookupSubmission: (submissionId) => lookupSubmission(submissionId).pipe(Effect.provide(local))
653
+ });
654
+ })).pipe(Layer.provide(localPorts), Layer.provide(messageStore), Layer.provide(wakes));
655
+ const routedPorts = Layer.mergeAll(Layer.effect(StorageOwner, StorageOwner), routedSubmissionLedgerLayer({ ownsThread }), routedSettlementPublisherLayer({ ownsThread }), routedThreadStoreLayer({ ownsThread }), routedWorkerAdmissionLayer({ ownsThread })).pipe(Layer.provide(localPorts), Layer.provide(threadPortTransportLayer));
656
+ const routedMessages = routedMessageDeliveryStoreLayer({ ownsThread }).pipe(Layer.provide(messageStore), Layer.provide(threadPortTransportLayer));
657
+ const runtimeStack = Layer.suspend(() => application.pipe(Layer.provideMerge(layer$1), Layer.provide(cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer))), Layer.provideMerge(routedMessages), Layer.provideMerge(routedPorts), Layer.provideMerge(wakes), Layer.provideMerge(base), Layer.provideMerge(portsEndpointLayer)));
658
+ const maintenanceRuntime = options.lifecyclePublication === void 0 ? runtimeStack : Layer.merge(runtimeStack, Layer.effect(ThreadNativeMaintenance)(Effect.gen(function* () {
659
+ const previous = yield* ThreadNativeMaintenance;
660
+ const storage = (yield* ThreadStore).lifecyclePublications;
661
+ const context = yield* Effect.context();
662
+ const failure = (cause) => {
663
+ const error = DurableAlarmError.make({
664
+ operation: "publish native lifecycle",
665
+ message: "Native lifecycle publication remains pending",
666
+ cause
667
+ });
668
+ return ErrorReporter.isIgnored(cause) ? Object.assign(error, { [ErrorReporter.ignore]: true }) : error;
669
+ };
670
+ const deadline = (storage === void 0 ? Effect.fail(failure("Native lifecycle storage unavailable")) : storage.pendingDeadline.pipe(Effect.mapError(failure))).pipe(Effect.withErrorReporting, Effect.catchCauseIf((cause) => !Cause.hasInterrupts(cause), (cause) => Effect.logError("Lifecycle publication deadline unavailable", cause).pipe(Effect.andThen(Effect.map(Clock.currentTimeMillis, (now) => Option.some(now + 6e4))))));
671
+ return { lanes: [...previous.lanes, {
672
+ id: Lifecycle,
673
+ dispatchTimeoutMillis: 6e4,
674
+ run: storage === void 0 ? Effect.fail(failure("Native lifecycle storage unavailable")) : drainLifecyclePublications(storage).pipe(Effect.provide(context), Effect.mapError(failure), Effect.andThen(deadline))
675
+ }] };
676
+ })).pipe(Layer.provide(rawLocalPorts), Layer.provide(options.lifecyclePublication.pipe(Layer.provide(rawLocalPorts))), Layer.provide(runtimeStack)));
677
+ return Layer.mergeAll(maintenanceRuntime, ThreadMaintenance.layer.pipe(Layer.provide(options.recoveryEvents ?? Layer.empty), Layer.provide(Layer.effect(ThreadNativeMaintenance)(Effect.gen(function* () {
678
+ const previous = yield* ThreadNativeMaintenance;
679
+ const runtime = yield* DurableAgentRuntime;
680
+ return {
681
+ lanes: previous.lanes,
682
+ ...placement.threadId === void 0 ? {} : { singleThreadRuntime: runtime }
683
+ };
684
+ }))), Layer.provide(maintenanceRuntime), Layer.provide(messageRecovery)), portsEndpointLayer, routedMessages, messageRecovery).pipe(Layer.provideMerge(sourceProgress), Layer.provideMerge(publication), Layer.provideMerge(projection), Layer.provideMerge(sourceOwner), Layer.provideMerge(ThreadMutationGate.layer), Layer.provideMerge(infrastructure), Layer.provideMerge(Layer.succeed(DurableObjectAlarm.ScheduleConfiguration, {
685
+ ...scheduling,
686
+ inFlightRecovery: config.recoveryWindowMillis || (scheduling.inFlightRecovery ?? 1e3)
687
+ })));
688
+ }));
689
+ // src/ThreadObject.ts
690
+ var ThreadObject_exports = /* @__PURE__ */ __exportAll({
691
+ AdminExplainRequest: () => AdminExplainRequest,
692
+ AdminFailed: () => AdminFailed,
693
+ AdminFailure: () => AdminFailure,
694
+ AdminResponse: () => AdminResponse,
695
+ AdminVerifyRequest: () => AdminVerifyRequest,
696
+ ExplainedRecovery: () => ExplainedRecovery,
697
+ ObligationsScanned: () => ObligationsScanned,
698
+ RetryExecuted: () => RetryExecuted,
699
+ ThreadObjectPorts: () => ThreadObjectPorts,
700
+ ThreadRpcOperation: () => ThreadRpcOperation,
701
+ VerifiedIntegrity: () => VerifiedIntegrity,
702
+ alarms: () => alarms,
703
+ decodeAdminExplainRequest: () => decodeAdminExplainRequest,
704
+ decodeAdminResponse: () => decodeAdminResponse,
705
+ decodeAdminVerifyRequest: () => decodeAdminVerifyRequest,
706
+ decodeObligationThresholds: () => decodeObligationThresholds,
707
+ decodeRetryCommand: () => decodeRetryCommand,
708
+ encodeAdminResponse: () => encodeAdminResponse,
709
+ handleRpc: () => handleRpc,
710
+ layer: () => layer,
711
+ layerConfig: () => layerConfig,
712
+ layerHostConfig: () => layerHostConfig,
713
+ layerInHost: () => layerInHost,
714
+ make: () => make,
715
+ portCall: () => portCall,
716
+ submit: () => submit
717
+ });
718
+ /** Classify only a decoded port request so new protocol members cannot bypass pre-arming. */
719
+ const isMutatingPortRequest = (request) => {
720
+ switch (request._tag) {
721
+ case "WorkerAdmit":
722
+ case "LedgerAdmit":
723
+ case "LedgerMarkReady":
724
+ case "LedgerStopWorker":
725
+ case "LedgerRequestAbort":
726
+ case "LedgerRecordChildSettled":
727
+ case "StoreMaterialize":
728
+ case "StoreAppend":
729
+ case "StoreWorkRebuild":
730
+ case "StoreRangeSeal":
731
+ case "StoreRangeArchive":
732
+ case "SettlementPublish":
733
+ case "MessageDeliveryComplete": return true;
734
+ case "LedgerInspectWorker":
735
+ case "LedgerLookup":
736
+ case "LedgerResolveAdmission":
737
+ case "LedgerFundingOwner":
738
+ case "StoreReadPage":
739
+ case "StoreReadPrompt":
740
+ case "StoreReadExecution":
741
+ case "StoreWorkPage":
742
+ case "StoreInspectTail":
743
+ case "StoreReadIdentity":
744
+ case "StoreCountPeerMessages":
745
+ case "StoreExport":
746
+ case "StoreRangePage":
747
+ case "StoreRangeVerify":
748
+ case "StoreVerification":
749
+ case "StoreWorkerCapacity":
750
+ case "MessageDeliveryList": return false;
751
+ }
752
+ return false;
753
+ };
754
+ /** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */
755
+ const encodedPortProtocolFailure = (message) => ({
756
+ _tag: "PortFailed",
757
+ failure: {
758
+ _tag: "PortProtocolError",
759
+ message: boundHostDiagnostic(message)
760
+ }
761
+ });
762
+ const protocolFailure = (context) => (error) => HostProtocolError.make({ message: boundHostDiagnostic(`${context}: ${error.message}`) });
763
+ /** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */
764
+ const respond = (effect) => effect.pipe(Effect.map((result) => result), Effect.catch((failure) => Effect.succeed(HostFailed.make({ failure }))));
765
+ /** Encode the response envelope; an unencodable response degrades to a protocol failure. */
766
+ const encodeResponse = (response) => encodeHostResponse(response).pipe(Effect.catch((error) => Effect.succeed({
767
+ _tag: "HostFailed",
768
+ failure: {
769
+ _tag: "HostProtocolError",
770
+ message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`)
771
+ }
772
+ })));
773
+ const utf8Bytes = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
774
+ /**
775
+ * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate
776
+ * "resource limits are checked before admission"; DEPLOY-007). A replayed idempotency key is
777
+ * exempt: its accepted-work obligation already exists, and returning the original Receipt
778
+ * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.
779
+ */
780
+ const gateAdmissionLimits = Effect.fnUntraced(function* (threadId, request) {
781
+ const config = yield* CloudflareDurableRuntimeConfig;
782
+ const ledger = yield* SubmissionLedger;
783
+ const { ctx } = yield* DurableObjectContext;
784
+ const refuseFresh = (error) => ledger.lookup(SubmissionLookupByKey.make({
785
+ threadId,
786
+ principal: request.principal,
787
+ idempotencyKey: request.idempotencyKey
788
+ })).pipe(Effect.flatMap((existing) => Option.isSome(existing) ? Effect.void : Effect.fail(error)));
789
+ const inputBytes = utf8Bytes(request.inputPayload);
790
+ if (inputBytes > config.limits.maxInputBytes) return yield* refuseFresh(AdmissionLimitExceeded.make({
791
+ limit: "input-bytes",
792
+ actual: inputBytes,
793
+ maximum: config.limits.maxInputBytes
794
+ }));
795
+ const queueDepth = yield* Stream.runFold(ledger.scanNonterminal, () => 0, (depth, submission) => depth + (submission.threadId === threadId ? 1 : 0));
796
+ if (queueDepth >= config.limits.maxQueueDepthPerLane) return yield* refuseFresh(AdmissionLimitExceeded.make({
797
+ limit: "queue-depth",
798
+ actual: queueDepth,
799
+ maximum: config.limits.maxQueueDepthPerLane
800
+ }));
801
+ const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);
802
+ if (databaseBytes > config.limits.maxDatabaseBytes) return yield* refuseFresh(AdmissionLimitExceeded.make({
803
+ limit: "database-bytes",
804
+ actual: databaseBytes,
805
+ maximum: config.limits.maxDatabaseBytes
806
+ }));
807
+ });
808
+ /**
809
+ * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived
810
+ * already encoded through the real input schema on the Worker side (`client.ts`), so the
811
+ * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives
812
+ * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).
813
+ */
814
+ const passthroughSubmitAgent = (agentId) => ({ definition: {
815
+ id: agentId,
816
+ input: PersistedJson
817
+ } });
818
+ /** A physical owner may hold other Threads; an addressed request cannot act on their IDs. */
819
+ const lookupAddressedSubmission = Effect.fnUntraced(function* (submissionId) {
820
+ const { threadId } = yield* ThreadObjectIdentity;
821
+ const submission = yield* (yield* ThreadObjectPorts).lookupSubmission(submissionId);
822
+ if (Option.isSome(submission) && submission.value.threadId !== threadId) return yield* HostProtocolError.make({ message: "The Submission belongs to another Thread" });
823
+ return submission;
824
+ });
825
+ const requireSubmissionThread = Effect.fnUntraced(function* (submissionId) {
826
+ const submission = yield* lookupAddressedSubmission(submissionId);
827
+ if (Option.isNone(submission)) return yield* LedgerError.make({
828
+ operation: "addressed Submission lookup",
829
+ message: "The addressed Thread has no such Submission"
830
+ });
831
+ });
832
+ const requireReceiptThread = Effect.fnUntraced(function* (threadId) {
833
+ if (threadId !== (yield* ThreadObjectIdentity).threadId) return yield* HostProtocolError.make({ message: "The Receipt belongs to another Thread" });
834
+ });
835
+ const requirePortThread = (request) => {
836
+ switch (request._tag) {
837
+ case "SettlementPublish": return requireReceiptThread(request.request.append.threadId).pipe(Effect.andThen(requireSubmissionThread(request.request.submissionId)));
838
+ case "MessageDeliveryComplete": return requireReceiptThread(request.key.ownerThreadId);
839
+ case "MessageDeliveryList": return requireReceiptThread(request.request.ownerThreadId);
840
+ case "LedgerLookup": return request.request._tag === "SubmissionLookupById" ? lookupAddressedSubmission(request.request.submissionId).pipe(Effect.asVoid) : requireReceiptThread(request.request.threadId);
841
+ case "LedgerMarkReady":
842
+ case "LedgerRequestAbort": return requireSubmissionThread(request.request.submissionId);
843
+ case "LedgerRecordChildSettled": return requireSubmissionThread(request.request.parentSubmissionId);
844
+ case "LedgerFundingOwner": return requireReceiptThread(request.request.threadId).pipe(Effect.andThen(requireSubmissionThread(request.request.submissionId)));
845
+ case "LedgerInspectWorker":
846
+ case "LedgerStopWorker":
847
+ case "WorkerAdmit":
848
+ case "LedgerAdmit":
849
+ case "LedgerResolveAdmission":
850
+ case "StoreMaterialize":
851
+ case "StoreAppend":
852
+ case "StoreReadPage":
853
+ case "StoreReadPrompt":
854
+ case "StoreReadExecution":
855
+ case "StoreInspectTail":
856
+ case "StoreReadIdentity":
857
+ case "StoreCountPeerMessages":
858
+ case "StoreExport":
859
+ case "StoreWorkPage":
860
+ case "StoreWorkRebuild":
861
+ case "StoreRangePage":
862
+ case "StoreRangeSeal":
863
+ case "StoreRangeArchive":
864
+ case "StoreRangeVerify":
865
+ case "StoreVerification":
866
+ case "StoreWorkerCapacity": return requireReceiptThread(request.request.threadId);
867
+ }
868
+ };
869
+ /**
870
+ * Admit an already Schema-decoded request to a logical Thread in this physical owner.
871
+ * Custom hosts validate local placement before calling this Effect and provide their same
872
+ * runtime, maintenance and alarm instances. The native endpoint uses this path too: queue limits,
873
+ * idempotent receipts and the pre-admission generation/alarm commit have one owner.
874
+ */
875
+ const submit = Effect.fnUntraced(function* (threadId, request) {
876
+ if (!(yield* ThreadObjectPlacement).ownsThread(threadId)) return yield* HostProtocolError.make({ message: "The Thread belongs to another Object" });
877
+ const mutations = yield* ThreadMutationGate;
878
+ const runtime = yield* DurableAgentRuntime;
879
+ const alarm = yield* DurableAlarmService;
880
+ yield* gateAdmissionLimits(threadId, request);
881
+ return yield* mutations.withMutation(runtime.submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {
882
+ threadId,
883
+ principal: request.principal,
884
+ idempotencyKey: request.idempotencyKey,
885
+ ...request.admissionGroup === void 0 ? {} : { admissionGroup: request.admissionGroup },
886
+ ...request.admissionFence === void 0 ? {} : { admissionFence: request.admissionFence },
887
+ ...request.workerAdmission === void 0 ? {} : { workerAdmission: request.workerAdmission },
888
+ ...request.messageAdmission === void 0 ? {} : { messageAdmission: request.messageAdmission },
889
+ definitions: request.definitions
890
+ }).pipe(alarm.withHintsDeferred, Effect.tap(() => publishCommitted)));
891
+ });
892
+ const submitEndpoint = (encoded) => decodeSubmitRequest(encoded).pipe(Effect.mapError(protocolFailure("The submit request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
893
+ const identity = yield* ThreadObjectIdentity;
894
+ const receipt = yield* submit(identity.threadId, request);
895
+ if ((yield* DurableObjectAlarm.ScheduleConfiguration).dispatchAfterEvent === true) yield* (yield* ThreadMaintenance).start(receipt);
896
+ return SubmitSucceeded.make({ receipt });
897
+ })), respond, Effect.flatMap(encodeResponse));
898
+ const submissionStatusEndpoint = (encoded) => decodeReceipt(encoded).pipe(Effect.mapError(protocolFailure("The receipt could not be decoded")), Effect.flatMap((receipt) => Effect.gen(function* () {
899
+ yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
900
+ operation: "awaitSettlement",
901
+ threadId: receipt.threadId,
902
+ submissionId: receipt.submissionId
903
+ }));
904
+ yield* requireReceiptThread(receipt.threadId);
905
+ yield* requireSubmissionThread(receipt.submissionId);
906
+ const runtime = yield* DurableAgentRuntime;
907
+ return SubmissionStatusResponse.make({ status: yield* runtime.submissionStatus(receipt) });
908
+ })), respond, Effect.flatMap(encodeResponse));
909
+ const awaitSettlementEndpoint = (encoded, includeRecord = false) => decodeAwaitSettlementRequest(encoded).pipe(Effect.mapError(protocolFailure("The receipt could not be decoded")), Effect.flatMap((receipt) => Effect.gen(function* () {
910
+ const authorizer = yield* OperationAuthorizer;
911
+ yield* authorizer.authorize(OperationAuthorizationRequest.make({
912
+ operation: "awaitSettlement",
913
+ threadId: receipt.threadId,
914
+ submissionId: receipt.submissionId
915
+ }));
916
+ if (includeRecord) yield* authorizer.authorize(OperationAuthorizationRequest.make({
917
+ operation: "observe",
918
+ threadId: receipt.threadId
919
+ }));
920
+ yield* requireReceiptThread(receipt.threadId);
921
+ yield* requireSubmissionThread(receipt.submissionId);
922
+ const runtime = yield* DurableAgentRuntime;
923
+ const wait = Effect.gen(function* () {
924
+ if (includeRecord) return SettlementRecordReached.make({ record: yield* runtime.awaitSettlementRecord(receipt) });
925
+ return SettlementReached.make({ settlement: yield* runtime.awaitSettlement(receipt) });
926
+ });
927
+ if (receipt.waiterId === void 0) return yield* wait;
928
+ const registry = yield* ProgressWaitRegistry;
929
+ return yield* Effect.scoped(Effect.gen(function* () {
930
+ const cancelled = yield* registry.subscribe(JSON.stringify([receipt.threadId, receipt.waiterId]));
931
+ return yield* Effect.raceFirst(wait, cancelled.pipe(Effect.as(ProgressCancelled.make())));
932
+ }));
933
+ })), respond, Effect.flatMap(encodeResponse));
934
+ const awaitProgressEndpoint = (encoded) => decodeAwaitProgressRequest(encoded).pipe(Effect.mapError(protocolFailure("The progress request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
935
+ const identity = yield* ThreadObjectIdentity;
936
+ const runtime = yield* DurableAgentRuntime;
937
+ const registry = yield* ProgressWaitRegistry;
938
+ yield* Effect.scoped(Effect.gen(function* () {
939
+ const cancelled = yield* registry.subscribe(JSON.stringify([identity.threadId, request.waiterId]));
940
+ yield* Effect.raceFirst(runtime.awaitProgress(identity.threadId, request.afterSequence), cancelled);
941
+ }));
942
+ return ProgressObserved.make();
943
+ })), respond, Effect.flatMap(encodeResponse));
944
+ const cancelProgressEndpoint = (encoded) => decodeCancelProgressRequest(encoded).pipe(Effect.mapError(protocolFailure("The progress cancellation could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
945
+ const identity = yield* ThreadObjectIdentity;
946
+ yield* (yield* ProgressWaitRegistry).cancel(JSON.stringify([identity.threadId, request.waiterId]));
947
+ return ProgressCancelled.make();
948
+ })), respond, Effect.flatMap(encodeResponse));
949
+ const observePageEndpoint = (encoded) => decodeObservePageRequest(encoded).pipe(Effect.mapError(protocolFailure("The observe request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
950
+ const identity = yield* ThreadObjectIdentity;
951
+ const store = yield* ThreadStore;
952
+ yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
953
+ operation: "observe",
954
+ threadId: identity.threadId
955
+ }));
956
+ const records = yield* Stream.runCollect(store.read(ThreadRead.make({
957
+ threadId: identity.threadId,
958
+ ...request.afterSequence === void 0 ? {} : { afterSequence: request.afterSequence },
959
+ limit: request.limit
960
+ })));
961
+ return ObservedPage.make({ records: [...records] });
962
+ })), respond, Effect.flatMap(encodeResponse));
963
+ const watchTextEndpoint = (encoded) => Schema.decodeUnknownEffect(Request)(encoded).pipe(Effect.mapError(protocolFailure("The provisional text request could not be decoded")), Effect.flatMap(() => Effect.gen(function* () {
964
+ const { threadId } = yield* ThreadObjectIdentity;
965
+ yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
966
+ operation: "observe",
967
+ threadId
968
+ }));
969
+ return yield* (yield* LiveTextHub).open(threadId);
970
+ })), Effect.catch((failure) => encodeResponse(HostFailed.make({ failure }))));
971
+ const abortEndpoint = (encoded) => decodeAbortCommand(encoded).pipe(Effect.mapError(protocolFailure("The abort command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
972
+ yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
973
+ operation: "abort",
974
+ submissionId: command.submissionId
975
+ }));
976
+ yield* requireSubmissionThread(command.submissionId);
977
+ const maintenance = yield* ThreadMaintenance;
978
+ const runtime = yield* DurableAgentRuntime;
979
+ const intent = yield* maintenance.withMutation(runtime.abort(command));
980
+ return AbortRecorded.make({ intent });
981
+ })), respond, Effect.flatMap(encodeResponse));
982
+ const resolveApprovalEndpoint = (encoded) => decodeApprovalDecisionCommand(encoded).pipe(Effect.mapError(protocolFailure("The approval command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
983
+ yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
984
+ operation: "resolveApproval",
985
+ submissionId: command.submissionId
986
+ }));
987
+ yield* requireSubmissionThread(command.submissionId);
988
+ const maintenance = yield* ThreadMaintenance;
989
+ const runtime = yield* DurableAgentRuntime;
990
+ const intent = yield* maintenance.withMutation(runtime.resolveApproval(command));
991
+ return ApprovalRecorded.make({ intent });
992
+ })), respond, Effect.flatMap(encodeResponse));
993
+ const resolveUnknownEndpoint = (encoded) => decodeUnknownResolutionCommand(encoded).pipe(Effect.mapError(protocolFailure("The resolution command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
994
+ yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
995
+ operation: "resolveUnknown",
996
+ submissionId: command.submissionId
997
+ }));
998
+ yield* requireSubmissionThread(command.submissionId);
999
+ const maintenance = yield* ThreadMaintenance;
1000
+ const runtime = yield* DurableAgentRuntime;
1001
+ const intent = yield* maintenance.withMutation(runtime.resolveUnknown(command));
1002
+ return UnknownResolutionRecorded.make({ intent });
1003
+ })), respond, Effect.flatMap(encodeResponse));
1004
+ /** Explain one Submission (`submissionId` present) or every nonterminal lane member. */
1005
+ var AdminExplainRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/AdminExplainRequest")({ submissionId: Schema.optionalKey(SubmissionId) }) {};
1006
+ /** Verify carries no parameters — the addressed Object IS the lane. */
1007
+ var AdminVerifyRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/AdminVerifyRequest")({}) {};
1008
+ /** Every typed failure of the four admin entry points, plus the protocol's own errors. */
1009
+ const AdminFailure = Schema.Union([
1010
+ AdmissionPolicyError,
1011
+ ApprovalSuspensionError,
1012
+ OperationDenied,
1013
+ RetryRefused,
1014
+ LedgerError,
1015
+ RunJournalError,
1016
+ DigestError,
1017
+ OwnershipLost,
1018
+ SettlementConflict,
1019
+ ThreadStoreError,
1020
+ ThreadNotMaterialized,
1021
+ AppendConflict,
1022
+ DurableRuntimeFailpointError,
1023
+ DurableAlarmError,
1024
+ HostProtocolError,
1025
+ RecoveryBlocked,
1026
+ WorkDiscoveryUnavailable
1027
+ ]);
1028
+ var ExplainedRecovery = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ExplainedRecovery")("ExplainedRecovery", { explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1024)) }) {};
1029
+ var VerifiedIntegrity = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/VerifiedIntegrity")("VerifiedIntegrity", { report: IntegrityReport }) {};
1030
+ var RetryExecuted = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/RetryExecuted")("RetryExecuted", { report: RecoveryReport }) {};
1031
+ var ObligationsScanned = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ObligationsScanned")("ObligationsScanned", { report: ObligationReport }) {};
1032
+ /** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */
1033
+ var AdminFailed = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/AdminFailed")("AdminFailed", { failure: AdminFailure }) {};
1034
+ /** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */
1035
+ const AdminResponse = Schema.Union([
1036
+ ExplainedRecovery,
1037
+ VerifiedIntegrity,
1038
+ RetryExecuted,
1039
+ ObligationsScanned,
1040
+ AdminFailed
1041
+ ]);
1042
+ const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);
1043
+ const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);
1044
+ const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);
1045
+ const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);
1046
+ const encodeAdminResponse = (...args) => Schema.encodeEffect(AdminResponse)(...args);
1047
+ const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);
1048
+ /** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */
1049
+ const respondAdmin = (effect) => effect.pipe(Effect.map((result) => result), Effect.catch((failure) => Effect.succeed(AdminFailed.make({ failure }))));
1050
+ /** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */
1051
+ const encodeAdminResponseTotal = (response) => encodeAdminResponse(response).pipe(Effect.catch((error) => Effect.succeed({
1052
+ _tag: "AdminFailed",
1053
+ failure: {
1054
+ _tag: "HostProtocolError",
1055
+ message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`)
1056
+ }
1057
+ })));
1058
+ const explainEndpoint = (encoded) => decodeAdminExplainRequest(encoded).pipe(Effect.mapError(protocolFailure("The explain request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
1059
+ const identity = yield* ThreadObjectIdentity;
1060
+ const runtime = yield* DurableAgentRuntime;
1061
+ const explanations = request.submissionId === void 0 ? yield* runtime.explainThread(identity.threadId) : [yield* runtime.explain(request.submissionId)];
1062
+ return ExplainedRecovery.make({ explanations });
1063
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
1064
+ const verifyEndpoint = (encoded) => decodeAdminVerifyRequest(encoded).pipe(Effect.mapError(protocolFailure("The verify request could not be decoded")), Effect.flatMap(() => Effect.gen(function* () {
1065
+ const identity = yield* ThreadObjectIdentity;
1066
+ const report = yield* (yield* DurableAgentRuntime).verify(identity.threadId);
1067
+ return VerifiedIntegrity.make({ report });
1068
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
1069
+ const retryEndpoint = (encoded) => decodeRetryCommand(encoded).pipe(Effect.mapError(protocolFailure("The retry command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
1070
+ const maintenance = yield* ThreadMaintenance;
1071
+ const runtime = yield* DurableAgentRuntime;
1072
+ const report = yield* maintenance.withMutation(runtime.retry(command));
1073
+ return RetryExecuted.make({ report });
1074
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
1075
+ const obligationsEndpoint = (encoded) => decodeObligationThresholds(encoded).pipe(Effect.mapError(protocolFailure("The obligation thresholds could not be decoded")), Effect.flatMap((thresholds) => Effect.gen(function* () {
1076
+ const report = yield* (yield* DurableAgentRuntime).scanObligations(thresholds);
1077
+ return ObligationsScanned.make({ report });
1078
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
1079
+ /**
1080
+ * Owner-side `portCall`: wrap a mutating envelope in the same pre-armed generation protocol as
1081
+ * public RPC (a routed mutation committed by THIS Object must already carry the alarm that will
1082
+ * finish it), execute on the LOCAL facets (never the routed decorators), then arm an immediate
1083
+ * alarm so the mutated lane is processed promptly. Protocol anomalies answer
1084
+ * `PortFailed(PortProtocolError)`.
1085
+ */
1086
+ const encodePortResponseTotal = (response) => encodePortResponse(response).pipe(Effect.catch((error) => Effect.succeed(encodedPortProtocolFailure(`The port response could not be encoded: ${error.message}`))));
1087
+ const portGuardFailure = (failure) => PortFailed.make({ failure: failure._tag === "LedgerError" ? failure : PortProtocolError.make({ message: "The port request is not for the addressed Thread" }) });
1088
+ const portCall = (encoded) => Effect.gen(function* () {
1089
+ const ports = yield* ThreadObjectPorts;
1090
+ const maintenance = yield* ThreadMaintenance;
1091
+ const alarm = yield* DurableAlarmService;
1092
+ const decoded = yield* decodePortRequest(encoded).pipe(Effect.map((request) => ({
1093
+ _tag: "success",
1094
+ request
1095
+ })), Effect.catch((error) => Effect.succeed({
1096
+ _tag: "failure",
1097
+ message: error.message
1098
+ })));
1099
+ if (decoded._tag === "failure") return encodedPortProtocolFailure(`The port request could not be decoded: ${decoded.message}`);
1100
+ if (decoded.request._tag === "LedgerLookup" && decoded.request.request._tag === "SubmissionLookupById") {
1101
+ const response = yield* lookupAddressedSubmission(decoded.request.request.submissionId).pipe(Effect.map((submission) => PortSucceeded.make({ result: LedgerLookupResult.make(Option.isSome(submission) ? { submission: submission.value } : {}) })), Effect.catch((failure) => Effect.succeed(portGuardFailure(failure))));
1102
+ return yield* encodePortResponseTotal(response);
1103
+ }
1104
+ const identityCheck = yield* requirePortThread(decoded.request).pipe(Effect.result);
1105
+ if (identityCheck._tag === "Failure") return yield* encodePortResponseTotal(portGuardFailure(identityCheck.failure));
1106
+ const mutating = isMutatingPortRequest(decoded.request);
1107
+ const handled = yield* (mutating ? maintenance.withMutation(ports.handle(decoded.request)) : ports.handle(decoded.request)).pipe(Effect.exit);
1108
+ if (handled._tag === "Failure") return encodedPortProtocolFailure("The owner Object could not arm its maintenance alarm before the mutation.");
1109
+ const response = yield* encodePortResponseTotal(handled.value);
1110
+ if (mutating) yield* alarm.scheduleNow.pipe(Effect.catch((error) => Effect.logWarning("ThreadObject.portCall: immediate re-arm failed", error)));
1111
+ return response;
1112
+ });
1113
+ const wakeEndpoint = Effect.gen(function* () {
1114
+ const identity = yield* ThreadObjectIdentity;
1115
+ yield* (yield* WakeScheduler).notify(identity.threadId);
1116
+ });
1117
+ /** The per-Thread wire operations supported by native and application-owned endpoints. */
1118
+ const ThreadRpcOperation = Schema.Literals([
1119
+ "submitEncoded",
1120
+ "submissionStatusEncoded",
1121
+ "awaitSettlementEncoded",
1122
+ "awaitSettlementRecordEncoded",
1123
+ "awaitProgressEncoded",
1124
+ "cancelProgressEncoded",
1125
+ "watchTextEncoded",
1126
+ "observePage",
1127
+ "abortEncoded",
1128
+ "resolveApprovalEncoded",
1129
+ "resolveUnknownEncoded",
1130
+ "portCall",
1131
+ "wake"
1132
+ ]);
1133
+ const threadRpc = {
1134
+ submitEncoded: submitEndpoint,
1135
+ submissionStatusEncoded: submissionStatusEndpoint,
1136
+ awaitSettlementEncoded: awaitSettlementEndpoint,
1137
+ awaitSettlementRecordEncoded: (encoded) => awaitSettlementEndpoint(encoded, true),
1138
+ awaitProgressEncoded: awaitProgressEndpoint,
1139
+ cancelProgressEncoded: cancelProgressEndpoint,
1140
+ watchTextEncoded: watchTextEndpoint,
1141
+ observePage: observePageEndpoint,
1142
+ abortEncoded: abortEndpoint,
1143
+ resolveApprovalEncoded: resolveApprovalEndpoint,
1144
+ resolveUnknownEncoded: resolveUnknownEndpoint,
1145
+ portCall,
1146
+ wake: () => wakeEndpoint
1147
+ };
1148
+ /**
1149
+ * Bind an addressed request to its logical Thread while sharing one physical runtime. This
1150
+ * validates local placement before invoking the same native handlers. Receipts, Submission
1151
+ * commands and port envelopes must match this identity; progress cancellation is Thread-scoped.
1152
+ * The producer comes from the actual runtime configuration, never from caller input. These
1153
+ * guards supplement the existing current model/Tool and operation authorization policies.
1154
+ */
1155
+ const handleRpc = Effect.fnUntraced(function* (threadId, operation, encoded) {
1156
+ if (!(yield* ThreadObjectPlacement).ownsThread(threadId)) return yield* HostProtocolError.make({ message: "The Thread belongs to another Object" });
1157
+ const { producerId } = yield* DurableRuntimeConfig;
1158
+ return yield* threadRpc[operation](encoded).pipe(Effect.provideService(ThreadObjectIdentity, {
1159
+ threadId,
1160
+ producerId
1161
+ }));
1162
+ });
1163
+ /** Compose with application registrations on a shared physical object. */
1164
+ const alarms = ThreadMaintenanceAlarm.handlers({ "@systemfsoftware/agent/thread-maintenance": () => Effect.flatMap(ThreadMaintenance, (maintenance) => Effect.asVoid(maintenance.pass)) });
1165
+ const gateEndpoint = Effect.gen(function* () {
1166
+ yield* (yield* ThreadMaintenance).ensureAlarm;
1167
+ });
1168
+ /**
1169
+ * Adapter from effect-cf's native Durable Object services to Effect Agent's existing platform
1170
+ * ports. effect-cf owns the cached ManagedRuntime and supplies these values once per Object
1171
+ * incarnation; the durable runtime continues to depend only on the narrow services below.
1172
+ */
1173
+ const effectCfPlatformLayer = (namespaceBinding, rpcTracing = false) => Layer.effectContext(Effect.gen(function* () {
1174
+ const state = yield* DurableObjectState.DurableObjectState;
1175
+ const env = yield* WorkerEnvironment;
1176
+ const binding = yield* threadNamespaceFromEnv(env, namespaceBinding);
1177
+ return Context.make(DurableObjectContext, {
1178
+ ctx: state.raw,
1179
+ env
1180
+ }).pipe(Context.add(ThreadObjectNamespace, ThreadObjectNamespace.of({
1181
+ get: (threadId) => binding.get(binding.idFromName(threadId)),
1182
+ ...rpcTracing === true ? { rpcTracing: namespaceBinding } : {}
1183
+ })));
1184
+ }));
1185
+ /**
1186
+ * Export a composed application Layer as a native Durable Object class.
1187
+ * Bootstrap services are provided to the whole graph before it acquires, so application Layers
1188
+ * can yield effect-cf's WorkerEnvironment and DurableObjectState, derived identity, Digest, and SecureRandom.
1189
+ * Effect Config reads scalar Worker vars and secrets through effect-cf's environment provider;
1190
+ * WorkerEnvironment exposes resource bindings without a separate config Layer.
1191
+ * Application dependencies remain visible until Layer.provide satisfies them. effect-cf owns the
1192
+ * cached ManagedRuntime, native RPC methods, event scopes, and telemetry flushing.
1193
+ * Initialization is local and bounded inside the constructor gate. Cloudflare eviction does not
1194
+ * guarantee finalizers; put resources requiring timely release in scoped operations or eventLayer.
1195
+ */
1196
+ const make = (applicationLayer, options) => {
1197
+ const application = applicationLayer.pipe(Layer.provideMerge(layerConfig(options)), Layer.provideMerge(effectCfPlatformLayer(options.namespaceBinding, options.rpcTracing)));
1198
+ const runtime = Layer.flatMap(application, (applicationServices) => {
1199
+ const scheduling = Context.get(applicationServices, DurableObjectAlarm.ScheduleConfiguration);
1200
+ const config = Context.get(applicationServices, CloudflareDurableRuntimeConfig);
1201
+ const services = Context.add(applicationServices, DurableObjectAlarm.ScheduleConfiguration, {
1202
+ ...scheduling,
1203
+ dispatchAfterEvent: scheduling.dispatchAfterEvent ?? true,
1204
+ inFlightRecovery: config.recoveryWindowMillis || (scheduling.inFlightRecovery ?? 1e3)
1205
+ });
1206
+ return Layer.effectContext(gateEndpoint.pipe(Effect.provide(services), Effect.as(services)));
1207
+ });
1208
+ const rpc = {
1209
+ ...threadRpc,
1210
+ explainEncoded: (encoded) => explainEndpoint(encoded),
1211
+ verifyEncoded: (encoded) => verifyEndpoint(encoded),
1212
+ retryEncoded: (encoded) => retryEndpoint(encoded),
1213
+ obligationsEncoded: (encoded) => obligationsEndpoint(encoded)
1214
+ };
1215
+ return DurableObject.make(runtime, {
1216
+ ...options.rpcTracing === true ? { rpcTracing: { service: options.namespaceBinding } } : {},
1217
+ ...options.eventLayer === void 0 ? {} : { eventLayer: options.eventLayer },
1218
+ initialize: Effect.void,
1219
+ rpc,
1220
+ alarms: options.alarms === void 0 ? alarms : DurableObjectAlarm.mergeAll(options.alarms, alarms)
1221
+ });
1222
+ };
1223
+ export { ThreadObjectPorts as C, layerInHost as D, layerHostConfig as E, submit as S, layerConfig as T, decodeRetryCommand as _, AdminVerifyRequest as a, make as b, RetryExecuted as c, VerifiedIntegrity as d, alarms as f, decodeObligationThresholds as g, decodeAdminVerifyRequest as h, AdminResponse as i, ThreadObject_exports as l, decodeAdminResponse as m, AdminFailed as n, ExplainedRecovery as o, decodeAdminExplainRequest as p, AdminFailure as r, ObligationsScanned as s, AdminExplainRequest as t, ThreadRpcOperation as u, encodeAdminResponse as v, layer as w, portCall as x, handleRpc as y };
1224
+
1225
+ //# sourceMappingURL=ThreadObject-D1pCeNrq.mjs.map