@mulmoclaude/core 0.8.2 → 0.10.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.
@@ -0,0 +1,13 @@
1
+ import { Firestore } from 'firebase/firestore';
2
+ import { Channel, CommandHandlers } from '../index.js';
3
+ export interface HostEvent {
4
+ phase: "received" | "done" | "error";
5
+ method: string;
6
+ message?: string;
7
+ }
8
+ export interface HostRunnerOptions {
9
+ onEvent?: (event: HostEvent) => void;
10
+ onClosed?: () => void;
11
+ heartbeatMs?: number;
12
+ }
13
+ export declare const startHostRunner: (firestore: Firestore, channel: Channel, handlers: CommandHandlers, options?: HostRunnerOptions) => (() => void);
@@ -0,0 +1,189 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_errorMessage = require("../../errorMessage--LvXe_Jx.cjs");
3
+ const require_remote_host_index = require("../index.cjs");
4
+ let firebase_firestore = require("firebase/firestore");
5
+ let firebase_auth = require("firebase/auth");
6
+ let firebase_app = require("firebase/app");
7
+ let firebase_storage = require("firebase/storage");
8
+ //#region src/remote-host/server/hostRunner.ts
9
+ var DEFAULT_HEARTBEAT_MS = 6e4;
10
+ var noop$1 = () => void 0;
11
+ var writeError = (ref, code, message) => (0, firebase_firestore.updateDoc)(ref, {
12
+ status: "error",
13
+ error: {
14
+ code,
15
+ message
16
+ },
17
+ updatedAt: (0, firebase_firestore.serverTimestamp)()
18
+ }).catch(noop$1);
19
+ var claimCommand = (firestore, ref) => (0, firebase_firestore.runTransaction)(firestore, async (txn) => {
20
+ const data = (await txn.get(ref)).data();
21
+ if (!data || data.status !== "queued") return null;
22
+ txn.update(ref, {
23
+ status: "processing",
24
+ updatedAt: (0, firebase_firestore.serverTimestamp)()
25
+ });
26
+ return {
27
+ method: data.method,
28
+ params: data.params ?? {}
29
+ };
30
+ });
31
+ var runHandler = async (ref, claim, handler) => {
32
+ try {
33
+ await (0, firebase_firestore.updateDoc)(ref, {
34
+ status: "done",
35
+ result: await handler(claim.params) ?? null,
36
+ updatedAt: (0, firebase_firestore.serverTimestamp)()
37
+ });
38
+ return {
39
+ phase: "done",
40
+ method: claim.method
41
+ };
42
+ } catch (error) {
43
+ const message = require_errorMessage.errorMessage(error);
44
+ await writeError(ref, "handler_error", message);
45
+ return {
46
+ phase: "error",
47
+ method: claim.method,
48
+ message
49
+ };
50
+ }
51
+ };
52
+ var processCommand = async (firestore, ref, handlers, onEvent) => {
53
+ const claim = await claimCommand(firestore, ref);
54
+ if (!claim) return;
55
+ onEvent?.({
56
+ phase: "received",
57
+ method: claim.method
58
+ });
59
+ const handler = handlers[claim.method];
60
+ if (!handler) {
61
+ await writeError(ref, "unknown_method", `No handler for method: ${claim.method}`);
62
+ onEvent?.({
63
+ phase: "error",
64
+ method: claim.method,
65
+ message: "unknown method"
66
+ });
67
+ return;
68
+ }
69
+ onEvent?.(await runHandler(ref, claim, handler));
70
+ };
71
+ var startHostRunner = (firestore, channel, handlers, options = {}) => {
72
+ const presence = require_remote_host_index.hostDoc(firestore, channel);
73
+ const writePresence = (online) => (0, firebase_firestore.setDoc)(presence, {
74
+ ...require_remote_host_index.buildHostPresence(channel, handlers, online),
75
+ updatedAt: (0, firebase_firestore.serverTimestamp)()
76
+ }).catch(noop$1);
77
+ const announce = () => {
78
+ writePresence(true);
79
+ };
80
+ announce();
81
+ const beat = setInterval(announce, options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
82
+ const unsubscribe = (0, firebase_firestore.onSnapshot)((0, firebase_firestore.query)(require_remote_host_index.commandsCollection(firestore, channel), (0, firebase_firestore.where)("status", "==", "queued")), (snapshot) => {
83
+ snapshot.docChanges().forEach((change) => {
84
+ if (change.type === "added") processCommand(firestore, change.doc.ref, handlers, options.onEvent).catch(noop$1);
85
+ });
86
+ }, (error) => {
87
+ options.onEvent?.({
88
+ phase: "error",
89
+ method: "listen",
90
+ message: error.message
91
+ });
92
+ clearInterval(beat);
93
+ writePresence(false);
94
+ options.onClosed?.();
95
+ });
96
+ return () => {
97
+ clearInterval(beat);
98
+ writePresence(false);
99
+ unsubscribe();
100
+ };
101
+ };
102
+ //#endregion
103
+ //#region src/remote-host/server/lifecycle.ts
104
+ var noop = () => void 0;
105
+ var silentLogger = {
106
+ info: noop,
107
+ warn: noop,
108
+ debug: noop
109
+ };
110
+ var createRemoteHost = (deps) => {
111
+ const log = deps.log ?? silentLogger;
112
+ let stopRunner = null;
113
+ let transition = Promise.resolve();
114
+ const serialize = (operation) => {
115
+ const next = transition.then(operation, operation);
116
+ transition = next.then(noop, noop);
117
+ return next;
118
+ };
119
+ const stopIfRunning = () => {
120
+ if (stopRunner) {
121
+ stopRunner();
122
+ stopRunner = null;
123
+ }
124
+ };
125
+ const status = () => ({
126
+ connected: stopRunner !== null,
127
+ uid: deps.currentUid()
128
+ });
129
+ const startRunner = (uid) => {
130
+ const runner = deps.startRunner({
131
+ uid,
132
+ hostId: deps.hostId
133
+ }, deps.handlers, {
134
+ onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),
135
+ onClosed: () => {
136
+ if (stopRunner === runner) {
137
+ stopRunner = null;
138
+ log.warn("host runner listener died; marked disconnected");
139
+ }
140
+ }
141
+ });
142
+ return runner;
143
+ };
144
+ const connect = (idToken) => serialize(async () => {
145
+ const uid = await deps.signIn(idToken);
146
+ stopIfRunning();
147
+ stopRunner = startRunner(uid);
148
+ log.info(`connected as ${uid}, host runner started (hostId=${deps.hostId})`);
149
+ return status();
150
+ });
151
+ const disconnect = () => serialize(async () => {
152
+ stopIfRunning();
153
+ await deps.signOut();
154
+ log.info("disconnected, host runner stopped");
155
+ return status();
156
+ });
157
+ return {
158
+ connect,
159
+ disconnect,
160
+ status
161
+ };
162
+ };
163
+ //#endregion
164
+ //#region src/remote-host/server/auth.ts
165
+ var createRemoteHostAuth = (auth) => ({
166
+ signInHost: async (idToken) => {
167
+ return (await (0, firebase_auth.signInWithCredential)(auth, firebase_auth.GoogleAuthProvider.credential(idToken))).user.uid;
168
+ },
169
+ signOutHost: () => (0, firebase_auth.signOut)(auth),
170
+ currentUid: () => auth.currentUser?.uid ?? null
171
+ });
172
+ //#endregion
173
+ //#region src/remote-host/server/firebase.ts
174
+ var createRemoteHostFirebase = (config) => {
175
+ const app = (0, firebase_app.initializeApp)(config);
176
+ return {
177
+ app,
178
+ auth: (0, firebase_auth.getAuth)(app),
179
+ firestore: (0, firebase_firestore.getFirestore)(app),
180
+ storage: (0, firebase_storage.getStorage)(app)
181
+ };
182
+ };
183
+ //#endregion
184
+ exports.createRemoteHost = createRemoteHost;
185
+ exports.createRemoteHostAuth = createRemoteHostAuth;
186
+ exports.createRemoteHostFirebase = createRemoteHostFirebase;
187
+ exports.startHostRunner = startHostRunner;
188
+
189
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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/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, onSnapshot, query, runTransaction, serverTimestamp, setDoc, updateDoc, where } from \"firebase/firestore\";\n\nimport { errorMessage } from \"../../collection/core/errorMessage.js\";\nimport { Channel, Command, CommandHandler, CommandHandlers, JsonObject, buildHostPresence, commandsCollection, hostDoc } 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 // 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\nconst processCommand = async (firestore: Firestore, ref: DocumentReference, handlers: CommandHandlers, onEvent?: HostRunnerOptions[\"onEvent\"]) => {\n const claim = await claimCommand(firestore, ref);\n if (!claim) {\n return;\n }\n 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 onEvent?.({ phase: \"error\", method: claim.method, message: \"unknown method\" });\n return;\n }\n 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 unsubscribe = onSnapshot(\n queuedCommands,\n (snapshot) => {\n snapshot.docChanges().forEach((change) => {\n if (change.type === \"added\") {\n processCommand(firestore, change.doc.ref, handlers, options.onEvent).catch(noop);\n }\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, 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 signOut: () => Promise<void>;\n currentUid: () => string | null;\n startRunner: (channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions) => () => void;\n handlers: CommandHandlers;\n log?: RemoteHostLogger;\n}\n\nexport interface RemoteHostLifecycle {\n connect: (idToken: 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 const startRunner = (uid: string) => {\n const runner = deps.startRunner({ uid, hostId: deps.hostId }, deps.handlers, {\n onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),\n // The listener died fatally (heartbeat already stopped + offline written);\n // clear the handle so status() stops reporting connected — but only if it\n // still points at THIS runner (a later 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 return runner;\n };\n\n const connect = (idToken: string): Promise<RemoteHostStatus> =>\n serialize(async () => {\n // Authenticate BEFORE any teardown, so a failed connect (expired/rejected\n // token) leaves an existing healthy session untouched instead of dropping it.\n const uid = await deps.signIn(idToken);\n stopIfRunning();\n stopRunner = startRunner(uid);\n log.info(`connected as ${uid}, host runner started (hostId=${deps.hostId})`);\n return status();\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, 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","// 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 { FirebaseApp, FirebaseOptions, initializeApp } from \"firebase/app\";\nimport { Auth, getAuth } from \"firebase/auth\";\nimport { Firestore, getFirestore } from \"firebase/firestore\";\nimport { FirebaseStorage, getStorage } from \"firebase/storage\";\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"],"mappings":";;;;;;;;AAYA,IAAM,uBAAuB;AAwB7B,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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 export { startHostRunner } from './hostRunner.js';
2
+ export type { HostEvent, HostRunnerOptions } from './hostRunner.js';
3
+ export { createRemoteHost } from './lifecycle.js';
4
+ export type { RemoteHostStatus, RemoteHostLogger, RemoteHostDeps, RemoteHostLifecycle } from './lifecycle.js';
5
+ export { createRemoteHostAuth } from './auth.js';
6
+ export type { RemoteHostAuth } from './auth.js';
7
+ export { createRemoteHostFirebase } from './firebase.js';
8
+ export type { RemoteHostFirebase } from './firebase.js';
@@ -0,0 +1,185 @@
1
+ import { t as errorMessage } from "../../errorMessage-DIdhheHk.js";
2
+ import { buildHostPresence, commandsCollection, hostDoc } from "../index.js";
3
+ import { getFirestore, onSnapshot, query, runTransaction, serverTimestamp, setDoc, updateDoc, where } from "firebase/firestore";
4
+ import { GoogleAuthProvider, getAuth, signInWithCredential, signOut } from "firebase/auth";
5
+ import { initializeApp } from "firebase/app";
6
+ import { getStorage } from "firebase/storage";
7
+ //#region src/remote-host/server/hostRunner.ts
8
+ var DEFAULT_HEARTBEAT_MS = 6e4;
9
+ var noop$1 = () => void 0;
10
+ var writeError = (ref, code, message) => updateDoc(ref, {
11
+ status: "error",
12
+ error: {
13
+ code,
14
+ message
15
+ },
16
+ updatedAt: serverTimestamp()
17
+ }).catch(noop$1);
18
+ var claimCommand = (firestore, ref) => runTransaction(firestore, async (txn) => {
19
+ const data = (await txn.get(ref)).data();
20
+ if (!data || data.status !== "queued") return null;
21
+ txn.update(ref, {
22
+ status: "processing",
23
+ updatedAt: serverTimestamp()
24
+ });
25
+ return {
26
+ method: data.method,
27
+ params: data.params ?? {}
28
+ };
29
+ });
30
+ var runHandler = async (ref, claim, handler) => {
31
+ try {
32
+ await updateDoc(ref, {
33
+ status: "done",
34
+ result: await handler(claim.params) ?? null,
35
+ updatedAt: serverTimestamp()
36
+ });
37
+ return {
38
+ phase: "done",
39
+ method: claim.method
40
+ };
41
+ } catch (error) {
42
+ const message = errorMessage(error);
43
+ await writeError(ref, "handler_error", message);
44
+ return {
45
+ phase: "error",
46
+ method: claim.method,
47
+ message
48
+ };
49
+ }
50
+ };
51
+ var processCommand = async (firestore, ref, handlers, onEvent) => {
52
+ const claim = await claimCommand(firestore, ref);
53
+ if (!claim) return;
54
+ onEvent?.({
55
+ phase: "received",
56
+ method: claim.method
57
+ });
58
+ const handler = handlers[claim.method];
59
+ if (!handler) {
60
+ await writeError(ref, "unknown_method", `No handler for method: ${claim.method}`);
61
+ onEvent?.({
62
+ phase: "error",
63
+ method: claim.method,
64
+ message: "unknown method"
65
+ });
66
+ return;
67
+ }
68
+ onEvent?.(await runHandler(ref, claim, handler));
69
+ };
70
+ var startHostRunner = (firestore, channel, handlers, options = {}) => {
71
+ const presence = hostDoc(firestore, channel);
72
+ const writePresence = (online) => setDoc(presence, {
73
+ ...buildHostPresence(channel, handlers, online),
74
+ updatedAt: serverTimestamp()
75
+ }).catch(noop$1);
76
+ const announce = () => {
77
+ writePresence(true);
78
+ };
79
+ announce();
80
+ const beat = setInterval(announce, options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
81
+ const unsubscribe = onSnapshot(query(commandsCollection(firestore, channel), where("status", "==", "queued")), (snapshot) => {
82
+ snapshot.docChanges().forEach((change) => {
83
+ if (change.type === "added") processCommand(firestore, change.doc.ref, handlers, options.onEvent).catch(noop$1);
84
+ });
85
+ }, (error) => {
86
+ options.onEvent?.({
87
+ phase: "error",
88
+ method: "listen",
89
+ message: error.message
90
+ });
91
+ clearInterval(beat);
92
+ writePresence(false);
93
+ options.onClosed?.();
94
+ });
95
+ return () => {
96
+ clearInterval(beat);
97
+ writePresence(false);
98
+ unsubscribe();
99
+ };
100
+ };
101
+ //#endregion
102
+ //#region src/remote-host/server/lifecycle.ts
103
+ var noop = () => void 0;
104
+ var silentLogger = {
105
+ info: noop,
106
+ warn: noop,
107
+ debug: noop
108
+ };
109
+ var createRemoteHost = (deps) => {
110
+ const log = deps.log ?? silentLogger;
111
+ let stopRunner = null;
112
+ let transition = Promise.resolve();
113
+ const serialize = (operation) => {
114
+ const next = transition.then(operation, operation);
115
+ transition = next.then(noop, noop);
116
+ return next;
117
+ };
118
+ const stopIfRunning = () => {
119
+ if (stopRunner) {
120
+ stopRunner();
121
+ stopRunner = null;
122
+ }
123
+ };
124
+ const status = () => ({
125
+ connected: stopRunner !== null,
126
+ uid: deps.currentUid()
127
+ });
128
+ const startRunner = (uid) => {
129
+ const runner = deps.startRunner({
130
+ uid,
131
+ hostId: deps.hostId
132
+ }, deps.handlers, {
133
+ onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),
134
+ onClosed: () => {
135
+ if (stopRunner === runner) {
136
+ stopRunner = null;
137
+ log.warn("host runner listener died; marked disconnected");
138
+ }
139
+ }
140
+ });
141
+ return runner;
142
+ };
143
+ const connect = (idToken) => serialize(async () => {
144
+ const uid = await deps.signIn(idToken);
145
+ stopIfRunning();
146
+ stopRunner = startRunner(uid);
147
+ log.info(`connected as ${uid}, host runner started (hostId=${deps.hostId})`);
148
+ return status();
149
+ });
150
+ const disconnect = () => serialize(async () => {
151
+ stopIfRunning();
152
+ await deps.signOut();
153
+ log.info("disconnected, host runner stopped");
154
+ return status();
155
+ });
156
+ return {
157
+ connect,
158
+ disconnect,
159
+ status
160
+ };
161
+ };
162
+ //#endregion
163
+ //#region src/remote-host/server/auth.ts
164
+ var createRemoteHostAuth = (auth) => ({
165
+ signInHost: async (idToken) => {
166
+ return (await signInWithCredential(auth, GoogleAuthProvider.credential(idToken))).user.uid;
167
+ },
168
+ signOutHost: () => signOut(auth),
169
+ currentUid: () => auth.currentUser?.uid ?? null
170
+ });
171
+ //#endregion
172
+ //#region src/remote-host/server/firebase.ts
173
+ var createRemoteHostFirebase = (config) => {
174
+ const app = initializeApp(config);
175
+ return {
176
+ app,
177
+ auth: getAuth(app),
178
+ firestore: getFirestore(app),
179
+ storage: getStorage(app)
180
+ };
181
+ };
182
+ //#endregion
183
+ export { createRemoteHost, createRemoteHostAuth, createRemoteHostFirebase, startHostRunner };
184
+
185
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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/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, onSnapshot, query, runTransaction, serverTimestamp, setDoc, updateDoc, where } from \"firebase/firestore\";\n\nimport { errorMessage } from \"../../collection/core/errorMessage.js\";\nimport { Channel, Command, CommandHandler, CommandHandlers, JsonObject, buildHostPresence, commandsCollection, hostDoc } 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 // 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\nconst processCommand = async (firestore: Firestore, ref: DocumentReference, handlers: CommandHandlers, onEvent?: HostRunnerOptions[\"onEvent\"]) => {\n const claim = await claimCommand(firestore, ref);\n if (!claim) {\n return;\n }\n 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 onEvent?.({ phase: \"error\", method: claim.method, message: \"unknown method\" });\n return;\n }\n 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 unsubscribe = onSnapshot(\n queuedCommands,\n (snapshot) => {\n snapshot.docChanges().forEach((change) => {\n if (change.type === \"added\") {\n processCommand(firestore, change.doc.ref, handlers, options.onEvent).catch(noop);\n }\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, 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 signOut: () => Promise<void>;\n currentUid: () => string | null;\n startRunner: (channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions) => () => void;\n handlers: CommandHandlers;\n log?: RemoteHostLogger;\n}\n\nexport interface RemoteHostLifecycle {\n connect: (idToken: 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 const startRunner = (uid: string) => {\n const runner = deps.startRunner({ uid, hostId: deps.hostId }, deps.handlers, {\n onEvent: (event) => log.debug(`host event: ${event.phase} ${event.method}`),\n // The listener died fatally (heartbeat already stopped + offline written);\n // clear the handle so status() stops reporting connected — but only if it\n // still points at THIS runner (a later 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 return runner;\n };\n\n const connect = (idToken: string): Promise<RemoteHostStatus> =>\n serialize(async () => {\n // Authenticate BEFORE any teardown, so a failed connect (expired/rejected\n // token) leaves an existing healthy session untouched instead of dropping it.\n const uid = await deps.signIn(idToken);\n stopIfRunning();\n stopRunner = startRunner(uid);\n log.info(`connected as ${uid}, host runner started (hostId=${deps.hostId})`);\n return status();\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, 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","// 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 { FirebaseApp, FirebaseOptions, initializeApp } from \"firebase/app\";\nimport { Auth, getAuth } from \"firebase/auth\";\nimport { Firestore, getFirestore } from \"firebase/firestore\";\nimport { FirebaseStorage, getStorage } from \"firebase/storage\";\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"],"mappings":";;;;;;;AAYA,IAAM,uBAAuB;AAwB7B,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;EACd,MAAM,UAAU,aAAa,KAAK;EAClC,MAAM,WAAW,KAAK,iBAA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AC5FA,IAAa,wBAAwB,UAAgC;CACnE,YAAY,OAAO,YAAqC;EAGtD,QAAO,MADsB,qBAAqB,MAD/B,mBAAmB,WAAW,OACO,CAAU,EAAA,CAC5C,KAAK;CAC7B;CACA,mBAAkC,QAAQ,IAAI;CAC9C,kBAAiC,KAAK,aAAa,OAAO;AAC5D;;;ACLA,IAAa,4BAA4B,WAAgD;CACvF,MAAM,MAAM,cAAc,MAAM;CAChC,OAAO;EAAE;EAAK,MAAM,QAAQ,GAAG;EAAG,WAAW,aAAa,GAAG;EAAG,SAAS,WAAW,GAAG;CAAE;AAC3F"}
@@ -0,0 +1,26 @@
1
+ import { Channel, CommandHandlers } from '../index.js';
2
+ import { HostRunnerOptions } from './hostRunner.js';
3
+ export interface RemoteHostStatus {
4
+ connected: boolean;
5
+ uid: string | null;
6
+ }
7
+ export interface RemoteHostLogger {
8
+ info: (msg: string) => void;
9
+ warn: (msg: string) => void;
10
+ debug: (msg: string) => void;
11
+ }
12
+ export interface RemoteHostDeps {
13
+ hostId: string;
14
+ signIn: (idToken: string) => Promise<string>;
15
+ signOut: () => Promise<void>;
16
+ currentUid: () => string | null;
17
+ startRunner: (channel: Channel, handlers: CommandHandlers, options: HostRunnerOptions) => () => void;
18
+ handlers: CommandHandlers;
19
+ log?: RemoteHostLogger;
20
+ }
21
+ export interface RemoteHostLifecycle {
22
+ connect: (idToken: string) => Promise<RemoteHostStatus>;
23
+ disconnect: () => Promise<RemoteHostStatus>;
24
+ status: () => RemoteHostStatus;
25
+ }
26
+ export declare const createRemoteHost: (deps: RemoteHostDeps) => RemoteHostLifecycle;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mulmoclaude/core",
3
- "version": "0.8.2",
4
- "description": "Shared server-side core for MulmoClaude and MulmoTerminal — the always-shipped-together subsystems consolidated behind subpath exports so the two hosts can't drift. Server-only except the browser-safe ./whisper/client, ./workspace-setup/slug, ./translation/client and ./remote-view entries. All host specifics are injected.",
3
+ "version": "0.10.0",
4
+ "description": "Shared server-side core for MulmoClaude and MulmoTerminal — the always-shipped-together subsystems consolidated behind subpath exports so the two hosts can't drift. Server-only except the browser-safe ./whisper/client, ./workspace-setup/slug, ./translation/client, ./remote-view and ./remote-host entries. All host specifics are injected.",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./collection": {
@@ -118,6 +118,18 @@
118
118
  "require": "./dist/remote-view/index.cjs",
119
119
  "default": "./dist/remote-view/index.js"
120
120
  },
121
+ "./remote-host": {
122
+ "types": "./dist/remote-host/index.d.ts",
123
+ "import": "./dist/remote-host/index.js",
124
+ "require": "./dist/remote-host/index.cjs",
125
+ "default": "./dist/remote-host/index.js"
126
+ },
127
+ "./remote-host/server": {
128
+ "types": "./dist/remote-host/server/index.d.ts",
129
+ "import": "./dist/remote-host/server/index.js",
130
+ "require": "./dist/remote-host/server/index.cjs",
131
+ "default": "./dist/remote-host/server/index.js"
132
+ },
121
133
  "./translation/client": {
122
134
  "types": "./dist/translation/client.d.ts",
123
135
  "import": "./dist/translation/client.js",
@@ -154,8 +166,14 @@
154
166
  },
155
167
  "peerDependencies": {
156
168
  "@receptron/task-scheduler": "*",
169
+ "firebase": "^12.0.0",
157
170
  "gui-chat-protocol": "^0.4.0"
158
171
  },
172
+ "peerDependenciesMeta": {
173
+ "firebase": {
174
+ "optional": true
175
+ }
176
+ },
159
177
  "devDependencies": {
160
178
  "@receptron/task-scheduler": "*",
161
179
  "@types/node": "^26.1.0",