@systemfsoftware/agent-platform-cloudflare 0.0.0-stage → 0.1.0-beta.192
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/Alarm-CbhflIzz.mjs +1931 -0
- package/dist/Alarm-CbhflIzz.mjs.map +1 -0
- package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
- package/dist/Alarm.d.mts +3 -0
- package/dist/Alarm.mjs +3 -0
- package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
- package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
- package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
- package/dist/BrowserCredentials.d.mts +2 -0
- package/dist/BrowserCredentials.mjs +1 -0
- package/dist/BrowserRestCapture.d.mts +14 -0
- package/dist/BrowserRestCapture.mjs +195 -0
- package/dist/BrowserRestCapture.mjs.map +1 -0
- package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
- package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
- package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
- package/dist/BrowserSession.d.mts +3 -0
- package/dist/BrowserSession.mjs +4 -0
- package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
- package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
- package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
- package/dist/BrowserUse.d.mts +2 -0
- package/dist/BrowserUse.mjs +1 -0
- package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
- package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
- package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
- package/dist/CloudflareAiGateway.d.mts +2 -0
- package/dist/CloudflareAiGateway.mjs +1 -0
- package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
- package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
- package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
- package/dist/CloudflareBindings.d.mts +2 -0
- package/dist/CloudflareBindings.mjs +1 -0
- package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
- package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
- package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
- package/dist/CloudflareBrowser.d.mts +3 -0
- package/dist/CloudflareBrowser.mjs +1 -0
- package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
- package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
- package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
- package/dist/CloudflareCodeMode.d.mts +2 -0
- package/dist/CloudflareCodeMode.mjs +1 -0
- package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
- package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
- package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
- package/dist/CloudflareConfig.d.mts +2 -0
- package/dist/CloudflareConfig.mjs +1 -0
- package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
- package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
- package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
- package/dist/CloudflareMemory.d.mts +2 -0
- package/dist/CloudflareMemory.mjs +1 -0
- package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
- package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
- package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
- package/dist/CloudflareScheduling.d.mts +2 -0
- package/dist/CloudflareScheduling.mjs +1 -0
- package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
- package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
- package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
- package/dist/CloudflareSubscriptions.d.mts +2 -0
- package/dist/CloudflareSubscriptions.mjs +1 -0
- package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
- package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
- package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
- package/dist/CloudflareThreadClient.d.mts +3 -0
- package/dist/CloudflareThreadClient.mjs +3 -0
- package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
- package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
- package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
- package/dist/InteractiveBrowser.d.mts +2 -0
- package/dist/InteractiveBrowser.mjs +1 -0
- package/dist/LiveText-CfpcZaGb.d.mts +91 -0
- package/dist/LiveText-DaF0tN_p.mjs +148 -0
- package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
- package/dist/LiveText.d.mts +2 -0
- package/dist/LiveText.mjs +1 -0
- package/dist/R2ToolResultStorage.d.mts +27 -0
- package/dist/R2ToolResultStorage.mjs +84 -0
- package/dist/R2ToolResultStorage.mjs.map +1 -0
- package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
- package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
- package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +2 -0
- package/dist/ThreadObject.mjs +1 -0
- package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
- package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
- package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
- package/dist/WakeScheduler.d.mts +2 -0
- package/dist/WakeScheduler.mjs +1 -0
- package/dist/boundary-YrOnE2zO.mjs +41 -0
- package/dist/boundary-YrOnE2zO.mjs.map +1 -0
- package/dist/browser-failure-CWBBnf1j.mjs +70 -0
- package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
- package/dist/index.d.mts +17 -0
- package/dist/index.mjs +17 -0
- package/dist/prepared-admission-DngoYN74.mjs +57 -0
- package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +134 -3
- package/src/Alarm.ts +3402 -0
- package/src/BrowserCredentials.ts +181 -0
- package/src/BrowserRestCapture.ts +383 -0
- package/src/BrowserSession.ts +993 -0
- package/src/BrowserUse.ts +438 -0
- package/src/CloudflareAiGateway.ts +176 -0
- package/src/CloudflareBindings.ts +225 -0
- package/src/CloudflareBrowser.ts +9 -0
- package/src/CloudflareCodeMode.ts +896 -0
- package/src/CloudflareConfig.ts +142 -0
- package/src/CloudflareMemory.ts +418 -0
- package/src/CloudflareScheduling.ts +736 -0
- package/src/CloudflareSubscriptions.ts +1032 -0
- package/src/CloudflareThreadClient.ts +980 -0
- package/src/InteractiveBrowser.ts +3300 -0
- package/src/LiveText.ts +145 -0
- package/src/R2ToolResultStorage.ts +131 -0
- package/src/ThreadObject.ts +1348 -0
- package/src/WakeScheduler.ts +102 -0
- package/src/index.ts +16 -0
- package/src/internal/boundary.ts +53 -0
- package/src/internal/browser-binding.ts +483 -0
- package/src/internal/browser-credentials.ts +481 -0
- package/src/internal/browser-failure.ts +145 -0
- package/src/internal/browser-file-selection.ts +146 -0
- package/src/internal/browser-quick-action.ts +666 -0
- package/src/internal/browser-readonly-live-view.ts +121 -0
- package/src/internal/browser-session-lifecycle.ts +200 -0
- package/src/internal/crypto.ts +44 -0
- package/src/internal/due-queue.ts +452 -0
- package/src/internal/host-protocol-error.ts +23 -0
- package/src/internal/layers.ts +1181 -0
- package/src/internal/live-text-observation.ts +8 -0
- package/src/internal/live-text-protocol.ts +59 -0
- package/src/internal/live-text.ts +339 -0
- package/src/internal/message-delivery.ts +149 -0
- package/src/internal/page-function.ts +12 -0
- package/src/internal/prepared-admission.ts +83 -0
- package/src/internal/progress-wait.ts +121 -0
- package/src/internal/transport.ts +53 -0
- package/README.md +0 -3
|
@@ -0,0 +1,980 @@
|
|
|
1
|
+
import { AgentInputError } from '@systemfsoftware/agent/agent-error'
|
|
2
|
+
import { DigestError } from '@systemfsoftware/agent/digest'
|
|
3
|
+
import { type DurableSubmitAgent, type DurableSubmitOptions } from '@systemfsoftware/agent/durable-agent-runtime'
|
|
4
|
+
import { DurableRuntimeFailpointError } from '@systemfsoftware/agent/durable-failpoint'
|
|
5
|
+
import { AgentId, type ThreadId } from '@systemfsoftware/agent/identifiers'
|
|
6
|
+
import { InputMessage } from '@systemfsoftware/agent/messaging'
|
|
7
|
+
import { OperationDenied } from '@systemfsoftware/agent/operation-authorizer'
|
|
8
|
+
import { Receipt } from '@systemfsoftware/agent/receipt'
|
|
9
|
+
import {
|
|
10
|
+
CanonicalRecordEnvelope,
|
|
11
|
+
CanonicalSequence,
|
|
12
|
+
DefinitionDigests,
|
|
13
|
+
PersistedJson,
|
|
14
|
+
SubmissionSettledRecord,
|
|
15
|
+
WorkerAdmission,
|
|
16
|
+
} from '@systemfsoftware/agent/records'
|
|
17
|
+
import {
|
|
18
|
+
AbortCommand,
|
|
19
|
+
AbortIntent,
|
|
20
|
+
AdmissionConflict,
|
|
21
|
+
AdmissionFence,
|
|
22
|
+
AdmissionGroup,
|
|
23
|
+
AdmissionPolicyError,
|
|
24
|
+
ApprovalConflict,
|
|
25
|
+
ApprovalDecisionCommand,
|
|
26
|
+
ApprovalDecisionIntent,
|
|
27
|
+
IdempotencyKey,
|
|
28
|
+
JoinedToHost,
|
|
29
|
+
LedgerError,
|
|
30
|
+
OwnershipLost,
|
|
31
|
+
Principal,
|
|
32
|
+
Settlement,
|
|
33
|
+
SettlementConflict,
|
|
34
|
+
UnknownResolutionCommand,
|
|
35
|
+
UnknownResolutionConflict,
|
|
36
|
+
UnknownResolutionIntent,
|
|
37
|
+
} from '@systemfsoftware/agent/submission-ledger'
|
|
38
|
+
import { SubmissionStatus } from '@systemfsoftware/agent/submission-status'
|
|
39
|
+
import { AppendConflict, ThreadNotMaterialized, ThreadStoreError } from '@systemfsoftware/agent/thread-store'
|
|
40
|
+
import { RpcTargets, RpcTracing } from 'effect-cf'
|
|
41
|
+
import * as Context from 'effect/Context'
|
|
42
|
+
import * as SecureRandom from 'effect/crypto/SecureRandom'
|
|
43
|
+
import * as Duration from 'effect/Duration'
|
|
44
|
+
import * as Effect from 'effect/Effect'
|
|
45
|
+
import * as Layer from 'effect/Layer'
|
|
46
|
+
import * as Predicate from 'effect/Predicate'
|
|
47
|
+
import * as Schema from 'effect/Schema'
|
|
48
|
+
import * as Stream from 'effect/Stream'
|
|
49
|
+
|
|
50
|
+
import { callThreadObject, DurableAlarmError, ThreadObjectNamespace, type ThreadObjectRpc } from './CloudflareBindings'
|
|
51
|
+
import { AdmissionLimitExceeded } from './CloudflareConfig'
|
|
52
|
+
import { cloudflareFailureSignals, safeCauseMessage } from './internal/boundary'
|
|
53
|
+
import { cloudflareCryptoLayer } from './internal/crypto'
|
|
54
|
+
import { boundHostDiagnostic, HostProtocolError } from './internal/host-protocol-error'
|
|
55
|
+
import { Observation as LiveTextObservation } from './internal/live-text-observation'
|
|
56
|
+
import { liveTextProtocolFailure, Request as WatchTextRequest } from './internal/live-text-protocol'
|
|
57
|
+
import { decodeLiveText, type LiveTextFrame } from './LiveText'
|
|
58
|
+
|
|
59
|
+
export { boundHostDiagnostic, HostProtocolError } from './internal/host-protocol-error'
|
|
60
|
+
export { decodeLiveText, LiveTextFrame } from './LiveText'
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The Worker↔Thread-Object host protocol (plan §1.4): Schema envelopes for the host
|
|
64
|
+
* entry points (`submitEncoded`, `awaitSettlementEncoded`, `observePage`, `abortEncoded`,
|
|
65
|
+
* `resolveApprovalEncoded`, `resolveUnknownEncoded`) plus the Worker-side client that speaks
|
|
66
|
+
* it. Mirrors the WP2 port protocol: requests and responses are closed Schema unions, typed
|
|
67
|
+
* failures travel as their own tagged classes and RE-DECODE to identical tags on the caller
|
|
68
|
+
* (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
const PROGRESS_CANCELLATION_TIMEOUT = '1 second'
|
|
72
|
+
|
|
73
|
+
/** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */
|
|
74
|
+
export class ThreadClientError extends Schema.TaggedError<ThreadClientError>()(
|
|
75
|
+
'ThreadClientError',
|
|
76
|
+
{
|
|
77
|
+
threadId: Schema.String,
|
|
78
|
+
message: Schema.String,
|
|
79
|
+
cause: Schema.optionalKey(Schema.Defect()),
|
|
80
|
+
/** Cloudflare's own classification for a failure safe to retry with a fresh stub. */
|
|
81
|
+
retryable: Schema.optionalKey(Schema.Boolean),
|
|
82
|
+
/** Cloudflare overloads are surfaced immediately instead of adding retry pressure. */
|
|
83
|
+
overloaded: Schema.optionalKey(Schema.Boolean),
|
|
84
|
+
},
|
|
85
|
+
) {}
|
|
86
|
+
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// Requests
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One durable submission, input ALREADY encoded by the caller through the Agent Binding's
|
|
93
|
+
* input schema (the Worker bundles the same Agent definitions as the Object, so schema
|
|
94
|
+
* validation happens client-side; the resolved Binding re-validates at claim time). The
|
|
95
|
+
* Thread identity is deliberately absent — the addressed Object IS the lane.
|
|
96
|
+
*/
|
|
97
|
+
export class SubmitRequest extends Schema.Class<SubmitRequest>(
|
|
98
|
+
'@effect-agent/platform-cloudflare/SubmitRequest',
|
|
99
|
+
)({
|
|
100
|
+
agentId: AgentId,
|
|
101
|
+
principal: Principal,
|
|
102
|
+
idempotencyKey: IdempotencyKey,
|
|
103
|
+
admissionGroup: Schema.optionalKey(AdmissionGroup),
|
|
104
|
+
admissionFence: Schema.optionalKey(AdmissionFence),
|
|
105
|
+
workerAdmission: Schema.optionalKey(WorkerAdmission),
|
|
106
|
+
messageAdmission: Schema.optionalKey(InputMessage),
|
|
107
|
+
definitions: DefinitionDigests,
|
|
108
|
+
inputPayload: PersistedJson,
|
|
109
|
+
}) {}
|
|
110
|
+
|
|
111
|
+
/** One bounded page of canonical records after an optional sequence. */
|
|
112
|
+
export class ObservePageRequest extends Schema.Class<ObservePageRequest>(
|
|
113
|
+
'@effect-agent/platform-cloudflare/ObservePageRequest',
|
|
114
|
+
)({
|
|
115
|
+
afterSequence: Schema.optionalKey(CanonicalSequence),
|
|
116
|
+
limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),
|
|
117
|
+
}) {}
|
|
118
|
+
|
|
119
|
+
/** Receipt-shaped observation request; the optional identity owns only the remote wait. */
|
|
120
|
+
export class AwaitSettlementRequest extends Receipt.extend<AwaitSettlementRequest>(
|
|
121
|
+
'@effect-agent/platform-cloudflare/AwaitSettlementRequest',
|
|
122
|
+
)({
|
|
123
|
+
waiterId: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256))),
|
|
124
|
+
}) {}
|
|
125
|
+
|
|
126
|
+
/** One event-driven wait for canonical progress strictly after this sequence. */
|
|
127
|
+
export class AwaitProgressRequest extends Schema.Class<AwaitProgressRequest>(
|
|
128
|
+
'@effect-agent/platform-cloudflare/AwaitProgressRequest',
|
|
129
|
+
)({
|
|
130
|
+
afterSequence: CanonicalSequence,
|
|
131
|
+
waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
|
|
132
|
+
}) {}
|
|
133
|
+
|
|
134
|
+
/** Best-effort cancellation of one in-flight progress or settlement observation. */
|
|
135
|
+
export class CancelProgressRequest extends Schema.Class<CancelProgressRequest>(
|
|
136
|
+
'@effect-agent/platform-cloudflare/CancelProgressRequest',
|
|
137
|
+
)({
|
|
138
|
+
waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),
|
|
139
|
+
}) {}
|
|
140
|
+
|
|
141
|
+
// ---------------------------------------------------------------------------
|
|
142
|
+
// Responses
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Every typed failure a host entry point can produce, plus the protocol's own errors. Same
|
|
147
|
+
* closed-union discipline as the WP2 `PortFailure`: members re-decode to the SAME tagged
|
|
148
|
+
* classes on the Worker side; `cause` chains travel as Schema defects without instance
|
|
149
|
+
* fidelity (plan §2.8).
|
|
150
|
+
*/
|
|
151
|
+
export const HostFailure = Schema.Union([
|
|
152
|
+
AgentInputError,
|
|
153
|
+
DigestError,
|
|
154
|
+
AdmissionConflict,
|
|
155
|
+
AdmissionPolicyError,
|
|
156
|
+
SettlementConflict,
|
|
157
|
+
ApprovalConflict,
|
|
158
|
+
UnknownResolutionConflict,
|
|
159
|
+
JoinedToHost,
|
|
160
|
+
LedgerError,
|
|
161
|
+
OwnershipLost,
|
|
162
|
+
ThreadStoreError,
|
|
163
|
+
ThreadNotMaterialized,
|
|
164
|
+
AppendConflict,
|
|
165
|
+
DurableRuntimeFailpointError,
|
|
166
|
+
AdmissionLimitExceeded,
|
|
167
|
+
DurableAlarmError,
|
|
168
|
+
OperationDenied,
|
|
169
|
+
HostProtocolError,
|
|
170
|
+
])
|
|
171
|
+
|
|
172
|
+
export type HostFailure = typeof HostFailure.Type
|
|
173
|
+
|
|
174
|
+
export class SubmitSucceeded extends Schema.TaggedClass<SubmitSucceeded>(
|
|
175
|
+
'@effect-agent/platform-cloudflare/SubmitSucceeded',
|
|
176
|
+
)('SubmitSucceeded', {
|
|
177
|
+
receipt: Receipt,
|
|
178
|
+
}) {}
|
|
179
|
+
|
|
180
|
+
export class SubmissionStatusResponse extends Schema.TaggedClass<SubmissionStatusResponse>(
|
|
181
|
+
'@effect-agent/platform-cloudflare/SubmissionStatusResponse',
|
|
182
|
+
)('SubmissionStatusResponse', { status: SubmissionStatus }) {}
|
|
183
|
+
|
|
184
|
+
export class SettlementReached extends Schema.TaggedClass<SettlementReached>(
|
|
185
|
+
'@effect-agent/platform-cloudflare/SettlementReached',
|
|
186
|
+
)('SettlementReached', {
|
|
187
|
+
settlement: Settlement,
|
|
188
|
+
}) {}
|
|
189
|
+
|
|
190
|
+
/** The exact canonical record of an operationally finalized Submission. */
|
|
191
|
+
export class SettlementRecordReached extends Schema.TaggedClass<SettlementRecordReached>(
|
|
192
|
+
'@effect-agent/platform-cloudflare/SettlementRecordReached',
|
|
193
|
+
)('SettlementRecordReached', {
|
|
194
|
+
record: SubmissionSettledRecord,
|
|
195
|
+
}) {}
|
|
196
|
+
|
|
197
|
+
export class ObservedPage extends Schema.TaggedClass<ObservedPage>(
|
|
198
|
+
'@effect-agent/platform-cloudflare/ObservedPage',
|
|
199
|
+
)('ObservedPage', {
|
|
200
|
+
records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),
|
|
201
|
+
}) {}
|
|
202
|
+
|
|
203
|
+
/** A record was already committed or an incarnation-local hint says the caller should re-read. */
|
|
204
|
+
export class ProgressObserved extends Schema.TaggedClass<ProgressObserved>(
|
|
205
|
+
'@effect-agent/platform-cloudflare/ProgressObserved',
|
|
206
|
+
)('ProgressObserved', {}) {}
|
|
207
|
+
|
|
208
|
+
export class ProgressCancelled extends Schema.TaggedClass<ProgressCancelled>(
|
|
209
|
+
'@effect-agent/platform-cloudflare/ProgressCancelled',
|
|
210
|
+
)('ProgressCancelled', {}) {}
|
|
211
|
+
|
|
212
|
+
export class AbortRecorded extends Schema.TaggedClass<AbortRecorded>(
|
|
213
|
+
'@effect-agent/platform-cloudflare/AbortRecorded',
|
|
214
|
+
)('AbortRecorded', {
|
|
215
|
+
intent: AbortIntent,
|
|
216
|
+
}) {}
|
|
217
|
+
|
|
218
|
+
export class ApprovalRecorded extends Schema.TaggedClass<ApprovalRecorded>(
|
|
219
|
+
'@effect-agent/platform-cloudflare/ApprovalRecorded',
|
|
220
|
+
)('ApprovalRecorded', {
|
|
221
|
+
intent: ApprovalDecisionIntent,
|
|
222
|
+
}) {}
|
|
223
|
+
|
|
224
|
+
export class UnknownResolutionRecorded extends Schema.TaggedClass<UnknownResolutionRecorded>(
|
|
225
|
+
'@effect-agent/platform-cloudflare/UnknownResolutionRecorded',
|
|
226
|
+
)('UnknownResolutionRecorded', {
|
|
227
|
+
intent: UnknownResolutionIntent,
|
|
228
|
+
}) {}
|
|
229
|
+
|
|
230
|
+
/** The entry point failed TYPED on the Object; the failure re-decodes verbatim. */
|
|
231
|
+
export class HostFailed extends Schema.TaggedClass<HostFailed>(
|
|
232
|
+
'@effect-agent/platform-cloudflare/HostFailed',
|
|
233
|
+
)('HostFailed', {
|
|
234
|
+
failure: HostFailure,
|
|
235
|
+
}) {}
|
|
236
|
+
|
|
237
|
+
/** The uniform answer of one host entry point. Callers narrow by the tag their call implies. */
|
|
238
|
+
export const HostResponse = Schema.Union([
|
|
239
|
+
SubmitSucceeded,
|
|
240
|
+
SettlementReached,
|
|
241
|
+
SettlementRecordReached,
|
|
242
|
+
SubmissionStatusResponse,
|
|
243
|
+
ObservedPage,
|
|
244
|
+
ProgressObserved,
|
|
245
|
+
ProgressCancelled,
|
|
246
|
+
AbortRecorded,
|
|
247
|
+
ApprovalRecorded,
|
|
248
|
+
UnknownResolutionRecorded,
|
|
249
|
+
HostFailed,
|
|
250
|
+
])
|
|
251
|
+
|
|
252
|
+
export type HostResponse = typeof HostResponse.Type
|
|
253
|
+
|
|
254
|
+
// ---------------------------------------------------------------------------
|
|
255
|
+
// Codecs (shared by the Object endpoints and the Worker client)
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
|
|
258
|
+
export const decodeSubmitRequest = Schema.decodeUnknownEffect(SubmitRequest)
|
|
259
|
+
// Encode the caller's fields directly: constructing a Class first would validate the
|
|
260
|
+
// same envelope twice. The Object still decodes its untrusted request independently.
|
|
261
|
+
export const encodeSubmitRequest = Schema.encodeEffect(Schema.Struct(SubmitRequest.fields))
|
|
262
|
+
export const decodeReceipt = Schema.decodeUnknownEffect(Receipt)
|
|
263
|
+
export const encodeReceipt = Schema.encodeEffect(Receipt)
|
|
264
|
+
export const decodeAwaitSettlementRequest = Schema.decodeUnknownEffect(AwaitSettlementRequest)
|
|
265
|
+
export const encodeAwaitSettlementRequest = Schema.encodeEffect(AwaitSettlementRequest)
|
|
266
|
+
export const decodeObservePageRequest = Schema.decodeUnknownEffect(ObservePageRequest)
|
|
267
|
+
export const encodeObservePageRequest = Schema.encodeEffect(ObservePageRequest)
|
|
268
|
+
export const decodeAwaitProgressRequest = Schema.decodeUnknownEffect(AwaitProgressRequest)
|
|
269
|
+
export const encodeAwaitProgressRequest = Schema.encodeEffect(AwaitProgressRequest)
|
|
270
|
+
export const decodeCancelProgressRequest = Schema.decodeUnknownEffect(CancelProgressRequest)
|
|
271
|
+
export const encodeCancelProgressRequest = Schema.encodeEffect(CancelProgressRequest)
|
|
272
|
+
export const decodeAbortCommand = Schema.decodeUnknownEffect(AbortCommand)
|
|
273
|
+
export const encodeAbortCommand = Schema.encodeEffect(AbortCommand)
|
|
274
|
+
export const decodeApprovalDecisionCommand = Schema.decodeUnknownEffect(ApprovalDecisionCommand)
|
|
275
|
+
export const encodeApprovalDecisionCommand = Schema.encodeEffect(ApprovalDecisionCommand)
|
|
276
|
+
export const decodeUnknownResolutionCommand = Schema.decodeUnknownEffect(UnknownResolutionCommand)
|
|
277
|
+
export const encodeUnknownResolutionCommand = Schema.encodeEffect(UnknownResolutionCommand)
|
|
278
|
+
export const encodeHostResponse = Schema.encodeEffect(HostResponse)
|
|
279
|
+
export const decodeHostResponse = Schema.decodeUnknownEffect(HostResponse)
|
|
280
|
+
|
|
281
|
+
// ---------------------------------------------------------------------------
|
|
282
|
+
// Worker-side client
|
|
283
|
+
// ---------------------------------------------------------------------------
|
|
284
|
+
|
|
285
|
+
/** Failure surface of `CloudflareThreadClient.submit`. */
|
|
286
|
+
const ClientSubmitHostFailure = Schema.Union([
|
|
287
|
+
AgentInputError,
|
|
288
|
+
DigestError,
|
|
289
|
+
AdmissionConflict,
|
|
290
|
+
AdmissionPolicyError,
|
|
291
|
+
LedgerError,
|
|
292
|
+
OwnershipLost,
|
|
293
|
+
ThreadStoreError,
|
|
294
|
+
ThreadNotMaterialized,
|
|
295
|
+
AppendConflict,
|
|
296
|
+
DurableRuntimeFailpointError,
|
|
297
|
+
AdmissionLimitExceeded,
|
|
298
|
+
DurableAlarmError,
|
|
299
|
+
HostProtocolError,
|
|
300
|
+
])
|
|
301
|
+
|
|
302
|
+
const ClientAwaitHostFailure = Schema.Union([
|
|
303
|
+
LedgerError,
|
|
304
|
+
OwnershipLost,
|
|
305
|
+
SettlementConflict,
|
|
306
|
+
OperationDenied,
|
|
307
|
+
HostProtocolError,
|
|
308
|
+
])
|
|
309
|
+
|
|
310
|
+
const ClientObserveHostFailure = Schema.Union([
|
|
311
|
+
ThreadStoreError,
|
|
312
|
+
ThreadNotMaterialized,
|
|
313
|
+
OperationDenied,
|
|
314
|
+
HostProtocolError,
|
|
315
|
+
])
|
|
316
|
+
|
|
317
|
+
const ClientAbortHostFailure = Schema.Union([
|
|
318
|
+
OperationDenied,
|
|
319
|
+
LedgerError,
|
|
320
|
+
OwnershipLost,
|
|
321
|
+
SettlementConflict,
|
|
322
|
+
JoinedToHost,
|
|
323
|
+
DurableRuntimeFailpointError,
|
|
324
|
+
DurableAlarmError,
|
|
325
|
+
HostProtocolError,
|
|
326
|
+
])
|
|
327
|
+
|
|
328
|
+
const ClientApprovalHostFailure = Schema.Union([
|
|
329
|
+
LedgerError,
|
|
330
|
+
OwnershipLost,
|
|
331
|
+
SettlementConflict,
|
|
332
|
+
ApprovalConflict,
|
|
333
|
+
OperationDenied,
|
|
334
|
+
DurableAlarmError,
|
|
335
|
+
HostProtocolError,
|
|
336
|
+
])
|
|
337
|
+
|
|
338
|
+
const ClientUnknownHostFailure = Schema.Union([
|
|
339
|
+
LedgerError,
|
|
340
|
+
OwnershipLost,
|
|
341
|
+
SettlementConflict,
|
|
342
|
+
UnknownResolutionConflict,
|
|
343
|
+
JoinedToHost,
|
|
344
|
+
DurableRuntimeFailpointError,
|
|
345
|
+
OperationDenied,
|
|
346
|
+
DurableAlarmError,
|
|
347
|
+
HostProtocolError,
|
|
348
|
+
])
|
|
349
|
+
|
|
350
|
+
export type ClientSubmitFailure = typeof ClientSubmitHostFailure.Type | ThreadClientError
|
|
351
|
+
export type ClientAwaitFailure = typeof ClientAwaitHostFailure.Type | ThreadClientError
|
|
352
|
+
export type ClientObserveFailure = typeof ClientObserveHostFailure.Type | ThreadClientError
|
|
353
|
+
export type ClientProgressFailure = ClientObserveFailure
|
|
354
|
+
export type ClientAbortFailure = typeof ClientAbortHostFailure.Type | ThreadClientError
|
|
355
|
+
export type ClientApprovalFailure = typeof ClientApprovalHostFailure.Type | ThreadClientError
|
|
356
|
+
export type ClientUnknownFailure = typeof ClientUnknownHostFailure.Type | ThreadClientError
|
|
357
|
+
|
|
358
|
+
const outOfContract = (threadId: string, operation: string, observed: string): ThreadClientError =>
|
|
359
|
+
ThreadClientError.make({
|
|
360
|
+
threadId,
|
|
361
|
+
message: boundHostDiagnostic(
|
|
362
|
+
`The Thread Object answered ${operation} with the out-of-contract ${observed}.`,
|
|
363
|
+
),
|
|
364
|
+
})
|
|
365
|
+
|
|
366
|
+
const hostRpcMethods = {
|
|
367
|
+
submit: 'submitEncoded',
|
|
368
|
+
awaitSettlement: 'awaitSettlementEncoded',
|
|
369
|
+
awaitSettlementRecord: 'awaitSettlementRecordEncoded',
|
|
370
|
+
submissionStatus: 'submissionStatusEncoded',
|
|
371
|
+
awaitProgress: 'awaitProgressEncoded',
|
|
372
|
+
cancelProgress: 'cancelProgressEncoded',
|
|
373
|
+
observePage: 'observePage',
|
|
374
|
+
abort: 'abortEncoded',
|
|
375
|
+
resolveApproval: 'resolveApprovalEncoded',
|
|
376
|
+
resolveUnknown: 'resolveUnknownEncoded',
|
|
377
|
+
} as const satisfies Record<string, keyof ThreadObjectRpc>
|
|
378
|
+
|
|
379
|
+
/** Worker-side client over the Thread Object namespace (DEPLOY-010). */
|
|
380
|
+
export class CloudflareThreadClient extends Context.Service<
|
|
381
|
+
CloudflareThreadClient,
|
|
382
|
+
{
|
|
383
|
+
/** Encode the input client-side, then durably submit to the owning Object. */
|
|
384
|
+
readonly submit: <InputSchema extends Schema.Top>(
|
|
385
|
+
agent: DurableSubmitAgent<InputSchema>,
|
|
386
|
+
input: InputSchema['Type'],
|
|
387
|
+
options: DurableSubmitOptions,
|
|
388
|
+
) => Effect.Effect<Receipt, ClientSubmitFailure, InputSchema['EncodingServices']>
|
|
389
|
+
/** Wake-hinted, poll-guaranteed settlement wait executed inside the owning Object. */
|
|
390
|
+
readonly submissionStatus: (
|
|
391
|
+
receipt: Receipt,
|
|
392
|
+
) => Effect.Effect<SubmissionStatus, ClientAwaitFailure>
|
|
393
|
+
/**
|
|
394
|
+
* Wait for settlement; interruption spends at most one second cancelling the remote
|
|
395
|
+
* observation best effort. Cancellation never aborts the admitted Run.
|
|
396
|
+
*/
|
|
397
|
+
readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, ClientAwaitFailure>
|
|
398
|
+
/**
|
|
399
|
+
* Wait for finalization and return this Receipt's canonical terminal record in one RPC.
|
|
400
|
+
* Requires both settlement and observation authority. Decode an ordinary completed
|
|
401
|
+
* record's result through the Agent output Schema; joined completion may have no result.
|
|
402
|
+
* Interruption uses the same bounded observation cancellation as `awaitSettlement`.
|
|
403
|
+
*/
|
|
404
|
+
readonly awaitSettlementRecord: (
|
|
405
|
+
receipt: Receipt,
|
|
406
|
+
) => Effect.Effect<SubmissionSettledRecord, ClientAwaitFailure>
|
|
407
|
+
/**
|
|
408
|
+
* Wait without polling until progress after `afterSequence` is already durable or hinted.
|
|
409
|
+
* The result is deliberately void: canonical records remain authoritative and must be read.
|
|
410
|
+
* Interruption waits at most one second for best-effort remote cancellation.
|
|
411
|
+
*/
|
|
412
|
+
readonly awaitProgress: (
|
|
413
|
+
threadId: ThreadId,
|
|
414
|
+
afterSequence: CanonicalSequence,
|
|
415
|
+
) => Effect.Effect<void, ClientProgressFailure>
|
|
416
|
+
/**
|
|
417
|
+
* Current provisional text followed by native deltas. Reset starts a replacement snapshot,
|
|
418
|
+
* including when a slow consumer exceeds the fixed backlog. Reconcile by
|
|
419
|
+
* Run/Turn identity to canonical records; discard drafts on Discard, AttemptEnded,
|
|
420
|
+
* Reset or stream failure. Snapshots exist only in the Object incarnation's memory.
|
|
421
|
+
* Scope the stream: interruption cancels its remote subscription.
|
|
422
|
+
*/
|
|
423
|
+
readonly watchText: (threadId: ThreadId) => Stream.Stream<LiveTextFrame, ClientObserveFailure>
|
|
424
|
+
/**
|
|
425
|
+
* Forward producer NDJSON bytes without decoding or re-encoding frames.
|
|
426
|
+
* Blank keepalive lines every 15 seconds expose idle transport disconnects.
|
|
427
|
+
* The final consumer must use `decodeLiveText` to validate untrusted frames.
|
|
428
|
+
* Interruption cancels the remote subscription; buffers remain producer-bounded.
|
|
429
|
+
*/
|
|
430
|
+
readonly watchTextBytes: (
|
|
431
|
+
threadId: ThreadId,
|
|
432
|
+
) => Stream.Stream<Uint8Array, ClientObserveFailure>
|
|
433
|
+
/** One bounded page of canonical records. */
|
|
434
|
+
readonly readPage: (
|
|
435
|
+
threadId: ThreadId,
|
|
436
|
+
options?: {
|
|
437
|
+
readonly afterSequence?: CanonicalSequence | undefined
|
|
438
|
+
readonly limit?: number | undefined
|
|
439
|
+
},
|
|
440
|
+
) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>
|
|
441
|
+
/**
|
|
442
|
+
* Every canonical record up to the CURRENT committed tail, via repeated pages. A
|
|
443
|
+
* snapshot read, not a live observation — callers wanting liveness re-read after
|
|
444
|
+
* `awaitSettlement`.
|
|
445
|
+
*/
|
|
446
|
+
readonly readAll: (
|
|
447
|
+
threadId: ThreadId,
|
|
448
|
+
) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>
|
|
449
|
+
/**
|
|
450
|
+
* Submission-addressed operations take the owning Thread explicitly (from the
|
|
451
|
+
* Receipt): minted Submission identities stay OPAQUE outside the storage adapter that
|
|
452
|
+
* minted them (D-P6-5), so the client never parses one to find the lane.
|
|
453
|
+
*/
|
|
454
|
+
readonly abort: (
|
|
455
|
+
threadId: ThreadId,
|
|
456
|
+
command: AbortCommand,
|
|
457
|
+
) => Effect.Effect<AbortIntent, ClientAbortFailure>
|
|
458
|
+
readonly resolveApproval: (
|
|
459
|
+
threadId: ThreadId,
|
|
460
|
+
command: ApprovalDecisionCommand,
|
|
461
|
+
) => Effect.Effect<ApprovalDecisionIntent, ClientApprovalFailure>
|
|
462
|
+
readonly resolveUnknown: (
|
|
463
|
+
threadId: ThreadId,
|
|
464
|
+
command: UnknownResolutionCommand,
|
|
465
|
+
) => Effect.Effect<UnknownResolutionIntent, ClientUnknownFailure>
|
|
466
|
+
}
|
|
467
|
+
>()('@effect-agent/platform-cloudflare/CloudflareThreadClient') {
|
|
468
|
+
/**
|
|
469
|
+
* Assemble the client from a resolved namespace and the platform SecureRandom implementation.
|
|
470
|
+
* rpcTracing is the binding name and remains opt-in. Caller authentication, principals,
|
|
471
|
+
* idempotency keys, and definition digests are still explicit submission inputs.
|
|
472
|
+
*/
|
|
473
|
+
static layerFromBinding(options: {
|
|
474
|
+
readonly namespace: DurableObjectNamespace<ThreadObjectRpc>
|
|
475
|
+
readonly rpcTracing?: string
|
|
476
|
+
}): Layer.Layer<CloudflareThreadClient> {
|
|
477
|
+
return CloudflareThreadClient.layer.pipe(
|
|
478
|
+
Layer.provide([
|
|
479
|
+
ThreadObjectNamespace.layer(options.namespace, options),
|
|
480
|
+
cloudflareCryptoLayer,
|
|
481
|
+
]),
|
|
482
|
+
)
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
static readonly layer: Layer.Layer<
|
|
486
|
+
CloudflareThreadClient,
|
|
487
|
+
never,
|
|
488
|
+
ThreadObjectNamespace | SecureRandom.SecureRandom
|
|
489
|
+
> = Layer.effect(CloudflareThreadClient)(
|
|
490
|
+
Effect.gen(function*() {
|
|
491
|
+
const namespace = yield* ThreadObjectNamespace
|
|
492
|
+
const { rpcTracing } = namespace
|
|
493
|
+
const crypto = yield* SecureRandom.SecureRandom
|
|
494
|
+
|
|
495
|
+
const call = Effect.fnUntraced(
|
|
496
|
+
function*(
|
|
497
|
+
threadId: ThreadId,
|
|
498
|
+
operation: keyof typeof hostRpcMethods,
|
|
499
|
+
encoded: unknown,
|
|
500
|
+
): Effect.fn.Return<HostResponse, ThreadClientError | HostProtocolError> {
|
|
501
|
+
// Empty arguments preserve native arity. Passing `undefined` still adds an argument.
|
|
502
|
+
const traceArgs = rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([])
|
|
503
|
+
|
|
504
|
+
const raw = yield* callThreadObject(
|
|
505
|
+
threadId,
|
|
506
|
+
(stub) => stub[hostRpcMethods[operation]](encoded, ...traceArgs),
|
|
507
|
+
(cause) =>
|
|
508
|
+
ThreadClientError.make({
|
|
509
|
+
threadId,
|
|
510
|
+
message: boundHostDiagnostic(
|
|
511
|
+
`${operation} did not reach the Thread Object: ${
|
|
512
|
+
safeCauseMessage(
|
|
513
|
+
cause,
|
|
514
|
+
'the RPC failed without a diagnostic',
|
|
515
|
+
)
|
|
516
|
+
}`,
|
|
517
|
+
),
|
|
518
|
+
cause,
|
|
519
|
+
...cloudflareFailureSignals(cause),
|
|
520
|
+
}),
|
|
521
|
+
).pipe(Effect.provideService(ThreadObjectNamespace, namespace))
|
|
522
|
+
|
|
523
|
+
return yield* decodeHostResponse(raw).pipe(
|
|
524
|
+
Effect.mapError((error): HostProtocolError =>
|
|
525
|
+
HostProtocolError.make({
|
|
526
|
+
message: boundHostDiagnostic(
|
|
527
|
+
`The ${operation} answer could not be decoded: ${error.message}`,
|
|
528
|
+
),
|
|
529
|
+
})
|
|
530
|
+
),
|
|
531
|
+
)
|
|
532
|
+
},
|
|
533
|
+
(effect, threadId, operation) =>
|
|
534
|
+
rpcTracing === undefined
|
|
535
|
+
? Effect.withSpan(effect, 'CloudflareThreadClient.call', {
|
|
536
|
+
attributes: { threadId, operation },
|
|
537
|
+
})
|
|
538
|
+
: RpcTracing.withRpcClientSpan(effect, rpcTracing, hostRpcMethods[operation]),
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
const expect = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(
|
|
542
|
+
threadId: string,
|
|
543
|
+
operation: string,
|
|
544
|
+
resultSchema: ResultSchema,
|
|
545
|
+
failureSchema: FailureSchema,
|
|
546
|
+
) => {
|
|
547
|
+
const isExpectedResult = Schema.is(resultSchema)
|
|
548
|
+
const isExpectedFailure = Schema.is(failureSchema)
|
|
549
|
+
|
|
550
|
+
return (
|
|
551
|
+
response: HostResponse,
|
|
552
|
+
): Effect.Effect<ResultSchema['Type'], FailureSchema['Type'] | ThreadClientError> => {
|
|
553
|
+
if (response._tag === 'HostFailed') {
|
|
554
|
+
const failure = response.failure
|
|
555
|
+
|
|
556
|
+
return isExpectedFailure(failure)
|
|
557
|
+
? Effect.fail(failure)
|
|
558
|
+
: Effect.fail(outOfContract(threadId, operation, `failure ${failure._tag}`))
|
|
559
|
+
}
|
|
560
|
+
if (!isExpectedResult(response)) {
|
|
561
|
+
return Effect.fail(outOfContract(threadId, operation, `result ${response._tag}`))
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
return Effect.succeed(response)
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const readPage = Effect.fnUntraced(function*(
|
|
569
|
+
threadId: ThreadId,
|
|
570
|
+
options?: {
|
|
571
|
+
readonly afterSequence?: CanonicalSequence | undefined
|
|
572
|
+
readonly limit?: number | undefined
|
|
573
|
+
},
|
|
574
|
+
) {
|
|
575
|
+
const request = ObservePageRequest.make({
|
|
576
|
+
...(options?.afterSequence === undefined ? {} : { afterSequence: options.afterSequence }),
|
|
577
|
+
limit: options?.limit ?? 256,
|
|
578
|
+
})
|
|
579
|
+
|
|
580
|
+
const encoded = yield* encodeObservePageRequest(request).pipe(
|
|
581
|
+
Effect.mapError((error) =>
|
|
582
|
+
HostProtocolError.make({
|
|
583
|
+
message: boundHostDiagnostic(`observePage request encode failed: ${error.message}`),
|
|
584
|
+
})
|
|
585
|
+
),
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
const response = yield* call(threadId, 'observePage', encoded)
|
|
589
|
+
|
|
590
|
+
const page = yield* expect(
|
|
591
|
+
threadId,
|
|
592
|
+
'observePage',
|
|
593
|
+
ObservedPage,
|
|
594
|
+
ClientObserveHostFailure,
|
|
595
|
+
)(response)
|
|
596
|
+
|
|
597
|
+
return page.records
|
|
598
|
+
})
|
|
599
|
+
|
|
600
|
+
const cancelProgress = (threadId: ThreadId, waiterId: string): Effect.Effect<void> =>
|
|
601
|
+
encodeCancelProgressRequest(CancelProgressRequest.make({ waiterId })).pipe(
|
|
602
|
+
Effect.mapError(() => undefined),
|
|
603
|
+
Effect.flatMap((encoded) => call(threadId, 'cancelProgress', encoded)),
|
|
604
|
+
// Finalizers are uninterruptible; only the foreign RPC branch must remain
|
|
605
|
+
// interruptible so a lost cancellation reply cannot prevent local shutdown.
|
|
606
|
+
Effect.interruptible,
|
|
607
|
+
Effect.timeout(PROGRESS_CANCELLATION_TIMEOUT),
|
|
608
|
+
Effect.asVoid,
|
|
609
|
+
Effect.ignore,
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
const awaitSettlementCall = Effect.fnUntraced(function*(
|
|
613
|
+
receipt: Receipt,
|
|
614
|
+
operation: 'awaitSettlement' | 'awaitSettlementRecord',
|
|
615
|
+
): Effect.fn.Return<HostResponse, ClientAwaitFailure> {
|
|
616
|
+
const waiterId = yield* crypto.uuidV4()
|
|
617
|
+
|
|
618
|
+
const encoded = yield* encodeAwaitSettlementRequest(
|
|
619
|
+
AwaitSettlementRequest.make({ ...receipt, waiterId }),
|
|
620
|
+
).pipe(
|
|
621
|
+
Effect.mapError((error) =>
|
|
622
|
+
HostProtocolError.make({
|
|
623
|
+
message: boundHostDiagnostic(`${operation} request encode failed: ${error.message}`),
|
|
624
|
+
})
|
|
625
|
+
),
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
return yield* call(receipt.threadId, operation, encoded).pipe(
|
|
629
|
+
Effect.onInterrupt(() => cancelProgress(receipt.threadId, waiterId)),
|
|
630
|
+
)
|
|
631
|
+
})
|
|
632
|
+
|
|
633
|
+
const watchTextBytes = (
|
|
634
|
+
threadId: ThreadId,
|
|
635
|
+
): Stream.Stream<Uint8Array, ClientObserveFailure> =>
|
|
636
|
+
Stream.unwrap(
|
|
637
|
+
Effect.gen(function*() {
|
|
638
|
+
const traceArgs = rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([])
|
|
639
|
+
|
|
640
|
+
const openingFailure = (cause: unknown) =>
|
|
641
|
+
ThreadClientError.make({
|
|
642
|
+
threadId,
|
|
643
|
+
message: 'Provisional text observation could not reach the Thread Object',
|
|
644
|
+
cause,
|
|
645
|
+
...cloudflareFailureSignals(cause),
|
|
646
|
+
})
|
|
647
|
+
|
|
648
|
+
// Retain the original RPC promise: resolving through callThreadObject would
|
|
649
|
+
// erase its optional native disposer before an interrupted opening can use it.
|
|
650
|
+
const target = yield* RpcTargets.get(namespace, threadId, () => namespace.get(threadId)).pipe(
|
|
651
|
+
Effect.mapError(openingFailure),
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
let request: Promise<unknown> | undefined
|
|
655
|
+
let received: unknown
|
|
656
|
+
let closed = false
|
|
657
|
+
|
|
658
|
+
const cancel = () => {
|
|
659
|
+
const value = received
|
|
660
|
+
|
|
661
|
+
received = undefined
|
|
662
|
+
|
|
663
|
+
const observation = Schema.is(LiveTextObservation)(value) ? value : undefined
|
|
664
|
+
|
|
665
|
+
// Native RPC disposes the capability with the request; also release
|
|
666
|
+
// it for application-owned endpoints and late opening responses.
|
|
667
|
+
try {
|
|
668
|
+
observation?.lifetime[Symbol.dispose]()
|
|
669
|
+
} catch {
|
|
670
|
+
// A request disposer may already have revoked this stub.
|
|
671
|
+
}
|
|
672
|
+
const stream = observation?.stream ?? value
|
|
673
|
+
|
|
674
|
+
return stream instanceof ReadableStream && !stream.locked
|
|
675
|
+
? stream.cancel().catch(() => undefined)
|
|
676
|
+
: Promise.resolve()
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// Install ownership before invoking foreign code, not after its promise settles.
|
|
680
|
+
yield* Effect.addFinalizer(() =>
|
|
681
|
+
Effect.try({
|
|
682
|
+
try: () => {
|
|
683
|
+
closed = true
|
|
684
|
+
if (Predicate.hasProperty(request, Symbol.dispose)) {
|
|
685
|
+
const dispose = request[Symbol.dispose]
|
|
686
|
+
|
|
687
|
+
if (typeof dispose === 'function') dispose.call(request)
|
|
688
|
+
}
|
|
689
|
+
},
|
|
690
|
+
catch: () => undefined,
|
|
691
|
+
}).pipe(
|
|
692
|
+
Effect.ignore,
|
|
693
|
+
Effect.andThen(
|
|
694
|
+
Effect.tryPromise({ try: cancel, catch: () => undefined }).pipe(
|
|
695
|
+
Effect.interruptible,
|
|
696
|
+
Effect.timeout(PROGRESS_CANCELLATION_TIMEOUT),
|
|
697
|
+
Effect.ignore,
|
|
698
|
+
),
|
|
699
|
+
),
|
|
700
|
+
)
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
const encodedRequest = yield* Schema.encodeEffect(WatchTextRequest)({
|
|
704
|
+
schemaVersion: 1,
|
|
705
|
+
}).pipe(Effect.mapError(openingFailure))
|
|
706
|
+
|
|
707
|
+
const raw = yield* Effect.tryPromise({
|
|
708
|
+
try: () => {
|
|
709
|
+
request = target.watchTextEncoded(encodedRequest, ...traceArgs)
|
|
710
|
+
|
|
711
|
+
return request.then((value) => {
|
|
712
|
+
received = value
|
|
713
|
+
|
|
714
|
+
// A custom endpoint may return a plain, non-cancellable promise. Keep
|
|
715
|
+
// late cleanup on that native promise chain; it starts no Effect fiber.
|
|
716
|
+
return closed ? cancel().then(() => value) : value
|
|
717
|
+
})
|
|
718
|
+
},
|
|
719
|
+
catch: openingFailure,
|
|
720
|
+
}).pipe(
|
|
721
|
+
Effect.interruptible,
|
|
722
|
+
Effect.tapCause(() => RpcTargets.invalidate(target)),
|
|
723
|
+
)
|
|
724
|
+
|
|
725
|
+
const stream = Schema.is(LiveTextObservation)(raw) ? raw.stream : raw
|
|
726
|
+
|
|
727
|
+
if (stream instanceof ReadableStream) {
|
|
728
|
+
return Stream.fromReadableStream<Uint8Array, ThreadClientError>({
|
|
729
|
+
evaluate: () => stream,
|
|
730
|
+
// The subscription Scope cancels after the reader releases its lock.
|
|
731
|
+
releaseLockOnEnd: true,
|
|
732
|
+
onError: (cause) =>
|
|
733
|
+
ThreadClientError.make({
|
|
734
|
+
threadId,
|
|
735
|
+
message: 'Provisional text disconnected; discard drafts and read canonical records',
|
|
736
|
+
cause,
|
|
737
|
+
}),
|
|
738
|
+
})
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
const response = yield* decodeHostResponse(raw).pipe(
|
|
742
|
+
Effect.mapError(liveTextProtocolFailure),
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
if (
|
|
746
|
+
response._tag === 'HostFailed' &&
|
|
747
|
+
Schema.is(ClientObserveHostFailure)(response.failure)
|
|
748
|
+
) {
|
|
749
|
+
return yield* response.failure
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
return yield* liveTextProtocolFailure()
|
|
753
|
+
}),
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
return CloudflareThreadClient.of({
|
|
757
|
+
submit: Effect.fnUntraced(function*<InputSchema extends Schema.Top>(
|
|
758
|
+
agent: DurableSubmitAgent<InputSchema>,
|
|
759
|
+
input: InputSchema['Type'],
|
|
760
|
+
options: DurableSubmitOptions,
|
|
761
|
+
) {
|
|
762
|
+
// Client-side half of `DurableAgentRuntime.submit`'s input boundary: encode
|
|
763
|
+
// through the Agent's input schema and prove the canonical persistence bounds.
|
|
764
|
+
const encodedInput = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(
|
|
765
|
+
Effect.mapError((cause) =>
|
|
766
|
+
AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` })
|
|
767
|
+
),
|
|
768
|
+
)
|
|
769
|
+
|
|
770
|
+
const inputPayload = yield* Schema.decodeUnknownEffect(PersistedJson)(encodedInput).pipe(
|
|
771
|
+
Effect.mapError(() =>
|
|
772
|
+
AgentInputError.make({
|
|
773
|
+
message: 'Agent input does not satisfy the canonical persistence bounds',
|
|
774
|
+
})
|
|
775
|
+
),
|
|
776
|
+
)
|
|
777
|
+
|
|
778
|
+
const request = {
|
|
779
|
+
agentId: agent.definition.id,
|
|
780
|
+
principal: options.principal,
|
|
781
|
+
idempotencyKey: options.idempotencyKey,
|
|
782
|
+
...(options.admissionGroup === undefined
|
|
783
|
+
? {}
|
|
784
|
+
: { admissionGroup: options.admissionGroup }),
|
|
785
|
+
...(options.admissionFence === undefined
|
|
786
|
+
? {}
|
|
787
|
+
: { admissionFence: options.admissionFence }),
|
|
788
|
+
...(options.workerAdmission === undefined
|
|
789
|
+
? {}
|
|
790
|
+
: { workerAdmission: options.workerAdmission }),
|
|
791
|
+
...(options.messageAdmission === undefined
|
|
792
|
+
? {}
|
|
793
|
+
: { messageAdmission: options.messageAdmission }),
|
|
794
|
+
definitions: options.definitions,
|
|
795
|
+
inputPayload,
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const encoded = yield* encodeSubmitRequest(request).pipe(
|
|
799
|
+
Effect.mapError((error) =>
|
|
800
|
+
HostProtocolError.make({
|
|
801
|
+
message: boundHostDiagnostic(`submit request encode failed: ${error.message}`),
|
|
802
|
+
})
|
|
803
|
+
),
|
|
804
|
+
)
|
|
805
|
+
|
|
806
|
+
const response = yield* call(options.threadId, 'submit', encoded)
|
|
807
|
+
|
|
808
|
+
const succeeded = yield* expect(
|
|
809
|
+
options.threadId,
|
|
810
|
+
'submit',
|
|
811
|
+
SubmitSucceeded,
|
|
812
|
+
ClientSubmitHostFailure,
|
|
813
|
+
)(response)
|
|
814
|
+
|
|
815
|
+
return succeeded.receipt
|
|
816
|
+
}),
|
|
817
|
+
|
|
818
|
+
submissionStatus: Effect.fnUntraced(function*(receipt) {
|
|
819
|
+
const encoded = yield* encodeReceipt(receipt).pipe(
|
|
820
|
+
Effect.mapError(() => HostProtocolError.make({ message: 'Invalid receipt' })),
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
const response = yield* call(receipt.threadId, 'submissionStatus', encoded)
|
|
824
|
+
|
|
825
|
+
const result = yield* expect(
|
|
826
|
+
receipt.threadId,
|
|
827
|
+
'submissionStatus',
|
|
828
|
+
SubmissionStatusResponse,
|
|
829
|
+
ClientAwaitHostFailure,
|
|
830
|
+
)(response)
|
|
831
|
+
|
|
832
|
+
return result.status
|
|
833
|
+
}),
|
|
834
|
+
awaitSettlement: Effect.fnUntraced(function*(receipt) {
|
|
835
|
+
const response = yield* awaitSettlementCall(receipt, 'awaitSettlement')
|
|
836
|
+
|
|
837
|
+
const settled = yield* expect(
|
|
838
|
+
receipt.threadId,
|
|
839
|
+
'awaitSettlement',
|
|
840
|
+
SettlementReached,
|
|
841
|
+
ClientAwaitHostFailure,
|
|
842
|
+
)(response)
|
|
843
|
+
|
|
844
|
+
return settled.settlement
|
|
845
|
+
}),
|
|
846
|
+
|
|
847
|
+
awaitSettlementRecord: Effect.fnUntraced(function*(receipt) {
|
|
848
|
+
const response = yield* awaitSettlementCall(receipt, 'awaitSettlementRecord')
|
|
849
|
+
|
|
850
|
+
const settled = yield* expect(
|
|
851
|
+
receipt.threadId,
|
|
852
|
+
'awaitSettlementRecord',
|
|
853
|
+
SettlementRecordReached,
|
|
854
|
+
ClientAwaitHostFailure,
|
|
855
|
+
)(response)
|
|
856
|
+
|
|
857
|
+
return settled.record
|
|
858
|
+
}),
|
|
859
|
+
|
|
860
|
+
awaitProgress: Effect.fnUntraced(function*(threadId, afterSequence) {
|
|
861
|
+
const waiterId = yield* crypto.uuidV4()
|
|
862
|
+
|
|
863
|
+
const request = AwaitProgressRequest.make({ afterSequence, waiterId })
|
|
864
|
+
|
|
865
|
+
const encoded = yield* encodeAwaitProgressRequest(request).pipe(
|
|
866
|
+
Effect.mapError((error) =>
|
|
867
|
+
HostProtocolError.make({
|
|
868
|
+
message: boundHostDiagnostic(
|
|
869
|
+
`awaitProgress request encode failed: ${error.message}`,
|
|
870
|
+
),
|
|
871
|
+
})
|
|
872
|
+
),
|
|
873
|
+
)
|
|
874
|
+
|
|
875
|
+
const attempt = (retry: number): Effect.Effect<void, ClientProgressFailure> =>
|
|
876
|
+
call(threadId, 'awaitProgress', encoded).pipe(
|
|
877
|
+
Effect.flatMap(
|
|
878
|
+
expect(threadId, 'awaitProgress', ProgressObserved, ClientObserveHostFailure),
|
|
879
|
+
),
|
|
880
|
+
Effect.asVoid,
|
|
881
|
+
Effect.catchTag(
|
|
882
|
+
'ThreadClientError',
|
|
883
|
+
(error) =>
|
|
884
|
+
error.retryable === true && error.overloaded !== true && retry < 5
|
|
885
|
+
? Effect.sleep(Duration.millis(10 * 2 ** retry)).pipe(
|
|
886
|
+
Effect.andThen(attempt(retry + 1)),
|
|
887
|
+
)
|
|
888
|
+
: Effect.fail(error),
|
|
889
|
+
),
|
|
890
|
+
)
|
|
891
|
+
|
|
892
|
+
yield* attempt(0).pipe(Effect.onInterrupt(() => cancelProgress(threadId, waiterId)))
|
|
893
|
+
}),
|
|
894
|
+
|
|
895
|
+
watchText: (threadId) => decodeLiveText(threadId, watchTextBytes(threadId)),
|
|
896
|
+
watchTextBytes,
|
|
897
|
+
|
|
898
|
+
readPage,
|
|
899
|
+
|
|
900
|
+
readAll: Effect.fnUntraced(function*(threadId) {
|
|
901
|
+
const all: Array<CanonicalRecordEnvelope> = []
|
|
902
|
+
let after: CanonicalSequence | undefined
|
|
903
|
+
|
|
904
|
+
for (;;) {
|
|
905
|
+
const page = yield* readPage(threadId, { afterSequence: after, limit: 1_024 })
|
|
906
|
+
|
|
907
|
+
all.push(...page)
|
|
908
|
+
const last = page.at(-1)
|
|
909
|
+
|
|
910
|
+
if (page.length < 1_024 || last === undefined) return all
|
|
911
|
+
after = last.sequence
|
|
912
|
+
}
|
|
913
|
+
}),
|
|
914
|
+
|
|
915
|
+
abort: Effect.fnUntraced(function*(threadId, command) {
|
|
916
|
+
const encoded = yield* encodeAbortCommand(command).pipe(
|
|
917
|
+
Effect.mapError((error) =>
|
|
918
|
+
HostProtocolError.make({
|
|
919
|
+
message: boundHostDiagnostic(`abort command encode failed: ${error.message}`),
|
|
920
|
+
})
|
|
921
|
+
),
|
|
922
|
+
)
|
|
923
|
+
|
|
924
|
+
const response = yield* call(threadId, 'abort', encoded)
|
|
925
|
+
|
|
926
|
+
const recorded = yield* expect(
|
|
927
|
+
threadId,
|
|
928
|
+
'abort',
|
|
929
|
+
AbortRecorded,
|
|
930
|
+
ClientAbortHostFailure,
|
|
931
|
+
)(response)
|
|
932
|
+
|
|
933
|
+
return recorded.intent
|
|
934
|
+
}),
|
|
935
|
+
|
|
936
|
+
resolveApproval: Effect.fnUntraced(function*(threadId, command) {
|
|
937
|
+
const encoded = yield* encodeApprovalDecisionCommand(command).pipe(
|
|
938
|
+
Effect.mapError((error) =>
|
|
939
|
+
HostProtocolError.make({
|
|
940
|
+
message: boundHostDiagnostic(`approval command encode failed: ${error.message}`),
|
|
941
|
+
})
|
|
942
|
+
),
|
|
943
|
+
)
|
|
944
|
+
|
|
945
|
+
const response = yield* call(threadId, 'resolveApproval', encoded)
|
|
946
|
+
|
|
947
|
+
const recorded = yield* expect(
|
|
948
|
+
threadId,
|
|
949
|
+
'resolveApproval',
|
|
950
|
+
ApprovalRecorded,
|
|
951
|
+
ClientApprovalHostFailure,
|
|
952
|
+
)(response)
|
|
953
|
+
|
|
954
|
+
return recorded.intent
|
|
955
|
+
}),
|
|
956
|
+
|
|
957
|
+
resolveUnknown: Effect.fnUntraced(function*(threadId, command) {
|
|
958
|
+
const encoded = yield* encodeUnknownResolutionCommand(command).pipe(
|
|
959
|
+
Effect.mapError((error) =>
|
|
960
|
+
HostProtocolError.make({
|
|
961
|
+
message: boundHostDiagnostic(`resolution command encode failed: ${error.message}`),
|
|
962
|
+
})
|
|
963
|
+
),
|
|
964
|
+
)
|
|
965
|
+
|
|
966
|
+
const response = yield* call(threadId, 'resolveUnknown', encoded)
|
|
967
|
+
|
|
968
|
+
const recorded = yield* expect(
|
|
969
|
+
threadId,
|
|
970
|
+
'resolveUnknown',
|
|
971
|
+
UnknownResolutionRecorded,
|
|
972
|
+
ClientUnknownHostFailure,
|
|
973
|
+
)(response)
|
|
974
|
+
|
|
975
|
+
return recorded.intent
|
|
976
|
+
}),
|
|
977
|
+
})
|
|
978
|
+
}),
|
|
979
|
+
)
|
|
980
|
+
}
|