@howaboua/pi-durable-gippity-voice 0.10.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.
- package/NOTICE +5 -0
- package/README.md +4 -2
- package/dist/activation.js +2108 -989
- package/dist/index.js +2115 -996
- package/dist/internal/voice/agent-observation.d.ts +13 -0
- package/dist/internal/voice/browser-provider.d.ts +65 -0
- package/dist/internal/voice/browser-settings.d.ts +24 -0
- package/dist/internal/voice/handoff-contract.d.ts +28 -0
- package/dist/internal/voice/lan-client-sdk.d.ts +1 -0
- package/dist/internal/voice/lan-listener-proof.d.ts +2 -0
- package/dist/packages/execution/src/invocation-state.d.ts +1 -1
- package/dist/packages/execution/src/invocation.d.ts +79 -2
- package/dist/packages/execution/src/native-tools.d.ts +18 -7
- package/dist/packages/execution/src/nested-call.d.ts +11 -3
- package/dist/packages/execution/src/nested-park.d.ts +9 -0
- package/dist/packages/execution/src/nested-result.d.ts +1 -1
- package/dist/packages/execution/src/tool-contract.d.ts +10 -3
- package/dist/packages/execution/src/tool-namespaces.d.ts +31 -0
- package/dist/packages/execution/src/tool-origin.d.ts +9 -1
- package/dist/packages/gippity-voice/src/controller.d.ts +10 -3
- package/dist/packages/gippity-voice/src/host.d.ts +6 -0
- package/dist/packages/gippity-voice/src/index.d.ts +2 -1
- package/dist/packages/gippity-voice/src/voice/browser-reservation.d.ts +30 -0
- package/dist/packages/gippity-voice/src/voice/conversation/peer.d.ts +6 -0
- package/dist/packages/gippity-voice/src/voice/conversation/public-turns.d.ts +2 -1
- package/dist/packages/gippity-voice/src/voice/conversation/session.d.ts +2 -0
- package/dist/packages/gippity-voice/src/voice/handoff-departure.d.ts +5 -0
- package/dist/packages/gippity-voice/src/voice/handoff-peer.d.ts +12 -0
- package/dist/packages/gippity-voice/src/voice/handoff-wire.d.ts +1 -1
- package/dist/packages/gippity-voice/src/voice/helper-protocol.d.ts +35 -0
- package/dist/packages/gippity-voice/src/voice/lan/browser-clients.d.ts +2 -1
- package/dist/packages/gippity-voice/src/voice/lan/browser-connections.d.ts +17 -0
- package/dist/packages/gippity-voice/src/voice/lan/browser-peer.d.ts +4 -0
- package/dist/packages/gippity-voice/src/voice/lan/browser-session.d.ts +10 -4
- package/dist/packages/gippity-voice/src/voice/lan/pcm-bridge.d.ts +25 -0
- package/dist/packages/gippity-voice/src/voice/lan/playback-drain.d.ts +8 -0
- package/dist/packages/gippity-voice/src/voice/lan/protocol.d.ts +4 -0
- package/dist/packages/gippity-voice/src/voice/lan/server.d.ts +5 -3
- package/dist/packages/gippity-voice/src/voice/lan/takeover.d.ts +2 -3
- package/dist/packages/gippity-voice/src/voice/lan/unified-settings.d.ts +3 -0
- package/dist/packages/gippity-voice/src/voice/realtime-auth.d.ts +3 -2
- package/dist/packages/gippity-voice/src/voice/turns.d.ts +2 -1
- package/dist/voice/bin/darwin-arm64/pi-codex-voice +0 -0
- package/dist/voice/bin/darwin-x64/pi-codex-voice +0 -0
- package/dist/voice/bin/linux-arm64/pi-codex-voice +0 -0
- package/dist/voice/bin/linux-x64/pi-codex-voice +0 -0
- package/dist/voice/bin/win32-arm64/pi-codex-voice.exe +0 -0
- package/dist/voice/bin/win32-x64/pi-codex-voice.exe +0 -0
- package/package.json +10 -9
- package/src/voice/rust/src/audio.rs +2 -2
- package/src/voice/rust/src/playout.rs +68 -8
- package/src/voice/rust/src/protocol.rs +43 -1
- package/src/voice/rust/src/v3_media.rs +138 -31
- /package/dist/{packages/gippity-voice/src → internal/voice}/deferred.d.ts +0 -0
- /package/dist/{packages/gippity-voice/src/voice/lan/activity.d.ts → internal/voice/lan-activity.d.ts} +0 -0
- /package/dist/{packages/gippity-voice/src/voice/lan/draft.d.ts → internal/voice/lan-draft.d.ts} +0 -0
- /package/dist/{packages/gippity-voice/src/voice/lan → internal/voice}/remote-json.d.ts +0 -0
package/dist/activation.js
CHANGED
|
@@ -36,17 +36,18 @@ function componentSettings(directory, initial) {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
// packages/gippity-voice/src/controller.ts
|
|
39
|
-
import { randomUUID as
|
|
39
|
+
import { randomUUID as randomUUID5, X509Certificate as X509Certificate2 } from "node:crypto";
|
|
40
40
|
import {
|
|
41
|
-
awaitWithContext as
|
|
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
|
+
AgentDoc,
|
|
47
|
+
CompactionEntry,
|
|
46
48
|
defineExtension,
|
|
47
49
|
defineTask as defineTask2,
|
|
48
|
-
UserEntry
|
|
49
|
-
watchEvents
|
|
50
|
+
UserEntry
|
|
50
51
|
} from "@earendil-works/pi-durable";
|
|
51
52
|
|
|
52
53
|
// internal/settings/index.ts
|
|
@@ -152,16 +153,105 @@ function createSettingsContribution(options) {
|
|
|
152
153
|
};
|
|
153
154
|
}
|
|
154
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
|
+
|
|
155
244
|
// packages/execution/src/nested.ts
|
|
245
|
+
import { copyJson as copyJson8 } from "@earendil-works/chord/json";
|
|
156
246
|
import {
|
|
157
247
|
defineTask
|
|
158
248
|
} from "@earendil-works/pi-durable";
|
|
159
|
-
import {
|
|
249
|
+
import { compile as compile2 } from "@earendil-works/pi-schema";
|
|
160
250
|
|
|
161
251
|
// packages/execution/src/forwarding.ts
|
|
162
|
-
import { copyJson as copyJson2 } from "@earendil-works/chord";
|
|
252
|
+
import { copyJson as copyJson2 } from "@earendil-works/chord/json";
|
|
163
253
|
import {
|
|
164
|
-
LiveDoc,
|
|
254
|
+
LiveDoc as LiveDoc2,
|
|
165
255
|
NestedCallDoc,
|
|
166
256
|
ToolTask
|
|
167
257
|
} from "@earendil-works/pi-durable";
|
|
@@ -169,7 +259,7 @@ import {
|
|
|
169
259
|
// packages/execution/src/invocation-state.ts
|
|
170
260
|
import {
|
|
171
261
|
copyJson
|
|
172
|
-
} from "@earendil-works/chord";
|
|
262
|
+
} from "@earendil-works/chord/json";
|
|
173
263
|
import {
|
|
174
264
|
defineDoc
|
|
175
265
|
} from "@earendil-works/pi-durable";
|
|
@@ -521,7 +611,7 @@ async function forwardInvocationResult(tx, taskId, result, status) {
|
|
|
521
611
|
async function captureNativeCalls(tx, conversationId, owner, cellId) {
|
|
522
612
|
if (cellId === undefined)
|
|
523
613
|
return;
|
|
524
|
-
const live = await tx.doc(
|
|
614
|
+
const live = await tx.doc(LiveDoc2, conversationId);
|
|
525
615
|
const owners = new Set([owner]);
|
|
526
616
|
const cell = await tx.doc(InvocationDoc, cellId);
|
|
527
617
|
const budget = cell.forwardingBudget ?? 40000;
|
|
@@ -611,26 +701,53 @@ async function captureNativeCalls(tx, conversationId, owner, cellId) {
|
|
|
611
701
|
}
|
|
612
702
|
|
|
613
703
|
// packages/execution/src/invocation.ts
|
|
614
|
-
import { copyJson as copyJson4 } from "@earendil-works/chord";
|
|
615
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";
|
|
616
710
|
|
|
617
711
|
// packages/execution/src/native-tools.ts
|
|
618
|
-
import { copyJson as copyJson3 } from "@earendil-works/chord";
|
|
619
|
-
import { withoutAbortSignal } from "@earendil-works/chord/context";
|
|
620
712
|
import {
|
|
621
|
-
|
|
713
|
+
withoutAbortSignal
|
|
714
|
+
} from "@earendil-works/chord/context";
|
|
715
|
+
import { copyJson as copyJson3 } from "@earendil-works/chord/json";
|
|
716
|
+
import {
|
|
717
|
+
LiveDoc as LiveDoc3,
|
|
622
718
|
NestedCallDoc as NestedCallDoc2,
|
|
623
|
-
ToolTask as
|
|
719
|
+
ToolTask as ToolTask3
|
|
624
720
|
} from "@earendil-works/pi-durable";
|
|
625
721
|
import { Equal } from "typebox/value";
|
|
626
|
-
|
|
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) {
|
|
627
742
|
let sequence = 0;
|
|
628
743
|
const admissions = [];
|
|
629
|
-
|
|
744
|
+
async function execute(name, args, callContext, options = {}) {
|
|
630
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");
|
|
631
750
|
const key = options.key ?? String(++sequence);
|
|
632
|
-
if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
|
|
633
|
-
throw new Error("Invalid nested call key");
|
|
634
751
|
const call = {
|
|
635
752
|
type: "toolCall",
|
|
636
753
|
id: `${callId}/${key}`,
|
|
@@ -642,11 +759,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
642
759
|
const admission = runtime.commit(async (tx) => {
|
|
643
760
|
const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
|
|
644
761
|
if (slot.taskId !== undefined) {
|
|
645
|
-
const input = (await tx.task(slot.taskId))?.input;
|
|
762
|
+
const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
|
|
646
763
|
if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
|
|
647
764
|
throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
|
|
648
765
|
} else {
|
|
649
|
-
slot.
|
|
766
|
+
slot.kind = "nested";
|
|
767
|
+
slot.taskId = await tx.createTask(ToolTask3, {
|
|
650
768
|
kind: "nested",
|
|
651
769
|
parent: runtime.taskId,
|
|
652
770
|
parentCallId: callId,
|
|
@@ -657,7 +775,10 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
657
775
|
ownership: { kind: "task", taskId: runtime.taskId },
|
|
658
776
|
abandonOnRestart: replay !== "safe"
|
|
659
777
|
});
|
|
660
|
-
const live = await tx.doc(
|
|
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 };
|
|
661
782
|
live.nestedTools ??= [];
|
|
662
783
|
live.nestedTools.push({
|
|
663
784
|
callId: call.id,
|
|
@@ -689,7 +810,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
689
810
|
const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
|
|
690
811
|
if (slot?.taskId === undefined)
|
|
691
812
|
throw new Error("Nested task creation did not commit");
|
|
692
|
-
const
|
|
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);
|
|
693
820
|
const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
|
|
694
821
|
await runtime.commit(async (tx) => {
|
|
695
822
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
@@ -697,7 +824,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
697
824
|
return;
|
|
698
825
|
}, callContext);
|
|
699
826
|
return result === undefined ? {
|
|
700
|
-
taskId
|
|
827
|
+
taskId,
|
|
701
828
|
isError: true,
|
|
702
829
|
diagnostics: [
|
|
703
830
|
{
|
|
@@ -707,9 +834,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
707
834
|
}
|
|
708
835
|
]
|
|
709
836
|
} : copyJson3(result);
|
|
710
|
-
}
|
|
837
|
+
}
|
|
711
838
|
return {
|
|
712
839
|
execute,
|
|
840
|
+
async drain() {
|
|
841
|
+
await Promise.allSettled(admissions);
|
|
842
|
+
},
|
|
713
843
|
async finish() {
|
|
714
844
|
await Promise.allSettled(admissions);
|
|
715
845
|
await cleanupNativeCalls(runtime, withoutAbortSignal(context));
|
|
@@ -717,11 +847,11 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
717
847
|
};
|
|
718
848
|
}
|
|
719
849
|
async function cleanupNativeCalls(runtime, context) {
|
|
720
|
-
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind ===
|
|
850
|
+
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
|
|
721
851
|
await runtime.commit(async (tx) => {
|
|
722
852
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
723
853
|
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
724
|
-
const live = await tx.doc(
|
|
854
|
+
const live = await tx.doc(LiveDoc3, runtime.conversationId);
|
|
725
855
|
const removed = new Set([runtime.taskId]);
|
|
726
856
|
for (const slot of live.nestedTools ?? [])
|
|
727
857
|
if (removed.has(slot.parentTaskId))
|
|
@@ -811,18 +941,6 @@ class Progress {
|
|
|
811
941
|
}
|
|
812
942
|
}
|
|
813
943
|
|
|
814
|
-
// packages/execution/src/tool-origin.ts
|
|
815
|
-
import {
|
|
816
|
-
defineDoc as defineDoc2
|
|
817
|
-
} from "@earendil-works/pi-durable";
|
|
818
|
-
var ToolOriginDoc = defineDoc2({
|
|
819
|
-
kind: "howaboua.tool-origin",
|
|
820
|
-
version: 1,
|
|
821
|
-
scope: "task",
|
|
822
|
-
checkpointWhen: () => false,
|
|
823
|
-
initial: () => ({})
|
|
824
|
-
});
|
|
825
|
-
|
|
826
944
|
// packages/execution/src/invocation.ts
|
|
827
945
|
function executionError(code, message) {
|
|
828
946
|
return {
|
|
@@ -834,21 +952,23 @@ function executionError(code, message) {
|
|
|
834
952
|
function errorText(error) {
|
|
835
953
|
return error instanceof Error ? error.message : String(error);
|
|
836
954
|
}
|
|
837
|
-
function createInvocation(runtime, tool, context) {
|
|
955
|
+
function createInvocation(runtime, tool, context, resume) {
|
|
838
956
|
const limits = {
|
|
839
957
|
maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
|
|
840
958
|
maxLines: tool.outputLimits?.maxLines ?? 2000,
|
|
841
959
|
retain: tool.outputLimits?.retain ?? "head"
|
|
842
960
|
};
|
|
843
961
|
const output = new OutputBuffer(limits);
|
|
844
|
-
const diagnostics = [
|
|
845
|
-
|
|
962
|
+
const diagnostics = [
|
|
963
|
+
...resume?.progress?.diagnostics ?? []
|
|
964
|
+
];
|
|
965
|
+
let details = resume?.progress?.details;
|
|
846
966
|
let ended = false;
|
|
847
967
|
const assertLive = () => {
|
|
848
968
|
if (ended)
|
|
849
969
|
throw new Error(`Invocation ${runtime.taskId} has settled`);
|
|
850
970
|
};
|
|
851
|
-
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);
|
|
852
972
|
const snapshot = () => {
|
|
853
973
|
const retained = output.snapshot();
|
|
854
974
|
return {
|
|
@@ -877,6 +997,8 @@ function createInvocation(runtime, tool, context) {
|
|
|
877
997
|
taskId: runtime.taskId,
|
|
878
998
|
conversationId: runtime.conversationId,
|
|
879
999
|
callId: `nested-${runtime.taskId}`,
|
|
1000
|
+
wake: resume?.wake,
|
|
1001
|
+
checkpoint: resume?.checkpoint,
|
|
880
1002
|
registry: runtime.registry,
|
|
881
1003
|
agent: runtime.agent,
|
|
882
1004
|
env: undefined,
|
|
@@ -897,7 +1019,7 @@ function createInvocation(runtime, tool, context) {
|
|
|
897
1019
|
const retained = output.snapshot();
|
|
898
1020
|
return { text: retained.text, truncated: retained.droppedBytes > 0 };
|
|
899
1021
|
},
|
|
900
|
-
executeTool:
|
|
1022
|
+
executeTool: native.execute,
|
|
901
1023
|
diagnostic: (value) => {
|
|
902
1024
|
assertLive();
|
|
903
1025
|
diagnostics.push(copyJson4(value, { omitUndefinedProperties: true }));
|
|
@@ -911,24 +1033,44 @@ function createInvocation(runtime, tool, context) {
|
|
|
911
1033
|
committed.catch(() => {});
|
|
912
1034
|
await awaitWithContext(committed, detailContext);
|
|
913
1035
|
},
|
|
914
|
-
commit: async (change, commitContext) => {
|
|
1036
|
+
commit: async (change, commitContext, options) => {
|
|
915
1037
|
assertLive();
|
|
916
1038
|
let result;
|
|
917
1039
|
await runtime.commit(async (tx) => {
|
|
918
1040
|
result = await change(tx);
|
|
919
1041
|
return;
|
|
920
|
-
}, commitContext);
|
|
1042
|
+
}, commitContext, options);
|
|
921
1043
|
return result;
|
|
922
1044
|
},
|
|
923
1045
|
memo: runtime.memo,
|
|
924
|
-
|
|
1046
|
+
readSignal: runtime.readSignal,
|
|
1047
|
+
async createTask(task, input, {
|
|
1048
|
+
key,
|
|
1049
|
+
...options
|
|
1050
|
+
}, taskContext) {
|
|
925
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");
|
|
926
1056
|
let id;
|
|
927
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
|
+
}
|
|
928
1066
|
id = await tx.createTask(task, input, {
|
|
929
1067
|
...options,
|
|
930
1068
|
...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
|
|
931
1069
|
});
|
|
1070
|
+
if (member !== undefined) {
|
|
1071
|
+
member.kind = "task";
|
|
1072
|
+
member.taskId = id;
|
|
1073
|
+
}
|
|
932
1074
|
const source = await tx.doc(ToolOriginDoc, runtime.taskId);
|
|
933
1075
|
if (source.origin !== undefined)
|
|
934
1076
|
(await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
|
|
@@ -975,6 +1117,14 @@ function createInvocation(runtime, tool, context) {
|
|
|
975
1117
|
for (const waiter of await progress.stop())
|
|
976
1118
|
waiter.reject(error);
|
|
977
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
|
+
},
|
|
978
1128
|
limits,
|
|
979
1129
|
output,
|
|
980
1130
|
progress
|
|
@@ -1008,12 +1158,22 @@ function truncation(dropped, retain) {
|
|
|
1008
1158
|
// packages/execution/src/nested-call.ts
|
|
1009
1159
|
import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
|
|
1010
1160
|
import {
|
|
1011
|
-
ToolTask as
|
|
1161
|
+
ToolTask as ToolTask4
|
|
1012
1162
|
} from "@earendil-works/pi-durable";
|
|
1013
|
-
import {
|
|
1163
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
1164
|
+
|
|
1165
|
+
// packages/execution/src/tool-contract.ts
|
|
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
|
+
}
|
|
1014
1175
|
|
|
1015
1176
|
// packages/execution/src/tool-contract.ts
|
|
1016
|
-
import { copyJson as copyJson5 } from "@earendil-works/chord";
|
|
1017
1177
|
function readToolContract(tool) {
|
|
1018
1178
|
const candidate = "executionHints" in tool ? tool.executionHints : undefined;
|
|
1019
1179
|
if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
|
|
@@ -1027,6 +1187,7 @@ function readToolContract(tool) {
|
|
|
1027
1187
|
"yieldTimeMs",
|
|
1028
1188
|
"inputSchema",
|
|
1029
1189
|
"nativeOnly",
|
|
1190
|
+
"nestedHidden",
|
|
1030
1191
|
"discovery"
|
|
1031
1192
|
]);
|
|
1032
1193
|
for (const key of Object.keys(hints))
|
|
@@ -1050,6 +1211,12 @@ function readToolContract(tool) {
|
|
|
1050
1211
|
const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
|
|
1051
1212
|
if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
|
|
1052
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`);
|
|
1053
1220
|
const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
|
|
1054
1221
|
if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
|
|
1055
1222
|
throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
|
|
@@ -1066,6 +1233,8 @@ function readToolContract(tool) {
|
|
|
1066
1233
|
inputSchema,
|
|
1067
1234
|
deferLoading: typeof deferred === "boolean" ? deferred : true,
|
|
1068
1235
|
nativeOnly: nativeOnly === true,
|
|
1236
|
+
nestedHidden: nestedHidden === true,
|
|
1237
|
+
...jsNamespace === undefined ? {} : { jsNamespace },
|
|
1069
1238
|
...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
|
|
1070
1239
|
...outputHint === undefined ? {} : { output: outputHint },
|
|
1071
1240
|
help: [
|
|
@@ -1099,7 +1268,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1099
1268
|
if (typeof input !== "string")
|
|
1100
1269
|
return input;
|
|
1101
1270
|
const contract = readToolContract(tool);
|
|
1102
|
-
if (Boolean(
|
|
1271
|
+
if (Boolean(compile(tool.parameters).check(input)) || (typeof contract.inputSchema === "boolean" || typeof contract.inputSchema === "object" && contract.inputSchema !== null && !Array.isArray(contract.inputSchema)) && Boolean(compile(contract.inputSchema).check(input)))
|
|
1103
1272
|
return input;
|
|
1104
1273
|
const text = input.trim();
|
|
1105
1274
|
if (contract.discovery === "help" && text === "help")
|
|
@@ -1122,7 +1291,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1122
1291
|
async function eachHook(agent, name, api, invoke) {
|
|
1123
1292
|
for (const extension of agent.extensions)
|
|
1124
1293
|
for (const registration of extension.hooks ?? []) {
|
|
1125
|
-
if (registration.task !==
|
|
1294
|
+
if (registration.task !== ToolTask4.definition.name)
|
|
1126
1295
|
continue;
|
|
1127
1296
|
const handler = registration.handlers[name];
|
|
1128
1297
|
if (handler === undefined)
|
|
@@ -1137,8 +1306,120 @@ async function eachHook(agent, name, api, invoke) {
|
|
|
1137
1306
|
}
|
|
1138
1307
|
}
|
|
1139
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
|
+
|
|
1140
1421
|
// packages/execution/src/nested-result.ts
|
|
1141
|
-
import { copyJson as
|
|
1422
|
+
import { copyJson as copyJson7 } from "@earendil-works/chord/json";
|
|
1142
1423
|
import {
|
|
1143
1424
|
defineEntry,
|
|
1144
1425
|
UsageDoc
|
|
@@ -1186,11 +1467,11 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1186
1467
|
taskId: runtime.taskId,
|
|
1187
1468
|
callId: call.id,
|
|
1188
1469
|
name: call.name,
|
|
1189
|
-
arguments:
|
|
1470
|
+
arguments: copyJson7(call.arguments),
|
|
1190
1471
|
result: stored,
|
|
1191
1472
|
...current.state.checkpoint.phase === "execute" ? {
|
|
1192
1473
|
intent: {
|
|
1193
|
-
arguments:
|
|
1474
|
+
arguments: copyJson7(current.state.checkpoint.arguments),
|
|
1194
1475
|
replay: current.state.checkpoint.replay
|
|
1195
1476
|
}
|
|
1196
1477
|
} : {}
|
|
@@ -1199,7 +1480,7 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1199
1480
|
if (result.usage !== undefined) {
|
|
1200
1481
|
const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
|
|
1201
1482
|
const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
|
|
1202
|
-
totals[call.name] =
|
|
1483
|
+
totals[call.name] = copyJson7(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
|
|
1203
1484
|
}
|
|
1204
1485
|
const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
|
|
1205
1486
|
status: ending,
|
|
@@ -1236,7 +1517,11 @@ function sumUsage(previous, added) {
|
|
|
1236
1517
|
function createNestedToolTask(name) {
|
|
1237
1518
|
return defineTask({
|
|
1238
1519
|
name,
|
|
1239
|
-
version:
|
|
1520
|
+
version: 2,
|
|
1521
|
+
migrate: (input, checkpoint) => ({
|
|
1522
|
+
input,
|
|
1523
|
+
checkpoint
|
|
1524
|
+
}),
|
|
1240
1525
|
initial: () => ({ phase: "call" }),
|
|
1241
1526
|
phases: {
|
|
1242
1527
|
call: async (task, runtime, context) => {
|
|
@@ -1262,22 +1547,25 @@ function createNestedToolTask(name) {
|
|
|
1262
1547
|
return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
|
|
1263
1548
|
let args;
|
|
1264
1549
|
try {
|
|
1265
|
-
const supplied = task.input.arguments === null && !
|
|
1550
|
+
const supplied = task.input.arguments === null && !compile2(tool.parameters).check(null) && compile2(tool.parameters).check({}) ? undefined : task.input.arguments;
|
|
1266
1551
|
const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
|
|
1267
|
-
args = checked(tool, call, prepared === undefined &&
|
|
1552
|
+
args = checked(tool, call, prepared === undefined && compile2(tool.parameters).check({}) ? {} : prepared);
|
|
1268
1553
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1269
1554
|
call.arguments = args;
|
|
1270
1555
|
} catch (error) {
|
|
1271
1556
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1272
1557
|
}
|
|
1273
1558
|
let block;
|
|
1559
|
+
let sleep;
|
|
1274
1560
|
await eachHook(agent, "beforeTool", runtime, async (handler) => {
|
|
1275
|
-
if (block !== undefined)
|
|
1561
|
+
if (block !== undefined || sleep !== undefined)
|
|
1276
1562
|
return;
|
|
1277
1563
|
try {
|
|
1278
1564
|
const decision = await handler({ ...call, arguments: args }, runtime, context);
|
|
1279
1565
|
if (decision?.block !== undefined)
|
|
1280
1566
|
block = decision.block;
|
|
1567
|
+
else if (decision?.sleep !== undefined)
|
|
1568
|
+
sleep = decision.sleep;
|
|
1281
1569
|
else if (decision?.arguments !== undefined)
|
|
1282
1570
|
args = decision.arguments;
|
|
1283
1571
|
} catch (error) {
|
|
@@ -1288,71 +1576,122 @@ function createNestedToolTask(name) {
|
|
|
1288
1576
|
});
|
|
1289
1577
|
if (block !== undefined)
|
|
1290
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
|
+
}
|
|
1291
1585
|
try {
|
|
1292
|
-
args = checked(tool, call, args)
|
|
1586
|
+
args = copyJson8(checked(tool, call, args), {
|
|
1587
|
+
omitUndefinedProperties: true
|
|
1588
|
+
});
|
|
1293
1589
|
} catch (error) {
|
|
1294
1590
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1295
1591
|
}
|
|
1296
|
-
await runtime
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
callId: call.id,
|
|
1300
|
-
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1301
|
-
name: call.name,
|
|
1302
|
-
arguments: args,
|
|
1303
|
-
status: "running",
|
|
1304
|
-
result: null,
|
|
1305
|
-
omittedFields: []
|
|
1306
|
-
});
|
|
1307
|
-
return {
|
|
1308
|
-
status: "running",
|
|
1309
|
-
checkpoint: {
|
|
1310
|
-
phase: "execute",
|
|
1311
|
-
arguments: args,
|
|
1312
|
-
replay: tool.replay ?? "unsafe"
|
|
1313
|
-
}
|
|
1314
|
-
};
|
|
1592
|
+
await startAttempt(runtime, call, tool, agent, {
|
|
1593
|
+
arguments: args,
|
|
1594
|
+
replay: tool.replay ?? "unsafe"
|
|
1315
1595
|
}, context);
|
|
1316
|
-
|
|
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);
|
|
1317
1609
|
},
|
|
1318
1610
|
execute: async (task, runtime, context) => {
|
|
1611
|
+
const intent = task.state.checkpoint;
|
|
1319
1612
|
const call = nestedCall(runtime, task.input);
|
|
1320
1613
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1321
1614
|
call.arguments = task.state.checkpoint.arguments;
|
|
1322
1615
|
const agent = await runtime.agent(context);
|
|
1323
1616
|
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1324
|
-
if (
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
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);
|
|
1333
1627
|
}
|
|
1628
|
+
if (intent.resume !== undefined)
|
|
1629
|
+
await cancelParkedTool(runtime, tool, intent, context);
|
|
1334
1630
|
await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
|
|
1335
1631
|
}
|
|
1336
1632
|
},
|
|
1337
1633
|
abort: async (task, runtime, context) => {
|
|
1338
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
|
+
}
|
|
1339
1641
|
await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
|
|
1340
1642
|
}
|
|
1341
1643
|
});
|
|
1342
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
|
+
}
|
|
1343
1668
|
async function reject(runtime, call, result, agent, tool, context) {
|
|
1344
1669
|
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1345
1670
|
result = await handler(call, result, runtime, context) ?? result;
|
|
1346
1671
|
});
|
|
1347
1672
|
await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
|
|
1348
1673
|
}
|
|
1349
|
-
async function run(runtime, call, tool,
|
|
1674
|
+
async function run(runtime, call, tool, intent, agent, context, wake) {
|
|
1350
1675
|
let invocation;
|
|
1351
1676
|
let result;
|
|
1352
1677
|
let ending = "completed";
|
|
1353
1678
|
try {
|
|
1354
|
-
|
|
1355
|
-
|
|
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
|
+
}
|
|
1356
1695
|
} catch (error) {
|
|
1357
1696
|
if (runtime.signal.aborted) {
|
|
1358
1697
|
await invocation?.stop(error);
|
|
@@ -1404,7 +1743,7 @@ function finishResult(tool, name, result) {
|
|
|
1404
1743
|
} else if (final.structuredOutput === undefined) {
|
|
1405
1744
|
if (!final.isError)
|
|
1406
1745
|
throw new Error(`Tool ${name} returned no structuredOutput`);
|
|
1407
|
-
} else if (!
|
|
1746
|
+
} else if (!compile2(tool.structuredOutputSchema).check(final.structuredOutput)) {
|
|
1408
1747
|
throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
|
|
1409
1748
|
}
|
|
1410
1749
|
} catch (error) {
|
|
@@ -1572,17 +1911,6 @@ function normalizeGippityControlConfig(value) {
|
|
|
1572
1911
|
};
|
|
1573
1912
|
}
|
|
1574
1913
|
|
|
1575
|
-
// packages/gippity-voice/src/deferred.ts
|
|
1576
|
-
function deferred() {
|
|
1577
|
-
let resolve;
|
|
1578
|
-
let reject;
|
|
1579
|
-
const promise = new Promise((yes, no) => {
|
|
1580
|
-
resolve = yes;
|
|
1581
|
-
reject = no;
|
|
1582
|
-
});
|
|
1583
|
-
return { promise, resolve, reject };
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
1914
|
// packages/gippity-voice/src/preferences.ts
|
|
1587
1915
|
function object(value, path) {
|
|
1588
1916
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
@@ -1726,55 +2054,295 @@ async function resolveCodexVoiceAuth(models, conversationId, signal) {
|
|
|
1726
2054
|
}
|
|
1727
2055
|
}
|
|
1728
2056
|
|
|
1729
|
-
// packages/gippity-voice/src/voice/
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
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();
|
|
1745
2082
|
}
|
|
1746
2083
|
}
|
|
1747
|
-
|
|
1748
|
-
this.
|
|
2084
|
+
get closed() {
|
|
2085
|
+
return this.failure !== undefined;
|
|
1749
2086
|
}
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
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
|
+
});
|
|
1765
2107
|
}
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
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
|
+
|
|
2297
|
+
// packages/gippity-voice/src/voice/context.ts
|
|
2298
|
+
import { createHash } from "node:crypto";
|
|
2299
|
+
var SUMMARY_CACHE_LIMIT = 32;
|
|
2300
|
+
|
|
2301
|
+
class VoiceContextSummaryCache {
|
|
2302
|
+
summaries = new Map;
|
|
2303
|
+
get(key) {
|
|
2304
|
+
return this.summaries.get(key);
|
|
2305
|
+
}
|
|
2306
|
+
set(key, summary) {
|
|
2307
|
+
this.summaries.set(key, summary);
|
|
2308
|
+
while (this.summaries.size > SUMMARY_CACHE_LIMIT) {
|
|
2309
|
+
const oldest = this.summaries.keys().next().value;
|
|
2310
|
+
if (oldest === undefined)
|
|
2311
|
+
break;
|
|
2312
|
+
this.summaries.delete(oldest);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
clear() {
|
|
2316
|
+
this.summaries.clear();
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
function voiceContextSummaryInput(conversationId, view, config) {
|
|
2320
|
+
const selected = config.voice.contextModel;
|
|
2321
|
+
if (!selected)
|
|
2322
|
+
return;
|
|
2323
|
+
const turns = [];
|
|
2324
|
+
for (const message of view.messages) {
|
|
2325
|
+
if (message.role !== "user" && message.role !== "assistant")
|
|
2326
|
+
continue;
|
|
2327
|
+
if (message.role === "assistant" && message.stopReason === "toolUse")
|
|
2328
|
+
continue;
|
|
2329
|
+
const text = typeof message.content === "string" ? message.content : message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
|
|
2330
|
+
`);
|
|
2331
|
+
if (text.trim())
|
|
2332
|
+
turns.push(`[${message.role}]: ${text.trim()}`);
|
|
2333
|
+
}
|
|
2334
|
+
if (!turns.length)
|
|
2335
|
+
return;
|
|
2336
|
+
const history = turns.join(`
|
|
2337
|
+
|
|
2338
|
+
`);
|
|
2339
|
+
return {
|
|
2340
|
+
history,
|
|
2341
|
+
key: JSON.stringify([
|
|
2342
|
+
conversationId,
|
|
2343
|
+
view.head?.id ?? null,
|
|
2344
|
+
createHash("sha256").update(history).digest("hex"),
|
|
2345
|
+
selected.provider,
|
|
1778
2346
|
selected.modelId,
|
|
1779
2347
|
config.voice.contextReasoning
|
|
1780
2348
|
])
|
|
@@ -1862,6 +2430,42 @@ function voiceTranscriptSince(view, before) {
|
|
|
1862
2430
|
var MAX_REALTIME_SDP_BYTES = 256 * 1024;
|
|
1863
2431
|
|
|
1864
2432
|
// packages/gippity-voice/src/voice/helper-protocol.ts
|
|
2433
|
+
var AUDIO_COUNTERS = [
|
|
2434
|
+
"elapsed_ms",
|
|
2435
|
+
"transitions",
|
|
2436
|
+
"drained_packets",
|
|
2437
|
+
"release_drained_packets",
|
|
2438
|
+
"rejected_packets",
|
|
2439
|
+
"buffering_entries",
|
|
2440
|
+
"tail_flushes",
|
|
2441
|
+
"clock_rebases",
|
|
2442
|
+
"decode_failures",
|
|
2443
|
+
"received_packets",
|
|
2444
|
+
"missing_packets",
|
|
2445
|
+
"decoded_packets",
|
|
2446
|
+
"decoded_packet_samples",
|
|
2447
|
+
"min_decoded_packet_samples",
|
|
2448
|
+
"max_decoded_packet_samples",
|
|
2449
|
+
"late_packets",
|
|
2450
|
+
"duplicate_packets",
|
|
2451
|
+
"reordered_packets",
|
|
2452
|
+
"resyncs",
|
|
2453
|
+
"resync_discarded_packets",
|
|
2454
|
+
"read_gaps_over_40ms",
|
|
2455
|
+
"max_read_gap_ms",
|
|
2456
|
+
"max_playout_lateness_us",
|
|
2457
|
+
"bridge_frames",
|
|
2458
|
+
"bridge_channel_full",
|
|
2459
|
+
"bridge_sends_over_1ms",
|
|
2460
|
+
"max_bridge_send_us"
|
|
2461
|
+
];
|
|
2462
|
+
function validAudioDiagnostics(value) {
|
|
2463
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2464
|
+
return false;
|
|
2465
|
+
const data = value;
|
|
2466
|
+
const counter = (item) => typeof item === "number" && Number.isInteger(item) && item >= 0 && item <= 4294967295;
|
|
2467
|
+
return data["epoch"] !== undefined && validEpoch(data["epoch"]) && typeof data["suppressed"] === "boolean" && AUDIO_COUNTERS.every((key) => counter(data[key])) && (data["first_packet_ms"] === null || counter(data["first_packet_ms"])) && Object.keys(data).every((key) => key === "epoch" || key === "suppressed" || key === "first_packet_ms" || AUDIO_COUNTERS.some((field) => field === key));
|
|
2468
|
+
}
|
|
1865
2469
|
var MAX_PCM_BYTES = 64 * 1024;
|
|
1866
2470
|
var MAX_DATA_MESSAGE_BYTES = 64 * 1024;
|
|
1867
2471
|
var MAX_TEXT_BYTES = 8 * 1024;
|
|
@@ -1938,6 +2542,8 @@ function parseVoiceHelperEvent(value) {
|
|
|
1938
2542
|
return event;
|
|
1939
2543
|
if (event["type"] === "playback_activity")
|
|
1940
2544
|
return { type: "playback_activity" };
|
|
2545
|
+
if (event["type"] === "audio_diagnostics" && validAudioDiagnostics(event["diagnostics"]))
|
|
2546
|
+
return { type: "audio_diagnostics", diagnostics: event["diagnostics"] };
|
|
1941
2547
|
if (event["type"] === "pcm" && validBase64(event["audio"], MAX_PCM_BYTES) && event["sample_rate"] === 24000 && event["num_channels"] === 1 && validEpoch(event["epoch"]))
|
|
1942
2548
|
return event;
|
|
1943
2549
|
if (event["type"] === "error" && boundedString(event["message"], MAX_TEXT_BYTES))
|
|
@@ -2022,7 +2628,7 @@ class VoiceHelperClient {
|
|
|
2022
2628
|
try {
|
|
2023
2629
|
const event = parseVoiceHelperEvent(JSON.parse(line));
|
|
2024
2630
|
if (event.type === "ready") {
|
|
2025
|
-
if (event.version === 2 || event.version === 3 || event.version === 4 || event.version === 5 || event.version === 6) {
|
|
2631
|
+
if (event.version === 2 || event.version === 3 || event.version === 4 || event.version === 5 || event.version === 6 || event.version === 7 || event.version === 8) {
|
|
2026
2632
|
this.helperProtocolVersion = event.version;
|
|
2027
2633
|
ready.resolve();
|
|
2028
2634
|
} else
|
|
@@ -2196,10 +2802,10 @@ class NativeCodexRealtimePeer {
|
|
|
2196
2802
|
}
|
|
2197
2803
|
async start(config) {
|
|
2198
2804
|
await this.helper.start();
|
|
2199
|
-
if (this.helper.protocolVersion !==
|
|
2805
|
+
if (this.helper.protocolVersion !== 8) {
|
|
2200
2806
|
const actualVersion = this.helper.protocolVersion ?? "unknown";
|
|
2201
2807
|
await this.helper.close();
|
|
2202
|
-
throw new Error(`Incompatible Codex voice helper protocol ${actualVersion}; expected
|
|
2808
|
+
throw new Error(`Incompatible Codex voice helper protocol ${actualVersion}; expected 8`);
|
|
2203
2809
|
}
|
|
2204
2810
|
const offer = deferred();
|
|
2205
2811
|
const removeEvent = this.helper.onEvent((event) => {
|
|
@@ -2245,7 +2851,7 @@ class NativeCodexRealtimePeer {
|
|
|
2245
2851
|
}
|
|
2246
2852
|
}
|
|
2247
2853
|
function toPeerEvent(event) {
|
|
2248
|
-
if (event.type === "state" || event.type === "data" || event.type === "error" || event.type === "playback_activity")
|
|
2854
|
+
if (event.type === "state" || event.type === "data" || event.type === "error" || event.type === "playback_activity" || event.type === "audio_diagnostics")
|
|
2249
2855
|
return event;
|
|
2250
2856
|
return;
|
|
2251
2857
|
}
|
|
@@ -2512,6 +3118,7 @@ function escapeXml(value) {
|
|
|
2512
3118
|
}
|
|
2513
3119
|
|
|
2514
3120
|
// packages/gippity-voice/src/voice/turns.ts
|
|
3121
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
2515
3122
|
var MAX_TRANSCRIPT_DELTA_BYTES = 32 * 1024;
|
|
2516
3123
|
|
|
2517
3124
|
class RealtimeTranscriptBuffer {
|
|
@@ -2569,9 +3176,9 @@ class RealtimeTranscriptBuffer {
|
|
|
2569
3176
|
this.reset();
|
|
2570
3177
|
return transcript || undefined;
|
|
2571
3178
|
}
|
|
2572
|
-
takeInterval(currentUser) {
|
|
3179
|
+
takeInterval(input, currentUser) {
|
|
2573
3180
|
const user = currentUser ?? this.active.get("user");
|
|
2574
|
-
const interval = this.entries.filter((entry) => entry !== user);
|
|
3181
|
+
const interval = this.entries.filter((entry) => entry !== user || entry.text.trim() !== input.trim());
|
|
2575
3182
|
const text = this.render(interval);
|
|
2576
3183
|
this.entries = interval.filter((entry) => !entry.final && entry.role === "assistant");
|
|
2577
3184
|
this.active.clear();
|
|
@@ -2632,6 +3239,7 @@ class RealtimeVoiceTurnTracker {
|
|
|
2632
3239
|
delegatedUserFinishes = 0;
|
|
2633
3240
|
delegatedUserTurns = new Set;
|
|
2634
3241
|
delegationIds = new Set;
|
|
3242
|
+
delegatedTurnInputs = new Set;
|
|
2635
3243
|
outstandingDelegations = new Map;
|
|
2636
3244
|
outstandingInputs = new Set;
|
|
2637
3245
|
get hasPendingInput() {
|
|
@@ -2666,12 +3274,17 @@ class RealtimeVoiceTurnTracker {
|
|
|
2666
3274
|
this.pendingUserInputs.push({ input, transcript });
|
|
2667
3275
|
return true;
|
|
2668
3276
|
}
|
|
2669
|
-
delegated(input, delegationId) {
|
|
3277
|
+
delegated(input, delegationId, userTurnId) {
|
|
2670
3278
|
if (this.delegationIds.has(delegationId))
|
|
2671
3279
|
return;
|
|
2672
3280
|
this.delegationIds.add(delegationId);
|
|
2673
3281
|
if (!this.preserveInterval && this.outstandingInputs.has(input))
|
|
2674
3282
|
return;
|
|
3283
|
+
const turnInput = userTurnId ? createHash2("sha256").update(JSON.stringify([userTurnId, input])).digest("hex") : undefined;
|
|
3284
|
+
if (turnInput && this.delegatedTurnInputs.has(turnInput))
|
|
3285
|
+
return;
|
|
3286
|
+
if (turnInput)
|
|
3287
|
+
this.delegatedTurnInputs.add(turnInput);
|
|
2675
3288
|
this.outstandingDelegations.set(delegationId, input);
|
|
2676
3289
|
this.outstandingInputs.add(input);
|
|
2677
3290
|
if (this.activeUserTurn) {
|
|
@@ -2748,11 +3361,12 @@ class RealtimeVoiceTurnTracker {
|
|
|
2748
3361
|
this.delegatedUserFinishes = 0;
|
|
2749
3362
|
this.delegatedUserTurns.clear();
|
|
2750
3363
|
this.delegationIds.clear();
|
|
3364
|
+
this.delegatedTurnInputs.clear();
|
|
2751
3365
|
this.outstandingDelegations.clear();
|
|
2752
3366
|
this.outstandingInputs.clear();
|
|
2753
3367
|
}
|
|
2754
3368
|
finishDelegation(delegation, currentUser) {
|
|
2755
|
-
const interval = this.preserveInterval ? this.transcript.takeInterval(currentUser) : undefined;
|
|
3369
|
+
const interval = this.preserveInterval ? this.transcript.takeInterval(delegation.input, currentUser) : undefined;
|
|
2756
3370
|
const transcriptDelta = interval ? interval.text : currentUser ? this.transcript.takeHistoryBefore(currentUser) : this.transcript.takeFinalized();
|
|
2757
3371
|
return {
|
|
2758
3372
|
input: delegation.input,
|
|
@@ -3012,7 +3626,7 @@ class RealtimePlayback {
|
|
|
3012
3626
|
var SEND_TASK_TOOL = {
|
|
3013
3627
|
type: "function",
|
|
3014
3628
|
name: "send_task",
|
|
3015
|
-
description: "Delegate
|
|
3629
|
+
description: "Delegate a new spoken user request once; never resubmit work progress",
|
|
3016
3630
|
parameters: {
|
|
3017
3631
|
type: "object",
|
|
3018
3632
|
properties: {
|
|
@@ -3025,7 +3639,7 @@ var SEND_TASK_TOOL = {
|
|
|
3025
3639
|
additionalProperties: false
|
|
3026
3640
|
}
|
|
3027
3641
|
};
|
|
3028
|
-
var PUBLIC_REALTIME_INSTRUCTIONS = "This call has tools.
|
|
3642
|
+
var PUBLIC_REALTIME_INSTRUCTIONS = "This call has tools. Delegate without narrating the routing. Other listed tools run directly. Tool availability supersedes earlier statements that voice has no tools. Agent updates describe work already underway, not new user instructions. Speak useful progress and results, then wait for the user";
|
|
3029
3643
|
function record(value) {
|
|
3030
3644
|
return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
3031
3645
|
}
|
|
@@ -3045,6 +3659,7 @@ class PublicRealtimeTurns {
|
|
|
3045
3659
|
activeResponse;
|
|
3046
3660
|
awaitingResponse = false;
|
|
3047
3661
|
speech = false;
|
|
3662
|
+
taskInputAvailable = false;
|
|
3048
3663
|
pendingTools = 0;
|
|
3049
3664
|
pendingWork = new Set;
|
|
3050
3665
|
ending = false;
|
|
@@ -3104,6 +3719,7 @@ class PublicRealtimeTurns {
|
|
|
3104
3719
|
this.onFailure(new Error(text2(error?.["message"], 1000) ?? "Realtime call failed. Stop and start voice to retry."));
|
|
3105
3720
|
} else if (type === "input_audio_buffer.speech_started") {
|
|
3106
3721
|
this.speech = true;
|
|
3722
|
+
this.taskInputAvailable = true;
|
|
3107
3723
|
this.tracker.inputStarted();
|
|
3108
3724
|
this.awaitingResponse = true;
|
|
3109
3725
|
this.continuation = false;
|
|
@@ -3117,8 +3733,8 @@ class PublicRealtimeTurns {
|
|
|
3117
3733
|
} else if (type === "conversation.item.input_audio_transcription.completed") {
|
|
3118
3734
|
const transcript = text2(event["transcript"]);
|
|
3119
3735
|
if (transcript) {
|
|
3120
|
-
|
|
3121
|
-
|
|
3736
|
+
this.tracker.userFinished(transcript);
|
|
3737
|
+
this.callbacks.onUserTranscript(transcript);
|
|
3122
3738
|
}
|
|
3123
3739
|
} else if (type === "response.created") {
|
|
3124
3740
|
const response = record(event["response"]);
|
|
@@ -3162,6 +3778,8 @@ class PublicRealtimeTurns {
|
|
|
3162
3778
|
}
|
|
3163
3779
|
if (!interrupted && response?.["status"] === "completed" && Array.isArray(response["output"])) {
|
|
3164
3780
|
this.completingResponse = true;
|
|
3781
|
+
if (!response["output"].some((item) => record(item)?.["type"] === "function_call"))
|
|
3782
|
+
this.taskInputAvailable = false;
|
|
3165
3783
|
for (const item of response["output"]) {
|
|
3166
3784
|
const call = record(item);
|
|
3167
3785
|
if (call?.["type"] === "function_call") {
|
|
@@ -3198,6 +3816,7 @@ class PublicRealtimeTurns {
|
|
|
3198
3816
|
this.calls.add(id);
|
|
3199
3817
|
this.pendingTools++;
|
|
3200
3818
|
let output;
|
|
3819
|
+
let continueResponse = true;
|
|
3201
3820
|
try {
|
|
3202
3821
|
const name = text2(call["name"], 64);
|
|
3203
3822
|
const raw = text2(call["arguments"], 32 * 1024);
|
|
@@ -3218,13 +3837,19 @@ class PublicRealtimeTurns {
|
|
|
3218
3837
|
const request = text2(args["request"]);
|
|
3219
3838
|
if (!request || Object.keys(args).some((key) => key !== "request"))
|
|
3220
3839
|
throw new Error("send_task requires only a nonempty request");
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3225
|
-
|
|
3840
|
+
if (!this.taskInputAvailable) {
|
|
3841
|
+
output = {
|
|
3842
|
+
accepted: false,
|
|
3843
|
+
reason: "No new user speech. Wait for the work already submitted; do not retry."
|
|
3844
|
+
};
|
|
3845
|
+
continueResponse = false;
|
|
3846
|
+
} else {
|
|
3847
|
+
this.taskInputAvailable = false;
|
|
3848
|
+
const delegated = this.tracker.delegated(request, id);
|
|
3849
|
+
if (delegated)
|
|
3850
|
+
this.callbacks.onTurn(delegated.turn);
|
|
3851
|
+
output = { accepted: Boolean(delegated), task_id: id };
|
|
3226
3852
|
}
|
|
3227
|
-
output = { accepted: Boolean(delegated), task_id: id };
|
|
3228
3853
|
} else {
|
|
3229
3854
|
if (!this.access)
|
|
3230
3855
|
throw new Error("Voice tool is unavailable; restart the call");
|
|
@@ -3253,7 +3878,8 @@ class PublicRealtimeTurns {
|
|
|
3253
3878
|
output: JSON.stringify(output)
|
|
3254
3879
|
}
|
|
3255
3880
|
});
|
|
3256
|
-
|
|
3881
|
+
if (continueResponse)
|
|
3882
|
+
this.continuation = true;
|
|
3257
3883
|
this.schedule();
|
|
3258
3884
|
}
|
|
3259
3885
|
send(event) {
|
|
@@ -3437,7 +4063,7 @@ class ConversationSetup {
|
|
|
3437
4063
|
import { randomUUID } from "node:crypto";
|
|
3438
4064
|
|
|
3439
4065
|
// packages/gippity-voice/src/voice/conversation/wire.ts
|
|
3440
|
-
import { createHash as
|
|
4066
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
3441
4067
|
function realtimeEventIdentity(value) {
|
|
3442
4068
|
if (!value || typeof value !== "object")
|
|
3443
4069
|
return;
|
|
@@ -3469,7 +4095,7 @@ function realtimeEventDetails(callId, event, text, accepted) {
|
|
|
3469
4095
|
...typeof offset === "number" && Number.isFinite(offset) ? { offsetMs: offset } : {},
|
|
3470
4096
|
...typeof start === "number" && Number.isFinite(start) ? { startMs: start } : {},
|
|
3471
4097
|
...typeof end === "number" && Number.isFinite(end) ? { endMs: end } : {},
|
|
3472
|
-
...transcript ? { textHash:
|
|
4098
|
+
...transcript ? { textHash: createHash3("sha256").update(transcript).digest("hex") } : {},
|
|
3473
4099
|
accepted
|
|
3474
4100
|
};
|
|
3475
4101
|
}
|
|
@@ -3621,7 +4247,7 @@ class ConversationTurns {
|
|
|
3621
4247
|
this.onFailure(new Error("Codex voice delegation was empty"));
|
|
3622
4248
|
return;
|
|
3623
4249
|
}
|
|
3624
|
-
const delegated = this.turnTracker.delegated(input, delegationId);
|
|
4250
|
+
const delegated = this.turnTracker.delegated(input, delegationId, typeof record["user_bidi_turn_id"] === "string" ? record["user_bidi_turn_id"] : undefined);
|
|
3625
4251
|
this.callbacks.onEvent?.(realtimeEventDetails(this.callId, event, input, Boolean(delegated)));
|
|
3626
4252
|
if (!delegated)
|
|
3627
4253
|
return;
|
|
@@ -3894,11 +4520,15 @@ class CodexRealtimeConversation {
|
|
|
3894
4520
|
this.turns.handoff.clear();
|
|
3895
4521
|
this.callbacks.onEndCall?.();
|
|
3896
4522
|
}
|
|
4523
|
+
get playbackSealed() {
|
|
4524
|
+
return this.peer.playbackSealed === true;
|
|
4525
|
+
}
|
|
3897
4526
|
get isEndingCall() {
|
|
3898
4527
|
return this.ending;
|
|
3899
4528
|
}
|
|
3900
|
-
waitForFinalPlayback() {
|
|
3901
|
-
|
|
4529
|
+
async waitForFinalPlayback() {
|
|
4530
|
+
await this.waitForPlaybackEnd(this.closing.signal, this.endingOutput);
|
|
4531
|
+
await this.peer.finishPlayback?.(this.closing.signal);
|
|
3902
4532
|
}
|
|
3903
4533
|
waitForPlaybackEnd(signal, minimumOutputs = 0) {
|
|
3904
4534
|
signal.throwIfAborted();
|
|
@@ -3986,6 +4616,8 @@ class CodexRealtimeConversation {
|
|
|
3986
4616
|
this.fail(error);
|
|
3987
4617
|
return;
|
|
3988
4618
|
}
|
|
4619
|
+
if (event.type === "audio_diagnostics")
|
|
4620
|
+
this.callbacks.onAudioDiagnostics?.(event.diagnostics);
|
|
3989
4621
|
if (event.type === "playback_activity") {
|
|
3990
4622
|
if (this.turns instanceof PublicRealtimeTurns)
|
|
3991
4623
|
this.turns.audioActivity();
|
|
@@ -4393,227 +5025,8 @@ function ownVoiceGrant(grant) {
|
|
|
4393
5025
|
};
|
|
4394
5026
|
}
|
|
4395
5027
|
|
|
4396
|
-
// packages/gippity-voice/src/voice/handoff-
|
|
4397
|
-
class
|
|
4398
|
-
pending = new Map;
|
|
4399
|
-
stages = new Map;
|
|
4400
|
-
stageWaiters = new Map;
|
|
4401
|
-
sequence = 0;
|
|
4402
|
-
failure;
|
|
4403
|
-
removeMessage;
|
|
4404
|
-
removeClose;
|
|
4405
|
-
channel;
|
|
4406
|
-
handlers;
|
|
4407
|
-
constructor(channel, handlers) {
|
|
4408
|
-
this.channel = channel;
|
|
4409
|
-
this.handlers = handlers;
|
|
4410
|
-
this.removeMessage = channel.onMessage((message) => {
|
|
4411
|
-
try {
|
|
4412
|
-
this.receive(message);
|
|
4413
|
-
} catch (error) {
|
|
4414
|
-
this.fail(asError(error));
|
|
4415
|
-
}
|
|
4416
|
-
});
|
|
4417
|
-
this.removeClose = channel.onClose((error) => this.finish(error));
|
|
4418
|
-
if (this.failure) {
|
|
4419
|
-
this.removeMessage();
|
|
4420
|
-
this.removeClose();
|
|
4421
|
-
}
|
|
4422
|
-
}
|
|
4423
|
-
get closed() {
|
|
4424
|
-
return this.failure !== undefined;
|
|
4425
|
-
}
|
|
4426
|
-
request(method, value) {
|
|
4427
|
-
if (this.failure)
|
|
4428
|
-
return Promise.reject(this.failure);
|
|
4429
|
-
if (this.pending.size >= 32)
|
|
4430
|
-
return Promise.reject(new Error("Too many pending voice controls"));
|
|
4431
|
-
const id = ++this.sequence;
|
|
4432
|
-
return new Promise((resolve, reject) => {
|
|
4433
|
-
const timer = setTimeout(() => {
|
|
4434
|
-
this.pending.delete(id);
|
|
4435
|
-
const error = new Error("Voice control did not respond");
|
|
4436
|
-
reject(error);
|
|
4437
|
-
this.fail(error);
|
|
4438
|
-
}, method === "session.start" ? 120000 : 30000);
|
|
4439
|
-
this.pending.set(id, { resolve, reject, timer });
|
|
4440
|
-
try {
|
|
4441
|
-
this.send({ type: "request", id, method, value });
|
|
4442
|
-
} catch (error) {
|
|
4443
|
-
this.fail(asError(error));
|
|
4444
|
-
}
|
|
4445
|
-
});
|
|
4446
|
-
}
|
|
4447
|
-
notify(message) {
|
|
4448
|
-
this.send(message);
|
|
4449
|
-
}
|
|
4450
|
-
stage(stage, value) {
|
|
4451
|
-
this.send({ type: "stage", stage, value });
|
|
4452
|
-
}
|
|
4453
|
-
waitFor(stage) {
|
|
4454
|
-
if (this.failure)
|
|
4455
|
-
return Promise.reject(this.failure);
|
|
4456
|
-
if (this.stages.has(stage))
|
|
4457
|
-
return Promise.resolve(this.stages.get(stage));
|
|
4458
|
-
if (this.stageWaiters.has(stage))
|
|
4459
|
-
return Promise.reject(new Error("Voice transfer stage already awaited"));
|
|
4460
|
-
return new Promise((resolve, reject) => {
|
|
4461
|
-
const timer = setTimeout(() => {
|
|
4462
|
-
this.stageWaiters.delete(stage);
|
|
4463
|
-
const error = new Error("Voice transfer did not finish preparing");
|
|
4464
|
-
reject(error);
|
|
4465
|
-
this.fail(error);
|
|
4466
|
-
}, 120000);
|
|
4467
|
-
this.stageWaiters.set(stage, { resolve, reject, timer });
|
|
4468
|
-
});
|
|
4469
|
-
}
|
|
4470
|
-
close() {
|
|
4471
|
-
this.fail(new Error("Voice connection closed"));
|
|
4472
|
-
}
|
|
4473
|
-
fail(error) {
|
|
4474
|
-
if (this.failure)
|
|
4475
|
-
return;
|
|
4476
|
-
try {
|
|
4477
|
-
this.channel.send({
|
|
4478
|
-
type: "failure",
|
|
4479
|
-
message: error.message.slice(0, 4000)
|
|
4480
|
-
});
|
|
4481
|
-
} catch {}
|
|
4482
|
-
this.finish(error);
|
|
4483
|
-
this.channel.close();
|
|
4484
|
-
}
|
|
4485
|
-
send(message) {
|
|
4486
|
-
if (this.failure)
|
|
4487
|
-
throw this.failure;
|
|
4488
|
-
try {
|
|
4489
|
-
this.channel.send(message);
|
|
4490
|
-
} catch (error) {
|
|
4491
|
-
this.fail(asError(error));
|
|
4492
|
-
throw error;
|
|
4493
|
-
}
|
|
4494
|
-
}
|
|
4495
|
-
finish(error) {
|
|
4496
|
-
if (this.failure)
|
|
4497
|
-
return;
|
|
4498
|
-
this.failure = error;
|
|
4499
|
-
this.removeMessage?.();
|
|
4500
|
-
this.removeClose?.();
|
|
4501
|
-
for (const pending of [
|
|
4502
|
-
...this.pending.values(),
|
|
4503
|
-
...this.stageWaiters.values()
|
|
4504
|
-
]) {
|
|
4505
|
-
clearTimeout(pending.timer);
|
|
4506
|
-
pending.reject(error);
|
|
4507
|
-
}
|
|
4508
|
-
this.pending.clear();
|
|
4509
|
-
this.stageWaiters.clear();
|
|
4510
|
-
this.handlers.closed(error);
|
|
4511
|
-
}
|
|
4512
|
-
receive(value) {
|
|
4513
|
-
if (this.failure)
|
|
4514
|
-
return;
|
|
4515
|
-
if (!isRecord(value))
|
|
4516
|
-
throw new Error("Invalid voice transfer frame");
|
|
4517
|
-
if (value["type"] === "failure" && typeof value["message"] === "string") {
|
|
4518
|
-
this.finish(new Error(value["message"].slice(0, 4000)));
|
|
4519
|
-
this.channel.close();
|
|
4520
|
-
return;
|
|
4521
|
-
}
|
|
4522
|
-
if (value["type"] === "stage" && isStage(value["stage"])) {
|
|
4523
|
-
this.stages.set(value["stage"], value["value"]);
|
|
4524
|
-
const waiter = this.stageWaiters.get(value["stage"]);
|
|
4525
|
-
if (waiter) {
|
|
4526
|
-
clearTimeout(waiter.timer);
|
|
4527
|
-
this.stageWaiters.delete(value["stage"]);
|
|
4528
|
-
waiter.resolve(value["value"]);
|
|
4529
|
-
}
|
|
4530
|
-
return;
|
|
4531
|
-
}
|
|
4532
|
-
if ((value["type"] === "request" || value["type"] === "reply") && typeof value["id"] === "number" && Number.isSafeInteger(value["id"]) && value["id"] > 0) {
|
|
4533
|
-
const id = value["id"];
|
|
4534
|
-
if (value["type"] === "reply") {
|
|
4535
|
-
if (typeof value["ok"] !== "boolean" || !value["ok"] && typeof value["error"] !== "string")
|
|
4536
|
-
throw new Error("Invalid voice control reply");
|
|
4537
|
-
const pending = this.pending.get(id);
|
|
4538
|
-
if (!pending)
|
|
4539
|
-
return;
|
|
4540
|
-
clearTimeout(pending.timer);
|
|
4541
|
-
this.pending.delete(id);
|
|
4542
|
-
if (value["ok"])
|
|
4543
|
-
pending.resolve(value["value"]);
|
|
4544
|
-
else
|
|
4545
|
-
pending.reject(new Error(String(value["error"])));
|
|
4546
|
-
return;
|
|
4547
|
-
}
|
|
4548
|
-
const method = value["method"];
|
|
4549
|
-
if (!isRequestMethod(method))
|
|
4550
|
-
throw new Error("Invalid voice control request");
|
|
4551
|
-
this.handlers.request(method, value["value"]).then((result) => {
|
|
4552
|
-
if (!this.failure)
|
|
4553
|
-
this.send({ type: "reply", id, ok: true, value: result });
|
|
4554
|
-
}, (error) => {
|
|
4555
|
-
if (!this.failure)
|
|
4556
|
-
this.send({
|
|
4557
|
-
type: "reply",
|
|
4558
|
-
id,
|
|
4559
|
-
ok: false,
|
|
4560
|
-
error: asError(error).message
|
|
4561
|
-
});
|
|
4562
|
-
}).catch((error) => this.fail(asError(error)));
|
|
4563
|
-
return;
|
|
4564
|
-
}
|
|
4565
|
-
const generation = value["generation"];
|
|
4566
|
-
const validGeneration = typeof generation === "number" && Number.isSafeInteger(generation) && generation > 0;
|
|
4567
|
-
if (value["type"] === "peer.command" && typeof value["command"] === "string" && validGeneration) {
|
|
4568
|
-
this.handlers.notification({
|
|
4569
|
-
type: "peer.command",
|
|
4570
|
-
generation,
|
|
4571
|
-
command: value["command"],
|
|
4572
|
-
value: value["value"]
|
|
4573
|
-
});
|
|
4574
|
-
return;
|
|
4575
|
-
}
|
|
4576
|
-
if (value["type"] === "peer.event" && validGeneration) {
|
|
4577
|
-
this.handlers.notification({
|
|
4578
|
-
type: "peer.event",
|
|
4579
|
-
generation,
|
|
4580
|
-
event: value["event"]
|
|
4581
|
-
});
|
|
4582
|
-
return;
|
|
4583
|
-
}
|
|
4584
|
-
if (value["type"] === "session.event" && typeof value["event"] === "string" && value["event"].length <= 64) {
|
|
4585
|
-
this.handlers.notification({
|
|
4586
|
-
type: "session.event",
|
|
4587
|
-
event: value["event"],
|
|
4588
|
-
data: value["data"]
|
|
4589
|
-
});
|
|
4590
|
-
return;
|
|
4591
|
-
}
|
|
4592
|
-
if (value["type"] === "session.mute" && typeof value["muted"] === "boolean") {
|
|
4593
|
-
this.handlers.notification({
|
|
4594
|
-
type: "session.mute",
|
|
4595
|
-
muted: value["muted"]
|
|
4596
|
-
});
|
|
4597
|
-
return;
|
|
4598
|
-
}
|
|
4599
|
-
throw new Error("Invalid voice transfer frame");
|
|
4600
|
-
}
|
|
4601
|
-
}
|
|
4602
|
-
function isRecord(value) {
|
|
4603
|
-
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
4604
|
-
}
|
|
4605
|
-
function asError(error) {
|
|
4606
|
-
return error instanceof Error ? error : new Error(String(error));
|
|
4607
|
-
}
|
|
4608
|
-
function isStage(value) {
|
|
4609
|
-
return value === "prepared" || value === "activate" || value === "active";
|
|
4610
|
-
}
|
|
4611
|
-
function isRequestMethod(value) {
|
|
4612
|
-
return value === "lan.verify" || value === "session.stop" || value === "session.start" || value === "peer.start" || value === "peer.close" || value === "session.send" || value === "session.rpc";
|
|
4613
|
-
}
|
|
4614
|
-
|
|
4615
|
-
// packages/gippity-voice/src/voice/handoff-peer.ts
|
|
4616
|
-
class HandoffAudioHost {
|
|
5028
|
+
// packages/gippity-voice/src/voice/handoff-peer.ts
|
|
5029
|
+
class HandoffAudioHost {
|
|
4617
5030
|
sequence = 0;
|
|
4618
5031
|
current;
|
|
4619
5032
|
lastPeer;
|
|
@@ -4663,12 +5076,18 @@ class HandoffAudioHost {
|
|
|
4663
5076
|
this.link.notify({ type: "peer.event", generation, event });
|
|
4664
5077
|
});
|
|
4665
5078
|
const removeExit = peer.onExit((error) => this.link.fail(error));
|
|
4666
|
-
this.current = {
|
|
5079
|
+
this.current = {
|
|
5080
|
+
generation,
|
|
5081
|
+
peer,
|
|
5082
|
+
abort: new AbortController,
|
|
5083
|
+
removeEvent,
|
|
5084
|
+
removeExit
|
|
5085
|
+
};
|
|
4667
5086
|
this.captured.transferred(peer, this.controls);
|
|
4668
5087
|
const sdp = await this.captured.start(peer);
|
|
4669
5088
|
if (this.closed || this.current?.generation !== generation)
|
|
4670
5089
|
throw new Error("Voice transfer cancelled");
|
|
4671
|
-
return { generation, sdp };
|
|
5090
|
+
return { generation, sdp, finishPlayback: true };
|
|
4672
5091
|
} finally {
|
|
4673
5092
|
this.starting = false;
|
|
4674
5093
|
}
|
|
@@ -4680,6 +5099,20 @@ class HandoffAudioHost {
|
|
|
4680
5099
|
return;
|
|
4681
5100
|
await this.closeCurrent();
|
|
4682
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
|
+
}
|
|
4683
5116
|
command(message) {
|
|
4684
5117
|
const current = this.current;
|
|
4685
5118
|
if (!current || message.generation !== current.generation)
|
|
@@ -4700,14 +5133,18 @@ class HandoffAudioHost {
|
|
|
4700
5133
|
if (this.closed)
|
|
4701
5134
|
return;
|
|
4702
5135
|
this.closed = true;
|
|
4703
|
-
|
|
4704
|
-
|
|
5136
|
+
try {
|
|
5137
|
+
await this.closeCurrent();
|
|
5138
|
+
} finally {
|
|
5139
|
+
await this.captured.finished(this.lastPeer, error);
|
|
5140
|
+
}
|
|
4705
5141
|
}
|
|
4706
5142
|
async closeCurrent() {
|
|
4707
5143
|
const current = this.current;
|
|
4708
5144
|
this.current = undefined;
|
|
4709
5145
|
if (!current)
|
|
4710
5146
|
return;
|
|
5147
|
+
current.abort.abort();
|
|
4711
5148
|
current.removeEvent();
|
|
4712
5149
|
current.removeExit();
|
|
4713
5150
|
await current.peer.close();
|
|
@@ -4719,6 +5156,8 @@ class HandoffRemotePeer {
|
|
|
4719
5156
|
listeners = new Set;
|
|
4720
5157
|
exitListeners = new Set;
|
|
4721
5158
|
generation;
|
|
5159
|
+
sealed = false;
|
|
5160
|
+
canFinishPlayback = false;
|
|
4722
5161
|
starting;
|
|
4723
5162
|
closed = false;
|
|
4724
5163
|
link;
|
|
@@ -4744,6 +5183,7 @@ class HandoffRemotePeer {
|
|
|
4744
5183
|
if (!isRecord(result) || typeof result["generation"] !== "number" || !Number.isSafeInteger(result["generation"]) || result["generation"] <= 0 || !validSdp(result["sdp"]))
|
|
4745
5184
|
throw new Error("Source audio did not return a valid voice offer");
|
|
4746
5185
|
this.generation = result["generation"];
|
|
5186
|
+
this.canFinishPlayback = result["finishPlayback"] === true;
|
|
4747
5187
|
return result["sdp"];
|
|
4748
5188
|
}
|
|
4749
5189
|
applyAnswer(sdp) {
|
|
@@ -4758,6 +5198,24 @@ class HandoffRemotePeer {
|
|
|
4758
5198
|
setSpeakerSuppressed(suppressed) {
|
|
4759
5199
|
this.command("suppress", suppressed);
|
|
4760
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
|
+
}
|
|
4761
5219
|
command(command, value) {
|
|
4762
5220
|
if (this.closed)
|
|
4763
5221
|
return;
|
|
@@ -4809,6 +5267,11 @@ function validSdp(value) {
|
|
|
4809
5267
|
}
|
|
4810
5268
|
function readPeerEvent(value) {
|
|
4811
5269
|
if (isRecord(value)) {
|
|
5270
|
+
if (value["type"] === "audio_diagnostics") {
|
|
5271
|
+
const event = parseVoiceHelperEvent(value);
|
|
5272
|
+
if (event.type === "audio_diagnostics")
|
|
5273
|
+
return event;
|
|
5274
|
+
}
|
|
4812
5275
|
if (value["type"] === "playback_activity")
|
|
4813
5276
|
return { type: "playback_activity" };
|
|
4814
5277
|
if (value["type"] === "state" && typeof value["state"] === "string" && value["state"].length <= 128)
|
|
@@ -4823,27 +5286,12 @@ function readPeerEvent(value) {
|
|
|
4823
5286
|
|
|
4824
5287
|
// packages/gippity-voice/src/voice/lan/takeover.ts
|
|
4825
5288
|
import { randomUUID as randomUUID2, X509Certificate } from "node:crypto";
|
|
5289
|
+
|
|
5290
|
+
// internal/voice/lan-listener-proof.ts
|
|
4826
5291
|
import { get } from "node:https";
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
offer: {
|
|
4831
|
-
certificate: new X509Certificate(certificate.cert).fingerprint256,
|
|
4832
|
-
token: randomUUID2()
|
|
4833
|
-
}
|
|
4834
|
-
};
|
|
4835
|
-
}
|
|
4836
|
-
function decodeLanTakeoverOffer(value) {
|
|
4837
|
-
if (!isRecord(value) || typeof value["certificate"] !== "string" || typeof value["token"] !== "string" || !/^[a-f0-9-]{36}$/.test(value["token"]))
|
|
4838
|
-
throw new Error("The selected voice provider does not support same-address LAN takeover; the source remains active");
|
|
4839
|
-
return { certificate: value["certificate"], token: value["token"] };
|
|
4840
|
-
}
|
|
4841
|
-
function assertLanTakeoverIdentity(source, target) {
|
|
4842
|
-
if (source.certificate !== target.certificate)
|
|
4843
|
-
throw new Error("LAN certificates differ; same-address takeover cannot preserve browser trust. The source remains active");
|
|
4844
|
-
}
|
|
4845
|
-
async function verifyLanTakeoverListener(certificate, value, signal) {
|
|
4846
|
-
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"]))
|
|
4847
5295
|
throw new Error("Invalid LAN listener proof");
|
|
4848
5296
|
const { port, token } = value;
|
|
4849
5297
|
await new Promise((resolve, reject) => {
|
|
@@ -4853,8 +5301,9 @@ async function verifyLanTakeoverListener(certificate, value, signal) {
|
|
|
4853
5301
|
path: `/api/takeover-proof?token=${token}`,
|
|
4854
5302
|
ca: certificate,
|
|
4855
5303
|
rejectUnauthorized: true,
|
|
5304
|
+
checkServerIdentity: (host, peer) => checkServerIdentity(host, peer) ?? (peer.fingerprint256 === fingerprint ? undefined : new Error("LAN listener certificate does not match the offer")),
|
|
4856
5305
|
agent: false,
|
|
4857
|
-
signal
|
|
5306
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(5000)])
|
|
4858
5307
|
}, (response) => {
|
|
4859
5308
|
let body = "";
|
|
4860
5309
|
response.setEncoding("utf8");
|
|
@@ -4864,13 +5313,54 @@ async function verifyLanTakeoverListener(certificate, value, signal) {
|
|
|
4864
5313
|
request.destroy(new Error("Invalid LAN listener proof"));
|
|
4865
5314
|
});
|
|
4866
5315
|
response.on("error", reject);
|
|
4867
|
-
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")));
|
|
4868
5317
|
});
|
|
4869
5318
|
request.setTimeout(5000, () => request.destroy(new Error("Same-address LAN takeover requires a reachable listener on this machine")));
|
|
4870
5319
|
request.on("error", reject);
|
|
4871
5320
|
});
|
|
4872
5321
|
}
|
|
4873
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
|
+
|
|
4874
5364
|
class LanTakeoverArrival {
|
|
4875
5365
|
pending;
|
|
4876
5366
|
constructor(token, value) {
|
|
@@ -4912,6 +5402,8 @@ function startVoiceDeparture(options) {
|
|
|
4912
5402
|
return audio.start();
|
|
4913
5403
|
if (method === "peer.close")
|
|
4914
5404
|
return audio.closePeer(value);
|
|
5405
|
+
if (method === "peer.finish")
|
|
5406
|
+
return audio.finishPlayback(value);
|
|
4915
5407
|
throw new Error("Voice control was sent to the audio host instead of the selected session");
|
|
4916
5408
|
},
|
|
4917
5409
|
notification(message) {
|
|
@@ -4972,6 +5464,25 @@ function startVoiceDeparture(options) {
|
|
|
4972
5464
|
link.waitFor("prepared"),
|
|
4973
5465
|
options.waitForSettled(abort.signal)
|
|
4974
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");
|
|
4975
5486
|
if (options.lanTakeover) {
|
|
4976
5487
|
const offered = isRecord(prepared) ? prepared["lanTakeover"] : undefined;
|
|
4977
5488
|
const offer = offered === undefined ? undefined : decodeLanTakeoverOffer(offered);
|
|
@@ -5023,7 +5534,244 @@ function startVoiceDeparture(options) {
|
|
|
5023
5534
|
};
|
|
5024
5535
|
}
|
|
5025
5536
|
|
|
5026
|
-
// packages/gippity-voice/src/voice/lan/
|
|
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
|
|
5027
5775
|
var MAX_REMOTE_VALUE_BYTES = 256 * 1024;
|
|
5028
5776
|
var MAX_REMOTE_STRING_BYTES = 32 * 1024;
|
|
5029
5777
|
var MAX_REMOTE_ARRAY_ITEMS = 256;
|
|
@@ -5174,11 +5922,11 @@ class GippityRemoteApps {
|
|
|
5174
5922
|
}
|
|
5175
5923
|
|
|
5176
5924
|
// packages/gippity-voice/src/voice/lan/server.ts
|
|
5177
|
-
import { randomUUID as
|
|
5925
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
5178
5926
|
import { createServer } from "node:https";
|
|
5179
|
-
import { WebSocket as
|
|
5927
|
+
import { WebSocket as WebSocket6, WebSocketServer } from "ws";
|
|
5180
5928
|
|
|
5181
|
-
//
|
|
5929
|
+
// internal/voice/lan-activity.ts
|
|
5182
5930
|
var MAX_ACTIVITY_BYTES = 16 * 1024;
|
|
5183
5931
|
|
|
5184
5932
|
class LanVoiceActivity {
|
|
@@ -5198,30 +5946,116 @@ class LanVoiceActivity {
|
|
|
5198
5946
|
this.state = { type: "activity", state: "working" };
|
|
5199
5947
|
this.publish(this.state);
|
|
5200
5948
|
}
|
|
5201
|
-
waiting(text) {
|
|
5202
|
-
const bounded = text ? truncateUtf82(text.trim(), MAX_ACTIVITY_BYTES) : "";
|
|
5203
|
-
this.state = bounded ? { type: "activity", state: "waiting", text: bounded } : { type: "activity", state: "waiting" };
|
|
5204
|
-
this.publish(this.state);
|
|
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"));
|
|
6023
|
+
}
|
|
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"));
|
|
5205
6044
|
}
|
|
5206
|
-
|
|
5207
|
-
|
|
5208
|
-
|
|
5209
|
-
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");
|
|
5210
6048
|
}
|
|
5211
6049
|
}
|
|
5212
|
-
function
|
|
5213
|
-
|
|
5214
|
-
|
|
5215
|
-
|
|
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;
|
|
5216
6056
|
}
|
|
5217
|
-
function
|
|
5218
|
-
|
|
5219
|
-
if (buffer.byteLength <= maxBytes)
|
|
5220
|
-
return value;
|
|
5221
|
-
let end = maxBytes - Buffer.byteLength("…");
|
|
5222
|
-
while (end > 0 && (buffer[end] & 192) === 128)
|
|
5223
|
-
end -= 1;
|
|
5224
|
-
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;
|
|
5225
6059
|
}
|
|
5226
6060
|
|
|
5227
6061
|
// packages/gippity-voice/src/voice/lan/app-assets.ts
|
|
@@ -5274,15 +6108,21 @@ function createLanVoiceWebManifest() {
|
|
|
5274
6108
|
}
|
|
5275
6109
|
|
|
5276
6110
|
// packages/gippity-voice/src/voice/lan/browser-clients.ts
|
|
5277
|
-
import { WebSocket as
|
|
6111
|
+
import { WebSocket as WebSocket5 } from "ws";
|
|
5278
6112
|
|
|
5279
6113
|
// packages/gippity-voice/src/voice/lan/browser-connections.ts
|
|
5280
6114
|
import { WebSocket as WebSocket2 } from "ws";
|
|
5281
6115
|
var MAX_SOCKET_AUDIO_BACKLOG = 24000 * 2;
|
|
6116
|
+
var AUDIO_REPORT_INTERVAL_MS = 5000;
|
|
5282
6117
|
|
|
5283
6118
|
class LanVoiceBrowserConnections {
|
|
5284
6119
|
eventResponses = new Map;
|
|
5285
6120
|
audioSockets = new Map;
|
|
6121
|
+
audioReports = new WeakMap;
|
|
6122
|
+
onAudioDiagnostics;
|
|
6123
|
+
constructor(onAudioDiagnostics) {
|
|
6124
|
+
this.onAudioDiagnostics = onAudioDiagnostics;
|
|
6125
|
+
}
|
|
5286
6126
|
connectEvents(clientId, response, closed) {
|
|
5287
6127
|
if (closed) {
|
|
5288
6128
|
response.end();
|
|
@@ -5303,12 +6143,15 @@ class LanVoiceBrowserConnections {
|
|
|
5303
6143
|
}
|
|
5304
6144
|
const previous = this.audioSockets.get(clientId);
|
|
5305
6145
|
this.audioSockets.set(clientId, socket);
|
|
5306
|
-
if (previous)
|
|
6146
|
+
if (previous) {
|
|
6147
|
+
this.finishAudioReport(previous, "replaced");
|
|
5307
6148
|
callbacks.onReplaced(previous);
|
|
6149
|
+
}
|
|
5308
6150
|
previous?.close(4001, "replaced");
|
|
5309
6151
|
socket.send(JSON.stringify({ type: "connected" }));
|
|
5310
6152
|
socket.on("message", callbacks.onMessage);
|
|
5311
6153
|
socket.once("close", () => {
|
|
6154
|
+
this.finishAudioReport(socket, "closed");
|
|
5312
6155
|
if (this.audioSockets.get(clientId) === socket)
|
|
5313
6156
|
this.audioSockets.delete(clientId);
|
|
5314
6157
|
callbacks.onClose();
|
|
@@ -5335,8 +6178,69 @@ class LanVoiceBrowserConnections {
|
|
|
5335
6178
|
this.sendControl(clientId, value);
|
|
5336
6179
|
}
|
|
5337
6180
|
sendAudio(socket, pcm) {
|
|
5338
|
-
if (socket.readyState
|
|
6181
|
+
if (socket.readyState !== WebSocket2.OPEN)
|
|
6182
|
+
return;
|
|
6183
|
+
const now = performance.now();
|
|
6184
|
+
const report = this.audioReports.get(socket) ?? {
|
|
6185
|
+
startedAt: now,
|
|
6186
|
+
lastArrivalAt: now,
|
|
6187
|
+
sentFrames: 0,
|
|
6188
|
+
sentBytes: 0,
|
|
6189
|
+
droppedFrames: 0,
|
|
6190
|
+
droppedBytes: 0,
|
|
6191
|
+
maxSocketBacklogBytes: 0,
|
|
6192
|
+
sourcePcmArrivalGapMaxMs: 0
|
|
6193
|
+
};
|
|
6194
|
+
this.audioReports.set(socket, report);
|
|
6195
|
+
report.sourcePcmArrivalGapMaxMs = Math.max(report.sourcePcmArrivalGapMaxMs, now - report.lastArrivalAt);
|
|
6196
|
+
report.lastArrivalAt = now;
|
|
6197
|
+
report.maxSocketBacklogBytes = Math.max(report.maxSocketBacklogBytes, socket.bufferedAmount);
|
|
6198
|
+
if (socket.bufferedAmount < MAX_SOCKET_AUDIO_BACKLOG) {
|
|
5339
6199
|
socket.send(pcm);
|
|
6200
|
+
report.maxSocketBacklogBytes = Math.max(report.maxSocketBacklogBytes, socket.bufferedAmount);
|
|
6201
|
+
report.sentFrames++;
|
|
6202
|
+
report.sentBytes += pcm.byteLength;
|
|
6203
|
+
} else {
|
|
6204
|
+
report.droppedFrames++;
|
|
6205
|
+
report.droppedBytes += pcm.byteLength;
|
|
6206
|
+
}
|
|
6207
|
+
if (!report.timer) {
|
|
6208
|
+
report.startedAt = now;
|
|
6209
|
+
report.timer = setTimeout(() => this.flushAudioReport(socket, "interval"), AUDIO_REPORT_INTERVAL_MS);
|
|
6210
|
+
report.timer.unref();
|
|
6211
|
+
}
|
|
6212
|
+
}
|
|
6213
|
+
flushAudioReport(socket, reason) {
|
|
6214
|
+
const report = this.audioReports.get(socket);
|
|
6215
|
+
if (!report)
|
|
6216
|
+
return;
|
|
6217
|
+
clearTimeout(report.timer);
|
|
6218
|
+
report.timer = undefined;
|
|
6219
|
+
if (report.sentFrames + report.droppedFrames === 0)
|
|
6220
|
+
return;
|
|
6221
|
+
const diagnostics = {
|
|
6222
|
+
source: "lan-playback",
|
|
6223
|
+
reason,
|
|
6224
|
+
windowMs: performance.now() - report.startedAt,
|
|
6225
|
+
sentFrames: report.sentFrames,
|
|
6226
|
+
sentBytes: report.sentBytes,
|
|
6227
|
+
droppedFrames: report.droppedFrames,
|
|
6228
|
+
droppedBytes: report.droppedBytes,
|
|
6229
|
+
maxSocketBacklogBytes: report.maxSocketBacklogBytes,
|
|
6230
|
+
sourcePcmArrivalGapMaxMs: report.sourcePcmArrivalGapMaxMs,
|
|
6231
|
+
sourcePcmArrivalGapIncludesPauses: true
|
|
6232
|
+
};
|
|
6233
|
+
report.sentFrames = report.sentBytes = report.droppedFrames = report.droppedBytes = 0;
|
|
6234
|
+
report.maxSocketBacklogBytes = report.sourcePcmArrivalGapMaxMs = 0;
|
|
6235
|
+
try {
|
|
6236
|
+
this.onAudioDiagnostics?.(diagnostics);
|
|
6237
|
+
} catch {
|
|
6238
|
+
console.warn("[voice audio] LAN playback diagnostics could not be saved");
|
|
6239
|
+
}
|
|
6240
|
+
}
|
|
6241
|
+
finishAudioReport(socket, reason) {
|
|
6242
|
+
this.flushAudioReport(socket, reason);
|
|
6243
|
+
this.audioReports.delete(socket);
|
|
5340
6244
|
}
|
|
5341
6245
|
sendAudioControl(socket, value) {
|
|
5342
6246
|
if (socket.readyState === WebSocket2.OPEN)
|
|
@@ -5351,6 +6255,7 @@ class LanVoiceBrowserConnections {
|
|
|
5351
6255
|
}
|
|
5352
6256
|
close(failures) {
|
|
5353
6257
|
for (const socket of this.audioSockets.values()) {
|
|
6258
|
+
this.finishAudioReport(socket, "server-closed");
|
|
5354
6259
|
try {
|
|
5355
6260
|
socket.terminate();
|
|
5356
6261
|
} catch (error) {
|
|
@@ -5370,7 +6275,7 @@ class LanVoiceBrowserConnections {
|
|
|
5370
6275
|
}
|
|
5371
6276
|
|
|
5372
6277
|
// packages/gippity-voice/src/voice/lan/browser-session.ts
|
|
5373
|
-
import { WebSocket as
|
|
6278
|
+
import { WebSocket as WebSocket4 } from "ws";
|
|
5374
6279
|
|
|
5375
6280
|
// packages/gippity-voice/src/voice/lan/protocol.ts
|
|
5376
6281
|
function decodeLanVoiceAudioCommand(value) {
|
|
@@ -5379,16 +6284,26 @@ function decodeLanVoiceAudioCommand(value) {
|
|
|
5379
6284
|
if (value.type === "start") {
|
|
5380
6285
|
if (!("mode" in value) || value.mode !== "conversation" && value.mode !== "dictation")
|
|
5381
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 } : {};
|
|
5382
6291
|
if ("takeoverToken" in value) {
|
|
5383
6292
|
if (value.mode !== "conversation" || typeof value.takeoverToken !== "string" || !/^[a-f0-9-]{36}$/.test(value.takeoverToken))
|
|
5384
6293
|
throw invalidCommand();
|
|
5385
6294
|
return {
|
|
5386
6295
|
type: "start",
|
|
5387
6296
|
mode: value.mode,
|
|
5388
|
-
takeoverToken: value.takeoverToken
|
|
6297
|
+
takeoverToken: value.takeoverToken,
|
|
6298
|
+
...capability
|
|
5389
6299
|
};
|
|
5390
6300
|
}
|
|
5391
|
-
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 };
|
|
5392
6307
|
}
|
|
5393
6308
|
if (value.type === "finish") {
|
|
5394
6309
|
if (!("draft" in value) || typeof value.draft !== "string")
|
|
@@ -5502,6 +6417,66 @@ class MicrophoneLevelMonitor {
|
|
|
5502
6417
|
}
|
|
5503
6418
|
}
|
|
5504
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
|
+
|
|
5505
6480
|
// packages/gippity-voice/src/voice/lan/browser-session.ts
|
|
5506
6481
|
class LanVoiceBrowserSession {
|
|
5507
6482
|
options;
|
|
@@ -5509,7 +6484,9 @@ class LanVoiceBrowserSession {
|
|
|
5509
6484
|
state = { type: "idle" };
|
|
5510
6485
|
operation = Promise.resolve();
|
|
5511
6486
|
conversationOwnerId;
|
|
6487
|
+
stopCompletion;
|
|
5512
6488
|
conversationSpeakerSuppressed = false;
|
|
6489
|
+
playbackDrain = new LanPlaybackDrain;
|
|
5513
6490
|
microphoneLevel;
|
|
5514
6491
|
constructor(options, connections) {
|
|
5515
6492
|
this.options = options;
|
|
@@ -5530,6 +6507,7 @@ class LanVoiceBrowserSession {
|
|
|
5530
6507
|
setConversationSpeakerSuppressed(suppressed) {
|
|
5531
6508
|
if (this.conversationSpeakerSuppressed === suppressed)
|
|
5532
6509
|
return;
|
|
6510
|
+
this.playbackDrain.cancel();
|
|
5533
6511
|
this.conversationSpeakerSuppressed = suppressed;
|
|
5534
6512
|
const active = this.state;
|
|
5535
6513
|
if (active.type === "active" && active.mode === "conversation") {
|
|
@@ -5539,28 +6517,59 @@ class LanVoiceBrowserSession {
|
|
|
5539
6517
|
});
|
|
5540
6518
|
}
|
|
5541
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
|
+
}
|
|
5542
6535
|
release(clientId, socket, terminateConversation = false) {
|
|
6536
|
+
if (terminateConversation && this.stopCompletion?.clientId === clientId)
|
|
6537
|
+
return this.stopCompletion.promise;
|
|
6538
|
+
const starting = this.state;
|
|
6539
|
+
if (starting.type === "active" && starting.mode === "conversation" && starting.clientId === clientId && (!socket || starting.socket === socket))
|
|
6540
|
+
this.playbackDrain.cancel();
|
|
6541
|
+
const ownsConversation = this.conversationOwnerId === clientId && (!socket || (starting.type === "active" || starting.type === "starting") && starting.socket === socket);
|
|
5543
6542
|
this.releaseStarting(clientId, socket);
|
|
5544
|
-
|
|
5545
|
-
|
|
5546
|
-
|
|
5547
|
-
|
|
5548
|
-
|
|
5549
|
-
if (ownsActive && active.mode === "conversation")
|
|
5550
|
-
this.microphoneLevel.reset();
|
|
5551
|
-
if (terminateConversation && this.conversationOwnerId === clientId) {
|
|
5552
|
-
this.conversationOwnerId = undefined;
|
|
5553
|
-
await this.options.onConversationActivity(false);
|
|
6543
|
+
let completion;
|
|
6544
|
+
if (terminateConversation && starting.type === "starting" && starting.mode === "conversation" && starting.clientId === clientId && (!socket || starting.socket === socket)) {
|
|
6545
|
+
this.conversationOwnerId = undefined;
|
|
6546
|
+
completion = Promise.resolve().then(() => this.options.onConversationActivity(false)).then(() => true);
|
|
6547
|
+
this.operation = Promise.all([this.operation, completion]).then(() => {
|
|
5554
6548
|
return;
|
|
5555
|
-
}
|
|
5556
|
-
if (!ownsActive)
|
|
6549
|
+
}, () => {
|
|
5557
6550
|
return;
|
|
5558
|
-
|
|
5559
|
-
|
|
5560
|
-
|
|
5561
|
-
|
|
5562
|
-
|
|
5563
|
-
|
|
6551
|
+
});
|
|
6552
|
+
} else {
|
|
6553
|
+
completion = this.enqueue(async () => {
|
|
6554
|
+
const active = this.state;
|
|
6555
|
+
const ownsActive = active.type === "active" && active.clientId === clientId && (!socket || active.socket === socket);
|
|
6556
|
+
if (ownsActive)
|
|
6557
|
+
this.state = { type: "idle" };
|
|
6558
|
+
if (ownsActive && active.mode === "conversation")
|
|
6559
|
+
this.microphoneLevel.reset();
|
|
6560
|
+
if (terminateConversation && this.conversationOwnerId === clientId && (!socket || ownsActive)) {
|
|
6561
|
+
this.conversationOwnerId = undefined;
|
|
6562
|
+
await this.options.onConversationActivity(false);
|
|
6563
|
+
return true;
|
|
6564
|
+
}
|
|
6565
|
+
if (ownsActive && active.mode === "dictation")
|
|
6566
|
+
await this.options.finishDictation(clientId);
|
|
6567
|
+
return false;
|
|
6568
|
+
});
|
|
6569
|
+
}
|
|
6570
|
+
if (terminateConversation && ownsConversation)
|
|
6571
|
+
this.stopCompletion = { clientId, promise: completion };
|
|
6572
|
+
return completion;
|
|
5564
6573
|
}
|
|
5565
6574
|
releaseStarting(clientId, socket) {
|
|
5566
6575
|
const starting = this.state;
|
|
@@ -5573,7 +6582,7 @@ class LanVoiceBrowserSession {
|
|
|
5573
6582
|
message: errorMessage(error)
|
|
5574
6583
|
}));
|
|
5575
6584
|
}
|
|
5576
|
-
claim(clientId, socket, mode, takeoverToken) {
|
|
6585
|
+
claim(clientId, socket, mode, takeoverToken, playbackDrain = false) {
|
|
5577
6586
|
const starting = this.state.type === "starting" ? this.state : undefined;
|
|
5578
6587
|
if (starting && (starting.clientId !== clientId || starting.socket !== socket || starting.mode !== mode)) {
|
|
5579
6588
|
this.releaseStarting(starting.clientId, starting.socket);
|
|
@@ -5584,11 +6593,12 @@ class LanVoiceBrowserSession {
|
|
|
5584
6593
|
starting.socket.close(4001, "replaced");
|
|
5585
6594
|
}
|
|
5586
6595
|
return this.enqueue(async () => {
|
|
5587
|
-
if (this.closed || socket.readyState !==
|
|
6596
|
+
if (this.closed || socket.readyState !== WebSocket4.OPEN || !this.connections.isCurrentAudio(clientId, socket))
|
|
5588
6597
|
return;
|
|
5589
6598
|
const previous = this.state.type === "active" ? this.state : undefined;
|
|
5590
6599
|
if (previous?.clientId === clientId && previous.socket === socket && previous.mode === mode)
|
|
5591
6600
|
return;
|
|
6601
|
+
this.playbackDrain.cancel();
|
|
5592
6602
|
this.state = { type: "idle" };
|
|
5593
6603
|
if (previous?.mode === "conversation")
|
|
5594
6604
|
this.microphoneLevel.reset();
|
|
@@ -5609,8 +6619,10 @@ class LanVoiceBrowserSession {
|
|
|
5609
6619
|
return;
|
|
5610
6620
|
const starting = { type: "starting", clientId, socket, mode };
|
|
5611
6621
|
this.state = starting;
|
|
5612
|
-
if (mode === "conversation")
|
|
6622
|
+
if (mode === "conversation") {
|
|
6623
|
+
this.stopCompletion = undefined;
|
|
5613
6624
|
this.conversationOwnerId = clientId;
|
|
6625
|
+
}
|
|
5614
6626
|
try {
|
|
5615
6627
|
if (mode === "conversation")
|
|
5616
6628
|
await this.options.ensureConversation(takeoverToken);
|
|
@@ -5623,12 +6635,12 @@ class LanVoiceBrowserSession {
|
|
|
5623
6635
|
this.conversationOwnerId = undefined;
|
|
5624
6636
|
throw error;
|
|
5625
6637
|
}
|
|
5626
|
-
if (this.closed || this.state !== starting || !this.connections.isCurrentAudio(clientId, socket) || socket.readyState !==
|
|
6638
|
+
if (this.closed || this.state !== starting || !this.connections.isCurrentAudio(clientId, socket) || socket.readyState !== WebSocket4.OPEN) {
|
|
5627
6639
|
if (mode === "dictation")
|
|
5628
6640
|
await this.options.cancelDictation(clientId);
|
|
5629
6641
|
return;
|
|
5630
6642
|
}
|
|
5631
|
-
this.state = { type: "active", clientId, socket, mode };
|
|
6643
|
+
this.state = { type: "active", clientId, socket, mode, playbackDrain };
|
|
5632
6644
|
if (mode === "conversation")
|
|
5633
6645
|
await this.options.onConversationActivity(true);
|
|
5634
6646
|
socket.send(JSON.stringify({
|
|
@@ -5648,7 +6660,7 @@ class LanVoiceBrowserSession {
|
|
|
5648
6660
|
return;
|
|
5649
6661
|
this.state = { type: "idle" };
|
|
5650
6662
|
await this.options.finishDictation(clientId, draft, revision, selection);
|
|
5651
|
-
if (!this.closed && socket.readyState ===
|
|
6663
|
+
if (!this.closed && socket.readyState === WebSocket4.OPEN)
|
|
5652
6664
|
socket.send(JSON.stringify({ type: "dictation.complete" }));
|
|
5653
6665
|
});
|
|
5654
6666
|
}
|
|
@@ -5675,6 +6687,7 @@ class LanVoiceBrowserSession {
|
|
|
5675
6687
|
this.options.onDictationAudio(clientId, pcm);
|
|
5676
6688
|
}
|
|
5677
6689
|
async close() {
|
|
6690
|
+
this.playbackDrain.cancel();
|
|
5678
6691
|
const active = this.state;
|
|
5679
6692
|
if (active.type === "closed") {
|
|
5680
6693
|
await this.operation;
|
|
@@ -5682,7 +6695,7 @@ class LanVoiceBrowserSession {
|
|
|
5682
6695
|
}
|
|
5683
6696
|
this.state = { type: "closed" };
|
|
5684
6697
|
const failures = [];
|
|
5685
|
-
if (active.type === "active" && active.mode === "conversation") {
|
|
6698
|
+
if ((active.type === "active" || active.type === "starting") && active.mode === "conversation") {
|
|
5686
6699
|
try {
|
|
5687
6700
|
this.conversationOwnerId = undefined;
|
|
5688
6701
|
await this.options.onConversationActivity(false);
|
|
@@ -5721,10 +6734,11 @@ class LanVoiceBrowserSession {
|
|
|
5721
6734
|
|
|
5722
6735
|
// packages/gippity-voice/src/voice/lan/browser-clients.ts
|
|
5723
6736
|
class LanVoiceBrowserClients {
|
|
5724
|
-
connections
|
|
6737
|
+
connections;
|
|
5725
6738
|
session;
|
|
5726
6739
|
takeoverAck;
|
|
5727
6740
|
constructor(options) {
|
|
6741
|
+
this.connections = new LanVoiceBrowserConnections(options.onAudioDiagnostics);
|
|
5728
6742
|
this.session = new LanVoiceBrowserSession(options, this.connections);
|
|
5729
6743
|
}
|
|
5730
6744
|
connectEvents(clientId, response) {
|
|
@@ -5733,8 +6747,13 @@ class LanVoiceBrowserClients {
|
|
|
5733
6747
|
connectAudio(clientId, socket) {
|
|
5734
6748
|
this.connections.connectAudio(clientId, socket, this.session.closed, {
|
|
5735
6749
|
onMessage: (data, isBinary) => this.receive(clientId, socket, data, isBinary),
|
|
5736
|
-
onReplaced: (previous) => this.session.
|
|
5737
|
-
onClose: () =>
|
|
6750
|
+
onReplaced: (previous) => this.session.replaceSocket(clientId, previous),
|
|
6751
|
+
onClose: () => {
|
|
6752
|
+
this.session.release(clientId, socket).catch((error) => this.connections.sendControl(clientId, {
|
|
6753
|
+
type: "error",
|
|
6754
|
+
message: errorMessage(error)
|
|
6755
|
+
}));
|
|
6756
|
+
}
|
|
5738
6757
|
});
|
|
5739
6758
|
}
|
|
5740
6759
|
sendControl(clientId, value) {
|
|
@@ -5751,7 +6770,7 @@ class LanVoiceBrowserClients {
|
|
|
5751
6770
|
}
|
|
5752
6771
|
takeover(token) {
|
|
5753
6772
|
const socket = this.session.conversationSocket;
|
|
5754
|
-
if (!socket || socket.readyState !==
|
|
6773
|
+
if (!socket || socket.readyState !== WebSocket5.OPEN)
|
|
5755
6774
|
return Promise.reject(new Error("The active browser microphone is not connected"));
|
|
5756
6775
|
if (this.takeoverAck)
|
|
5757
6776
|
return Promise.reject(new Error("A browser takeover is already preparing"));
|
|
@@ -5781,6 +6800,9 @@ class LanVoiceBrowserClients {
|
|
|
5781
6800
|
sendConversationAudio(pcm) {
|
|
5782
6801
|
this.session.sendConversationAudio(pcm);
|
|
5783
6802
|
}
|
|
6803
|
+
drainPlayback(signal, seal) {
|
|
6804
|
+
return this.session.drainPlayback(signal, seal);
|
|
6805
|
+
}
|
|
5784
6806
|
setConversationSpeakerSuppressed(suppressed) {
|
|
5785
6807
|
this.session.setConversationSpeakerSuppressed(suppressed);
|
|
5786
6808
|
}
|
|
@@ -5788,7 +6810,7 @@ class LanVoiceBrowserClients {
|
|
|
5788
6810
|
this.session.resetConversationInputLevel();
|
|
5789
6811
|
}
|
|
5790
6812
|
release(clientId, socket, terminateConversation = false) {
|
|
5791
|
-
this.session.release(clientId, socket, terminateConversation);
|
|
6813
|
+
return this.session.release(clientId, socket, terminateConversation);
|
|
5792
6814
|
}
|
|
5793
6815
|
heartbeat() {
|
|
5794
6816
|
this.connections.heartbeat();
|
|
@@ -5813,11 +6835,13 @@ class LanVoiceBrowserClients {
|
|
|
5813
6835
|
}
|
|
5814
6836
|
const message = input.command;
|
|
5815
6837
|
if (message.type === "start") {
|
|
5816
|
-
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);
|
|
5817
6841
|
} else if (message.type === "finish") {
|
|
5818
6842
|
this.session.finish(clientId, socket, message.draft, message.revision, message.selection).catch((error) => this.sendSocketError(socket, error));
|
|
5819
6843
|
} else if (message.type === "release") {
|
|
5820
|
-
this.session.release(clientId, socket, true);
|
|
6844
|
+
this.session.release(clientId, socket, true).catch((error) => this.sendSocketError(socket, error));
|
|
5821
6845
|
} else if (message.type === "mute") {
|
|
5822
6846
|
this.session.mute(clientId, socket, message.muted);
|
|
5823
6847
|
} else {
|
|
@@ -5828,112 +6852,145 @@ class LanVoiceBrowserClients {
|
|
|
5828
6852
|
}
|
|
5829
6853
|
}
|
|
5830
6854
|
sendSocketError(socket, error) {
|
|
5831
|
-
if (socket.readyState ===
|
|
6855
|
+
if (socket.readyState === WebSocket5.OPEN)
|
|
5832
6856
|
socket.send(JSON.stringify({ type: "error", message: errorMessage(error) }));
|
|
5833
6857
|
}
|
|
5834
6858
|
}
|
|
5835
6859
|
|
|
5836
|
-
//
|
|
5837
|
-
var
|
|
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'); };
|
|
5838
6874
|
|
|
5839
|
-
|
|
5840
|
-
|
|
5841
|
-
|
|
5842
|
-
|
|
5843
|
-
|
|
5844
|
-
|
|
5845
|
-
|
|
5846
|
-
|
|
5847
|
-
|
|
5848
|
-
|
|
5849
|
-
|
|
5850
|
-
|
|
5851
|
-
|
|
5852
|
-
|
|
5853
|
-
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
if (
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
|
|
5875
|
-
|
|
5876
|
-
|
|
5877
|
-
|
|
5878
|
-
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
|
|
5882
|
-
|
|
5883
|
-
|
|
5884
|
-
|
|
5885
|
-
|
|
5886
|
-
|
|
5887
|
-
|
|
5888
|
-
|
|
5889
|
-
|
|
5890
|
-
|
|
5891
|
-
|
|
5892
|
-
|
|
5893
|
-
}
|
|
5894
|
-
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
|
|
5899
|
-
|
|
5900
|
-
|
|
5901
|
-
|
|
5902
|
-
|
|
5903
|
-
|
|
5904
|
-
|
|
5905
|
-
|
|
5906
|
-
|
|
5907
|
-
|
|
5908
|
-
|
|
5909
|
-
|
|
5910
|
-
|
|
5911
|
-
|
|
5912
|
-
|
|
5913
|
-
|
|
5914
|
-
|
|
5915
|
-
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
5920
|
-
return;
|
|
5921
|
-
|
|
5922
|
-
|
|
5923
|
-
|
|
5924
|
-
|
|
5925
|
-
|
|
5926
|
-
|
|
5927
|
-
|
|
5928
|
-
|
|
5929
|
-
|
|
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;
|
|
5930
6989
|
}
|
|
5931
|
-
|
|
5932
|
-
|
|
5933
|
-
|
|
5934
|
-
|
|
5935
|
-
return;
|
|
5936
|
-
}
|
|
6990
|
+
|
|
6991
|
+
global.GippityRemote = Object.freeze({ connect });
|
|
6992
|
+
})(globalThis);
|
|
6993
|
+
`;
|
|
5937
6994
|
|
|
5938
6995
|
// packages/gippity-voice/src/voice/lan/audio-worklet.ts
|
|
5939
6996
|
var LAN_VOICE_AUDIO_WORKLET = String.raw`
|
|
@@ -5956,9 +7013,8 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
|
|
|
5956
7013
|
this.playbackLength = 0;
|
|
5957
7014
|
this.playing = false;
|
|
5958
7015
|
this.playbackPhase = 0;
|
|
5959
|
-
this.playbackCurrent = 0;
|
|
5960
|
-
this.playbackNext = 0;
|
|
5961
7016
|
this.speakerSuppressed = false;
|
|
7017
|
+
this.drain = undefined;
|
|
5962
7018
|
this.port.onmessage = (event) => this.handleMessage(event.data);
|
|
5963
7019
|
}
|
|
5964
7020
|
|
|
@@ -5967,6 +7023,10 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
|
|
|
5967
7023
|
if (!this.inputMuted && input?.[0]) this.captureInput(input);
|
|
5968
7024
|
const output = outputs[0]?.[0];
|
|
5969
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
|
+
}
|
|
5970
7030
|
return true;
|
|
5971
7031
|
}
|
|
5972
7032
|
|
|
@@ -5999,6 +7059,10 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
|
|
|
5999
7059
|
}
|
|
6000
7060
|
|
|
6001
7061
|
handleMessage(value) {
|
|
7062
|
+
if (value?.type === 'drain' && typeof value.id === 'string') {
|
|
7063
|
+
this.drain = value.id;
|
|
7064
|
+
return;
|
|
7065
|
+
}
|
|
6002
7066
|
if (value?.type === 'input_muted' && typeof value.muted === 'boolean' && Number.isSafeInteger(value.epoch)) {
|
|
6003
7067
|
this.captureEpoch = value.epoch;
|
|
6004
7068
|
this.inputMuted = value.muted;
|
|
@@ -6036,42 +7100,45 @@ class PiLanVoiceProcessor extends AudioWorkletProcessor {
|
|
|
6036
7100
|
}
|
|
6037
7101
|
}
|
|
6038
7102
|
|
|
6039
|
-
|
|
7103
|
+
clearPlayback() {
|
|
6040
7104
|
this.playback.fill(0);
|
|
6041
7105
|
this.playbackRead = 0;
|
|
6042
7106
|
this.playbackLength = 0;
|
|
6043
7107
|
this.playing = false;
|
|
6044
7108
|
this.playbackPhase = 0;
|
|
6045
|
-
|
|
6046
|
-
|
|
7109
|
+
}
|
|
7110
|
+
|
|
7111
|
+
resetPlayback() {
|
|
7112
|
+
this.drain = undefined;
|
|
7113
|
+
this.clearPlayback();
|
|
6047
7114
|
}
|
|
6048
7115
|
|
|
6049
7116
|
renderPlayback(output) {
|
|
6050
7117
|
output.fill(0);
|
|
6051
7118
|
if (!this.playing) {
|
|
6052
|
-
if (this.playbackLength < PLAYBACK_START_SAMPLES) return;
|
|
7119
|
+
if (this.playbackLength === 0 || (!this.drain && this.playbackLength < PLAYBACK_START_SAMPLES)) return;
|
|
6053
7120
|
this.playing = true;
|
|
6054
7121
|
this.playbackPhase = 0;
|
|
6055
|
-
this.playbackCurrent = this.shiftPlayback();
|
|
6056
|
-
this.playbackNext = this.shiftPlayback();
|
|
6057
7122
|
}
|
|
6058
7123
|
const step = TARGET_RATE / sampleRate;
|
|
6059
7124
|
for (let index = 0; index < output.length; index++) {
|
|
6060
|
-
|
|
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;
|
|
6061
7128
|
this.playbackPhase += step;
|
|
6062
7129
|
while (this.playbackPhase >= 1) {
|
|
6063
7130
|
this.playbackPhase -= 1;
|
|
6064
|
-
this.
|
|
7131
|
+
this.shiftPlayback();
|
|
6065
7132
|
if (this.playbackLength === 0) {
|
|
6066
7133
|
this.playing = false;
|
|
6067
7134
|
return;
|
|
6068
7135
|
}
|
|
6069
|
-
this.playbackNext = this.shiftPlayback();
|
|
6070
7136
|
}
|
|
6071
7137
|
}
|
|
6072
7138
|
}
|
|
6073
7139
|
|
|
6074
7140
|
shiftPlayback() {
|
|
7141
|
+
if (this.playbackLength === 0) return 0;
|
|
6075
7142
|
const sample = this.playback[this.playbackRead] || 0;
|
|
6076
7143
|
this.playbackRead = (this.playbackRead + 1) % PLAYBACK_MAX_SAMPLES;
|
|
6077
7144
|
this.playbackLength -= 1;
|
|
@@ -6186,6 +7253,15 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
|
|
|
6186
7253
|
processor.connect(context.destination);
|
|
6187
7254
|
return {
|
|
6188
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
|
+
},
|
|
6189
7265
|
acceptCapture(value) { return value?.type === 'capture' && value.epoch === inputEpoch && value.pcm instanceof ArrayBuffer ? value.pcm : undefined; },
|
|
6190
7266
|
releaseInput() { microphoneBuffer.port.postMessage({ type:'release' }); },
|
|
6191
7267
|
setInputMuted(muted) {
|
|
@@ -6319,6 +7395,10 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
|
|
|
6319
7395
|
if (event.data instanceof ArrayBuffer) { realtimeAudio?.play(event.data); return; }
|
|
6320
7396
|
try {
|
|
6321
7397
|
const message = JSON.parse(event.data);
|
|
7398
|
+
if (message.type === 'drain' && typeof message.id === 'string') {
|
|
7399
|
+
realtimeAudio?.drain(message.id);
|
|
7400
|
+
return;
|
|
7401
|
+
}
|
|
6322
7402
|
if (message.type === 'takeover') { beginTakeover(message); return; }
|
|
6323
7403
|
if (message.type === 'stop') { finishStop(false, message.reason || 'server'); return; }
|
|
6324
7404
|
if (message.type === 'mute') setMuted(message.muted, false);
|
|
@@ -6388,6 +7468,14 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
|
|
|
6388
7468
|
finishStop(false, 'connect-timeout'); publish('error', 'Connection timed out.');
|
|
6389
7469
|
}, 10000);
|
|
6390
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
|
+
}
|
|
6391
7479
|
const pcm = realtimeAudio
|
|
6392
7480
|
? realtimeAudio.acceptCapture(event.data)
|
|
6393
7481
|
: event.data?.type === 'capture' && event.data.epoch === 0 && event.data.pcm instanceof ArrayBuffer ? event.data.pcm : undefined;
|
|
@@ -6395,7 +7483,7 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
|
|
|
6395
7483
|
};
|
|
6396
7484
|
current.onopen = () => {
|
|
6397
7485
|
if (socket !== current || !context) return;
|
|
6398
|
-
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');
|
|
6399
7487
|
};
|
|
6400
7488
|
current.onmessage = (event) => receive(current, event);
|
|
6401
7489
|
current.onclose = (event) => {
|
|
@@ -6425,192 +7513,61 @@ var LAN_REMOTE_AUDIO_SCRIPT = String.raw` const audioWorkletSource = ${AUDIO_WO
|
|
|
6425
7513
|
clearTimeout(staleEventsTimer); staleEventsTimer = undefined;
|
|
6426
7514
|
resumeMuted = muted;
|
|
6427
7515
|
active = false; busy = true; finishing = false;
|
|
6428
|
-
const oldSocket = socket; socket = undefined;
|
|
6429
|
-
if (oldSocket?.readyState === WebSocket.OPEN) oldSocket.send(JSON.stringify({ type:'takeover.ack', token:command.token }));
|
|
6430
|
-
oldSocket?.close(1000, 'takeover');
|
|
6431
|
-
realtimeAudio?.setSpeakerSuppressed(true);
|
|
6432
|
-
if (!resume) closeHardware();
|
|
6433
|
-
takeoverTimer = setTimeout(() => {
|
|
6434
|
-
finishStop(false, 'takeover-timeout');
|
|
6435
|
-
publish('error', 'New session did not become ready. Check the server, then start voice again.');
|
|
6436
|
-
}, 20000);
|
|
6437
|
-
publish('takeover', resume ? 'Reconnecting voice to the new session…' : 'Waiting for the new session…');
|
|
6438
|
-
};
|
|
6439
|
-
const completeTakeover = (command) => {
|
|
6440
|
-
if (!takeover || command.takeoverToken !== takeover.token) return;
|
|
6441
|
-
const { resume, token } = takeover;
|
|
6442
|
-
clearTimeout(takeoverTimer); takeover = undefined; busy = false;
|
|
6443
|
-
if (resume) { replacingCall = true; void start('conversation', token); }
|
|
6444
|
-
else { resumeMuted = false; publish('idle', 'Connected to the new session'); }
|
|
6445
|
-
};
|
|
6446
|
-
const serverCommand = (command) => {
|
|
6447
|
-
if (command.type === 'connection') {
|
|
6448
|
-
if (command.state === 'connected') { clearTimeout(staleEventsTimer); staleEventsTimer = undefined; }
|
|
6449
|
-
if (command.state === 'reconnecting' && !staleEventsTimer && !retryAttempt && !takeover && mode === 'conversation' && (active || socket)) {
|
|
6450
|
-
staleEventsTimer = setTimeout(() => { staleEventsTimer = undefined; retryConnection('Server updates disconnected.'); }, 5000);
|
|
6451
|
-
}
|
|
6452
|
-
return;
|
|
6453
|
-
}
|
|
6454
|
-
if (command.type === 'takeover') { beginTakeover(command); return; }
|
|
6455
|
-
if (command.type === 'ready') { completeTakeover(command); return; }
|
|
6456
|
-
if (takeover) return;
|
|
6457
|
-
if (command.type === 'stop') finishStop(false, command.reason || 'server');
|
|
6458
|
-
if (command.type === 'error' && (active || busy || socket)) connectionError(command.message);
|
|
6459
|
-
if (command.type === 'mute' && mode === 'conversation') setMuted(command.muted, false);
|
|
6460
|
-
if (command.type === 'status' && busy && !active && !retryTimer) publish(command.status === 'summarizing…' ? 'summarizing' : 'connecting');
|
|
6461
|
-
if (command.type === 'microphone') { inputTooQuiet = command.state === 'too-quiet'; if (active && !muted) publish('listening', inputTooQuiet ? 'Microphone level is too low' : ''); }
|
|
6462
|
-
};
|
|
6463
|
-
return {
|
|
6464
|
-
start(...args) { assertOpen(); return start(...args); },
|
|
6465
|
-
stop(...args) { assertOpen(); return stop(...args); },
|
|
6466
|
-
setMuted(...args) { assertOpen(); return setMuted(...args); },
|
|
6467
|
-
get state() { return snapshot(); },
|
|
6468
|
-
_serverCommand: serverCommand,
|
|
6469
|
-
_pagehide() {
|
|
6470
|
-
if (finishing && socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type:'cancel' }));
|
|
6471
|
-
else if (active) navigator.sendBeacon('/api/stop', new Blob([JSON.stringify({ clientId:client.clientId })], {type:'application/json'}));
|
|
6472
|
-
generation += 1; finishStop(false, 'pagehide');
|
|
6473
|
-
},
|
|
6474
|
-
_close() { if (finishing) stop(); else { generation += 1; finishStop(true, 'client-closed'); } },
|
|
6475
|
-
};
|
|
6476
|
-
}
|
|
6477
|
-
|
|
6478
|
-
`;
|
|
6479
|
-
|
|
6480
|
-
// packages/gippity-voice/src/voice/lan/client-sdk-script.ts
|
|
6481
|
-
var LAN_REMOTE_CLIENT_SCRIPT = String.raw`
|
|
6482
|
-
(function (global) {
|
|
6483
|
-
'use strict';
|
|
6484
|
-
${LAN_REMOTE_AUDIO_SCRIPT} function connect(options = {}) {
|
|
6485
|
-
const clientId = options.clientId || id();
|
|
6486
|
-
const listeners = new Map();
|
|
6487
|
-
let closed = false, eventSource, rpcId = 0;
|
|
6488
|
-
let draft = { type:'draft', text:'', revision:-1 };
|
|
6489
|
-
let dirty = false, syncing = false, syncPromise, timer;
|
|
6490
|
-
let resolveInitialDraft;
|
|
6491
|
-
const initialDraft = new Promise((resolve) => { resolveInitialDraft = resolve; });
|
|
6492
|
-
const assertOpen = () => { if (closed) throw new Error('GipPity remote is closed'); };
|
|
6493
|
-
|
|
6494
|
-
const emit = (type, value, wildcard = true) => {
|
|
6495
|
-
for (const listener of listeners.get(type) || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
|
|
6496
|
-
if (wildcard && type !== '*') for (const listener of listeners.get('*') || []) { try { listener(value); } catch (error) { setTimeout(() => { throw error; }); } }
|
|
6497
|
-
};
|
|
6498
|
-
const post = async (path, body) => {
|
|
6499
|
-
assertOpen();
|
|
6500
|
-
const response = await fetch(path, { method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({ clientId, ...body }) });
|
|
6501
|
-
const result = await response.json().catch(() => ({}));
|
|
6502
|
-
if (!response.ok) throw new Error(result.error || 'Pi rejected the request');
|
|
6503
|
-
return result;
|
|
6504
|
-
};
|
|
6505
|
-
const client = {
|
|
6506
|
-
clientId,
|
|
6507
|
-
_emit: emit,
|
|
6508
|
-
_post: post,
|
|
6509
|
-
get draft() { return { ...draft }; },
|
|
6510
|
-
on(type, listener) {
|
|
6511
|
-
assertOpen();
|
|
6512
|
-
if (typeof listener !== 'function') throw new Error('Event listener must be a function');
|
|
6513
|
-
let group = listeners.get(type); if (!group) { group = new Set(); listeners.set(type, group); }
|
|
6514
|
-
group.add(listener); return () => group.delete(listener);
|
|
6515
|
-
},
|
|
6516
|
-
async call(target, method, ...args) {
|
|
6517
|
-
const id = ++rpcId;
|
|
6518
|
-
const result = await post('/api/rpc', { id, target, method, args });
|
|
6519
|
-
if (!result.ok) {
|
|
6520
|
-
const error = new Error(result.error?.message || 'Pi RPC failed');
|
|
6521
|
-
if (result.error?.name) error.name = result.error.name;
|
|
6522
|
-
throw error;
|
|
6523
|
-
}
|
|
6524
|
-
return result.result;
|
|
6525
|
-
},
|
|
6526
|
-
setDraft(text) {
|
|
6527
|
-
assertOpen();
|
|
6528
|
-
if (typeof text !== 'string') throw new Error('Draft text must be a string');
|
|
6529
|
-
draft = { ...draft, text, local:true };
|
|
6530
|
-
dirty = true; emit('draft', { ...draft });
|
|
6531
|
-
clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180);
|
|
6532
|
-
},
|
|
6533
|
-
flushDraft: () => flush(),
|
|
6534
|
-
async send(text) {
|
|
6535
|
-
if (typeof text === 'string' && text !== draft.text) client.setDraft(text);
|
|
6536
|
-
clearTimeout(timer);
|
|
6537
|
-
await flush();
|
|
6538
|
-
if (!draft.text.trim()) throw new Error('A message is required');
|
|
6539
|
-
await post('/api/send', { text:draft.text, revision:draft.revision });
|
|
6540
|
-
},
|
|
6541
|
-
close() {
|
|
6542
|
-
if (closed) return; clearTimeout(timer);
|
|
6543
|
-
client.audio._close(); closed = true; resolveInitialDraft();
|
|
6544
|
-
navigator.sendBeacon('/api/draft', new Blob([JSON.stringify({ clientId, text:draft.text, revision:draft.revision })], {type:'application/json'}));
|
|
6545
|
-
global.removeEventListener('pagehide', pagehide);
|
|
6546
|
-
eventSource?.close(); listeners.clear();
|
|
6547
|
-
},
|
|
6548
|
-
};
|
|
6549
|
-
const flush = async () => {
|
|
6550
|
-
if (closed) throw new Error('GipPity remote is closed');
|
|
6551
|
-
if (syncing) return syncPromise;
|
|
6552
|
-
if (!dirty) return true;
|
|
6553
|
-
syncing = true;
|
|
6554
|
-
syncPromise = (async () => {
|
|
6555
|
-
if (draft.revision < 0) await initialDraft;
|
|
6556
|
-
if (closed) throw new Error('GipPity remote is closed');
|
|
6557
|
-
while (dirty) {
|
|
6558
|
-
if (closed) throw new Error('GipPity remote is closed');
|
|
6559
|
-
dirty = false;
|
|
6560
|
-
const text = draft.text;
|
|
6561
|
-
try {
|
|
6562
|
-
const result = await post('/api/draft', { text, revision:draft.revision });
|
|
6563
|
-
if (typeof result.revision === 'number') draft = { ...draft, revision:Math.max(draft.revision, result.revision) };
|
|
6564
|
-
} catch (error) {
|
|
6565
|
-
dirty = true; emit('error', { type:'error', source:'draft', message:error instanceof Error ? error.message : String(error) });
|
|
6566
|
-
throw error;
|
|
6567
|
-
}
|
|
6568
|
-
}
|
|
6569
|
-
return true;
|
|
6570
|
-
})();
|
|
6571
|
-
try { return await syncPromise; }
|
|
6572
|
-
finally { syncing = false; syncPromise = undefined; }
|
|
6573
|
-
};
|
|
6574
|
-
const applyDraft = (command) => {
|
|
6575
|
-
if (typeof command.text !== 'string' || typeof command.revision !== 'number' || command.revision < draft.revision) return;
|
|
6576
|
-
if (draft.revision < 0 && dirty) {
|
|
6577
|
-
draft = { ...draft, revision:command.revision };
|
|
6578
|
-
resolveInitialDraft(); emit('draft', { ...draft }); return;
|
|
6579
|
-
}
|
|
6580
|
-
const reconnectSnapshot = !command.sourceClientId && !command.reason;
|
|
6581
|
-
const preserveLocal = (dirty || syncing) && draft.text !== command.text && (reconnectSnapshot || (command.sourceClientId === clientId && (command.reason === 'update' || command.reason === 'sent')));
|
|
6582
|
-
draft = preserveLocal ? { ...draft, revision:command.revision } : { ...command };
|
|
6583
|
-
if (!preserveLocal && command.sourceClientId !== clientId) { clearTimeout(timer); dirty = false; }
|
|
6584
|
-
if (reconnectSnapshot && preserveLocal && dirty) { clearTimeout(timer); timer = setTimeout(() => { void flush().catch(() => {}); }, 180); }
|
|
6585
|
-
resolveInitialDraft();
|
|
6586
|
-
emit('draft', { ...draft });
|
|
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…');
|
|
6587
7526
|
};
|
|
6588
|
-
|
|
6589
|
-
|
|
6590
|
-
|
|
6591
|
-
|
|
6592
|
-
|
|
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'); }
|
|
6593
7533
|
};
|
|
6594
|
-
|
|
6595
|
-
|
|
6596
|
-
|
|
6597
|
-
|
|
6598
|
-
|
|
6599
|
-
|
|
6600
|
-
|
|
6601
|
-
|
|
6602
|
-
|
|
6603
|
-
|
|
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'); } },
|
|
6604
7563
|
};
|
|
6605
|
-
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'})); };
|
|
6606
|
-
global.addEventListener('pagehide', pagehide);
|
|
6607
|
-
return client;
|
|
6608
7564
|
}
|
|
6609
7565
|
|
|
6610
|
-
global.GippityRemote = Object.freeze({ connect });
|
|
6611
|
-
})(globalThis);
|
|
6612
7566
|
`;
|
|
6613
7567
|
|
|
7568
|
+
// packages/gippity-voice/src/voice/lan/client-sdk-script.ts
|
|
7569
|
+
var LAN_REMOTE_CLIENT_SCRIPT = lanClientScript(LAN_REMOTE_AUDIO_SCRIPT);
|
|
7570
|
+
|
|
6614
7571
|
// packages/gippity-voice/src/voice/lan/dictation.ts
|
|
6615
7572
|
class LanVoiceDictation {
|
|
6616
7573
|
resolveAuth;
|
|
@@ -6700,92 +7657,6 @@ class LanVoiceDictation {
|
|
|
6700
7657
|
// packages/gippity-voice/src/voice/lan/discovery.ts
|
|
6701
7658
|
var LAN_REMOTE_CLIENT_PATH = "/_gippity/client.js";
|
|
6702
7659
|
|
|
6703
|
-
// packages/gippity-voice/src/voice/lan/draft.ts
|
|
6704
|
-
var MAX_LAN_VOICE_DRAFT_BYTES = 64 * 1024;
|
|
6705
|
-
|
|
6706
|
-
class LanVoiceDraftError extends Error {
|
|
6707
|
-
}
|
|
6708
|
-
|
|
6709
|
-
class LanVoiceDraftConflictError extends LanVoiceDraftError {
|
|
6710
|
-
}
|
|
6711
|
-
|
|
6712
|
-
class LanVoiceDraft {
|
|
6713
|
-
publish;
|
|
6714
|
-
sendMessage;
|
|
6715
|
-
text = "";
|
|
6716
|
-
revision = 0;
|
|
6717
|
-
sending = false;
|
|
6718
|
-
constructor(options) {
|
|
6719
|
-
this.publish = options.publish;
|
|
6720
|
-
this.sendMessage = options.sendMessage;
|
|
6721
|
-
}
|
|
6722
|
-
snapshot(sourceClientId, reason) {
|
|
6723
|
-
return {
|
|
6724
|
-
type: "draft",
|
|
6725
|
-
text: this.text,
|
|
6726
|
-
revision: this.revision,
|
|
6727
|
-
...sourceClientId ? { sourceClientId } : {},
|
|
6728
|
-
...reason ? { reason } : {}
|
|
6729
|
-
};
|
|
6730
|
-
}
|
|
6731
|
-
update(clientId, value, expectedRevision) {
|
|
6732
|
-
this.assertRevision(expectedRevision);
|
|
6733
|
-
this.text = validatedDraft(value);
|
|
6734
|
-
this.revision += 1;
|
|
6735
|
-
this.publish(this.snapshot(clientId, "update"));
|
|
6736
|
-
return this.revision;
|
|
6737
|
-
}
|
|
6738
|
-
insertTranscript(clientId, transcript, selection) {
|
|
6739
|
-
const clean = transcript.trim();
|
|
6740
|
-
if (!clean)
|
|
6741
|
-
return;
|
|
6742
|
-
const start = boundedIndex(selection?.start, this.text.length, this.text.length);
|
|
6743
|
-
const end = boundedIndex(selection?.end, this.text.length, start);
|
|
6744
|
-
const before = this.text.slice(0, Math.min(start, end));
|
|
6745
|
-
const after = this.text.slice(Math.max(start, end));
|
|
6746
|
-
const leftSpace = before && !/\s$/.test(before) ? " " : "";
|
|
6747
|
-
const rightSpace = after && !/^\s/.test(after) ? " " : "";
|
|
6748
|
-
this.text = validatedDraft(`${before}${leftSpace}${clean}${rightSpace}${after}`);
|
|
6749
|
-
this.revision += 1;
|
|
6750
|
-
this.publish(this.snapshot(clientId, "transcript"));
|
|
6751
|
-
}
|
|
6752
|
-
async send(clientId, value, expectedRevision) {
|
|
6753
|
-
this.assertRevision(expectedRevision);
|
|
6754
|
-
if (this.sending)
|
|
6755
|
-
throw new LanVoiceDraftConflictError("A message is already being sent");
|
|
6756
|
-
const text = validatedDraft(value);
|
|
6757
|
-
if (!text.trim())
|
|
6758
|
-
throw new LanVoiceDraftError("A message is required");
|
|
6759
|
-
this.text = text;
|
|
6760
|
-
const revision = this.revision;
|
|
6761
|
-
this.sending = true;
|
|
6762
|
-
try {
|
|
6763
|
-
await this.sendMessage(text);
|
|
6764
|
-
} finally {
|
|
6765
|
-
this.sending = false;
|
|
6766
|
-
}
|
|
6767
|
-
if (this.revision === revision && this.text === text)
|
|
6768
|
-
this.text = "";
|
|
6769
|
-
this.revision += 1;
|
|
6770
|
-
this.publish({ type: "sent" });
|
|
6771
|
-
this.publish(this.snapshot(clientId, "sent"));
|
|
6772
|
-
}
|
|
6773
|
-
assertRevision(value) {
|
|
6774
|
-
if (!Number.isInteger(value) || value !== this.revision)
|
|
6775
|
-
throw new LanVoiceDraftConflictError("Draft changed on another device; review it and try again");
|
|
6776
|
-
}
|
|
6777
|
-
}
|
|
6778
|
-
function validatedDraft(value) {
|
|
6779
|
-
if (typeof value !== "string")
|
|
6780
|
-
throw new LanVoiceDraftError("Draft text is required");
|
|
6781
|
-
if (Buffer.byteLength(value) > MAX_LAN_VOICE_DRAFT_BYTES)
|
|
6782
|
-
throw new LanVoiceDraftError("Draft is too large");
|
|
6783
|
-
return value;
|
|
6784
|
-
}
|
|
6785
|
-
function boundedIndex(value, length, fallback) {
|
|
6786
|
-
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= length ? value : fallback;
|
|
6787
|
-
}
|
|
6788
|
-
|
|
6789
7660
|
// packages/gippity-voice/src/voice/lan/browser-audio-script.ts
|
|
6790
7661
|
var LAN_VOICE_BROWSER_AUDIO_SCRIPT = String.raw`
|
|
6791
7662
|
function createAudioController({ button, muteButton, audioState, audioDetail, modeButtons, composer, client }) {
|
|
@@ -7306,6 +8177,7 @@ async function startGippityLanServer(options) {
|
|
|
7306
8177
|
}
|
|
7307
8178
|
});
|
|
7308
8179
|
clients = new LanVoiceBrowserClients({
|
|
8180
|
+
...options.onAudioDiagnostics ? { onAudioDiagnostics: options.onAudioDiagnostics } : {},
|
|
7309
8181
|
async ensureConversation(takeoverToken) {
|
|
7310
8182
|
if (closing)
|
|
7311
8183
|
throw new Error("LAN server is closing");
|
|
@@ -7316,7 +8188,8 @@ async function startGippityLanServer(options) {
|
|
|
7316
8188
|
const factory = () => {
|
|
7317
8189
|
browserPeer = new LanHostRealtimePeer(options.audio, {
|
|
7318
8190
|
onAudio: (pcm) => clients.sendConversationAudio(pcm),
|
|
7319
|
-
onSpeakerSuppressed: (suppressed) => clients.setConversationSpeakerSuppressed(suppressed)
|
|
8191
|
+
onSpeakerSuppressed: (suppressed) => clients.setConversationSpeakerSuppressed(suppressed),
|
|
8192
|
+
drain: (signal, seal) => clients.drainPlayback(signal, seal)
|
|
7320
8193
|
});
|
|
7321
8194
|
return browserPeer;
|
|
7322
8195
|
};
|
|
@@ -7371,7 +8244,7 @@ async function startGippityLanServer(options) {
|
|
|
7371
8244
|
async onConversationActivity(active) {
|
|
7372
8245
|
if (releasing)
|
|
7373
8246
|
return;
|
|
7374
|
-
if (!active && browserVoice) {
|
|
8247
|
+
if (!active && (browserVoice || browserStarting)) {
|
|
7375
8248
|
browserVoice = false;
|
|
7376
8249
|
browserPeer = undefined;
|
|
7377
8250
|
await controls.stopVoice();
|
|
@@ -7606,7 +8479,7 @@ data: {}
|
|
|
7606
8479
|
return send(response, 200, { ok: true });
|
|
7607
8480
|
}
|
|
7608
8481
|
if (path === "/api/stop") {
|
|
7609
|
-
clients.release(client, undefined, body["terminateConversation"] === true);
|
|
8482
|
+
await clients.release(client, undefined, body["terminateConversation"] === true);
|
|
7610
8483
|
return send(response, 200, { ok: true });
|
|
7611
8484
|
}
|
|
7612
8485
|
if (path === "/api/rpc") {
|
|
@@ -7679,13 +8552,13 @@ data: {}
|
|
|
7679
8552
|
server.on("error", (error) => clients.broadcastControl({ type: "error", message: error.message }));
|
|
7680
8553
|
return {
|
|
7681
8554
|
urls: origins.map((origin) => `${origin.origin}/`),
|
|
7682
|
-
browserAttached: () => [...sockets.clients].some((peer) => peer.readyState ===
|
|
8555
|
+
browserAttached: () => [...sockets.clients].some((peer) => peer.readyState === WebSocket6.OPEN),
|
|
7683
8556
|
hasConversation: () => browserVoice && controls.active,
|
|
7684
8557
|
acknowledgeTakeover: (token) => clients.takeover(token),
|
|
7685
8558
|
async proveTakeover(verify) {
|
|
7686
8559
|
if (takeoverProof)
|
|
7687
8560
|
throw new Error("A LAN listener proof is already pending");
|
|
7688
|
-
const token =
|
|
8561
|
+
const token = randomUUID4();
|
|
7689
8562
|
takeoverProof = token;
|
|
7690
8563
|
try {
|
|
7691
8564
|
await verify({ port: permission.port, token });
|
|
@@ -7726,28 +8599,21 @@ data: {}
|
|
|
7726
8599
|
else if (event.type === "lifecycle" && !event.active)
|
|
7727
8600
|
clients.broadcastControl({ type: "stop", reason: "voice-ended" });
|
|
7728
8601
|
},
|
|
7729
|
-
|
|
7730
|
-
if (
|
|
7731
|
-
|
|
7732
|
-
|
|
7733
|
-
|
|
7734
|
-
|
|
7735
|
-
|
|
7736
|
-
}
|
|
8602
|
+
agentState(working) {
|
|
8603
|
+
if (working)
|
|
8604
|
+
activity.working();
|
|
8605
|
+
else if (activity.snapshot().state === "working")
|
|
8606
|
+
activity.settled();
|
|
8607
|
+
},
|
|
8608
|
+
agentEntry(entry) {
|
|
7737
8609
|
clients.broadcastControl({
|
|
7738
8610
|
type: "durable.event",
|
|
7739
|
-
event:
|
|
7740
|
-
data: remoteJsonValue(
|
|
8611
|
+
event: "message_end",
|
|
8612
|
+
data: remoteJsonValue({ type: "message_end", entry })
|
|
7741
8613
|
});
|
|
7742
|
-
|
|
7743
|
-
|
|
7744
|
-
|
|
7745
|
-
activity.settled();
|
|
7746
|
-
if (event.type === "message_end") {
|
|
7747
|
-
const text = boundedAssistantText((event.entry.model ?? []).flatMap((message) => message.role === "assistant" && message.stopReason !== "toolUse" ? message.content : []));
|
|
7748
|
-
if (text)
|
|
7749
|
-
activity.settled(text);
|
|
7750
|
-
}
|
|
8614
|
+
const text = boundedAssistantText((entry.model ?? []).flatMap((message) => message.role === "assistant" && message.stopReason !== "toolUse" ? message.content : []));
|
|
8615
|
+
if (text)
|
|
8616
|
+
activity.settled(text);
|
|
7751
8617
|
}
|
|
7752
8618
|
};
|
|
7753
8619
|
}
|
|
@@ -7793,6 +8659,72 @@ async function readBody(request) {
|
|
|
7793
8659
|
return body;
|
|
7794
8660
|
}
|
|
7795
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
|
+
|
|
7796
8728
|
// packages/gippity-voice/src/voice/realtime-auth.ts
|
|
7797
8729
|
async function resolvePublicRealtimeAuth(models, name, signal, access) {
|
|
7798
8730
|
if (!normalizeVoiceApiProvider(name))
|
|
@@ -7859,7 +8791,10 @@ async function resolvePublicRealtimeAuth(models, name, signal, access) {
|
|
|
7859
8791
|
|
|
7860
8792
|
// packages/gippity-voice/src/voice/realtime-tools.ts
|
|
7861
8793
|
function createRealtimeAccess(agent, webSearch, execute) {
|
|
7862
|
-
const tools = agent.tools.filter((tool) =>
|
|
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
|
+
});
|
|
7863
8798
|
const selected = new Set;
|
|
7864
8799
|
for (const tool of tools) {
|
|
7865
8800
|
if (!tool.name || ["send_task", "end_call", "web_search"].includes(tool.name) || selected.has(tool.name))
|
|
@@ -8027,7 +8962,7 @@ import {
|
|
|
8027
8962
|
uuidv7,
|
|
8028
8963
|
validateToolArguments as validateToolArguments2
|
|
8029
8964
|
} from "@earendil-works/pi-ai";
|
|
8030
|
-
var SYSTEM_PROMPT = "Rewrite this conversation as a natural, self-contained request to another assistant. Preserve the user's intent, relevant context and uncertainty without inventing facts or decisions. Don't carry out the request. Prioritise the user's messages over assistant speech or work progress when deciding whether to end the call. Use end_call
|
|
8965
|
+
var SYSTEM_PROMPT = "Rewrite this conversation as a natural, self-contained request to another assistant. Preserve the user's intent, relevant context and uncertainty without inventing facts or decisions. Preserve the user's tone, register and emphasis. Remove transcription noise without formalising, softening or embellishing the request. Do not turn instructions into questions or add conversational next steps the user did not ask for. Don't carry out the request. Prioritise the user's messages over assistant speech or work progress when deciding whether to end the call. Use end_call when the user wants or agrees to end the call, including natural wrap-ups like 'that's all I needed for now'. Thanks alone, assistant completion or finishing one task while continuing the call is not end intent. Otherwise return only the request";
|
|
8031
8966
|
async function rewriteTaskDelegation(models, voice, turn, signal) {
|
|
8032
8967
|
let failure;
|
|
8033
8968
|
for (let attempt = 0;attempt < 4; attempt++) {
|
|
@@ -8111,9 +9046,9 @@ function createGippityVoice(options) {
|
|
|
8111
9046
|
throw new Error("Voice requires explicit audio permission, namespace, and instructions");
|
|
8112
9047
|
if (options.lan && options.lan.namespace !== options.namespace || options.appFiles && options.appFiles.namespace !== options.namespace)
|
|
8113
9048
|
throw new Error("Voice host capabilities must share the conversation namespace");
|
|
8114
|
-
const instance =
|
|
9049
|
+
const instance = randomUUID5();
|
|
8115
9050
|
const leaseOwner = `${registrationName}:${instance}`;
|
|
8116
|
-
let providerSessionId =
|
|
9051
|
+
let providerSessionId = randomUUID5();
|
|
8117
9052
|
let harness;
|
|
8118
9053
|
let conversationId;
|
|
8119
9054
|
let conversation;
|
|
@@ -8131,6 +9066,8 @@ function createGippityVoice(options) {
|
|
|
8131
9066
|
let session;
|
|
8132
9067
|
let activeCallId;
|
|
8133
9068
|
let dictation;
|
|
9069
|
+
let browserAudio;
|
|
9070
|
+
const preparedBrowsers = new WeakMap;
|
|
8134
9071
|
let lease;
|
|
8135
9072
|
let peerFactory;
|
|
8136
9073
|
let activeConfig;
|
|
@@ -8153,6 +9090,14 @@ function createGippityVoice(options) {
|
|
|
8153
9090
|
const contextSummaryCache = new VoiceContextSummaryCache;
|
|
8154
9091
|
const listeners = new Set;
|
|
8155
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
|
+
}
|
|
8156
9101
|
options.present?.(event);
|
|
8157
9102
|
for (const listener of listeners)
|
|
8158
9103
|
listener(event.type, event);
|
|
@@ -8190,6 +9135,16 @@ function createGippityVoice(options) {
|
|
|
8190
9135
|
}
|
|
8191
9136
|
}
|
|
8192
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
|
+
};
|
|
8193
9148
|
const enqueue = (work) => {
|
|
8194
9149
|
const result = serial.then(work);
|
|
8195
9150
|
serial = result.then(() => {}, () => {});
|
|
@@ -8197,7 +9152,7 @@ function createGippityVoice(options) {
|
|
|
8197
9152
|
};
|
|
8198
9153
|
const changeConfig = (create) => {
|
|
8199
9154
|
const result = configSerial.then(async () => {
|
|
8200
|
-
await
|
|
9155
|
+
await loadConfig();
|
|
8201
9156
|
if (settingsContribution && options.preferences) {
|
|
8202
9157
|
const next = mergeGippityPreferences(validateGippityPreferences(create()));
|
|
8203
9158
|
const snapshot = await settingsContribution.read();
|
|
@@ -8267,6 +9222,8 @@ function createGippityVoice(options) {
|
|
|
8267
9222
|
handoffGrant = undefined;
|
|
8268
9223
|
await Promise.all([...incomingBindings].map((binding) => binding.grant.release()));
|
|
8269
9224
|
incomingBindings.clear();
|
|
9225
|
+
await browserAudio?.close();
|
|
9226
|
+
browserAudio = undefined;
|
|
8270
9227
|
session = undefined;
|
|
8271
9228
|
activeCallId = undefined;
|
|
8272
9229
|
dictation = undefined;
|
|
@@ -8298,7 +9255,7 @@ function createGippityVoice(options) {
|
|
|
8298
9255
|
await api.commit(() => ({ status: "running", checkpoint: { phase: "active" } }), context);
|
|
8299
9256
|
},
|
|
8300
9257
|
async active(record, api, context) {
|
|
8301
|
-
const nonce =
|
|
9258
|
+
const nonce = randomUUID5();
|
|
8302
9259
|
if (record.input.instance !== instance || await api.memo("started", nonce, context) !== nonce) {
|
|
8303
9260
|
await api.commit(() => ({
|
|
8304
9261
|
status: "terminal",
|
|
@@ -8324,16 +9281,39 @@ function createGippityVoice(options) {
|
|
|
8324
9281
|
runtimeContext = context;
|
|
8325
9282
|
closing = false;
|
|
8326
9283
|
await configSerial;
|
|
8327
|
-
await
|
|
8328
|
-
|
|
8329
|
-
|
|
8330
|
-
|
|
8331
|
-
|
|
8332
|
-
|
|
8333
|
-
|
|
8334
|
-
|
|
8335
|
-
|
|
8336
|
-
|
|
9284
|
+
await loadConfig();
|
|
9285
|
+
events = await observeVoiceAgent(conversation, context, {
|
|
9286
|
+
state(value) {
|
|
9287
|
+
if (transferred)
|
|
9288
|
+
return;
|
|
9289
|
+
const changed = working !== value;
|
|
9290
|
+
working = value;
|
|
9291
|
+
lan?.agentState(working);
|
|
9292
|
+
if (!changed)
|
|
9293
|
+
return;
|
|
9294
|
+
const type = working ? "run_start" : "run_end";
|
|
9295
|
+
for (const listener of listeners)
|
|
9296
|
+
listener(type, { type });
|
|
9297
|
+
if (working) {
|
|
9298
|
+
session?.agentStarted();
|
|
9299
|
+
session?.resumeAgentWork();
|
|
9300
|
+
} else
|
|
9301
|
+
session?.settleAgentTurn();
|
|
9302
|
+
},
|
|
9303
|
+
entry: handleEntry,
|
|
9304
|
+
partial(delta, active) {
|
|
9305
|
+
if (transferred)
|
|
9306
|
+
return;
|
|
9307
|
+
if (delta)
|
|
9308
|
+
session?.streamAgentDelta(delta);
|
|
9309
|
+
if (active)
|
|
9310
|
+
session?.resumeAgentWork();
|
|
9311
|
+
},
|
|
9312
|
+
compacting: (reason) => session?.announceCompactionStart(reason),
|
|
9313
|
+
failed(error) {
|
|
9314
|
+
report(error);
|
|
9315
|
+
enqueue(stopSession).catch(report);
|
|
9316
|
+
}
|
|
8337
9317
|
});
|
|
8338
9318
|
ready?.resolve();
|
|
8339
9319
|
await new Promise((resolve) => {
|
|
@@ -8378,7 +9358,7 @@ function createGippityVoice(options) {
|
|
|
8378
9358
|
if (runtime && !closing)
|
|
8379
9359
|
return;
|
|
8380
9360
|
if (serviceStart)
|
|
8381
|
-
return
|
|
9361
|
+
return awaitWithContext3(serviceStart, context);
|
|
8382
9362
|
if (!harness || !conversationId)
|
|
8383
9363
|
throw new Error("Bind voice to its Harness and conversation first");
|
|
8384
9364
|
ready = deferred();
|
|
@@ -8399,7 +9379,7 @@ function createGippityVoice(options) {
|
|
|
8399
9379
|
serviceStart = undefined;
|
|
8400
9380
|
throw error;
|
|
8401
9381
|
});
|
|
8402
|
-
return
|
|
9382
|
+
return awaitWithContext3(serviceStart, context);
|
|
8403
9383
|
}
|
|
8404
9384
|
async function passive(kind, data, text) {
|
|
8405
9385
|
if (!conversation || !runtimeContext)
|
|
@@ -8443,7 +9423,7 @@ function createGippityVoice(options) {
|
|
|
8443
9423
|
throw new Error("Context summary export requires explicit host permission");
|
|
8444
9424
|
const project = async () => {
|
|
8445
9425
|
const view = await conversation.context(context);
|
|
8446
|
-
return options.projectContext && settings.voice.contextModel ? options.projectContext({ conversationId: runtime.conversationId, view },
|
|
9426
|
+
return options.projectContext && settings.voice.contextModel ? options.projectContext({ conversationId: runtime.conversationId, view }, withAbortSignal2(signal, context)) : view;
|
|
8447
9427
|
};
|
|
8448
9428
|
const view = await project();
|
|
8449
9429
|
const input = voiceContextSummaryInput(runtime.conversationId, view, settings);
|
|
@@ -8468,12 +9448,12 @@ function createGippityVoice(options) {
|
|
|
8468
9448
|
const execute = async (name, args, toolContext) => {
|
|
8469
9449
|
toolContext.signal.throwIfAborted();
|
|
8470
9450
|
let id;
|
|
8471
|
-
const context =
|
|
9451
|
+
const context = withAbortSignal2(toolContext.signal, runtimeContext);
|
|
8472
9452
|
await runtime.commit(async (tx) => {
|
|
8473
9453
|
id = await tx.createTask(toolTask, { name, arguments: args }, { ownership: { kind: "task", taskId: runtime.taskId } });
|
|
8474
9454
|
}, context);
|
|
8475
9455
|
const abort = () => {
|
|
8476
|
-
harness.abortTask(id,
|
|
9456
|
+
harness.abortTask(id, BACKGROUND_CONTEXT2).catch(report);
|
|
8477
9457
|
};
|
|
8478
9458
|
toolContext.signal.addEventListener("abort", abort, { once: true });
|
|
8479
9459
|
try {
|
|
@@ -8485,8 +9465,8 @@ function createGippityVoice(options) {
|
|
|
8485
9465
|
} finally {
|
|
8486
9466
|
toolContext.signal.removeEventListener("abort", abort);
|
|
8487
9467
|
if (toolContext.signal.aborted) {
|
|
8488
|
-
await harness.abortTask(id,
|
|
8489
|
-
await harness.waitForTask(id,
|
|
9468
|
+
await harness.abortTask(id, BACKGROUND_CONTEXT2);
|
|
9469
|
+
await harness.waitForTask(id, BACKGROUND_CONTEXT2);
|
|
8490
9470
|
}
|
|
8491
9471
|
}
|
|
8492
9472
|
};
|
|
@@ -8505,7 +9485,7 @@ function createGippityVoice(options) {
|
|
|
8505
9485
|
const auth = await resolveAuth(signal, settings);
|
|
8506
9486
|
signal.throwIfAborted();
|
|
8507
9487
|
const peer = factory();
|
|
8508
|
-
const callId =
|
|
9488
|
+
const callId = randomUUID5();
|
|
8509
9489
|
let current;
|
|
8510
9490
|
current = new CodexRealtimeConversation({
|
|
8511
9491
|
onStatus: (status) => publish({ type: "status", status }),
|
|
@@ -8517,11 +9497,16 @@ function createGippityVoice(options) {
|
|
|
8517
9497
|
delegations.push(turn, callId);
|
|
8518
9498
|
},
|
|
8519
9499
|
onEvent: (event) => publish({ type: "voice-event", event }),
|
|
9500
|
+
onAudioDiagnostics: (diagnostics) => publish({ type: "audio-diagnostics", diagnostics }),
|
|
8520
9501
|
rewriteDelegation: (turn, signal) => rewriteTaskDelegation(requireRuntime().runtime.models, settings.voice, turn, signal),
|
|
8521
9502
|
onDelegationError: report,
|
|
8522
9503
|
onEndCall: () => {
|
|
8523
|
-
current.waitForFinalPlayback().
|
|
8524
|
-
if (
|
|
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))
|
|
8525
9510
|
await stopSession(true);
|
|
8526
9511
|
})).catch(report);
|
|
8527
9512
|
},
|
|
@@ -8591,7 +9576,9 @@ function createGippityVoice(options) {
|
|
|
8591
9576
|
signal.removeEventListener("abort", abort);
|
|
8592
9577
|
}
|
|
8593
9578
|
}
|
|
8594
|
-
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");
|
|
8595
9582
|
if (!startup && transferred)
|
|
8596
9583
|
return transferred.startCall();
|
|
8597
9584
|
if (!startup && selectedCall)
|
|
@@ -8601,6 +9588,8 @@ function createGippityVoice(options) {
|
|
|
8601
9588
|
return enqueue(async () => {
|
|
8602
9589
|
if (requestedEpoch !== startEpoch)
|
|
8603
9590
|
throw new Error("Voice startup cancelled");
|
|
9591
|
+
if (browserAudio !== browser)
|
|
9592
|
+
throw new Error("Stop the shared browser session first");
|
|
8604
9593
|
if (dictation || transferring && !startup || transferred || session && !replace || lease && !session)
|
|
8605
9594
|
throw new Error("Voice or dictation is already active");
|
|
8606
9595
|
const previous = session;
|
|
@@ -8691,80 +9680,43 @@ ${tail}
|
|
|
8691
9680
|
releaseDelegations();
|
|
8692
9681
|
}
|
|
8693
9682
|
}
|
|
8694
|
-
function
|
|
9683
|
+
function handleEntry(entry) {
|
|
8695
9684
|
if (transferred)
|
|
8696
9685
|
return;
|
|
8697
|
-
const notification = event.type === "snapshot" ? {
|
|
8698
|
-
type: "snapshot",
|
|
8699
|
-
working: Boolean(event.run),
|
|
8700
|
-
model: event.agent.model ?? null
|
|
8701
|
-
} : event;
|
|
8702
9686
|
for (const listener of listeners)
|
|
8703
|
-
listener(
|
|
8704
|
-
lan?.
|
|
8705
|
-
if (
|
|
8706
|
-
|
|
8707
|
-
|
|
8708
|
-
working = true;
|
|
8709
|
-
if (event.type === "run_end")
|
|
8710
|
-
working = false;
|
|
8711
|
-
if (event.type === "run_start") {
|
|
8712
|
-
session?.agentStarted();
|
|
8713
|
-
session?.resumeAgentWork();
|
|
8714
|
-
}
|
|
8715
|
-
if (event.type === "run_end")
|
|
8716
|
-
session?.settleAgentTurn();
|
|
8717
|
-
if (event.type === "message_update") {
|
|
8718
|
-
for (const change of event.changes)
|
|
8719
|
-
if (change.type === "text_delta")
|
|
8720
|
-
session?.streamAgentDelta(change.delta);
|
|
8721
|
-
else if (change.type === "thinking_start" || change.type === "toolcall_start")
|
|
8722
|
-
session?.resumeAgentWork();
|
|
8723
|
-
}
|
|
8724
|
-
if (event.type === "message_end" && event.entry.kind === "gippity.voice.delegation" && isRecord(event.entry.data) && typeof event.entry.data["id"] === "string")
|
|
8725
|
-
if (event.entry.data["callId"] === activeCallId)
|
|
8726
|
-
session?.activateDelegation(event.entry.data["id"]);
|
|
9687
|
+
listener("message_end", { type: "message_end", entry });
|
|
9688
|
+
lan?.agentEntry(entry);
|
|
9689
|
+
if (entry.kind === "gippity.voice.delegation" && isRecord(entry.data) && typeof entry.data["id"] === "string")
|
|
9690
|
+
if (entry.data["callId"] === activeCallId)
|
|
9691
|
+
session?.activateDelegation(entry.data["id"]);
|
|
8727
9692
|
else
|
|
8728
9693
|
session?.agentStarted();
|
|
8729
|
-
|
|
8730
|
-
|
|
8731
|
-
|
|
8732
|
-
const text = typeof message.content === "string" ? message.content : message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
|
|
8733
|
-
`);
|
|
8734
|
-
session?.piInput(text, working ? "steer" : undefined);
|
|
8735
|
-
session?.piUserMessage(message);
|
|
8736
|
-
}
|
|
8737
|
-
if (message.role !== "assistant")
|
|
8738
|
-
continue;
|
|
8739
|
-
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
|
|
9694
|
+
for (const message of entry.model ?? []) {
|
|
9695
|
+
if (message.role === "user" && UserEntry.is(entry)) {
|
|
9696
|
+
const text = typeof message.content === "string" ? message.content : message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
|
|
8740
9697
|
`);
|
|
8741
|
-
|
|
8742
|
-
|
|
8743
|
-
} else
|
|
8744
|
-
session?.agentResult(text, message.stopReason);
|
|
9698
|
+
session?.piInput(text, working ? "steer" : undefined);
|
|
9699
|
+
session?.piUserMessage(message);
|
|
8745
9700
|
}
|
|
8746
|
-
|
|
8747
|
-
|
|
8748
|
-
|
|
8749
|
-
|
|
8750
|
-
|
|
8751
|
-
|
|
8752
|
-
|
|
8753
|
-
|
|
8754
|
-
const submission = await harness.submission(result.submissionId, runtimeContext);
|
|
8755
|
-
if (!submission || (await submission.wait(runtimeContext)).status !== "done")
|
|
8756
|
-
return;
|
|
8757
|
-
} else if (result.entryId === undefined)
|
|
8758
|
-
return;
|
|
8759
|
-
return enqueue(refreshContext);
|
|
8760
|
-
}).catch(report);
|
|
9701
|
+
if (message.role !== "assistant")
|
|
9702
|
+
continue;
|
|
9703
|
+
const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join(`
|
|
9704
|
+
`);
|
|
9705
|
+
if (message.stopReason === "toolUse") {
|
|
9706
|
+
session?.agentProgress(text, activeConfig?.voice.forwardReasoningSummaries ? completedVoiceReasoningSummary(message) : undefined);
|
|
9707
|
+
} else
|
|
9708
|
+
session?.agentResult(text, message.stopReason);
|
|
8761
9709
|
}
|
|
9710
|
+
if (CompactionEntry.is(entry) && activeConfig?.voice.refreshRealtimeAfterCompaction)
|
|
9711
|
+
enqueue(refreshContext).catch(report);
|
|
8762
9712
|
}
|
|
8763
9713
|
async function ensureLan(context, takeover) {
|
|
8764
9714
|
await ensureService(context);
|
|
8765
9715
|
if (!options.lan)
|
|
8766
9716
|
throw new Error("HTTPS LAN permission was not supplied");
|
|
8767
9717
|
await enqueue(async () => {
|
|
9718
|
+
if (browserAudio)
|
|
9719
|
+
throw new Error("Stop the shared browser session first");
|
|
8768
9720
|
if (lan) {
|
|
8769
9721
|
if (takeover)
|
|
8770
9722
|
throw new Error("LAN takeover requires a free listener");
|
|
@@ -8782,11 +9734,12 @@ ${tail}
|
|
|
8782
9734
|
context: runtimeContext,
|
|
8783
9735
|
resolveAuth: () => resolveDictationAuth(runtime.signal),
|
|
8784
9736
|
remoteApps,
|
|
9737
|
+
onAudioDiagnostics: (diagnostics) => publish({ type: "lan-playback-diagnostics", diagnostics }),
|
|
8785
9738
|
...takeover ? { takeoverToken: takeover.token } : {},
|
|
8786
9739
|
startConversation: (factory, token) => startVoice(runtimeContext, factory, true, arrival.consume(token))
|
|
8787
9740
|
});
|
|
8788
9741
|
if (events)
|
|
8789
|
-
lan.
|
|
9742
|
+
lan.agentState(working);
|
|
8790
9743
|
});
|
|
8791
9744
|
return lan.urls;
|
|
8792
9745
|
}
|
|
@@ -8796,7 +9749,7 @@ ${tail}
|
|
|
8796
9749
|
if (taskId || runtime || serviceStart)
|
|
8797
9750
|
throw new Error("Stop voice before switching conversation");
|
|
8798
9751
|
if (harness !== value || conversationId !== target) {
|
|
8799
|
-
providerSessionId =
|
|
9752
|
+
providerSessionId = randomUUID5();
|
|
8800
9753
|
contextSummaryCache.clear();
|
|
8801
9754
|
}
|
|
8802
9755
|
harness = value;
|
|
@@ -8836,7 +9789,7 @@ ${tail}
|
|
|
8836
9789
|
lan?.broadcast({ type: "mute", muted });
|
|
8837
9790
|
},
|
|
8838
9791
|
get active() {
|
|
8839
|
-
return Boolean(session || dictation || transferred);
|
|
9792
|
+
return Boolean(session || dictation || transferred || browserAudio);
|
|
8840
9793
|
},
|
|
8841
9794
|
async startDictation(context) {
|
|
8842
9795
|
const requestedEpoch = startEpoch;
|
|
@@ -8844,7 +9797,7 @@ ${tail}
|
|
|
8844
9797
|
await enqueue(async () => {
|
|
8845
9798
|
if (requestedEpoch !== startEpoch)
|
|
8846
9799
|
throw new Error("Dictation startup cancelled");
|
|
8847
|
-
if (session || dictation || lease || transferring || transferred)
|
|
9800
|
+
if (session || dictation || lease || transferring || transferred || browserAudio)
|
|
8848
9801
|
throw new Error("Voice or dictation is already active");
|
|
8849
9802
|
const { runtime } = requireRuntime();
|
|
8850
9803
|
startAbort = new AbortController;
|
|
@@ -8903,7 +9856,7 @@ ${tail}
|
|
|
8903
9856
|
type: "input",
|
|
8904
9857
|
content: text,
|
|
8905
9858
|
whenBusy: "steer",
|
|
8906
|
-
requestId:
|
|
9859
|
+
requestId: randomUUID5()
|
|
8907
9860
|
}, context);
|
|
8908
9861
|
},
|
|
8909
9862
|
async rpc(body) {
|
|
@@ -9064,7 +10017,9 @@ ${tail}
|
|
|
9064
10017
|
get summary() {
|
|
9065
10018
|
return summary;
|
|
9066
10019
|
},
|
|
9067
|
-
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");
|
|
9068
10023
|
if (transport !== "webrtc")
|
|
9069
10024
|
throw new Error("GipPity handoff requires WebRTC; PCM conversion is not available");
|
|
9070
10025
|
if (!options.handoff || transferring || transferred || !session || !peerFactory || !activeConfig || !lease && (!handoffLink || !handoffGrant))
|
|
@@ -9148,7 +10103,7 @@ ${tail}
|
|
|
9148
10103
|
},
|
|
9149
10104
|
async waitForSettled(signal) {
|
|
9150
10105
|
await source.waitForInput(signal);
|
|
9151
|
-
await
|
|
10106
|
+
await awaitWithContext3(conversation.waitForIdle(context), context);
|
|
9152
10107
|
signal.throwIfAborted();
|
|
9153
10108
|
await source.waitForPlaybackEnd(signal);
|
|
9154
10109
|
},
|
|
@@ -9157,6 +10112,19 @@ ${tail}
|
|
|
9157
10112
|
transferred = value;
|
|
9158
10113
|
},
|
|
9159
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
|
+
} : {},
|
|
9160
10128
|
...lan?.hasConversation() ? {
|
|
9161
10129
|
lanTakeover: async (offer, releaseAudio, verify) => {
|
|
9162
10130
|
const server = lan;
|
|
@@ -9195,7 +10163,7 @@ ${tail}
|
|
|
9195
10163
|
transferring = false;
|
|
9196
10164
|
}
|
|
9197
10165
|
},
|
|
9198
|
-
async arrive(channel, continuity, context, transport = "webrtc") {
|
|
10166
|
+
async arrive(channel, continuity, context, transport = "webrtc", reservation) {
|
|
9199
10167
|
if (transport !== "webrtc")
|
|
9200
10168
|
throw new Error("GipPity handoff requires WebRTC; PCM conversion is not available");
|
|
9201
10169
|
const returning = Boolean(transferred && sourceBindings.size && !session && !dictation);
|
|
@@ -9203,7 +10171,6 @@ ${tail}
|
|
|
9203
10171
|
throw new Error("Destination voice is busy or handoff is unauthorized");
|
|
9204
10172
|
if (Buffer.byteLength(continuity) > 64 * 1024)
|
|
9205
10173
|
throw new Error("Voice handoff continuity is oversized");
|
|
9206
|
-
transferring = true;
|
|
9207
10174
|
let remote;
|
|
9208
10175
|
let removeStartupAbort;
|
|
9209
10176
|
let lanCommitted = false;
|
|
@@ -9214,6 +10181,10 @@ ${tail}
|
|
|
9214
10181
|
const previousIncoming = handoffLink;
|
|
9215
10182
|
const previousGrant = handoffGrant;
|
|
9216
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;
|
|
9217
10188
|
try {
|
|
9218
10189
|
await ensureService(context);
|
|
9219
10190
|
const { runtime } = requireRuntime();
|
|
@@ -9228,12 +10199,15 @@ ${tail}
|
|
|
9228
10199
|
const prepared = await prepareSummary(signal);
|
|
9229
10200
|
await resolveAuth(signal);
|
|
9230
10201
|
let lanPreparation;
|
|
10202
|
+
const browserPreparation = reservation && prepareBrowserReservation(reservation, withAbortSignal2(signal, context));
|
|
9231
10203
|
try {
|
|
9232
|
-
if (options.lan && !lan)
|
|
10204
|
+
if (!reservation && options.lan && !lan)
|
|
9233
10205
|
lanPreparation = prepareLanTakeover(options.lan);
|
|
9234
10206
|
} catch {}
|
|
9235
10207
|
const link = new VoiceHandoffLink(channel, {
|
|
9236
10208
|
async request(method, value) {
|
|
10209
|
+
if (method === "browser.verify" && browserPreparation)
|
|
10210
|
+
return browserPreparation.verify(value);
|
|
9237
10211
|
if (method === "session.stop" || method === "session.start") {
|
|
9238
10212
|
if (transferred)
|
|
9239
10213
|
return method === "session.stop" ? transferred.stopCall() : transferred.startCall();
|
|
@@ -9242,9 +10216,9 @@ ${tail}
|
|
|
9242
10216
|
return method === "session.stop" ? selectedCall.stop() : selectedCall.start();
|
|
9243
10217
|
}
|
|
9244
10218
|
if (method === "lan.verify") {
|
|
9245
|
-
if (!lanPreparation
|
|
10219
|
+
if (!lanPreparation)
|
|
9246
10220
|
throw new Error("LAN takeover requires permission for the source listener's port");
|
|
9247
|
-
await
|
|
10221
|
+
await lanPreparation.verify(value, signal);
|
|
9248
10222
|
return;
|
|
9249
10223
|
}
|
|
9250
10224
|
if (method === "session.send" && typeof value === "string")
|
|
@@ -9281,7 +10255,7 @@ ${tail}
|
|
|
9281
10255
|
signal.addEventListener("abort", cancelled, { once: true });
|
|
9282
10256
|
removeStartupAbort = () => signal.removeEventListener("abort", cancelled);
|
|
9283
10257
|
signal.throwIfAborted();
|
|
9284
|
-
link.stage("prepared", lanPreparation ? { lanTakeover: lanPreparation.offer } : undefined);
|
|
10258
|
+
link.stage("prepared", reservation ? { browserTakeover: reservation.identity } : lanPreparation ? { lanTakeover: lanPreparation.offer } : undefined);
|
|
9285
10259
|
const activation = await link.waitFor("activate");
|
|
9286
10260
|
if (!isRecord(activation) || typeof activation["inputMuted"] !== "boolean" || activation["alternateVoice"] !== undefined && typeof activation["alternateVoice"] !== "boolean")
|
|
9287
10261
|
throw new Error("Invalid handoff microphone or voice selection");
|
|
@@ -9308,11 +10282,32 @@ ${continuity}`
|
|
|
9308
10282
|
}
|
|
9309
10283
|
];
|
|
9310
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
|
+
}
|
|
9311
10306
|
if (takeover !== undefined) {
|
|
9312
|
-
if (!lanPreparation
|
|
10307
|
+
if (!lanPreparation)
|
|
9313
10308
|
throw new Error("Invalid LAN takeover activation");
|
|
9314
10309
|
await ensureLan(context, {
|
|
9315
|
-
token: lanPreparation.
|
|
10310
|
+
token: lanPreparation.claim(takeover),
|
|
9316
10311
|
startup: {
|
|
9317
10312
|
settings,
|
|
9318
10313
|
summary: prepared,
|
|
@@ -9392,7 +10387,7 @@ ${continuity}`
|
|
|
9392
10387
|
event: "binding",
|
|
9393
10388
|
data: {
|
|
9394
10389
|
conversationId: runtime.conversationId,
|
|
9395
|
-
model: events?.
|
|
10390
|
+
model: events?.view.docs[AgentDoc.definition.kind]?.model ?? null
|
|
9396
10391
|
}
|
|
9397
10392
|
});
|
|
9398
10393
|
link.notify({
|
|
@@ -9404,6 +10399,8 @@ ${continuity}`
|
|
|
9404
10399
|
try {
|
|
9405
10400
|
channel.close();
|
|
9406
10401
|
} finally {
|
|
10402
|
+
if (reservation)
|
|
10403
|
+
await reservation.cancel().catch(report);
|
|
9407
10404
|
if (returning && !arrivalActivated) {
|
|
9408
10405
|
await arrivedGrant?.release();
|
|
9409
10406
|
if (incoming)
|
|
@@ -9422,7 +10419,129 @@ ${continuity}`
|
|
|
9422
10419
|
}
|
|
9423
10420
|
}
|
|
9424
10421
|
};
|
|
9425
|
-
|
|
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 };
|
|
9426
10545
|
}
|
|
9427
10546
|
function asError2(value) {
|
|
9428
10547
|
return value instanceof Error ? value : new Error(String(value));
|