@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.
- 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,8 @@
|
|
|
1
|
+
import { Rpc } from 'effect-cf'
|
|
2
|
+
import * as Schema from 'effect/Schema'
|
|
3
|
+
|
|
4
|
+
/** The RPC lifetime survives an idle byte stream and is disposed on caller disconnect. */
|
|
5
|
+
export const Observation = Schema.Struct({
|
|
6
|
+
stream: Schema.instanceOf(ReadableStream<Uint8Array>),
|
|
7
|
+
lifetime: Schema.declare(Rpc.isDisposable),
|
|
8
|
+
})
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { ThreadId } from '@systemfsoftware/agent/identifiers'
|
|
2
|
+
import { Event } from '@systemfsoftware/agent/provisional-text'
|
|
3
|
+
import * as Schema from 'effect/Schema'
|
|
4
|
+
|
|
5
|
+
import { HostProtocolError } from './host-protocol-error'
|
|
6
|
+
|
|
7
|
+
export const MAX_FRAME_BYTES = 32 * 1_024
|
|
8
|
+
export const MAX_ID_LENGTH = 256
|
|
9
|
+
export const MAX_DELTA_LENGTH = 4_096
|
|
10
|
+
export const BUFFER_SIZE = 32
|
|
11
|
+
export const MAX_OBSERVERS = 8
|
|
12
|
+
export const MAX_DRAFT_PARTS = 32
|
|
13
|
+
export const MAX_DRAFT_LENGTH = 2 * 1_024 * 1_024
|
|
14
|
+
|
|
15
|
+
const streamId = Schema.NonEmptyString.check(Schema.isMaxLength(MAX_ID_LENGTH))
|
|
16
|
+
|
|
17
|
+
export const Request = Schema.Struct({ schemaVersion: Schema.Literal(1) })
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Reset replaces all drafts with a snapshot, streamed as native Text parts before live deltas.
|
|
21
|
+
* Each snapshot starts a fresh streamId. Its sequences are unrelated to canonical sequences.
|
|
22
|
+
*/
|
|
23
|
+
export const Frame = Schema.Union([
|
|
24
|
+
Schema.TaggedStruct('Reset', {
|
|
25
|
+
schemaVersion: Schema.Literal(1),
|
|
26
|
+
streamId,
|
|
27
|
+
threadId: ThreadId,
|
|
28
|
+
sequence: Schema.Literal(0),
|
|
29
|
+
}),
|
|
30
|
+
Schema.TaggedStruct('Event', {
|
|
31
|
+
schemaVersion: Schema.Literal(1),
|
|
32
|
+
streamId,
|
|
33
|
+
sequence: Schema.Int.check(Schema.isGreaterThan(0)),
|
|
34
|
+
event: Event,
|
|
35
|
+
}),
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
export type Frame = typeof Frame.Type
|
|
39
|
+
|
|
40
|
+
/** Bounds are checked before queueing; provider metadata is deliberately absent. */
|
|
41
|
+
export const isBoundedEvent = (event: Event): boolean => {
|
|
42
|
+
const ids: string[] = [event.threadId, event.submissionId, event.attemptId]
|
|
43
|
+
|
|
44
|
+
if (event._tag !== 'AttemptEnded') ids.push(event.runId, event.turnId)
|
|
45
|
+
if (ids.some((id) => id.length > MAX_ID_LENGTH)) return false
|
|
46
|
+
|
|
47
|
+
return (
|
|
48
|
+
event._tag !== 'Text' ||
|
|
49
|
+
(event.part.id.length <= MAX_ID_LENGTH &&
|
|
50
|
+
Object.keys(event.part.metadata).length === 0 &&
|
|
51
|
+
((event.part.type !== 'text-delta' && event.part.type !== 'reasoning-delta') ||
|
|
52
|
+
event.part.delta.length <= MAX_DELTA_LENGTH))
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const liveTextProtocolFailure = () =>
|
|
57
|
+
HostProtocolError.make({
|
|
58
|
+
message: 'Provisional text is incomplete or invalid; discard drafts and read canonical records',
|
|
59
|
+
})
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { type ThreadId } from '@systemfsoftware/agent/identifiers'
|
|
2
|
+
import { type Event, Publisher } from '@systemfsoftware/agent/provisional-text'
|
|
3
|
+
import { RpcTarget } from 'cloudflare:workers'
|
|
4
|
+
import * as Response from 'effect/ai/Response'
|
|
5
|
+
import * as Context from 'effect/Context'
|
|
6
|
+
import * as Effect from 'effect/Effect'
|
|
7
|
+
import * as Layer from 'effect/Layer'
|
|
8
|
+
import * as Schema from 'effect/Schema'
|
|
9
|
+
|
|
10
|
+
import { HostProtocolError } from './host-protocol-error'
|
|
11
|
+
import { Observation } from './live-text-observation'
|
|
12
|
+
import {
|
|
13
|
+
BUFFER_SIZE,
|
|
14
|
+
Frame,
|
|
15
|
+
isBoundedEvent,
|
|
16
|
+
MAX_DELTA_LENGTH,
|
|
17
|
+
MAX_DRAFT_LENGTH,
|
|
18
|
+
MAX_DRAFT_PARTS,
|
|
19
|
+
MAX_FRAME_BYTES,
|
|
20
|
+
MAX_ID_LENGTH,
|
|
21
|
+
MAX_OBSERVERS,
|
|
22
|
+
} from './live-text-protocol'
|
|
23
|
+
|
|
24
|
+
class ObservationLifetime extends RpcTarget {
|
|
25
|
+
readonly #close: () => void
|
|
26
|
+
|
|
27
|
+
constructor(close: () => void) {
|
|
28
|
+
super()
|
|
29
|
+
this.#close = close
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
[Symbol.dispose]() {
|
|
33
|
+
this.#close()
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type TextEvent = Extract<Event, { readonly _tag: 'Text' }>
|
|
38
|
+
|
|
39
|
+
interface Draft {
|
|
40
|
+
readonly start: TextEvent
|
|
41
|
+
text: string
|
|
42
|
+
ended: boolean
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface Observer {
|
|
46
|
+
readonly threadId: ThreadId
|
|
47
|
+
readonly offer: (event: Event) => void
|
|
48
|
+
readonly close: (error?: HostProtocolError) => void
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The observer callback is synchronous; compile its frame encoder once.
|
|
52
|
+
const encode = Schema.encodeSync(Frame)
|
|
53
|
+
|
|
54
|
+
/** One Object incarnation; owns drafts and subscriptions independently of RPC event scopes. */
|
|
55
|
+
export class LiveTextHub extends Context.Service<
|
|
56
|
+
LiveTextHub,
|
|
57
|
+
{
|
|
58
|
+
readonly open: (
|
|
59
|
+
threadId: ThreadId,
|
|
60
|
+
) => Effect.Effect<typeof Observation.Type, HostProtocolError>
|
|
61
|
+
}
|
|
62
|
+
>()('@effect-agent/platform-cloudflare/LiveTextHub') {
|
|
63
|
+
static readonly layer: Layer.Layer<LiveTextHub> = Layer.effectContext(
|
|
64
|
+
Effect.gen(function*() {
|
|
65
|
+
const observers = new Set<Observer>()
|
|
66
|
+
const drafts = new Map<string, Draft>()
|
|
67
|
+
let length = 0
|
|
68
|
+
let stopped = false
|
|
69
|
+
|
|
70
|
+
let unavailable:
|
|
71
|
+
| { readonly error: HostProtocolError; readonly attemptId: Event['attemptId'] }
|
|
72
|
+
| undefined
|
|
73
|
+
|
|
74
|
+
const encoder = new TextEncoder()
|
|
75
|
+
|
|
76
|
+
yield* Effect.addFinalizer(() =>
|
|
77
|
+
Effect.sync(() => {
|
|
78
|
+
stopped = true
|
|
79
|
+
drafts.clear()
|
|
80
|
+
for (const observer of observers) observer.close()
|
|
81
|
+
})
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
const fail = (attemptId: Event['attemptId']) => {
|
|
85
|
+
const error = HostProtocolError.make({
|
|
86
|
+
message: 'Provisional text exceeds its draft bounds or is invalid; read canonical records',
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
unavailable = { error, attemptId }
|
|
90
|
+
drafts.clear()
|
|
91
|
+
length = 0
|
|
92
|
+
for (const observer of observers) observer.close(error)
|
|
93
|
+
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const offerUnsafe = (event: Event): boolean => {
|
|
98
|
+
// Retain drafts even without subscribers. Invalid input disables previews until an
|
|
99
|
+
// offending Attempt ends; canonical execution never depends on the observer's state.
|
|
100
|
+
if (stopped) return false
|
|
101
|
+
if (event._tag === 'AttemptEnded' && event.attemptId === unavailable?.attemptId) {
|
|
102
|
+
unavailable = undefined
|
|
103
|
+
}
|
|
104
|
+
if (unavailable !== undefined) return false
|
|
105
|
+
if (!isBoundedEvent(event)) {
|
|
106
|
+
// Drop an oversized terminal frame without disabling an already-ended Attempt.
|
|
107
|
+
return event._tag === 'AttemptEnded' ? false : fail(event.attemptId)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (event._tag === 'Text') {
|
|
111
|
+
const key = JSON.stringify([
|
|
112
|
+
event.threadId,
|
|
113
|
+
event.submissionId,
|
|
114
|
+
event.attemptId,
|
|
115
|
+
event.runId,
|
|
116
|
+
event.turnId,
|
|
117
|
+
event.generation,
|
|
118
|
+
event.part.type.startsWith('reasoning-') ? 'reasoning' : 'text',
|
|
119
|
+
event.part.id,
|
|
120
|
+
])
|
|
121
|
+
|
|
122
|
+
const draft = drafts.get(key)
|
|
123
|
+
|
|
124
|
+
if (event.part.type === 'text-start' || event.part.type === 'reasoning-start') {
|
|
125
|
+
if (draft !== undefined || drafts.size >= MAX_DRAFT_PARTS) return fail(event.attemptId)
|
|
126
|
+
drafts.set(key, { start: event, text: '', ended: false })
|
|
127
|
+
} else {
|
|
128
|
+
// After invalidation, never expose an orphaned suffix as a complete prefix.
|
|
129
|
+
if (draft === undefined) return false
|
|
130
|
+
if (draft.ended) return fail(event.attemptId)
|
|
131
|
+
if (event.part.type === 'text-delta' || event.part.type === 'reasoning-delta') {
|
|
132
|
+
if (length + event.part.delta.length > MAX_DRAFT_LENGTH) return fail(event.attemptId)
|
|
133
|
+
draft.text += event.part.delta
|
|
134
|
+
length += event.part.delta.length
|
|
135
|
+
} else {
|
|
136
|
+
draft.ended = true
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
} else {
|
|
140
|
+
for (const [key, draft] of drafts) {
|
|
141
|
+
const start = draft.start
|
|
142
|
+
|
|
143
|
+
if (
|
|
144
|
+
start.threadId === event.threadId &&
|
|
145
|
+
start.submissionId === event.submissionId &&
|
|
146
|
+
start.attemptId === event.attemptId &&
|
|
147
|
+
(event._tag === 'AttemptEnded' ||
|
|
148
|
+
(start.runId === event.runId &&
|
|
149
|
+
start.turnId === event.turnId &&
|
|
150
|
+
start.generation === event.generation))
|
|
151
|
+
) {
|
|
152
|
+
drafts.delete(key)
|
|
153
|
+
length -= draft.text.length
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Fulfill native demand inline. A slow reader only fills its bounded buffer;
|
|
159
|
+
// canonical execution never waits for a pull or a transport acknowledgement.
|
|
160
|
+
for (const observer of observers) {
|
|
161
|
+
if (observer.threadId === event.threadId) observer.offer(event)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return true
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const open = Effect.fnUntraced(function*(threadId: ThreadId) {
|
|
168
|
+
if (stopped) {
|
|
169
|
+
return yield* HostProtocolError.make({ message: 'Provisional text owner is closed' })
|
|
170
|
+
}
|
|
171
|
+
if (unavailable !== undefined) return yield* unavailable.error
|
|
172
|
+
if (threadId.length > MAX_ID_LENGTH || observers.size >= MAX_OBSERVERS) {
|
|
173
|
+
return yield* HostProtocolError.make({
|
|
174
|
+
message: 'Provisional text observation capacity exceeded',
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
const buffer: Event[] = []
|
|
178
|
+
let controller: ReadableStreamDefaultController<Uint8Array> | undefined
|
|
179
|
+
let pending: Generator<Frame> | undefined
|
|
180
|
+
let snapshotNeeded = true
|
|
181
|
+
let streamId = ''
|
|
182
|
+
let sequence = 0
|
|
183
|
+
let closed = false
|
|
184
|
+
let keepalive: ReturnType<typeof setInterval> | undefined
|
|
185
|
+
|
|
186
|
+
const dispose = () => {
|
|
187
|
+
closed = true
|
|
188
|
+
clearInterval(keepalive)
|
|
189
|
+
buffer.length = 0
|
|
190
|
+
pending = undefined
|
|
191
|
+
observers.delete(observer)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const observer: Observer = {
|
|
195
|
+
threadId,
|
|
196
|
+
offer(event) {
|
|
197
|
+
if (buffer.length === BUFFER_SIZE) snapshotNeeded = true
|
|
198
|
+
else buffer.push(event)
|
|
199
|
+
flush()
|
|
200
|
+
},
|
|
201
|
+
close(error) {
|
|
202
|
+
if (closed) return
|
|
203
|
+
dispose()
|
|
204
|
+
if (error === undefined) controller?.close()
|
|
205
|
+
else controller?.error(error)
|
|
206
|
+
},
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const frame = (event: Event): Frame => ({
|
|
210
|
+
_tag: 'Event',
|
|
211
|
+
schemaVersion: 1,
|
|
212
|
+
streamId,
|
|
213
|
+
sequence: ++sequence,
|
|
214
|
+
event,
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
const snapshot = function*(): Generator<Frame> {
|
|
218
|
+
// Capture immutable strings once, then encode bounded slices on consumer pulls.
|
|
219
|
+
// Buffer drain and capture are synchronous so no delta can straddle the snapshot.
|
|
220
|
+
buffer.length = 0
|
|
221
|
+
|
|
222
|
+
const current = Array.from(drafts.values())
|
|
223
|
+
.filter((draft) => draft.start.threadId === threadId)
|
|
224
|
+
.map((draft) => ({ ...draft }))
|
|
225
|
+
|
|
226
|
+
snapshotNeeded = false
|
|
227
|
+
streamId = crypto.randomUUID()
|
|
228
|
+
sequence = 0
|
|
229
|
+
yield {
|
|
230
|
+
_tag: 'Reset',
|
|
231
|
+
schemaVersion: 1,
|
|
232
|
+
streamId,
|
|
233
|
+
threadId,
|
|
234
|
+
sequence: 0,
|
|
235
|
+
}
|
|
236
|
+
for (const draft of current) {
|
|
237
|
+
yield frame(draft.start)
|
|
238
|
+
for (let offset = 0; offset < draft.text.length; offset += MAX_DELTA_LENGTH) {
|
|
239
|
+
yield frame({
|
|
240
|
+
...draft.start,
|
|
241
|
+
part: Response.makePart(
|
|
242
|
+
draft.start.part.type === 'reasoning-start' ? 'reasoning-delta' : 'text-delta',
|
|
243
|
+
{
|
|
244
|
+
id: draft.start.part.id,
|
|
245
|
+
delta: draft.text.slice(offset, offset + MAX_DELTA_LENGTH),
|
|
246
|
+
},
|
|
247
|
+
),
|
|
248
|
+
})
|
|
249
|
+
}
|
|
250
|
+
if (draft.ended) {
|
|
251
|
+
yield frame({
|
|
252
|
+
...draft.start,
|
|
253
|
+
part: Response.makePart(
|
|
254
|
+
draft.start.part.type === 'reasoning-start' ? 'reasoning-end' : 'text-end',
|
|
255
|
+
{ id: draft.start.part.id },
|
|
256
|
+
),
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const flush = () => {
|
|
263
|
+
if (closed || controller === undefined) return
|
|
264
|
+
// Native demand and one queued Frame bound this loop. There is no
|
|
265
|
+
// scheduled consumer fiber between an offered part and its enqueue.
|
|
266
|
+
while (controller.desiredSize !== null && controller.desiredSize > 0) {
|
|
267
|
+
if (snapshotNeeded) pending = snapshot()
|
|
268
|
+
let value: Frame
|
|
269
|
+
|
|
270
|
+
if (pending !== undefined) {
|
|
271
|
+
const next = pending.next()
|
|
272
|
+
|
|
273
|
+
if (next.done) {
|
|
274
|
+
pending = undefined
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
value = next.value
|
|
278
|
+
} else {
|
|
279
|
+
const event = buffer.shift()
|
|
280
|
+
|
|
281
|
+
if (event === undefined) return
|
|
282
|
+
value = frame(event)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
let json: string
|
|
286
|
+
|
|
287
|
+
try {
|
|
288
|
+
json = JSON.stringify(encode(value))
|
|
289
|
+
} catch {
|
|
290
|
+
observer.close(
|
|
291
|
+
HostProtocolError.make({ message: 'Provisional text frame is invalid' }),
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
return
|
|
295
|
+
}
|
|
296
|
+
const bytes = encoder.encode(json + '\n')
|
|
297
|
+
|
|
298
|
+
if (bytes.byteLength > MAX_FRAME_BYTES) {
|
|
299
|
+
observer.close(
|
|
300
|
+
HostProtocolError.make({
|
|
301
|
+
message: 'Provisional text frame exceeds its wire bound',
|
|
302
|
+
}),
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
controller.enqueue(bytes)
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
312
|
+
start(value) {
|
|
313
|
+
controller = value
|
|
314
|
+
observers.add(observer)
|
|
315
|
+
// Write only between complete frames, before RPC can split their bytes.
|
|
316
|
+
// Idle writes expose disconnected consumers without growing the native queue.
|
|
317
|
+
keepalive = setInterval(() => {
|
|
318
|
+
if (closed || value.desiredSize === null || value.desiredSize <= 0) return
|
|
319
|
+
value.enqueue(new Uint8Array([10]))
|
|
320
|
+
}, 15_000)
|
|
321
|
+
flush()
|
|
322
|
+
},
|
|
323
|
+
pull: flush,
|
|
324
|
+
cancel: dispose,
|
|
325
|
+
})
|
|
326
|
+
|
|
327
|
+
// An idle RPC stream may not receive source cancellation until its next
|
|
328
|
+
// enqueue. The returned capability also releases it when the caller's
|
|
329
|
+
// RPC scope ends, without requiring another Frame or producer work.
|
|
330
|
+
return Observation.make({
|
|
331
|
+
stream,
|
|
332
|
+
lifetime: new ObservationLifetime(() => observer.close()),
|
|
333
|
+
})
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
return Context.make(LiveTextHub, { open }).pipe(Context.add(Publisher, { offerUnsafe }))
|
|
337
|
+
}),
|
|
338
|
+
)
|
|
339
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { type ThreadId } from '@systemfsoftware/agent/identifiers'
|
|
2
|
+
import {
|
|
3
|
+
MessageDeliveryDriver,
|
|
4
|
+
MessageDeliveryError,
|
|
5
|
+
MessageDeliveryStore,
|
|
6
|
+
} from '@systemfsoftware/agent/message-delivery'
|
|
7
|
+
import { WakeScheduler } from '@systemfsoftware/agent/wake-scheduler'
|
|
8
|
+
import * as Clock from 'effect/Clock'
|
|
9
|
+
import * as Context from 'effect/Context'
|
|
10
|
+
import * as Duration from 'effect/Duration'
|
|
11
|
+
import * as Effect from 'effect/Effect'
|
|
12
|
+
import * as Exit from 'effect/Exit'
|
|
13
|
+
import * as Layer from 'effect/Layer'
|
|
14
|
+
import * as Option from 'effect/Option'
|
|
15
|
+
|
|
16
|
+
import { DurableAlarmError, ThreadMessageDelivery, ThreadMutationGate } from '../Alarm'
|
|
17
|
+
import { ThreadObjectPlacement } from '../CloudflareBindings'
|
|
18
|
+
import * as DueQueue from './due-queue'
|
|
19
|
+
|
|
20
|
+
/** Every write prearms its owner; the delivery due index owns its recovery deadline. */
|
|
21
|
+
export const guardedMessageDeliveryStoreLayer = Layer.effect(
|
|
22
|
+
MessageDeliveryStore,
|
|
23
|
+
Effect.gen(function*() {
|
|
24
|
+
const store = yield* MessageDeliveryStore
|
|
25
|
+
const mutations = yield* ThreadMutationGate
|
|
26
|
+
const wakes = yield* WakeScheduler
|
|
27
|
+
const { ownsThread } = yield* ThreadObjectPlacement
|
|
28
|
+
|
|
29
|
+
const local = <A, E>(
|
|
30
|
+
owner: ThreadId | undefined,
|
|
31
|
+
body: Effect.Effect<A, E>,
|
|
32
|
+
): Effect.Effect<A, E | MessageDeliveryError> =>
|
|
33
|
+
owner === undefined || ownsThread(owner)
|
|
34
|
+
? body
|
|
35
|
+
: Effect.fail(
|
|
36
|
+
MessageDeliveryError.make({ reason: 'validation', operation: 'message owner' }),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
const mutate = <A, E>(body: Effect.Effect<A, E>) =>
|
|
40
|
+
mutations
|
|
41
|
+
.withMutation(body, {
|
|
42
|
+
invalidatesRecovery: false,
|
|
43
|
+
lanes: [
|
|
44
|
+
DueQueue.Messages,
|
|
45
|
+
...(store.lifecyclePublications === undefined ? [] : [DueQueue.Lifecycle]),
|
|
46
|
+
],
|
|
47
|
+
})
|
|
48
|
+
.pipe(
|
|
49
|
+
Effect.catchTag('DurableAlarmError', (cause) =>
|
|
50
|
+
MessageDeliveryError.make({
|
|
51
|
+
reason: 'storage',
|
|
52
|
+
operation: 'prearm message delivery',
|
|
53
|
+
cause,
|
|
54
|
+
})),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return MessageDeliveryStore.of({
|
|
58
|
+
limits: store.limits,
|
|
59
|
+
maxStoredValueBytes: store.maxStoredValueBytes,
|
|
60
|
+
insert: (record) =>
|
|
61
|
+
local(
|
|
62
|
+
record.key.ownerThreadId,
|
|
63
|
+
mutate(store.insert(record)).pipe(
|
|
64
|
+
Effect.tap(() => wakes.notify(record.key.ownerThreadId)),
|
|
65
|
+
),
|
|
66
|
+
),
|
|
67
|
+
get: (key) => local(key.ownerThreadId, store.get(key)),
|
|
68
|
+
list: (request) => local(request.ownerThreadId, store.list(request)),
|
|
69
|
+
change: (key, change) => local(key.ownerThreadId, mutate(store.change(key, change))),
|
|
70
|
+
// Only the trusted physical-owner selection omits an owner. All returned keys still
|
|
71
|
+
// pass placement validation before the driver may dispatch any of the wave.
|
|
72
|
+
due: (nowMillis, limit, owner) =>
|
|
73
|
+
local(owner, store.due(nowMillis, limit, owner)).pipe(
|
|
74
|
+
Effect.filterOrFail(
|
|
75
|
+
(keys) => keys.every((key) => ownsThread(key.ownerThreadId)),
|
|
76
|
+
() => MessageDeliveryError.make({ reason: 'validation', operation: 'message owner' }),
|
|
77
|
+
),
|
|
78
|
+
),
|
|
79
|
+
nextDeadline: (owner) => local(owner, store.nextDeadline(owner)),
|
|
80
|
+
})
|
|
81
|
+
}),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
/** Build the driver in the Object's Scope only when retained delivery work is due. */
|
|
85
|
+
export const lazyThreadMessageDeliveryLayer = <E, R>(
|
|
86
|
+
driver: Layer.Layer<MessageDeliveryDriver, E, R>,
|
|
87
|
+
) =>
|
|
88
|
+
Layer.fromBuildMemo((memoMap, scope) =>
|
|
89
|
+
Effect.gen(function*() {
|
|
90
|
+
const context = yield* Effect.context<R>()
|
|
91
|
+
const store = yield* MessageDeliveryStore
|
|
92
|
+
|
|
93
|
+
// Failed builds release their Layer scopes; let a later wave build again.
|
|
94
|
+
const service = yield* Effect.cachedWithTTL(
|
|
95
|
+
Layer.buildWithMemoMap(driver, memoMap, scope).pipe(
|
|
96
|
+
Effect.provide(context),
|
|
97
|
+
Effect.map(Context.get(MessageDeliveryDriver)),
|
|
98
|
+
Effect.mapError((cause) =>
|
|
99
|
+
DurableAlarmError.make({
|
|
100
|
+
operation: 'prepare message delivery',
|
|
101
|
+
message: 'Durable message recovery remains pending',
|
|
102
|
+
cause,
|
|
103
|
+
})
|
|
104
|
+
),
|
|
105
|
+
),
|
|
106
|
+
(exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
const failure = (operation: string) => () =>
|
|
110
|
+
DurableAlarmError.make({
|
|
111
|
+
operation,
|
|
112
|
+
message: 'Durable message recovery remains pending',
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
const prepare = Effect.gen(function*() {
|
|
116
|
+
const deadline = yield* store.nextDeadline()
|
|
117
|
+
|
|
118
|
+
if (deadline === null || deadline > (yield* Clock.currentTimeMillis)) {
|
|
119
|
+
return { timeoutMillis: 1, run: Effect.succeed(Option.fromNullishOr(deadline)) }
|
|
120
|
+
}
|
|
121
|
+
// The assembled driver has four permits: a wave is one parallel attempt window.
|
|
122
|
+
const keys = yield* store.due(yield* Clock.currentTimeMillis, 4)
|
|
123
|
+
const records = yield* Effect.forEach(keys, (key) => store.get(key))
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
timeoutMillis: Math.max(
|
|
127
|
+
1,
|
|
128
|
+
...records.map((record) => record?.policy.attemptTimeoutMillis ?? 1),
|
|
129
|
+
),
|
|
130
|
+
run: Effect.flatMap(service, (driver) =>
|
|
131
|
+
Effect.forEach(keys, (key) => driver.process(key), {
|
|
132
|
+
concurrency: 4,
|
|
133
|
+
discard: true,
|
|
134
|
+
})).pipe(
|
|
135
|
+
Effect.andThen(store.nextDeadline()),
|
|
136
|
+
Effect.map(Option.fromNullishOr),
|
|
137
|
+
Effect.mapError(failure('dispatch message delivery')),
|
|
138
|
+
),
|
|
139
|
+
}
|
|
140
|
+
}).pipe(Effect.mapError(failure('prepare message delivery')))
|
|
141
|
+
|
|
142
|
+
return Context.make(ThreadMessageDelivery, { prepare })
|
|
143
|
+
})
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
/** Message progress shares the native alarm slot without blocking source runtime work. */
|
|
147
|
+
export const threadMessageDeliveryLayer = lazyThreadMessageDeliveryLayer(
|
|
148
|
+
Layer.effect(MessageDeliveryDriver, MessageDeliveryDriver),
|
|
149
|
+
)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Puppeteer sends a page function's source to the browser. Bundlers that keep function names,
|
|
3
|
+
* including Wrangler by default, insert `__name(...)` calls into that source, and the page has no
|
|
4
|
+
* such helper. The returned function's source declares a local no-op `__name` first.
|
|
5
|
+
*/
|
|
6
|
+
export const pageFunction = <A extends ReadonlyArray<unknown>, R>(
|
|
7
|
+
fn: (...args: A) => R,
|
|
8
|
+
): (...args: A) => R =>
|
|
9
|
+
Object.assign((...args: A) => fn(...args), {
|
|
10
|
+
toString: () =>
|
|
11
|
+
`(...args) => { const __name = (target) => target; return (${Function.prototype.toString.call(fn)})(...args); }`,
|
|
12
|
+
})
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type DurableSubmitAgent } from '@systemfsoftware/agent/durable-agent-runtime'
|
|
2
|
+
import { type AgentId } from '@systemfsoftware/agent/identifiers'
|
|
3
|
+
import {
|
|
4
|
+
PreparedInputAdmission,
|
|
5
|
+
PreparedInputRefused,
|
|
6
|
+
PreparedInputRetryable,
|
|
7
|
+
} from '@systemfsoftware/agent/prepared-input-admission'
|
|
8
|
+
import { PersistedJson } from '@systemfsoftware/agent/records'
|
|
9
|
+
import { ScheduleStorageError } from '@systemfsoftware/agent/schedule'
|
|
10
|
+
import * as Effect from 'effect/Effect'
|
|
11
|
+
import * as Layer from 'effect/Layer'
|
|
12
|
+
|
|
13
|
+
import { CloudflareThreadClient, type ThreadClientError } from '../CloudflareThreadClient'
|
|
14
|
+
|
|
15
|
+
const passthroughAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({
|
|
16
|
+
definition: { id: agentId, input: PersistedJson },
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
/** Ordinary prepared admission through one freshly addressed Thread Object call. */
|
|
20
|
+
export const cloudflarePreparedInputAdmissionLayer: Layer.Layer<
|
|
21
|
+
PreparedInputAdmission,
|
|
22
|
+
never,
|
|
23
|
+
CloudflareThreadClient
|
|
24
|
+
> = Layer.effect(
|
|
25
|
+
PreparedInputAdmission,
|
|
26
|
+
Effect.gen(function*() {
|
|
27
|
+
const client = yield* CloudflareThreadClient
|
|
28
|
+
|
|
29
|
+
return PreparedInputAdmission.of({
|
|
30
|
+
submissionStatus: (receipt) =>
|
|
31
|
+
client
|
|
32
|
+
.submissionStatus(receipt)
|
|
33
|
+
.pipe(Effect.mapError(() => PreparedInputRetryable.make({ reason: 'storage' }))),
|
|
34
|
+
submit: (envelope) =>
|
|
35
|
+
client
|
|
36
|
+
.submit(passthroughAgent(envelope.agentId), envelope.input, {
|
|
37
|
+
threadId: envelope.threadId,
|
|
38
|
+
principal: envelope.deliveryPrincipal,
|
|
39
|
+
idempotencyKey: envelope.admissionKey,
|
|
40
|
+
...(envelope.admissionGroup === undefined
|
|
41
|
+
? {}
|
|
42
|
+
: { admissionGroup: envelope.admissionGroup }),
|
|
43
|
+
...(envelope.admissionFence === undefined
|
|
44
|
+
? {}
|
|
45
|
+
: { admissionFence: envelope.admissionFence }),
|
|
46
|
+
...(envelope.workerAdmission === undefined
|
|
47
|
+
? {}
|
|
48
|
+
: { workerAdmission: envelope.workerAdmission }),
|
|
49
|
+
...(envelope.messageAdmission === undefined
|
|
50
|
+
? {}
|
|
51
|
+
: { messageAdmission: envelope.messageAdmission }),
|
|
52
|
+
definitions: envelope.definitions,
|
|
53
|
+
})
|
|
54
|
+
.pipe(
|
|
55
|
+
Effect.catchTags({
|
|
56
|
+
AdmissionConflict: () =>
|
|
57
|
+
ScheduleStorageError.make({ operation: 'prepared admission', reason: 'corrupt' }),
|
|
58
|
+
AdmissionLimitExceeded: () => PreparedInputRetryable.make({ reason: 'capacity' }),
|
|
59
|
+
ThreadClientError: (error: ThreadClientError) =>
|
|
60
|
+
PreparedInputRetryable.make({
|
|
61
|
+
reason: error.overloaded === true ? 'capacity' : 'transport',
|
|
62
|
+
}),
|
|
63
|
+
HostProtocolError: () => PreparedInputRetryable.make({ reason: 'ambiguous' }),
|
|
64
|
+
AdmissionPolicyError: (error) =>
|
|
65
|
+
error.reason === 'refused'
|
|
66
|
+
? PreparedInputRefused.make({ code: error.code })
|
|
67
|
+
: PreparedInputRetryable.make({
|
|
68
|
+
reason: error.reason === 'occupied' ? 'capacity' : 'storage',
|
|
69
|
+
}),
|
|
70
|
+
LedgerError: () => PreparedInputRetryable.make({ reason: 'storage' }),
|
|
71
|
+
ThreadStoreError: () => PreparedInputRetryable.make({ reason: 'storage' }),
|
|
72
|
+
DurableAlarmError: () => PreparedInputRetryable.make({ reason: 'storage' }),
|
|
73
|
+
AgentInputError: () => ScheduleStorageError.make({ operation: 'prepared admission', reason: 'corrupt' }),
|
|
74
|
+
DigestError: () => ScheduleStorageError.make({ operation: 'prepared admission', reason: 'corrupt' }),
|
|
75
|
+
ThreadNotMaterialized: () => PreparedInputRetryable.make({ reason: 'storage' }),
|
|
76
|
+
AppendConflict: () => PreparedInputRetryable.make({ reason: 'ambiguous' }),
|
|
77
|
+
OwnershipLost: () => PreparedInputRetryable.make({ reason: 'ambiguous' }),
|
|
78
|
+
DurableRuntimeFailpointError: () => PreparedInputRetryable.make({ reason: 'ambiguous' }),
|
|
79
|
+
}),
|
|
80
|
+
),
|
|
81
|
+
})
|
|
82
|
+
}),
|
|
83
|
+
)
|