@proveanything/smartlinks 2.1.17 → 2.1.19
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/adminViews.d.ts +104 -0
- package/dist/adminViews.js +275 -0
- package/dist/api/ai.d.ts +15 -5
- package/dist/api/ai.js +15 -9
- package/dist/api/aiGuide.d.ts +108 -0
- package/dist/api/aiGuide.js +161 -0
- package/dist/api/appObjects.d.ts +21 -0
- package/dist/api/appObjects.js +33 -1
- package/dist/api/authKit.d.ts +37 -1
- package/dist/api/authKit.js +51 -0
- package/dist/api/index.d.ts +2 -0
- package/dist/api/index.js +2 -0
- package/dist/api/operations.d.ts +36 -0
- package/dist/api/operations.js +56 -0
- package/dist/api/order.d.ts +12 -1
- package/dist/api/order.js +15 -0
- package/dist/api/userGroups.d.ts +78 -0
- package/dist/api/userGroups.js +124 -0
- package/dist/docs/API_SUMMARY.md +1111 -80
- package/dist/docs/admin-lists-and-pickers.md +140 -0
- package/dist/docs/admin-views.md +147 -0
- package/dist/docs/app-data-storage.md +277 -276
- package/dist/docs/app-manifest.md +2 -0
- package/dist/docs/auth-kit.md +872 -741
- package/dist/docs/comms.md +686 -644
- package/dist/docs/customer-guide.md +70 -0
- package/dist/docs/headless-providers.md +112 -112
- package/dist/docs/operations.md +281 -0
- package/dist/docs/overview.md +3 -0
- package/dist/docs/server-functions.md +87 -1
- package/dist/docs/ui-utils.md +123 -121
- package/dist/docs/user-groups.md +175 -0
- package/dist/docs/utils.md +17 -0
- package/dist/headless.js +38 -2
- package/dist/http.js +8 -0
- package/dist/iframeResponder.d.ts +15 -0
- package/dist/iframeResponder.js +39 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/live.d.ts +80 -0
- package/dist/live.js +315 -0
- package/dist/openapi.yaml +1864 -48
- package/dist/testing/index.d.ts +35 -0
- package/dist/testing/index.js +86 -0
- package/dist/types/appManifest.d.ts +297 -1
- package/dist/types/appOptions.d.ts +32 -0
- package/dist/types/appOptions.js +3 -0
- package/dist/types/authKit.d.ts +193 -4
- package/dist/types/comms.d.ts +41 -2
- package/dist/types/containers.d.ts +8 -0
- package/dist/types/headless.d.ts +49 -1
- package/dist/types/iframeResponder.d.ts +16 -1
- package/dist/types/index.d.ts +3 -0
- package/dist/types/index.js +3 -0
- package/dist/types/operations.d.ts +598 -0
- package/dist/types/operations.js +8 -0
- package/dist/types/order.d.ts +35 -6
- package/dist/types/userGroups.d.ts +103 -0
- package/dist/types/userGroups.js +5 -0
- package/dist/utils/conditions.d.ts +7 -0
- package/dist/utils/conditions.js +16 -9
- package/docs/API_SUMMARY.md +1111 -80
- package/docs/admin-lists-and-pickers.md +140 -0
- package/docs/admin-views.md +147 -0
- package/docs/app-data-storage.md +277 -276
- package/docs/app-manifest.md +2 -0
- package/docs/auth-kit.md +872 -741
- package/docs/comms.md +686 -644
- package/docs/customer-guide.md +70 -0
- package/docs/headless-providers.md +112 -112
- package/docs/operations.md +281 -0
- package/docs/overview.md +3 -0
- package/docs/server-functions.md +87 -1
- package/docs/ui-utils.md +123 -121
- package/docs/user-groups.md +175 -0
- package/docs/utils.md +17 -0
- package/openapi.yaml +1864 -48
- package/package.json +1 -1
- package/scripts/doctor.mjs +454 -428
- package/scripts/lib/keyed-app-data.mjs +21 -0
package/dist/http.js
CHANGED
|
@@ -222,6 +222,14 @@ function shouldSkipCache(path) {
|
|
|
222
222
|
// Tag ranges change as tags are programmed, and carry the tags' keys — never cached, never persisted.
|
|
223
223
|
if (/\/claimSet\/[^/]+\/ranges(\/|\?|$)/i.test(path))
|
|
224
224
|
return true;
|
|
225
|
+
// User groups say who may do what: a change (someone added or removed) must show at once, and
|
|
226
|
+
// `mine` is about one person.
|
|
227
|
+
if (/\/userGroups?(\/|\?|$)/i.test(path))
|
|
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;
|
|
225
233
|
return false;
|
|
226
234
|
}
|
|
227
235
|
/** Evict the oldest (LRU) entry when the cache is at capacity. */
|
|
@@ -39,6 +39,8 @@ export declare class IframeResponder {
|
|
|
39
39
|
private uploads;
|
|
40
40
|
private activeStreams;
|
|
41
41
|
private isInitialLoad;
|
|
42
|
+
/** The app follows `smartlinks:navigate` (it said so with `smartlinks:navigable`). */
|
|
43
|
+
private navigable;
|
|
42
44
|
private messageHandler;
|
|
43
45
|
private resizeHandler;
|
|
44
46
|
private appUrl;
|
|
@@ -50,6 +52,19 @@ export declare class IframeResponder {
|
|
|
50
52
|
* Returns the src URL to set on the iframe.
|
|
51
53
|
*/
|
|
52
54
|
attach(iframe: HTMLIFrameElement): Promise<string>;
|
|
55
|
+
/**
|
|
56
|
+
* Ask the app to open one of its admin views (or a hash path) without reloading. Returns false when
|
|
57
|
+
* the app hasn't said it follows navigate (an older build): reload the frame at the new path instead.
|
|
58
|
+
* See docs/admin-views.md.
|
|
59
|
+
*/
|
|
60
|
+
navigate(req: {
|
|
61
|
+
view?: string;
|
|
62
|
+
path?: string;
|
|
63
|
+
params?: Record<string, string>;
|
|
64
|
+
highlight?: string;
|
|
65
|
+
}): boolean;
|
|
66
|
+
/** True once the app has said it follows `smartlinks:navigate`. */
|
|
67
|
+
get isNavigable(): boolean;
|
|
53
68
|
/**
|
|
54
69
|
* Update cached data (e.g., after user logs in).
|
|
55
70
|
*/
|
package/dist/iframeResponder.js
CHANGED
|
@@ -43,6 +43,8 @@ export class IframeResponder {
|
|
|
43
43
|
this.uploads = new Map();
|
|
44
44
|
this.activeStreams = new Map();
|
|
45
45
|
this.isInitialLoad = true;
|
|
46
|
+
/** The app follows `smartlinks:navigate` (it said so with `smartlinks:navigable`). */
|
|
47
|
+
this.navigable = false;
|
|
46
48
|
this.messageHandler = null;
|
|
47
49
|
this.resizeHandler = null;
|
|
48
50
|
this.appUrl = null;
|
|
@@ -89,6 +91,28 @@ export class IframeResponder {
|
|
|
89
91
|
const src = this.buildIframeSrc();
|
|
90
92
|
return src;
|
|
91
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Ask the app to open one of its admin views (or a hash path) without reloading. Returns false when
|
|
96
|
+
* the app hasn't said it follows navigate (an older build): reload the frame at the new path instead.
|
|
97
|
+
* See docs/admin-views.md.
|
|
98
|
+
*/
|
|
99
|
+
navigate(req) {
|
|
100
|
+
var _a;
|
|
101
|
+
const win = (_a = this.iframe) === null || _a === void 0 ? void 0 : _a.contentWindow;
|
|
102
|
+
if (!this.navigable || !win)
|
|
103
|
+
return false;
|
|
104
|
+
try {
|
|
105
|
+
win.postMessage(Object.assign({ type: 'smartlinks:navigate' }, req), '*');
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
catch (_b) {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** True once the app has said it follows `smartlinks:navigate`. */
|
|
113
|
+
get isNavigable() {
|
|
114
|
+
return this.navigable;
|
|
115
|
+
}
|
|
92
116
|
/**
|
|
93
117
|
* Update cached data (e.g., after user logs in).
|
|
94
118
|
*/
|
|
@@ -356,7 +380,7 @@ export class IframeResponder {
|
|
|
356
380
|
// Standard Iframe Messages
|
|
357
381
|
// ===========================================================================
|
|
358
382
|
async handleStandardMessage(data, event) {
|
|
359
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
383
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
|
|
360
384
|
switch (data.type) {
|
|
361
385
|
case 'smartlinks:resize': {
|
|
362
386
|
const contentHeight = (_a = data.payload) === null || _a === void 0 ? void 0 : _a.height;
|
|
@@ -424,6 +448,20 @@ export class IframeResponder {
|
|
|
424
448
|
}
|
|
425
449
|
break;
|
|
426
450
|
}
|
|
451
|
+
case 'smartlinks:navigable': {
|
|
452
|
+
this.navigable = true;
|
|
453
|
+
const p = data.payload || {};
|
|
454
|
+
(_j = (_h = this.options).onNavigable) === null || _j === void 0 ? void 0 : _j.call(_h, {
|
|
455
|
+
views: Array.isArray(p.views) ? p.views.filter((v) => typeof v === 'string') : [],
|
|
456
|
+
chrome: p.chrome === 'none' ? 'none' : 'full',
|
|
457
|
+
});
|
|
458
|
+
break;
|
|
459
|
+
}
|
|
460
|
+
case 'smartlinks:navigate-result': {
|
|
461
|
+
const p = data.payload || {};
|
|
462
|
+
(_l = (_k = this.options).onNavigateResult) === null || _l === void 0 ? void 0 : _l.call(_k, Object.assign({ ok: p.ok === true, view: typeof p.view === 'string' ? p.view : null, path: typeof p.path === 'string' ? p.path : null }, (typeof p.reason === 'string' ? { reason: p.reason } : {})));
|
|
463
|
+
break;
|
|
464
|
+
}
|
|
427
465
|
}
|
|
428
466
|
}
|
|
429
467
|
// ===========================================================================
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ export * from "./api/index.js";
|
|
|
3
3
|
export * from "./types/index.js";
|
|
4
4
|
export { iframe } from "./iframe.js";
|
|
5
5
|
export { readContext } from "./context.js";
|
|
6
|
+
export * as adminViews from "./adminViews.js";
|
|
7
|
+
export type { NavigateRequest, NavigateTarget, OpenAppRequest } from "./adminViews.js";
|
|
6
8
|
export { widgetStyleVars, widgetStyleControls, readableOn, WIDGET_STYLE_VARS } from "./widgetStyle.js";
|
|
7
9
|
export type { WidgetStyling } from "./widgetStyle.js";
|
|
8
10
|
export type { SmartLinksContext } from "./context.js";
|
|
@@ -41,4 +43,4 @@ AdminMobileHostContext, AdminMobileComponentManifest, AdminMobileBundleManifest,
|
|
|
41
43
|
MobileAdminBundleManifest, } from './mobile-admin/types.js';
|
|
42
44
|
export { HostCapabilityUnavailableError, HostPermissionDeniedError, HostTimeoutError, HostCancelledError, } from './mobile-admin/errors.js';
|
|
43
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';
|
|
44
|
-
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/index.js
CHANGED
|
@@ -7,6 +7,8 @@ export * from "./types/index.js";
|
|
|
7
7
|
export { iframe } from "./iframe.js";
|
|
8
8
|
// App context reader (props → hash → search), for pages and containers alike
|
|
9
9
|
export { readContext } from "./context.js";
|
|
10
|
+
import * as adminViews_1 from "./adminViews.js";
|
|
11
|
+
export { adminViews_1 as adminViews };
|
|
10
12
|
export { widgetStyleVars, widgetStyleControls, readableOn, WIDGET_STYLE_VARS } from "./widgetStyle.js";
|
|
11
13
|
import * as cache_1 from './cache.js';
|
|
12
14
|
export { cache_1 as cache };
|
package/dist/live.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
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
|
+
/** Names this client in the logs. */
|
|
56
|
+
build?: string;
|
|
57
|
+
}
|
|
58
|
+
export interface LiveHandle {
|
|
59
|
+
stop: () => void;
|
|
60
|
+
/** Stop listening and speaking without ending the session; anything it would say waits for `resume`. */
|
|
61
|
+
pause: () => void;
|
|
62
|
+
resume: () => void;
|
|
63
|
+
/** Text mode (or voice): give the assistant the person's words and have it answer. */
|
|
64
|
+
send: (text: string) => void;
|
|
65
|
+
/** Tell the assistant something that happened in the page, and have it answer. */
|
|
66
|
+
tell: (what: string) => void;
|
|
67
|
+
/** Give the assistant a message as it is, and have it answer. */
|
|
68
|
+
report: (text: string) => void;
|
|
69
|
+
/** Let the assistant know something without asking it to answer (where the person is now). */
|
|
70
|
+
note: (what: string) => void;
|
|
71
|
+
/** Run one of this session's server tools directly. */
|
|
72
|
+
ask: (name: string, args: Record<string, unknown>) => Promise<unknown>;
|
|
73
|
+
/** The SmartLinks session id (where its history is kept). */
|
|
74
|
+
session: () => string | null;
|
|
75
|
+
state: () => LiveState;
|
|
76
|
+
/** 0..1, how loud the person (listening) or the assistant (speaking) is right now. */
|
|
77
|
+
level: () => number;
|
|
78
|
+
}
|
|
79
|
+
/** Start a live conversation. Resolves once connected (or failed: then it is stopped and onError was told). */
|
|
80
|
+
export declare function startLive(opts: LiveOptions): Promise<LiveHandle>;
|
package/dist/live.js
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
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
|
+
function meter(ctx, stream) {
|
|
15
|
+
const analyser = ctx.createAnalyser();
|
|
16
|
+
analyser.fftSize = 256;
|
|
17
|
+
ctx.createMediaStreamSource(stream).connect(analyser);
|
|
18
|
+
const buf = new Uint8Array(analyser.frequencyBinCount);
|
|
19
|
+
return () => {
|
|
20
|
+
analyser.getByteTimeDomainData(buf);
|
|
21
|
+
let sum = 0;
|
|
22
|
+
for (const v of buf)
|
|
23
|
+
sum += (v - 128) * (v - 128);
|
|
24
|
+
return Math.min(1, Math.sqrt(sum / buf.length) / 40);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Start a live conversation. Resolves once connected (or failed: then it is stopped and onError was told). */
|
|
28
|
+
export async function startLive(opts) {
|
|
29
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
30
|
+
const textMode = opts.mode === 'text';
|
|
31
|
+
const screenTools = opts.screenTools || {};
|
|
32
|
+
const t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
|
|
33
|
+
let stopped = false;
|
|
34
|
+
let state = 'connecting';
|
|
35
|
+
let caption = '';
|
|
36
|
+
let sessionId = null;
|
|
37
|
+
let paused = false;
|
|
38
|
+
let startedAt = null;
|
|
39
|
+
let toolCalls = 0;
|
|
40
|
+
let replies = 0;
|
|
41
|
+
const held = [];
|
|
42
|
+
let replyOwed = false;
|
|
43
|
+
let micTrack = null;
|
|
44
|
+
let micSender = null;
|
|
45
|
+
let micLevel = () => 0;
|
|
46
|
+
let voiceLevel = () => 0;
|
|
47
|
+
const log = (e) => {
|
|
48
|
+
var _a, _b, _c;
|
|
49
|
+
try {
|
|
50
|
+
(_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 } : {})));
|
|
51
|
+
}
|
|
52
|
+
catch ( /* never in the way */_d) { /* never in the way */ }
|
|
53
|
+
};
|
|
54
|
+
const setState = (s) => {
|
|
55
|
+
var _a;
|
|
56
|
+
if (stopped || state === s || (paused && s !== 'paused'))
|
|
57
|
+
return;
|
|
58
|
+
state = s;
|
|
59
|
+
(_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, s);
|
|
60
|
+
};
|
|
61
|
+
(_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'connecting');
|
|
62
|
+
const pc = new RTCPeerConnection();
|
|
63
|
+
const audio = textMode ? null : new Audio();
|
|
64
|
+
if (audio)
|
|
65
|
+
audio.autoplay = true;
|
|
66
|
+
let mic = null;
|
|
67
|
+
let ctx = null;
|
|
68
|
+
const dc = pc.createDataChannel('oai-events');
|
|
69
|
+
const send = (ev) => { if (dc.readyState === 'open')
|
|
70
|
+
dc.send(JSON.stringify(ev)); };
|
|
71
|
+
const stop = () => {
|
|
72
|
+
var _a;
|
|
73
|
+
if (stopped)
|
|
74
|
+
return;
|
|
75
|
+
stopped = true;
|
|
76
|
+
if (startedAt)
|
|
77
|
+
log({ kind: 'stop', ms: Date.now() - startedAt, detail: `${toolCalls} tool calls, ${replies} replies` });
|
|
78
|
+
try {
|
|
79
|
+
dc.close();
|
|
80
|
+
}
|
|
81
|
+
catch ( /* closed */_b) { /* closed */ }
|
|
82
|
+
try {
|
|
83
|
+
pc.close();
|
|
84
|
+
}
|
|
85
|
+
catch ( /* closed */_c) { /* closed */ }
|
|
86
|
+
mic === null || mic === void 0 ? void 0 : mic.getTracks().forEach((t) => t.stop());
|
|
87
|
+
if (audio)
|
|
88
|
+
audio.srcObject = null;
|
|
89
|
+
void (ctx === null || ctx === void 0 ? void 0 : ctx.close().catch(() => undefined));
|
|
90
|
+
state = 'idle';
|
|
91
|
+
(_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'idle');
|
|
92
|
+
};
|
|
93
|
+
async function runTool(call) {
|
|
94
|
+
var _a;
|
|
95
|
+
const started = Date.now();
|
|
96
|
+
let output;
|
|
97
|
+
let ok = true;
|
|
98
|
+
const screen = screenTools[call.name];
|
|
99
|
+
try {
|
|
100
|
+
const args = call.arguments ? JSON.parse(call.arguments) : {};
|
|
101
|
+
if (screen) {
|
|
102
|
+
output = await screen(args);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const reply = await opts.endpoints.tool(call.name, args, sessionId);
|
|
106
|
+
await ((_a = opts.onToolReply) === null || _a === void 0 ? void 0 : _a.call(opts, call.name, reply));
|
|
107
|
+
output = reply.result;
|
|
108
|
+
}
|
|
109
|
+
if (output && typeof output === 'object' && 'error' in output)
|
|
110
|
+
ok = false;
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
ok = false;
|
|
114
|
+
output = { error: err instanceof Error ? err.message : "That didn't work" };
|
|
115
|
+
}
|
|
116
|
+
toolCalls++;
|
|
117
|
+
const failed = !ok && output && typeof output === 'object' && 'error' in output ? String(output.error) : undefined;
|
|
118
|
+
log(Object.assign({ kind: 'tool', tool: call.name, where: screen ? 'screen' : 'server', ms: Date.now() - started, ok }, (failed ? { error: failed } : {})));
|
|
119
|
+
send({ type: 'conversation.item.create', item: { type: 'function_call_output', call_id: call.call_id, output: JSON.stringify(output !== null && output !== void 0 ? output : {}) } });
|
|
120
|
+
}
|
|
121
|
+
dc.onmessage = (e) => {
|
|
122
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
123
|
+
let ev;
|
|
124
|
+
try {
|
|
125
|
+
ev = JSON.parse(String(e.data));
|
|
126
|
+
}
|
|
127
|
+
catch (_k) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const type = String((_a = ev['type']) !== null && _a !== void 0 ? _a : '');
|
|
131
|
+
if (type === 'input_audio_buffer.speech_started')
|
|
132
|
+
setState('hearing');
|
|
133
|
+
else if (type === 'input_audio_buffer.speech_stopped')
|
|
134
|
+
setState('thinking');
|
|
135
|
+
else if (type === 'response.created') {
|
|
136
|
+
caption = '';
|
|
137
|
+
if (textMode)
|
|
138
|
+
setState('thinking');
|
|
139
|
+
}
|
|
140
|
+
else if (type === 'output_audio_buffer.started')
|
|
141
|
+
setState('speaking');
|
|
142
|
+
else if (type === 'output_audio_buffer.stopped' || type === 'output_audio_buffer.cleared')
|
|
143
|
+
setState('listening');
|
|
144
|
+
else if (/^response\.(output_audio_transcript|audio_transcript|output_text|text)\.delta$/.test(type)) {
|
|
145
|
+
caption += String((_b = ev['delta']) !== null && _b !== void 0 ? _b : '');
|
|
146
|
+
if (textMode)
|
|
147
|
+
setState('speaking');
|
|
148
|
+
(_c = opts.onCaption) === null || _c === void 0 ? void 0 : _c.call(opts, caption);
|
|
149
|
+
}
|
|
150
|
+
else if (type === 'response.done') {
|
|
151
|
+
if (caption.trim()) {
|
|
152
|
+
replies++;
|
|
153
|
+
(_d = opts.onReply) === null || _d === void 0 ? void 0 : _d.call(opts, caption.trim());
|
|
154
|
+
log({ kind: 'reply', detail: caption.trim().slice(0, 300) });
|
|
155
|
+
}
|
|
156
|
+
const response = ((_e = ev['response']) !== null && _e !== void 0 ? _e : {});
|
|
157
|
+
const calls = ((_f = response.output) !== null && _f !== void 0 ? _f : []).filter((o) => o['type'] === 'function_call');
|
|
158
|
+
if (calls.length) {
|
|
159
|
+
setState('thinking');
|
|
160
|
+
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 : '') }); }))
|
|
161
|
+
.then(() => { if (paused)
|
|
162
|
+
replyOwed = true;
|
|
163
|
+
else
|
|
164
|
+
send({ type: 'response.create' }); });
|
|
165
|
+
}
|
|
166
|
+
else if (textMode)
|
|
167
|
+
setState('listening');
|
|
168
|
+
}
|
|
169
|
+
else if (type === 'error') {
|
|
170
|
+
const message = String((_h = ((_g = ev['error']) !== null && _g !== void 0 ? _g : {})['message']) !== null && _h !== void 0 ? _h : 'The assistant hit a problem');
|
|
171
|
+
log({ kind: 'error', error: message, detail: 'realtime service' });
|
|
172
|
+
(_j = opts.onError) === null || _j === void 0 ? void 0 : _j.call(opts, message);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
pc.onconnectionstatechange = () => {
|
|
176
|
+
var _a;
|
|
177
|
+
if (stopped)
|
|
178
|
+
return;
|
|
179
|
+
if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected' || pc.connectionState === 'closed') {
|
|
180
|
+
if (paused) {
|
|
181
|
+
log({ kind: 'stop', detail: `ended while paused (${pc.connectionState})` });
|
|
182
|
+
stop();
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
log({ kind: 'error', error: `connection ${pc.connectionState}` });
|
|
186
|
+
(_a = opts.onError) === null || _a === void 0 ? void 0 : _a.call(opts, 'The connection dropped.');
|
|
187
|
+
stop();
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
const noop = async () => null;
|
|
191
|
+
try {
|
|
192
|
+
const [mint, stream] = await Promise.all([
|
|
193
|
+
opts.endpoints.mint(),
|
|
194
|
+
textMode ? Promise.resolve(null) : navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } }),
|
|
195
|
+
]);
|
|
196
|
+
if (stopped) {
|
|
197
|
+
stream === null || stream === void 0 ? void 0 : stream.getTracks().forEach((t) => t.stop());
|
|
198
|
+
return handle();
|
|
199
|
+
}
|
|
200
|
+
mic = stream;
|
|
201
|
+
sessionId = (_b = mint.sessionId) !== null && _b !== void 0 ? _b : null;
|
|
202
|
+
const missing = ((_c = mint.tools) !== null && _c !== void 0 ? _c : []).filter((t) => t.runs === 'screen' && !screenTools[t.name]).map((t) => t.name);
|
|
203
|
+
if (missing.length)
|
|
204
|
+
log({ kind: 'error', error: `this page can't run: ${missing.join(', ')}`, detail: 'client older than the server' });
|
|
205
|
+
if (stream) {
|
|
206
|
+
ctx = new AudioContext();
|
|
207
|
+
micLevel = meter(ctx, stream);
|
|
208
|
+
for (const track of stream.getTracks()) {
|
|
209
|
+
const sender = pc.addTrack(track, stream);
|
|
210
|
+
if (track.kind === 'audio' && !micTrack) {
|
|
211
|
+
micTrack = track;
|
|
212
|
+
micSender = sender;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
pc.ontrack = (e) => {
|
|
216
|
+
const remote = e.streams[0];
|
|
217
|
+
if (!remote || !audio)
|
|
218
|
+
return;
|
|
219
|
+
audio.srcObject = remote;
|
|
220
|
+
if (ctx)
|
|
221
|
+
voiceLevel = meter(ctx, remote);
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
// A typed conversation: nothing to send, nothing to hear, but the call still carries an audio line.
|
|
226
|
+
pc.addTransceiver('audio', { direction: 'recvonly' });
|
|
227
|
+
}
|
|
228
|
+
const offer = await pc.createOffer();
|
|
229
|
+
await pc.setLocalDescription(offer);
|
|
230
|
+
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 : '' });
|
|
231
|
+
if (!res.ok)
|
|
232
|
+
throw new Error(`The assistant's service refused the call (${res.status})`);
|
|
233
|
+
await pc.setRemoteDescription({ type: 'answer', sdp: await res.text() });
|
|
234
|
+
await new Promise((resolve, reject) => {
|
|
235
|
+
if (dc.readyState === 'open')
|
|
236
|
+
return resolve();
|
|
237
|
+
const timer = setTimeout(() => reject(new Error("The assistant's service didn't answer")), 15000);
|
|
238
|
+
dc.onopen = () => { clearTimeout(timer); resolve(); };
|
|
239
|
+
});
|
|
240
|
+
startedAt = Date.now();
|
|
241
|
+
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'}` });
|
|
242
|
+
setState('listening');
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
const denied = typeof DOMException !== 'undefined' && err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'NotFoundError');
|
|
246
|
+
log({ kind: 'error', error: err instanceof Error ? err.message : String(err), detail: denied ? 'microphone' : 'starting' });
|
|
247
|
+
(_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");
|
|
248
|
+
stop();
|
|
249
|
+
}
|
|
250
|
+
function handle() {
|
|
251
|
+
const say = (text) => send({ type: 'conversation.item.create', item: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] } });
|
|
252
|
+
const answer = (text) => {
|
|
253
|
+
if (stopped)
|
|
254
|
+
return;
|
|
255
|
+
if (paused)
|
|
256
|
+
return void held.push(text);
|
|
257
|
+
say(text);
|
|
258
|
+
send({ type: 'response.create' });
|
|
259
|
+
};
|
|
260
|
+
return {
|
|
261
|
+
stop,
|
|
262
|
+
pause: () => {
|
|
263
|
+
var _a;
|
|
264
|
+
if (stopped || paused || state === 'connecting')
|
|
265
|
+
return;
|
|
266
|
+
paused = true;
|
|
267
|
+
void (micSender === null || micSender === void 0 ? void 0 : micSender.replaceTrack(null).catch(() => undefined));
|
|
268
|
+
send({ type: 'input_audio_buffer.clear' });
|
|
269
|
+
send({ type: 'response.cancel' });
|
|
270
|
+
if (!textMode)
|
|
271
|
+
send({ type: 'output_audio_buffer.clear' });
|
|
272
|
+
if (audio)
|
|
273
|
+
audio.muted = true;
|
|
274
|
+
state = 'paused';
|
|
275
|
+
(_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'paused');
|
|
276
|
+
log({ kind: 'pause' });
|
|
277
|
+
},
|
|
278
|
+
resume: () => {
|
|
279
|
+
var _a;
|
|
280
|
+
if (stopped || !paused)
|
|
281
|
+
return;
|
|
282
|
+
paused = false;
|
|
283
|
+
void (micSender === null || micSender === void 0 ? void 0 : micSender.replaceTrack(micTrack).catch(() => undefined));
|
|
284
|
+
if (audio)
|
|
285
|
+
audio.muted = false;
|
|
286
|
+
state = 'listening';
|
|
287
|
+
(_a = opts.onState) === null || _a === void 0 ? void 0 : _a.call(opts, 'listening');
|
|
288
|
+
const waiting = held.splice(0);
|
|
289
|
+
for (const text of waiting)
|
|
290
|
+
say(text);
|
|
291
|
+
if (waiting.length || replyOwed)
|
|
292
|
+
send({ type: 'response.create' });
|
|
293
|
+
replyOwed = false;
|
|
294
|
+
log({ kind: 'resume', detail: waiting.length ? `${waiting.length} message(s) held while paused` : '' });
|
|
295
|
+
},
|
|
296
|
+
send: (text) => { if (text.trim())
|
|
297
|
+
answer(text.trim()); },
|
|
298
|
+
tell: (what) => answer(`[On screen] ${what}`),
|
|
299
|
+
report: (text) => answer(text),
|
|
300
|
+
note: (what) => { if (!stopped)
|
|
301
|
+
say(`[On screen] ${what}`); },
|
|
302
|
+
ask: async (name, args) => {
|
|
303
|
+
var _a;
|
|
304
|
+
if (stopped || !sessionId)
|
|
305
|
+
return noop();
|
|
306
|
+
const reply = await opts.endpoints.tool(name, args, sessionId);
|
|
307
|
+
return (_a = reply.result) !== null && _a !== void 0 ? _a : null;
|
|
308
|
+
},
|
|
309
|
+
session: () => sessionId,
|
|
310
|
+
state: () => state,
|
|
311
|
+
level: () => (state === 'speaking' ? voiceLevel() : state === 'hearing' || state === 'listening' ? micLevel() : 0),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
return handle();
|
|
315
|
+
}
|