@mulmobridge/chat-service 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/relay.d.ts CHANGED
@@ -6,6 +6,12 @@ export interface RelayParams {
6
6
  externalChatId: string;
7
7
  text: string;
8
8
  attachments?: Attachment[];
9
+ /** Flat primitive bag captured at handshake time (string /
10
+ * number / boolean values only — see socket.ts sanitiser).
11
+ * Forwarded to the host app's startChat callback as
12
+ * `bridgeOptions`. Empty when the bridge didn't send any.
13
+ * See plans/feat-bridge-options-passthrough.md. */
14
+ bridgeOptions?: Readonly<Record<string, string | number | boolean>>;
9
15
  /** Called for each text chunk as the agent generates it. Used by
10
16
  * the socket transport to stream text to the bridge in real time
11
17
  * (Phase C of #268). */
@@ -30,3 +36,4 @@ export interface RelayDeps {
30
36
  logger: Logger;
31
37
  }
32
38
  export declare function createRelay(deps: RelayDeps): RelayFn;
39
+ export declare function resolveDefaultRole(bridgeOptions: Readonly<Record<string, string | number | boolean>> | undefined, getRole: (roleId: string) => Role, fallbackRoleId: string, logger: Logger, transportId: string): string;
package/dist/relay.js CHANGED
@@ -13,7 +13,7 @@ const REPLY_TIMEOUT_MS = 5 * 60 * 1000;
13
13
  export function createRelay(deps) {
14
14
  const { store, handleCommand, startChat, onSessionEvent, getRole, defaultRoleId, logger } = deps;
15
15
  return async function relayMessage(params) {
16
- const { transportId, externalChatId, text, attachments } = params;
16
+ const { transportId, externalChatId, text, attachments, bridgeOptions } = params;
17
17
  // Log attachment summary (count + mimeTypes) — NEVER log raw
18
18
  // base64 data (performance, log size, information leak risk).
19
19
  const attachmentSummary = attachments
@@ -30,8 +30,13 @@ export function createRelay(deps) {
30
30
  });
31
31
  let chatState = await store.getChatState(transportId, externalChatId);
32
32
  if (!chatState) {
33
- const defaultRole = getRole(defaultRoleId);
34
- chatState = await store.resetChatState(transportId, externalChatId, defaultRole.id);
33
+ // Only on FIRST contact do we honour `bridgeOptions.defaultRole`
34
+ // — once the session exists, whatever role the user / command
35
+ // handler settled on is the source of truth. An unknown role
36
+ // id silently falls back to the host-app default (we log it so
37
+ // a typo in the bridge's env var is discoverable).
38
+ const resolved = resolveDefaultRole(bridgeOptions, getRole, defaultRoleId, logger, transportId);
39
+ chatState = await store.resetChatState(transportId, externalChatId, resolved);
35
40
  }
36
41
  const commandResult = await handleCommand(text, transportId, chatState);
37
42
  if (commandResult) {
@@ -43,6 +48,9 @@ export function createRelay(deps) {
43
48
  chatSessionId: chatState.sessionId,
44
49
  attachments,
45
50
  origin: "bridge",
51
+ // Host app may use other keys (e.g. a future `defaultModel`);
52
+ // we forward the whole bag untouched.
53
+ bridgeOptions,
46
54
  });
47
55
  if (result.kind === "error") {
48
56
  const status = result.status ?? 500;
@@ -90,6 +98,28 @@ export function createRelay(deps) {
90
98
  };
91
99
  }
92
100
  // ── Internals ────────────────────────────────────────────────
101
+ // Resolve the role id to seed a NEW bridge chat state with. Prefers
102
+ // `bridgeOptions.defaultRole` when the bridge sent one and it names
103
+ // a role the host app actually has. Falls back to the host-app
104
+ // default on absence / unknown id (with a warn log so an env-var
105
+ // typo is traceable). Exported for direct unit testing.
106
+ export function resolveDefaultRole(bridgeOptions, getRole, fallbackRoleId, logger, transportId) {
107
+ const requested = bridgeOptions?.defaultRole;
108
+ if (typeof requested !== "string" || requested.length === 0)
109
+ return fallbackRoleId;
110
+ // `getRole` on an unknown id silently returns the first built-in
111
+ // role — compare ids to catch that before we commit to it.
112
+ const resolved = getRole(requested);
113
+ if (resolved.id !== requested) {
114
+ logger.warn("chat-service", "bridge requested unknown default role; falling back", {
115
+ transportId,
116
+ requested,
117
+ fallback: fallbackRoleId,
118
+ });
119
+ return fallbackRoleId;
120
+ }
121
+ return resolved.id;
122
+ }
93
123
  // Kept out of the factory closure so future packaging doesn't need
94
124
  // to re-capture anything; `onSessionEvent` arrives as a plain param.
95
125
  function collectAgentReply(onSessionEvent, chatSessionId, onChunk) {
package/dist/socket.d.ts CHANGED
@@ -39,5 +39,8 @@ export interface ChatSocketHandle {
39
39
  * joiner. */
40
40
  pushToBridge: PushFn;
41
41
  }
42
+ type BridgeOptions = Readonly<Record<string, string | number | boolean>>;
42
43
  export declare function bridgeRoom(transportId: string): string;
43
44
  export declare function attachChatSocket(server: http.Server, deps: ChatSocketDeps): ChatSocketHandle;
45
+ export declare function sanitiseOptions(raw: unknown): BridgeOptions;
46
+ export {};
package/dist/socket.js CHANGED
@@ -63,6 +63,9 @@ export function attachChatSocket(server, deps) {
63
63
  return;
64
64
  }
65
65
  socket.data.transportId = result.transportId;
66
+ // Stash options on the socket so every subsequent message from
67
+ // this bridge inherits the same config without re-sending it.
68
+ socket.data.bridgeOptions = result.options;
66
69
  next();
67
70
  });
68
71
  io.on("connection", (socket) => {
@@ -116,6 +119,10 @@ export function attachChatSocket(server, deps) {
116
119
  externalChatId: parsed.externalChatId,
117
120
  text: parsed.text,
118
121
  attachments: parsed.attachments,
122
+ // Options captured at handshake time (see io.use). Empty
123
+ // object when the bridge didn't send any — the host app
124
+ // treats absence and empty identically.
125
+ bridgeOptions: socket.data.bridgeOptions ?? {},
119
126
  // Stream text chunks to this bridge socket in real time
120
127
  // (Phase C of #268). The ack still returns the full text
121
128
  // for backward compatibility.
@@ -151,6 +158,36 @@ export function attachChatSocket(server, deps) {
151
158
  };
152
159
  return { io, pushToBridge };
153
160
  }
161
+ // `options` on the handshake is reduced to a FLAT PRIMITIVE bag:
162
+ // string / number / boolean only. This serves two purposes —
163
+ // 1. Rejects nested objects / arrays / functions so a downstream
164
+ // merge in the host app can't reintroduce prototype-pollution
165
+ // via a deeply-nested `__proto__` (top-level `__proto__` is
166
+ // stripped separately as a belt-and-braces guard).
167
+ // 2. Makes the wire contract explicit: every value the host sees
168
+ // is something you could put in an env var.
169
+ // Anything else (objects, arrays, null, undefined, functions,
170
+ // symbols, bigints) is dropped silently. The bridge author is
171
+ // responsible for flattening complex config into primitives before
172
+ // sending.
173
+ export function sanitiseOptions(raw) {
174
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
175
+ return {};
176
+ const out = {};
177
+ for (const [key, value] of Object.entries(raw)) {
178
+ if (key === "__proto__" || key === "prototype" || key === "constructor")
179
+ continue;
180
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
181
+ // Drop non-finite numbers (NaN / Infinity) — they serialise
182
+ // oddly and the host app shouldn't be asked to distinguish
183
+ // "valid zero" from "broken input".
184
+ if (typeof value === "number" && !Number.isFinite(value))
185
+ continue;
186
+ out[key] = value;
187
+ }
188
+ }
189
+ return out;
190
+ }
154
191
  function validateHandshake(auth, tokenProvider) {
155
192
  if (!auth || typeof auth !== "object") {
156
193
  return { ok: false, error: "handshake auth is required" };
@@ -160,8 +197,9 @@ function validateHandshake(auth, tokenProvider) {
160
197
  return { ok: false, error: "transportId is required" };
161
198
  }
162
199
  const transportId = transportIdRaw.trim();
200
+ const options = sanitiseOptions(auth.options);
163
201
  if (!tokenProvider) {
164
- return { ok: true, transportId };
202
+ return { ok: true, transportId, options };
165
203
  }
166
204
  const expected = tokenProvider();
167
205
  if (expected === null || expected.length === 0) {
@@ -177,7 +215,7 @@ function validateHandshake(auth, tokenProvider) {
177
215
  if (provided !== expected) {
178
216
  return { ok: false, error: "invalid token" };
179
217
  }
180
- return { ok: true, transportId };
218
+ return { ok: true, transportId, options };
181
219
  }
182
220
  function parseMessagePayload(payload) {
183
221
  if (!payload || typeof payload !== "object") {
package/dist/types.d.ts CHANGED
@@ -25,6 +25,14 @@ export interface StartChatParams {
25
25
  attachments?: Attachment[];
26
26
  /** Session origin — application-defined (e.g. "human", "bridge") */
27
27
  origin?: string;
28
+ /** Flat primitive bag forwarded from the bridge handshake. Chat-
29
+ * service sanitises to string / number / boolean values only
30
+ * before this point — nested objects are dropped at the socket
31
+ * boundary so a downstream merge can't reintroduce prototype-
32
+ * pollution. The host app is free to look up its own keys
33
+ * (e.g. `defaultRole`). Empty object when the bridge didn't
34
+ * send any. */
35
+ bridgeOptions?: Readonly<Record<string, string | number | boolean>>;
28
36
  }
29
37
  export type StartChatResult = {
30
38
  kind: "started";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mulmobridge/chat-service",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Server-side chat service for MulmoBridge — socket.io + REST bridge to Claude Code agents",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -27,7 +27,7 @@
27
27
  "license": "MIT",
28
28
  "author": "Receptron Team",
29
29
  "dependencies": {
30
- "@mulmobridge/protocol": "^0.1.3"
30
+ "@mulmobridge/protocol": "^0.1.4"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "express": "^5.0.0",