osborn 0.9.266 → 0.9.267

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.
Files changed (2) hide show
  1. package/dist/index.js +142 -82
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -559,6 +559,51 @@ function startApiServer(workingDir, port) {
559
559
  }
560
560
  return;
561
561
  }
562
+ if (req.method === 'GET' && url.pathname === '/session-messages') {
563
+ // Prior-conversation hydration for the chat page. The browser calls this at
564
+ // MOUNT, in parallel with the LiveKit connect, so the resumed transcript
565
+ // paints before the voice handshake finishes. Reads the per-session recall
566
+ // store directly (readonly, no JSONL replay) — same source as the
567
+ // data-channel prior_messages push, which remains the fallback for older
568
+ // frontends. Rows carry real timestamps so the UI can date-stamp them.
569
+ try {
570
+ const sessionId = url.searchParams.get('session') || '';
571
+ const limit = Math.min(parseInt(url.searchParams.get('limit') || '50', 10), 200);
572
+ if (!sessionId) {
573
+ res.writeHead(400, { 'Content-Type': 'application/json' });
574
+ res.end(JSON.stringify({ error: 'session required' }));
575
+ return;
576
+ }
577
+ const dbPath = storeExists(sessionId, workingDir);
578
+ if (!dbPath) {
579
+ res.writeHead(200, { 'Content-Type': 'application/json' });
580
+ res.end(JSON.stringify({ sessionId, messages: [] }));
581
+ return;
582
+ }
583
+ const db = openStore(dbPath, { readonly: true });
584
+ try {
585
+ const rows = recentRows(db, limit, ['user', 'assistant']);
586
+ const messages = rows
587
+ .reverse() // newest-first → chronological
588
+ .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 1200), ts: r.ts || null }))
589
+ .filter(m => m.content.trim().length > 0);
590
+ res.writeHead(200, { 'Content-Type': 'application/json' });
591
+ res.end(JSON.stringify({ sessionId, messages }));
592
+ }
593
+ finally {
594
+ try {
595
+ db.close();
596
+ }
597
+ catch { }
598
+ }
599
+ }
600
+ catch (err) {
601
+ console.error('API /session-messages error:', err);
602
+ res.writeHead(500, { 'Content-Type': 'application/json' });
603
+ res.end(JSON.stringify({ error: 'failed to read session messages' }));
604
+ }
605
+ return;
606
+ }
562
607
  if (req.method === 'GET' && url.pathname === '/canvas-token') {
563
608
  // Listen-only LiveKit credentials for the meeting canvas (see hook doc).
564
609
  const out = canvasTokenHook ? await canvasTokenHook() : null;
@@ -5260,7 +5305,7 @@ async function main() {
5260
5305
  const rows = recentRows(db, 20, ['user', 'assistant']); // newest-first
5261
5306
  const priorMessages = rows
5262
5307
  .reverse() // → chronological
5263
- .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 800) }))
5308
+ .map(r => ({ role: r.msgType === 'assistant' ? 'assistant' : 'user', content: (r.text || '').slice(0, 800), ts: r.ts || null }))
5264
5309
  .filter(m => m.content.trim().length > 0);
5265
5310
  if (priorMessages.length > 0) {
5266
5311
  await sendToFrontend({ type: 'prior_messages', sessionId: preSelectedSessionId, messages: priorMessages });
@@ -6548,92 +6593,103 @@ async function main() {
6548
6593
  // attempts fail we surface status='failed' and rethrow so the caller sees it.
6549
6594
  // A single transient blip is absorbed; a persistent failure (quota/auth) is
6550
6595
  // reported promptly rather than hanging the connect flow.
6551
- let creatingRoomSession = false;
6596
+ // Tracks an in-flight createRoomSession so concurrent /connect-room calls
6597
+ // await the same underlying room.connect() rather than racing or triggering a
6598
+ // double-connect cycle (which previously doubled cold-path latency when the
6599
+ // sandbox route's 6s timeout fired before room.connect() finished).
6600
+ let createRoomSessionInflight = null;
6552
6601
  const createRoomSession = async (targetRoomName) => {
6553
- if (creatingRoomSession) {
6554
- console.log('⏳ createRoomSession already in progress — skipping duplicate');
6555
- return;
6602
+ if (createRoomSessionInflight) {
6603
+ console.log('⏳ createRoomSession already in progress — awaiting in-flight connect (idempotent)');
6604
+ return createRoomSessionInflight;
6556
6605
  }
6557
- creatingRoomSession = true;
6558
- try {
6559
- // Discard any prior (dead/stale) instance without reuse.
6560
- if (activeRoom) {
6561
- console.warn('⚠️ createRoomSession called with an existing activeRoom — discarding it (no reuse)');
6562
- activeRoom = null;
6563
- }
6564
- const room = new Room();
6565
- room.setMaxListeners(50); // Prevent MaxListenersExceeded warnings
6566
- wireRoomHandlers(room);
6567
- const backoffSchedule = [5_000, 10_000, 20_000];
6568
- let lastErr = null;
6569
- for (let attempt = 0; attempt < 3; attempt++) {
6570
- livekitState.status = livekitState.attemptCount === 0 ? 'connecting' : 'retrying';
6571
- livekitState.lastAttemptAt = Date.now();
6572
- livekitState.attemptCount += 1;
6573
- try {
6574
- const jwt = await mintAgentToken(targetRoomName);
6575
- await room.connect(livekitUrl, jwt, {
6576
- autoSubscribe: true,
6577
- dynacast: true,
6578
- });
6579
- // Success — adopt this instance as the active room.
6580
- activeRoom = room;
6581
- activeRoomName = targetRoomName;
6582
- currentRoomCode = targetRoomName; // legacy /room-code returns last-created NAME
6583
- localParticipant = room.localParticipant;
6584
- livekitState.status = 'connected';
6585
- livekitState.error = null;
6586
- livekitState.errorCode = null;
6587
- console.log('✅ Connected to room:', targetRoomName);
6588
- // Post-connect setup (re-homed from the dead RoomEvent.Connected handler).
6589
- postConnectSetup(room, targetRoomName);
6590
- // Adopt-sweep: ParticipantConnected only fires for participants who join
6591
- // AFTER us. Anyone already in the room at connect time is populated by
6592
- // rtc-node from the connect callback (no event) — invoke the handler
6593
- // directly so their voice session is created. Runs exactly once per
6594
- // connect (replaces the old adopt-poll + connectRoomHook adopt loop).
6595
- for (const p of room.remoteParticipants.values()) {
6596
- console.log(`👥 Participant already in room at join: ${p.identity} — adopting (invoking handler directly)`);
6597
- participantConnectedHandler?.(p).catch((e) => console.error('👥 adopt handler error:', e instanceof Error ? e.message : e));
6606
+ const run = async () => {
6607
+ try {
6608
+ // Discard any prior (dead/stale) instance without reuse.
6609
+ if (activeRoom) {
6610
+ console.warn('⚠️ createRoomSession called with an existing activeRoom — discarding it (no reuse)');
6611
+ activeRoom = null;
6612
+ }
6613
+ const room = new Room();
6614
+ room.setMaxListeners(50); // Prevent MaxListenersExceeded warnings
6615
+ wireRoomHandlers(room);
6616
+ const backoffSchedule = [5_000, 10_000, 20_000];
6617
+ let lastErr = null;
6618
+ for (let attempt = 0; attempt < 3; attempt++) {
6619
+ livekitState.status = livekitState.attemptCount === 0 ? 'connecting' : 'retrying';
6620
+ livekitState.lastAttemptAt = Date.now();
6621
+ livekitState.attemptCount += 1;
6622
+ try {
6623
+ const t0 = Date.now();
6624
+ const jwt = await mintAgentToken(targetRoomName);
6625
+ const t1 = Date.now();
6626
+ await room.connect(livekitUrl, jwt, {
6627
+ autoSubscribe: true,
6628
+ dynacast: true,
6629
+ });
6630
+ const t2 = Date.now();
6631
+ console.log(`⏱️ [room-connect] mintToken=${t1 - t0}ms connect=${t2 - t1}ms total=${t2 - t0}ms`);
6632
+ // Success — adopt this instance as the active room.
6633
+ activeRoom = room;
6634
+ activeRoomName = targetRoomName;
6635
+ currentRoomCode = targetRoomName; // legacy /room-code returns last-created NAME
6636
+ localParticipant = room.localParticipant;
6637
+ livekitState.status = 'connected';
6638
+ livekitState.error = null;
6639
+ livekitState.errorCode = null;
6640
+ console.log('✅ Connected to room:', targetRoomName);
6641
+ // Post-connect setup (re-homed from the dead RoomEvent.Connected handler).
6642
+ postConnectSetup(room, targetRoomName);
6643
+ // Adopt-sweep: ParticipantConnected only fires for participants who join
6644
+ // AFTER us. Anyone already in the room at connect time is populated by
6645
+ // rtc-node from the connect callback (no event) — invoke the handler
6646
+ // directly so their voice session is created. Runs exactly once per
6647
+ // connect (replaces the old adopt-poll + connectRoomHook adopt loop).
6648
+ for (const p of room.remoteParticipants.values()) {
6649
+ console.log(`👥 Participant already in room at join: ${p.identity} — adopting (invoking handler directly)`);
6650
+ participantConnectedHandler?.(p).catch((e) => console.error('👥 adopt handler error:', e instanceof Error ? e.message : e));
6651
+ }
6652
+ console.log('\n⏳ Waiting for user to connect...');
6653
+ console.log(` Room: ${targetRoomName}\n`);
6654
+ return;
6598
6655
  }
6599
- console.log('\n⏳ Waiting for user to connect...');
6600
- console.log(` Room: ${targetRoomName}\n`);
6601
- return;
6602
- }
6603
- catch (err) {
6604
- lastErr = err;
6605
- const msg = err instanceof Error ? err.message : String(err);
6606
- // Categorize the error so the frontend can show specific guidance.
6607
- let errorCode;
6608
- if (/429|connection minutes limit/i.test(msg))
6609
- errorCode = 'quota_exceeded';
6610
- else if (/401|403|unauthorized|invalid/i.test(msg))
6611
- errorCode = 'auth';
6612
- else if (/ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network/i.test(msg))
6613
- errorCode = 'network';
6614
- else
6615
- errorCode = 'unknown';
6616
- livekitState.status = 'failed';
6617
- livekitState.error = msg;
6618
- livekitState.errorCode = errorCode;
6619
- console.error(`❌ LiveKit connect failed (${errorCode}, attempt ${attempt + 1}/3): ${msg.substring(0, 200)}`);
6620
- if (attempt < 2) {
6621
- const waitMs = backoffSchedule[attempt];
6622
- console.error(` Retrying in ${waitMs / 1000}s...`);
6623
- await new Promise(r => setTimeout(r, waitMs));
6656
+ catch (err) {
6657
+ lastErr = err;
6658
+ const msg = err instanceof Error ? err.message : String(err);
6659
+ // Categorize the error so the frontend can show specific guidance.
6660
+ let errorCode;
6661
+ if (/429|connection minutes limit/i.test(msg))
6662
+ errorCode = 'quota_exceeded';
6663
+ else if (/401|403|unauthorized|invalid/i.test(msg))
6664
+ errorCode = 'auth';
6665
+ else if (/ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network/i.test(msg))
6666
+ errorCode = 'network';
6667
+ else
6668
+ errorCode = 'unknown';
6669
+ livekitState.status = 'failed';
6670
+ livekitState.error = msg;
6671
+ livekitState.errorCode = errorCode;
6672
+ console.error(`❌ LiveKit connect failed (${errorCode}, attempt ${attempt + 1}/3): ${msg.substring(0, 200)}`);
6673
+ if (attempt < 2) {
6674
+ const waitMs = backoffSchedule[attempt];
6675
+ console.error(` Retrying in ${waitMs / 1000}s...`);
6676
+ await new Promise(r => setTimeout(r, waitMs));
6677
+ }
6624
6678
  }
6625
6679
  }
6680
+ // All attempts failed. Drop the dead instance; leave status='failed' so
6681
+ // /health surfaces it and the frontend can retry /connect-room.
6682
+ activeRoom = null;
6683
+ activeRoomName = null;
6684
+ console.error('❌ createRoomSession: all 3 connect attempts failed — giving up (status=failed)');
6685
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
6626
6686
  }
6627
- // All attempts failed. Drop the dead instance; leave status='failed' so
6628
- // /health surfaces it and the frontend can retry /connect-room.
6629
- activeRoom = null;
6630
- activeRoomName = null;
6631
- console.error('❌ createRoomSession: all 3 connect attempts failed — giving up (status=failed)');
6632
- throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
6633
- }
6634
- finally {
6635
- creatingRoomSession = false;
6636
- }
6687
+ finally {
6688
+ createRoomSessionInflight = null;
6689
+ }
6690
+ };
6691
+ createRoomSessionInflight = run();
6692
+ return createRoomSessionInflight;
6637
6693
  };
6638
6694
  // destroyRoomSession(reason): tear down the active room session and DISCARD
6639
6695
  // the Room instance (never reused). A hung rtc-node disconnect() (signal-less
@@ -6724,7 +6780,11 @@ async function main() {
6724
6780
  const targetRoomName = buildRoomName();
6725
6781
  console.log(`🔌 /connect-room — creating fresh room session: ${targetRoomName}`);
6726
6782
  await createRoomSession(targetRoomName);
6727
- return targetRoomName;
6783
+ // Return the room the agent actually joined. When a concurrent /connect-room
6784
+ // call awaited an in-flight session, activeRoomName is the first call's room
6785
+ // name — which differs from targetRoomName generated here. Always use the
6786
+ // actual active name so the client mints a token for the right room.
6787
+ return activeRoomName || targetRoomName;
6728
6788
  };
6729
6789
  leaveRoomHook = async (reason) => {
6730
6790
  if (aloneTimer) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.266",
3
+ "version": "0.9.267",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {