| 227 | } |
| 228 | |
| 229 | export function createSetupContext( |
| 230 | config: SetupContextConfig |
| 231 | ): SetupContextResult { |
| 232 | const { |
| 233 | entityUrl, |
| 234 | entityType, |
| 235 | args, |
| 236 | db, |
| 237 | effectScope, |
| 238 | customStateNames = [], |
| 239 | wakeSession = createWakeSession(db), |
| 240 | definition, |
| 241 | wiring, |
| 242 | executeSend: executeSendFn, |
| 243 | } = config |
| 244 | let inSetup = true |
| 245 | |
| 246 | const dbActions = |
| 247 | ( |
| 248 | db as EntityStreamDBWithActions & { |
| 249 | actions?: Record<string, (...args: Array<unknown>) => unknown> |
| 250 | } |
| 251 | ).actions ?? {} |
| 252 | |
| 253 | // Build ctx.state proxy — routes CRUD through auto-generated actions, |
| 254 | // reads through the underlying TanStack DB collection. |
| 255 | const stateProxy: StateProxy = {} |
| 256 | for (const name of customStateNames) { |
| 257 | const insertAction = dbActions[`${name}_insert`] |
| 258 | const updateAction = dbActions[`${name}_update`] |
| 259 | const deleteAction = dbActions[`${name}_delete`] |
| 260 | const collection = db.collections[name] |
| 261 | |
| 262 | const proxy: StateCollectionProxy = { |
| 263 | insert: (row: Record<string, unknown>) => { |
| 264 | if (!insertAction) { |
| 265 | throw new Error( |
| 266 | `[agent-runtime] No insert action for collection "${name}"` |
| 267 | ) |
| 268 | } |
| 269 | return insertAction({ row }) |
| 270 | }, |
| 271 | update: ( |
| 272 | key: string, |
| 273 | updater: (draft: Record<string, unknown>) => void |
| 274 | ) => { |
| 275 | if (!updateAction) { |
| 276 | throw new Error( |
| 277 | `[agent-runtime] No update action for collection "${name}"` |
| 278 | ) |
| 279 | } |
| 280 | return updateAction({ key, updater }) |
| 281 | }, |
| 282 | delete: (key: string) => { |
| 283 | if (!deleteAction) { |
| 284 | throw new Error( |
| 285 | `[agent-runtime] No delete action for collection "${name}"` |
| 286 | ) |