-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdurable-plan-flow.ts
More file actions
253 lines (229 loc) · 9.64 KB
/
Copy pathdurable-plan-flow.ts
File metadata and controls
253 lines (229 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import { useCallback, useEffect, useRef, useState } from 'react'
import type { ChatPlan } from '../plans/index'
/** Represent durable plan decisions as either approved or rejected */
export type DurablePlanDecision = 'approved' | 'rejected'
/** Stable authority receipt for the follow-up turn dispatched by a plan
* decision. Consumers must make `attachFollowUp` idempotent by `receiptId`;
* reload and retry deliberately invoke it again. */
export interface DurablePlanFollowUpReceipt {
receiptId: string
planId: string
revision: number
turnId: string
state: string
}
/** Describe the result of a durable plan decision including plan details and pending statuses */
export interface DurablePlanDecisionResult {
plan: ChatPlan
followUp?: DurablePlanFollowUpReceipt
idempotent: boolean
projectionPending?: boolean
effectPending?: boolean
}
/** Define input parameters for making a durable plan decision including optional feedback */
export interface DurablePlanDecisionInput {
planId: string
revision: number
decision: DurablePlanDecision
feedback?: string
}
/** Define input parameters for retrieving the current durable plan including optional revision number */
export interface DurablePlanCurrentInput {
planId: string
revision?: number
}
/** Define methods to obtain and decide durable plan decisions asynchronously */
export interface DurablePlanDecisionClient {
current: (input: DurablePlanCurrentInput) => Promise<DurablePlanDecisionResult>
decide: (input: DurablePlanDecisionInput) => Promise<DurablePlanDecisionResult>
}
/** Represent errors from DurablePlanClient operations including status, code, and current plan details */
export class DurablePlanClientError extends Error {
constructor(
message: string,
readonly status: number,
readonly code?: string,
readonly currentPlan?: ChatPlan,
) {
super(message)
this.name = 'DurablePlanClientError'
}
}
/** Define configuration options for creating a durable plan decision client */
export interface DurablePlanDecisionClientOptions {
url: string | ((input: DurablePlanCurrentInput | DurablePlanDecisionInput) => string)
body?: Record<string, unknown> | ((input: DurablePlanDecisionInput) => Record<string, unknown>)
fetchImpl?: typeof fetch
}
function recordOf(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: null
}
function readPlan(value: unknown): ChatPlan | null {
const plan = recordOf(value)
if (!plan) return null
const planId = typeof plan.planId === 'string' ? plan.planId : typeof plan.id === 'string' ? plan.id : null
if (!planId || typeof plan.revision !== 'number' || typeof plan.body !== 'string' ||
typeof plan.submittedAt !== 'string' || typeof plan.status !== 'string') return null
return { ...plan, planId } as ChatPlan
}
function receiptIdentity(plan: ChatPlan, followUp: Record<string, unknown>): string {
if (typeof followUp.receiptId === 'string' && followUp.receiptId) return followUp.receiptId
const turnId = typeof followUp.turnId === 'string' ? followUp.turnId : ''
return `${plan.planId}:${plan.revision}:${turnId}`
}
function parseDecisionResult(value: unknown): DurablePlanDecisionResult | null {
const body = recordOf(value)
const plan = readPlan(body?.plan)
if (!body || !plan) return null
const rawFollowUp = recordOf(body.followUp) ?? recordOf(body.receipt)
const followUp = rawFollowUp && typeof rawFollowUp.turnId === 'string'
? {
receiptId: receiptIdentity(plan, rawFollowUp),
planId: plan.planId,
revision: plan.revision,
turnId: rawFollowUp.turnId,
state: typeof rawFollowUp.state === 'string' ? rawFollowUp.state : 'unknown',
}
: undefined
return {
plan,
...(followUp ? { followUp } : {}),
idempotent: body.idempotent === true || body.replayed === true,
...(body.projectionPending === true ? { projectionPending: true } : {}),
...(body.effectPending === true ? { effectPending: true } : {}),
}
}
async function responseBody(response: Response): Promise<Record<string, unknown>> {
return recordOf(await response.json().catch(() => null)) ?? {}
}
/** Browser client for the shared durable-plan route. The route URL and all
* product routing fields are injected; workspace/session identity is still
* resolved and authorized on the server. */
export function createDurablePlanDecisionClient(
options: DurablePlanDecisionClientOptions,
): DurablePlanDecisionClient {
const fetchImpl = options.fetchImpl ?? fetch
const urlFor = (input: DurablePlanCurrentInput | DurablePlanDecisionInput) =>
typeof options.url === 'function' ? options.url(input) : options.url
const read = async (response: Response): Promise<DurablePlanDecisionResult> => {
const body = await responseBody(response)
const result = parseDecisionResult(body)
if (response.ok && result) return result
const currentPlan = readPlan(body.plan) ?? undefined
const message = typeof body.error === 'string'
? body.error
: typeof body.message === 'string' ? body.message : `Plan request failed (${response.status})`
throw new DurablePlanClientError(
message,
response.status,
typeof body.code === 'string' ? body.code : undefined,
currentPlan,
)
}
return {
async current(input) {
const rawUrl = urlFor(input)
const url = new URL(rawUrl, globalThis.location?.origin ?? 'http://localhost')
url.searchParams.set('planId', input.planId)
if (input.revision !== undefined) url.searchParams.set('revision', String(input.revision))
const target = /^https?:/.test(rawUrl)
? url.toString()
: `${url.pathname}${url.search}`
return read(await fetchImpl(target, { method: 'GET' }))
},
async decide(input) {
const extra = typeof options.body === 'function' ? options.body(input) : options.body ?? {}
return read(await fetchImpl(urlFor(input), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...extra, ...input }),
}))
},
}
}
/** Define options to configure durable plan flow with plan, client, and optional callbacks */
export interface UseDurablePlanFlowOptions {
plan: ChatPlan
client: DurablePlanDecisionClient
/** Must be idempotent by receipt.receiptId. */
attachFollowUp?: (receipt: DurablePlanFollowUpReceipt) => Promise<void> | void
onUpdated?: (plan: ChatPlan) => void
}
/** Define the result and actions for managing a durable plan flow including decisions, restoration, and error handling */
export interface UseDurablePlanFlowResult {
plan: ChatPlan
deciding: DurablePlanDecision | null
restoring: boolean
error: string | null
decide: (decision: DurablePlanDecision, feedback?: string) => Promise<DurablePlanDecisionResult | null>
restore: () => Promise<DurablePlanDecisionResult | null>
clearError: () => void
}
/** Shared plan decision controller. It coalesces only concurrent attachment
* attempts; a later retry/restore calls the consumer's idempotent transport
* again so a lost response cannot strand an already-dispatched follow-up. */
export function useDurablePlanFlow(options: UseDurablePlanFlowOptions): UseDurablePlanFlowResult {
const [plan, setPlan] = useState(options.plan)
const [deciding, setDeciding] = useState<DurablePlanDecision | null>(null)
const [restoring, setRestoring] = useState(false)
const [error, setError] = useState<string | null>(null)
const attachments = useRef(new Map<string, Promise<void>>())
const decisionInFlight = useRef(false)
useEffect(() => setPlan(options.plan), [options.plan])
const apply = useCallback(async (result: DurablePlanDecisionResult) => {
setPlan(result.plan)
options.onUpdated?.(result.plan)
const receipt = result.followUp
if (!receipt || !options.attachFollowUp) return
let pending = attachments.current.get(receipt.receiptId)
if (!pending) {
pending = Promise.resolve(options.attachFollowUp(receipt))
attachments.current.set(receipt.receiptId, pending)
void pending.finally(() => attachments.current.delete(receipt.receiptId))
}
await pending
}, [options.attachFollowUp, options.onUpdated])
const decide = useCallback(async (decision: DurablePlanDecision, feedback?: string) => {
if (decisionInFlight.current) return null
decisionInFlight.current = true
setDeciding(decision)
setError(null)
try {
const result = await options.client.decide({
planId: plan.planId,
revision: plan.revision,
decision,
...(feedback?.trim() ? { feedback: feedback.trim() } : {}),
})
await apply(result)
return result
} catch (cause) {
if (cause instanceof DurablePlanClientError && cause.currentPlan) {
setPlan(cause.currentPlan)
options.onUpdated?.(cause.currentPlan)
}
setError(cause instanceof Error ? cause.message : 'Could not decide the plan.')
return null
} finally {
decisionInFlight.current = false
setDeciding(null)
}
}, [apply, options.client, options.onUpdated, plan.planId, plan.revision])
const restore = useCallback(async () => {
setRestoring(true)
setError(null)
try {
const result = await options.client.current({ planId: plan.planId, revision: plan.revision })
await apply(result)
return result
} catch (cause) {
setError(cause instanceof Error ? cause.message : 'Could not restore the plan.')
return null
} finally {
setRestoring(false)
}
}, [apply, options.client, plan.planId, plan.revision])
return { plan, deciding, restoring, error, decide, restore, clearError: () => setError(null) }
}