rivetkit 2.0.14 → 2.0.16

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.
Files changed (73) hide show
  1. package/dist/tsup/{chunk-3HCSWRUA.cjs → chunk-3DCOI5K7.cjs} +8 -8
  2. package/dist/tsup/{chunk-3HCSWRUA.cjs.map → chunk-3DCOI5K7.cjs.map} +1 -1
  3. package/dist/tsup/{chunk-SXEHZODB.cjs → chunk-5IJOWDWM.cjs} +211 -201
  4. package/dist/tsup/chunk-5IJOWDWM.cjs.map +1 -0
  5. package/dist/tsup/{chunk-INNBRUPH.cjs → chunk-BYE4DZ6O.cjs} +14 -14
  6. package/dist/tsup/{chunk-INNBRUPH.cjs.map → chunk-BYE4DZ6O.cjs.map} +1 -1
  7. package/dist/tsup/{chunk-DJDDJDWR.cjs → chunk-E67WWRQI.cjs} +12 -12
  8. package/dist/tsup/{chunk-DJDDJDWR.cjs.map → chunk-E67WWRQI.cjs.map} +1 -1
  9. package/dist/tsup/{chunk-ATMZDEVA.cjs → chunk-ESUKZPDA.cjs} +3 -3
  10. package/dist/tsup/{chunk-ATMZDEVA.cjs.map → chunk-ESUKZPDA.cjs.map} +1 -1
  11. package/dist/tsup/{chunk-MF76IOZD.cjs → chunk-GY6U6LVW.cjs} +7 -7
  12. package/dist/tsup/{chunk-MF76IOZD.cjs.map → chunk-GY6U6LVW.cjs.map} +1 -1
  13. package/dist/tsup/{chunk-PO352AW7.js → chunk-IZCQKDOT.js} +2 -2
  14. package/dist/tsup/{chunk-HNC6Y6JC.cjs → chunk-KVIKPT4T.cjs} +208 -208
  15. package/dist/tsup/{chunk-HNC6Y6JC.cjs.map → chunk-KVIKPT4T.cjs.map} +1 -1
  16. package/dist/tsup/{chunk-QZWHQAOF.cjs → chunk-LHYMXJFI.cjs} +6 -6
  17. package/dist/tsup/{chunk-QZWHQAOF.cjs.map → chunk-LHYMXJFI.cjs.map} +1 -1
  18. package/dist/tsup/{chunk-G3R2O5VL.js → chunk-MIX6ZN57.js} +92 -82
  19. package/dist/tsup/chunk-MIX6ZN57.js.map +1 -0
  20. package/dist/tsup/{chunk-3LGDBNZG.js → chunk-MLBIVAMM.js} +2 -2
  21. package/dist/tsup/{chunk-Q6ESJU7P.cjs → chunk-N7ICOIWW.cjs} +26 -26
  22. package/dist/tsup/{chunk-Q6ESJU7P.cjs.map → chunk-N7ICOIWW.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-SQPFZW4U.js → chunk-NC7XHLWT.js} +6 -6
  24. package/dist/tsup/{chunk-EY5EMNAB.js → chunk-O2GJQSMM.js} +2 -2
  25. package/dist/tsup/{chunk-EY5EMNAB.js.map → chunk-O2GJQSMM.js.map} +1 -1
  26. package/dist/tsup/{chunk-ZD5CZSSF.js → chunk-OWTB6Z2E.js} +10 -10
  27. package/dist/tsup/{chunk-OWPBIHFM.cjs → chunk-Q6GERFRB.cjs} +2 -2
  28. package/dist/tsup/{chunk-OWPBIHFM.cjs.map → chunk-Q6GERFRB.cjs.map} +1 -1
  29. package/dist/tsup/{chunk-43PTNF7W.js → chunk-RCDOEPDO.js} +3 -3
  30. package/dist/tsup/{chunk-XQR2BHQP.js → chunk-SHJXQIRA.js} +4 -4
  31. package/dist/tsup/{chunk-5C3MRFAU.js → chunk-TILGZ45J.js} +2 -2
  32. package/dist/tsup/{chunk-HY3MZSKX.js → chunk-W4U4VMXG.js} +3 -3
  33. package/dist/tsup/{chunk-FNCNYJFG.cjs → chunk-WOWWTL7O.cjs} +3 -3
  34. package/dist/tsup/{chunk-FNCNYJFG.cjs.map → chunk-WOWWTL7O.cjs.map} +1 -1
  35. package/dist/tsup/{chunk-FNQGHSFJ.js → chunk-YZVPBLQL.js} +2 -2
  36. package/dist/tsup/client/mod.cjs +9 -9
  37. package/dist/tsup/client/mod.js +8 -8
  38. package/dist/tsup/common/log.cjs +3 -3
  39. package/dist/tsup/common/log.js +2 -2
  40. package/dist/tsup/common/websocket.cjs +4 -4
  41. package/dist/tsup/common/websocket.js +3 -3
  42. package/dist/tsup/driver-helpers/mod.cjs +5 -5
  43. package/dist/tsup/driver-helpers/mod.js +4 -4
  44. package/dist/tsup/driver-test-suite/mod.cjs +71 -71
  45. package/dist/tsup/driver-test-suite/mod.cjs.map +1 -1
  46. package/dist/tsup/driver-test-suite/mod.js +13 -13
  47. package/dist/tsup/inspector/mod.cjs +6 -6
  48. package/dist/tsup/inspector/mod.js +5 -5
  49. package/dist/tsup/mod.cjs +10 -10
  50. package/dist/tsup/mod.cjs.map +1 -1
  51. package/dist/tsup/mod.js +9 -9
  52. package/dist/tsup/test/mod.cjs +11 -11
  53. package/dist/tsup/test/mod.js +10 -10
  54. package/dist/tsup/utils.cjs +2 -2
  55. package/dist/tsup/utils.js +1 -1
  56. package/package.json +1 -1
  57. package/src/common/router.ts +12 -2
  58. package/src/drivers/default.ts +5 -1
  59. package/src/drivers/engine/actor-driver.ts +2 -7
  60. package/src/manager/router.ts +6 -2
  61. package/src/registry/config.ts +8 -0
  62. package/src/registry/mod.ts +2 -1
  63. package/dist/tsup/chunk-G3R2O5VL.js.map +0 -1
  64. package/dist/tsup/chunk-SXEHZODB.cjs.map +0 -1
  65. /package/dist/tsup/{chunk-PO352AW7.js.map → chunk-IZCQKDOT.js.map} +0 -0
  66. /package/dist/tsup/{chunk-3LGDBNZG.js.map → chunk-MLBIVAMM.js.map} +0 -0
  67. /package/dist/tsup/{chunk-SQPFZW4U.js.map → chunk-NC7XHLWT.js.map} +0 -0
  68. /package/dist/tsup/{chunk-ZD5CZSSF.js.map → chunk-OWTB6Z2E.js.map} +0 -0
  69. /package/dist/tsup/{chunk-43PTNF7W.js.map → chunk-RCDOEPDO.js.map} +0 -0
  70. /package/dist/tsup/{chunk-XQR2BHQP.js.map → chunk-SHJXQIRA.js.map} +0 -0
  71. /package/dist/tsup/{chunk-5C3MRFAU.js.map → chunk-TILGZ45J.js.map} +0 -0
  72. /package/dist/tsup/{chunk-HY3MZSKX.js.map → chunk-W4U4VMXG.js.map} +0 -0
  73. /package/dist/tsup/{chunk-FNQGHSFJ.js.map → chunk-YZVPBLQL.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/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/registry/mod.ts","../../src/drivers/default.ts","../../src/engine-process/mod.ts","../../src/engine-process/log.ts","../../src/manager/router.ts","../../src/manager-api/actors.ts","../../src/manager-api/common.ts","../../src/manager/gateway.ts","../../src/manager/router-schema.ts","../../src/registry/config.ts","../../src/registry/log.ts","../../src/registry/serve.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 { RunnerConfig } 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: RunnerConfig,\n\tactorDriver: ActorDriver,\n\tisTest: boolean,\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\tif (isTest) {\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 connId = c.req.query(\"conn\");\n\n\t\t\tif (!connId) {\n\t\t\t\treturn c.text(\"Missing conn query parameter\", 400);\n\t\t\t}\n\n\t\t\tconst actor = await actorDriver.loadActor(c.env.actorId);\n\t\t\tconst conn = actor.__getConnForId(connId);\n\n\t\t\tif (!conn) {\n\t\t\t\treturn c.text(`Connection not found: ${connId}`, 404);\n\t\t\t}\n\n\t\t\t// Force close the websocket/SSE connection without clean shutdown\n\t\t\tconst driverState = conn.__driverState;\n\t\t\tif (driverState && ConnDriverKind.WEBSOCKET in driverState) {\n\t\t\t\tconst ws = driverState[ConnDriverKind.WEBSOCKET].websocket;\n\n\t\t\t\t// Force close without sending close frame\n\t\t\t\t(ws.raw as any).terminate();\n\t\t\t} else if (driverState && ConnDriverKind.SSE in driverState) {\n\t\t\t\tconst stream = driverState[ConnDriverKind.SSE].stream;\n\n\t\t\t\t// Force close the SSE stream\n\t\t\t\tstream.abort();\n\t\t\t}\n\n\t\t\treturn c.json({ success: true });\n\t\t});\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 { RunnerConfig } 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: RunnerConfig,\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\tconst wasClean = event.wasClean || event.code === 1000;\n\t\t\t\t\tactor.__connDisconnected(conn, 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: RunnerConfig,\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: RunnerConfig,\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: RunnerConfig,\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: RunnerConfig,\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 type { RunnerConfig } from \"@/registry/run-config\";\nimport { getEndpoint } from \"@/remote-manager-driver/api-utils\";\nimport { HttpResponseError } from \"@/schemas/client-protocol/mod\";\nimport { HTTP_RESPONSE_ERROR_VERSIONED } from \"@/schemas/client-protocol/versioned\";\nimport { encodingIsBinary, serializeWithEncoding } from \"@/serde\";\nimport { bufferToArrayBuffer, VERSION } 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\n/**\n * Metadata response interface for the /metadata endpoint\n */\nexport interface MetadataResponse {\n\truntime: string;\n\tversion: string;\n\trunner?: {\n\t\tkind:\n\t\t\t| { serverless: Record<never, never> }\n\t\t\t| { normal: Record<never, never> };\n\t};\n\t/**\n\t * Endpoint that the client should connect to to access this runner.\n\t *\n\t * If defined, will override the endpoint the user has configured on startup.\n\t *\n\t * This is helpful if attempting to connect to a serverless runner, so the serverless runner can define where the main endpoint lives.\n\t *\n\t * This is also helpful for setting up clean redirects as needed.\n\t **/\n\tclientEndpoint?: string;\n}\n\nexport function handleMetadataRequest(c: HonoContext, runConfig: RunnerConfig) {\n\tconst response: MetadataResponse = {\n\t\truntime: \"rivetkit\",\n\t\tversion: VERSION,\n\t\trunner: {\n\t\t\tkind:\n\t\t\t\trunConfig.runnerKind === \"serverless\"\n\t\t\t\t\t? { serverless: {} }\n\t\t\t\t\t: { normal: {} },\n\t\t},\n\t\tclientEndpoint: getEndpoint(runConfig),\n\t};\n\n\treturn c.json(response);\n}\n\nexport function handleHealthRequest(c: HonoContext) {\n\treturn c.json({\n\t\tstatus: \"ok\",\n\t\truntime: \"rivetkit\",\n\t\tversion: VERSION,\n\t});\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\tRunnerConfig as EngineRunnerConfig,\n\tActorConfig as RunnerActorConfig,\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 { RunnerConfig } from \"@/registry/run-config\";\nimport { getEndpoint } from \"@/remote-manager-driver/api-utils\";\nimport {\n\ttype LongTimeoutHandle,\n\tpromiseWithResolvers,\n\tsetLongTimeout,\n} from \"@/utils\";\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: RunnerConfig;\n\t#managerDriver: ManagerDriver;\n\t#inlineClient: Client<any>;\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\t#alarmTimeout?: LongTimeoutHandle;\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: RunnerConfig,\n\t\tmanagerDriver: ManagerDriver,\n\t\tinlineClient: Client<any>,\n\t) {\n\t\tthis.#registryConfig = registryConfig;\n\t\tthis.#runConfig = runConfig;\n\t\tthis.#managerDriver = managerDriver;\n\t\tthis.#inlineClient = inlineClient;\n\n\t\t// HACK: Override inspector token (which are likely to be\n\t\t// removed later on) with token from x-rivet-token header\n\t\tconst token = runConfig.token ?? runConfig.token;\n\t\tif (token && runConfig.inspector && runConfig.inspector.enabled) {\n\t\t\trunConfig.inspector.token = () => token;\n\t\t}\n\n\t\tthis.#actorRouter = createActorRouter(\n\t\t\trunConfig,\n\t\t\tthis,\n\t\t\tregistryConfig.test.enabled,\n\t\t);\n\n\t\t// Create runner configuration\n\t\tlet hasDisconnected = false;\n\t\tconst engineRunnerConfig: EngineRunnerConfig = {\n\t\t\tversion: this.#version,\n\t\t\tendpoint: getEndpoint(runConfig),\n\t\t\ttoken,\n\t\t\tnamespace: runConfig.namespace ?? runConfig.namespace,\n\t\t\ttotalSlots: runConfig.totalSlots ?? runConfig.totalSlots,\n\t\t\trunnerName: runConfig.runnerName ?? runConfig.runnerName,\n\t\t\trunnerKey: runConfig.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.#runConfig.namespace,\n\t\t\t\t\t\trunnerName: this.#runConfig.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.#runConfig.namespace,\n\t\t\t\t\t\trunnerName: this.#runConfig.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.#runConfig.namespace,\n\t\t\t\t\trunnerName: this.#runConfig.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(engineRunnerConfig);\n\t\tthis.#runner.start();\n\t\tlogger().debug({\n\t\t\tmsg: \"engine runner started\",\n\t\t\tendpoint: runConfig.endpoint,\n\t\t\tnamespace: runConfig.namespace,\n\t\t\trunnerName: runConfig.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\n\t\t// This was loaded during actor startup\n\t\treturn handler.persistedData;\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// Clear prev timeout\n\t\tif (this.#alarmTimeout) {\n\t\t\tthis.#alarmTimeout.abort();\n\t\t\tthis.#alarmTimeout = undefined;\n\t\t}\n\n\t\t// Set alarm\n\t\tconst delay = Math.max(0, timestamp - Date.now());\n\t\tthis.#alarmTimeout = setLongTimeout(() => {\n\t\t\tactor._onAlarm();\n\t\t\tthis.#alarmTimeout = undefined;\n\t\t}, delay);\n\n\t\t// TODO: This call may not be needed on ActorInstance.start, but it does help ensure that the local state is synced with the alarm state\n\t\t// Set alarm on Rivet\n\t\t//\n\t\t// This does not call an \"alarm\" event like Durable Objects.\n\t\t// Instead, it just wakes the actor on the alarm (if not\n\t\t// already awake).\n\t\t//\n\t\t// _onAlarm is automatically called on `ActorInstance.start` when waking\n\t\t// again.\n\t\tthis.#runner.setAlarm(actor.id, timestamp);\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\trunConfig: RunnerActorConfig,\n\t): Promise<void> {\n\t\tlogger().debug({\n\t\t\tmsg: \"runner actor starting\",\n\t\t\tactorId,\n\t\t\tname: runConfig.name,\n\t\t\tkey: runConfig.key,\n\t\t\tgeneration,\n\t\t});\n\n\t\t// Deserialize input\n\t\tlet input: any;\n\t\tif (runConfig.input) {\n\t\t\tinput = cbor.decode(runConfig.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\t// IMPORTANT: We must set the handler in the map synchronously before doing any\n\t\t\t// async operations to avoid race conditions where multiple calls might try to\n\t\t\t// create the same handler simultaneously.\n\t\t\thandler = {\n\t\t\t\tactorStartPromise: promiseWithResolvers(),\n\t\t\t\tpersistedData: undefined,\n\t\t\t};\n\t\t\tthis.#actors.set(actorId, handler);\n\n\t\t\t// Load persisted data from storage\n\t\t\tconst [persistedValue] = await this.#runner.kvGet(actorId, [\n\t\t\t\tKEYS.PERSIST_DATA,\n\t\t\t]);\n\n\t\t\thandler.persistedData =\n\t\t\t\tpersistedValue !== null\n\t\t\t\t\t? persistedValue\n\t\t\t\t\t: serializeEmptyPersistData(input);\n\t\t}\n\n\t\tconst name = runConfig.name as string;\n\t\tinvariant(runConfig.key, \"actor should have a key\");\n\t\tconst key = deserializeActorKey(runConfig.key);\n\n\t\t// Create actor instance\n\t\tconst definition = lookupInRegistry(this.#registryConfig, runConfig.name);\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\tstream.onAbort(() => this.shutdown(true));\n\n\t\t\t// Runner id should be set if the runner started\n\t\t\tconst payload = this.#runner.getServerlessInitPacket();\n\t\t\tinvariant(payload, \"runnerId not set\");\n\t\t\tawait stream.writeSSE({ data: payload });\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 { Client } from \"@/client/client\";\nimport type { ManagerDriver } from \"@/manager/driver\";\nimport type { RegistryConfig } from \"@/registry/config\";\nimport type { DriverConfig, RunnerConfig } from \"@/registry/run-config\";\nimport { RemoteManagerDriver } from \"@/remote-manager-driver/mod\";\nimport { EngineActorDriver } from \"./actor-driver\";\nimport { type EngineConfigInput, EngingConfigSchema } from \"./config\";\n\nexport { EngineActorDriver } from \"./actor-driver\";\nexport {\n\ttype EngineConfig as Config,\n\ttype EngineConfigInput as InputConfig,\n\tEngingConfigSchema as ConfigSchema,\n} from \"./config\";\n\nexport function createEngineDriver(): DriverConfig {\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: RunnerConfig,\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);\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 { RunnerConfig } 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: RunnerConfig;\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: RunnerConfig,\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: RunnerConfig,\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 { ClientConfigSchema } from \"@/client/config\";\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(\n\t\t\tthis,\n\t\t\tClientConfigSchema.parse({}),\n\t\t);\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(\n\t\t\tthis.#runConfig,\n\t\t\tthis.#actorDriver,\n\t\t\tregistryConfig.test.enabled,\n\t\t);\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 invariant from \"invariant\";\nimport { type Client, createClientWithDriver } from \"@/client/client\";\nimport type { ClientConfig } from \"@/client/config\";\nimport { configureBaseLogger, configureDefaultLogger } from \"@/common/log\";\nimport type { ActorDriver } from \"@/driver-helpers/mod\";\nimport { chooseDefaultDriver } from \"@/drivers/default\";\nimport { ENGINE_ENDPOINT, ensureEngineProcess } from \"@/engine-process/mod\";\nimport {\n\tconfigureInspectorAccessToken,\n\tgetInspectorUrl,\n\tisInspectorEnabled,\n} from \"@/inspector/utils\";\nimport { createManagerRouter } from \"@/manager/router\";\nimport {\n\tgetDatacenters,\n\ttype RunnerConfigRequest,\n\tupdateRunnerConfig,\n} from \"@/remote-manager-driver/api-endpoints\";\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 RunnerConfig,\n\ttype RunnerConfigInput,\n\tRunnerConfigSchema,\n} from \"./run-config\";\nimport { crossPlatformServe } from \"./serve\";\n\nexport type ServerlessActorDriverBuilder = (\n\tupdateConfig: (config: RunnerConfig) => void,\n) => ActorDriver;\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?: RunnerConfigInput): ServerOutput<this> {\n\t\tconst config = RunnerConfigSchema.parse(inputConfig);\n\n\t\t// Validate autoConfigureServerless is only used with serverless runner\n\t\tif (config.autoConfigureServerless && config.runnerKind !== \"serverless\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"autoConfigureServerless can only be configured when runnerKind is 'serverless'\",\n\t\t\t);\n\t\t}\n\n\t\t// Promise for any async operations we need to wait to complete\n\t\tconst readyPromises = [];\n\n\t\t// Start engine\n\t\tif (config.runEngine) {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"run engine requested\",\n\t\t\t\tversion: config.runEngineVersion,\n\t\t\t});\n\n\t\t\t// Set config to point to the engine\n\t\t\tinvariant(\n\t\t\t\tconfig.endpoint === undefined,\n\t\t\t\t\"cannot specify 'endpoint' with 'runEngine'\",\n\t\t\t);\n\t\t\tconfig.endpoint = ENGINE_ENDPOINT;\n\t\t\tconfig.disableActorDriver = true;\n\n\t\t\t// Start the engine\n\t\t\tconst engineProcessPromise = ensureEngineProcess({\n\t\t\t\tversion: config.runEngineVersion,\n\t\t\t});\n\n\t\t\t// Chain ready promise\n\t\t\treadyPromises.push(engineProcessPromise);\n\t\t}\n\n\t\t// Configure for serverless\n\t\tif (config.runnerKind === \"serverless\") {\n\t\t\tconfig.defaultServerPort = 8080;\n\t\t\tconfig.overrideServerAddress = config.endpoint;\n\t\t\tconfig.disableActorDriver = true;\n\t\t}\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// Set defaults based on the driver\n\t\tif (driver.name === \"engine\") {\n\t\t\tconfig.inspector.enabled = { manager: false, actor: true };\n\n\t\t\t// We need to leave the default server enabled for dev\n\t\t\tif (config.runnerKind !== \"serverless\") {\n\t\t\t\tconfig.disableDefaultServer = true;\n\t\t\t}\n\t\t}\n\t\tif (driver.name === \"cloudflare-workers\") {\n\t\t\tconfig.inspector.enabled = { manager: false, actor: true };\n\t\t\tconfig.disableDefaultServer = 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\tif (!config.disableDefaultServer) {\n\t\t\t\tconsole.log(` - Endpoint: ${config.endpoint}`);\n\t\t\t} else if (config.overrideServerAddress) {\n\t\t\t\tconsole.log(` - Endpoint: ${config.overrideServerAddress}`);\n\t\t\t}\n\t\t\tif (config.runEngine) {\n\t\t\t\tconst padding = \" \".repeat(Math.max(0, 13 - \"Engine\".length));\n\t\t\t\tconsole.log(` - Engine:${padding}v${config.runEngineVersion}`);\n\t\t\t}\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 returned ActorDriver, this is required to start the code that will handle incoming actors\n\t\tif (!config.disableActorDriver) {\n\t\t\tPromise.all(readyPromises).then(async () => {\n\t\t\t\tdriver.actor(this.#config, config, managerDriver, client);\n\t\t\t});\n\t\t}\n\n\t\t// Configure serverless runner if enabled when actor driver is disabled\n\t\tif (config.runnerKind === \"serverless\" && config.autoConfigureServerless) {\n\t\t\tPromise.all(readyPromises).then(async () => {\n\t\t\t\tawait configureServerlessRunner(config);\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\tdriver,\n\t\t\tclient,\n\t\t);\n\n\t\t// Start server\n\t\tif (!config.disableDefaultServer) {\n\t\t\t(async () => {\n\t\t\t\tconst out = await crossPlatformServe(config, 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\nasync function configureServerlessRunner(config: RunnerConfig): Promise<void> {\n\ttry {\n\t\t// Ensure we have required config values\n\t\tif (!config.runnerName) {\n\t\t\tthrow new Error(\"runnerName is required for serverless configuration\");\n\t\t}\n\t\tif (!config.namespace) {\n\t\t\tthrow new Error(\"namespace is required for serverless configuration\");\n\t\t}\n\t\tif (!config.endpoint) {\n\t\t\tthrow new Error(\"endpoint is required for serverless configuration\");\n\t\t}\n\n\t\t// Prepare the configuration\n\t\tconst customConfig =\n\t\t\ttypeof config.autoConfigureServerless === \"object\"\n\t\t\t\t? config.autoConfigureServerless\n\t\t\t\t: {};\n\n\t\t// Create a ClientConfig from RunnerConfig for API calls\n\t\tconst clientConfig: ClientConfig = {\n\t\t\tendpoint: config.endpoint,\n\t\t\ttoken: config.token,\n\t\t\tnamespace: config.namespace,\n\t\t\trunnerName: config.runnerName,\n\t\t\tencoding: config.encoding,\n\t\t\ttransport: config.transport,\n\t\t\theaders: config.headers,\n\t\t\tgetUpgradeWebSocket: config.getUpgradeWebSocket,\n\t\t\tdisableHealthCheck: true, // We don't need health check for this operation\n\t\t};\n\n\t\t// Fetch all datacenters\n\t\tlogger().debug({\n\t\t\tmsg: \"fetching datacenters\",\n\t\t\tendpoint: config.endpoint,\n\t\t});\n\t\tconst dcsRes = await getDatacenters(clientConfig);\n\n\t\t// Build the request body\n\t\tlogger().debug({\n\t\t\tmsg: \"configuring serverless runner\",\n\t\t\trunnerName: config.runnerName,\n\t\t\tnamespace: config.namespace,\n\t\t});\n\t\tconst serverlessConfig = {\n\t\t\tserverless: {\n\t\t\t\turl:\n\t\t\t\t\tcustomConfig.url ||\n\t\t\t\t\t`http://localhost:${config.defaultServerPort}/start`,\n\t\t\t\theaders: customConfig.headers || {},\n\t\t\t\tmax_runners: customConfig.maxRunners ?? 100,\n\t\t\t\tmin_runners: customConfig.minRunners ?? 0,\n\t\t\t\trequest_lifespan: customConfig.requestLifespan ?? 15 * 60,\n\t\t\t\trunners_margin: customConfig.runnersMargin ?? 0,\n\t\t\t\tslots_per_runner:\n\t\t\t\t\tcustomConfig.slotsPerRunner ?? config.totalSlots ?? 1000,\n\t\t\t},\n\t\t};\n\t\tawait updateRunnerConfig(clientConfig, config.runnerName, {\n\t\t\tdatacenters: Object.fromEntries(\n\t\t\t\tdcsRes.datacenters.map((dc) => [dc.name, serverlessConfig]),\n\t\t\t),\n\t\t});\n\n\t\tlogger().info({\n\t\t\tmsg: \"serverless runner configured successfully\",\n\t\t\trunnerName: config.runnerName,\n\t\t\tnamespace: config.namespace,\n\t\t});\n\t} catch (error) {\n\t\tlogger().error({\n\t\t\tmsg: \"failed to configure serverless runner\",\n\t\t\terror,\n\t\t});\n\t\tthrow error;\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\tRunnerConfig as RunConfig,\n\tRunnerConfigInput as RunConfigInput,\n\tDriverConfig,\n};\nexport { RegistryConfigSchema };\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, RunnerConfig } from \"@/registry/run-config\";\n\n/**\n * Chooses the appropriate driver based on the run configuration.\n */\nexport function chooseDefaultDriver(runConfig: RunnerConfig): DriverConfig {\n\tif (runConfig.endpoint && runConfig.driver) {\n\t\tthrow new UserError(\n\t\t\t\"Cannot specify both 'endpoint' 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 || runConfig.token) {\n\t\tloggerWithoutContext().debug({\n\t\t\tmsg: \"using rivet engine driver\",\n\t\t\tendpoint: runConfig.endpoint,\n\t\t});\n\t\treturn createEngineDriver();\n\t}\n\n\tloggerWithoutContext().debug({ msg: \"using default file system driver\" });\n\treturn createFileSystemOrMemoryDriver(true);\n}\n","import { spawn } from \"node:child_process\";\nimport { createWriteStream } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport {\n\tensureDirectoryExists,\n\tgetStoragePath,\n} from \"@/drivers/file-system/utils\";\nimport { logger } from \"./log\";\n\nexport const ENGINE_PORT = 6420;\nexport const ENGINE_ENDPOINT = `http://localhost:${ENGINE_PORT}`;\n\nconst ENGINE_BASE_URL = \"https://releases.rivet.gg/engine\";\nconst ENGINE_BINARY_NAME = \"rivet-engine\";\n\ninterface EnsureEngineProcessOptions {\n\tversion: string;\n}\n\nexport async function ensureEngineProcess(\n\toptions: EnsureEngineProcessOptions,\n): Promise<void> {\n\tlogger().debug({ msg: \"ensuring engine process\", version: options.version });\n\tconst storageRoot = getStoragePath();\n\tconst binDir = path.join(storageRoot, \"bin\");\n\tconst varDir = path.join(storageRoot, \"var\");\n\tconst logsDir = path.join(varDir, \"logs\", \"rivet-engine\");\n\tawait ensureDirectoryExists(binDir);\n\tawait ensureDirectoryExists(varDir);\n\tawait ensureDirectoryExists(logsDir);\n\n\tconst executableName =\n\t\tprocess.platform === \"win32\"\n\t\t\t? `${ENGINE_BINARY_NAME}-${options.version}.exe`\n\t\t\t: `${ENGINE_BINARY_NAME}-${options.version}`;\n\tconst binaryPath = path.join(binDir, executableName);\n\tawait downloadEngineBinaryIfNeeded(binaryPath, options.version, varDir);\n\n\t// Check if the engine is already running on the port\n\tif (await isEngineRunning()) {\n\t\ttry {\n\t\t\tawait waitForEngineHealth();\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"engine already running and healthy\",\n\t\t\t\tversion: options.version,\n\t\t\t});\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tlogger().warn({\n\t\t\t\tmsg: \"existing engine process not healthy, cannot restart automatically\",\n\t\t\t\terror,\n\t\t\t});\n\t\t\tthrow new Error(\n\t\t\t\t\"Engine process exists but is not healthy. Please manually stop the process on port 6420 and retry.\",\n\t\t\t);\n\t\t}\n\t}\n\n\t// Create log file streams with timestamp in the filename\n\tconst timestamp = new Date()\n\t\t.toISOString()\n\t\t.replace(/:/g, \"-\")\n\t\t.replace(/\\./g, \"-\");\n\tconst stdoutLogPath = path.join(logsDir, `engine-${timestamp}-stdout.log`);\n\tconst stderrLogPath = path.join(logsDir, `engine-${timestamp}-stderr.log`);\n\n\tconst stdoutStream = createWriteStream(stdoutLogPath, { flags: \"a\" });\n\tconst stderrStream = createWriteStream(stderrLogPath, { flags: \"a\" });\n\n\tlogger().debug({\n\t\tmsg: \"creating engine log files\",\n\t\tstdout: stdoutLogPath,\n\t\tstderr: stderrLogPath,\n\t});\n\n\tconst child = spawn(binaryPath, [\"start\"], {\n\t\tcwd: path.dirname(binaryPath),\n\t\tstdio: [\"inherit\", \"pipe\", \"pipe\"],\n\t\tenv: {\n\t\t\t...process.env,\n\t\t},\n\t});\n\n\tif (!child.pid) {\n\t\tthrow new Error(\"failed to spawn rivet engine process\");\n\t}\n\n\t// Pipe stdout and stderr to log files\n\tif (child.stdout) {\n\t\tchild.stdout.pipe(stdoutStream);\n\t}\n\tif (child.stderr) {\n\t\tchild.stderr.pipe(stderrStream);\n\t}\n\n\tlogger().debug({\n\t\tmsg: \"spawned engine process\",\n\t\tpid: child.pid,\n\t\tcwd: path.dirname(binaryPath),\n\t});\n\n\tchild.once(\"exit\", (code, signal) => {\n\t\tlogger().warn({\n\t\t\tmsg: \"engine process exited\",\n\t\t\tcode,\n\t\t\tsignal,\n\t\t});\n\t\t// Clean up log streams\n\t\tstdoutStream.end();\n\t\tstderrStream.end();\n\t});\n\n\tchild.once(\"error\", (error) => {\n\t\tlogger().error({\n\t\t\tmsg: \"engine process failed\",\n\t\t\terror,\n\t\t});\n\t\t// Clean up log streams on error\n\t\tstdoutStream.end();\n\t\tstderrStream.end();\n\t});\n\n\t// Wait for engine to be ready\n\tawait waitForEngineHealth();\n\n\tlogger().info({\n\t\tmsg: \"engine process started\",\n\t\tpid: child.pid,\n\t\tversion: options.version,\n\t\tlogs: {\n\t\t\tstdout: stdoutLogPath,\n\t\t\tstderr: stderrLogPath,\n\t\t},\n\t});\n}\n\nasync function downloadEngineBinaryIfNeeded(\n\tbinaryPath: string,\n\tversion: string,\n\tvarDir: string,\n): Promise<void> {\n\tconst binaryExists = await fileExists(binaryPath);\n\tif (binaryExists) {\n\t\tlogger().debug({\n\t\t\tmsg: \"engine binary already cached\",\n\t\t\tversion,\n\t\t\tpath: binaryPath,\n\t\t});\n\t\treturn;\n\t}\n\n\tconst { targetTriplet, extension } = resolveTargetTriplet();\n\tconst remoteFile = `${ENGINE_BINARY_NAME}-${targetTriplet}${extension}`;\n\tconst downloadUrl = `${ENGINE_BASE_URL}/${version}/${remoteFile}`;\n\tlogger().info({\n\t\tmsg: \"downloading engine binary\",\n\t\turl: downloadUrl,\n\t\tpath: binaryPath,\n\t\tversion,\n\t});\n\n\tconst response = await fetch(downloadUrl);\n\tif (!response.ok || !response.body) {\n\t\tthrow new Error(\n\t\t\t`failed to download rivet engine binary from ${downloadUrl}: ${response.status} ${response.statusText}`,\n\t\t);\n\t}\n\n\tconst tempPath = `${binaryPath}.${process.pid}.tmp`;\n\tawait pipeline(response.body, createWriteStream(tempPath));\n\tif (process.platform !== \"win32\") {\n\t\tawait fs.chmod(tempPath, 0o755);\n\t}\n\tawait fs.rename(tempPath, binaryPath);\n\tlogger().debug({\n\t\tmsg: \"engine binary download complete\",\n\t\tversion,\n\t\tpath: binaryPath,\n\t});\n\tlogger().info({\n\t\tmsg: \"engine binary downloaded\",\n\t\tversion,\n\t\tpath: binaryPath,\n\t});\n}\n\nfunction resolveTargetTriplet(): { targetTriplet: string; extension: string } {\n\treturn resolveTargetTripletFor(process.platform, process.arch);\n}\n\nexport function resolveTargetTripletFor(\n\tplatform: NodeJS.Platform,\n\tarch: typeof process.arch,\n): { targetTriplet: string; extension: string } {\n\tswitch (platform) {\n\t\tcase \"darwin\":\n\t\t\tif (arch === \"arm64\") {\n\t\t\t\treturn { targetTriplet: \"aarch64-apple-darwin\", extension: \"\" };\n\t\t\t}\n\t\t\tif (arch === \"x64\") {\n\t\t\t\treturn { targetTriplet: \"x86_64-apple-darwin\", extension: \"\" };\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"linux\":\n\t\t\tif (arch === \"x64\") {\n\t\t\t\treturn { targetTriplet: \"x86_64-unknown-linux-musl\", extension: \"\" };\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"win32\":\n\t\t\tif (arch === \"x64\") {\n\t\t\t\treturn { targetTriplet: \"x86_64-pc-windows-gnu\", extension: \".exe\" };\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\tthrow new Error(\n\t\t`unsupported platform for rivet engine binary: ${platform}/${arch}`,\n\t);\n}\n\nasync function isEngineRunning(): Promise<boolean> {\n\t// Check if the engine is running on the port\n\treturn await checkIfEngineAlreadyRunningOnPort(ENGINE_PORT);\n}\n\nasync function checkIfEngineAlreadyRunningOnPort(\n\tport: number,\n): Promise<boolean> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(`http://localhost:${port}/health`);\n\t} catch (err) {\n\t\t// Nothing is running on this port\n\t\treturn false;\n\t}\n\n\tif (response.ok) {\n\t\tconst health = (await response.json()) as {\n\t\t\tstatus?: string;\n\t\t\truntime?: string;\n\t\t\tversion?: string;\n\t\t};\n\n\t\t// Check what's running on this port\n\t\tif (health.runtime === \"engine\") {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"rivet engine already running on port\",\n\t\t\t\tport,\n\t\t\t});\n\t\t\treturn true;\n\t\t} else if (health.runtime === \"rivetkit\") {\n\t\t\tlogger().error({\n\t\t\t\tmsg: \"another rivetkit process is already running on port\",\n\t\t\t\tport,\n\t\t\t});\n\t\t\tthrow new Error(\n\t\t\t\t\"RivetKit process already running on port 6420, stop that process and restart this.\",\n\t\t\t);\n\t\t} else {\n\t\t\tthrow new Error(\n\t\t\t\t\"Unknown process running on port 6420, cannot identify what it is.\",\n\t\t\t);\n\t\t}\n\t}\n\n\t// Port responded but not with OK status\n\treturn false;\n}\n\nasync function fileExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(filePath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nconst HEALTH_MAX_WAIT = 10_000;\nconst HEALTH_INTERVAL = 100;\n\nasync function waitForEngineHealth(): Promise<void> {\n\tconst maxRetries = Math.ceil(HEALTH_MAX_WAIT / HEALTH_INTERVAL);\n\n\tlogger().debug({ msg: \"waiting for engine health check\" });\n\n\tfor (let i = 0; i < maxRetries; i++) {\n\t\ttry {\n\t\t\tconst response = await fetch(`${ENGINE_ENDPOINT}/health`);\n\t\t\tif (response.ok) {\n\t\t\t\tlogger().debug({ msg: \"engine health check passed\" });\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Expected to fail while engine is starting up\n\t\t\tif (i === maxRetries - 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`engine health check failed after ${maxRetries} retries: ${error}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (i < maxRetries - 1) {\n\t\t\tlogger().trace({\n\t\t\t\tmsg: \"engine not ready, retrying\",\n\t\t\t\tattempt: i + 1,\n\t\t\t\tmaxRetries,\n\t\t\t});\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, HEALTH_INTERVAL));\n\t\t}\n\t}\n\n\tthrow new Error(`engine health check failed after ${maxRetries} retries`);\n}\n","import { getLogger } from \"@/common/log\";\n\nexport function logger() {\n\treturn getLogger(\"engine-process\");\n}\n","import { createRoute, OpenAPIHono } from \"@hono/zod-openapi\";\nimport * as cbor from \"cbor-x\";\nimport {\n\tHono,\n\ttype Context as HonoContext,\n\ttype MiddlewareHandler,\n\ttype Next,\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, InvalidRequest, Unsupported } from \"@/actor/errors\";\nimport { serializeActorKey } from \"@/actor/keys\";\nimport type { Client, 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\thandleHealthRequest,\n\thandleMetadataRequest,\n\thandleRouteError,\n\thandleRouteNotFound,\n\tloggerMiddleware,\n\ttype MetadataResponse,\n} from \"@/common/router\";\nimport {\n\tassertUnreachable,\n\tdeconstructError,\n\tnoopNext,\n\tstringifyError,\n} 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 { AnyClient } from \"@/mod\";\nimport type { RegistryConfig } from \"@/registry/config\";\nimport type { DriverConfig, RunnerConfig } from \"@/registry/run-config\";\nimport { VERSION } from \"@/utils\";\nimport type { ActorOutput, ManagerDriver } from \"./driver\";\nimport { actorGateway, createTestWebSocketProxy } from \"./gateway\";\nimport { logger } from \"./log\";\nimport { ServerlessStartHeadersSchema } from \"./router-schema\";\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: RunnerConfig,\n\tmanagerDriver: ManagerDriver,\n\tdriverConfig: DriverConfig,\n\tclient: AnyClient,\n): { router: Hono; openapi: OpenAPIHono } {\n\tconst router = new OpenAPIHono({ strict: false }).basePath(\n\t\trunConfig.basePath,\n\t);\n\n\trouter.use(\"*\", loggerMiddleware(logger()));\n\n\t// HACK: Add Sec-WebSocket-Protocol header to fix KIT-339\n\t//\n\t// Some Deno WebSocket providers do not auto-set the protocol, which\n\t// will cause some WebSocket clients to fail\n\trouter.use(\n\t\t\"*\",\n\t\tcreateMiddleware(async (c, next) => {\n\t\t\tconst upgrade = c.req.header(\"upgrade\");\n\t\t\tconst isWebSocket = upgrade?.toLowerCase() === \"websocket\";\n\t\t\tconst isGet = c.req.method === \"GET\";\n\n\t\t\tif (isGet && isWebSocket) {\n\t\t\t\tc.header(\"Sec-WebSocket-Protocol\", \"rivet\");\n\t\t\t}\n\n\t\t\tawait next();\n\t\t}),\n\t);\n\n\tif (runConfig.runnerKind === \"serverless\") {\n\t\taddServerlessRoutes(\n\t\t\tdriverConfig,\n\t\t\tregistryConfig,\n\t\t\trunConfig,\n\t\t\tmanagerDriver,\n\t\t\tclient,\n\t\t\trouter,\n\t\t);\n\t} else if (runConfig.runnerKind === \"normal\") {\n\t\taddManagerRoutes(registryConfig, runConfig, managerDriver, router);\n\t} else {\n\t\tassertUnreachable(runConfig.runnerKind);\n\t}\n\n\t// Error handling\n\trouter.notFound(handleRouteNotFound);\n\trouter.onError(handleRouteError);\n\n\treturn { router: router as Hono, openapi: router };\n}\n\nfunction addServerlessRoutes(\n\tdriverConfig: DriverConfig,\n\tregistryConfig: RegistryConfig,\n\trunConfig: RunnerConfig,\n\tmanagerDriver: ManagerDriver,\n\tclient: AnyClient,\n\trouter: OpenAPIHono,\n) {\n\t// Apply CORS\n\tif (runConfig.cors) router.use(\"*\", corsMiddleware(runConfig.cors));\n\n\t// GET /\n\trouter.get(\"/\", (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\", async (c) => {\n\t\t// Parse headers\n\t\tconst parseResult = ServerlessStartHeadersSchema.safeParse({\n\t\t\tendpoint: c.req.header(\"x-rivet-endpoint\"),\n\t\t\ttoken: c.req.header(\"x-rivet-token\") ?? undefined,\n\t\t\ttotalSlots: c.req.header(\"x-rivet-total-slots\"),\n\t\t\trunnerName: c.req.header(\"x-rivet-runner-name\"),\n\t\t\tnamespace: c.req.header(\"x-rivet-namespace-id\"),\n\t\t});\n\t\tif (!parseResult.success) {\n\t\t\tthrow new InvalidRequest(\n\t\t\t\tparseResult.error.issues[0]?.message ??\n\t\t\t\t\t\"invalid serverless start headers\",\n\t\t\t);\n\t\t}\n\t\tconst { endpoint, token, totalSlots, runnerName, namespace } =\n\t\t\tparseResult.data;\n\n\t\tlogger().debug({\n\t\t\tmsg: \"received serverless runner start request\",\n\t\t\tendpoint,\n\t\t\ttotalSlots,\n\t\t\trunnerName,\n\t\t\tnamespace,\n\t\t});\n\n\t\t// Override config\n\t\t//\n\t\t// We can't do a structuredClone here since this holds functions\n\t\tconst newRunConfig = Object.assign({}, runConfig);\n\t\tnewRunConfig.endpoint = endpoint;\n\t\tnewRunConfig.token = token;\n\t\tnewRunConfig.totalSlots = totalSlots;\n\t\tnewRunConfig.runnerName = runnerName;\n\t\tnewRunConfig.namespace = namespace;\n\n\t\t// Create new actor driver with updated config\n\t\tconst actorDriver = driverConfig.actor(\n\t\t\tregistryConfig,\n\t\t\tnewRunConfig,\n\t\t\tmanagerDriver,\n\t\t\tclient,\n\t\t);\n\t\tinvariant(\n\t\t\tactorDriver.serverlessHandleStart,\n\t\t\t\"missing serverlessHandleStart on ActorDriver\",\n\t\t);\n\n\t\treturn await actorDriver.serverlessHandleStart(c);\n\t});\n\n\trouter.get(\"/health\", (c) => handleHealthRequest(c));\n\n\trouter.get(\"/metadata\", (c) => handleMetadataRequest(c, runConfig));\n}\n\nfunction addManagerRoutes(\n\tregistryConfig: RegistryConfig,\n\trunConfig: RunnerConfig,\n\tmanagerDriver: ManagerDriver,\n\trouter: OpenAPIHono,\n) {\n\t// Serve inspector BEFORE the rest of the routes, since this has a special\n\t// CORS config that should take precedence for the `/inspector` path\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\t// Apply CORS\n\tif (runConfig.cors) router.use(\"*\", corsMiddleware(runConfig.cors));\n\n\t// Actor gateway\n\trouter.use(\"*\", actorGateway.bind(undefined, runConfig, managerDriver));\n\n\t// GET /\n\trouter.get(\"/\", (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\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((actor) =>\n\t\t\t\t\tcreateApiActor(actor, runConfig.runnerName),\n\t\t\t\t),\n\t\t\t});\n\t\t});\n\t}\n\n\t// PUT /actors\n\t{\n\t\tconst route = createRoute({\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, runConfig.runnerName),\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, runConfig.runnerName),\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\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, runConfig.runnerName);\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\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\", (c) => handleHealthRequest(c));\n\n\trouter.get(\"/metadata\", (c) => handleMetadataRequest(c, runConfig));\n\n\tmanagerDriver.modifyManagerRouter?.(\n\t\tregistryConfig,\n\t\trouter as unknown as Hono,\n\t);\n}\n\nfunction createApiActor(\n\tactor: ActorOutput,\n\trunnerName: string = \"default\",\n): 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: runnerName,\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 { RunnerConfig } 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: RunnerConfig,\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// Strip basePath from the request path\n\tlet strippedPath = c.req.path;\n\tif (runConfig.basePath && strippedPath.startsWith(runConfig.basePath)) {\n\t\tstrippedPath = strippedPath.slice(runConfig.basePath.length);\n\t\t// Ensure the path starts with /\n\t\tif (!strippedPath.startsWith(\"/\")) {\n\t\t\tstrippedPath = \"/\" + strippedPath;\n\t\t}\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(\n\t\t\trunConfig,\n\t\t\tmanagerDriver,\n\t\t\tc,\n\t\t\tstrippedPath,\n\t\t);\n\t}\n\n\t// Handle regular HTTP requests\n\treturn await handleHttpGateway(managerDriver, c, next, strippedPath);\n}\n\n/**\n * Handle WebSocket requests using sec-websocket-protocol for routing\n */\nasync function handleWebSocketGateway(\n\trunConfig: RunnerConfig,\n\tmanagerDriver: ManagerDriver,\n\tc: HonoContext,\n\tstrippedPath: string,\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: strippedPath,\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? strippedPath + c.req.url.substring(c.req.url.indexOf(\"?\"))\n\t\t: strippedPath;\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\tstrippedPath: string,\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: strippedPath,\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${strippedPath}${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\tduplex: \"half\",\n\t} as RequestInit);\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","import { z } from \"zod\";\n\nexport const ServerlessStartHeadersSchema = z.object({\n\tendpoint: z.string({ required_error: \"x-rivet-endpoint header is required\" }),\n\ttoken: z\n\t\t.string({ invalid_type_error: \"x-rivet-token header must be a string\" })\n\t\t.optional(),\n\ttotalSlots: z.coerce\n\t\t.number({\n\t\t\tinvalid_type_error: \"x-rivet-total-slots header must be a number\",\n\t\t})\n\t\t.int(\"x-rivet-total-slots header must be an integer\")\n\t\t.gte(1, \"x-rivet-total-slots header must be positive\"),\n\trunnerName: z.string({\n\t\trequired_error: \"x-rivet-runner-name header is required\",\n\t}),\n\tnamespace: z.string({\n\t\trequired_error: \"x-rivet-namespace-id header is required\",\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\";\nimport type { RunnerConfig } from \"./run-config\";\n\nexport async function crossPlatformServe(\n\trunConfig: RunnerConfig,\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 = runConfig.defaultServerPort;\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"],"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,aAA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AC3D;AAAA,IACD,CAAC;AAED,IAAAC,QAAO,EAAE,KAAK;AAAA,MACb,KAAK;AAAA,MACL,YAAYD,QAAO;AAAA,MACnB,WAAWA,QAAO;AAAA,IACnB,CAAC;AAAA,EACF,SAAS,OAAO;AACf,IAAAC,QAAO,EAAE,MAAM;AAAA,MACd,KAAK;AAAA,MACL;AAAA,IACD,CAAC;AACD,UAAM;AAAA,EACP;AACD;AAEO,SAAS,MACf,OACc;AACd,QAAMD,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","logger","actor","invariant","WSContext","streamSSE","actor","crypto","fsSync","fs","path","invariant","logger","crypto","path","logger","invariant","actor","invariant","Hono","Hono","actor","transformActor","actor","path","invariant","logger","invariant","fs","path","logger","logger","cbor","Hono","invariant","z","z","z","z","z","invariant","Hono","z","actor","_a","c","path","z","logger","Hono","Hono","logger","config","logger","invariant"]}