@proveanything/smartlinks 2.1.18 → 2.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/adminViews.d.ts +19 -0
  2. package/dist/adminViews.js +16 -0
  3. package/dist/api/ai.d.ts +15 -5
  4. package/dist/api/ai.js +15 -9
  5. package/dist/api/aiGuide.d.ts +110 -0
  6. package/dist/api/aiGuide.js +162 -0
  7. package/dist/api/appObjects.d.ts +21 -0
  8. package/dist/api/appObjects.js +33 -1
  9. package/dist/api/authKit.d.ts +37 -1
  10. package/dist/api/authKit.js +51 -0
  11. package/dist/docs/API_SUMMARY.md +510 -40
  12. package/dist/docs/admin-lists-and-pickers.md +140 -0
  13. package/dist/docs/admin-views.md +22 -0
  14. package/dist/docs/app-data-storage.md +277 -276
  15. package/dist/docs/auth-kit.md +872 -741
  16. package/dist/docs/comms.md +686 -644
  17. package/dist/docs/customer-guide.md +70 -0
  18. package/dist/docs/headless-providers.md +112 -112
  19. package/dist/docs/server-functions.md +69 -1
  20. package/dist/docs/ui-utils.md +123 -121
  21. package/dist/docs/user-groups.md +175 -168
  22. package/dist/headless.js +38 -2
  23. package/dist/http.js +4 -0
  24. package/dist/index.d.ts +2 -2
  25. package/dist/live.d.ts +88 -0
  26. package/dist/live.js +357 -0
  27. package/dist/openapi.yaml +888 -34
  28. package/dist/testing/index.d.ts +22 -0
  29. package/dist/testing/index.js +31 -0
  30. package/dist/types/appManifest.d.ts +214 -1
  31. package/dist/types/appOptions.d.ts +32 -0
  32. package/dist/types/appOptions.js +3 -0
  33. package/dist/types/authKit.d.ts +193 -4
  34. package/dist/types/comms.d.ts +41 -2
  35. package/dist/types/headless.d.ts +49 -1
  36. package/dist/types/iframeResponder.d.ts +1 -1
  37. package/dist/types/index.d.ts +1 -0
  38. package/dist/types/index.js +1 -0
  39. package/docs/API_SUMMARY.md +510 -40
  40. package/docs/admin-lists-and-pickers.md +140 -0
  41. package/docs/admin-views.md +22 -0
  42. package/docs/app-data-storage.md +277 -276
  43. package/docs/auth-kit.md +872 -741
  44. package/docs/comms.md +686 -644
  45. package/docs/customer-guide.md +70 -0
  46. package/docs/headless-providers.md +112 -112
  47. package/docs/server-functions.md +69 -1
  48. package/docs/ui-utils.md +123 -121
  49. package/docs/user-groups.md +175 -168
  50. package/openapi.yaml +888 -34
  51. package/package.json +1 -1
  52. package/scripts/doctor.mjs +454 -428
  53. package/scripts/lib/keyed-app-data.mjs +21 -0
package/dist/headless.js CHANGED
@@ -87,6 +87,9 @@ function mismatch(field, value) {
87
87
  case 'datetime':
88
88
  return typeof value === 'string' && !Number.isNaN(Date.parse(value)) ? null : 'expected an ISO date-time';
89
89
  case 'enum':
90
+ // A value list's values are the admin's, so an example can only be checked for being a code.
91
+ if (field.list && !field.options)
92
+ return typeof value === 'string' && value ? null : 'expected a value code (a string)';
90
93
  return (field.options || []).includes(value) ? null : `expected one of ${(field.options || []).join(', ')}`;
91
94
  case 'image':
92
95
  case 'file':
@@ -180,8 +183,16 @@ export function validate(manifest, opts = {}) {
180
183
  err(fat, `unknown type "${f && f.type}" (one of ${[...FIELD_TYPES].join(', ')})`);
181
184
  continue;
182
185
  }
183
- if (f.type === 'enum' && !(f.options && f.options.length))
184
- err(fat, 'an enum needs options');
186
+ if (f.type === 'enum') {
187
+ if (f.list && f.options)
188
+ err(fat, 'an enum has options (fixed) or a list (edited by the admin), not both');
189
+ else if (f.list) {
190
+ if (!(data.lists && data.lists[f.list]))
191
+ err(fat, `"${f.list}" isn't a list in data.lists`);
192
+ }
193
+ else if (!(f.options && f.options.length))
194
+ err(fat, 'an enum needs options, or a list the admin edits');
195
+ }
185
196
  if ((f.type === 'ref' || f.type === 'ref[]') && !(f.to && (typeIds.has(f.to) || PLATFORM_REFS.has(f.to)))) {
186
197
  err(fat, `"to" must name a declared type or product/contact/proof`);
187
198
  }
@@ -190,6 +201,15 @@ export function validate(manifest, opts = {}) {
190
201
  if (f.public && f.zone && f.zone !== 'data')
191
202
  err(fat, `a ${f.zone}-zone field can't be public — only the data zone is readable publicly`);
192
203
  }
204
+ for (const k of ['label', 'sublabel', 'activeField', 'orderField']) {
205
+ const name = type[k];
206
+ if (name !== undefined && !(typeof name === 'string' && name in fields))
207
+ err(`${at}.${k}`, `"${name}" isn't a field`);
208
+ }
209
+ if (type.activeField && fields[type.activeField] && fields[type.activeField].type !== 'boolean')
210
+ err(`${at}.activeField`, 'must name a boolean field');
211
+ if (type.orderField && fields[type.orderField] && fields[type.orderField].type !== 'number')
212
+ err(`${at}.orderField`, 'must name a number field');
193
213
  for (const k of (type.listing && type.listing.sort) || [])
194
214
  if (!(k.replace(/^-/, '') in fields))
195
215
  err(`${at}.listing.sort`, `"${k}" isn't a field`);
@@ -205,6 +225,22 @@ export function validate(manifest, opts = {}) {
205
225
  const get = (type.read && type.read.get) || std.get;
206
226
  recipes[typeId] = Object.assign(Object.assign({ list: (type.read && type.read.list) || std.list }, (get ? { get } : {})), responseShape(type));
207
227
  }
228
+ for (const [listId, list] of Object.entries(data.lists || {})) {
229
+ const at = `data.lists.${listId}`;
230
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(listId))
231
+ err(at, 'list ids are lowercase letters, digits and dashes (e.g. "hold-reasons")');
232
+ if (!list || !list.label)
233
+ err(`${at}.label`, 'say what the list is, e.g. "Hold reasons"');
234
+ const codes = new Set();
235
+ for (const [i, v] of ((list && list.values) || []).entries()) {
236
+ if (!v || typeof v.code !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(v.code))
237
+ err(`${at}.values[${i}]`, 'each value needs a code: letters, digits, dots, dashes');
238
+ else if (codes.has(v.code))
239
+ err(`${at}.values[${i}]`, `"${v.code}" is in the list twice`);
240
+ else
241
+ codes.add(v.code);
242
+ }
243
+ }
208
244
  }
209
245
  // ---- headless
210
246
  if (headless) {
package/dist/http.js CHANGED
@@ -226,6 +226,10 @@ function shouldSkipCache(path) {
226
226
  // `mine` is about one person.
227
227
  if (/\/userGroups?(\/|\?|$)/i.test(path))
228
228
  return true;
229
+ // Pickers: the server caches them and clears them on every save, and a repeat with `version` costs
230
+ // nothing. Cached here as well, a list just saved would look unchanged for a minute.
231
+ if (/\/app\/[^/]+\/options\//i.test(path))
232
+ return true;
229
233
  return false;
230
234
  }
231
235
  /** Evict the oldest (LRU) entry when the cache is at capacity. */
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export * from "./types/index.js";
4
4
  export { iframe } from "./iframe.js";
5
5
  export { readContext } from "./context.js";
6
6
  export * as adminViews from "./adminViews.js";
7
- export type { NavigateRequest, NavigateTarget } from "./adminViews.js";
7
+ export type { NavigateRequest, NavigateTarget, OpenAppRequest } from "./adminViews.js";
8
8
  export { widgetStyleVars, widgetStyleControls, readableOn, WIDGET_STYLE_VARS } from "./widgetStyle.js";
9
9
  export type { WidgetStyling } from "./widgetStyle.js";
10
10
  export type { SmartLinksContext } from "./context.js";
@@ -43,4 +43,4 @@ AdminMobileHostContext, AdminMobileComponentManifest, AdminMobileBundleManifest,
43
43
  MobileAdminBundleManifest, } from './mobile-admin/types.js';
44
44
  export { HostCapabilityUnavailableError, HostPermissionDeniedError, HostTimeoutError, HostCancelledError, } from './mobile-admin/errors.js';
45
45
  export type { NativeCapability, NativeFacade, ShareFacade, ClipboardFacade, HapticImpactStyle, HapticNotificationStyle, HapticsFacade, NetworkStatus, NetworkFacade, DeviceInfo, DeviceFacade, StorageFacade, QrScanOptions, QrFacade, AuthFacade, NfcReadResult, NfcFacade, RfidScanOptions, RfidFacade, EventsFacade, WebSourceMode, WebSourceConfig, WebSourceFacade, } from './native/types.js';
46
- export type { AuthKitUser, UserProfile, ProfileUpdateData, UpdateProfileResponse, SuccessResponse, AuthLoginResponse, AppleLoginOptions, AuthKitErrorCode, RefreshResponse, LogoutResponse, RefreshErrorCode, MagicLinkSendResponse, MagicLinkVerifyResponse, PhoneSendCodeResponse, PhoneVerifyResponse, PasswordResetRequestResponse, VerifyResetTokenResponse, PasswordResetCompleteResponse, EmailVerificationActionResponse, EmailVerifyTokenResponse, VerifyStatus, WhatsAppReplyCta, WhatsAppReplyOptions, WhatsAppContactData, SendWhatsAppRequest, SendWhatsAppResponse, ExchangeWhatsAppSessionResponse, VerifyWhatsAppResponse, WhatsAppStatusResponse, SendSmsVerifyRequest, SendSmsVerifyResponse, VerifySmsResponse, UpsertContactRequest, UpsertContactResponse, AuthKitBrandingConfig, AuthKitConfig, AuthKitConfigInput, AuthKitSecurityConfig, AuthKitIdentity, AuthKitSetIdentityResponse, AuthKitPasswordPolicy, AuthKitSessionPolicy, AuthKitLockoutPolicy, PasswordPolicyErrorCode, LoginSecurityErrorCode, } from './types/authKit.js';
46
+ export type { AuthKitUser, UserProfile, ProfileUpdateData, UpdateProfileResponse, SuccessResponse, AuthLoginResponse, AppleLoginOptions, AuthKitErrorCode, RefreshResponse, LogoutResponse, RefreshErrorCode, MagicLinkSendResponse, MagicLinkVerifyResponse, PhoneSendCodeResponse, PhoneVerifyResponse, PasswordResetRequestResponse, VerifyResetTokenResponse, PasswordResetCompleteResponse, EmailVerificationActionResponse, EmailVerifyTokenResponse, VerifyStatus, WhatsAppReplyCta, WhatsAppReplyOptions, WhatsAppContactData, SendWhatsAppRequest, SendWhatsAppResponse, ExchangeWhatsAppSessionResponse, VerifyWhatsAppResponse, WhatsAppStatusResponse, SendSmsVerifyRequest, SendSmsVerifyResponse, VerifySmsResponse, UpsertContactRequest, UpsertContactResponse, AuthKitBrandingConfig, AuthKitConfig, AuthKitConfigInput, AuthKitSecurityConfig, AuthKitIdentity, AuthKitSetIdentityResponse, AuthKitPasswordPolicy, AuthKitSessionPolicy, AuthKitLockoutPolicy, PasswordPolicyErrorCode, LoginSecurityErrorCode, AuthKitProvider, AuthKitEmailTemplate, AuthKitEmailKind, AuthKitTextKey, AuthKitMfaConfig, AuthKitSchema, AuthKitCheck, AuthKitSettingsResponse, AuthKitSetupRequest, AuthKitSetupResponse, AuthKitEmailPreview, AuthKitSecretLink, } from './types/authKit.js';
package/dist/live.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ export type LiveState = 'idle' | 'connecting' | 'listening' | 'hearing' | 'thinking' | 'speaking' | 'paused' | 'error';
2
+ export type LiveToolHandler = (args: Record<string, unknown>) => Promise<unknown> | unknown;
3
+ /** What SmartLinks returns when it mints a live session. */
4
+ export interface LiveMintReply {
5
+ clientSecret: string;
6
+ expiresAt?: number | null;
7
+ model: string;
8
+ voice?: string | null;
9
+ tools: Array<{
10
+ name: string;
11
+ runs: 'screen' | 'server';
12
+ }>;
13
+ sessionId: string;
14
+ mode?: 'voice' | 'text';
15
+ [key: string]: unknown;
16
+ }
17
+ /** A server tool's answer: `result` goes back to the assistant; anything else is for the page. */
18
+ export interface LiveToolReply {
19
+ result?: unknown;
20
+ [key: string]: unknown;
21
+ }
22
+ export interface LiveEvent {
23
+ kind: 'tool' | 'error' | 'start' | 'stop' | 'reply' | 'pause' | 'resume' | 'handoff';
24
+ sessionId?: string | null;
25
+ tool?: string;
26
+ where?: 'screen' | 'server';
27
+ ms?: number;
28
+ ok?: boolean;
29
+ error?: string;
30
+ detail?: string;
31
+ build?: string;
32
+ }
33
+ export interface LiveEndpoints {
34
+ /** Mint the session (instructions and tools are fixed on the key by SmartLinks). */
35
+ mint: () => Promise<LiveMintReply>;
36
+ /** Run one server tool. */
37
+ tool: (name: string, args: Record<string, unknown>, sessionId: string | null) => Promise<LiveToolReply>;
38
+ /** Log what happened here, into SmartLinks' logs. Fire and forget. */
39
+ event?: (event: LiveEvent) => void;
40
+ }
41
+ export interface LiveOptions {
42
+ endpoints: LiveEndpoints;
43
+ /** 'voice' (default) or 'text'. Text: no microphone, `send` to say something, answers come as captions. */
44
+ mode?: 'voice' | 'text';
45
+ /** The tools that run in the page (open a screen, read it). Everything else runs in SmartLinks. */
46
+ screenTools?: Record<string, LiveToolHandler>;
47
+ onState?: (s: LiveState) => void;
48
+ /** What the assistant is saying or writing, as it goes (replaces the previous caption each turn). */
49
+ onCaption?: (text: string) => void;
50
+ /** A whole reply, once finished. */
51
+ onReply?: (text: string) => void;
52
+ /** A server tool's reply, for the page to act on (cards, screens to open…). */
53
+ onToolReply?: (name: string, reply: LiveToolReply) => void | Promise<void>;
54
+ onError?: (message: string) => void;
55
+ /** The microphone was muted or unmuted (mute / unmute). */
56
+ onMuted?: (muted: boolean) => void;
57
+ /** Names this client in the logs. */
58
+ build?: string;
59
+ }
60
+ export interface LiveHandle {
61
+ stop: () => void;
62
+ /** Stop listening and speaking without ending the session; anything it would say waits for `resume`. */
63
+ pause: () => void;
64
+ resume: () => void;
65
+ /** Stop listening, and only that: the assistant finishes what it is saying, keeps working, and still speaks. */
66
+ mute: () => void;
67
+ unmute: () => void;
68
+ muted: () => boolean;
69
+ /** Stop the sentence it is saying now; it keeps listening. */
70
+ hush: () => void;
71
+ /** Text mode (or voice): give the assistant the person's words and have it answer. */
72
+ send: (text: string) => void;
73
+ /** Tell the assistant something that happened in the page, and have it answer. */
74
+ tell: (what: string) => void;
75
+ /** Give the assistant a message as it is, and have it answer. */
76
+ report: (text: string) => void;
77
+ /** Let the assistant know something without asking it to answer (where the person is now). */
78
+ note: (what: string) => void;
79
+ /** Run one of this session's server tools directly. */
80
+ ask: (name: string, args: Record<string, unknown>) => Promise<unknown>;
81
+ /** The SmartLinks session id (where its history is kept). */
82
+ session: () => string | null;
83
+ state: () => LiveState;
84
+ /** 0..1, how loud the person (listening) or the assistant (speaking) is right now. */
85
+ level: () => number;
86
+ }
87
+ /** Start a live conversation. Resolves once connected (or failed: then it is stopped and onError was told). */
88
+ export declare function startLive(opts: LiveOptions): Promise<LiveHandle>;
package/dist/live.js ADDED
@@ -0,0 +1,357 @@
1
+ // Live conversations with an AI assistant, by voice or by text (browser only).
2
+ //
3
+ // SmartLinks mints a short-lived key with the assistant's instructions and tools fixed on it; the browser
4
+ // then connects straight to the provider's realtime service (WebRTC), so audio never passes through
5
+ // SmartLinks. Tool calls arrive on the data channel: a tool that belongs to the page (open a screen, read
6
+ // what's on it) runs here; anything else runs in SmartLinks through the caller's `tool` endpoint.
7
+ //
8
+ // The same client serves the Studio assistant and the customer guide (`ai.guide.start`): what differs is
9
+ // where a session is minted, where server tools run and where events are logged — the `endpoints`.
10
+ //
11
+ // Voice: microphone in, speech out, captions of what the assistant says. Text: no microphone, the person
12
+ // types (`send`), the assistant answers in text (captions carry it).
13
+ const CALLS_URL = 'https://api.openai.com/v1/realtime/calls';
14
+ /** The service's answers that mean "there was nothing to cancel or clear": not shown as errors. */
15
+ const HARMLESS = /response_cancel_not_active|no active response|output_audio_buffer|nothing to clear/i;
16
+ function meter(ctx, stream) {
17
+ const analyser = ctx.createAnalyser();
18
+ analyser.fftSize = 256;
19
+ ctx.createMediaStreamSource(stream).connect(analyser);
20
+ const buf = new Uint8Array(analyser.frequencyBinCount);
21
+ return () => {
22
+ analyser.getByteTimeDomainData(buf);
23
+ let sum = 0;
24
+ for (const v of buf)
25
+ sum += (v - 128) * (v - 128);
26
+ return Math.min(1, Math.sqrt(sum / buf.length) / 40);
27
+ };
28
+ }
29
+ /** Start a live conversation. Resolves once connected (or failed: then it is stopped and onError was told). */
30
+ export async function startLive(opts) {
31
+ var _a, _b, _c, _d, _e, _f, _g;
32
+ const textMode = opts.mode === 'text';
33
+ const screenTools = opts.screenTools || {};
34
+ const t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
35
+ let stopped = false;
36
+ let state = 'connecting';
37
+ let caption = '';
38
+ let sessionId = null;
39
+ let paused = false;
40
+ let startedAt = null;
41
+ let toolCalls = 0;
42
+ let replies = 0;
43
+ const held = [];
44
+ let replyOwed = false;
45
+ let micTrack = null;
46
+ let micSender = null;
47
+ // A reply is being made (between response.created and response.done): only then is there one to cancel.
48
+ let responding = false;
49
+ let muted = false;
50
+ let micLevel = () => 0;
51
+ let voiceLevel = () => 0;
52
+ const log = (e) => {
53
+ var _a, _b, _c;
54
+ try {
55
+ (_b = (_a = opts.endpoints).event) === null || _b === void 0 ? void 0 : _b.call(_a, Object.assign(Object.assign(Object.assign({}, e), { sessionId: (_c = e.sessionId) !== null && _c !== void 0 ? _c : sessionId }), (opts.build ? { build: opts.build } : {})));
56
+ }
57
+ catch ( /* never in the way */_d) { /* never in the way */ }
58
+ };
59
+ const setState = (s) => {
60
+ var _a;
61
+ if (stopped || state === s || (paused && s !== 'paused'))
62
+ return;
63
+ state = s;
64
+ (_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, s);
65
+ };
66
+ (_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'connecting');
67
+ const pc = new RTCPeerConnection();
68
+ const audio = textMode ? null : new Audio();
69
+ if (audio)
70
+ audio.autoplay = true;
71
+ let mic = null;
72
+ let ctx = null;
73
+ const dc = pc.createDataChannel('oai-events');
74
+ const send = (ev) => { if (dc.readyState === 'open')
75
+ dc.send(JSON.stringify(ev)); };
76
+ const stop = () => {
77
+ var _a;
78
+ if (stopped)
79
+ return;
80
+ stopped = true;
81
+ if (startedAt)
82
+ log({ kind: 'stop', ms: Date.now() - startedAt, detail: `${toolCalls} tool calls, ${replies} replies` });
83
+ try {
84
+ dc.close();
85
+ }
86
+ catch ( /* closed */_b) { /* closed */ }
87
+ try {
88
+ pc.close();
89
+ }
90
+ catch ( /* closed */_c) { /* closed */ }
91
+ mic === null || mic === void 0 ? void 0 : mic.getTracks().forEach((t) => t.stop());
92
+ if (audio)
93
+ audio.srcObject = null;
94
+ void (ctx === null || ctx === void 0 ? void 0 : ctx.close().catch(() => undefined));
95
+ state = 'idle';
96
+ (_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'idle');
97
+ };
98
+ async function runTool(call) {
99
+ var _a;
100
+ const started = Date.now();
101
+ let output;
102
+ let ok = true;
103
+ const screen = screenTools[call.name];
104
+ try {
105
+ const args = call.arguments ? JSON.parse(call.arguments) : {};
106
+ if (screen) {
107
+ output = await screen(args);
108
+ }
109
+ else {
110
+ const reply = await opts.endpoints.tool(call.name, args, sessionId);
111
+ await ((_a = opts.onToolReply) === null || _a === void 0 ? void 0 : _a.call(opts, call.name, reply));
112
+ output = reply.result;
113
+ }
114
+ if (output && typeof output === 'object' && 'error' in output)
115
+ ok = false;
116
+ }
117
+ catch (err) {
118
+ ok = false;
119
+ output = { error: err instanceof Error ? err.message : "That didn't work" };
120
+ }
121
+ toolCalls++;
122
+ const failed = !ok && output && typeof output === 'object' && 'error' in output ? String(output.error) : undefined;
123
+ log(Object.assign({ kind: 'tool', tool: call.name, where: screen ? 'screen' : 'server', ms: Date.now() - started, ok }, (failed ? { error: failed } : {})));
124
+ send({ type: 'conversation.item.create', item: { type: 'function_call_output', call_id: call.call_id, output: JSON.stringify(output !== null && output !== void 0 ? output : {}) } });
125
+ }
126
+ dc.onmessage = (e) => {
127
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
128
+ let ev;
129
+ try {
130
+ ev = JSON.parse(String(e.data));
131
+ }
132
+ catch (_l) {
133
+ return;
134
+ }
135
+ const type = String((_a = ev['type']) !== null && _a !== void 0 ? _a : '');
136
+ if (type === 'input_audio_buffer.speech_started')
137
+ setState('hearing');
138
+ else if (type === 'input_audio_buffer.speech_stopped')
139
+ setState('thinking');
140
+ else if (type === 'response.created') {
141
+ responding = true;
142
+ caption = '';
143
+ if (textMode)
144
+ setState('thinking');
145
+ }
146
+ else if (type === 'output_audio_buffer.started')
147
+ setState('speaking');
148
+ else if (type === 'output_audio_buffer.stopped' || type === 'output_audio_buffer.cleared')
149
+ setState('listening');
150
+ else if (/^response\.(output_audio_transcript|audio_transcript|output_text|text)\.delta$/.test(type)) {
151
+ caption += String((_b = ev['delta']) !== null && _b !== void 0 ? _b : '');
152
+ if (textMode)
153
+ setState('speaking');
154
+ (_c = opts.onCaption) === null || _c === void 0 ? void 0 : _c.call(opts, caption);
155
+ }
156
+ else if (type === 'response.done') {
157
+ responding = false;
158
+ if (caption.trim()) {
159
+ replies++;
160
+ (_d = opts.onReply) === null || _d === void 0 ? void 0 : _d.call(opts, caption.trim());
161
+ log({ kind: 'reply', detail: caption.trim().slice(0, 300) });
162
+ }
163
+ const response = ((_e = ev['response']) !== null && _e !== void 0 ? _e : {});
164
+ const calls = ((_f = response.output) !== null && _f !== void 0 ? _f : []).filter((o) => o['type'] === 'function_call');
165
+ if (calls.length) {
166
+ setState('thinking');
167
+ void Promise.all(calls.map((c) => { var _a, _b, _c; return runTool({ name: String((_a = c['name']) !== null && _a !== void 0 ? _a : ''), call_id: String((_b = c['call_id']) !== null && _b !== void 0 ? _b : ''), arguments: String((_c = c['arguments']) !== null && _c !== void 0 ? _c : '') }); }))
168
+ .then(() => { if (paused)
169
+ replyOwed = true;
170
+ else
171
+ send({ type: 'response.create' }); });
172
+ }
173
+ else if (textMode)
174
+ setState('listening');
175
+ }
176
+ else if (type === 'error') {
177
+ const err = ((_g = ev['error']) !== null && _g !== void 0 ? _g : {});
178
+ const message = String((_h = err['message']) !== null && _h !== void 0 ? _h : 'The assistant hit a problem');
179
+ // "Nothing to cancel" (a pause or a stop between replies) is not a problem: say nothing.
180
+ if (HARMLESS.test(String((_j = err['code']) !== null && _j !== void 0 ? _j : '')) || HARMLESS.test(message))
181
+ return;
182
+ log({ kind: 'error', error: message, detail: 'realtime service' });
183
+ (_k = opts.onError) === null || _k === void 0 ? void 0 : _k.call(opts, message);
184
+ }
185
+ };
186
+ pc.onconnectionstatechange = () => {
187
+ var _a;
188
+ if (stopped)
189
+ return;
190
+ if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected' || pc.connectionState === 'closed') {
191
+ if (paused) {
192
+ log({ kind: 'stop', detail: `ended while paused (${pc.connectionState})` });
193
+ stop();
194
+ return;
195
+ }
196
+ log({ kind: 'error', error: `connection ${pc.connectionState}` });
197
+ (_a = opts.onError) === null || _a === void 0 ? void 0 : _a.call(opts, 'The connection dropped.');
198
+ stop();
199
+ }
200
+ };
201
+ const noop = async () => null;
202
+ try {
203
+ const [mint, stream] = await Promise.all([
204
+ opts.endpoints.mint(),
205
+ textMode ? Promise.resolve(null) : navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } }),
206
+ ]);
207
+ if (stopped) {
208
+ stream === null || stream === void 0 ? void 0 : stream.getTracks().forEach((t) => t.stop());
209
+ return handle();
210
+ }
211
+ mic = stream;
212
+ sessionId = (_b = mint.sessionId) !== null && _b !== void 0 ? _b : null;
213
+ const missing = ((_c = mint.tools) !== null && _c !== void 0 ? _c : []).filter((t) => t.runs === 'screen' && !screenTools[t.name]).map((t) => t.name);
214
+ if (missing.length)
215
+ log({ kind: 'error', error: `this page can't run: ${missing.join(', ')}`, detail: 'client older than the server' });
216
+ if (stream) {
217
+ ctx = new AudioContext();
218
+ micLevel = meter(ctx, stream);
219
+ for (const track of stream.getTracks()) {
220
+ const sender = pc.addTrack(track, stream);
221
+ if (track.kind === 'audio' && !micTrack) {
222
+ micTrack = track;
223
+ micSender = sender;
224
+ }
225
+ }
226
+ pc.ontrack = (e) => {
227
+ const remote = e.streams[0];
228
+ if (!remote || !audio)
229
+ return;
230
+ audio.srcObject = remote;
231
+ if (ctx)
232
+ voiceLevel = meter(ctx, remote);
233
+ };
234
+ }
235
+ else {
236
+ // A typed conversation: nothing to send, nothing to hear, but the call still carries an audio line.
237
+ pc.addTransceiver('audio', { direction: 'recvonly' });
238
+ }
239
+ const offer = await pc.createOffer();
240
+ await pc.setLocalDescription(offer);
241
+ const res = await fetch(CALLS_URL, { method: 'POST', headers: { Authorization: `Bearer ${mint.clientSecret}`, 'Content-Type': 'application/sdp' }, body: (_d = offer.sdp) !== null && _d !== void 0 ? _d : '' });
242
+ if (!res.ok)
243
+ throw new Error(`The assistant's service refused the call (${res.status})`);
244
+ await pc.setRemoteDescription({ type: 'answer', sdp: await res.text() });
245
+ await new Promise((resolve, reject) => {
246
+ if (dc.readyState === 'open')
247
+ return resolve();
248
+ const timer = setTimeout(() => reject(new Error("The assistant's service didn't answer")), 15000);
249
+ dc.onopen = () => { clearTimeout(timer); resolve(); };
250
+ });
251
+ startedAt = Date.now();
252
+ log({ kind: 'start', ms: Math.round((typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0), detail: `${mint.model} ${(_f = (_e = mint.tools) === null || _e === void 0 ? void 0 : _e.length) !== null && _f !== void 0 ? _f : 0} tools ${textMode ? 'text' : 'voice'}` });
253
+ setState('listening');
254
+ }
255
+ catch (err) {
256
+ const denied = typeof DOMException !== 'undefined' && err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'NotFoundError');
257
+ log({ kind: 'error', error: err instanceof Error ? err.message : String(err), detail: denied ? 'microphone' : 'starting' });
258
+ (_g = opts.onError) === null || _g === void 0 ? void 0 : _g.call(opts, denied ? 'I need the microphone to listen. Allow it for this page and try again.' : err instanceof Error ? err.message.replace(/^Error \d+:\s*/, '') : "Couldn't start");
259
+ stop();
260
+ }
261
+ function handle() {
262
+ const say = (text) => send({ type: 'conversation.item.create', item: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] } });
263
+ const answer = (text) => {
264
+ if (stopped)
265
+ return;
266
+ if (paused)
267
+ return void held.push(text);
268
+ say(text);
269
+ send({ type: 'response.create' });
270
+ };
271
+ return {
272
+ stop,
273
+ pause: () => {
274
+ var _a;
275
+ if (stopped || paused || state === 'connecting')
276
+ return;
277
+ paused = true;
278
+ void (micSender === null || micSender === void 0 ? void 0 : micSender.replaceTrack(null).catch(() => undefined));
279
+ send({ type: 'input_audio_buffer.clear' });
280
+ if (responding)
281
+ send({ type: 'response.cancel' });
282
+ if (!textMode && state === 'speaking')
283
+ send({ type: 'output_audio_buffer.clear' });
284
+ if (audio)
285
+ audio.muted = true;
286
+ state = 'paused';
287
+ (_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'paused');
288
+ log({ kind: 'pause' });
289
+ },
290
+ resume: () => {
291
+ var _a;
292
+ if (stopped || !paused)
293
+ return;
294
+ paused = false;
295
+ if (!muted)
296
+ void (micSender === null || micSender === void 0 ? void 0 : micSender.replaceTrack(micTrack).catch(() => undefined));
297
+ if (audio)
298
+ audio.muted = false;
299
+ state = 'listening';
300
+ (_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'listening');
301
+ const waiting = held.splice(0);
302
+ for (const text of waiting)
303
+ say(text);
304
+ if (waiting.length || replyOwed)
305
+ send({ type: 'response.create' });
306
+ replyOwed = false;
307
+ log({ kind: 'resume', detail: waiting.length ? `${waiting.length} message(s) held while paused` : '' });
308
+ },
309
+ mute: () => {
310
+ var _a;
311
+ if (stopped || muted || state === 'connecting' || textMode)
312
+ return;
313
+ muted = true;
314
+ void (micSender === null || micSender === void 0 ? void 0 : micSender.replaceTrack(null).catch(() => undefined));
315
+ send({ type: 'input_audio_buffer.clear' });
316
+ (_a = opts.onMuted) === null || _a === void 0 ? void 0 : _a.call(opts, true);
317
+ log({ kind: 'pause', detail: 'mic muted' });
318
+ },
319
+ unmute: () => {
320
+ var _a;
321
+ if (stopped || !muted)
322
+ return;
323
+ muted = false;
324
+ if (!paused)
325
+ void (micSender === null || micSender === void 0 ? void 0 : micSender.replaceTrack(micTrack).catch(() => undefined));
326
+ (_a = opts.onMuted) === null || _a === void 0 ? void 0 : _a.call(opts, false);
327
+ log({ kind: 'resume', detail: 'mic on' });
328
+ },
329
+ muted: () => muted,
330
+ hush: () => {
331
+ if (stopped)
332
+ return;
333
+ if (responding)
334
+ send({ type: 'response.cancel' });
335
+ if (!textMode && state === 'speaking')
336
+ send({ type: 'output_audio_buffer.clear' });
337
+ },
338
+ send: (text) => { if (text.trim())
339
+ answer(text.trim()); },
340
+ tell: (what) => answer(`[On screen] ${what}`),
341
+ report: (text) => answer(text),
342
+ note: (what) => { if (!stopped)
343
+ say(`[On screen] ${what}`); },
344
+ ask: async (name, args) => {
345
+ var _a;
346
+ if (stopped || !sessionId)
347
+ return noop();
348
+ const reply = await opts.endpoints.tool(name, args, sessionId);
349
+ return (_a = reply.result) !== null && _a !== void 0 ? _a : null;
350
+ },
351
+ session: () => sessionId,
352
+ state: () => state,
353
+ level: () => (state === 'speaking' ? voiceLevel() : !muted && (state === 'hearing' || state === 'listening') ? micLevel() : 0),
354
+ };
355
+ }
356
+ return handle();
357
+ }