@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
@@ -36,11 +36,11 @@ function componentSettings(directory, initial) {
36
36
  }
37
37
 
38
38
  // packages/gippity-voice/src/controller.ts
39
- import { randomUUID as randomUUID4, X509Certificate as X509Certificate2 } from "node:crypto";
39
+ import { randomUUID as randomUUID5, X509Certificate as X509Certificate2 } from "node:crypto";
40
40
  import {
41
- awaitWithContext as awaitWithContext2,
42
- BACKGROUND_CONTEXT,
43
- withAbortSignal
41
+ awaitWithContext as awaitWithContext3,
42
+ BACKGROUND_CONTEXT as BACKGROUND_CONTEXT2,
43
+ withAbortSignal as withAbortSignal2
44
44
  } from "@earendil-works/chord/context";
45
45
  import {
46
46
  AgentDoc,
@@ -153,16 +153,105 @@ function createSettingsContribution(options) {
153
153
  };
154
154
  }
155
155
 
156
+ // internal/voice/agent-observation.ts
157
+ import {
158
+ LiveDoc
159
+ } from "@earendil-works/pi-durable";
160
+ async function observeVoiceAgent(conversation, context, callbacks) {
161
+ const watch = await conversation.watch(context);
162
+ let newest = watch.value.entries.at(-1)?.id ?? watch.value.before;
163
+ let previous = liveState(watch.value);
164
+ let text = "";
165
+ let stopped = false;
166
+ let work = Promise.resolve();
167
+ callbacks.state(Boolean(previous.run));
168
+ async function advance(view) {
169
+ if (stopped)
170
+ return;
171
+ const live = liveState(view);
172
+ if (live.run)
173
+ callbacks.state(true);
174
+ const upTo = view.entries.at(-1)?.id;
175
+ if (upTo !== undefined && (newest === undefined || upTo > newest)) {
176
+ const from = newest;
177
+ let cursor;
178
+ do {
179
+ const page = await conversation.entries({
180
+ ...from === undefined ? {} : { minEntryId: from },
181
+ maxEntryId: upTo,
182
+ order: "ascending"
183
+ }, 128, cursor, context);
184
+ if (stopped)
185
+ return;
186
+ for (const entry of page.items) {
187
+ if (newest !== undefined && entry.id <= newest)
188
+ continue;
189
+ callbacks.entry(entry);
190
+ newest = entry.id;
191
+ }
192
+ cursor = page.next;
193
+ } while (cursor);
194
+ }
195
+ const partial = live.generation?.message;
196
+ const nextText = partial?.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
197
+ `) ?? "";
198
+ if (previous.run?.taskId !== live.run?.taskId || previous.generation?.attempt !== live.generation?.attempt || !nextText.startsWith(text))
199
+ text = "";
200
+ callbacks.partial(nextText.slice(text.length), Boolean(partial?.content.some((part) => part.type === "thinking" || part.type === "toolCall")));
201
+ text = nextText;
202
+ for (const compact of live.compactions ?? []) {
203
+ if (compact.trigger !== "manual" && !previous.compactions?.some((old) => old.taskId === compact.taskId))
204
+ callbacks.compacting(compact.trigger === "overflow" ? "overflow" : "threshold");
205
+ }
206
+ if (!live.run)
207
+ callbacks.state(false);
208
+ previous = live;
209
+ }
210
+ watch.start((call) => {
211
+ work = call.kind === "failed" ? Promise.reject(call.error) : advance(call.value);
212
+ return work;
213
+ });
214
+ watch.closed.then((end) => {
215
+ if (end.kind === "failed" || end.kind === "listener_error")
216
+ callbacks.failed(end.error);
217
+ });
218
+ return {
219
+ get view() {
220
+ return watch.value;
221
+ },
222
+ async stop() {
223
+ stopped = true;
224
+ await watch.stop();
225
+ await work;
226
+ }
227
+ };
228
+ }
229
+ function liveState(view) {
230
+ return view.docs[LiveDoc.definition.kind] ?? {};
231
+ }
232
+
233
+ // internal/voice/deferred.ts
234
+ function deferred() {
235
+ let resolve;
236
+ let reject;
237
+ const promise = new Promise((yes, no) => {
238
+ resolve = yes;
239
+ reject = no;
240
+ });
241
+ return { promise, resolve, reject };
242
+ }
243
+
156
244
  // packages/execution/src/nested.ts
245
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
157
246
  import {
158
247
  defineTask
159
248
  } from "@earendil-works/pi-durable";
160
249
  import { compile as compile2 } from "@earendil-works/pi-schema";
161
250
 
162
251
  // packages/execution/src/forwarding.ts
163
- import { copyJson as copyJson2 } from "@earendil-works/chord";
252
+ import { copyJson as copyJson2 } from "@earendil-works/chord/json";
164
253
  import {
165
- LiveDoc,
254
+ LiveDoc as LiveDoc2,
166
255
  NestedCallDoc,
167
256
  ToolTask
168
257
  } from "@earendil-works/pi-durable";
@@ -170,7 +259,7 @@ import {
170
259
  // packages/execution/src/invocation-state.ts
171
260
  import {
172
261
  copyJson
173
- } from "@earendil-works/chord";
262
+ } from "@earendil-works/chord/json";
174
263
  import {
175
264
  defineDoc
176
265
  } from "@earendil-works/pi-durable";
@@ -522,7 +611,7 @@ async function forwardInvocationResult(tx, taskId, result, status) {
522
611
  async function captureNativeCalls(tx, conversationId, owner, cellId) {
523
612
  if (cellId === undefined)
524
613
  return;
525
- const live = await tx.doc(LiveDoc, conversationId);
614
+ const live = await tx.doc(LiveDoc2, conversationId);
526
615
  const owners = new Set([owner]);
527
616
  const cell = await tx.doc(InvocationDoc, cellId);
528
617
  const budget = cell.forwardingBudget ?? 40000;
@@ -612,26 +701,53 @@ async function captureNativeCalls(tx, conversationId, owner, cellId) {
612
701
  }
613
702
 
614
703
  // packages/execution/src/invocation.ts
615
- import { copyJson as copyJson4 } from "@earendil-works/chord";
616
704
  import { awaitWithContext } from "@earendil-works/chord/context";
705
+ import { copyJson as copyJson4 } from "@earendil-works/chord/json";
706
+ import {
707
+ NestedCallDoc as NestedCallDoc3
708
+ } from "@earendil-works/pi-durable";
709
+ import { equal } from "@earendil-works/pi-schema";
617
710
 
618
711
  // packages/execution/src/native-tools.ts
619
- import { copyJson as copyJson3 } from "@earendil-works/chord";
620
- import { withoutAbortSignal } from "@earendil-works/chord/context";
621
712
  import {
622
- LiveDoc as LiveDoc2,
713
+ withoutAbortSignal
714
+ } from "@earendil-works/chord/context";
715
+ import { copyJson as copyJson3 } from "@earendil-works/chord/json";
716
+ import {
717
+ LiveDoc as LiveDoc3,
623
718
  NestedCallDoc as NestedCallDoc2,
624
- ToolTask as ToolTask2
719
+ ToolTask as ToolTask3
625
720
  } from "@earendil-works/pi-durable";
626
721
  import { Equal } from "typebox/value";
627
- function nativeToolCalls(runtime, callId, replay, assertLive, context) {
722
+
723
+ // packages/execution/src/tool-origin.ts
724
+ import {
725
+ defineDoc as defineDoc2,
726
+ ToolTask as ToolTask2
727
+ } from "@earendil-works/pi-durable";
728
+ var ToolOriginDoc = defineDoc2({
729
+ kind: "howaboua.tool-origin",
730
+ version: 1,
731
+ scope: "task",
732
+ checkpointWhen: () => false,
733
+ initial: () => ({})
734
+ });
735
+
736
+ // packages/execution/src/native-tools.ts
737
+ function assertNestedKey(key) {
738
+ if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
739
+ throw new Error("Invalid nested call or task key");
740
+ }
741
+ function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
628
742
  let sequence = 0;
629
743
  const admissions = [];
630
- const execute = async (name, args, callContext, options = {}) => {
744
+ async function execute(name, args, callContext, options = {}) {
631
745
  assertLive();
746
+ if (options.key !== undefined)
747
+ assertNestedKey(options.key);
748
+ else if (resumed)
749
+ throw new Error("Nested calls require an explicit key after waking");
632
750
  const key = options.key ?? String(++sequence);
633
- if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
634
- throw new Error("Invalid nested call key");
635
751
  const call = {
636
752
  type: "toolCall",
637
753
  id: `${callId}/${key}`,
@@ -643,11 +759,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
643
759
  const admission = runtime.commit(async (tx) => {
644
760
  const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
645
761
  if (slot.taskId !== undefined) {
646
- const input = (await tx.task(slot.taskId))?.input;
762
+ const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
647
763
  if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
648
764
  throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
649
765
  } else {
650
- slot.taskId = await tx.createTask(ToolTask2, {
766
+ slot.kind = "nested";
767
+ slot.taskId = await tx.createTask(ToolTask3, {
651
768
  kind: "nested",
652
769
  parent: runtime.taskId,
653
770
  parentCallId: callId,
@@ -658,7 +775,10 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
658
775
  ownership: { kind: "task", taskId: runtime.taskId },
659
776
  abandonOnRestart: replay !== "safe"
660
777
  });
661
- const live = await tx.doc(LiveDoc2, runtime.conversationId);
778
+ const live = await tx.doc(LiveDoc3, runtime.conversationId);
779
+ const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
780
+ if (origin)
781
+ (await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
662
782
  live.nestedTools ??= [];
663
783
  live.nestedTools.push({
664
784
  callId: call.id,
@@ -690,7 +810,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
690
810
  const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
691
811
  if (slot?.taskId === undefined)
692
812
  throw new Error("Nested task creation did not commit");
693
- const settled = await runtime.waitForTask(slot.taskId, callContext);
813
+ const taskId = slot.taskId;
814
+ const result = (resultContext) => readResult(name, key, taskId, resultContext);
815
+ return options.wait === false ? { taskId, result } : result(callContext);
816
+ }
817
+ async function readResult(name, key, taskId, callContext) {
818
+ assertLive();
819
+ const settled = await runtime.waitForTask(taskId, callContext);
694
820
  const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
695
821
  await runtime.commit(async (tx) => {
696
822
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
@@ -698,7 +824,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
698
824
  return;
699
825
  }, callContext);
700
826
  return result === undefined ? {
701
- taskId: slot.taskId,
827
+ taskId,
702
828
  isError: true,
703
829
  diagnostics: [
704
830
  {
@@ -708,9 +834,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
708
834
  }
709
835
  ]
710
836
  } : copyJson3(result);
711
- };
837
+ }
712
838
  return {
713
839
  execute,
840
+ async drain() {
841
+ await Promise.allSettled(admissions);
842
+ },
714
843
  async finish() {
715
844
  await Promise.allSettled(admissions);
716
845
  await cleanupNativeCalls(runtime, withoutAbortSignal(context));
@@ -718,11 +847,11 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
718
847
  };
719
848
  }
720
849
  async function cleanupNativeCalls(runtime, context) {
721
- await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
850
+ await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
722
851
  await runtime.commit(async (tx) => {
723
852
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
724
853
  await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
725
- const live = await tx.doc(LiveDoc2, runtime.conversationId);
854
+ const live = await tx.doc(LiveDoc3, runtime.conversationId);
726
855
  const removed = new Set([runtime.taskId]);
727
856
  for (const slot of live.nestedTools ?? [])
728
857
  if (removed.has(slot.parentTaskId))
@@ -812,18 +941,6 @@ class Progress {
812
941
  }
813
942
  }
814
943
 
815
- // packages/execution/src/tool-origin.ts
816
- import {
817
- defineDoc as defineDoc2
818
- } from "@earendil-works/pi-durable";
819
- var ToolOriginDoc = defineDoc2({
820
- kind: "howaboua.tool-origin",
821
- version: 1,
822
- scope: "task",
823
- checkpointWhen: () => false,
824
- initial: () => ({})
825
- });
826
-
827
944
  // packages/execution/src/invocation.ts
828
945
  function executionError(code, message) {
829
946
  return {
@@ -835,21 +952,23 @@ function executionError(code, message) {
835
952
  function errorText(error) {
836
953
  return error instanceof Error ? error.message : String(error);
837
954
  }
838
- function createInvocation(runtime, tool, context) {
955
+ function createInvocation(runtime, tool, context, resume) {
839
956
  const limits = {
840
957
  maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
841
958
  maxLines: tool.outputLimits?.maxLines ?? 2000,
842
959
  retain: tool.outputLimits?.retain ?? "head"
843
960
  };
844
961
  const output = new OutputBuffer(limits);
845
- const diagnostics = [];
846
- let details;
962
+ const diagnostics = [
963
+ ...resume?.progress?.diagnostics ?? []
964
+ ];
965
+ let details = resume?.progress?.details;
847
966
  let ended = false;
848
967
  const assertLive = () => {
849
968
  if (ended)
850
969
  throw new Error(`Invocation ${runtime.taskId} has settled`);
851
970
  };
852
- const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
971
+ const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
853
972
  const snapshot = () => {
854
973
  const retained = output.snapshot();
855
974
  return {
@@ -878,6 +997,8 @@ function createInvocation(runtime, tool, context) {
878
997
  taskId: runtime.taskId,
879
998
  conversationId: runtime.conversationId,
880
999
  callId: `nested-${runtime.taskId}`,
1000
+ wake: resume?.wake,
1001
+ checkpoint: resume?.checkpoint,
881
1002
  registry: runtime.registry,
882
1003
  agent: runtime.agent,
883
1004
  env: undefined,
@@ -898,7 +1019,7 @@ function createInvocation(runtime, tool, context) {
898
1019
  const retained = output.snapshot();
899
1020
  return { text: retained.text, truncated: retained.droppedBytes > 0 };
900
1021
  },
901
- executeTool: (...args) => native.execute(...args),
1022
+ executeTool: native.execute,
902
1023
  diagnostic: (value) => {
903
1024
  assertLive();
904
1025
  diagnostics.push(copyJson4(value, { omitUndefinedProperties: true }));
@@ -912,24 +1033,44 @@ function createInvocation(runtime, tool, context) {
912
1033
  committed.catch(() => {});
913
1034
  await awaitWithContext(committed, detailContext);
914
1035
  },
915
- commit: async (change, commitContext) => {
1036
+ commit: async (change, commitContext, options) => {
916
1037
  assertLive();
917
1038
  let result;
918
1039
  await runtime.commit(async (tx) => {
919
1040
  result = await change(tx);
920
1041
  return;
921
- }, commitContext);
1042
+ }, commitContext, options);
922
1043
  return result;
923
1044
  },
924
1045
  memo: runtime.memo,
925
- createTask: async (task, input, options, taskContext) => {
1046
+ readSignal: runtime.readSignal,
1047
+ async createTask(task, input, {
1048
+ key,
1049
+ ...options
1050
+ }, taskContext) {
926
1051
  assertLive();
1052
+ if (key !== undefined)
1053
+ assertNestedKey(key);
1054
+ else if (resume?.wake !== undefined)
1055
+ throw new Error("Child tasks require an explicit key after waking");
927
1056
  let id;
928
1057
  await runtime.commit(async (tx) => {
1058
+ const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
1059
+ if (member?.taskId !== undefined) {
1060
+ const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
1061
+ if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson4(input, { omitUndefinedProperties: true })))
1062
+ throw new Error(`Key ${key} was already used for another call or task`);
1063
+ id = member.taskId;
1064
+ return;
1065
+ }
929
1066
  id = await tx.createTask(task, input, {
930
1067
  ...options,
931
1068
  ...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
932
1069
  });
1070
+ if (member !== undefined) {
1071
+ member.kind = "task";
1072
+ member.taskId = id;
1073
+ }
933
1074
  const source = await tx.doc(ToolOriginDoc, runtime.taskId);
934
1075
  if (source.origin !== undefined)
935
1076
  (await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
@@ -976,6 +1117,14 @@ function createInvocation(runtime, tool, context) {
976
1117
  for (const waiter of await progress.stop())
977
1118
  waiter.reject(error);
978
1119
  },
1120
+ async park() {
1121
+ ended = true;
1122
+ await native.drain();
1123
+ output.end();
1124
+ const pending = await progress.stop();
1125
+ const { output: _output, ...kept } = snapshot();
1126
+ return { progress: storeResult(kept), pending };
1127
+ },
979
1128
  limits,
980
1129
  output,
981
1130
  progress
@@ -1009,12 +1158,22 @@ function truncation(dropped, retain) {
1009
1158
  // packages/execution/src/nested-call.ts
1010
1159
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1011
1160
  import {
1012
- ToolTask as ToolTask3
1161
+ ToolTask as ToolTask4
1013
1162
  } from "@earendil-works/pi-durable";
1014
1163
  import { compile } from "@earendil-works/pi-schema";
1015
1164
 
1016
1165
  // packages/execution/src/tool-contract.ts
1017
- import { copyJson as copyJson5 } from "@earendil-works/chord";
1166
+ import { copyJson as copyJson5 } from "@earendil-works/chord/json";
1167
+
1168
+ // packages/execution/src/tool-namespaces.ts
1169
+ import { isJsonValue } from "@earendil-works/chord/json";
1170
+ function validateJsToolNamespace(tool, namespace) {
1171
+ const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
1172
+ 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))))
1173
+ throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
1174
+ }
1175
+
1176
+ // packages/execution/src/tool-contract.ts
1018
1177
  function readToolContract(tool) {
1019
1178
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
1020
1179
  if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
@@ -1028,6 +1187,7 @@ function readToolContract(tool) {
1028
1187
  "yieldTimeMs",
1029
1188
  "inputSchema",
1030
1189
  "nativeOnly",
1190
+ "nestedHidden",
1031
1191
  "discovery"
1032
1192
  ]);
1033
1193
  for (const key of Object.keys(hints))
@@ -1051,6 +1211,12 @@ function readToolContract(tool) {
1051
1211
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1052
1212
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1053
1213
  throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
1214
+ const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
1215
+ const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
1216
+ if (jsNamespace !== undefined)
1217
+ validateJsToolNamespace(tool.name, jsNamespace);
1218
+ if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
1219
+ throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
1054
1220
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1055
1221
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1056
1222
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1067,6 +1233,8 @@ function readToolContract(tool) {
1067
1233
  inputSchema,
1068
1234
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1069
1235
  nativeOnly: nativeOnly === true,
1236
+ nestedHidden: nestedHidden === true,
1237
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1070
1238
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1071
1239
  ...outputHint === undefined ? {} : { output: outputHint },
1072
1240
  help: [
@@ -1123,7 +1291,7 @@ function prepareNestedInput(tool, input) {
1123
1291
  async function eachHook(agent, name, api, invoke) {
1124
1292
  for (const extension of agent.extensions)
1125
1293
  for (const registration of extension.hooks ?? []) {
1126
- if (registration.task !== ToolTask3.definition.name)
1294
+ if (registration.task !== ToolTask4.definition.name)
1127
1295
  continue;
1128
1296
  const handler = registration.handlers[name];
1129
1297
  if (handler === undefined)
@@ -1138,8 +1306,120 @@ async function eachHook(agent, name, api, invoke) {
1138
1306
  }
1139
1307
  }
1140
1308
 
1309
+ // packages/execution/src/nested-park.ts
1310
+ import {
1311
+ withCancel,
1312
+ withoutAbortSignal as withoutAbortSignal2
1313
+ } from "@earendil-works/chord/context";
1314
+ import { copyJson as copyJson6 } from "@earendil-works/chord/json";
1315
+ var resultFields = [
1316
+ "output",
1317
+ "structuredOutput",
1318
+ "isError",
1319
+ "details",
1320
+ "diagnostics",
1321
+ "usage",
1322
+ "control"
1323
+ ];
1324
+ function sleepState(checkpoint, { until, signals }) {
1325
+ return {
1326
+ status: "sleeping",
1327
+ checkpoint,
1328
+ ...until === undefined ? {} : { until },
1329
+ ...signals === undefined ? {} : { signals }
1330
+ };
1331
+ }
1332
+ async function parkGate(runtime, sleep, context) {
1333
+ try {
1334
+ await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
1335
+ } catch (error) {
1336
+ runtime.signal.throwIfAborted();
1337
+ return errorText(error);
1338
+ }
1339
+ }
1340
+ async function parkTool(runtime, invocation, tool, args, park, context) {
1341
+ if (park.kind !== "sleep" && park.kind !== "wait")
1342
+ return "Unknown park kind";
1343
+ const mixed = resultFields.find((field) => (field in park));
1344
+ if (mixed !== undefined)
1345
+ return `A park cannot carry the result field ${mixed}`;
1346
+ const intent = {
1347
+ arguments: args,
1348
+ replay: tool.replay ?? "unsafe",
1349
+ ...park.checkpoint === undefined ? {} : { checkpoint: copyJson6(park.checkpoint) }
1350
+ };
1351
+ const { progress, pending } = await invocation.park();
1352
+ try {
1353
+ await runtime.commit(async (tx) => {
1354
+ if (park.kind === "wait") {
1355
+ for (const id of park.on)
1356
+ if ((await tx.task(id))?.owner !== runtime.taskId)
1357
+ throw new Error(`Task ${id} is not owned by the call`);
1358
+ }
1359
+ const checkpoint = { ...intent, phase: "parked" };
1360
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1361
+ doc.result = progress;
1362
+ doc.droppedBytes = 0;
1363
+ doc.droppedLines = 0;
1364
+ await forwardInvocationResult(tx, runtime.taskId, progress, "running");
1365
+ return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
1366
+ }, context);
1367
+ } catch (error) {
1368
+ for (const waiter of pending)
1369
+ waiter.reject(error);
1370
+ const detached = withoutAbortSignal2(context);
1371
+ const record = await runtime.getTask(runtime.taskId, detached);
1372
+ if (record?.abortRequested) {
1373
+ const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
1374
+ if (watch !== undefined) {
1375
+ const cleanup = withCancel(detached);
1376
+ watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
1377
+ try {
1378
+ await cancelParkedTool(runtime, tool, intent, cleanup.context);
1379
+ } finally {
1380
+ await watch.stop();
1381
+ }
1382
+ }
1383
+ throw error;
1384
+ }
1385
+ runtime.signal.throwIfAborted();
1386
+ return errorText(error);
1387
+ }
1388
+ for (const waiter of pending)
1389
+ waiter.resolve();
1390
+ }
1391
+ async function cancelParkedTool(runtime, tool, intent, context) {
1392
+ if (!tool) {
1393
+ runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
1394
+ return;
1395
+ }
1396
+ if (tool.cancel === undefined)
1397
+ return;
1398
+ const cleanup = createInvocation(runtime, tool, context, {
1399
+ checkpoint: intent.checkpoint,
1400
+ wake: undefined
1401
+ });
1402
+ const refuseWork = () => {
1403
+ throw new Error("A tool cannot start tasks or nested calls during cancellation");
1404
+ };
1405
+ let reason = new Error("Tool cancellation finished");
1406
+ try {
1407
+ const api = await cleanup.executionApi();
1408
+ await tool.cancel(intent.arguments, {
1409
+ ...api,
1410
+ createTask: refuseWork,
1411
+ executeTool: refuseWork
1412
+ }, context);
1413
+ } catch (error) {
1414
+ reason = error;
1415
+ runtime.report(error);
1416
+ } finally {
1417
+ await cleanup.stop(reason);
1418
+ }
1419
+ }
1420
+
1141
1421
  // packages/execution/src/nested-result.ts
1142
- import { copyJson as copyJson6 } from "@earendil-works/chord";
1422
+ import { copyJson as copyJson7 } from "@earendil-works/chord/json";
1143
1423
  import {
1144
1424
  defineEntry,
1145
1425
  UsageDoc
@@ -1187,11 +1467,11 @@ async function settle(runtime, call, result, ending, context) {
1187
1467
  taskId: runtime.taskId,
1188
1468
  callId: call.id,
1189
1469
  name: call.name,
1190
- arguments: copyJson6(call.arguments),
1470
+ arguments: copyJson7(call.arguments),
1191
1471
  result: stored,
1192
1472
  ...current.state.checkpoint.phase === "execute" ? {
1193
1473
  intent: {
1194
- arguments: copyJson6(current.state.checkpoint.arguments),
1474
+ arguments: copyJson7(current.state.checkpoint.arguments),
1195
1475
  replay: current.state.checkpoint.replay
1196
1476
  }
1197
1477
  } : {}
@@ -1200,7 +1480,7 @@ async function settle(runtime, call, result, ending, context) {
1200
1480
  if (result.usage !== undefined) {
1201
1481
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1202
1482
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1203
- totals[call.name] = copyJson6(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1483
+ totals[call.name] = copyJson7(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1204
1484
  }
1205
1485
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1206
1486
  status: ending,
@@ -1237,7 +1517,11 @@ function sumUsage(previous, added) {
1237
1517
  function createNestedToolTask(name) {
1238
1518
  return defineTask({
1239
1519
  name,
1240
- version: 1,
1520
+ version: 2,
1521
+ migrate: (input, checkpoint) => ({
1522
+ input,
1523
+ checkpoint
1524
+ }),
1241
1525
  initial: () => ({ phase: "call" }),
1242
1526
  phases: {
1243
1527
  call: async (task, runtime, context) => {
@@ -1272,13 +1556,16 @@ function createNestedToolTask(name) {
1272
1556
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1273
1557
  }
1274
1558
  let block;
1559
+ let sleep;
1275
1560
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1276
- if (block !== undefined)
1561
+ if (block !== undefined || sleep !== undefined)
1277
1562
  return;
1278
1563
  try {
1279
1564
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1280
1565
  if (decision?.block !== undefined)
1281
1566
  block = decision.block;
1567
+ else if (decision?.sleep !== undefined)
1568
+ sleep = decision.sleep;
1282
1569
  else if (decision?.arguments !== undefined)
1283
1570
  args = decision.arguments;
1284
1571
  } catch (error) {
@@ -1289,71 +1576,122 @@ function createNestedToolTask(name) {
1289
1576
  });
1290
1577
  if (block !== undefined)
1291
1578
  return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
1579
+ if (sleep !== undefined) {
1580
+ const reason = await parkGate(runtime, sleep, context);
1581
+ if (reason === undefined)
1582
+ return;
1583
+ return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
1584
+ }
1292
1585
  try {
1293
- args = checked(tool, call, args);
1586
+ args = copyJson8(checked(tool, call, args), {
1587
+ omitUndefinedProperties: true
1588
+ });
1294
1589
  } catch (error) {
1295
1590
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1296
1591
  }
1297
- await runtime.commit(async (tx) => {
1298
- await tx.doc(InvocationDoc, runtime.taskId);
1299
- await forwardCall(tx, task.input.cellId, {
1300
- callId: call.id,
1301
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1302
- name: call.name,
1303
- arguments: args,
1304
- status: "running",
1305
- result: null,
1306
- omittedFields: []
1307
- });
1308
- return {
1309
- status: "running",
1310
- checkpoint: {
1311
- phase: "execute",
1312
- arguments: args,
1313
- replay: tool.replay ?? "unsafe"
1314
- }
1315
- };
1592
+ await startAttempt(runtime, call, tool, agent, {
1593
+ arguments: args,
1594
+ replay: tool.replay ?? "unsafe"
1316
1595
  }, context);
1317
- await run(runtime, call, tool, args, agent, context);
1596
+ },
1597
+ parked: async (task, runtime, context) => {
1598
+ const intent = task.state.checkpoint;
1599
+ const call = nestedCall(runtime, task.input);
1600
+ call.arguments = intent.arguments;
1601
+ const agent = await runtime.agent(context);
1602
+ const tool = agent.callable.find((each) => each.name === call.name);
1603
+ if (tool === undefined || readToolContract(tool).nativeOnly)
1604
+ return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
1605
+ await startAttempt(runtime, call, tool, agent, {
1606
+ ...intent,
1607
+ replay: tool.replay ?? "unsafe"
1608
+ }, context, task.state.wake);
1318
1609
  },
1319
1610
  execute: async (task, runtime, context) => {
1611
+ const intent = task.state.checkpoint;
1320
1612
  const call = nestedCall(runtime, task.input);
1321
1613
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1322
1614
  call.arguments = task.state.checkpoint.arguments;
1323
1615
  const agent = await runtime.agent(context);
1324
1616
  const tool = agent.callable.find((each) => each.name === call.name);
1325
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1326
- await runtime.commit(async (tx) => {
1327
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1328
- doc.result = {};
1329
- doc.droppedBytes = 0;
1330
- doc.droppedLines = 0;
1331
- return;
1332
- }, context);
1333
- return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
1617
+ if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1618
+ if (intent.resume === undefined)
1619
+ await runtime.commit(async (tx) => {
1620
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1621
+ doc.result = {};
1622
+ doc.droppedBytes = 0;
1623
+ doc.droppedLines = 0;
1624
+ return;
1625
+ }, context);
1626
+ return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
1334
1627
  }
1628
+ if (intent.resume !== undefined)
1629
+ await cancelParkedTool(runtime, tool, intent, context);
1335
1630
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1336
1631
  }
1337
1632
  },
1338
1633
  abort: async (task, runtime, context) => {
1339
1634
  const call = nestedCall(runtime, task.input);
1635
+ const intent = task.state.checkpoint;
1636
+ if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
1637
+ const agent = await runtime.agent(context);
1638
+ const tool = agent.callable.find((each) => each.name === call.name);
1639
+ await cancelParkedTool(runtime, tool, intent, context);
1640
+ }
1340
1641
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1341
1642
  }
1342
1643
  });
1343
1644
  }
1645
+ async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
1646
+ await runtime.commit(async (tx) => {
1647
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1648
+ await forwardCall(tx, doc.forwardingCellId, {
1649
+ callId: call.id,
1650
+ parentCallId: call.parent?.callId ?? call.id,
1651
+ name: call.name,
1652
+ arguments: intent.arguments,
1653
+ status: "running",
1654
+ result: null,
1655
+ omittedFields: []
1656
+ });
1657
+ return {
1658
+ status: "running",
1659
+ checkpoint: {
1660
+ ...intent,
1661
+ phase: "execute",
1662
+ ...wake === undefined ? {} : { resume: { wake } }
1663
+ }
1664
+ };
1665
+ }, context);
1666
+ await run(runtime, call, tool, intent, agent, context, wake);
1667
+ }
1344
1668
  async function reject(runtime, call, result, agent, tool, context) {
1345
1669
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1346
1670
  result = await handler(call, result, runtime, context) ?? result;
1347
1671
  });
1348
1672
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1349
1673
  }
1350
- async function run(runtime, call, tool, args, agent, context) {
1674
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1351
1675
  let invocation;
1352
1676
  let result;
1353
1677
  let ending = "completed";
1354
1678
  try {
1355
- invocation = createInvocation(runtime, tool, context);
1356
- result = await tool.execute(args, await invocation.executionApi(), context);
1679
+ const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
1680
+ invocation = createInvocation(runtime, tool, context, {
1681
+ wake,
1682
+ checkpoint: intent.checkpoint,
1683
+ ...previous === undefined ? {} : { progress: previous.result }
1684
+ });
1685
+ const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
1686
+ if (returned.kind === undefined)
1687
+ result = returned;
1688
+ else {
1689
+ const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
1690
+ if (reason === undefined)
1691
+ return;
1692
+ result = executionError("invalid_park", reason);
1693
+ ending = "failed";
1694
+ }
1357
1695
  } catch (error) {
1358
1696
  if (runtime.signal.aborted) {
1359
1697
  await invocation?.stop(error);
@@ -1426,83 +1764,6 @@ function finishResult(tool, name, result) {
1426
1764
  return final;
1427
1765
  }
1428
1766
 
1429
- // packages/gippity-voice/src/agent-observation.ts
1430
- import {
1431
- LiveDoc as LiveDoc3
1432
- } from "@earendil-works/pi-durable";
1433
- async function observeVoiceAgent(conversation, context, callbacks) {
1434
- const watch = await conversation.watch(context);
1435
- let newest = watch.value.entries.at(-1)?.id ?? watch.value.before;
1436
- let previous = liveState(watch.value);
1437
- let text = "";
1438
- let stopped = false;
1439
- let work = Promise.resolve();
1440
- callbacks.state(Boolean(previous.run));
1441
- async function advance(view) {
1442
- if (stopped)
1443
- return;
1444
- const live = liveState(view);
1445
- if (live.run)
1446
- callbacks.state(true);
1447
- const upTo = view.entries.at(-1)?.id;
1448
- if (upTo !== undefined && (newest === undefined || upTo > newest)) {
1449
- const from = newest;
1450
- let cursor;
1451
- do {
1452
- const page = await conversation.entries({
1453
- ...from === undefined ? {} : { minEntryId: from },
1454
- maxEntryId: upTo,
1455
- order: "ascending"
1456
- }, 128, cursor, context);
1457
- if (stopped)
1458
- return;
1459
- for (const entry of page.items) {
1460
- if (newest !== undefined && entry.id <= newest)
1461
- continue;
1462
- callbacks.entry(entry);
1463
- newest = entry.id;
1464
- }
1465
- cursor = page.next;
1466
- } while (cursor);
1467
- }
1468
- const partial = live.generation?.message;
1469
- const nextText = partial?.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
1470
- `) ?? "";
1471
- if (previous.run?.taskId !== live.run?.taskId || previous.generation?.attempt !== live.generation?.attempt || !nextText.startsWith(text))
1472
- text = "";
1473
- callbacks.partial(nextText.slice(text.length), Boolean(partial?.content.some((part) => part.type === "thinking" || part.type === "toolCall")));
1474
- text = nextText;
1475
- for (const compact of live.compactions ?? []) {
1476
- if (compact.trigger !== "manual" && !previous.compactions?.some((old) => old.taskId === compact.taskId))
1477
- callbacks.compacting(compact.trigger === "overflow" ? "overflow" : "threshold");
1478
- }
1479
- if (!live.run)
1480
- callbacks.state(false);
1481
- previous = live;
1482
- }
1483
- watch.start((call) => {
1484
- work = call.kind === "failed" ? Promise.reject(call.error) : advance(call.value);
1485
- return work;
1486
- });
1487
- watch.closed.then((end) => {
1488
- if (end.kind === "failed" || end.kind === "listener_error")
1489
- callbacks.failed(end.error);
1490
- });
1491
- return {
1492
- get view() {
1493
- return watch.value;
1494
- },
1495
- async stop() {
1496
- stopped = true;
1497
- await watch.stop();
1498
- await work;
1499
- }
1500
- };
1501
- }
1502
- function liveState(view) {
1503
- return view.docs[LiveDoc3.definition.kind] ?? {};
1504
- }
1505
-
1506
1767
  // packages/gippity-voice/src/config.ts
1507
1768
  function normalizeVoiceApiProvider(value) {
1508
1769
  return typeof value === "string" && value.trim() === value && value.length > 0 && Buffer.byteLength(value) <= 512 && !/[\u0000-\u001f\u007f]/u.test(value) ? value : undefined;
@@ -1650,17 +1911,6 @@ function normalizeGippityControlConfig(value) {
1650
1911
  };
1651
1912
  }
1652
1913
 
1653
- // packages/gippity-voice/src/deferred.ts
1654
- function deferred() {
1655
- let resolve;
1656
- let reject;
1657
- const promise = new Promise((yes, no) => {
1658
- resolve = yes;
1659
- reject = no;
1660
- });
1661
- return { promise, resolve, reject };
1662
- }
1663
-
1664
1914
  // packages/gippity-voice/src/preferences.ts
1665
1915
  function object(value, path) {
1666
1916
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -1804,6 +2054,246 @@ async function resolveCodexVoiceAuth(models, conversationId, signal) {
1804
2054
  }
1805
2055
  }
1806
2056
 
2057
+ // packages/gippity-voice/src/voice/handoff-wire.ts
2058
+ class VoiceHandoffLink {
2059
+ pending = new Map;
2060
+ stages = new Map;
2061
+ stageWaiters = new Map;
2062
+ sequence = 0;
2063
+ failure;
2064
+ removeMessage;
2065
+ removeClose;
2066
+ channel;
2067
+ handlers;
2068
+ constructor(channel, handlers) {
2069
+ this.channel = channel;
2070
+ this.handlers = handlers;
2071
+ this.removeMessage = channel.onMessage((message) => {
2072
+ try {
2073
+ this.receive(message);
2074
+ } catch (error) {
2075
+ this.fail(asError(error));
2076
+ }
2077
+ });
2078
+ this.removeClose = channel.onClose((error) => this.finish(error));
2079
+ if (this.failure) {
2080
+ this.removeMessage();
2081
+ this.removeClose();
2082
+ }
2083
+ }
2084
+ get closed() {
2085
+ return this.failure !== undefined;
2086
+ }
2087
+ request(method, value) {
2088
+ if (this.failure)
2089
+ return Promise.reject(this.failure);
2090
+ if (this.pending.size >= 32)
2091
+ return Promise.reject(new Error("Too many pending voice controls"));
2092
+ const id = ++this.sequence;
2093
+ return new Promise((resolve, reject) => {
2094
+ const timer = setTimeout(() => {
2095
+ this.pending.delete(id);
2096
+ const error = new Error("Voice control did not respond");
2097
+ reject(error);
2098
+ this.fail(error);
2099
+ }, method === "session.start" ? 120000 : 30000);
2100
+ this.pending.set(id, { resolve, reject, timer });
2101
+ try {
2102
+ this.send({ type: "request", id, method, value });
2103
+ } catch (error) {
2104
+ this.fail(asError(error));
2105
+ }
2106
+ });
2107
+ }
2108
+ notify(message) {
2109
+ this.send(message);
2110
+ }
2111
+ stage(stage, value) {
2112
+ this.send({ type: "stage", stage, value });
2113
+ }
2114
+ waitFor(stage) {
2115
+ if (this.failure)
2116
+ return Promise.reject(this.failure);
2117
+ if (this.stages.has(stage))
2118
+ return Promise.resolve(this.stages.get(stage));
2119
+ if (this.stageWaiters.has(stage))
2120
+ return Promise.reject(new Error("Voice transfer stage already awaited"));
2121
+ return new Promise((resolve, reject) => {
2122
+ const timer = setTimeout(() => {
2123
+ this.stageWaiters.delete(stage);
2124
+ const error = new Error("Voice transfer did not finish preparing");
2125
+ reject(error);
2126
+ this.fail(error);
2127
+ }, 120000);
2128
+ this.stageWaiters.set(stage, { resolve, reject, timer });
2129
+ });
2130
+ }
2131
+ close() {
2132
+ this.fail(new Error("Voice connection closed"));
2133
+ }
2134
+ fail(error) {
2135
+ if (this.failure)
2136
+ return;
2137
+ try {
2138
+ this.channel.send({
2139
+ type: "failure",
2140
+ message: error.message.slice(0, 4000)
2141
+ });
2142
+ } catch {}
2143
+ this.finish(error);
2144
+ this.channel.close();
2145
+ }
2146
+ send(message) {
2147
+ if (this.failure)
2148
+ throw this.failure;
2149
+ try {
2150
+ this.channel.send(message);
2151
+ } catch (error) {
2152
+ this.fail(asError(error));
2153
+ throw error;
2154
+ }
2155
+ }
2156
+ finish(error) {
2157
+ if (this.failure)
2158
+ return;
2159
+ this.failure = error;
2160
+ this.removeMessage?.();
2161
+ this.removeClose?.();
2162
+ for (const pending of [
2163
+ ...this.pending.values(),
2164
+ ...this.stageWaiters.values()
2165
+ ]) {
2166
+ clearTimeout(pending.timer);
2167
+ pending.reject(error);
2168
+ }
2169
+ this.pending.clear();
2170
+ this.stageWaiters.clear();
2171
+ this.handlers.closed(error);
2172
+ }
2173
+ receive(value) {
2174
+ if (this.failure)
2175
+ return;
2176
+ if (!isRecord(value))
2177
+ throw new Error("Invalid voice transfer frame");
2178
+ if (value["type"] === "failure" && typeof value["message"] === "string") {
2179
+ this.finish(new Error(value["message"].slice(0, 4000)));
2180
+ this.channel.close();
2181
+ return;
2182
+ }
2183
+ if (value["type"] === "stage" && isStage(value["stage"])) {
2184
+ this.stages.set(value["stage"], value["value"]);
2185
+ const waiter = this.stageWaiters.get(value["stage"]);
2186
+ if (waiter) {
2187
+ clearTimeout(waiter.timer);
2188
+ this.stageWaiters.delete(value["stage"]);
2189
+ waiter.resolve(value["value"]);
2190
+ }
2191
+ return;
2192
+ }
2193
+ if ((value["type"] === "request" || value["type"] === "reply") && typeof value["id"] === "number" && Number.isSafeInteger(value["id"]) && value["id"] > 0) {
2194
+ const id = value["id"];
2195
+ if (value["type"] === "reply") {
2196
+ if (typeof value["ok"] !== "boolean" || !value["ok"] && typeof value["error"] !== "string")
2197
+ throw new Error("Invalid voice control reply");
2198
+ const pending = this.pending.get(id);
2199
+ if (!pending)
2200
+ return;
2201
+ clearTimeout(pending.timer);
2202
+ this.pending.delete(id);
2203
+ if (value["ok"])
2204
+ pending.resolve(value["value"]);
2205
+ else
2206
+ pending.reject(new Error(String(value["error"])));
2207
+ return;
2208
+ }
2209
+ const method = value["method"];
2210
+ if (!isRequestMethod(method))
2211
+ throw new Error("Invalid voice control request");
2212
+ this.handlers.request(method, value["value"]).then((result) => {
2213
+ if (!this.failure)
2214
+ this.send({ type: "reply", id, ok: true, value: result });
2215
+ }, (error) => {
2216
+ if (!this.failure)
2217
+ this.send({
2218
+ type: "reply",
2219
+ id,
2220
+ ok: false,
2221
+ error: asError(error).message
2222
+ });
2223
+ }).catch((error) => this.fail(asError(error)));
2224
+ return;
2225
+ }
2226
+ const generation = value["generation"];
2227
+ const validGeneration = typeof generation === "number" && Number.isSafeInteger(generation) && generation > 0;
2228
+ if (value["type"] === "peer.command" && typeof value["command"] === "string" && validGeneration) {
2229
+ this.handlers.notification({
2230
+ type: "peer.command",
2231
+ generation,
2232
+ command: value["command"],
2233
+ value: value["value"]
2234
+ });
2235
+ return;
2236
+ }
2237
+ if (value["type"] === "peer.event" && validGeneration) {
2238
+ this.handlers.notification({
2239
+ type: "peer.event",
2240
+ generation,
2241
+ event: value["event"]
2242
+ });
2243
+ return;
2244
+ }
2245
+ if (value["type"] === "session.event" && typeof value["event"] === "string" && value["event"].length <= 64) {
2246
+ this.handlers.notification({
2247
+ type: "session.event",
2248
+ event: value["event"],
2249
+ data: value["data"]
2250
+ });
2251
+ return;
2252
+ }
2253
+ if (value["type"] === "session.mute" && typeof value["muted"] === "boolean") {
2254
+ this.handlers.notification({
2255
+ type: "session.mute",
2256
+ muted: value["muted"]
2257
+ });
2258
+ return;
2259
+ }
2260
+ throw new Error("Invalid voice transfer frame");
2261
+ }
2262
+ }
2263
+ function isRecord(value) {
2264
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
2265
+ }
2266
+ function asError(error) {
2267
+ return error instanceof Error ? error : new Error(String(error));
2268
+ }
2269
+ function isStage(value) {
2270
+ return value === "prepared" || value === "activate" || value === "active";
2271
+ }
2272
+ function isRequestMethod(value) {
2273
+ 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";
2274
+ }
2275
+
2276
+ // packages/gippity-voice/src/voice/browser-reservation.ts
2277
+ function prepareBrowserReservation(reservation, context) {
2278
+ const handle = {};
2279
+ let path;
2280
+ return {
2281
+ handle,
2282
+ async verify(proof) {
2283
+ if (!isRecord(proof) || typeof proof["port"] !== "number" || typeof proof["token"] !== "string")
2284
+ throw new Error("Invalid browser listener proof");
2285
+ const offer = await reservation.offerBrowserArrival({ port: proof["port"], token: proof["token"] }, handle, context);
2286
+ path = offer.path;
2287
+ return offer;
2288
+ },
2289
+ async activate(value) {
2290
+ if (!path || value !== path)
2291
+ throw new Error("Unconfirmed browser arrival");
2292
+ await reservation.activate(context);
2293
+ }
2294
+ };
2295
+ }
2296
+
1807
2297
  // packages/gippity-voice/src/voice/context.ts
1808
2298
  import { createHash } from "node:crypto";
1809
2299
  var SUMMARY_CACHE_LIMIT = 32;
@@ -4030,11 +4520,15 @@ class CodexRealtimeConversation {
4030
4520
  this.turns.handoff.clear();
4031
4521
  this.callbacks.onEndCall?.();
4032
4522
  }
4523
+ get playbackSealed() {
4524
+ return this.peer.playbackSealed === true;
4525
+ }
4033
4526
  get isEndingCall() {
4034
4527
  return this.ending;
4035
4528
  }
4036
- waitForFinalPlayback() {
4037
- return this.waitForPlaybackEnd(this.closing.signal, this.endingOutput);
4529
+ async waitForFinalPlayback() {
4530
+ await this.waitForPlaybackEnd(this.closing.signal, this.endingOutput);
4531
+ await this.peer.finishPlayback?.(this.closing.signal);
4038
4532
  }
4039
4533
  waitForPlaybackEnd(signal, minimumOutputs = 0) {
4040
4534
  signal.throwIfAborted();
@@ -4531,225 +5025,6 @@ function ownVoiceGrant(grant) {
4531
5025
  };
4532
5026
  }
4533
5027
 
4534
- // packages/gippity-voice/src/voice/handoff-wire.ts
4535
- class VoiceHandoffLink {
4536
- pending = new Map;
4537
- stages = new Map;
4538
- stageWaiters = new Map;
4539
- sequence = 0;
4540
- failure;
4541
- removeMessage;
4542
- removeClose;
4543
- channel;
4544
- handlers;
4545
- constructor(channel, handlers) {
4546
- this.channel = channel;
4547
- this.handlers = handlers;
4548
- this.removeMessage = channel.onMessage((message) => {
4549
- try {
4550
- this.receive(message);
4551
- } catch (error) {
4552
- this.fail(asError(error));
4553
- }
4554
- });
4555
- this.removeClose = channel.onClose((error) => this.finish(error));
4556
- if (this.failure) {
4557
- this.removeMessage();
4558
- this.removeClose();
4559
- }
4560
- }
4561
- get closed() {
4562
- return this.failure !== undefined;
4563
- }
4564
- request(method, value) {
4565
- if (this.failure)
4566
- return Promise.reject(this.failure);
4567
- if (this.pending.size >= 32)
4568
- return Promise.reject(new Error("Too many pending voice controls"));
4569
- const id = ++this.sequence;
4570
- return new Promise((resolve, reject) => {
4571
- const timer = setTimeout(() => {
4572
- this.pending.delete(id);
4573
- const error = new Error("Voice control did not respond");
4574
- reject(error);
4575
- this.fail(error);
4576
- }, method === "session.start" ? 120000 : 30000);
4577
- this.pending.set(id, { resolve, reject, timer });
4578
- try {
4579
- this.send({ type: "request", id, method, value });
4580
- } catch (error) {
4581
- this.fail(asError(error));
4582
- }
4583
- });
4584
- }
4585
- notify(message) {
4586
- this.send(message);
4587
- }
4588
- stage(stage, value) {
4589
- this.send({ type: "stage", stage, value });
4590
- }
4591
- waitFor(stage) {
4592
- if (this.failure)
4593
- return Promise.reject(this.failure);
4594
- if (this.stages.has(stage))
4595
- return Promise.resolve(this.stages.get(stage));
4596
- if (this.stageWaiters.has(stage))
4597
- return Promise.reject(new Error("Voice transfer stage already awaited"));
4598
- return new Promise((resolve, reject) => {
4599
- const timer = setTimeout(() => {
4600
- this.stageWaiters.delete(stage);
4601
- const error = new Error("Voice transfer did not finish preparing");
4602
- reject(error);
4603
- this.fail(error);
4604
- }, 120000);
4605
- this.stageWaiters.set(stage, { resolve, reject, timer });
4606
- });
4607
- }
4608
- close() {
4609
- this.fail(new Error("Voice connection closed"));
4610
- }
4611
- fail(error) {
4612
- if (this.failure)
4613
- return;
4614
- try {
4615
- this.channel.send({
4616
- type: "failure",
4617
- message: error.message.slice(0, 4000)
4618
- });
4619
- } catch {}
4620
- this.finish(error);
4621
- this.channel.close();
4622
- }
4623
- send(message) {
4624
- if (this.failure)
4625
- throw this.failure;
4626
- try {
4627
- this.channel.send(message);
4628
- } catch (error) {
4629
- this.fail(asError(error));
4630
- throw error;
4631
- }
4632
- }
4633
- finish(error) {
4634
- if (this.failure)
4635
- return;
4636
- this.failure = error;
4637
- this.removeMessage?.();
4638
- this.removeClose?.();
4639
- for (const pending of [
4640
- ...this.pending.values(),
4641
- ...this.stageWaiters.values()
4642
- ]) {
4643
- clearTimeout(pending.timer);
4644
- pending.reject(error);
4645
- }
4646
- this.pending.clear();
4647
- this.stageWaiters.clear();
4648
- this.handlers.closed(error);
4649
- }
4650
- receive(value) {
4651
- if (this.failure)
4652
- return;
4653
- if (!isRecord(value))
4654
- throw new Error("Invalid voice transfer frame");
4655
- if (value["type"] === "failure" && typeof value["message"] === "string") {
4656
- this.finish(new Error(value["message"].slice(0, 4000)));
4657
- this.channel.close();
4658
- return;
4659
- }
4660
- if (value["type"] === "stage" && isStage(value["stage"])) {
4661
- this.stages.set(value["stage"], value["value"]);
4662
- const waiter = this.stageWaiters.get(value["stage"]);
4663
- if (waiter) {
4664
- clearTimeout(waiter.timer);
4665
- this.stageWaiters.delete(value["stage"]);
4666
- waiter.resolve(value["value"]);
4667
- }
4668
- return;
4669
- }
4670
- if ((value["type"] === "request" || value["type"] === "reply") && typeof value["id"] === "number" && Number.isSafeInteger(value["id"]) && value["id"] > 0) {
4671
- const id = value["id"];
4672
- if (value["type"] === "reply") {
4673
- if (typeof value["ok"] !== "boolean" || !value["ok"] && typeof value["error"] !== "string")
4674
- throw new Error("Invalid voice control reply");
4675
- const pending = this.pending.get(id);
4676
- if (!pending)
4677
- return;
4678
- clearTimeout(pending.timer);
4679
- this.pending.delete(id);
4680
- if (value["ok"])
4681
- pending.resolve(value["value"]);
4682
- else
4683
- pending.reject(new Error(String(value["error"])));
4684
- return;
4685
- }
4686
- const method = value["method"];
4687
- if (!isRequestMethod(method))
4688
- throw new Error("Invalid voice control request");
4689
- this.handlers.request(method, value["value"]).then((result) => {
4690
- if (!this.failure)
4691
- this.send({ type: "reply", id, ok: true, value: result });
4692
- }, (error) => {
4693
- if (!this.failure)
4694
- this.send({
4695
- type: "reply",
4696
- id,
4697
- ok: false,
4698
- error: asError(error).message
4699
- });
4700
- }).catch((error) => this.fail(asError(error)));
4701
- return;
4702
- }
4703
- const generation = value["generation"];
4704
- const validGeneration = typeof generation === "number" && Number.isSafeInteger(generation) && generation > 0;
4705
- if (value["type"] === "peer.command" && typeof value["command"] === "string" && validGeneration) {
4706
- this.handlers.notification({
4707
- type: "peer.command",
4708
- generation,
4709
- command: value["command"],
4710
- value: value["value"]
4711
- });
4712
- return;
4713
- }
4714
- if (value["type"] === "peer.event" && validGeneration) {
4715
- this.handlers.notification({
4716
- type: "peer.event",
4717
- generation,
4718
- event: value["event"]
4719
- });
4720
- return;
4721
- }
4722
- if (value["type"] === "session.event" && typeof value["event"] === "string" && value["event"].length <= 64) {
4723
- this.handlers.notification({
4724
- type: "session.event",
4725
- event: value["event"],
4726
- data: value["data"]
4727
- });
4728
- return;
4729
- }
4730
- if (value["type"] === "session.mute" && typeof value["muted"] === "boolean") {
4731
- this.handlers.notification({
4732
- type: "session.mute",
4733
- muted: value["muted"]
4734
- });
4735
- return;
4736
- }
4737
- throw new Error("Invalid voice transfer frame");
4738
- }
4739
- }
4740
- function isRecord(value) {
4741
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
4742
- }
4743
- function asError(error) {
4744
- return error instanceof Error ? error : new Error(String(error));
4745
- }
4746
- function isStage(value) {
4747
- return value === "prepared" || value === "activate" || value === "active";
4748
- }
4749
- function isRequestMethod(value) {
4750
- return value === "lan.verify" || value === "session.stop" || value === "session.start" || value === "peer.start" || value === "peer.close" || value === "session.send" || value === "session.rpc";
4751
- }
4752
-
4753
5028
  // packages/gippity-voice/src/voice/handoff-peer.ts
4754
5029
  class HandoffAudioHost {
4755
5030
  sequence = 0;
@@ -4801,12 +5076,18 @@ class HandoffAudioHost {
4801
5076
  this.link.notify({ type: "peer.event", generation, event });
4802
5077
  });
4803
5078
  const removeExit = peer.onExit((error) => this.link.fail(error));
4804
- this.current = { generation, peer, removeEvent, removeExit };
5079
+ this.current = {
5080
+ generation,
5081
+ peer,
5082
+ abort: new AbortController,
5083
+ removeEvent,
5084
+ removeExit
5085
+ };
4805
5086
  this.captured.transferred(peer, this.controls);
4806
5087
  const sdp = await this.captured.start(peer);
4807
5088
  if (this.closed || this.current?.generation !== generation)
4808
5089
  throw new Error("Voice transfer cancelled");
4809
- return { generation, sdp };
5090
+ return { generation, sdp, finishPlayback: true };
4810
5091
  } finally {
4811
5092
  this.starting = false;
4812
5093
  }
@@ -4818,6 +5099,20 @@ class HandoffAudioHost {
4818
5099
  return;
4819
5100
  await this.closeCurrent();
4820
5101
  }
5102
+ async finishPlayback(value) {
5103
+ const owner = this.current;
5104
+ if (!owner || !isRecord(value) || value["generation"] !== owner.generation)
5105
+ throw new Error("Voice playback owner changed");
5106
+ try {
5107
+ await owner.peer.finishPlayback?.(owner.abort.signal);
5108
+ return { sealed: owner.peer.playbackSealed === true };
5109
+ } catch (error) {
5110
+ return {
5111
+ sealed: owner.peer.playbackSealed === true,
5112
+ error: asError(error).message.slice(0, 4000)
5113
+ };
5114
+ }
5115
+ }
4821
5116
  command(message) {
4822
5117
  const current = this.current;
4823
5118
  if (!current || message.generation !== current.generation)
@@ -4838,14 +5133,18 @@ class HandoffAudioHost {
4838
5133
  if (this.closed)
4839
5134
  return;
4840
5135
  this.closed = true;
4841
- await this.closeCurrent();
4842
- await this.captured.finished(this.lastPeer, error);
5136
+ try {
5137
+ await this.closeCurrent();
5138
+ } finally {
5139
+ await this.captured.finished(this.lastPeer, error);
5140
+ }
4843
5141
  }
4844
5142
  async closeCurrent() {
4845
5143
  const current = this.current;
4846
5144
  this.current = undefined;
4847
5145
  if (!current)
4848
5146
  return;
5147
+ current.abort.abort();
4849
5148
  current.removeEvent();
4850
5149
  current.removeExit();
4851
5150
  await current.peer.close();
@@ -4857,6 +5156,8 @@ class HandoffRemotePeer {
4857
5156
  listeners = new Set;
4858
5157
  exitListeners = new Set;
4859
5158
  generation;
5159
+ sealed = false;
5160
+ canFinishPlayback = false;
4860
5161
  starting;
4861
5162
  closed = false;
4862
5163
  link;
@@ -4882,6 +5183,7 @@ class HandoffRemotePeer {
4882
5183
  if (!isRecord(result) || typeof result["generation"] !== "number" || !Number.isSafeInteger(result["generation"]) || result["generation"] <= 0 || !validSdp(result["sdp"]))
4883
5184
  throw new Error("Source audio did not return a valid voice offer");
4884
5185
  this.generation = result["generation"];
5186
+ this.canFinishPlayback = result["finishPlayback"] === true;
4885
5187
  return result["sdp"];
4886
5188
  }
4887
5189
  applyAnswer(sdp) {
@@ -4896,6 +5198,24 @@ class HandoffRemotePeer {
4896
5198
  setSpeakerSuppressed(suppressed) {
4897
5199
  this.command("suppress", suppressed);
4898
5200
  }
5201
+ get playbackSealed() {
5202
+ return this.sealed;
5203
+ }
5204
+ async finishPlayback(signal) {
5205
+ signal.throwIfAborted();
5206
+ if (this.closed || this.generation === undefined)
5207
+ throw new Error("Voice peer is not connected");
5208
+ if (!this.canFinishPlayback)
5209
+ return;
5210
+ const result = await interruptible(this.link.request("peer.finish", { generation: this.generation }), signal);
5211
+ if (result === CANCELLED)
5212
+ throw new Error("Playback wait cancelled");
5213
+ if (!isRecord(result) || typeof result["sealed"] !== "boolean" || result["error"] !== undefined && (typeof result["error"] !== "string" || result["error"].length > 4000))
5214
+ throw new Error("Source audio did not confirm playback completion");
5215
+ this.sealed = result["sealed"];
5216
+ if (typeof result["error"] === "string")
5217
+ throw new Error(result["error"]);
5218
+ }
4899
5219
  command(command, value) {
4900
5220
  if (this.closed)
4901
5221
  return;
@@ -4966,27 +5286,12 @@ function readPeerEvent(value) {
4966
5286
 
4967
5287
  // packages/gippity-voice/src/voice/lan/takeover.ts
4968
5288
  import { randomUUID as randomUUID2, X509Certificate } from "node:crypto";
5289
+
5290
+ // internal/voice/lan-listener-proof.ts
4969
5291
  import { get } from "node:https";
4970
- function prepareLanTakeover(certificate) {
4971
- return {
4972
- certificate,
4973
- offer: {
4974
- certificate: new X509Certificate(certificate.cert).fingerprint256,
4975
- token: randomUUID2()
4976
- }
4977
- };
4978
- }
4979
- function decodeLanTakeoverOffer(value) {
4980
- if (!isRecord(value) || typeof value["certificate"] !== "string" || typeof value["token"] !== "string" || !/^[a-f0-9-]{36}$/.test(value["token"]))
4981
- throw new Error("The selected voice provider does not support same-address LAN takeover; the source remains active");
4982
- return { certificate: value["certificate"], token: value["token"] };
4983
- }
4984
- function assertLanTakeoverIdentity(source, target) {
4985
- if (source.certificate !== target.certificate)
4986
- throw new Error("LAN certificates differ; same-address takeover cannot preserve browser trust. The source remains active");
4987
- }
4988
- async function verifyLanTakeoverListener(certificate, value, signal) {
4989
- 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"]))
5292
+ import { checkServerIdentity } from "node:tls";
5293
+ async function verifyLanTakeoverListener(certificate, fingerprint, value, signal, browserRealm) {
5294
+ 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"]))
4990
5295
  throw new Error("Invalid LAN listener proof");
4991
5296
  const { port, token } = value;
4992
5297
  await new Promise((resolve, reject) => {
@@ -4996,8 +5301,9 @@ async function verifyLanTakeoverListener(certificate, value, signal) {
4996
5301
  path: `/api/takeover-proof?token=${token}`,
4997
5302
  ca: certificate,
4998
5303
  rejectUnauthorized: true,
5304
+ checkServerIdentity: (host, peer) => checkServerIdentity(host, peer) ?? (peer.fingerprint256 === fingerprint ? undefined : new Error("LAN listener certificate does not match the offer")),
4999
5305
  agent: false,
5000
- signal
5306
+ signal: AbortSignal.any([signal, AbortSignal.timeout(5000)])
5001
5307
  }, (response) => {
5002
5308
  let body = "";
5003
5309
  response.setEncoding("utf8");
@@ -5007,13 +5313,54 @@ async function verifyLanTakeoverListener(certificate, value, signal) {
5007
5313
  request.destroy(new Error("Invalid LAN listener proof"));
5008
5314
  });
5009
5315
  response.on("error", reject);
5010
- response.on("end", () => response.statusCode === 200 && body === token ? resolve() : reject(new Error("The target could not verify the source LAN listener on this machine")));
5316
+ 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")));
5011
5317
  });
5012
5318
  request.setTimeout(5000, () => request.destroy(new Error("Same-address LAN takeover requires a reachable listener on this machine")));
5013
5319
  request.on("error", reject);
5014
5320
  });
5015
5321
  }
5016
5322
 
5323
+ // packages/gippity-voice/src/voice/lan/takeover.ts
5324
+ function prepareLanTakeover(certificate) {
5325
+ const { port, cert } = certificate;
5326
+ const offer = {
5327
+ certificate: new X509Certificate(cert).fingerprint256,
5328
+ token: randomUUID2()
5329
+ };
5330
+ let phase = "offered";
5331
+ return {
5332
+ offer,
5333
+ async verify(value, signal) {
5334
+ if (phase !== "offered" || !isRecord(value) || value["port"] !== port)
5335
+ throw new Error("LAN takeover requires a fresh proof for the granted port");
5336
+ phase = "verifying";
5337
+ try {
5338
+ await verifyLanTakeoverListener(cert, offer.certificate, value, signal);
5339
+ signal.throwIfAborted();
5340
+ phase = "verified";
5341
+ } catch (error) {
5342
+ phase = "offered";
5343
+ throw error;
5344
+ }
5345
+ },
5346
+ claim(value) {
5347
+ if (phase !== "verified" || !isRecord(value) || value["port"] !== port || value["token"] !== offer.token)
5348
+ throw new Error("Invalid or unverified LAN takeover activation");
5349
+ phase = "claimed";
5350
+ return offer.token;
5351
+ }
5352
+ };
5353
+ }
5354
+ function decodeLanTakeoverOffer(value) {
5355
+ if (!isRecord(value) || typeof value["certificate"] !== "string" || typeof value["token"] !== "string" || !/^[a-f0-9-]{36}$/.test(value["token"]))
5356
+ throw new Error("The selected voice provider does not support same-address LAN takeover; the source remains active");
5357
+ return { certificate: value["certificate"], token: value["token"] };
5358
+ }
5359
+ function assertLanTakeoverIdentity(source, target) {
5360
+ if (source.certificate !== target.certificate)
5361
+ throw new Error("LAN certificates differ; same-address takeover cannot preserve browser trust. The source remains active");
5362
+ }
5363
+
5017
5364
  class LanTakeoverArrival {
5018
5365
  pending;
5019
5366
  constructor(token, value) {
@@ -5055,6 +5402,8 @@ function startVoiceDeparture(options) {
5055
5402
  return audio.start();
5056
5403
  if (method === "peer.close")
5057
5404
  return audio.closePeer(value);
5405
+ if (method === "peer.finish")
5406
+ return audio.finishPlayback(value);
5058
5407
  throw new Error("Voice control was sent to the audio host instead of the selected session");
5059
5408
  },
5060
5409
  notification(message) {
@@ -5115,6 +5464,25 @@ function startVoiceDeparture(options) {
5115
5464
  link.waitFor("prepared"),
5116
5465
  options.waitForSettled(abort.signal)
5117
5466
  ]);
5467
+ if (options.browser) {
5468
+ const offer = await options.browser.transfer.authorize(isRecord(prepared) ? prepared["browserTakeover"] : undefined, (proof) => link.request("browser.verify", proof));
5469
+ await audio.release(abort.signal, () => options.browser.transfer.acknowledge(offer, abort.signal));
5470
+ await options.browser.release();
5471
+ link.stage("activate", {
5472
+ inputMuted: audio.inputMuted,
5473
+ alternateVoice: !options.captured.alternateVoice,
5474
+ browserTakeover: offer.path
5475
+ });
5476
+ const active = await link.waitFor("active");
5477
+ if (!isRecord(active) || active["browserTakeover"] !== true)
5478
+ throw new Error("Destination did not confirm the browser listener");
5479
+ takenOver = true;
5480
+ link.close();
5481
+ await cleanup;
5482
+ return;
5483
+ }
5484
+ if (isRecord(prepared) && prepared["browserTakeover"] !== undefined)
5485
+ throw new Error("This source cannot move its paired browser to the destination");
5118
5486
  if (options.lanTakeover) {
5119
5487
  const offered = isRecord(prepared) ? prepared["lanTakeover"] : undefined;
5120
5488
  const offer = offered === undefined ? undefined : decodeLanTakeoverOffer(offered);
@@ -5166,7 +5534,244 @@ function startVoiceDeparture(options) {
5166
5534
  };
5167
5535
  }
5168
5536
 
5169
- // packages/gippity-voice/src/voice/lan/remote-json.ts
5537
+ // packages/gippity-voice/src/voice/lan/browser-peer.ts
5538
+ import {
5539
+ awaitWithContext as awaitWithContext2,
5540
+ BACKGROUND_CONTEXT,
5541
+ withAbortSignal
5542
+ } from "@earendil-works/chord/context";
5543
+ var OFFER_TIMEOUT_MS2 = 15000;
5544
+
5545
+ class LanHostRealtimePeer {
5546
+ kind = "webrtc";
5547
+ helper;
5548
+ onAudio;
5549
+ onSpeakerSuppressed;
5550
+ drain;
5551
+ playbackEpoch = 0;
5552
+ speakerSuppressed = false;
5553
+ inputState = "pending";
5554
+ constructor(host, options) {
5555
+ this.helper = new VoiceHelperClient(host);
5556
+ this.onAudio = options.onAudio;
5557
+ this.onSpeakerSuppressed = options.onSpeakerSuppressed;
5558
+ this.drain = options.drain;
5559
+ }
5560
+ get isSpeakerSuppressed() {
5561
+ return this.speakerSuppressed;
5562
+ }
5563
+ onEvent(listener) {
5564
+ return this.helper.onEvent((event) => {
5565
+ if (event.type === "pcm") {
5566
+ if (this.inputState === "closed" || this.speakerSuppressed || event.epoch !== this.playbackEpoch)
5567
+ return;
5568
+ this.onAudio(Buffer.from(event.audio, "base64"));
5569
+ return;
5570
+ }
5571
+ if (this.inputState === "finishing" && event.type === "state" && event.state === "closed")
5572
+ return;
5573
+ const peerEvent = toPeerEvent2(event);
5574
+ if (peerEvent)
5575
+ listener(peerEvent);
5576
+ });
5577
+ }
5578
+ onExit(listener) {
5579
+ return this.helper.onExit(listener);
5580
+ }
5581
+ async start(_config) {
5582
+ await this.helper.start();
5583
+ if (this.helper.protocolVersion !== 8) {
5584
+ const actualVersion = this.helper.protocolVersion ?? "unknown";
5585
+ await this.helper.close();
5586
+ throw new Error(`Incompatible Codex voice helper protocol ${actualVersion}; expected 8`);
5587
+ }
5588
+ const offer = deferred();
5589
+ const removeEvent = this.helper.onEvent((event) => {
5590
+ if (event.type === "offer")
5591
+ offer.resolve(event.sdp);
5592
+ else if (event.type === "error")
5593
+ offer.reject(new Error(event.message));
5594
+ });
5595
+ const removeExit = this.helper.onExit((error) => offer.reject(error));
5596
+ const timeout = setTimeout(() => offer.reject(new Error("Codex voice helper did not create an offer")), OFFER_TIMEOUT_MS2);
5597
+ this.helper.send({ type: "start_v3_bridge" });
5598
+ try {
5599
+ const sdp = await offer.promise;
5600
+ if (this.inputState === "pending")
5601
+ this.inputState = "ready";
5602
+ return sdp;
5603
+ } finally {
5604
+ clearTimeout(timeout);
5605
+ removeEvent();
5606
+ removeExit();
5607
+ }
5608
+ }
5609
+ applyAnswer(sdp) {
5610
+ this.helper.send({ type: "apply_answer", sdp });
5611
+ }
5612
+ sendData(message) {
5613
+ if (this.inputState === "finishing")
5614
+ return;
5615
+ this.helper.send({ type: "send_data", message });
5616
+ }
5617
+ sendAudio(pcm) {
5618
+ if (this.inputState !== "ready")
5619
+ return;
5620
+ this.helper.send({
5621
+ type: "send_pcm",
5622
+ audio: pcm.toString("base64"),
5623
+ sample_rate: 24000,
5624
+ num_channels: 1
5625
+ });
5626
+ }
5627
+ setInputMuted(muted) {
5628
+ this.helper.send({ type: "set_input_muted", muted });
5629
+ }
5630
+ setSpeakerSuppressed(suppressed) {
5631
+ if (this.speakerSuppressed === suppressed)
5632
+ return;
5633
+ const epoch = this.playbackEpoch + 1;
5634
+ this.helper.send({ type: "set_speaker_suppressed", suppressed, epoch });
5635
+ this.playbackEpoch = epoch;
5636
+ this.speakerSuppressed = suppressed;
5637
+ this.onSpeakerSuppressed(suppressed);
5638
+ }
5639
+ get playbackSealed() {
5640
+ return this.inputState === "finishing";
5641
+ }
5642
+ async finishPlayback(signal) {
5643
+ if (!this.drain)
5644
+ return;
5645
+ signal.throwIfAborted();
5646
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(15000)]);
5647
+ await awaitWithContext2(this.drain(deadline, async () => {
5648
+ deadline.throwIfAborted();
5649
+ this.inputState = "finishing";
5650
+ await this.helper.stop();
5651
+ }), withAbortSignal(deadline, BACKGROUND_CONTEXT));
5652
+ }
5653
+ close() {
5654
+ this.inputState = "closed";
5655
+ return this.helper.close();
5656
+ }
5657
+ }
5658
+ function toPeerEvent2(event) {
5659
+ if (event.type === "state" || event.type === "data" || event.type === "error" || event.type === "playback_activity" || event.type === "audio_diagnostics")
5660
+ return event;
5661
+ return;
5662
+ }
5663
+
5664
+ // packages/gippity-voice/src/voice/lan/pcm-bridge.ts
5665
+ class GippityBrowserAudio {
5666
+ status = "connecting";
5667
+ transcript = "";
5668
+ error;
5669
+ peer;
5670
+ transcriber;
5671
+ shutdown;
5672
+ failure;
5673
+ mode;
5674
+ audio;
5675
+ onFailure;
5676
+ constructor(mode, audio, onFailure) {
5677
+ this.mode = mode;
5678
+ this.audio = audio;
5679
+ this.onFailure = onFailure;
5680
+ }
5681
+ createPeer(host) {
5682
+ const peer = new LanHostRealtimePeer(host, {
5683
+ onAudio: (pcm) => {
5684
+ if (this.peer === peer && !this.shutdown)
5685
+ this.audio.play(pcm);
5686
+ },
5687
+ onSpeakerSuppressed: (suppressed) => {
5688
+ if (this.peer === peer && suppressed)
5689
+ this.audio.clear();
5690
+ },
5691
+ drain: async (signal, seal) => {
5692
+ if (this.audio.finishPlayback)
5693
+ return this.audio.finishPlayback(signal, seal);
5694
+ throw new Error("Browser audio does not support final playback receipts");
5695
+ }
5696
+ });
5697
+ this.peer = peer;
5698
+ return peer;
5699
+ }
5700
+ async startCapture() {
5701
+ if (this.shutdown)
5702
+ throw new Error("Browser audio was closed");
5703
+ await this.audio.start({
5704
+ onAudio: (pcm) => {
5705
+ if (this.shutdown)
5706
+ return;
5707
+ if (this.mode === "dictation")
5708
+ this.transcriber?.append(pcm);
5709
+ else
5710
+ this.peer?.sendAudio(pcm);
5711
+ },
5712
+ onError: (error) => this.fail(error)
5713
+ });
5714
+ }
5715
+ async startDictation(auth, signal) {
5716
+ signal.throwIfAborted();
5717
+ const transcriber = new CodexDictationTranscriber({
5718
+ onError: (error) => this.fail(error),
5719
+ onStatus: () => {}
5720
+ });
5721
+ this.transcriber = transcriber;
5722
+ const cancel = () => void transcriber.close().catch(this.onFailure);
5723
+ signal.addEventListener("abort", cancel, { once: true });
5724
+ try {
5725
+ await transcriber.start(auth);
5726
+ signal.throwIfAborted();
5727
+ await this.startCapture();
5728
+ this.status = "recording";
5729
+ } finally {
5730
+ signal.removeEventListener("abort", cancel);
5731
+ }
5732
+ }
5733
+ setMuted(muted) {
5734
+ this.audio.setMuted(muted);
5735
+ }
5736
+ async finish() {
5737
+ if (this.failure)
5738
+ throw this.failure;
5739
+ if (!this.transcriber || this.shutdown)
5740
+ throw new Error("Browser dictation is not recording");
5741
+ this.status = "finishing";
5742
+ this.audio.setMuted(true);
5743
+ const text = await this.transcriber.finish();
5744
+ if (this.failure)
5745
+ throw this.failure;
5746
+ if (this.shutdown)
5747
+ throw new Error("Browser dictation was cancelled");
5748
+ return text ?? "";
5749
+ }
5750
+ close() {
5751
+ this.shutdown ??= (async () => {
5752
+ this.peer = undefined;
5753
+ this.status = this.failure ? "error" : "idle";
5754
+ const results = await Promise.allSettled([
5755
+ this.transcriber?.close(),
5756
+ this.audio.close()
5757
+ ]);
5758
+ const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
5759
+ if (errors.length)
5760
+ throw new AggregateError(errors, "GipPity browser audio could not close cleanly");
5761
+ })();
5762
+ return this.shutdown;
5763
+ }
5764
+ fail(error) {
5765
+ if (this.shutdown || this.failure)
5766
+ return;
5767
+ this.failure = error;
5768
+ this.error = error.message;
5769
+ this.status = "error";
5770
+ this.onFailure(error);
5771
+ }
5772
+ }
5773
+
5774
+ // internal/voice/remote-json.ts
5170
5775
  var MAX_REMOTE_VALUE_BYTES = 256 * 1024;
5171
5776
  var MAX_REMOTE_STRING_BYTES = 32 * 1024;
5172
5777
  var MAX_REMOTE_ARRAY_ITEMS = 256;
@@ -5317,11 +5922,11 @@ class GippityRemoteApps {
5317
5922
  }
5318
5923
 
5319
5924
  // packages/gippity-voice/src/voice/lan/server.ts
5320
- import { randomUUID as randomUUID3 } from "node:crypto";
5925
+ import { randomUUID as randomUUID4 } from "node:crypto";
5321
5926
  import { createServer } from "node:https";
5322
- import { WebSocket as WebSocket5, WebSocketServer } from "ws";
5927
+ import { WebSocket as WebSocket6, WebSocketServer } from "ws";
5323
5928
 
5324
- // packages/gippity-voice/src/voice/lan/activity.ts
5929
+ // internal/voice/lan-activity.ts
5325
5930
  var MAX_ACTIVITY_BYTES = 16 * 1024;
5326
5931
 
5327
5932
  class LanVoiceActivity {
@@ -5337,34 +5942,120 @@ class LanVoiceActivity {
5337
5942
  snapshot() {
5338
5943
  return this.state;
5339
5944
  }
5340
- working() {
5341
- this.state = { type: "activity", state: "working" };
5342
- this.publish(this.state);
5945
+ working() {
5946
+ this.state = { type: "activity", state: "working" };
5947
+ this.publish(this.state);
5948
+ }
5949
+ waiting(text) {
5950
+ const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
5951
+ this.state = bounded ? { type: "activity", state: "waiting", text: bounded } : { type: "activity", state: "waiting" };
5952
+ this.publish(this.state);
5953
+ }
5954
+ settled(text) {
5955
+ const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
5956
+ this.state = bounded ? { type: "activity", state: "settled", text: bounded } : { type: "activity", state: "idle" };
5957
+ this.publish(this.state);
5958
+ }
5959
+ }
5960
+ function boundedAssistantText(parts) {
5961
+ const text = parts.flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join(`
5962
+ `).trim();
5963
+ return text ? truncateUtf82(text, MAX_ACTIVITY_BYTES) : undefined;
5964
+ }
5965
+ function truncateUtf82(value, maxBytes) {
5966
+ const buffer = Buffer.from(value);
5967
+ if (buffer.byteLength <= maxBytes)
5968
+ return value;
5969
+ let end = maxBytes - Buffer.byteLength("…");
5970
+ while (end > 0 && (buffer[end] & 192) === 128)
5971
+ end -= 1;
5972
+ return `${buffer.subarray(0, end).toString("utf8").trimEnd()}…`;
5973
+ }
5974
+
5975
+ // internal/voice/lan-draft.ts
5976
+ var MAX_LAN_VOICE_DRAFT_BYTES = 64 * 1024;
5977
+
5978
+ class LanVoiceDraftError extends Error {
5979
+ }
5980
+
5981
+ class LanVoiceDraftConflictError extends LanVoiceDraftError {
5982
+ }
5983
+
5984
+ class LanVoiceDraft {
5985
+ publish;
5986
+ sendMessage;
5987
+ text = "";
5988
+ revision = 0;
5989
+ sending = false;
5990
+ constructor(options) {
5991
+ this.publish = options.publish;
5992
+ this.sendMessage = options.sendMessage;
5993
+ }
5994
+ snapshot(sourceClientId, reason) {
5995
+ return {
5996
+ type: "draft",
5997
+ text: this.text,
5998
+ revision: this.revision,
5999
+ ...sourceClientId ? { sourceClientId } : {},
6000
+ ...reason ? { reason } : {}
6001
+ };
6002
+ }
6003
+ update(clientId, value, expectedRevision) {
6004
+ this.assertRevision(expectedRevision);
6005
+ this.text = validatedDraft(value);
6006
+ this.revision += 1;
6007
+ this.publish(this.snapshot(clientId, "update"));
6008
+ return this.revision;
6009
+ }
6010
+ insertTranscript(clientId, transcript, selection) {
6011
+ const clean = transcript.trim();
6012
+ if (!clean)
6013
+ return;
6014
+ const start = boundedIndex(selection?.start, this.text.length, this.text.length);
6015
+ const end = boundedIndex(selection?.end, this.text.length, start);
6016
+ const before = this.text.slice(0, Math.min(start, end));
6017
+ const after = this.text.slice(Math.max(start, end));
6018
+ const leftSpace = before && !/\s$/.test(before) ? " " : "";
6019
+ const rightSpace = after && !/^\s/.test(after) ? " " : "";
6020
+ this.text = validatedDraft(`${before}${leftSpace}${clean}${rightSpace}${after}`);
6021
+ this.revision += 1;
6022
+ this.publish(this.snapshot(clientId, "transcript"));
5343
6023
  }
5344
- waiting(text) {
5345
- const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
5346
- this.state = bounded ? { type: "activity", state: "waiting", text: bounded } : { type: "activity", state: "waiting" };
5347
- this.publish(this.state);
6024
+ async send(clientId, value, expectedRevision) {
6025
+ this.assertRevision(expectedRevision);
6026
+ if (this.sending)
6027
+ throw new LanVoiceDraftConflictError("A message is already being sent");
6028
+ const text = validatedDraft(value);
6029
+ if (!text.trim())
6030
+ throw new LanVoiceDraftError("A message is required");
6031
+ this.text = text;
6032
+ const revision = this.revision;
6033
+ this.sending = true;
6034
+ try {
6035
+ await this.sendMessage(text);
6036
+ } finally {
6037
+ this.sending = false;
6038
+ }
6039
+ if (this.revision === revision && this.text === text)
6040
+ this.text = "";
6041
+ this.revision += 1;
6042
+ this.publish({ type: "sent" });
6043
+ this.publish(this.snapshot(clientId, "sent"));
5348
6044
  }
5349
- settled(text) {
5350
- const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
5351
- this.state = bounded ? { type: "activity", state: "settled", text: bounded } : { type: "activity", state: "idle" };
5352
- this.publish(this.state);
6045
+ assertRevision(value) {
6046
+ if (!Number.isInteger(value) || value !== this.revision)
6047
+ throw new LanVoiceDraftConflictError("Draft changed on another device; review it and try again");
5353
6048
  }
5354
6049
  }
5355
- function boundedAssistantText(parts) {
5356
- const text = parts.flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join(`
5357
- `).trim();
5358
- return text ? truncateUtf82(text, MAX_ACTIVITY_BYTES) : undefined;
6050
+ function validatedDraft(value) {
6051
+ if (typeof value !== "string")
6052
+ throw new LanVoiceDraftError("Draft text is required");
6053
+ if (Buffer.byteLength(value) > MAX_LAN_VOICE_DRAFT_BYTES)
6054
+ throw new LanVoiceDraftError("Draft is too large");
6055
+ return value;
5359
6056
  }
5360
- function truncateUtf82(value, maxBytes) {
5361
- const buffer = Buffer.from(value);
5362
- if (buffer.byteLength <= maxBytes)
5363
- return value;
5364
- let end = maxBytes - Buffer.byteLength("…");
5365
- while (end > 0 && (buffer[end] & 192) === 128)
5366
- end -= 1;
5367
- return `${buffer.subarray(0, end).toString("utf8").trimEnd()}…`;
6057
+ function boundedIndex(value, length, fallback) {
6058
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= length ? value : fallback;
5368
6059
  }
5369
6060
 
5370
6061
  // packages/gippity-voice/src/voice/lan/app-assets.ts
@@ -5417,7 +6108,7 @@ function createLanVoiceWebManifest() {
5417
6108
  }
5418
6109
 
5419
6110
  // packages/gippity-voice/src/voice/lan/browser-clients.ts
5420
- import { WebSocket as WebSocket4 } from "ws";
6111
+ import { WebSocket as WebSocket5 } from "ws";
5421
6112
 
5422
6113
  // packages/gippity-voice/src/voice/lan/browser-connections.ts
5423
6114
  import { WebSocket as WebSocket2 } from "ws";
@@ -5584,7 +6275,7 @@ class LanVoiceBrowserConnections {
5584
6275
  }
5585
6276
 
5586
6277
  // packages/gippity-voice/src/voice/lan/browser-session.ts
5587
- import { WebSocket as WebSocket3 } from "ws";
6278
+ import { WebSocket as WebSocket4 } from "ws";
5588
6279
 
5589
6280
  // packages/gippity-voice/src/voice/lan/protocol.ts
5590
6281
  function decodeLanVoiceAudioCommand(value) {
@@ -5593,16 +6284,26 @@ function decodeLanVoiceAudioCommand(value) {
5593
6284
  if (value.type === "start") {
5594
6285
  if (!("mode" in value) || value.mode !== "conversation" && value.mode !== "dictation")
5595
6286
  throw invalidCommand();
6287
+ const playback = "playbackDrain" in value ? value.playbackDrain : undefined;
6288
+ if (playback !== undefined && typeof playback !== "boolean")
6289
+ throw invalidCommand();
6290
+ const capability = playback === true ? { playbackDrain: true } : {};
5596
6291
  if ("takeoverToken" in value) {
5597
6292
  if (value.mode !== "conversation" || typeof value.takeoverToken !== "string" || !/^[a-f0-9-]{36}$/.test(value.takeoverToken))
5598
6293
  throw invalidCommand();
5599
6294
  return {
5600
6295
  type: "start",
5601
6296
  mode: value.mode,
5602
- takeoverToken: value.takeoverToken
6297
+ takeoverToken: value.takeoverToken,
6298
+ ...capability
5603
6299
  };
5604
6300
  }
5605
- return { type: "start", mode: value.mode };
6301
+ return { type: "start", mode: value.mode, ...capability };
6302
+ }
6303
+ if (value.type === "drained") {
6304
+ if (!("id" in value) || typeof value.id !== "string" || !/^[a-f0-9-]{36}$/.test(value.id))
6305
+ throw invalidCommand();
6306
+ return { type: "drained", id: value.id };
5606
6307
  }
5607
6308
  if (value.type === "finish") {
5608
6309
  if (!("draft" in value) || typeof value.draft !== "string")
@@ -5716,6 +6417,66 @@ class MicrophoneLevelMonitor {
5716
6417
  }
5717
6418
  }
5718
6419
 
6420
+ // packages/gippity-voice/src/voice/lan/playback-drain.ts
6421
+ import { randomUUID as randomUUID3 } from "node:crypto";
6422
+ import { WebSocket as WebSocket3 } from "ws";
6423
+
6424
+ class LanPlaybackDrain {
6425
+ pending;
6426
+ wait(socket, signal, seal) {
6427
+ signal.throwIfAborted();
6428
+ if (socket.readyState !== WebSocket3.OPEN)
6429
+ throw new Error("The active browser speaker is not connected");
6430
+ if (this.pending)
6431
+ throw new Error("Voice playback is already finishing");
6432
+ return new Promise((resolve, reject) => {
6433
+ const id = randomUUID3();
6434
+ const finish = (error) => {
6435
+ if (this.pending?.id !== id)
6436
+ return;
6437
+ this.pending = undefined;
6438
+ clearTimeout(timer);
6439
+ socket.off("close", closed);
6440
+ signal.removeEventListener("abort", aborted);
6441
+ if (error)
6442
+ reject(error);
6443
+ else
6444
+ resolve();
6445
+ };
6446
+ const closed = () => finish(new Error("Voice device disconnected before playback finished"));
6447
+ const aborted = () => finish(new Error("Playback wait cancelled"));
6448
+ const timer = setTimeout(() => finish(new Error("Voice device did not confirm playback; reconnect it and try again")), 30000);
6449
+ this.pending = { socket, id, finish, sent: false };
6450
+ socket.once("close", closed);
6451
+ signal.addEventListener("abort", aborted, { once: true });
6452
+ Promise.resolve().then(() => {
6453
+ if (this.pending?.id === id)
6454
+ return seal();
6455
+ }).then(() => {
6456
+ if (this.pending?.id !== id)
6457
+ return;
6458
+ if (socket.readyState !== WebSocket3.OPEN) {
6459
+ closed();
6460
+ return;
6461
+ }
6462
+ this.pending.sent = true;
6463
+ socket.send(JSON.stringify({ type: "drain", id }), (error) => {
6464
+ if (error)
6465
+ finish(error);
6466
+ });
6467
+ }).catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
6468
+ });
6469
+ }
6470
+ acknowledge(socket, id) {
6471
+ const pending = this.pending;
6472
+ if (pending?.sent && pending.socket === socket && pending.id === id)
6473
+ pending.finish();
6474
+ }
6475
+ cancel() {
6476
+ this.pending?.finish(new Error("Voice playback owner changed"));
6477
+ }
6478
+ }
6479
+
5719
6480
  // packages/gippity-voice/src/voice/lan/browser-session.ts
5720
6481
  class LanVoiceBrowserSession {
5721
6482
  options;
@@ -5725,6 +6486,7 @@ class LanVoiceBrowserSession {
5725
6486
  conversationOwnerId;
5726
6487
  stopCompletion;
5727
6488
  conversationSpeakerSuppressed = false;
6489
+ playbackDrain = new LanPlaybackDrain;
5728
6490
  microphoneLevel;
5729
6491
  constructor(options, connections) {
5730
6492
  this.options = options;
@@ -5745,6 +6507,7 @@ class LanVoiceBrowserSession {
5745
6507
  setConversationSpeakerSuppressed(suppressed) {
5746
6508
  if (this.conversationSpeakerSuppressed === suppressed)
5747
6509
  return;
6510
+ this.playbackDrain.cancel();
5748
6511
  this.conversationSpeakerSuppressed = suppressed;
5749
6512
  const active = this.state;
5750
6513
  if (active.type === "active" && active.mode === "conversation") {
@@ -5754,10 +6517,27 @@ class LanVoiceBrowserSession {
5754
6517
  });
5755
6518
  }
5756
6519
  }
6520
+ drainPlayback(signal, seal) {
6521
+ const active = this.state;
6522
+ if (active.type !== "active" || active.mode !== "conversation" || !active.playbackDrain || !this.connections.isCurrentAudio(active.clientId, active.socket))
6523
+ throw new Error("This voice device cannot confirm playback; update or reconnect it, or use Stop");
6524
+ return this.playbackDrain.wait(active.socket, signal, seal);
6525
+ }
6526
+ acknowledgePlayback(socket, id) {
6527
+ if (this.conversationSocket === socket)
6528
+ this.playbackDrain.acknowledge(socket, id);
6529
+ }
6530
+ replaceSocket(clientId, socket) {
6531
+ if (this.conversationSocket === socket)
6532
+ this.playbackDrain.cancel();
6533
+ this.releaseStarting(clientId, socket);
6534
+ }
5757
6535
  release(clientId, socket, terminateConversation = false) {
5758
6536
  if (terminateConversation && this.stopCompletion?.clientId === clientId)
5759
6537
  return this.stopCompletion.promise;
5760
6538
  const starting = this.state;
6539
+ if (starting.type === "active" && starting.mode === "conversation" && starting.clientId === clientId && (!socket || starting.socket === socket))
6540
+ this.playbackDrain.cancel();
5761
6541
  const ownsConversation = this.conversationOwnerId === clientId && (!socket || (starting.type === "active" || starting.type === "starting") && starting.socket === socket);
5762
6542
  this.releaseStarting(clientId, socket);
5763
6543
  let completion;
@@ -5802,7 +6582,7 @@ class LanVoiceBrowserSession {
5802
6582
  message: errorMessage(error)
5803
6583
  }));
5804
6584
  }
5805
- claim(clientId, socket, mode, takeoverToken) {
6585
+ claim(clientId, socket, mode, takeoverToken, playbackDrain = false) {
5806
6586
  const starting = this.state.type === "starting" ? this.state : undefined;
5807
6587
  if (starting && (starting.clientId !== clientId || starting.socket !== socket || starting.mode !== mode)) {
5808
6588
  this.releaseStarting(starting.clientId, starting.socket);
@@ -5813,11 +6593,12 @@ class LanVoiceBrowserSession {
5813
6593
  starting.socket.close(4001, "replaced");
5814
6594
  }
5815
6595
  return this.enqueue(async () => {
5816
- if (this.closed || socket.readyState !== WebSocket3.OPEN || !this.connections.isCurrentAudio(clientId, socket))
6596
+ if (this.closed || socket.readyState !== WebSocket4.OPEN || !this.connections.isCurrentAudio(clientId, socket))
5817
6597
  return;
5818
6598
  const previous = this.state.type === "active" ? this.state : undefined;
5819
6599
  if (previous?.clientId === clientId && previous.socket === socket && previous.mode === mode)
5820
6600
  return;
6601
+ this.playbackDrain.cancel();
5821
6602
  this.state = { type: "idle" };
5822
6603
  if (previous?.mode === "conversation")
5823
6604
  this.microphoneLevel.reset();
@@ -5854,12 +6635,12 @@ class LanVoiceBrowserSession {
5854
6635
  this.conversationOwnerId = undefined;
5855
6636
  throw error;
5856
6637
  }
5857
- if (this.closed || this.state !== starting || !this.connections.isCurrentAudio(clientId, socket) || socket.readyState !== WebSocket3.OPEN) {
6638
+ if (this.closed || this.state !== starting || !this.connections.isCurrentAudio(clientId, socket) || socket.readyState !== WebSocket4.OPEN) {
5858
6639
  if (mode === "dictation")
5859
6640
  await this.options.cancelDictation(clientId);
5860
6641
  return;
5861
6642
  }
5862
- this.state = { type: "active", clientId, socket, mode };
6643
+ this.state = { type: "active", clientId, socket, mode, playbackDrain };
5863
6644
  if (mode === "conversation")
5864
6645
  await this.options.onConversationActivity(true);
5865
6646
  socket.send(JSON.stringify({
@@ -5879,7 +6660,7 @@ class LanVoiceBrowserSession {
5879
6660
  return;
5880
6661
  this.state = { type: "idle" };
5881
6662
  await this.options.finishDictation(clientId, draft, revision, selection);
5882
- if (!this.closed && socket.readyState === WebSocket3.OPEN)
6663
+ if (!this.closed && socket.readyState === WebSocket4.OPEN)
5883
6664
  socket.send(JSON.stringify({ type: "dictation.complete" }));
5884
6665
  });
5885
6666
  }
@@ -5906,6 +6687,7 @@ class LanVoiceBrowserSession {
5906
6687
  this.options.onDictationAudio(clientId, pcm);
5907
6688
  }
5908
6689
  async close() {
6690
+ this.playbackDrain.cancel();
5909
6691
  const active = this.state;
5910
6692
  if (active.type === "closed") {
5911
6693
  await this.operation;
@@ -5965,7 +6747,7 @@ class LanVoiceBrowserClients {
5965
6747
  connectAudio(clientId, socket) {
5966
6748
  this.connections.connectAudio(clientId, socket, this.session.closed, {
5967
6749
  onMessage: (data, isBinary) => this.receive(clientId, socket, data, isBinary),
5968
- onReplaced: (previous) => this.session.releaseStarting(clientId, previous),
6750
+ onReplaced: (previous) => this.session.replaceSocket(clientId, previous),
5969
6751
  onClose: () => {
5970
6752
  this.session.release(clientId, socket).catch((error) => this.connections.sendControl(clientId, {
5971
6753
  type: "error",
@@ -5988,7 +6770,7 @@ class LanVoiceBrowserClients {
5988
6770
  }
5989
6771
  takeover(token) {
5990
6772
  const socket = this.session.conversationSocket;
5991
- if (!socket || socket.readyState !== WebSocket4.OPEN)
6773
+ if (!socket || socket.readyState !== WebSocket5.OPEN)
5992
6774
  return Promise.reject(new Error("The active browser microphone is not connected"));
5993
6775
  if (this.takeoverAck)
5994
6776
  return Promise.reject(new Error("A browser takeover is already preparing"));
@@ -6018,6 +6800,9 @@ class LanVoiceBrowserClients {
6018
6800
  sendConversationAudio(pcm) {
6019
6801
  this.session.sendConversationAudio(pcm);
6020
6802
  }
6803
+ drainPlayback(signal, seal) {
6804
+ return this.session.drainPlayback(signal, seal);
6805
+ }
6021
6806
  setConversationSpeakerSuppressed(suppressed) {
6022
6807
  this.session.setConversationSpeakerSuppressed(suppressed);
6023
6808
  }
@@ -6050,7 +6835,9 @@ class LanVoiceBrowserClients {
6050
6835
  }
6051
6836
  const message = input.command;
6052
6837
  if (message.type === "start") {
6053
- this.session.claim(clientId, socket, message.mode, message.takeoverToken).catch((error) => this.sendSocketError(socket, error));
6838
+ this.session.claim(clientId, socket, message.mode, message.takeoverToken, message.playbackDrain).catch((error) => this.sendSocketError(socket, error));
6839
+ } else if (message.type === "drained") {
6840
+ this.session.acknowledgePlayback(socket, message.id);
6054
6841
  } else if (message.type === "finish") {
6055
6842
  this.session.finish(clientId, socket, message.draft, message.revision, message.selection).catch((error) => this.sendSocketError(socket, error));
6056
6843
  } else if (message.type === "release") {
@@ -6065,112 +6852,145 @@ class LanVoiceBrowserClients {
6065
6852
  }
6066
6853
  }
6067
6854
  sendSocketError(socket, error) {
6068
- if (socket.readyState === WebSocket4.OPEN)
6855
+ if (socket.readyState === WebSocket5.OPEN)
6069
6856
  socket.send(JSON.stringify({ type: "error", message: errorMessage(error) }));
6070
6857
  }
6071
6858
  }
6072
6859
 
6073
- // packages/gippity-voice/src/voice/lan/browser-peer.ts
6074
- var OFFER_TIMEOUT_MS2 = 15000;
6860
+ // internal/voice/lan-client-sdk.ts
6861
+ var lanClientScript = (audioScript, listenerPath = "") => String.raw`
6862
+ (function (global) {
6863
+ 'use strict';
6864
+ const listenerPath = ${JSON.stringify(listenerPath)};
6865
+ ${audioScript} function connect(options = {}) {
6866
+ const clientId = options.clientId || id();
6867
+ const listeners = new Map();
6868
+ let closed = false, eventSource, rpcId = 0;
6869
+ let draft = { type:'draft', text:'', revision:-1 };
6870
+ let dirty = false, syncing = false, syncPromise, timer;
6871
+ let resolveInitialDraft;
6872
+ const initialDraft = new Promise((resolve) => { resolveInitialDraft = resolve; });
6873
+ const assertOpen = () => { if (closed) throw new Error('GipPity remote is closed'); };
6075
6874
 
6076
- class LanHostRealtimePeer {
6077
- kind = "webrtc";
6078
- helper;
6079
- onAudio;
6080
- onSpeakerSuppressed;
6081
- playbackEpoch = 0;
6082
- speakerSuppressed = false;
6083
- inputState = "pending";
6084
- constructor(host, options) {
6085
- this.helper = new VoiceHelperClient(host);
6086
- this.onAudio = options.onAudio;
6087
- this.onSpeakerSuppressed = options.onSpeakerSuppressed;
6088
- }
6089
- get isSpeakerSuppressed() {
6090
- return this.speakerSuppressed;
6091
- }
6092
- onEvent(listener) {
6093
- return this.helper.onEvent((event) => {
6094
- if (event.type === "pcm") {
6095
- if (this.speakerSuppressed || event.epoch !== this.playbackEpoch)
6096
- return;
6097
- this.onAudio(Buffer.from(event.audio, "base64"));
6098
- return;
6099
- }
6100
- const peerEvent = toPeerEvent2(event);
6101
- if (peerEvent)
6102
- listener(peerEvent);
6103
- });
6104
- }
6105
- onExit(listener) {
6106
- return this.helper.onExit(listener);
6107
- }
6108
- async start(_config) {
6109
- await this.helper.start();
6110
- if (this.helper.protocolVersion !== 8) {
6111
- const actualVersion = this.helper.protocolVersion ?? "unknown";
6112
- await this.helper.close();
6113
- throw new Error(`Incompatible Codex voice helper protocol ${actualVersion}; expected 8`);
6114
- }
6115
- const offer = deferred();
6116
- const removeEvent = this.helper.onEvent((event) => {
6117
- if (event.type === "offer")
6118
- offer.resolve(event.sdp);
6119
- else if (event.type === "error")
6120
- offer.reject(new Error(event.message));
6121
- });
6122
- const removeExit = this.helper.onExit((error) => offer.reject(error));
6123
- const timeout = setTimeout(() => offer.reject(new Error("Codex voice helper did not create an offer")), OFFER_TIMEOUT_MS2);
6124
- this.helper.send({ type: "start_v3_bridge" });
6125
- try {
6126
- const sdp = await offer.promise;
6127
- if (this.inputState === "pending")
6128
- this.inputState = "ready";
6129
- return sdp;
6130
- } finally {
6131
- clearTimeout(timeout);
6132
- removeEvent();
6133
- removeExit();
6134
- }
6135
- }
6136
- applyAnswer(sdp) {
6137
- this.helper.send({ type: "apply_answer", sdp });
6138
- }
6139
- sendData(message) {
6140
- this.helper.send({ type: "send_data", message });
6141
- }
6142
- sendAudio(pcm) {
6143
- if (this.inputState !== "ready")
6144
- return;
6145
- this.helper.send({
6146
- type: "send_pcm",
6147
- audio: pcm.toString("base64"),
6148
- sample_rate: 24000,
6149
- num_channels: 1
6150
- });
6151
- }
6152
- setInputMuted(muted) {
6153
- this.helper.send({ type: "set_input_muted", muted });
6154
- }
6155
- setSpeakerSuppressed(suppressed) {
6156
- if (this.speakerSuppressed === suppressed)
6157
- return;
6158
- const epoch = this.playbackEpoch + 1;
6159
- this.helper.send({ type: "set_speaker_suppressed", suppressed, epoch });
6160
- this.playbackEpoch = epoch;
6161
- this.speakerSuppressed = suppressed;
6162
- this.onSpeakerSuppressed(suppressed);
6163
- }
6164
- close() {
6165
- this.inputState = "closed";
6166
- return this.helper.close();
6875
+ const emit = (type, value, wildcard = true) => {
6876
+ for (const listener of listeners.get(type) || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6877
+ if (wildcard && type !== '*') for (const listener of listeners.get('*') || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6878
+ };
6879
+ const post = async (path, body) => {
6880
+ assertOpen();
6881
+ const response = await fetch(listenerPath + path, { method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({ clientId, ...body }) });
6882
+ const result = await response.json().catch(() => ({}));
6883
+ if (!response.ok) throw new Error(result.error || 'Pi rejected the request');
6884
+ return result;
6885
+ };
6886
+ const client = {
6887
+ clientId,
6888
+ _emit: emit,
6889
+ _post: post,
6890
+ get draft() { return { ...draft }; },
6891
+ on(type, listener) {
6892
+ assertOpen();
6893
+ if (typeof listener !== 'function') throw new Error('Event listener must be a function');
6894
+ let group = listeners.get(type); if (!group) { group = new Set(); listeners.set(type, group); }
6895
+ group.add(listener); return () => group.delete(listener);
6896
+ },
6897
+ async call(target, method, ...args) {
6898
+ const id = ++rpcId;
6899
+ const result = await post('/api/rpc', { id, target, method, args });
6900
+ if (!result.ok) {
6901
+ const error = new Error(result.error?.message || 'Pi RPC failed');
6902
+ if (result.error?.name) error.name = result.error.name;
6903
+ throw error;
6904
+ }
6905
+ return result.result;
6906
+ },
6907
+ setDraft(text) {
6908
+ assertOpen();
6909
+ if (typeof text !== 'string') throw new Error('Draft text must be a string');
6910
+ draft = { ...draft, text, local:true };
6911
+ dirty = true; emit('draft', { ...draft });
6912
+ clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180);
6913
+ },
6914
+ flushDraft: () => flush(),
6915
+ async send(text) {
6916
+ if (typeof text === 'string' && text !== draft.text) client.setDraft(text);
6917
+ clearTimeout(timer);
6918
+ await flush();
6919
+ if (!draft.text.trim()) throw new Error('A message is required');
6920
+ await post('/api/send', { text:draft.text, revision:draft.revision });
6921
+ },
6922
+ close() {
6923
+ if (closed) return; clearTimeout(timer);
6924
+ client.audio._close(); closed = true; resolveInitialDraft();
6925
+ navigator.sendBeacon(listenerPath + '/api/draft', new Blob([JSON.stringify({ clientId, text:draft.text, revision:draft.revision })], {type:'application/json'}));
6926
+ global.removeEventListener('pagehide', pagehide);
6927
+ eventSource?.close(); listeners.clear();
6928
+ },
6929
+ };
6930
+ const flush = async () => {
6931
+ if (closed) throw new Error('GipPity remote is closed');
6932
+ if (syncing) return syncPromise;
6933
+ if (!dirty) return true;
6934
+ syncing = true;
6935
+ syncPromise = (async () => {
6936
+ if (draft.revision < 0) await initialDraft;
6937
+ if (closed) throw new Error('GipPity remote is closed');
6938
+ while (dirty) {
6939
+ if (closed) throw new Error('GipPity remote is closed');
6940
+ dirty = false;
6941
+ const text = draft.text;
6942
+ try {
6943
+ const result = await post('/api/draft', { text, revision:draft.revision });
6944
+ if (typeof result.revision === 'number') draft = { ...draft, revision:Math.max(draft.revision, result.revision) };
6945
+ } catch (error) {
6946
+ dirty = true; emit('error', { type:'error', source:'draft', message:error instanceof Error ? error.message : String(error) });
6947
+ throw error;
6948
+ }
6949
+ }
6950
+ return true;
6951
+ })();
6952
+ try { return await syncPromise; }
6953
+ finally { syncing = false; syncPromise = undefined; }
6954
+ };
6955
+ const applyDraft = (command) => {
6956
+ if (typeof command.text !== 'string' || typeof command.revision !== 'number' || command.revision < draft.revision) return;
6957
+ if (draft.revision < 0 && dirty) {
6958
+ draft = { ...draft, revision:command.revision };
6959
+ resolveInitialDraft(); emit('draft', { ...draft }); return;
6960
+ }
6961
+ const reconnectSnapshot = !command.sourceClientId && !command.reason;
6962
+ const preserveLocal = (dirty || syncing) && draft.text !== command.text && (reconnectSnapshot || (command.sourceClientId === clientId && (command.reason === 'update' || command.reason === 'sent')));
6963
+ draft = preserveLocal ? { ...draft, revision:command.revision } : { ...command };
6964
+ if (!preserveLocal && command.sourceClientId !== clientId) { clearTimeout(timer); dirty = false; }
6965
+ if (reconnectSnapshot && preserveLocal && dirty) { clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180); }
6966
+ resolveInitialDraft();
6967
+ emit('draft', { ...draft });
6968
+ };
6969
+ client.audio = createAudio(client, assertOpen);
6970
+ eventSource = new EventSource(listenerPath + '/api/events?client=' + encodeURIComponent(clientId));
6971
+ const connectionState = (state) => {
6972
+ const command = { type:'connection', state };
6973
+ client.audio._serverCommand(command); emit('connection', command);
6974
+ };
6975
+ eventSource.onopen = () => connectionState('connected');
6976
+ eventSource.onerror = () => connectionState('reconnecting');
6977
+ eventSource.onmessage = (event) => {
6978
+ try {
6979
+ const command = JSON.parse(event.data);
6980
+ client.audio._serverCommand(command);
6981
+ if (command.type === 'draft') applyDraft(command);
6982
+ else emit(command.type, command);
6983
+ if (command.type === 'durable.event') emit('durable:' + command.event, command.data, false);
6984
+ } catch {}
6985
+ };
6986
+ 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'})); };
6987
+ global.addEventListener('pagehide', pagehide);
6988
+ return client;
6167
6989
  }
6168
- }
6169
- function toPeerEvent2(event) {
6170
- if (event.type === "state" || event.type === "data" || event.type === "error" || event.type === "playback_activity" || event.type === "audio_diagnostics")
6171
- return event;
6172
- return;
6173
- }
6990
+
6991
+ global.GippityRemote = Object.freeze({ connect });
6992
+ })(globalThis);
6993
+ `;
6174
6994
 
6175
6995
  // packages/gippity-voice/src/voice/lan/audio-worklet.ts
6176
6996
  var LAN_VOICE_AUDIO_WORKLET = String.raw`
@@ -6193,9 +7013,8 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6193
7013
  this.playbackLength = 0;
6194
7014
  this.playing = false;
6195
7015
  this.playbackPhase = 0;
6196
- this.playbackCurrent = 0;
6197
- this.playbackNext = 0;
6198
7016
  this.speakerSuppressed = false;
7017
+ this.drain = undefined;
6199
7018
  this.port.onmessage = (event) => this.handleMessage(event.data);
6200
7019
  }
6201
7020
 
@@ -6204,6 +7023,10 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6204
7023
  if (!this.inputMuted && input?.[0]) this.captureInput(input);
6205
7024
  const output = outputs[0]?.[0];
6206
7025
  if (output) this.renderPlayback(output);
7026
+ if (output && this.drain && !this.playing && this.playbackLength === 0) {
7027
+ this.port.postMessage({ type:'rendered', id:this.drain, endTime:(currentFrame + output.length) / sampleRate });
7028
+ this.drain = undefined;
7029
+ }
6207
7030
  return true;
6208
7031
  }
6209
7032
 
@@ -6236,6 +7059,10 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6236
7059
  }
6237
7060
 
6238
7061
  handleMessage(value) {
7062
+ if (value?.type === 'drain' && typeof value.id === 'string') {
7063
+ this.drain = value.id;
7064
+ return;
7065
+ }
6239
7066
  if (value?.type === 'input_muted' && typeof value.muted === 'boolean' && Number.isSafeInteger(value.epoch)) {
6240
7067
  this.captureEpoch = value.epoch;
6241
7068
  this.inputMuted = value.muted;
@@ -6273,42 +7100,45 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
6273
7100
  }
6274
7101
  }
6275
7102
 
6276
- resetPlayback() {
7103
+ clearPlayback() {
6277
7104
  this.playback.fill(0);
6278
7105
  this.playbackRead = 0;
6279
7106
  this.playbackLength = 0;
6280
7107
  this.playing = false;
6281
7108
  this.playbackPhase = 0;
6282
- this.playbackCurrent = 0;
6283
- this.playbackNext = 0;
7109
+ }
7110
+
7111
+ resetPlayback() {
7112
+ this.drain = undefined;
7113
+ this.clearPlayback();
6284
7114
  }
6285
7115
 
6286
7116
  renderPlayback(output) {
6287
7117
  output.fill(0);
6288
7118
  if (!this.playing) {
6289
- if (this.playbackLength < PLAYBACK_START_SAMPLES) return;
7119
+ if (this.playbackLength === 0 || (!this.drain && this.playbackLength < PLAYBACK_START_SAMPLES)) return;
6290
7120
  this.playing = true;
6291
7121
  this.playbackPhase = 0;
6292
- this.playbackCurrent = this.shiftPlayback();
6293
- this.playbackNext = this.shiftPlayback();
6294
7122
  }
6295
7123
  const step = TARGET_RATE / sampleRate;
6296
7124
  for (let index = 0; index < output.length; index++) {
6297
- output[index] = this.playbackCurrent + (this.playbackNext - this.playbackCurrent) * this.playbackPhase;
7125
+ const current = this.playback[this.playbackRead];
7126
+ const next = this.playbackLength > 1 ? this.playback[(this.playbackRead + 1) % PLAYBACK_MAX_SAMPLES] : current;
7127
+ output[index] = current + (next - current) * this.playbackPhase;
6298
7128
  this.playbackPhase += step;
6299
7129
  while (this.playbackPhase >= 1) {
6300
7130
  this.playbackPhase -= 1;
6301
- this.playbackCurrent = this.playbackNext;
7131
+ this.shiftPlayback();
6302
7132
  if (this.playbackLength === 0) {
6303
7133
  this.playing = false;
6304
7134
  return;
6305
7135
  }
6306
- this.playbackNext = this.shiftPlayback();
6307
7136
  }
6308
7137
  }
6309
7138
  }
6310
7139
 
6311
7140
  shiftPlayback() {
7141
+ if (this.playbackLength === 0) return 0;
6312
7142
  const sample = this.playback[this.playbackRead] || 0;
6313
7143
  this.playbackRead = (this.playbackRead + 1) % PLAYBACK_MAX_SAMPLES;
6314
7144
  this.playbackLength -= 1;
@@ -6423,6 +7253,15 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6423
7253
  processor.connect(context.destination);
6424
7254
  return {
6425
7255
  context, processor,
7256
+ canDrain: typeof context.getOutputTimestamp === 'function',
7257
+ drain(id) { processor.port.postMessage({ type:'drain', id }); },
7258
+ async rendered(value, stillCurrent) {
7259
+ if (value?.type !== 'rendered' || typeof value.id !== 'string' || !Number.isFinite(value.endTime)) return;
7260
+ while (stillCurrent() && context.state === 'running') {
7261
+ if (context.getOutputTimestamp().contextTime >= value.endTime) return value.id;
7262
+ await new Promise((resolve) => setTimeout(resolve, 10));
7263
+ }
7264
+ },
6426
7265
  acceptCapture(value) { return value?.type === 'capture' && value.epoch === inputEpoch && value.pcm instanceof ArrayBuffer ? value.pcm : undefined; },
6427
7266
  releaseInput() { microphoneBuffer.port.postMessage({ type:'release' }); },
6428
7267
  setInputMuted(muted) {
@@ -6556,6 +7395,10 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6556
7395
  if (event.data instanceof ArrayBuffer) { realtimeAudio?.play(event.data); return; }
6557
7396
  try {
6558
7397
  const message = JSON.parse(event.data);
7398
+ if (message.type === 'drain' && typeof message.id === 'string') {
7399
+ realtimeAudio?.drain(message.id);
7400
+ return;
7401
+ }
6559
7402
  if (message.type === 'takeover') { beginTakeover(message); return; }
6560
7403
  if (message.type === 'stop') { finishStop(false, message.reason || 'server'); return; }
6561
7404
  if (message.type === 'mute') setMuted(message.muted, false);
@@ -6625,6 +7468,14 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6625
7468
  finishStop(false, 'connect-timeout'); publish('error', 'Connection timed out.');
6626
7469
  }, 10000);
6627
7470
  processor.port.onmessage = (event) => {
7471
+ if (event.data?.type === 'rendered' && realtimeAudio) {
7472
+ const audio = realtimeAudio;
7473
+ const stillCurrent = () => realtimeAudio === audio && socket === current && current.readyState === WebSocket.OPEN;
7474
+ void audio.rendered(event.data, stillCurrent).then((marker) => {
7475
+ if (marker && stillCurrent()) current.send(JSON.stringify({ type:'drained', id:marker }));
7476
+ }).catch(() => {});
7477
+ return;
7478
+ }
6628
7479
  const pcm = realtimeAudio
6629
7480
  ? realtimeAudio.acceptCapture(event.data)
6630
7481
  : event.data?.type === 'capture' && event.data.epoch === 0 && event.data.pcm instanceof ArrayBuffer ? event.data.pcm : undefined;
@@ -6632,7 +7483,7 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6632
7483
  };
6633
7484
  current.onopen = () => {
6634
7485
  if (socket !== current || !context) return;
6635
- clearTimeout(timer); current.send(JSON.stringify({ type:'start', mode, ...(takeoverToken ? { takeoverToken } : {}) })); publish('connecting');
7486
+ clearTimeout(timer); current.send(JSON.stringify({ type:'start', mode, playbackDrain:Boolean(realtimeAudio?.canDrain), ...(takeoverToken ? { takeoverToken } : {}) })); publish('connecting');
6636
7487
  };
6637
7488
  current.onmessage = (event) => receive(current, event);
6638
7489
  current.onclose = (event) => {
@@ -6641,213 +7492,82 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
6641
7492
  if (mode === 'conversation' && ![1002, 1003, 1007, 1008, 1009, 4001].includes(event.code)) { retryConnection('Voice connection lost.'); return; }
6642
7493
  const failedTakeover = replacingCall || retryAttempt > 0;
6643
7494
  const detail = event.reason || 'Voice connection closed unexpectedly (' + event.code + ').';
6644
- finishStop(false, 'connection-closed'); publish('error', failedTakeover ? 'Check the server and connection, then start voice again.' : detail);
6645
- };
6646
- } catch (error) {
6647
- if (currentGeneration !== generation) return;
6648
- finishStop(false, 'start-error'); publish('error', error instanceof Error ? error.message : String(error));
6649
- } finally {
6650
- starting = false;
6651
- if (currentGeneration === generation && !socket) busy = false;
6652
- client._emit('audio', snapshot());
6653
- }
6654
- };
6655
- const beginTakeover = (command) => {
6656
- if (typeof command.token !== 'string' || !command.token || command.token.length > 256 || takeover) return;
6657
- const resume = mode === 'conversation' && (active || busy || Boolean(socket));
6658
- // Only an established audio runtime can be retained across replacement.
6659
- if (starting) { stop(undefined, false, 'takeover'); publish('error', 'Server changed during startup. Start voice again.'); return; }
6660
- takeover = { resume, token:command.token };
6661
- clearTimeout(retryTimer); retryTimer = undefined; retryAttempt = 0; retryDetail = '';
6662
- clearTimeout(staleEventsTimer); staleEventsTimer = undefined;
6663
- resumeMuted = muted;
6664
- active = false; busy = true; finishing = false;
6665
- const oldSocket = socket; socket = undefined;
6666
- if (oldSocket?.readyState === WebSocket.OPEN) oldSocket.send(JSON.stringify({ type:'takeover.ack', token:command.token }));
6667
- oldSocket?.close(1000, 'takeover');
6668
- realtimeAudio?.setSpeakerSuppressed(true);
6669
- if (!resume) closeHardware();
6670
- takeoverTimer = setTimeout(() => {
6671
- finishStop(false, 'takeover-timeout');
6672
- publish('error', 'New session did not become ready. Check the server, then start voice again.');
6673
- }, 20000);
6674
- publish('takeover', resume ? 'Reconnecting voice to the new session…' : 'Waiting for the new session…');
6675
- };
6676
- const completeTakeover = (command) => {
6677
- if (!takeover || command.takeoverToken !== takeover.token) return;
6678
- const { resume, token } = takeover;
6679
- clearTimeout(takeoverTimer); takeover = undefined; busy = false;
6680
- if (resume) { replacingCall = true; void start('conversation', token); }
6681
- else { resumeMuted = false; publish('idle', 'Connected to the new session'); }
6682
- };
6683
- const serverCommand = (command) => {
6684
- if (command.type === 'connection') {
6685
- if (command.state === 'connected') { clearTimeout(staleEventsTimer); staleEventsTimer = undefined; }
6686
- if (command.state === 'reconnecting' && !staleEventsTimer && !retryAttempt && !takeover && mode === 'conversation' && (active || socket)) {
6687
- staleEventsTimer = setTimeout(() => { staleEventsTimer = undefined; retryConnection('Server updates disconnected.'); }, 5000);
6688
- }
6689
- return;
6690
- }
6691
- if (command.type === 'takeover') { beginTakeover(command); return; }
6692
- if (command.type === 'ready') { completeTakeover(command); return; }
6693
- if (takeover) return;
6694
- if (command.type === 'stop') finishStop(false, command.reason || 'server');
6695
- if (command.type === 'error' && (active || busy || socket)) connectionError(command.message);
6696
- if (command.type === 'mute' && mode === 'conversation') setMuted(command.muted, false);
6697
- if (command.type === 'status' && busy && !active && !retryTimer) publish(command.status === 'summarizing…' ? 'summarizing' : 'connecting');
6698
- if (command.type === 'microphone') { inputTooQuiet = command.state === 'too-quiet'; if (active && !muted) publish('listening', inputTooQuiet ? 'Microphone level is too low' : ''); }
6699
- };
6700
- return {
6701
- start(...args) { assertOpen(); return start(...args); },
6702
- stop(...args) { assertOpen(); return stop(...args); },
6703
- setMuted(...args) { assertOpen(); return setMuted(...args); },
6704
- get state() { return snapshot(); },
6705
- _serverCommand: serverCommand,
6706
- _pagehide() {
6707
- if (finishing && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type:'cancel' }));
6708
- else if (active) navigator.sendBeacon('/api/stop', new Blob([JSON.stringify({ clientId:client.clientId })], {type:'application/json'}));
6709
- generation += 1; finishStop(false, 'pagehide');
6710
- },
6711
- _close() { if (finishing) stop(); else { generation += 1; finishStop(true, 'client-closed'); } },
6712
- };
6713
- }
6714
-
6715
- `;
6716
-
6717
- // packages/gippity-voice/src/voice/lan/client-sdk-script.ts
6718
- var LAN_REMOTE_CLIENT_SCRIPT = String.raw`
6719
- (function (global) {
6720
- 'use strict';
6721
- ${LAN_REMOTE_AUDIO_SCRIPT} function connect(options = {}) {
6722
- const clientId = options.clientId || id();
6723
- const listeners = new Map();
6724
- let closed = false, eventSource, rpcId = 0;
6725
- let draft = { type:'draft', text:'', revision:-1 };
6726
- let dirty = false, syncing = false, syncPromise, timer;
6727
- let resolveInitialDraft;
6728
- const initialDraft = new Promise((resolve) => { resolveInitialDraft = resolve; });
6729
- const assertOpen = () => { if (closed) throw new Error('GipPity remote is closed'); };
6730
-
6731
- const emit = (type, value, wildcard = true) => {
6732
- for (const listener of listeners.get(type) || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6733
- if (wildcard && type !== '*') for (const listener of listeners.get('*') || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
6734
- };
6735
- const post = async (path, body) => {
6736
- assertOpen();
6737
- const response = await fetch(path, { method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({ clientId, ...body }) });
6738
- const result = await response.json().catch(() => ({}));
6739
- if (!response.ok) throw new Error(result.error || 'Pi rejected the request');
6740
- return result;
6741
- };
6742
- const client = {
6743
- clientId,
6744
- _emit: emit,
6745
- _post: post,
6746
- get draft() { return { ...draft }; },
6747
- on(type, listener) {
6748
- assertOpen();
6749
- if (typeof listener !== 'function') throw new Error('Event listener must be a function');
6750
- let group = listeners.get(type); if (!group) { group = new Set(); listeners.set(type, group); }
6751
- group.add(listener); return () => group.delete(listener);
6752
- },
6753
- async call(target, method, ...args) {
6754
- const id = ++rpcId;
6755
- const result = await post('/api/rpc', { id, target, method, args });
6756
- if (!result.ok) {
6757
- const error = new Error(result.error?.message || 'Pi RPC failed');
6758
- if (result.error?.name) error.name = result.error.name;
6759
- throw error;
6760
- }
6761
- return result.result;
6762
- },
6763
- setDraft(text) {
6764
- assertOpen();
6765
- if (typeof text !== 'string') throw new Error('Draft text must be a string');
6766
- draft = { ...draft, text, local:true };
6767
- dirty = true; emit('draft', { ...draft });
6768
- clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180);
6769
- },
6770
- flushDraft: () => flush(),
6771
- async send(text) {
6772
- if (typeof text === 'string' && text !== draft.text) client.setDraft(text);
6773
- clearTimeout(timer);
6774
- await flush();
6775
- if (!draft.text.trim()) throw new Error('A message is required');
6776
- await post('/api/send', { text:draft.text, revision:draft.revision });
6777
- },
6778
- close() {
6779
- if (closed) return; clearTimeout(timer);
6780
- client.audio._close(); closed = true; resolveInitialDraft();
6781
- navigator.sendBeacon('/api/draft', new Blob([JSON.stringify({ clientId, text:draft.text, revision:draft.revision })], {type:'application/json'}));
6782
- global.removeEventListener('pagehide', pagehide);
6783
- eventSource?.close(); listeners.clear();
6784
- },
6785
- };
6786
- const flush = async () => {
6787
- if (closed) throw new Error('GipPity remote is closed');
6788
- if (syncing) return syncPromise;
6789
- if (!dirty) return true;
6790
- syncing = true;
6791
- syncPromise = (async () => {
6792
- if (draft.revision < 0) await initialDraft;
6793
- if (closed) throw new Error('GipPity remote is closed');
6794
- while (dirty) {
6795
- if (closed) throw new Error('GipPity remote is closed');
6796
- dirty = false;
6797
- const text = draft.text;
6798
- try {
6799
- const result = await post('/api/draft', { text, revision:draft.revision });
6800
- if (typeof result.revision === 'number') draft = { ...draft, revision:Math.max(draft.revision, result.revision) };
6801
- } catch (error) {
6802
- dirty = true; emit('error', { type:'error', source:'draft', message:error instanceof Error ? error.message : String(error) });
6803
- throw error;
6804
- }
6805
- }
6806
- return true;
6807
- })();
6808
- try { return await syncPromise; }
6809
- finally { syncing = false; syncPromise = undefined; }
7495
+ finishStop(false, 'connection-closed'); publish('error', failedTakeover ? 'Check the server and connection, then start voice again.' : detail);
7496
+ };
7497
+ } catch (error) {
7498
+ if (currentGeneration !== generation) return;
7499
+ finishStop(false, 'start-error'); publish('error', error instanceof Error ? error.message : String(error));
7500
+ } finally {
7501
+ starting = false;
7502
+ if (currentGeneration === generation && !socket) busy = false;
7503
+ client._emit('audio', snapshot());
7504
+ }
6810
7505
  };
6811
- const applyDraft = (command) => {
6812
- if (typeof command.text !== 'string' || typeof command.revision !== 'number' || command.revision < draft.revision) return;
6813
- if (draft.revision < 0 && dirty) {
6814
- draft = { ...draft, revision:command.revision };
6815
- resolveInitialDraft(); emit('draft', { ...draft }); return;
6816
- }
6817
- const reconnectSnapshot = !command.sourceClientId && !command.reason;
6818
- const preserveLocal = (dirty || syncing) && draft.text !== command.text && (reconnectSnapshot || (command.sourceClientId === clientId && (command.reason === 'update' || command.reason === 'sent')));
6819
- draft = preserveLocal ? { ...draft, revision:command.revision } : { ...command };
6820
- if (!preserveLocal && command.sourceClientId !== clientId) { clearTimeout(timer); dirty = false; }
6821
- if (reconnectSnapshot && preserveLocal && dirty) { clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180); }
6822
- resolveInitialDraft();
6823
- emit('draft', { ...draft });
7506
+ const beginTakeover = (command) => {
7507
+ if (typeof command.token !== 'string' || !command.token || command.token.length > 256 || takeover) return;
7508
+ const resume = mode === 'conversation' && (active || busy || Boolean(socket));
7509
+ // Only an established audio runtime can be retained across replacement.
7510
+ if (starting) { stop(undefined, false, 'takeover'); publish('error', 'Server changed during startup. Start voice again.'); return; }
7511
+ takeover = { resume, token:command.token };
7512
+ clearTimeout(retryTimer); retryTimer = undefined; retryAttempt = 0; retryDetail = '';
7513
+ clearTimeout(staleEventsTimer); staleEventsTimer = undefined;
7514
+ resumeMuted = muted;
7515
+ active = false; busy = true; finishing = false;
7516
+ const oldSocket = socket; socket = undefined;
7517
+ if (oldSocket?.readyState === WebSocket.OPEN) oldSocket.send(JSON.stringify({ type:'takeover.ack', token:command.token }));
7518
+ oldSocket?.close(1000, 'takeover');
7519
+ realtimeAudio?.setSpeakerSuppressed(true);
7520
+ if (!resume) closeHardware();
7521
+ takeoverTimer = setTimeout(() => {
7522
+ finishStop(false, 'takeover-timeout');
7523
+ publish('error', 'New session did not become ready. Check the server, then start voice again.');
7524
+ }, 20000);
7525
+ publish('takeover', resume ? 'Reconnecting voice to the new session…' : 'Waiting for the new session…');
6824
7526
  };
6825
- client.audio = createAudio(client, assertOpen);
6826
- eventSource = new EventSource('/api/events?client=' + encodeURIComponent(clientId));
6827
- const connectionState = (state) => {
6828
- const command = { type:'connection', state };
6829
- client.audio._serverCommand(command); emit('connection', command);
7527
+ const completeTakeover = (command) => {
7528
+ if (!takeover || command.takeoverToken !== takeover.token) return;
7529
+ const { resume, token } = takeover;
7530
+ clearTimeout(takeoverTimer); takeover = undefined; busy = false;
7531
+ if (resume) { replacingCall = true; void start('conversation', token); }
7532
+ else { resumeMuted = false; publish('idle', 'Connected to the new session'); }
6830
7533
  };
6831
- eventSource.onopen = () => connectionState('connected');
6832
- eventSource.onerror = () => connectionState('reconnecting');
6833
- eventSource.onmessage = (event) => {
6834
- try {
6835
- const command = JSON.parse(event.data);
6836
- client.audio._serverCommand(command);
6837
- if (command.type === 'draft') applyDraft(command);
6838
- else emit(command.type, command);
6839
- if (command.type === 'durable.event') emit('durable:' + command.event, command.data, false);
6840
- } catch {}
7534
+ const serverCommand = (command) => {
7535
+ if (command.type === 'connection') {
7536
+ if (command.state === 'connected') { clearTimeout(staleEventsTimer); staleEventsTimer = undefined; }
7537
+ if (command.state === 'reconnecting' && !staleEventsTimer && !retryAttempt && !takeover && mode === 'conversation' && (active || socket)) {
7538
+ staleEventsTimer = setTimeout(() => { staleEventsTimer = undefined; retryConnection('Server updates disconnected.'); }, 5000);
7539
+ }
7540
+ return;
7541
+ }
7542
+ if (command.type === 'takeover') { beginTakeover(command); return; }
7543
+ if (command.type === 'ready') { completeTakeover(command); return; }
7544
+ if (takeover) return;
7545
+ if (command.type === 'stop') finishStop(false, command.reason || 'server');
7546
+ if (command.type === 'error' && (active || busy || socket)) connectionError(command.message);
7547
+ if (command.type === 'mute' && mode === 'conversation') setMuted(command.muted, false);
7548
+ if (command.type === 'status' && busy && !active && !retryTimer) publish(command.status === 'summarizing…' ? 'summarizing' : 'connecting');
7549
+ if (command.type === 'microphone') { inputTooQuiet = command.state === 'too-quiet'; if (active && !muted) publish('listening', inputTooQuiet ? 'Microphone level is too low' : ''); }
7550
+ };
7551
+ return {
7552
+ start(...args) { assertOpen(); return start(...args); },
7553
+ stop(...args) { assertOpen(); return stop(...args); },
7554
+ setMuted(...args) { assertOpen(); return setMuted(...args); },
7555
+ get state() { return snapshot(); },
7556
+ _serverCommand: serverCommand,
7557
+ _pagehide() {
7558
+ if (finishing && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type:'cancel' }));
7559
+ else if (active) navigator.sendBeacon('/api/stop', new Blob([JSON.stringify({ clientId:client.clientId })], {type:'application/json'}));
7560
+ generation += 1; finishStop(false, 'pagehide');
7561
+ },
7562
+ _close() { if (finishing) stop(); else { generation += 1; finishStop(true, 'client-closed'); } },
6841
7563
  };
6842
- 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'})); };
6843
- global.addEventListener('pagehide', pagehide);
6844
- return client;
6845
7564
  }
6846
7565
 
6847
- global.GippityRemote = Object.freeze({ connect });
6848
- })(globalThis);
6849
7566
  `;
6850
7567
 
7568
+ // packages/gippity-voice/src/voice/lan/client-sdk-script.ts
7569
+ var LAN_REMOTE_CLIENT_SCRIPT = lanClientScript(LAN_REMOTE_AUDIO_SCRIPT);
7570
+
6851
7571
  // packages/gippity-voice/src/voice/lan/dictation.ts
6852
7572
  class LanVoiceDictation {
6853
7573
  resolveAuth;
@@ -6937,92 +7657,6 @@ class LanVoiceDictation {
6937
7657
  // packages/gippity-voice/src/voice/lan/discovery.ts
6938
7658
  var LAN_REMOTE_CLIENT_PATH = "/_gippity/client.js";
6939
7659
 
6940
- // packages/gippity-voice/src/voice/lan/draft.ts
6941
- var MAX_LAN_VOICE_DRAFT_BYTES = 64 * 1024;
6942
-
6943
- class LanVoiceDraftError extends Error {
6944
- }
6945
-
6946
- class LanVoiceDraftConflictError extends LanVoiceDraftError {
6947
- }
6948
-
6949
- class LanVoiceDraft {
6950
- publish;
6951
- sendMessage;
6952
- text = "";
6953
- revision = 0;
6954
- sending = false;
6955
- constructor(options) {
6956
- this.publish = options.publish;
6957
- this.sendMessage = options.sendMessage;
6958
- }
6959
- snapshot(sourceClientId, reason) {
6960
- return {
6961
- type: "draft",
6962
- text: this.text,
6963
- revision: this.revision,
6964
- ...sourceClientId ? { sourceClientId } : {},
6965
- ...reason ? { reason } : {}
6966
- };
6967
- }
6968
- update(clientId, value, expectedRevision) {
6969
- this.assertRevision(expectedRevision);
6970
- this.text = validatedDraft(value);
6971
- this.revision += 1;
6972
- this.publish(this.snapshot(clientId, "update"));
6973
- return this.revision;
6974
- }
6975
- insertTranscript(clientId, transcript, selection) {
6976
- const clean = transcript.trim();
6977
- if (!clean)
6978
- return;
6979
- const start = boundedIndex(selection?.start, this.text.length, this.text.length);
6980
- const end = boundedIndex(selection?.end, this.text.length, start);
6981
- const before = this.text.slice(0, Math.min(start, end));
6982
- const after = this.text.slice(Math.max(start, end));
6983
- const leftSpace = before && !/\s$/.test(before) ? " " : "";
6984
- const rightSpace = after && !/^\s/.test(after) ? " " : "";
6985
- this.text = validatedDraft(`${before}${leftSpace}${clean}${rightSpace}${after}`);
6986
- this.revision += 1;
6987
- this.publish(this.snapshot(clientId, "transcript"));
6988
- }
6989
- async send(clientId, value, expectedRevision) {
6990
- this.assertRevision(expectedRevision);
6991
- if (this.sending)
6992
- throw new LanVoiceDraftConflictError("A message is already being sent");
6993
- const text = validatedDraft(value);
6994
- if (!text.trim())
6995
- throw new LanVoiceDraftError("A message is required");
6996
- this.text = text;
6997
- const revision = this.revision;
6998
- this.sending = true;
6999
- try {
7000
- await this.sendMessage(text);
7001
- } finally {
7002
- this.sending = false;
7003
- }
7004
- if (this.revision === revision && this.text === text)
7005
- this.text = "";
7006
- this.revision += 1;
7007
- this.publish({ type: "sent" });
7008
- this.publish(this.snapshot(clientId, "sent"));
7009
- }
7010
- assertRevision(value) {
7011
- if (!Number.isInteger(value) || value !== this.revision)
7012
- throw new LanVoiceDraftConflictError("Draft changed on another device; review it and try again");
7013
- }
7014
- }
7015
- function validatedDraft(value) {
7016
- if (typeof value !== "string")
7017
- throw new LanVoiceDraftError("Draft text is required");
7018
- if (Buffer.byteLength(value) > MAX_LAN_VOICE_DRAFT_BYTES)
7019
- throw new LanVoiceDraftError("Draft is too large");
7020
- return value;
7021
- }
7022
- function boundedIndex(value, length, fallback) {
7023
- return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= length ? value : fallback;
7024
- }
7025
-
7026
7660
  // packages/gippity-voice/src/voice/lan/browser-audio-script.ts
7027
7661
  var LAN_VOICE_BROWSER_AUDIO_SCRIPT = String.raw`
7028
7662
  function createAudioController({ button, muteButton, audioState, audioDetail, modeButtons, composer, client }) {
@@ -7554,7 +8188,8 @@ async function startGippityLanServer(options) {
7554
8188
  const factory = () => {
7555
8189
  browserPeer = new LanHostRealtimePeer(options.audio, {
7556
8190
  onAudio: (pcm) => clients.sendConversationAudio(pcm),
7557
- onSpeakerSuppressed: (suppressed) => clients.setConversationSpeakerSuppressed(suppressed)
8191
+ onSpeakerSuppressed: (suppressed) => clients.setConversationSpeakerSuppressed(suppressed),
8192
+ drain: (signal, seal) => clients.drainPlayback(signal, seal)
7558
8193
  });
7559
8194
  return browserPeer;
7560
8195
  };
@@ -7917,13 +8552,13 @@ data: {}
7917
8552
  server.on("error", (error) => clients.broadcastControl({ type: "error", message: error.message }));
7918
8553
  return {
7919
8554
  urls: origins.map((origin) => `${origin.origin}/`),
7920
- browserAttached: () => [...sockets.clients].some((peer) => peer.readyState === WebSocket5.OPEN),
8555
+ browserAttached: () => [...sockets.clients].some((peer) => peer.readyState === WebSocket6.OPEN),
7921
8556
  hasConversation: () => browserVoice && controls.active,
7922
8557
  acknowledgeTakeover: (token) => clients.takeover(token),
7923
8558
  async proveTakeover(verify) {
7924
8559
  if (takeoverProof)
7925
8560
  throw new Error("A LAN listener proof is already pending");
7926
- const token = randomUUID3();
8561
+ const token = randomUUID4();
7927
8562
  takeoverProof = token;
7928
8563
  try {
7929
8564
  await verify({ port: permission.port, token });
@@ -8024,6 +8659,72 @@ async function readBody(request) {
8024
8659
  return body;
8025
8660
  }
8026
8661
 
8662
+ // internal/voice/browser-settings.ts
8663
+ function setting(name, label, value, list) {
8664
+ const choices = list ? [...new Set([...list, value])].map((entry) => ({
8665
+ value: entry,
8666
+ label: entry === null ? "Off" : String(entry)
8667
+ })) : undefined;
8668
+ return { name, label, value, ...choices ? { choices } : {} };
8669
+ }
8670
+
8671
+ // packages/gippity-voice/src/voice/lan/unified-settings.ts
8672
+ var switches = {
8673
+ webSearch: "Web search",
8674
+ autoResumeRealtime: "Resume after interruption",
8675
+ refreshRealtimeAfterCompaction: "Refresh after context compaction",
8676
+ delegationAcknowledgements: "Acknowledge delegated requests",
8677
+ forwardReasoningSummaries: "Relay reasoning summaries"
8678
+ };
8679
+ var modelId = (model) => `${model.provider}/${model.modelId}`;
8680
+ function gippityBrowserFields(config, models, contextAllowed) {
8681
+ const ids = models.map(modelId);
8682
+ return [
8683
+ setting("model", "Model", config.model, GIPPITY_VOICE_MODELS),
8684
+ setting("apiProvider", "API provider", config.apiProvider),
8685
+ setting("realtimeVoice", "Realtime voice", config.realtimeVoice, OPENAI_REALTIME_VOICES),
8686
+ setting("realtimeAlternateVoice", "Alternate Realtime voice", config.realtimeAlternateVoice, OPENAI_REALTIME_VOICES),
8687
+ setting("v3Voice", "Live voice", config.v3Voice, REALTIME_V3_VOICES),
8688
+ setting("v3AlternateVoice", "Alternate Live voice", config.v3AlternateVoice, REALTIME_V3_VOICES),
8689
+ setting("taskDelegationModel", "Delegation model", config.taskDelegationModel, ids),
8690
+ setting("taskDelegationReasoning", "Delegation reasoning", config.taskDelegationReasoning, VOICE_CONTEXT_REASONING_LEVELS),
8691
+ ...contextAllowed ? [
8692
+ setting("contextModel", "Context summary model", config.contextModel ? modelId(config.contextModel) : null, [null, ...ids]),
8693
+ setting("contextReasoning", "Context summary reasoning", config.contextReasoning, VOICE_CONTEXT_REASONING_LEVELS)
8694
+ ] : [],
8695
+ ...Object.entries(switches).map(([name, label]) => {
8696
+ const value = Object.getOwnPropertyDescriptor(config, name)?.value === true;
8697
+ return setting(name, label, value);
8698
+ })
8699
+ ];
8700
+ }
8701
+ function decodeGippityBrowserSettings(patch, config, models, contextAllowed) {
8702
+ const fields = gippityBrowserFields(config, models, contextAllowed);
8703
+ const decoded = {};
8704
+ for (const [key, value] of Object.entries(patch)) {
8705
+ const field = fields.find((field) => field.name === key);
8706
+ if (!field || (field.choices ? !field.choices.some((entry) => entry.value === value) : typeof value !== typeof field.value))
8707
+ throw new Error("Invalid GipPity browser setting");
8708
+ if (key === "contextModel") {
8709
+ decoded[key] = value === null ? undefined : [
8710
+ ...models,
8711
+ ...config.contextModel ? [config.contextModel] : []
8712
+ ].find((model) => modelId(model) === value);
8713
+ if (value === null)
8714
+ decoded["refreshRealtimeAfterCompaction"] = false;
8715
+ } else if (key === "apiProvider") {
8716
+ const provider = normalizeVoiceApiProvider(value);
8717
+ if (!provider)
8718
+ throw new Error("Enter a valid API provider name");
8719
+ decoded[key] = provider;
8720
+ } else
8721
+ decoded[key] = value;
8722
+ }
8723
+ if (Object.hasOwn(decoded, "contextModel") && decoded["contextModel"] === undefined)
8724
+ decoded["refreshRealtimeAfterCompaction"] = false;
8725
+ return decoded;
8726
+ }
8727
+
8027
8728
  // packages/gippity-voice/src/voice/realtime-auth.ts
8028
8729
  async function resolvePublicRealtimeAuth(models, name, signal, access) {
8029
8730
  if (!normalizeVoiceApiProvider(name))
@@ -8090,7 +8791,10 @@ async function resolvePublicRealtimeAuth(models, name, signal, access) {
8090
8791
 
8091
8792
  // packages/gippity-voice/src/voice/realtime-tools.ts
8092
8793
  function createRealtimeAccess(agent, webSearch, execute) {
8093
- const tools = agent.tools.filter((tool) => !readToolContract(tool).nativeOnly && agent.callable.some((candidate) => candidate.name === tool.name));
8794
+ const tools = agent.tools.filter((tool) => {
8795
+ const contract = readToolContract(tool);
8796
+ return !contract.nativeOnly && !contract.nestedHidden && agent.callable.some((candidate) => candidate.name === tool.name);
8797
+ });
8094
8798
  const selected = new Set;
8095
8799
  for (const tool of tools) {
8096
8800
  if (!tool.name || ["send_task", "end_call", "web_search"].includes(tool.name) || selected.has(tool.name))
@@ -8342,9 +9046,9 @@ function createGippityVoice(options) {
8342
9046
  throw new Error("Voice requires explicit audio permission, namespace, and instructions");
8343
9047
  if (options.lan && options.lan.namespace !== options.namespace || options.appFiles && options.appFiles.namespace !== options.namespace)
8344
9048
  throw new Error("Voice host capabilities must share the conversation namespace");
8345
- const instance = randomUUID4();
9049
+ const instance = randomUUID5();
8346
9050
  const leaseOwner = `${registrationName}:${instance}`;
8347
- let providerSessionId = randomUUID4();
9051
+ let providerSessionId = randomUUID5();
8348
9052
  let harness;
8349
9053
  let conversationId;
8350
9054
  let conversation;
@@ -8362,6 +9066,8 @@ function createGippityVoice(options) {
8362
9066
  let session;
8363
9067
  let activeCallId;
8364
9068
  let dictation;
9069
+ let browserAudio;
9070
+ const preparedBrowsers = new WeakMap;
8365
9071
  let lease;
8366
9072
  let peerFactory;
8367
9073
  let activeConfig;
@@ -8384,6 +9090,14 @@ function createGippityVoice(options) {
8384
9090
  const contextSummaryCache = new VoiceContextSummaryCache;
8385
9091
  const listeners = new Set;
8386
9092
  const publish = (event) => {
9093
+ if (browserAudio?.mode === "voice") {
9094
+ if (event.type === "status")
9095
+ browserAudio.status = event.status;
9096
+ else if (event.type === "transcript" && event.role === "user")
9097
+ browserAudio.transcript = event.text;
9098
+ else if (event.type === "error")
9099
+ browserAudio.error = event.message;
9100
+ }
8387
9101
  options.present?.(event);
8388
9102
  for (const listener of listeners)
8389
9103
  listener(event.type, event);
@@ -8421,6 +9135,16 @@ function createGippityVoice(options) {
8421
9135
  }
8422
9136
  }
8423
9137
  };
9138
+ const loadConfig = async () => {
9139
+ await loadPreferences();
9140
+ if (!saved && options.settings) {
9141
+ const loaded = normalizeGippityControlConfig(await options.settings.read());
9142
+ if (!saved) {
9143
+ config = loaded;
9144
+ saved = true;
9145
+ }
9146
+ }
9147
+ };
8424
9148
  const enqueue = (work) => {
8425
9149
  const result = serial.then(work);
8426
9150
  serial = result.then(() => {}, () => {});
@@ -8428,7 +9152,7 @@ function createGippityVoice(options) {
8428
9152
  };
8429
9153
  const changeConfig = (create) => {
8430
9154
  const result = configSerial.then(async () => {
8431
- await loadPreferences();
9155
+ await loadConfig();
8432
9156
  if (settingsContribution && options.preferences) {
8433
9157
  const next = mergeGippityPreferences(validateGippityPreferences(create()));
8434
9158
  const snapshot = await settingsContribution.read();
@@ -8498,6 +9222,8 @@ function createGippityVoice(options) {
8498
9222
  handoffGrant = undefined;
8499
9223
  await Promise.all([...incomingBindings].map((binding) => binding.grant.release()));
8500
9224
  incomingBindings.clear();
9225
+ await browserAudio?.close();
9226
+ browserAudio = undefined;
8501
9227
  session = undefined;
8502
9228
  activeCallId = undefined;
8503
9229
  dictation = undefined;
@@ -8529,7 +9255,7 @@ function createGippityVoice(options) {
8529
9255
  await api.commit(() => ({ status: "running", checkpoint: { phase: "active" } }), context);
8530
9256
  },
8531
9257
  async active(record, api, context) {
8532
- const nonce = randomUUID4();
9258
+ const nonce = randomUUID5();
8533
9259
  if (record.input.instance !== instance || await api.memo("started", nonce, context) !== nonce) {
8534
9260
  await api.commit(() => ({
8535
9261
  status: "terminal",
@@ -8555,11 +9281,7 @@ function createGippityVoice(options) {
8555
9281
  runtimeContext = context;
8556
9282
  closing = false;
8557
9283
  await configSerial;
8558
- await loadPreferences();
8559
- if (!saved && options.settings) {
8560
- config = normalizeGippityControlConfig(await options.settings.read());
8561
- saved = true;
8562
- }
9284
+ await loadConfig();
8563
9285
  events = await observeVoiceAgent(conversation, context, {
8564
9286
  state(value) {
8565
9287
  if (transferred)
@@ -8636,7 +9358,7 @@ function createGippityVoice(options) {
8636
9358
  if (runtime && !closing)
8637
9359
  return;
8638
9360
  if (serviceStart)
8639
- return awaitWithContext2(serviceStart, context);
9361
+ return awaitWithContext3(serviceStart, context);
8640
9362
  if (!harness || !conversationId)
8641
9363
  throw new Error("Bind voice to its Harness and conversation first");
8642
9364
  ready = deferred();
@@ -8657,7 +9379,7 @@ function createGippityVoice(options) {
8657
9379
  serviceStart = undefined;
8658
9380
  throw error;
8659
9381
  });
8660
- return awaitWithContext2(serviceStart, context);
9382
+ return awaitWithContext3(serviceStart, context);
8661
9383
  }
8662
9384
  async function passive(kind, data, text) {
8663
9385
  if (!conversation || !runtimeContext)
@@ -8701,7 +9423,7 @@ function createGippityVoice(options) {
8701
9423
  throw new Error("Context summary export requires explicit host permission");
8702
9424
  const project = async () => {
8703
9425
  const view = await conversation.context(context);
8704
- return options.projectContext && settings.voice.contextModel ? options.projectContext({ conversationId: runtime.conversationId, view }, withAbortSignal(signal, context)) : view;
9426
+ return options.projectContext && settings.voice.contextModel ? options.projectContext({ conversationId: runtime.conversationId, view }, withAbortSignal2(signal, context)) : view;
8705
9427
  };
8706
9428
  const view = await project();
8707
9429
  const input = voiceContextSummaryInput(runtime.conversationId, view, settings);
@@ -8726,12 +9448,12 @@ function createGippityVoice(options) {
8726
9448
  const execute = async (name, args, toolContext) => {
8727
9449
  toolContext.signal.throwIfAborted();
8728
9450
  let id;
8729
- const context = withAbortSignal(toolContext.signal, runtimeContext);
9451
+ const context = withAbortSignal2(toolContext.signal, runtimeContext);
8730
9452
  await runtime.commit(async (tx) => {
8731
9453
  id = await tx.createTask(toolTask, { name, arguments: args }, { ownership: { kind: "task", taskId: runtime.taskId } });
8732
9454
  }, context);
8733
9455
  const abort = () => {
8734
- harness.abortTask(id, BACKGROUND_CONTEXT).catch(report);
9456
+ harness.abortTask(id, BACKGROUND_CONTEXT2).catch(report);
8735
9457
  };
8736
9458
  toolContext.signal.addEventListener("abort", abort, { once: true });
8737
9459
  try {
@@ -8743,8 +9465,8 @@ function createGippityVoice(options) {
8743
9465
  } finally {
8744
9466
  toolContext.signal.removeEventListener("abort", abort);
8745
9467
  if (toolContext.signal.aborted) {
8746
- await harness.abortTask(id, BACKGROUND_CONTEXT);
8747
- await harness.waitForTask(id, BACKGROUND_CONTEXT);
9468
+ await harness.abortTask(id, BACKGROUND_CONTEXT2);
9469
+ await harness.waitForTask(id, BACKGROUND_CONTEXT2);
8748
9470
  }
8749
9471
  }
8750
9472
  };
@@ -8763,7 +9485,7 @@ function createGippityVoice(options) {
8763
9485
  const auth = await resolveAuth(signal, settings);
8764
9486
  signal.throwIfAborted();
8765
9487
  const peer = factory();
8766
- const callId = randomUUID4();
9488
+ const callId = randomUUID5();
8767
9489
  let current;
8768
9490
  current = new CodexRealtimeConversation({
8769
9491
  onStatus: (status) => publish({ type: "status", status }),
@@ -8779,8 +9501,12 @@ function createGippityVoice(options) {
8779
9501
  rewriteDelegation: (turn, signal) => rewriteTaskDelegation(requireRuntime().runtime.models, settings.voice, turn, signal),
8780
9502
  onDelegationError: report,
8781
9503
  onEndCall: () => {
8782
- current.waitForFinalPlayback().then(() => enqueue(async () => {
8783
- if (session === current && current.isEndingCall)
9504
+ current.waitForFinalPlayback().catch((error) => {
9505
+ if (!current.playbackSealed)
9506
+ throw error;
9507
+ report(error);
9508
+ }).then(() => enqueue(async () => {
9509
+ if (session === current && (current.isEndingCall || current.playbackSealed))
8784
9510
  await stopSession(true);
8785
9511
  })).catch(report);
8786
9512
  },
@@ -8850,7 +9576,9 @@ function createGippityVoice(options) {
8850
9576
  signal.removeEventListener("abort", abort);
8851
9577
  }
8852
9578
  }
8853
- async function startVoice(context, factory = () => new NativeCodexRealtimePeer(options.audio), replace = false, startup) {
9579
+ async function startVoice(context, factory = () => new NativeCodexRealtimePeer(options.audio), replace = false, startup, browser) {
9580
+ if (browserAudio !== browser)
9581
+ throw new Error("Stop the shared browser session first");
8854
9582
  if (!startup && transferred)
8855
9583
  return transferred.startCall();
8856
9584
  if (!startup && selectedCall)
@@ -8860,6 +9588,8 @@ function createGippityVoice(options) {
8860
9588
  return enqueue(async () => {
8861
9589
  if (requestedEpoch !== startEpoch)
8862
9590
  throw new Error("Voice startup cancelled");
9591
+ if (browserAudio !== browser)
9592
+ throw new Error("Stop the shared browser session first");
8863
9593
  if (dictation || transferring && !startup || transferred || session && !replace || lease && !session)
8864
9594
  throw new Error("Voice or dictation is already active");
8865
9595
  const previous = session;
@@ -8985,6 +9715,8 @@ ${tail}
8985
9715
  if (!options.lan)
8986
9716
  throw new Error("HTTPS LAN permission was not supplied");
8987
9717
  await enqueue(async () => {
9718
+ if (browserAudio)
9719
+ throw new Error("Stop the shared browser session first");
8988
9720
  if (lan) {
8989
9721
  if (takeover)
8990
9722
  throw new Error("LAN takeover requires a free listener");
@@ -9017,7 +9749,7 @@ ${tail}
9017
9749
  if (taskId || runtime || serviceStart)
9018
9750
  throw new Error("Stop voice before switching conversation");
9019
9751
  if (harness !== value || conversationId !== target) {
9020
- providerSessionId = randomUUID4();
9752
+ providerSessionId = randomUUID5();
9021
9753
  contextSummaryCache.clear();
9022
9754
  }
9023
9755
  harness = value;
@@ -9057,7 +9789,7 @@ ${tail}
9057
9789
  lan?.broadcast({ type: "mute", muted });
9058
9790
  },
9059
9791
  get active() {
9060
- return Boolean(session || dictation || transferred);
9792
+ return Boolean(session || dictation || transferred || browserAudio);
9061
9793
  },
9062
9794
  async startDictation(context) {
9063
9795
  const requestedEpoch = startEpoch;
@@ -9065,7 +9797,7 @@ ${tail}
9065
9797
  await enqueue(async () => {
9066
9798
  if (requestedEpoch !== startEpoch)
9067
9799
  throw new Error("Dictation startup cancelled");
9068
- if (session || dictation || lease || transferring || transferred)
9800
+ if (session || dictation || lease || transferring || transferred || browserAudio)
9069
9801
  throw new Error("Voice or dictation is already active");
9070
9802
  const { runtime } = requireRuntime();
9071
9803
  startAbort = new AbortController;
@@ -9124,7 +9856,7 @@ ${tail}
9124
9856
  type: "input",
9125
9857
  content: text,
9126
9858
  whenBusy: "steer",
9127
- requestId: randomUUID4()
9859
+ requestId: randomUUID5()
9128
9860
  }, context);
9129
9861
  },
9130
9862
  async rpc(body) {
@@ -9285,7 +10017,9 @@ ${tail}
9285
10017
  get summary() {
9286
10018
  return summary;
9287
10019
  },
9288
- async depart(channel, context, transport = "webrtc") {
10020
+ async depart(channel, context, transport = "webrtc", browser) {
10021
+ if (browser && browserAudio !== browser.owner)
10022
+ throw new Error("Browser call changed before departure");
9289
10023
  if (transport !== "webrtc")
9290
10024
  throw new Error("GipPity handoff requires WebRTC; PCM conversion is not available");
9291
10025
  if (!options.handoff || transferring || transferred || !session || !peerFactory || !activeConfig || !lease && (!handoffLink || !handoffGrant))
@@ -9369,7 +10103,7 @@ ${tail}
9369
10103
  },
9370
10104
  async waitForSettled(signal) {
9371
10105
  await source.waitForInput(signal);
9372
- await awaitWithContext2(conversation.waitForIdle(context), context);
10106
+ await awaitWithContext3(conversation.waitForIdle(context), context);
9373
10107
  signal.throwIfAborted();
9374
10108
  await source.waitForPlaybackEnd(signal);
9375
10109
  },
@@ -9378,6 +10112,19 @@ ${tail}
9378
10112
  transferred = value;
9379
10113
  },
9380
10114
  onClosed: report,
10115
+ ...browser ? {
10116
+ browser: {
10117
+ transfer: browser.transfer,
10118
+ async release() {
10119
+ if (browserAudio !== browser.owner || session)
10120
+ throw new Error("Browser call changed during departure");
10121
+ browserAudio = undefined;
10122
+ await browser.owner.close();
10123
+ await releaseLease();
10124
+ await browser.transfer.releaseListener();
10125
+ }
10126
+ }
10127
+ } : {},
9381
10128
  ...lan?.hasConversation() ? {
9382
10129
  lanTakeover: async (offer, releaseAudio, verify) => {
9383
10130
  const server = lan;
@@ -9416,7 +10163,7 @@ ${tail}
9416
10163
  transferring = false;
9417
10164
  }
9418
10165
  },
9419
- async arrive(channel, continuity, context, transport = "webrtc") {
10166
+ async arrive(channel, continuity, context, transport = "webrtc", reservation) {
9420
10167
  if (transport !== "webrtc")
9421
10168
  throw new Error("GipPity handoff requires WebRTC; PCM conversion is not available");
9422
10169
  const returning = Boolean(transferred && sourceBindings.size && !session && !dictation);
@@ -9424,7 +10171,6 @@ ${tail}
9424
10171
  throw new Error("Destination voice is busy or handoff is unauthorized");
9425
10172
  if (Buffer.byteLength(continuity) > 64 * 1024)
9426
10173
  throw new Error("Voice handoff continuity is oversized");
9427
- transferring = true;
9428
10174
  let remote;
9429
10175
  let removeStartupAbort;
9430
10176
  let lanCommitted = false;
@@ -9435,6 +10181,10 @@ ${tail}
9435
10181
  const previousIncoming = handoffLink;
9436
10182
  const previousGrant = handoffGrant;
9437
10183
  const previousAbort = startAbort;
10184
+ if (reservation && (returning || !harness || !conversationId || !reservation.ownsBrowserProvider(harness, conversationId, browserProvider))) {
10185
+ throw new Error("OpenAI browser reservation belongs to a different destination");
10186
+ }
10187
+ transferring = true;
9438
10188
  try {
9439
10189
  await ensureService(context);
9440
10190
  const { runtime } = requireRuntime();
@@ -9449,12 +10199,15 @@ ${tail}
9449
10199
  const prepared = await prepareSummary(signal);
9450
10200
  await resolveAuth(signal);
9451
10201
  let lanPreparation;
10202
+ const browserPreparation = reservation && prepareBrowserReservation(reservation, withAbortSignal2(signal, context));
9452
10203
  try {
9453
- if (options.lan && !lan)
10204
+ if (!reservation && options.lan && !lan)
9454
10205
  lanPreparation = prepareLanTakeover(options.lan);
9455
10206
  } catch {}
9456
10207
  const link = new VoiceHandoffLink(channel, {
9457
10208
  async request(method, value) {
10209
+ if (method === "browser.verify" && browserPreparation)
10210
+ return browserPreparation.verify(value);
9458
10211
  if (method === "session.stop" || method === "session.start") {
9459
10212
  if (transferred)
9460
10213
  return method === "session.stop" ? transferred.stopCall() : transferred.startCall();
@@ -9463,9 +10216,9 @@ ${tail}
9463
10216
  return method === "session.stop" ? selectedCall.stop() : selectedCall.start();
9464
10217
  }
9465
10218
  if (method === "lan.verify") {
9466
- if (!lanPreparation || !isRecord(value) || value["port"] !== lanPreparation.certificate.port)
10219
+ if (!lanPreparation)
9467
10220
  throw new Error("LAN takeover requires permission for the source listener's port");
9468
- await verifyLanTakeoverListener(lanPreparation.certificate.cert, value, signal);
10221
+ await lanPreparation.verify(value, signal);
9469
10222
  return;
9470
10223
  }
9471
10224
  if (method === "session.send" && typeof value === "string")
@@ -9502,7 +10255,7 @@ ${tail}
9502
10255
  signal.addEventListener("abort", cancelled, { once: true });
9503
10256
  removeStartupAbort = () => signal.removeEventListener("abort", cancelled);
9504
10257
  signal.throwIfAborted();
9505
- link.stage("prepared", lanPreparation ? { lanTakeover: lanPreparation.offer } : undefined);
10258
+ link.stage("prepared", reservation ? { browserTakeover: reservation.identity } : lanPreparation ? { lanTakeover: lanPreparation.offer } : undefined);
9506
10259
  const activation = await link.waitFor("activate");
9507
10260
  if (!isRecord(activation) || typeof activation["inputMuted"] !== "boolean" || activation["alternateVoice"] !== undefined && typeof activation["alternateVoice"] !== "boolean")
9508
10261
  throw new Error("Invalid handoff microphone or voice selection");
@@ -9529,11 +10282,32 @@ ${continuity}`
9529
10282
  }
9530
10283
  ];
9531
10284
  const takeover = activation["lanTakeover"];
10285
+ if (browserPreparation) {
10286
+ preparedBrowsers.set(browserPreparation.handle, {
10287
+ epoch: startEpoch,
10288
+ startup: {
10289
+ settings,
10290
+ summary: prepared,
10291
+ items,
10292
+ inputMuted: muted,
10293
+ alternateVoice
10294
+ }
10295
+ });
10296
+ await browserPreparation.activate(activation["browserTakeover"]);
10297
+ signal.throwIfAborted();
10298
+ lanCommitted = true;
10299
+ handoffLink = undefined;
10300
+ await arrivedGrant.release();
10301
+ handoffGrant = undefined;
10302
+ incomingBindings.delete(incoming);
10303
+ link.stage("active", { browserTakeover: true });
10304
+ return;
10305
+ }
9532
10306
  if (takeover !== undefined) {
9533
- if (!lanPreparation || !isRecord(takeover) || takeover["token"] !== lanPreparation.offer.token || takeover["port"] !== lanPreparation.certificate.port)
10307
+ if (!lanPreparation)
9534
10308
  throw new Error("Invalid LAN takeover activation");
9535
10309
  await ensureLan(context, {
9536
- token: lanPreparation.offer.token,
10310
+ token: lanPreparation.claim(takeover),
9537
10311
  startup: {
9538
10312
  settings,
9539
10313
  summary: prepared,
@@ -9625,6 +10399,8 @@ ${continuity}`
9625
10399
  try {
9626
10400
  channel.close();
9627
10401
  } finally {
10402
+ if (reservation)
10403
+ await reservation.cancel().catch(report);
9628
10404
  if (returning && !arrivalActivated) {
9629
10405
  await arrivedGrant?.release();
9630
10406
  if (incoming)
@@ -9643,7 +10419,129 @@ ${continuity}`
9643
10419
  }
9644
10420
  }
9645
10421
  };
9646
- return { extension, controls, settingsContribution };
10422
+ const browserProvider = {
10423
+ settings: {
10424
+ async read(scope) {
10425
+ if (scope.environment.id !== options.namespace)
10426
+ throw new Error("Browser settings and GipPity must share a namespace");
10427
+ await configSerial;
10428
+ await loadConfig();
10429
+ const models = await scope.models.getAvailable(undefined, {
10430
+ signal: scope.signal
10431
+ });
10432
+ return {
10433
+ scope: options.preferences?.writeScope ?? (options.settings ? "Application settings" : "This instance"),
10434
+ fields: gippityBrowserFields(config.voice, models.map((model) => ({
10435
+ provider: model.provider,
10436
+ modelId: model.id
10437
+ })), options.allowContextSummary === true)
10438
+ };
10439
+ },
10440
+ async write(scope, patch) {
10441
+ if (scope.environment.id !== options.namespace)
10442
+ throw new Error("Browser settings and GipPity must share a namespace");
10443
+ const models = (await scope.models.getAvailable(undefined, { signal: scope.signal })).map((model) => ({ provider: model.provider, modelId: model.id }));
10444
+ await changeConfig(() => {
10445
+ scope.signal.throwIfAborted();
10446
+ const values = decodeGippityBrowserSettings(patch, config.voice, models, options.allowContextSummary === true);
10447
+ return { ...config, voice: { ...config.voice, ...values } };
10448
+ });
10449
+ }
10450
+ },
10451
+ resume(input, handle) {
10452
+ const prepared = preparedBrowsers.get(handle);
10453
+ preparedBrowsers.delete(handle);
10454
+ if (!prepared || prepared.epoch !== startEpoch || input.mode !== "voice")
10455
+ throw new Error("Prepared browser session no longer available");
10456
+ return openBrowser(input, prepared.startup);
10457
+ },
10458
+ open(input) {
10459
+ return openBrowser(input);
10460
+ }
10461
+ };
10462
+ async function openBrowser(input, startup) {
10463
+ if (input.environmentId !== options.namespace)
10464
+ throw new Error("Browser audio and GipPity must share a namespace");
10465
+ if (harness === undefined && conversationId === undefined)
10466
+ controls.bindHarness(input.harness, input.conversationId);
10467
+ if (harness !== input.harness || conversationId !== input.conversationId)
10468
+ throw new Error("GipPity is bound to a different conversation");
10469
+ if (browserAudio || session || dictation || lease || !startup && startAbort?.signal.aborted === false || lan || !startup && transferring || transferred || selectedCall)
10470
+ throw new Error("GipPity voice, dictation or LAN is already active");
10471
+ const browser = new GippityBrowserAudio(input.mode, input.audio, (error) => {
10472
+ if (browserAudio !== browser)
10473
+ return;
10474
+ report(error);
10475
+ startAbort?.abort(error);
10476
+ close().catch(report);
10477
+ });
10478
+ const close = () => enqueue(async () => {
10479
+ if (browserAudio === browser)
10480
+ await stopSession();
10481
+ });
10482
+ browserAudio = browser;
10483
+ try {
10484
+ if (input.mode === "voice") {
10485
+ await startVoice(input.context, () => browser.createPeer(options.audio), false, startup, browser);
10486
+ input.context.abortSignal?.throwIfAborted();
10487
+ if (startup)
10488
+ browser.setMuted(startup.inputMuted);
10489
+ await browser.startCapture();
10490
+ } else {
10491
+ await ensureService(input.context);
10492
+ await enqueue(async () => {
10493
+ if (browserAudio !== browser)
10494
+ throw new Error("Browser dictation cancelled");
10495
+ const { runtime } = requireRuntime();
10496
+ startAbort = new AbortController;
10497
+ const signal = AbortSignal.any([
10498
+ runtime.signal,
10499
+ startAbort.signal,
10500
+ ...input.context.abortSignal ? [input.context.abortSignal] : []
10501
+ ]);
10502
+ lease = await options.lease.acquire({
10503
+ owner: `${leaseOwner}:${runtime.conversationId}`,
10504
+ mode: "dictation"
10505
+ }, signal);
10506
+ await browser.startDictation(await resolveDictationAuth(signal), signal);
10507
+ });
10508
+ }
10509
+ input.context.abortSignal?.throwIfAborted();
10510
+ } catch (error) {
10511
+ await close();
10512
+ throw error;
10513
+ }
10514
+ return {
10515
+ state: () => ({
10516
+ status: browser.status,
10517
+ muted: browserAudio === browser && controls.inputMuted,
10518
+ transcript: browser.transcript,
10519
+ ...browser.error ? { error: browser.error } : {}
10520
+ }),
10521
+ mute(value) {
10522
+ if (browserAudio !== browser)
10523
+ throw new Error("GipPity browser call ended");
10524
+ controls.setInputMuted(value);
10525
+ browser.setMuted(value);
10526
+ },
10527
+ async send(text) {
10528
+ if (browserAudio !== browser)
10529
+ throw new Error("GipPity browser call ended");
10530
+ await controls.sendText(text, BACKGROUND_CONTEXT2);
10531
+ },
10532
+ finish: () => browser.finish(),
10533
+ departBrowser(channel, context, transfer) {
10534
+ if (browserAudio !== browser || input.mode !== "voice")
10535
+ throw new Error("OpenAI browser call ended");
10536
+ return controls.depart(channel, context, "webrtc", {
10537
+ owner: browser,
10538
+ transfer
10539
+ });
10540
+ },
10541
+ close
10542
+ };
10543
+ }
10544
+ return { extension, controls, settingsContribution, browserProvider };
9647
10545
  }
9648
10546
  function asError2(value) {
9649
10547
  return value instanceof Error ? value : new Error(String(value));