@mulmoclaude/core 0.23.1 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/helps/collection-skills.md +27 -3
- package/assets/helps/google-calendar-collection.md +79 -0
- package/assets/helps/index.md +1 -0
- package/dist/collection/core/completion.d.ts +18 -0
- package/dist/collection/core/deriveAll.d.ts +14 -9
- package/dist/collection/core/schema.d.ts +9 -4
- package/dist/collection/core/schemaZ.d.ts +126 -43
- package/dist/collection/index.cjs +16 -14
- package/dist/collection/index.cjs.map +1 -1
- package/dist/collection/index.d.ts +1 -0
- package/dist/collection/index.js +3 -2
- package/dist/collection/index.js.map +1 -1
- package/dist/collection/paths.cjs +5 -55
- package/dist/collection/paths.js +1 -51
- package/dist/collection/registry/server/index.cjs +20 -19
- package/dist/collection/registry/server/index.cjs.map +1 -1
- package/dist/collection/registry/server/index.js +3 -2
- package/dist/collection/registry/server/index.js.map +1 -1
- package/dist/collection/server/index.cjs +41 -40
- package/dist/collection/server/index.js +4 -3
- package/dist/collection-watchers/index.cjs +15 -23
- package/dist/collection-watchers/index.cjs.map +1 -1
- package/dist/collection-watchers/index.js +3 -11
- package/dist/collection-watchers/index.js.map +1 -1
- package/dist/collection-watchers/reconciler.d.ts +2 -4
- package/dist/discovery-3K_Wtkvn.js +1636 -0
- package/dist/discovery-3K_Wtkvn.js.map +1 -0
- package/dist/discovery-BZ2ms1tE.cjs +1865 -0
- package/dist/discovery-BZ2ms1tE.cjs.map +1 -0
- package/dist/feeds/index.cjs +4 -4
- package/dist/feeds/index.js +2 -2
- package/dist/feeds/server/index.cjs +16 -15
- package/dist/feeds/server/index.cjs.map +1 -1
- package/dist/feeds/server/index.js +4 -3
- package/dist/feeds/server/index.js.map +1 -1
- package/dist/google/apiClient.d.ts +8 -1
- package/dist/google/calendar.d.ts +35 -0
- package/dist/google/calendarSyncStore.d.ts +7 -0
- package/dist/google/collectionSync.d.ts +70 -0
- package/dist/google/index.cjs +296 -4
- package/dist/google/index.cjs.map +1 -1
- package/dist/google/index.d.ts +4 -2
- package/dist/google/index.js +281 -5
- package/dist/google/index.js.map +1 -1
- package/dist/ids-BR4U1dJD.cjs +150 -0
- package/dist/ids-BR4U1dJD.cjs.map +1 -0
- package/dist/ids-D4e10971.js +85 -0
- package/dist/ids-D4e10971.js.map +1 -0
- package/dist/{ingestTypes-B-dXxUF9.js → ingestTypes-BsGOjR2l.js} +2 -2
- package/dist/{ingestTypes-B-dXxUF9.js.map → ingestTypes-BsGOjR2l.js.map} +1 -1
- package/dist/{ingestTypes-Cev9q77C.cjs → ingestTypes-CygUXsjf.cjs} +3 -3
- package/dist/{ingestTypes-Cev9q77C.cjs.map → ingestTypes-CygUXsjf.cjs.map} +1 -1
- package/dist/{promptSafety-rDWA9_JS.js → promptSafety-Boz5qOs-.js} +48 -102
- package/dist/promptSafety-Boz5qOs-.js.map +1 -0
- package/dist/{promptSafety-DRd15gQ6.cjs → promptSafety-Co4cYQ_Z.cjs} +49 -163
- package/dist/promptSafety-Co4cYQ_Z.cjs.map +1 -0
- package/dist/remote-host/server/index.cjs +6 -4
- package/dist/remote-host/server/index.cjs.map +1 -1
- package/dist/remote-host/server/index.js +6 -4
- package/dist/remote-host/server/index.js.map +1 -1
- package/dist/scheduler/index.cjs +3 -1
- package/dist/scheduler/index.cjs.map +1 -1
- package/dist/scheduler/index.js +3 -1
- package/dist/scheduler/index.js.map +1 -1
- package/dist/{server-Jaogu3Ky.cjs → server-DLRz-U7F.cjs} +80 -1806
- package/dist/server-DLRz-U7F.cjs.map +1 -0
- package/dist/{server-D2ibbixF.js → server-DZH7OjOD.js} +9 -1531
- package/dist/server-DZH7OjOD.js.map +1 -0
- package/dist/skill-bridge/index.cjs +2 -2
- package/dist/skill-bridge/index.cjs.map +1 -1
- package/dist/skill-bridge/index.js +1 -1
- package/dist/templatePath-27vUZowm.cjs +75 -0
- package/dist/templatePath-27vUZowm.cjs.map +1 -0
- package/dist/templatePath-k_WNbL_Q.js +52 -0
- package/dist/templatePath-k_WNbL_Q.js.map +1 -0
- package/package.json +1 -1
- package/dist/collection/paths.cjs.map +0 -1
- package/dist/collection/paths.js.map +0 -1
- package/dist/promptSafety-DRd15gQ6.cjs.map +0 -1
- package/dist/promptSafety-rDWA9_JS.js.map +0 -1
- package/dist/server-D2ibbixF.js.map +0 -1
- package/dist/server-Jaogu3Ky.cjs.map +0 -1
|
@@ -98,10 +98,12 @@ var processCommand = async (ctx, ref, command, now) => {
|
|
|
98
98
|
};
|
|
99
99
|
var startHostRunner = (firestore, channel, handlers, options = {}) => {
|
|
100
100
|
const presence = require_remote_host_index.hostDoc(firestore, channel);
|
|
101
|
-
const writePresence = (online) =>
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
101
|
+
const writePresence = (online) => {
|
|
102
|
+
(0, firebase_firestore.setDoc)(presence, {
|
|
103
|
+
...require_remote_host_index.buildHostPresence(channel, handlers, online),
|
|
104
|
+
updatedAt: (0, firebase_firestore.serverTimestamp)()
|
|
105
|
+
}).catch(noop$2);
|
|
106
|
+
};
|
|
105
107
|
const announce = () => {
|
|
106
108
|
writePresence(true);
|
|
107
109
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/remote-host/server/hostRunner.ts","../../../src/remote-host/server/lifecycle.ts","../../../src/remote-host/server/auth.ts","../../../src/remote-host/server/sessionPersistence.ts","../../../src/remote-host/server/firebase.ts"],"sourcesContent":["// Host side of the command channel: claim queued commands, run handlers, write\n// results back, and announce presence via heartbeat.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/hostRunner.ts (itself\n// ported from ../mulmoserver). The only signature change vs. that copy: the\n// `firestore` instance is a parameter (each host supplies its own Firebase init),\n// and the heartbeat interval is an option (defaults to one minute).\nimport { DocumentReference, Firestore, deleteDoc, onSnapshot, query, runTransaction, serverTimestamp, setDoc, updateDoc, where } from \"firebase/firestore\";\n\nimport { errorMessage } from \"../../collection/core/errorMessage.js\";\nimport {\n Channel,\n Command,\n CommandHandler,\n CommandHandlers,\n JsonObject,\n buildHostPresence,\n byCreatedAt,\n commandsCollection,\n hostDoc,\n isExpired,\n} from \"../index.js\";\n\nconst DEFAULT_HEARTBEAT_MS = 60_000;\n\nexport interface HostEvent {\n phase: \"received\" | \"done\" | \"error\";\n method: string;\n message?: string;\n}\n\nexport interface HostRunnerOptions {\n onEvent?: (event: HostEvent) => void;\n // Called once when the listener dies fatally (after presence has been set\n // offline), so the lifecycle owner can reconcile its own state — e.g. clear\n // the runner handle so status() no longer reports connected. NOT called on a\n // normal stop().\n onClosed?: () => void;\n // Called when a command is dropped for being past its `expiresAt`, BEFORE the\n // doc is deleted, so the host can clean up out-of-band resources the command\n // referenced (e.g. staged attachment uploads in Storage). `uid` is THIS runner's\n // session uid (channel.uid) — passed in rather than read from a global so a\n // concurrent reconnect as a different account can't point cleanup at the wrong\n // user's Storage path. Best-effort: a throw is logged via onEvent and does NOT\n // block the doc deletion. Absent ⇒ the expired doc is simply deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n // Presence heartbeat interval; defaults to one minute.\n heartbeatMs?: number;\n}\n\ninterface Claim {\n method: string;\n params: JsonObject;\n}\n\nconst noop = () => undefined;\n\n// The remote may have deleted the doc on timeout, so ignore write-after-delete.\nconst writeError = (ref: DocumentReference, code: string, message: string) =>\n updateDoc(ref, { status: \"error\", error: { code, message }, updatedAt: serverTimestamp() }).catch(noop);\n\n// Atomically move a command queued -> processing so it is handled exactly once.\n// Returns the method/params to run, or null if another handler already took it.\nconst claimCommand = (firestore: Firestore, ref: DocumentReference): Promise<Claim | null> =>\n runTransaction(firestore, async (txn) => {\n const data = (await txn.get(ref)).data() as Command | undefined;\n if (!data || data.status !== \"queued\") {\n return null;\n }\n txn.update(ref, { status: \"processing\", updatedAt: serverTimestamp() });\n return { method: data.method, params: data.params ?? {} };\n });\n\nconst runHandler = async (ref: DocumentReference, claim: Claim, handler: CommandHandler): Promise<HostEvent> => {\n try {\n const result = await handler(claim.params);\n await updateDoc(ref, { status: \"done\", result: result ?? null, updatedAt: serverTimestamp() });\n return { phase: \"done\", method: claim.method };\n } catch (error) {\n const message = errorMessage(error);\n await writeError(ref, \"handler_error\", message);\n return { phase: \"error\", method: claim.method, message };\n }\n};\n\n// A command past its deadline is removed entirely rather than run: give the host\n// a chance to clean up out-of-band resources (staged attachments), then delete\n// the doc so it is neither reprocessed nor left as a stale error. Both steps are\n// best-effort/idempotent, so a snapshot replay surfacing the same expired doc\n// twice is harmless (no claim transaction needed — see plan edge #3).\nconst expireCommand = async (ref: DocumentReference, command: Command, options: HostRunnerOptions, uid: string) => {\n try {\n await options.onExpire?.(command, uid);\n } catch (error) {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `onExpire failed: ${errorMessage(error)}` });\n }\n // Surface a delete failure (permissions / transient network) the same way the\n // onExpire failure above is surfaced — otherwise the expired doc lingers as\n // \"queued\" with no signal as to why cleanup didn't happen.\n await deleteDoc(ref).catch((error) => {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `expire delete failed: ${errorMessage(error)}` });\n });\n options.onEvent?.({ phase: \"done\", method: command.method, message: \"expired\" });\n};\n\n// Per-runner constants bundled into one context so processCommand stays under the\n// max-params cap: firestore, the handler table, options, and the session uid are\n// all fixed for the runner's lifetime; only ref/command/now vary per command.\ninterface RunnerContext {\n firestore: Firestore;\n handlers: CommandHandlers;\n options: HostRunnerOptions;\n uid: string;\n}\n\nconst processCommand = async (ctx: RunnerContext, ref: DocumentReference, command: Command, now: number) => {\n const { handlers, options } = ctx;\n // Drop an expired command before claiming it — it must never reach a handler.\n if (isExpired(command, now)) {\n await expireCommand(ref, command, options, ctx.uid);\n return;\n }\n const claim = await claimCommand(ctx.firestore, ref);\n if (!claim) {\n return;\n }\n options.onEvent?.({ phase: \"received\", method: claim.method });\n const handler: CommandHandler | undefined = handlers[claim.method];\n if (!handler) {\n await writeError(ref, \"unknown_method\", `No handler for method: ${claim.method}`);\n options.onEvent?.({ phase: \"error\", method: claim.method, message: \"unknown method\" });\n return;\n }\n options.onEvent?.(await runHandler(ref, claim, handler));\n};\n\n// startHostRunner subscribes to queued commands for the given channel and runs\n// each one through the supplied handler table. It also announces presence (a\n// heartbeat on users/{uid}/hosts/{hostId}) so the remote can tell it is online.\n// Returns a stop function that goes offline and detaches the listener.\nexport const startHostRunner = (firestore: Firestore, channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions = {}): (() => void) => {\n const presence = hostDoc(firestore, channel);\n // Advertise online/offline + the capability set (method names + protocol\n // version) on the same doc the remote already listens to for presence.\n const writePresence = (online: boolean) => setDoc(presence, { ...buildHostPresence(channel, handlers, online), updatedAt: serverTimestamp() }).catch(noop);\n const announce = () => {\n writePresence(true);\n };\n announce();\n const beat = setInterval(announce, options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);\n\n const queuedCommands = query(commandsCollection(firestore, channel), where(\"status\", \"==\", \"queued\"));\n const ctx: RunnerContext = { firestore, handlers, options, uid: channel.uid };\n const unsubscribe = onSnapshot(\n queuedCommands,\n (snapshot) => {\n const now = Date.now();\n // Best-effort oldest-first DISPATCH only. Commands are processed\n // concurrently (not awaited in turn) and out-of-order completion is fine by\n // design — chat is asynchronous — so this sort just biases which command\n // starts first; it is not an ordering guarantee. We still sort in memory\n // rather than orderBy(\"createdAt\") on the query because a Firestore orderBy\n // silently EXCLUDES docs missing the field — which would drop every\n // pre-offline-queue command (no createdAt) from the queue entirely.\n const added = snapshot\n .docChanges()\n .filter((change) => change.type === \"added\")\n .map((change) => ({ ref: change.doc.ref, command: change.doc.data() as Command }))\n .sort((left, right) => byCreatedAt(left.command, right.command));\n added.forEach(({ ref, command }) => {\n processCommand(ctx, ref, command, now).catch(noop);\n });\n },\n (error) => {\n options.onEvent?.({ phase: \"error\", method: \"listen\", message: error.message });\n // A Firestore onSnapshot error terminates the listener and it does not\n // recover on its own. Stop advertising presence (clear the heartbeat +\n // write online:false) so remotes see the host as offline instead of a\n // live host that silently consumes no commands.\n clearInterval(beat);\n writePresence(false);\n options.onClosed?.();\n },\n );\n\n return () => {\n clearInterval(beat);\n writePresence(false);\n unsubscribe();\n };\n};\n","// Remote-host lifecycle: wire a Firebase session to the Firestore host runner so\n// connecting starts the command loop + presence heartbeat, and disconnecting\n// stops both.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/index.ts. The factory\n// takes injected collaborators — real hosts bind them to Firebase; tests pass\n// fakes to exercise the invariants (non-destructive connect, serialized\n// transitions, status/liveness reconciliation on fatal listener death) without a\n// network. `hostId` and the logger are injected too, so this file imports no\n// Firebase and no host logger and stays trivially unit-testable.\n//\n// Single-account, single-host per instance, in-memory session: a host restart\n// drops the session and needs a re-connect.\nimport type { Channel, Command, CommandHandlers } from \"../index.js\";\nimport type { HostRunnerOptions } from \"./hostRunner.js\";\n\nexport interface RemoteHostStatus {\n connected: boolean;\n uid: string | null;\n}\n\n// Minimal logger the factory calls; each host adapts its own logger to this\n// shape (or omits it to run silently, as the tests do).\nexport interface RemoteHostLogger {\n info: (msg: string) => void;\n warn: (msg: string) => void;\n debug: (msg: string) => void;\n}\n\n// Injectable collaborators — a real host binds these to Firebase + its own\n// hostId; tests pass fakes to exercise the lifecycle without a network.\n// `startRunner` is the host's `startHostRunner` pre-bound with its Firestore\n// instance, so this module needs no Firebase of its own.\nexport interface RemoteHostDeps {\n hostId: string;\n signIn: (idToken: string) => Promise<string>;\n // Restore a session from a browser-parked blob (case A', mulmoserver#50) and\n // resolve to its uid — no popup. MUST reject when the blob yields no valid\n // session so `reconnect` stays non-destructive. Absent ⇒ `reconnect` throws.\n restore?: (sessionBlob: string) => Promise<string>;\n signOut: () => Promise<void>;\n currentUid: () => string | null;\n startRunner: (channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions) => () => void;\n handlers: CommandHandlers;\n // Optional host-specific cleanup for a command the runner drops as expired\n // (e.g. delete its staged attachment uploads). Threaded verbatim into the\n // runner's `onExpire`, which supplies the session `uid` so cleanup targets the\n // right user's Storage path even across a reconnect; absent ⇒ an expired doc is\n // just deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n log?: RemoteHostLogger;\n}\n\nexport interface RemoteHostLifecycle {\n connect: (idToken: string) => Promise<RemoteHostStatus>;\n // Restore a browser-parked session and start the runner — popup-free re-attach\n // after a host restart. Non-destructive like `connect`. Rejects if `deps.restore`\n // isn't wired, or if restore fails (blob expired/invalid → caller falls back to connect).\n reconnect: (sessionBlob: string) => Promise<RemoteHostStatus>;\n disconnect: () => Promise<RemoteHostStatus>;\n status: () => RemoteHostStatus;\n}\n\nconst noop = () => undefined;\nconst silentLogger: RemoteHostLogger = { info: noop, warn: noop, debug: noop };\n\nexport const createRemoteHost = (deps: RemoteHostDeps): RemoteHostLifecycle => {\n const log = deps.log ?? silentLogger;\n\n // The running host runner's stop() handle, or null when disconnected. Keeps\n // the single-host invariant — one runner at a time.\n let stopRunner: (() => void) | null = null;\n\n // Serialize connect/disconnect so overlapping requests can't both mutate\n // stopRunner (which would leak a second runner) or race auth against teardown.\n // Each transition runs only after the previous one settles; a failed\n // transition does not block the next (both handlers run the next op).\n let transition: Promise<unknown> = Promise.resolve();\n\n const serialize = <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n\n const stopIfRunning = () => {\n if (stopRunner) {\n stopRunner();\n stopRunner = null;\n }\n };\n\n const status = (): RemoteHostStatus => ({ connected: stopRunner !== null, uid: deps.currentUid() });\n\n // Swap the running runner for one bound to `uid`. Callers authenticate FIRST\n // (before this teardown) so a failed connect/reconnect keeps a healthy session.\n const attach = (uid: string, verb: string): RemoteHostStatus => {\n stopIfRunning();\n const runner = deps.startRunner({ uid, hostId: deps.hostId }, deps.handlers, {\n onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),\n onExpire: deps.onExpire,\n // Fatal listener death: drop the handle so status() stops reporting\n // connected — but only if it still points at THIS runner (a later\n // reconnect may have replaced it).\n onClosed: () => {\n if (stopRunner === runner) {\n stopRunner = null;\n log.warn(\"host runner listener died; marked disconnected\");\n }\n },\n });\n stopRunner = runner;\n log.info(`${verb} as ${uid}, host runner started (hostId=${deps.hostId})`);\n return status();\n };\n\n const connect = (idToken: string): Promise<RemoteHostStatus> => serialize(async () => attach(await deps.signIn(idToken), \"connected\"));\n\n const reconnect = (sessionBlob: string): Promise<RemoteHostStatus> =>\n serialize(async () => {\n const { restore } = deps;\n if (!restore) throw new Error(\"remote-host reconnect requires a `restore` dependency\");\n return attach(await restore(sessionBlob), \"reconnected\");\n });\n\n const disconnect = (): Promise<RemoteHostStatus> =>\n serialize(async () => {\n stopIfRunning();\n await deps.signOut();\n log.info(\"disconnected, host runner stopped\");\n return status();\n });\n\n return { connect, reconnect, disconnect, status };\n};\n","// Firebase credential exchange for the remote-host runner.\n//\n// The host authenticates to Firestore *as the user* (Option B) using the\n// Firebase JS SDK's signInWithCredential with a browser-minted Google OAuth ID\n// token — no Admin SDK, no project service account. Security rules keep the host\n// scoped to that user's own users/{uid}/… subtree.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/auth.ts. The `auth`\n// instance is a parameter so each host binds its own Firebase init; the factory\n// returns the low-level credential primitives (the connect/disconnect lifecycle\n// that starts/stops the host runner lives in createRemoteHost).\nimport { Auth, GoogleAuthProvider, signInWithCredential, signOut } from \"firebase/auth\";\n\nexport interface RemoteHostAuth {\n // Establish the Firebase session from a browser-minted Google OAuth ID token.\n // The token is used once here; the JS SDK then holds its own refresh token for\n // the process lifetime. Resolves to the authenticated uid.\n signInHost: (idToken: string) => Promise<string>;\n // Tear down the Firebase session (in-memory persistence → re-login on restart).\n signOutHost: () => Promise<void>;\n // The currently signed-in uid, or null when disconnected.\n currentUid: () => string | null;\n}\n\nexport const createRemoteHostAuth = (auth: Auth): RemoteHostAuth => ({\n signInHost: async (idToken: string): Promise<string> => {\n const credential = GoogleAuthProvider.credential(idToken);\n const userCredential = await signInWithCredential(auth, credential);\n return userCredential.user.uid;\n },\n signOutHost: (): Promise<void> => signOut(auth),\n currentUid: (): string | null => auth.currentUser?.uid ?? null,\n});\n","// A custom Firebase Auth persistence that keeps the signed-in session in memory\n// but can be seeded from — and exported back to — an opaque blob, so a host's\n// Firebase session survives a process restart by being parked in the browser's\n// localStorage (mulmoserver#50, \"case A'\"). The blob is whatever the SDK wrote\n// into persistence, round-tripped through JSON; we NEVER interpret its fields,\n// so we don't couple to the SDK's serialized-user format across versions.\n//\n// **Persistence is a CLASS, not an instance.** `initializeAuth(app, { persistence })`\n// hands the value to the SDK's `_getInstance(cls)`, which asserts `cls instanceof\n// Function` (\"Expected a class definition\") and then `new cls()`. Passing a plain\n// object throws — the SDK's own `inMemoryPersistence` is likewise a class. The\n// class is defined per factory call so its instances share this call's store;\n// `type: \"LOCAL\"` makes the SDK treat it as durable and persist the user.\n//\n// Seed BEFORE `initializeAuth` — the SDK reads persistence once at init. `onChange`\n// fires when the SDK writes/removes a key (a token update that rotates the stored\n// blob, or a sign-out) — the signal to re-sync the browser copy.\nimport type { Persistence } from \"firebase/auth\";\n\n// The SDK stores values as JSON objects (a serialized user) or strings. We treat\n// them opaquely — a value is either.\ntype PersistenceValue = Record<string, unknown> | string;\n\ntype StorageListener = (value: PersistenceValue | null) => void;\n\n// The instance the SDK builds via `new` and then drives with these `_`-methods.\nexport interface HostAuthPersistenceInstance extends Persistence {\n type: \"LOCAL\";\n _isAvailable: () => Promise<boolean>;\n _set: (key: string, value: PersistenceValue) => Promise<void>;\n _get: (key: string) => Promise<PersistenceValue | null>;\n _remove: (key: string) => Promise<void>;\n _addListener: (key: string, listener: StorageListener) => void;\n _removeListener: (key: string, listener: StorageListener) => void;\n}\n\n// The class value passed to `initializeAuth`. The static `type` makes it\n// assignable to the SDK's `Persistence` (a class-valued-typed-as-instance, the\n// same trick the SDK uses for `inMemoryPersistence`); `new ()` lets the SDK — and\n// the tests — instantiate it.\nexport interface HostAuthPersistenceClass extends Persistence {\n type: \"LOCAL\";\n new (): HostAuthPersistenceInstance;\n}\n\nexport interface HostSessionPersistence {\n /** Pass to `initializeAuth(app, { persistence })`. It's a class the SDK `new`s. */\n persistence: HostAuthPersistenceClass;\n /** Load a previously exported blob. Call BEFORE `initializeAuth`. */\n seed: (blob: string) => void;\n /** Serialize the current contents, or `null` when empty (no session). */\n exportBlob: () => string | null;\n /** Notified with the fresh blob (or `null`) whenever the SDK writes/removes. */\n onChange: (listener: (blob: string | null) => void) => () => void;\n /** Drop all contents (used when tearing down the Firebase app). */\n clear: () => void;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isPersistenceValue = (value: unknown): value is PersistenceValue => typeof value === \"string\" || isRecord(value);\n\n// True when `blob` is a JSON object `seed` can load. A blob that fails this can\n// never restore a session (corrupt localStorage, wrong shape), so callers treat\n// it as an expired/invalid session rather than a transient error — the client\n// then drops it instead of retrying the same doomed blob forever.\nexport const isSeedableBlob = (blob: string): boolean => {\n try {\n return isRecord(JSON.parse(blob));\n } catch {\n return false;\n }\n};\n\n// A class (constructor) so the SDK's `_getInstance` accepts it (it asserts\n// `cls instanceof Function`, then `new cls()`); instances hold the shared\n// `store`/`notify`, so a fresh `new` still sees the seeded/live data. `static\n// type` is for the `Persistence` type bridge; the instance `type` is what the\n// SDK reads after `new`.\nconst makeHostPersistenceClass = (store: Map<string, PersistenceValue>, notify: () => void): HostAuthPersistenceClass => {\n class HostAuthPersistence {\n static readonly type = \"LOCAL\" as const;\n readonly type = \"LOCAL\" as const;\n private readonly store = store;\n private readonly notify = notify;\n private readonly external = new Set<StorageListener>();\n _isAvailable(): Promise<boolean> {\n return Promise.resolve(this.store instanceof Map);\n }\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.store.set(key, value);\n this.notify();\n }\n _get(key: string): Promise<PersistenceValue | null> {\n return Promise.resolve(this.store.get(key) ?? null);\n }\n async _remove(key: string): Promise<void> {\n this.store.delete(key);\n this.notify();\n }\n // Node has no cross-tab storage events to deliver, so registered listeners\n // never fire; we still track them so add/remove stay symmetric.\n _addListener(_key: string, listener: StorageListener): void {\n this.external.add(listener);\n }\n _removeListener(_key: string, listener: StorageListener): void {\n this.external.delete(listener);\n }\n }\n return HostAuthPersistence;\n};\n\nexport const createHostSessionPersistence = (): HostSessionPersistence => {\n const store = new Map<string, PersistenceValue>();\n const listeners = new Set<(blob: string | null) => void>();\n\n const exportBlob = (): string | null => (store.size === 0 ? null : JSON.stringify(Object.fromEntries(store)));\n\n const notify = (): void => {\n const blob = exportBlob();\n listeners.forEach((listener) => listener(blob));\n };\n\n const persistence = makeHostPersistenceClass(store, notify);\n\n const seed = (blob: string): void => {\n const parsed: unknown = JSON.parse(blob);\n if (!isRecord(parsed)) throw new Error(\"host session blob must be a JSON object\");\n store.clear();\n for (const [key, value] of Object.entries(parsed)) {\n if (isPersistenceValue(value)) store.set(key, value);\n }\n };\n\n const onChange = (listener: (blob: string | null) => void): (() => void) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n const clear = (): void => {\n store.clear();\n };\n\n return { persistence, seed, exportBlob, onChange, clear };\n};\n","// Firebase init for a remote-host runner.\n//\n// A host acts as a *host*: it signs in to Firebase as the user (via\n// signInWithCredential, see auth.ts) and listens to that user's command queue in\n// Firestore. The modular firebase/firestore + firebase/auth SDKs run in Node, so\n// this mirrors a browser init but also exposes Firestore (default database,\n// which must be in Native mode) and Storage.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/firebase.ts. The\n// public web config is a parameter so each host supplies its own (both hosts\n// reuse the shared mulmoserver project).\nimport { deleteApp, FirebaseApp, FirebaseOptions, initializeApp } from \"firebase/app\";\nimport { Auth, getAuth, initializeAuth } from \"firebase/auth\";\nimport { Firestore, getFirestore } from \"firebase/firestore\";\nimport { FirebaseStorage, getStorage } from \"firebase/storage\";\n\nimport { createHostSessionPersistence, type HostSessionPersistence } from \"./sessionPersistence.js\";\n\nexport interface RemoteHostFirebase {\n app: FirebaseApp;\n auth: Auth;\n firestore: Firestore;\n // Storage carries the full-res attachment bytes the command channel can't (a\n // Firestore command doc caps at ~1 MiB). The host, signed in as the user,\n // pulls each staged upload from `users/{uid}/uploads/{id}` and deletes it\n // after ingest.\n storage: FirebaseStorage;\n}\n\nexport const createRemoteHostFirebase = (config: FirebaseOptions): RemoteHostFirebase => {\n const app = initializeApp(config);\n return { app, auth: getAuth(app), firestore: getFirestore(app), storage: getStorage(app) };\n};\n\nexport interface RemoteHostSessionHandles {\n auth: Auth;\n firestore: Firestore;\n storage: FirebaseStorage;\n // The signed-in uid restored from a seed blob, or null when opened fresh\n // (before `signInHost`) or when the blob held no valid session.\n uid: string | null;\n}\n\n// A restartable Firebase session for a host, backed by the export/seed-able\n// persistence (mulmoserver#50, \"case A'\"). Because `initializeAuth` reads\n// persistence once and can run only once per app, each `open` spins up a FRESH\n// app (unique name) with the persistence seeded first, then tears down the\n// previous app — so a reconnect can restore a browser-parked session, and a\n// fresh connect starts clean. `exportSession`/`onSessionChange` expose the blob\n// the browser stores and the signal to re-sync it.\n// Runs on the freshly opened handles BEFORE the previous session is torn down.\n// Reject to keep the open non-destructive: the fresh app is rolled back and the\n// previous session is preserved (so a failed sign-in or an expired blob doesn't\n// replace a healthy live session).\nexport type RemoteHostSessionValidate = (handles: RemoteHostSessionHandles) => Promise<void>;\n\nexport interface RemoteHostSession {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => Promise<RemoteHostSessionHandles>;\n close: () => Promise<void>;\n exportSession: () => string | null;\n onSessionChange: (cb: (blob: string | null) => void) => () => void;\n}\n\nconst noop = (): void => undefined;\n\n// Run operations one-at-a-time in submission order. `open`/`close` mutate shared\n// store/app state, so overlapping calls must not interleave (they would leak an\n// app or leave `app` pointing at a torn-down instance). Mirrors the lifecycle's\n// serialization; a failed op doesn't block the next.\nconst makeSerializer = () => {\n let transition: Promise<unknown> = Promise.resolve();\n return <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n};\n\n// Build a fresh app from the (already seeded) persistence and wait for the\n// restored auth state to settle. Persistence restore is async, so `uid`\n// reflects a seeded session only after `authStateReady()` (null when the blob\n// was empty/invalid, or on a fresh connect before `signInHost`).\nconst openFreshApp = async (\n config: FirebaseOptions,\n store: HostSessionPersistence,\n name: string,\n): Promise<{ app: FirebaseApp; handles: RemoteHostSessionHandles }> => {\n // `initializeApp` registers the app in the SDK's global registry, so if init\n // then throws we must delete it — otherwise repeated reconnect failures leak\n // a registered app each time.\n const app = initializeApp(config, name);\n try {\n const auth = initializeAuth(app, { persistence: store.persistence });\n await auth.authStateReady();\n return { app, handles: { auth, firestore: getFirestore(app), storage: getStorage(app), uid: auth.currentUser?.uid ?? null } };\n } catch (error) {\n await deleteApp(app).catch(() => undefined);\n throw error;\n }\n};\n\nexport const createRemoteHostSession = (config: FirebaseOptions): RemoteHostSession => {\n const store = createHostSessionPersistence();\n let app: FirebaseApp | null = null;\n let appSeq = 0;\n const serialize = makeSerializer();\n\n const closeInner = async (): Promise<void> => {\n const previous = app;\n app = null;\n store.clear();\n if (previous) await deleteApp(previous);\n };\n\n // Run the caller's check on the fresh handles; on rejection, delete the fresh\n // app so only the caller-visible error escapes and the previous session (never\n // touched here) stays live.\n const validateOrRollback = async (nextApp: FirebaseApp, handles: RemoteHostSessionHandles, validate?: RemoteHostSessionValidate): Promise<void> => {\n if (!validate) return;\n try {\n await validate(handles);\n } catch (error) {\n await deleteApp(nextApp).catch(() => undefined);\n throw error;\n }\n };\n\n const openInner = async (seedBlob?: string, validate?: RemoteHostSessionValidate): Promise<RemoteHostSessionHandles> => {\n // Non-destructive: keep the current session intact until the fresh app is\n // proven to come up AND pass `validate` (sign-in / uid). A bad seed blob, a\n // failed init, or a rejected validation must not tear down a healthy session\n // — the reconnect contract (mulmoserver#50). So we tear the previous app\n // down only AFTER success, and roll the store back on failure.\n const previousApp = app;\n const previousBlob = store.exportBlob();\n appSeq += 1;\n try {\n store.clear();\n if (seedBlob) store.seed(seedBlob);\n const { app: nextApp, handles } = await openFreshApp(config, store, `remote-host-${appSeq}`);\n await validateOrRollback(nextApp, handles, validate);\n app = nextApp;\n if (previousApp) await deleteApp(previousApp).catch(() => undefined);\n return handles;\n } catch (error) {\n store.clear();\n if (previousBlob) store.seed(previousBlob);\n throw error;\n }\n };\n\n return {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => serialize(() => openInner(seedBlob, validate)),\n close: () => serialize(closeInner),\n exportSession: store.exportBlob,\n onSessionChange: store.onChange,\n };\n};\n"],"mappings":";;;;;;;;AAuBA,IAAM,uBAAuB;AAgC7B,IAAM,eAAa,KAAA;AAGnB,IAAM,cAAc,KAAwB,MAAc,aAAA,GAAA,mBAAA,UAAA,CAC9C,KAAK;CAAE,QAAQ;CAAS,OAAO;EAAE;EAAM;CAAQ;CAAG,YAAA,GAAA,mBAAA,gBAAA,CAA2B;AAAE,CAAC,CAAC,CAAC,MAAM,MAAI;AAIxG,IAAM,gBAAgB,WAAsB,SAAA,GAAA,mBAAA,eAAA,CAC3B,WAAW,OAAO,QAAQ;CACvC,MAAM,QAAQ,MAAM,IAAI,IAAI,GAAG,EAAA,CAAG,KAAK;CACvC,IAAI,CAAC,QAAQ,KAAK,WAAW,UAC3B,OAAO;CAET,IAAI,OAAO,KAAK;EAAE,QAAQ;EAAc,YAAA,GAAA,mBAAA,gBAAA,CAA2B;CAAE,CAAC;CACtE,OAAO;EAAE,QAAQ,KAAK;EAAQ,QAAQ,KAAK,UAAU,CAAC;CAAE;AAC1D,CAAC;AAEH,IAAM,aAAa,OAAO,KAAwB,OAAc,YAAgD;CAC9G,IAAI;EAEF,OAAA,GAAA,mBAAA,UAAA,CAAgB,KAAK;GAAE,QAAQ;GAAQ,QAAQ,MAD1B,QAAQ,MAAM,MAAM,KACgB;GAAM,YAAA,GAAA,mBAAA,gBAAA,CAA2B;EAAE,CAAC;EAC7F,OAAO;GAAE,OAAO;GAAQ,QAAQ,MAAM;EAAO;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AI,aAAa,OAAA,GAAA,aAAA,UAAA,CAAgB,WAAW,CAAC,CAAC,YAAY,KAAA,CAAS;GACnE,OAAO;EACT,SAAS,OAAO;GACd,MAAM,MAAM;GACZ,IAAI,cAAc,MAAM,KAAK,YAAY;GACzC,MAAM;EACR;CACF;CAEA,OAAO;EACL,OAAO,UAAmB,aAAyC,gBAAgB,UAAU,UAAU,QAAQ,CAAC;EAChH,aAAa,UAAU,UAAU;EACjC,eAAe,MAAM;EACrB,iBAAiB,MAAM;CACzB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/remote-host/server/hostRunner.ts","../../../src/remote-host/server/lifecycle.ts","../../../src/remote-host/server/auth.ts","../../../src/remote-host/server/sessionPersistence.ts","../../../src/remote-host/server/firebase.ts"],"sourcesContent":["// Host side of the command channel: claim queued commands, run handlers, write\n// results back, and announce presence via heartbeat.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/hostRunner.ts (itself\n// ported from ../mulmoserver). The only signature change vs. that copy: the\n// `firestore` instance is a parameter (each host supplies its own Firebase init),\n// and the heartbeat interval is an option (defaults to one minute).\nimport { DocumentReference, Firestore, deleteDoc, onSnapshot, query, runTransaction, serverTimestamp, setDoc, updateDoc, where } from \"firebase/firestore\";\n\nimport { errorMessage } from \"../../collection/core/errorMessage.js\";\nimport {\n Channel,\n Command,\n CommandHandler,\n CommandHandlers,\n JsonObject,\n buildHostPresence,\n byCreatedAt,\n commandsCollection,\n hostDoc,\n isExpired,\n} from \"../index.js\";\n\nconst DEFAULT_HEARTBEAT_MS = 60_000;\n\nexport interface HostEvent {\n phase: \"received\" | \"done\" | \"error\";\n method: string;\n message?: string;\n}\n\nexport interface HostRunnerOptions {\n onEvent?: (event: HostEvent) => void;\n // Called once when the listener dies fatally (after presence has been set\n // offline), so the lifecycle owner can reconcile its own state — e.g. clear\n // the runner handle so status() no longer reports connected. NOT called on a\n // normal stop().\n onClosed?: () => void;\n // Called when a command is dropped for being past its `expiresAt`, BEFORE the\n // doc is deleted, so the host can clean up out-of-band resources the command\n // referenced (e.g. staged attachment uploads in Storage). `uid` is THIS runner's\n // session uid (channel.uid) — passed in rather than read from a global so a\n // concurrent reconnect as a different account can't point cleanup at the wrong\n // user's Storage path. Best-effort: a throw is logged via onEvent and does NOT\n // block the doc deletion. Absent ⇒ the expired doc is simply deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n // Presence heartbeat interval; defaults to one minute.\n heartbeatMs?: number;\n}\n\ninterface Claim {\n method: string;\n params: JsonObject;\n}\n\nconst noop = () => undefined;\n\n// The remote may have deleted the doc on timeout, so ignore write-after-delete.\nconst writeError = (ref: DocumentReference, code: string, message: string) =>\n updateDoc(ref, { status: \"error\", error: { code, message }, updatedAt: serverTimestamp() }).catch(noop);\n\n// Atomically move a command queued -> processing so it is handled exactly once.\n// Returns the method/params to run, or null if another handler already took it.\nconst claimCommand = (firestore: Firestore, ref: DocumentReference): Promise<Claim | null> =>\n runTransaction(firestore, async (txn) => {\n const data = (await txn.get(ref)).data() as Command | undefined;\n if (!data || data.status !== \"queued\") {\n return null;\n }\n txn.update(ref, { status: \"processing\", updatedAt: serverTimestamp() });\n return { method: data.method, params: data.params ?? {} };\n });\n\nconst runHandler = async (ref: DocumentReference, claim: Claim, handler: CommandHandler): Promise<HostEvent> => {\n try {\n const result = await handler(claim.params);\n await updateDoc(ref, { status: \"done\", result: result ?? null, updatedAt: serverTimestamp() });\n return { phase: \"done\", method: claim.method };\n } catch (error) {\n const message = errorMessage(error);\n await writeError(ref, \"handler_error\", message);\n return { phase: \"error\", method: claim.method, message };\n }\n};\n\n// A command past its deadline is removed entirely rather than run: give the host\n// a chance to clean up out-of-band resources (staged attachments), then delete\n// the doc so it is neither reprocessed nor left as a stale error. Both steps are\n// best-effort/idempotent, so a snapshot replay surfacing the same expired doc\n// twice is harmless (no claim transaction needed — see plan edge #3).\nconst expireCommand = async (ref: DocumentReference, command: Command, options: HostRunnerOptions, uid: string) => {\n try {\n await options.onExpire?.(command, uid);\n } catch (error) {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `onExpire failed: ${errorMessage(error)}` });\n }\n // Surface a delete failure (permissions / transient network) the same way the\n // onExpire failure above is surfaced — otherwise the expired doc lingers as\n // \"queued\" with no signal as to why cleanup didn't happen.\n await deleteDoc(ref).catch((error) => {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `expire delete failed: ${errorMessage(error)}` });\n });\n options.onEvent?.({ phase: \"done\", method: command.method, message: \"expired\" });\n};\n\n// Per-runner constants bundled into one context so processCommand stays under the\n// max-params cap: firestore, the handler table, options, and the session uid are\n// all fixed for the runner's lifetime; only ref/command/now vary per command.\ninterface RunnerContext {\n firestore: Firestore;\n handlers: CommandHandlers;\n options: HostRunnerOptions;\n uid: string;\n}\n\nconst processCommand = async (ctx: RunnerContext, ref: DocumentReference, command: Command, now: number) => {\n const { handlers, options } = ctx;\n // Drop an expired command before claiming it — it must never reach a handler.\n if (isExpired(command, now)) {\n await expireCommand(ref, command, options, ctx.uid);\n return;\n }\n const claim = await claimCommand(ctx.firestore, ref);\n if (!claim) {\n return;\n }\n options.onEvent?.({ phase: \"received\", method: claim.method });\n const handler: CommandHandler | undefined = handlers[claim.method];\n if (!handler) {\n await writeError(ref, \"unknown_method\", `No handler for method: ${claim.method}`);\n options.onEvent?.({ phase: \"error\", method: claim.method, message: \"unknown method\" });\n return;\n }\n options.onEvent?.(await runHandler(ref, claim, handler));\n};\n\n// startHostRunner subscribes to queued commands for the given channel and runs\n// each one through the supplied handler table. It also announces presence (a\n// heartbeat on users/{uid}/hosts/{hostId}) so the remote can tell it is online.\n// Returns a stop function that goes offline and detaches the listener.\nexport const startHostRunner = (firestore: Firestore, channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions = {}): (() => void) => {\n const presence = hostDoc(firestore, channel);\n // Advertise online/offline + the capability set (method names + protocol\n // version) on the same doc the remote already listens to for presence.\n // Returns void, not the promise: presence is advertised best-effort from\n // three call sites (announce, the snapshot-error path, the teardown), none of\n // which can await. Terminating the chain here with `.catch(noop)` keeps every\n // caller from floating a promise it has no way to handle.\n const writePresence = (online: boolean): void => {\n setDoc(presence, { ...buildHostPresence(channel, handlers, online), updatedAt: serverTimestamp() }).catch(noop);\n };\n const announce = () => {\n writePresence(true);\n };\n announce();\n const beat = setInterval(announce, options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);\n\n const queuedCommands = query(commandsCollection(firestore, channel), where(\"status\", \"==\", \"queued\"));\n const ctx: RunnerContext = { firestore, handlers, options, uid: channel.uid };\n const unsubscribe = onSnapshot(\n queuedCommands,\n (snapshot) => {\n const now = Date.now();\n // Best-effort oldest-first DISPATCH only. Commands are processed\n // concurrently (not awaited in turn) and out-of-order completion is fine by\n // design — chat is asynchronous — so this sort just biases which command\n // starts first; it is not an ordering guarantee. We still sort in memory\n // rather than orderBy(\"createdAt\") on the query because a Firestore orderBy\n // silently EXCLUDES docs missing the field — which would drop every\n // pre-offline-queue command (no createdAt) from the queue entirely.\n const added = snapshot\n .docChanges()\n .filter((change) => change.type === \"added\")\n .map((change) => ({ ref: change.doc.ref, command: change.doc.data() as Command }))\n .sort((left, right) => byCreatedAt(left.command, right.command));\n added.forEach(({ ref, command }) => {\n processCommand(ctx, ref, command, now).catch(noop);\n });\n },\n (error) => {\n options.onEvent?.({ phase: \"error\", method: \"listen\", message: error.message });\n // A Firestore onSnapshot error terminates the listener and it does not\n // recover on its own. Stop advertising presence (clear the heartbeat +\n // write online:false) so remotes see the host as offline instead of a\n // live host that silently consumes no commands.\n clearInterval(beat);\n writePresence(false);\n options.onClosed?.();\n },\n );\n\n return () => {\n clearInterval(beat);\n writePresence(false);\n unsubscribe();\n };\n};\n","// Remote-host lifecycle: wire a Firebase session to the Firestore host runner so\n// connecting starts the command loop + presence heartbeat, and disconnecting\n// stops both.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/index.ts. The factory\n// takes injected collaborators — real hosts bind them to Firebase; tests pass\n// fakes to exercise the invariants (non-destructive connect, serialized\n// transitions, status/liveness reconciliation on fatal listener death) without a\n// network. `hostId` and the logger are injected too, so this file imports no\n// Firebase and no host logger and stays trivially unit-testable.\n//\n// Single-account, single-host per instance, in-memory session: a host restart\n// drops the session and needs a re-connect.\nimport type { Channel, Command, CommandHandlers } from \"../index.js\";\nimport type { HostRunnerOptions } from \"./hostRunner.js\";\n\nexport interface RemoteHostStatus {\n connected: boolean;\n uid: string | null;\n}\n\n// Minimal logger the factory calls; each host adapts its own logger to this\n// shape (or omits it to run silently, as the tests do).\nexport interface RemoteHostLogger {\n info: (msg: string) => void;\n warn: (msg: string) => void;\n debug: (msg: string) => void;\n}\n\n// Injectable collaborators — a real host binds these to Firebase + its own\n// hostId; tests pass fakes to exercise the lifecycle without a network.\n// `startRunner` is the host's `startHostRunner` pre-bound with its Firestore\n// instance, so this module needs no Firebase of its own.\nexport interface RemoteHostDeps {\n hostId: string;\n signIn: (idToken: string) => Promise<string>;\n // Restore a session from a browser-parked blob (case A', mulmoserver#50) and\n // resolve to its uid — no popup. MUST reject when the blob yields no valid\n // session so `reconnect` stays non-destructive. Absent ⇒ `reconnect` throws.\n restore?: (sessionBlob: string) => Promise<string>;\n signOut: () => Promise<void>;\n currentUid: () => string | null;\n startRunner: (channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions) => () => void;\n handlers: CommandHandlers;\n // Optional host-specific cleanup for a command the runner drops as expired\n // (e.g. delete its staged attachment uploads). Threaded verbatim into the\n // runner's `onExpire`, which supplies the session `uid` so cleanup targets the\n // right user's Storage path even across a reconnect; absent ⇒ an expired doc is\n // just deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n log?: RemoteHostLogger;\n}\n\nexport interface RemoteHostLifecycle {\n connect: (idToken: string) => Promise<RemoteHostStatus>;\n // Restore a browser-parked session and start the runner — popup-free re-attach\n // after a host restart. Non-destructive like `connect`. Rejects if `deps.restore`\n // isn't wired, or if restore fails (blob expired/invalid → caller falls back to connect).\n reconnect: (sessionBlob: string) => Promise<RemoteHostStatus>;\n disconnect: () => Promise<RemoteHostStatus>;\n status: () => RemoteHostStatus;\n}\n\nconst noop = () => undefined;\nconst silentLogger: RemoteHostLogger = { info: noop, warn: noop, debug: noop };\n\nexport const createRemoteHost = (deps: RemoteHostDeps): RemoteHostLifecycle => {\n const log = deps.log ?? silentLogger;\n\n // The running host runner's stop() handle, or null when disconnected. Keeps\n // the single-host invariant — one runner at a time.\n let stopRunner: (() => void) | null = null;\n\n // Serialize connect/disconnect so overlapping requests can't both mutate\n // stopRunner (which would leak a second runner) or race auth against teardown.\n // Each transition runs only after the previous one settles; a failed\n // transition does not block the next (both handlers run the next op).\n let transition: Promise<unknown> = Promise.resolve();\n\n const serialize = <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n\n const stopIfRunning = () => {\n if (stopRunner) {\n stopRunner();\n stopRunner = null;\n }\n };\n\n const status = (): RemoteHostStatus => ({ connected: stopRunner !== null, uid: deps.currentUid() });\n\n // Swap the running runner for one bound to `uid`. Callers authenticate FIRST\n // (before this teardown) so a failed connect/reconnect keeps a healthy session.\n const attach = (uid: string, verb: string): RemoteHostStatus => {\n stopIfRunning();\n const runner = deps.startRunner({ uid, hostId: deps.hostId }, deps.handlers, {\n onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),\n onExpire: deps.onExpire,\n // Fatal listener death: drop the handle so status() stops reporting\n // connected — but only if it still points at THIS runner (a later\n // reconnect may have replaced it).\n onClosed: () => {\n if (stopRunner === runner) {\n stopRunner = null;\n log.warn(\"host runner listener died; marked disconnected\");\n }\n },\n });\n stopRunner = runner;\n log.info(`${verb} as ${uid}, host runner started (hostId=${deps.hostId})`);\n return status();\n };\n\n const connect = (idToken: string): Promise<RemoteHostStatus> => serialize(async () => attach(await deps.signIn(idToken), \"connected\"));\n\n const reconnect = (sessionBlob: string): Promise<RemoteHostStatus> =>\n serialize(async () => {\n const { restore } = deps;\n if (!restore) throw new Error(\"remote-host reconnect requires a `restore` dependency\");\n return attach(await restore(sessionBlob), \"reconnected\");\n });\n\n const disconnect = (): Promise<RemoteHostStatus> =>\n serialize(async () => {\n stopIfRunning();\n await deps.signOut();\n log.info(\"disconnected, host runner stopped\");\n return status();\n });\n\n return { connect, reconnect, disconnect, status };\n};\n","// Firebase credential exchange for the remote-host runner.\n//\n// The host authenticates to Firestore *as the user* (Option B) using the\n// Firebase JS SDK's signInWithCredential with a browser-minted Google OAuth ID\n// token — no Admin SDK, no project service account. Security rules keep the host\n// scoped to that user's own users/{uid}/… subtree.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/auth.ts. The `auth`\n// instance is a parameter so each host binds its own Firebase init; the factory\n// returns the low-level credential primitives (the connect/disconnect lifecycle\n// that starts/stops the host runner lives in createRemoteHost).\nimport { Auth, GoogleAuthProvider, signInWithCredential, signOut } from \"firebase/auth\";\n\nexport interface RemoteHostAuth {\n // Establish the Firebase session from a browser-minted Google OAuth ID token.\n // The token is used once here; the JS SDK then holds its own refresh token for\n // the process lifetime. Resolves to the authenticated uid.\n signInHost: (idToken: string) => Promise<string>;\n // Tear down the Firebase session (in-memory persistence → re-login on restart).\n signOutHost: () => Promise<void>;\n // The currently signed-in uid, or null when disconnected.\n currentUid: () => string | null;\n}\n\nexport const createRemoteHostAuth = (auth: Auth): RemoteHostAuth => ({\n signInHost: async (idToken: string): Promise<string> => {\n const credential = GoogleAuthProvider.credential(idToken);\n const userCredential = await signInWithCredential(auth, credential);\n return userCredential.user.uid;\n },\n signOutHost: (): Promise<void> => signOut(auth),\n currentUid: (): string | null => auth.currentUser?.uid ?? null,\n});\n","// A custom Firebase Auth persistence that keeps the signed-in session in memory\n// but can be seeded from — and exported back to — an opaque blob, so a host's\n// Firebase session survives a process restart by being parked in the browser's\n// localStorage (mulmoserver#50, \"case A'\"). The blob is whatever the SDK wrote\n// into persistence, round-tripped through JSON; we NEVER interpret its fields,\n// so we don't couple to the SDK's serialized-user format across versions.\n//\n// **Persistence is a CLASS, not an instance.** `initializeAuth(app, { persistence })`\n// hands the value to the SDK's `_getInstance(cls)`, which asserts `cls instanceof\n// Function` (\"Expected a class definition\") and then `new cls()`. Passing a plain\n// object throws — the SDK's own `inMemoryPersistence` is likewise a class. The\n// class is defined per factory call so its instances share this call's store;\n// `type: \"LOCAL\"` makes the SDK treat it as durable and persist the user.\n//\n// Seed BEFORE `initializeAuth` — the SDK reads persistence once at init. `onChange`\n// fires when the SDK writes/removes a key (a token update that rotates the stored\n// blob, or a sign-out) — the signal to re-sync the browser copy.\nimport type { Persistence } from \"firebase/auth\";\n\n// The SDK stores values as JSON objects (a serialized user) or strings. We treat\n// them opaquely — a value is either.\ntype PersistenceValue = Record<string, unknown> | string;\n\ntype StorageListener = (value: PersistenceValue | null) => void;\n\n// The instance the SDK builds via `new` and then drives with these `_`-methods.\nexport interface HostAuthPersistenceInstance extends Persistence {\n type: \"LOCAL\";\n _isAvailable: () => Promise<boolean>;\n _set: (key: string, value: PersistenceValue) => Promise<void>;\n _get: (key: string) => Promise<PersistenceValue | null>;\n _remove: (key: string) => Promise<void>;\n _addListener: (key: string, listener: StorageListener) => void;\n _removeListener: (key: string, listener: StorageListener) => void;\n}\n\n// The class value passed to `initializeAuth`. The static `type` makes it\n// assignable to the SDK's `Persistence` (a class-valued-typed-as-instance, the\n// same trick the SDK uses for `inMemoryPersistence`); `new ()` lets the SDK — and\n// the tests — instantiate it.\nexport interface HostAuthPersistenceClass extends Persistence {\n type: \"LOCAL\";\n new (): HostAuthPersistenceInstance;\n}\n\nexport interface HostSessionPersistence {\n /** Pass to `initializeAuth(app, { persistence })`. It's a class the SDK `new`s. */\n persistence: HostAuthPersistenceClass;\n /** Load a previously exported blob. Call BEFORE `initializeAuth`. */\n seed: (blob: string) => void;\n /** Serialize the current contents, or `null` when empty (no session). */\n exportBlob: () => string | null;\n /** Notified with the fresh blob (or `null`) whenever the SDK writes/removes. */\n onChange: (listener: (blob: string | null) => void) => () => void;\n /** Drop all contents (used when tearing down the Firebase app). */\n clear: () => void;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isPersistenceValue = (value: unknown): value is PersistenceValue => typeof value === \"string\" || isRecord(value);\n\n// True when `blob` is a JSON object `seed` can load. A blob that fails this can\n// never restore a session (corrupt localStorage, wrong shape), so callers treat\n// it as an expired/invalid session rather than a transient error — the client\n// then drops it instead of retrying the same doomed blob forever.\nexport const isSeedableBlob = (blob: string): boolean => {\n try {\n return isRecord(JSON.parse(blob));\n } catch {\n return false;\n }\n};\n\n// A class (constructor) so the SDK's `_getInstance` accepts it (it asserts\n// `cls instanceof Function`, then `new cls()`); instances hold the shared\n// `store`/`notify`, so a fresh `new` still sees the seeded/live data. `static\n// type` is for the `Persistence` type bridge; the instance `type` is what the\n// SDK reads after `new`.\nconst makeHostPersistenceClass = (store: Map<string, PersistenceValue>, notify: () => void): HostAuthPersistenceClass => {\n class HostAuthPersistence {\n static readonly type = \"LOCAL\" as const;\n readonly type = \"LOCAL\" as const;\n private readonly store = store;\n private readonly notify = notify;\n private readonly external = new Set<StorageListener>();\n _isAvailable(): Promise<boolean> {\n return Promise.resolve(this.store instanceof Map);\n }\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.store.set(key, value);\n this.notify();\n }\n _get(key: string): Promise<PersistenceValue | null> {\n return Promise.resolve(this.store.get(key) ?? null);\n }\n async _remove(key: string): Promise<void> {\n this.store.delete(key);\n this.notify();\n }\n // Node has no cross-tab storage events to deliver, so registered listeners\n // never fire; we still track them so add/remove stay symmetric.\n _addListener(_key: string, listener: StorageListener): void {\n this.external.add(listener);\n }\n _removeListener(_key: string, listener: StorageListener): void {\n this.external.delete(listener);\n }\n }\n return HostAuthPersistence;\n};\n\nexport const createHostSessionPersistence = (): HostSessionPersistence => {\n const store = new Map<string, PersistenceValue>();\n const listeners = new Set<(blob: string | null) => void>();\n\n const exportBlob = (): string | null => (store.size === 0 ? null : JSON.stringify(Object.fromEntries(store)));\n\n const notify = (): void => {\n const blob = exportBlob();\n listeners.forEach((listener) => listener(blob));\n };\n\n const persistence = makeHostPersistenceClass(store, notify);\n\n const seed = (blob: string): void => {\n const parsed: unknown = JSON.parse(blob);\n if (!isRecord(parsed)) throw new Error(\"host session blob must be a JSON object\");\n store.clear();\n for (const [key, value] of Object.entries(parsed)) {\n if (isPersistenceValue(value)) store.set(key, value);\n }\n };\n\n const onChange = (listener: (blob: string | null) => void): (() => void) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n const clear = (): void => {\n store.clear();\n };\n\n return { persistence, seed, exportBlob, onChange, clear };\n};\n","// Firebase init for a remote-host runner.\n//\n// A host acts as a *host*: it signs in to Firebase as the user (via\n// signInWithCredential, see auth.ts) and listens to that user's command queue in\n// Firestore. The modular firebase/firestore + firebase/auth SDKs run in Node, so\n// this mirrors a browser init but also exposes Firestore (default database,\n// which must be in Native mode) and Storage.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/firebase.ts. The\n// public web config is a parameter so each host supplies its own (both hosts\n// reuse the shared mulmoserver project).\nimport { deleteApp, FirebaseApp, FirebaseOptions, initializeApp } from \"firebase/app\";\nimport { Auth, getAuth, initializeAuth } from \"firebase/auth\";\nimport { Firestore, getFirestore } from \"firebase/firestore\";\nimport { FirebaseStorage, getStorage } from \"firebase/storage\";\n\nimport { createHostSessionPersistence, type HostSessionPersistence } from \"./sessionPersistence.js\";\n\nexport interface RemoteHostFirebase {\n app: FirebaseApp;\n auth: Auth;\n firestore: Firestore;\n // Storage carries the full-res attachment bytes the command channel can't (a\n // Firestore command doc caps at ~1 MiB). The host, signed in as the user,\n // pulls each staged upload from `users/{uid}/uploads/{id}` and deletes it\n // after ingest.\n storage: FirebaseStorage;\n}\n\nexport const createRemoteHostFirebase = (config: FirebaseOptions): RemoteHostFirebase => {\n const app = initializeApp(config);\n return { app, auth: getAuth(app), firestore: getFirestore(app), storage: getStorage(app) };\n};\n\nexport interface RemoteHostSessionHandles {\n auth: Auth;\n firestore: Firestore;\n storage: FirebaseStorage;\n // The signed-in uid restored from a seed blob, or null when opened fresh\n // (before `signInHost`) or when the blob held no valid session.\n uid: string | null;\n}\n\n// A restartable Firebase session for a host, backed by the export/seed-able\n// persistence (mulmoserver#50, \"case A'\"). Because `initializeAuth` reads\n// persistence once and can run only once per app, each `open` spins up a FRESH\n// app (unique name) with the persistence seeded first, then tears down the\n// previous app — so a reconnect can restore a browser-parked session, and a\n// fresh connect starts clean. `exportSession`/`onSessionChange` expose the blob\n// the browser stores and the signal to re-sync it.\n// Runs on the freshly opened handles BEFORE the previous session is torn down.\n// Reject to keep the open non-destructive: the fresh app is rolled back and the\n// previous session is preserved (so a failed sign-in or an expired blob doesn't\n// replace a healthy live session).\nexport type RemoteHostSessionValidate = (handles: RemoteHostSessionHandles) => Promise<void>;\n\nexport interface RemoteHostSession {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => Promise<RemoteHostSessionHandles>;\n close: () => Promise<void>;\n exportSession: () => string | null;\n onSessionChange: (cb: (blob: string | null) => void) => () => void;\n}\n\nconst noop = (): void => undefined;\n\n// Run operations one-at-a-time in submission order. `open`/`close` mutate shared\n// store/app state, so overlapping calls must not interleave (they would leak an\n// app or leave `app` pointing at a torn-down instance). Mirrors the lifecycle's\n// serialization; a failed op doesn't block the next.\nconst makeSerializer = () => {\n let transition: Promise<unknown> = Promise.resolve();\n return <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n};\n\n// Build a fresh app from the (already seeded) persistence and wait for the\n// restored auth state to settle. Persistence restore is async, so `uid`\n// reflects a seeded session only after `authStateReady()` (null when the blob\n// was empty/invalid, or on a fresh connect before `signInHost`).\nconst openFreshApp = async (\n config: FirebaseOptions,\n store: HostSessionPersistence,\n name: string,\n): Promise<{ app: FirebaseApp; handles: RemoteHostSessionHandles }> => {\n // `initializeApp` registers the app in the SDK's global registry, so if init\n // then throws we must delete it — otherwise repeated reconnect failures leak\n // a registered app each time.\n const app = initializeApp(config, name);\n try {\n const auth = initializeAuth(app, { persistence: store.persistence });\n await auth.authStateReady();\n return { app, handles: { auth, firestore: getFirestore(app), storage: getStorage(app), uid: auth.currentUser?.uid ?? null } };\n } catch (error) {\n await deleteApp(app).catch(() => undefined);\n throw error;\n }\n};\n\nexport const createRemoteHostSession = (config: FirebaseOptions): RemoteHostSession => {\n const store = createHostSessionPersistence();\n let app: FirebaseApp | null = null;\n let appSeq = 0;\n const serialize = makeSerializer();\n\n const closeInner = async (): Promise<void> => {\n const previous = app;\n app = null;\n store.clear();\n if (previous) await deleteApp(previous);\n };\n\n // Run the caller's check on the fresh handles; on rejection, delete the fresh\n // app so only the caller-visible error escapes and the previous session (never\n // touched here) stays live.\n const validateOrRollback = async (nextApp: FirebaseApp, handles: RemoteHostSessionHandles, validate?: RemoteHostSessionValidate): Promise<void> => {\n if (!validate) return;\n try {\n await validate(handles);\n } catch (error) {\n await deleteApp(nextApp).catch(() => undefined);\n throw error;\n }\n };\n\n const openInner = async (seedBlob?: string, validate?: RemoteHostSessionValidate): Promise<RemoteHostSessionHandles> => {\n // Non-destructive: keep the current session intact until the fresh app is\n // proven to come up AND pass `validate` (sign-in / uid). A bad seed blob, a\n // failed init, or a rejected validation must not tear down a healthy session\n // — the reconnect contract (mulmoserver#50). So we tear the previous app\n // down only AFTER success, and roll the store back on failure.\n const previousApp = app;\n const previousBlob = store.exportBlob();\n appSeq += 1;\n try {\n store.clear();\n if (seedBlob) store.seed(seedBlob);\n const { app: nextApp, handles } = await openFreshApp(config, store, `remote-host-${appSeq}`);\n await validateOrRollback(nextApp, handles, validate);\n app = nextApp;\n if (previousApp) await deleteApp(previousApp).catch(() => undefined);\n return handles;\n } catch (error) {\n store.clear();\n if (previousBlob) store.seed(previousBlob);\n throw error;\n }\n };\n\n return {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => serialize(() => openInner(seedBlob, validate)),\n close: () => serialize(closeIn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,eAAe,MAAM;EACrB,iBAAiB,MAAM;CACzB;AACF"}
|
|
@@ -97,10 +97,12 @@ var processCommand = async (ctx, ref, command, now) => {
|
|
|
97
97
|
};
|
|
98
98
|
var startHostRunner = (firestore, channel, handlers, options = {}) => {
|
|
99
99
|
const presence = hostDoc(firestore, channel);
|
|
100
|
-
const writePresence = (online) =>
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
100
|
+
const writePresence = (online) => {
|
|
101
|
+
setDoc(presence, {
|
|
102
|
+
...buildHostPresence(channel, handlers, online),
|
|
103
|
+
updatedAt: serverTimestamp()
|
|
104
|
+
}).catch(noop$2);
|
|
105
|
+
};
|
|
104
106
|
const announce = () => {
|
|
105
107
|
writePresence(true);
|
|
106
108
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/remote-host/server/hostRunner.ts","../../../src/remote-host/server/lifecycle.ts","../../../src/remote-host/server/auth.ts","../../../src/remote-host/server/sessionPersistence.ts","../../../src/remote-host/server/firebase.ts"],"sourcesContent":["// Host side of the command channel: claim queued commands, run handlers, write\n// results back, and announce presence via heartbeat.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/hostRunner.ts (itself\n// ported from ../mulmoserver). The only signature change vs. that copy: the\n// `firestore` instance is a parameter (each host supplies its own Firebase init),\n// and the heartbeat interval is an option (defaults to one minute).\nimport { DocumentReference, Firestore, deleteDoc, onSnapshot, query, runTransaction, serverTimestamp, setDoc, updateDoc, where } from \"firebase/firestore\";\n\nimport { errorMessage } from \"../../collection/core/errorMessage.js\";\nimport {\n Channel,\n Command,\n CommandHandler,\n CommandHandlers,\n JsonObject,\n buildHostPresence,\n byCreatedAt,\n commandsCollection,\n hostDoc,\n isExpired,\n} from \"../index.js\";\n\nconst DEFAULT_HEARTBEAT_MS = 60_000;\n\nexport interface HostEvent {\n phase: \"received\" | \"done\" | \"error\";\n method: string;\n message?: string;\n}\n\nexport interface HostRunnerOptions {\n onEvent?: (event: HostEvent) => void;\n // Called once when the listener dies fatally (after presence has been set\n // offline), so the lifecycle owner can reconcile its own state — e.g. clear\n // the runner handle so status() no longer reports connected. NOT called on a\n // normal stop().\n onClosed?: () => void;\n // Called when a command is dropped for being past its `expiresAt`, BEFORE the\n // doc is deleted, so the host can clean up out-of-band resources the command\n // referenced (e.g. staged attachment uploads in Storage). `uid` is THIS runner's\n // session uid (channel.uid) — passed in rather than read from a global so a\n // concurrent reconnect as a different account can't point cleanup at the wrong\n // user's Storage path. Best-effort: a throw is logged via onEvent and does NOT\n // block the doc deletion. Absent ⇒ the expired doc is simply deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n // Presence heartbeat interval; defaults to one minute.\n heartbeatMs?: number;\n}\n\ninterface Claim {\n method: string;\n params: JsonObject;\n}\n\nconst noop = () => undefined;\n\n// The remote may have deleted the doc on timeout, so ignore write-after-delete.\nconst writeError = (ref: DocumentReference, code: string, message: string) =>\n updateDoc(ref, { status: \"error\", error: { code, message }, updatedAt: serverTimestamp() }).catch(noop);\n\n// Atomically move a command queued -> processing so it is handled exactly once.\n// Returns the method/params to run, or null if another handler already took it.\nconst claimCommand = (firestore: Firestore, ref: DocumentReference): Promise<Claim | null> =>\n runTransaction(firestore, async (txn) => {\n const data = (await txn.get(ref)).data() as Command | undefined;\n if (!data || data.status !== \"queued\") {\n return null;\n }\n txn.update(ref, { status: \"processing\", updatedAt: serverTimestamp() });\n return { method: data.method, params: data.params ?? {} };\n });\n\nconst runHandler = async (ref: DocumentReference, claim: Claim, handler: CommandHandler): Promise<HostEvent> => {\n try {\n const result = await handler(claim.params);\n await updateDoc(ref, { status: \"done\", result: result ?? null, updatedAt: serverTimestamp() });\n return { phase: \"done\", method: claim.method };\n } catch (error) {\n const message = errorMessage(error);\n await writeError(ref, \"handler_error\", message);\n return { phase: \"error\", method: claim.method, message };\n }\n};\n\n// A command past its deadline is removed entirely rather than run: give the host\n// a chance to clean up out-of-band resources (staged attachments), then delete\n// the doc so it is neither reprocessed nor left as a stale error. Both steps are\n// best-effort/idempotent, so a snapshot replay surfacing the same expired doc\n// twice is harmless (no claim transaction needed — see plan edge #3).\nconst expireCommand = async (ref: DocumentReference, command: Command, options: HostRunnerOptions, uid: string) => {\n try {\n await options.onExpire?.(command, uid);\n } catch (error) {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `onExpire failed: ${errorMessage(error)}` });\n }\n // Surface a delete failure (permissions / transient network) the same way the\n // onExpire failure above is surfaced — otherwise the expired doc lingers as\n // \"queued\" with no signal as to why cleanup didn't happen.\n await deleteDoc(ref).catch((error) => {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `expire delete failed: ${errorMessage(error)}` });\n });\n options.onEvent?.({ phase: \"done\", method: command.method, message: \"expired\" });\n};\n\n// Per-runner constants bundled into one context so processCommand stays under the\n// max-params cap: firestore, the handler table, options, and the session uid are\n// all fixed for the runner's lifetime; only ref/command/now vary per command.\ninterface RunnerContext {\n firestore: Firestore;\n handlers: CommandHandlers;\n options: HostRunnerOptions;\n uid: string;\n}\n\nconst processCommand = async (ctx: RunnerContext, ref: DocumentReference, command: Command, now: number) => {\n const { handlers, options } = ctx;\n // Drop an expired command before claiming it — it must never reach a handler.\n if (isExpired(command, now)) {\n await expireCommand(ref, command, options, ctx.uid);\n return;\n }\n const claim = await claimCommand(ctx.firestore, ref);\n if (!claim) {\n return;\n }\n options.onEvent?.({ phase: \"received\", method: claim.method });\n const handler: CommandHandler | undefined = handlers[claim.method];\n if (!handler) {\n await writeError(ref, \"unknown_method\", `No handler for method: ${claim.method}`);\n options.onEvent?.({ phase: \"error\", method: claim.method, message: \"unknown method\" });\n return;\n }\n options.onEvent?.(await runHandler(ref, claim, handler));\n};\n\n// startHostRunner subscribes to queued commands for the given channel and runs\n// each one through the supplied handler table. It also announces presence (a\n// heartbeat on users/{uid}/hosts/{hostId}) so the remote can tell it is online.\n// Returns a stop function that goes offline and detaches the listener.\nexport const startHostRunner = (firestore: Firestore, channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions = {}): (() => void) => {\n const presence = hostDoc(firestore, channel);\n // Advertise online/offline + the capability set (method names + protocol\n // version) on the same doc the remote already listens to for presence.\n const writePresence = (online: boolean) => setDoc(presence, { ...buildHostPresence(channel, handlers, online), updatedAt: serverTimestamp() }).catch(noop);\n const announce = () => {\n writePresence(true);\n };\n announce();\n const beat = setInterval(announce, options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);\n\n const queuedCommands = query(commandsCollection(firestore, channel), where(\"status\", \"==\", \"queued\"));\n const ctx: RunnerContext = { firestore, handlers, options, uid: channel.uid };\n const unsubscribe = onSnapshot(\n queuedCommands,\n (snapshot) => {\n const now = Date.now();\n // Best-effort oldest-first DISPATCH only. Commands are processed\n // concurrently (not awaited in turn) and out-of-order completion is fine by\n // design — chat is asynchronous — so this sort just biases which command\n // starts first; it is not an ordering guarantee. We still sort in memory\n // rather than orderBy(\"createdAt\") on the query because a Firestore orderBy\n // silently EXCLUDES docs missing the field — which would drop every\n // pre-offline-queue command (no createdAt) from the queue entirely.\n const added = snapshot\n .docChanges()\n .filter((change) => change.type === \"added\")\n .map((change) => ({ ref: change.doc.ref, command: change.doc.data() as Command }))\n .sort((left, right) => byCreatedAt(left.command, right.command));\n added.forEach(({ ref, command }) => {\n processCommand(ctx, ref, command, now).catch(noop);\n });\n },\n (error) => {\n options.onEvent?.({ phase: \"error\", method: \"listen\", message: error.message });\n // A Firestore onSnapshot error terminates the listener and it does not\n // recover on its own. Stop advertising presence (clear the heartbeat +\n // write online:false) so remotes see the host as offline instead of a\n // live host that silently consumes no commands.\n clearInterval(beat);\n writePresence(false);\n options.onClosed?.();\n },\n );\n\n return () => {\n clearInterval(beat);\n writePresence(false);\n unsubscribe();\n };\n};\n","// Remote-host lifecycle: wire a Firebase session to the Firestore host runner so\n// connecting starts the command loop + presence heartbeat, and disconnecting\n// stops both.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/index.ts. The factory\n// takes injected collaborators — real hosts bind them to Firebase; tests pass\n// fakes to exercise the invariants (non-destructive connect, serialized\n// transitions, status/liveness reconciliation on fatal listener death) without a\n// network. `hostId` and the logger are injected too, so this file imports no\n// Firebase and no host logger and stays trivially unit-testable.\n//\n// Single-account, single-host per instance, in-memory session: a host restart\n// drops the session and needs a re-connect.\nimport type { Channel, Command, CommandHandlers } from \"../index.js\";\nimport type { HostRunnerOptions } from \"./hostRunner.js\";\n\nexport interface RemoteHostStatus {\n connected: boolean;\n uid: string | null;\n}\n\n// Minimal logger the factory calls; each host adapts its own logger to this\n// shape (or omits it to run silently, as the tests do).\nexport interface RemoteHostLogger {\n info: (msg: string) => void;\n warn: (msg: string) => void;\n debug: (msg: string) => void;\n}\n\n// Injectable collaborators — a real host binds these to Firebase + its own\n// hostId; tests pass fakes to exercise the lifecycle without a network.\n// `startRunner` is the host's `startHostRunner` pre-bound with its Firestore\n// instance, so this module needs no Firebase of its own.\nexport interface RemoteHostDeps {\n hostId: string;\n signIn: (idToken: string) => Promise<string>;\n // Restore a session from a browser-parked blob (case A', mulmoserver#50) and\n // resolve to its uid — no popup. MUST reject when the blob yields no valid\n // session so `reconnect` stays non-destructive. Absent ⇒ `reconnect` throws.\n restore?: (sessionBlob: string) => Promise<string>;\n signOut: () => Promise<void>;\n currentUid: () => string | null;\n startRunner: (channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions) => () => void;\n handlers: CommandHandlers;\n // Optional host-specific cleanup for a command the runner drops as expired\n // (e.g. delete its staged attachment uploads). Threaded verbatim into the\n // runner's `onExpire`, which supplies the session `uid` so cleanup targets the\n // right user's Storage path even across a reconnect; absent ⇒ an expired doc is\n // just deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n log?: RemoteHostLogger;\n}\n\nexport interface RemoteHostLifecycle {\n connect: (idToken: string) => Promise<RemoteHostStatus>;\n // Restore a browser-parked session and start the runner — popup-free re-attach\n // after a host restart. Non-destructive like `connect`. Rejects if `deps.restore`\n // isn't wired, or if restore fails (blob expired/invalid → caller falls back to connect).\n reconnect: (sessionBlob: string) => Promise<RemoteHostStatus>;\n disconnect: () => Promise<RemoteHostStatus>;\n status: () => RemoteHostStatus;\n}\n\nconst noop = () => undefined;\nconst silentLogger: RemoteHostLogger = { info: noop, warn: noop, debug: noop };\n\nexport const createRemoteHost = (deps: RemoteHostDeps): RemoteHostLifecycle => {\n const log = deps.log ?? silentLogger;\n\n // The running host runner's stop() handle, or null when disconnected. Keeps\n // the single-host invariant — one runner at a time.\n let stopRunner: (() => void) | null = null;\n\n // Serialize connect/disconnect so overlapping requests can't both mutate\n // stopRunner (which would leak a second runner) or race auth against teardown.\n // Each transition runs only after the previous one settles; a failed\n // transition does not block the next (both handlers run the next op).\n let transition: Promise<unknown> = Promise.resolve();\n\n const serialize = <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n\n const stopIfRunning = () => {\n if (stopRunner) {\n stopRunner();\n stopRunner = null;\n }\n };\n\n const status = (): RemoteHostStatus => ({ connected: stopRunner !== null, uid: deps.currentUid() });\n\n // Swap the running runner for one bound to `uid`. Callers authenticate FIRST\n // (before this teardown) so a failed connect/reconnect keeps a healthy session.\n const attach = (uid: string, verb: string): RemoteHostStatus => {\n stopIfRunning();\n const runner = deps.startRunner({ uid, hostId: deps.hostId }, deps.handlers, {\n onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),\n onExpire: deps.onExpire,\n // Fatal listener death: drop the handle so status() stops reporting\n // connected — but only if it still points at THIS runner (a later\n // reconnect may have replaced it).\n onClosed: () => {\n if (stopRunner === runner) {\n stopRunner = null;\n log.warn(\"host runner listener died; marked disconnected\");\n }\n },\n });\n stopRunner = runner;\n log.info(`${verb} as ${uid}, host runner started (hostId=${deps.hostId})`);\n return status();\n };\n\n const connect = (idToken: string): Promise<RemoteHostStatus> => serialize(async () => attach(await deps.signIn(idToken), \"connected\"));\n\n const reconnect = (sessionBlob: string): Promise<RemoteHostStatus> =>\n serialize(async () => {\n const { restore } = deps;\n if (!restore) throw new Error(\"remote-host reconnect requires a `restore` dependency\");\n return attach(await restore(sessionBlob), \"reconnected\");\n });\n\n const disconnect = (): Promise<RemoteHostStatus> =>\n serialize(async () => {\n stopIfRunning();\n await deps.signOut();\n log.info(\"disconnected, host runner stopped\");\n return status();\n });\n\n return { connect, reconnect, disconnect, status };\n};\n","// Firebase credential exchange for the remote-host runner.\n//\n// The host authenticates to Firestore *as the user* (Option B) using the\n// Firebase JS SDK's signInWithCredential with a browser-minted Google OAuth ID\n// token — no Admin SDK, no project service account. Security rules keep the host\n// scoped to that user's own users/{uid}/… subtree.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/auth.ts. The `auth`\n// instance is a parameter so each host binds its own Firebase init; the factory\n// returns the low-level credential primitives (the connect/disconnect lifecycle\n// that starts/stops the host runner lives in createRemoteHost).\nimport { Auth, GoogleAuthProvider, signInWithCredential, signOut } from \"firebase/auth\";\n\nexport interface RemoteHostAuth {\n // Establish the Firebase session from a browser-minted Google OAuth ID token.\n // The token is used once here; the JS SDK then holds its own refresh token for\n // the process lifetime. Resolves to the authenticated uid.\n signInHost: (idToken: string) => Promise<string>;\n // Tear down the Firebase session (in-memory persistence → re-login on restart).\n signOutHost: () => Promise<void>;\n // The currently signed-in uid, or null when disconnected.\n currentUid: () => string | null;\n}\n\nexport const createRemoteHostAuth = (auth: Auth): RemoteHostAuth => ({\n signInHost: async (idToken: string): Promise<string> => {\n const credential = GoogleAuthProvider.credential(idToken);\n const userCredential = await signInWithCredential(auth, credential);\n return userCredential.user.uid;\n },\n signOutHost: (): Promise<void> => signOut(auth),\n currentUid: (): string | null => auth.currentUser?.uid ?? null,\n});\n","// A custom Firebase Auth persistence that keeps the signed-in session in memory\n// but can be seeded from — and exported back to — an opaque blob, so a host's\n// Firebase session survives a process restart by being parked in the browser's\n// localStorage (mulmoserver#50, \"case A'\"). The blob is whatever the SDK wrote\n// into persistence, round-tripped through JSON; we NEVER interpret its fields,\n// so we don't couple to the SDK's serialized-user format across versions.\n//\n// **Persistence is a CLASS, not an instance.** `initializeAuth(app, { persistence })`\n// hands the value to the SDK's `_getInstance(cls)`, which asserts `cls instanceof\n// Function` (\"Expected a class definition\") and then `new cls()`. Passing a plain\n// object throws — the SDK's own `inMemoryPersistence` is likewise a class. The\n// class is defined per factory call so its instances share this call's store;\n// `type: \"LOCAL\"` makes the SDK treat it as durable and persist the user.\n//\n// Seed BEFORE `initializeAuth` — the SDK reads persistence once at init. `onChange`\n// fires when the SDK writes/removes a key (a token update that rotates the stored\n// blob, or a sign-out) — the signal to re-sync the browser copy.\nimport type { Persistence } from \"firebase/auth\";\n\n// The SDK stores values as JSON objects (a serialized user) or strings. We treat\n// them opaquely — a value is either.\ntype PersistenceValue = Record<string, unknown> | string;\n\ntype StorageListener = (value: PersistenceValue | null) => void;\n\n// The instance the SDK builds via `new` and then drives with these `_`-methods.\nexport interface HostAuthPersistenceInstance extends Persistence {\n type: \"LOCAL\";\n _isAvailable: () => Promise<boolean>;\n _set: (key: string, value: PersistenceValue) => Promise<void>;\n _get: (key: string) => Promise<PersistenceValue | null>;\n _remove: (key: string) => Promise<void>;\n _addListener: (key: string, listener: StorageListener) => void;\n _removeListener: (key: string, listener: StorageListener) => void;\n}\n\n// The class value passed to `initializeAuth`. The static `type` makes it\n// assignable to the SDK's `Persistence` (a class-valued-typed-as-instance, the\n// same trick the SDK uses for `inMemoryPersistence`); `new ()` lets the SDK — and\n// the tests — instantiate it.\nexport interface HostAuthPersistenceClass extends Persistence {\n type: \"LOCAL\";\n new (): HostAuthPersistenceInstance;\n}\n\nexport interface HostSessionPersistence {\n /** Pass to `initializeAuth(app, { persistence })`. It's a class the SDK `new`s. */\n persistence: HostAuthPersistenceClass;\n /** Load a previously exported blob. Call BEFORE `initializeAuth`. */\n seed: (blob: string) => void;\n /** Serialize the current contents, or `null` when empty (no session). */\n exportBlob: () => string | null;\n /** Notified with the fresh blob (or `null`) whenever the SDK writes/removes. */\n onChange: (listener: (blob: string | null) => void) => () => void;\n /** Drop all contents (used when tearing down the Firebase app). */\n clear: () => void;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isPersistenceValue = (value: unknown): value is PersistenceValue => typeof value === \"string\" || isRecord(value);\n\n// True when `blob` is a JSON object `seed` can load. A blob that fails this can\n// never restore a session (corrupt localStorage, wrong shape), so callers treat\n// it as an expired/invalid session rather than a transient error — the client\n// then drops it instead of retrying the same doomed blob forever.\nexport const isSeedableBlob = (blob: string): boolean => {\n try {\n return isRecord(JSON.parse(blob));\n } catch {\n return false;\n }\n};\n\n// A class (constructor) so the SDK's `_getInstance` accepts it (it asserts\n// `cls instanceof Function`, then `new cls()`); instances hold the shared\n// `store`/`notify`, so a fresh `new` still sees the seeded/live data. `static\n// type` is for the `Persistence` type bridge; the instance `type` is what the\n// SDK reads after `new`.\nconst makeHostPersistenceClass = (store: Map<string, PersistenceValue>, notify: () => void): HostAuthPersistenceClass => {\n class HostAuthPersistence {\n static readonly type = \"LOCAL\" as const;\n readonly type = \"LOCAL\" as const;\n private readonly store = store;\n private readonly notify = notify;\n private readonly external = new Set<StorageListener>();\n _isAvailable(): Promise<boolean> {\n return Promise.resolve(this.store instanceof Map);\n }\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.store.set(key, value);\n this.notify();\n }\n _get(key: string): Promise<PersistenceValue | null> {\n return Promise.resolve(this.store.get(key) ?? null);\n }\n async _remove(key: string): Promise<void> {\n this.store.delete(key);\n this.notify();\n }\n // Node has no cross-tab storage events to deliver, so registered listeners\n // never fire; we still track them so add/remove stay symmetric.\n _addListener(_key: string, listener: StorageListener): void {\n this.external.add(listener);\n }\n _removeListener(_key: string, listener: StorageListener): void {\n this.external.delete(listener);\n }\n }\n return HostAuthPersistence;\n};\n\nexport const createHostSessionPersistence = (): HostSessionPersistence => {\n const store = new Map<string, PersistenceValue>();\n const listeners = new Set<(blob: string | null) => void>();\n\n const exportBlob = (): string | null => (store.size === 0 ? null : JSON.stringify(Object.fromEntries(store)));\n\n const notify = (): void => {\n const blob = exportBlob();\n listeners.forEach((listener) => listener(blob));\n };\n\n const persistence = makeHostPersistenceClass(store, notify);\n\n const seed = (blob: string): void => {\n const parsed: unknown = JSON.parse(blob);\n if (!isRecord(parsed)) throw new Error(\"host session blob must be a JSON object\");\n store.clear();\n for (const [key, value] of Object.entries(parsed)) {\n if (isPersistenceValue(value)) store.set(key, value);\n }\n };\n\n const onChange = (listener: (blob: string | null) => void): (() => void) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n const clear = (): void => {\n store.clear();\n };\n\n return { persistence, seed, exportBlob, onChange, clear };\n};\n","// Firebase init for a remote-host runner.\n//\n// A host acts as a *host*: it signs in to Firebase as the user (via\n// signInWithCredential, see auth.ts) and listens to that user's command queue in\n// Firestore. The modular firebase/firestore + firebase/auth SDKs run in Node, so\n// this mirrors a browser init but also exposes Firestore (default database,\n// which must be in Native mode) and Storage.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/firebase.ts. The\n// public web config is a parameter so each host supplies its own (both hosts\n// reuse the shared mulmoserver project).\nimport { deleteApp, FirebaseApp, FirebaseOptions, initializeApp } from \"firebase/app\";\nimport { Auth, getAuth, initializeAuth } from \"firebase/auth\";\nimport { Firestore, getFirestore } from \"firebase/firestore\";\nimport { FirebaseStorage, getStorage } from \"firebase/storage\";\n\nimport { createHostSessionPersistence, type HostSessionPersistence } from \"./sessionPersistence.js\";\n\nexport interface RemoteHostFirebase {\n app: FirebaseApp;\n auth: Auth;\n firestore: Firestore;\n // Storage carries the full-res attachment bytes the command channel can't (a\n // Firestore command doc caps at ~1 MiB). The host, signed in as the user,\n // pulls each staged upload from `users/{uid}/uploads/{id}` and deletes it\n // after ingest.\n storage: FirebaseStorage;\n}\n\nexport const createRemoteHostFirebase = (config: FirebaseOptions): RemoteHostFirebase => {\n const app = initializeApp(config);\n return { app, auth: getAuth(app), firestore: getFirestore(app), storage: getStorage(app) };\n};\n\nexport interface RemoteHostSessionHandles {\n auth: Auth;\n firestore: Firestore;\n storage: FirebaseStorage;\n // The signed-in uid restored from a seed blob, or null when opened fresh\n // (before `signInHost`) or when the blob held no valid session.\n uid: string | null;\n}\n\n// A restartable Firebase session for a host, backed by the export/seed-able\n// persistence (mulmoserver#50, \"case A'\"). Because `initializeAuth` reads\n// persistence once and can run only once per app, each `open` spins up a FRESH\n// app (unique name) with the persistence seeded first, then tears down the\n// previous app — so a reconnect can restore a browser-parked session, and a\n// fresh connect starts clean. `exportSession`/`onSessionChange` expose the blob\n// the browser stores and the signal to re-sync it.\n// Runs on the freshly opened handles BEFORE the previous session is torn down.\n// Reject to keep the open non-destructive: the fresh app is rolled back and the\n// previous session is preserved (so a failed sign-in or an expired blob doesn't\n// replace a healthy live session).\nexport type RemoteHostSessionValidate = (handles: RemoteHostSessionHandles) => Promise<void>;\n\nexport interface RemoteHostSession {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => Promise<RemoteHostSessionHandles>;\n close: () => Promise<void>;\n exportSession: () => string | null;\n onSessionChange: (cb: (blob: string | null) => void) => () => void;\n}\n\nconst noop = (): void => undefined;\n\n// Run operations one-at-a-time in submission order. `open`/`close` mutate shared\n// store/app state, so overlapping calls must not interleave (they would leak an\n// app or leave `app` pointing at a torn-down instance). Mirrors the lifecycle's\n// serialization; a failed op doesn't block the next.\nconst makeSerializer = () => {\n let transition: Promise<unknown> = Promise.resolve();\n return <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n};\n\n// Build a fresh app from the (already seeded) persistence and wait for the\n// restored auth state to settle. Persistence restore is async, so `uid`\n// reflects a seeded session only after `authStateReady()` (null when the blob\n// was empty/invalid, or on a fresh connect before `signInHost`).\nconst openFreshApp = async (\n config: FirebaseOptions,\n store: HostSessionPersistence,\n name: string,\n): Promise<{ app: FirebaseApp; handles: RemoteHostSessionHandles }> => {\n // `initializeApp` registers the app in the SDK's global registry, so if init\n // then throws we must delete it — otherwise repeated reconnect failures leak\n // a registered app each time.\n const app = initializeApp(config, name);\n try {\n const auth = initializeAuth(app, { persistence: store.persistence });\n await auth.authStateReady();\n return { app, handles: { auth, firestore: getFirestore(app), storage: getStorage(app), uid: auth.currentUser?.uid ?? null } };\n } catch (error) {\n await deleteApp(app).catch(() => undefined);\n throw error;\n }\n};\n\nexport const createRemoteHostSession = (config: FirebaseOptions): RemoteHostSession => {\n const store = createHostSessionPersistence();\n let app: FirebaseApp | null = null;\n let appSeq = 0;\n const serialize = makeSerializer();\n\n const closeInner = async (): Promise<void> => {\n const previous = app;\n app = null;\n store.clear();\n if (previous) await deleteApp(previous);\n };\n\n // Run the caller's check on the fresh handles; on rejection, delete the fresh\n // app so only the caller-visible error escapes and the previous session (never\n // touched here) stays live.\n const validateOrRollback = async (nextApp: FirebaseApp, handles: RemoteHostSessionHandles, validate?: RemoteHostSessionValidate): Promise<void> => {\n if (!validate) return;\n try {\n await validate(handles);\n } catch (error) {\n await deleteApp(nextApp).catch(() => undefined);\n throw error;\n }\n };\n\n const openInner = async (seedBlob?: string, validate?: RemoteHostSessionValidate): Promise<RemoteHostSessionHandles> => {\n // Non-destructive: keep the current session intact until the fresh app is\n // proven to come up AND pass `validate` (sign-in / uid). A bad seed blob, a\n // failed init, or a rejected validation must not tear down a healthy session\n // — the reconnect contract (mulmoserver#50). So we tear the previous app\n // down only AFTER success, and roll the store back on failure.\n const previousApp = app;\n const previousBlob = store.exportBlob();\n appSeq += 1;\n try {\n store.clear();\n if (seedBlob) store.seed(seedBlob);\n const { app: nextApp, handles } = await openFreshApp(config, store, `remote-host-${appSeq}`);\n await validateOrRollback(nextApp, handles, validate);\n app = nextApp;\n if (previousApp) await deleteApp(previousApp).catch(() => undefined);\n return handles;\n } catch (error) {\n store.clear();\n if (previousBlob) store.seed(previousBlob);\n throw error;\n }\n };\n\n return {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => serialize(()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AI;GACF,MAAM,SAAS,OAAO;EACxB,SAAS,OAAO;GACd,MAAM,UAAU,OAAO,CAAC,CAAC,YAAY,KAAA,CAAS;GAC9C,MAAM;EACR;CACF;CAEA,MAAM,YAAY,OAAO,UAAmB,aAA4E;EAMtH,MAAM,cAAc;EACpB,MAAM,eAAe,MAAM,WAAW;EACtC,UAAU;EACV,IAAI;GACF,MAAM,MAAM;GACZ,IAAI,UAAU,MAAM,KAAK,QAAQ;GACjC,MAAM,EAAE,KAAK,SAAS,YAAY,MAAM,aAAa,QAAQ,OAAO,eAAe,QAAQ;GAC3F,MAAM,mBAAmB,SAAS,SAAS,QAAQ;GACnD,MAAM;GACN,IAAI,aAAa,MAAM,UAAU,WAAW,CAAC,CAAC,YAAY,KAAA,CAAS;GACnE,OAAO;EACT,SAAS,OAAO;GACd,MAAM,MAAM;GACZ,IAAI,cAAc,MAAM,KAAK,YAAY;GACzC,MAAM;EACR;CACF;CAEA,OAAO;EACL,OAAO,UAAmB,aAAyC,gBAAgB,UAAU,UAAU,QAAQ,CAAC;EAChH,aAAa,UAAU,UAAU;EACjC,eAAe,MAAM;EACrB,iBAAiB,MAAM;CACzB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/remote-host/server/hostRunner.ts","../../../src/remote-host/server/lifecycle.ts","../../../src/remote-host/server/auth.ts","../../../src/remote-host/server/sessionPersistence.ts","../../../src/remote-host/server/firebase.ts"],"sourcesContent":["// Host side of the command channel: claim queued commands, run handlers, write\n// results back, and announce presence via heartbeat.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/hostRunner.ts (itself\n// ported from ../mulmoserver). The only signature change vs. that copy: the\n// `firestore` instance is a parameter (each host supplies its own Firebase init),\n// and the heartbeat interval is an option (defaults to one minute).\nimport { DocumentReference, Firestore, deleteDoc, onSnapshot, query, runTransaction, serverTimestamp, setDoc, updateDoc, where } from \"firebase/firestore\";\n\nimport { errorMessage } from \"../../collection/core/errorMessage.js\";\nimport {\n Channel,\n Command,\n CommandHandler,\n CommandHandlers,\n JsonObject,\n buildHostPresence,\n byCreatedAt,\n commandsCollection,\n hostDoc,\n isExpired,\n} from \"../index.js\";\n\nconst DEFAULT_HEARTBEAT_MS = 60_000;\n\nexport interface HostEvent {\n phase: \"received\" | \"done\" | \"error\";\n method: string;\n message?: string;\n}\n\nexport interface HostRunnerOptions {\n onEvent?: (event: HostEvent) => void;\n // Called once when the listener dies fatally (after presence has been set\n // offline), so the lifecycle owner can reconcile its own state — e.g. clear\n // the runner handle so status() no longer reports connected. NOT called on a\n // normal stop().\n onClosed?: () => void;\n // Called when a command is dropped for being past its `expiresAt`, BEFORE the\n // doc is deleted, so the host can clean up out-of-band resources the command\n // referenced (e.g. staged attachment uploads in Storage). `uid` is THIS runner's\n // session uid (channel.uid) — passed in rather than read from a global so a\n // concurrent reconnect as a different account can't point cleanup at the wrong\n // user's Storage path. Best-effort: a throw is logged via onEvent and does NOT\n // block the doc deletion. Absent ⇒ the expired doc is simply deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n // Presence heartbeat interval; defaults to one minute.\n heartbeatMs?: number;\n}\n\ninterface Claim {\n method: string;\n params: JsonObject;\n}\n\nconst noop = () => undefined;\n\n// The remote may have deleted the doc on timeout, so ignore write-after-delete.\nconst writeError = (ref: DocumentReference, code: string, message: string) =>\n updateDoc(ref, { status: \"error\", error: { code, message }, updatedAt: serverTimestamp() }).catch(noop);\n\n// Atomically move a command queued -> processing so it is handled exactly once.\n// Returns the method/params to run, or null if another handler already took it.\nconst claimCommand = (firestore: Firestore, ref: DocumentReference): Promise<Claim | null> =>\n runTransaction(firestore, async (txn) => {\n const data = (await txn.get(ref)).data() as Command | undefined;\n if (!data || data.status !== \"queued\") {\n return null;\n }\n txn.update(ref, { status: \"processing\", updatedAt: serverTimestamp() });\n return { method: data.method, params: data.params ?? {} };\n });\n\nconst runHandler = async (ref: DocumentReference, claim: Claim, handler: CommandHandler): Promise<HostEvent> => {\n try {\n const result = await handler(claim.params);\n await updateDoc(ref, { status: \"done\", result: result ?? null, updatedAt: serverTimestamp() });\n return { phase: \"done\", method: claim.method };\n } catch (error) {\n const message = errorMessage(error);\n await writeError(ref, \"handler_error\", message);\n return { phase: \"error\", method: claim.method, message };\n }\n};\n\n// A command past its deadline is removed entirely rather than run: give the host\n// a chance to clean up out-of-band resources (staged attachments), then delete\n// the doc so it is neither reprocessed nor left as a stale error. Both steps are\n// best-effort/idempotent, so a snapshot replay surfacing the same expired doc\n// twice is harmless (no claim transaction needed — see plan edge #3).\nconst expireCommand = async (ref: DocumentReference, command: Command, options: HostRunnerOptions, uid: string) => {\n try {\n await options.onExpire?.(command, uid);\n } catch (error) {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `onExpire failed: ${errorMessage(error)}` });\n }\n // Surface a delete failure (permissions / transient network) the same way the\n // onExpire failure above is surfaced — otherwise the expired doc lingers as\n // \"queued\" with no signal as to why cleanup didn't happen.\n await deleteDoc(ref).catch((error) => {\n options.onEvent?.({ phase: \"error\", method: command.method, message: `expire delete failed: ${errorMessage(error)}` });\n });\n options.onEvent?.({ phase: \"done\", method: command.method, message: \"expired\" });\n};\n\n// Per-runner constants bundled into one context so processCommand stays under the\n// max-params cap: firestore, the handler table, options, and the session uid are\n// all fixed for the runner's lifetime; only ref/command/now vary per command.\ninterface RunnerContext {\n firestore: Firestore;\n handlers: CommandHandlers;\n options: HostRunnerOptions;\n uid: string;\n}\n\nconst processCommand = async (ctx: RunnerContext, ref: DocumentReference, command: Command, now: number) => {\n const { handlers, options } = ctx;\n // Drop an expired command before claiming it — it must never reach a handler.\n if (isExpired(command, now)) {\n await expireCommand(ref, command, options, ctx.uid);\n return;\n }\n const claim = await claimCommand(ctx.firestore, ref);\n if (!claim) {\n return;\n }\n options.onEvent?.({ phase: \"received\", method: claim.method });\n const handler: CommandHandler | undefined = handlers[claim.method];\n if (!handler) {\n await writeError(ref, \"unknown_method\", `No handler for method: ${claim.method}`);\n options.onEvent?.({ phase: \"error\", method: claim.method, message: \"unknown method\" });\n return;\n }\n options.onEvent?.(await runHandler(ref, claim, handler));\n};\n\n// startHostRunner subscribes to queued commands for the given channel and runs\n// each one through the supplied handler table. It also announces presence (a\n// heartbeat on users/{uid}/hosts/{hostId}) so the remote can tell it is online.\n// Returns a stop function that goes offline and detaches the listener.\nexport const startHostRunner = (firestore: Firestore, channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions = {}): (() => void) => {\n const presence = hostDoc(firestore, channel);\n // Advertise online/offline + the capability set (method names + protocol\n // version) on the same doc the remote already listens to for presence.\n // Returns void, not the promise: presence is advertised best-effort from\n // three call sites (announce, the snapshot-error path, the teardown), none of\n // which can await. Terminating the chain here with `.catch(noop)` keeps every\n // caller from floating a promise it has no way to handle.\n const writePresence = (online: boolean): void => {\n setDoc(presence, { ...buildHostPresence(channel, handlers, online), updatedAt: serverTimestamp() }).catch(noop);\n };\n const announce = () => {\n writePresence(true);\n };\n announce();\n const beat = setInterval(announce, options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);\n\n const queuedCommands = query(commandsCollection(firestore, channel), where(\"status\", \"==\", \"queued\"));\n const ctx: RunnerContext = { firestore, handlers, options, uid: channel.uid };\n const unsubscribe = onSnapshot(\n queuedCommands,\n (snapshot) => {\n const now = Date.now();\n // Best-effort oldest-first DISPATCH only. Commands are processed\n // concurrently (not awaited in turn) and out-of-order completion is fine by\n // design — chat is asynchronous — so this sort just biases which command\n // starts first; it is not an ordering guarantee. We still sort in memory\n // rather than orderBy(\"createdAt\") on the query because a Firestore orderBy\n // silently EXCLUDES docs missing the field — which would drop every\n // pre-offline-queue command (no createdAt) from the queue entirely.\n const added = snapshot\n .docChanges()\n .filter((change) => change.type === \"added\")\n .map((change) => ({ ref: change.doc.ref, command: change.doc.data() as Command }))\n .sort((left, right) => byCreatedAt(left.command, right.command));\n added.forEach(({ ref, command }) => {\n processCommand(ctx, ref, command, now).catch(noop);\n });\n },\n (error) => {\n options.onEvent?.({ phase: \"error\", method: \"listen\", message: error.message });\n // A Firestore onSnapshot error terminates the listener and it does not\n // recover on its own. Stop advertising presence (clear the heartbeat +\n // write online:false) so remotes see the host as offline instead of a\n // live host that silently consumes no commands.\n clearInterval(beat);\n writePresence(false);\n options.onClosed?.();\n },\n );\n\n return () => {\n clearInterval(beat);\n writePresence(false);\n unsubscribe();\n };\n};\n","// Remote-host lifecycle: wire a Firebase session to the Firestore host runner so\n// connecting starts the command loop + presence heartbeat, and disconnecting\n// stops both.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/index.ts. The factory\n// takes injected collaborators — real hosts bind them to Firebase; tests pass\n// fakes to exercise the invariants (non-destructive connect, serialized\n// transitions, status/liveness reconciliation on fatal listener death) without a\n// network. `hostId` and the logger are injected too, so this file imports no\n// Firebase and no host logger and stays trivially unit-testable.\n//\n// Single-account, single-host per instance, in-memory session: a host restart\n// drops the session and needs a re-connect.\nimport type { Channel, Command, CommandHandlers } from \"../index.js\";\nimport type { HostRunnerOptions } from \"./hostRunner.js\";\n\nexport interface RemoteHostStatus {\n connected: boolean;\n uid: string | null;\n}\n\n// Minimal logger the factory calls; each host adapts its own logger to this\n// shape (or omits it to run silently, as the tests do).\nexport interface RemoteHostLogger {\n info: (msg: string) => void;\n warn: (msg: string) => void;\n debug: (msg: string) => void;\n}\n\n// Injectable collaborators — a real host binds these to Firebase + its own\n// hostId; tests pass fakes to exercise the lifecycle without a network.\n// `startRunner` is the host's `startHostRunner` pre-bound with its Firestore\n// instance, so this module needs no Firebase of its own.\nexport interface RemoteHostDeps {\n hostId: string;\n signIn: (idToken: string) => Promise<string>;\n // Restore a session from a browser-parked blob (case A', mulmoserver#50) and\n // resolve to its uid — no popup. MUST reject when the blob yields no valid\n // session so `reconnect` stays non-destructive. Absent ⇒ `reconnect` throws.\n restore?: (sessionBlob: string) => Promise<string>;\n signOut: () => Promise<void>;\n currentUid: () => string | null;\n startRunner: (channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions) => () => void;\n handlers: CommandHandlers;\n // Optional host-specific cleanup for a command the runner drops as expired\n // (e.g. delete its staged attachment uploads). Threaded verbatim into the\n // runner's `onExpire`, which supplies the session `uid` so cleanup targets the\n // right user's Storage path even across a reconnect; absent ⇒ an expired doc is\n // just deleted.\n onExpire?: (command: Command, uid: string) => void | Promise<void>;\n log?: RemoteHostLogger;\n}\n\nexport interface RemoteHostLifecycle {\n connect: (idToken: string) => Promise<RemoteHostStatus>;\n // Restore a browser-parked session and start the runner — popup-free re-attach\n // after a host restart. Non-destructive like `connect`. Rejects if `deps.restore`\n // isn't wired, or if restore fails (blob expired/invalid → caller falls back to connect).\n reconnect: (sessionBlob: string) => Promise<RemoteHostStatus>;\n disconnect: () => Promise<RemoteHostStatus>;\n status: () => RemoteHostStatus;\n}\n\nconst noop = () => undefined;\nconst silentLogger: RemoteHostLogger = { info: noop, warn: noop, debug: noop };\n\nexport const createRemoteHost = (deps: RemoteHostDeps): RemoteHostLifecycle => {\n const log = deps.log ?? silentLogger;\n\n // The running host runner's stop() handle, or null when disconnected. Keeps\n // the single-host invariant — one runner at a time.\n let stopRunner: (() => void) | null = null;\n\n // Serialize connect/disconnect so overlapping requests can't both mutate\n // stopRunner (which would leak a second runner) or race auth against teardown.\n // Each transition runs only after the previous one settles; a failed\n // transition does not block the next (both handlers run the next op).\n let transition: Promise<unknown> = Promise.resolve();\n\n const serialize = <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n\n const stopIfRunning = () => {\n if (stopRunner) {\n stopRunner();\n stopRunner = null;\n }\n };\n\n const status = (): RemoteHostStatus => ({ connected: stopRunner !== null, uid: deps.currentUid() });\n\n // Swap the running runner for one bound to `uid`. Callers authenticate FIRST\n // (before this teardown) so a failed connect/reconnect keeps a healthy session.\n const attach = (uid: string, verb: string): RemoteHostStatus => {\n stopIfRunning();\n const runner = deps.startRunner({ uid, hostId: deps.hostId }, deps.handlers, {\n onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),\n onExpire: deps.onExpire,\n // Fatal listener death: drop the handle so status() stops reporting\n // connected — but only if it still points at THIS runner (a later\n // reconnect may have replaced it).\n onClosed: () => {\n if (stopRunner === runner) {\n stopRunner = null;\n log.warn(\"host runner listener died; marked disconnected\");\n }\n },\n });\n stopRunner = runner;\n log.info(`${verb} as ${uid}, host runner started (hostId=${deps.hostId})`);\n return status();\n };\n\n const connect = (idToken: string): Promise<RemoteHostStatus> => serialize(async () => attach(await deps.signIn(idToken), \"connected\"));\n\n const reconnect = (sessionBlob: string): Promise<RemoteHostStatus> =>\n serialize(async () => {\n const { restore } = deps;\n if (!restore) throw new Error(\"remote-host reconnect requires a `restore` dependency\");\n return attach(await restore(sessionBlob), \"reconnected\");\n });\n\n const disconnect = (): Promise<RemoteHostStatus> =>\n serialize(async () => {\n stopIfRunning();\n await deps.signOut();\n log.info(\"disconnected, host runner stopped\");\n return status();\n });\n\n return { connect, reconnect, disconnect, status };\n};\n","// Firebase credential exchange for the remote-host runner.\n//\n// The host authenticates to Firestore *as the user* (Option B) using the\n// Firebase JS SDK's signInWithCredential with a browser-minted Google OAuth ID\n// token — no Admin SDK, no project service account. Security rules keep the host\n// scoped to that user's own users/{uid}/… subtree.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/auth.ts. The `auth`\n// instance is a parameter so each host binds its own Firebase init; the factory\n// returns the low-level credential primitives (the connect/disconnect lifecycle\n// that starts/stops the host runner lives in createRemoteHost).\nimport { Auth, GoogleAuthProvider, signInWithCredential, signOut } from \"firebase/auth\";\n\nexport interface RemoteHostAuth {\n // Establish the Firebase session from a browser-minted Google OAuth ID token.\n // The token is used once here; the JS SDK then holds its own refresh token for\n // the process lifetime. Resolves to the authenticated uid.\n signInHost: (idToken: string) => Promise<string>;\n // Tear down the Firebase session (in-memory persistence → re-login on restart).\n signOutHost: () => Promise<void>;\n // The currently signed-in uid, or null when disconnected.\n currentUid: () => string | null;\n}\n\nexport const createRemoteHostAuth = (auth: Auth): RemoteHostAuth => ({\n signInHost: async (idToken: string): Promise<string> => {\n const credential = GoogleAuthProvider.credential(idToken);\n const userCredential = await signInWithCredential(auth, credential);\n return userCredential.user.uid;\n },\n signOutHost: (): Promise<void> => signOut(auth),\n currentUid: (): string | null => auth.currentUser?.uid ?? null,\n});\n","// A custom Firebase Auth persistence that keeps the signed-in session in memory\n// but can be seeded from — and exported back to — an opaque blob, so a host's\n// Firebase session survives a process restart by being parked in the browser's\n// localStorage (mulmoserver#50, \"case A'\"). The blob is whatever the SDK wrote\n// into persistence, round-tripped through JSON; we NEVER interpret its fields,\n// so we don't couple to the SDK's serialized-user format across versions.\n//\n// **Persistence is a CLASS, not an instance.** `initializeAuth(app, { persistence })`\n// hands the value to the SDK's `_getInstance(cls)`, which asserts `cls instanceof\n// Function` (\"Expected a class definition\") and then `new cls()`. Passing a plain\n// object throws — the SDK's own `inMemoryPersistence` is likewise a class. The\n// class is defined per factory call so its instances share this call's store;\n// `type: \"LOCAL\"` makes the SDK treat it as durable and persist the user.\n//\n// Seed BEFORE `initializeAuth` — the SDK reads persistence once at init. `onChange`\n// fires when the SDK writes/removes a key (a token update that rotates the stored\n// blob, or a sign-out) — the signal to re-sync the browser copy.\nimport type { Persistence } from \"firebase/auth\";\n\n// The SDK stores values as JSON objects (a serialized user) or strings. We treat\n// them opaquely — a value is either.\ntype PersistenceValue = Record<string, unknown> | string;\n\ntype StorageListener = (value: PersistenceValue | null) => void;\n\n// The instance the SDK builds via `new` and then drives with these `_`-methods.\nexport interface HostAuthPersistenceInstance extends Persistence {\n type: \"LOCAL\";\n _isAvailable: () => Promise<boolean>;\n _set: (key: string, value: PersistenceValue) => Promise<void>;\n _get: (key: string) => Promise<PersistenceValue | null>;\n _remove: (key: string) => Promise<void>;\n _addListener: (key: string, listener: StorageListener) => void;\n _removeListener: (key: string, listener: StorageListener) => void;\n}\n\n// The class value passed to `initializeAuth`. The static `type` makes it\n// assignable to the SDK's `Persistence` (a class-valued-typed-as-instance, the\n// same trick the SDK uses for `inMemoryPersistence`); `new ()` lets the SDK — and\n// the tests — instantiate it.\nexport interface HostAuthPersistenceClass extends Persistence {\n type: \"LOCAL\";\n new (): HostAuthPersistenceInstance;\n}\n\nexport interface HostSessionPersistence {\n /** Pass to `initializeAuth(app, { persistence })`. It's a class the SDK `new`s. */\n persistence: HostAuthPersistenceClass;\n /** Load a previously exported blob. Call BEFORE `initializeAuth`. */\n seed: (blob: string) => void;\n /** Serialize the current contents, or `null` when empty (no session). */\n exportBlob: () => string | null;\n /** Notified with the fresh blob (or `null`) whenever the SDK writes/removes. */\n onChange: (listener: (blob: string | null) => void) => () => void;\n /** Drop all contents (used when tearing down the Firebase app). */\n clear: () => void;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isPersistenceValue = (value: unknown): value is PersistenceValue => typeof value === \"string\" || isRecord(value);\n\n// True when `blob` is a JSON object `seed` can load. A blob that fails this can\n// never restore a session (corrupt localStorage, wrong shape), so callers treat\n// it as an expired/invalid session rather than a transient error — the client\n// then drops it instead of retrying the same doomed blob forever.\nexport const isSeedableBlob = (blob: string): boolean => {\n try {\n return isRecord(JSON.parse(blob));\n } catch {\n return false;\n }\n};\n\n// A class (constructor) so the SDK's `_getInstance` accepts it (it asserts\n// `cls instanceof Function`, then `new cls()`); instances hold the shared\n// `store`/`notify`, so a fresh `new` still sees the seeded/live data. `static\n// type` is for the `Persistence` type bridge; the instance `type` is what the\n// SDK reads after `new`.\nconst makeHostPersistenceClass = (store: Map<string, PersistenceValue>, notify: () => void): HostAuthPersistenceClass => {\n class HostAuthPersistence {\n static readonly type = \"LOCAL\" as const;\n readonly type = \"LOCAL\" as const;\n private readonly store = store;\n private readonly notify = notify;\n private readonly external = new Set<StorageListener>();\n _isAvailable(): Promise<boolean> {\n return Promise.resolve(this.store instanceof Map);\n }\n async _set(key: string, value: PersistenceValue): Promise<void> {\n this.store.set(key, value);\n this.notify();\n }\n _get(key: string): Promise<PersistenceValue | null> {\n return Promise.resolve(this.store.get(key) ?? null);\n }\n async _remove(key: string): Promise<void> {\n this.store.delete(key);\n this.notify();\n }\n // Node has no cross-tab storage events to deliver, so registered listeners\n // never fire; we still track them so add/remove stay symmetric.\n _addListener(_key: string, listener: StorageListener): void {\n this.external.add(listener);\n }\n _removeListener(_key: string, listener: StorageListener): void {\n this.external.delete(listener);\n }\n }\n return HostAuthPersistence;\n};\n\nexport const createHostSessionPersistence = (): HostSessionPersistence => {\n const store = new Map<string, PersistenceValue>();\n const listeners = new Set<(blob: string | null) => void>();\n\n const exportBlob = (): string | null => (store.size === 0 ? null : JSON.stringify(Object.fromEntries(store)));\n\n const notify = (): void => {\n const blob = exportBlob();\n listeners.forEach((listener) => listener(blob));\n };\n\n const persistence = makeHostPersistenceClass(store, notify);\n\n const seed = (blob: string): void => {\n const parsed: unknown = JSON.parse(blob);\n if (!isRecord(parsed)) throw new Error(\"host session blob must be a JSON object\");\n store.clear();\n for (const [key, value] of Object.entries(parsed)) {\n if (isPersistenceValue(value)) store.set(key, value);\n }\n };\n\n const onChange = (listener: (blob: string | null) => void): (() => void) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n const clear = (): void => {\n store.clear();\n };\n\n return { persistence, seed, exportBlob, onChange, clear };\n};\n","// Firebase init for a remote-host runner.\n//\n// A host acts as a *host*: it signs in to Firebase as the user (via\n// signInWithCredential, see auth.ts) and listens to that user's command queue in\n// Firestore. The modular firebase/firestore + firebase/auth SDKs run in Node, so\n// this mirrors a browser init but also exposes Firestore (default database,\n// which must be in Native mode) and Storage.\n//\n// Extracted into core from MulmoClaude's server/remoteHost/firebase.ts. The\n// public web config is a parameter so each host supplies its own (both hosts\n// reuse the shared mulmoserver project).\nimport { deleteApp, FirebaseApp, FirebaseOptions, initializeApp } from \"firebase/app\";\nimport { Auth, getAuth, initializeAuth } from \"firebase/auth\";\nimport { Firestore, getFirestore } from \"firebase/firestore\";\nimport { FirebaseStorage, getStorage } from \"firebase/storage\";\n\nimport { createHostSessionPersistence, type HostSessionPersistence } from \"./sessionPersistence.js\";\n\nexport interface RemoteHostFirebase {\n app: FirebaseApp;\n auth: Auth;\n firestore: Firestore;\n // Storage carries the full-res attachment bytes the command channel can't (a\n // Firestore command doc caps at ~1 MiB). The host, signed in as the user,\n // pulls each staged upload from `users/{uid}/uploads/{id}` and deletes it\n // after ingest.\n storage: FirebaseStorage;\n}\n\nexport const createRemoteHostFirebase = (config: FirebaseOptions): RemoteHostFirebase => {\n const app = initializeApp(config);\n return { app, auth: getAuth(app), firestore: getFirestore(app), storage: getStorage(app) };\n};\n\nexport interface RemoteHostSessionHandles {\n auth: Auth;\n firestore: Firestore;\n storage: FirebaseStorage;\n // The signed-in uid restored from a seed blob, or null when opened fresh\n // (before `signInHost`) or when the blob held no valid session.\n uid: string | null;\n}\n\n// A restartable Firebase session for a host, backed by the export/seed-able\n// persistence (mulmoserver#50, \"case A'\"). Because `initializeAuth` reads\n// persistence once and can run only once per app, each `open` spins up a FRESH\n// app (unique name) with the persistence seeded first, then tears down the\n// previous app — so a reconnect can restore a browser-parked session, and a\n// fresh connect starts clean. `exportSession`/`onSessionChange` expose the blob\n// the browser stores and the signal to re-sync it.\n// Runs on the freshly opened handles BEFORE the previous session is torn down.\n// Reject to keep the open non-destructive: the fresh app is rolled back and the\n// previous session is preserved (so a failed sign-in or an expired blob doesn't\n// replace a healthy live session).\nexport type RemoteHostSessionValidate = (handles: RemoteHostSessionHandles) => Promise<void>;\n\nexport interface RemoteHostSession {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => Promise<RemoteHostSessionHandles>;\n close: () => Promise<void>;\n exportSession: () => string | null;\n onSessionChange: (cb: (blob: string | null) => void) => () => void;\n}\n\nconst noop = (): void => undefined;\n\n// Run operations one-at-a-time in submission order. `open`/`close` mutate shared\n// store/app state, so overlapping calls must not interleave (they would leak an\n// app or leave `app` pointing at a torn-down instance). Mirrors the lifecycle's\n// serialization; a failed op doesn't block the next.\nconst makeSerializer = () => {\n let transition: Promise<unknown> = Promise.resolve();\n return <T>(operation: () => Promise<T>): Promise<T> => {\n const next = transition.then(operation, operation);\n transition = next.then(noop, noop);\n return next;\n };\n};\n\n// Build a fresh app from the (already seeded) persistence and wait for the\n// restored auth state to settle. Persistence restore is async, so `uid`\n// reflects a seeded session only after `authStateReady()` (null when the blob\n// was empty/invalid, or on a fresh connect before `signInHost`).\nconst openFreshApp = async (\n config: FirebaseOptions,\n store: HostSessionPersistence,\n name: string,\n): Promise<{ app: FirebaseApp; handles: RemoteHostSessionHandles }> => {\n // `initializeApp` registers the app in the SDK's global registry, so if init\n // then throws we must delete it — otherwise repeated reconnect failures leak\n // a registered app each time.\n const app = initializeApp(config, name);\n try {\n const auth = initializeAuth(app, { persistence: store.persistence });\n await auth.authStateReady();\n return { app, handles: { auth, firestore: getFirestore(app), storage: getStorage(app), uid: auth.currentUser?.uid ?? null } };\n } catch (error) {\n await deleteApp(app).catch(() => undefined);\n throw error;\n }\n};\n\nexport const createRemoteHostSession = (config: FirebaseOptions): RemoteHostSession => {\n const store = createHostSessionPersistence();\n let app: FirebaseApp | null = null;\n let appSeq = 0;\n const serialize = makeSerializer();\n\n const closeInner = async (): Promise<void> => {\n const previous = app;\n app = null;\n store.clear();\n if (previous) await deleteApp(previous);\n };\n\n // Run the caller's check on the fresh handles; on rejection, delete the fresh\n // app so only the caller-visible error escapes and the previous session (never\n // touched here) stays live.\n const validateOrRollback = async (nextApp: FirebaseApp, handles: RemoteHostSessionHandles, validate?: RemoteHostSessionValidate): Promise<void> => {\n if (!validate) return;\n try {\n await validate(handles);\n } catch (error) {\n await deleteApp(nextApp).catch(() => undefined);\n throw error;\n }\n };\n\n const openInner = async (seedBlob?: string, validate?: RemoteHostSessionValidate): Promise<RemoteHostSessionHandles> => {\n // Non-destructive: keep the current session intact until the fresh app is\n // proven to come up AND pass `validate` (sign-in / uid). A bad seed blob, a\n // failed init, or a rejected validation must not tear down a healthy session\n // — the reconnect contract (mulmoserver#50). So we tear the previous app\n // down only AFTER success, and roll the store back on failure.\n const previousApp = app;\n const previousBlob = store.exportBlob();\n appSeq += 1;\n try {\n store.clear();\n if (seedBlob) store.seed(seedBlob);\n const { app: nextApp, handles } = await openFreshApp(config, store, `remote-host-${appSeq}`);\n await validateOrRollback(nextApp, handles, validate);\n app = nextApp;\n if (previousApp) await deleteApp(previousApp).catch(() => undefined);\n return handles;\n } catch (error) {\n store.clear();\n if (previousBlob) store.seed(previousBlob);\n throw error;\n }\n };\n\n return {\n open: (seedBlob?: string, validate?: RemoteHostSessionValidate) => serialize(() => openInner(seedBlob, validate)),\n close: () => serialize(closeInner),\n exportSession: store.exportBlob,\n onSessionChange: store.onChange,\n };\n};\n"],"mappings":";;;;;;;AAuBA,IAAM,uBAAuB;AAgC7B,IAAM,eAAa,KAAA;AAGnB,IAAM,cAAc,KAAwB,MAAc,YACxD,UAAU,KAAK;CAAE,QAAQ;CAAS,OAAO;EAAE;EAAM;CAAQ;CAAG,WAAW,gBAAgB;AAAE,CAAC,CAAC,CAAC,MAAM,MAAI;AAIxG,IAAM,gBAAgB,WAAsB,QAC1C,eAAe,WAAW,OAAO,QAAQ;CACvC,MAAM,QAAQ,MAAM,IAAI,IAAI,GAAG,EAAA,CAAG,KAAK;CACvC,IAAI,CAAC,QAAQ,KAAK,WAAW,UAC3B,OAAO;CAET,IAAI,OAAO,KAAK;EAAE,QAAQ;EAAc,WAAW,gBAAgB;CAAE,CAAC;CACtE,OAAO;EAAE,QAAQ,KAAK;EAAQ,QAAQ,KAAK,UAAU,CAAC;CAAE;AAC1D,CAAC;AAEH,IAAM,aAAa,OAAO,KAAwB,OAAc,YAAgD;CAC9G,IAAI;EAEF,MAAM,UAAU,KAAK;GAAE,QAAQ;GAAQ,QAAQ,MAD1B,QAAQ,MAAM,MAAM,KACgB;GAAM,WAAW,gBAAgB;EAAE,CAAC;EAC7F,OAAO;GAAE,OAAO;GAAQ,QAAQ,MAAM;EAAO;CAC/C,SAAS,OAAO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GAAG,CAAC,CAAC,YAAY,KAAA,CAAS;EAC1C,MAAM;CACR;AACF;AAEA,IAAa,2BAA2B,WAA+C;CACrF,MAAM,QAAQ,6BAA6B;CAC3C,IAAI,MAA0B;CAC9B,IAAI,SAAS;CACb,MAAM,YAAY,eAAe;CAEjC,MAAM,aAAa,YAA2B;EAC5C,MAAM,WAAW;EACjB,MAAM;EACN,MAAM,MAAM;EACZ,IAAI,UAAU,MAAM,UAAU,QAAQ;CACxC;CAKA,MAAM,qBAAqB,OAAO,SAAsB,SAAmC,aAAwD;EACjJ,IAAI,CAAC,UAAU;EACf,IAAI;GACF,MAAM,SAAS,OAAO;EACxB,SAAS,OAAO;GACd,MAAM,UAAU,OAAO,CAAC,CAAC,YAAY,KAAA,CAAS;GAC9C,MAAM;EACR;CACF;CAEA,MAAM,YAAY,OAAO,UAAmB,aAA4E;EAMtH,MAAM,cAAc;EACpB,MAAM,eAAe,MAAM,WAAW;EACtC,UAAU;EACV,IAAI;GACF,MAAM,MAAM;GACZ,IAAI,UAAU,MAAM,KAAK,QAAQ;GACjC,MAAM,EAAE,KAAK,SAAS,YAAY,MAAM,aAAa,QAAQ,OAAO,eAAe,QAAQ;GAC3F,MAAM,mBAAmB,SAAS,SAAS,QAAQ;GACnD,MAAM;GACN,IAAI,aAAa,MAAM,UAAU,WAAW,CAAC,CAAC,YAAY,KAAA,CAAS;GACnE,OAAO;EACT,SAAS,OAAO;GACd,MAAM,MAAM;GACZ,IAAI,cAAc,MAAM,KAAK,YAAY;GACzC,MAAM;EACR;CACF;CAEA,OAAO;EACL,OAAO,UAAmB,aAAyC,gBAAgB,UAAU,UAAU,QAAQ,CAAC;EAChH,aAAa,UAAU,UAAU;EACjC,eAAe,MAAM;EACrB,iBAAiB,MAAM;CACzB;AACF"}
|
package/dist/scheduler/index.cjs
CHANGED
|
@@ -154,7 +154,9 @@ function createTaskManager(options) {
|
|
|
154
154
|
},
|
|
155
155
|
start() {
|
|
156
156
|
if (timer) return;
|
|
157
|
-
timer = setInterval(
|
|
157
|
+
timer = setInterval(() => {
|
|
158
|
+
onTick().catch((err) => log.error("tick failed", { error: String(err) }));
|
|
159
|
+
}, tickMs);
|
|
158
160
|
log.info("started", { tickMs });
|
|
159
161
|
},
|
|
160
162
|
stop() {
|