@zhin.js/adapter-sandbox 1.1.33 → 1.1.35

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/src/protocol.ts CHANGED
@@ -75,6 +75,8 @@ export type ResolvedSandboxBot = {
75
75
  readonly randomNamePerConnection: boolean;
76
76
  readonly streaming: boolean;
77
77
  readonly streamingIntervalMs: number;
78
+ /** Configured `nickname`; `[@nickname]` also mentions this bot. */
79
+ readonly nickname?: string;
78
80
  };
79
81
 
80
82
  /** One endpoint config after AdapterIndex expands `plugins.<instanceKey>.endpoints`. */
@@ -102,6 +104,7 @@ export function resolveSandboxEndpoint(
102
104
  randomNamePerConnection: false,
103
105
  streaming: config.streaming !== false,
104
106
  streamingIntervalMs,
107
+ ...(optionalEndpointField(config.nickname) ? { nickname: optionalEndpointField(config.nickname)! } : {}),
105
108
  };
106
109
  }
107
110
 
@@ -175,6 +178,11 @@ export interface SandboxParsedMessage {
175
178
  senderId?: string;
176
179
  senderName?: string;
177
180
  senderRole?: SandboxSenderRole;
181
+ /**
182
+ * ADR 0060 §5.4: speak as the chat identity linked to the authenticated Console user instead of
183
+ * `senderId`. The server decides; without such an identity the message is simulated.
184
+ */
185
+ asMe?: boolean;
178
186
  }
179
187
 
180
188
  export type SandboxInboundEnvelope = SandboxParsedMessage;
@@ -190,6 +198,7 @@ interface SandboxWirePayload {
190
198
  senderId?: unknown;
191
199
  senderName?: unknown;
192
200
  senderRole?: unknown;
201
+ asMe?: unknown;
193
202
  }
194
203
 
195
204
  function readSandboxWirePayload(raw: string): SandboxWirePayload & { op?: unknown; conversation?: unknown } {
@@ -208,8 +217,72 @@ export type SandboxWsFrame =
208
217
  | { readonly kind: 'message'; readonly message: SandboxParsedMessage }
209
218
  | { readonly kind: 'invalid' };
210
219
 
220
+ /**
221
+ * The bot this socket talks to. Typed `[@<id or name>]` text (the input hint the Sandbox page shows)
222
+ * becomes a mention segment; a match on `id` or one of `names` (case-insensitive) targets `id`,
223
+ * so the IM layer recognises it as a mention of the bot.
224
+ */
225
+ export interface SandboxSelfMention {
226
+ readonly id: string;
227
+ readonly names?: readonly string[];
228
+ }
229
+
230
+ const TYPED_MENTION = /\[@([^\[\]\n]{1,64})\]/gu;
231
+
232
+ function expandTypedMentions(
233
+ content: MessageElement[],
234
+ text: string,
235
+ self: SandboxSelfMention | undefined,
236
+ ): { content: MessageElement[]; text: string } {
237
+ const selfKeys = new Set([self?.id, ...(self?.names ?? [])]
238
+ .flatMap(value => typeof value === 'string' && value.trim() ? [value.trim().toLowerCase()] : []));
239
+ const resolve = (name: string): { target: string; self: boolean } => {
240
+ const trimmed = name.trim();
241
+ return self && selfKeys.has(trimmed.toLowerCase()) ? { target: self.id, self: true } : { target: trimmed, self: false };
242
+ };
243
+ let expanded = false;
244
+ const next: MessageElement[] = [];
245
+ for (const segment of content) {
246
+ // A picked mention (`mention` segment) may carry the bot's name instead of its id.
247
+ if ((segment.type === 'mention' || segment.type === 'at') && self && typeof segment.data?.target === 'string'
248
+ && segment.data.target !== self.id && selfKeys.has(segment.data.target.trim().toLowerCase())) {
249
+ expanded = true;
250
+ next.push({ ...segment, data: { ...segment.data, target: self.id } });
251
+ continue;
252
+ }
253
+ const value = segment.type === 'text' ? segment.data?.text : undefined;
254
+ if (typeof value !== 'string' || !value.includes('[@')) {
255
+ next.push(segment);
256
+ continue;
257
+ }
258
+ let last = 0;
259
+ for (const match of value.matchAll(TYPED_MENTION)) {
260
+ const name = match[1]!;
261
+ if (!name.trim()) continue;
262
+ expanded = true;
263
+ if (match.index > last) next.push({ type: 'text', data: { text: value.slice(last, match.index) } });
264
+ const { target } = resolve(name);
265
+ next.push({ type: 'mention', data: { target, name: name.trim() } });
266
+ last = match.index + match[0].length;
267
+ }
268
+ if (last === 0) next.push(segment);
269
+ else if (last < value.length) next.push({ type: 'text', data: { text: value.slice(last) } });
270
+ }
271
+ if (!expanded) return { content, text };
272
+ // Plain-text view: drop mentions of the bot (like other platforms strip the at-self prefix),
273
+ // keep `@name` for anyone else so commands and the Agent still see who was addressed.
274
+ let removedSelf = false;
275
+ const plain = text.replace(TYPED_MENTION, (whole, name: string) => {
276
+ if (!name.trim()) return whole;
277
+ const resolved = resolve(name);
278
+ if (resolved.self) { removedSelf = true; return ''; }
279
+ return `@${resolved.target}`;
280
+ });
281
+ return { content: next, text: removedSelf ? plain.replace(/[ \t]{2,}/gu, ' ').trim() : plain };
282
+ }
283
+
211
284
  /** Control frames never fall through into chat or platform message hooks. */
212
- export function parseSandboxWsFrame(raw: string): SandboxWsFrame {
285
+ export function parseSandboxWsFrame(raw: string, self?: SandboxSelfMention): SandboxWsFrame {
213
286
  const payload = readSandboxWirePayload(raw);
214
287
  if ('op' in payload) {
215
288
  const conversation = payload.conversation as Partial<SandboxConversation> | null;
@@ -218,28 +291,28 @@ export function parseSandboxWsFrame(raw: string): SandboxWsFrame {
218
291
  || typeof conversation.id !== 'string' || !conversation.id.trim()) return { kind: 'invalid' };
219
292
  return { kind: 'subscribe', conversation: { type: conversation.type, id: conversation.id } };
220
293
  }
221
- const message = normalizeSandboxWsPayload(payload, raw);
294
+ const message = normalizeSandboxWsPayload(payload, raw, self);
222
295
  if (!['private', 'direct', 'group', 'channel', 'guild'].includes(message.type)
223
296
  || typeof message.id !== 'string') return { kind: 'invalid' };
224
297
  return { kind: 'message', message };
225
298
  }
226
299
 
227
- export function parseSandboxWsPayload(raw: string): SandboxParsedMessage {
228
- return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw);
300
+ export function parseSandboxWsPayload(raw: string, self?: SandboxSelfMention): SandboxParsedMessage {
301
+ return normalizeSandboxWsPayload(readSandboxWirePayload(raw), raw, self);
229
302
  }
230
303
 
231
304
  export const parseSandboxInboundPayload = parseSandboxWsPayload;
232
305
 
233
- function normalizeSandboxWsPayload(payload: SandboxWirePayload, raw: string): SandboxParsedMessage {
306
+ function normalizeSandboxWsPayload(payload: SandboxWirePayload, raw: string, self?: SandboxSelfMention): SandboxParsedMessage {
234
307
  const type = payload.type ?? 'private';
235
308
  const id = payload.id ?? 'sandbox-user';
236
- const content: MessageElement[] = typeof payload.content === 'string'
309
+ const wireContent: MessageElement[] = typeof payload.content === 'string'
237
310
  ? [{ type: 'text', data: { text: payload.content } }]
238
311
  : Array.isArray(payload.content)
239
312
  ? payload.content
240
313
  : [{ type: 'text', data: { text: payload.text ?? raw } }];
241
314
 
242
- const actionSegment = content.find((segment) => segment.type === 'action');
315
+ const actionSegment = wireContent.find((segment) => segment.type === 'action');
243
316
  let action: { id: string; payload: string } | undefined;
244
317
  if (actionSegment?.data) {
245
318
  const actionPayload = typeof actionSegment.data.payload === 'string'
@@ -255,7 +328,7 @@ function normalizeSandboxWsPayload(payload: SandboxWirePayload, raw: string): Sa
255
328
  }
256
329
  }
257
330
 
258
- let text = content
331
+ let text = wireContent
259
332
  .flatMap((segment) => (segment.type === 'text' && typeof segment.data?.text === 'string'
260
333
  ? [segment.data.text]
261
334
  : []))
@@ -265,6 +338,9 @@ function normalizeSandboxWsPayload(payload: SandboxWirePayload, raw: string): Sa
265
338
  ? payload.text
266
339
  : action?.payload ?? raw;
267
340
  }
341
+ const typed = expandTypedMentions(wireContent, text, self);
342
+ const content = typed.content;
343
+ text = typed.text;
268
344
  const agentRun = normalizeSandboxAgentRunConfig(payload.agentRun);
269
345
  const rawMessageId = typeof payload.messageId === 'string' ? payload.messageId.trim() : '';
270
346
  const messageId = /^[A-Za-z0-9._:-]{1,160}$/u.test(rawMessageId) ? rawMessageId : undefined;
@@ -291,9 +367,21 @@ function normalizeSandboxWsPayload(payload: SandboxWirePayload, raw: string): Sa
291
367
  ...(senderId ? { senderId } : {}),
292
368
  ...(senderName ? { senderName } : {}),
293
369
  ...(senderRole ? { senderRole } : {}),
370
+ ...(payload.asMe === true ? { asMe: true } : {}),
294
371
  };
295
372
  }
296
373
 
374
+ /**
375
+ * ADR 0060 §5.4: a client-chosen sender id becomes a reserved simulated id (`~sim:<id>`). Ids
376
+ * starting with `~` are never chat identities (`isChatIdentity`), so a simulated sender holds no
377
+ * zhin role whatever id it types — including the id of an owner.
378
+ */
379
+ export const SANDBOX_SIMULATED_PREFIX = '~sim:';
380
+
381
+ export function sandboxSimulatedSenderId(clientId: string): string {
382
+ return clientId.startsWith(SANDBOX_SIMULATED_PREFIX) ? clientId : `${SANDBOX_SIMULATED_PREFIX}${clientId}`;
383
+ }
384
+
297
385
  /**
298
386
  * 入站归一化 → ConversationRef。sandbox 无平台社交图谱:
299
387
  * `private`/`group`/`channel` 直映射;`direct`(私聊)归 'private';