create-freeholder 0.2.0-beta.4 → 0.2.0-beta.6
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/dist/template/.changeset/blog-playground-content.md +4 -0
- package/dist/template/.changeset/blog-wordpress-structure.md +6 -0
- package/dist/template/.changeset/managed-preview-assistant.md +4 -0
- package/dist/template/.changeset/native-linux-install.md +6 -0
- package/dist/template/.changeset/public-beta-5.md +4 -0
- package/dist/template/.changeset/public-beta-6.md +4 -0
- package/dist/template/.github/ISSUE_TEMPLATE/bug_report.yml +1 -1
- package/dist/template/.github/workflows/release-tarballs.yml +117 -0
- package/dist/template/AGENTS.md +15 -2
- package/dist/template/Dockerfile +3 -0
- package/dist/template/MASTER.md +114 -11
- package/dist/template/README.md +1 -1
- package/dist/template/app/(admin)/admin/assistant/page.tsx +9 -1
- package/dist/template/app/(admin)/admin/blog/PostSettings.tsx +26 -0
- package/dist/template/app/(admin)/admin/blog/[kind]/page.tsx +53 -0
- package/dist/template/app/(admin)/admin/blog/actions.ts +186 -6
- package/dist/template/app/(admin)/admin/blog/comments/page.tsx +25 -0
- package/dist/template/app/(admin)/admin/blog/page.tsx +21 -5
- package/dist/template/app/(admin)/admin/imports/[id]/page.tsx +2 -0
- package/dist/template/app/(admin)/admin/pages/[id]/page.tsx +3 -0
- package/dist/template/app/(admin)/assistant-actions.ts +13 -6
- package/dist/template/app/(public)/[[...slug]]/ReaderComments.tsx +25 -0
- package/dist/template/app/(public)/[[...slug]]/blog-parts.tsx +153 -0
- package/dist/template/app/(public)/[[...slug]]/comment-actions.ts +16 -0
- package/dist/template/app/(public)/[[...slug]]/page.tsx +182 -18
- package/dist/template/app/api/chat/assistant/call/route.ts +35 -0
- package/dist/template/db/migrations/0061_blog_structure.sql +89 -0
- package/dist/template/db/migrations/0062_blog_reader_comments.sql +24 -0
- package/dist/template/db/migrations/meta/_journal.json +14 -0
- package/dist/template/deploy/README.md +26 -9
- package/dist/template/deploy/blog-wordpress-2026-11-07.md +146 -0
- package/dist/template/deploy/docker-selfhost/.env.example +11 -1
- package/dist/template/deploy/docker-selfhost/README.md +79 -50
- package/dist/template/deploy/docker-selfhost/infra/backup.sh +81 -0
- package/dist/template/deploy/docker-selfhost/infra/compose.https.yml +37 -1
- package/dist/template/deploy/docker-selfhost/infra/compose.yml +37 -1
- package/dist/template/deploy/docker-selfhost/migrate.md +8 -5
- package/dist/template/deploy/docker-selfhost/recipe.yaml +9 -10
- package/dist/template/deploy/docker-selfhost/selfhost.sh +206 -0
- package/dist/template/deploy/docker-selfhost/verify.md +11 -4
- package/dist/template/deploy/f-criteria-matrix.md +89 -0
- package/dist/template/deploy/linux/.env.example +28 -0
- package/dist/template/deploy/linux/README.md +181 -0
- package/dist/template/deploy/linux/freeholder +655 -0
- package/dist/template/deploy/linux/install.sh +173 -0
- package/dist/template/deploy/linux/migrate.md +17 -0
- package/dist/template/deploy/linux/recipe.yaml +50 -0
- package/dist/template/deploy/linux/share/Caddyfile.template +19 -0
- package/dist/template/deploy/linux/share/systemd/freeholder-backup.service +13 -0
- package/dist/template/deploy/linux/share/systemd/freeholder-backup.timer +12 -0
- package/dist/template/deploy/linux/share/systemd/freeholder.service +41 -0
- package/dist/template/deploy/linux/verify.md +22 -0
- package/dist/template/deploy/managed-preview-assistant.md +99 -0
- package/dist/template/eslint.config.mjs +3 -1
- package/dist/template/gitignore.template +1 -0
- package/dist/template/locales/ar.json +85 -6
- package/dist/template/locales/en.json +83 -4
- package/dist/template/locales/es.json +83 -4
- package/dist/template/locales/fr.json +85 -6
- package/dist/template/next.config.ts +2 -0
- package/dist/template/package.json +3 -2
- package/dist/template/packages/cli/package.json +1 -1
- package/dist/template/packages/create-freeholder/package.json +1 -1
- package/dist/template/packages/freeholder-app/package.json +1 -1
- package/dist/template/packages/mobile-app/package.json +1 -1
- package/dist/template/packages/plugin-kit/package.json +1 -1
- package/dist/template/packages/sdk/package.json +1 -1
- package/dist/template/packages/sdk/src/generated.ts +177 -9
- package/dist/template/packages/sdk/src/version.ts +1 -1
- package/dist/template/packages/templates/package.json +1 -1
- package/dist/template/proxy.ts +18 -1
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/NOTICE.txt +117 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/audio-output-processor.js +267 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.js +847 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.wasm +0 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/encoderWorker.min.js +1 -0
- package/dist/template/public/managed-assistant/0.1.10/manifest.json +12 -0
- package/dist/template/public/managed-assistant/0.1.10/pm-ai-duplex-client.js +1376 -0
- package/dist/template/scripts/build-release.d.mts +4 -0
- package/dist/template/scripts/build-release.mjs +171 -0
- package/dist/template/scripts/launch-prepare.mjs +6 -3
- package/dist/template/scripts/license-headers.mjs +3 -0
- package/dist/template/scripts/recipe-matrix.sh +22 -7
- package/dist/template/scripts/verify-wordpress-migration.d.mts +8 -0
- package/dist/template/scripts/verify-wordpress-migration.mjs +105 -0
- package/dist/template/security/adversarial-audit-2026-10-08.md +1 -1
- package/dist/template/src/adapters/ai/types.ts +5 -0
- package/dist/template/src/adapters/paradise/assistant.ts +37 -0
- package/dist/template/src/adapters/paradise/http.ts +4 -3
- package/dist/template/src/adapters/storage/local-mode.ts +54 -0
- package/dist/template/src/adapters/storage/local.ts +53 -26
- package/dist/template/src/core/contract/json-schema.ts +8 -0
- package/dist/template/src/core/demo/playground-inserts.ts +29 -0
- package/dist/template/src/core/demo/playground-policy.ts +9 -0
- package/dist/template/src/core/doctor/index.ts +19 -10
- package/dist/template/src/core/env.ts +8 -1
- package/dist/template/src/core/http/csp.ts +10 -2
- package/dist/template/src/core/http/csrf-client.ts +10 -0
- package/dist/template/src/core/import/service.ts +217 -12
- package/dist/template/src/core/import/wordpress.ts +80 -15
- package/dist/template/src/core/notifications/service.ts +1 -0
- package/dist/template/src/core/retention/registry.ts +2 -0
- package/dist/template/src/core/search/registry.ts +2 -0
- package/dist/template/src/core/seo/feeds.ts +2 -0
- package/dist/template/src/core/seo/jsonld.ts +46 -2
- package/dist/template/src/core/seo/legacy-proxy.ts +53 -0
- package/dist/template/src/core/seo/meta.ts +10 -7
- package/dist/template/src/core/seo/service.ts +14 -1
- package/dist/template/src/core/update/preflight.ts +3 -2
- package/dist/template/src/core/update/release-declaration.json +1 -1
- package/dist/template/src/core/update/service.ts +7 -17
- package/dist/template/src/modules/assistant/contract.ts +1 -1
- package/dist/template/src/modules/assistant/limits.ts +3 -0
- package/dist/template/src/modules/assistant/preview.ts +124 -0
- package/dist/template/src/modules/assistant/provider.ts +7 -0
- package/dist/template/src/modules/assistant/service.ts +21 -5
- package/dist/template/src/modules/cms/blocks/PreviewAssistantCall.tsx +176 -0
- package/dist/template/src/modules/cms/blocks/SiteChatClient.tsx +10 -4
- package/dist/template/src/modules/cms/blocks/surfaces.tsx +10 -0
- package/dist/template/src/modules/cms/blog-comments-schema.ts +27 -0
- package/dist/template/src/modules/cms/blog-comments.ts +111 -0
- package/dist/template/src/modules/cms/blog-schema.ts +146 -0
- package/dist/template/src/modules/cms/blog-service.ts +999 -0
- package/dist/template/src/modules/cms/blog.tsx +245 -25
- package/dist/template/src/modules/cms/manifest.ts +7 -1
- package/dist/template/src/modules/cms/read.ts +18 -0
- package/dist/template/src/modules/cms/service.ts +22 -4
- package/dist/template/src/modules/cms/tables.ts +2 -0
- package/dist/template/src/modules/seed/launch.ts +31 -3
- package/dist/template/tests/browser/blog-structure.spec.ts +69 -0
- package/dist/template/tests/core/agent-launch.test.ts +7 -2
- package/dist/template/tests/core/analytics-consent.test.ts +1 -1
- package/dist/template/tests/core/blog-playground.test.ts +106 -0
- package/dist/template/tests/core/blog-structure-comments.test.ts +166 -0
- package/dist/template/tests/core/client-readiness-security.test.ts +3 -1
- package/dist/template/tests/core/csp.test.ts +1 -1
- package/dist/template/tests/core/deploy-recipe.test.ts +54 -4
- package/dist/template/tests/core/internal-services.test.ts +4 -0
- package/dist/template/tests/core/legacy-redirect-proxy.test.ts +59 -0
- package/dist/template/tests/core/linux-install.test.ts +169 -0
- package/dist/template/tests/core/local-storage-mode.test.ts +29 -0
- package/dist/template/tests/core/locale-routing.test.ts +1 -1
- package/dist/template/tests/core/playground-cache.test.ts +1 -1
- package/dist/template/tests/core/playground.test.ts +3 -3
- package/dist/template/tests/core/preview-assistant-call.test.ts +88 -0
- package/dist/template/tests/core/private-preview-webhooks.test.ts +1 -1
- package/dist/template/tests/core/private-preview.test.ts +1 -1
- package/dist/template/tests/core/proxy-locale.test.ts +1 -1
- package/dist/template/tests/core/sdk-schema.test.ts +20 -0
- package/dist/template/tests/core/seo.test.ts +1 -1
- package/dist/template/tests/core/site-chat-client.test.ts +50 -0
- package/dist/template/tests/core/storage.test.ts +38 -2
- package/dist/template/tests/core/wordpress-import-flow.test.ts +81 -18
- package/dist/template/tests/core/wordpress-import.test.ts +25 -12
- package/dist/template/tests/core/wordpress-migration-verification.test.ts +37 -0
- package/dist/template/tests/modules/preview-assistant.test.ts +164 -0
- package/dist/template-manifest.json +490 -175
- package/package.json +1 -1
|
@@ -0,0 +1,1376 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// Shared PM duplex transport 0.1.10, bundled without product admission or billing.
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
7
|
+
|
|
8
|
+
// client-library/duplex-versions/0.1.10/pm-ai-call-hooks.ts
|
|
9
|
+
function callHookEmitter(hooks, sessionId, now = Date.now) {
|
|
10
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11
|
+
const safe = (run) => {
|
|
12
|
+
try {
|
|
13
|
+
run();
|
|
14
|
+
} catch {
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
state(state) {
|
|
19
|
+
if (seen.has(state) || seen.has("ended")) return;
|
|
20
|
+
seen.add(state);
|
|
21
|
+
const at = now();
|
|
22
|
+
safe(() => hooks?.onState?.(state, { ...sessionId === void 0 ? {} : { sessionId }, at }));
|
|
23
|
+
},
|
|
24
|
+
segment(speaker, text, startedAt, endedAt) {
|
|
25
|
+
const trimmed = text.trim();
|
|
26
|
+
if (hooks?.onTranscriptSegment === void 0 || trimmed.length === 0) return;
|
|
27
|
+
const end = endedAt ?? now();
|
|
28
|
+
safe(() => hooks.onTranscriptSegment?.({ speaker, text: trimmed, startedAt, endedAt: Math.max(startedAt, end), final: true }));
|
|
29
|
+
},
|
|
30
|
+
partial(speaker, text) {
|
|
31
|
+
if (seen.has("ended")) return;
|
|
32
|
+
safe(() => hooks?.onTranscriptPartial?.({ speaker, text }));
|
|
33
|
+
},
|
|
34
|
+
mute(muted) {
|
|
35
|
+
if (hooks?.onMuteChange === void 0) return;
|
|
36
|
+
safe(() => hooks.onMuteChange?.(muted));
|
|
37
|
+
},
|
|
38
|
+
replyUnavailable() {
|
|
39
|
+
if (seen.has("ended")) return;
|
|
40
|
+
safe(() => hooks?.onReplyUnavailable?.({ ...sessionId === void 0 ? {} : { sessionId }, at: now(), code: "no_usable_reply" }));
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// client-library/duplex-versions/0.1.10/pm-ai-call-media.mts
|
|
46
|
+
var PM_AI_CALL_MEDIA_VERSION = "0.1.0";
|
|
47
|
+
var bounded = (value, fallback, min, max) => typeof value === "number" && Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : fallback;
|
|
48
|
+
var FaceFrameMonitor = class {
|
|
49
|
+
constructor(video, options) {
|
|
50
|
+
this.video = video;
|
|
51
|
+
this.options = options;
|
|
52
|
+
__publicField(this, "phase", "starting");
|
|
53
|
+
__publicField(this, "startedAt");
|
|
54
|
+
__publicField(this, "lastFrameAt", null);
|
|
55
|
+
__publicField(this, "firstFrameAfterMs", null);
|
|
56
|
+
__publicField(this, "mediaTime", null);
|
|
57
|
+
__publicField(this, "advancingFrames", 0);
|
|
58
|
+
__publicField(this, "consecutiveFrames", 0);
|
|
59
|
+
__publicField(this, "everLive", false);
|
|
60
|
+
__publicField(this, "closed", false);
|
|
61
|
+
__publicField(this, "frameHandle", null);
|
|
62
|
+
__publicField(this, "decodedFrames", 0);
|
|
63
|
+
__publicField(this, "interval");
|
|
64
|
+
__publicField(this, "now");
|
|
65
|
+
__publicField(this, "readyTimeoutMs");
|
|
66
|
+
__publicField(this, "stallTimeoutMs");
|
|
67
|
+
__publicField(this, "observation");
|
|
68
|
+
this.now = options.now ?? (() => performance.now());
|
|
69
|
+
this.startedAt = this.now();
|
|
70
|
+
this.readyTimeoutMs = bounded(options.readyTimeoutMs, 1e4, 500, 3e4);
|
|
71
|
+
this.stallTimeoutMs = bounded(options.stallTimeoutMs, 750, 200, 5e3);
|
|
72
|
+
this.observation = typeof video.requestVideoFrameCallback === "function" ? "presented_frame_callback" : "decoded_frame_counter";
|
|
73
|
+
this.decodedFrames = this.readDecodedFrames();
|
|
74
|
+
this.interval = setInterval(() => this.tick(), 100);
|
|
75
|
+
this.requestFrame();
|
|
76
|
+
}
|
|
77
|
+
snapshot() {
|
|
78
|
+
return {
|
|
79
|
+
version: PM_AI_CALL_MEDIA_VERSION,
|
|
80
|
+
phase: this.phase,
|
|
81
|
+
advancingFrames: this.advancingFrames,
|
|
82
|
+
firstFrameAfterMs: this.firstFrameAfterMs,
|
|
83
|
+
lastFrameAgeMs: this.lastFrameAt === null ? null : Math.max(0, this.now() - this.lastFrameAt),
|
|
84
|
+
mediaTime: this.mediaTime,
|
|
85
|
+
observation: this.observation
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Remote track ended, call closed, or the owning client disposed the element. */
|
|
89
|
+
stop() {
|
|
90
|
+
if (this.closed) return;
|
|
91
|
+
this.close();
|
|
92
|
+
this.change("ended");
|
|
93
|
+
}
|
|
94
|
+
requestFrame() {
|
|
95
|
+
if (this.closed || this.observation !== "presented_frame_callback") return;
|
|
96
|
+
this.frameHandle = this.video.requestVideoFrameCallback((_now, metadata) => {
|
|
97
|
+
this.frameHandle = null;
|
|
98
|
+
if (this.closed) return;
|
|
99
|
+
if (metadata.width > 0 && metadata.height > 0) this.recordFrame(metadata.mediaTime);
|
|
100
|
+
this.requestFrame();
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
readDecodedFrames() {
|
|
104
|
+
const quality = this.video.getVideoPlaybackQuality?.();
|
|
105
|
+
const total = quality?.totalVideoFrames;
|
|
106
|
+
const dropped = quality?.droppedVideoFrames ?? 0;
|
|
107
|
+
return typeof total === "number" && Number.isFinite(total) && Number.isFinite(dropped) ? Math.max(0, total - dropped) : 0;
|
|
108
|
+
}
|
|
109
|
+
recordFrame(mediaTime) {
|
|
110
|
+
if (!Number.isFinite(mediaTime) || mediaTime < 0 || this.mediaTime !== null && mediaTime <= this.mediaTime) return;
|
|
111
|
+
const now = this.now();
|
|
112
|
+
if (!this.everLive && now - this.startedAt >= this.readyTimeoutMs) {
|
|
113
|
+
this.close();
|
|
114
|
+
this.change("timed_out");
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (this.lastFrameAt !== null && now - this.lastFrameAt > this.stallTimeoutMs) {
|
|
118
|
+
this.consecutiveFrames = 0;
|
|
119
|
+
if (this.phase === "live") this.change("stalled");
|
|
120
|
+
}
|
|
121
|
+
this.mediaTime = mediaTime;
|
|
122
|
+
this.lastFrameAt = now;
|
|
123
|
+
this.firstFrameAfterMs ?? (this.firstFrameAfterMs = Math.max(0, now - this.startedAt));
|
|
124
|
+
this.advancingFrames++;
|
|
125
|
+
this.consecutiveFrames++;
|
|
126
|
+
if (this.consecutiveFrames >= 2) {
|
|
127
|
+
this.everLive = true;
|
|
128
|
+
this.change("live");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
tick() {
|
|
132
|
+
if (this.closed) return;
|
|
133
|
+
if (this.observation === "decoded_frame_counter") {
|
|
134
|
+
const count = this.readDecodedFrames();
|
|
135
|
+
if (count > this.decodedFrames && this.video.readyState >= 2 && this.video.videoWidth > 0 && this.video.videoHeight > 0) {
|
|
136
|
+
this.recordFrame(this.video.currentTime);
|
|
137
|
+
}
|
|
138
|
+
this.decodedFrames = count;
|
|
139
|
+
}
|
|
140
|
+
const now = this.now();
|
|
141
|
+
if (!this.everLive && now - this.startedAt >= this.readyTimeoutMs) {
|
|
142
|
+
this.close();
|
|
143
|
+
this.change("timed_out");
|
|
144
|
+
} else if (this.phase === "live" && this.lastFrameAt !== null && now - this.lastFrameAt > this.stallTimeoutMs) {
|
|
145
|
+
this.consecutiveFrames = 0;
|
|
146
|
+
this.change("stalled");
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
change(phase) {
|
|
150
|
+
if (phase === this.phase) return;
|
|
151
|
+
this.phase = phase;
|
|
152
|
+
this.options.onState(this.snapshot());
|
|
153
|
+
}
|
|
154
|
+
close() {
|
|
155
|
+
this.closed = true;
|
|
156
|
+
clearInterval(this.interval);
|
|
157
|
+
if (this.frameHandle !== null) this.video.cancelVideoFrameCallback?.(this.frameHandle);
|
|
158
|
+
this.frameHandle = null;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// client-library/duplex-versions/0.1.10/pm-ai-duplex-client.ts
|
|
163
|
+
var PM_AI_DUPLEX_CLIENT_VERSION = "0.1.10";
|
|
164
|
+
var duplexCodecBase = "/api/hub/client-library/duplex-codec/";
|
|
165
|
+
var duplexFaceReadyMs = 1e4;
|
|
166
|
+
var duplexFaceRelayReadyMs = 4e3;
|
|
167
|
+
var duplexPreLiveMs = 8e3;
|
|
168
|
+
var duplexFirstAudioMs = 25e3;
|
|
169
|
+
var lipSyncMaxMs = 1e3;
|
|
170
|
+
var lipSyncDefaultMs = 120;
|
|
171
|
+
var lipSyncCrossfadeMs = 200;
|
|
172
|
+
var lipSyncFlushDrainMs = 150;
|
|
173
|
+
var lipSyncFlushRecoverMs = 250;
|
|
174
|
+
var faceAudioDefaultOffsetMs = 200;
|
|
175
|
+
var faceAudioMaxOffsetMs = 500;
|
|
176
|
+
var faceAudioDuckDownMs = 30;
|
|
177
|
+
var faceAudioDuckHoldMs = 200;
|
|
178
|
+
var faceAudioDuckUpMs = 100;
|
|
179
|
+
function parsePairedFaceTimeline(value) {
|
|
180
|
+
const v = asRecord(value);
|
|
181
|
+
if (v?.["version"] !== 1 || v["sample_rate"] !== 16e3 || v["video_fps"] !== 25 || v["paired_audio"] !== true || v["source_alignment"] !== "ordered_sdk_frames_unqualified") return void 0;
|
|
182
|
+
return {
|
|
183
|
+
version: 1,
|
|
184
|
+
sample_rate: 16e3,
|
|
185
|
+
video_fps: 25,
|
|
186
|
+
paired_audio: true,
|
|
187
|
+
source_alignment: "ordered_sdk_frames_unqualified"
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
var duplexDecoderRestartLimit = 1;
|
|
191
|
+
function duplexWorkerErrorReason(worker, kind, afterFirstAudio, restarts) {
|
|
192
|
+
return `${worker}_worker_${kind === "error" ? "error" : "messageerror"}; phase=${afterFirstAudio ? "after_first_audio" : "before_first_audio"}; restarts=${Math.max(0, Math.min(9, Math.trunc(restarts)))}`;
|
|
193
|
+
}
|
|
194
|
+
function duplexDegradeCopy(reason) {
|
|
195
|
+
switch (reason) {
|
|
196
|
+
case "face_unavailable":
|
|
197
|
+
return "Video could not connect. Voice still works.";
|
|
198
|
+
case "face_lost":
|
|
199
|
+
return "Live video dropped. Continuing by voice.";
|
|
200
|
+
case "codec_failed":
|
|
201
|
+
return "This browser could not start live voice. Try another browser, or send a message.";
|
|
202
|
+
case "pod_error":
|
|
203
|
+
return "Trying another connection for this call.";
|
|
204
|
+
default:
|
|
205
|
+
return "The call could not connect. Try again or send a message.";
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function duplexSessionUpdate(grant) {
|
|
209
|
+
return {
|
|
210
|
+
type: "session.update",
|
|
211
|
+
session: {
|
|
212
|
+
instructions: { type: "constant", text: grant.instructions },
|
|
213
|
+
voice: grant.voice,
|
|
214
|
+
allow_recording: false,
|
|
215
|
+
pm_grant: grant
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function parseDuplexMessage(data) {
|
|
220
|
+
if (typeof data !== "string") return void 0;
|
|
221
|
+
try {
|
|
222
|
+
const parsed = JSON.parse(data);
|
|
223
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
224
|
+
} catch {
|
|
225
|
+
return void 0;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
var replyTimingStages = /* @__PURE__ */ new Set([
|
|
229
|
+
"response_created",
|
|
230
|
+
"eager_adopted",
|
|
231
|
+
"confirmed_repeat_text",
|
|
232
|
+
"eager_close_start",
|
|
233
|
+
"eager_close_done",
|
|
234
|
+
"tts_enroll_start",
|
|
235
|
+
"tts_enroll_done",
|
|
236
|
+
"tts_connect_start",
|
|
237
|
+
"tts_ready",
|
|
238
|
+
"generation_stream_entered",
|
|
239
|
+
"llm_request_started",
|
|
240
|
+
"llm_stream_opened",
|
|
241
|
+
"llm_first_content",
|
|
242
|
+
"first_guarded_text",
|
|
243
|
+
"tts_get_start",
|
|
244
|
+
"tts_get_ready",
|
|
245
|
+
"first_text_sent",
|
|
246
|
+
"first_pcm_received",
|
|
247
|
+
"first_pcm_queued",
|
|
248
|
+
"audio_done_queued"
|
|
249
|
+
]);
|
|
250
|
+
var replyTimingMetrics = [
|
|
251
|
+
["response_created", "response-created"],
|
|
252
|
+
["llm_first_content", "llm-first-token"],
|
|
253
|
+
["first_pcm_received", "pcm-first-received-by-worker"],
|
|
254
|
+
["first_pcm_queued", "pcm-first-queued-by-worker"]
|
|
255
|
+
];
|
|
256
|
+
var replyEventId = /^event_[A-Za-z0-9]{21}$/u;
|
|
257
|
+
function createDuplexReplyTimingMetrics(emit) {
|
|
258
|
+
let closed = false;
|
|
259
|
+
let nextTurn = 0;
|
|
260
|
+
const seen = /* @__PURE__ */ new Set();
|
|
261
|
+
let current;
|
|
262
|
+
const invalidate = () => {
|
|
263
|
+
current = void 0;
|
|
264
|
+
};
|
|
265
|
+
return {
|
|
266
|
+
invalidate,
|
|
267
|
+
close() {
|
|
268
|
+
closed = true;
|
|
269
|
+
invalidate();
|
|
270
|
+
seen.clear();
|
|
271
|
+
},
|
|
272
|
+
handle(message) {
|
|
273
|
+
try {
|
|
274
|
+
if (closed) return;
|
|
275
|
+
const type = message["type"];
|
|
276
|
+
if (type === "session.updated" || type === "input_audio_buffer.speech_started" || type === "response.cancelled" || type === "unmute.interrupted_by_vad" || type === "response.done" || type === "response.audio.done") {
|
|
277
|
+
invalidate();
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (type === "response.created") {
|
|
281
|
+
const id = message["event_id"];
|
|
282
|
+
if (typeof id !== "string" || id.length !== 27 || !replyEventId.test(id)) {
|
|
283
|
+
invalidate();
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (current?.eventId === id) return;
|
|
287
|
+
if (seen.has(id) || nextTurn >= 1e4) {
|
|
288
|
+
invalidate();
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
seen.add(id);
|
|
292
|
+
current = { eventId: id, turn: ++nextTurn, observed: {} };
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (type !== "unmute.additional_outputs" || current === void 0) return;
|
|
296
|
+
const probe = asRecord(asRecord(asRecord(message["args"])?.["debug_dict"])?.["reply_timing_v1"]);
|
|
297
|
+
if (probe === void 0 || Object.keys(probe).length !== 3 || Object.keys(probe).some((key) => !["version", "responseEventId", "elapsedMs"].includes(key)) || probe["version"] !== 1 || probe["responseEventId"] !== current.eventId) return;
|
|
298
|
+
const points = asRecord(probe["elapsedMs"]);
|
|
299
|
+
if (points === void 0 || points["response_created"] !== 0 || Object.keys(points).length > replyTimingStages.size || Object.entries(points).some(([stage, value]) => !replyTimingStages.has(stage) || typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 36e5)) return;
|
|
300
|
+
if (points["first_pcm_queued"] !== void 0 && (typeof points["first_pcm_received"] !== "number" || points["first_pcm_queued"] < points["first_pcm_received"])) return;
|
|
301
|
+
if (Object.entries(current.observed).some(([stage, value]) => points[stage] !== value)) return;
|
|
302
|
+
const owner = current;
|
|
303
|
+
const additions = replyTimingMetrics.filter(([stage]) => points[stage] !== void 0 && owner.observed[stage] === void 0);
|
|
304
|
+
owner.observed = { ...points };
|
|
305
|
+
for (const [stage, metricStage] of additions) {
|
|
306
|
+
if (closed || current !== owner) return;
|
|
307
|
+
try {
|
|
308
|
+
const result = emit({ turn: owner.turn, stage: metricStage, clock: "server", elapsedMs: owner.observed[stage] });
|
|
309
|
+
void Promise.resolve(result).catch(() => void 0);
|
|
310
|
+
} catch {
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
} catch {
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
function asRecord(value) {
|
|
319
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
320
|
+
}
|
|
321
|
+
function extractAiCallTranscript(envelope) {
|
|
322
|
+
const outerType = typeof envelope["type"] === "string" ? envelope["type"] : "";
|
|
323
|
+
const frame = asRecord(envelope["data"]) ?? envelope;
|
|
324
|
+
const type = typeof frame["type"] === "string" ? frame["type"] : outerType;
|
|
325
|
+
const message = asRecord(frame["message"]) ?? frame;
|
|
326
|
+
if (frame["interim"] === true || message["interim"] === true) return null;
|
|
327
|
+
const content = message["content"] ?? message["text"] ?? frame["transcript"] ?? frame["text"] ?? envelope["transcript"] ?? envelope["text"];
|
|
328
|
+
const text = typeof content === "string" ? content.trim() : "";
|
|
329
|
+
if (text.length === 0) return null;
|
|
330
|
+
const roleValue = message["role"] ?? frame["role"] ?? envelope["role"];
|
|
331
|
+
const role = typeof roleValue === "string" ? roleValue : "";
|
|
332
|
+
if (type === "user_message" || role === "user") return { role: "you", text };
|
|
333
|
+
if (type === "assistant_message" || role === "assistant") return { role: "them", text };
|
|
334
|
+
if (/transcript|message/iu.test(type)) return { role: role === "user" ? "you" : "them", text };
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
function joinCaptionDelta(line, delta) {
|
|
338
|
+
return line.length === 0 || /^[\s.,!?;:)\]}'’–-]/u.test(delta) ? line + delta : `${line} ${delta}`;
|
|
339
|
+
}
|
|
340
|
+
function createDuplexCaptions(emit, now = Date.now, partial) {
|
|
341
|
+
let you = "";
|
|
342
|
+
let them = "";
|
|
343
|
+
let youAt = 0;
|
|
344
|
+
let themAt = 0;
|
|
345
|
+
const finishYou = () => {
|
|
346
|
+
if (you.trim().length > 0) emit({ role: "you", text: you.trim() }, youAt, now());
|
|
347
|
+
if (you.length > 0) partial?.({ role: "you", text: "" });
|
|
348
|
+
you = "";
|
|
349
|
+
};
|
|
350
|
+
const finishThem = () => {
|
|
351
|
+
if (them.trim().length > 0) emit({ role: "them", text: them.trim() }, themAt, now());
|
|
352
|
+
if (them.length > 0) partial?.({ role: "them", text: "" });
|
|
353
|
+
them = "";
|
|
354
|
+
};
|
|
355
|
+
return {
|
|
356
|
+
handle(message) {
|
|
357
|
+
const type = message["type"];
|
|
358
|
+
const delta = message["delta"];
|
|
359
|
+
if (type === "conversation.item.input_audio_transcription.delta" && typeof delta === "string") {
|
|
360
|
+
finishThem();
|
|
361
|
+
if (you.length === 0) youAt = now();
|
|
362
|
+
you = joinCaptionDelta(you, delta);
|
|
363
|
+
partial?.({ role: "you", text: you });
|
|
364
|
+
} else if (type === "response.text.delta" && typeof delta === "string") {
|
|
365
|
+
finishYou();
|
|
366
|
+
if (them.length === 0) themAt = now();
|
|
367
|
+
them = joinCaptionDelta(them, delta);
|
|
368
|
+
partial?.({ role: "them", text: them });
|
|
369
|
+
} else if (type === "response.text.done" || type === "response.done") {
|
|
370
|
+
finishYou();
|
|
371
|
+
finishThem();
|
|
372
|
+
} else if (type === "user_message" || type === "assistant_message" || asRecord(message["data"]) !== void 0) {
|
|
373
|
+
const turn = extractAiCallTranscript(message);
|
|
374
|
+
if (turn !== null) {
|
|
375
|
+
const at = now();
|
|
376
|
+
emit(turn, at, at);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
flush() {
|
|
381
|
+
finishYou();
|
|
382
|
+
finishThem();
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
function isOggBeginningOfStream(page) {
|
|
387
|
+
return page.length > 5 && page[0] === 79 && page[1] === 103 && page[2] === 103 && page[3] === 83 && (page[5] & 2) !== 0;
|
|
388
|
+
}
|
|
389
|
+
function clampLipSyncMs(lipSyncMs) {
|
|
390
|
+
if (typeof lipSyncMs !== "number" || !Number.isFinite(lipSyncMs)) return lipSyncDefaultMs;
|
|
391
|
+
return Math.min(lipSyncMaxMs, Math.max(0, lipSyncMs));
|
|
392
|
+
}
|
|
393
|
+
function clampFaceAudioOffsetMs(offsetMs) {
|
|
394
|
+
if (typeof offsetMs !== "number" || !Number.isFinite(offsetMs)) return faceAudioDefaultOffsetMs;
|
|
395
|
+
return Math.min(faceAudioMaxOffsetMs, Math.max(0, offsetMs));
|
|
396
|
+
}
|
|
397
|
+
function isDuplexInterruptMessage(type) {
|
|
398
|
+
return type === "input_audio_buffer.speech_started" || type === "response.cancelled";
|
|
399
|
+
}
|
|
400
|
+
function oggStreamHeader(page) {
|
|
401
|
+
if (!isOggBeginningOfStream(page) || page.length < 27) return void 0;
|
|
402
|
+
const segments = page[26];
|
|
403
|
+
if (page.length < 27 + segments) return void 0;
|
|
404
|
+
let length = 27 + segments;
|
|
405
|
+
for (let index = 0; index < segments; index += 1) length += page[27 + index];
|
|
406
|
+
return page.length >= length ? page.slice(0, length) : void 0;
|
|
407
|
+
}
|
|
408
|
+
function createPagePump(send, maxQueued = 3e3) {
|
|
409
|
+
const queue = [];
|
|
410
|
+
let ready = false;
|
|
411
|
+
let muted = false;
|
|
412
|
+
const frame = (audio) => JSON.stringify({ type: "input_audio_buffer.append", audio });
|
|
413
|
+
return {
|
|
414
|
+
page(base64, header) {
|
|
415
|
+
if (muted && !header) return;
|
|
416
|
+
if (!ready) {
|
|
417
|
+
if (queue.length < maxQueued) queue.push(base64);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
send(frame(base64));
|
|
421
|
+
},
|
|
422
|
+
open() {
|
|
423
|
+
ready = true;
|
|
424
|
+
while (queue.length > 0) send(frame(queue.shift()));
|
|
425
|
+
},
|
|
426
|
+
setMuted(next) {
|
|
427
|
+
muted = next;
|
|
428
|
+
},
|
|
429
|
+
queued: () => queue.length
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
function createLipSyncVoiceDelay(ctx, output, sink, lipSyncMs) {
|
|
433
|
+
const targetSec = clampLipSyncMs(lipSyncMs) / 1e3;
|
|
434
|
+
const dry = ctx.createGain();
|
|
435
|
+
const wet = ctx.createGain();
|
|
436
|
+
const bus = ctx.createGain();
|
|
437
|
+
let delay = ctx.createDelay(1.5);
|
|
438
|
+
dry.gain.value = 1;
|
|
439
|
+
wet.gain.value = 0;
|
|
440
|
+
bus.gain.value = 1;
|
|
441
|
+
delay.delayTime.value = targetSec;
|
|
442
|
+
output.connect(dry);
|
|
443
|
+
dry.connect(bus);
|
|
444
|
+
output.connect(delay);
|
|
445
|
+
delay.connect(wet);
|
|
446
|
+
wet.connect(bus);
|
|
447
|
+
bus.connect(sink);
|
|
448
|
+
let connected = true;
|
|
449
|
+
let disposed = false;
|
|
450
|
+
const connectSource = () => {
|
|
451
|
+
if (connected || disposed) return;
|
|
452
|
+
output.connect(dry);
|
|
453
|
+
output.connect(delay);
|
|
454
|
+
connected = true;
|
|
455
|
+
};
|
|
456
|
+
let faceLive = false;
|
|
457
|
+
let wsAudible = true;
|
|
458
|
+
const rampGain = (param, value, now) => {
|
|
459
|
+
param.cancelScheduledValues(now);
|
|
460
|
+
param.setValueAtTime(param.value, now);
|
|
461
|
+
param.linearRampToValueAtTime(value, now + lipSyncCrossfadeMs / 1e3);
|
|
462
|
+
};
|
|
463
|
+
return {
|
|
464
|
+
isFaceLive: () => faceLive,
|
|
465
|
+
isWsAudible: () => wsAudible,
|
|
466
|
+
setFaceLive(live) {
|
|
467
|
+
if (live === faceLive) return;
|
|
468
|
+
faceLive = live;
|
|
469
|
+
const now = ctx.currentTime;
|
|
470
|
+
rampGain(dry.gain, live ? 0 : 1, now);
|
|
471
|
+
rampGain(wet.gain, live ? 1 : 0, now);
|
|
472
|
+
},
|
|
473
|
+
setWsAudible(audible) {
|
|
474
|
+
if (audible === wsAudible) return;
|
|
475
|
+
wsAudible = audible;
|
|
476
|
+
const now = ctx.currentTime;
|
|
477
|
+
rampGain(bus.gain, audible ? 1 : 0, now);
|
|
478
|
+
},
|
|
479
|
+
flush(waitForSourceReset = false) {
|
|
480
|
+
if (disposed) return;
|
|
481
|
+
if (connected) {
|
|
482
|
+
output.disconnect(dry);
|
|
483
|
+
output.disconnect(delay);
|
|
484
|
+
connected = false;
|
|
485
|
+
}
|
|
486
|
+
delay.disconnect();
|
|
487
|
+
delay = ctx.createDelay(1.5);
|
|
488
|
+
delay.delayTime.value = targetSec;
|
|
489
|
+
delay.connect(wet);
|
|
490
|
+
if (!waitForSourceReset) connectSource();
|
|
491
|
+
},
|
|
492
|
+
resumeAfterReset: connectSource,
|
|
493
|
+
disconnect() {
|
|
494
|
+
disposed = true;
|
|
495
|
+
if (connected) {
|
|
496
|
+
try {
|
|
497
|
+
output.disconnect(dry);
|
|
498
|
+
} catch {
|
|
499
|
+
}
|
|
500
|
+
try {
|
|
501
|
+
output.disconnect(delay);
|
|
502
|
+
} catch {
|
|
503
|
+
}
|
|
504
|
+
connected = false;
|
|
505
|
+
}
|
|
506
|
+
try {
|
|
507
|
+
dry.disconnect();
|
|
508
|
+
} catch {
|
|
509
|
+
}
|
|
510
|
+
try {
|
|
511
|
+
wet.disconnect();
|
|
512
|
+
} catch {
|
|
513
|
+
}
|
|
514
|
+
try {
|
|
515
|
+
bus.disconnect();
|
|
516
|
+
} catch {
|
|
517
|
+
}
|
|
518
|
+
try {
|
|
519
|
+
delay.disconnect();
|
|
520
|
+
} catch {
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
function createFaceAudioVoice(ctx, audioTrack, sink, offsetMs) {
|
|
526
|
+
const delay = ctx.createDelay(1);
|
|
527
|
+
delay.delayTime.value = clampFaceAudioOffsetMs(offsetMs) / 1e3;
|
|
528
|
+
const duck = ctx.createGain();
|
|
529
|
+
duck.gain.value = 0;
|
|
530
|
+
const stream = new MediaStream([audioTrack]);
|
|
531
|
+
const source = ctx.createMediaStreamSource(stream);
|
|
532
|
+
source.connect(delay);
|
|
533
|
+
delay.connect(duck);
|
|
534
|
+
duck.connect(sink);
|
|
535
|
+
let active = false;
|
|
536
|
+
let closed = false;
|
|
537
|
+
const player = document.createElement("audio");
|
|
538
|
+
player.hidden = true;
|
|
539
|
+
player.muted = true;
|
|
540
|
+
player.srcObject = stream;
|
|
541
|
+
document.body?.append(player);
|
|
542
|
+
let ready;
|
|
543
|
+
try {
|
|
544
|
+
ready = player.play().then(() => !closed, () => false);
|
|
545
|
+
} catch {
|
|
546
|
+
ready = Promise.resolve(false);
|
|
547
|
+
}
|
|
548
|
+
return {
|
|
549
|
+
ready,
|
|
550
|
+
isActive: () => active,
|
|
551
|
+
setActive(next) {
|
|
552
|
+
if (closed) return;
|
|
553
|
+
if (next === active) return;
|
|
554
|
+
active = next;
|
|
555
|
+
const now = ctx.currentTime;
|
|
556
|
+
duck.gain.cancelScheduledValues(now);
|
|
557
|
+
duck.gain.setValueAtTime(duck.gain.value, now);
|
|
558
|
+
duck.gain.linearRampToValueAtTime(next ? 1 : 0, now + lipSyncCrossfadeMs / 1e3);
|
|
559
|
+
},
|
|
560
|
+
duckVoice() {
|
|
561
|
+
if (!active) return;
|
|
562
|
+
const now = ctx.currentTime;
|
|
563
|
+
const holdUntil = now + faceAudioDuckHoldMs / 1e3;
|
|
564
|
+
duck.gain.cancelScheduledValues(now);
|
|
565
|
+
duck.gain.setValueAtTime(duck.gain.value, now);
|
|
566
|
+
duck.gain.linearRampToValueAtTime(0, now + faceAudioDuckDownMs / 1e3);
|
|
567
|
+
duck.gain.setValueAtTime(0, holdUntil);
|
|
568
|
+
duck.gain.linearRampToValueAtTime(1, holdUntil + faceAudioDuckUpMs / 1e3);
|
|
569
|
+
},
|
|
570
|
+
disconnect() {
|
|
571
|
+
if (closed) return;
|
|
572
|
+
closed = true;
|
|
573
|
+
active = false;
|
|
574
|
+
try {
|
|
575
|
+
player.pause();
|
|
576
|
+
} catch {
|
|
577
|
+
}
|
|
578
|
+
player.srcObject = null;
|
|
579
|
+
player.remove();
|
|
580
|
+
try {
|
|
581
|
+
source.disconnect();
|
|
582
|
+
} catch {
|
|
583
|
+
}
|
|
584
|
+
try {
|
|
585
|
+
delay.disconnect();
|
|
586
|
+
} catch {
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
duck.disconnect();
|
|
590
|
+
} catch {
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
function syncVoicePaths(input) {
|
|
596
|
+
const pending = input.enabled && input.faceLive && input.awaitingRelay === true;
|
|
597
|
+
const useFaceAudio = !pending && input.enabled && input.faceLive && input.hasFaceAudio;
|
|
598
|
+
input.lipSync?.setFaceLive(input.faceLive);
|
|
599
|
+
input.lipSync?.setWsAudible(!useFaceAudio && !pending);
|
|
600
|
+
input.faceAudio?.setActive(useFaceAudio);
|
|
601
|
+
}
|
|
602
|
+
function observeSelectedAudioOutput(ctx, output, sink, eligible, onAudible) {
|
|
603
|
+
const analyser = ctx.createAnalyser();
|
|
604
|
+
analyser.fftSize = 2048;
|
|
605
|
+
const samples = new Float32Array(analyser.fftSize);
|
|
606
|
+
output.connect(analyser);
|
|
607
|
+
analyser.connect(sink);
|
|
608
|
+
let closed = false;
|
|
609
|
+
let observed = false;
|
|
610
|
+
let eligibleSince;
|
|
611
|
+
let notBefore = 0;
|
|
612
|
+
let timer;
|
|
613
|
+
const poll = () => {
|
|
614
|
+
if (closed || observed) return;
|
|
615
|
+
if (ctx.state !== "running" || !eligible()) eligibleSince = void 0;
|
|
616
|
+
else {
|
|
617
|
+
const now = ctx.currentTime;
|
|
618
|
+
eligibleSince ?? (eligibleSince = Math.max(now, notBefore));
|
|
619
|
+
if (now - eligibleSince >= samples.length / ctx.sampleRate) {
|
|
620
|
+
analyser.getFloatTimeDomainData(samples);
|
|
621
|
+
let power = 0;
|
|
622
|
+
for (const value of samples) power += value * value;
|
|
623
|
+
const rms = Math.sqrt(power / samples.length);
|
|
624
|
+
if (Number.isFinite(rms) && rms > 1e-4) {
|
|
625
|
+
observed = true;
|
|
626
|
+
onAudible();
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
timer = globalThis.setTimeout(poll, 20);
|
|
632
|
+
};
|
|
633
|
+
timer = globalThis.setTimeout(poll, 20);
|
|
634
|
+
return {
|
|
635
|
+
reset: (settleMs = 0) => {
|
|
636
|
+
eligibleSince = void 0;
|
|
637
|
+
notBefore = ctx.currentTime + settleMs / 1e3;
|
|
638
|
+
},
|
|
639
|
+
disconnect() {
|
|
640
|
+
if (closed) return;
|
|
641
|
+
closed = true;
|
|
642
|
+
if (timer !== void 0) globalThis.clearTimeout(timer);
|
|
643
|
+
try {
|
|
644
|
+
output.disconnect(analyser);
|
|
645
|
+
} catch {
|
|
646
|
+
}
|
|
647
|
+
try {
|
|
648
|
+
analyser.disconnect();
|
|
649
|
+
} catch {
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
function bytesToBase64(bytes) {
|
|
655
|
+
let binary = "";
|
|
656
|
+
for (let index = 0; index < bytes.length; index += 1) binary += String.fromCharCode(bytes[index]);
|
|
657
|
+
return globalThis.btoa(binary);
|
|
658
|
+
}
|
|
659
|
+
function base64ToBytes(value) {
|
|
660
|
+
try {
|
|
661
|
+
const binary = globalThis.atob(value);
|
|
662
|
+
const bytes = new Uint8Array(binary.length);
|
|
663
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
664
|
+
return bytes;
|
|
665
|
+
} catch {
|
|
666
|
+
return void 0;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
function waitForIce(pc, capMs = 4e3) {
|
|
670
|
+
if (pc.iceGatheringState === "complete") return Promise.resolve();
|
|
671
|
+
return new Promise((resolve) => {
|
|
672
|
+
const done = () => {
|
|
673
|
+
if (pc.iceGatheringState !== "complete") return;
|
|
674
|
+
pc.removeEventListener("icegatheringstatechange", done);
|
|
675
|
+
resolve();
|
|
676
|
+
};
|
|
677
|
+
pc.addEventListener("icegatheringstatechange", done);
|
|
678
|
+
globalThis.setTimeout(resolve, capMs);
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
async function startDuplexCall(started, onTranscript, deps, hooks) {
|
|
682
|
+
const grant = started.duplex;
|
|
683
|
+
const sessionId = started.sessionId;
|
|
684
|
+
if (grant === void 0 || sessionId === void 0) return void 0;
|
|
685
|
+
const emit = callHookEmitter(hooks, sessionId);
|
|
686
|
+
const callerStream = hooks?.localStream;
|
|
687
|
+
const ditto = started.callKind === "video" ? grant.ditto : void 0;
|
|
688
|
+
const codecBase = deps.codecBase ?? duplexCodecBase;
|
|
689
|
+
const faceAudioVoiceEnabled = ditto !== void 0 && deps.faceAudioVoiceEnabled === true;
|
|
690
|
+
const report = (stage, detail, level = "info") => {
|
|
691
|
+
try {
|
|
692
|
+
const result = deps.report(sessionId, stage, detail, level);
|
|
693
|
+
void Promise.resolve(result).catch(() => void 0);
|
|
694
|
+
} catch {
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
const replyMetrics = createDuplexReplyTimingMetrics((metric) => report("call-metrics-v1", JSON.stringify(metric)));
|
|
698
|
+
const faceState = (state) => {
|
|
699
|
+
try {
|
|
700
|
+
deps.onFaceState?.(state);
|
|
701
|
+
} catch {
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
const ENDED = Symbol("call-ended");
|
|
705
|
+
let releaseEnded = () => void 0;
|
|
706
|
+
const ended = new Promise((resolve) => {
|
|
707
|
+
releaseEnded = () => resolve(ENDED);
|
|
708
|
+
});
|
|
709
|
+
const untilEnded = (pending) => Promise.race([pending, ended]);
|
|
710
|
+
let running = true;
|
|
711
|
+
let hardFailure = false;
|
|
712
|
+
let podLive = false;
|
|
713
|
+
let firstAudioOutput = false;
|
|
714
|
+
let faceAudioPlayoutReady = false;
|
|
715
|
+
let faceRelayReady = false;
|
|
716
|
+
let faceRelayTimer;
|
|
717
|
+
let faceFramesLive = false;
|
|
718
|
+
let detachFaceAudioTrack;
|
|
719
|
+
let pairedFaceTimeline;
|
|
720
|
+
let microphoneReady = false;
|
|
721
|
+
let faceSettled = ditto === void 0;
|
|
722
|
+
let faceLive = false;
|
|
723
|
+
let faceEvicted = false;
|
|
724
|
+
let faceAbandoned = false;
|
|
725
|
+
let faceMonitor;
|
|
726
|
+
const faceOfferAbort = new AbortController();
|
|
727
|
+
let muted = false;
|
|
728
|
+
let paused = false;
|
|
729
|
+
let replyOpen = false;
|
|
730
|
+
let replyHasOutput = false;
|
|
731
|
+
let emptyTextDone = false;
|
|
732
|
+
let dropReply = false;
|
|
733
|
+
let dropHeldAudio = () => void 0;
|
|
734
|
+
let turnPhase = "listening";
|
|
735
|
+
let ws;
|
|
736
|
+
let pc;
|
|
737
|
+
let decoder;
|
|
738
|
+
let decoderGeneration = 0;
|
|
739
|
+
let decoderHeader;
|
|
740
|
+
let encoder;
|
|
741
|
+
let micSource;
|
|
742
|
+
let micProcessor;
|
|
743
|
+
let micSink;
|
|
744
|
+
let output;
|
|
745
|
+
let lipSync;
|
|
746
|
+
let faceAudio;
|
|
747
|
+
let gain;
|
|
748
|
+
let audibleOutput;
|
|
749
|
+
let stream;
|
|
750
|
+
const timers = [];
|
|
751
|
+
const captions = createDuplexCaptions((turn, startedAt, endedAt) => {
|
|
752
|
+
onTranscript?.(turn.role === "you" ? `You: ${turn.text}` : turn.text);
|
|
753
|
+
emit.segment(turn.role === "you" ? "member" : "muse", turn.text, startedAt, endedAt);
|
|
754
|
+
}, Date.now, (turn) => emit.partial(turn.role === "you" ? "member" : "muse", turn.text));
|
|
755
|
+
const relayPending = () => faceAudioVoiceEnabled && pairedFaceTimeline !== void 0 && !faceAbandoned && !faceRelayReady;
|
|
756
|
+
const checkLive = () => {
|
|
757
|
+
if (running && podLive && microphoneReady && firstAudioOutput && faceSettled && !relayPending()) emit.state("live");
|
|
758
|
+
};
|
|
759
|
+
const pump = createPagePump((message) => {
|
|
760
|
+
if (ws?.readyState === 1) ws.send(message);
|
|
761
|
+
});
|
|
762
|
+
const stop = () => {
|
|
763
|
+
if (!running) return;
|
|
764
|
+
running = false;
|
|
765
|
+
replyMetrics.close();
|
|
766
|
+
releaseEnded();
|
|
767
|
+
captions.flush();
|
|
768
|
+
emit.state("ended");
|
|
769
|
+
for (const timer of timers) globalThis.clearTimeout(timer);
|
|
770
|
+
audibleOutput?.disconnect();
|
|
771
|
+
detachFaceAudioTrack?.();
|
|
772
|
+
detachFaceAudioTrack = void 0;
|
|
773
|
+
faceMonitor?.stop();
|
|
774
|
+
faceOfferAbort.abort();
|
|
775
|
+
try {
|
|
776
|
+
ws?.close();
|
|
777
|
+
} catch {
|
|
778
|
+
}
|
|
779
|
+
try {
|
|
780
|
+
pc?.close();
|
|
781
|
+
} catch {
|
|
782
|
+
}
|
|
783
|
+
try {
|
|
784
|
+
micProcessor?.disconnect();
|
|
785
|
+
micSource?.disconnect();
|
|
786
|
+
micSink?.disconnect();
|
|
787
|
+
} catch {
|
|
788
|
+
}
|
|
789
|
+
try {
|
|
790
|
+
encoder?.terminate();
|
|
791
|
+
decoder?.terminate();
|
|
792
|
+
} catch {
|
|
793
|
+
}
|
|
794
|
+
try {
|
|
795
|
+
output?.disconnect();
|
|
796
|
+
lipSync?.disconnect();
|
|
797
|
+
faceAudio?.disconnect();
|
|
798
|
+
gain?.disconnect();
|
|
799
|
+
} catch {
|
|
800
|
+
}
|
|
801
|
+
if (callerStream === void 0) stream?.getTracks().forEach((track) => track.stop());
|
|
802
|
+
deps.signal?.removeEventListener("abort", stop);
|
|
803
|
+
try {
|
|
804
|
+
void Promise.resolve(deps.endSession(sessionId)).catch(() => void 0);
|
|
805
|
+
} catch {
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
const fail = (reason, detail) => {
|
|
809
|
+
if (!running) return;
|
|
810
|
+
report(reason, detail, "error");
|
|
811
|
+
onTranscript?.(duplexDegradeCopy(reason));
|
|
812
|
+
hardFailure = true;
|
|
813
|
+
emit.state("failed");
|
|
814
|
+
stop();
|
|
815
|
+
};
|
|
816
|
+
deps.signal?.addEventListener("abort", stop, { once: true });
|
|
817
|
+
if (deps.signal?.aborted) {
|
|
818
|
+
stop();
|
|
819
|
+
return void 0;
|
|
820
|
+
}
|
|
821
|
+
try {
|
|
822
|
+
const ctx = deps.audioContext();
|
|
823
|
+
if (ctx === void 0 || typeof globalThis.AudioWorkletNode !== "function" || typeof globalThis.Worker !== "function" || typeof globalThis.WebSocket !== "function") {
|
|
824
|
+
fail("codec_failed", "audio worklet, worker, websocket, or unlocked audio context unavailable");
|
|
825
|
+
return void 0;
|
|
826
|
+
}
|
|
827
|
+
if (ctx.state === "suspended" && await untilEnded(ctx.resume().catch(() => void 0)) === ENDED) return void 0;
|
|
828
|
+
if (!running) return void 0;
|
|
829
|
+
emit.state("connecting");
|
|
830
|
+
const microphone = callerStream ? Promise.resolve(callerStream) : deps.microphone();
|
|
831
|
+
void microphone.then((late) => {
|
|
832
|
+
if (!running && callerStream === void 0) late?.getTracks().forEach((track) => track.stop());
|
|
833
|
+
}, () => void 0);
|
|
834
|
+
const acquired = await untilEnded(microphone);
|
|
835
|
+
if (acquired === ENDED || !running) return void 0;
|
|
836
|
+
stream = acquired;
|
|
837
|
+
if (stream === void 0) {
|
|
838
|
+
onTranscript?.("Microphone is unavailable. Allow microphone access and try the call again, or type a message.");
|
|
839
|
+
stop();
|
|
840
|
+
return void 0;
|
|
841
|
+
}
|
|
842
|
+
try {
|
|
843
|
+
output = new AudioWorkletNode(ctx, "audio-output-processor-reset-v1");
|
|
844
|
+
} catch {
|
|
845
|
+
if (await untilEnded(ctx.audioWorklet.addModule(`${codecBase}audio-output-processor.js?v=20261021-reset-barrier`)) === ENDED) return void 0;
|
|
846
|
+
if (!running) return void 0;
|
|
847
|
+
output = new AudioWorkletNode(ctx, "audio-output-processor-reset-v1");
|
|
848
|
+
}
|
|
849
|
+
gain = ctx.createGain();
|
|
850
|
+
if (faceAudioVoiceEnabled) {
|
|
851
|
+
audibleOutput = observeSelectedAudioOutput(
|
|
852
|
+
ctx,
|
|
853
|
+
gain,
|
|
854
|
+
ctx.destination,
|
|
855
|
+
() => running && !paused && faceSettled && !relayPending(),
|
|
856
|
+
() => {
|
|
857
|
+
if (!running || paused) return;
|
|
858
|
+
firstAudioOutput = true;
|
|
859
|
+
report("first-audio-output", "selected browser output produced non-silent audio after path selection and pause gain");
|
|
860
|
+
checkLive();
|
|
861
|
+
}
|
|
862
|
+
);
|
|
863
|
+
} else gain.connect(ctx.destination);
|
|
864
|
+
if (ditto !== void 0) {
|
|
865
|
+
lipSync = createLipSyncVoiceDelay(ctx, output, gain, ditto.lip_sync_ms);
|
|
866
|
+
} else {
|
|
867
|
+
output.connect(gain);
|
|
868
|
+
}
|
|
869
|
+
const attachFaceAudio = (track) => {
|
|
870
|
+
if (faceAudio !== void 0 || lipSync === void 0 || pairedFaceTimeline === void 0) return;
|
|
871
|
+
faceAudio = createFaceAudioVoice(ctx, track, gain, 0);
|
|
872
|
+
const attached = faceAudio;
|
|
873
|
+
let playerStarted = false;
|
|
874
|
+
let wasPlayable = false;
|
|
875
|
+
const current = () => running && !faceAbandoned && faceAudio === attached;
|
|
876
|
+
const activate = () => {
|
|
877
|
+
if (!current() || track.readyState === "ended") return;
|
|
878
|
+
if (!track.muted) {
|
|
879
|
+
wasPlayable = true;
|
|
880
|
+
if (playerStarted && initialAudioTimer !== void 0) globalThis.clearTimeout(initialAudioTimer);
|
|
881
|
+
}
|
|
882
|
+
faceAudioPlayoutReady = true;
|
|
883
|
+
if (faceFramesLive) applyFaceState(true);
|
|
884
|
+
};
|
|
885
|
+
const retire = () => {
|
|
886
|
+
if (!current()) return;
|
|
887
|
+
report("face-audio-unavailable", "paired audio ended or lost connectivity; face retired and streamed voice restored", "warn");
|
|
888
|
+
abandonFace();
|
|
889
|
+
};
|
|
890
|
+
const onMute = () => {
|
|
891
|
+
if (wasPlayable) retire();
|
|
892
|
+
};
|
|
893
|
+
track.addEventListener("ended", retire);
|
|
894
|
+
track.addEventListener("mute", onMute);
|
|
895
|
+
track.addEventListener("unmute", activate);
|
|
896
|
+
detachFaceAudioTrack = () => {
|
|
897
|
+
if (initialAudioTimer !== void 0) globalThis.clearTimeout(initialAudioTimer);
|
|
898
|
+
track.removeEventListener("ended", retire);
|
|
899
|
+
track.removeEventListener("mute", onMute);
|
|
900
|
+
track.removeEventListener("unmute", activate);
|
|
901
|
+
};
|
|
902
|
+
const initialAudioTimer = globalThis.setTimeout(() => {
|
|
903
|
+
if (!wasPlayable || !playerStarted) retire();
|
|
904
|
+
}, duplexFaceReadyMs);
|
|
905
|
+
if (track.readyState === "ended") retire();
|
|
906
|
+
else activate();
|
|
907
|
+
void attached.ready.then((ready) => {
|
|
908
|
+
if (!current()) return;
|
|
909
|
+
if (!ready || track.readyState === "ended") {
|
|
910
|
+
retire();
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
playerStarted = true;
|
|
914
|
+
activate();
|
|
915
|
+
report("face-audio-playout", "remote audio player started; shared output graph owns sound");
|
|
916
|
+
});
|
|
917
|
+
};
|
|
918
|
+
const worklet = output;
|
|
919
|
+
let resetGeneration = 0;
|
|
920
|
+
worklet.port.onmessage = (event) => {
|
|
921
|
+
if (event.data?.type === "audio-output-reset") {
|
|
922
|
+
if (!running || event.data.generation !== resetGeneration) return;
|
|
923
|
+
lipSync?.resumeAfterReset();
|
|
924
|
+
worklet.port.postMessage({ type: "resume", generation: resetGeneration });
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
if (faceAudioVoiceEnabled || !running || paused || event.data?.type !== "audio-output-started" || firstAudioOutput) return;
|
|
928
|
+
firstAudioOutput = true;
|
|
929
|
+
report("first-audio-output", "browser worklet produced non-silent output");
|
|
930
|
+
checkLive();
|
|
931
|
+
};
|
|
932
|
+
let decoderRestarts = 0;
|
|
933
|
+
const onDecoderError = (generation, kind, event) => {
|
|
934
|
+
if (!running || generation !== decoderGeneration) return;
|
|
935
|
+
event.preventDefault();
|
|
936
|
+
const reason = duplexWorkerErrorReason("decoder", kind, firstAudioOutput, decoderRestarts);
|
|
937
|
+
report("decoder-error", reason, decoderRestarts < duplexDecoderRestartLimit ? "warn" : "error");
|
|
938
|
+
if (decoderRestarts >= duplexDecoderRestartLimit) {
|
|
939
|
+
fail("codec_failed", `decoder_worker_failed_after_restart; ${reason}`);
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
decoderRestarts += 1;
|
|
943
|
+
try {
|
|
944
|
+
decoder?.terminate();
|
|
945
|
+
} catch {
|
|
946
|
+
}
|
|
947
|
+
startDecoder();
|
|
948
|
+
report("decoder-restart", `decoder worker restarted (${decoderRestarts}/${duplexDecoderRestartLimit}); output graph retained`, "warn");
|
|
949
|
+
};
|
|
950
|
+
const startDecoder = () => {
|
|
951
|
+
decoderGeneration += 1;
|
|
952
|
+
const generation = decoderGeneration;
|
|
953
|
+
const worker = new Worker(`${codecBase}decoderWorker.min.js`);
|
|
954
|
+
decoder = worker;
|
|
955
|
+
worker.onmessage = (event) => {
|
|
956
|
+
if (!running || generation !== decoderGeneration || event.data === null || event.data[0] === void 0) return;
|
|
957
|
+
worklet.port.postMessage({ frame: event.data[0], type: "audio", micDuration: 0 });
|
|
958
|
+
};
|
|
959
|
+
worker.onerror = (event) => onDecoderError(generation, "error", event);
|
|
960
|
+
worker.onmessageerror = (event) => onDecoderError(generation, "messageerror", event);
|
|
961
|
+
worker.postMessage({
|
|
962
|
+
command: "init",
|
|
963
|
+
bufferLength: 960 * ctx.sampleRate / 24e3,
|
|
964
|
+
decoderSampleRate: 24e3,
|
|
965
|
+
outputBufferSampleRate: ctx.sampleRate,
|
|
966
|
+
resampleQuality: 0
|
|
967
|
+
});
|
|
968
|
+
if (decoderHeader !== void 0) worker.postMessage({ command: "decode", pages: decoderHeader.slice() });
|
|
969
|
+
};
|
|
970
|
+
startDecoder();
|
|
971
|
+
const clearInterruptedAudio = () => {
|
|
972
|
+
audibleOutput?.reset(faceAudioDuckHoldMs + faceAudioDuckUpMs);
|
|
973
|
+
decoder?.terminate();
|
|
974
|
+
resetGeneration += 1;
|
|
975
|
+
lipSync?.flush(true);
|
|
976
|
+
worklet.port.postMessage({ type: "reset", generation: resetGeneration });
|
|
977
|
+
faceAudio?.duckVoice();
|
|
978
|
+
startDecoder();
|
|
979
|
+
};
|
|
980
|
+
dropHeldAudio = clearInterruptedAudio;
|
|
981
|
+
let settleFace = () => void 0;
|
|
982
|
+
let faceReadyResolve = () => void 0;
|
|
983
|
+
let faceStartupTimer;
|
|
984
|
+
const applyFaceState = (ok) => {
|
|
985
|
+
if (!running || ok && faceAbandoned) return;
|
|
986
|
+
faceFramesLive = ok;
|
|
987
|
+
if (ok && faceAudioVoiceEnabled && pairedFaceTimeline !== void 0 && !faceAudioPlayoutReady) return;
|
|
988
|
+
const wasLive = faceLive;
|
|
989
|
+
const wasSettled = faceSettled;
|
|
990
|
+
faceSettled = true;
|
|
991
|
+
faceLive = ok;
|
|
992
|
+
faceEvicted = !ok;
|
|
993
|
+
if (faceStartupTimer !== void 0) globalThis.clearTimeout(faceStartupTimer);
|
|
994
|
+
audibleOutput?.reset(lipSyncCrossfadeMs);
|
|
995
|
+
syncVoicePaths({ enabled: faceAudioVoiceEnabled, faceLive: ok, hasFaceAudio: faceAudio !== void 0 && faceAudioPlayoutReady && faceRelayReady, awaitingRelay: relayPending(), lipSync, faceAudio });
|
|
996
|
+
faceState(ok ? relayPending() ? "connecting" : "playing" : "failed");
|
|
997
|
+
if (!ok && (!wasSettled || wasLive)) {
|
|
998
|
+
const reason = wasSettled ? "face_lost" : "face_unavailable";
|
|
999
|
+
report(reason, wasSettled ? "face frames stopped advancing" : "face startup failed", "warn");
|
|
1000
|
+
onTranscript?.(duplexDegradeCopy(reason));
|
|
1001
|
+
}
|
|
1002
|
+
checkLive();
|
|
1003
|
+
faceReadyResolve();
|
|
1004
|
+
};
|
|
1005
|
+
const abandonFace = () => {
|
|
1006
|
+
if (!running || faceAbandoned) return;
|
|
1007
|
+
faceAbandoned = true;
|
|
1008
|
+
faceRelayReady = false;
|
|
1009
|
+
if (faceRelayTimer !== void 0) globalThis.clearTimeout(faceRelayTimer);
|
|
1010
|
+
faceMonitor?.stop();
|
|
1011
|
+
faceOfferAbort.abort();
|
|
1012
|
+
detachFaceAudioTrack?.();
|
|
1013
|
+
detachFaceAudioTrack = void 0;
|
|
1014
|
+
faceAudio?.disconnect();
|
|
1015
|
+
faceAudio = void 0;
|
|
1016
|
+
faceAudioPlayoutReady = false;
|
|
1017
|
+
try {
|
|
1018
|
+
pc?.close();
|
|
1019
|
+
} catch {
|
|
1020
|
+
}
|
|
1021
|
+
applyFaceState(false);
|
|
1022
|
+
};
|
|
1023
|
+
const faceReady = new Promise((resolve) => {
|
|
1024
|
+
faceReadyResolve = resolve;
|
|
1025
|
+
if (ditto === void 0) {
|
|
1026
|
+
resolve();
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
settleFace = (ok) => {
|
|
1030
|
+
if (ok) applyFaceState(true);
|
|
1031
|
+
else abandonFace();
|
|
1032
|
+
};
|
|
1033
|
+
faceStartupTimer = globalThis.setTimeout(() => abandonFace(), duplexFaceReadyMs);
|
|
1034
|
+
timers.push(faceStartupTimer);
|
|
1035
|
+
});
|
|
1036
|
+
if (ditto !== void 0) {
|
|
1037
|
+
void (async () => {
|
|
1038
|
+
const video = deps.videoElement;
|
|
1039
|
+
if (!video) throw new Error("no video surface");
|
|
1040
|
+
video.autoplay = true;
|
|
1041
|
+
video.playsInline = true;
|
|
1042
|
+
video.muted = true;
|
|
1043
|
+
faceState("connecting");
|
|
1044
|
+
const peer = new RTCPeerConnection({ iceServers: started.iceServers ?? [] });
|
|
1045
|
+
pc = peer;
|
|
1046
|
+
const update = () => {
|
|
1047
|
+
if (peer.connectionState === "failed" || peer.iceConnectionState === "failed" || peer.connectionState === "closed" || peer.iceConnectionState === "closed") abandonFace();
|
|
1048
|
+
};
|
|
1049
|
+
peer.addEventListener("connectionstatechange", update);
|
|
1050
|
+
peer.addEventListener("iceconnectionstatechange", update);
|
|
1051
|
+
const remote = new MediaStream();
|
|
1052
|
+
peer.addEventListener("track", (event) => {
|
|
1053
|
+
if (!running || faceAbandoned) return;
|
|
1054
|
+
if (event.track.kind === "audio" && faceAudioVoiceEnabled) attachFaceAudio(event.track);
|
|
1055
|
+
if (event.track.kind !== "video") return;
|
|
1056
|
+
remote.addTrack(event.track);
|
|
1057
|
+
video.srcObject = remote;
|
|
1058
|
+
video.muted = true;
|
|
1059
|
+
void video.play()?.catch(() => void 0);
|
|
1060
|
+
event.track.addEventListener("ended", () => abandonFace());
|
|
1061
|
+
faceMonitor?.stop();
|
|
1062
|
+
faceMonitor = new FaceFrameMonitor(video, {
|
|
1063
|
+
readyTimeoutMs: duplexFaceReadyMs,
|
|
1064
|
+
onState: (observation) => {
|
|
1065
|
+
if (!running || faceAbandoned || observation.phase === "ended") return;
|
|
1066
|
+
report("face-frames", JSON.stringify(observation));
|
|
1067
|
+
if (observation.phase === "live") applyFaceState(true);
|
|
1068
|
+
else if (observation.phase === "stalled") {
|
|
1069
|
+
if (faceAudioVoiceEnabled && pairedFaceTimeline !== void 0) abandonFace();
|
|
1070
|
+
else applyFaceState(false);
|
|
1071
|
+
} else if (observation.phase === "timed_out") abandonFace();
|
|
1072
|
+
}
|
|
1073
|
+
});
|
|
1074
|
+
});
|
|
1075
|
+
peer.addTransceiver("video", { direction: "recvonly" });
|
|
1076
|
+
peer.addTransceiver("audio", { direction: "recvonly" });
|
|
1077
|
+
const offer = await peer.createOffer();
|
|
1078
|
+
if (!running || faceAbandoned) return;
|
|
1079
|
+
await peer.setLocalDescription(offer);
|
|
1080
|
+
await waitForIce(peer);
|
|
1081
|
+
if (!running || faceAbandoned) return;
|
|
1082
|
+
const offered = Date.now();
|
|
1083
|
+
const answer = await fetch(ditto.offer_url, {
|
|
1084
|
+
signal: faceOfferAbort.signal,
|
|
1085
|
+
method: "POST",
|
|
1086
|
+
headers: { "content-type": "application/json" },
|
|
1087
|
+
body: JSON.stringify({
|
|
1088
|
+
sdp: peer.localDescription?.sdp,
|
|
1089
|
+
type: peer.localDescription?.type,
|
|
1090
|
+
session_id: ditto.session_id,
|
|
1091
|
+
...ditto.source_url === void 0 ? {} : { source: ditto.source_url },
|
|
1092
|
+
...ditto.sig === void 0 ? {} : { sig: ditto.sig, exp: ditto.exp }
|
|
1093
|
+
})
|
|
1094
|
+
});
|
|
1095
|
+
report("face-offer", `HTTP ${answer.status} in ${Date.now() - offered}ms`, answer.ok ? "info" : "error");
|
|
1096
|
+
if (!answer.ok) throw new Error(`face offer HTTP ${answer.status}`);
|
|
1097
|
+
const body = await answer.json();
|
|
1098
|
+
pairedFaceTimeline = parsePairedFaceTimeline(body.media_timeline);
|
|
1099
|
+
if (faceAudioVoiceEnabled) report("face-media-timeline", pairedFaceTimeline ? "paired timeline v1; zero additional audio hold; device alignment unqualified" : "worker has no supported paired timeline; streamed voice retained", pairedFaceTimeline ? "info" : "warn");
|
|
1100
|
+
if (faceAudioVoiceEnabled && pairedFaceTimeline === void 0) throw new Error("paired worker timeline unavailable");
|
|
1101
|
+
if (body.sdp === void 0) throw new Error("face answer had no SDP");
|
|
1102
|
+
if (!running || faceAbandoned) return;
|
|
1103
|
+
await peer.setRemoteDescription({ type: body.type ?? "answer", sdp: body.sdp });
|
|
1104
|
+
})().catch((error) => {
|
|
1105
|
+
if (!running || faceAbandoned) return;
|
|
1106
|
+
report("face-failed", error instanceof Error ? error.message : String(error), "warn");
|
|
1107
|
+
settleFace(false);
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
let attempts = 0;
|
|
1111
|
+
let sessionSent = false;
|
|
1112
|
+
const openSocket = () => {
|
|
1113
|
+
attempts += 1;
|
|
1114
|
+
replyMetrics.invalidate();
|
|
1115
|
+
const socket = new WebSocket(grant.ws_url, ["realtime"]);
|
|
1116
|
+
ws = socket;
|
|
1117
|
+
socket.onopen = () => {
|
|
1118
|
+
void faceReady.then(() => {
|
|
1119
|
+
if (!running || ws !== socket || socket.readyState !== 1) return;
|
|
1120
|
+
socket.send(JSON.stringify(duplexSessionUpdate(grant)));
|
|
1121
|
+
sessionSent = true;
|
|
1122
|
+
if (relayPending()) {
|
|
1123
|
+
faceRelayTimer = globalThis.setTimeout(() => {
|
|
1124
|
+
if (!running || ws !== socket || !relayPending()) return;
|
|
1125
|
+
report("face-relay-timeout", "voice-to-face relay did not confirm readiness; voice retained", "warn");
|
|
1126
|
+
abandonFace();
|
|
1127
|
+
}, duplexFaceRelayReadyMs);
|
|
1128
|
+
timers.push(faceRelayTimer);
|
|
1129
|
+
}
|
|
1130
|
+
pump.open();
|
|
1131
|
+
});
|
|
1132
|
+
};
|
|
1133
|
+
socket.onmessage = (event) => {
|
|
1134
|
+
if (!running || ws !== socket) return;
|
|
1135
|
+
const message = parseDuplexMessage(event.data);
|
|
1136
|
+
if (message === void 0) return;
|
|
1137
|
+
if (podLive && !paused && (!dropReply || message["type"] === "response.created")) replyMetrics.handle(message);
|
|
1138
|
+
else replyMetrics.invalidate();
|
|
1139
|
+
const type = message["type"];
|
|
1140
|
+
if (type === "unmute.face_relay") {
|
|
1141
|
+
if (ditto === void 0 || faceAbandoned || message["version"] !== 1 || message["session_id"] !== ditto.session_id) return;
|
|
1142
|
+
if (message["state"] === "failed") {
|
|
1143
|
+
report("face-relay-failed", "voice-to-face relay stopped; face retired and voice restored", "warn");
|
|
1144
|
+
abandonFace();
|
|
1145
|
+
} else if (message["state"] === "ready" && faceAudioVoiceEnabled && pairedFaceTimeline !== void 0) {
|
|
1146
|
+
faceRelayReady = true;
|
|
1147
|
+
if (faceRelayTimer !== void 0) globalThis.clearTimeout(faceRelayTimer);
|
|
1148
|
+
if (faceFramesLive) applyFaceState(true);
|
|
1149
|
+
}
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
if (type === "response.created" || type === "input_audio_buffer.speech_started" || type === "response.cancelled") {
|
|
1153
|
+
replyHasOutput = false;
|
|
1154
|
+
emptyTextDone = false;
|
|
1155
|
+
}
|
|
1156
|
+
if (type === "response.audio.delta" || type === "response.text.delta" && typeof message["delta"] === "string" && message["delta"].length > 0) {
|
|
1157
|
+
replyHasOutput = true;
|
|
1158
|
+
emptyTextDone = false;
|
|
1159
|
+
}
|
|
1160
|
+
if (type === "response.text.done") {
|
|
1161
|
+
emptyTextDone = replyOpen && !replyHasOutput && message["text"] === "";
|
|
1162
|
+
}
|
|
1163
|
+
if (type === "response.audio.done" && emptyTextDone && !replyHasOutput) {
|
|
1164
|
+
if (!paused && !dropReply) emit.replyUnavailable();
|
|
1165
|
+
turnPhase = "listening";
|
|
1166
|
+
replyOpen = false;
|
|
1167
|
+
dropReply = false;
|
|
1168
|
+
emptyTextDone = false;
|
|
1169
|
+
}
|
|
1170
|
+
if (type === "response.audio.delta" && relayPending()) abandonFace();
|
|
1171
|
+
if (type === "input_audio_buffer.speech_stopped" || type === "response.created" || type === "response.text.delta") {
|
|
1172
|
+
turnPhase = "thinking";
|
|
1173
|
+
} else if (type === "input_audio_buffer.speech_started" || type === "response.cancelled" || type === "unmute.interrupted_by_vad" || type === "response.done") {
|
|
1174
|
+
turnPhase = "listening";
|
|
1175
|
+
}
|
|
1176
|
+
if (type === "response.created" || type === "response.audio.delta" || type === "response.text.delta") {
|
|
1177
|
+
if (type === "response.created" && !paused) dropReply = false;
|
|
1178
|
+
replyOpen = true;
|
|
1179
|
+
} else if (type === "response.done" || type === "response.cancelled" || type === "input_audio_buffer.speech_started") {
|
|
1180
|
+
const dropped = paused || dropReply;
|
|
1181
|
+
replyOpen = false;
|
|
1182
|
+
dropReply = false;
|
|
1183
|
+
if (dropped && type !== "input_audio_buffer.speech_started") return;
|
|
1184
|
+
}
|
|
1185
|
+
if ((paused || dropReply) && (type === "response.audio.delta" || type === "response.text.delta" || type === "response.text.done" || extractAiCallTranscript(message)?.role === "them")) {
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
if (type === "session.updated") {
|
|
1189
|
+
if (!podLive) {
|
|
1190
|
+
report("session-updated", `live after ${attempts} attempt(s)`);
|
|
1191
|
+
timers.push(globalThis.setTimeout(() => {
|
|
1192
|
+
if (running && !firstAudioOutput) fail("pre_live_timeout", `no reply audio within ${duplexFirstAudioMs}ms`);
|
|
1193
|
+
}, duplexFirstAudioMs));
|
|
1194
|
+
}
|
|
1195
|
+
podLive = true;
|
|
1196
|
+
checkLive();
|
|
1197
|
+
} else if (type === "response.audio.delta" && typeof message["delta"] === "string") {
|
|
1198
|
+
const bytes = base64ToBytes(message["delta"]);
|
|
1199
|
+
if (bytes === void 0 || decoder === void 0) return;
|
|
1200
|
+
turnPhase = "speaking";
|
|
1201
|
+
decoderHeader ?? (decoderHeader = oggStreamHeader(bytes));
|
|
1202
|
+
decoder.postMessage({ command: "decode", pages: bytes }, [bytes.buffer]);
|
|
1203
|
+
} else if (type === "unmute.interrupted_by_vad" || isDuplexInterruptMessage(type)) {
|
|
1204
|
+
clearInterruptedAudio();
|
|
1205
|
+
} else if (type === "error") {
|
|
1206
|
+
const detail = asRecord(message["error"])?.["message"];
|
|
1207
|
+
if (typeof detail === "string" && /^Looking for the resources, expect some latency\.?$/i.test(detail.trim())) {
|
|
1208
|
+
report("resource-wait", "voice resources are loading", "warn");
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
fail("pod_error", typeof detail === "string" ? detail.slice(0, 200) : "voice session error");
|
|
1212
|
+
} else {
|
|
1213
|
+
captions.handle(message);
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
socket.onclose = () => {
|
|
1217
|
+
if (!running || ws !== socket) return;
|
|
1218
|
+
if (!podLive && !sessionSent && attempts < 2) {
|
|
1219
|
+
timers.push(globalThis.setTimeout(() => {
|
|
1220
|
+
if (running) openSocket();
|
|
1221
|
+
}, 400));
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
if (!podLive) {
|
|
1225
|
+
fail("ws_failed", "voice socket closed before the session went live");
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
report("socket-closed", "voice socket closed", "warn");
|
|
1229
|
+
onTranscript?.("The call ended.");
|
|
1230
|
+
stop();
|
|
1231
|
+
};
|
|
1232
|
+
};
|
|
1233
|
+
openSocket();
|
|
1234
|
+
timers.push(globalThis.setTimeout(() => {
|
|
1235
|
+
if (running && !podLive) fail("pre_live_timeout", `no session.updated within ${duplexPreLiveMs + (ditto === void 0 ? 0 : duplexFaceReadyMs)}ms`);
|
|
1236
|
+
}, duplexPreLiveMs + (ditto === void 0 ? 0 : duplexFaceReadyMs)));
|
|
1237
|
+
if (typeof started.maxSeconds === "number" && started.maxSeconds > 0) {
|
|
1238
|
+
timers.push(globalThis.setTimeout(() => {
|
|
1239
|
+
if (!running) return;
|
|
1240
|
+
report("free-time", "granted seconds used up");
|
|
1241
|
+
stop();
|
|
1242
|
+
}, started.maxSeconds * 1e3 + 2e3));
|
|
1243
|
+
}
|
|
1244
|
+
const encoderWorker = new Worker(`${codecBase}encoderWorker.min.js`);
|
|
1245
|
+
encoder = encoderWorker;
|
|
1246
|
+
const onEncoderError = (kind, event) => {
|
|
1247
|
+
if (!running || encoder !== encoderWorker) return;
|
|
1248
|
+
event.preventDefault();
|
|
1249
|
+
const reason = duplexWorkerErrorReason("encoder", kind, firstAudioOutput, 0);
|
|
1250
|
+
report("encoder-error", reason, "error");
|
|
1251
|
+
fail("codec_failed", `encoder_worker_failed; ${reason}`);
|
|
1252
|
+
};
|
|
1253
|
+
encoderWorker.onerror = (event) => onEncoderError("error", event);
|
|
1254
|
+
encoderWorker.onmessageerror = (event) => onEncoderError("messageerror", event);
|
|
1255
|
+
const encoderReady = new Promise((resolve, reject) => {
|
|
1256
|
+
const timeout = globalThis.setTimeout(() => reject(new Error("encoder did not start")), 1e4);
|
|
1257
|
+
timers.push(timeout);
|
|
1258
|
+
encoderWorker.onmessage = (event) => {
|
|
1259
|
+
const data = event.data;
|
|
1260
|
+
if (data.message === "ready") {
|
|
1261
|
+
globalThis.clearTimeout(timeout);
|
|
1262
|
+
resolve();
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
if (data.page instanceof Uint8Array && running) pump.page(bytesToBase64(data.page), isOggBeginningOfStream(data.page) || data.samplePosition === 0);
|
|
1266
|
+
};
|
|
1267
|
+
});
|
|
1268
|
+
encoderWorker.postMessage({
|
|
1269
|
+
command: "init",
|
|
1270
|
+
originalSampleRate: ctx.sampleRate,
|
|
1271
|
+
encoderSampleRate: 24e3,
|
|
1272
|
+
encoderFrameSize: 20,
|
|
1273
|
+
maxFramesPerPage: 2,
|
|
1274
|
+
numberOfChannels: 1,
|
|
1275
|
+
resampleQuality: 3,
|
|
1276
|
+
encoderComplexity: 0,
|
|
1277
|
+
encoderApplication: 2049,
|
|
1278
|
+
streamPages: true
|
|
1279
|
+
});
|
|
1280
|
+
if (await untilEnded(encoderReady) === ENDED) return void 0;
|
|
1281
|
+
if (await untilEnded(faceReady) === ENDED) return void 0;
|
|
1282
|
+
if (!running) return void 0;
|
|
1283
|
+
encoderWorker.postMessage({ command: "getHeaderPages" });
|
|
1284
|
+
micSource = ctx.createMediaStreamSource(stream);
|
|
1285
|
+
micProcessor = ctx.createScriptProcessor(2048, 1, 1);
|
|
1286
|
+
micSink = ctx.createGain();
|
|
1287
|
+
micSink.gain.value = 0;
|
|
1288
|
+
micProcessor.onaudioprocess = (event) => {
|
|
1289
|
+
if (!running) return;
|
|
1290
|
+
encoderWorker.postMessage({ command: "encode", buffers: [new Float32Array(event.inputBuffer.getChannelData(0))] });
|
|
1291
|
+
};
|
|
1292
|
+
micSource.connect(micProcessor);
|
|
1293
|
+
micProcessor.connect(micSink);
|
|
1294
|
+
micSink.connect(ctx.destination);
|
|
1295
|
+
microphoneReady = true;
|
|
1296
|
+
checkLive();
|
|
1297
|
+
try {
|
|
1298
|
+
deps.onAttached?.(ditto === void 0 ? "voice" : "video");
|
|
1299
|
+
} catch {
|
|
1300
|
+
}
|
|
1301
|
+
} catch (error) {
|
|
1302
|
+
fail("codec_failed", error instanceof Error ? error.message : String(error));
|
|
1303
|
+
return void 0;
|
|
1304
|
+
}
|
|
1305
|
+
return {
|
|
1306
|
+
sessionId,
|
|
1307
|
+
callKind: ditto === void 0 ? "voice" : "video",
|
|
1308
|
+
stack: "ditto-duplex",
|
|
1309
|
+
...started.fallbackReason === void 0 ? {} : { fallbackReason: started.fallbackReason },
|
|
1310
|
+
...started.contentPolicy === void 0 ? {} : { contentPolicy: started.contentPolicy },
|
|
1311
|
+
// The free clock starts at the first reply audio, after the face has shown or bowed out.
|
|
1312
|
+
isReady: () => running && podLive && microphoneReady && firstAudioOutput && faceSettled && !relayPending(),
|
|
1313
|
+
failed: () => hardFailure,
|
|
1314
|
+
degradedToVoice: () => faceEvicted,
|
|
1315
|
+
turnState: () => turnPhase,
|
|
1316
|
+
setMuted: (next) => {
|
|
1317
|
+
muted = next;
|
|
1318
|
+
pump.setMuted(muted || paused);
|
|
1319
|
+
emit.mute(next);
|
|
1320
|
+
},
|
|
1321
|
+
setPaused: (next) => {
|
|
1322
|
+
if (!running || next === paused) return;
|
|
1323
|
+
paused = next;
|
|
1324
|
+
pump.setMuted(muted || paused);
|
|
1325
|
+
if (gain !== void 0) gain.gain.value = paused ? 0 : 1;
|
|
1326
|
+
if (paused) {
|
|
1327
|
+
replyMetrics.invalidate();
|
|
1328
|
+
captions.flush();
|
|
1329
|
+
turnPhase = "listening";
|
|
1330
|
+
} else {
|
|
1331
|
+
dropReply = replyOpen;
|
|
1332
|
+
}
|
|
1333
|
+
dropHeldAudio();
|
|
1334
|
+
report("pause", paused ? "caller paused the call; microphone and reply audio held" : "caller resumed the call");
|
|
1335
|
+
},
|
|
1336
|
+
stop
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
export {
|
|
1340
|
+
PM_AI_DUPLEX_CLIENT_VERSION,
|
|
1341
|
+
clampFaceAudioOffsetMs,
|
|
1342
|
+
clampLipSyncMs,
|
|
1343
|
+
createDuplexCaptions,
|
|
1344
|
+
createDuplexReplyTimingMetrics,
|
|
1345
|
+
createFaceAudioVoice,
|
|
1346
|
+
createLipSyncVoiceDelay,
|
|
1347
|
+
createPagePump,
|
|
1348
|
+
duplexCodecBase,
|
|
1349
|
+
duplexDecoderRestartLimit,
|
|
1350
|
+
duplexDegradeCopy,
|
|
1351
|
+
duplexFaceReadyMs,
|
|
1352
|
+
duplexFaceRelayReadyMs,
|
|
1353
|
+
duplexFirstAudioMs,
|
|
1354
|
+
duplexPreLiveMs,
|
|
1355
|
+
duplexSessionUpdate,
|
|
1356
|
+
duplexWorkerErrorReason,
|
|
1357
|
+
extractAiCallTranscript,
|
|
1358
|
+
faceAudioDefaultOffsetMs,
|
|
1359
|
+
faceAudioDuckDownMs,
|
|
1360
|
+
faceAudioDuckHoldMs,
|
|
1361
|
+
faceAudioDuckUpMs,
|
|
1362
|
+
faceAudioMaxOffsetMs,
|
|
1363
|
+
isDuplexInterruptMessage,
|
|
1364
|
+
isOggBeginningOfStream,
|
|
1365
|
+
joinCaptionDelta,
|
|
1366
|
+
lipSyncCrossfadeMs,
|
|
1367
|
+
lipSyncDefaultMs,
|
|
1368
|
+
lipSyncFlushDrainMs,
|
|
1369
|
+
lipSyncFlushRecoverMs,
|
|
1370
|
+
lipSyncMaxMs,
|
|
1371
|
+
observeSelectedAudioOutput,
|
|
1372
|
+
parseDuplexMessage,
|
|
1373
|
+
parsePairedFaceTimeline,
|
|
1374
|
+
startDuplexCall,
|
|
1375
|
+
syncVoicePaths
|
|
1376
|
+
};
|