rivetkit 2.0.7 → 2.0.9
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/dist/tsup/{chunk-OSK2VSJF.cjs → chunk-2MJYYF2Q.cjs} +12 -12
- package/dist/tsup/{chunk-OSK2VSJF.cjs.map → chunk-2MJYYF2Q.cjs.map} +1 -1
- package/dist/tsup/{chunk-NUA6LOOJ.cjs → chunk-4PSLOAXR.cjs} +216 -204
- package/dist/tsup/chunk-4PSLOAXR.cjs.map +1 -0
- package/dist/tsup/{chunk-F7YL5G7Q.cjs → chunk-4YV6RDZL.cjs} +255 -229
- package/dist/tsup/chunk-4YV6RDZL.cjs.map +1 -0
- package/dist/tsup/{chunk-3ALZ7EGX.cjs → chunk-7OMMIAWP.cjs} +11 -11
- package/dist/tsup/{chunk-3ALZ7EGX.cjs.map → chunk-7OMMIAWP.cjs.map} +1 -1
- package/dist/tsup/{chunk-GWJTWY3G.cjs → chunk-A44TWAS5.cjs} +6 -6
- package/dist/tsup/{chunk-GWJTWY3G.cjs.map → chunk-A44TWAS5.cjs.map} +1 -1
- package/dist/tsup/{chunk-B6N6VM37.js → chunk-APHV6WXU.js} +2 -2
- package/dist/tsup/{chunk-ETDWYT2P.cjs → chunk-DL7TPF63.cjs} +7 -7
- package/dist/tsup/{chunk-ETDWYT2P.cjs.map → chunk-DL7TPF63.cjs.map} +1 -1
- package/dist/tsup/{chunk-YL4VZMMT.js → chunk-DLPIL3VC.js} +2 -2
- package/dist/tsup/{chunk-VAF63BEI.cjs → chunk-DZZQG7VH.cjs} +3 -3
- package/dist/tsup/{chunk-VAF63BEI.cjs.map → chunk-DZZQG7VH.cjs.map} +1 -1
- package/dist/tsup/{chunk-RLBM6D4L.js → chunk-E63WU5PL.js} +3 -3
- package/dist/tsup/chunk-E63WU5PL.js.map +1 -0
- package/dist/tsup/{chunk-DIHKN7NM.js → chunk-F2YZNUPU.js} +3 -3
- package/dist/tsup/{chunk-KHRZPP5T.js → chunk-FZP2IBIX.js} +94 -68
- package/dist/tsup/chunk-FZP2IBIX.js.map +1 -0
- package/dist/tsup/{chunk-NII4KKHD.js → chunk-KHZ2QSQ4.js} +28 -16
- package/dist/tsup/chunk-KHZ2QSQ4.js.map +1 -0
- package/dist/tsup/{chunk-4EXJ4ITR.cjs → chunk-QGRYH6TU.cjs} +3 -3
- package/dist/tsup/{chunk-4EXJ4ITR.cjs.map → chunk-QGRYH6TU.cjs.map} +1 -1
- package/dist/tsup/{chunk-NRELKXIX.js → chunk-R7OP5N25.js} +56 -46
- package/dist/tsup/chunk-R7OP5N25.js.map +1 -0
- package/dist/tsup/{chunk-NDCVQZBS.cjs → chunk-SDXTJDDR.cjs} +62 -52
- package/dist/tsup/chunk-SDXTJDDR.cjs.map +1 -0
- package/dist/tsup/{chunk-7OOBMCQI.cjs → chunk-SOC4HWCG.cjs} +23 -22
- package/dist/tsup/chunk-SOC4HWCG.cjs.map +1 -0
- package/dist/tsup/{chunk-LXAVET4A.cjs → chunk-U2IXX6DY.cjs} +3 -3
- package/dist/tsup/{chunk-LXAVET4A.cjs.map → chunk-U2IXX6DY.cjs.map} +1 -1
- package/dist/tsup/{chunk-2NL3KGJ7.js → chunk-VVCL5DXN.js} +5 -4
- package/dist/tsup/chunk-VVCL5DXN.js.map +1 -0
- package/dist/tsup/{chunk-54MAHBLL.js → chunk-WBSPHV5V.js} +2 -2
- package/dist/tsup/{chunk-WAT5AE7S.js → chunk-WRSWUDFA.js} +5 -5
- package/dist/tsup/{chunk-PD6HCAJE.js → chunk-YR2VY4XS.js} +2 -2
- package/dist/tsup/client/mod.cjs +9 -9
- package/dist/tsup/client/mod.d.cts +2 -2
- package/dist/tsup/client/mod.d.ts +2 -2
- package/dist/tsup/client/mod.js +8 -8
- package/dist/tsup/common/log.cjs +3 -3
- package/dist/tsup/common/log.js +2 -2
- package/dist/tsup/common/websocket.cjs +4 -4
- package/dist/tsup/common/websocket.js +3 -3
- package/dist/tsup/{conn-DCSQgIlw.d.ts → conn-Bt8rkUzm.d.ts} +19 -1
- package/dist/tsup/{conn-DdzHTm2E.d.cts → conn-CEh3WKbA.d.cts} +19 -1
- package/dist/tsup/driver-helpers/mod.cjs +7 -5
- package/dist/tsup/driver-helpers/mod.cjs.map +1 -1
- package/dist/tsup/driver-helpers/mod.d.cts +4 -2
- package/dist/tsup/driver-helpers/mod.d.ts +4 -2
- package/dist/tsup/driver-helpers/mod.js +7 -5
- package/dist/tsup/driver-test-suite/mod.cjs +103 -113
- package/dist/tsup/driver-test-suite/mod.cjs.map +1 -1
- package/dist/tsup/driver-test-suite/mod.d.cts +3 -1
- package/dist/tsup/driver-test-suite/mod.d.ts +3 -1
- package/dist/tsup/driver-test-suite/mod.js +45 -55
- package/dist/tsup/driver-test-suite/mod.js.map +1 -1
- package/dist/tsup/inspector/mod.cjs +6 -6
- package/dist/tsup/inspector/mod.d.cts +2 -2
- package/dist/tsup/inspector/mod.d.ts +2 -2
- package/dist/tsup/inspector/mod.js +5 -5
- package/dist/tsup/mod.cjs +10 -10
- package/dist/tsup/mod.d.cts +5 -5
- package/dist/tsup/mod.d.ts +5 -5
- package/dist/tsup/mod.js +9 -9
- package/dist/tsup/test/mod.cjs +11 -11
- package/dist/tsup/test/mod.d.cts +1 -1
- package/dist/tsup/test/mod.d.ts +1 -1
- package/dist/tsup/test/mod.js +10 -10
- package/dist/tsup/utils.cjs +2 -2
- package/dist/tsup/utils.js +1 -1
- package/package.json +2 -2
- package/src/actor/instance.ts +20 -7
- package/src/actor/router-endpoints.ts +2 -1
- package/src/actor/router.ts +27 -24
- package/src/client/actor-conn.ts +5 -1
- package/src/client/config.ts +2 -0
- package/src/driver-helpers/mod.ts +1 -0
- package/src/driver-test-suite/mod.ts +11 -2
- package/src/driver-test-suite/tests/actor-schedule.ts +14 -37
- package/src/driver-test-suite/tests/actor-sleep.ts +18 -18
- package/src/drivers/engine/actor-driver.ts +39 -10
- package/src/drivers/file-system/manager.ts +5 -1
- package/src/manager/driver.ts +1 -1
- package/src/manager/router.ts +49 -41
- package/src/registry/mod.ts +11 -2
- package/src/remote-manager-driver/mod.ts +3 -2
- package/src/serde.ts +15 -0
- package/dist/tsup/chunk-2NL3KGJ7.js.map +0 -1
- package/dist/tsup/chunk-7OOBMCQI.cjs.map +0 -1
- package/dist/tsup/chunk-F7YL5G7Q.cjs.map +0 -1
- package/dist/tsup/chunk-KHRZPP5T.js.map +0 -1
- package/dist/tsup/chunk-NDCVQZBS.cjs.map +0 -1
- package/dist/tsup/chunk-NII4KKHD.js.map +0 -1
- package/dist/tsup/chunk-NRELKXIX.js.map +0 -1
- package/dist/tsup/chunk-NUA6LOOJ.cjs.map +0 -1
- package/dist/tsup/chunk-RLBM6D4L.js.map +0 -1
- /package/dist/tsup/{chunk-B6N6VM37.js.map → chunk-APHV6WXU.js.map} +0 -0
- /package/dist/tsup/{chunk-YL4VZMMT.js.map → chunk-DLPIL3VC.js.map} +0 -0
- /package/dist/tsup/{chunk-DIHKN7NM.js.map → chunk-F2YZNUPU.js.map} +0 -0
- /package/dist/tsup/{chunk-54MAHBLL.js.map → chunk-WBSPHV5V.js.map} +0 -0
- /package/dist/tsup/{chunk-WAT5AE7S.js.map → chunk-WRSWUDFA.js.map} +0 -0
- /package/dist/tsup/{chunk-PD6HCAJE.js.map → chunk-YR2VY4XS.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/actor/config.ts","../../src/actor/router.ts","../../src/actor/router-endpoints.ts","../../src/manager/log.ts","../../src/manager/hono-websocket-adapter.ts","../../src/common/router.ts","../../src/actor/mod.ts","../../src/common/inline-websocket-adapter2.ts","../../src/drivers/engine/actor-driver.ts","../../src/drivers/engine/kv.ts","../../src/drivers/engine/log.ts","../../src/drivers/engine/config.ts","../../src/drivers/engine/mod.ts","../../src/drivers/file-system/actor.ts","../../src/drivers/file-system/global-state.ts","../schemas/file-system-driver/v1.ts","../../src/schemas/file-system-driver/versioned.ts","../../src/drivers/file-system/log.ts","../../src/drivers/file-system/utils.ts","../../src/drivers/file-system/manager.ts","../../src/inspector/manager.ts","../../src/drivers/file-system/mod.ts","../../src/drivers/default.ts","../../src/manager/router.ts","../../src/manager-api/actors.ts","../../src/manager-api/common.ts","../../src/manager/gateway.ts","../../src/registry/config.ts","../../src/registry/log.ts","../../src/registry/serve.ts","../../src/registry/mod.ts"],"sourcesContent":["import { z } from \"zod\";\nimport type { UniversalWebSocket } from \"@/common/websocket-interface\";\nimport type { ActionContext } from \"./action\";\nimport type { Conn } from \"./conn\";\nimport type { ActorContext } from \"./context\";\nimport type { AnyDatabaseProvider } from \"./database\";\n\nexport type InitContext = ActorContext<\n\tundefined,\n\tundefined,\n\tundefined,\n\tundefined,\n\tundefined,\n\tundefined\n>;\n\nexport interface ActorTypes<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase extends AnyDatabaseProvider,\n> {\n\tstate?: TState;\n\tconnParams?: TConnParams;\n\tconnState?: TConnState;\n\tvars?: TVars;\n\tinput?: TInput;\n\tdatabase?: TDatabase;\n}\n\n// This schema is used to validate the input at runtime. The generic types are defined below in `ActorConfig`.\n//\n// We don't use Zod generics with `z.custom` because:\n// (a) there seems to be a weird bug in either Zod, tsup, or TSC that causese external packages to have different types from `z.infer` than from within the same package and\n// (b) it makes the type definitions incredibly difficult to read as opposed to vanilla TypeScript.\nexport const ActorConfigSchema = z\n\t.object({\n\t\tonCreate: z.function().optional(),\n\t\tonStart: z.function().optional(),\n\t\tonStop: z.function().optional(),\n\t\tonStateChange: z.function().optional(),\n\t\tonBeforeConnect: z.function().optional(),\n\t\tonConnect: z.function().optional(),\n\t\tonDisconnect: z.function().optional(),\n\t\tonBeforeActionResponse: z.function().optional(),\n\t\tonFetch: z.function().optional(),\n\t\tonWebSocket: z.function().optional(),\n\t\tactions: z.record(z.function()).default({}),\n\t\tstate: z.any().optional(),\n\t\tcreateState: z.function().optional(),\n\t\tconnState: z.any().optional(),\n\t\tcreateConnState: z.function().optional(),\n\t\tvars: z.any().optional(),\n\t\tdb: z.any().optional(),\n\t\tcreateVars: z.function().optional(),\n\t\toptions: z\n\t\t\t.object({\n\t\t\t\tcreateVarsTimeout: z.number().positive().default(5000),\n\t\t\t\tcreateConnStateTimeout: z.number().positive().default(5000),\n\t\t\t\tonConnectTimeout: z.number().positive().default(5000),\n\t\t\t\t// This must be less than ACTOR_STOP_THRESHOLD_MS\n\t\t\t\tonStopTimeout: z.number().positive().default(5000),\n\t\t\t\tstateSaveInterval: z.number().positive().default(10_000),\n\t\t\t\tactionTimeout: z.number().positive().default(60_000),\n\t\t\t\t// Max time to wait for waitUntil background promises during shutdown\n\t\t\t\twaitUntilTimeout: z.number().positive().default(15_000),\n\t\t\t\tconnectionLivenessTimeout: z.number().positive().default(2500),\n\t\t\t\tconnectionLivenessInterval: z.number().positive().default(5000),\n\t\t\t\tnoSleep: z.boolean().default(false),\n\t\t\t\tsleepTimeout: z.number().positive().default(30_000),\n\t\t\t})\n\t\t\t.strict()\n\t\t\t.default({}),\n\t})\n\t.strict()\n\t.refine(\n\t\t(data) => !(data.state !== undefined && data.createState !== undefined),\n\t\t{\n\t\t\tmessage: \"Cannot define both 'state' and 'createState'\",\n\t\t\tpath: [\"state\"],\n\t\t},\n\t)\n\t.refine(\n\t\t(data) =>\n\t\t\t!(data.connState !== undefined && data.createConnState !== undefined),\n\t\t{\n\t\t\tmessage: \"Cannot define both 'connState' and 'createConnState'\",\n\t\t\tpath: [\"connState\"],\n\t\t},\n\t)\n\t.refine(\n\t\t(data) => !(data.vars !== undefined && data.createVars !== undefined),\n\t\t{\n\t\t\tmessage: \"Cannot define both 'vars' and 'createVars'\",\n\t\t\tpath: [\"vars\"],\n\t\t},\n\t);\n\nexport interface OnConnectOptions {\n\t/**\n\t * The request object associated with the connection.\n\t *\n\t * @experimental\n\t */\n\trequest?: Request;\n}\n\n// Creates state config\n//\n// This must have only one or the other or else TState will not be able to be inferred\n//\n// Data returned from this handler will be available on `c.state`.\ntype CreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase> =\n\t| { state: TState }\n\t| {\n\t\t\tcreateState: (c: InitContext, input: TInput) => TState | Promise<TState>;\n\t }\n\t| Record<never, never>;\n\n// Creates connection state config\n//\n// This must have only one or the other or else TState will not be able to be inferred\n//\n// Data returned from this handler will be available on `c.conn.state`.\ntype CreateConnState<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase,\n> =\n\t| { connState: TConnState }\n\t| {\n\t\t\tcreateConnState: (\n\t\t\t\tc: InitContext,\n\t\t\t\topts: OnConnectOptions,\n\t\t\t\tparams: TConnParams,\n\t\t\t) => TConnState | Promise<TConnState>;\n\t }\n\t| Record<never, never>;\n\n// Creates vars config\n//\n// This must have only one or the other or else TState will not be able to be inferred\n/**\n * @experimental\n */\ntype CreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase> =\n\t| {\n\t\t\t/**\n\t\t\t * @experimental\n\t\t\t */\n\t\t\tvars: TVars;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * @experimental\n\t\t\t */\n\t\t\tcreateVars: (c: InitContext, driverCtx: any) => TVars | Promise<TVars>;\n\t }\n\t| Record<never, never>;\n\nexport interface Actions<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase extends AnyDatabaseProvider,\n> {\n\t[Action: string]: (\n\t\tc: ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\t...args: any[]\n\t) => any;\n}\n\n//export type ActorConfig<TState, TConnParams, TConnState, TVars, TInput, TAuthData> = BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TAuthData> &\n//\tActorConfigLifecycle<TState, TConnParams, TConnState, TVars, TInput, TAuthData> &\n//\tCreateState<TState, TConnParams, TConnState, TVars, TInput, TAuthData> &\n//\tCreateConnState<TState, TConnParams, TConnState, TVars, TInput, TAuthData>;\n\n/**\n * @experimental\n */\nexport type AuthIntent = \"get\" | \"create\" | \"connect\" | \"action\" | \"message\";\n\ninterface BaseActorConfig<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase extends AnyDatabaseProvider,\n\tTActions extends Actions<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase\n\t>,\n> {\n\t/**\n\t * Called when the actor is first initialized.\n\t *\n\t * Use this hook to initialize your actor's state.\n\t * This is called before any other lifecycle hooks.\n\t */\n\tonCreate?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\tinput: TInput,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called when the actor is started and ready to receive connections and action.\n\t *\n\t * Use this hook to initialize resources needed for the actor's operation\n\t * (timers, external connections, etc.)\n\t *\n\t * @returns Void or a Promise that resolves when startup is complete\n\t */\n\tonStart?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called when the actor is stopping or sleeping.\n\t *\n\t * Use this hook to clean up resources, save state, or perform\n\t * any shutdown operations before the actor sleeps or stops.\n\t *\n\t * Not supported on all platforms.\n\t *\n\t * @returns Void or a Promise that resolves when shutdown is complete\n\t */\n\tonStop?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called when the actor's state changes.\n\t *\n\t * Use this hook to react to state changes, such as updating\n\t * external systems or triggering events.\n\t *\n\t * State changes made within this hook will NOT trigger\n\t * another onStateChange call, preventing infinite recursion.\n\t *\n\t * @param newState The updated state\n\t */\n\tonStateChange?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\tnewState: TState,\n\t) => void;\n\n\t/**\n\t * Called before a client connects to the actor.\n\t *\n\t * Use this hook to determine if a connection should be accepted\n\t * and to initialize connection-specific state.\n\t *\n\t * @param opts Connection parameters including client-provided data\n\t * @returns The initial connection state or a Promise that resolves to it\n\t * @throws Throw an error to reject the connection\n\t */\n\tonBeforeConnect?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\topts: OnConnectOptions,\n\t\tparams: TConnParams,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called when a client successfully connects to the actor.\n\t *\n\t * Use this hook to perform actions when a connection is established,\n\t * such as sending initial data or updating the actor's state.\n\t *\n\t * @param conn The connection object\n\t * @returns Void or a Promise that resolves when connection handling is complete\n\t */\n\tonConnect?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\tconn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called when a client disconnects from the actor.\n\t *\n\t * Use this hook to clean up resources associated with the connection\n\t * or update the actor's state.\n\t *\n\t * @param conn The connection that is being closed\n\t * @returns Void or a Promise that resolves when disconnect handling is complete\n\t */\n\tonDisconnect?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\tconn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t) => void | Promise<void>;\n\n\t/**\n\t * Called before sending an action response to the client.\n\t *\n\t * Use this hook to modify or transform the output of an action before it's sent\n\t * to the client. This is useful for formatting responses, adding metadata,\n\t * or applying transformations to the output.\n\t *\n\t * @param name The name of the action that was called\n\t * @param args The arguments that were passed to the action\n\t * @param output The output that will be sent to the client\n\t * @returns The modified output to send to the client\n\t */\n\tonBeforeActionResponse?: <Out>(\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\tname: string,\n\t\targs: unknown[],\n\t\toutput: Out,\n\t) => Out | Promise<Out>;\n\n\t/**\n\t * Called when a raw HTTP request is made to the actor.\n\t *\n\t * This handler receives raw HTTP requests made to `/actors/{actorName}/http/*` endpoints.\n\t * Use this hook to handle custom HTTP patterns, REST APIs, or other HTTP-based protocols.\n\t *\n\t * @param request The raw HTTP request object\n\t * @returns A Response object to send back, or void to continue with default routing\n\t */\n\tonFetch?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\trequest: Request,\n\t\topts: {},\n\t) => Response | Promise<Response>;\n\n\t/**\n\t * Called when a raw WebSocket connection is established to the actor.\n\t *\n\t * This handler receives WebSocket connections made to `/actors/{actorName}/websocket/*` endpoints.\n\t * Use this hook to handle custom WebSocket protocols, binary streams, or other WebSocket-based communication.\n\t *\n\t * @param websocket The raw WebSocket connection\n\t * @param request The original HTTP upgrade request\n\t */\n\tonWebSocket?: (\n\t\tc: ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase>,\n\t\twebsocket: UniversalWebSocket,\n\t\topts: { request: Request },\n\t) => void | Promise<void>;\n\n\tactions: TActions;\n}\n\ntype ActorDatabaseConfig<TDatabase extends AnyDatabaseProvider> =\n\t| {\n\t\t\t/**\n\t\t\t * @experimental\n\t\t\t */\n\t\t\tdb: TDatabase;\n\t }\n\t| Record<never, never>;\n\n// 1. Infer schema\n// 2. Omit keys that we'll manually define (because of generics)\n// 3. Define our own types that have generic constraints\nexport type ActorConfig<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase extends AnyDatabaseProvider,\n> = Omit<\n\tz.infer<typeof ActorConfigSchema>,\n\t| \"actions\"\n\t| \"onCreate\"\n\t| \"onStart\"\n\t| \"onStateChange\"\n\t| \"onBeforeConnect\"\n\t| \"onConnect\"\n\t| \"onDisconnect\"\n\t| \"onBeforeActionResponse\"\n\t| \"onFetch\"\n\t| \"onWebSocket\"\n\t| \"state\"\n\t| \"createState\"\n\t| \"connState\"\n\t| \"createConnState\"\n\t| \"vars\"\n\t| \"createVars\"\n\t| \"db\"\n> &\n\tBaseActorConfig<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase,\n\t\tActions<TState, TConnParams, TConnState, TVars, TInput, TDatabase>\n\t> &\n\tCreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase> &\n\tCreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase> &\n\tCreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase> &\n\tActorDatabaseConfig<TDatabase>;\n\n// See description on `ActorConfig`\nexport type ActorConfigInput<\n\tTState = undefined,\n\tTConnParams = undefined,\n\tTConnState = undefined,\n\tTVars = undefined,\n\tTInput = undefined,\n\tTDatabase extends AnyDatabaseProvider = undefined,\n\tTActions extends Actions<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase\n\t> = Record<never, never>,\n> = {\n\ttypes?: ActorTypes<TState, TConnParams, TConnState, TVars, TInput, TDatabase>;\n} & Omit<\n\tz.input<typeof ActorConfigSchema>,\n\t| \"actions\"\n\t| \"onCreate\"\n\t| \"onStart\"\n\t| \"onStop\"\n\t| \"onStateChange\"\n\t| \"onBeforeConnect\"\n\t| \"onConnect\"\n\t| \"onDisconnect\"\n\t| \"onBeforeActionResponse\"\n\t| \"onFetch\"\n\t| \"onWebSocket\"\n\t| \"state\"\n\t| \"createState\"\n\t| \"connState\"\n\t| \"createConnState\"\n\t| \"vars\"\n\t| \"createVars\"\n\t| \"db\"\n> &\n\tBaseActorConfig<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase,\n\t\tTActions\n\t> &\n\tCreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase> &\n\tCreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase> &\n\tCreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase> &\n\tActorDatabaseConfig<TDatabase>;\n\n// For testing type definitions:\nexport function test<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase extends AnyDatabaseProvider,\n\tTActions extends Actions<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase\n\t>,\n>(\n\tinput: ActorConfigInput<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase,\n\t\tTActions\n\t>,\n): ActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase> {\n\tconst config = ActorConfigSchema.parse(input) as ActorConfig<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase\n\t>;\n\treturn config;\n}\n","import { Hono, type Context as HonoContext } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport invariant from \"invariant\";\nimport { EncodingSchema } from \"@/actor/protocol/serde\";\nimport {\n\ttype ActionOpts,\n\ttype ActionOutput,\n\ttype ConnectSseOpts,\n\ttype ConnectSseOutput,\n\ttype ConnectWebSocketOpts,\n\ttype ConnectWebSocketOutput,\n\ttype ConnsMessageOpts,\n\thandleAction,\n\thandleConnectionClose,\n\thandleConnectionMessage,\n\thandleRawWebSocketHandler,\n\thandleSseConnect,\n\thandleWebSocketConnect,\n} from \"@/actor/router-endpoints\";\nimport {\n\tHEADER_CONN_ID,\n\tHEADER_CONN_PARAMS,\n\tHEADER_CONN_TOKEN,\n\tHEADER_ENCODING,\n\tPATH_CONNECT_WEBSOCKET,\n\tPATH_RAW_WEBSOCKET_PREFIX,\n\tWS_PROTOCOL_CONN_ID,\n\tWS_PROTOCOL_CONN_PARAMS,\n\tWS_PROTOCOL_CONN_TOKEN,\n\tWS_PROTOCOL_ENCODING,\n\tWS_PROTOCOL_TOKEN,\n} from \"@/common/actor-router-consts\";\nimport {\n\thandleRouteError,\n\thandleRouteNotFound,\n\tloggerMiddleware,\n} from \"@/common/router\";\nimport { noopNext } from \"@/common/utils\";\nimport {\n\ttype ActorInspectorRouterEnv,\n\tcreateActorInspectorRouter,\n} from \"@/inspector/actor\";\nimport { isInspectorEnabled, secureInspector } from \"@/inspector/utils\";\nimport type { RunConfig } from \"@/registry/run-config\";\nimport { ConnDriverKind } from \"./conn-drivers\";\nimport type { ActorDriver } from \"./driver\";\nimport { InternalError } from \"./errors\";\nimport { loggerWithoutContext } from \"./log\";\n\nexport type {\n\tConnectWebSocketOpts,\n\tConnectWebSocketOutput,\n\tConnectSseOpts,\n\tConnectSseOutput,\n\tActionOpts,\n\tActionOutput,\n\tConnsMessageOpts,\n};\n\ninterface ActorRouterBindings {\n\tactorId: string;\n}\n\nexport type ActorRouter = Hono<{ Bindings: ActorRouterBindings }>;\n\n/**\n * Creates a router that runs on the partitioned instance.\n */\nexport function createActorRouter(\n\trunConfig: RunConfig,\n\tactorDriver: ActorDriver,\n): ActorRouter {\n\tconst router = new Hono<{ Bindings: ActorRouterBindings }>({ strict: false });\n\n\trouter.use(\"*\", loggerMiddleware(loggerWithoutContext()));\n\n\trouter.get(\"/\", (c) => {\n\t\treturn c.text(\n\t\t\t\"This is an RivetKit actor.\\n\\nLearn more at https://rivetkit.org\",\n\t\t);\n\t});\n\n\trouter.get(\"/health\", (c) => {\n\t\treturn c.text(\"ok\");\n\t});\n\n\t// Test endpoint to force disconnect a connection non-cleanly\n\trouter.post(\"/.test/force-disconnect\", async (c) => {\n\t\tconst connId = c.req.query(\"conn\");\n\n\t\tif (!connId) {\n\t\t\treturn c.text(\"Missing conn query parameter\", 400);\n\t\t}\n\n\t\tconst actor = await actorDriver.loadActor(c.env.actorId);\n\t\tconst conn = actor.__getConnForId(connId);\n\n\t\tif (!conn) {\n\t\t\treturn c.text(`Connection not found: ${connId}`, 404);\n\t\t}\n\n\t\t// Force close the websocket/SSE connection without clean shutdown\n\t\tconst driverState = conn.__driverState;\n\t\tif (driverState && ConnDriverKind.WEBSOCKET in driverState) {\n\t\t\tconst ws = driverState[ConnDriverKind.WEBSOCKET].websocket;\n\n\t\t\t// Force close without sending close frame\n\t\t\t(ws.raw as any).terminate();\n\t\t} else if (driverState && ConnDriverKind.SSE in driverState) {\n\t\t\tconst stream = driverState[ConnDriverKind.SSE].stream;\n\n\t\t\t// Force close the SSE stream\n\t\t\tstream.abort();\n\t\t}\n\n\t\treturn c.json({ success: true });\n\t});\n\n\trouter.get(PATH_CONNECT_WEBSOCKET, async (c) => {\n\t\tconst upgradeWebSocket = runConfig.getUpgradeWebSocket?.();\n\t\tif (upgradeWebSocket) {\n\t\t\treturn upgradeWebSocket(async (c) => {\n\t\t\t\t// Parse configuration from Sec-WebSocket-Protocol header\n\t\t\t\tconst protocols = c.req.header(\"sec-websocket-protocol\");\n\t\t\t\tlet encodingRaw: string | undefined;\n\t\t\t\tlet connParamsRaw: string | undefined;\n\t\t\t\tlet connIdRaw: string | undefined;\n\t\t\t\tlet connTokenRaw: string | undefined;\n\n\t\t\t\tif (protocols) {\n\t\t\t\t\tconst protocolList = protocols.split(\",\").map((p) => p.trim());\n\t\t\t\t\tfor (const protocol of protocolList) {\n\t\t\t\t\t\tif (protocol.startsWith(WS_PROTOCOL_ENCODING)) {\n\t\t\t\t\t\t\tencodingRaw = protocol.substring(WS_PROTOCOL_ENCODING.length);\n\t\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_PARAMS)) {\n\t\t\t\t\t\t\tconnParamsRaw = decodeURIComponent(\n\t\t\t\t\t\t\t\tprotocol.substring(WS_PROTOCOL_CONN_PARAMS.length),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_ID)) {\n\t\t\t\t\t\t\tconnIdRaw = protocol.substring(WS_PROTOCOL_CONN_ID.length);\n\t\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_TOKEN)) {\n\t\t\t\t\t\t\tconnTokenRaw = protocol.substring(WS_PROTOCOL_CONN_TOKEN.length);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst encoding = EncodingSchema.parse(encodingRaw);\n\t\t\t\tconst connParams = connParamsRaw\n\t\t\t\t\t? JSON.parse(connParamsRaw)\n\t\t\t\t\t: undefined;\n\n\t\t\t\treturn await handleWebSocketConnect(\n\t\t\t\t\tc.req.raw,\n\t\t\t\t\trunConfig,\n\t\t\t\t\tactorDriver,\n\t\t\t\t\tc.env.actorId,\n\t\t\t\t\tencoding,\n\t\t\t\t\tconnParams,\n\t\t\t\t\tconnIdRaw,\n\t\t\t\t\tconnTokenRaw,\n\t\t\t\t);\n\t\t\t})(c, noopNext());\n\t\t} else {\n\t\t\treturn c.text(\n\t\t\t\t\"WebSockets are not enabled for this driver. Use SSE instead.\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\trouter.get(\"/connect/sse\", async (c) => {\n\t\treturn handleSseConnect(c, runConfig, actorDriver, c.env.actorId);\n\t});\n\n\trouter.post(\"/action/:action\", async (c) => {\n\t\tconst actionName = c.req.param(\"action\");\n\n\t\treturn handleAction(c, runConfig, actorDriver, actionName, c.env.actorId);\n\t});\n\n\trouter.post(\"/connections/message\", async (c) => {\n\t\tconst connId = c.req.header(HEADER_CONN_ID);\n\t\tconst connToken = c.req.header(HEADER_CONN_TOKEN);\n\t\tif (!connId || !connToken) {\n\t\t\tthrow new Error(\"Missing required parameters\");\n\t\t}\n\t\treturn handleConnectionMessage(\n\t\t\tc,\n\t\t\trunConfig,\n\t\t\tactorDriver,\n\t\t\tconnId,\n\t\t\tconnToken,\n\t\t\tc.env.actorId,\n\t\t);\n\t});\n\n\trouter.post(\"/connections/close\", async (c) => {\n\t\tconst connId = c.req.header(HEADER_CONN_ID);\n\t\tconst connToken = c.req.header(HEADER_CONN_TOKEN);\n\t\tif (!connId || !connToken) {\n\t\t\tthrow new Error(\"Missing required parameters\");\n\t\t}\n\t\treturn handleConnectionClose(\n\t\t\tc,\n\t\t\trunConfig,\n\t\t\tactorDriver,\n\t\t\tconnId,\n\t\t\tconnToken,\n\t\t\tc.env.actorId,\n\t\t);\n\t});\n\n\t// Raw HTTP endpoints - /http/*\n\trouter.all(\"/raw/http/*\", async (c) => {\n\t\tconst actor = await actorDriver.loadActor(c.env.actorId);\n\n\t\t// TODO: This is not a clean way of doing this since `/http/` might exist mid-path\n\t\t// Strip the /http prefix from the URL to get the original path\n\t\tconst url = new URL(c.req.url);\n\t\tconst originalPath = url.pathname.replace(/^\\/raw\\/http/, \"\") || \"/\";\n\n\t\t// Create a new request with the corrected URL\n\t\tconst correctedUrl = new URL(originalPath + url.search, url.origin);\n\t\tconst correctedRequest = new Request(correctedUrl, {\n\t\t\tmethod: c.req.method,\n\t\t\theaders: c.req.raw.headers,\n\t\t\tbody: c.req.raw.body,\n\t\t\tduplex: \"half\",\n\t\t} as RequestInit);\n\n\t\tloggerWithoutContext().debug({\n\t\t\tmsg: \"rewriting http url\",\n\t\t\tfrom: c.req.url,\n\t\t\tto: correctedRequest.url,\n\t\t});\n\n\t\t// Call the actor's onFetch handler - it will throw appropriate errors\n\t\tconst response = await actor.handleFetch(correctedRequest, {});\n\n\t\t// This should never happen now since handleFetch throws errors\n\t\tif (!response) {\n\t\t\tthrow new InternalError(\"handleFetch returned void unexpectedly\");\n\t\t}\n\n\t\treturn response;\n\t});\n\n\t// Raw WebSocket endpoint - /websocket/*\n\trouter.get(`${PATH_RAW_WEBSOCKET_PREFIX}*`, async (c) => {\n\t\tconst upgradeWebSocket = runConfig.getUpgradeWebSocket?.();\n\t\tif (upgradeWebSocket) {\n\t\t\treturn upgradeWebSocket(async (c) => {\n\t\t\t\tconst url = new URL(c.req.url);\n\t\t\t\tconst pathWithQuery = c.req.path + url.search;\n\n\t\t\t\tloggerWithoutContext().debug({\n\t\t\t\t\tmsg: \"actor router raw websocket\",\n\t\t\t\t\tpath: c.req.path,\n\t\t\t\t\turl: c.req.url,\n\t\t\t\t\tsearch: url.search,\n\t\t\t\t\tpathWithQuery,\n\t\t\t\t});\n\n\t\t\t\treturn await handleRawWebSocketHandler(\n\t\t\t\t\tc.req.raw,\n\t\t\t\t\tpathWithQuery,\n\t\t\t\t\tactorDriver,\n\t\t\t\t\tc.env.actorId,\n\t\t\t\t);\n\t\t\t})(c, noopNext());\n\t\t} else {\n\t\t\treturn c.text(\n\t\t\t\t\"WebSockets are not enabled for this driver. Use SSE instead.\",\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tif (isInspectorEnabled(runConfig, \"actor\")) {\n\t\trouter.route(\n\t\t\t\"/inspect\",\n\t\t\tnew Hono<ActorInspectorRouterEnv & { Bindings: ActorRouterBindings }>()\n\t\t\t\t.use(\n\t\t\t\t\tcors(runConfig.inspector.cors),\n\t\t\t\t\tsecureInspector(runConfig),\n\t\t\t\t\tasync (c, next) => {\n\t\t\t\t\t\tconst inspector = (await actorDriver.loadActor(c.env.actorId))\n\t\t\t\t\t\t\t.inspector;\n\t\t\t\t\t\tinvariant(inspector, \"inspector not supported on this platform\");\n\n\t\t\t\t\t\tc.set(\"inspector\", inspector);\n\t\t\t\t\t\treturn next();\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\t.route(\"/\", createActorInspectorRouter()),\n\t\t);\n\t}\n\n\trouter.notFound(handleRouteNotFound);\n\trouter.onError(handleRouteError);\n\n\treturn router;\n}\n","import * as cbor from \"cbor-x\";\nimport type { Context as HonoContext, HonoRequest } from \"hono\";\nimport { type SSEStreamingApi, streamSSE } from \"hono/streaming\";\nimport type { WSContext } from \"hono/ws\";\nimport invariant from \"invariant\";\nimport { ActionContext } from \"@/actor/action\";\nimport type { AnyConn } from \"@/actor/conn\";\nimport {\n\tgenerateConnId,\n\tgenerateConnSocketId,\n\tgenerateConnToken,\n} from \"@/actor/conn\";\nimport { ConnDriverKind } from \"@/actor/conn-drivers\";\nimport * as errors from \"@/actor/errors\";\nimport type { AnyActorInstance } from \"@/actor/instance\";\nimport type { InputData } from \"@/actor/protocol/serde\";\nimport { type Encoding, EncodingSchema } from \"@/actor/protocol/serde\";\nimport {\n\tHEADER_ACTOR_QUERY,\n\tHEADER_CONN_ID,\n\tHEADER_CONN_PARAMS,\n\tHEADER_CONN_TOKEN,\n\tHEADER_ENCODING,\n} from \"@/common/actor-router-consts\";\nimport type { UpgradeWebSocketArgs } from \"@/common/inline-websocket-adapter2\";\nimport { deconstructError, stringifyError } from \"@/common/utils\";\nimport type { UniversalWebSocket } from \"@/common/websocket-interface\";\nimport { HonoWebSocketAdapter } from \"@/manager/hono-websocket-adapter\";\nimport type { RunConfig } from \"@/registry/run-config\";\nimport type * as protocol from \"@/schemas/client-protocol/mod\";\nimport {\n\tHTTP_ACTION_REQUEST_VERSIONED,\n\tHTTP_ACTION_RESPONSE_VERSIONED,\n\tTO_SERVER_VERSIONED,\n} from \"@/schemas/client-protocol/versioned\";\nimport {\n\tcontentTypeForEncoding,\n\tdeserializeWithEncoding,\n\tserializeWithEncoding,\n} from \"@/serde\";\nimport { bufferToArrayBuffer, promiseWithResolvers } from \"@/utils\";\nimport type { ActorDriver } from \"./driver\";\nimport { loggerWithoutContext } from \"./log\";\nimport { parseMessage } from \"./protocol/old\";\n\nexport const SSE_PING_INTERVAL = 1000;\n\nexport interface ConnectWebSocketOpts {\n\treq?: HonoRequest;\n\tencoding: Encoding;\n\tactorId: string;\n\tparams: unknown;\n}\n\nexport interface ConnectWebSocketOutput {\n\tonOpen: (ws: WSContext) => void;\n\tonMessage: (message: protocol.ToServer) => void;\n\tonClose: () => void;\n}\n\nexport interface ConnectSseOpts {\n\treq?: HonoRequest;\n\tencoding: Encoding;\n\tparams: unknown;\n\tactorId: string;\n}\n\nexport interface ConnectSseOutput {\n\tonOpen: (stream: SSEStreamingApi) => void;\n\tonClose: () => Promise<void>;\n}\n\nexport interface ActionOpts {\n\treq?: HonoRequest;\n\tparams: unknown;\n\tactionName: string;\n\tactionArgs: unknown[];\n\tactorId: string;\n}\n\nexport interface ActionOutput {\n\toutput: unknown;\n}\n\nexport interface ConnsMessageOpts {\n\treq?: HonoRequest;\n\tconnId: string;\n\tconnToken: string;\n\tmessage: protocol.ToServer;\n\tactorId: string;\n}\n\nexport interface FetchOpts {\n\trequest: Request;\n\tactorId: string;\n}\n\nexport interface WebSocketOpts {\n\trequest: Request;\n\twebsocket: UniversalWebSocket;\n\tactorId: string;\n}\n\n/**\n * Creates a WebSocket connection handler\n */\nexport async function handleWebSocketConnect(\n\treq: Request | undefined,\n\trunConfig: RunConfig,\n\tactorDriver: ActorDriver,\n\tactorId: string,\n\tencoding: Encoding,\n\tparameters: unknown,\n\tconnId?: string,\n\tconnToken?: string,\n): Promise<UpgradeWebSocketArgs> {\n\tconst exposeInternalError = req ? getRequestExposeInternalError(req) : false;\n\n\t// Setup promise for the init handlers since all other behavior depends on this\n\tconst {\n\t\tpromise: handlersPromise,\n\t\tresolve: handlersResolve,\n\t\treject: handlersReject,\n\t} = promiseWithResolvers<{\n\t\tconn: AnyConn;\n\t\tactor: AnyActorInstance;\n\t\tconnId: string;\n\t}>();\n\n\t// Pre-load the actor to catch errors early\n\tlet actor: AnyActorInstance;\n\ttry {\n\t\tactor = await actorDriver.loadActor(actorId);\n\t} catch (error) {\n\t\t// Return handler that immediately closes with error\n\t\treturn {\n\t\t\tonOpen: (_evt: any, ws: WSContext) => {\n\t\t\t\tconst { code } = deconstructError(\n\t\t\t\t\terror,\n\t\t\t\t\tactor.rLog,\n\t\t\t\t\t{\n\t\t\t\t\t\twsEvent: \"open\",\n\t\t\t\t\t},\n\t\t\t\t\texposeInternalError,\n\t\t\t\t);\n\t\t\t\tws.close(1011, code);\n\t\t\t},\n\t\t\tonMessage: (_evt: { data: any }, ws: WSContext) => {\n\t\t\t\tws.close(1011, \"Actor not loaded\");\n\t\t\t},\n\t\t\tonClose: (_event: any, _ws: WSContext) => {},\n\t\t\tonError: (_error: unknown) => {},\n\t\t};\n\t}\n\n\t// Promise used to wait for the websocket close in `disconnect`\n\tconst closePromise = promiseWithResolvers<void>();\n\tconst socketId = generateConnSocketId();\n\n\treturn {\n\t\tonOpen: (_evt: any, ws: WSContext) => {\n\t\t\tactor.rLog.debug(\"actor websocket open\");\n\n\t\t\t// Run async operations in background\n\t\t\t(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tlet conn: AnyConn;\n\n\t\t\t\t\t// Create or reconnect connection\n\t\t\t\t\tactor.rLog.debug({\n\t\t\t\t\t\tmsg: connId\n\t\t\t\t\t\t\t? \"websocket reconnection attempt\"\n\t\t\t\t\t\t\t: \"new websocket connection\",\n\t\t\t\t\t\tconnId,\n\t\t\t\t\t\tactorId,\n\t\t\t\t\t});\n\n\t\t\t\t\tconn = await actor.createConn(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsocketId,\n\t\t\t\t\t\t\tdriverState: {\n\t\t\t\t\t\t\t\t[ConnDriverKind.WEBSOCKET]: {\n\t\t\t\t\t\t\t\t\tencoding,\n\t\t\t\t\t\t\t\t\twebsocket: ws,\n\t\t\t\t\t\t\t\t\tclosePromise,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tparameters,\n\t\t\t\t\t\treq,\n\t\t\t\t\t\tconnId,\n\t\t\t\t\t\tconnToken,\n\t\t\t\t\t);\n\n\t\t\t\t\t// Unblock other handlers\n\t\t\t\t\thandlersResolve({ conn, actor, connId: conn.id });\n\t\t\t\t} catch (error) {\n\t\t\t\t\thandlersReject(error);\n\n\t\t\t\t\tconst { code } = deconstructError(\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tactor.rLog,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twsEvent: \"open\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\texposeInternalError,\n\t\t\t\t\t);\n\t\t\t\t\tws.close(1011, code);\n\t\t\t\t}\n\t\t\t})();\n\t\t},\n\t\tonMessage: (evt: { data: any }, ws: WSContext) => {\n\t\t\t// Handle message asynchronously\n\t\t\thandlersPromise\n\t\t\t\t.then(({ conn, actor }) => {\n\t\t\t\t\tactor.rLog.debug({ msg: \"received message\" });\n\n\t\t\t\t\tconst value = evt.data.valueOf() as InputData;\n\t\t\t\t\tparseMessage(value, {\n\t\t\t\t\t\tencoding: encoding,\n\t\t\t\t\t\tmaxIncomingMessageSize: runConfig.maxIncomingMessageSize,\n\t\t\t\t\t})\n\t\t\t\t\t\t.then((message) => {\n\t\t\t\t\t\t\tactor.processMessage(message, conn).catch((error) => {\n\t\t\t\t\t\t\t\tconst { code } = deconstructError(\n\t\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\t\tactor.rLog,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\twsEvent: \"message\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\texposeInternalError,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tws.close(1011, code);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.catch((error) => {\n\t\t\t\t\t\t\tconst { code } = deconstructError(\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tactor.rLog,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\twsEvent: \"message\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\texposeInternalError,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tws.close(1011, code);\n\t\t\t\t\t\t});\n\t\t\t\t})\n\t\t\t\t.catch((error) => {\n\t\t\t\t\tconst { code } = deconstructError(\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tactor.rLog,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twsEvent: \"message\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\texposeInternalError,\n\t\t\t\t\t);\n\t\t\t\t\tws.close(1011, code);\n\t\t\t\t});\n\t\t},\n\t\tonClose: (\n\t\t\tevent: {\n\t\t\t\twasClean: boolean;\n\t\t\t\tcode: number;\n\t\t\t\treason: string;\n\t\t\t},\n\t\t\tws: WSContext,\n\t\t) => {\n\t\t\thandlersReject(`WebSocket closed (${event.code}): ${event.reason}`);\n\n\t\t\tclosePromise.resolve();\n\n\t\t\tif (event.wasClean) {\n\t\t\t\tactor.rLog.info({\n\t\t\t\t\tmsg: \"websocket closed\",\n\t\t\t\t\tcode: event.code,\n\t\t\t\t\treason: event.reason,\n\t\t\t\t\twasClean: event.wasClean,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tactor.rLog.warn({\n\t\t\t\t\tmsg: \"websocket closed\",\n\t\t\t\t\tcode: event.code,\n\t\t\t\t\treason: event.reason,\n\t\t\t\t\twasClean: event.wasClean,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// HACK: Close socket in order to fix bug with Cloudflare leaving WS in closing state\n\t\t\t// https://github.com/cloudflare/workerd/issues/2569\n\t\t\tws.close(1000, \"hack_force_close\");\n\n\t\t\t// Handle cleanup asynchronously\n\t\t\thandlersPromise\n\t\t\t\t.then(({ conn, actor }) => {\n\t\t\t\t\tactor.__connDisconnected(conn, event.wasClean, socketId);\n\t\t\t\t})\n\t\t\t\t.catch((error) => {\n\t\t\t\t\tdeconstructError(\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tactor.rLog,\n\t\t\t\t\t\t{ wsEvent: \"close\" },\n\t\t\t\t\t\texposeInternalError,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t},\n\t\tonError: (_error: unknown) => {\n\t\t\ttry {\n\t\t\t\t// Actors don't need to know about this, since it's abstracted away\n\t\t\t\tactor.rLog.warn({ msg: \"websocket error\" });\n\t\t\t} catch (error) {\n\t\t\t\tdeconstructError(\n\t\t\t\t\terror,\n\t\t\t\t\tactor.rLog,\n\t\t\t\t\t{ wsEvent: \"error\" },\n\t\t\t\t\texposeInternalError,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Creates an SSE connection handler\n */\nexport async function handleSseConnect(\n\tc: HonoContext,\n\t_runConfig: RunConfig,\n\tactorDriver: ActorDriver,\n\tactorId: string,\n) {\n\tc.header(\"Content-Encoding\", \"Identity\");\n\n\tconst encoding = getRequestEncoding(c.req);\n\tconst parameters = getRequestConnParams(c.req);\n\tconst socketId = generateConnSocketId();\n\n\t// Check for reconnection parameters\n\tconst connId = c.req.header(HEADER_CONN_ID);\n\tconst connToken = c.req.header(HEADER_CONN_TOKEN);\n\n\t// Return the main handler with all async work inside\n\treturn streamSSE(c, async (stream) => {\n\t\tlet actor: AnyActorInstance | undefined;\n\t\tlet conn: AnyConn | undefined;\n\n\t\ttry {\n\t\t\t// Do all async work inside the handler\n\t\t\tactor = await actorDriver.loadActor(actorId);\n\n\t\t\t// Create or reconnect connection\n\t\t\tactor.rLog.debug({\n\t\t\t\tmsg: connId ? \"sse reconnection attempt\" : \"sse open\",\n\t\t\t\tconnId,\n\t\t\t});\n\n\t\t\tconn = await actor.createConn(\n\t\t\t\t{\n\t\t\t\t\tsocketId,\n\t\t\t\t\tdriverState: {\n\t\t\t\t\t\t[ConnDriverKind.SSE]: {\n\t\t\t\t\t\t\tencoding,\n\t\t\t\t\t\t\tstream: stream,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tparameters,\n\t\t\t\tc.req.raw,\n\t\t\t\tconnId,\n\t\t\t\tconnToken,\n\t\t\t);\n\n\t\t\t// Wait for close\n\t\t\tconst abortResolver = promiseWithResolvers();\n\n\t\t\t// HACK: This is required so the abort handler below works\n\t\t\t//\n\t\t\t// See https://github.com/honojs/hono/issues/1770#issuecomment-2461966225\n\t\t\tstream.onAbort(() => {});\n\n\t\t\t// Handle stream abort (when client closes the connection)\n\t\t\tc.req.raw.signal.addEventListener(\"abort\", async () => {\n\t\t\t\tinvariant(actor, \"actor should exist\");\n\t\t\t\tconst rLog = actor.rLog ?? loggerWithoutContext();\n\t\t\t\ttry {\n\t\t\t\t\trLog.debug(\"sse stream aborted\");\n\n\t\t\t\t\t// Cleanup\n\t\t\t\t\tif (conn) {\n\t\t\t\t\t\tactor.__connDisconnected(conn, false, socketId);\n\t\t\t\t\t}\n\n\t\t\t\t\tabortResolver.resolve(undefined);\n\t\t\t\t} catch (error) {\n\t\t\t\t\trLog.error({ msg: \"error closing sse connection\", error });\n\t\t\t\t\tabortResolver.resolve(undefined);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// // HACK: Will throw if not configured\n\t\t\t// try {\n\t\t\t// \tc.executionCtx.waitUntil(abortResolver.promise);\n\t\t\t// } catch {}\n\n\t\t\t// Send ping every second to keep the connection alive\n\t\t\t//\n\t\t\t// NOTE: This is required on Cloudflare Workers in order to detect when the connection is closed\n\t\t\twhile (true) {\n\t\t\t\tif (stream.closed || stream.aborted) {\n\t\t\t\t\tactor?.rLog.debug({\n\t\t\t\t\t\tmsg: \"sse stream closed\",\n\t\t\t\t\t\tclosed: stream.closed,\n\t\t\t\t\t\taborted: stream.aborted,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tawait stream.writeSSE({ event: \"ping\", data: \"\" });\n\t\t\t\tawait stream.sleep(SSE_PING_INTERVAL);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tloggerWithoutContext().error({ msg: \"error in sse connection\", error });\n\n\t\t\t// Cleanup on error\n\t\t\tif (conn && actor !== undefined) {\n\t\t\t\tactor.__connDisconnected(conn, false, socketId);\n\t\t\t}\n\n\t\t\t// Close the stream on error\n\t\t\tstream.close();\n\t\t}\n\t});\n}\n\n/**\n * Creates an action handler\n */\nexport async function handleAction(\n\tc: HonoContext,\n\t_runConfig: RunConfig,\n\tactorDriver: ActorDriver,\n\tactionName: string,\n\tactorId: string,\n) {\n\tconst encoding = getRequestEncoding(c.req);\n\tconst parameters = getRequestConnParams(c.req);\n\n\t// Validate incoming request\n\tconst arrayBuffer = await c.req.arrayBuffer();\n\tconst request = deserializeWithEncoding(\n\t\tencoding,\n\t\tnew Uint8Array(arrayBuffer),\n\t\tHTTP_ACTION_REQUEST_VERSIONED,\n\t);\n\tconst actionArgs = cbor.decode(new Uint8Array(request.args));\n\tconst socketId = generateConnSocketId();\n\n\t// Invoke the action\n\tlet actor: AnyActorInstance | undefined;\n\tlet conn: AnyConn | undefined;\n\tlet output: unknown | undefined;\n\ttry {\n\t\tactor = await actorDriver.loadActor(actorId);\n\n\t\tactor.rLog.debug({ msg: \"handling action\", actionName, encoding });\n\n\t\t// Create conn\n\t\tconn = await actor.createConn(\n\t\t\t{\n\t\t\t\tsocketId,\n\t\t\t\tdriverState: { [ConnDriverKind.HTTP]: {} },\n\t\t\t},\n\t\t\tparameters,\n\t\t\tc.req.raw,\n\t\t);\n\n\t\t// Call action\n\t\tconst ctx = new ActionContext(actor.actorContext!, conn!);\n\t\toutput = await actor.executeAction(ctx, actionName, actionArgs);\n\t} finally {\n\t\tif (conn) {\n\t\t\t// HTTP connections don't have persistent sockets, so no socket ID needed\n\t\t\tactor?.__connDisconnected(conn, true, socketId);\n\t\t}\n\t}\n\n\t// Send response\n\tconst responseData: protocol.HttpActionResponse = {\n\t\toutput: bufferToArrayBuffer(cbor.encode(output)),\n\t};\n\tconst serialized = serializeWithEncoding(\n\t\tencoding,\n\t\tresponseData,\n\t\tHTTP_ACTION_RESPONSE_VERSIONED,\n\t);\n\n\t// TODO: Remvoe any, Hono is being a dumbass\n\treturn c.body(serialized as Uint8Array as any, 200, {\n\t\t\"Content-Type\": contentTypeForEncoding(encoding),\n\t});\n}\n\n/**\n * Create a connection message handler\n */\nexport async function handleConnectionMessage(\n\tc: HonoContext,\n\t_runConfig: RunConfig,\n\tactorDriver: ActorDriver,\n\tconnId: string,\n\tconnToken: string,\n\tactorId: string,\n) {\n\tconst encoding = getRequestEncoding(c.req);\n\n\t// Validate incoming request\n\tconst arrayBuffer = await c.req.arrayBuffer();\n\tconst message = deserializeWithEncoding(\n\t\tencoding,\n\t\tnew Uint8Array(arrayBuffer),\n\t\tTO_SERVER_VERSIONED,\n\t);\n\n\tconst actor = await actorDriver.loadActor(actorId);\n\n\t// Find connection\n\tconst conn = actor.conns.get(connId);\n\tif (!conn) {\n\t\tthrow new errors.ConnNotFound(connId);\n\t}\n\n\t// Authenticate connection\n\tif (conn._token !== connToken) {\n\t\tthrow new errors.IncorrectConnToken();\n\t}\n\n\t// Process message\n\tawait actor.processMessage(message, conn);\n\n\treturn c.json({});\n}\n\nexport async function handleConnectionClose(\n\tc: HonoContext,\n\t_runConfig: RunConfig,\n\tactorDriver: ActorDriver,\n\tconnId: string,\n\tconnToken: string,\n\tactorId: string,\n) {\n\tconst actor = await actorDriver.loadActor(actorId);\n\n\t// Find connection\n\tconst conn = actor.conns.get(connId);\n\tif (!conn) {\n\t\tthrow new errors.ConnNotFound(connId);\n\t}\n\n\t// Authenticate connection\n\tif (conn._token !== connToken) {\n\t\tthrow new errors.IncorrectConnToken();\n\t}\n\n\t// Check if this is an SSE connection\n\tif (\n\t\t!conn.__socket?.driverState ||\n\t\t!(ConnDriverKind.SSE in conn.__socket.driverState)\n\t) {\n\t\tthrow new errors.UserError(\n\t\t\t\"Connection close is only supported for SSE connections\",\n\t\t);\n\t}\n\n\t// Close the SSE connection\n\tawait conn.disconnect(\"Connection closed by client request\");\n\n\treturn c.json({});\n}\n\nexport async function handleRawWebSocketHandler(\n\treq: Request | undefined,\n\tpath: string,\n\tactorDriver: ActorDriver,\n\tactorId: string,\n): Promise<UpgradeWebSocketArgs> {\n\tconst actor = await actorDriver.loadActor(actorId);\n\n\t// Return WebSocket event handlers\n\treturn {\n\t\tonOpen: (_evt: any, ws: any) => {\n\t\t\t// Wrap the Hono WebSocket in our adapter\n\t\t\tconst adapter = new HonoWebSocketAdapter(ws);\n\n\t\t\t// Store adapter reference on the WebSocket for event handlers\n\t\t\t(ws as any).__adapter = adapter;\n\n\t\t\t// Extract the path after prefix and preserve query parameters\n\t\t\t// Use URL API for cleaner parsing\n\t\t\tconst url = new URL(path, \"http://actor\");\n\t\t\tconst pathname = url.pathname.replace(/^\\/raw\\/websocket\\/?/, \"\") || \"/\";\n\t\t\tconst normalizedPath =\n\t\t\t\t(pathname.startsWith(\"/\") ? pathname : \"/\" + pathname) + url.search;\n\n\t\t\tlet newRequest: Request;\n\t\t\tif (req) {\n\t\t\t\tnewRequest = new Request(`http://actor${normalizedPath}`, req);\n\t\t\t} else {\n\t\t\t\tnewRequest = new Request(`http://actor${normalizedPath}`, {\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tactor.rLog.debug({\n\t\t\t\tmsg: \"rewriting websocket url\",\n\t\t\t\tfrom: path,\n\t\t\t\tto: newRequest.url,\n\t\t\t\tpathname: url.pathname,\n\t\t\t\tsearch: url.search,\n\t\t\t\tnormalizedPath,\n\t\t\t});\n\n\t\t\t// Call the actor's onWebSocket handler with the adapted WebSocket\n\t\t\tactor.handleWebSocket(adapter, {\n\t\t\t\trequest: newRequest,\n\t\t\t});\n\t\t},\n\t\tonMessage: (event: any, ws: any) => {\n\t\t\t// Find the adapter for this WebSocket\n\t\t\tconst adapter = (ws as any).__adapter;\n\t\t\tif (adapter) {\n\t\t\t\tadapter._handleMessage(event);\n\t\t\t}\n\t\t},\n\t\tonClose: (evt: any, ws: any) => {\n\t\t\t// Find the adapter for this WebSocket\n\t\t\tconst adapter = (ws as any).__adapter;\n\t\t\tif (adapter) {\n\t\t\t\tadapter._handleClose(evt?.code || 1006, evt?.reason || \"\");\n\t\t\t}\n\t\t},\n\t\tonError: (error: any, ws: any) => {\n\t\t\t// Find the adapter for this WebSocket\n\t\t\tconst adapter = (ws as any).__adapter;\n\t\t\tif (adapter) {\n\t\t\t\tadapter._handleError(error);\n\t\t\t}\n\t\t},\n\t};\n}\n\n// Helper to get the connection encoding from a request\nexport function getRequestEncoding(req: HonoRequest): Encoding {\n\tconst encodingParam = req.header(HEADER_ENCODING);\n\tif (!encodingParam) {\n\t\tthrow new errors.InvalidEncoding(\"undefined\");\n\t}\n\n\tconst result = EncodingSchema.safeParse(encodingParam);\n\tif (!result.success) {\n\t\tthrow new errors.InvalidEncoding(encodingParam as string);\n\t}\n\n\treturn result.data;\n}\n\nexport function getRequestExposeInternalError(_req: Request): boolean {\n\t// Unipmlemented\n\treturn false;\n}\n\nexport function getRequestQuery(c: HonoContext): unknown {\n\t// Get query parameters for actor lookup\n\tconst queryParam = c.req.header(HEADER_ACTOR_QUERY);\n\tif (!queryParam) {\n\t\tloggerWithoutContext().error({ msg: \"missing query parameter\" });\n\t\tthrow new errors.InvalidRequest(\"missing query\");\n\t}\n\n\t// Parse the query JSON and validate with schema\n\ttry {\n\t\tconst parsed = JSON.parse(queryParam);\n\t\treturn parsed;\n\t} catch (error) {\n\t\tloggerWithoutContext().error({ msg: \"invalid query json\", error });\n\t\tthrow new errors.InvalidQueryJSON(error);\n\t}\n}\n\n// Helper to get connection parameters for the request\nexport function getRequestConnParams(req: HonoRequest): unknown {\n\tconst paramsParam = req.header(HEADER_CONN_PARAMS);\n\tif (!paramsParam) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\treturn JSON.parse(paramsParam);\n\t} catch (err) {\n\t\tthrow new errors.InvalidParams(\n\t\t\t`Invalid params JSON: ${stringifyError(err)}`,\n\t\t);\n\t}\n}\n","import { getLogger } from \"@/common/log\";\n\nexport function logger() {\n\treturn getLogger(\"actor-manager\");\n}\n","import type { WSContext } from \"hono/ws\";\nimport type {\n\tRivetCloseEvent,\n\tRivetEvent,\n\tRivetMessageEvent,\n\tUniversalWebSocket,\n} from \"@/common/websocket-interface\";\nimport { logger } from \"./log\";\n\n/**\n * HonoWebSocketAdapter provides a WebSocket-like interface over WSContext\n * for raw WebSocket handling in actors\n */\nexport class HonoWebSocketAdapter implements UniversalWebSocket {\n\t// WebSocket readyState values\n\treadonly CONNECTING = 0 as const;\n\treadonly OPEN = 1 as const;\n\treadonly CLOSING = 2 as const;\n\treadonly CLOSED = 3 as const;\n\n\t#ws: WSContext;\n\t#readyState: 0 | 1 | 2 | 3 = 1; // Start as OPEN since WSContext is already connected\n\t#eventListeners: Map<string, Set<(event: any) => void>> = new Map();\n\t#closeCode?: number;\n\t#closeReason?: string;\n\n\tconstructor(ws: WSContext) {\n\t\tthis.#ws = ws;\n\n\t\t// The WSContext is already open when we receive it\n\t\tthis.#readyState = this.OPEN;\n\n\t\t// Immediately fire the open event\n\t\tsetTimeout(() => {\n\t\t\tthis.#fireEvent(\"open\", { type: \"open\", target: this });\n\t\t}, 0);\n\t}\n\n\tget readyState(): 0 | 1 | 2 | 3 {\n\t\treturn this.#readyState;\n\t}\n\n\tget binaryType(): \"arraybuffer\" | \"blob\" {\n\t\treturn \"arraybuffer\";\n\t}\n\n\tset binaryType(value: \"arraybuffer\" | \"blob\") {\n\t\t// Ignored for now - always use arraybuffer\n\t}\n\n\tget bufferedAmount(): number {\n\t\treturn 0; // Not tracked in WSContext\n\t}\n\n\tget extensions(): string {\n\t\treturn \"\"; // Not available in WSContext\n\t}\n\n\tget protocol(): string {\n\t\treturn \"\"; // Not available in WSContext\n\t}\n\n\tget url(): string {\n\t\treturn \"\"; // Not available in WSContext\n\t}\n\n\tsend(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n\t\tif (this.readyState !== this.OPEN) {\n\t\t\tthrow new Error(\"WebSocket is not open\");\n\t\t}\n\n\t\ttry {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"bridge sending data\",\n\t\t\t\tdataType: typeof data,\n\t\t\t\tisString: typeof data === \"string\",\n\t\t\t\tisArrayBuffer: data instanceof ArrayBuffer,\n\t\t\t\tdataStr:\n\t\t\t\t\ttypeof data === \"string\" ? data.substring(0, 100) : \"<non-string>\",\n\t\t\t});\n\n\t\t\tif (typeof data === \"string\") {\n\t\t\t\t(this.#ws as any).send(data);\n\t\t\t} else if (data instanceof ArrayBuffer) {\n\t\t\t\t(this.#ws as any).send(data);\n\t\t\t} else if (ArrayBuffer.isView(data)) {\n\t\t\t\t// Convert ArrayBufferView to ArrayBuffer\n\t\t\t\tconst buffer = data.buffer.slice(\n\t\t\t\t\tdata.byteOffset,\n\t\t\t\t\tdata.byteOffset + data.byteLength,\n\t\t\t\t);\n\t\t\t\t// Check if it's a SharedArrayBuffer and convert to ArrayBuffer\n\t\t\t\tif (buffer instanceof SharedArrayBuffer) {\n\t\t\t\t\tconst arrayBuffer = new ArrayBuffer(buffer.byteLength);\n\t\t\t\t\tnew Uint8Array(arrayBuffer).set(new Uint8Array(buffer));\n\t\t\t\t\t(this.#ws as any).send(arrayBuffer);\n\t\t\t\t} else {\n\t\t\t\t\t(this.#ws as any).send(buffer);\n\t\t\t\t}\n\t\t\t} else if (data instanceof Blob) {\n\t\t\t\t// Convert Blob to ArrayBuffer\n\t\t\t\tdata\n\t\t\t\t\t.arrayBuffer()\n\t\t\t\t\t.then((buffer) => {\n\t\t\t\t\t\t(this.#ws as any).send(buffer);\n\t\t\t\t\t})\n\t\t\t\t\t.catch((error) => {\n\t\t\t\t\t\tlogger().error({\n\t\t\t\t\t\t\tmsg: \"failed to convert blob to arraybuffer\",\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.#fireEvent(\"error\", { type: \"error\", target: this, error });\n\t\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// Try to convert to string as a fallback\n\t\t\t\tlogger().warn({\n\t\t\t\t\tmsg: \"unsupported data type, converting to string\",\n\t\t\t\t\tdataType: typeof data,\n\t\t\t\t\tdata,\n\t\t\t\t});\n\t\t\t\t(this.#ws as any).send(String(data));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger().error({ msg: \"error sending websocket data\", error });\n\t\t\tthis.#fireEvent(\"error\", { type: \"error\", target: this, error });\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tclose(code = 1000, reason = \"\"): void {\n\t\tif (this.readyState === this.CLOSING || this.readyState === this.CLOSED) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#readyState = this.CLOSING;\n\t\tthis.#closeCode = code;\n\t\tthis.#closeReason = reason;\n\n\t\ttry {\n\t\t\t(this.#ws as any).close(code, reason);\n\n\t\t\t// Update state and fire close event\n\t\t\tthis.#readyState = this.CLOSED;\n\t\t\tthis.#fireEvent(\"close\", {\n\t\t\t\ttype: \"close\",\n\t\t\t\ttarget: this,\n\t\t\t\tcode,\n\t\t\t\treason,\n\t\t\t\twasClean: code === 1000,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger().error({ msg: \"error closing websocket\", error });\n\t\t\tthis.#readyState = this.CLOSED;\n\t\t\tthis.#fireEvent(\"close\", {\n\t\t\t\ttype: \"close\",\n\t\t\t\ttarget: this,\n\t\t\t\tcode: 1006,\n\t\t\t\treason: \"Abnormal closure\",\n\t\t\t\twasClean: false,\n\t\t\t});\n\t\t}\n\t}\n\n\taddEventListener(type: string, listener: (event: any) => void): void {\n\t\tif (!this.#eventListeners.has(type)) {\n\t\t\tthis.#eventListeners.set(type, new Set());\n\t\t}\n\t\tthis.#eventListeners.get(type)!.add(listener);\n\t}\n\n\tremoveEventListener(type: string, listener: (event: any) => void): void {\n\t\tconst listeners = this.#eventListeners.get(type);\n\t\tif (listeners) {\n\t\t\tlisteners.delete(listener);\n\t\t}\n\t}\n\n\tdispatchEvent(event: RivetEvent): boolean {\n\t\tconst listeners = this.#eventListeners.get(event.type);\n\t\tif (listeners) {\n\t\t\tfor (const listener of listeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(event);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger().error({\n\t\t\t\t\t\tmsg: `error in ${event.type} event listener`,\n\t\t\t\t\t\terror,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Internal method to handle incoming messages from WSContext\n\t_handleMessage(data: any): void {\n\t\t// Hono may pass either raw data or a MessageEvent-like object\n\t\tlet messageData: string | ArrayBuffer | ArrayBufferView;\n\n\t\tif (typeof data === \"string\") {\n\t\t\tmessageData = data;\n\t\t} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n\t\t\tmessageData = data;\n\t\t} else if (data && typeof data === \"object\" && \"data\" in data) {\n\t\t\t// Handle MessageEvent-like objects\n\t\t\tmessageData = data.data;\n\t\t} else {\n\t\t\t// Fallback - shouldn't happen in normal operation\n\t\t\tmessageData = String(data);\n\t\t}\n\n\t\tlogger().debug({\n\t\t\tmsg: \"bridge handling message\",\n\t\t\tdataType: typeof messageData,\n\t\t\tisArrayBuffer: messageData instanceof ArrayBuffer,\n\t\t\tdataStr: typeof messageData === \"string\" ? messageData : \"<binary>\",\n\t\t});\n\n\t\tthis.#fireEvent(\"message\", {\n\t\t\ttype: \"message\",\n\t\t\ttarget: this,\n\t\t\tdata: messageData,\n\t\t});\n\t}\n\n\t// Internal method to handle close from WSContext\n\t_handleClose(code: number, reason: string): void {\n\t\t// HACK: Close socket in order to fix bug with Cloudflare leaving WS in closing state\n\t\t// https://github.com/cloudflare/workerd/issues/2569\n\t\t(this.#ws as any).close(1000, \"hack_force_close\");\n\n\t\tif (this.readyState === this.CLOSED) return;\n\n\t\tthis.#readyState = this.CLOSED;\n\t\tthis.#closeCode = code;\n\t\tthis.#closeReason = reason;\n\n\t\tthis.#fireEvent(\"close\", {\n\t\t\ttype: \"close\",\n\t\t\ttarget: this,\n\t\t\tcode,\n\t\t\treason,\n\t\t\twasClean: code === 1000,\n\t\t});\n\t}\n\n\t// Internal method to handle errors from WSContext\n\t_handleError(error: any): void {\n\t\tthis.#fireEvent(\"error\", {\n\t\t\ttype: \"error\",\n\t\t\ttarget: this,\n\t\t\terror,\n\t\t});\n\t}\n\n\t#fireEvent(type: string, event: any): void {\n\t\tconst listeners = this.#eventListeners.get(type);\n\t\tif (listeners) {\n\t\t\tfor (const listener of listeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(event);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger().error({ msg: `error in ${type} event listener`, error });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Also check for on* properties\n\t\tswitch (type) {\n\t\t\tcase \"open\":\n\t\t\t\tif (this.#onopen) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onopen(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onopen handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"close\":\n\t\t\t\tif (this.#onclose) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onclose(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onclose handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"error\":\n\t\t\t\tif (this.#onerror) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onerror(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onerror handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"message\":\n\t\t\t\tif (this.#onmessage) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onmessage(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onmessage handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Event handler properties with getters/setters\n\t#onopen: ((event: RivetEvent) => void) | null = null;\n\t#onclose: ((event: RivetCloseEvent) => void) | null = null;\n\t#onerror: ((event: RivetEvent) => void) | null = null;\n\t#onmessage: ((event: RivetMessageEvent) => void) | null = null;\n\n\tget onopen(): ((event: RivetEvent) => void) | null {\n\t\treturn this.#onopen;\n\t}\n\tset onopen(handler: ((event: RivetEvent) => void) | null) {\n\t\tthis.#onopen = handler;\n\t}\n\n\tget onclose(): ((event: RivetCloseEvent) => void) | null {\n\t\treturn this.#onclose;\n\t}\n\tset onclose(handler: ((event: RivetCloseEvent) => void) | null) {\n\t\tthis.#onclose = handler;\n\t}\n\n\tget onerror(): ((event: RivetEvent) => void) | null {\n\t\treturn this.#onerror;\n\t}\n\tset onerror(handler: ((event: RivetEvent) => void) | null) {\n\t\tthis.#onerror = handler;\n\t}\n\n\tget onmessage(): ((event: RivetMessageEvent) => void) | null {\n\t\treturn this.#onmessage;\n\t}\n\tset onmessage(handler: ((event: RivetMessageEvent) => void) | null) {\n\t\tthis.#onmessage = handler;\n\t}\n}\n","import * as cbor from \"cbor-x\";\nimport type { Context as HonoContext, Next } from \"hono\";\nimport type { Encoding } from \"@/actor/protocol/serde\";\nimport {\n\tgetRequestEncoding,\n\tgetRequestExposeInternalError,\n} from \"@/actor/router-endpoints\";\nimport { HttpResponseError } from \"@/schemas/client-protocol/mod\";\nimport { HTTP_RESPONSE_ERROR_VERSIONED } from \"@/schemas/client-protocol/versioned\";\nimport { encodingIsBinary, serializeWithEncoding } from \"@/serde\";\nimport { bufferToArrayBuffer } from \"@/utils\";\nimport { getLogger, type Logger } from \"./log\";\nimport { deconstructError, stringifyError } from \"./utils\";\n\nexport function logger() {\n\treturn getLogger(\"router\");\n}\n\nexport function loggerMiddleware(logger: Logger) {\n\treturn async (c: HonoContext, next: Next) => {\n\t\tconst method = c.req.method;\n\t\tconst path = c.req.path;\n\t\tconst startTime = Date.now();\n\n\t\tawait next();\n\n\t\tconst duration = Date.now() - startTime;\n\t\tlogger.debug({\n\t\t\tmsg: \"http request\",\n\t\t\tmethod,\n\t\t\tpath,\n\t\t\tstatus: c.res.status,\n\t\t\tdt: `${duration}ms`,\n\t\t\treqSize: c.req.header(\"content-length\"),\n\t\t\tresSize: c.res.headers.get(\"content-length\"),\n\t\t\tuserAgent: c.req.header(\"user-agent\"),\n\t\t});\n\t};\n}\n\nexport function handleRouteNotFound(c: HonoContext) {\n\treturn c.text(\"Not Found (RivetKit)\", 404);\n}\n\nexport function handleRouteError(error: unknown, c: HonoContext) {\n\tconst exposeInternalError = getRequestExposeInternalError(c.req.raw);\n\n\tconst { statusCode, group, code, message, metadata } = deconstructError(\n\t\terror,\n\t\tlogger(),\n\t\t{\n\t\t\tmethod: c.req.method,\n\t\t\tpath: c.req.path,\n\t\t},\n\t\texposeInternalError,\n\t);\n\n\tlet encoding: Encoding;\n\ttry {\n\t\tencoding = getRequestEncoding(c.req);\n\t} catch (_) {\n\t\tencoding = \"json\";\n\t}\n\n\tconst output = serializeWithEncoding(\n\t\tencoding,\n\t\t{\n\t\t\tgroup,\n\t\t\tcode,\n\t\t\tmessage,\n\t\t\t// TODO: Cannot serialize non-binary meta since it requires ArrayBuffer atm\n\t\t\tmetadata: encodingIsBinary(encoding)\n\t\t\t\t? bufferToArrayBuffer(cbor.encode(metadata))\n\t\t\t\t: null,\n\t\t},\n\t\tHTTP_RESPONSE_ERROR_VERSIONED,\n\t);\n\n\t// TODO: Remove any\n\treturn c.body(output as any, { status: statusCode });\n}\n","import {\n\ttype Actions,\n\ttype ActorConfig,\n\ttype ActorConfigInput,\n\tActorConfigSchema,\n\tActorTypes,\n} from \"./config\";\nimport type { AnyDatabaseProvider } from \"./database\";\nimport { ActorDefinition } from \"./definition\";\n\nexport function actor<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase extends AnyDatabaseProvider,\n\tTActions extends Actions<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase\n\t>,\n>(\n\tinput: ActorConfigInput<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase,\n\t\tTActions\n\t>,\n): ActorDefinition<\n\tTState,\n\tTConnParams,\n\tTConnState,\n\tTVars,\n\tTInput,\n\tTDatabase,\n\tTActions\n> {\n\tconst config = ActorConfigSchema.parse(input) as ActorConfig<\n\t\tTState,\n\t\tTConnParams,\n\t\tTConnState,\n\t\tTVars,\n\t\tTInput,\n\t\tTDatabase\n\t>;\n\treturn new ActorDefinition(config);\n}\nexport type { Encoding } from \"@/actor/protocol/serde\";\nexport {\n\tALLOWED_PUBLIC_HEADERS,\n\tPATH_CONNECT_WEBSOCKET,\n\tPATH_RAW_WEBSOCKET_PREFIX,\n} from \"@/common/actor-router-consts\";\nexport type {\n\tUniversalErrorEvent,\n\tUniversalEvent,\n\tUniversalEventSource,\n\tUniversalMessageEvent,\n} from \"@/common/eventsource-interface\";\nexport type { UpgradeWebSocketArgs } from \"@/common/inline-websocket-adapter2\";\nexport type {\n\tRivetCloseEvent,\n\tRivetEvent,\n\tRivetMessageEvent,\n\tUniversalWebSocket,\n} from \"@/common/websocket-interface\";\nexport type { ActorKey } from \"@/manager/protocol/query\";\nexport type { ActionContext } from \"./action\";\nexport type * from \"./config\";\nexport type {\n\tConn,\n\tConnectionStatus,\n\tgenerateConnId,\n\tgenerateConnToken,\n} from \"./conn\";\nexport type { ActorContext } from \"./context\";\nexport type {\n\tActionContextOf,\n\tActorContextOf,\n\tActorDefinition,\n\tAnyActorDefinition,\n} from \"./definition\";\nexport { lookupInRegistry } from \"./definition\";\nexport { UserError, type UserErrorOptions } from \"./errors\";\nexport type { AnyActorInstance } from \"./instance\";\nexport {\n\ttype ActorRouter,\n\tcreateActorRouter,\n} from \"./router\";\nexport {\n\thandleRawWebSocketHandler,\n\thandleWebSocketConnect,\n} from \"./router-endpoints\";\n","import { WSContext } from \"hono/ws\";\nimport type {\n\tRivetCloseEvent,\n\tRivetEvent,\n\tRivetMessageEvent,\n\tUniversalWebSocket,\n} from \"@/common/websocket-interface\";\nimport { getLogger } from \"./log\";\n\nexport function logger() {\n\treturn getLogger(\"fake-event-source2\");\n}\n\n// TODO: Merge with ConnectWebSocketOutput interface\nexport interface UpgradeWebSocketArgs {\n\tonOpen: (event: any, ws: WSContext) => void;\n\tonMessage: (event: any, ws: WSContext) => void;\n\tonClose: (event: any, ws: WSContext) => void;\n\tonError: (error: any, ws: WSContext) => void;\n}\n\n// TODO: Remove `2` suffix\n/**\n * InlineWebSocketAdapter implements a WebSocket-like interface\n * that connects to a UpgradeWebSocketArgs handler\n */\nexport class InlineWebSocketAdapter2 implements UniversalWebSocket {\n\t// WebSocket readyState values\n\treadonly CONNECTING = 0 as const;\n\treadonly OPEN = 1 as const;\n\treadonly CLOSING = 2 as const;\n\treadonly CLOSED = 3 as const;\n\n\t// Private properties\n\t#handler: UpgradeWebSocketArgs;\n\t#wsContext: WSContext;\n\t#readyState: 0 | 1 | 2 | 3 = 0; // Start in CONNECTING state\n\t#queuedMessages: Array<string | ArrayBuffer | Uint8Array> = [];\n\t// Event buffering is needed since events can be fired\n\t// before JavaScript has a chance to add event listeners (e.g. within the same tick)\n\t#bufferedEvents: Array<{\n\t\ttype: string;\n\t\tevent: any;\n\t}> = [];\n\n\t// Event listeners with buffering\n\t#eventListeners: Map<string, ((ev: any) => void)[]> = new Map();\n\n\tconstructor(handler: UpgradeWebSocketArgs) {\n\t\tthis.#handler = handler;\n\n\t\t// Create a fake WSContext to pass to the handler\n\t\tthis.#wsContext = new WSContext({\n\t\t\traw: this,\n\t\t\tsend: (data: string | ArrayBuffer | Uint8Array) => {\n\t\t\t\tlogger().debug({ msg: \"WSContext.send called\" });\n\t\t\t\tthis.#handleMessage(data);\n\t\t\t},\n\t\t\tclose: (code?: number, reason?: string) => {\n\t\t\t\tlogger().debug({ msg: \"WSContext.close called\", code, reason });\n\t\t\t\tthis.#handleClose(code || 1000, reason || \"\");\n\t\t\t},\n\t\t\t// Set readyState to 1 (OPEN) since handlers expect an open connection\n\t\t\treadyState: 1,\n\t\t});\n\n\t\t// Initialize the connection\n\t\tthis.#initialize();\n\t}\n\n\tget readyState(): 0 | 1 | 2 | 3 {\n\t\treturn this.#readyState;\n\t}\n\n\tget binaryType(): \"arraybuffer\" | \"blob\" {\n\t\treturn \"arraybuffer\";\n\t}\n\n\tset binaryType(value: \"arraybuffer\" | \"blob\") {\n\t\t// Ignored for now - always use arraybuffer\n\t}\n\n\tget bufferedAmount(): number {\n\t\treturn 0; // Not tracked in InlineWebSocketAdapter\n\t}\n\n\tget extensions(): string {\n\t\treturn \"\"; // Not available in InlineWebSocketAdapter\n\t}\n\n\tget protocol(): string {\n\t\treturn \"\"; // Not available in InlineWebSocketAdapter\n\t}\n\n\tget url(): string {\n\t\treturn \"\"; // Not available in InlineWebSocketAdapter\n\t}\n\n\tsend(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n\t\tlogger().debug({ msg: \"send called\", readyState: this.readyState });\n\n\t\tif (this.readyState !== this.OPEN) {\n\t\t\tconst error = new Error(\"WebSocket is not open\");\n\t\t\tlogger().warn({\n\t\t\t\tmsg: \"cannot send message, websocket not open\",\n\t\t\t\treadyState: this.readyState,\n\t\t\t\tdataType: typeof data,\n\t\t\t\tdataLength: typeof data === \"string\" ? data.length : \"binary\",\n\t\t\t\terror,\n\t\t\t});\n\t\t\tthis.#fireError(error);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#handler.onMessage({ data }, this.#wsContext);\n\t}\n\n\t/**\n\t * Closes the connection\n\t */\n\tclose(code = 1000, reason = \"\"): void {\n\t\tif (this.readyState === this.CLOSED || this.readyState === this.CLOSING) {\n\t\t\treturn;\n\t\t}\n\n\t\tlogger().debug({ msg: \"closing fake websocket\", code, reason });\n\n\t\tthis.#readyState = this.CLOSING;\n\n\t\t// Call the handler's onClose method\n\t\ttry {\n\t\t\tthis.#handler.onClose({ code, reason, wasClean: true }, this.#wsContext);\n\t\t} catch (err) {\n\t\t\tlogger().error({ msg: \"error closing websocket\", error: err });\n\t\t} finally {\n\t\t\tthis.#readyState = this.CLOSED;\n\n\t\t\t// Fire the close event\n\t\t\t// Create a close event object since CloseEvent is not available in Node.js\n\t\t\tconst closeEvent = {\n\t\t\t\ttype: \"close\",\n\t\t\t\twasClean: code === 1000,\n\t\t\t\tcode,\n\t\t\t\treason,\n\t\t\t\ttarget: this,\n\t\t\t\tcurrentTarget: this,\n\t\t\t} as unknown as RivetCloseEvent;\n\n\t\t\tthis.#fireClose(closeEvent);\n\t\t}\n\t}\n\n\t/**\n\t * Initialize the connection with the handler\n\t */\n\tasync #initialize(): Promise<void> {\n\t\ttry {\n\t\t\tlogger().debug({ msg: \"fake websocket initializing\" });\n\n\t\t\t// Call the handler's onOpen method\n\t\t\tlogger().debug({ msg: \"calling handler.onOpen with WSContext\" });\n\t\t\tthis.#handler.onOpen(undefined, this.#wsContext);\n\n\t\t\t// Update the ready state and fire events\n\t\t\tthis.#readyState = this.OPEN;\n\t\t\tlogger().debug({ msg: \"fake websocket initialized and now OPEN\" });\n\n\t\t\t// Fire the open event\n\t\t\tthis.#fireOpen();\n\n\t\t\t// Delay processing queued messages slightly to allow event handlers to be set up\n\t\t\tif (this.#queuedMessages.length > 0) {\n\t\t\t\tif (this.readyState !== this.OPEN) {\n\t\t\t\t\tlogger().warn({\n\t\t\t\t\t\tmsg: \"socket no longer open, dropping queued messages\",\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: `now processing ${this.#queuedMessages.length} queued messages`,\n\t\t\t\t});\n\n\t\t\t\t// Create a copy to avoid issues if new messages arrive during processing\n\t\t\t\tconst messagesToProcess = [...this.#queuedMessages];\n\t\t\t\tthis.#queuedMessages = [];\n\n\t\t\t\t// Process each queued message\n\t\t\t\tfor (const message of messagesToProcess) {\n\t\t\t\t\tlogger().debug({ msg: \"processing queued message\" });\n\t\t\t\t\tthis.#handleMessage(message);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger().error({\n\t\t\t\tmsg: \"error opening fake websocket\",\n\t\t\t\terror: err,\n\t\t\t\terrorMessage: err instanceof Error ? err.message : String(err),\n\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t});\n\t\t\tthis.#fireError(err);\n\t\t\tthis.close(1011, \"Internal error during initialization\");\n\t\t}\n\t}\n\n\t/**\n\t * Handle messages received from the server via the WSContext\n\t */\n\t#handleMessage(data: string | ArrayBuffer | Uint8Array): void {\n\t\t// Store messages that arrive before the socket is fully initialized\n\t\tif (this.readyState !== this.OPEN) {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"message received before socket is OPEN, queuing\",\n\t\t\t\treadyState: this.readyState,\n\t\t\t\tdataType: typeof data,\n\t\t\t\tdataLength:\n\t\t\t\t\ttypeof data === \"string\"\n\t\t\t\t\t\t? data.length\n\t\t\t\t\t\t: data instanceof ArrayBuffer\n\t\t\t\t\t\t\t? data.byteLength\n\t\t\t\t\t\t\t: data instanceof Uint8Array\n\t\t\t\t\t\t\t\t? data.byteLength\n\t\t\t\t\t\t\t\t: \"unknown\",\n\t\t\t});\n\n\t\t\t// Queue the message to be processed once the socket is open\n\t\t\tthis.#queuedMessages.push(data);\n\t\t\treturn;\n\t\t}\n\n\t\t// Log message received from server\n\t\tlogger().debug({\n\t\t\tmsg: \"fake websocket received message from server\",\n\t\t\tdataType: typeof data,\n\t\t\tdataLength:\n\t\t\t\ttypeof data === \"string\"\n\t\t\t\t\t? data.length\n\t\t\t\t\t: data instanceof ArrayBuffer\n\t\t\t\t\t\t? data.byteLength\n\t\t\t\t\t\t: data instanceof Uint8Array\n\t\t\t\t\t\t\t? data.byteLength\n\t\t\t\t\t\t\t: \"unknown\",\n\t\t});\n\n\t\t// Create a MessageEvent-like object\n\t\tconst event = {\n\t\t\ttype: \"message\",\n\t\t\tdata,\n\t\t\ttarget: this,\n\t\t\tcurrentTarget: this,\n\t\t} as unknown as RivetMessageEvent;\n\n\t\t// Dispatch the event\n\t\tthis.#dispatchEvent(\"message\", event);\n\t}\n\n\t#handleClose(code: number, reason: string): void {\n\t\tif (this.readyState === this.CLOSED) return;\n\n\t\tthis.#readyState = this.CLOSED;\n\n\t\t// Create a CloseEvent-like object\n\t\tconst event = {\n\t\t\ttype: \"close\",\n\t\t\tcode,\n\t\t\treason,\n\t\t\twasClean: code === 1000,\n\t\t\ttarget: this,\n\t\t\tcurrentTarget: this,\n\t\t} as unknown as RivetCloseEvent;\n\n\t\t// Dispatch the event\n\t\tthis.#dispatchEvent(\"close\", event);\n\t}\n\n\taddEventListener(type: string, listener: (ev: any) => void): void {\n\t\tif (!this.#eventListeners.has(type)) {\n\t\t\tthis.#eventListeners.set(type, []);\n\t\t}\n\t\tthis.#eventListeners.get(type)!.push(listener);\n\n\t\t// Flush any buffered events for this type\n\t\tthis.#flushBufferedEvents(type);\n\t}\n\n\tremoveEventListener(type: string, listener: (ev: any) => void): void {\n\t\tconst listeners = this.#eventListeners.get(type);\n\t\tif (listeners) {\n\t\t\tconst index = listeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tlisteners.splice(index, 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t#dispatchEvent(type: string, event: any): void {\n\t\tconst listeners = this.#eventListeners.get(type);\n\t\tif (listeners && listeners.length > 0) {\n\t\t\tlogger().debug(\n\t\t\t\t`dispatching ${type} event to ${listeners.length} listeners`,\n\t\t\t);\n\t\t\tfor (const listener of listeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(event);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger().error({\n\t\t\t\t\t\tmsg: `error in ${type} event listener`,\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: `no ${type} listeners registered, buffering event`,\n\t\t\t});\n\t\t\tthis.#bufferedEvents.push({ type, event });\n\t\t}\n\n\t\t// Also check for on* properties\n\t\tswitch (type) {\n\t\t\tcase \"open\":\n\t\t\t\tif (this.#onopen) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onopen(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onopen handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"close\":\n\t\t\t\tif (this.#onclose) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onclose(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onclose handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"error\":\n\t\t\t\tif (this.#onerror) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onerror(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onerror handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"message\":\n\t\t\t\tif (this.#onmessage) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#onmessage(event);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger().error({ msg: \"error in onmessage handler\", error });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tdispatchEvent(event: RivetEvent): boolean {\n\t\tthis.#dispatchEvent(event.type, event);\n\t\treturn true;\n\t}\n\n\t#flushBufferedEvents(type: string): void {\n\t\tconst eventsToFlush = this.#bufferedEvents.filter(\n\t\t\t(buffered) => buffered.type === type,\n\t\t);\n\t\tthis.#bufferedEvents = this.#bufferedEvents.filter(\n\t\t\t(buffered) => buffered.type !== type,\n\t\t);\n\n\t\tfor (const { event } of eventsToFlush) {\n\t\t\tthis.#dispatchEvent(type, event);\n\t\t}\n\t}\n\n\t#fireOpen(): void {\n\t\ttry {\n\t\t\t// Create an Event-like object since Event constructor may not be available\n\t\t\tconst event = {\n\t\t\t\ttype: \"open\",\n\t\t\t\ttarget: this,\n\t\t\t\tcurrentTarget: this,\n\t\t\t} as unknown as RivetEvent;\n\n\t\t\tthis.#dispatchEvent(\"open\", event);\n\t\t} catch (err) {\n\t\t\tlogger().error({ msg: \"error in open event\", error: err });\n\t\t}\n\t}\n\n\t#fireClose(event: RivetCloseEvent): void {\n\t\ttry {\n\t\t\tthis.#dispatchEvent(\"close\", event);\n\t\t} catch (err) {\n\t\t\tlogger().error({ msg: \"error in close event\", error: err });\n\t\t}\n\t}\n\n\t#fireError(error: unknown): void {\n\t\ttry {\n\t\t\t// Create an Event-like object for error\n\t\t\tconst event = {\n\t\t\t\ttype: \"error\",\n\t\t\t\ttarget: this,\n\t\t\t\tcurrentTarget: this,\n\t\t\t\terror,\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t} as unknown as RivetEvent;\n\n\t\t\tthis.#dispatchEvent(\"error\", event);\n\t\t} catch (err) {\n\t\t\tlogger().error({ msg: \"error in error event\", error: err });\n\t\t}\n\n\t\t// Log the error\n\t\tlogger().error({ msg: \"websocket error\", error });\n\t}\n\n\t// Event handler properties with getters/setters\n\t#onopen: ((event: RivetEvent) => void) | null = null;\n\t#onclose: ((event: RivetCloseEvent) => void) | null = null;\n\t#onerror: ((event: RivetEvent) => void) | null = null;\n\t#onmessage: ((event: RivetMessageEvent) => void) | null = null;\n\n\tget onopen(): ((event: RivetEvent) => void) | null {\n\t\treturn this.#onopen;\n\t}\n\tset onopen(handler: ((event: RivetEvent) => void) | null) {\n\t\tthis.#onopen = handler;\n\t}\n\n\tget onclose(): ((event: RivetCloseEvent) => void) | null {\n\t\treturn this.#onclose;\n\t}\n\tset onclose(handler: ((event: RivetCloseEvent) => void) | null) {\n\t\tthis.#onclose = handler;\n\t}\n\n\tget onerror(): ((event: RivetEvent) => void) | null {\n\t\treturn this.#onerror;\n\t}\n\tset onerror(handler: ((event: RivetEvent) => void) | null) {\n\t\tthis.#onerror = handler;\n\t}\n\n\tget onmessage(): ((event: RivetMessageEvent) => void) | null {\n\t\treturn this.#onmessage;\n\t}\n\tset onmessage(handler: ((event: RivetMessageEvent) => void) | null) {\n\t\tthis.#onmessage = handler;\n\t}\n}\n","import type {\n\tActorConfig as RunnerActorConfig,\n\tRunnerConfig,\n} from \"@rivetkit/engine-runner\";\nimport { Runner } from \"@rivetkit/engine-runner\";\nimport * as cbor from \"cbor-x\";\nimport type { Context as HonoContext } from \"hono\";\nimport { streamSSE } from \"hono/streaming\";\nimport { WSContext } from \"hono/ws\";\nimport invariant from \"invariant\";\nimport { lookupInRegistry } from \"@/actor/definition\";\nimport { deserializeActorKey } from \"@/actor/keys\";\nimport { EncodingSchema } from \"@/actor/protocol/serde\";\nimport { type ActorRouter, createActorRouter } from \"@/actor/router\";\nimport {\n\thandleRawWebSocketHandler,\n\thandleWebSocketConnect,\n} from \"@/actor/router-endpoints\";\nimport type { Client } from \"@/client/client\";\nimport {\n\tPATH_CONNECT_WEBSOCKET,\n\tPATH_RAW_WEBSOCKET_PREFIX,\n\tWS_PROTOCOL_CONN_PARAMS,\n\tWS_PROTOCOL_ENCODING,\n\tWS_PROTOCOL_TOKEN,\n} from \"@/common/actor-router-consts\";\nimport type { UpgradeWebSocketArgs } from \"@/common/inline-websocket-adapter2\";\nimport { getLogger } from \"@/common/log\";\nimport type { UniversalWebSocket } from \"@/common/websocket-interface\";\nimport {\n\ttype ActorDriver,\n\ttype AnyActorInstance,\n\ttype ManagerDriver,\n\tserializeEmptyPersistData,\n} from \"@/driver-helpers/mod\";\nimport type { RegistryConfig } from \"@/registry/config\";\nimport type { RunConfig } from \"@/registry/run-config\";\nimport { promiseWithResolvers } from \"@/utils\";\nimport type { Config } from \"./config\";\nimport { KEYS } from \"./kv\";\nimport { logger } from \"./log\";\n\ninterface ActorHandler {\n\tactor?: AnyActorInstance;\n\tactorStartPromise?: ReturnType<typeof promiseWithResolvers<void>>;\n\tpersistedData?: Uint8Array;\n}\n\nexport type DriverContext = {};\n\nexport class EngineActorDriver implements ActorDriver {\n\t#registryConfig: RegistryConfig;\n\t#runConfig: RunConfig;\n\t#managerDriver: ManagerDriver;\n\t#inlineClient: Client<any>;\n\t#config: Config;\n\t#runner: Runner;\n\t#actors: Map<string, ActorHandler> = new Map();\n\t#actorRouter: ActorRouter;\n\t#version: number = 1; // Version for the runner protocol\n\n\t#runnerStarted: PromiseWithResolvers<undefined> = Promise.withResolvers();\n\t#runnerStopped: PromiseWithResolvers<undefined> = Promise.withResolvers();\n\n\tconstructor(\n\t\tregistryConfig: RegistryConfig,\n\t\trunConfig: RunConfig,\n\t\tmanagerDriver: ManagerDriver,\n\t\tinlineClient: Client<any>,\n\t\tconfig: Config,\n\t) {\n\t\tthis.#registryConfig = registryConfig;\n\t\tthis.#runConfig = runConfig;\n\t\tthis.#managerDriver = managerDriver;\n\t\tthis.#inlineClient = inlineClient;\n\t\tthis.#config = config;\n\t\tthis.#actorRouter = createActorRouter(runConfig, this);\n\n\t\t// Create runner configuration\n\t\tlet hasDisconnected = false;\n\t\tconst runnerConfig: RunnerConfig = {\n\t\t\tversion: this.#version,\n\t\t\tendpoint: config.endpoint,\n\t\t\ttoken: config.token,\n\t\t\tpegboardEndpoint: config.pegboardEndpoint,\n\t\t\tnamespace: config.namespace,\n\t\t\ttotalSlots: config.totalSlots,\n\t\t\trunnerName: config.runnerName,\n\t\t\trunnerKey: config.runnerKey,\n\t\t\tmetadata: {\n\t\t\t\tinspectorToken: this.#runConfig.inspector.token(),\n\t\t\t},\n\t\t\tprepopulateActorNames: Object.fromEntries(\n\t\t\t\tObject.keys(this.#registryConfig.use).map((name) => [\n\t\t\t\t\tname,\n\t\t\t\t\t{ metadata: {} },\n\t\t\t\t]),\n\t\t\t),\n\t\t\tonConnected: () => {\n\t\t\t\tif (hasDisconnected) {\n\t\t\t\t\tlogger().info({\n\t\t\t\t\t\tmsg: \"runner reconnected\",\n\t\t\t\t\t\tnamespace: this.#config.namespace,\n\t\t\t\t\t\trunnerName: this.#config.runnerName,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\tmsg: \"runner connected\",\n\t\t\t\t\t\tnamespace: this.#config.namespace,\n\t\t\t\t\t\trunnerName: this.#config.runnerName,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tthis.#runnerStarted.resolve(undefined);\n\t\t\t},\n\t\t\tonDisconnected: () => {\n\t\t\t\tlogger().warn({\n\t\t\t\t\tmsg: \"runner disconnected\",\n\t\t\t\t\tnamespace: this.#config.namespace,\n\t\t\t\t\trunnerName: this.#config.runnerName,\n\t\t\t\t});\n\t\t\t\thasDisconnected = true;\n\t\t\t},\n\t\t\tonShutdown: () => {\n\t\t\t\tthis.#runnerStopped.resolve(undefined);\n\t\t\t},\n\t\t\tfetch: this.#runnerFetch.bind(this),\n\t\t\twebsocket: this.#runnerWebSocket.bind(this),\n\t\t\tonActorStart: this.#runnerOnActorStart.bind(this),\n\t\t\tonActorStop: this.#runnerOnActorStop.bind(this),\n\t\t\tlogger: getLogger(\"engine-runner\"),\n\t\t};\n\n\t\t// Create and start runner\n\t\tthis.#runner = new Runner(runnerConfig);\n\t\tthis.#runner.start();\n\t\tlogger().debug({\n\t\t\tmsg: \"engine runner started\",\n\t\t\tendpoint: config.endpoint,\n\t\t\tnamespace: config.namespace,\n\t\t\trunnerName: config.runnerName,\n\t\t});\n\t}\n\n\tasync #loadActorHandler(actorId: string): Promise<ActorHandler> {\n\t\t// Check if actor is already loaded\n\t\tconst handler = this.#actors.get(actorId);\n\t\tif (!handler) throw new Error(`Actor handler does not exist ${actorId}`);\n\t\tif (handler.actorStartPromise) await handler.actorStartPromise.promise;\n\t\tif (!handler.actor) throw new Error(\"Actor should be loaded\");\n\t\treturn handler;\n\t}\n\n\tasync loadActor(actorId: string): Promise<AnyActorInstance> {\n\t\tconst handler = await this.#loadActorHandler(actorId);\n\t\tif (!handler.actor) throw new Error(`Actor ${actorId} failed to load`);\n\t\treturn handler.actor;\n\t}\n\n\tgetContext(actorId: string): DriverContext {\n\t\treturn {};\n\t}\n\n\tasync readPersistedData(actorId: string): Promise<Uint8Array | undefined> {\n\t\tconst handler = this.#actors.get(actorId);\n\t\tif (!handler) throw new Error(`Actor ${actorId} not loaded`);\n\t\tif (handler.persistedData) return handler.persistedData;\n\n\t\tconst [value] = await this.#runner.kvGet(actorId, [KEYS.PERSIST_DATA]);\n\n\t\tif (value !== null) {\n\t\t\thandler.persistedData = value;\n\t\t\treturn value;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tasync writePersistedData(actorId: string, data: Uint8Array): Promise<void> {\n\t\tconst handler = this.#actors.get(actorId);\n\t\tif (!handler) throw new Error(`Actor ${actorId} not loaded`);\n\n\t\thandler.persistedData = data;\n\n\t\tawait this.#runner.kvPut(actorId, [[KEYS.PERSIST_DATA, data]]);\n\t}\n\n\tasync setAlarm(actor: AnyActorInstance, timestamp: number): Promise<void> {\n\t\t// TODO: Set timeout\n\t\t// TODO: Use alarm on sleep\n\t\t// TODO: Send alarm to runner\n\t}\n\n\tasync getDatabase(_actorId: string): Promise<unknown | undefined> {\n\t\treturn undefined;\n\t}\n\n\t// Runner lifecycle callbacks\n\tasync #runnerOnActorStart(\n\t\tactorId: string,\n\t\tgeneration: number,\n\t\tconfig: RunnerActorConfig,\n\t): Promise<void> {\n\t\tlogger().debug({\n\t\t\tmsg: \"runner actor starting\",\n\t\t\tactorId,\n\t\t\tname: config.name,\n\t\t\tkey: config.key,\n\t\t\tgeneration,\n\t\t});\n\n\t\t// Deserialize input\n\t\tlet input: any;\n\t\tif (config.input) {\n\t\t\tinput = cbor.decode(config.input);\n\t\t}\n\n\t\t// Get or create handler\n\t\tlet handler = this.#actors.get(actorId);\n\t\tif (!handler) {\n\t\t\thandler = {\n\t\t\t\tactorStartPromise: promiseWithResolvers(),\n\t\t\t\tpersistedData: serializeEmptyPersistData(input),\n\t\t\t};\n\t\t\tthis.#actors.set(actorId, handler);\n\t\t}\n\n\t\tconst name = config.name as string;\n\t\tinvariant(config.key, \"actor should have a key\");\n\t\tconst key = deserializeActorKey(config.key);\n\n\t\t// Create actor instance\n\t\tconst definition = lookupInRegistry(\n\t\t\tthis.#registryConfig,\n\t\t\tconfig.name as string, // TODO: Remove cast\n\t\t);\n\t\thandler.actor = definition.instantiate();\n\n\t\t// Start actor\n\t\tawait handler.actor.start(\n\t\t\tthis,\n\t\t\tthis.#inlineClient,\n\t\t\tactorId,\n\t\t\tname,\n\t\t\tkey,\n\t\t\t\"unknown\", // TODO: Add regions\n\t\t);\n\n\t\t// Resolve promise if waiting\n\t\thandler.actorStartPromise?.resolve();\n\t\thandler.actorStartPromise = undefined;\n\n\t\tlogger().debug({ msg: \"runner actor started\", actorId, name, key });\n\t}\n\n\tasync #runnerOnActorStop(actorId: string, generation: number): Promise<void> {\n\t\tlogger().debug({ msg: \"runner actor stopping\", actorId, generation });\n\n\t\tconst handler = this.#actors.get(actorId);\n\t\tif (handler?.actor) {\n\t\t\tawait handler.actor._stop();\n\t\t\tthis.#actors.delete(actorId);\n\t\t}\n\n\t\tlogger().debug({ msg: \"runner actor stopped\", actorId });\n\t}\n\n\tasync #runnerFetch(actorId: string, request: Request): Promise<Response> {\n\t\tlogger().debug({\n\t\t\tmsg: \"runner fetch\",\n\t\t\tactorId,\n\t\t\turl: request.url,\n\t\t\tmethod: request.method,\n\t\t});\n\t\treturn await this.#actorRouter.fetch(request, { actorId });\n\t}\n\n\tasync #runnerWebSocket(\n\t\tactorId: string,\n\t\twebsocketRaw: any,\n\t\trequest: Request,\n\t): Promise<void> {\n\t\tconst websocket = websocketRaw as UniversalWebSocket;\n\n\t\tlogger().debug({ msg: \"runner websocket\", actorId, url: request.url });\n\n\t\tconst url = new URL(request.url);\n\n\t\t// Parse configuration from Sec-WebSocket-Protocol header\n\t\tconst protocols = request.headers.get(\"sec-websocket-protocol\");\n\t\tif (protocols === null)\n\t\t\tthrow new Error(`Missing sec-websocket-protocol header`);\n\n\t\tlet encodingRaw: string | undefined;\n\t\tlet connParamsRaw: string | undefined;\n\n\t\tif (protocols) {\n\t\t\tconst protocolList = protocols.split(\",\").map((p) => p.trim());\n\t\t\tfor (const protocol of protocolList) {\n\t\t\t\tif (protocol.startsWith(WS_PROTOCOL_ENCODING)) {\n\t\t\t\t\tencodingRaw = protocol.substring(WS_PROTOCOL_ENCODING.length);\n\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_PARAMS)) {\n\t\t\t\t\tconnParamsRaw = decodeURIComponent(\n\t\t\t\t\t\tprotocol.substring(WS_PROTOCOL_CONN_PARAMS.length),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst encoding = EncodingSchema.parse(encodingRaw);\n\t\tconst connParams = connParamsRaw ? JSON.parse(connParamsRaw) : undefined;\n\n\t\t// Fetch WS handler\n\t\t//\n\t\t// We store the promise since we need to add WebSocket event listeners immediately that will wait for the promise to resolve\n\t\tlet wsHandlerPromise: Promise<UpgradeWebSocketArgs>;\n\t\tif (url.pathname === PATH_CONNECT_WEBSOCKET) {\n\t\t\twsHandlerPromise = handleWebSocketConnect(\n\t\t\t\trequest,\n\t\t\t\tthis.#runConfig,\n\t\t\t\tthis,\n\t\t\t\tactorId,\n\t\t\t\tencoding,\n\t\t\t\tconnParams,\n\t\t\t\t// Extract connId and connToken from protocols if needed\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t);\n\t\t} else if (url.pathname.startsWith(PATH_RAW_WEBSOCKET_PREFIX)) {\n\t\t\twsHandlerPromise = handleRawWebSocketHandler(\n\t\t\t\trequest,\n\t\t\t\turl.pathname + url.search,\n\t\t\t\tthis,\n\t\t\t\tactorId,\n\t\t\t);\n\t\t} else {\n\t\t\tthrow new Error(`Unreachable path: ${url.pathname}`);\n\t\t}\n\n\t\t// TODO: Add close\n\n\t\t// Connect the Hono WS hook to the adapter\n\t\tconst wsContext = new WSContext(websocket);\n\n\t\twsHandlerPromise.catch((err) => {\n\t\t\tlogger().error({ msg: \"building websocket handlers errored\", err });\n\t\t\twsContext.close(1011, `${err}`);\n\t\t});\n\n\t\tif (websocket.readyState === 1) {\n\t\t\twsHandlerPromise.then((x) => x.onOpen?.(new Event(\"open\"), wsContext));\n\t\t} else {\n\t\t\twebsocket.addEventListener(\"open\", (event) => {\n\t\t\t\twsHandlerPromise.then((x) => x.onOpen?.(event, wsContext));\n\t\t\t});\n\t\t}\n\n\t\twebsocket.addEventListener(\"message\", (event) => {\n\t\t\twsHandlerPromise.then((x) => x.onMessage?.(event, wsContext));\n\t\t});\n\n\t\twebsocket.addEventListener(\"close\", (event) => {\n\t\t\twsHandlerPromise.then((x) => x.onClose?.(event, wsContext));\n\t\t});\n\n\t\twebsocket.addEventListener(\"error\", (event) => {\n\t\t\twsHandlerPromise.then((x) => x.onError?.(event, wsContext));\n\t\t});\n\t}\n\n\tasync sleep(actorId: string) {\n\t\tthis.#runner.sleepActor(actorId);\n\t}\n\n\tasync shutdown(immediate: boolean): Promise<void> {\n\t\tlogger().info({ msg: \"stopping engine actor driver\" });\n\t\tawait this.#runner.shutdown(immediate);\n\t}\n\n\tasync serverlessHandleStart(c: HonoContext): Promise<Response> {\n\t\tawait this.#runnerStarted.promise;\n\n\t\treturn streamSSE(c, async (stream) => {\n\t\t\t// Runner id should be set if the runner started\n\t\t\tconst runnerId = this.#runner.runnerId;\n\t\t\tinvariant(runnerId, \"runnerId not set\");\n\t\t\tstream.writeSSE({ data: runnerId });\n\n\t\t\treturn this.#runnerStopped.promise;\n\t\t});\n\t}\n}\n","export const KEYS = {\n\tPERSIST_DATA: Uint8Array.from([1]),\n};\n","import { getLogger } from \"@/common/log\";\n\nexport function logger() {\n\treturn getLogger(\"driver-engine\");\n}\n","import type { Hono } from \"hono\";\nimport { z } from \"zod\";\nimport { getEnvUniversal } from \"@/utils\";\n\nexport const ConfigSchema = z\n\t.object({\n\t\tapp: z.custom<Hono>().optional(),\n\t\tendpoint: z\n\t\t\t.string()\n\t\t\t.default(\n\t\t\t\t() => getEnvUniversal(\"RIVET_ENGINE\") ?? \"http://localhost:6420\",\n\t\t\t),\n\t\ttoken: z\n\t\t\t.string()\n\t\t\t.optional()\n\t\t\t.transform((val) => val ?? getEnvUniversal(\"RIVET_TOKEN\")),\n\t\tpegboardEndpoint: z.string().optional(),\n\t\tnamespace: z\n\t\t\t.string()\n\t\t\t.default(() => getEnvUniversal(\"RIVET_NAMESPACE\") ?? \"default\"),\n\t\trunnerName: z\n\t\t\t.string()\n\t\t\t.default(() => getEnvUniversal(\"RIVET_RUNNER\") ?? \"rivetkit\"),\n\t\t// TODO: Automatically attempt to determine key by common env vars (e.g. k8s pod name)\n\t\trunnerKey: z\n\t\t\t.string()\n\t\t\t.default(\n\t\t\t\t() => getEnvUniversal(\"RIVET_RUNNER_KEY\") ?? crypto.randomUUID(),\n\t\t\t),\n\t\ttotalSlots: z.number().default(100_000),\n\t})\n\t.default({});\n\nexport type InputConfig = z.input<typeof ConfigSchema>;\nexport type Config = z.infer<typeof ConfigSchema>;\n","import type { Client } from \"@/client/client\";\nimport type { ManagerDriver } from \"@/manager/driver\";\nimport type { RegistryConfig } from \"@/registry/config\";\nimport type { DriverConfig, RunConfig } from \"@/registry/run-config\";\nimport { RemoteManagerDriver } from \"@/remote-manager-driver/mod\";\nimport { EngineActorDriver } from \"./actor-driver\";\nimport { ConfigSchema, type InputConfig } from \"./config\";\n\nexport { EngineActorDriver } from \"./actor-driver\";\nexport { type Config, ConfigSchema, type InputConfig } from \"./config\";\n\nexport function createEngineDriver(inputConfig?: InputConfig): DriverConfig {\n\tconst config = ConfigSchema.parse(inputConfig);\n\n\treturn {\n\t\tname: \"engine\",\n\t\tmanager: (_registryConfig, runConfig) => {\n\t\t\treturn new RemoteManagerDriver(runConfig);\n\t\t},\n\t\tactor: (\n\t\t\tregistryConfig: RegistryConfig,\n\t\t\trunConfig: RunConfig,\n\t\t\tmanagerDriver: ManagerDriver,\n\t\t\tinlineClient: Client<any>,\n\t\t) => {\n\t\t\treturn new EngineActorDriver(\n\t\t\t\tregistryConfig,\n\t\t\t\trunConfig,\n\t\t\t\tmanagerDriver,\n\t\t\t\tinlineClient,\n\t\t\t\tconfig,\n\t\t\t);\n\t\t},\n\t};\n}\n","import type { AnyClient } from \"@/client/client\";\nimport type {\n\tActorDriver,\n\tAnyActorInstance,\n\tManagerDriver,\n} from \"@/driver-helpers/mod\";\nimport type { RegistryConfig, RunConfig } from \"@/mod\";\nimport { bufferToArrayBuffer } from \"@/utils\";\nimport type { FileSystemGlobalState } from \"./global-state\";\n\nexport type ActorDriverContext = Record<never, never>;\n\n/**\n * File System implementation of the Actor Driver\n */\nexport class FileSystemActorDriver implements ActorDriver {\n\t#registryConfig: RegistryConfig;\n\t#runConfig: RunConfig;\n\t#managerDriver: ManagerDriver;\n\t#inlineClient: AnyClient;\n\t#state: FileSystemGlobalState;\n\n\tconstructor(\n\t\tregistryConfig: RegistryConfig,\n\t\trunConfig: RunConfig,\n\t\tmanagerDriver: ManagerDriver,\n\t\tinlineClient: AnyClient,\n\t\tstate: FileSystemGlobalState,\n\t) {\n\t\tthis.#registryConfig = registryConfig;\n\t\tthis.#runConfig = runConfig;\n\t\tthis.#managerDriver = managerDriver;\n\t\tthis.#inlineClient = inlineClient;\n\t\tthis.#state = state;\n\t}\n\n\tasync loadActor(actorId: string): Promise<AnyActorInstance> {\n\t\treturn this.#state.startActor(\n\t\t\tthis.#registryConfig,\n\t\t\tthis.#runConfig,\n\t\t\tthis.#inlineClient,\n\t\t\tthis,\n\t\t\tactorId,\n\t\t);\n\t}\n\n\t/**\n\t * Get the current storage directory path\n\t */\n\tget storagePath(): string {\n\t\treturn this.#state.storagePath;\n\t}\n\n\tgetContext(_actorId: string): ActorDriverContext {\n\t\treturn {};\n\t}\n\n\tasync readPersistedData(actorId: string): Promise<Uint8Array | undefined> {\n\t\treturn new Uint8Array(\n\t\t\t(await this.#state.loadActorStateOrError(actorId)).persistedData,\n\t\t);\n\t}\n\n\tasync writePersistedData(actorId: string, data: Uint8Array): Promise<void> {\n\t\tconst state = await this.#state.loadActorStateOrError(actorId);\n\n\t\t// Save state to disk\n\t\tawait this.#state.writeActor(actorId, {\n\t\t\t...state,\n\t\t\tpersistedData: bufferToArrayBuffer(data),\n\t\t});\n\t}\n\n\tasync setAlarm(actor: AnyActorInstance, timestamp: number): Promise<void> {\n\t\tawait this.#state.setActorAlarm(actor.id, timestamp);\n\t}\n\n\tgetDatabase(actorId: string): Promise<unknown | undefined> {\n\t\treturn this.#state.createDatabase(actorId);\n\t}\n\n\tsleep(actorId: string): Promise<void> {\n\t\treturn this.#state.sleepActor(actorId);\n\t}\n}\n","import * as crypto from \"node:crypto\";\nimport * as fsSync from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport invariant from \"invariant\";\nimport { lookupInRegistry } from \"@/actor/definition\";\nimport { ActorAlreadyExists } from \"@/actor/errors\";\nimport type { AnyActorInstance } from \"@/actor/instance\";\nimport type { ActorKey } from \"@/actor/mod\";\nimport { generateRandomString } from \"@/actor/utils\";\nimport type { AnyClient } from \"@/client/client\";\nimport {\n\ttype ActorDriver,\n\tserializeEmptyPersistData,\n} from \"@/driver-helpers/mod\";\nimport type { RegistryConfig } from \"@/registry/config\";\nimport type { RunConfig } from \"@/registry/run-config\";\nimport type * as schema from \"@/schemas/file-system-driver/mod\";\nimport {\n\tACTOR_ALARM_VERSIONED,\n\tACTOR_STATE_VERSIONED,\n} from \"@/schemas/file-system-driver/versioned\";\nimport {\n\tbufferToArrayBuffer,\n\ttype LongTimeoutHandle,\n\tpromiseWithResolvers,\n\tsetLongTimeout,\n\tstringifyError,\n} from \"@/utils\";\nimport { logger } from \"./log\";\nimport {\n\tensureDirectoryExists,\n\tensureDirectoryExistsSync,\n\tgetStoragePath,\n} from \"./utils\";\n\n// Actor handler to track running instances\n\ninterface ActorEntry {\n\tid: string;\n\n\tstate?: schema.ActorState;\n\t/** Promise for loading the actor state. */\n\tloadPromise?: Promise<ActorEntry>;\n\n\tactor?: AnyActorInstance;\n\t/** Promise for starting the actor. */\n\tstartPromise?: ReturnType<typeof promiseWithResolvers<void>>;\n\n\talarmTimeout?: LongTimeoutHandle;\n\t/** The timestamp currently scheduled for this actor's alarm (ms since epoch). */\n\talarmTimestamp?: number;\n\n\t/** Resolver for pending write operations that need to be notified when any write completes */\n\tpendingWriteResolver?: PromiseWithResolvers<void>;\n\n\t/** If the actor has been removed by destroy or sleep. */\n\tremoved: boolean;\n}\n\n/**\n * Global state for the file system driver\n */\nexport class FileSystemGlobalState {\n\t#storagePath: string;\n\t#stateDir: string;\n\t#dbsDir: string;\n\t#alarmsDir: string;\n\n\t#persist: boolean;\n\t#actors = new Map<string, ActorEntry>();\n\t#actorCountOnStartup: number = 0;\n\n\t#runnerParams?: {\n\t\tregistryConfig: RegistryConfig;\n\t\trunConfig: RunConfig;\n\t\tinlineClient: AnyClient;\n\t\tactorDriver: ActorDriver;\n\t};\n\n\tget persist(): boolean {\n\t\treturn this.#persist;\n\t}\n\n\tget storagePath() {\n\t\treturn this.#storagePath;\n\t}\n\n\tget actorCountOnStartup() {\n\t\treturn this.#actorCountOnStartup;\n\t}\n\n\tconstructor(persist: boolean = true, customPath?: string) {\n\t\tthis.#persist = persist;\n\t\tthis.#storagePath = persist ? getStoragePath(customPath) : \"/tmp\";\n\t\tthis.#stateDir = path.join(this.#storagePath, \"state\");\n\t\tthis.#dbsDir = path.join(this.#storagePath, \"databases\");\n\t\tthis.#alarmsDir = path.join(this.#storagePath, \"alarms\");\n\n\t\tif (this.#persist) {\n\t\t\t// Ensure storage directories exist synchronously during initialization\n\t\t\tensureDirectoryExistsSync(this.#stateDir);\n\t\t\tensureDirectoryExistsSync(this.#dbsDir);\n\t\t\tensureDirectoryExistsSync(this.#alarmsDir);\n\n\t\t\ttry {\n\t\t\t\tconst actorIds = fsSync.readdirSync(this.#stateDir);\n\t\t\t\tthis.#actorCountOnStartup = actorIds.length;\n\t\t\t} catch (error) {\n\t\t\t\tlogger().error({ msg: \"failed to count actors\", error });\n\t\t\t}\n\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"file system driver ready\",\n\t\t\t\tdir: this.#storagePath,\n\t\t\t\tactorCount: this.#actorCountOnStartup,\n\t\t\t});\n\n\t\t\t// Cleanup stale temp files on startup\n\t\t\ttry {\n\t\t\t\tthis.#cleanupTempFilesSync();\n\t\t\t} catch (err) {\n\t\t\t\tlogger().error({ msg: \"failed to cleanup temp files\", error: err });\n\t\t\t}\n\t\t} else {\n\t\t\tlogger().debug({ msg: \"memory driver ready\" });\n\t\t}\n\t}\n\n\tgetActorStatePath(actorId: string): string {\n\t\treturn path.join(this.#stateDir, actorId);\n\t}\n\n\tgetActorDbPath(actorId: string): string {\n\t\treturn path.join(this.#dbsDir, `${actorId}.db`);\n\t}\n\n\tgetActorAlarmPath(actorId: string): string {\n\t\treturn path.join(this.#alarmsDir, actorId);\n\t}\n\n\tasync *getActorsIterator(params: {\n\t\tcursor?: string;\n\t}): AsyncGenerator<schema.ActorState> {\n\t\tlet actorIds = Array.from(this.#actors.keys()).sort();\n\n\t\t// Check if state directory exists first\n\t\tif (fsSync.existsSync(this.#stateDir)) {\n\t\t\tactorIds = fsSync\n\t\t\t\t.readdirSync(this.#stateDir)\n\t\t\t\t.filter((id) => !id.includes(\".tmp\"))\n\t\t\t\t.sort();\n\t\t}\n\n\t\tconst startIndex = params.cursor ? actorIds.indexOf(params.cursor) + 1 : 0;\n\n\t\tfor (let i = startIndex; i < actorIds.length; i++) {\n\t\t\tconst actorId = actorIds[i];\n\t\t\tif (!actorId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst state = await this.loadActorStateOrError(actorId);\n\t\t\t\tyield state;\n\t\t\t} catch (error) {\n\t\t\t\tlogger().error({ msg: \"failed to load actor state\", actorId, error });\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Ensures an entry exists for this actor.\n\t *\n\t * Used for #createActor and #loadActor.\n\t */\n\t#upsertEntry(actorId: string): ActorEntry {\n\t\tlet entry = this.#actors.get(actorId);\n\t\tif (entry) {\n\t\t\treturn entry;\n\t\t}\n\n\t\tentry = {\n\t\t\tid: actorId,\n\t\t\tremoved: false,\n\t\t};\n\t\tthis.#actors.set(actorId, entry);\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Creates a new actor and writes to file system.\n\t */\n\tasync createActor(\n\t\tactorId: string,\n\t\tname: string,\n\t\tkey: ActorKey,\n\t\tinput: unknown | undefined,\n\t): Promise<ActorEntry> {\n\t\t// TODO: Does not check if actor already exists on fs\n\n\t\tif (this.#actors.has(actorId)) {\n\t\t\tthrow new ActorAlreadyExists(name, key);\n\t\t}\n\n\t\tconst entry = this.#upsertEntry(actorId);\n\t\tentry.state = {\n\t\t\tactorId,\n\t\t\tname,\n\t\t\tkey,\n\t\t\tcreatedAt: BigInt(Date.now()),\n\t\t\tpersistedData: bufferToArrayBuffer(serializeEmptyPersistData(input)),\n\t\t};\n\t\tawait this.writeActor(actorId, entry.state);\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Loads the actor from disk or returns the existing actor entry. This will return an entry even if the actor does not actually exist.\n\t */\n\tasync loadActor(actorId: string): Promise<ActorEntry> {\n\t\tconst entry = this.#upsertEntry(actorId);\n\n\t\t// Check if already loaded\n\t\tif (entry.state) {\n\t\t\treturn entry;\n\t\t}\n\n\t\t// If not persisted, then don't load from FS\n\t\tif (!this.#persist) {\n\t\t\treturn entry;\n\t\t}\n\n\t\t// If state is currently being loaded, wait for it\n\t\tif (entry.loadPromise) {\n\t\t\tawait entry.loadPromise;\n\t\t\treturn entry;\n\t\t}\n\n\t\t// Start loading state\n\t\tentry.loadPromise = this.loadActorState(entry);\n\t\treturn entry.loadPromise;\n\t}\n\n\tprivate async loadActorState(entry: ActorEntry) {\n\t\tconst stateFilePath = this.getActorStatePath(entry.id);\n\n\t\t// Read & parse file\n\t\ttry {\n\t\t\tconst stateData = await fs.readFile(stateFilePath);\n\n\t\t\t// Cache the loaded state in handler\n\t\t\tentry.state = ACTOR_STATE_VERSIONED.deserializeWithEmbeddedVersion(\n\t\t\t\tnew Uint8Array(stateData),\n\t\t\t);\n\n\t\t\treturn entry;\n\t\t} catch (innerError: any) {\n\t\t\t// File does not exist, meaning the actor does not exist\n\t\t\tif (innerError.code === \"ENOENT\") {\n\t\t\t\tentry.loadPromise = undefined;\n\t\t\t\treturn entry;\n\t\t\t}\n\n\t\t\t// For other errors, throw\n\t\t\tconst error = new Error(`Failed to load actor state: ${innerError}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync loadOrCreateActor(\n\t\tactorId: string,\n\t\tname: string,\n\t\tkey: ActorKey,\n\t\tinput: unknown | undefined,\n\t): Promise<ActorEntry> {\n\t\t// Attempt to load actor\n\t\tconst entry = await this.loadActor(actorId);\n\n\t\t// If no state for this actor, then create & write state\n\t\tif (!entry.state) {\n\t\t\tentry.state = {\n\t\t\t\tactorId,\n\t\t\t\tname,\n\t\t\t\tkey: key as readonly string[],\n\t\t\t\tcreatedAt: BigInt(Date.now()),\n\t\t\t\tpersistedData: bufferToArrayBuffer(serializeEmptyPersistData(input)),\n\t\t\t};\n\t\t\tawait this.writeActor(actorId, entry.state);\n\t\t}\n\t\treturn entry;\n\t}\n\n\tasync sleepActor(actorId: string) {\n\t\tinvariant(\n\t\t\tthis.#persist,\n\t\t\t\"cannot sleep actor with memory driver, must use file system driver\",\n\t\t);\n\n\t\tconst actor = this.#actors.get(actorId);\n\t\tinvariant(actor, `tried to sleep ${actorId}, does not exist`);\n\n\t\t// Wait for actor to fully start before stopping it to avoid race conditions\n\t\tif (actor.loadPromise) await actor.loadPromise.catch();\n\t\tif (actor.startPromise?.promise) await actor.startPromise.promise.catch();\n\n\t\t// Mark as removed\n\t\tactor.removed = true;\n\n\t\t// Stop actor\n\t\tinvariant(actor.actor, \"actor should be loaded\");\n\t\tawait actor.actor._stop();\n\n\t\t// Remove from map after stop is complete\n\t\tthis.#actors.delete(actorId);\n\t}\n\n\t/**\n\t * Save actor state to disk.\n\t */\n\tasync writeActor(actorId: string, state: schema.ActorState): Promise<void> {\n\t\tif (!this.#persist) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst entry = this.#actors.get(actorId);\n\t\tinvariant(entry, \"actor entry does not exist\");\n\n\t\tawait this.#performWrite(actorId, state);\n\t}\n\n\tasync setActorAlarm(actorId: string, timestamp: number) {\n\t\tconst entry = this.#actors.get(actorId);\n\t\tinvariant(entry, \"actor entry does not exist\");\n\n\t\t// Persist alarm to disk\n\t\tif (this.#persist) {\n\t\t\tconst alarmPath = this.getActorAlarmPath(actorId);\n\t\t\tconst tempPath = `${alarmPath}.tmp.${crypto.randomUUID()}`;\n\t\t\ttry {\n\t\t\t\tawait ensureDirectoryExists(path.dirname(alarmPath));\n\t\t\t\tconst alarmData: schema.ActorAlarm = {\n\t\t\t\t\tactorId,\n\t\t\t\t\ttimestamp: BigInt(timestamp),\n\t\t\t\t};\n\t\t\t\tconst data =\n\t\t\t\t\tACTOR_ALARM_VERSIONED.serializeWithEmbeddedVersion(alarmData);\n\t\t\t\tawait fs.writeFile(tempPath, data);\n\t\t\t\tawait fs.rename(tempPath, alarmPath);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait fs.unlink(tempPath);\n\t\t\t\t} catch {}\n\t\t\t\tlogger().error({ msg: \"failed to write alarm\", actorId, error });\n\t\t\t\tthrow new Error(`Failed to write alarm: ${error}`);\n\t\t\t}\n\t\t}\n\n\t\t// Schedule timeout\n\t\tthis.#scheduleAlarmTimeout(actorId, timestamp);\n\t}\n\n\t/**\n\t * Perform the actual write operation with atomic writes\n\t */\n\tasync #performWrite(\n\t\tactorId: string,\n\t\tstate: schema.ActorState,\n\t): Promise<void> {\n\t\tconst dataPath = this.getActorStatePath(actorId);\n\t\t// Generate unique temp filename to prevent any race conditions\n\t\tconst tempPath = `${dataPath}.tmp.${crypto.randomUUID()}`;\n\n\t\ttry {\n\t\t\t// Create directory if needed\n\t\t\tawait ensureDirectoryExists(path.dirname(dataPath));\n\n\t\t\t// Convert to BARE types for serialization\n\t\t\tconst bareState: schema.ActorState = {\n\t\t\t\tactorId: state.actorId,\n\t\t\t\tname: state.name,\n\t\t\t\tkey: state.key,\n\t\t\t\tcreatedAt: state.createdAt,\n\t\t\t\tpersistedData: state.persistedData,\n\t\t\t};\n\n\t\t\t// Perform atomic write\n\t\t\tconst serializedState =\n\t\t\t\tACTOR_STATE_VERSIONED.serializeWithEmbeddedVersion(bareState);\n\t\t\tawait fs.writeFile(tempPath, serializedState);\n\t\t\tawait fs.rename(tempPath, dataPath);\n\t\t} catch (error) {\n\t\t\t// Cleanup temp file on error\n\t\t\ttry {\n\t\t\t\tawait fs.unlink(tempPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t\tlogger().error({ msg: \"failed to save actor state\", actorId, error });\n\t\t\tthrow new Error(`Failed to save actor state: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Call this method after the actor driver has been initiated.\n\t *\n\t * This will trigger all initial alarms from the file system.\n\t *\n\t * This needs to be sync since DriverConfig.actor is sync\n\t */\n\tonRunnerStart(\n\t\tregistryConfig: RegistryConfig,\n\t\trunConfig: RunConfig,\n\t\tinlineClient: AnyClient,\n\t\tactorDriver: ActorDriver,\n\t) {\n\t\tif (this.#runnerParams) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Save runner params for future use\n\t\tthis.#runnerParams = {\n\t\t\tregistryConfig,\n\t\t\trunConfig,\n\t\t\tinlineClient,\n\t\t\tactorDriver,\n\t\t};\n\n\t\t// Load alarms from disk and schedule timeouts\n\t\ttry {\n\t\t\tthis.#loadAlarmsSync();\n\t\t} catch (err) {\n\t\t\tlogger().error({ msg: \"failed to load alarms on startup\", error: err });\n\t\t}\n\t}\n\n\tasync startActor(\n\t\tregistryConfig: RegistryConfig,\n\t\trunConfig: RunConfig,\n\t\tinlineClient: AnyClient,\n\t\tactorDriver: ActorDriver,\n\t\tactorId: string,\n\t): Promise<AnyActorInstance> {\n\t\t// Get the actor metadata\n\t\tconst entry = await this.loadActor(actorId);\n\t\tif (!entry.state) {\n\t\t\tthrow new Error(\n\t\t\t\t`Actor does not exist and cannot be started: \"${actorId}\"`,\n\t\t\t);\n\t\t}\n\n\t\t// Actor already starting\n\t\tif (entry.startPromise) {\n\t\t\tawait entry.startPromise.promise;\n\t\t\tinvariant(entry.actor, \"actor should have loaded\");\n\t\t\treturn entry.actor;\n\t\t}\n\n\t\t// Actor already loaded\n\t\tif (entry.actor) {\n\t\t\treturn entry.actor;\n\t\t}\n\n\t\t// Create start promise\n\t\tentry.startPromise = promiseWithResolvers();\n\n\t\ttry {\n\t\t\t// Create actor\n\t\t\tconst definition = lookupInRegistry(registryConfig, entry.state.name);\n\t\t\tentry.actor = definition.instantiate();\n\n\t\t\t// Start actor\n\t\t\tawait entry.actor.start(\n\t\t\t\tactorDriver,\n\t\t\t\tinlineClient,\n\t\t\t\tactorId,\n\t\t\t\tentry.state.name,\n\t\t\t\tentry.state.key as string[],\n\t\t\t\t\"unknown\",\n\t\t\t);\n\n\t\t\t// Finish\n\t\t\tentry.startPromise.resolve();\n\t\t\tentry.startPromise = undefined;\n\n\t\t\treturn entry.actor;\n\t\t} catch (innerError) {\n\t\t\tconst error = new Error(\n\t\t\t\t`Failed to start actor ${actorId}: ${innerError}`,\n\t\t\t\t{ cause: innerError },\n\t\t\t);\n\t\t\tentry.startPromise?.reject(error);\n\t\t\tentry.startPromise = undefined;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync loadActorStateOrError(actorId: string): Promise<schema.ActorState> {\n\t\tconst state = (await this.loadActor(actorId)).state;\n\t\tif (!state) throw new Error(`Actor does not exist: ${actorId}`);\n\t\treturn state;\n\t}\n\n\tgetActorOrError(actorId: string): ActorEntry {\n\t\tconst entry = this.#actors.get(actorId);\n\t\tif (!entry) throw new Error(`No entry for actor: ${actorId}`);\n\t\treturn entry;\n\t}\n\n\tasync createDatabase(actorId: string): Promise<string | undefined> {\n\t\treturn this.getActorDbPath(actorId);\n\t}\n\n\t/**\n\t * Load all persisted alarms from disk and schedule their timers.\n\t */\n\t#loadAlarmsSync(): void {\n\t\ttry {\n\t\t\tconst files = fsSync.existsSync(this.#alarmsDir)\n\t\t\t\t? fsSync.readdirSync(this.#alarmsDir)\n\t\t\t\t: [];\n\t\t\tfor (const file of files) {\n\t\t\t\t// Skip temp files\n\t\t\t\tif (file.includes(\".tmp.\")) continue;\n\t\t\t\tconst fullPath = path.join(this.#alarmsDir, file);\n\t\t\t\ttry {\n\t\t\t\t\tconst buf = fsSync.readFileSync(fullPath);\n\t\t\t\t\tconst alarmData =\n\t\t\t\t\t\tACTOR_ALARM_VERSIONED.deserializeWithEmbeddedVersion(\n\t\t\t\t\t\t\tnew Uint8Array(buf),\n\t\t\t\t\t\t);\n\t\t\t\t\tconst timestamp = Number(alarmData.timestamp);\n\t\t\t\t\tif (Number.isFinite(timestamp)) {\n\t\t\t\t\t\tthis.#scheduleAlarmTimeout(alarmData.actorId, timestamp);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger().debug({ msg: \"invalid alarm file contents\", file });\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger().error({\n\t\t\t\t\t\tmsg: \"failed to read alarm file\",\n\t\t\t\t\t\tfile,\n\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger().error({ msg: \"failed to list alarms directory\", error: err });\n\t\t}\n\t}\n\n\t/**\n\t * Schedule an alarm timer for an actor without writing to disk.\n\t */\n\t#scheduleAlarmTimeout(actorId: string, timestamp: number) {\n\t\tconst entry = this.#upsertEntry(actorId);\n\n\t\t// If there's already an earlier alarm scheduled, do not override it.\n\t\tif (\n\t\t\tentry.alarmTimestamp !== undefined &&\n\t\t\ttimestamp >= entry.alarmTimestamp\n\t\t) {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"skipping alarm schedule (later than existing)\",\n\t\t\t\tactorId,\n\t\t\t\ttimestamp,\n\t\t\t\tcurrent: entry.alarmTimestamp,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tlogger().debug({ msg: \"scheduling alarm\", actorId, timestamp });\n\n\t\t// Cancel existing timeout and update the current scheduled timestamp\n\t\tentry.alarmTimeout?.abort();\n\t\tentry.alarmTimestamp = timestamp;\n\n\t\tconst delay = Math.max(0, timestamp - Date.now());\n\t\tentry.alarmTimeout = setLongTimeout(async () => {\n\t\t\t// Clear currently scheduled timestamp as this alarm is firing now\n\t\t\tentry.alarmTimestamp = undefined;\n\t\t\t// On trigger: remove persisted alarm file\n\t\t\tif (this.#persist) {\n\t\t\t\ttry {\n\t\t\t\t\tawait fs.unlink(this.getActorAlarmPath(actorId));\n\t\t\t\t} catch (err: any) {\n\t\t\t\t\tif (err?.code !== \"ENOENT\") {\n\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\tmsg: \"failed to remove alarm file\",\n\t\t\t\t\t\t\tactorId,\n\t\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tlogger().debug({ msg: \"triggering alarm\", actorId, timestamp });\n\n\t\t\t\t// Ensure actor state exists and start actor if needed\n\t\t\t\tconst loaded = await this.loadActor(actorId);\n\t\t\t\tif (!loaded.state) throw new Error(`Actor does not exist: ${actorId}`);\n\n\t\t\t\t// Start actor if not already running\n\t\t\t\tconst runnerParams = this.#runnerParams;\n\t\t\t\tinvariant(runnerParams, \"missing runner params\");\n\t\t\t\tif (!loaded.actor) {\n\t\t\t\t\tawait this.startActor(\n\t\t\t\t\t\trunnerParams.registryConfig,\n\t\t\t\t\t\trunnerParams.runConfig,\n\t\t\t\t\t\trunnerParams.inlineClient,\n\t\t\t\t\t\trunnerParams.actorDriver,\n\t\t\t\t\t\tactorId,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tinvariant(loaded.actor, \"actor should be loaded after wake\");\n\t\t\t\tawait loaded.actor._onAlarm();\n\t\t\t} catch (err) {\n\t\t\t\tlogger().error({\n\t\t\t\t\tmsg: \"failed to handle alarm\",\n\t\t\t\t\tactorId,\n\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}, delay);\n\t}\n\n\tgetOrCreateInspectorAccessToken(): string {\n\t\tconst tokenPath = path.join(this.#storagePath, \"inspector-token\");\n\t\tif (fsSync.existsSync(tokenPath)) {\n\t\t\treturn fsSync.readFileSync(tokenPath, \"utf-8\");\n\t\t}\n\n\t\tconst newToken = generateRandomString();\n\t\tfsSync.writeFileSync(tokenPath, newToken);\n\t\treturn newToken;\n\t}\n\n\t/**\n\t * Cleanup stale temp files on startup (synchronous)\n\t */\n\t#cleanupTempFilesSync(): void {\n\t\ttry {\n\t\t\tconst files = fsSync.readdirSync(this.#stateDir);\n\t\t\tconst tempFiles = files.filter((f) => f.includes(\".tmp.\"));\n\n\t\t\tconst oneHourAgo = Date.now() - 3600000; // 1 hour in ms\n\n\t\t\tfor (const tempFile of tempFiles) {\n\t\t\t\ttry {\n\t\t\t\t\tconst fullPath = path.join(this.#stateDir, tempFile);\n\t\t\t\t\tconst stat = fsSync.statSync(fullPath);\n\n\t\t\t\t\t// Remove if older than 1 hour\n\t\t\t\t\tif (stat.mtimeMs < oneHourAgo) {\n\t\t\t\t\t\tfsSync.unlinkSync(fullPath);\n\t\t\t\t\t\tlogger().info({\n\t\t\t\t\t\t\tmsg: \"cleaned up stale temp file\",\n\t\t\t\t\t\t\tfile: tempFile,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\tmsg: \"failed to cleanup temp file\",\n\t\t\t\t\t\tfile: tempFile,\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger().error({\n\t\t\t\tmsg: \"failed to read actors directory for cleanup\",\n\t\t\t\terror: err,\n\t\t\t});\n\t\t}\n\t}\n}\n","import * as bare from \"@bare-ts/lib\"\n\nconst config = /* @__PURE__ */ bare.Config({})\n\nexport type u64 = bigint\nexport type uint = bigint\n\nfunction read0(bc: bare.ByteCursor): readonly string[] {\n const len = bare.readUintSafe(bc)\n if (len === 0) { return [] }\n const result = [bare.readString(bc)]\n for (let i = 1; i < len; i++) {\n result[i] = bare.readString(bc)\n }\n return result\n}\n\nfunction write0(bc: bare.ByteCursor, x: readonly string[]): void {\n bare.writeUintSafe(bc, x.length)\n for (let i = 0; i < x.length; i++) {\n bare.writeString(bc, x[i])\n }\n}\n\nexport type ActorState = {\n readonly actorId: string,\n readonly name: string,\n readonly key: readonly string[],\n readonly persistedData: ArrayBuffer,\n readonly createdAt: u64,\n}\n\nexport function readActorState(bc: bare.ByteCursor): ActorState {\n return {\n actorId: bare.readString(bc),\n name: bare.readString(bc),\n key: read0(bc),\n persistedData: bare.readData(bc),\n createdAt: bare.readU64(bc),\n }\n}\n\nexport function writeActorState(bc: bare.ByteCursor, x: ActorState): void {\n bare.writeString(bc, x.actorId)\n bare.writeString(bc, x.name)\n write0(bc, x.key)\n bare.writeData(bc, x.persistedData)\n bare.writeU64(bc, x.createdAt)\n}\n\nexport function encodeActorState(x: ActorState): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorState(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorState(bytes: Uint8Array): ActorState {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorState(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n\nexport type ActorAlarm = {\n readonly actorId: string,\n readonly timestamp: uint,\n}\n\nexport function readActorAlarm(bc: bare.ByteCursor): ActorAlarm {\n return {\n actorId: bare.readString(bc),\n timestamp: bare.readUint(bc),\n }\n}\n\nexport function writeActorAlarm(bc: bare.ByteCursor, x: ActorAlarm): void {\n bare.writeString(bc, x.actorId)\n bare.writeUint(bc, x.timestamp)\n}\n\nexport function encodeActorAlarm(x: ActorAlarm): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorAlarm(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorAlarm(bytes: Uint8Array): ActorAlarm {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorAlarm(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n","import {\n\tcreateVersionedDataHandler,\n\ttype MigrationFn,\n} from \"@/common/versioned-data\";\nimport * as v1 from \"../../../dist/schemas/file-system-driver/v1\";\n\nexport const CURRENT_VERSION = 1;\n\nexport type CurrentActorState = v1.ActorState;\nexport type CurrentActorAlarm = v1.ActorAlarm;\n\nconst migrations = new Map<number, MigrationFn<any, any>>();\n\nexport const ACTOR_STATE_VERSIONED =\n\tcreateVersionedDataHandler<CurrentActorState>({\n\t\tcurrentVersion: CURRENT_VERSION,\n\t\tmigrations,\n\t\tserializeVersion: (data) => v1.encodeActorState(data),\n\t\tdeserializeVersion: (bytes) => v1.decodeActorState(bytes),\n\t});\n\nexport const ACTOR_ALARM_VERSIONED =\n\tcreateVersionedDataHandler<CurrentActorAlarm>({\n\t\tcurrentVersion: CURRENT_VERSION,\n\t\tmigrations,\n\t\tserializeVersion: (data) => v1.encodeActorAlarm(data),\n\t\tdeserializeVersion: (bytes) => v1.decodeActorAlarm(bytes),\n\t});\n","import { getLogger } from \"@/common/log\";\n\nexport function logger() {\n\treturn getLogger(\"driver-fs\");\n}\n","import * as crypto from \"node:crypto\";\nimport * as fsSync from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { ActorKey } from \"@/actor/mod\";\n\n/**\n * Generate a deterministic actor ID from name and key\n */\nexport function generateActorId(name: string, key: ActorKey): string {\n\t// Generate deterministic key string\n\tconst jsonString = JSON.stringify([name, key]);\n\n\t// Hash to ensure safe file system names\n\tconst hash = crypto\n\t\t.createHash(\"sha256\")\n\t\t.update(jsonString)\n\t\t.digest(\"hex\")\n\t\t.substring(0, 16);\n\n\treturn hash;\n}\n\n/**\n * Create a hash for a path, normalizing it first\n */\nfunction createHashForPath(dirPath: string): string {\n\t// Normalize the path first\n\tconst normalizedPath = path.normalize(dirPath);\n\n\t// Extract the last path component for readability\n\tconst lastComponent = path.basename(normalizedPath);\n\n\t// Create SHA-256 hash\n\tconst hash = crypto\n\t\t.createHash(\"sha256\")\n\t\t.update(normalizedPath)\n\t\t.digest(\"hex\")\n\t\t.substring(0, 8); // Take first 8 characters for brevity\n\n\treturn `${lastComponent}-${hash}`;\n}\n\n/**\n * Get the storage path for the current working directory or a specified path\n */\nexport function getStoragePath(customPath?: string): string {\n\tconst dataPath = getDataPath(\"rivetkit\");\n\tconst pathToHash = customPath || process.cwd();\n\tconst dirHash = createHashForPath(pathToHash);\n\treturn path.join(dataPath, dirHash);\n}\n\n/**\n * Check if a path exists\n */\nexport async function pathExists(path: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(path);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Ensure a directory exists, creating it if necessary\n */\nexport async function ensureDirectoryExists(\n\tdirectoryPath: string,\n): Promise<void> {\n\tif (!(await pathExists(directoryPath))) {\n\t\tawait fs.mkdir(directoryPath, { recursive: true });\n\t}\n}\n\n/**\n * Ensure a directory exists synchronously - only used during initialization\n * All other operations use the async version\n */\nexport function ensureDirectoryExistsSync(directoryPath: string): void {\n\tif (!fsSync.existsSync(directoryPath)) {\n\t\tfsSync.mkdirSync(directoryPath, { recursive: true });\n\t}\n}\n\n/**\n * Returns platform-specific data directory\n */\nfunction getDataPath(appName: string): string {\n\tconst platform = process.platform;\n\tconst homeDir = os.homedir();\n\n\tswitch (platform) {\n\t\tcase \"win32\":\n\t\t\treturn path.join(\n\t\t\t\tprocess.env.APPDATA || path.join(homeDir, \"AppData\", \"Roaming\"),\n\t\t\t\tappName,\n\t\t\t);\n\t\tcase \"darwin\":\n\t\t\treturn path.join(homeDir, \"Library\", \"Application Support\", appName);\n\t\tdefault: // linux and others\n\t\t\treturn path.join(\n\t\t\t\tprocess.env.XDG_DATA_HOME || path.join(homeDir, \".local\", \"share\"),\n\t\t\t\tappName,\n\t\t\t);\n\t}\n}\n","import type { Context as HonoContext } from \"hono\";\nimport invariant from \"invariant\";\nimport { type ActorRouter, createActorRouter } from \"@/actor/router\";\nimport {\n\thandleRawWebSocketHandler,\n\thandleWebSocketConnect,\n} from \"@/actor/router-endpoints\";\nimport { createClientWithDriver } from \"@/client/client\";\nimport { InlineWebSocketAdapter2 } from \"@/common/inline-websocket-adapter2\";\nimport { noopNext } from \"@/common/utils\";\nimport type {\n\tActorDriver,\n\tActorOutput,\n\tCreateInput,\n\tGetForIdInput,\n\tGetOrCreateWithKeyInput,\n\tGetWithKeyInput,\n\tManagerDriver,\n} from \"@/driver-helpers/mod\";\nimport { ManagerInspector } from \"@/inspector/manager\";\nimport { type Actor, ActorFeature, type ActorId } from \"@/inspector/mod\";\nimport type { ManagerDisplayInformation } from \"@/manager/driver\";\nimport {\n\ttype DriverConfig,\n\ttype Encoding,\n\tPATH_CONNECT_WEBSOCKET,\n\tPATH_RAW_WEBSOCKET_PREFIX,\n\ttype RegistryConfig,\n\ttype RunConfig,\n\ttype UniversalWebSocket,\n} from \"@/mod\";\nimport type * as schema from \"@/schemas/file-system-driver/mod\";\nimport type { FileSystemGlobalState } from \"./global-state\";\nimport { logger } from \"./log\";\nimport { generateActorId } from \"./utils\";\n\nexport class FileSystemManagerDriver implements ManagerDriver {\n\t#registryConfig: RegistryConfig;\n\t#runConfig: RunConfig;\n\t#state: FileSystemGlobalState;\n\t#driverConfig: DriverConfig;\n\n\t#actorDriver: ActorDriver;\n\t#actorRouter: ActorRouter;\n\n\tinspector?: ManagerInspector;\n\n\tconstructor(\n\t\tregistryConfig: RegistryConfig,\n\t\trunConfig: RunConfig,\n\t\tstate: FileSystemGlobalState,\n\t\tdriverConfig: DriverConfig,\n\t) {\n\t\tthis.#registryConfig = registryConfig;\n\t\tthis.#runConfig = runConfig;\n\t\tthis.#state = state;\n\t\tthis.#driverConfig = driverConfig;\n\n\t\tif (runConfig.inspector.enabled) {\n\t\t\tconst startedAt = new Date().toISOString();\n\t\t\tfunction transformActor(actorState: schema.ActorState): Actor {\n\t\t\t\treturn {\n\t\t\t\t\tid: actorState.actorId as ActorId,\n\t\t\t\t\tname: actorState.name,\n\t\t\t\t\tkey: actorState.key as string[],\n\t\t\t\t\tstartedAt: startedAt,\n\t\t\t\t\tcreatedAt: new Date(Number(actorState.createdAt)).toISOString(),\n\t\t\t\t\tfeatures: [\n\t\t\t\t\t\tActorFeature.State,\n\t\t\t\t\t\tActorFeature.Connections,\n\t\t\t\t\t\tActorFeature.Console,\n\t\t\t\t\t\tActorFeature.EventsMonitoring,\n\t\t\t\t\t\tActorFeature.Database,\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tthis.inspector = new ManagerInspector(() => {\n\t\t\t\treturn {\n\t\t\t\t\tgetAllActors: async ({ cursor, limit }) => {\n\t\t\t\t\t\tconst itr = this.#state.getActorsIterator({ cursor });\n\t\t\t\t\t\tconst actors: Actor[] = [];\n\n\t\t\t\t\t\tfor await (const actor of itr) {\n\t\t\t\t\t\t\tactors.push(transformActor(actor));\n\t\t\t\t\t\t\tif (limit && actors.length >= limit) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn actors;\n\t\t\t\t\t},\n\t\t\t\t\tgetActorById: async (id) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await this.#state.loadActorStateOrError(id);\n\t\t\t\t\t\t\treturn transformActor(result);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tgetBuilds: async () => {\n\t\t\t\t\t\treturn Object.keys(this.#registryConfig.use).map((name) => ({\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t}));\n\t\t\t\t\t},\n\t\t\t\t\tcreateActor: async (input) => {\n\t\t\t\t\t\tconst { actorId } = await this.createActor(input);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await this.#state.loadActorStateOrError(actorId);\n\t\t\t\t\t\t\treturn transformActor(result);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\n\t\t// Actors run on the same node as the manager, so we create a dummy actor router that we route requests to\n\t\tconst inlineClient = createClientWithDriver(this);\n\t\tthis.#actorDriver = this.#driverConfig.actor(\n\t\t\tregistryConfig,\n\t\t\trunConfig,\n\t\t\tthis,\n\t\t\tinlineClient,\n\t\t);\n\t\tthis.#actorRouter = createActorRouter(this.#runConfig, this.#actorDriver);\n\t}\n\n\tasync sendRequest(actorId: string, actorRequest: Request): Promise<Response> {\n\t\treturn await this.#actorRouter.fetch(actorRequest, {\n\t\t\tactorId,\n\t\t});\n\t}\n\n\tasync openWebSocket(\n\t\tpath: string,\n\t\tactorId: string,\n\t\tencoding: Encoding,\n\t\tparams: unknown,\n\t\tconnId?: string,\n\t\tconnToken?: string,\n\t): Promise<UniversalWebSocket> {\n\t\t// Handle raw WebSocket paths\n\t\tconst pathOnly = path.split(\"?\")[0];\n\t\tconst normalizedPath = pathOnly.startsWith(\"/\") ? pathOnly : `/${pathOnly}`;\n\t\tif (normalizedPath === PATH_CONNECT_WEBSOCKET) {\n\t\t\t// Handle standard connect\n\t\t\tconst wsHandler = await handleWebSocketConnect(\n\t\t\t\tundefined,\n\t\t\t\tthis.#runConfig,\n\t\t\t\tthis.#actorDriver,\n\t\t\t\tactorId,\n\t\t\t\tencoding,\n\t\t\t\tparams,\n\t\t\t\tconnId,\n\t\t\t\tconnToken,\n\t\t\t);\n\t\t\treturn new InlineWebSocketAdapter2(wsHandler);\n\t\t} else if (\n\t\t\tnormalizedPath.startsWith(PATH_RAW_WEBSOCKET_PREFIX) ||\n\t\t\tnormalizedPath === \"/raw/websocket\"\n\t\t) {\n\t\t\t// Handle websocket proxy\n\t\t\t// Use the full path with query parameters\n\t\t\tconst wsHandler = await handleRawWebSocketHandler(\n\t\t\t\tundefined,\n\t\t\t\tpath,\n\t\t\t\tthis.#actorDriver,\n\t\t\t\tactorId,\n\t\t\t);\n\t\t\treturn new InlineWebSocketAdapter2(wsHandler);\n\t\t} else {\n\t\t\tthrow new Error(`Unreachable path: ${path}`);\n\t\t}\n\t}\n\n\tasync proxyRequest(\n\t\tc: HonoContext,\n\t\tactorRequest: Request,\n\t\tactorId: string,\n\t): Promise<Response> {\n\t\treturn await this.#actorRouter.fetch(actorRequest, {\n\t\t\tactorId,\n\t\t});\n\t}\n\n\tasync proxyWebSocket(\n\t\tc: HonoContext,\n\t\tpath: string,\n\t\tactorId: string,\n\t\tencoding: Encoding,\n\t\tconnParams: unknown,\n\t\tconnId?: string,\n\t\tconnToken?: string,\n\t): Promise<Response> {\n\t\tconst upgradeWebSocket = this.#runConfig.getUpgradeWebSocket?.();\n\t\tinvariant(upgradeWebSocket, \"missing getUpgradeWebSocket\");\n\n\t\t// Handle raw WebSocket paths\n\t\tconst pathOnly = path.split(\"?\")[0];\n\t\tconst normalizedPath = pathOnly.startsWith(\"/\") ? pathOnly : `/${pathOnly}`;\n\t\tif (normalizedPath === PATH_CONNECT_WEBSOCKET) {\n\t\t\t// Handle standard connect\n\t\t\tconst wsHandler = await handleWebSocketConnect(\n\t\t\t\tc.req.raw,\n\t\t\t\tthis.#runConfig,\n\t\t\t\tthis.#actorDriver,\n\t\t\t\tactorId,\n\t\t\t\tencoding,\n\t\t\t\tconnParams,\n\t\t\t\tconnId,\n\t\t\t\tconnToken,\n\t\t\t);\n\t\t\treturn upgradeWebSocket(() => wsHandler)(c, noopNext());\n\t\t} else if (\n\t\t\tnormalizedPath.startsWith(PATH_RAW_WEBSOCKET_PREFIX) ||\n\t\t\tnormalizedPath === \"/raw/websocket\"\n\t\t) {\n\t\t\t// Handle websocket proxy\n\t\t\t// Use the full path with query parameters\n\t\t\tconst wsHandler = await handleRawWebSocketHandler(\n\t\t\t\tc.req.raw,\n\t\t\t\tpath,\n\t\t\t\tthis.#actorDriver,\n\t\t\t\tactorId,\n\t\t\t);\n\t\t\treturn upgradeWebSocket(() => wsHandler)(c, noopNext());\n\t\t} else {\n\t\t\tthrow new Error(`Unreachable path: ${path}`);\n\t\t}\n\t}\n\n\tasync getForId({ actorId }: GetForIdInput): Promise<ActorOutput | undefined> {\n\t\t// Validate the actor exists\n\t\tconst actor = await this.#state.loadActor(actorId);\n\t\tif (!actor.state) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\ttry {\n\t\t\t// Load actor state\n\t\t\treturn {\n\t\t\t\tactorId,\n\t\t\t\tname: actor.state.name,\n\t\t\t\tkey: actor.state.key as string[],\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tlogger().error({ msg: \"failed to read actor state\", actorId, error });\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tasync getWithKey({\n\t\tname,\n\t\tkey,\n\t}: GetWithKeyInput): Promise<ActorOutput | undefined> {\n\t\t// Generate the deterministic actor ID\n\t\tconst actorId = generateActorId(name, key);\n\n\t\t// Check if actor exists\n\t\tconst actor = await this.#state.loadActor(actorId);\n\t\tif (actor.state) {\n\t\t\treturn {\n\t\t\t\tactorId,\n\t\t\t\tname,\n\t\t\t\tkey,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync getOrCreateWithKey(\n\t\tinput: GetOrCreateWithKeyInput,\n\t): Promise<ActorOutput> {\n\t\t// Generate the deterministic actor ID\n\t\tconst actorId = generateActorId(input.name, input.key);\n\n\t\t// Use the atomic getOrCreateActor method\n\t\tconst actorEntry = await this.#state.loadOrCreateActor(\n\t\t\tactorId,\n\t\t\tinput.name,\n\t\t\tinput.key,\n\t\t\tinput.input,\n\t\t);\n\t\tinvariant(actorEntry.state, \"must have state\");\n\n\t\treturn {\n\t\t\tactorId: actorEntry.state.actorId,\n\t\t\tname: actorEntry.state.name,\n\t\t\tkey: actorEntry.state.key as string[],\n\t\t};\n\t}\n\n\tasync createActor({ name, key, input }: CreateInput): Promise<ActorOutput> {\n\t\t// Generate the deterministic actor ID\n\t\tconst actorId = generateActorId(name, key);\n\n\t\tawait this.#state.createActor(actorId, name, key, input);\n\n\t\treturn {\n\t\t\tactorId,\n\t\t\tname,\n\t\t\tkey,\n\t\t};\n\t}\n\n\tdisplayInformation(): ManagerDisplayInformation {\n\t\treturn {\n\t\t\tname: this.#state.persist ? \"File System\" : \"Memory\",\n\t\t\tproperties: {\n\t\t\t\t...(this.#state.persist ? { Data: this.#state.storagePath } : {}),\n\t\t\t\tInstances: this.#state.actorCountOnStartup.toString(),\n\t\t\t},\n\t\t};\n\t}\n\n\textraStartupLog() {\n\t\treturn {\n\t\t\tinstances: this.#state.actorCountOnStartup,\n\t\t\tdata: this.#state.storagePath,\n\t\t};\n\t}\n\n\tgetOrCreateInspectorAccessToken() {\n\t\treturn this.#state.getOrCreateInspectorAccessToken();\n\t}\n}\n","import { sValidator } from \"@hono/standard-validator\";\nimport { Hono } from \"hono\";\nimport invariant from \"invariant\";\nimport type { CreateInput } from \"@/manager/driver\";\nimport { inspectorLogger } from \"./log\";\nimport { type Actor, type Builds, CreateActorSchema } from \"./protocol/common\";\n\nexport type ManagerInspectorRouterEnv = {\n\tVariables: {\n\t\tinspector: ManagerInspector;\n\t};\n};\n\n/**\n * Create a router for the Manager Inspector.\n * @internal\n */\nexport function createManagerInspectorRouter() {\n\treturn new Hono<ManagerInspectorRouterEnv>()\n\t\t.get(\"/ping\", (c) => {\n\t\t\treturn c.json({ message: \"pong\" }, 200);\n\t\t})\n\t\t.get(\"/actors\", async (c) => {\n\t\t\tconst limit = Number.parseInt(c.req.query(\"limit\") ?? \"\") || undefined;\n\t\t\tconst cursor = c.req.query(\"cursor\") || undefined;\n\n\t\t\tif (!limit || (limit && limit <= 0)) {\n\t\t\t\treturn c.json(\"Invalid limit\", 400);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst actors = await c.var.inspector.accessors.getAllActors({\n\t\t\t\t\tlimit,\n\t\t\t\t\tcursor,\n\t\t\t\t});\n\t\t\t\treturn c.json(actors, 200);\n\t\t\t} catch (error) {\n\t\t\t\tinspectorLogger().error({ msg: \"Failed to fetch actors\", error });\n\t\t\t\treturn c.json(\"Failed to fetch actors\", 500);\n\t\t\t}\n\t\t})\n\n\t\t.post(\"/actors\", sValidator(\"json\", CreateActorSchema), async (c) => {\n\t\t\tconst actor = await c.var.inspector.accessors.createActor(\n\t\t\t\tc.req.valid(\"json\"),\n\t\t\t);\n\t\t\treturn c.json(actor, 201);\n\t\t})\n\t\t.get(\"/builds\", async (c) => {\n\t\t\tconst builds = await c.var.inspector.accessors.getBuilds();\n\t\t\treturn c.json(builds, 200);\n\t\t})\n\t\t.get(\"/actor/:id\", async (c) => {\n\t\t\tconst id = c.req.param(\"id\");\n\t\t\tconst actor = await c.var.inspector.accessors.getActorById(id);\n\t\t\tif (!actor) {\n\t\t\t\treturn c.json({ error: \"Actor not found\" }, 404);\n\t\t\t}\n\t\t\treturn c.json(actor, 200);\n\t\t})\n\t\t.get(\"/bootstrap\", async (c) => {\n\t\t\tconst actors = await c.var.inspector.accessors.getAllActors({\n\t\t\t\tlimit: 10,\n\t\t\t});\n\t\t\treturn c.json({ actors }, 200);\n\t\t});\n}\n\ninterface ManagerInspectorAccessors {\n\tgetAllActors: (param: { cursor?: string; limit: number }) => Promise<Actor[]>;\n\tgetActorById: (id: string) => Promise<Actor | null>;\n\tgetBuilds: () => Promise<Builds>;\n\tcreateActor: (input: CreateInput) => Promise<Actor | null>;\n}\n\n/**\n * Provides a unified interface for inspecting actor external and internal state.\n */\nexport class ManagerInspector {\n\tpublic readonly accessors: ManagerInspectorAccessors;\n\n\tconstructor(accessors: () => ManagerInspectorAccessors) {\n\t\tthis.accessors = accessors();\n\t\tinspectorLogger().debug({ msg: \"Manager Inspector enabled and ready\" });\n\t}\n}\n","import type { DriverConfig } from \"@/registry/run-config\";\nimport { FileSystemActorDriver } from \"./actor\";\nimport { FileSystemGlobalState } from \"./global-state\";\nimport { FileSystemManagerDriver } from \"./manager\";\n\nexport { FileSystemActorDriver } from \"./actor\";\nexport { FileSystemGlobalState } from \"./global-state\";\nexport { FileSystemManagerDriver } from \"./manager\";\nexport { getStoragePath } from \"./utils\";\n\nexport function createFileSystemOrMemoryDriver(\n\tpersist: boolean = true,\n\tcustomPath?: string,\n): DriverConfig {\n\tconst state = new FileSystemGlobalState(persist, customPath);\n\tconst driverConfig: DriverConfig = {\n\t\tname: persist ? \"file-system\" : \"memory\",\n\t\tmanager: (registryConfig, runConfig) =>\n\t\t\tnew FileSystemManagerDriver(\n\t\t\t\tregistryConfig,\n\t\t\t\trunConfig,\n\t\t\t\tstate,\n\t\t\t\tdriverConfig,\n\t\t\t),\n\t\tactor: (registryConfig, runConfig, managerDriver, inlineClient) => {\n\t\t\tconst actorDriver = new FileSystemActorDriver(\n\t\t\t\tregistryConfig,\n\t\t\t\trunConfig,\n\t\t\t\tmanagerDriver,\n\t\t\t\tinlineClient,\n\t\t\t\tstate,\n\t\t\t);\n\n\t\t\tstate.onRunnerStart(registryConfig, runConfig, inlineClient, actorDriver);\n\n\t\t\treturn actorDriver;\n\t\t},\n\t};\n\treturn driverConfig;\n}\n\nexport function createFileSystemDriver(opts?: { path?: string }): DriverConfig {\n\treturn createFileSystemOrMemoryDriver(true, opts?.path);\n}\n\nexport function createMemoryDriver(): DriverConfig {\n\treturn createFileSystemOrMemoryDriver(false);\n}\n","import { UserError } from \"@/actor/errors\";\nimport { loggerWithoutContext } from \"@/actor/log\";\nimport { createEngineDriver } from \"@/drivers/engine/mod\";\nimport { createFileSystemOrMemoryDriver } from \"@/drivers/file-system/mod\";\nimport type { DriverConfig, RunConfig } from \"@/registry/run-config\";\n\n/**\n * Chooses the appropriate driver based on the run configuration.\n */\nexport function chooseDefaultDriver(runConfig: RunConfig): DriverConfig {\n\tif (runConfig.endpoint && runConfig.driver) {\n\t\tthrow new UserError(\n\t\t\t\"Cannot specify both 'engine' and 'driver' in configuration\",\n\t\t);\n\t}\n\n\tif (runConfig.driver) {\n\t\treturn runConfig.driver;\n\t}\n\n\tif (runConfig.endpoint) {\n\t\tloggerWithoutContext().debug({\n\t\t\tmsg: \"using rivet engine driver\",\n\t\t\tendpoint: runConfig.endpoint,\n\t\t});\n\t\t// TODO: Add all properties from config\n\t\treturn createEngineDriver({\n\t\t\tendpoint: runConfig.endpoint,\n\t\t\ttoken: runConfig.token,\n\t\t});\n\t}\n\n\tloggerWithoutContext().debug({ msg: \"using default file system driver\" });\n\treturn createFileSystemOrMemoryDriver(true);\n}\n","import { createRoute, OpenAPIHono } from \"@hono/zod-openapi\";\nimport * as cbor from \"cbor-x\";\nimport {\n\tHono,\n\tContext as HonoContext,\n\ttype MiddlewareHandler,\n\tNext,\n} from \"hono\";\nimport { cors as corsMiddleware } from \"hono/cors\";\nimport { createMiddleware } from \"hono/factory\";\nimport { streamSSE } from \"hono/streaming\";\nimport invariant from \"invariant\";\nimport { z } from \"zod\";\nimport { ActorNotFound, Unsupported } from \"@/actor/errors\";\nimport { serializeActorKey } from \"@/actor/keys\";\nimport type { Encoding, Transport } from \"@/client/mod\";\nimport {\n\tWS_PROTOCOL_ACTOR,\n\tWS_PROTOCOL_CONN_ID,\n\tWS_PROTOCOL_CONN_PARAMS,\n\tWS_PROTOCOL_CONN_TOKEN,\n\tWS_PROTOCOL_ENCODING,\n\tWS_PROTOCOL_PATH,\n\tWS_PROTOCOL_TRANSPORT,\n} from \"@/common/actor-router-consts\";\nimport {\n\thandleRouteError,\n\thandleRouteNotFound,\n\tloggerMiddleware,\n} from \"@/common/router\";\nimport { deconstructError, noopNext, stringifyError } from \"@/common/utils\";\nimport { type ActorDriver, HEADER_ACTOR_ID } from \"@/driver-helpers/mod\";\nimport type {\n\tTestInlineDriverCallRequest,\n\tTestInlineDriverCallResponse,\n} from \"@/driver-test-suite/test-inline-client-driver\";\nimport { createManagerInspectorRouter } from \"@/inspector/manager\";\nimport { isInspectorEnabled, secureInspector } from \"@/inspector/utils\";\nimport {\n\ttype ActorsCreateRequest,\n\tActorsCreateRequestSchema,\n\ttype ActorsCreateResponse,\n\tActorsCreateResponseSchema,\n\ttype ActorsGetOrCreateRequest,\n\tActorsGetOrCreateRequestSchema,\n\ttype ActorsGetOrCreateResponse,\n\tActorsGetOrCreateResponseSchema,\n\ttype ActorsListResponse,\n\tActorsListResponseSchema,\n\ttype Actor as ApiActor,\n} from \"@/manager-api/actors\";\nimport { RivetIdSchema } from \"@/manager-api/common\";\nimport type { RegistryConfig } from \"@/registry/config\";\nimport type { RunConfig } from \"@/registry/run-config\";\nimport type { ActorOutput, ManagerDriver } from \"./driver\";\nimport { actorGateway, createTestWebSocketProxy } from \"./gateway\";\nimport { logger } from \"./log\";\n\nfunction buildOpenApiResponses<T>(schema: T) {\n\treturn {\n\t\t200: {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: {\n\t\t\t\t\"application/json\": {\n\t\t\t\t\tschema,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t400: {\n\t\t\tdescription: \"User error\",\n\t\t},\n\t\t500: {\n\t\t\tdescription: \"Internal error\",\n\t\t},\n\t};\n}\n\nexport function createManagerRouter(\n\tregistryConfig: RegistryConfig,\n\trunConfig: RunConfig,\n\tmanagerDriver: ManagerDriver,\n\tserverlessActorDriverBuilder: (() => ActorDriver) | undefined,\n): { router: Hono; openapi: OpenAPIHono; cors: MiddlewareHandler } {\n\tconst router = new OpenAPIHono({ strict: false }).basePath(\n\t\trunConfig.basePath,\n\t);\n\n\trouter.use(\"*\", loggerMiddleware(logger()));\n\n\tconst cors = runConfig.cors\n\t\t? corsMiddleware(runConfig.cors)\n\t\t: createMiddleware((_c, next) => next());\n\n\tif (serverlessActorDriverBuilder) {\n\t\taddServerlessRoutes(serverlessActorDriverBuilder, router, cors);\n\t} else {\n\t\taddManagerRoutes(registryConfig, runConfig, managerDriver, router, cors);\n\t}\n\n\t// Error handling\n\trouter.notFound(handleRouteNotFound);\n\trouter.onError(handleRouteError);\n\n\treturn { router: router as Hono, openapi: router, cors };\n}\n\nfunction addServerlessRoutes(\n\tserverlessActorDriverBuilder: () => ActorDriver,\n\trouter: OpenAPIHono,\n\tcors: MiddlewareHandler,\n) {\n\t// GET /\n\trouter.get(\"/\", cors, (c) => {\n\t\treturn c.text(\n\t\t\t\"This is a RivetKit server.\\n\\nLearn more at https://rivetkit.org\",\n\t\t);\n\t});\n\n\t// Serverless start endpoint\n\trouter.get(\"/start\", cors, async (c) => {\n\t\tconst actorDriver = serverlessActorDriverBuilder();\n\t\tinvariant(\n\t\t\tactorDriver.serverlessHandleStart,\n\t\t\t\"missing serverlessHandleStart on ActorDriver\",\n\t\t);\n\t\treturn await actorDriver.serverlessHandleStart(c);\n\t});\n\n\trouter.get(\"/health\", cors, (c) => {\n\t\treturn c.text(\"ok\");\n\t});\n}\n\nfunction addManagerRoutes(\n\tregistryConfig: RegistryConfig,\n\trunConfig: RunConfig,\n\tmanagerDriver: ManagerDriver,\n\trouter: OpenAPIHono,\n\tcors: MiddlewareHandler,\n) {\n\t// Actor gateway\n\trouter.use(\"*\", cors, actorGateway.bind(undefined, runConfig, managerDriver));\n\n\t// GET /\n\trouter.get(\"/\", cors, (c) => {\n\t\treturn c.text(\n\t\t\t\"This is a RivetKit server.\\n\\nLearn more at https://rivetkit.org\",\n\t\t);\n\t});\n\n\t// GET /actors\n\t{\n\t\tconst route = createRoute({\n\t\t\tmiddleware: [cors],\n\t\t\tmethod: \"get\",\n\t\t\tpath: \"/actors\",\n\t\t\trequest: {\n\t\t\t\tquery: z.object({\n\t\t\t\t\tname: z.string(),\n\t\t\t\t\tactor_ids: z.string().optional(),\n\t\t\t\t\tkey: z.string().optional(),\n\t\t\t\t}),\n\t\t\t},\n\t\t\tresponses: buildOpenApiResponses(ActorsListResponseSchema),\n\t\t});\n\n\t\trouter.openapi(route, async (c) => {\n\t\t\tconst { name, actor_ids, key } = c.req.valid(\"query\");\n\n\t\t\tconst actorIdsParsed = actor_ids\n\t\t\t\t? actor_ids\n\t\t\t\t\t\t.split(\",\")\n\t\t\t\t\t\t.map((id) => id.trim())\n\t\t\t\t\t\t.filter((id) => id.length > 0)\n\t\t\t\t: undefined;\n\n\t\t\tconst actors: ActorOutput[] = [];\n\n\t\t\tif (actorIdsParsed) {\n\t\t\t\tif (actorIdsParsed.length > 32) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: `Too many actor IDs. Maximum is 32, got ${actorIdsParsed.length}.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (actorIdsParsed.length === 0) {\n\t\t\t\t\treturn c.json<ActorsListResponse>({\n\t\t\t\t\t\tactors: [],\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const actorId of actorIdsParsed) {\n\t\t\t\t\tif (name) {\n\t\t\t\t\t\tconst actorOutput = await managerDriver.getForId({\n\t\t\t\t\t\t\tc,\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tactorId,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (actorOutput) {\n\t\t\t\t\t\t\tactors.push(actorOutput);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (key) {\n\t\t\t\tconst actorOutput = await managerDriver.getWithKey({\n\t\t\t\t\tc,\n\t\t\t\t\tname,\n\t\t\t\t\tkey: [key], // Convert string to ActorKey array\n\t\t\t\t});\n\t\t\t\tif (actorOutput) {\n\t\t\t\t\tactors.push(actorOutput);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn c.json<ActorsListResponse>({\n\t\t\t\tactors: actors.map(createApiActor),\n\t\t\t});\n\t\t});\n\t}\n\n\t// PUT /actors\n\t{\n\t\tconst route = createRoute({\n\t\t\tmiddleware: [cors],\n\t\t\tmethod: \"put\",\n\t\t\tpath: \"/actors\",\n\t\t\trequest: {\n\t\t\t\tbody: {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\t\tschema: ActorsGetOrCreateRequestSchema,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresponses: buildOpenApiResponses(ActorsGetOrCreateResponseSchema),\n\t\t});\n\n\t\trouter.openapi(route, async (c) => {\n\t\t\tconst body = c.req.valid(\"json\");\n\n\t\t\t// Check if actor already exists\n\t\t\tconst existingActor = await managerDriver.getWithKey({\n\t\t\t\tc,\n\t\t\t\tname: body.name,\n\t\t\t\tkey: [body.key], // Convert string to ActorKey array\n\t\t\t});\n\n\t\t\tif (existingActor) {\n\t\t\t\treturn c.json<ActorsGetOrCreateResponse>({\n\t\t\t\t\tactor: createApiActor(existingActor),\n\t\t\t\t\tcreated: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Create new actor\n\t\t\tconst newActor = await managerDriver.getOrCreateWithKey({\n\t\t\t\tc,\n\t\t\t\tname: body.name,\n\t\t\t\tkey: [body.key], // Convert string to ActorKey array\n\t\t\t\tinput: body.input\n\t\t\t\t\t? cbor.decode(Buffer.from(body.input, \"base64\"))\n\t\t\t\t\t: undefined,\n\t\t\t\tregion: undefined, // Not provided in the request schema\n\t\t\t});\n\n\t\t\treturn c.json<ActorsGetOrCreateResponse>({\n\t\t\t\tactor: createApiActor(newActor),\n\t\t\t\tcreated: true,\n\t\t\t});\n\t\t});\n\t}\n\n\t// POST /actors\n\t{\n\t\tconst route = createRoute({\n\t\t\tmiddleware: [cors],\n\t\t\tmethod: \"post\",\n\t\t\tpath: \"/actors\",\n\t\t\trequest: {\n\t\t\t\tbody: {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\"application/json\": {\n\t\t\t\t\t\t\tschema: ActorsCreateRequestSchema,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresponses: buildOpenApiResponses(ActorsCreateResponseSchema),\n\t\t});\n\n\t\trouter.openapi(route, async (c) => {\n\t\t\tconst body = c.req.valid(\"json\");\n\n\t\t\t// Create actor using the driver\n\t\t\tconst actorOutput = await managerDriver.createActor({\n\t\t\t\tc,\n\t\t\t\tname: body.name,\n\t\t\t\tkey: [body.key || crypto.randomUUID()], // Generate key if not provided, convert to ActorKey array\n\t\t\t\tinput: body.input\n\t\t\t\t\t? cbor.decode(Buffer.from(body.input, \"base64\"))\n\t\t\t\t\t: undefined,\n\t\t\t\tregion: undefined, // Not provided in the request schema\n\t\t\t});\n\n\t\t\t// Transform ActorOutput to match ActorSchema\n\t\t\tconst actor = createApiActor(actorOutput);\n\n\t\t\treturn c.json<ActorsCreateResponse>({ actor });\n\t\t});\n\t}\n\n\t// TODO:\n\t// // DELETE /actors/{actor_id}\n\t// {\n\t// \tconst route = createRoute({\n\t// \t\tmiddleware: [cors],\n\t// \t\tmethod: \"delete\",\n\t// \t\tpath: \"/actors/{actor_id}\",\n\t// \t\trequest: {\n\t// \t\t\tparams: z.object({\n\t// \t\t\t\tactor_id: RivetIdSchema,\n\t// \t\t\t}),\n\t// \t\t},\n\t// \t\tresponses: buildOpenApiResponses(\n\t// \t\t\tActorsDeleteResponseSchema,\n\t// \t\t\tvalidateBody,\n\t// \t\t),\n\t// \t});\n\t//\n\t// \trouter.openapi(route, async (c) => {\n\t// \t\tconst { actor_id } = c.req.valid(\"param\");\n\t//\n\t// \t});\n\t// }\n\n\tif (registryConfig.test.enabled) {\n\t\t// Add HTTP endpoint to test the inline client\n\t\t//\n\t\t// We have to do this in a router since this needs to run in the same server as the RivetKit registry. Some test contexts to not run in the same server.\n\t\trouter.post(\".test/inline-driver/call\", async (c) => {\n\t\t\t// TODO: use openapi instead\n\t\t\tconst buffer = await c.req.arrayBuffer();\n\t\t\tconst { encoding, transport, method, args }: TestInlineDriverCallRequest =\n\t\t\t\tcbor.decode(new Uint8Array(buffer));\n\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"received inline request\",\n\t\t\t\tencoding,\n\t\t\t\ttransport,\n\t\t\t\tmethod,\n\t\t\t\targs,\n\t\t\t});\n\n\t\t\t// Forward inline driver request\n\t\t\tlet response: TestInlineDriverCallResponse<unknown>;\n\t\t\ttry {\n\t\t\t\tconst output = await ((managerDriver as any)[method] as any)(...args);\n\t\t\t\tresponse = { ok: output };\n\t\t\t} catch (rawErr) {\n\t\t\t\tconst err = deconstructError(rawErr, logger(), {}, true);\n\t\t\t\tresponse = { err };\n\t\t\t}\n\n\t\t\t// TODO: Remove any\n\t\t\treturn c.body(cbor.encode(response) as any);\n\t\t});\n\n\t\trouter.get(\".test/inline-driver/connect-websocket/*\", async (c) => {\n\t\t\tconst upgradeWebSocket = runConfig.getUpgradeWebSocket?.();\n\t\t\tinvariant(upgradeWebSocket, \"websockets not supported on this platform\");\n\n\t\t\treturn upgradeWebSocket(async (c: any) => {\n\t\t\t\t// Extract information from sec-websocket-protocol header\n\t\t\t\tconst protocolHeader = c.req.header(\"sec-websocket-protocol\") || \"\";\n\t\t\t\tconst protocols = protocolHeader.split(/,\\s*/);\n\n\t\t\t\t// Parse protocols to extract connection info\n\t\t\t\tlet actorId = \"\";\n\t\t\t\tlet encoding: Encoding = \"bare\";\n\t\t\t\tlet transport: Transport = \"websocket\";\n\t\t\t\tlet path = \"\";\n\t\t\t\tlet params: unknown;\n\t\t\t\tlet connId: string | undefined;\n\t\t\t\tlet connToken: string | undefined;\n\n\t\t\t\tfor (const protocol of protocols) {\n\t\t\t\t\tif (protocol.startsWith(WS_PROTOCOL_ACTOR)) {\n\t\t\t\t\t\tactorId = protocol.substring(WS_PROTOCOL_ACTOR.length);\n\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_ENCODING)) {\n\t\t\t\t\t\tencoding = protocol.substring(\n\t\t\t\t\t\t\tWS_PROTOCOL_ENCODING.length,\n\t\t\t\t\t\t) as Encoding;\n\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_TRANSPORT)) {\n\t\t\t\t\t\ttransport = protocol.substring(\n\t\t\t\t\t\t\tWS_PROTOCOL_TRANSPORT.length,\n\t\t\t\t\t\t) as Transport;\n\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_PATH)) {\n\t\t\t\t\t\tpath = decodeURIComponent(\n\t\t\t\t\t\t\tprotocol.substring(WS_PROTOCOL_PATH.length),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_PARAMS)) {\n\t\t\t\t\t\tconst paramsRaw = decodeURIComponent(\n\t\t\t\t\t\t\tprotocol.substring(WS_PROTOCOL_CONN_PARAMS.length),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tparams = JSON.parse(paramsRaw);\n\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_ID)) {\n\t\t\t\t\t\tconnId = protocol.substring(WS_PROTOCOL_CONN_ID.length);\n\t\t\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_TOKEN)) {\n\t\t\t\t\t\tconnToken = protocol.substring(WS_PROTOCOL_CONN_TOKEN.length);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: \"received test inline driver websocket\",\n\t\t\t\t\tactorId,\n\t\t\t\t\tparams,\n\t\t\t\t\tencodingKind: encoding,\n\t\t\t\t\ttransport,\n\t\t\t\t\tpath: path,\n\t\t\t\t});\n\n\t\t\t\t// Connect to the actor using the inline client driver - this returns a Promise<WebSocket>\n\t\t\t\tconst clientWsPromise = managerDriver.openWebSocket(\n\t\t\t\t\tpath,\n\t\t\t\t\tactorId,\n\t\t\t\t\tencoding,\n\t\t\t\t\tparams,\n\t\t\t\t\tconnId,\n\t\t\t\t\tconnToken,\n\t\t\t\t);\n\n\t\t\t\treturn await createTestWebSocketProxy(clientWsPromise);\n\t\t\t})(c, noopNext());\n\t\t});\n\n\t\trouter.all(\".test/inline-driver/send-request/*\", async (c) => {\n\t\t\t// Extract parameters from headers\n\t\t\tconst actorId = c.req.header(HEADER_ACTOR_ID);\n\n\t\t\tif (!actorId) {\n\t\t\t\treturn c.text(\"Missing required headers\", 400);\n\t\t\t}\n\n\t\t\t// Extract the path after /send-request/\n\t\t\tconst pathOnly =\n\t\t\t\tc.req.path.split(\"/.test/inline-driver/send-request/\")[1] || \"\";\n\n\t\t\t// Include query string\n\t\t\tconst url = new URL(c.req.url);\n\t\t\tconst pathWithQuery = pathOnly + url.search;\n\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"received test inline driver raw http\",\n\t\t\t\tactorId,\n\t\t\t\tpath: pathWithQuery,\n\t\t\t\tmethod: c.req.method,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\t// Forward the request using the inline client driver\n\t\t\t\tconst response = await managerDriver.sendRequest(\n\t\t\t\t\tactorId,\n\t\t\t\t\tnew Request(`http://actor/${pathWithQuery}`, {\n\t\t\t\t\t\tmethod: c.req.method,\n\t\t\t\t\t\theaders: c.req.raw.headers,\n\t\t\t\t\t\tbody: c.req.raw.body,\n\t\t\t\t\t\tduplex: \"half\",\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\t// Return the response directly\n\t\t\t\treturn response;\n\t\t\t} catch (error) {\n\t\t\t\tlogger().error({\n\t\t\t\t\tmsg: \"error in test inline raw http\",\n\t\t\t\t\terror: stringifyError(error),\n\t\t\t\t});\n\n\t\t\t\t// Return error response\n\t\t\t\tconst err = deconstructError(error, logger(), {}, true);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: err.code,\n\t\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t\t\tmetadata: err.metadata,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\terr.statusCode,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t\t// Test endpoint to force disconnect a connection non-cleanly\n\t\trouter.post(\"/.test/force-disconnect\", async (c) => {\n\t\t\tconst actorId = c.req.query(\"actor\");\n\t\t\tconst connId = c.req.query(\"conn\");\n\n\t\t\tif (!actorId || !connId) {\n\t\t\t\treturn c.text(\"Missing actor or conn query parameters\", 400);\n\t\t\t}\n\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"forcing unclean disconnect\",\n\t\t\t\tactorId,\n\t\t\t\tconnId,\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\t// Send a special request to the actor to force disconnect the connection\n\t\t\t\tconst response = await managerDriver.sendRequest(\n\t\t\t\t\tactorId,\n\t\t\t\t\tnew Request(`http://actor/.test/force-disconnect?conn=${connId}`, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tconst text = await response.text();\n\t\t\t\t\treturn c.text(\n\t\t\t\t\t\t`Failed to force disconnect: ${text}`,\n\t\t\t\t\t\tresponse.status as any,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn c.json({ success: true });\n\t\t\t} catch (error) {\n\t\t\t\tlogger().error({\n\t\t\t\t\tmsg: \"error forcing disconnect\",\n\t\t\t\t\terror: stringifyError(error),\n\t\t\t\t});\n\t\t\t\treturn c.text(`Error: ${error}`, 500);\n\t\t\t}\n\t\t});\n\t}\n\n\trouter.get(\"/health\", cors, (c) => {\n\t\treturn c.text(\"ok\");\n\t});\n\n\tmanagerDriver.modifyManagerRouter?.(\n\t\tregistryConfig,\n\t\trouter as unknown as Hono,\n\t);\n\n\tif (isInspectorEnabled(runConfig, \"manager\")) {\n\t\tif (!managerDriver.inspector) {\n\t\t\tthrow new Unsupported(\"inspector\");\n\t\t}\n\t\trouter.route(\n\t\t\t\"/inspect\",\n\t\t\tnew Hono<{ Variables: { inspector: any } }>()\n\t\t\t\t.use(corsMiddleware(runConfig.inspector.cors))\n\t\t\t\t.use(secureInspector(runConfig))\n\t\t\t\t.use((c, next) => {\n\t\t\t\t\tc.set(\"inspector\", managerDriver.inspector!);\n\t\t\t\t\treturn next();\n\t\t\t\t})\n\t\t\t\t.route(\"/\", createManagerInspectorRouter()),\n\t\t);\n\t}\n}\n\nfunction createApiActor(actor: ActorOutput): ApiActor {\n\treturn {\n\t\tactor_id: actor.actorId,\n\t\tname: actor.name,\n\t\tkey: serializeActorKey(actor.key),\n\t\tnamespace_id: \"default\", // Assert default namespace\n\t\trunner_name_selector: \"rivetkit\", // Assert rivetkit runner\n\t\tcreate_ts: Date.now(),\n\t\tconnectable_ts: null,\n\t\tdestroy_ts: null,\n\t\tsleep_ts: null,\n\t\tstart_ts: null,\n\t};\n}\n","import { z } from \"zod\";\nimport { RivetIdSchema } from \"./common\";\n\nexport const ActorSchema = z.object({\n\tactor_id: RivetIdSchema,\n\tname: z.string(),\n\tkey: z.string(),\n\tnamespace_id: RivetIdSchema,\n\trunner_name_selector: z.string(),\n\tcreate_ts: z.number(),\n\tconnectable_ts: z.number().nullable().optional(),\n\tdestroy_ts: z.number().nullable().optional(),\n\tsleep_ts: z.number().nullable().optional(),\n\tstart_ts: z.number().nullable().optional(),\n});\nexport type Actor = z.infer<typeof ActorSchema>;\n\n// MARK: GET /actors\nexport const ActorsListResponseSchema = z.object({\n\tactors: z.array(ActorSchema),\n});\nexport type ActorsListResponse = z.infer<typeof ActorsListResponseSchema>;\n\n// MARK: POST /actors\nexport const ActorsCreateRequestSchema = z.object({\n\tname: z.string(),\n\trunner_name_selector: z.string(),\n\tcrash_policy: z.string(),\n\tkey: z.string().nullable().optional(),\n\tinput: z.string().nullable().optional(),\n});\nexport type ActorsCreateRequest = z.infer<typeof ActorsCreateRequestSchema>;\n\nexport const ActorsCreateResponseSchema = z.object({\n\tactor: ActorSchema,\n});\nexport type ActorsCreateResponse = z.infer<typeof ActorsCreateResponseSchema>;\n\n// MARK: PUT /actors\nexport const ActorsGetOrCreateRequestSchema = z.object({\n\tname: z.string(),\n\tkey: z.string(),\n\trunner_name_selector: z.string(),\n\tcrash_policy: z.string(),\n\tinput: z.string().nullable().optional(),\n});\nexport type ActorsGetOrCreateRequest = z.infer<\n\ttypeof ActorsGetOrCreateRequestSchema\n>;\n\nexport const ActorsGetOrCreateResponseSchema = z.object({\n\tactor: ActorSchema,\n\tcreated: z.boolean(),\n});\nexport type ActorsGetOrCreateResponse = z.infer<\n\ttypeof ActorsGetOrCreateResponseSchema\n>;\n\n// MARK: DELETE /actors/{}\nexport const ActorsDeleteResponseSchema = z.object({});\nexport type ActorsDeleteResponse = z.infer<typeof ActorsDeleteResponseSchema>;\n","import { z } from \"zod\";\n\nexport const RivetIdSchema = z.string();\nexport type RivetId = z.infer<typeof RivetIdSchema>;\n","import type { Context as HonoContext, Next } from \"hono\";\nimport type { WSContext } from \"hono/ws\";\nimport { MissingActorHeader, WebSocketsNotEnabled } from \"@/actor/errors\";\nimport type { Encoding, Transport } from \"@/client/mod\";\nimport {\n\tHEADER_RIVET_ACTOR,\n\tHEADER_RIVET_TARGET,\n\tWS_PROTOCOL_ACTOR,\n\tWS_PROTOCOL_CONN_ID,\n\tWS_PROTOCOL_CONN_PARAMS,\n\tWS_PROTOCOL_CONN_TOKEN,\n\tWS_PROTOCOL_ENCODING,\n\tWS_PROTOCOL_TARGET,\n} from \"@/common/actor-router-consts\";\nimport { deconstructError, noopNext } from \"@/common/utils\";\nimport type { UniversalWebSocket, UpgradeWebSocketArgs } from \"@/mod\";\nimport type { RunConfig } from \"@/registry/run-config\";\nimport { promiseWithResolvers, stringifyError } from \"@/utils\";\nimport type { ManagerDriver } from \"./driver\";\nimport { logger } from \"./log\";\n\n/**\n * Provides an endpoint to connect to individual actors.\n *\n * Routes requests based on the Upgrade header:\n * - WebSocket requests: Uses sec-websocket-protocol for routing (target.actor, actor.{id})\n * - HTTP requests: Uses x-rivet-target and x-rivet-actor headers for routing\n */\nexport async function actorGateway(\n\trunConfig: RunConfig,\n\tmanagerDriver: ManagerDriver,\n\tc: HonoContext,\n\tnext: Next,\n) {\n\t// Skip test routes - let them be handled by their specific handlers\n\tif (c.req.path.startsWith(\"/.test/\")) {\n\t\treturn next();\n\t}\n\n\t// Check if this is a WebSocket upgrade request\n\tif (c.req.header(\"upgrade\") === \"websocket\") {\n\t\treturn await handleWebSocketGateway(runConfig, managerDriver, c);\n\t}\n\n\t// Handle regular HTTP requests\n\treturn await handleHttpGateway(managerDriver, c, next);\n}\n\n/**\n * Handle WebSocket requests using sec-websocket-protocol for routing\n */\nasync function handleWebSocketGateway(\n\trunConfig: RunConfig,\n\tmanagerDriver: ManagerDriver,\n\tc: HonoContext,\n) {\n\tconst upgradeWebSocket = runConfig.getUpgradeWebSocket?.();\n\tif (!upgradeWebSocket) {\n\t\tthrow new WebSocketsNotEnabled();\n\t}\n\n\t// Parse configuration from Sec-WebSocket-Protocol header\n\tconst protocols = c.req.header(\"sec-websocket-protocol\");\n\tlet target: string | undefined;\n\tlet actorId: string | undefined;\n\tlet encodingRaw: string | undefined;\n\tlet connParamsRaw: string | undefined;\n\tlet connIdRaw: string | undefined;\n\tlet connTokenRaw: string | undefined;\n\n\tif (protocols) {\n\t\tconst protocolList = protocols.split(\",\").map((p) => p.trim());\n\t\tfor (const protocol of protocolList) {\n\t\t\tif (protocol.startsWith(WS_PROTOCOL_TARGET)) {\n\t\t\t\ttarget = protocol.substring(WS_PROTOCOL_TARGET.length);\n\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_ACTOR)) {\n\t\t\t\tactorId = protocol.substring(WS_PROTOCOL_ACTOR.length);\n\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_ENCODING)) {\n\t\t\t\tencodingRaw = protocol.substring(WS_PROTOCOL_ENCODING.length);\n\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_PARAMS)) {\n\t\t\t\tconnParamsRaw = decodeURIComponent(\n\t\t\t\t\tprotocol.substring(WS_PROTOCOL_CONN_PARAMS.length),\n\t\t\t\t);\n\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_ID)) {\n\t\t\t\tconnIdRaw = protocol.substring(WS_PROTOCOL_CONN_ID.length);\n\t\t\t} else if (protocol.startsWith(WS_PROTOCOL_CONN_TOKEN)) {\n\t\t\t\tconnTokenRaw = protocol.substring(WS_PROTOCOL_CONN_TOKEN.length);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (target !== \"actor\") {\n\t\treturn c.text(\"WebSocket upgrade requires target.actor protocol\", 400);\n\t}\n\n\tif (!actorId) {\n\t\tthrow new MissingActorHeader();\n\t}\n\n\tlogger().debug({\n\t\tmsg: \"proxying websocket to actor\",\n\t\tactorId,\n\t\tpath: c.req.path,\n\t\tencoding: encodingRaw,\n\t});\n\n\tconst encoding = encodingRaw || \"json\";\n\tconst connParams = connParamsRaw ? JSON.parse(connParamsRaw) : undefined;\n\n\t// Include query string if present\n\tconst pathWithQuery = c.req.url.includes(\"?\")\n\t\t? c.req.path + c.req.url.substring(c.req.url.indexOf(\"?\"))\n\t\t: c.req.path;\n\n\treturn await managerDriver.proxyWebSocket(\n\t\tc,\n\t\tpathWithQuery,\n\t\tactorId,\n\t\tencoding as any, // Will be validated by driver\n\t\tconnParams,\n\t\tconnIdRaw,\n\t\tconnTokenRaw,\n\t);\n}\n\n/**\n * Handle HTTP requests using x-rivet headers for routing\n */\nasync function handleHttpGateway(\n\tmanagerDriver: ManagerDriver,\n\tc: HonoContext,\n\tnext: Next,\n) {\n\tconst target = c.req.header(HEADER_RIVET_TARGET);\n\tconst actorId = c.req.header(HEADER_RIVET_ACTOR);\n\n\tif (target !== \"actor\") {\n\t\treturn next();\n\t}\n\n\tif (!actorId) {\n\t\tthrow new MissingActorHeader();\n\t}\n\n\tlogger().debug({\n\t\tmsg: \"proxying request to actor\",\n\t\tactorId,\n\t\tpath: c.req.path,\n\t\tmethod: c.req.method,\n\t});\n\n\t// Preserve all headers except the routing headers\n\tconst proxyHeaders = new Headers(c.req.raw.headers);\n\tproxyHeaders.delete(HEADER_RIVET_TARGET);\n\tproxyHeaders.delete(HEADER_RIVET_ACTOR);\n\n\t// Build the proxy request with the actor URL format\n\tconst url = new URL(c.req.url);\n\tconst proxyUrl = new URL(`http://actor${url.pathname}${url.search}`);\n\n\tconst proxyRequest = new Request(proxyUrl, {\n\t\tmethod: c.req.raw.method,\n\t\theaders: proxyHeaders,\n\t\tbody: c.req.raw.body,\n\t\tsignal: c.req.raw.signal,\n\t});\n\n\treturn await managerDriver.proxyRequest(c, proxyRequest, actorId);\n}\n\n/**\n * Creates a WebSocket proxy for test endpoints that forwards messages between server and client WebSockets\n */\nexport async function createTestWebSocketProxy(\n\tclientWsPromise: Promise<UniversalWebSocket>,\n): Promise<UpgradeWebSocketArgs> {\n\t// Store a reference to the resolved WebSocket\n\tlet clientWs: UniversalWebSocket | null = null;\n\tconst {\n\t\tpromise: serverWsPromise,\n\t\tresolve: serverWsResolve,\n\t\treject: serverWsReject,\n\t} = promiseWithResolvers<WSContext>();\n\ttry {\n\t\t// Resolve the client WebSocket promise\n\t\tlogger().debug({ msg: \"awaiting client websocket promise\" });\n\t\tconst ws = await clientWsPromise;\n\t\tclientWs = ws;\n\t\tlogger().debug({\n\t\t\tmsg: \"client websocket promise resolved\",\n\t\t\tconstructor: ws?.constructor.name,\n\t\t});\n\n\t\t// Wait for ws to open\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst onOpen = () => {\n\t\t\t\tlogger().debug({ msg: \"test websocket connection to actor opened\" });\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst onError = (error: any) => {\n\t\t\t\tlogger().error({ msg: \"test websocket connection failed\", error });\n\t\t\t\treject(\n\t\t\t\t\tnew Error(`Failed to open WebSocket: ${error.message || error}`),\n\t\t\t\t);\n\t\t\t\tserverWsReject();\n\t\t\t};\n\n\t\t\tws.addEventListener(\"open\", onOpen);\n\n\t\t\tws.addEventListener(\"error\", onError);\n\n\t\t\tws.addEventListener(\"message\", async (clientEvt: MessageEvent) => {\n\t\t\t\tconst serverWs = await serverWsPromise;\n\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: `test websocket connection message from client`,\n\t\t\t\t\tdataType: typeof clientEvt.data,\n\t\t\t\t\tisBlob: clientEvt.data instanceof Blob,\n\t\t\t\t\tisArrayBuffer: clientEvt.data instanceof ArrayBuffer,\n\t\t\t\t\tdataConstructor: clientEvt.data?.constructor?.name,\n\t\t\t\t\tdataStr:\n\t\t\t\t\t\ttypeof clientEvt.data === \"string\"\n\t\t\t\t\t\t\t? clientEvt.data.substring(0, 100)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t});\n\n\t\t\t\tif (serverWs.readyState === 1) {\n\t\t\t\t\t// OPEN\n\t\t\t\t\t// Handle Blob data\n\t\t\t\t\tif (clientEvt.data instanceof Blob) {\n\t\t\t\t\t\tclientEvt.data\n\t\t\t\t\t\t\t.arrayBuffer()\n\t\t\t\t\t\t\t.then((buffer) => {\n\t\t\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\t\t\tmsg: \"converted client blob to arraybuffer, sending to server\",\n\t\t\t\t\t\t\t\t\tbufferSize: buffer.byteLength,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tserverWs.send(buffer as any);\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.catch((error) => {\n\t\t\t\t\t\t\t\tlogger().error({\n\t\t\t\t\t\t\t\t\tmsg: \"failed to convert blob to arraybuffer\",\n\t\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\tmsg: \"sending client data directly to server\",\n\t\t\t\t\t\t\tdataType: typeof clientEvt.data,\n\t\t\t\t\t\t\tdataLength:\n\t\t\t\t\t\t\t\ttypeof clientEvt.data === \"string\"\n\t\t\t\t\t\t\t\t\t? clientEvt.data.length\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tserverWs.send(clientEvt.data as any);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.addEventListener(\"close\", async (clientEvt: any) => {\n\t\t\t\tconst serverWs = await serverWsPromise;\n\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: `test websocket connection closed`,\n\t\t\t\t});\n\n\t\t\t\tif (serverWs.readyState !== 3) {\n\t\t\t\t\t// Not CLOSED\n\t\t\t\t\tserverWs.close(clientEvt.code, clientEvt.reason);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tws.addEventListener(\"error\", async () => {\n\t\t\t\tconst serverWs = await serverWsPromise;\n\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: `test websocket connection error`,\n\t\t\t\t});\n\n\t\t\t\tif (serverWs.readyState !== 3) {\n\t\t\t\t\t// Not CLOSED\n\t\t\t\t\tserverWs.close(1011, \"Error in client websocket\");\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t} catch (error) {\n\t\tlogger().error({\n\t\t\tmsg: `failed to establish client websocket connection`,\n\t\t\terror,\n\t\t});\n\t\treturn {\n\t\t\tonOpen: (_evt, serverWs) => {\n\t\t\t\tserverWs.close(1011, \"Failed to establish connection\");\n\t\t\t},\n\t\t\tonMessage: () => {},\n\t\t\tonError: () => {},\n\t\t\tonClose: () => {},\n\t\t};\n\t}\n\n\t// Create WebSocket proxy handlers to relay messages between client and server\n\treturn {\n\t\tonOpen: (_evt: any, serverWs: WSContext) => {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: `test websocket connection from client opened`,\n\t\t\t});\n\n\t\t\t// Check WebSocket type\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"clientWs info\",\n\t\t\t\tconstructor: clientWs.constructor.name,\n\t\t\t\thasAddEventListener: typeof clientWs.addEventListener === \"function\",\n\t\t\t\treadyState: clientWs.readyState,\n\t\t\t});\n\n\t\t\tserverWsResolve(serverWs);\n\t\t},\n\t\tonMessage: (evt: { data: any }) => {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"received message from server\",\n\t\t\t\tdataType: typeof evt.data,\n\t\t\t\tisBlob: evt.data instanceof Blob,\n\t\t\t\tisArrayBuffer: evt.data instanceof ArrayBuffer,\n\t\t\t\tdataConstructor: evt.data?.constructor?.name,\n\t\t\t\tdataStr:\n\t\t\t\t\ttypeof evt.data === \"string\" ? evt.data.substring(0, 100) : undefined,\n\t\t\t});\n\n\t\t\t// Forward messages from server websocket to client websocket\n\t\t\tif (clientWs.readyState === 1) {\n\t\t\t\t// OPEN\n\t\t\t\t// Handle Blob data\n\t\t\t\tif (evt.data instanceof Blob) {\n\t\t\t\t\tevt.data\n\t\t\t\t\t\t.arrayBuffer()\n\t\t\t\t\t\t.then((buffer) => {\n\t\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\t\tmsg: \"converted blob to arraybuffer, sending\",\n\t\t\t\t\t\t\t\tbufferSize: buffer.byteLength,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tclientWs.send(buffer);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.catch((error) => {\n\t\t\t\t\t\t\tlogger().error({\n\t\t\t\t\t\t\t\tmsg: \"failed to convert blob to arraybuffer\",\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\tmsg: \"sending data directly\",\n\t\t\t\t\t\tdataType: typeof evt.data,\n\t\t\t\t\t\tdataLength:\n\t\t\t\t\t\t\ttypeof evt.data === \"string\" ? evt.data.length : undefined,\n\t\t\t\t\t});\n\t\t\t\t\tclientWs.send(evt.data);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tonClose: (\n\t\t\tevent: {\n\t\t\t\twasClean: boolean;\n\t\t\t\tcode: number;\n\t\t\t\treason: string;\n\t\t\t},\n\t\t\tserverWs: WSContext,\n\t\t) => {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: `server websocket closed`,\n\t\t\t\twasClean: event.wasClean,\n\t\t\t\tcode: event.code,\n\t\t\t\treason: event.reason,\n\t\t\t});\n\n\t\t\t// HACK: Close socket in order to fix bug with Cloudflare leaving WS in closing state\n\t\t\t// https://github.com/cloudflare/workerd/issues/2569\n\t\t\tserverWs.close(1000, \"hack_force_close\");\n\n\t\t\t// Close the client websocket when the server websocket closes\n\t\t\tif (\n\t\t\t\tclientWs &&\n\t\t\t\tclientWs.readyState !== clientWs.CLOSED &&\n\t\t\t\tclientWs.readyState !== clientWs.CLOSING\n\t\t\t) {\n\t\t\t\t// Don't pass code/message since this may affect how close events are triggered\n\t\t\t\tclientWs.close(1000, event.reason);\n\t\t\t}\n\t\t},\n\t\tonError: (error: unknown) => {\n\t\t\tlogger().error({\n\t\t\t\tmsg: `error in server websocket`,\n\t\t\t\terror,\n\t\t\t});\n\n\t\t\t// Close the client websocket on error\n\t\t\tif (\n\t\t\t\tclientWs &&\n\t\t\t\tclientWs.readyState !== clientWs.CLOSED &&\n\t\t\t\tclientWs.readyState !== clientWs.CLOSING\n\t\t\t) {\n\t\t\t\tclientWs.close(1011, \"Error in server websocket\");\n\t\t\t}\n\n\t\t\tserverWsReject();\n\t\t},\n\t};\n}\n","//! These configs configs hold anything that's not platform-specific about running actors.\n\nimport { z } from \"zod\";\nimport type { ActorDefinition, AnyActorDefinition } from \"@/actor/definition\";\n\nexport const ActorsSchema = z.record(\n\tz.string(),\n\tz.custom<ActorDefinition<any, any, any, any, any, any, any>>(),\n);\nexport type RegistryActors = z.infer<typeof ActorsSchema>;\n\nexport const TestConfigSchema = z.object({ enabled: z.boolean() });\nexport type TestConfig = z.infer<typeof TestConfigSchema>;\n\n/** Base config used for the actor config across all platforms. */\nexport const RegistryConfigSchema = z.object({\n\tuse: z.record(z.string(), z.custom<AnyActorDefinition>()),\n\n\t// TODO: Find a better way of passing around the test config\n\t/**\n\t * Test configuration.\n\t *\n\t * DO NOT MANUALLY ENABLE. THIS IS USED INTERNALLY.\n\t * @internal\n\t **/\n\ttest: TestConfigSchema.optional().default({ enabled: false }),\n});\nexport type RegistryConfig = z.infer<typeof RegistryConfigSchema>;\nexport type RegistryConfigInput<A extends RegistryActors> = Omit<\n\tz.input<typeof RegistryConfigSchema>,\n\t\"use\"\n> & { use: A };\n","import { getLogger } from \"@/common/log\";\n\nexport function logger() {\n\treturn getLogger(\"registry\");\n}\n","import { Hono } from \"hono\";\nimport { logger } from \"./log\";\n\nexport async function crossPlatformServe(\n\trivetKitRouter: Hono<any>,\n\tuserRouter: Hono | undefined,\n) {\n\tconst app = userRouter ?? new Hono();\n\n\t// Import @hono/node-server\n\tlet serve: any;\n\ttry {\n\t\tconst dep = await import(\n\t\t\t/* webpackIgnore: true */\n\t\t\t\"@hono/node-server\"\n\t\t);\n\t\tserve = dep.serve;\n\t} catch (err) {\n\t\tlogger().error(\n\t\t\t\"failed to import @hono/node-server. please run 'npm install @hono/node-server @hono/node-ws'\",\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\t// Mount registry\n\t// app.route(\"/registry\", rivetKitRouter);\n\tapp.route(\"/\", rivetKitRouter);\n\n\t// Import @hono/node-ws\n\tlet createNodeWebSocket: any;\n\ttry {\n\t\tconst dep = await import(\n\t\t\t/* webpackIgnore: true */\n\t\t\t\"@hono/node-ws\"\n\t\t);\n\t\tcreateNodeWebSocket = dep.createNodeWebSocket;\n\t} catch (err) {\n\t\tlogger().error(\n\t\t\t\"failed to import @hono/node-ws. please run 'npm install @hono/node-server @hono/node-ws'\",\n\t\t);\n\t\tprocess.exit(1);\n\t}\n\n\t// Inject WS\n\tconst { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({\n\t\tapp,\n\t});\n\n\t// Start server\n\tconst port = 6420;\n\tconst server = serve({ fetch: app.fetch, port }, () =>\n\t\tlogger().info({ msg: \"server listening\", port }),\n\t);\n\tinjectWebSocket(server);\n\n\treturn { upgradeWebSocket };\n}\n","import { type Client, createClientWithDriver } from \"@/client/client\";\nimport { configureBaseLogger, configureDefaultLogger } from \"@/common/log\";\nimport type { ActorDriver } from \"@/driver-helpers/mod\";\nimport { chooseDefaultDriver } from \"@/drivers/default\";\nimport {\n\tconfigureInspectorAccessToken,\n\tgetInspectorUrl,\n\tisInspectorEnabled,\n} from \"@/inspector/utils\";\nimport { createManagerRouter } from \"@/manager/router\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\nimport {\n\ttype RegistryActors,\n\ttype RegistryConfig,\n\ttype RegistryConfigInput,\n\tRegistryConfigSchema,\n} from \"./config\";\nimport { logger } from \"./log\";\nimport {\n\ttype DriverConfig,\n\ttype RunConfig,\n\ttype RunConfigInput,\n\tRunConfigSchema,\n} from \"./run-config\";\nimport { crossPlatformServe } from \"./serve\";\n\ninterface ServerOutput<A extends Registry<any>> {\n\t/** Client to communicate with the actors. */\n\tclient: Client<A>;\n\t/** Fetch handler to manually route requests to the Rivet manager API. */\n\tfetch: (request: Request, ...args: any) => Response | Promise<Response>;\n}\n\nexport class Registry<A extends RegistryActors> {\n\t#config: RegistryConfig;\n\n\tpublic get config(): RegistryConfig {\n\t\treturn this.#config;\n\t}\n\n\tconstructor(config: RegistryConfig) {\n\t\tthis.#config = config;\n\t}\n\n\t/**\n\t * Runs the registry for a server.\n\t */\n\tpublic start(inputConfig?: RunConfigInput): ServerOutput<this> {\n\t\tconst config = RunConfigSchema.parse(inputConfig);\n\n\t\t// Configure logger\n\t\tif (config.logging?.baseLogger) {\n\t\t\t// Use provided base logger\n\t\t\tconfigureBaseLogger(config.logging.baseLogger);\n\t\t} else {\n\t\t\t// Configure default logger with log level from config\n\t\t\t// getPinoLevel will handle env variable priority\n\t\t\tconfigureDefaultLogger(config.logging?.level);\n\t\t}\n\n\t\t// Choose the driver based on configuration\n\t\tconst driver = chooseDefaultDriver(config);\n\n\t\t// TODO: Find cleaner way of disabling by default\n\t\tif (driver.name === \"engine\") {\n\t\t\tconfig.inspector.enabled = { manager: false, actor: true };\n\t\t\tconfig.disableServer = true;\n\t\t}\n\t\tif (driver.name === \"cloudflare-workers\") {\n\t\t\tconfig.inspector.enabled = { manager: false, actor: true };\n\t\t\tconfig.disableServer = true;\n\t\t\tconfig.disableActorDriver = true;\n\t\t\tconfig.noWelcome = true;\n\t\t}\n\n\t\t// Configure getUpgradeWebSocket lazily so we can assign it in crossPlatformServe\n\t\tlet upgradeWebSocket: any;\n\t\tif (!config.getUpgradeWebSocket) {\n\t\t\tconfig.getUpgradeWebSocket = () => upgradeWebSocket!;\n\t\t}\n\n\t\t// Create router\n\t\tconst managerDriver = driver.manager(this.#config, config);\n\t\tconfigureInspectorAccessToken(config, managerDriver);\n\n\t\t// Create client\n\t\tconst client = createClientWithDriver<this>(managerDriver, config);\n\n\t\tconst driverLog = managerDriver.extraStartupLog?.() ?? {};\n\t\tlogger().info({\n\t\t\tmsg: \"rivetkit ready\",\n\t\t\tdriver: driver.name,\n\t\t\tdefinitions: Object.keys(this.#config.use).length,\n\t\t\t...driverLog,\n\t\t});\n\t\tif (isInspectorEnabled(config, \"manager\") && managerDriver.inspector) {\n\t\t\tlogger().info({ msg: \"inspector ready\", url: getInspectorUrl(config) });\n\t\t}\n\n\t\t// Print welcome information\n\t\tif (!config.noWelcome) {\n\t\t\tconst displayInfo = managerDriver.displayInformation();\n\t\t\tconsole.log();\n\t\t\tconsole.log(` RivetKit ${pkg.version} (${displayInfo.name})`);\n\t\t\tconsole.log(` - Endpoint: http://127.0.0.1:6420`);\n\t\t\tfor (const [k, v] of Object.entries(displayInfo.properties)) {\n\t\t\t\tconst padding = \" \".repeat(Math.max(0, 13 - k.length));\n\t\t\t\tconsole.log(` - ${k}:${padding}${v}`);\n\t\t\t}\n\t\t\tif (isInspectorEnabled(config, \"manager\") && managerDriver.inspector) {\n\t\t\t\tconsole.log(` - Inspector: ${getInspectorUrl(config)}`);\n\t\t\t}\n\t\t\tconsole.log();\n\t\t}\n\n\t\t// HACK: We need to find a better way to let the driver itself decide when to start the actor driver\n\t\t// Create runner\n\t\t//\n\t\t// Even though we do not use the return value, this is required to start the code that will handle incoming actors\n\t\tif (!config.disableActorDriver) {\n\t\t\tconst _actorDriver = driver.actor(\n\t\t\t\tthis.#config,\n\t\t\t\tconfig,\n\t\t\t\tmanagerDriver,\n\t\t\t\tclient,\n\t\t\t);\n\t\t}\n\n\t\tconst { router: hono } = createManagerRouter(\n\t\t\tthis.#config,\n\t\t\tconfig,\n\t\t\tmanagerDriver,\n\t\t\tundefined,\n\t\t);\n\n\t\t// Start server\n\t\tif (!config.disableServer) {\n\t\t\t(async () => {\n\t\t\t\tconst out = await crossPlatformServe(hono, undefined);\n\t\t\t\tupgradeWebSocket = out.upgradeWebSocket;\n\t\t\t})();\n\t\t}\n\n\t\treturn {\n\t\t\tclient,\n\t\t\tfetch: hono.fetch.bind(hono),\n\t\t};\n\t}\n\n\tpublic startServerless(inputConfig?: RunConfigInput): ServerOutput<this> {\n\t\tconst config = RunConfigSchema.parse(inputConfig);\n\n\t\t// Configure logger\n\t\tif (config.logging?.baseLogger) {\n\t\t\t// Use provided base logger\n\t\t\tconfigureBaseLogger(config.logging.baseLogger);\n\t\t} else {\n\t\t\t// Configure default logger with log level from config\n\t\t\t// getPinoLevel will handle env variable priority\n\t\t\tconfigureDefaultLogger(config.logging?.level);\n\t\t}\n\n\t\t// Choose the driver based on configuration\n\t\tconst driver = chooseDefaultDriver(config);\n\n\t\t// TODO: Find cleaner way of disabling by default\n\t\tif (driver.name === \"engine\") {\n\t\t\tconfig.inspector.enabled = false;\n\t\t\tconfig.disableServer = true;\n\t\t\tconfig.disableActorDriver = true;\n\t\t}\n\t\tif (driver.name === \"cloudflare-workers\") {\n\t\t\tconfig.inspector.enabled = false;\n\t\t\tconfig.disableServer = true;\n\t\t\tconfig.disableActorDriver = true;\n\t\t\tconfig.noWelcome = true;\n\t\t}\n\n\t\t// Configure getUpgradeWebSocket lazily so we can assign it in crossPlatformServe\n\t\tlet upgradeWebSocket: any;\n\t\tif (!config.getUpgradeWebSocket) {\n\t\t\tconfig.getUpgradeWebSocket = () => upgradeWebSocket!;\n\t\t}\n\n\t\t// Create router\n\t\tconst managerDriver = driver.manager(this.#config, config);\n\n\t\t// Create client\n\t\tconst client = createClientWithDriver<this>(managerDriver, config);\n\n\t\tconst driverLog = managerDriver.extraStartupLog?.() ?? {};\n\t\tlogger().info({\n\t\t\tmsg: \"rivetkit ready\",\n\t\t\tdriver: driver.name,\n\t\t\tdefinitions: Object.keys(this.#config.use).length,\n\t\t\t...driverLog,\n\t\t});\n\t\tif (config.inspector?.enabled && managerDriver.inspector) {\n\t\t\tlogger().info({ msg: \"inspector ready\", url: getInspectorUrl(config) });\n\t\t}\n\n\t\t// Print welcome information\n\t\tif (!config.noWelcome) {\n\t\t\tconst displayInfo = managerDriver.displayInformation();\n\t\t\tconsole.log();\n\t\t\tconsole.log(` RivetKit ${pkg.version} (${displayInfo.name})`);\n\t\t\tconsole.log(` - Endpoint: http://127.0.0.1:6420`);\n\t\t\tfor (const [k, v] of Object.entries(displayInfo.properties)) {\n\t\t\t\tconst padding = \" \".repeat(Math.max(0, 13 - k.length));\n\t\t\t\tconsole.log(` - ${k}:${padding}${v}`);\n\t\t\t}\n\t\t\tif (config.inspector?.enabled && managerDriver.inspector) {\n\t\t\t\tconsole.log(` - Inspector: ${getInspectorUrl(config)}`);\n\t\t\t}\n\t\t\tconsole.log();\n\t\t}\n\n\t\tlet serverlessActorDriverBuilder: (() => ActorDriver) | undefined = () => {\n\t\t\treturn driver.actor(this.#config, config, managerDriver, client);\n\t\t};\n\n\t\t// HACK: We need to find a better way to let the driver itself decide when to start the actor driver\n\t\t// Create runner\n\t\t//\n\t\t// Even though we do not use the return value, this is required to start the code that will handle incoming actors\n\t\tif (!config.disableActorDriver) {\n\t\t\tconst _actorDriver = serverlessActorDriverBuilder();\n\t\t\tserverlessActorDriverBuilder = undefined;\n\t\t}\n\n\t\tconst { router: hono } = createManagerRouter(\n\t\t\tthis.#config,\n\t\t\tconfig,\n\t\t\tmanagerDriver,\n\t\t\tserverlessActorDriverBuilder,\n\t\t);\n\n\t\t// Start server\n\t\tif (!config.disableServer) {\n\t\t\t(async () => {\n\t\t\t\tconst out = await crossPlatformServe(hono, undefined);\n\t\t\t\tupgradeWebSocket = out.upgradeWebSocket;\n\t\t\t})();\n\t\t}\n\n\t\treturn {\n\t\t\tclient,\n\t\t\tfetch: hono.fetch.bind(hono),\n\t\t};\n\t}\n}\n\nexport function setup<A extends RegistryActors>(\n\tinput: RegistryConfigInput<A>,\n): Registry<A> {\n\tconst config = RegistryConfigSchema.parse(input);\n\treturn new Registry(config);\n}\n\nexport type {\n\tRegistryConfig,\n\tRegistryActors,\n\tRunConfig,\n\tRunConfigInput,\n\tDriverConfig,\n};\nexport { RegistryConfigSchema };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;AAqCX,IAAM,oBAAoB,EAC/B,OAAO;AAAA,EACP,UAAU,EAAE,SAAS,EAAE,SAAS;AAAA,EAChC,SAAS,EAAE,SAAS,EAAE,SAAS;AAAA,EAC/B,QAAQ,EAAE,SAAS,EAAE,SAAS;AAAA,EAC9B,eAAe,EAAE,SAAS,EAAE,SAAS;AAAA,EACrC,iBAAiB,EAAE,SAAS,EAAE,SAAS;AAAA,EACvC,WAAW,EAAE,SAAS,EAAE,SAAS;AAAA,EACjC,cAAc,EAAE,SAAS,EAAE,SAAS;AAAA,EACpC,wBAAwB,EAAE,SAAS,EAAE,SAAS;AAAA,EAC9C,SAAS,EAAE,SAAS,EAAE,SAAS;AAAA,EAC/B,aAAa,EAAE,SAAS,EAAE,SAAS;AAAA,EACnC,SAAS,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EAC1C,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EACxB,aAAa,EAAE,SAAS,EAAE,SAAS;AAAA,EACnC,WAAW,EAAE,IAAI,EAAE,SAAS;AAAA,EAC5B,iBAAiB,EAAE,SAAS,EA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AAM,MAAS;AACpD,2BAAmB,IAAI;AAAA,MACxB,GAAG;AAAA,IACJ;AAEA,WAAO;AAAA,MACN;AAAA,MACA,OAAO,KAAK,MAAM,KAAK,IAAI;AAAA,IAC5B;AAAA,EACD;AACD;AAEO,SAAS,MACf,OACc;AACd,QAAMA,UAAS,qBAAqB,MAAM,KAAK;AAC/C,SAAO,IAAI,SAASA,OAAM;AAC3B;","names":["invariant","actor","path","cbor","logger","path","actor","c","invariant","config","logger","cbor","streamSSE","WSContext","invariant","logger","config","logger","actor","invariant","WSContext","streamSSE","z","z","config","actor","crypto","fsSync","fs","path","invariant","logger","crypto","path","logger","invariant","actor","invariant","Hono","Hono","actor","transformActor","actor","path","invariant","logger","cbor","Hono","invariant","z","z","z","z","cors","invariant","z","actor","_a","c","path","Hono","z","logger","Hono","Hono","logger","config","logger"]}
|