@howaboua/pi-durable-gippity-voice 0.11.0 → 0.13.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.
Files changed (40) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +4 -2
  3. package/dist/activation.js +1795 -897
  4. package/dist/index.js +1787 -889
  5. package/dist/{packages/gippity-voice/src → internal/voice}/agent-observation.d.ts +2 -2
  6. package/dist/internal/voice/browser-provider.d.ts +65 -0
  7. package/dist/internal/voice/browser-settings.d.ts +24 -0
  8. package/dist/internal/voice/handoff-contract.d.ts +28 -0
  9. package/dist/internal/voice/lan-client-sdk.d.ts +1 -0
  10. package/dist/internal/voice/lan-listener-proof.d.ts +2 -0
  11. package/dist/packages/execution/src/invocation-state.d.ts +1 -1
  12. package/dist/packages/execution/src/invocation.d.ts +79 -2
  13. package/dist/packages/execution/src/native-tools.d.ts +18 -7
  14. package/dist/packages/execution/src/nested-call.d.ts +11 -3
  15. package/dist/packages/execution/src/nested-park.d.ts +9 -0
  16. package/dist/packages/execution/src/nested-result.d.ts +1 -1
  17. package/dist/packages/execution/src/tool-contract.d.ts +8 -1
  18. package/dist/packages/execution/src/tool-namespaces.d.ts +31 -0
  19. package/dist/packages/execution/src/tool-origin.d.ts +9 -1
  20. package/dist/packages/gippity-voice/src/controller.d.ts +10 -3
  21. package/dist/packages/gippity-voice/src/voice/browser-reservation.d.ts +30 -0
  22. package/dist/packages/gippity-voice/src/voice/conversation/peer.d.ts +2 -0
  23. package/dist/packages/gippity-voice/src/voice/conversation/session.d.ts +1 -0
  24. package/dist/packages/gippity-voice/src/voice/handoff-departure.d.ts +5 -0
  25. package/dist/packages/gippity-voice/src/voice/handoff-peer.d.ts +12 -0
  26. package/dist/packages/gippity-voice/src/voice/handoff-wire.d.ts +1 -1
  27. package/dist/packages/gippity-voice/src/voice/lan/browser-clients.d.ts +1 -0
  28. package/dist/packages/gippity-voice/src/voice/lan/browser-peer.d.ts +4 -0
  29. package/dist/packages/gippity-voice/src/voice/lan/browser-session.d.ts +6 -2
  30. package/dist/packages/gippity-voice/src/voice/lan/pcm-bridge.d.ts +25 -0
  31. package/dist/packages/gippity-voice/src/voice/lan/playback-drain.d.ts +8 -0
  32. package/dist/packages/gippity-voice/src/voice/lan/protocol.d.ts +4 -0
  33. package/dist/packages/gippity-voice/src/voice/lan/server.d.ts +1 -1
  34. package/dist/packages/gippity-voice/src/voice/lan/takeover.d.ts +2 -3
  35. package/dist/packages/gippity-voice/src/voice/lan/unified-settings.d.ts +3 -0
  36. package/package.json +10 -10
  37. /package/dist/{packages/gippity-voice/src → internal/voice}/deferred.d.ts +0 -0
  38. /package/dist/{packages/gippity-voice/src/voice/lan/activity.d.ts → internal/voice/lan-activity.d.ts} +0 -0
  39. /package/dist/{packages/gippity-voice/src/voice/lan/draft.d.ts → internal/voice/lan-draft.d.ts} +0 -0
  40. /package/dist/{packages/gippity-voice/src/voice/lan → internal/voice}/remote-json.d.ts +0 -0
package/dist/index.js CHANGED
@@ -103,7 +103,7 @@ async function resolveCodexVoiceAuth(models, conversationId, signal) {
103
103
  }
104
104
  }
105
105
 
106
- // packages/gippity-voice/src/deferred.ts
106
+ // internal/voice/deferred.ts
107
107
  function deferred() {
108
108
  let resolve;
109
109
  let reject;
@@ -635,11 +635,11 @@ function normalizeGippityControlConfig(value) {
635
635
  };
636
636
  }
637
637
  // packages/gippity-voice/src/controller.ts
638
- import { randomUUID as randomUUID5, X509Certificate as X509Certificate2 } from "node:crypto";
638
+ import { randomUUID as randomUUID6, X509Certificate as X509Certificate2 } from "node:crypto";
639
639
  import {
640
- awaitWithContext as awaitWithContext2,
641
- BACKGROUND_CONTEXT,
642
- withAbortSignal
640
+ awaitWithContext as awaitWithContext3,
641
+ BACKGROUND_CONTEXT as BACKGROUND_CONTEXT2,
642
+ withAbortSignal as withAbortSignal2
643
643
  } from "@earendil-works/chord/context";
644
644
  import {
645
645
  AgentDoc,
@@ -752,16 +752,94 @@ function createSettingsContribution(options) {
752
752
  };
753
753
  }
754
754
 
755
+ // internal/voice/agent-observation.ts
756
+ import {
757
+ LiveDoc
758
+ } from "@earendil-works/pi-durable";
759
+ async function observeVoiceAgent(conversation, context, callbacks) {
760
+ const watch = await conversation.watch(context);
761
+ let newest = watch.value.entries.at(-1)?.id ?? watch.value.before;
762
+ let previous = liveState(watch.value);
763
+ let text = "";
764
+ let stopped = false;
765
+ let work = Promise.resolve();
766
+ callbacks.state(Boolean(previous.run));
767
+ async function advance(view) {
768
+ if (stopped)
769
+ return;
770
+ const live = liveState(view);
771
+ if (live.run)
772
+ callbacks.state(true);
773
+ const upTo = view.entries.at(-1)?.id;
774
+ if (upTo !== undefined && (newest === undefined || upTo > newest)) {
775
+ const from = newest;
776
+ let cursor;
777
+ do {
778
+ const page = await conversation.entries({
779
+ ...from === undefined ? {} : { minEntryId: from },
780
+ maxEntryId: upTo,
781
+ order: "ascending"
782
+ }, 128, cursor, context);
783
+ if (stopped)
784
+ return;
785
+ for (const entry of page.items) {
786
+ if (newest !== undefined && entry.id <= newest)
787
+ continue;
788
+ callbacks.entry(entry);
789
+ newest = entry.id;
790
+ }
791
+ cursor = page.next;
792
+ } while (cursor);
793
+ }
794
+ const partial = live.generation?.message;
795
+ const nextText = partial?.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
796
+ `) ?? "";
797
+ if (previous.run?.taskId !== live.run?.taskId || previous.generation?.attempt !== live.generation?.attempt || !nextText.startsWith(text))
798
+ text = "";
799
+ callbacks.partial(nextText.slice(text.length), Boolean(partial?.content.some((part) => part.type === "thinking" || part.type === "toolCall")));
800
+ text = nextText;
801
+ for (const compact of live.compactions ?? []) {
802
+ if (compact.trigger !== "manual" && !previous.compactions?.some((old) => old.taskId === compact.taskId))
803
+ callbacks.compacting(compact.trigger === "overflow" ? "overflow" : "threshold");
804
+ }
805
+ if (!live.run)
806
+ callbacks.state(false);
807
+ previous = live;
808
+ }
809
+ watch.start((call) => {
810
+ work = call.kind === "failed" ? Promise.reject(call.error) : advance(call.value);
811
+ return work;
812
+ });
813
+ watch.closed.then((end) => {
814
+ if (end.kind === "failed" || end.kind === "listener_error")
815
+ callbacks.failed(end.error);
816
+ });
817
+ return {
818
+ get view() {
819
+ return watch.value;
820
+ },
821
+ async stop() {
822
+ stopped = true;
823
+ await watch.stop();
824
+ await work;
825
+ }
826
+ };
827
+ }
828
+ function liveState(view) {
829
+ return view.docs[LiveDoc.definition.kind] ?? {};
830
+ }
831
+
755
832
  // packages/execution/src/nested.ts
833
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
756
834
  import {
757
835
  defineTask
758
836
  } from "@earendil-works/pi-durable";
759
837
  import { compile as compile2 } from "@earendil-works/pi-schema";
760
838
 
761
839
  // packages/execution/src/forwarding.ts
762
- import { copyJson as copyJson2 } from "@earendil-works/chord";
840
+ import { copyJson as copyJson2 } from "@earendil-works/chord/json";
763
841
  import {
764
- LiveDoc,
842
+ LiveDoc as LiveDoc2,
765
843
  NestedCallDoc,
766
844
  ToolTask
767
845
  } from "@earendil-works/pi-durable";
@@ -769,7 +847,7 @@ import {
769
847
  // packages/execution/src/invocation-state.ts
770
848
  import {
771
849
  copyJson
772
- } from "@earendil-works/chord";
850
+ } from "@earendil-works/chord/json";
773
851
  import {
774
852
  defineDoc
775
853
  } from "@earendil-works/pi-durable";
@@ -1121,7 +1199,7 @@ async function forwardInvocationResult(tx, taskId, result, status) {
1121
1199
  async function captureNativeCalls(tx, conversationId, owner, cellId) {
1122
1200
  if (cellId === undefined)
1123
1201
  return;
1124
- const live = await tx.doc(LiveDoc, conversationId);
1202
+ const live = await tx.doc(LiveDoc2, conversationId);
1125
1203
  const owners = new Set([owner]);
1126
1204
  const cell = await tx.doc(InvocationDoc, cellId);
1127
1205
  const budget = cell.forwardingBudget ?? 40000;
@@ -1211,26 +1289,53 @@ async function captureNativeCalls(tx, conversationId, owner, cellId) {
1211
1289
  }
1212
1290
 
1213
1291
  // packages/execution/src/invocation.ts
1214
- import { copyJson as copyJson4 } from "@earendil-works/chord";
1215
1292
  import { awaitWithContext } from "@earendil-works/chord/context";
1293
+ import { copyJson as copyJson4 } from "@earendil-works/chord/json";
1294
+ import {
1295
+ NestedCallDoc as NestedCallDoc3
1296
+ } from "@earendil-works/pi-durable";
1297
+ import { equal } from "@earendil-works/pi-schema";
1216
1298
 
1217
1299
  // packages/execution/src/native-tools.ts
1218
- import { copyJson as copyJson3 } from "@earendil-works/chord";
1219
- import { withoutAbortSignal } from "@earendil-works/chord/context";
1220
1300
  import {
1221
- LiveDoc as LiveDoc2,
1301
+ withoutAbortSignal
1302
+ } from "@earendil-works/chord/context";
1303
+ import { copyJson as copyJson3 } from "@earendil-works/chord/json";
1304
+ import {
1305
+ LiveDoc as LiveDoc3,
1222
1306
  NestedCallDoc as NestedCallDoc2,
1223
- ToolTask as ToolTask2
1307
+ ToolTask as ToolTask3
1224
1308
  } from "@earendil-works/pi-durable";
1225
1309
  import { Equal } from "typebox/value";
1226
- function nativeToolCalls(runtime, callId, replay, assertLive, context) {
1310
+
1311
+ // packages/execution/src/tool-origin.ts
1312
+ import {
1313
+ defineDoc as defineDoc2,
1314
+ ToolTask as ToolTask2
1315
+ } from "@earendil-works/pi-durable";
1316
+ var ToolOriginDoc = defineDoc2({
1317
+ kind: "howaboua.tool-origin",
1318
+ version: 1,
1319
+ scope: "task",
1320
+ checkpointWhen: () => false,
1321
+ initial: () => ({})
1322
+ });
1323
+
1324
+ // packages/execution/src/native-tools.ts
1325
+ function assertNestedKey(key) {
1326
+ if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
1327
+ throw new Error("Invalid nested call or task key");
1328
+ }
1329
+ function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
1227
1330
  let sequence = 0;
1228
1331
  const admissions = [];
1229
- const execute = async (name, args, callContext, options = {}) => {
1332
+ async function execute(name, args, callContext, options = {}) {
1230
1333
  assertLive();
1334
+ if (options.key !== undefined)
1335
+ assertNestedKey(options.key);
1336
+ else if (resumed)
1337
+ throw new Error("Nested calls require an explicit key after waking");
1231
1338
  const key = options.key ?? String(++sequence);
1232
- if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
1233
- throw new Error("Invalid nested call key");
1234
1339
  const call = {
1235
1340
  type: "toolCall",
1236
1341
  id: `${callId}/${key}`,
@@ -1242,11 +1347,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
1242
1347
  const admission = runtime.commit(async (tx) => {
1243
1348
  const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
1244
1349
  if (slot.taskId !== undefined) {
1245
- const input = (await tx.task(slot.taskId))?.input;
1350
+ const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
1246
1351
  if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
1247
1352
  throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
1248
1353
  } else {
1249
- slot.taskId = await tx.createTask(ToolTask2, {
1354
+ slot.kind = "nested";
1355
+ slot.taskId = await tx.createTask(ToolTask3, {
1250
1356
  kind: "nested",
1251
1357
  parent: runtime.taskId,
1252
1358
  parentCallId: callId,
@@ -1257,7 +1363,10 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
1257
1363
  ownership: { kind: "task", taskId: runtime.taskId },
1258
1364
  abandonOnRestart: replay !== "safe"
1259
1365
  });
1260
- const live = await tx.doc(LiveDoc2, runtime.conversationId);
1366
+ const live = await tx.doc(LiveDoc3, runtime.conversationId);
1367
+ const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
1368
+ if (origin)
1369
+ (await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
1261
1370
  live.nestedTools ??= [];
1262
1371
  live.nestedTools.push({
1263
1372
  callId: call.id,
@@ -1289,7 +1398,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
1289
1398
  const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
1290
1399
  if (slot?.taskId === undefined)
1291
1400
  throw new Error("Nested task creation did not commit");
1292
- const settled = await runtime.waitForTask(slot.taskId, callContext);
1401
+ const taskId = slot.taskId;
1402
+ const result = (resultContext) => readResult(name, key, taskId, resultContext);
1403
+ return options.wait === false ? { taskId, result } : result(callContext);
1404
+ }
1405
+ async function readResult(name, key, taskId, callContext) {
1406
+ assertLive();
1407
+ const settled = await runtime.waitForTask(taskId, callContext);
1293
1408
  const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
1294
1409
  await runtime.commit(async (tx) => {
1295
1410
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
@@ -1297,7 +1412,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
1297
1412
  return;
1298
1413
  }, callContext);
1299
1414
  return result === undefined ? {
1300
- taskId: slot.taskId,
1415
+ taskId,
1301
1416
  isError: true,
1302
1417
  diagnostics: [
1303
1418
  {
@@ -1307,9 +1422,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
1307
1422
  }
1308
1423
  ]
1309
1424
  } : copyJson3(result);
1310
- };
1425
+ }
1311
1426
  return {
1312
1427
  execute,
1428
+ async drain() {
1429
+ await Promise.allSettled(admissions);
1430
+ },
1313
1431
  async finish() {
1314
1432
  await Promise.allSettled(admissions);
1315
1433
  await cleanupNativeCalls(runtime, withoutAbortSignal(context));
@@ -1317,11 +1435,11 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
1317
1435
  };
1318
1436
  }
1319
1437
  async function cleanupNativeCalls(runtime, context) {
1320
- await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
1438
+ await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
1321
1439
  await runtime.commit(async (tx) => {
1322
1440
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
1323
1441
  await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
1324
- const live = await tx.doc(LiveDoc2, runtime.conversationId);
1442
+ const live = await tx.doc(LiveDoc3, runtime.conversationId);
1325
1443
  const removed = new Set([runtime.taskId]);
1326
1444
  for (const slot of live.nestedTools ?? [])
1327
1445
  if (removed.has(slot.parentTaskId))
@@ -1411,18 +1529,6 @@ class Progress {
1411
1529
  }
1412
1530
  }
1413
1531
 
1414
- // packages/execution/src/tool-origin.ts
1415
- import {
1416
- defineDoc as defineDoc2
1417
- } from "@earendil-works/pi-durable";
1418
- var ToolOriginDoc = defineDoc2({
1419
- kind: "howaboua.tool-origin",
1420
- version: 1,
1421
- scope: "task",
1422
- checkpointWhen: () => false,
1423
- initial: () => ({})
1424
- });
1425
-
1426
1532
  // packages/execution/src/invocation.ts
1427
1533
  function executionError(code, message) {
1428
1534
  return {
@@ -1434,21 +1540,23 @@ function executionError(code, message) {
1434
1540
  function errorText(error) {
1435
1541
  return error instanceof Error ? error.message : String(error);
1436
1542
  }
1437
- function createInvocation(runtime, tool, context) {
1543
+ function createInvocation(runtime, tool, context, resume) {
1438
1544
  const limits = {
1439
1545
  maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
1440
1546
  maxLines: tool.outputLimits?.maxLines ?? 2000,
1441
1547
  retain: tool.outputLimits?.retain ?? "head"
1442
1548
  };
1443
1549
  const output = new OutputBuffer(limits);
1444
- const diagnostics = [];
1445
- let details;
1550
+ const diagnostics = [
1551
+ ...resume?.progress?.diagnostics ?? []
1552
+ ];
1553
+ let details = resume?.progress?.details;
1446
1554
  let ended = false;
1447
1555
  const assertLive = () => {
1448
1556
  if (ended)
1449
1557
  throw new Error(`Invocation ${runtime.taskId} has settled`);
1450
1558
  };
1451
- const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
1559
+ const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
1452
1560
  const snapshot = () => {
1453
1561
  const retained = output.snapshot();
1454
1562
  return {
@@ -1477,6 +1585,8 @@ function createInvocation(runtime, tool, context) {
1477
1585
  taskId: runtime.taskId,
1478
1586
  conversationId: runtime.conversationId,
1479
1587
  callId: `nested-${runtime.taskId}`,
1588
+ wake: resume?.wake,
1589
+ checkpoint: resume?.checkpoint,
1480
1590
  registry: runtime.registry,
1481
1591
  agent: runtime.agent,
1482
1592
  env: undefined,
@@ -1497,7 +1607,7 @@ function createInvocation(runtime, tool, context) {
1497
1607
  const retained = output.snapshot();
1498
1608
  return { text: retained.text, truncated: retained.droppedBytes > 0 };
1499
1609
  },
1500
- executeTool: (...args) => native.execute(...args),
1610
+ executeTool: native.execute,
1501
1611
  diagnostic: (value) => {
1502
1612
  assertLive();
1503
1613
  diagnostics.push(copyJson4(value, { omitUndefinedProperties: true }));
@@ -1511,24 +1621,44 @@ function createInvocation(runtime, tool, context) {
1511
1621
  committed.catch(() => {});
1512
1622
  await awaitWithContext(committed, detailContext);
1513
1623
  },
1514
- commit: async (change, commitContext) => {
1624
+ commit: async (change, commitContext, options) => {
1515
1625
  assertLive();
1516
1626
  let result;
1517
1627
  await runtime.commit(async (tx) => {
1518
1628
  result = await change(tx);
1519
1629
  return;
1520
- }, commitContext);
1630
+ }, commitContext, options);
1521
1631
  return result;
1522
1632
  },
1523
1633
  memo: runtime.memo,
1524
- createTask: async (task, input, options, taskContext) => {
1634
+ readSignal: runtime.readSignal,
1635
+ async createTask(task, input, {
1636
+ key,
1637
+ ...options
1638
+ }, taskContext) {
1525
1639
  assertLive();
1640
+ if (key !== undefined)
1641
+ assertNestedKey(key);
1642
+ else if (resume?.wake !== undefined)
1643
+ throw new Error("Child tasks require an explicit key after waking");
1526
1644
  let id;
1527
1645
  await runtime.commit(async (tx) => {
1646
+ const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
1647
+ if (member?.taskId !== undefined) {
1648
+ const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
1649
+ if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson4(input, { omitUndefinedProperties: true })))
1650
+ throw new Error(`Key ${key} was already used for another call or task`);
1651
+ id = member.taskId;
1652
+ return;
1653
+ }
1528
1654
  id = await tx.createTask(task, input, {
1529
1655
  ...options,
1530
1656
  ...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
1531
1657
  });
1658
+ if (member !== undefined) {
1659
+ member.kind = "task";
1660
+ member.taskId = id;
1661
+ }
1532
1662
  const source = await tx.doc(ToolOriginDoc, runtime.taskId);
1533
1663
  if (source.origin !== undefined)
1534
1664
  (await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
@@ -1575,6 +1705,14 @@ function createInvocation(runtime, tool, context) {
1575
1705
  for (const waiter of await progress.stop())
1576
1706
  waiter.reject(error);
1577
1707
  },
1708
+ async park() {
1709
+ ended = true;
1710
+ await native.drain();
1711
+ output.end();
1712
+ const pending = await progress.stop();
1713
+ const { output: _output, ...kept } = snapshot();
1714
+ return { progress: storeResult(kept), pending };
1715
+ },
1578
1716
  limits,
1579
1717
  output,
1580
1718
  progress
@@ -1608,12 +1746,22 @@ function truncation(dropped, retain) {
1608
1746
  // packages/execution/src/nested-call.ts
1609
1747
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1610
1748
  import {
1611
- ToolTask as ToolTask3
1749
+ ToolTask as ToolTask4
1612
1750
  } from "@earendil-works/pi-durable";
1613
1751
  import { compile } from "@earendil-works/pi-schema";
1614
1752
 
1615
1753
  // packages/execution/src/tool-contract.ts
1616
- import { copyJson as copyJson5 } from "@earendil-works/chord";
1754
+ import { copyJson as copyJson5 } from "@earendil-works/chord/json";
1755
+
1756
+ // packages/execution/src/tool-namespaces.ts
1757
+ import { isJsonValue } from "@earendil-works/chord/json";
1758
+ function validateJsToolNamespace(tool, namespace) {
1759
+ const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
1760
+ if (!namespace || !key(namespace.name) || typeof namespace.prompt !== "string" || !namespace.prompt.trim() || !Array.isArray(namespace.methods) || !namespace.methods.length || namespace.methods.some((method) => !method || !key(method.name) || method.bind !== undefined && !key(method.bind) || method.defaults !== undefined && (!method.defaults || typeof method.defaults !== "object" || Array.isArray(method.defaults) || !isJsonValue(method.defaults))))
1761
+ throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
1762
+ }
1763
+
1764
+ // packages/execution/src/tool-contract.ts
1617
1765
  function readToolContract(tool) {
1618
1766
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
1619
1767
  if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
@@ -1627,6 +1775,7 @@ function readToolContract(tool) {
1627
1775
  "yieldTimeMs",
1628
1776
  "inputSchema",
1629
1777
  "nativeOnly",
1778
+ "nestedHidden",
1630
1779
  "discovery"
1631
1780
  ]);
1632
1781
  for (const key of Object.keys(hints))
@@ -1650,6 +1799,12 @@ function readToolContract(tool) {
1650
1799
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1651
1800
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1652
1801
  throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
1802
+ const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
1803
+ const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
1804
+ if (jsNamespace !== undefined)
1805
+ validateJsToolNamespace(tool.name, jsNamespace);
1806
+ if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
1807
+ throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
1653
1808
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1654
1809
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1655
1810
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1666,6 +1821,8 @@ function readToolContract(tool) {
1666
1821
  inputSchema,
1667
1822
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1668
1823
  nativeOnly: nativeOnly === true,
1824
+ nestedHidden: nestedHidden === true,
1825
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1669
1826
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1670
1827
  ...outputHint === undefined ? {} : { output: outputHint },
1671
1828
  help: [
@@ -1722,7 +1879,7 @@ function prepareNestedInput(tool, input) {
1722
1879
  async function eachHook(agent, name, api, invoke) {
1723
1880
  for (const extension of agent.extensions)
1724
1881
  for (const registration of extension.hooks ?? []) {
1725
- if (registration.task !== ToolTask3.definition.name)
1882
+ if (registration.task !== ToolTask4.definition.name)
1726
1883
  continue;
1727
1884
  const handler = registration.handlers[name];
1728
1885
  if (handler === undefined)
@@ -1737,8 +1894,120 @@ async function eachHook(agent, name, api, invoke) {
1737
1894
  }
1738
1895
  }
1739
1896
 
1897
+ // packages/execution/src/nested-park.ts
1898
+ import {
1899
+ withCancel,
1900
+ withoutAbortSignal as withoutAbortSignal2
1901
+ } from "@earendil-works/chord/context";
1902
+ import { copyJson as copyJson6 } from "@earendil-works/chord/json";
1903
+ var resultFields = [
1904
+ "output",
1905
+ "structuredOutput",
1906
+ "isError",
1907
+ "details",
1908
+ "diagnostics",
1909
+ "usage",
1910
+ "control"
1911
+ ];
1912
+ function sleepState(checkpoint, { until, signals }) {
1913
+ return {
1914
+ status: "sleeping",
1915
+ checkpoint,
1916
+ ...until === undefined ? {} : { until },
1917
+ ...signals === undefined ? {} : { signals }
1918
+ };
1919
+ }
1920
+ async function parkGate(runtime, sleep, context) {
1921
+ try {
1922
+ await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
1923
+ } catch (error) {
1924
+ runtime.signal.throwIfAborted();
1925
+ return errorText(error);
1926
+ }
1927
+ }
1928
+ async function parkTool(runtime, invocation, tool, args, park, context) {
1929
+ if (park.kind !== "sleep" && park.kind !== "wait")
1930
+ return "Unknown park kind";
1931
+ const mixed = resultFields.find((field) => (field in park));
1932
+ if (mixed !== undefined)
1933
+ return `A park cannot carry the result field ${mixed}`;
1934
+ const intent = {
1935
+ arguments: args,
1936
+ replay: tool.replay ?? "unsafe",
1937
+ ...park.checkpoint === undefined ? {} : { checkpoint: copyJson6(park.checkpoint) }
1938
+ };
1939
+ const { progress, pending } = await invocation.park();
1940
+ try {
1941
+ await runtime.commit(async (tx) => {
1942
+ if (park.kind === "wait") {
1943
+ for (const id of park.on)
1944
+ if ((await tx.task(id))?.owner !== runtime.taskId)
1945
+ throw new Error(`Task ${id} is not owned by the call`);
1946
+ }
1947
+ const checkpoint = { ...intent, phase: "parked" };
1948
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1949
+ doc.result = progress;
1950
+ doc.droppedBytes = 0;
1951
+ doc.droppedLines = 0;
1952
+ await forwardInvocationResult(tx, runtime.taskId, progress, "running");
1953
+ return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
1954
+ }, context);
1955
+ } catch (error) {
1956
+ for (const waiter of pending)
1957
+ waiter.reject(error);
1958
+ const detached = withoutAbortSignal2(context);
1959
+ const record = await runtime.getTask(runtime.taskId, detached);
1960
+ if (record?.abortRequested) {
1961
+ const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
1962
+ if (watch !== undefined) {
1963
+ const cleanup = withCancel(detached);
1964
+ watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
1965
+ try {
1966
+ await cancelParkedTool(runtime, tool, intent, cleanup.context);
1967
+ } finally {
1968
+ await watch.stop();
1969
+ }
1970
+ }
1971
+ throw error;
1972
+ }
1973
+ runtime.signal.throwIfAborted();
1974
+ return errorText(error);
1975
+ }
1976
+ for (const waiter of pending)
1977
+ waiter.resolve();
1978
+ }
1979
+ async function cancelParkedTool(runtime, tool, intent, context) {
1980
+ if (!tool) {
1981
+ runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
1982
+ return;
1983
+ }
1984
+ if (tool.cancel === undefined)
1985
+ return;
1986
+ const cleanup = createInvocation(runtime, tool, context, {
1987
+ checkpoint: intent.checkpoint,
1988
+ wake: undefined
1989
+ });
1990
+ const refuseWork = () => {
1991
+ throw new Error("A tool cannot start tasks or nested calls during cancellation");
1992
+ };
1993
+ let reason = new Error("Tool cancellation finished");
1994
+ try {
1995
+ const api = await cleanup.executionApi();
1996
+ await tool.cancel(intent.arguments, {
1997
+ ...api,
1998
+ createTask: refuseWork,
1999
+ executeTool: refuseWork
2000
+ }, context);
2001
+ } catch (error) {
2002
+ reason = error;
2003
+ runtime.report(error);
2004
+ } finally {
2005
+ await cleanup.stop(reason);
2006
+ }
2007
+ }
2008
+
1740
2009
  // packages/execution/src/nested-result.ts
1741
- import { copyJson as copyJson6 } from "@earendil-works/chord";
2010
+ import { copyJson as copyJson7 } from "@earendil-works/chord/json";
1742
2011
  import {
1743
2012
  defineEntry,
1744
2013
  UsageDoc
@@ -1786,11 +2055,11 @@ async function settle(runtime, call, result, ending, context) {
1786
2055
  taskId: runtime.taskId,
1787
2056
  callId: call.id,
1788
2057
  name: call.name,
1789
- arguments: copyJson6(call.arguments),
2058
+ arguments: copyJson7(call.arguments),
1790
2059
  result: stored,
1791
2060
  ...current.state.checkpoint.phase === "execute" ? {
1792
2061
  intent: {
1793
- arguments: copyJson6(current.state.checkpoint.arguments),
2062
+ arguments: copyJson7(current.state.checkpoint.arguments),
1794
2063
  replay: current.state.checkpoint.replay
1795
2064
  }
1796
2065
  } : {}
@@ -1799,7 +2068,7 @@ async function settle(runtime, call, result, ending, context) {
1799
2068
  if (result.usage !== undefined) {
1800
2069
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1801
2070
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1802
- totals[call.name] = copyJson6(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
2071
+ totals[call.name] = copyJson7(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1803
2072
  }
1804
2073
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1805
2074
  status: ending,
@@ -1836,7 +2105,11 @@ function sumUsage(previous, added) {
1836
2105
  function createNestedToolTask(name) {
1837
2106
  return defineTask({
1838
2107
  name,
1839
- version: 1,
2108
+ version: 2,
2109
+ migrate: (input, checkpoint) => ({
2110
+ input,
2111
+ checkpoint
2112
+ }),
1840
2113
  initial: () => ({ phase: "call" }),
1841
2114
  phases: {
1842
2115
  call: async (task, runtime, context) => {
@@ -1871,13 +2144,16 @@ function createNestedToolTask(name) {
1871
2144
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1872
2145
  }
1873
2146
  let block;
2147
+ let sleep;
1874
2148
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1875
- if (block !== undefined)
2149
+ if (block !== undefined || sleep !== undefined)
1876
2150
  return;
1877
2151
  try {
1878
2152
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1879
2153
  if (decision?.block !== undefined)
1880
2154
  block = decision.block;
2155
+ else if (decision?.sleep !== undefined)
2156
+ sleep = decision.sleep;
1881
2157
  else if (decision?.arguments !== undefined)
1882
2158
  args = decision.arguments;
1883
2159
  } catch (error) {
@@ -1888,71 +2164,122 @@ function createNestedToolTask(name) {
1888
2164
  });
1889
2165
  if (block !== undefined)
1890
2166
  return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
2167
+ if (sleep !== undefined) {
2168
+ const reason = await parkGate(runtime, sleep, context);
2169
+ if (reason === undefined)
2170
+ return;
2171
+ return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
2172
+ }
1891
2173
  try {
1892
- args = checked(tool, call, args);
2174
+ args = copyJson8(checked(tool, call, args), {
2175
+ omitUndefinedProperties: true
2176
+ });
1893
2177
  } catch (error) {
1894
2178
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1895
2179
  }
1896
- await runtime.commit(async (tx) => {
1897
- await tx.doc(InvocationDoc, runtime.taskId);
1898
- await forwardCall(tx, task.input.cellId, {
1899
- callId: call.id,
1900
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1901
- name: call.name,
1902
- arguments: args,
1903
- status: "running",
1904
- result: null,
1905
- omittedFields: []
1906
- });
1907
- return {
1908
- status: "running",
1909
- checkpoint: {
1910
- phase: "execute",
1911
- arguments: args,
1912
- replay: tool.replay ?? "unsafe"
1913
- }
1914
- };
2180
+ await startAttempt(runtime, call, tool, agent, {
2181
+ arguments: args,
2182
+ replay: tool.replay ?? "unsafe"
1915
2183
  }, context);
1916
- await run(runtime, call, tool, args, agent, context);
2184
+ },
2185
+ parked: async (task, runtime, context) => {
2186
+ const intent = task.state.checkpoint;
2187
+ const call = nestedCall(runtime, task.input);
2188
+ call.arguments = intent.arguments;
2189
+ const agent = await runtime.agent(context);
2190
+ const tool = agent.callable.find((each) => each.name === call.name);
2191
+ if (tool === undefined || readToolContract(tool).nativeOnly)
2192
+ return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
2193
+ await startAttempt(runtime, call, tool, agent, {
2194
+ ...intent,
2195
+ replay: tool.replay ?? "unsafe"
2196
+ }, context, task.state.wake);
1917
2197
  },
1918
2198
  execute: async (task, runtime, context) => {
2199
+ const intent = task.state.checkpoint;
1919
2200
  const call = nestedCall(runtime, task.input);
1920
2201
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1921
2202
  call.arguments = task.state.checkpoint.arguments;
1922
2203
  const agent = await runtime.agent(context);
1923
2204
  const tool = agent.callable.find((each) => each.name === call.name);
1924
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1925
- await runtime.commit(async (tx) => {
1926
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1927
- doc.result = {};
1928
- doc.droppedBytes = 0;
1929
- doc.droppedLines = 0;
1930
- return;
1931
- }, context);
1932
- return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
2205
+ if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
2206
+ if (intent.resume === undefined)
2207
+ await runtime.commit(async (tx) => {
2208
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
2209
+ doc.result = {};
2210
+ doc.droppedBytes = 0;
2211
+ doc.droppedLines = 0;
2212
+ return;
2213
+ }, context);
2214
+ return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
1933
2215
  }
2216
+ if (intent.resume !== undefined)
2217
+ await cancelParkedTool(runtime, tool, intent, context);
1934
2218
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1935
2219
  }
1936
2220
  },
1937
2221
  abort: async (task, runtime, context) => {
1938
2222
  const call = nestedCall(runtime, task.input);
2223
+ const intent = task.state.checkpoint;
2224
+ if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
2225
+ const agent = await runtime.agent(context);
2226
+ const tool = agent.callable.find((each) => each.name === call.name);
2227
+ await cancelParkedTool(runtime, tool, intent, context);
2228
+ }
1939
2229
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1940
2230
  }
1941
2231
  });
1942
2232
  }
2233
+ async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
2234
+ await runtime.commit(async (tx) => {
2235
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
2236
+ await forwardCall(tx, doc.forwardingCellId, {
2237
+ callId: call.id,
2238
+ parentCallId: call.parent?.callId ?? call.id,
2239
+ name: call.name,
2240
+ arguments: intent.arguments,
2241
+ status: "running",
2242
+ result: null,
2243
+ omittedFields: []
2244
+ });
2245
+ return {
2246
+ status: "running",
2247
+ checkpoint: {
2248
+ ...intent,
2249
+ phase: "execute",
2250
+ ...wake === undefined ? {} : { resume: { wake } }
2251
+ }
2252
+ };
2253
+ }, context);
2254
+ await run(runtime, call, tool, intent, agent, context, wake);
2255
+ }
1943
2256
  async function reject(runtime, call, result, agent, tool, context) {
1944
2257
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1945
2258
  result = await handler(call, result, runtime, context) ?? result;
1946
2259
  });
1947
2260
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1948
2261
  }
1949
- async function run(runtime, call, tool, args, agent, context) {
2262
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1950
2263
  let invocation;
1951
2264
  let result;
1952
2265
  let ending = "completed";
1953
2266
  try {
1954
- invocation = createInvocation(runtime, tool, context);
1955
- result = await tool.execute(args, await invocation.executionApi(), context);
2267
+ const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
2268
+ invocation = createInvocation(runtime, tool, context, {
2269
+ wake,
2270
+ checkpoint: intent.checkpoint,
2271
+ ...previous === undefined ? {} : { progress: previous.result }
2272
+ });
2273
+ const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
2274
+ if (returned.kind === undefined)
2275
+ result = returned;
2276
+ else {
2277
+ const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
2278
+ if (reason === undefined)
2279
+ return;
2280
+ result = executionError("invalid_park", reason);
2281
+ ending = "failed";
2282
+ }
1956
2283
  } catch (error) {
1957
2284
  if (runtime.signal.aborted) {
1958
2285
  await invocation?.stop(error);
@@ -2025,83 +2352,6 @@ function finishResult(tool, name, result) {
2025
2352
  return final;
2026
2353
  }
2027
2354
 
2028
- // packages/gippity-voice/src/agent-observation.ts
2029
- import {
2030
- LiveDoc as LiveDoc3
2031
- } from "@earendil-works/pi-durable";
2032
- async function observeVoiceAgent(conversation, context, callbacks) {
2033
- const watch = await conversation.watch(context);
2034
- let newest = watch.value.entries.at(-1)?.id ?? watch.value.before;
2035
- let previous = liveState(watch.value);
2036
- let text = "";
2037
- let stopped = false;
2038
- let work = Promise.resolve();
2039
- callbacks.state(Boolean(previous.run));
2040
- async function advance(view) {
2041
- if (stopped)
2042
- return;
2043
- const live = liveState(view);
2044
- if (live.run)
2045
- callbacks.state(true);
2046
- const upTo = view.entries.at(-1)?.id;
2047
- if (upTo !== undefined && (newest === undefined || upTo > newest)) {
2048
- const from = newest;
2049
- let cursor;
2050
- do {
2051
- const page = await conversation.entries({
2052
- ...from === undefined ? {} : { minEntryId: from },
2053
- maxEntryId: upTo,
2054
- order: "ascending"
2055
- }, 128, cursor, context);
2056
- if (stopped)
2057
- return;
2058
- for (const entry of page.items) {
2059
- if (newest !== undefined && entry.id <= newest)
2060
- continue;
2061
- callbacks.entry(entry);
2062
- newest = entry.id;
2063
- }
2064
- cursor = page.next;
2065
- } while (cursor);
2066
- }
2067
- const partial = live.generation?.message;
2068
- const nextText = partial?.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
2069
- `) ?? "";
2070
- if (previous.run?.taskId !== live.run?.taskId || previous.generation?.attempt !== live.generation?.attempt || !nextText.startsWith(text))
2071
- text = "";
2072
- callbacks.partial(nextText.slice(text.length), Boolean(partial?.content.some((part) => part.type === "thinking" || part.type === "toolCall")));
2073
- text = nextText;
2074
- for (const compact of live.compactions ?? []) {
2075
- if (compact.trigger !== "manual" && !previous.compactions?.some((old) => old.taskId === compact.taskId))
2076
- callbacks.compacting(compact.trigger === "overflow" ? "overflow" : "threshold");
2077
- }
2078
- if (!live.run)
2079
- callbacks.state(false);
2080
- previous = live;
2081
- }
2082
- watch.start((call) => {
2083
- work = call.kind === "failed" ? Promise.reject(call.error) : advance(call.value);
2084
- return work;
2085
- });
2086
- watch.closed.then((end) => {
2087
- if (end.kind === "failed" || end.kind === "listener_error")
2088
- callbacks.failed(end.error);
2089
- });
2090
- return {
2091
- get view() {
2092
- return watch.value;
2093
- },
2094
- async stop() {
2095
- stopped = true;
2096
- await watch.stop();
2097
- await work;
2098
- }
2099
- };
2100
- }
2101
- function liveState(view) {
2102
- return view.docs[LiveDoc3.definition.kind] ?? {};
2103
- }
2104
-
2105
2355
  // packages/gippity-voice/src/preferences.ts
2106
2356
  function object(value, path) {
2107
2357
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -2190,6 +2440,246 @@ function changedGippityPreferences(current, next, target) {
2190
2440
  return validateGippityPreferences(result);
2191
2441
  }
2192
2442
 
2443
+ // packages/gippity-voice/src/voice/handoff-wire.ts
2444
+ class VoiceHandoffLink {
2445
+ pending = new Map;
2446
+ stages = new Map;
2447
+ stageWaiters = new Map;
2448
+ sequence = 0;
2449
+ failure;
2450
+ removeMessage;
2451
+ removeClose;
2452
+ channel;
2453
+ handlers;
2454
+ constructor(channel, handlers) {
2455
+ this.channel = channel;
2456
+ this.handlers = handlers;
2457
+ this.removeMessage = channel.onMessage((message) => {
2458
+ try {
2459
+ this.receive(message);
2460
+ } catch (error) {
2461
+ this.fail(asError(error));
2462
+ }
2463
+ });
2464
+ this.removeClose = channel.onClose((error) => this.finish(error));
2465
+ if (this.failure) {
2466
+ this.removeMessage();
2467
+ this.removeClose();
2468
+ }
2469
+ }
2470
+ get closed() {
2471
+ return this.failure !== undefined;
2472
+ }
2473
+ request(method, value) {
2474
+ if (this.failure)
2475
+ return Promise.reject(this.failure);
2476
+ if (this.pending.size >= 32)
2477
+ return Promise.reject(new Error("Too many pending voice controls"));
2478
+ const id = ++this.sequence;
2479
+ return new Promise((resolve, reject) => {
2480
+ const timer = setTimeout(() => {
2481
+ this.pending.delete(id);
2482
+ const error = new Error("Voice control did not respond");
2483
+ reject(error);
2484
+ this.fail(error);
2485
+ }, method === "session.start" ? 120000 : 30000);
2486
+ this.pending.set(id, { resolve, reject, timer });
2487
+ try {
2488
+ this.send({ type: "request", id, method, value });
2489
+ } catch (error) {
2490
+ this.fail(asError(error));
2491
+ }
2492
+ });
2493
+ }
2494
+ notify(message) {
2495
+ this.send(message);
2496
+ }
2497
+ stage(stage, value) {
2498
+ this.send({ type: "stage", stage, value });
2499
+ }
2500
+ waitFor(stage) {
2501
+ if (this.failure)
2502
+ return Promise.reject(this.failure);
2503
+ if (this.stages.has(stage))
2504
+ return Promise.resolve(this.stages.get(stage));
2505
+ if (this.stageWaiters.has(stage))
2506
+ return Promise.reject(new Error("Voice transfer stage already awaited"));
2507
+ return new Promise((resolve, reject) => {
2508
+ const timer = setTimeout(() => {
2509
+ this.stageWaiters.delete(stage);
2510
+ const error = new Error("Voice transfer did not finish preparing");
2511
+ reject(error);
2512
+ this.fail(error);
2513
+ }, 120000);
2514
+ this.stageWaiters.set(stage, { resolve, reject, timer });
2515
+ });
2516
+ }
2517
+ close() {
2518
+ this.fail(new Error("Voice connection closed"));
2519
+ }
2520
+ fail(error) {
2521
+ if (this.failure)
2522
+ return;
2523
+ try {
2524
+ this.channel.send({
2525
+ type: "failure",
2526
+ message: error.message.slice(0, 4000)
2527
+ });
2528
+ } catch {}
2529
+ this.finish(error);
2530
+ this.channel.close();
2531
+ }
2532
+ send(message) {
2533
+ if (this.failure)
2534
+ throw this.failure;
2535
+ try {
2536
+ this.channel.send(message);
2537
+ } catch (error) {
2538
+ this.fail(asError(error));
2539
+ throw error;
2540
+ }
2541
+ }
2542
+ finish(error) {
2543
+ if (this.failure)
2544
+ return;
2545
+ this.failure = error;
2546
+ this.removeMessage?.();
2547
+ this.removeClose?.();
2548
+ for (const pending of [
2549
+ ...this.pending.values(),
2550
+ ...this.stageWaiters.values()
2551
+ ]) {
2552
+ clearTimeout(pending.timer);
2553
+ pending.reject(error);
2554
+ }
2555
+ this.pending.clear();
2556
+ this.stageWaiters.clear();
2557
+ this.handlers.closed(error);
2558
+ }
2559
+ receive(value) {
2560
+ if (this.failure)
2561
+ return;
2562
+ if (!isRecord(value))
2563
+ throw new Error("Invalid voice transfer frame");
2564
+ if (value["type"] === "failure" && typeof value["message"] === "string") {
2565
+ this.finish(new Error(value["message"].slice(0, 4000)));
2566
+ this.channel.close();
2567
+ return;
2568
+ }
2569
+ if (value["type"] === "stage" && isStage(value["stage"])) {
2570
+ this.stages.set(value["stage"], value["value"]);
2571
+ const waiter = this.stageWaiters.get(value["stage"]);
2572
+ if (waiter) {
2573
+ clearTimeout(waiter.timer);
2574
+ this.stageWaiters.delete(value["stage"]);
2575
+ waiter.resolve(value["value"]);
2576
+ }
2577
+ return;
2578
+ }
2579
+ if ((value["type"] === "request" || value["type"] === "reply") && typeof value["id"] === "number" && Number.isSafeInteger(value["id"]) && value["id"] > 0) {
2580
+ const id = value["id"];
2581
+ if (value["type"] === "reply") {
2582
+ if (typeof value["ok"] !== "boolean" || !value["ok"] && typeof value["error"] !== "string")
2583
+ throw new Error("Invalid voice control reply");
2584
+ const pending = this.pending.get(id);
2585
+ if (!pending)
2586
+ return;
2587
+ clearTimeout(pending.timer);
2588
+ this.pending.delete(id);
2589
+ if (value["ok"])
2590
+ pending.resolve(value["value"]);
2591
+ else
2592
+ pending.reject(new Error(String(value["error"])));
2593
+ return;
2594
+ }
2595
+ const method = value["method"];
2596
+ if (!isRequestMethod(method))
2597
+ throw new Error("Invalid voice control request");
2598
+ this.handlers.request(method, value["value"]).then((result) => {
2599
+ if (!this.failure)
2600
+ this.send({ type: "reply", id, ok: true, value: result });
2601
+ }, (error) => {
2602
+ if (!this.failure)
2603
+ this.send({
2604
+ type: "reply",
2605
+ id,
2606
+ ok: false,
2607
+ error: asError(error).message
2608
+ });
2609
+ }).catch((error) => this.fail(asError(error)));
2610
+ return;
2611
+ }
2612
+ const generation = value["generation"];
2613
+ const validGeneration = typeof generation === "number" && Number.isSafeInteger(generation) && generation > 0;
2614
+ if (value["type"] === "peer.command" && typeof value["command"] === "string" && validGeneration) {
2615
+ this.handlers.notification({
2616
+ type: "peer.command",
2617
+ generation,
2618
+ command: value["command"],
2619
+ value: value["value"]
2620
+ });
2621
+ return;
2622
+ }
2623
+ if (value["type"] === "peer.event" && validGeneration) {
2624
+ this.handlers.notification({
2625
+ type: "peer.event",
2626
+ generation,
2627
+ event: value["event"]
2628
+ });
2629
+ return;
2630
+ }
2631
+ if (value["type"] === "session.event" && typeof value["event"] === "string" && value["event"].length <= 64) {
2632
+ this.handlers.notification({
2633
+ type: "session.event",
2634
+ event: value["event"],
2635
+ data: value["data"]
2636
+ });
2637
+ return;
2638
+ }
2639
+ if (value["type"] === "session.mute" && typeof value["muted"] === "boolean") {
2640
+ this.handlers.notification({
2641
+ type: "session.mute",
2642
+ muted: value["muted"]
2643
+ });
2644
+ return;
2645
+ }
2646
+ throw new Error("Invalid voice transfer frame");
2647
+ }
2648
+ }
2649
+ function isRecord(value) {
2650
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
2651
+ }
2652
+ function asError(error) {
2653
+ return error instanceof Error ? error : new Error(String(error));
2654
+ }
2655
+ function isStage(value) {
2656
+ return value === "prepared" || value === "activate" || value === "active";
2657
+ }
2658
+ function isRequestMethod(value) {
2659
+ return value === "lan.verify" || value === "browser.verify" || value === "session.stop" || value === "session.start" || value === "peer.start" || value === "peer.close" || value === "peer.finish" || value === "session.send" || value === "session.rpc";
2660
+ }
2661
+
2662
+ // packages/gippity-voice/src/voice/browser-reservation.ts
2663
+ function prepareBrowserReservation(reservation, context) {
2664
+ const handle = {};
2665
+ let path;
2666
+ return {
2667
+ handle,
2668
+ async verify(proof) {
2669
+ if (!isRecord(proof) || typeof proof["port"] !== "number" || typeof proof["token"] !== "string")
2670
+ throw new Error("Invalid browser listener proof");
2671
+ const offer = await reservation.offerBrowserArrival({ port: proof["port"], token: proof["token"] }, handle, context);
2672
+ path = offer.path;
2673
+ return offer;
2674
+ },
2675
+ async activate(value) {
2676
+ if (!path || value !== path)
2677
+ throw new Error("Unconfirmed browser arrival");
2678
+ await reservation.activate(context);
2679
+ }
2680
+ };
2681
+ }
2682
+
2193
2683
  // packages/gippity-voice/src/voice/context.ts
2194
2684
  import { createHash } from "node:crypto";
2195
2685
  var SUMMARY_CACHE_LIMIT = 32;
@@ -4293,11 +4783,15 @@ class CodexRealtimeConversation {
4293
4783
  this.turns.handoff.clear();
4294
4784
  this.callbacks.onEndCall?.();
4295
4785
  }
4786
+ get playbackSealed() {
4787
+ return this.peer.playbackSealed === true;
4788
+ }
4296
4789
  get isEndingCall() {
4297
4790
  return this.ending;
4298
4791
  }
4299
- waitForFinalPlayback() {
4300
- return this.waitForPlaybackEnd(this.closing.signal, this.endingOutput);
4792
+ async waitForFinalPlayback() {
4793
+ await this.waitForPlaybackEnd(this.closing.signal, this.endingOutput);
4794
+ await this.peer.finishPlayback?.(this.closing.signal);
4301
4795
  }
4302
4796
  waitForPlaybackEnd(signal, minimumOutputs = 0) {
4303
4797
  signal.throwIfAborted();
@@ -4590,227 +5084,8 @@ function ownVoiceGrant(grant) {
4590
5084
  };
4591
5085
  }
4592
5086
 
4593
- // packages/gippity-voice/src/voice/handoff-wire.ts
4594
- class VoiceHandoffLink {
4595
- pending = new Map;
4596
- stages = new Map;
4597
- stageWaiters = new Map;
4598
- sequence = 0;
4599
- failure;
4600
- removeMessage;
4601
- removeClose;
4602
- channel;
4603
- handlers;
4604
- constructor(channel, handlers) {
4605
- this.channel = channel;
4606
- this.handlers = handlers;
4607
- this.removeMessage = channel.onMessage((message) => {
4608
- try {
4609
- this.receive(message);
4610
- } catch (error) {
4611
- this.fail(asError(error));
4612
- }
4613
- });
4614
- this.removeClose = channel.onClose((error) => this.finish(error));
4615
- if (this.failure) {
4616
- this.removeMessage();
4617
- this.removeClose();
4618
- }
4619
- }
4620
- get closed() {
4621
- return this.failure !== undefined;
4622
- }
4623
- request(method, value) {
4624
- if (this.failure)
4625
- return Promise.reject(this.failure);
4626
- if (this.pending.size >= 32)
4627
- return Promise.reject(new Error("Too many pending voice controls"));
4628
- const id = ++this.sequence;
4629
- return new Promise((resolve, reject) => {
4630
- const timer = setTimeout(() => {
4631
- this.pending.delete(id);
4632
- const error = new Error("Voice control did not respond");
4633
- reject(error);
4634
- this.fail(error);
4635
- }, method === "session.start" ? 120000 : 30000);
4636
- this.pending.set(id, { resolve, reject, timer });
4637
- try {
4638
- this.send({ type: "request", id, method, value });
4639
- } catch (error) {
4640
- this.fail(asError(error));
4641
- }
4642
- });
4643
- }
4644
- notify(message) {
4645
- this.send(message);
4646
- }
4647
- stage(stage, value) {
4648
- this.send({ type: "stage", stage, value });
4649
- }
4650
- waitFor(stage) {
4651
- if (this.failure)
4652
- return Promise.reject(this.failure);
4653
- if (this.stages.has(stage))
4654
- return Promise.resolve(this.stages.get(stage));
4655
- if (this.stageWaiters.has(stage))
4656
- return Promise.reject(new Error("Voice transfer stage already awaited"));
4657
- return new Promise((resolve, reject) => {
4658
- const timer = setTimeout(() => {
4659
- this.stageWaiters.delete(stage);
4660
- const error = new Error("Voice transfer did not finish preparing");
4661
- reject(error);
4662
- this.fail(error);
4663
- }, 120000);
4664
- this.stageWaiters.set(stage, { resolve, reject, timer });
4665
- });
4666
- }
4667
- close() {
4668
- this.fail(new Error("Voice connection closed"));
4669
- }
4670
- fail(error) {
4671
- if (this.failure)
4672
- return;
4673
- try {
4674
- this.channel.send({
4675
- type: "failure",
4676
- message: error.message.slice(0, 4000)
4677
- });
4678
- } catch {}
4679
- this.finish(error);
4680
- this.channel.close();
4681
- }
4682
- send(message) {
4683
- if (this.failure)
4684
- throw this.failure;
4685
- try {
4686
- this.channel.send(message);
4687
- } catch (error) {
4688
- this.fail(asError(error));
4689
- throw error;
4690
- }
4691
- }
4692
- finish(error) {
4693
- if (this.failure)
4694
- return;
4695
- this.failure = error;
4696
- this.removeMessage?.();
4697
- this.removeClose?.();
4698
- for (const pending of [
4699
- ...this.pending.values(),
4700
- ...this.stageWaiters.values()
4701
- ]) {
4702
- clearTimeout(pending.timer);
4703
- pending.reject(error);
4704
- }
4705
- this.pending.clear();
4706
- this.stageWaiters.clear();
4707
- this.handlers.closed(error);
4708
- }
4709
- receive(value) {
4710
- if (this.failure)
4711
- return;
4712
- if (!isRecord(value))
4713
- throw new Error("Invalid voice transfer frame");
4714
- if (value["type"] === "failure" && typeof value["message"] === "string") {
4715
- this.finish(new Error(value["message"].slice(0, 4000)));
4716
- this.channel.close();
4717
- return;
4718
- }
4719
- if (value["type"] === "stage" && isStage(value["stage"])) {
4720
- this.stages.set(value["stage"], value["value"]);
4721
- const waiter = this.stageWaiters.get(value["stage"]);
4722
- if (waiter) {
4723
- clearTimeout(waiter.timer);
4724
- this.stageWaiters.delete(value["stage"]);
4725
- waiter.resolve(value["value"]);
4726
- }
4727
- return;
4728
- }
4729
- if ((value["type"] === "request" || value["type"] === "reply") && typeof value["id"] === "number" && Number.isSafeInteger(value["id"]) && value["id"] > 0) {
4730
- const id = value["id"];
4731
- if (value["type"] === "reply") {
4732
- if (typeof value["ok"] !== "boolean" || !value["ok"] && typeof value["error"] !== "string")
4733
- throw new Error("Invalid voice control reply");
4734
- const pending = this.pending.get(id);
4735
- if (!pending)
4736
- return;
4737
- clearTimeout(pending.timer);
4738
- this.pending.delete(id);
4739
- if (value["ok"])
4740
- pending.resolve(value["value"]);
4741
- else
4742
- pending.reject(new Error(String(value["error"])));
4743
- return;
4744
- }
4745
- const method = value["method"];
4746
- if (!isRequestMethod(method))
4747
- throw new Error("Invalid voice control request");
4748
- this.handlers.request(method, value["value"]).then((result) => {
4749
- if (!this.failure)
4750
- this.send({ type: "reply", id, ok: true, value: result });
4751
- }, (error) => {
4752
- if (!this.failure)
4753
- this.send({
4754
- type: "reply",
4755
- id,
4756
- ok: false,
4757
- error: asError(error).message
4758
- });
4759
- }).catch((error) => this.fail(asError(error)));
4760
- return;
4761
- }
4762
- const generation = value["generation"];
4763
- const validGeneration = typeof generation === "number" && Number.isSafeInteger(generation) && generation > 0;
4764
- if (value["type"] === "peer.command" && typeof value["command"] === "string" && validGeneration) {
4765
- this.handlers.notification({
4766
- type: "peer.command",
4767
- generation,
4768
- command: value["command"],
4769
- value: value["value"]
4770
- });
4771
- return;
4772
- }
4773
- if (value["type"] === "peer.event" && validGeneration) {
4774
- this.handlers.notification({
4775
- type: "peer.event",
4776
- generation,
4777
- event: value["event"]
4778
- });
4779
- return;
4780
- }
4781
- if (value["type"] === "session.event" && typeof value["event"] === "string" && value["event"].length <= 64) {
4782
- this.handlers.notification({
4783
- type: "session.event",
4784
- event: value["event"],
4785
- data: value["data"]
4786
- });
4787
- return;
4788
- }
4789
- if (value["type"] === "session.mute" && typeof value["muted"] === "boolean") {
4790
- this.handlers.notification({
4791
- type: "session.mute",
4792
- muted: value["muted"]
4793
- });
4794
- return;
4795
- }
4796
- throw new Error("Invalid voice transfer frame");
4797
- }
4798
- }
4799
- function isRecord(value) {
4800
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
4801
- }
4802
- function asError(error) {
4803
- return error instanceof Error ? error : new Error(String(error));
4804
- }
4805
- function isStage(value) {
4806
- return value === "prepared" || value === "activate" || value === "active";
4807
- }
4808
- function isRequestMethod(value) {
4809
- return value === "lan.verify" || value === "session.stop" || value === "session.start" || value === "peer.start" || value === "peer.close" || value === "session.send" || value === "session.rpc";
4810
- }
4811
-
4812
- // packages/gippity-voice/src/voice/handoff-peer.ts
4813
- class HandoffAudioHost {
5087
+ // packages/gippity-voice/src/voice/handoff-peer.ts
5088
+ class HandoffAudioHost {
4814
5089
  sequence = 0;
4815
5090
  current;
4816
5091
  lastPeer;
@@ -4860,12 +5135,18 @@ class HandoffAudioHost {
4860
5135
  this.link.notify({ type: "peer.event", generation, event });
4861
5136
  });
4862
5137
  const removeExit = peer.onExit((error) => this.link.fail(error));
4863
- this.current = { generation, peer, removeEvent, removeExit };
5138
+ this.current = {
5139
+ generation,
5140
+ peer,
5141
+ abort: new AbortController,
5142
+ removeEvent,
5143
+ removeExit
5144
+ };
4864
5145
  this.captured.transferred(peer, this.controls);
4865
5146
  const sdp = await this.captured.start(peer);
4866
5147
  if (this.closed || this.current?.generation !== generation)
4867
5148
  throw new Error("Voice transfer cancelled");
4868
- return { generation, sdp };
5149
+ return { generation, sdp, finishPlayback: true };
4869
5150
  } finally {
4870
5151
  this.starting = false;
4871
5152
  }
@@ -4877,6 +5158,20 @@ class HandoffAudioHost {
4877
5158
  return;
4878
5159
  await this.closeCurrent();
4879
5160
  }
5161
+ async finishPlayback(value) {
5162
+ const owner = this.current;
5163
+ if (!owner || !isRecord(value) || value["generation"] !== owner.generation)
5164
+ throw new Error("Voice playback owner changed");
5165
+ try {
5166
+ await owner.peer.finishPlayback?.(owner.abort.signal);
5167
+ return { sealed: owner.peer.playbackSealed === true };
5168
+ } catch (error) {
5169
+ return {
5170
+ sealed: owner.peer.playbackSealed === true,
5171
+ error: asError(error).message.slice(0, 4000)
5172
+ };
5173
+ }
5174
+ }
4880
5175
  command(message) {
4881
5176
  const current = this.current;
4882
5177
  if (!current || message.generation !== current.generation)
@@ -4897,14 +5192,18 @@ class HandoffAudioHost {
4897
5192
  if (this.closed)
4898
5193
  return;
4899
5194
  this.closed = true;
4900
- await this.closeCurrent();
4901
- await this.captured.finished(this.lastPeer, error);
5195
+ try {
5196
+ await this.closeCurrent();
5197
+ } finally {
5198
+ await this.captured.finished(this.lastPeer, error);
5199
+ }
4902
5200
  }
4903
5201
  async closeCurrent() {
4904
5202
  const current = this.current;
4905
5203
  this.current = undefined;
4906
5204
  if (!current)
4907
5205
  return;
5206
+ current.abort.abort();
4908
5207
  current.removeEvent();
4909
5208
  current.removeExit();
4910
5209
  await current.peer.close();
@@ -4916,6 +5215,8 @@ class HandoffRemotePeer {
4916
5215
  listeners = new Set;
4917
5216
  exitListeners = new Set;
4918
5217
  generation;
5218
+ sealed = false;
5219
+ canFinishPlayback = false;
4919
5220
  starting;
4920
5221
  closed = false;
4921
5222
  link;
@@ -4941,6 +5242,7 @@ class HandoffRemotePeer {
4941
5242
  if (!isRecord(result) || typeof result["generation"] !== "number" || !Number.isSafeInteger(result["generation"]) || result["generation"] <= 0 || !validSdp(result["sdp"]))
4942
5243
  throw new Error("Source audio did not return a valid voice offer");
4943
5244
  this.generation = result["generation"];
5245
+ this.canFinishPlayback = result["finishPlayback"] === true;
4944
5246
  return result["sdp"];
4945
5247
  }
4946
5248
  applyAnswer(sdp) {
@@ -4955,6 +5257,24 @@ class HandoffRemotePeer {
4955
5257
  setSpeakerSuppressed(suppressed) {
4956
5258
  this.command("suppress", suppressed);
4957
5259
  }
5260
+ get playbackSealed() {
5261
+ return this.sealed;
5262
+ }
5263
+ async finishPlayback(signal) {
5264
+ signal.throwIfAborted();
5265
+ if (this.closed || this.generation === undefined)
5266
+ throw new Error("Voice peer is not connected");
5267
+ if (!this.canFinishPlayback)
5268
+ return;
5269
+ const result = await interruptible(this.link.request("peer.finish", { generation: this.generation }), signal);
5270
+ if (result === CANCELLED)
5271
+ throw new Error("Playback wait cancelled");
5272
+ if (!isRecord(result) || typeof result["sealed"] !== "boolean" || result["error"] !== undefined && (typeof result["error"] !== "string" || result["error"].length > 4000))
5273
+ throw new Error("Source audio did not confirm playback completion");
5274
+ this.sealed = result["sealed"];
5275
+ if (typeof result["error"] === "string")
5276
+ throw new Error(result["error"]);
5277
+ }
4958
5278
  command(command, value) {
4959
5279
  if (this.closed)
4960
5280
  return;
@@ -5025,27 +5345,12 @@ function readPeerEvent(value) {
5025
5345
 
5026
5346
  // packages/gippity-voice/src/voice/lan/takeover.ts
5027
5347
  import { randomUUID as randomUUID3, X509Certificate } from "node:crypto";
5348
+
5349
+ // internal/voice/lan-listener-proof.ts
5028
5350
  import { get } from "node:https";
5029
- function prepareLanTakeover(certificate) {
5030
- return {
5031
- certificate,
5032
- offer: {
5033
- certificate: new X509Certificate(certificate.cert).fingerprint256,
5034
- token: randomUUID3()
5035
- }
5036
- };
5037
- }
5038
- function decodeLanTakeoverOffer(value) {
5039
- if (!isRecord(value) || typeof value["certificate"] !== "string" || typeof value["token"] !== "string" || !/^[a-f0-9-]{36}$/.test(value["token"]))
5040
- throw new Error("The selected voice provider does not support same-address LAN takeover; the source remains active");
5041
- return { certificate: value["certificate"], token: value["token"] };
5042
- }
5043
- function assertLanTakeoverIdentity(source, target) {
5044
- if (source.certificate !== target.certificate)
5045
- throw new Error("LAN certificates differ; same-address takeover cannot preserve browser trust. The source remains active");
5046
- }
5047
- async function verifyLanTakeoverListener(certificate, value, signal) {
5048
- if (!isRecord(value) || typeof value["port"] !== "number" || !Number.isInteger(value["port"]) || value["port"] < 1 || value["port"] > 65535 || typeof value["token"] !== "string" || !/^[a-f0-9-]{36}$/.test(value["token"]))
5351
+ import { checkServerIdentity } from "node:tls";
5352
+ async function verifyLanTakeoverListener(certificate, fingerprint, value, signal, browserRealm) {
5353
+ if (typeof value !== "object" || value === null || !("port" in value) || !("token" in value) || typeof value["port"] !== "number" || !Number.isInteger(value["port"]) || value["port"] < 1 || value["port"] > 65535 || typeof value["token"] !== "string" || !/^[a-f0-9-]{36}$/.test(value["token"]))
5049
5354
  throw new Error("Invalid LAN listener proof");
5050
5355
  const { port, token } = value;
5051
5356
  await new Promise((resolve, reject) => {
@@ -5055,8 +5360,9 @@ async function verifyLanTakeoverListener(certificate, value, signal) {
5055
5360
  path: `/api/takeover-proof?token=${token}`,
5056
5361
  ca: certificate,
5057
5362
  rejectUnauthorized: true,
5363
+ checkServerIdentity: (host, peer) => checkServerIdentity(host, peer) ?? (peer.fingerprint256 === fingerprint ? undefined : new Error("LAN listener certificate does not match the offer")),
5058
5364
  agent: false,
5059
- signal
5365
+ signal: AbortSignal.any([signal, AbortSignal.timeout(5000)])
5060
5366
  }, (response) => {
5061
5367
  let body = "";
5062
5368
  response.setEncoding("utf8");
@@ -5066,13 +5372,54 @@ async function verifyLanTakeoverListener(certificate, value, signal) {
5066
5372
  request.destroy(new Error("Invalid LAN listener proof"));
5067
5373
  });
5068
5374
  response.on("error", reject);
5069
- response.on("end", () => response.statusCode === 200 && body === token ? resolve() : reject(new Error("The target could not verify the source LAN listener on this machine")));
5375
+ response.on("end", () => response.statusCode === 200 && body === (browserRealm ? token + ":" + browserRealm : token) ? resolve() : reject(new Error("The target could not verify the source LAN listener on this machine")));
5070
5376
  });
5071
5377
  request.setTimeout(5000, () => request.destroy(new Error("Same-address LAN takeover requires a reachable listener on this machine")));
5072
5378
  request.on("error", reject);
5073
5379
  });
5074
5380
  }
5075
5381
 
5382
+ // packages/gippity-voice/src/voice/lan/takeover.ts
5383
+ function prepareLanTakeover(certificate) {
5384
+ const { port, cert } = certificate;
5385
+ const offer = {
5386
+ certificate: new X509Certificate(cert).fingerprint256,
5387
+ token: randomUUID3()
5388
+ };
5389
+ let phase = "offered";
5390
+ return {
5391
+ offer,
5392
+ async verify(value, signal) {
5393
+ if (phase !== "offered" || !isRecord(value) || value["port"] !== port)
5394
+ throw new Error("LAN takeover requires a fresh proof for the granted port");
5395
+ phase = "verifying";
5396
+ try {
5397
+ await verifyLanTakeoverListener(cert, offer.certificate, value, signal);
5398
+ signal.throwIfAborted();
5399
+ phase = "verified";
5400
+ } catch (error) {
5401
+ phase = "offered";
5402
+ throw error;
5403
+ }
5404
+ },
5405
+ claim(value) {
5406
+ if (phase !== "verified" || !isRecord(value) || value["port"] !== port || value["token"] !== offer.token)
5407
+ throw new Error("Invalid or unverified LAN takeover activation");
5408
+ phase = "claimed";
5409
+ return offer.token;
5410
+ }
5411
+ };
5412
+ }
5413
+ function decodeLanTakeoverOffer(value) {
5414
+ if (!isRecord(value) || typeof value["certificate"] !== "string" || typeof value["token"] !== "string" || !/^[a-f0-9-]{36}$/.test(value["token"]))
5415
+ throw new Error("The selected voice provider does not support same-address LAN takeover; the source remains active");
5416
+ return { certificate: value["certificate"], token: value["token"] };
5417
+ }
5418
+ function assertLanTakeoverIdentity(source, target) {
5419
+ if (source.certificate !== target.certificate)
5420
+ throw new Error("LAN certificates differ; same-address takeover cannot preserve browser trust. The source remains active");
5421
+ }
5422
+
5076
5423
  class LanTakeoverArrival {
5077
5424
  pending;
5078
5425
  constructor(token, value) {
@@ -5114,6 +5461,8 @@ function startVoiceDeparture(options) {
5114
5461
  return audio.start();
5115
5462
  if (method === "peer.close")
5116
5463
  return audio.closePeer(value);
5464
+ if (method === "peer.finish")
5465
+ return audio.finishPlayback(value);
5117
5466
  throw new Error("Voice control was sent to the audio host instead of the selected session");
5118
5467
  },
5119
5468
  notification(message) {
@@ -5174,6 +5523,25 @@ function startVoiceDeparture(options) {
5174
5523
  link.waitFor("prepared"),
5175
5524
  options.waitForSettled(abort.signal)
5176
5525
  ]);
5526
+ if (options.browser) {
5527
+ const offer = await options.browser.transfer.authorize(isRecord(prepared) ? prepared["browserTakeover"] : undefined, (proof) => link.request("browser.verify", proof));
5528
+ await audio.release(abort.signal, () => options.browser.transfer.acknowledge(offer, abort.signal));
5529
+ await options.browser.release();
5530
+ link.stage("activate", {
5531
+ inputMuted: audio.inputMuted,
5532
+ alternateVoice: !options.captured.alternateVoice,
5533
+ browserTakeover: offer.path
5534
+ });
5535
+ const active = await link.waitFor("active");
5536
+ if (!isRecord(active) || active["browserTakeover"] !== true)
5537
+ throw new Error("Destination did not confirm the browser listener");
5538
+ takenOver = true;
5539
+ link.close();
5540
+ await cleanup;
5541
+ return;
5542
+ }
5543
+ if (isRecord(prepared) && prepared["browserTakeover"] !== undefined)
5544
+ throw new Error("This source cannot move its paired browser to the destination");
5177
5545
  if (options.lanTakeover) {
5178
5546
  const offered = isRecord(prepared) ? prepared["lanTakeover"] : undefined;
5179
5547
  const offer = offered === undefined ? undefined : decodeLanTakeoverOffer(offered);
@@ -5225,7 +5593,244 @@ function startVoiceDeparture(options) {
5225
5593
  };
5226
5594
  }
5227
5595
 
5228
- // packages/gippity-voice/src/voice/lan/remote-json.ts
5596
+ // packages/gippity-voice/src/voice/lan/browser-peer.ts
5597
+ import {
5598
+ awaitWithContext as awaitWithContext2,
5599
+ BACKGROUND_CONTEXT,
5600
+ withAbortSignal
5601
+ } from "@earendil-works/chord/context";
5602
+ var OFFER_TIMEOUT_MS2 = 15000;
5603
+
5604
+ class LanHostRealtimePeer {
5605
+ kind = "webrtc";
5606
+ helper;
5607
+ onAudio;
5608
+ onSpeakerSuppressed;
5609
+ drain;
5610
+ playbackEpoch = 0;
5611
+ speakerSuppressed = false;
5612
+ inputState = "pending";
5613
+ constructor(host, options) {
5614
+ this.helper = new VoiceHelperClient(host);
5615
+ this.onAudio = options.onAudio;
5616
+ this.onSpeakerSuppressed = options.onSpeakerSuppressed;
5617
+ this.drain = options.drain;
5618
+ }
5619
+ get isSpeakerSuppressed() {
5620
+ return this.speakerSuppressed;
5621
+ }
5622
+ onEvent(listener) {
5623
+ return this.helper.onEvent((event) => {
5624
+ if (event.type === "pcm") {
5625
+ if (this.inputState === "closed" || this.speakerSuppressed || event.epoch !== this.playbackEpoch)
5626
+ return;
5627
+ this.onAudio(Buffer.from(event.audio, "base64"));
5628
+ return;
5629
+ }
5630
+ if (this.inputState === "finishing" && event.type === "state" && event.state === "closed")
5631
+ return;
5632
+ const peerEvent = toPeerEvent2(event);
5633
+ if (peerEvent)
5634
+ listener(peerEvent);
5635
+ });
5636
+ }
5637
+ onExit(listener) {
5638
+ return this.helper.onExit(listener);
5639
+ }
5640
+ async start(_config) {
5641
+ await this.helper.start();
5642
+ if (this.helper.protocolVersion !== 8) {
5643
+ const actualVersion = this.helper.protocolVersion ?? "unknown";
5644
+ await this.helper.close();
5645
+ throw new Error(`Incompatible Codex voice helper protocol ${actualVersion}; expected 8`);
5646
+ }
5647
+ const offer = deferred();
5648
+ const removeEvent = this.helper.onEvent((event) => {
5649
+ if (event.type === "offer")
5650
+ offer.resolve(event.sdp);
5651
+ else if (event.type === "error")
5652
+ offer.reject(new Error(event.message));
5653
+ });
5654
+ const removeExit = this.helper.onExit((error) => offer.reject(error));
5655
+ const timeout = setTimeout(() => offer.reject(new Error("Codex voice helper did not create an offer")), OFFER_TIMEOUT_MS2);
5656
+ this.helper.send({ type: "start_v3_bridge" });
5657
+ try {
5658
+ const sdp = await offer.promise;
5659
+ if (this.inputState === "pending")
5660
+ this.inputState = "ready";
5661
+ return sdp;
5662
+ } finally {
5663
+ clearTimeout(timeout);
5664
+ removeEvent();
5665
+ removeExit();
5666
+ }
5667
+ }
5668
+ applyAnswer(sdp) {
5669
+ this.helper.send({ type: "apply_answer", sdp });
5670
+ }
5671
+ sendData(message) {
5672
+ if (this.inputState === "finishing")
5673
+ return;
5674
+ this.helper.send({ type: "send_data", message });
5675
+ }
5676
+ sendAudio(pcm) {
5677
+ if (this.inputState !== "ready")
5678
+ return;
5679
+ this.helper.send({
5680
+ type: "send_pcm",
5681
+ audio: pcm.toString("base64"),
5682
+ sample_rate: 24000,
5683
+ num_channels: 1
5684
+ });
5685
+ }
5686
+ setInputMuted(muted) {
5687
+ this.helper.send({ type: "set_input_muted", muted });
5688
+ }
5689
+ setSpeakerSuppressed(suppressed) {
5690
+ if (this.speakerSuppressed === suppressed)
5691
+ return;
5692
+ const epoch = this.playbackEpoch + 1;
5693
+ this.helper.send({ type: "set_speaker_suppressed", suppressed, epoch });
5694
+ this.playbackEpoch = epoch;
5695
+ this.speakerSuppressed = suppressed;
5696
+ this.onSpeakerSuppressed(suppressed);
5697
+ }
5698
+ get playbackSealed() {
5699
+ return this.inputState === "finishing";
5700
+ }
5701
+ async finishPlayback(signal) {
5702
+ if (!this.drain)
5703
+ return;
5704
+ signal.throwIfAborted();
5705
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(15000)]);
5706
+ await awaitWithContext2(this.drain(deadline, async () => {
5707
+ deadline.throwIfAborted();
5708
+ this.inputState = "finishing";
5709
+ await this.helper.stop();
5710
+ }), withAbortSignal(deadline, BACKGROUND_CONTEXT));
5711
+ }
5712
+ close() {
5713
+ this.inputState = "closed";
5714
+ return this.helper.close();
5715
+ }
5716
+ }
5717
+ function toPeerEvent2(event) {
5718
+ if (event.type === "state" || event.type === "data" || event.type === "error" || event.type === "playback_activity" || event.type === "audio_diagnostics")
5719
+ return event;
5720
+ return;
5721
+ }
5722
+
5723
+ // packages/gippity-voice/src/voice/lan/pcm-bridge.ts
5724
+ class GippityBrowserAudio {
5725
+ status = "connecting";
5726
+ transcript = "";
5727
+ error;
5728
+ peer;
5729
+ transcriber;
5730
+ shutdown;
5731
+ failure;
5732
+ mode;
5733
+ audio;
5734
+ onFailure;
5735
+ constructor(mode, audio, onFailure) {
5736
+ this.mode = mode;
5737
+ this.audio = audio;
5738
+ this.onFailure = onFailure;
5739
+ }
5740
+ createPeer(host) {
5741
+ const peer = new LanHostRealtimePeer(host, {
5742
+ onAudio: (pcm) => {
5743
+ if (this.peer === peer && !this.shutdown)
5744
+ this.audio.play(pcm);
5745
+ },
5746
+ onSpeakerSuppressed: (suppressed) => {
5747
+ if (this.peer === peer && suppressed)
5748
+ this.audio.clear();
5749
+ },
5750
+ drain: async (signal, seal) => {
5751
+ if (this.audio.finishPlayback)
5752
+ return this.audio.finishPlayback(signal, seal);
5753
+ throw new Error("Browser audio does not support final playback receipts");
5754
+ }
5755
+ });
5756
+ this.peer = peer;
5757
+ return peer;
5758
+ }
5759
+ async startCapture() {
5760
+ if (this.shutdown)
5761
+ throw new Error("Browser audio was closed");
5762
+ await this.audio.start({
5763
+ onAudio: (pcm) => {
5764
+ if (this.shutdown)
5765
+ return;
5766
+ if (this.mode === "dictation")
5767
+ this.transcriber?.append(pcm);
5768
+ else
5769
+ this.peer?.sendAudio(pcm);
5770
+ },
5771
+ onError: (error) => this.fail(error)
5772
+ });
5773
+ }
5774
+ async startDictation(auth, signal) {
5775
+ signal.throwIfAborted();
5776
+ const transcriber = new CodexDictationTranscriber({
5777
+ onError: (error) => this.fail(error),
5778
+ onStatus: () => {}
5779
+ });
5780
+ this.transcriber = transcriber;
5781
+ const cancel = () => void transcriber.close().catch(this.onFailure);
5782
+ signal.addEventListener("abort", cancel, { once: true });
5783
+ try {
5784
+ await transcriber.start(auth);
5785
+ signal.throwIfAborted();
5786
+ await this.startCapture();
5787
+ this.status = "recording";
5788
+ } finally {
5789
+ signal.removeEventListener("abort", cancel);
5790
+ }
5791
+ }
5792
+ setMuted(muted) {
5793
+ this.audio.setMuted(muted);
5794
+ }
5795
+ async finish() {
5796
+ if (this.failure)
5797
+ throw this.failure;
5798
+ if (!this.transcriber || this.shutdown)
5799
+ throw new Error("Browser dictation is not recording");
5800
+ this.status = "finishing";
5801
+ this.audio.setMuted(true);
5802
+ const text = await this.transcriber.finish();
5803
+ if (this.failure)
5804
+ throw this.failure;
5805
+ if (this.shutdown)
5806
+ throw new Error("Browser dictation was cancelled");
5807
+ return text ?? "";
5808
+ }
5809
+ close() {
5810
+ this.shutdown ??= (async () => {
5811
+ this.peer = undefined;
5812
+ this.status = this.failure ? "error" : "idle";
5813
+ const results = await Promise.allSettled([
5814
+ this.transcriber?.close(),
5815
+ this.audio.close()
5816
+ ]);
5817
+ const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
5818
+ if (errors.length)
5819
+ throw new AggregateError(errors, "GipPity browser audio could not close cleanly");
5820
+ })();
5821
+ return this.shutdown;
5822
+ }
5823
+ fail(error) {
5824
+ if (this.shutdown || this.failure)
5825
+ return;
5826
+ this.failure = error;
5827
+ this.error = error.message;
5828
+ this.status = "error";
5829
+ this.onFailure(error);
5830
+ }
5831
+ }
5832
+
5833
+ // internal/voice/remote-json.ts
5229
5834
  var MAX_REMOTE_VALUE_BYTES = 256 * 1024;
5230
5835
  var MAX_REMOTE_STRING_BYTES = 32 * 1024;
5231
5836
  var MAX_REMOTE_ARRAY_ITEMS = 256;
@@ -5376,11 +5981,11 @@ class GippityRemoteApps {
5376
5981
  }
5377
5982
 
5378
5983
  // packages/gippity-voice/src/voice/lan/server.ts
5379
- import { randomUUID as randomUUID4 } from "node:crypto";
5984
+ import { randomUUID as randomUUID5 } from "node:crypto";
5380
5985
  import { createServer } from "node:https";
5381
- import { WebSocket as WebSocket5, WebSocketServer } from "ws";
5986
+ import { WebSocket as WebSocket6, WebSocketServer } from "ws";
5382
5987
 
5383
- // packages/gippity-voice/src/voice/lan/activity.ts
5988
+ // internal/voice/lan-activity.ts
5384
5989
  var MAX_ACTIVITY_BYTES = 16 * 1024;
5385
5990
 
5386
5991
  class LanVoiceActivity {
@@ -5396,34 +6001,120 @@ class LanVoiceActivity {
5396
6001
  snapshot() {
5397
6002
  return this.state;
5398
6003
  }
5399
- working() {
5400
- this.state = { type: "activity", state: "working" };
5401
- this.publish(this.state);
6004
+ working() {
6005
+ this.state = { type: "activity", state: "working" };
6006
+ this.publish(this.state);
6007
+ }
6008
+ waiting(text) {
6009
+ const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
6010
+ this.state = bounded ? { type: "activity", state: "waiting", text: bounded } : { type: "activity", state: "waiting" };
6011
+ this.publish(this.state);
6012
+ }
6013
+ settled(text) {
6014
+ const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
6015
+ this.state = bounded ? { type: "activity", state: "settled", text: bounded } : { type: "activity", state: "idle" };
6016
+ this.publish(this.state);
6017
+ }
6018
+ }
6019
+ function boundedAssistantText(parts) {
6020
+ const text = parts.flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join(`
6021
+ `).trim();
6022
+ return text ? truncateUtf82(text, MAX_ACTIVITY_BYTES) : undefined;
6023
+ }
6024
+ function truncateUtf82(value, maxBytes) {
6025
+ const buffer = Buffer.from(value);
6026
+ if (buffer.byteLength <= maxBytes)
6027
+ return value;
6028
+ let end = maxBytes - Buffer.byteLength("…");
6029
+ while (end > 0 && (buffer[end] & 192) === 128)
6030
+ end -= 1;
6031
+ return `${buffer.subarray(0, end).toString("utf8").trimEnd()}…`;
6032
+ }
6033
+
6034
+ // internal/voice/lan-draft.ts
6035
+ var MAX_LAN_VOICE_DRAFT_BYTES = 64 * 1024;
6036
+
6037
+ class LanVoiceDraftError extends Error {
6038
+ }
6039
+
6040
+ class LanVoiceDraftConflictError extends LanVoiceDraftError {
6041
+ }
6042
+
6043
+ class LanVoiceDraft {
6044
+ publish;
6045
+ sendMessage;
6046
+ text = "";
6047
+ revision = 0;
6048
+ sending = false;
6049
+ constructor(options) {
6050
+ this.publish = options.publish;
6051
+ this.sendMessage = options.sendMessage;
6052
+ }
6053
+ snapshot(sourceClientId, reason) {
6054
+ return {
6055
+ type: "draft",
6056
+ text: this.text,
6057
+ revision: this.revision,
6058
+ ...sourceClientId ? { sourceClientId } : {},
6059
+ ...reason ? { reason } : {}
6060
+ };
6061
+ }
6062
+ update(clientId, value, expectedRevision) {
6063
+ this.assertRevision(expectedRevision);
6064
+ this.text = validatedDraft(value);
6065
+ this.revision += 1;
6066
+ this.publish(this.snapshot(clientId, "update"));
6067
+ return this.revision;
6068
+ }
6069
+ insertTranscript(clientId, transcript, selection) {
6070
+ const clean = transcript.trim();
6071
+ if (!clean)
6072
+ return;
6073
+ const start = boundedIndex(selection?.start, this.text.length, this.text.length);
6074
+ const end = boundedIndex(selection?.end, this.text.length, start);
6075
+ const before = this.text.slice(0, Math.min(start, end));
6076
+ const after = this.text.slice(Math.max(start, end));
6077
+ const leftSpace = before && !/\s$/.test(before) ? " " : "";
6078
+ const rightSpace = after && !/^\s/.test(after) ? " " : "";
6079
+ this.text = validatedDraft(`${before}${leftSpace}${clean}${rightSpace}${after}`);
6080
+ this.revision += 1;
6081
+ this.publish(this.snapshot(clientId, "transcript"));
5402
6082
  }
5403
- waiting(text) {
5404
- const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
5405
- this.state = bounded ? { type: "activity", state: "waiting", text: bounded } : { type: "activity", state: "waiting" };
5406
- this.publish(this.state);
6083
+ async send(clientId, value, expectedRevision) {
6084
+ this.assertRevision(expectedRevision);
6085
+ if (this.sending)
6086
+ throw new LanVoiceDraftConflictError("A message is already being sent");
6087
+ const text = validatedDraft(value);
6088
+ if (!text.trim())
6089
+ throw new LanVoiceDraftError("A message is required");
6090
+ this.text = text;
6091
+ const revision = this.revision;
6092
+ this.sending = true;
6093
+ try {
6094
+ await this.sendMessage(text);
6095
+ } finally {
6096
+ this.sending = false;
6097
+ }
6098
+ if (this.revision === revision && this.text === text)
6099
+ this.text = "";
6100
+ this.revision += 1;
6101
+ this.publish({ type: "sent" });
6102
+ this.publish(this.snapshot(clientId, "sent"));
5407
6103
  }
5408
- settled(text) {
5409
- const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
5410
- this.state = bounded ? { type: "activity", state: "settled", text: bounded } : { type: "activity", state: "idle" };
5411
- this.publish(this.state);
6104
+ assertRevision(value) {
6105
+ if (!Number.isInteger(value) || value !== this.revision)
6106
+ throw new LanVoiceDraftConflictError("Draft changed on another device; review it and try again");
5412
6107
  }
5413
6108
  }
5414
- function boundedAssistantText(parts) {
5415
- const text = parts.flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join(`
5416
- `).trim();
5417
- return text ? truncateUtf82(text, MAX_ACTIVITY_BYTES) : undefined;
6109
+ function validatedDraft(value) {
6110
+ if (typeof value !== "string")
6111
+ throw new LanVoiceDraftError("Draft text is required");
6112
+ if (Buffer.byteLength(value) > MAX_LAN_VOICE_DRAFT_BYTES)
6113
+ throw new LanVoiceDraftError("Draft is too large");
6114
+ return value;
5418
6115
  }
5419
- function truncateUtf82(value, maxBytes) {
5420
- const buffer = Buffer.from(value);
5421
- if (buffer.byteLength <= maxBytes)
5422
- return value;
5423
- let end = maxBytes - Buffer.byteLength("…");
5424
- while (end > 0 && (buffer[end] & 192) === 128)
5425
- end -= 1;
5426
- return `${buffer.subarray(0, end).toString("utf8").trimEnd()}…`;
6116
+ function boundedIndex(value, length, fallback) {
6117
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= length ? value : fallback;
5427
6118
  }
5428
6119
 
5429
6120
  // packages/gippity-voice/src/voice/lan/app-assets.ts
@@ -5476,7 +6167,7 @@ function createLanVoiceWebManifest() {
5476
6167
  }
5477
6168
 
5478
6169
  // packages/gippity-voice/src/voice/lan/browser-clients.ts
5479
- import { WebSocket as WebSocket4 } from "ws";
6170
+ import { WebSocket as WebSocket5 } from "ws";
5480
6171
 
5481
6172
  // packages/gippity-voice/src/voice/lan/browser-connections.ts
5482
6173
  import { WebSocket as WebSocket2 } from "ws";
@@ -5643,7 +6334,7 @@ class LanVoiceBrowserConnections {
5643
6334
  }
5644
6335
 
5645
6336
  // packages/gippity-voice/src/voice/lan/browser-session.ts
5646
- import { WebSocket as WebSocket3 } from "ws";
6337
+ import { WebSocket as WebSocket4 } from "ws";
5647
6338
 
5648
6339
  // packages/gippity-voice/src/voice/lan/protocol.ts
5649
6340
  function decodeLanVoiceAudioCommand(value) {
@@ -5652,16 +6343,26 @@ function decodeLanVoiceAudioCommand(value) {
5652
6343
  if (value.type === "start") {
5653
6344
  if (!("mode" in value) || value.mode !== "conversation" && value.mode !== "dictation")
5654
6345
  throw invalidCommand();
6346
+ const playback = "playbackDrain" in value ? value.playbackDrain : undefined;
6347
+ if (playback !== undefined && typeof playback !== "boolean")
6348
+ throw invalidCommand();
6349
+ const capability = playback === true ? { playbackDrain: true } : {};
5655
6350
  if ("takeoverToken" in value) {
5656
6351
  if (value.mode !== "conversation" || typeof value.takeoverToken !== "string" || !/^[a-f0-9-]{36}$/.test(value.takeoverToken))
5657
6352
  throw invalidCommand();
5658
6353
  return {
5659
6354
  type: "start",
5660
6355
  mode: value.mode,
5661
- takeoverToken: value.takeoverToken
6356
+ takeoverToken: value.takeoverToken,
6357
+ ...capability
5662
6358
  };
5663
6359
  }
5664
- return { type: "start", mode: value.mode };
6360
+ return { type: "start", mode: value.mode, ...capability };
6361
+ }
6362
+ if (value.type === "drained") {
6363
+ if (!("id" in value) || typeof value.id !== "string" || !/^[a-f0-9-]{36}$/.test(value.id))
6364
+ throw invalidCommand();
6365
+ return { type: "drained", id: value.id };
5665
6366
  }
5666
6367
  if (value.type === "finish") {
5667
6368
  if (!("draft" in value) || typeof value.draft !== "string")
@@ -5775,6 +6476,66 @@ class MicrophoneLevelMonitor {
5775
6476
  }
5776
6477
  }
5777
6478
 
6479
+ // packages/gippity-voice/src/voice/lan/playback-drain.ts
6480
+ import { randomUUID as randomUUID4 } from "node:crypto";
6481
+ import { WebSocket as WebSocket3 } from "ws";
6482
+
6483
+ class LanPlaybackDrain {
6484
+ pending;
6485
+ wait(socket, signal, seal) {
6486
+ signal.throwIfAborted();
6487
+ if (socket.readyState !== WebSocket3.OPEN)
6488
+ throw new Error("The active browser speaker is not connected");
6489
+ if (this.pending)
6490
+ throw new Error("Voice playback is already finishing");
6491
+ return new Promise((resolve, reject) => {
6492
+ const id = randomUUID4();
6493
+ const finish = (error) => {
6494
+ if (this.pending?.id !== id)
6495
+ return;
6496
+ this.pending = undefined;
6497
+ clearTimeout(timer);
6498
+ socket.off("close", closed);
6499
+ signal.removeEventListener("abort", aborted);
6500
+ if (error)
6501
+ reject(error);
6502
+ else
6503
+ resolve();
6504
+ };
6505
+ const closed = () => finish(new Error("Voice device disconnected before playback finished"));
6506
+ const aborted = () => finish(new Error("Playback wait cancelled"));
6507
+ const timer = setTimeout(() => finish(new Error("Voice device did not confirm playback; reconnect it and try again")), 30000);
6508
+ this.pending = { socket, id, finish, sent: false };
6509
+ socket.once("close", closed);
6510
+ signal.addEventListener("abort", aborted, { once: true });
6511
+ Promise.resolve().then(() => {
6512
+ if (this.pending?.id === id)
6513
+ return seal();
6514
+ }).then(() => {
6515
+ if (this.pending?.id !== id)
6516
+ return;
6517
+ if (socket.readyState !== WebSocket3.OPEN) {
6518
+ closed();
6519
+ return;
6520
+ }
6521
+ this.pending.sent = true;
6522
+ socket.send(JSON.stringify({ type: "drain", id }), (error) => {
6523
+ if (error)
6524
+ finish(error);
6525
+ });
6526
+ }).catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
6527
+ });
6528
+ }
6529
+ acknowledge(socket, id) {
6530
+ const pending = this.pending;
6531
+ if (pending?.sent && pending.socket === socket && pending.id === id)
6532
+ pending.finish();
6533
+ }
6534
+ cancel() {
6535
+ this.pending?.finish(new Error("Voice playback owner changed"));
6536
+ }
6537
+ }
6538
+
5778
6539
  // packages/gippity-voice/src/voice/lan/browser-session.ts
5779
6540
  class LanVoiceBrowserSession {
5780
6541
  options;
@@ -5784,6 +6545,7 @@ class LanVoiceBrowserSession {
5784
6545
  conversationOwnerId;
5785
6546
  stopCompletion;
5786
6547
  conversationSpeakerSuppressed = false;
6548
+ playbackDrain = new LanPlaybackDrain;
5787
6549
  microphoneLevel;
5788
6550
  constructor(options, connections) {
5789
6551
  this.options = options;
@@ -5804,6 +6566,7 @@ class LanVoiceBrowserSession {
5804
6566
  setConversationSpeakerSuppressed(suppressed) {
5805
6567
  if (this.conversationSpeakerSuppressed === suppressed)
5806
6568
  return;
6569
+ this.playbackDrain.cancel();
5807
6570
  this.conversationSpeakerSuppressed = suppressed;
5808
6571
  const active = this.state;
5809
6572
  if (active.type === "active" && active.mode === "conversation") {
@@ -5813,10 +6576,27 @@ class LanVoiceBrowserSession {
5813
6576
  });
5814
6577
  }
5815
6578
  }
6579
+ drainPlayback(signal, seal) {
6580
+ const active = this.state;
6581
+ if (active.type !== "active" || active.mode !== "conversation" || !active.playbackDrain || !this.connections.isCurrentAudio(active.clientId, active.socket))
6582
+ throw new Error("This voice device cannot confirm playback; update or reconnect it, or use Stop");
6583
+ return this.playbackDrain.wait(active.socket, signal, seal);
6584
+ }
6585
+ acknowledgePlayback(socket, id) {
6586
+ if (this.conversationSocket === socket)
6587
+ this.playbackDrain.acknowledge(socket, id);
6588
+ }
6589
+ replaceSocket(clientId, socket) {
6590
+ if (this.conversationSocket === socket)
6591
+ this.playbackDrain.cancel();
6592
+ this.releaseStarting(clientId, socket);
6593
+ }
5816
6594
  release(clientId, socket, terminateConversation = false) {
5817
6595
  if (terminateConversation && this.stopCompletion?.clientId === clientId)
5818
6596
  return this.stopCompletion.promise;
5819
6597
  const starting = this.state;
6598
+ if (starting.type === "active" && starting.mode === "conversation" && starting.clientId === clientId && (!socket || starting.socket === socket))
6599
+ this.playbackDrain.cancel();
5820
6600
  const ownsConversation = this.conversationOwnerId === clientId && (!socket || (starting.type === "active" || starting.type === "starting") && starting.socket === socket);
5821
6601
  this.releaseStarting(clientId, socket);
5822
6602
  let completion;
@@ -5861,7 +6641,7 @@ class LanVoiceBrowserSession {
5861
6641
  message: errorMessage(error)
5862
6642
  }));
5863
6643
  }
5864
- claim(clientId, socket, mode, takeoverToken) {
6644
+ claim(clientId, socket, mode, takeoverToken, playbackDrain = false) {
5865
6645
  const starting = this.state.type === "starting" ? this.state : undefined;
5866
6646
  if (starting && (starting.clientId !== clientId || starting.socket !== socket || starting.mode !== mode)) {
5867
6647
  this.releaseStarting(starting.clientId, starting.socket);
@@ -5872,11 +6652,12 @@ class LanVoiceBrowserSession {
5872
6652
  starting.socket.close(4001, "replaced");
5873
6653
  }
5874
6654
  return this.enqueue(async () => {
5875
- if (this.closed || socket.readyState !== WebSocket3.OPEN || !this.connections.isCurrentAudio(clientId, socket))
6655
+ if (this.closed || socket.readyState !== WebSocket4.OPEN || !this.connections.isCurrentAudio(clientId, socket))
5876
6656
  return;
5877
6657
  const previous = this.state.type === "active" ? this.state : undefined;
5878
6658
  if (previous?.clientId === clientId && previous.socket === socket && previous.mode === mode)
5879
6659
  return;
6660
+ this.playbackDrain.cancel();
5880
6661
  this.state = { type: "idle" };
5881
6662
  if (previous?.mode === "conversation")
5882
6663
  this.microphoneLevel.reset();
@@ -5913,12 +6694,12 @@ class LanVoiceBrowserSession {
5913
6694
  this.conversationOwnerId = undefined;
5914
6695
  throw error;
5915
6696
  }
5916
- if (this.closed || this.state !== starting || !this.connections.isCurrentAudio(clientId, socket) || socket.readyState !== WebSocket3.OPEN) {
6697
+ if (this.closed || this.state !== starting || !this.connections.isCurrentAudio(clientId, socket) || socket.readyState !== WebSocket4.OPEN) {
5917
6698
  if (mode === "dictation")
5918
6699
  await this.options.cancelDictation(clientId);
5919
6700
  return;
5920
6701
  }
5921
- this.state = { type: "active", clientId, socket, mode };
6702
+ this.state = { type: "active", clientId, socket, mode, playbackDrain };
5922
6703
  if (mode === "conversation")
5923
6704
  await this.options.onConversationActivity(true);
5924
6705
  socket.send(JSON.stringify({
@@ -5938,7 +6719,7 @@ class LanVoiceBrowserSession {
5938
6719
  return;
5939
6720
  this.state = { type: "idle" };
5940
6721
  await this.options.finishDictation(clientId, draft, revision, selection);
5941
- if (!this.closed && socket.readyState === WebSocket3.OPEN)
6722
+ if (!this.closed && socket.readyState === WebSocket4.OPEN)
5942
6723
  socket.send(JSON.stringify({ type: "dictation.complete" }));
5943
6724
  });
5944
6725
  }
@@ -5965,6 +6746,7 @@ class LanVoiceBrowserSession {
5965
6746
  this.options.onDictationAudio(clientId, pcm);
5966
6747
  }
5967
6748
  async close() {
6749
+ this.playbackDrain.cancel();
5968
6750
  const active = this.state;
5969
6751
  if (active.type === "closed") {
5970
6752
  await this.operation;
@@ -6024,7 +6806,7 @@ class LanVoiceBrowserClients {
6024
6806
  connectAudio(clientId, socket) {
6025
6807
  this.connections.connectAudio(clientId, socket, this.session.closed, {
6026
6808
  onMessage: (data, isBinary) => this.receive(clientId, socket, data, isBinary),
6027
- onReplaced: (previous) => this.session.releaseStarting(clientId, previous),
6809
+ onReplaced: (previous) => this.session.replaceSocket(clientId, previous),
6028
6810
  onClose: () => {
6029
6811
  this.session.release(clientId, socket).catch((error) => this.connections.sendControl(clientId, {
6030
6812
  type: "error",
@@ -6047,7 +6829,7 @@ class LanVoiceBrowserClients {
6047
6829
  }
6048
6830
  takeover(token) {
6049
6831
  const socket = this.session.conversationSocket;
6050
- if (!socket || socket.readyState !== WebSocket4.OPEN)
6832
+ if (!socket || socket.readyState !== WebSocket5.OPEN)
6051
6833
  return Promise.reject(new Error("The active browser microphone is not connected"));
6052
6834
  if (this.takeoverAck)
6053
6835
  return Promise.reject(new Error("A browser takeover is already preparing"));
@@ -6077,6 +6859,9 @@ class LanVoiceBrowserClients {
6077
6859
  sendConversationAudio(pcm) {
6078
6860
  this.session.sendConversationAudio(pcm);
6079
6861
  }
6862
+ drainPlayback(signal, seal) {
6863
+ return this.session.drainPlayback(signal, seal);
6864
+ }
6080
6865
  setConversationSpeakerSuppressed(suppressed) {
6081
6866
  this.session.setConversationSpeakerSuppressed(suppressed);
6082
6867
  }
@@ -6109,7 +6894,9 @@ class LanVoiceBrowserClients {
6109
6894
  }
6110
6895
  const message = input.command;
6111
6896
  if (message.type === "start") {
6112
- this.session.claim(clientId, socket, message.mode, message.takeoverToken).catch((error) => this.sendSocketError(socket, error));
6897
+ this.session.claim(clientId, socket, message.mode, message.takeoverToken, message.playbackDrain).catch((error) => this.sendSocketError(socket, error));
6898
+ } else if (message.type === "drained") {
6899
+ this.session.acknowledgePlayback(socket, message.id);
6113
6900
  } else if (message.type === "finish") {
6114
6901
  this.session.finish(clientId, socket, message.draft, message.revision, message.selection).catch((error) => this.sendSocketError(socket, error));
6115
6902
  } else if (message.type === "release") {
@@ -6124,112 +6911,145 @@ class LanVoiceBrowserClients {
6124
6911
  }
6125
6912
  }
6126
6913
  sendSocketError(socket, error) {
6127
- if (socket.readyState === WebSocket4.OPEN)
6914
+ if (socket.readyState === WebSocket5.OPEN)
6128
6915
  socket.send(JSON.stringify({ type: "error", message: errorMessage(error) }));
6129
6916
  }
6130
6917
  }
6131
6918
 
6132
- // packages/gippity-voice/src/voice/lan/browser-peer.ts
6133
- var OFFER_TIMEOUT_MS2 = 15000;
6919
+ // internal/voice/lan-client-sdk.ts
6920
+ var lanClientScript = (audioScript, listenerPath = "") => String.raw`
6921
+ (function (global) {
6922
+ 'use strict';
6923
+ const listenerPath = ${JSON.stringify(listenerPath)};
6924
+ ${audioScript} function connect(options = {}) {
6925
+ const clientId = options.clientId || id();
6926
+ const listeners = new Map();
6927
+ let closed = false, eventSource, rpcId = 0;
6928
+ let draft = { type:'draft', text:'', revision:-1 };
6929
+ let dirty = false, syncing = false, syncPromise, timer;
6930
+ let resolveInitialDraft;
6931
+ const initialDraft = new Promise((resolve) => { resolveInitialDraft = resolve; });
6932
+ const assertOpen = () => { if (closed) throw new Error('GipPity remote is closed'); };
6134
6933
 
6135
- class LanHostRealtimePeer {
6136
- kind = "webrtc";
6137
- helper;
6138
- onAudio;
6139
- onSpeakerSuppressed;
6140
- playbackEpoch = 0;
6141
- speakerSuppressed = false;
6142
- inputState = "pending";
6143
- constructor(host, options) {
6144
- this.helper = new VoiceHelperClient(host);
6145
- this.onAudio = options.onAudio;
6146
- this.onSpeakerSuppressed = options.onSpeakerSuppressed;
6147
- }
6148
- get isSpeakerSuppressed() {
6149
- return this.speakerSuppressed;
6150
- }
6151
- onEvent(listener) {
6152
- return this.helper.onEvent((event) => {
6153
- if (event.type === "pcm") {
6154
- if (this.speakerSuppressed || event.epoch !== this.playbackEpoch)
6155
- return;
6156
- this.onAudio(Buffer.from(event.audio, "base64"));
6157
- return;
6158
- }
6159
- const peerEvent = toPeerEvent2(event);
6160
- if (peerEvent)
6161
- listener(peerEvent);
6162
- });
6163
- }
6164
- onExit(listener) {
6165
- return this.helper.onExit(listener);
6166
- }
6167
- async start(_config) {
6168
- await this.helper.start();
6169
- if (this.helper.protocolVersion !== 8) {
6170
- const actualVersion = this.helper.protocolVersion ?? "unknown";
6171
- await this.helper.close();
6172
- throw new Error(`Incompatible Codex voice helper protocol ${actualVersion}; expected 8`);
6173
- }
6174
- const offer = deferred();
6175
- const removeEvent = this.helper.onEvent((event) => {
6176
- if (event.type === "offer")
6177
- offer.resolve(event.sdp);
6178
- else if (event.type === "error")
6179
- offer.reject(new Error(event.message));
6180
- });
6181
- const removeExit = this.helper.onExit((error) => offer.reject(error));
6182
- const timeout = setTimeout(() => offer.reject(new Error("Codex voice helper did not create an offer")), OFFER_TIMEOUT_MS2);
6183
- this.helper.send({ type: "start_v3_bridge" });
6184
- try {
6185
- const sdp = await offer.promise;
6186
- if (this.inputState === "pending")
6187
- this.inputState = "ready";
6188
- return sdp;
6189
- } finally {
6190
- clearTimeout(timeout);
6191
- removeEvent();
6192
- removeExit();
6193
- }
6194
- }
6195
- applyAnswer(sdp) {
6196
- this.helper.send({ type: "apply_answer", sdp });
6197
- }
6198
- sendData(message) {
6199
- this.helper.send({ type: "send_data", message });
6200
- }
6201
- sendAudio(pcm) {
6202
- if (this.inputState !== "ready")
6203
- return;
6204
- this.helper.send({
6205
- type: "send_pcm",
6206
- audio: pcm.toString("base64"),
6207
- sample_rate: 24000,
6208
- num_channels: 1
6209
- });
6210
- }
6211
- setInputMuted(muted) {
6212
- this.helper.send({ type: "set_input_muted", muted });
6213
- }
6214
- setSpeakerSuppressed(suppressed) {
6215
- if (this.speakerSuppressed === suppressed)
6216
- return;
6217
- const epoch = this.playbackEpoch + 1;
6218
- this.helper.send({ type: "set_speaker_suppressed", suppressed, epoch });
6219
- this.playbackEpoch = epoch;
6220
- this.speakerSuppressed = suppressed;
6221
- this.onSpeakerSuppressed(suppressed);
6222
- }
6223
- close() {
6224
- this.inputState = "closed";
6225
- return this.helper.close();
6934
+ const emit = (type, value, wildcard = true) => {
6935
+ for (const listener of listeners.get(type) || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6936
+ if (wildcard && type !== '*') for (const listener of listeners.get('*') || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6937
+ };
6938
+ const post = async (path, body) => {
6939
+ assertOpen();
6940
+ const response = await fetch(listenerPath + path, { method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({ clientId, ...body }) });
6941
+ const result = await response.json().catch(() => ({}));
6942
+ if (!response.ok) throw new Error(result.error || 'Pi rejected the request');
6943
+ return result;
6944
+ };
6945
+ const client = {
6946
+ clientId,
6947
+ _emit: emit,
6948
+ _post: post,
6949
+ get draft() { return { ...draft }; },
6950
+ on(type, listener) {
6951
+ assertOpen();
6952
+ if (typeof listener !== 'function') throw new Error('Event listener must be a function');
6953
+ let group = listeners.get(type); if (!group) { group = new Set(); listeners.set(type, group); }
6954
+ group.add(listener); return () => group.delete(listener);
6955
+ },
6956
+ async call(target, method, ...args) {
6957
+ const id = ++rpcId;
6958
+ const result = await post('/api/rpc', { id, target, method, args });
6959
+ if (!result.ok) {
6960
+ const error = new Error(result.error?.message || 'Pi RPC failed');
6961
+ if (result.error?.name) error.name = result.error.name;
6962
+ throw error;
6963
+ }
6964
+ return result.result;
6965
+ },
6966
+ setDraft(text) {
6967
+ assertOpen();
6968
+ if (typeof text !== 'string') throw new Error('Draft text must be a string');
6969
+ draft = { ...draft, text, local:true };
6970
+ dirty = true; emit('draft', { ...draft });
6971
+ clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180);
6972
+ },
6973
+ flushDraft: () => flush(),
6974
+ async send(text) {
6975
+ if (typeof text === 'string' && text !== draft.text) client.setDraft(text);
6976
+ clearTimeout(timer);
6977
+ await flush();
6978
+ if (!draft.text.trim()) throw new Error('A message is required');
6979
+ await post('/api/send', { text:draft.text, revision:draft.revision });
6980
+ },
6981
+ close() {
6982
+ if (closed) return; clearTimeout(timer);
6983
+ client.audio._close(); closed = true; resolveInitialDraft();
6984
+ navigator.sendBeacon(listenerPath + '/api/draft', new Blob([JSON.stringify({ clientId, text:draft.text, revision:draft.revision })], {type:'application/json'}));
6985
+ global.removeEventListener('pagehide', pagehide);
6986
+ eventSource?.close(); listeners.clear();
6987
+ },
6988
+ };
6989
+ const flush = async () => {
6990
+ if (closed) throw new Error('GipPity remote is closed');
6991
+ if (syncing) return syncPromise;
6992
+ if (!dirty) return true;
6993
+ syncing = true;
6994
+ syncPromise = (async () => {
6995
+ if (draft.revision < 0) await initialDraft;
6996
+ if (closed) throw new Error('GipPity remote is closed');
6997
+ while (dirty) {
6998
+ if (closed) throw new Error('GipPity remote is closed');
6999
+ dirty = false;
7000
+ const text = draft.text;
7001
+ try {
7002
+ const result = await post('/api/draft', { text, revision:draft.revision });
7003
+ if (typeof result.revision === 'number') draft = { ...draft, revision:Math.max(draft.revision, result.revision) };
7004
+ } catch (error) {
7005
+ dirty = true; emit('error', { type:'error', source:'draft', message:error instanceof Error ? error.message : String(error) });
7006
+ throw error;
7007
+ }
7008
+ }
7009
+ return true;
7010
+ })();
7011
+ try { return await syncPromise; }
7012
+ finally { syncing = false; syncPromise = undefined; }
7013
+ };
7014
+ const applyDraft = (command) => {
7015
+ if (typeof command.text !== 'string' || typeof command.revision !== 'number' || command.revision < draft.revision) return;
7016
+ if (draft.revision < 0 && dirty) {
7017
+ draft = { ...draft, revision:command.revision };
7018
+ resolveInitialDraft(); emit('draft', { ...draft }); return;
7019
+ }
7020
+ const reconnectSnapshot = !command.sourceClientId && !command.reason;
7021
+ const preserveLocal = (dirty || syncing) && draft.text !== command.text && (reconnectSnapshot || (command.sourceClientId === clientId && (command.reason === 'update' || command.reason === 'sent')));
7022
+ draft = preserveLocal ? { ...draft, revision:command.revision } : { ...command };
7023
+ if (!preserveLocal && command.sourceClientId !== clientId) { clearTimeout(timer); dirty = false; }
7024
+ if (reconnectSnapshot && preserveLocal && dirty) { clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180); }
7025
+ resolveInitialDraft();
7026
+ emit('draft', { ...draft });
7027
+ };
7028
+ client.audio = createAudio(client, assertOpen);
7029
+ eventSource = new EventSource(listenerPath + '/api/events?client=' + encodeURIComponent(clientId));
7030
+ const connectionState = (state) => {
7031
+ const command = { type:'connection', state };
7032
+ client.audio._serverCommand(command); emit('connection', command);
7033
+ };
7034
+ eventSource.onopen = () => connectionState('connected');
7035
+ eventSource.onerror = () => connectionState('reconnecting');
7036
+ eventSource.onmessage = (event) => {
7037
+ try {
7038
+ const command = JSON.parse(event.data);
7039
+ client.audio._serverCommand(command);
7040
+ if (command.type === 'draft') applyDraft(command);
7041
+ else emit(command.type, command);
7042
+ if (command.type === 'durable.event') emit('durable:' + command.event, command.data, false);
7043
+ } catch {}
7044
+ };
7045
+ const pagehide = () => { client.audio._pagehide(); clearTimeout(timer); navigator.sendBeacon(listenerPath + '/api/draft', new Blob([JSON.stringify({ clientId, text:draft.text, revision:draft.revision })], {type:'application/json'})); };
7046
+ global.addEventListener('pagehide', pagehide);
7047
+ return client;
6226
7048
  }
6227
- }
6228
- function toPeerEvent2(event) {
6229
- if (event.type === "state" || event.type === "data" || event.type === "error" || event.type === "playback_activity" || event.type === "audio_diagnostics")
6230
- return event;
6231
- return;
6232
- }
7049
+
7050
+ global.GippityRemote = Object.freeze({ connect });
7051
+ })(globalThis);
7052
+ `;
6233
7053
 
6234
7054
  // packages/gippity-voice/src/voice/lan/audio-worklet.ts
6235
7055
  var LAN_VOICE_AUDIO_WORKLET = String.raw`
@@ -6252,9 +7072,8 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6252
7072
  this.playbackLength = 0;
6253
7073
  this.playing = false;
6254
7074
  this.playbackPhase = 0;
6255
- this.playbackCurrent = 0;
6256
- this.playbackNext = 0;
6257
7075
  this.speakerSuppressed = false;
7076
+ this.drain = undefined;
6258
7077
  this.port.onmessage = (event) => this.handleMessage(event.data);
6259
7078
  }
6260
7079
 
@@ -6263,6 +7082,10 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6263
7082
  if (!this.inputMuted && input?.[0]) this.captureInput(input);
6264
7083
  const output = outputs[0]?.[0];
6265
7084
  if (output) this.renderPlayback(output);
7085
+ if (output && this.drain && !this.playing && this.playbackLength === 0) {
7086
+ this.port.postMessage({ type:'rendered', id:this.drain, endTime:(currentFrame + output.length) / sampleRate });
7087
+ this.drain = undefined;
7088
+ }
6266
7089
  return true;
6267
7090
  }
6268
7091
 
@@ -6295,6 +7118,10 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6295
7118
  }
6296
7119
 
6297
7120
  handleMessage(value) {
7121
+ if (value?.type === 'drain' && typeof value.id === 'string') {
7122
+ this.drain = value.id;
7123
+ return;
7124
+ }
6298
7125
  if (value?.type === 'input_muted' && typeof value.muted === 'boolean' && Number.isSafeInteger(value.epoch)) {
6299
7126
  this.captureEpoch = value.epoch;
6300
7127
  this.inputMuted = value.muted;
@@ -6332,42 +7159,45 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6332
7159
  }
6333
7160
  }
6334
7161
 
6335
- resetPlayback() {
7162
+ clearPlayback() {
6336
7163
  this.playback.fill(0);
6337
7164
  this.playbackRead = 0;
6338
7165
  this.playbackLength = 0;
6339
7166
  this.playing = false;
6340
7167
  this.playbackPhase = 0;
6341
- this.playbackCurrent = 0;
6342
- this.playbackNext = 0;
7168
+ }
7169
+
7170
+ resetPlayback() {
7171
+ this.drain = undefined;
7172
+ this.clearPlayback();
6343
7173
  }
6344
7174
 
6345
7175
  renderPlayback(output) {
6346
7176
  output.fill(0);
6347
7177
  if (!this.playing) {
6348
- if (this.playbackLength < PLAYBACK_START_SAMPLES) return;
7178
+ if (this.playbackLength === 0 || (!this.drain && this.playbackLength < PLAYBACK_START_SAMPLES)) return;
6349
7179
  this.playing = true;
6350
7180
  this.playbackPhase = 0;
6351
- this.playbackCurrent = this.shiftPlayback();
6352
- this.playbackNext = this.shiftPlayback();
6353
7181
  }
6354
7182
  const step = TARGET_RATE / sampleRate;
6355
7183
  for (let index = 0; index < output.length; index++) {
6356
- output[index] = this.playbackCurrent + (this.playbackNext - this.playbackCurrent) * this.playbackPhase;
7184
+ const current = this.playback[this.playbackRead];
7185
+ const next = this.playbackLength > 1 ? this.playback[(this.playbackRead + 1) % PLAYBACK_MAX_SAMPLES] : current;
7186
+ output[index] = current + (next - current) * this.playbackPhase;
6357
7187
  this.playbackPhase += step;
6358
7188
  while (this.playbackPhase >= 1) {
6359
7189
  this.playbackPhase -= 1;
6360
- this.playbackCurrent = this.playbackNext;
7190
+ this.shiftPlayback();
6361
7191
  if (this.playbackLength === 0) {
6362
7192
  this.playing = false;
6363
7193
  return;
6364
7194
  }
6365
- this.playbackNext = this.shiftPlayback();
6366
7195
  }
6367
7196
  }
6368
7197
  }
6369
7198
 
6370
7199
  shiftPlayback() {
7200
+ if (this.playbackLength === 0) return 0;
6371
7201
  const sample = this.playback[this.playbackRead] || 0;
6372
7202
  this.playbackRead = (this.playbackRead + 1) % PLAYBACK_MAX_SAMPLES;
6373
7203
  this.playbackLength -= 1;
@@ -6482,6 +7312,15 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6482
7312
  processor.connect(context.destination);
6483
7313
  return {
6484
7314
  context, processor,
7315
+ canDrain: typeof context.getOutputTimestamp === 'function',
7316
+ drain(id) { processor.port.postMessage({ type:'drain', id }); },
7317
+ async rendered(value, stillCurrent) {
7318
+ if (value?.type !== 'rendered' || typeof value.id !== 'string' || !Number.isFinite(value.endTime)) return;
7319
+ while (stillCurrent() && context.state === 'running') {
7320
+ if (context.getOutputTimestamp().contextTime >= value.endTime) return value.id;
7321
+ await new Promise((resolve) => setTimeout(resolve, 10));
7322
+ }
7323
+ },
6485
7324
  acceptCapture(value) { return value?.type === 'capture' && value.epoch === inputEpoch && value.pcm instanceof ArrayBuffer ? value.pcm : undefined; },
6486
7325
  releaseInput() { microphoneBuffer.port.postMessage({ type:'release' }); },
6487
7326
  setInputMuted(muted) {
@@ -6615,6 +7454,10 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6615
7454
  if (event.data instanceof ArrayBuffer) { realtimeAudio?.play(event.data); return; }
6616
7455
  try {
6617
7456
  const message = JSON.parse(event.data);
7457
+ if (message.type === 'drain' && typeof message.id === 'string') {
7458
+ realtimeAudio?.drain(message.id);
7459
+ return;
7460
+ }
6618
7461
  if (message.type === 'takeover') { beginTakeover(message); return; }
6619
7462
  if (message.type === 'stop') { finishStop(false, message.reason || 'server'); return; }
6620
7463
  if (message.type === 'mute') setMuted(message.muted, false);
@@ -6684,6 +7527,14 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6684
7527
  finishStop(false, 'connect-timeout'); publish('error', 'Connection timed out.');
6685
7528
  }, 10000);
6686
7529
  processor.port.onmessage = (event) => {
7530
+ if (event.data?.type === 'rendered' && realtimeAudio) {
7531
+ const audio = realtimeAudio;
7532
+ const stillCurrent = () => realtimeAudio === audio && socket === current && current.readyState === WebSocket.OPEN;
7533
+ void audio.rendered(event.data, stillCurrent).then((marker) => {
7534
+ if (marker && stillCurrent()) current.send(JSON.stringify({ type:'drained', id:marker }));
7535
+ }).catch(() => {});
7536
+ return;
7537
+ }
6687
7538
  const pcm = realtimeAudio
6688
7539
  ? realtimeAudio.acceptCapture(event.data)
6689
7540
  : event.data?.type === 'capture' && event.data.epoch === 0 && event.data.pcm instanceof ArrayBuffer ? event.data.pcm : undefined;
@@ -6691,7 +7542,7 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6691
7542
  };
6692
7543
  current.onopen = () => {
6693
7544
  if (socket !== current || !context) return;
6694
- clearTimeout(timer); current.send(JSON.stringify({ type:'start', mode, ...(takeoverToken ? { takeoverToken } : {}) })); publish('connecting');
7545
+ clearTimeout(timer); current.send(JSON.stringify({ type:'start', mode, playbackDrain:Boolean(realtimeAudio?.canDrain), ...(takeoverToken ? { takeoverToken } : {}) })); publish('connecting');
6695
7546
  };
6696
7547
  current.onmessage = (event) => receive(current, event);
6697
7548
  current.onclose = (event) => {
@@ -6700,213 +7551,82 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6700
7551
  if (mode === 'conversation' && ![1002, 1003, 1007, 1008, 1009, 4001].includes(event.code)) { retryConnection('Voice connection lost.'); return; }
6701
7552
  const failedTakeover = replacingCall || retryAttempt > 0;
6702
7553
  const detail = event.reason || 'Voice connection closed unexpectedly (' + event.code + ').';
6703
- finishStop(false, 'connection-closed'); publish('error', failedTakeover ? 'Check the server and connection, then start voice again.' : detail);
6704
- };
6705
- } catch (error) {
6706
- if (currentGeneration !== generation) return;
6707
- finishStop(false, 'start-error'); publish('error', error instanceof Error ? error.message : String(error));
6708
- } finally {
6709
- starting = false;
6710
- if (currentGeneration === generation && !socket) busy = false;
6711
- client._emit('audio', snapshot());
6712
- }
6713
- };
6714
- const beginTakeover = (command) => {
6715
- if (typeof command.token !== 'string' || !command.token || command.token.length > 256 || takeover) return;
6716
- const resume = mode === 'conversation' && (active || busy || Boolean(socket));
6717
- // Only an established audio runtime can be retained across replacement.
6718
- if (starting) { stop(undefined, false, 'takeover'); publish('error', 'Server changed during startup. Start voice again.'); return; }
6719
- takeover = { resume, token:command.token };
6720
- clearTimeout(retryTimer); retryTimer = undefined; retryAttempt = 0; retryDetail = '';
6721
- clearTimeout(staleEventsTimer); staleEventsTimer = undefined;
6722
- resumeMuted = muted;
6723
- active = false; busy = true; finishing = false;
6724
- const oldSocket = socket; socket = undefined;
6725
- if (oldSocket?.readyState === WebSocket.OPEN) oldSocket.send(JSON.stringify({ type:'takeover.ack', token:command.token }));
6726
- oldSocket?.close(1000, 'takeover');
6727
- realtimeAudio?.setSpeakerSuppressed(true);
6728
- if (!resume) closeHardware();
6729
- takeoverTimer = setTimeout(() => {
6730
- finishStop(false, 'takeover-timeout');
6731
- publish('error', 'New session did not become ready. Check the server, then start voice again.');
6732
- }, 20000);
6733
- publish('takeover', resume ? 'Reconnecting voice to the new session…' : 'Waiting for the new session…');
6734
- };
6735
- const completeTakeover = (command) => {
6736
- if (!takeover || command.takeoverToken !== takeover.token) return;
6737
- const { resume, token } = takeover;
6738
- clearTimeout(takeoverTimer); takeover = undefined; busy = false;
6739
- if (resume) { replacingCall = true; void start('conversation', token); }
6740
- else { resumeMuted = false; publish('idle', 'Connected to the new session'); }
6741
- };
6742
- const serverCommand = (command) => {
6743
- if (command.type === 'connection') {
6744
- if (command.state === 'connected') { clearTimeout(staleEventsTimer); staleEventsTimer = undefined; }
6745
- if (command.state === 'reconnecting' && !staleEventsTimer && !retryAttempt && !takeover && mode === 'conversation' && (active || socket)) {
6746
- staleEventsTimer = setTimeout(() => { staleEventsTimer = undefined; retryConnection('Server updates disconnected.'); }, 5000);
6747
- }
6748
- return;
6749
- }
6750
- if (command.type === 'takeover') { beginTakeover(command); return; }
6751
- if (command.type === 'ready') { completeTakeover(command); return; }
6752
- if (takeover) return;
6753
- if (command.type === 'stop') finishStop(false, command.reason || 'server');
6754
- if (command.type === 'error' && (active || busy || socket)) connectionError(command.message);
6755
- if (command.type === 'mute' && mode === 'conversation') setMuted(command.muted, false);
6756
- if (command.type === 'status' && busy && !active && !retryTimer) publish(command.status === 'summarizing…' ? 'summarizing' : 'connecting');
6757
- if (command.type === 'microphone') { inputTooQuiet = command.state === 'too-quiet'; if (active && !muted) publish('listening', inputTooQuiet ? 'Microphone level is too low' : ''); }
6758
- };
6759
- return {
6760
- start(...args) { assertOpen(); return start(...args); },
6761
- stop(...args) { assertOpen(); return stop(...args); },
6762
- setMuted(...args) { assertOpen(); return setMuted(...args); },
6763
- get state() { return snapshot(); },
6764
- _serverCommand: serverCommand,
6765
- _pagehide() {
6766
- if (finishing && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type:'cancel' }));
6767
- else if (active) navigator.sendBeacon('/api/stop', new Blob([JSON.stringify({ clientId:client.clientId })], {type:'application/json'}));
6768
- generation += 1; finishStop(false, 'pagehide');
6769
- },
6770
- _close() { if (finishing) stop(); else { generation += 1; finishStop(true, 'client-closed'); } },
6771
- };
6772
- }
6773
-
6774
- `;
6775
-
6776
- // packages/gippity-voice/src/voice/lan/client-sdk-script.ts
6777
- var LAN_REMOTE_CLIENT_SCRIPT = String.raw`
6778
- (function (global) {
6779
- 'use strict';
6780
- ${LAN_REMOTE_AUDIO_SCRIPT} function connect(options = {}) {
6781
- const clientId = options.clientId || id();
6782
- const listeners = new Map();
6783
- let closed = false, eventSource, rpcId = 0;
6784
- let draft = { type:'draft', text:'', revision:-1 };
6785
- let dirty = false, syncing = false, syncPromise, timer;
6786
- let resolveInitialDraft;
6787
- const initialDraft = new Promise((resolve) => { resolveInitialDraft = resolve; });
6788
- const assertOpen = () => { if (closed) throw new Error('GipPity remote is closed'); };
6789
-
6790
- const emit = (type, value, wildcard = true) => {
6791
- for (const listener of listeners.get(type) || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6792
- if (wildcard && type !== '*') for (const listener of listeners.get('*') || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6793
- };
6794
- const post = async (path, body) => {
6795
- assertOpen();
6796
- const response = await fetch(path, { method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({ clientId, ...body }) });
6797
- const result = await response.json().catch(() => ({}));
6798
- if (!response.ok) throw new Error(result.error || 'Pi rejected the request');
6799
- return result;
6800
- };
6801
- const client = {
6802
- clientId,
6803
- _emit: emit,
6804
- _post: post,
6805
- get draft() { return { ...draft }; },
6806
- on(type, listener) {
6807
- assertOpen();
6808
- if (typeof listener !== 'function') throw new Error('Event listener must be a function');
6809
- let group = listeners.get(type); if (!group) { group = new Set(); listeners.set(type, group); }
6810
- group.add(listener); return () => group.delete(listener);
6811
- },
6812
- async call(target, method, ...args) {
6813
- const id = ++rpcId;
6814
- const result = await post('/api/rpc', { id, target, method, args });
6815
- if (!result.ok) {
6816
- const error = new Error(result.error?.message || 'Pi RPC failed');
6817
- if (result.error?.name) error.name = result.error.name;
6818
- throw error;
6819
- }
6820
- return result.result;
6821
- },
6822
- setDraft(text) {
6823
- assertOpen();
6824
- if (typeof text !== 'string') throw new Error('Draft text must be a string');
6825
- draft = { ...draft, text, local:true };
6826
- dirty = true; emit('draft', { ...draft });
6827
- clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180);
6828
- },
6829
- flushDraft: () => flush(),
6830
- async send(text) {
6831
- if (typeof text === 'string' && text !== draft.text) client.setDraft(text);
6832
- clearTimeout(timer);
6833
- await flush();
6834
- if (!draft.text.trim()) throw new Error('A message is required');
6835
- await post('/api/send', { text:draft.text, revision:draft.revision });
6836
- },
6837
- close() {
6838
- if (closed) return; clearTimeout(timer);
6839
- client.audio._close(); closed = true; resolveInitialDraft();
6840
- navigator.sendBeacon('/api/draft', new Blob([JSON.stringify({ clientId, text:draft.text, revision:draft.revision })], {type:'application/json'}));
6841
- global.removeEventListener('pagehide', pagehide);
6842
- eventSource?.close(); listeners.clear();
6843
- },
6844
- };
6845
- const flush = async () => {
6846
- if (closed) throw new Error('GipPity remote is closed');
6847
- if (syncing) return syncPromise;
6848
- if (!dirty) return true;
6849
- syncing = true;
6850
- syncPromise = (async () => {
6851
- if (draft.revision < 0) await initialDraft;
6852
- if (closed) throw new Error('GipPity remote is closed');
6853
- while (dirty) {
6854
- if (closed) throw new Error('GipPity remote is closed');
6855
- dirty = false;
6856
- const text = draft.text;
6857
- try {
6858
- const result = await post('/api/draft', { text, revision:draft.revision });
6859
- if (typeof result.revision === 'number') draft = { ...draft, revision:Math.max(draft.revision, result.revision) };
6860
- } catch (error) {
6861
- dirty = true; emit('error', { type:'error', source:'draft', message:error instanceof Error ? error.message : String(error) });
6862
- throw error;
6863
- }
6864
- }
6865
- return true;
6866
- })();
6867
- try { return await syncPromise; }
6868
- finally { syncing = false; syncPromise = undefined; }
7554
+ finishStop(false, 'connection-closed'); publish('error', failedTakeover ? 'Check the server and connection, then start voice again.' : detail);
7555
+ };
7556
+ } catch (error) {
7557
+ if (currentGeneration !== generation) return;
7558
+ finishStop(false, 'start-error'); publish('error', error instanceof Error ? error.message : String(error));
7559
+ } finally {
7560
+ starting = false;
7561
+ if (currentGeneration === generation && !socket) busy = false;
7562
+ client._emit('audio', snapshot());
7563
+ }
6869
7564
  };
6870
- const applyDraft = (command) => {
6871
- if (typeof command.text !== 'string' || typeof command.revision !== 'number' || command.revision < draft.revision) return;
6872
- if (draft.revision < 0 && dirty) {
6873
- draft = { ...draft, revision:command.revision };
6874
- resolveInitialDraft(); emit('draft', { ...draft }); return;
6875
- }
6876
- const reconnectSnapshot = !command.sourceClientId && !command.reason;
6877
- const preserveLocal = (dirty || syncing) && draft.text !== command.text && (reconnectSnapshot || (command.sourceClientId === clientId && (command.reason === 'update' || command.reason === 'sent')));
6878
- draft = preserveLocal ? { ...draft, revision:command.revision } : { ...command };
6879
- if (!preserveLocal && command.sourceClientId !== clientId) { clearTimeout(timer); dirty = false; }
6880
- if (reconnectSnapshot && preserveLocal && dirty) { clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180); }
6881
- resolveInitialDraft();
6882
- emit('draft', { ...draft });
7565
+ const beginTakeover = (command) => {
7566
+ if (typeof command.token !== 'string' || !command.token || command.token.length > 256 || takeover) return;
7567
+ const resume = mode === 'conversation' && (active || busy || Boolean(socket));
7568
+ // Only an established audio runtime can be retained across replacement.
7569
+ if (starting) { stop(undefined, false, 'takeover'); publish('error', 'Server changed during startup. Start voice again.'); return; }
7570
+ takeover = { resume, token:command.token };
7571
+ clearTimeout(retryTimer); retryTimer = undefined; retryAttempt = 0; retryDetail = '';
7572
+ clearTimeout(staleEventsTimer); staleEventsTimer = undefined;
7573
+ resumeMuted = muted;
7574
+ active = false; busy = true; finishing = false;
7575
+ const oldSocket = socket; socket = undefined;
7576
+ if (oldSocket?.readyState === WebSocket.OPEN) oldSocket.send(JSON.stringify({ type:'takeover.ack', token:command.token }));
7577
+ oldSocket?.close(1000, 'takeover');
7578
+ realtimeAudio?.setSpeakerSuppressed(true);
7579
+ if (!resume) closeHardware();
7580
+ takeoverTimer = setTimeout(() => {
7581
+ finishStop(false, 'takeover-timeout');
7582
+ publish('error', 'New session did not become ready. Check the server, then start voice again.');
7583
+ }, 20000);
7584
+ publish('takeover', resume ? 'Reconnecting voice to the new session…' : 'Waiting for the new session…');
6883
7585
  };
6884
- client.audio = createAudio(client, assertOpen);
6885
- eventSource = new EventSource('/api/events?client=' + encodeURIComponent(clientId));
6886
- const connectionState = (state) => {
6887
- const command = { type:'connection', state };
6888
- client.audio._serverCommand(command); emit('connection', command);
7586
+ const completeTakeover = (command) => {
7587
+ if (!takeover || command.takeoverToken !== takeover.token) return;
7588
+ const { resume, token } = takeover;
7589
+ clearTimeout(takeoverTimer); takeover = undefined; busy = false;
7590
+ if (resume) { replacingCall = true; void start('conversation', token); }
7591
+ else { resumeMuted = false; publish('idle', 'Connected to the new session'); }
6889
7592
  };
6890
- eventSource.onopen = () => connectionState('connected');
6891
- eventSource.onerror = () => connectionState('reconnecting');
6892
- eventSource.onmessage = (event) => {
6893
- try {
6894
- const command = JSON.parse(event.data);
6895
- client.audio._serverCommand(command);
6896
- if (command.type === 'draft') applyDraft(command);
6897
- else emit(command.type, command);
6898
- if (command.type === 'durable.event') emit('durable:' + command.event, command.data, false);
6899
- } catch {}
7593
+ const serverCommand = (command) => {
7594
+ if (command.type === 'connection') {
7595
+ if (command.state === 'connected') { clearTimeout(staleEventsTimer); staleEventsTimer = undefined; }
7596
+ if (command.state === 'reconnecting' && !staleEventsTimer && !retryAttempt && !takeover && mode === 'conversation' && (active || socket)) {
7597
+ staleEventsTimer = setTimeout(() => { staleEventsTimer = undefined; retryConnection('Server updates disconnected.'); }, 5000);
7598
+ }
7599
+ return;
7600
+ }
7601
+ if (command.type === 'takeover') { beginTakeover(command); return; }
7602
+ if (command.type === 'ready') { completeTakeover(command); return; }
7603
+ if (takeover) return;
7604
+ if (command.type === 'stop') finishStop(false, command.reason || 'server');
7605
+ if (command.type === 'error' && (active || busy || socket)) connectionError(command.message);
7606
+ if (command.type === 'mute' && mode === 'conversation') setMuted(command.muted, false);
7607
+ if (command.type === 'status' && busy && !active && !retryTimer) publish(command.status === 'summarizing…' ? 'summarizing' : 'connecting');
7608
+ if (command.type === 'microphone') { inputTooQuiet = command.state === 'too-quiet'; if (active && !muted) publish('listening', inputTooQuiet ? 'Microphone level is too low' : ''); }
7609
+ };
7610
+ return {
7611
+ start(...args) { assertOpen(); return start(...args); },
7612
+ stop(...args) { assertOpen(); return stop(...args); },
7613
+ setMuted(...args) { assertOpen(); return setMuted(...args); },
7614
+ get state() { return snapshot(); },
7615
+ _serverCommand: serverCommand,
7616
+ _pagehide() {
7617
+ if (finishing && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type:'cancel' }));
7618
+ else if (active) navigator.sendBeacon('/api/stop', new Blob([JSON.stringify({ clientId:client.clientId })], {type:'application/json'}));
7619
+ generation += 1; finishStop(false, 'pagehide');
7620
+ },
7621
+ _close() { if (finishing) stop(); else { generation += 1; finishStop(true, 'client-closed'); } },
6900
7622
  };
6901
- const pagehide = () => { client.audio._pagehide(); clearTimeout(timer); navigator.sendBeacon('/api/draft', new Blob([JSON.stringify({ clientId, text:draft.text, revision:draft.revision })], {type:'application/json'})); };
6902
- global.addEventListener('pagehide', pagehide);
6903
- return client;
6904
7623
  }
6905
7624
 
6906
- global.GippityRemote = Object.freeze({ connect });
6907
- })(globalThis);
6908
7625
  `;
6909
7626
 
7627
+ // packages/gippity-voice/src/voice/lan/client-sdk-script.ts
7628
+ var LAN_REMOTE_CLIENT_SCRIPT = lanClientScript(LAN_REMOTE_AUDIO_SCRIPT);
7629
+
6910
7630
  // packages/gippity-voice/src/voice/lan/dictation.ts
6911
7631
  class LanVoiceDictation {
6912
7632
  resolveAuth;
@@ -6996,92 +7716,6 @@ class LanVoiceDictation {
6996
7716
  // packages/gippity-voice/src/voice/lan/discovery.ts
6997
7717
  var LAN_REMOTE_CLIENT_PATH = "/_gippity/client.js";
6998
7718
 
6999
- // packages/gippity-voice/src/voice/lan/draft.ts
7000
- var MAX_LAN_VOICE_DRAFT_BYTES = 64 * 1024;
7001
-
7002
- class LanVoiceDraftError extends Error {
7003
- }
7004
-
7005
- class LanVoiceDraftConflictError extends LanVoiceDraftError {
7006
- }
7007
-
7008
- class LanVoiceDraft {
7009
- publish;
7010
- sendMessage;
7011
- text = "";
7012
- revision = 0;
7013
- sending = false;
7014
- constructor(options) {
7015
- this.publish = options.publish;
7016
- this.sendMessage = options.sendMessage;
7017
- }
7018
- snapshot(sourceClientId, reason) {
7019
- return {
7020
- type: "draft",
7021
- text: this.text,
7022
- revision: this.revision,
7023
- ...sourceClientId ? { sourceClientId } : {},
7024
- ...reason ? { reason } : {}
7025
- };
7026
- }
7027
- update(clientId, value, expectedRevision) {
7028
- this.assertRevision(expectedRevision);
7029
- this.text = validatedDraft(value);
7030
- this.revision += 1;
7031
- this.publish(this.snapshot(clientId, "update"));
7032
- return this.revision;
7033
- }
7034
- insertTranscript(clientId, transcript, selection) {
7035
- const clean = transcript.trim();
7036
- if (!clean)
7037
- return;
7038
- const start = boundedIndex(selection?.start, this.text.length, this.text.length);
7039
- const end = boundedIndex(selection?.end, this.text.length, start);
7040
- const before = this.text.slice(0, Math.min(start, end));
7041
- const after = this.text.slice(Math.max(start, end));
7042
- const leftSpace = before && !/\s$/.test(before) ? " " : "";
7043
- const rightSpace = after && !/^\s/.test(after) ? " " : "";
7044
- this.text = validatedDraft(`${before}${leftSpace}${clean}${rightSpace}${after}`);
7045
- this.revision += 1;
7046
- this.publish(this.snapshot(clientId, "transcript"));
7047
- }
7048
- async send(clientId, value, expectedRevision) {
7049
- this.assertRevision(expectedRevision);
7050
- if (this.sending)
7051
- throw new LanVoiceDraftConflictError("A message is already being sent");
7052
- const text = validatedDraft(value);
7053
- if (!text.trim())
7054
- throw new LanVoiceDraftError("A message is required");
7055
- this.text = text;
7056
- const revision = this.revision;
7057
- this.sending = true;
7058
- try {
7059
- await this.sendMessage(text);
7060
- } finally {
7061
- this.sending = false;
7062
- }
7063
- if (this.revision === revision && this.text === text)
7064
- this.text = "";
7065
- this.revision += 1;
7066
- this.publish({ type: "sent" });
7067
- this.publish(this.snapshot(clientId, "sent"));
7068
- }
7069
- assertRevision(value) {
7070
- if (!Number.isInteger(value) || value !== this.revision)
7071
- throw new LanVoiceDraftConflictError("Draft changed on another device; review it and try again");
7072
- }
7073
- }
7074
- function validatedDraft(value) {
7075
- if (typeof value !== "string")
7076
- throw new LanVoiceDraftError("Draft text is required");
7077
- if (Buffer.byteLength(value) > MAX_LAN_VOICE_DRAFT_BYTES)
7078
- throw new LanVoiceDraftError("Draft is too large");
7079
- return value;
7080
- }
7081
- function boundedIndex(value, length, fallback) {
7082
- return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= length ? value : fallback;
7083
- }
7084
-
7085
7719
  // packages/gippity-voice/src/voice/lan/browser-audio-script.ts
7086
7720
  var LAN_VOICE_BROWSER_AUDIO_SCRIPT = String.raw`
7087
7721
  function createAudioController({ button, muteButton, audioState, audioDetail, modeButtons, composer, client }) {
@@ -7613,7 +8247,8 @@ async function startGippityLanServer(options) {
7613
8247
  const factory = () => {
7614
8248
  browserPeer = new LanHostRealtimePeer(options.audio, {
7615
8249
  onAudio: (pcm) => clients.sendConversationAudio(pcm),
7616
- onSpeakerSuppressed: (suppressed) => clients.setConversationSpeakerSuppressed(suppressed)
8250
+ onSpeakerSuppressed: (suppressed) => clients.setConversationSpeakerSuppressed(suppressed),
8251
+ drain: (signal, seal) => clients.drainPlayback(signal, seal)
7617
8252
  });
7618
8253
  return browserPeer;
7619
8254
  };
@@ -7976,13 +8611,13 @@ data: {}
7976
8611
  server.on("error", (error) => clients.broadcastControl({ type: "error", message: error.message }));
7977
8612
  return {
7978
8613
  urls: origins.map((origin) => `${origin.origin}/`),
7979
- browserAttached: () => [...sockets.clients].some((peer) => peer.readyState === WebSocket5.OPEN),
8614
+ browserAttached: () => [...sockets.clients].some((peer) => peer.readyState === WebSocket6.OPEN),
7980
8615
  hasConversation: () => browserVoice && controls.active,
7981
8616
  acknowledgeTakeover: (token) => clients.takeover(token),
7982
8617
  async proveTakeover(verify) {
7983
8618
  if (takeoverProof)
7984
8619
  throw new Error("A LAN listener proof is already pending");
7985
- const token = randomUUID4();
8620
+ const token = randomUUID5();
7986
8621
  takeoverProof = token;
7987
8622
  try {
7988
8623
  await verify({ port: permission.port, token });
@@ -8083,6 +8718,72 @@ async function readBody(request) {
8083
8718
  return body;
8084
8719
  }
8085
8720
 
8721
+ // internal/voice/browser-settings.ts
8722
+ function setting(name, label, value, list) {
8723
+ const choices = list ? [...new Set([...list, value])].map((entry) => ({
8724
+ value: entry,
8725
+ label: entry === null ? "Off" : String(entry)
8726
+ })) : undefined;
8727
+ return { name, label, value, ...choices ? { choices } : {} };
8728
+ }
8729
+
8730
+ // packages/gippity-voice/src/voice/lan/unified-settings.ts
8731
+ var switches = {
8732
+ webSearch: "Web search",
8733
+ autoResumeRealtime: "Resume after interruption",
8734
+ refreshRealtimeAfterCompaction: "Refresh after context compaction",
8735
+ delegationAcknowledgements: "Acknowledge delegated requests",
8736
+ forwardReasoningSummaries: "Relay reasoning summaries"
8737
+ };
8738
+ var modelId = (model) => `${model.provider}/${model.modelId}`;
8739
+ function gippityBrowserFields(config, models, contextAllowed) {
8740
+ const ids = models.map(modelId);
8741
+ return [
8742
+ setting("model", "Model", config.model, GIPPITY_VOICE_MODELS),
8743
+ setting("apiProvider", "API provider", config.apiProvider),
8744
+ setting("realtimeVoice", "Realtime voice", config.realtimeVoice, OPENAI_REALTIME_VOICES),
8745
+ setting("realtimeAlternateVoice", "Alternate Realtime voice", config.realtimeAlternateVoice, OPENAI_REALTIME_VOICES),
8746
+ setting("v3Voice", "Live voice", config.v3Voice, REALTIME_V3_VOICES),
8747
+ setting("v3AlternateVoice", "Alternate Live voice", config.v3AlternateVoice, REALTIME_V3_VOICES),
8748
+ setting("taskDelegationModel", "Delegation model", config.taskDelegationModel, ids),
8749
+ setting("taskDelegationReasoning", "Delegation reasoning", config.taskDelegationReasoning, VOICE_CONTEXT_REASONING_LEVELS),
8750
+ ...contextAllowed ? [
8751
+ setting("contextModel", "Context summary model", config.contextModel ? modelId(config.contextModel) : null, [null, ...ids]),
8752
+ setting("contextReasoning", "Context summary reasoning", config.contextReasoning, VOICE_CONTEXT_REASONING_LEVELS)
8753
+ ] : [],
8754
+ ...Object.entries(switches).map(([name, label]) => {
8755
+ const value = Object.getOwnPropertyDescriptor(config, name)?.value === true;
8756
+ return setting(name, label, value);
8757
+ })
8758
+ ];
8759
+ }
8760
+ function decodeGippityBrowserSettings(patch, config, models, contextAllowed) {
8761
+ const fields = gippityBrowserFields(config, models, contextAllowed);
8762
+ const decoded = {};
8763
+ for (const [key, value] of Object.entries(patch)) {
8764
+ const field = fields.find((field) => field.name === key);
8765
+ if (!field || (field.choices ? !field.choices.some((entry) => entry.value === value) : typeof value !== typeof field.value))
8766
+ throw new Error("Invalid GipPity browser setting");
8767
+ if (key === "contextModel") {
8768
+ decoded[key] = value === null ? undefined : [
8769
+ ...models,
8770
+ ...config.contextModel ? [config.contextModel] : []
8771
+ ].find((model) => modelId(model) === value);
8772
+ if (value === null)
8773
+ decoded["refreshRealtimeAfterCompaction"] = false;
8774
+ } else if (key === "apiProvider") {
8775
+ const provider = normalizeVoiceApiProvider(value);
8776
+ if (!provider)
8777
+ throw new Error("Enter a valid API provider name");
8778
+ decoded[key] = provider;
8779
+ } else
8780
+ decoded[key] = value;
8781
+ }
8782
+ if (Object.hasOwn(decoded, "contextModel") && decoded["contextModel"] === undefined)
8783
+ decoded["refreshRealtimeAfterCompaction"] = false;
8784
+ return decoded;
8785
+ }
8786
+
8086
8787
  // packages/gippity-voice/src/voice/realtime-auth.ts
8087
8788
  async function resolvePublicRealtimeAuth(models, name, signal, access) {
8088
8789
  if (!normalizeVoiceApiProvider(name))
@@ -8149,7 +8850,10 @@ async function resolvePublicRealtimeAuth(models, name, signal, access) {
8149
8850
 
8150
8851
  // packages/gippity-voice/src/voice/realtime-tools.ts
8151
8852
  function createRealtimeAccess(agent, webSearch, execute) {
8152
- const tools = agent.tools.filter((tool) => !readToolContract(tool).nativeOnly && agent.callable.some((candidate) => candidate.name === tool.name));
8853
+ const tools = agent.tools.filter((tool) => {
8854
+ const contract = readToolContract(tool);
8855
+ return !contract.nativeOnly && !contract.nestedHidden && agent.callable.some((candidate) => candidate.name === tool.name);
8856
+ });
8153
8857
  const selected = new Set;
8154
8858
  for (const tool of tools) {
8155
8859
  if (!tool.name || ["send_task", "end_call", "web_search"].includes(tool.name) || selected.has(tool.name))
@@ -8401,9 +9105,9 @@ function createGippityVoice(options) {
8401
9105
  throw new Error("Voice requires explicit audio permission, namespace, and instructions");
8402
9106
  if (options.lan && options.lan.namespace !== options.namespace || options.appFiles && options.appFiles.namespace !== options.namespace)
8403
9107
  throw new Error("Voice host capabilities must share the conversation namespace");
8404
- const instance = randomUUID5();
9108
+ const instance = randomUUID6();
8405
9109
  const leaseOwner = `${registrationName}:${instance}`;
8406
- let providerSessionId = randomUUID5();
9110
+ let providerSessionId = randomUUID6();
8407
9111
  let harness;
8408
9112
  let conversationId;
8409
9113
  let conversation;
@@ -8421,6 +9125,8 @@ function createGippityVoice(options) {
8421
9125
  let session;
8422
9126
  let activeCallId;
8423
9127
  let dictation;
9128
+ let browserAudio;
9129
+ const preparedBrowsers = new WeakMap;
8424
9130
  let lease;
8425
9131
  let peerFactory;
8426
9132
  let activeConfig;
@@ -8443,6 +9149,14 @@ function createGippityVoice(options) {
8443
9149
  const contextSummaryCache = new VoiceContextSummaryCache;
8444
9150
  const listeners = new Set;
8445
9151
  const publish = (event) => {
9152
+ if (browserAudio?.mode === "voice") {
9153
+ if (event.type === "status")
9154
+ browserAudio.status = event.status;
9155
+ else if (event.type === "transcript" && event.role === "user")
9156
+ browserAudio.transcript = event.text;
9157
+ else if (event.type === "error")
9158
+ browserAudio.error = event.message;
9159
+ }
8446
9160
  options.present?.(event);
8447
9161
  for (const listener of listeners)
8448
9162
  listener(event.type, event);
@@ -8480,6 +9194,16 @@ function createGippityVoice(options) {
8480
9194
  }
8481
9195
  }
8482
9196
  };
9197
+ const loadConfig = async () => {
9198
+ await loadPreferences();
9199
+ if (!saved && options.settings) {
9200
+ const loaded = normalizeGippityControlConfig(await options.settings.read());
9201
+ if (!saved) {
9202
+ config = loaded;
9203
+ saved = true;
9204
+ }
9205
+ }
9206
+ };
8483
9207
  const enqueue = (work) => {
8484
9208
  const result = serial.then(work);
8485
9209
  serial = result.then(() => {}, () => {});
@@ -8487,7 +9211,7 @@ function createGippityVoice(options) {
8487
9211
  };
8488
9212
  const changeConfig = (create) => {
8489
9213
  const result = configSerial.then(async () => {
8490
- await loadPreferences();
9214
+ await loadConfig();
8491
9215
  if (settingsContribution && options.preferences) {
8492
9216
  const next = mergeGippityPreferences(validateGippityPreferences(create()));
8493
9217
  const snapshot = await settingsContribution.read();
@@ -8557,6 +9281,8 @@ function createGippityVoice(options) {
8557
9281
  handoffGrant = undefined;
8558
9282
  await Promise.all([...incomingBindings].map((binding) => binding.grant.release()));
8559
9283
  incomingBindings.clear();
9284
+ await browserAudio?.close();
9285
+ browserAudio = undefined;
8560
9286
  session = undefined;
8561
9287
  activeCallId = undefined;
8562
9288
  dictation = undefined;
@@ -8588,7 +9314,7 @@ function createGippityVoice(options) {
8588
9314
  await api.commit(() => ({ status: "running", checkpoint: { phase: "active" } }), context);
8589
9315
  },
8590
9316
  async active(record, api, context) {
8591
- const nonce = randomUUID5();
9317
+ const nonce = randomUUID6();
8592
9318
  if (record.input.instance !== instance || await api.memo("started", nonce, context) !== nonce) {
8593
9319
  await api.commit(() => ({
8594
9320
  status: "terminal",
@@ -8614,11 +9340,7 @@ function createGippityVoice(options) {
8614
9340
  runtimeContext = context;
8615
9341
  closing = false;
8616
9342
  await configSerial;
8617
- await loadPreferences();
8618
- if (!saved && options.settings) {
8619
- config = normalizeGippityControlConfig(await options.settings.read());
8620
- saved = true;
8621
- }
9343
+ await loadConfig();
8622
9344
  events = await observeVoiceAgent(conversation, context, {
8623
9345
  state(value) {
8624
9346
  if (transferred)
@@ -8695,7 +9417,7 @@ function createGippityVoice(options) {
8695
9417
  if (runtime && !closing)
8696
9418
  return;
8697
9419
  if (serviceStart)
8698
- return awaitWithContext2(serviceStart, context);
9420
+ return awaitWithContext3(serviceStart, context);
8699
9421
  if (!harness || !conversationId)
8700
9422
  throw new Error("Bind voice to its Harness and conversation first");
8701
9423
  ready = deferred();
@@ -8716,7 +9438,7 @@ function createGippityVoice(options) {
8716
9438
  serviceStart = undefined;
8717
9439
  throw error;
8718
9440
  });
8719
- return awaitWithContext2(serviceStart, context);
9441
+ return awaitWithContext3(serviceStart, context);
8720
9442
  }
8721
9443
  async function passive(kind, data, text) {
8722
9444
  if (!conversation || !runtimeContext)
@@ -8760,7 +9482,7 @@ function createGippityVoice(options) {
8760
9482
  throw new Error("Context summary export requires explicit host permission");
8761
9483
  const project = async () => {
8762
9484
  const view = await conversation.context(context);
8763
- return options.projectContext && settings.voice.contextModel ? options.projectContext({ conversationId: runtime.conversationId, view }, withAbortSignal(signal, context)) : view;
9485
+ return options.projectContext && settings.voice.contextModel ? options.projectContext({ conversationId: runtime.conversationId, view }, withAbortSignal2(signal, context)) : view;
8764
9486
  };
8765
9487
  const view = await project();
8766
9488
  const input = voiceContextSummaryInput(runtime.conversationId, view, settings);
@@ -8785,12 +9507,12 @@ function createGippityVoice(options) {
8785
9507
  const execute = async (name, args, toolContext) => {
8786
9508
  toolContext.signal.throwIfAborted();
8787
9509
  let id;
8788
- const context = withAbortSignal(toolContext.signal, runtimeContext);
9510
+ const context = withAbortSignal2(toolContext.signal, runtimeContext);
8789
9511
  await runtime.commit(async (tx) => {
8790
9512
  id = await tx.createTask(toolTask, { name, arguments: args }, { ownership: { kind: "task", taskId: runtime.taskId } });
8791
9513
  }, context);
8792
9514
  const abort = () => {
8793
- harness.abortTask(id, BACKGROUND_CONTEXT).catch(report);
9515
+ harness.abortTask(id, BACKGROUND_CONTEXT2).catch(report);
8794
9516
  };
8795
9517
  toolContext.signal.addEventListener("abort", abort, { once: true });
8796
9518
  try {
@@ -8802,8 +9524,8 @@ function createGippityVoice(options) {
8802
9524
  } finally {
8803
9525
  toolContext.signal.removeEventListener("abort", abort);
8804
9526
  if (toolContext.signal.aborted) {
8805
- await harness.abortTask(id, BACKGROUND_CONTEXT);
8806
- await harness.waitForTask(id, BACKGROUND_CONTEXT);
9527
+ await harness.abortTask(id, BACKGROUND_CONTEXT2);
9528
+ await harness.waitForTask(id, BACKGROUND_CONTEXT2);
8807
9529
  }
8808
9530
  }
8809
9531
  };
@@ -8822,7 +9544,7 @@ function createGippityVoice(options) {
8822
9544
  const auth = await resolveAuth(signal, settings);
8823
9545
  signal.throwIfAborted();
8824
9546
  const peer = factory();
8825
- const callId = randomUUID5();
9547
+ const callId = randomUUID6();
8826
9548
  let current;
8827
9549
  current = new CodexRealtimeConversation({
8828
9550
  onStatus: (status) => publish({ type: "status", status }),
@@ -8838,8 +9560,12 @@ function createGippityVoice(options) {
8838
9560
  rewriteDelegation: (turn, signal) => rewriteTaskDelegation(requireRuntime().runtime.models, settings.voice, turn, signal),
8839
9561
  onDelegationError: report,
8840
9562
  onEndCall: () => {
8841
- current.waitForFinalPlayback().then(() => enqueue(async () => {
8842
- if (session === current && current.isEndingCall)
9563
+ current.waitForFinalPlayback().catch((error) => {
9564
+ if (!current.playbackSealed)
9565
+ throw error;
9566
+ report(error);
9567
+ }).then(() => enqueue(async () => {
9568
+ if (session === current && (current.isEndingCall || current.playbackSealed))
8843
9569
  await stopSession(true);
8844
9570
  })).catch(report);
8845
9571
  },
@@ -8909,7 +9635,9 @@ function createGippityVoice(options) {
8909
9635
  signal.removeEventListener("abort", abort);
8910
9636
  }
8911
9637
  }
8912
- async function startVoice(context, factory = () => new NativeCodexRealtimePeer(options.audio), replace = false, startup) {
9638
+ async function startVoice(context, factory = () => new NativeCodexRealtimePeer(options.audio), replace = false, startup, browser) {
9639
+ if (browserAudio !== browser)
9640
+ throw new Error("Stop the shared browser session first");
8913
9641
  if (!startup && transferred)
8914
9642
  return transferred.startCall();
8915
9643
  if (!startup && selectedCall)
@@ -8919,6 +9647,8 @@ function createGippityVoice(options) {
8919
9647
  return enqueue(async () => {
8920
9648
  if (requestedEpoch !== startEpoch)
8921
9649
  throw new Error("Voice startup cancelled");
9650
+ if (browserAudio !== browser)
9651
+ throw new Error("Stop the shared browser session first");
8922
9652
  if (dictation || transferring && !startup || transferred || session && !replace || lease && !session)
8923
9653
  throw new Error("Voice or dictation is already active");
8924
9654
  const previous = session;
@@ -9044,6 +9774,8 @@ ${tail}
9044
9774
  if (!options.lan)
9045
9775
  throw new Error("HTTPS LAN permission was not supplied");
9046
9776
  await enqueue(async () => {
9777
+ if (browserAudio)
9778
+ throw new Error("Stop the shared browser session first");
9047
9779
  if (lan) {
9048
9780
  if (takeover)
9049
9781
  throw new Error("LAN takeover requires a free listener");
@@ -9076,7 +9808,7 @@ ${tail}
9076
9808
  if (taskId || runtime || serviceStart)
9077
9809
  throw new Error("Stop voice before switching conversation");
9078
9810
  if (harness !== value || conversationId !== target) {
9079
- providerSessionId = randomUUID5();
9811
+ providerSessionId = randomUUID6();
9080
9812
  contextSummaryCache.clear();
9081
9813
  }
9082
9814
  harness = value;
@@ -9116,7 +9848,7 @@ ${tail}
9116
9848
  lan?.broadcast({ type: "mute", muted });
9117
9849
  },
9118
9850
  get active() {
9119
- return Boolean(session || dictation || transferred);
9851
+ return Boolean(session || dictation || transferred || browserAudio);
9120
9852
  },
9121
9853
  async startDictation(context) {
9122
9854
  const requestedEpoch = startEpoch;
@@ -9124,7 +9856,7 @@ ${tail}
9124
9856
  await enqueue(async () => {
9125
9857
  if (requestedEpoch !== startEpoch)
9126
9858
  throw new Error("Dictation startup cancelled");
9127
- if (session || dictation || lease || transferring || transferred)
9859
+ if (session || dictation || lease || transferring || transferred || browserAudio)
9128
9860
  throw new Error("Voice or dictation is already active");
9129
9861
  const { runtime } = requireRuntime();
9130
9862
  startAbort = new AbortController;
@@ -9183,7 +9915,7 @@ ${tail}
9183
9915
  type: "input",
9184
9916
  content: text,
9185
9917
  whenBusy: "steer",
9186
- requestId: randomUUID5()
9918
+ requestId: randomUUID6()
9187
9919
  }, context);
9188
9920
  },
9189
9921
  async rpc(body) {
@@ -9344,7 +10076,9 @@ ${tail}
9344
10076
  get summary() {
9345
10077
  return summary;
9346
10078
  },
9347
- async depart(channel, context, transport = "webrtc") {
10079
+ async depart(channel, context, transport = "webrtc", browser) {
10080
+ if (browser && browserAudio !== browser.owner)
10081
+ throw new Error("Browser call changed before departure");
9348
10082
  if (transport !== "webrtc")
9349
10083
  throw new Error("GipPity handoff requires WebRTC; PCM conversion is not available");
9350
10084
  if (!options.handoff || transferring || transferred || !session || !peerFactory || !activeConfig || !lease && (!handoffLink || !handoffGrant))
@@ -9428,7 +10162,7 @@ ${tail}
9428
10162
  },
9429
10163
  async waitForSettled(signal) {
9430
10164
  await source.waitForInput(signal);
9431
- await awaitWithContext2(conversation.waitForIdle(context), context);
10165
+ await awaitWithContext3(conversation.waitForIdle(context), context);
9432
10166
  signal.throwIfAborted();
9433
10167
  await source.waitForPlaybackEnd(signal);
9434
10168
  },
@@ -9437,6 +10171,19 @@ ${tail}
9437
10171
  transferred = value;
9438
10172
  },
9439
10173
  onClosed: report,
10174
+ ...browser ? {
10175
+ browser: {
10176
+ transfer: browser.transfer,
10177
+ async release() {
10178
+ if (browserAudio !== browser.owner || session)
10179
+ throw new Error("Browser call changed during departure");
10180
+ browserAudio = undefined;
10181
+ await browser.owner.close();
10182
+ await releaseLease();
10183
+ await browser.transfer.releaseListener();
10184
+ }
10185
+ }
10186
+ } : {},
9440
10187
  ...lan?.hasConversation() ? {
9441
10188
  lanTakeover: async (offer, releaseAudio, verify) => {
9442
10189
  const server = lan;
@@ -9475,7 +10222,7 @@ ${tail}
9475
10222
  transferring = false;
9476
10223
  }
9477
10224
  },
9478
- async arrive(channel, continuity, context, transport = "webrtc") {
10225
+ async arrive(channel, continuity, context, transport = "webrtc", reservation) {
9479
10226
  if (transport !== "webrtc")
9480
10227
  throw new Error("GipPity handoff requires WebRTC; PCM conversion is not available");
9481
10228
  const returning = Boolean(transferred && sourceBindings.size && !session && !dictation);
@@ -9483,7 +10230,6 @@ ${tail}
9483
10230
  throw new Error("Destination voice is busy or handoff is unauthorized");
9484
10231
  if (Buffer.byteLength(continuity) > 64 * 1024)
9485
10232
  throw new Error("Voice handoff continuity is oversized");
9486
- transferring = true;
9487
10233
  let remote;
9488
10234
  let removeStartupAbort;
9489
10235
  let lanCommitted = false;
@@ -9494,6 +10240,10 @@ ${tail}
9494
10240
  const previousIncoming = handoffLink;
9495
10241
  const previousGrant = handoffGrant;
9496
10242
  const previousAbort = startAbort;
10243
+ if (reservation && (returning || !harness || !conversationId || !reservation.ownsBrowserProvider(harness, conversationId, browserProvider))) {
10244
+ throw new Error("OpenAI browser reservation belongs to a different destination");
10245
+ }
10246
+ transferring = true;
9497
10247
  try {
9498
10248
  await ensureService(context);
9499
10249
  const { runtime } = requireRuntime();
@@ -9508,12 +10258,15 @@ ${tail}
9508
10258
  const prepared = await prepareSummary(signal);
9509
10259
  await resolveAuth(signal);
9510
10260
  let lanPreparation;
10261
+ const browserPreparation = reservation && prepareBrowserReservation(reservation, withAbortSignal2(signal, context));
9511
10262
  try {
9512
- if (options.lan && !lan)
10263
+ if (!reservation && options.lan && !lan)
9513
10264
  lanPreparation = prepareLanTakeover(options.lan);
9514
10265
  } catch {}
9515
10266
  const link = new VoiceHandoffLink(channel, {
9516
10267
  async request(method, value) {
10268
+ if (method === "browser.verify" && browserPreparation)
10269
+ return browserPreparation.verify(value);
9517
10270
  if (method === "session.stop" || method === "session.start") {
9518
10271
  if (transferred)
9519
10272
  return method === "session.stop" ? transferred.stopCall() : transferred.startCall();
@@ -9522,9 +10275,9 @@ ${tail}
9522
10275
  return method === "session.stop" ? selectedCall.stop() : selectedCall.start();
9523
10276
  }
9524
10277
  if (method === "lan.verify") {
9525
- if (!lanPreparation || !isRecord(value) || value["port"] !== lanPreparation.certificate.port)
10278
+ if (!lanPreparation)
9526
10279
  throw new Error("LAN takeover requires permission for the source listener's port");
9527
- await verifyLanTakeoverListener(lanPreparation.certificate.cert, value, signal);
10280
+ await lanPreparation.verify(value, signal);
9528
10281
  return;
9529
10282
  }
9530
10283
  if (method === "session.send" && typeof value === "string")
@@ -9561,7 +10314,7 @@ ${tail}
9561
10314
  signal.addEventListener("abort", cancelled, { once: true });
9562
10315
  removeStartupAbort = () => signal.removeEventListener("abort", cancelled);
9563
10316
  signal.throwIfAborted();
9564
- link.stage("prepared", lanPreparation ? { lanTakeover: lanPreparation.offer } : undefined);
10317
+ link.stage("prepared", reservation ? { browserTakeover: reservation.identity } : lanPreparation ? { lanTakeover: lanPreparation.offer } : undefined);
9565
10318
  const activation = await link.waitFor("activate");
9566
10319
  if (!isRecord(activation) || typeof activation["inputMuted"] !== "boolean" || activation["alternateVoice"] !== undefined && typeof activation["alternateVoice"] !== "boolean")
9567
10320
  throw new Error("Invalid handoff microphone or voice selection");
@@ -9588,11 +10341,32 @@ ${continuity}`
9588
10341
  }
9589
10342
  ];
9590
10343
  const takeover = activation["lanTakeover"];
10344
+ if (browserPreparation) {
10345
+ preparedBrowsers.set(browserPreparation.handle, {
10346
+ epoch: startEpoch,
10347
+ startup: {
10348
+ settings,
10349
+ summary: prepared,
10350
+ items,
10351
+ inputMuted: muted,
10352
+ alternateVoice
10353
+ }
10354
+ });
10355
+ await browserPreparation.activate(activation["browserTakeover"]);
10356
+ signal.throwIfAborted();
10357
+ lanCommitted = true;
10358
+ handoffLink = undefined;
10359
+ await arrivedGrant.release();
10360
+ handoffGrant = undefined;
10361
+ incomingBindings.delete(incoming);
10362
+ link.stage("active", { browserTakeover: true });
10363
+ return;
10364
+ }
9591
10365
  if (takeover !== undefined) {
9592
- if (!lanPreparation || !isRecord(takeover) || takeover["token"] !== lanPreparation.offer.token || takeover["port"] !== lanPreparation.certificate.port)
10366
+ if (!lanPreparation)
9593
10367
  throw new Error("Invalid LAN takeover activation");
9594
10368
  await ensureLan(context, {
9595
- token: lanPreparation.offer.token,
10369
+ token: lanPreparation.claim(takeover),
9596
10370
  startup: {
9597
10371
  settings,
9598
10372
  summary: prepared,
@@ -9684,6 +10458,8 @@ ${continuity}`
9684
10458
  try {
9685
10459
  channel.close();
9686
10460
  } finally {
10461
+ if (reservation)
10462
+ await reservation.cancel().catch(report);
9687
10463
  if (returning && !arrivalActivated) {
9688
10464
  await arrivedGrant?.release();
9689
10465
  if (incoming)
@@ -9702,7 +10478,129 @@ ${continuity}`
9702
10478
  }
9703
10479
  }
9704
10480
  };
9705
- return { extension, controls, settingsContribution };
10481
+ const browserProvider = {
10482
+ settings: {
10483
+ async read(scope) {
10484
+ if (scope.environment.id !== options.namespace)
10485
+ throw new Error("Browser settings and GipPity must share a namespace");
10486
+ await configSerial;
10487
+ await loadConfig();
10488
+ const models = await scope.models.getAvailable(undefined, {
10489
+ signal: scope.signal
10490
+ });
10491
+ return {
10492
+ scope: options.preferences?.writeScope ?? (options.settings ? "Application settings" : "This instance"),
10493
+ fields: gippityBrowserFields(config.voice, models.map((model) => ({
10494
+ provider: model.provider,
10495
+ modelId: model.id
10496
+ })), options.allowContextSummary === true)
10497
+ };
10498
+ },
10499
+ async write(scope, patch) {
10500
+ if (scope.environment.id !== options.namespace)
10501
+ throw new Error("Browser settings and GipPity must share a namespace");
10502
+ const models = (await scope.models.getAvailable(undefined, { signal: scope.signal })).map((model) => ({ provider: model.provider, modelId: model.id }));
10503
+ await changeConfig(() => {
10504
+ scope.signal.throwIfAborted();
10505
+ const values = decodeGippityBrowserSettings(patch, config.voice, models, options.allowContextSummary === true);
10506
+ return { ...config, voice: { ...config.voice, ...values } };
10507
+ });
10508
+ }
10509
+ },
10510
+ resume(input, handle) {
10511
+ const prepared = preparedBrowsers.get(handle);
10512
+ preparedBrowsers.delete(handle);
10513
+ if (!prepared || prepared.epoch !== startEpoch || input.mode !== "voice")
10514
+ throw new Error("Prepared browser session no longer available");
10515
+ return openBrowser(input, prepared.startup);
10516
+ },
10517
+ open(input) {
10518
+ return openBrowser(input);
10519
+ }
10520
+ };
10521
+ async function openBrowser(input, startup) {
10522
+ if (input.environmentId !== options.namespace)
10523
+ throw new Error("Browser audio and GipPity must share a namespace");
10524
+ if (harness === undefined && conversationId === undefined)
10525
+ controls.bindHarness(input.harness, input.conversationId);
10526
+ if (harness !== input.harness || conversationId !== input.conversationId)
10527
+ throw new Error("GipPity is bound to a different conversation");
10528
+ if (browserAudio || session || dictation || lease || !startup && startAbort?.signal.aborted === false || lan || !startup && transferring || transferred || selectedCall)
10529
+ throw new Error("GipPity voice, dictation or LAN is already active");
10530
+ const browser = new GippityBrowserAudio(input.mode, input.audio, (error) => {
10531
+ if (browserAudio !== browser)
10532
+ return;
10533
+ report(error);
10534
+ startAbort?.abort(error);
10535
+ close().catch(report);
10536
+ });
10537
+ const close = () => enqueue(async () => {
10538
+ if (browserAudio === browser)
10539
+ await stopSession();
10540
+ });
10541
+ browserAudio = browser;
10542
+ try {
10543
+ if (input.mode === "voice") {
10544
+ await startVoice(input.context, () => browser.createPeer(options.audio), false, startup, browser);
10545
+ input.context.abortSignal?.throwIfAborted();
10546
+ if (startup)
10547
+ browser.setMuted(startup.inputMuted);
10548
+ await browser.startCapture();
10549
+ } else {
10550
+ await ensureService(input.context);
10551
+ await enqueue(async () => {
10552
+ if (browserAudio !== browser)
10553
+ throw new Error("Browser dictation cancelled");
10554
+ const { runtime } = requireRuntime();
10555
+ startAbort = new AbortController;
10556
+ const signal = AbortSignal.any([
10557
+ runtime.signal,
10558
+ startAbort.signal,
10559
+ ...input.context.abortSignal ? [input.context.abortSignal] : []
10560
+ ]);
10561
+ lease = await options.lease.acquire({
10562
+ owner: `${leaseOwner}:${runtime.conversationId}`,
10563
+ mode: "dictation"
10564
+ }, signal);
10565
+ await browser.startDictation(await resolveDictationAuth(signal), signal);
10566
+ });
10567
+ }
10568
+ input.context.abortSignal?.throwIfAborted();
10569
+ } catch (error) {
10570
+ await close();
10571
+ throw error;
10572
+ }
10573
+ return {
10574
+ state: () => ({
10575
+ status: browser.status,
10576
+ muted: browserAudio === browser && controls.inputMuted,
10577
+ transcript: browser.transcript,
10578
+ ...browser.error ? { error: browser.error } : {}
10579
+ }),
10580
+ mute(value) {
10581
+ if (browserAudio !== browser)
10582
+ throw new Error("GipPity browser call ended");
10583
+ controls.setInputMuted(value);
10584
+ browser.setMuted(value);
10585
+ },
10586
+ async send(text) {
10587
+ if (browserAudio !== browser)
10588
+ throw new Error("GipPity browser call ended");
10589
+ await controls.sendText(text, BACKGROUND_CONTEXT2);
10590
+ },
10591
+ finish: () => browser.finish(),
10592
+ departBrowser(channel, context, transfer) {
10593
+ if (browserAudio !== browser || input.mode !== "voice")
10594
+ throw new Error("OpenAI browser call ended");
10595
+ return controls.depart(channel, context, "webrtc", {
10596
+ owner: browser,
10597
+ transfer
10598
+ });
10599
+ },
10600
+ close
10601
+ };
10602
+ }
10603
+ return { extension, controls, settingsContribution, browserProvider };
9706
10604
  }
9707
10605
  function asError2(value) {
9708
10606
  return value instanceof Error ? value : new Error(String(value));