@volter/teams 0.1.62 → 0.1.64

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@volter/teams",
3
- "version": "0.1.62",
3
+ "version": "0.1.64",
4
4
  "type": "module",
5
5
  "description": "Volter Teams, the neutral team plane: machine identity and daemon core, the local door and server link, admission from machine grants, product doors, and the Teams server's neutral routes (company RFC 0008).",
6
6
  "license": "MIT",
@@ -33,7 +33,7 @@ export interface FollowTeamSessionOptions {
33
33
  export function followTeamSession(options: FollowTeamSessionOptions): { stop(): void; read(): Promise<TeamSessionSnapshot> };
34
34
 
35
35
  /** A message another session sent this one, from its envelope: its sender and body, or null for an ordinary turn. */
36
- export function peerMessage(text: string): { name: string; address: string; body: string } | null;
36
+ export function peerMessage(text: string): { id: string | null; name: string; address: string; body: string; subject: string | null; via: string | null; inReplyTo: string | null } | null;
37
37
 
38
38
  /** Overlay actual envelopes, deduplicating copies already delivered into the native transcript. */
39
39
  export function withMail<Entry extends { id: string; ts: number | null; mail?: { id: string } }>(transcript: Entry[], rows: import('./browser-channel.js').MailHistoryEntry[], options?: { agentName?: string; agentId?: string; agentImage?(seed: string): string }): Array<Entry | { id: string; role: 'notice'; text: string; ts: number; truncated: boolean; mail: { id: string; from: string; to: string; direction: 'in' | 'out'; inReplyTo?: string | null; image?: string; via?: 'voice' } }>;
@@ -15,29 +15,41 @@
15
15
  */
16
16
  export function followTeamSession({ origin, teamId, sessionId, token, tail = 300, onSnapshot, onLive = () => {}, onError = () => {}, onDeleted = () => {}, fetchImpl = globalThis.fetch, retryMs = 2000 }) {
17
17
  const base = `${origin}/api/v1/teams/${encodeURIComponent(teamId)}/sessions/${encodeURIComponent(sessionId)}`;
18
- const decoder = new TextDecoder();
19
18
  const controller = new AbortController();
20
19
  const headers = async () => ({ Authorization: `Bearer ${await token()}` });
21
20
  const failure = (stage, status, message) => Object.assign(new Error(message), { stage, status });
22
- let reading = null;
23
- const read = () => (reading ??= (async () => {
24
- try {
25
- const response = await fetchImpl(`${base}/messages?tail=${tail}`, { headers: await headers(), signal: controller.signal });
26
- if (!response.ok) throw failure('read', response.status, `reading the session failed (${response.status})`);
27
- const body = await response.json();
28
- onSnapshot(body.data ?? body);
29
- return body.data ?? body;
30
- } finally { reading = null; }
31
- })());
21
+ let reading = null, requested = false;
22
+ const read = () => {
23
+ requested = true;
24
+ return reading ??= (async () => {
25
+ let snapshot;
26
+ do {
27
+ requested = false;
28
+ const response = await fetchImpl(`${base}/messages?tail=${tail}`, { headers: await headers(), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]) });
29
+ if (!response.ok) throw failure('read', response.status, `reading the session failed (${response.status})`);
30
+ const body = await response.json();
31
+ if (controller.signal.aborted) throw new DOMException('Session follow stopped', 'AbortError');
32
+ snapshot = body.data ?? body;
33
+ onSnapshot(snapshot);
34
+ // A change during the HTTP read may be newer than the capture it
35
+ // returned. Coalesce the callers, but do not drop that invalidation.
36
+ } while (requested);
37
+ return snapshot;
38
+ })().finally(() => { reading = null; });
39
+ };
32
40
  (async () => {
33
- let cursor = null;
41
+ let cursor = null, following = null, watched = null;
34
42
  while (!controller.signal.aborted) {
43
+ const connection = new AbortController();
44
+ following = connection;
45
+ let reader;
35
46
  try {
36
47
  if (!cursor) cursor = String((await read()).event_cursor ?? '') || null;
37
- const response = await fetchImpl(`${base}/events?${cursor ? `after=${encodeURIComponent(cursor)}` : 'tail=1'}`, { headers: await headers(), signal: controller.signal });
48
+ const response = await fetchImpl(`${base}/events?${cursor ? `after=${encodeURIComponent(cursor)}` : 'tail=1'}`, { headers: await headers(), signal: AbortSignal.any([controller.signal, connection.signal]) });
38
49
  if (!response.ok) throw failure('follow', response.status, `following the session failed (${response.status})`);
39
50
  onLive(true);
40
- const reader = response.body.getReader();
51
+ reader = response.body.getReader();
52
+ const decoder = new TextDecoder();
41
53
  let buffer = '';
42
54
  for (;;) {
43
55
  const { value, done } = await reader.read();
@@ -54,13 +66,33 @@ export function followTeamSession({ origin, teamId, sessionId, token, tail = 300
54
66
  // The server ends a stream it can no longer resume (a slow reader, a retired cursor): start from a snapshot.
55
67
  if (event.terminal && event.type === 'resync_required') cursor = null;
56
68
  if (event.type === 'snapshot') onSnapshot(event.data);
57
- else if (event.type === 'session_changed') read().catch((error) => { if (!controller.signal.aborted) onError({ stage: error.stage ?? 'read', status: error.status ?? null, message: error.message }); });
69
+ else if (event.type === 'session_changed') {
70
+ const refresh = read();
71
+ // One recovery handler per coalesced read, including when a
72
+ // token-expiry reconnect overtakes the unfinished HTTP read.
73
+ if (watched !== refresh) {
74
+ watched = refresh;
75
+ void refresh.then(() => { if (watched === refresh) watched = null; }, (error) => {
76
+ if (watched === refresh) watched = null;
77
+ if (controller.signal.aborted) return;
78
+ // Its event cursor advanced, but its snapshot was not read.
79
+ // Recover even if no further message arrives.
80
+ cursor = null;
81
+ following?.abort();
82
+ onError({ stage: error.stage ?? 'read', status: error.status ?? null, message: error.message, snapshot: true });
83
+ });
84
+ }
85
+ }
58
86
  else if (event.type === 'session_deleted') { onLive(false); onDeleted(); return; }
59
87
  }
60
88
  }
61
89
  } catch (error) {
62
90
  if (controller.signal.aborted) return;
63
- onError({ stage: error.stage ?? 'follow', status: error.status ?? null, message: error.message, snapshot: Boolean(cursor) });
91
+ if (!connection.signal.aborted) onError({ stage: error.stage ?? 'follow', status: error.status ?? null, message: error.message, snapshot: Boolean(cursor) });
92
+ } finally {
93
+ if (following === connection) following = null;
94
+ connection.abort();
95
+ await reader?.cancel().catch(() => {});
64
96
  }
65
97
  onLive(false);
66
98
  await new Promise((resolve) => setTimeout(resolve, retryMs));
@@ -72,7 +104,7 @@ export function followTeamSession({ origin, teamId, sessionId, token, tail = 300
72
104
  /**
73
105
  * A message another session sent this one, as its harness delivers it: an envelope naming the sender (a
74
106
  * `cross-session-message` tag, the innermost one when the harness wraps it in its own) around the body. Returns
75
- * { name, address, body }, or null for an ordinary turn.
107
+ * { id, name, address, body, subject, via, inReplyTo }, or null for an ordinary turn.
76
108
  */
77
109
  export function peerMessage(text) {
78
110
  const close = text.search(/<\\?\/cross-session-message>/);
@@ -80,10 +112,15 @@ export function peerMessage(text) {
80
112
  const opens = [...text.slice(0, close).matchAll(/<\\?cross-session-message\b([^>]*)>/g)];
81
113
  if (!opens.length) return null;
82
114
  const inner = opens[opens.length - 1];
83
- const attributes = (tag) => Object.fromEntries([...tag.matchAll(/([\w-]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
115
+ // Match the producer's escaping, exactly once. An original literal &lt;
116
+ // arrives as &amp;lt; and must remain &lt;, rather than becoming a tag.
117
+ const entities = { amp: '&', lt: '<', gt: '>', quot: '"' };
118
+ const decodeAttribute = value => value.replace(/&(amp|lt|gt|quot);/g, (_, name) => entities[name]);
119
+ const attributes = (tag) => Object.fromEntries([...tag.matchAll(/([\w-]+)="([^"]*)"/g)].map((m) => [m[1], decodeAttribute(m[2])]));
84
120
  const own = attributes(inner[1]), outer = attributes(opens[0][1]);
85
- const body = text.slice(inner.index + inner[0].length, close).trim();
86
- return { id: own.id || outer.id || null, name: own['from-name'] || outer['from-name'] || own.from || outer.from || 'Another session', address: own.from || outer.from || '', body };
121
+ const body = text.slice(inner.index + inner[0].length, close).trim().replace(/&(amp|lt);/g, (_, name) => entities[name]);
122
+ return { id: own.id || outer.id || null, name: own['from-name'] || outer['from-name'] || own.from || outer.from || 'Another session', address: own.from || outer.from || '', body,
123
+ subject: own.subject || outer.subject || null, via: own.via || outer.via || null, inReplyTo: own['in-reply-to'] || outer['in-reply-to'] || null };
87
124
  }
88
125
 
89
126
  /** A known person's picture; an unnamed sender gets the neutral brand user icon. */
@@ -128,7 +165,7 @@ export function withPeople(transcript, messages, { agentName = null, sessionId =
128
165
  const peer = attributed ? null : peerMessage(entry.text);
129
166
  if (peer) {
130
167
  const seed = peer.address.startsWith('sc:') ? peer.address : peer.name;
131
- return { ...entry, text: peer.body, mail: { id: peer.id || entry.id, from: peer.name, to: agentName || 'This session', direction: 'in' }, actor: { id: seed, name: peer.name, image: agent(seed), kind: 'agent' }, context: [{ id: `${entry.id}:envelope`, kind: 'envelope', label: 'Delivered by supercode', detail: entry.text }] };
168
+ return { ...entry, text: peer.body, mail: { id: peer.id || entry.id, from: peer.name, to: agentName || 'This session', direction: 'in', ...(peer.subject ? { subject: peer.subject } : {}), ...(peer.via === 'voice' ? { via: 'voice' } : {}), ...(peer.inReplyTo ? { inReplyTo: peer.inReplyTo } : {}) }, actor: { id: seed, name: peer.name, image: agent(seed), kind: 'agent' }, context: [{ id: `${entry.id}:envelope`, kind: 'envelope', label: 'Delivered by supercode', detail: entry.text }] };
132
169
  }
133
170
  const name = metadata.source_name || null;
134
171
  const seed = name ? (metadata.source_principal_id || name) : '';