@mcpstack/agent-sdk 1.0.0-pr.16.7572c080abaa.13.1

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.
@@ -0,0 +1,4075 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/react-native/index.tsx
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AppAgentProvider: () => AppAgentProvider,
24
+ useAppAgent: () => useAppAgent,
25
+ useAppAgentContext: () => useAppAgentContext
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var import_react2 = require("react");
29
+
30
+ // src/framework/useAppAgentBinding.tsx
31
+ var import_react = require("react");
32
+
33
+ // src/core/sse-client.ts
34
+ function* parseEventBlocks(input) {
35
+ const normalized = input.replace(/\r\n/g, "\n");
36
+ const eventBlocks = normalized.split("\n\n");
37
+ for (const eventBlock of eventBlocks) {
38
+ if (!eventBlock.trim()) continue;
39
+ let eventType = "";
40
+ const dataLines = [];
41
+ for (const line of eventBlock.split("\n")) {
42
+ if (line.startsWith("event: ")) {
43
+ eventType = line.slice("event: ".length);
44
+ } else if (line.startsWith("data: ")) {
45
+ dataLines.push(line.slice("data: ".length));
46
+ } else if (line === "data:") {
47
+ dataLines.push("");
48
+ }
49
+ }
50
+ if (!eventType || dataLines.length === 0) {
51
+ continue;
52
+ }
53
+ try {
54
+ const parsed = JSON.parse(dataLines.join("\n"));
55
+ yield { type: eventType, data: parsed };
56
+ } catch {
57
+ }
58
+ }
59
+ }
60
+ async function* parseSseStream(response, signal) {
61
+ const reader = response.body?.getReader();
62
+ if (!reader) {
63
+ const text = await response.text().catch(() => "");
64
+ yield* parseEventBlocks(text);
65
+ return;
66
+ }
67
+ const decoder = new TextDecoder();
68
+ let buffer = "";
69
+ try {
70
+ while (true) {
71
+ if (signal?.aborted) break;
72
+ const { done, value } = await reader.read();
73
+ if (done) break;
74
+ buffer += decoder.decode(value, { stream: true });
75
+ const normalized = buffer.replace(/\r\n/g, "\n");
76
+ const events = normalized.split("\n\n");
77
+ buffer = events.pop() ?? "";
78
+ for (const eventBlock of events) {
79
+ yield* parseEventBlocks(eventBlock);
80
+ }
81
+ }
82
+ if (buffer.trim()) {
83
+ yield* parseEventBlocks(buffer);
84
+ }
85
+ } finally {
86
+ reader.releaseLock();
87
+ }
88
+ }
89
+
90
+ // src/core/auth/registration.ts
91
+ var REGISTRATION_STORAGE_PREFIX = "mcpstack_oauth_registration_";
92
+ function getStorage(storage) {
93
+ if (storage) {
94
+ return storage;
95
+ }
96
+ try {
97
+ return typeof localStorage === "undefined" ? null : localStorage;
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+ function encodeCacheKey(raw) {
103
+ return btoa(raw).replace(/[^a-zA-Z0-9]/g, "");
104
+ }
105
+ function getPreferredRegistrationPreference(authConfig) {
106
+ return authConfig?.registrationPreference ?? "auto";
107
+ }
108
+ function getEffectiveCallbackUrl(authConfig, fallbackCallbackUrl) {
109
+ const configuredCallbackUrl = authConfig?.callbackUrl?.trim();
110
+ if (!configuredCallbackUrl) {
111
+ return fallbackCallbackUrl;
112
+ }
113
+ if (isNativeCallbackUrl(fallbackCallbackUrl) && !isNativeCallbackUrl(configuredCallbackUrl)) {
114
+ return fallbackCallbackUrl;
115
+ }
116
+ return configuredCallbackUrl;
117
+ }
118
+ function buildRegistrationCacheKey(authConfig, callbackUrl, requestedMode) {
119
+ const raw = [
120
+ authConfig.authorizationServerUrl ?? "",
121
+ authConfig.authorizationServerMetadataUrl ?? "",
122
+ authConfig.resource ?? "",
123
+ callbackUrl,
124
+ requestedMode
125
+ ].join("|");
126
+ return encodeCacheKey(raw);
127
+ }
128
+ function buildTokenCacheKey(authConfig, mcpServerUrl) {
129
+ if (!authConfig) {
130
+ return encodeCacheKey(`legacy|${mcpServerUrl}`);
131
+ }
132
+ const callbackUrl = authConfig.callbackUrl ?? "";
133
+ const clientMode = authConfig.clientMode ?? "manual";
134
+ const raw = [
135
+ authConfig.authorizationServerUrl ?? mcpServerUrl,
136
+ authConfig.resource ?? "",
137
+ callbackUrl,
138
+ clientMode
139
+ ].join("|");
140
+ return encodeCacheKey(raw);
141
+ }
142
+ function loadStoredRegistration(cacheKey, storage) {
143
+ const targetStorage = getStorage(storage);
144
+ if (!targetStorage) return null;
145
+ try {
146
+ const raw = targetStorage.getItem(`${REGISTRATION_STORAGE_PREFIX}${cacheKey}`);
147
+ if (!raw) return null;
148
+ return JSON.parse(raw);
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+ function saveStoredRegistration(registration, storage) {
154
+ const targetStorage = getStorage(storage);
155
+ if (!targetStorage) return;
156
+ try {
157
+ targetStorage.setItem(
158
+ `${REGISTRATION_STORAGE_PREFIX}${registration.key}`,
159
+ JSON.stringify(registration)
160
+ );
161
+ } catch {
162
+ }
163
+ }
164
+ function applyResolvedRegistration(authConfig, registration) {
165
+ return {
166
+ ...authConfig,
167
+ callbackUrl: registration.callbackUrl,
168
+ clientId: registration.clientId ?? authConfig.clientId,
169
+ clientMode: registration.mode,
170
+ resource: registration.resource ?? authConfig.resource,
171
+ authorizationServerUrl: registration.authorizationServerUrl ?? authConfig.authorizationServerUrl,
172
+ authorizationServerMetadataUrl: registration.authorizationServerMetadataUrl ?? authConfig.authorizationServerMetadataUrl,
173
+ registrationEndpoint: registration.registrationEndpoint ?? authConfig.registrationEndpoint
174
+ };
175
+ }
176
+ function createResolvedRegistration(authConfig, mode, callbackUrl, clientId, clientMetadataUrl) {
177
+ return {
178
+ cacheKey: buildRegistrationCacheKey(authConfig, callbackUrl, mode),
179
+ mode,
180
+ clientId,
181
+ callbackUrl,
182
+ resource: authConfig.resource,
183
+ authorizationServerUrl: authConfig.authorizationServerUrl,
184
+ authorizationServerMetadataUrl: authConfig.authorizationServerMetadataUrl,
185
+ registrationEndpoint: authConfig.registrationEndpoint,
186
+ clientMetadataUrl
187
+ };
188
+ }
189
+ function shouldAttemptMode(preferred, candidate) {
190
+ return preferred === "auto" || preferred === candidate;
191
+ }
192
+ function isLoopbackHost(hostname) {
193
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
194
+ }
195
+ function isNativeCallbackUrl(callbackUrl) {
196
+ try {
197
+ const url = new URL(callbackUrl);
198
+ return url.protocol !== "http:" && url.protocol !== "https:";
199
+ } catch {
200
+ return !callbackUrl.startsWith("http://") && !callbackUrl.startsWith("https://");
201
+ }
202
+ }
203
+ function inferApplicationType(callbackUrl) {
204
+ try {
205
+ const url = new URL(callbackUrl);
206
+ if (url.protocol === "http:" || url.protocol === "https:") {
207
+ return isLoopbackHost(url.hostname) ? "native" : "web";
208
+ }
209
+ return "native";
210
+ } catch {
211
+ return "native";
212
+ }
213
+ }
214
+ async function registerPublicClient(authConfig, options) {
215
+ const fetchImpl = options.fetchImpl ?? fetch;
216
+ const callbackUrl = options.callbackUrl;
217
+ const registration = createResolvedRegistration(authConfig, "dcr", callbackUrl);
218
+ if (!authConfig.registrationEndpoint) {
219
+ throw new Error("Dynamic client registration is not available for this server.");
220
+ }
221
+ const existing = loadStoredRegistration(registration.cacheKey, options.storage);
222
+ if (existing?.clientId) {
223
+ return {
224
+ ...registration,
225
+ clientId: existing.clientId
226
+ };
227
+ }
228
+ const requestBody = {
229
+ client_name: options.clientName ?? "MCP Stack MCP Client",
230
+ application_type: inferApplicationType(callbackUrl),
231
+ redirect_uris: [callbackUrl],
232
+ grant_types: ["authorization_code", "refresh_token"],
233
+ response_types: ["code"],
234
+ token_endpoint_auth_method: "none",
235
+ scope: authConfig.scopes?.join(" "),
236
+ client_uri: options.clientUri
237
+ };
238
+ const response = await fetchImpl(authConfig.registrationEndpoint, {
239
+ method: "POST",
240
+ headers: {
241
+ Accept: "application/json",
242
+ "Content-Type": "application/json"
243
+ },
244
+ body: JSON.stringify(requestBody)
245
+ });
246
+ if (!response.ok) {
247
+ const errorText = await response.text().catch(() => "Dynamic client registration failed.");
248
+ throw new Error(`Dynamic client registration failed (${response.status}): ${errorText}`);
249
+ }
250
+ const payload = await response.json();
251
+ if (!payload.client_id) {
252
+ throw new Error("Dynamic client registration response did not include a client_id.");
253
+ }
254
+ saveStoredRegistration({
255
+ key: registration.cacheKey,
256
+ mode: "dcr",
257
+ authorizationServerUrl: authConfig.authorizationServerUrl ?? "",
258
+ authorizationServerMetadataUrl: authConfig.authorizationServerMetadataUrl,
259
+ registrationEndpoint: authConfig.registrationEndpoint,
260
+ clientId: payload.client_id,
261
+ callbackUrl,
262
+ resource: authConfig.resource,
263
+ createdAt: Date.now(),
264
+ updatedAt: Date.now()
265
+ }, options.storage);
266
+ return {
267
+ ...registration,
268
+ clientId: payload.client_id
269
+ };
270
+ }
271
+ async function resolveOAuthRegistration(authConfig, options) {
272
+ const callbackUrl = getEffectiveCallbackUrl(authConfig, options.callbackUrl);
273
+ const preferred = getPreferredRegistrationPreference(authConfig);
274
+ const preregClientId = authConfig.clientId?.trim();
275
+ if (preregClientId && shouldAttemptMode(preferred, "preregistered")) {
276
+ return createResolvedRegistration(
277
+ authConfig,
278
+ "preregistered",
279
+ callbackUrl,
280
+ preregClientId
281
+ );
282
+ }
283
+ if (authConfig.clientIdMetadataDocumentSupported && options.oauthClientMetadataUrl && shouldAttemptMode(preferred, "cimd")) {
284
+ return createResolvedRegistration(
285
+ authConfig,
286
+ "cimd",
287
+ callbackUrl,
288
+ options.oauthClientMetadataUrl,
289
+ options.oauthClientMetadataUrl
290
+ );
291
+ }
292
+ if (authConfig.registrationEndpoint && shouldAttemptMode(preferred, "dcr")) {
293
+ return registerPublicClient(authConfig, {
294
+ ...options,
295
+ callbackUrl
296
+ });
297
+ }
298
+ return createResolvedRegistration(
299
+ authConfig,
300
+ preregClientId ? "preregistered" : "manual",
301
+ callbackUrl,
302
+ preregClientId
303
+ );
304
+ }
305
+
306
+ // src/core/auth-storage.ts
307
+ var LEGACY_OAUTH_TOKEN_STORAGE_PREFIX = "mcpstack_oauth_";
308
+ var SCOPED_OAUTH_TOKEN_STORAGE_PREFIX = "mcpstack_oauth_session_";
309
+ function hashAuthSessionKey(value) {
310
+ let hash = 2166136261;
311
+ for (let index = 0; index < value.length; index += 1) {
312
+ hash ^= value.charCodeAt(index);
313
+ hash = Math.imul(hash, 16777619);
314
+ }
315
+ return (hash >>> 0).toString(36);
316
+ }
317
+ function normalizeAuthSessionKey(value) {
318
+ if (typeof value !== "string") {
319
+ return null;
320
+ }
321
+ const normalized = value.trim();
322
+ return normalized || null;
323
+ }
324
+ function resolveExplicitAuthSessionKey(config) {
325
+ return normalizeAuthSessionKey(config.authSessionKey);
326
+ }
327
+ function buildScopedOAuthTokenStoragePrefix(authSessionKey) {
328
+ const normalizedSessionKey = normalizeAuthSessionKey(authSessionKey);
329
+ if (!normalizedSessionKey) {
330
+ return LEGACY_OAUTH_TOKEN_STORAGE_PREFIX;
331
+ }
332
+ return `${SCOPED_OAUTH_TOKEN_STORAGE_PREFIX}${hashAuthSessionKey(normalizedSessionKey)}_`;
333
+ }
334
+ function buildScopedOAuthTokenStorageKey(cacheKey, authSessionKey) {
335
+ return `${buildScopedOAuthTokenStoragePrefix(authSessionKey)}${cacheKey}`;
336
+ }
337
+
338
+ // src/core/EmcyAgent.ts
339
+ var DEFAULT_MCP_PROTOCOL_VERSION = "2025-11-25";
340
+ var DEFAULT_LOCAL_PUBLIC_APP_PORT = "3100";
341
+ var DEFAULT_OAUTH_CALLBACK_URL = "https://mcpstack.com/oauth/callback";
342
+ var DEFAULT_OAUTH_CLIENT_METADATA_URL = "https://mcpstack.com/.well-known/oauth-client-metadata.json";
343
+ var DEFAULT_AUDIO_TURN_DETECTION = {
344
+ enabled: true,
345
+ autoSubmit: true,
346
+ silenceDurationMs: 850,
347
+ minSpeechDurationMs: 180,
348
+ noSpeechTimeoutMs: 12e3,
349
+ speechThreshold: 0.012,
350
+ noiseMultiplier: 2.4
351
+ };
352
+ var AUDIO_ACTIVITY_EMIT_INTERVAL_MS = 120;
353
+ var MIN_AUDIO_LEVEL_DELTA_FOR_STATE = 0.03;
354
+ function isLocalhostHost(hostname) {
355
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
356
+ }
357
+ function getDefaultOAuthHelperOrigin(agentServiceUrl) {
358
+ if (!agentServiceUrl) {
359
+ return DEFAULT_OAUTH_CALLBACK_URL.replace(/\/oauth\/callback$/, "");
360
+ }
361
+ try {
362
+ const url = new URL(agentServiceUrl);
363
+ if (isLocalhostHost(url.hostname)) {
364
+ return `${url.protocol}//${url.hostname}:${DEFAULT_LOCAL_PUBLIC_APP_PORT}`;
365
+ }
366
+ } catch {
367
+ }
368
+ return DEFAULT_OAUTH_CALLBACK_URL.replace(/\/oauth\/callback$/, "");
369
+ }
370
+ function getDefaultOAuthCallbackUrl(agentServiceUrl) {
371
+ return `${getDefaultOAuthHelperOrigin(agentServiceUrl)}/oauth/callback`;
372
+ }
373
+ function getDefaultOAuthClientMetadataUrl(agentServiceUrl) {
374
+ return `${getDefaultOAuthHelperOrigin(agentServiceUrl)}/.well-known/oauth-client-metadata.json`;
375
+ }
376
+ function buildEmbeddedExchangeUrl(mcpServerUrl) {
377
+ const url = new URL(mcpServerUrl);
378
+ if (/\/mcp\/?$/i.test(url.pathname)) {
379
+ url.pathname = url.pathname.replace(/\/mcp\/?$/i, "/embedded/exchange");
380
+ } else {
381
+ url.pathname = `${url.pathname.replace(/\/$/, "")}/embedded/exchange`;
382
+ }
383
+ return url.toString();
384
+ }
385
+ function normalizeOAuthTokenResponse(payload, authConfig) {
386
+ const accessToken = typeof payload.accessToken === "string" ? payload.accessToken : typeof payload.access_token === "string" ? payload.access_token : "";
387
+ if (!accessToken) {
388
+ return void 0;
389
+ }
390
+ return {
391
+ accessToken,
392
+ refreshToken: typeof payload.refreshToken === "string" ? payload.refreshToken : typeof payload.refresh_token === "string" ? payload.refresh_token : void 0,
393
+ expiresIn: typeof payload.expiresIn === "number" ? payload.expiresIn : typeof payload.expires_in === "number" ? payload.expires_in : void 0,
394
+ tokenType: typeof payload.tokenType === "string" ? payload.tokenType : typeof payload.token_type === "string" ? payload.token_type : "Bearer",
395
+ resolvedAuthConfig: authConfig
396
+ };
397
+ }
398
+ function createAppTokenAuthHandler(agentId, auth) {
399
+ return async (mcpServerUrl, authConfig) => {
400
+ const appToken = await auth.getToken();
401
+ const trimmedToken = appToken?.trim();
402
+ if (!trimmedToken) {
403
+ return void 0;
404
+ }
405
+ const headers = {
406
+ "Content-Type": "application/json",
407
+ Authorization: `Bearer ${trimmedToken}`
408
+ };
409
+ if (auth.appId?.trim()) {
410
+ headers["x-mcpstack-embedded-app-id"] = auth.appId.trim();
411
+ }
412
+ const body = {
413
+ agentId,
414
+ resource: authConfig.resource ?? mcpServerUrl,
415
+ scopes: authConfig.scopes
416
+ };
417
+ if (auth.appId?.trim()) {
418
+ body.appId = auth.appId.trim();
419
+ }
420
+ const response = await fetch(buildEmbeddedExchangeUrl(mcpServerUrl), {
421
+ method: "POST",
422
+ headers,
423
+ body: JSON.stringify(body)
424
+ });
425
+ const payload = await response.json().catch(() => null);
426
+ if (!response.ok) {
427
+ const description = typeof payload?.error_description === "string" ? payload.error_description : typeof payload?.error === "string" ? payload.error : `App token exchange failed (${response.status}).`;
428
+ throw new Error(description);
429
+ }
430
+ return normalizeOAuthTokenResponse(payload ?? {}, authConfig);
431
+ };
432
+ }
433
+ function extractErrorMessage(payload) {
434
+ if (typeof payload === "string") {
435
+ const message = payload.trim();
436
+ return message || null;
437
+ }
438
+ if (!payload || typeof payload !== "object") {
439
+ return null;
440
+ }
441
+ const record = payload;
442
+ for (const key of ["error", "message", "detail"]) {
443
+ const value = record[key];
444
+ if (typeof value === "string" && value.trim()) {
445
+ return value.trim();
446
+ }
447
+ }
448
+ return null;
449
+ }
450
+ async function getResponseErrorMessage(response) {
451
+ const fallback = `HTTP ${response.status}`;
452
+ try {
453
+ const payload = await response.clone().json();
454
+ const message = extractErrorMessage(payload);
455
+ if (message) {
456
+ return message;
457
+ }
458
+ } catch {
459
+ }
460
+ const text = await response.text().catch(() => "");
461
+ return text.trim() || fallback;
462
+ }
463
+ function parameterToJsonSchema(parameter) {
464
+ const schema = {
465
+ type: parameter.type
466
+ };
467
+ if (parameter.description) {
468
+ schema.description = parameter.description;
469
+ }
470
+ if (parameter.enum) {
471
+ schema.enum = parameter.enum;
472
+ }
473
+ if (parameter.type === "array") {
474
+ schema.items = parameter.items ? parameterToJsonSchema(parameter.items) : { type: "string" };
475
+ }
476
+ if (parameter.type === "object" && parameter.properties) {
477
+ const properties = {};
478
+ const required = [];
479
+ for (const [key, child] of Object.entries(parameter.properties)) {
480
+ properties[key] = parameterToJsonSchema(child);
481
+ if (child.required) required.push(key);
482
+ }
483
+ schema.properties = properties;
484
+ schema.required = required;
485
+ }
486
+ if (parameter.additionalProperties !== void 0) {
487
+ schema.additionalProperties = typeof parameter.additionalProperties === "boolean" ? parameter.additionalProperties : parameterToJsonSchema(parameter.additionalProperties);
488
+ }
489
+ return schema;
490
+ }
491
+ function parametersToJsonSchema(params) {
492
+ const properties = {};
493
+ const required = [];
494
+ for (const [key, p] of Object.entries(params)) {
495
+ properties[key] = parameterToJsonSchema(p);
496
+ if (p.required) required.push(key);
497
+ }
498
+ return { type: "object", properties, required };
499
+ }
500
+ var McpStackAgent = class {
501
+ constructor(config) {
502
+ this.agentConfig = null;
503
+ this.budgetSnapshot = null;
504
+ this.conversationId = null;
505
+ this.messages = [];
506
+ this.historyCursor = null;
507
+ this.hasOlderMessages = false;
508
+ this.isLoadingHistory = false;
509
+ this.abortController = null;
510
+ this.isLoading = false;
511
+ this.listeners = /* @__PURE__ */ new Map();
512
+ /** Per-server MCP session tracking */
513
+ this.mcpSessions = /* @__PURE__ */ new Map();
514
+ /** OAuth tokens per MCP server URL (standalone mode only) */
515
+ this.oauthTokens = /* @__PURE__ */ new Map();
516
+ /** Servers explicitly disconnected by the user and awaiting manual re-auth */
517
+ this.manuallySignedOutServers = /* @__PURE__ */ new Set();
518
+ this.audioState = {
519
+ status: "idle",
520
+ isSupported: false,
521
+ isEnabled: false,
522
+ transcript: "",
523
+ partialTranscript: "",
524
+ error: null
525
+ };
526
+ this.audioStream = null;
527
+ this.audioContext = null;
528
+ this.audioSource = null;
529
+ this.audioProcessor = null;
530
+ this.audioSilentGain = null;
531
+ this.audioSocket = null;
532
+ this.audioSessionTimer = null;
533
+ this.audioSessionStopRequested = false;
534
+ this.audioFinalTranscript = "";
535
+ this.audioTurnState = null;
536
+ const appTokenAuthHandler = config.auth?.mode === "app-token" ? createAppTokenAuthHandler(config.agentId, config.auth) : void 0;
537
+ this.config = {
538
+ ...config,
539
+ agentServiceUrl: config.agentServiceUrl ?? "https://api.mcpstack.com",
540
+ oauthCallbackUrl: config.oauthCallbackUrl ?? getDefaultOAuthCallbackUrl(config.agentServiceUrl),
541
+ oauthClientMetadataUrl: config.oauthClientMetadataUrl ?? getDefaultOAuthClientMetadataUrl(config.agentServiceUrl),
542
+ onAuthRequired: config.onAuthRequired ?? appTokenAuthHandler
543
+ };
544
+ this.audioState = this.buildAudioState({ status: "idle" });
545
+ }
546
+ async resolveAuthToken() {
547
+ if (this.config.getAuthToken) {
548
+ const token = await this.config.getAuthToken();
549
+ if (token) return token;
550
+ }
551
+ return this.config.apiKey;
552
+ }
553
+ /** Initialize: fetch agent config (tools, widget settings, MCP servers) */
554
+ async init() {
555
+ const token = await this.resolveAuthToken();
556
+ const response = await fetch(
557
+ `${this.config.agentServiceUrl}/api/v1/agents/${this.config.agentId}/config`,
558
+ {
559
+ headers: {
560
+ Authorization: `Bearer ${token}`
561
+ }
562
+ }
563
+ );
564
+ if (!response.ok) {
565
+ throw new Error(await getResponseErrorMessage(response));
566
+ }
567
+ this.agentConfig = await response.json();
568
+ this.audioState = this.buildAudioState({ status: "idle" });
569
+ this.emit("audio_state", this.audioState);
570
+ await this.refreshBudgetSnapshot().catch(() => void 0);
571
+ if (this.agentConfig?.mcpServers?.length) {
572
+ await Promise.all(
573
+ this.agentConfig.mcpServers.map(async (server) => {
574
+ server.authConfig = await this.resolveServerAuthConfig(server.url, server.authConfig ?? null);
575
+ })
576
+ );
577
+ }
578
+ if (this.agentConfig?.mcpServers) {
579
+ for (const server of this.agentConfig.mcpServers) {
580
+ if (!this.mcpSessions.has(server.url)) {
581
+ let authStatus;
582
+ if (server.authConfig?.authType === "oauth2") {
583
+ authStatus = server.authStatus === "connected" || this.hasValidOAuthToken(server.url) ? "connected" : "needs_auth";
584
+ } else {
585
+ authStatus = server.authStatus || "connected";
586
+ }
587
+ this.mcpSessions.set(server.url, { sessionId: null, authStatus });
588
+ }
589
+ }
590
+ }
591
+ if (this.config.initialConversationId) {
592
+ await this.loadConversation(this.config.initialConversationId);
593
+ }
594
+ return this.agentConfig;
595
+ }
596
+ /** Get current MCP server auth statuses */
597
+ getMcpServers() {
598
+ if (!this.agentConfig?.mcpServers) return [];
599
+ return this.agentConfig.mcpServers.map((server) => ({
600
+ url: server.url,
601
+ name: server.name,
602
+ authStatus: this.mcpSessions.get(server.url)?.authStatus ?? server.authStatus ?? "connected",
603
+ canSignOut: (server.authConfig?.authType ?? "none") !== "none"
604
+ }));
605
+ }
606
+ /** Send a message and process the full orchestration loop (including tool calls) */
607
+ async sendMessage(message) {
608
+ if (!this.agentConfig) {
609
+ await this.init();
610
+ }
611
+ this.isLoading = true;
612
+ this.emit("loading", true);
613
+ const userMsg = {
614
+ id: crypto.randomUUID(),
615
+ role: "user",
616
+ content: message,
617
+ timestamp: /* @__PURE__ */ new Date()
618
+ };
619
+ this.messages.push(userMsg);
620
+ this.emit("message", userMsg);
621
+ try {
622
+ await this.runChatLoop(message);
623
+ } catch (err) {
624
+ const errorMsg = err instanceof Error ? err.message : "Unknown error";
625
+ this.emit("error", { code: "sdk_error", message: errorMsg });
626
+ } finally {
627
+ this.isLoading = false;
628
+ this.emit("loading", false);
629
+ this.emit("thinking", false);
630
+ }
631
+ }
632
+ /** Start a new conversation */
633
+ newConversation() {
634
+ this.conversationId = null;
635
+ this.messages = [];
636
+ this.historyCursor = null;
637
+ this.hasOlderMessages = false;
638
+ this.isLoadingHistory = false;
639
+ }
640
+ /** Cancel the current in-flight request */
641
+ cancel() {
642
+ this.abortController?.abort();
643
+ this.abortController = null;
644
+ }
645
+ /** Get all messages in the current conversation */
646
+ getMessages() {
647
+ return [...this.messages];
648
+ }
649
+ /** Get the current conversation ID */
650
+ getConversationId() {
651
+ return this.conversationId;
652
+ }
653
+ getHasOlderMessages() {
654
+ return this.hasOlderMessages;
655
+ }
656
+ getIsLoadingHistory() {
657
+ return this.isLoadingHistory;
658
+ }
659
+ /** Get the loaded agent config */
660
+ getAgentConfig() {
661
+ return this.agentConfig;
662
+ }
663
+ getAudioInputState() {
664
+ return { ...this.audioState };
665
+ }
666
+ async startVoiceInput() {
667
+ if (!this.agentConfig) {
668
+ await this.init();
669
+ }
670
+ if (!this.isAudioInputSupported()) {
671
+ this.setAudioState({
672
+ status: "error",
673
+ error: {
674
+ code: "unsupported_browser",
675
+ message: "Microphone input is not supported in this browser."
676
+ }
677
+ });
678
+ return;
679
+ }
680
+ if (!this.isAudioInputEnabled()) {
681
+ this.setAudioState({
682
+ status: "error",
683
+ error: {
684
+ code: "audio_not_enabled",
685
+ message: "Microphone input is not enabled for this agent."
686
+ }
687
+ });
688
+ return;
689
+ }
690
+ if (this.audioState.status === "requesting_permission" || this.audioState.status === "connecting" || this.audioState.status === "listening" || this.audioState.status === "transcribing") {
691
+ return;
692
+ }
693
+ this.audioSessionStopRequested = false;
694
+ this.audioFinalTranscript = "";
695
+ this.audioTurnState = null;
696
+ this.setAudioState({
697
+ status: "requesting_permission",
698
+ transcript: "",
699
+ partialTranscript: "",
700
+ error: null,
701
+ sessionId: null,
702
+ conversationId: this.conversationId,
703
+ inputLevel: 0,
704
+ isSpeaking: false,
705
+ speechMs: 0,
706
+ silenceMs: 0,
707
+ autoSubmitEnabled: this.getAudioTurnDetectionConfig().enabled && this.getAudioTurnDetectionConfig().autoSubmit
708
+ });
709
+ let stream = null;
710
+ try {
711
+ stream = await navigator.mediaDevices.getUserMedia({
712
+ audio: {
713
+ channelCount: 1,
714
+ echoCancellation: true,
715
+ noiseSuppression: true,
716
+ autoGainControl: true
717
+ }
718
+ });
719
+ } catch (error) {
720
+ this.setAudioState({
721
+ status: "error",
722
+ error: {
723
+ code: "microphone_permission_denied",
724
+ message: error instanceof Error ? error.message : "Microphone permission was denied."
725
+ }
726
+ });
727
+ return;
728
+ }
729
+ try {
730
+ this.audioStream = stream;
731
+ this.setAudioState({ status: "connecting" });
732
+ const session = await this.createRealtimeTranscriptionSession();
733
+ this.conversationId = session.conversationId;
734
+ this.setAudioState({
735
+ sessionId: session.sessionId,
736
+ conversationId: session.conversationId,
737
+ maxSessionSeconds: session.maxSessionSeconds
738
+ });
739
+ const socket = await this.openAudioSocket(session.webSocketUrl);
740
+ this.audioSocket = socket;
741
+ this.bindAudioSocket(socket);
742
+ await this.startAudioCapture(stream, socket);
743
+ const maxSessionMs = Math.max(1, session.maxSessionSeconds) * 1e3;
744
+ this.audioSessionTimer = setTimeout(() => {
745
+ void this.commitVoiceInput();
746
+ }, maxSessionMs);
747
+ this.setAudioState({ status: "listening" });
748
+ } catch (error) {
749
+ this.cleanupAudioCapture();
750
+ this.setAudioState({
751
+ status: "error",
752
+ error: {
753
+ code: this.extractErrorCode(error) ?? "audio_start_failed",
754
+ message: error instanceof Error ? error.message : "Could not start microphone input."
755
+ }
756
+ });
757
+ }
758
+ }
759
+ async stopVoiceInput() {
760
+ await this.commitVoiceInput();
761
+ }
762
+ cancelVoiceInput() {
763
+ this.audioSessionStopRequested = true;
764
+ this.cleanupAudioCapture();
765
+ this.audioTurnState = null;
766
+ this.setAudioState({
767
+ status: "idle",
768
+ transcript: "",
769
+ partialTranscript: "",
770
+ error: null,
771
+ sessionId: null,
772
+ inputLevel: 0,
773
+ isSpeaking: false,
774
+ speechMs: 0,
775
+ silenceMs: 0
776
+ });
777
+ }
778
+ async loadConversation(conversationId, pageSize = this.config.conversationHistoryPageSize ?? 50) {
779
+ this.isLoadingHistory = true;
780
+ try {
781
+ const page = await this.fetchConversationMessages(conversationId, void 0, pageSize);
782
+ this.applyConversationPage(page, false);
783
+ return page;
784
+ } finally {
785
+ this.isLoadingHistory = false;
786
+ }
787
+ }
788
+ async loadOlderMessages(pageSize = this.config.conversationHistoryPageSize ?? 50) {
789
+ if (!this.conversationId || !this.historyCursor || !this.hasOlderMessages) {
790
+ return null;
791
+ }
792
+ this.isLoadingHistory = true;
793
+ try {
794
+ const page = await this.fetchConversationMessages(this.conversationId, this.historyCursor, pageSize);
795
+ this.applyConversationPage(page, true);
796
+ return page;
797
+ } finally {
798
+ this.isLoadingHistory = false;
799
+ }
800
+ }
801
+ async submitFeedback(input) {
802
+ if (!this.conversationId) {
803
+ throw new Error("No active conversation to rate.");
804
+ }
805
+ const token = await this.resolveAuthToken();
806
+ const response = await fetch(
807
+ `${this.config.agentServiceUrl}/api/v1/chat/conversations/${encodeURIComponent(this.conversationId)}/feedback`,
808
+ {
809
+ method: "POST",
810
+ headers: {
811
+ "Content-Type": "application/json",
812
+ Authorization: `Bearer ${token}`
813
+ },
814
+ body: JSON.stringify(input)
815
+ }
816
+ );
817
+ if (!response.ok) {
818
+ throw new Error(await getResponseErrorMessage(response));
819
+ }
820
+ return await response.json();
821
+ }
822
+ /** Convert client tools to the API schema format. */
823
+ clientToolsToSchemas() {
824
+ if (!this.config.clientTools) return [];
825
+ return Object.entries(this.config.clientTools).map(([name, def]) => ({
826
+ name,
827
+ description: def.description,
828
+ inputSchema: parametersToJsonSchema(def.parameters),
829
+ selection: def.selection
830
+ }));
831
+ }
832
+ resolveExternalUserId() {
833
+ const hostIdentity = this.config.embeddedAuth?.hostIdentity;
834
+ return this.config.externalUserId ?? hostIdentity?.subject ?? hostIdentity?.email ?? void 0;
835
+ }
836
+ buildExternalUserContext() {
837
+ const hostIdentity = this.config.embeddedAuth?.hostIdentity;
838
+ const id = this.resolveExternalUserId();
839
+ const externalUser = {};
840
+ if (id) externalUser.id = id;
841
+ if (hostIdentity?.email) externalUser.email = hostIdentity.email;
842
+ if (hostIdentity?.displayName) externalUser.displayName = hostIdentity.displayName;
843
+ if (hostIdentity?.avatarUrl) externalUser.avatarUrl = hostIdentity.avatarUrl;
844
+ if (hostIdentity?.organizationId) externalUser.organizationId = hostIdentity.organizationId;
845
+ return Object.keys(externalUser).length > 0 ? externalUser : void 0;
846
+ }
847
+ /** Latest runtime budget snapshot for the current SDK identity. */
848
+ getBudgetSnapshot() {
849
+ return this.budgetSnapshot;
850
+ }
851
+ /** Refresh the current SDK identity's budget snapshot from the API. */
852
+ async refreshBudgetSnapshot() {
853
+ const token = await this.resolveAuthToken();
854
+ const params = new URLSearchParams();
855
+ const externalUserId = this.resolveExternalUserId();
856
+ if (externalUserId) {
857
+ params.set("externalUserId", externalUserId);
858
+ }
859
+ const query = params.toString();
860
+ const response = await fetch(
861
+ `${this.config.agentServiceUrl}/api/v1/agents/${this.config.agentId}/budget${query ? `?${query}` : ""}`,
862
+ {
863
+ headers: {
864
+ Authorization: `Bearer ${token}`
865
+ }
866
+ }
867
+ );
868
+ if (!response.ok) {
869
+ throw new Error(await getResponseErrorMessage(response));
870
+ }
871
+ this.budgetSnapshot = await response.json();
872
+ this.emit("budget_snapshot", this.budgetSnapshot);
873
+ return this.budgetSnapshot;
874
+ }
875
+ /** Whether a request is currently in flight */
876
+ getIsLoading() {
877
+ return this.isLoading;
878
+ }
879
+ /** Update the per-turn app context sent with each chat request. */
880
+ setAppContext(context) {
881
+ this.config = {
882
+ ...this.config,
883
+ context
884
+ };
885
+ }
886
+ /** Update the client tools exposed to the agent without recreating the session. */
887
+ setClientTools(clientTools) {
888
+ this.config = {
889
+ ...this.config,
890
+ clientTools
891
+ };
892
+ }
893
+ /**
894
+ * Proactively authenticate with an MCP server before sending a message.
895
+ * If a token response is provided directly, it is stored immediately.
896
+ * Otherwise, this uses the configured OAuth flow and verifies via MCP init.
897
+ *
898
+ * @param mcpServerUrl - The MCP server URL to authenticate with
899
+ * @param tokenResponse - Optional: provide token response directly (from OAuth popup)
900
+ */
901
+ async authenticate(mcpServerUrl, tokenResponse) {
902
+ const wasManuallySignedOut = this.manuallySignedOutServers.delete(mcpServerUrl);
903
+ try {
904
+ if (tokenResponse?.accessToken) {
905
+ if (tokenResponse.resolvedAuthConfig) {
906
+ this.updateServerAuthConfig(mcpServerUrl, tokenResponse.resolvedAuthConfig);
907
+ }
908
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
909
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
910
+ return true;
911
+ }
912
+ const token = await this.resolveToken(mcpServerUrl);
913
+ if (!token) {
914
+ if (wasManuallySignedOut) {
915
+ this.manuallySignedOutServers.add(mcpServerUrl);
916
+ }
917
+ return false;
918
+ }
919
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
920
+ try {
921
+ await this.initMcpSession(mcpServerUrl);
922
+ return true;
923
+ } catch {
924
+ return true;
925
+ }
926
+ } catch {
927
+ if (wasManuallySignedOut) {
928
+ this.manuallySignedOutServers.add(mcpServerUrl);
929
+ }
930
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
931
+ return false;
932
+ }
933
+ }
934
+ /** Disconnect from an MCP server and require explicit re-authentication before reuse. */
935
+ async signOutMcpServer(mcpServerUrl) {
936
+ this.manuallySignedOutServers.add(mcpServerUrl);
937
+ await this.closeMcpSession(mcpServerUrl);
938
+ this.clearOAuthToken(mcpServerUrl);
939
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
940
+ }
941
+ /** Get the auth config for an MCP server (from agent config) */
942
+ getServerAuthConfig(mcpServerUrl) {
943
+ const server = this.agentConfig?.mcpServers?.find((s) => s.url === mcpServerUrl);
944
+ return server?.authConfig ?? null;
945
+ }
946
+ getOAuthCallbackUrl() {
947
+ return this.config.oauthCallbackUrl ?? DEFAULT_OAUTH_CALLBACK_URL;
948
+ }
949
+ getOAuthClientMetadataUrl() {
950
+ return this.config.oauthClientMetadataUrl ?? DEFAULT_OAUTH_CLIENT_METADATA_URL;
951
+ }
952
+ getDefaultAuthRequiredHandler() {
953
+ return this.config.auth?.mode === "app-token" ? createAppTokenAuthHandler(this.config.agentId, this.config.auth) : void 0;
954
+ }
955
+ setOnAuthRequired(onAuthRequired) {
956
+ this.config = {
957
+ ...this.config,
958
+ onAuthRequired: onAuthRequired ?? this.getDefaultAuthRequiredHandler()
959
+ };
960
+ }
961
+ isAudioInputSupported() {
962
+ const audioContextCtor = this.getAudioContextConstructor();
963
+ return typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia) && typeof WebSocket !== "undefined" && Boolean(audioContextCtor) && typeof crypto !== "undefined";
964
+ }
965
+ isAudioInputEnabled() {
966
+ const capabilities = this.agentConfig?.modelConfig?.capabilities;
967
+ return Boolean(
968
+ this.agentConfig?.audio?.inputEnabled && (capabilities?.audioInput ?? capabilities?.realtimeAudioInput)
969
+ );
970
+ }
971
+ isAudioAutoSubmitEnabled() {
972
+ const turnDetection = this.getAudioTurnDetectionConfig();
973
+ return turnDetection.enabled && turnDetection.autoSubmit;
974
+ }
975
+ getAudioTurnDetectionConfig() {
976
+ const override = this.config.audioInput?.turnDetection ?? {};
977
+ return {
978
+ enabled: override.enabled ?? DEFAULT_AUDIO_TURN_DETECTION.enabled,
979
+ autoSubmit: override.autoSubmit ?? DEFAULT_AUDIO_TURN_DETECTION.autoSubmit,
980
+ silenceDurationMs: this.clampNumber(
981
+ override.silenceDurationMs,
982
+ 250,
983
+ 3e3,
984
+ DEFAULT_AUDIO_TURN_DETECTION.silenceDurationMs
985
+ ),
986
+ minSpeechDurationMs: this.clampNumber(
987
+ override.minSpeechDurationMs,
988
+ 80,
989
+ 1e3,
990
+ DEFAULT_AUDIO_TURN_DETECTION.minSpeechDurationMs
991
+ ),
992
+ noSpeechTimeoutMs: this.clampNumber(
993
+ override.noSpeechTimeoutMs,
994
+ 0,
995
+ 6e4,
996
+ DEFAULT_AUDIO_TURN_DETECTION.noSpeechTimeoutMs
997
+ ),
998
+ speechThreshold: this.clampNumber(
999
+ override.speechThreshold,
1000
+ 2e-3,
1001
+ 0.2,
1002
+ DEFAULT_AUDIO_TURN_DETECTION.speechThreshold
1003
+ ),
1004
+ noiseMultiplier: this.clampNumber(
1005
+ override.noiseMultiplier,
1006
+ 1.2,
1007
+ 8,
1008
+ DEFAULT_AUDIO_TURN_DETECTION.noiseMultiplier
1009
+ )
1010
+ };
1011
+ }
1012
+ clampNumber(value, min, max, fallback) {
1013
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1014
+ return fallback;
1015
+ }
1016
+ return Math.min(max, Math.max(min, value));
1017
+ }
1018
+ buildAudioState(patch) {
1019
+ const hasPatch = (key) => Object.prototype.hasOwnProperty.call(patch, key);
1020
+ return {
1021
+ status: patch.status ?? this.audioState.status,
1022
+ isSupported: this.isAudioInputSupported(),
1023
+ isEnabled: this.isAudioInputEnabled(),
1024
+ transcript: patch.transcript ?? this.audioState.transcript,
1025
+ partialTranscript: patch.partialTranscript ?? this.audioState.partialTranscript,
1026
+ error: hasPatch("error") ? patch.error ?? null : this.audioState.error,
1027
+ sessionId: hasPatch("sessionId") ? patch.sessionId ?? null : this.audioState.sessionId ?? null,
1028
+ conversationId: hasPatch("conversationId") ? patch.conversationId ?? null : this.audioState.conversationId ?? this.conversationId,
1029
+ maxSessionSeconds: hasPatch("maxSessionSeconds") ? patch.maxSessionSeconds ?? null : this.audioState.maxSessionSeconds ?? this.agentConfig?.audio?.maxSessionSeconds ?? null,
1030
+ inputLevel: hasPatch("inputLevel") ? patch.inputLevel ?? 0 : this.audioState.inputLevel ?? 0,
1031
+ isSpeaking: hasPatch("isSpeaking") ? patch.isSpeaking ?? false : this.audioState.isSpeaking ?? false,
1032
+ speechMs: hasPatch("speechMs") ? patch.speechMs ?? 0 : this.audioState.speechMs ?? 0,
1033
+ silenceMs: hasPatch("silenceMs") ? patch.silenceMs ?? 0 : this.audioState.silenceMs ?? 0,
1034
+ autoSubmitEnabled: hasPatch("autoSubmitEnabled") ? patch.autoSubmitEnabled ?? false : this.audioState.autoSubmitEnabled ?? this.isAudioAutoSubmitEnabled()
1035
+ };
1036
+ }
1037
+ setAudioState(patch) {
1038
+ this.audioState = this.buildAudioState(patch);
1039
+ this.emit("audio_state", this.audioState);
1040
+ }
1041
+ getAudioContextConstructor() {
1042
+ if (typeof window === "undefined") {
1043
+ return null;
1044
+ }
1045
+ return window.AudioContext ?? window.webkitAudioContext ?? null;
1046
+ }
1047
+ async createRealtimeTranscriptionSession() {
1048
+ const token = await this.resolveAuthToken();
1049
+ const externalUser = this.buildExternalUserContext();
1050
+ const response = await fetch(
1051
+ `${this.config.agentServiceUrl}/api/v1/agents/${encodeURIComponent(this.config.agentId)}/realtime/transcription-sessions`,
1052
+ {
1053
+ method: "POST",
1054
+ headers: {
1055
+ "Content-Type": "application/json",
1056
+ Authorization: `Bearer ${token}`
1057
+ },
1058
+ body: JSON.stringify({
1059
+ conversationId: this.conversationId,
1060
+ externalUserId: this.resolveExternalUserId(),
1061
+ externalUser
1062
+ })
1063
+ }
1064
+ );
1065
+ if (!response.ok) {
1066
+ throw await this.buildApiError(response);
1067
+ }
1068
+ return await response.json();
1069
+ }
1070
+ async buildApiError(response) {
1071
+ let code = null;
1072
+ let message = null;
1073
+ try {
1074
+ const payload = await response.clone().json();
1075
+ if (payload && typeof payload === "object") {
1076
+ const record = payload;
1077
+ code = typeof record.code === "string" ? record.code : null;
1078
+ message = extractErrorMessage(payload);
1079
+ }
1080
+ } catch {
1081
+ }
1082
+ const error = new Error(message ?? await getResponseErrorMessage(response));
1083
+ if (code) {
1084
+ error.code = code;
1085
+ }
1086
+ return error;
1087
+ }
1088
+ async openAudioSocket(url) {
1089
+ return new Promise((resolve, reject) => {
1090
+ const socket = new WebSocket(this.normalizeAudioSocketUrl(url));
1091
+ const cleanup = () => {
1092
+ socket.removeEventListener("open", handleOpen);
1093
+ socket.removeEventListener("error", handleError);
1094
+ };
1095
+ const handleOpen = () => {
1096
+ cleanup();
1097
+ resolve(socket);
1098
+ };
1099
+ const handleError = () => {
1100
+ cleanup();
1101
+ reject(new Error("Could not connect to the realtime microphone service."));
1102
+ };
1103
+ socket.addEventListener("open", handleOpen);
1104
+ socket.addEventListener("error", handleError);
1105
+ });
1106
+ }
1107
+ normalizeAudioSocketUrl(url) {
1108
+ if (typeof window === "undefined") {
1109
+ return url;
1110
+ }
1111
+ try {
1112
+ const parsed = new URL(url, window.location.href);
1113
+ if (window.location.protocol === "https:" && parsed.protocol === "ws:") {
1114
+ parsed.protocol = "wss:";
1115
+ }
1116
+ return parsed.toString();
1117
+ } catch {
1118
+ return url;
1119
+ }
1120
+ }
1121
+ bindAudioSocket(socket) {
1122
+ socket.addEventListener("message", (event) => {
1123
+ void this.handleAudioSocketMessage(event);
1124
+ });
1125
+ socket.addEventListener("close", () => {
1126
+ if (this.audioSocket !== socket) {
1127
+ return;
1128
+ }
1129
+ this.audioSocket = null;
1130
+ this.clearAudioSessionTimer();
1131
+ if (this.audioState.status === "listening" || this.audioState.status === "transcribing" || this.audioState.status === "connecting") {
1132
+ this.cleanupAudioCapture(false);
1133
+ this.audioTurnState = null;
1134
+ this.setAudioState({
1135
+ status: "idle",
1136
+ inputLevel: 0,
1137
+ isSpeaking: false,
1138
+ speechMs: 0,
1139
+ silenceMs: 0
1140
+ });
1141
+ }
1142
+ });
1143
+ socket.addEventListener("error", () => {
1144
+ if (this.audioSocket !== socket) {
1145
+ return;
1146
+ }
1147
+ this.cleanupAudioCapture();
1148
+ this.audioTurnState = null;
1149
+ this.setAudioState({
1150
+ status: "error",
1151
+ error: {
1152
+ code: "audio_socket_error",
1153
+ message: "The realtime microphone connection failed."
1154
+ },
1155
+ inputLevel: 0,
1156
+ isSpeaking: false,
1157
+ speechMs: 0,
1158
+ silenceMs: 0
1159
+ });
1160
+ });
1161
+ }
1162
+ async handleAudioSocketMessage(event) {
1163
+ const raw = typeof event.data === "string" ? event.data : event.data instanceof Blob ? await event.data.text() : "";
1164
+ if (!raw) {
1165
+ return;
1166
+ }
1167
+ let payload;
1168
+ try {
1169
+ payload = JSON.parse(raw);
1170
+ } catch {
1171
+ return;
1172
+ }
1173
+ const type = typeof payload.type === "string" ? payload.type : "";
1174
+ if (type === "transcript_delta") {
1175
+ const text = typeof payload.text === "string" ? payload.text : "";
1176
+ if (!text) {
1177
+ return;
1178
+ }
1179
+ this.audioFinalTranscript += text;
1180
+ this.setAudioState({
1181
+ partialTranscript: this.audioFinalTranscript,
1182
+ transcript: this.audioFinalTranscript
1183
+ });
1184
+ this.emit("audio_transcript_delta", {
1185
+ text,
1186
+ transcript: this.audioFinalTranscript,
1187
+ isFinal: false
1188
+ });
1189
+ return;
1190
+ }
1191
+ if (type === "transcript_final") {
1192
+ const finalText = (typeof payload.text === "string" && payload.text.trim() ? payload.text : this.audioFinalTranscript).trim();
1193
+ this.cleanupAudioCapture();
1194
+ this.audioTurnState = null;
1195
+ if (!finalText) {
1196
+ this.setAudioState({
1197
+ status: "idle",
1198
+ transcript: "",
1199
+ partialTranscript: "",
1200
+ inputLevel: 0,
1201
+ isSpeaking: false,
1202
+ speechMs: 0,
1203
+ silenceMs: 0
1204
+ });
1205
+ return;
1206
+ }
1207
+ this.setAudioState({
1208
+ status: "sending",
1209
+ transcript: finalText,
1210
+ partialTranscript: "",
1211
+ error: null,
1212
+ inputLevel: 0,
1213
+ isSpeaking: false
1214
+ });
1215
+ this.emit("audio_transcript_final", {
1216
+ text: finalText,
1217
+ transcript: finalText,
1218
+ conversationId: this.conversationId ?? ""
1219
+ });
1220
+ await this.sendMessage(finalText);
1221
+ this.setAudioState({
1222
+ status: "idle",
1223
+ transcript: finalText,
1224
+ partialTranscript: "",
1225
+ sessionId: null,
1226
+ inputLevel: 0,
1227
+ isSpeaking: false,
1228
+ speechMs: 0,
1229
+ silenceMs: 0
1230
+ });
1231
+ return;
1232
+ }
1233
+ if (type === "error") {
1234
+ const code = typeof payload.code === "string" ? payload.code : "audio_error";
1235
+ const message = typeof payload.message === "string" ? payload.message : "Microphone input failed.";
1236
+ this.cleanupAudioCapture();
1237
+ this.audioTurnState = null;
1238
+ this.setAudioState({
1239
+ status: "error",
1240
+ error: { code, message },
1241
+ inputLevel: 0,
1242
+ isSpeaking: false,
1243
+ speechMs: 0,
1244
+ silenceMs: 0
1245
+ });
1246
+ }
1247
+ }
1248
+ async commitVoiceInput() {
1249
+ if (this.audioSessionStopRequested || this.audioState.status !== "listening" && this.audioState.status !== "connecting") {
1250
+ return;
1251
+ }
1252
+ this.audioSessionStopRequested = true;
1253
+ this.cleanupAudioCapture(false);
1254
+ if (this.audioSocket?.readyState === WebSocket.OPEN) {
1255
+ this.audioSocket.send(JSON.stringify({ type: "audio.commit" }));
1256
+ this.setAudioState({
1257
+ status: "transcribing",
1258
+ inputLevel: 0,
1259
+ isSpeaking: false,
1260
+ silenceMs: this.audioTurnState?.silenceMs ?? this.audioState.silenceMs ?? 0,
1261
+ speechMs: this.audioTurnState?.speechMs ?? this.audioState.speechMs ?? 0
1262
+ });
1263
+ return;
1264
+ }
1265
+ this.audioTurnState = null;
1266
+ this.setAudioState({
1267
+ status: "idle",
1268
+ inputLevel: 0,
1269
+ isSpeaking: false,
1270
+ speechMs: 0,
1271
+ silenceMs: 0
1272
+ });
1273
+ }
1274
+ stopVoiceInputWithoutTranscript(message) {
1275
+ this.audioSessionStopRequested = true;
1276
+ this.cleanupAudioCapture();
1277
+ this.audioTurnState = null;
1278
+ this.setAudioState({
1279
+ status: "idle",
1280
+ transcript: "",
1281
+ partialTranscript: "",
1282
+ sessionId: null,
1283
+ inputLevel: 0,
1284
+ isSpeaking: false,
1285
+ speechMs: 0,
1286
+ silenceMs: 0,
1287
+ error: {
1288
+ code: "no_speech_detected",
1289
+ message
1290
+ }
1291
+ });
1292
+ }
1293
+ createAudioTurnState(nowMs) {
1294
+ return {
1295
+ startedAtMs: nowMs,
1296
+ lastFrameAtMs: nowMs,
1297
+ speechStartedAtMs: null,
1298
+ lastSpeechAtMs: null,
1299
+ speechMs: 0,
1300
+ silenceMs: 0,
1301
+ noiseFloor: DEFAULT_AUDIO_TURN_DETECTION.speechThreshold / 2,
1302
+ isSpeaking: false,
1303
+ autoCommitted: false,
1304
+ lastActivityEmitMs: 0
1305
+ };
1306
+ }
1307
+ analyzeAudioFrame(input, durationMs) {
1308
+ if (input.length === 0) {
1309
+ return { rms: 0, peak: 0, inputLevel: 0, durationMs };
1310
+ }
1311
+ let sumSquares = 0;
1312
+ let peak = 0;
1313
+ for (let index = 0; index < input.length; index += 1) {
1314
+ const sample = input[index];
1315
+ const abs = Math.abs(sample);
1316
+ sumSquares += sample * sample;
1317
+ if (abs > peak) {
1318
+ peak = abs;
1319
+ }
1320
+ }
1321
+ const rms = Math.sqrt(sumSquares / input.length);
1322
+ return {
1323
+ rms,
1324
+ peak,
1325
+ inputLevel: Math.min(1, rms * 14),
1326
+ durationMs
1327
+ };
1328
+ }
1329
+ processAudioTurnActivity(activity, nowMs) {
1330
+ const config = this.getAudioTurnDetectionConfig();
1331
+ if (!config.enabled) {
1332
+ this.emitAudioActivity(activity, nowMs, false, 0, 0, DEFAULT_AUDIO_TURN_DETECTION.speechThreshold / 2);
1333
+ return;
1334
+ }
1335
+ const state = this.audioTurnState ?? this.createAudioTurnState(nowMs);
1336
+ this.audioTurnState = state;
1337
+ const frameGapMs = Math.max(1, nowMs - state.lastFrameAtMs);
1338
+ const frameDurationMs = Math.max(activity.durationMs, frameGapMs);
1339
+ state.lastFrameAtMs = nowMs;
1340
+ const adaptiveThreshold = Math.max(
1341
+ config.speechThreshold,
1342
+ Math.min(0.08, state.noiseFloor * config.noiseMultiplier)
1343
+ );
1344
+ const peakThreshold = Math.max(adaptiveThreshold * 2.2, config.speechThreshold * 2.5);
1345
+ const speechCandidate = activity.rms >= adaptiveThreshold || activity.rms >= adaptiveThreshold * 0.72 && activity.peak >= peakThreshold;
1346
+ if (speechCandidate) {
1347
+ if (state.speechStartedAtMs === null) {
1348
+ state.speechStartedAtMs = nowMs;
1349
+ state.speechMs = 0;
1350
+ }
1351
+ state.lastSpeechAtMs = nowMs;
1352
+ state.speechMs += frameDurationMs;
1353
+ state.silenceMs = 0;
1354
+ state.isSpeaking = true;
1355
+ } else {
1356
+ state.noiseFloor = this.updateNoiseFloor(state.noiseFloor, activity.rms);
1357
+ state.isSpeaking = false;
1358
+ if (state.lastSpeechAtMs !== null) {
1359
+ state.silenceMs = nowMs - state.lastSpeechAtMs;
1360
+ }
1361
+ }
1362
+ if (state.speechStartedAtMs !== null && state.speechMs < config.minSpeechDurationMs && state.silenceMs >= config.silenceDurationMs) {
1363
+ state.speechStartedAtMs = null;
1364
+ state.lastSpeechAtMs = null;
1365
+ state.speechMs = 0;
1366
+ state.silenceMs = 0;
1367
+ }
1368
+ this.emitAudioActivity(
1369
+ activity,
1370
+ nowMs,
1371
+ state.isSpeaking,
1372
+ state.speechMs,
1373
+ state.silenceMs,
1374
+ state.noiseFloor
1375
+ );
1376
+ const noSpeechElapsedMs = nowMs - state.startedAtMs;
1377
+ if (config.noSpeechTimeoutMs > 0 && state.speechStartedAtMs === null && noSpeechElapsedMs >= config.noSpeechTimeoutMs && !state.autoCommitted) {
1378
+ state.autoCommitted = true;
1379
+ this.stopVoiceInputWithoutTranscript("No speech was detected. Try again when you are ready to speak.");
1380
+ return;
1381
+ }
1382
+ if (config.autoSubmit && state.speechStartedAtMs !== null && state.speechMs >= config.minSpeechDurationMs && state.silenceMs >= config.silenceDurationMs && !state.autoCommitted) {
1383
+ state.autoCommitted = true;
1384
+ void this.commitVoiceInput();
1385
+ }
1386
+ }
1387
+ updateNoiseFloor(currentNoiseFloor, rms) {
1388
+ const sample = Math.max(15e-4, Math.min(0.08, rms));
1389
+ const smoothing = sample > currentNoiseFloor ? 0.02 : 0.12;
1390
+ return currentNoiseFloor * (1 - smoothing) + sample * smoothing;
1391
+ }
1392
+ emitAudioActivity(activity, nowMs, isSpeaking, speechMs, silenceMs, noiseFloor) {
1393
+ const state = this.audioTurnState;
1394
+ const shouldEmitState = !state || nowMs - state.lastActivityEmitMs >= AUDIO_ACTIVITY_EMIT_INTERVAL_MS || isSpeaking !== this.audioState.isSpeaking || Math.abs(activity.inputLevel - (this.audioState.inputLevel ?? 0)) >= MIN_AUDIO_LEVEL_DELTA_FOR_STATE;
1395
+ if (!shouldEmitState) {
1396
+ return;
1397
+ }
1398
+ if (state) {
1399
+ state.lastActivityEmitMs = nowMs;
1400
+ }
1401
+ const roundedLevel = Number(activity.inputLevel.toFixed(3));
1402
+ const roundedNoiseFloor = Number(noiseFloor.toFixed(5));
1403
+ this.setAudioState({
1404
+ inputLevel: roundedLevel,
1405
+ isSpeaking,
1406
+ speechMs: Math.round(speechMs),
1407
+ silenceMs: Math.round(silenceMs),
1408
+ autoSubmitEnabled: this.isAudioAutoSubmitEnabled()
1409
+ });
1410
+ this.emit("audio_activity", {
1411
+ inputLevel: roundedLevel,
1412
+ noiseFloor: roundedNoiseFloor,
1413
+ isSpeaking,
1414
+ speechMs: Math.round(speechMs),
1415
+ silenceMs: Math.round(silenceMs)
1416
+ });
1417
+ }
1418
+ async startAudioCapture(stream, socket) {
1419
+ const AudioContextCtor = this.getAudioContextConstructor();
1420
+ if (!AudioContextCtor) {
1421
+ throw new Error("Audio capture is not available in this browser.");
1422
+ }
1423
+ const context = new AudioContextCtor();
1424
+ if (context.state === "suspended") {
1425
+ await context.resume();
1426
+ }
1427
+ const source = context.createMediaStreamSource(stream);
1428
+ const processor = context.createScriptProcessor(4096, 1, 1);
1429
+ const silentGain = context.createGain();
1430
+ silentGain.gain.value = 0;
1431
+ this.audioTurnState = this.createAudioTurnState(performance.now());
1432
+ processor.onaudioprocess = (event) => {
1433
+ if (this.audioSessionStopRequested || socket.readyState !== WebSocket.OPEN || this.audioState.status !== "listening") {
1434
+ return;
1435
+ }
1436
+ const input = event.inputBuffer.getChannelData(0);
1437
+ const durationMs = input.length / context.sampleRate * 1e3;
1438
+ this.processAudioTurnActivity(
1439
+ this.analyzeAudioFrame(input, durationMs),
1440
+ performance.now()
1441
+ );
1442
+ if (this.audioSessionStopRequested) {
1443
+ return;
1444
+ }
1445
+ const resampled = this.resampleToPcm16(input, context.sampleRate, 24e3);
1446
+ if (resampled.length === 0) {
1447
+ return;
1448
+ }
1449
+ socket.send(JSON.stringify({
1450
+ type: "audio.append",
1451
+ audio: this.pcm16ToBase64(resampled)
1452
+ }));
1453
+ };
1454
+ source.connect(processor);
1455
+ processor.connect(silentGain);
1456
+ silentGain.connect(context.destination);
1457
+ this.audioContext = context;
1458
+ this.audioSource = source;
1459
+ this.audioProcessor = processor;
1460
+ this.audioSilentGain = silentGain;
1461
+ }
1462
+ resampleToPcm16(input, inputSampleRate, outputSampleRate) {
1463
+ if (inputSampleRate === outputSampleRate) {
1464
+ return this.floatToPcm16(input);
1465
+ }
1466
+ const ratio = inputSampleRate / outputSampleRate;
1467
+ const outputLength = Math.floor(input.length / ratio);
1468
+ const output = new Float32Array(outputLength);
1469
+ for (let index = 0; index < outputLength; index += 1) {
1470
+ const inputIndex = index * ratio;
1471
+ const lower = Math.floor(inputIndex);
1472
+ const upper = Math.min(lower + 1, input.length - 1);
1473
+ const weight = inputIndex - lower;
1474
+ output[index] = input[lower] * (1 - weight) + input[upper] * weight;
1475
+ }
1476
+ return this.floatToPcm16(output);
1477
+ }
1478
+ floatToPcm16(input) {
1479
+ const output = new Int16Array(input.length);
1480
+ for (let index = 0; index < input.length; index += 1) {
1481
+ const sample = Math.max(-1, Math.min(1, input[index]));
1482
+ output[index] = sample < 0 ? sample * 32768 : sample * 32767;
1483
+ }
1484
+ return output;
1485
+ }
1486
+ pcm16ToBase64(input) {
1487
+ const bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
1488
+ let binary = "";
1489
+ const chunkSize = 32768;
1490
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
1491
+ const chunk = bytes.subarray(offset, offset + chunkSize);
1492
+ binary += String.fromCharCode(...chunk);
1493
+ }
1494
+ return btoa(binary);
1495
+ }
1496
+ cleanupAudioCapture(closeSocket = true) {
1497
+ this.clearAudioSessionTimer();
1498
+ this.audioProcessor?.disconnect();
1499
+ this.audioSource?.disconnect();
1500
+ this.audioSilentGain?.disconnect();
1501
+ this.audioProcessor = null;
1502
+ this.audioSource = null;
1503
+ this.audioSilentGain = null;
1504
+ if (this.audioContext) {
1505
+ void this.audioContext.close().catch(() => void 0);
1506
+ this.audioContext = null;
1507
+ }
1508
+ this.audioStream?.getTracks().forEach((track) => track.stop());
1509
+ this.audioStream = null;
1510
+ if (closeSocket && this.audioSocket) {
1511
+ const socket = this.audioSocket;
1512
+ this.audioSocket = null;
1513
+ if (socket.readyState === WebSocket.OPEN) {
1514
+ socket.send(JSON.stringify({ type: "audio.close" }));
1515
+ socket.close();
1516
+ } else if (socket.readyState === WebSocket.CONNECTING) {
1517
+ socket.close();
1518
+ }
1519
+ }
1520
+ }
1521
+ clearAudioSessionTimer() {
1522
+ if (!this.audioSessionTimer) {
1523
+ return;
1524
+ }
1525
+ clearTimeout(this.audioSessionTimer);
1526
+ this.audioSessionTimer = null;
1527
+ }
1528
+ extractErrorCode(error) {
1529
+ if (error && typeof error === "object" && "code" in error) {
1530
+ const code = error.code;
1531
+ return typeof code === "string" ? code : null;
1532
+ }
1533
+ return null;
1534
+ }
1535
+ getPersistentStorage() {
1536
+ return this.config.storage ?? null;
1537
+ }
1538
+ async resolveOAuthClientRegistration(authConfig) {
1539
+ if (!authConfig || authConfig.authType !== "oauth2") {
1540
+ return authConfig ?? null;
1541
+ }
1542
+ const registration = await resolveOAuthRegistration(authConfig, {
1543
+ callbackUrl: this.getOAuthCallbackUrl(),
1544
+ oauthClientMetadataUrl: this.config.oauthClientMetadataUrl,
1545
+ clientName: "MCP Stack MCP Client",
1546
+ clientUri: "https://mcpstack.com",
1547
+ storage: this.getPersistentStorage()
1548
+ });
1549
+ return applyResolvedRegistration(authConfig, registration);
1550
+ }
1551
+ /** Subscribe to events */
1552
+ on(event, handler) {
1553
+ if (!this.listeners.has(event)) {
1554
+ this.listeners.set(event, /* @__PURE__ */ new Set());
1555
+ }
1556
+ this.listeners.get(event).add(handler);
1557
+ }
1558
+ /** Unsubscribe from events */
1559
+ off(event, handler) {
1560
+ this.listeners.get(event)?.delete(handler);
1561
+ }
1562
+ // ================================================================
1563
+ // Private methods
1564
+ // ================================================================
1565
+ buildProtectedResourceMetadataCandidates(mcpServerUrl) {
1566
+ const url = new URL(mcpServerUrl);
1567
+ const candidates = /* @__PURE__ */ new Set();
1568
+ const normalizedPath = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1569
+ if (!normalizedPath || normalizedPath === "/") {
1570
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource`);
1571
+ return [...candidates];
1572
+ }
1573
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource${normalizedPath}`);
1574
+ candidates.add(`${url.origin}${normalizedPath}/.well-known/oauth-protected-resource`);
1575
+ candidates.add(`${url.origin}/.well-known/oauth-protected-resource`);
1576
+ return [...candidates];
1577
+ }
1578
+ hasSameOrigin(left, right) {
1579
+ try {
1580
+ const leftUrl = new URL(left);
1581
+ const rightUrl = new URL(right);
1582
+ return leftUrl.origin === rightUrl.origin;
1583
+ } catch {
1584
+ return false;
1585
+ }
1586
+ }
1587
+ extractQuotedHeaderValue(header, key) {
1588
+ const match = header.match(new RegExp(`${key}="([^"]+)"`, "i"));
1589
+ return match?.[1] ?? null;
1590
+ }
1591
+ buildAuthorizationServerMetadataCandidates(issuerOrMetadataUrl) {
1592
+ const candidates = /* @__PURE__ */ new Set();
1593
+ if (issuerOrMetadataUrl.includes("/.well-known/oauth-authorization-server") || issuerOrMetadataUrl.includes("/.well-known/openid-configuration")) {
1594
+ candidates.add(issuerOrMetadataUrl);
1595
+ return [...candidates];
1596
+ }
1597
+ const url = new URL(issuerOrMetadataUrl);
1598
+ const normalizedPath = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1599
+ if (!normalizedPath || normalizedPath === "/") {
1600
+ candidates.add(`${url.origin}/.well-known/oauth-authorization-server`);
1601
+ candidates.add(`${url.origin}/.well-known/openid-configuration`);
1602
+ return [...candidates];
1603
+ }
1604
+ candidates.add(`${url.origin}/.well-known/oauth-authorization-server${normalizedPath}`);
1605
+ candidates.add(`${url.origin}/.well-known/openid-configuration${normalizedPath}`);
1606
+ candidates.add(`${url.origin}${normalizedPath}/.well-known/openid-configuration`);
1607
+ return [...candidates];
1608
+ }
1609
+ hasExplicitManualOverride(manualConfig, field) {
1610
+ return manualConfig?.manualOverrides?.includes(field) ?? false;
1611
+ }
1612
+ pickAuthConfigValue(field, manualConfig, manualValue, discoveredValue) {
1613
+ if (this.hasExplicitManualOverride(manualConfig, field) && manualValue != null) {
1614
+ return manualValue;
1615
+ }
1616
+ return discoveredValue ?? manualValue;
1617
+ }
1618
+ pickAuthConfigArrayValue(field, manualConfig, manualValue, discoveredValue) {
1619
+ if (this.hasExplicitManualOverride(manualConfig, field) && manualValue?.length) {
1620
+ return manualValue;
1621
+ }
1622
+ if (discoveredValue?.length) {
1623
+ return discoveredValue;
1624
+ }
1625
+ return manualValue?.length ? manualValue : void 0;
1626
+ }
1627
+ mergeAuthConfigs(manualConfig, discoveredConfig) {
1628
+ if (!manualConfig && !discoveredConfig) return null;
1629
+ const manualOverrides = new Set(manualConfig?.manualOverrides ?? []);
1630
+ const authorizationEndpoint = this.pickAuthConfigValue(
1631
+ "authorizationEndpoint",
1632
+ manualConfig,
1633
+ manualConfig?.authorizationEndpoint ?? manualConfig?.loginUrl,
1634
+ discoveredConfig?.authorizationEndpoint ?? discoveredConfig?.loginUrl
1635
+ );
1636
+ const tokenEndpoint = this.pickAuthConfigValue(
1637
+ "tokenEndpoint",
1638
+ manualConfig,
1639
+ manualConfig?.tokenEndpoint ?? manualConfig?.tokenUrl,
1640
+ discoveredConfig?.tokenEndpoint ?? discoveredConfig?.tokenUrl
1641
+ );
1642
+ const callbackUrl = this.pickAuthConfigValue(
1643
+ "callbackUrl",
1644
+ manualConfig,
1645
+ manualConfig?.callbackUrl,
1646
+ discoveredConfig?.callbackUrl
1647
+ ) ?? this.getOAuthCallbackUrl();
1648
+ const merged = {
1649
+ authType: manualConfig?.authType ?? discoveredConfig?.authType ?? "oauth2",
1650
+ issuer: discoveredConfig?.issuer ?? manualConfig?.issuer,
1651
+ authorizationServerUrl: this.pickAuthConfigValue(
1652
+ "authorizationServerUrl",
1653
+ manualConfig,
1654
+ manualConfig?.authorizationServerUrl,
1655
+ discoveredConfig?.authorizationServerUrl
1656
+ ),
1657
+ authorizationServerMetadataUrl: this.pickAuthConfigValue(
1658
+ "authorizationServerMetadataUrl",
1659
+ manualConfig,
1660
+ manualConfig?.authorizationServerMetadataUrl,
1661
+ discoveredConfig?.authorizationServerMetadataUrl
1662
+ ),
1663
+ authorizationEndpoint,
1664
+ loginUrl: authorizationEndpoint,
1665
+ tokenEndpoint,
1666
+ tokenUrl: tokenEndpoint,
1667
+ registrationEndpoint: this.pickAuthConfigValue(
1668
+ "registrationEndpoint",
1669
+ manualConfig,
1670
+ manualConfig?.registrationEndpoint,
1671
+ discoveredConfig?.registrationEndpoint
1672
+ ),
1673
+ clientId: this.pickAuthConfigValue(
1674
+ "clientId",
1675
+ manualConfig,
1676
+ manualConfig?.clientId,
1677
+ discoveredConfig?.clientId
1678
+ ),
1679
+ scopes: this.pickAuthConfigArrayValue(
1680
+ "scopes",
1681
+ manualConfig,
1682
+ manualConfig?.scopes,
1683
+ discoveredConfig?.scopes
1684
+ ),
1685
+ resource: this.pickAuthConfigValue(
1686
+ "resource",
1687
+ manualConfig,
1688
+ manualConfig?.resource,
1689
+ discoveredConfig?.resource
1690
+ ),
1691
+ callbackUrl,
1692
+ protectedResourceMetadataUrl: discoveredConfig?.protectedResourceMetadataUrl ?? manualConfig?.protectedResourceMetadataUrl,
1693
+ clientIdMetadataDocumentSupported: discoveredConfig?.clientIdMetadataDocumentSupported ?? manualConfig?.clientIdMetadataDocumentSupported,
1694
+ resourceParameterSupported: discoveredConfig?.resourceParameterSupported ?? manualConfig?.resourceParameterSupported,
1695
+ registrationPreference: manualConfig?.registrationPreference ?? discoveredConfig?.registrationPreference ?? "auto",
1696
+ clientMode: discoveredConfig?.clientMode ?? manualConfig?.clientMode,
1697
+ authRecipe: manualConfig?.authRecipe ?? discoveredConfig?.authRecipe,
1698
+ manualOverrides: manualOverrides.size ? [...manualOverrides] : void 0,
1699
+ discovered: discoveredConfig?.discovered ?? false
1700
+ };
1701
+ return merged;
1702
+ }
1703
+ async discoverAuthConfig(mcpServerUrl, manualConfig) {
1704
+ let protectedResourceUrl = null;
1705
+ let protectedResource = null;
1706
+ const protectedResourceCandidates = /* @__PURE__ */ new Set();
1707
+ if (manualConfig?.protectedResourceMetadataUrl) {
1708
+ protectedResourceCandidates.add(manualConfig.protectedResourceMetadataUrl);
1709
+ }
1710
+ for (const candidate of this.buildProtectedResourceMetadataCandidates(mcpServerUrl)) {
1711
+ protectedResourceCandidates.add(candidate);
1712
+ }
1713
+ for (const candidate of protectedResourceCandidates) {
1714
+ try {
1715
+ const response = await fetch(candidate, {
1716
+ method: "GET",
1717
+ headers: { Accept: "application/json" }
1718
+ });
1719
+ if (response.ok) {
1720
+ protectedResource = await response.json();
1721
+ protectedResourceUrl = candidate;
1722
+ break;
1723
+ }
1724
+ const authenticateHeader = response.headers.get("www-authenticate");
1725
+ if (authenticateHeader) {
1726
+ const resourceMetadataUrl = this.extractQuotedHeaderValue(authenticateHeader, "resource_metadata");
1727
+ if (resourceMetadataUrl && this.hasSameOrigin(candidate, resourceMetadataUrl)) {
1728
+ const metadataResponse = await fetch(resourceMetadataUrl, {
1729
+ method: "GET",
1730
+ headers: { Accept: "application/json" }
1731
+ });
1732
+ if (metadataResponse.ok) {
1733
+ protectedResource = await metadataResponse.json();
1734
+ protectedResourceUrl = resourceMetadataUrl;
1735
+ break;
1736
+ }
1737
+ }
1738
+ }
1739
+ } catch {
1740
+ }
1741
+ }
1742
+ const authServerUrl = protectedResource?.authorization_servers?.[0] ?? protectedResource?.authorization_server ?? manualConfig?.authorizationServerUrl;
1743
+ try {
1744
+ let metadata = null;
1745
+ let metadataUrl = manualConfig?.authorizationServerMetadataUrl ?? null;
1746
+ const metadataCandidates = /* @__PURE__ */ new Set();
1747
+ if (manualConfig?.authorizationServerMetadataUrl) {
1748
+ metadataCandidates.add(manualConfig.authorizationServerMetadataUrl);
1749
+ }
1750
+ if (authServerUrl) {
1751
+ for (const candidate of this.buildAuthorizationServerMetadataCandidates(authServerUrl)) {
1752
+ metadataCandidates.add(candidate);
1753
+ }
1754
+ }
1755
+ for (const candidate of metadataCandidates) {
1756
+ try {
1757
+ const response = await fetch(candidate, {
1758
+ method: "GET",
1759
+ headers: { Accept: "application/json" }
1760
+ });
1761
+ if (response.ok) {
1762
+ metadata = await response.json();
1763
+ metadataUrl = candidate;
1764
+ break;
1765
+ }
1766
+ } catch {
1767
+ }
1768
+ }
1769
+ if (!metadata && !protectedResource && !manualConfig) {
1770
+ return null;
1771
+ }
1772
+ return {
1773
+ authType: "oauth2",
1774
+ issuer: metadata?.issuer ?? authServerUrl ?? manualConfig?.issuer,
1775
+ authorizationServerUrl: authServerUrl ?? manualConfig?.authorizationServerUrl,
1776
+ authorizationServerMetadataUrl: metadataUrl ?? void 0,
1777
+ authorizationEndpoint: metadata?.authorization_endpoint ?? manualConfig?.authorizationEndpoint ?? manualConfig?.loginUrl,
1778
+ loginUrl: metadata?.authorization_endpoint ?? manualConfig?.loginUrl ?? manualConfig?.authorizationEndpoint,
1779
+ tokenEndpoint: metadata?.token_endpoint ?? manualConfig?.tokenEndpoint ?? manualConfig?.tokenUrl,
1780
+ tokenUrl: metadata?.token_endpoint ?? manualConfig?.tokenUrl ?? manualConfig?.tokenEndpoint,
1781
+ registrationEndpoint: metadata?.registration_endpoint ?? manualConfig?.registrationEndpoint,
1782
+ clientId: manualConfig?.clientId,
1783
+ scopes: protectedResource?.scopes_supported?.length ? protectedResource.scopes_supported : metadata?.scopes_supported ?? manualConfig?.scopes,
1784
+ resource: protectedResource?.resource ?? manualConfig?.resource,
1785
+ callbackUrl: getEffectiveCallbackUrl(manualConfig, this.getOAuthCallbackUrl()),
1786
+ protectedResourceMetadataUrl: protectedResourceUrl ?? manualConfig?.protectedResourceMetadataUrl,
1787
+ clientIdMetadataDocumentSupported: metadata?.client_id_metadata_document_supported ?? manualConfig?.clientIdMetadataDocumentSupported,
1788
+ resourceParameterSupported: metadata?.resource_parameter_supported ?? manualConfig?.resourceParameterSupported,
1789
+ registrationPreference: manualConfig?.registrationPreference ?? "auto",
1790
+ authRecipe: manualConfig?.authRecipe,
1791
+ discovered: Boolean(protectedResource || metadata)
1792
+ };
1793
+ } catch {
1794
+ return manualConfig ? {
1795
+ ...manualConfig,
1796
+ callbackUrl: getEffectiveCallbackUrl(manualConfig, this.getOAuthCallbackUrl()),
1797
+ protectedResourceMetadataUrl: protectedResourceUrl ?? manualConfig.protectedResourceMetadataUrl,
1798
+ resource: protectedResource?.resource ?? manualConfig.resource,
1799
+ scopes: protectedResource?.scopes_supported?.length ? protectedResource.scopes_supported : manualConfig.scopes,
1800
+ discovered: Boolean(protectedResource)
1801
+ } : null;
1802
+ }
1803
+ }
1804
+ async resolveServerAuthConfig(mcpServerUrl, manualConfig) {
1805
+ const discoveredConfig = await this.discoverAuthConfig(mcpServerUrl, manualConfig);
1806
+ return this.mergeAuthConfigs(manualConfig, discoveredConfig);
1807
+ }
1808
+ async ensureServerAuthConfig(mcpServerUrl) {
1809
+ const server = this.agentConfig?.mcpServers?.find((item) => item.url === mcpServerUrl);
1810
+ if (!server) {
1811
+ return null;
1812
+ }
1813
+ if (server.authConfig && (server.authConfig.authType !== "oauth2" || server.authConfig.discovered || !!server.authConfig.authorizationEndpoint || !!server.authConfig.tokenEndpoint || !!server.authConfig.tokenUrl || !!server.authConfig.registrationEndpoint || !!server.authConfig.resource)) {
1814
+ return server.authConfig;
1815
+ }
1816
+ server.authConfig = await this.resolveServerAuthConfig(mcpServerUrl, server.authConfig ?? null);
1817
+ return server.authConfig;
1818
+ }
1819
+ updateServerAuthConfig(mcpServerUrl, authConfig) {
1820
+ const server = this.agentConfig?.mcpServers?.find((item) => item.url === mcpServerUrl);
1821
+ if (server) {
1822
+ server.authConfig = authConfig;
1823
+ }
1824
+ }
1825
+ emit(event, data) {
1826
+ this.listeners.get(event)?.forEach((handler) => handler(data));
1827
+ }
1828
+ // ================================================================
1829
+ // OAuth Token Storage (standalone mode only)
1830
+ // ================================================================
1831
+ /** Generate the legacy token cache suffix used before auth-aware keying. */
1832
+ hashUrl(url) {
1833
+ return btoa(url).replace(/[^a-zA-Z0-9]/g, "").slice(0, 32);
1834
+ }
1835
+ getLegacyTokenStorageKey(mcpServerUrl) {
1836
+ return buildScopedOAuthTokenStorageKey(this.hashUrl(mcpServerUrl));
1837
+ }
1838
+ getAuthSessionKey() {
1839
+ return resolveExplicitAuthSessionKey(this.config);
1840
+ }
1841
+ getTokenStorageKey(mcpServerUrl, authConfig) {
1842
+ return buildScopedOAuthTokenStorageKey(
1843
+ buildTokenCacheKey(authConfig, mcpServerUrl),
1844
+ this.getAuthSessionKey()
1845
+ );
1846
+ }
1847
+ getTokenStorageCandidates(mcpServerUrl) {
1848
+ const currentAuthConfig = this.getServerAuthConfig(mcpServerUrl);
1849
+ const hasExplicitAuthSessionKey = this.getAuthSessionKey() !== null;
1850
+ if (!currentAuthConfig) {
1851
+ return hasExplicitAuthSessionKey ? [{
1852
+ storageKey: this.getTokenStorageKey(mcpServerUrl, null),
1853
+ authConfig: null
1854
+ }] : [{
1855
+ storageKey: this.getLegacyTokenStorageKey(mcpServerUrl),
1856
+ authConfig: null
1857
+ }];
1858
+ }
1859
+ const callbackUrl = getEffectiveCallbackUrl(currentAuthConfig, this.getOAuthCallbackUrl());
1860
+ const candidates = [currentAuthConfig];
1861
+ if (currentAuthConfig.authType === "oauth2") {
1862
+ candidates.push({
1863
+ ...currentAuthConfig,
1864
+ clientMode: "manual",
1865
+ callbackUrl
1866
+ });
1867
+ if (currentAuthConfig.clientId) {
1868
+ candidates.push({
1869
+ ...currentAuthConfig,
1870
+ clientMode: "preregistered",
1871
+ callbackUrl
1872
+ });
1873
+ }
1874
+ if (currentAuthConfig.clientIdMetadataDocumentSupported && this.config.oauthClientMetadataUrl) {
1875
+ candidates.push({
1876
+ ...currentAuthConfig,
1877
+ clientId: this.config.oauthClientMetadataUrl,
1878
+ clientMode: "cimd",
1879
+ callbackUrl
1880
+ });
1881
+ }
1882
+ if (currentAuthConfig.registrationEndpoint) {
1883
+ const cacheKey = buildRegistrationCacheKey(currentAuthConfig, callbackUrl, "dcr");
1884
+ const storedRegistration = loadStoredRegistration(cacheKey, this.getPersistentStorage());
1885
+ if (storedRegistration?.clientId) {
1886
+ candidates.push(applyResolvedRegistration(currentAuthConfig, {
1887
+ cacheKey,
1888
+ mode: "dcr",
1889
+ clientId: storedRegistration.clientId,
1890
+ callbackUrl,
1891
+ resource: currentAuthConfig.resource,
1892
+ authorizationServerUrl: currentAuthConfig.authorizationServerUrl,
1893
+ authorizationServerMetadataUrl: currentAuthConfig.authorizationServerMetadataUrl,
1894
+ registrationEndpoint: currentAuthConfig.registrationEndpoint
1895
+ }));
1896
+ }
1897
+ }
1898
+ }
1899
+ const seen = /* @__PURE__ */ new Set();
1900
+ const resolved = candidates.map((candidate) => ({
1901
+ storageKey: this.getTokenStorageKey(mcpServerUrl, candidate),
1902
+ authConfig: candidate
1903
+ })).filter((candidate) => {
1904
+ if (seen.has(candidate.storageKey)) return false;
1905
+ seen.add(candidate.storageKey);
1906
+ return true;
1907
+ });
1908
+ if (!hasExplicitAuthSessionKey) {
1909
+ resolved.push({
1910
+ storageKey: this.getLegacyTokenStorageKey(mcpServerUrl),
1911
+ authConfig: currentAuthConfig
1912
+ });
1913
+ }
1914
+ return resolved;
1915
+ }
1916
+ /** Load OAuth token from memory/persistent storage using auth-aware cache keying. */
1917
+ loadOAuthToken(mcpServerUrl) {
1918
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1919
+ const cached = this.oauthTokens.get(candidate.storageKey);
1920
+ if (cached) {
1921
+ if (candidate.authConfig) {
1922
+ this.updateServerAuthConfig(mcpServerUrl, candidate.authConfig);
1923
+ }
1924
+ return cached;
1925
+ }
1926
+ }
1927
+ try {
1928
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
1929
+ if (storage) {
1930
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1931
+ const stored = storage.getItem(candidate.storageKey);
1932
+ if (stored) {
1933
+ const data = JSON.parse(stored);
1934
+ if (data.accessToken && data.expiresAt) {
1935
+ this.oauthTokens.set(candidate.storageKey, data);
1936
+ if (candidate.authConfig) {
1937
+ this.updateServerAuthConfig(mcpServerUrl, candidate.authConfig);
1938
+ }
1939
+ return data;
1940
+ }
1941
+ }
1942
+ }
1943
+ }
1944
+ } catch {
1945
+ }
1946
+ return null;
1947
+ }
1948
+ /** Check if we have a valid (non-expired) OAuth token */
1949
+ hasValidOAuthToken(mcpServerUrl) {
1950
+ const token = this.loadOAuthToken(mcpServerUrl);
1951
+ if (!token) return false;
1952
+ return token.expiresAt > Date.now() || !!token.refreshToken;
1953
+ }
1954
+ /** Store OAuth token to memory and persistent storage */
1955
+ storeOAuthToken(mcpServerUrl, tokenResponse) {
1956
+ const resolvedAuthConfig = tokenResponse.resolvedAuthConfig ?? this.getServerAuthConfig(mcpServerUrl);
1957
+ const storageKey = this.getTokenStorageKey(mcpServerUrl, resolvedAuthConfig);
1958
+ const expiresIn = tokenResponse.expiresIn ?? 3600;
1959
+ const expiresAt = Date.now() + expiresIn * 1e3 - 60 * 1e3;
1960
+ const data = {
1961
+ accessToken: tokenResponse.accessToken,
1962
+ refreshToken: tokenResponse.refreshToken,
1963
+ expiresAt
1964
+ };
1965
+ this.oauthTokens.set(storageKey, data);
1966
+ try {
1967
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
1968
+ if (storage) {
1969
+ storage.setItem(storageKey, JSON.stringify(data));
1970
+ }
1971
+ } catch {
1972
+ }
1973
+ }
1974
+ /** Clear OAuth token from memory and persistent storage */
1975
+ clearOAuthToken(mcpServerUrl) {
1976
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1977
+ this.oauthTokens.delete(candidate.storageKey);
1978
+ }
1979
+ try {
1980
+ const storage = this.getPersistentStorage() ?? (typeof localStorage !== "undefined" ? localStorage : null);
1981
+ if (storage) {
1982
+ for (const candidate of this.getTokenStorageCandidates(mcpServerUrl)) {
1983
+ storage.removeItem(candidate.storageKey);
1984
+ }
1985
+ }
1986
+ } catch {
1987
+ }
1988
+ }
1989
+ /** Refresh OAuth token using refresh token */
1990
+ async refreshOAuthToken(mcpServerUrl, refreshToken) {
1991
+ const authConfig = await this.ensureServerAuthConfig(mcpServerUrl);
1992
+ const tokenUrl = authConfig?.tokenEndpoint ?? authConfig?.tokenUrl;
1993
+ if (!tokenUrl) return void 0;
1994
+ try {
1995
+ const body = new URLSearchParams({
1996
+ grant_type: "refresh_token",
1997
+ refresh_token: refreshToken
1998
+ });
1999
+ if (authConfig?.clientId) body.set("client_id", authConfig.clientId);
2000
+ if (authConfig?.resource) body.set("resource", authConfig.resource);
2001
+ const response = await fetch(tokenUrl, {
2002
+ method: "POST",
2003
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
2004
+ body
2005
+ });
2006
+ if (response.ok) {
2007
+ const data = await response.json();
2008
+ if (data.access_token) {
2009
+ const tokenResponse = {
2010
+ accessToken: data.access_token,
2011
+ refreshToken: data.refresh_token ?? refreshToken,
2012
+ expiresIn: data.expires_in,
2013
+ resolvedAuthConfig: authConfig ?? void 0
2014
+ };
2015
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
2016
+ return data.access_token;
2017
+ }
2018
+ }
2019
+ } catch {
2020
+ }
2021
+ return void 0;
2022
+ }
2023
+ // ================================================================
2024
+ // Token Resolution
2025
+ // ================================================================
2026
+ /**
2027
+ * Resolve the auth token for an MCP server.
2028
+ * - OAuth mode: Checks stored token, refreshes if expired, triggers auth if needed
2029
+ */
2030
+ async resolveToken(mcpServerUrl) {
2031
+ if (this.manuallySignedOutServers.has(mcpServerUrl)) {
2032
+ return void 0;
2033
+ }
2034
+ const authConfig = await this.ensureServerAuthConfig(mcpServerUrl);
2035
+ const stored = this.loadOAuthToken(mcpServerUrl);
2036
+ if (stored) {
2037
+ if (stored.expiresAt > Date.now()) {
2038
+ return stored.accessToken;
2039
+ }
2040
+ if (stored.refreshToken) {
2041
+ const refreshed = await this.refreshOAuthToken(mcpServerUrl, stored.refreshToken);
2042
+ if (refreshed) return refreshed;
2043
+ }
2044
+ this.clearOAuthToken(mcpServerUrl);
2045
+ }
2046
+ if (this.config.onAuthRequired) {
2047
+ if (authConfig) {
2048
+ const isBuiltInPopupAuth = this.config.onAuthRequired.__mcpStackBuiltinPopupAuth === true;
2049
+ const isAppTokenAuth = this.config.auth?.mode === "app-token";
2050
+ const authConfigForHandler = authConfig.authType === "oauth2" && !isBuiltInPopupAuth && !isAppTokenAuth ? await this.resolveOAuthClientRegistration(authConfig) : authConfig;
2051
+ if (authConfigForHandler) {
2052
+ this.updateServerAuthConfig(mcpServerUrl, authConfigForHandler);
2053
+ }
2054
+ const tokenResponse = await this.config.onAuthRequired(
2055
+ mcpServerUrl,
2056
+ authConfigForHandler ?? authConfig
2057
+ );
2058
+ if (tokenResponse?.accessToken) {
2059
+ if (tokenResponse.resolvedAuthConfig) {
2060
+ this.updateServerAuthConfig(mcpServerUrl, tokenResponse.resolvedAuthConfig);
2061
+ }
2062
+ this.storeOAuthToken(mcpServerUrl, tokenResponse);
2063
+ return tokenResponse.accessToken;
2064
+ }
2065
+ }
2066
+ }
2067
+ return void 0;
2068
+ }
2069
+ // ================================================================
2070
+ // Chat Loop
2071
+ // ================================================================
2072
+ /**
2073
+ * The core orchestration loop:
2074
+ * 1. Send message to chat API
2075
+ * 2. Stream response
2076
+ * 3. If tool_call → execute tool via MCP → send result → continue
2077
+ * 4. If message_end → done
2078
+ */
2079
+ async runChatLoop(message) {
2080
+ this.abortController = new AbortController();
2081
+ this.emit("thinking", true);
2082
+ const chatBody = {
2083
+ agentId: this.config.agentId,
2084
+ conversationId: this.conversationId,
2085
+ message,
2086
+ externalUserId: this.resolveExternalUserId(),
2087
+ context: this.config.context
2088
+ };
2089
+ const externalUser = this.buildExternalUserContext();
2090
+ if (externalUser) {
2091
+ chatBody.externalUser = externalUser;
2092
+ }
2093
+ const clientToolSchemas = this.clientToolsToSchemas();
2094
+ if (clientToolSchemas.length > 0) {
2095
+ chatBody.clientTools = clientToolSchemas;
2096
+ }
2097
+ let response = await this.callChatApi(chatBody, "chat");
2098
+ while (true) {
2099
+ const result = await this.processSseStream(response);
2100
+ if (result.type === "message_end") {
2101
+ break;
2102
+ }
2103
+ if (result.type === "tool_call") {
2104
+ const toolCall = result.data;
2105
+ const startTime = Date.now();
2106
+ try {
2107
+ const toolResult = await this.executeTool(toolCall);
2108
+ const duration = Date.now() - startTime;
2109
+ const toolCallMsg = this.messages.find(
2110
+ (m) => m.role === "tool_call" && m.toolCallId === toolCall.toolCallId
2111
+ );
2112
+ if (toolCallMsg) {
2113
+ toolCallMsg.toolCallStatus = "completed";
2114
+ toolCallMsg.toolCallDuration = duration;
2115
+ toolCallMsg.toolResult = typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult);
2116
+ }
2117
+ this.emit("tool_result", { toolCallId: toolCall.toolCallId, result: toolResult, duration });
2118
+ const toolResultMsg = {
2119
+ id: crypto.randomUUID(),
2120
+ role: "tool_result",
2121
+ content: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult),
2122
+ toolCallId: toolCall.toolCallId,
2123
+ toolName: toolCall.toolName,
2124
+ timestamp: /* @__PURE__ */ new Date()
2125
+ };
2126
+ this.messages.push(toolResultMsg);
2127
+ this.emit("thinking", true);
2128
+ const toolResultBody = {
2129
+ conversationId: this.conversationId,
2130
+ toolCallId: toolCall.toolCallId,
2131
+ result: toolResult,
2132
+ durationMs: duration,
2133
+ context: this.config.context
2134
+ };
2135
+ const clientToolSchemas2 = this.clientToolsToSchemas();
2136
+ if (clientToolSchemas2.length > 0) {
2137
+ toolResultBody.clientTools = clientToolSchemas2;
2138
+ }
2139
+ response = await this.callChatApi(toolResultBody, "chat/tool-result");
2140
+ } catch (err) {
2141
+ const duration = Date.now() - startTime;
2142
+ const errorMsg = err instanceof Error ? err.message : "Tool execution failed";
2143
+ const toolCallMsg = this.messages.find(
2144
+ (m) => m.role === "tool_call" && m.toolCallId === toolCall.toolCallId
2145
+ );
2146
+ if (toolCallMsg) {
2147
+ toolCallMsg.toolCallStatus = "error";
2148
+ toolCallMsg.toolCallDuration = duration;
2149
+ toolCallMsg.toolError = errorMsg;
2150
+ }
2151
+ this.emit("tool_error", { toolCallId: toolCall.toolCallId, error: errorMsg, duration });
2152
+ const errorResult = `Error: ${errorMsg}`;
2153
+ const toolResultMsg = {
2154
+ id: crypto.randomUUID(),
2155
+ role: "tool_result",
2156
+ content: errorResult,
2157
+ toolCallId: toolCall.toolCallId,
2158
+ toolName: toolCall.toolName,
2159
+ timestamp: /* @__PURE__ */ new Date()
2160
+ };
2161
+ this.messages.push(toolResultMsg);
2162
+ this.emit("thinking", true);
2163
+ try {
2164
+ const toolResultBody = {
2165
+ conversationId: this.conversationId,
2166
+ toolCallId: toolCall.toolCallId,
2167
+ result: errorResult,
2168
+ isError: true,
2169
+ durationMs: duration,
2170
+ context: this.config.context
2171
+ };
2172
+ const clientToolSchemas2 = this.clientToolsToSchemas();
2173
+ if (clientToolSchemas2.length > 0) {
2174
+ toolResultBody.clientTools = clientToolSchemas2;
2175
+ }
2176
+ response = await this.callChatApi(toolResultBody, "chat/tool-result");
2177
+ } catch {
2178
+ this.emit("error", { code: "tool_error", message: errorMsg });
2179
+ break;
2180
+ }
2181
+ }
2182
+ }
2183
+ if (result.type === "error") {
2184
+ break;
2185
+ }
2186
+ }
2187
+ }
2188
+ async callChatApi(body, endpoint) {
2189
+ const token = await this.resolveAuthToken();
2190
+ const response = await fetch(
2191
+ `${this.config.agentServiceUrl}/api/v1/${endpoint}`,
2192
+ {
2193
+ method: "POST",
2194
+ headers: {
2195
+ "Content-Type": "application/json",
2196
+ Authorization: `Bearer ${token}`
2197
+ },
2198
+ body: JSON.stringify(body),
2199
+ signal: this.abortController?.signal
2200
+ }
2201
+ );
2202
+ if (!response.ok) {
2203
+ throw new Error(await getResponseErrorMessage(response));
2204
+ }
2205
+ return response;
2206
+ }
2207
+ async fetchConversationMessages(conversationId, cursor, pageSize = 50) {
2208
+ const token = await this.resolveAuthToken();
2209
+ const params = new URLSearchParams();
2210
+ params.set("pageSize", String(pageSize));
2211
+ if (cursor) {
2212
+ params.set("cursor", cursor);
2213
+ }
2214
+ const response = await fetch(
2215
+ `${this.config.agentServiceUrl}/api/v1/chat/conversations/${encodeURIComponent(conversationId)}/messages?${params.toString()}`,
2216
+ {
2217
+ headers: {
2218
+ Authorization: `Bearer ${token}`
2219
+ }
2220
+ }
2221
+ );
2222
+ if (!response.ok) {
2223
+ throw new Error(await getResponseErrorMessage(response));
2224
+ }
2225
+ return await response.json();
2226
+ }
2227
+ applyConversationPage(page, prepend) {
2228
+ const mappedMessages = page.messages.map((message) => this.mapReplayMessage(message));
2229
+ this.conversationId = page.conversationId;
2230
+ this.historyCursor = page.nextCursor ?? null;
2231
+ this.hasOlderMessages = page.hasNextPage;
2232
+ this.messages = prepend ? [...mappedMessages, ...this.messages] : mappedMessages;
2233
+ }
2234
+ mapReplayMessage(message) {
2235
+ const timestamp = new Date(message.createdAt);
2236
+ return {
2237
+ id: message.id,
2238
+ role: message.role,
2239
+ content: message.content ?? "",
2240
+ toolName: message.toolName ?? void 0,
2241
+ toolLabel: message.toolLabel ?? void 0,
2242
+ toolCallId: message.toolCallId ?? void 0,
2243
+ timestamp,
2244
+ toolCallStatus: message.toolCallStatus ?? void 0,
2245
+ toolCallStartTime: message.toolCallDurationMs != null ? timestamp.getTime() - message.toolCallDurationMs : void 0,
2246
+ toolCallDuration: message.toolCallDurationMs ?? void 0,
2247
+ toolResult: message.toolResultJson ?? void 0,
2248
+ toolError: message.toolError ?? void 0,
2249
+ errorCode: message.errorCode ?? void 0,
2250
+ metadataJson: message.metadataJson ?? null
2251
+ };
2252
+ }
2253
+ /**
2254
+ * Process an SSE stream from the chat API.
2255
+ * Returns when the stream ends (either message_end or tool_call).
2256
+ */
2257
+ async processSseStream(response) {
2258
+ let assistantContent = "";
2259
+ let lastToolCall = null;
2260
+ let emittedThinkingFalse = false;
2261
+ for await (const event of parseSseStream(response, this.abortController?.signal)) {
2262
+ switch (event.type) {
2263
+ case "message_start": {
2264
+ const data = event.data;
2265
+ this.conversationId = data.conversationId;
2266
+ break;
2267
+ }
2268
+ case "content_delta": {
2269
+ const data = event.data;
2270
+ if (!emittedThinkingFalse) {
2271
+ this.emit("thinking", false);
2272
+ emittedThinkingFalse = true;
2273
+ }
2274
+ assistantContent += data.text;
2275
+ this.emit("content_delta", data);
2276
+ break;
2277
+ }
2278
+ case "tool_call": {
2279
+ const data = event.data;
2280
+ if (!emittedThinkingFalse) {
2281
+ this.emit("thinking", false);
2282
+ emittedThinkingFalse = true;
2283
+ }
2284
+ lastToolCall = data;
2285
+ const toolCallMsg = {
2286
+ id: crypto.randomUUID(),
2287
+ role: "tool_call",
2288
+ content: `Calling ${data.toolLabel ?? data.toolName}...`,
2289
+ toolName: data.toolName,
2290
+ toolLabel: data.toolLabel,
2291
+ toolCallId: data.toolCallId,
2292
+ timestamp: /* @__PURE__ */ new Date(),
2293
+ toolCallStatus: "calling",
2294
+ toolCallStartTime: Date.now()
2295
+ };
2296
+ this.messages.push(toolCallMsg);
2297
+ this.emit("tool_call", data);
2298
+ break;
2299
+ }
2300
+ case "message_end": {
2301
+ const data = event.data;
2302
+ if (assistantContent) {
2303
+ const assistantMsg = {
2304
+ id: crypto.randomUUID(),
2305
+ role: "assistant",
2306
+ content: assistantContent,
2307
+ timestamp: /* @__PURE__ */ new Date()
2308
+ };
2309
+ this.messages.push(assistantMsg);
2310
+ this.emit("message", assistantMsg);
2311
+ }
2312
+ this.emit("message_end", data);
2313
+ return { type: "message_end", data };
2314
+ }
2315
+ case "budget_snapshot": {
2316
+ const data = event.data;
2317
+ this.budgetSnapshot = data;
2318
+ this.emit("budget_snapshot", data);
2319
+ break;
2320
+ }
2321
+ case "error": {
2322
+ const data = event.data;
2323
+ if (data.budget) {
2324
+ this.budgetSnapshot = data.budget;
2325
+ this.emit("budget_snapshot", data.budget);
2326
+ }
2327
+ const errorMsg = {
2328
+ id: crypto.randomUUID(),
2329
+ role: "error",
2330
+ content: data.message,
2331
+ timestamp: /* @__PURE__ */ new Date(),
2332
+ errorCode: data.code
2333
+ };
2334
+ this.messages.push(errorMsg);
2335
+ this.emit("message", errorMsg);
2336
+ this.emit("error", data);
2337
+ return { type: "error", data };
2338
+ }
2339
+ }
2340
+ }
2341
+ if (lastToolCall) {
2342
+ if (assistantContent) {
2343
+ const assistantMsg = {
2344
+ id: crypto.randomUUID(),
2345
+ role: "assistant",
2346
+ content: assistantContent,
2347
+ timestamp: /* @__PURE__ */ new Date()
2348
+ };
2349
+ this.messages.push(assistantMsg);
2350
+ this.emit("message", assistantMsg);
2351
+ }
2352
+ return { type: "tool_call", data: lastToolCall };
2353
+ }
2354
+ if (assistantContent) {
2355
+ const assistantMsg = {
2356
+ id: crypto.randomUUID(),
2357
+ role: "assistant",
2358
+ content: assistantContent,
2359
+ timestamp: /* @__PURE__ */ new Date()
2360
+ };
2361
+ this.messages.push(assistantMsg);
2362
+ this.emit("message", assistantMsg);
2363
+ }
2364
+ return { type: "message_end" };
2365
+ }
2366
+ // ================================================================
2367
+ // MCP Session Management
2368
+ // ================================================================
2369
+ /** Build headers for MCP server requests */
2370
+ getMcpHeaders(mcpServerUrl) {
2371
+ const headers = {
2372
+ "Content-Type": "application/json",
2373
+ "Accept": "application/json, text/event-stream"
2374
+ };
2375
+ const session = this.mcpSessions.get(mcpServerUrl);
2376
+ if (session?.sessionId) {
2377
+ headers["Mcp-Session-Id"] = session.sessionId;
2378
+ }
2379
+ return headers;
2380
+ }
2381
+ /** Best-effort MCP session teardown so reconnect starts cleanly after sign-out. */
2382
+ async closeMcpSession(mcpServerUrl) {
2383
+ const session = this.mcpSessions.get(mcpServerUrl);
2384
+ if (!session?.sessionId) return;
2385
+ const headers = {
2386
+ "Accept": "application/json, text/event-stream",
2387
+ "Mcp-Session-Id": session.sessionId
2388
+ };
2389
+ const storedToken = this.loadOAuthToken(mcpServerUrl);
2390
+ if (storedToken?.accessToken) {
2391
+ headers["Authorization"] = `Bearer ${storedToken.accessToken}`;
2392
+ }
2393
+ try {
2394
+ await fetch(mcpServerUrl, {
2395
+ method: "DELETE",
2396
+ headers,
2397
+ credentials: this.config.useCookies ? "include" : "omit"
2398
+ });
2399
+ } catch {
2400
+ }
2401
+ this.mcpSessions.set(mcpServerUrl, {
2402
+ sessionId: null,
2403
+ authStatus: session.authStatus
2404
+ });
2405
+ }
2406
+ /** Initialize the MCP session for a specific server (required before tools/call) */
2407
+ async initMcpSession(mcpServerUrl) {
2408
+ const session = this.mcpSessions.get(mcpServerUrl);
2409
+ if (session?.sessionId) return;
2410
+ const headers = this.getMcpHeaders(mcpServerUrl);
2411
+ await this.ensureServerAuthConfig(mcpServerUrl);
2412
+ const token = await this.resolveToken(mcpServerUrl);
2413
+ if (token) headers["Authorization"] = `Bearer ${token}`;
2414
+ const initPayload = JSON.stringify({
2415
+ jsonrpc: "2.0",
2416
+ id: 1,
2417
+ method: "initialize",
2418
+ params: {
2419
+ protocolVersion: DEFAULT_MCP_PROTOCOL_VERSION,
2420
+ capabilities: {},
2421
+ clientInfo: { name: "mcpstack-agent-sdk", version: "0.1.0" }
2422
+ }
2423
+ });
2424
+ const initResponse = await fetch(mcpServerUrl, {
2425
+ method: "POST",
2426
+ headers,
2427
+ credentials: this.config.useCookies ? "include" : "omit",
2428
+ body: initPayload
2429
+ });
2430
+ if (initResponse.status === 401) {
2431
+ this.clearOAuthToken(mcpServerUrl);
2432
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
2433
+ const freshToken = await this.resolveToken(mcpServerUrl);
2434
+ if (freshToken) {
2435
+ headers["Authorization"] = `Bearer ${freshToken}`;
2436
+ const retryResponse = await fetch(mcpServerUrl, {
2437
+ method: "POST",
2438
+ headers,
2439
+ credentials: this.config.useCookies ? "include" : "omit",
2440
+ body: initPayload
2441
+ });
2442
+ if (retryResponse.ok) {
2443
+ const sessionId2 = retryResponse.headers.get("mcp-session-id");
2444
+ this.mcpSessions.set(mcpServerUrl, { sessionId: sessionId2, authStatus: "connected" });
2445
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2446
+ await retryResponse.text().catch(() => {
2447
+ });
2448
+ const notifyHeaders2 = this.getMcpHeaders(mcpServerUrl);
2449
+ notifyHeaders2["Authorization"] = `Bearer ${freshToken}`;
2450
+ await fetch(mcpServerUrl, {
2451
+ method: "POST",
2452
+ headers: notifyHeaders2,
2453
+ credentials: this.config.useCookies ? "include" : "omit",
2454
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
2455
+ });
2456
+ return;
2457
+ }
2458
+ }
2459
+ throw new Error("MCP initialization failed (401): Authentication required");
2460
+ }
2461
+ if (!initResponse.ok) {
2462
+ const errorText = await initResponse.text().catch(() => "MCP init error");
2463
+ throw new Error(`MCP initialization failed (${initResponse.status}): ${errorText}`);
2464
+ }
2465
+ const sessionId = initResponse.headers.get("mcp-session-id");
2466
+ this.mcpSessions.set(mcpServerUrl, { sessionId, authStatus: "connected" });
2467
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2468
+ await initResponse.text().catch(() => {
2469
+ });
2470
+ const notifyHeaders = this.getMcpHeaders(mcpServerUrl);
2471
+ if (token) notifyHeaders["Authorization"] = `Bearer ${token}`;
2472
+ await fetch(mcpServerUrl, {
2473
+ method: "POST",
2474
+ headers: notifyHeaders,
2475
+ credentials: this.config.useCookies ? "include" : "omit",
2476
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })
2477
+ });
2478
+ }
2479
+ /** Update auth status for an MCP server and emit event */
2480
+ updateMcpAuthStatus(mcpServerUrl, authStatus) {
2481
+ const session = this.mcpSessions.get(mcpServerUrl);
2482
+ if (session) {
2483
+ session.authStatus = authStatus;
2484
+ } else {
2485
+ this.mcpSessions.set(mcpServerUrl, { sessionId: null, authStatus });
2486
+ }
2487
+ const serverInfo = this.agentConfig?.mcpServers?.find((s) => s.url === mcpServerUrl);
2488
+ this.emit("mcp_auth_status", {
2489
+ mcpServerUrl,
2490
+ mcpServerName: serverInfo?.name ?? mcpServerUrl,
2491
+ authStatus
2492
+ });
2493
+ }
2494
+ /** Parse a JSON-RPC response from either JSON or SSE format */
2495
+ async parseMcpResponse(response) {
2496
+ const contentType = (response.headers.get("content-type") || "").toLowerCase();
2497
+ if (contentType.includes("text/event-stream")) {
2498
+ const text = await response.text();
2499
+ const lines = text.split("\n");
2500
+ let jsonData = "";
2501
+ for (const line of lines) {
2502
+ if (line.startsWith("data: ")) {
2503
+ jsonData += line.slice(6);
2504
+ }
2505
+ }
2506
+ if (!jsonData) {
2507
+ throw new Error("No data received from MCP server SSE response");
2508
+ }
2509
+ return JSON.parse(jsonData);
2510
+ }
2511
+ return response.json();
2512
+ }
2513
+ // ================================================================
2514
+ // Tool Execution
2515
+ // ================================================================
2516
+ async executeTool(toolCall) {
2517
+ const isClientTool = toolCall.source === "client" || !toolCall.mcpServerUrl;
2518
+ if (isClientTool && this.config.clientTools) {
2519
+ const def = this.config.clientTools[toolCall.toolName];
2520
+ if (def) {
2521
+ const result2 = await def.execute(toolCall.arguments ?? {});
2522
+ return result2;
2523
+ }
2524
+ throw new Error(`Unknown client tool: ${toolCall.toolName}`);
2525
+ }
2526
+ const mcpServerUrl = toolCall.mcpServerUrl || this.agentConfig?.mcpServerUrl;
2527
+ if (!mcpServerUrl) {
2528
+ throw new Error("No MCP server URL for tool call");
2529
+ }
2530
+ await this.initMcpSession(mcpServerUrl);
2531
+ const token = await this.resolveToken(mcpServerUrl);
2532
+ const headers = this.getMcpHeaders(mcpServerUrl);
2533
+ if (token) headers["Authorization"] = `Bearer ${token}`;
2534
+ const toolCallBody = JSON.stringify({
2535
+ jsonrpc: "2.0",
2536
+ id: 2,
2537
+ method: "tools/call",
2538
+ params: { name: toolCall.toolName, arguments: toolCall.arguments }
2539
+ });
2540
+ let response = await fetch(mcpServerUrl, {
2541
+ method: "POST",
2542
+ headers,
2543
+ credentials: this.config.useCookies ? "include" : "omit",
2544
+ body: toolCallBody,
2545
+ signal: this.abortController?.signal
2546
+ });
2547
+ const session = this.mcpSessions.get(mcpServerUrl);
2548
+ if (response.status === 404 && session?.sessionId) {
2549
+ this.mcpSessions.set(mcpServerUrl, { ...session, sessionId: null });
2550
+ await this.initMcpSession(mcpServerUrl);
2551
+ const retryHeaders = this.getMcpHeaders(mcpServerUrl);
2552
+ if (token) retryHeaders["Authorization"] = `Bearer ${token}`;
2553
+ response = await fetch(mcpServerUrl, {
2554
+ method: "POST",
2555
+ headers: retryHeaders,
2556
+ credentials: this.config.useCookies ? "include" : "omit",
2557
+ body: toolCallBody,
2558
+ signal: this.abortController?.signal
2559
+ });
2560
+ }
2561
+ if (response.status === 401) {
2562
+ this.clearOAuthToken(mcpServerUrl);
2563
+ this.updateMcpAuthStatus(mcpServerUrl, "needs_auth");
2564
+ const freshToken = await this.resolveToken(mcpServerUrl);
2565
+ if (freshToken) {
2566
+ const authHeaders = this.getMcpHeaders(mcpServerUrl);
2567
+ authHeaders["Authorization"] = `Bearer ${freshToken}`;
2568
+ response = await fetch(mcpServerUrl, {
2569
+ method: "POST",
2570
+ headers: authHeaders,
2571
+ credentials: this.config.useCookies ? "include" : "omit",
2572
+ body: toolCallBody,
2573
+ signal: this.abortController?.signal
2574
+ });
2575
+ if (response.ok) {
2576
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2577
+ }
2578
+ }
2579
+ if (!response.ok) {
2580
+ const errorText = await response.text().catch(() => "Authentication required");
2581
+ throw new Error(`Tool execution failed (401): ${errorText}`);
2582
+ }
2583
+ }
2584
+ if (!response.ok) {
2585
+ const errorText = await response.text().catch(() => "MCP server error");
2586
+ throw new Error(`Tool execution failed (${response.status}): ${errorText}`);
2587
+ }
2588
+ const currentSession = this.mcpSessions.get(mcpServerUrl);
2589
+ if (currentSession?.authStatus === "needs_auth") {
2590
+ this.updateMcpAuthStatus(mcpServerUrl, "connected");
2591
+ }
2592
+ const result = await this.parseMcpResponse(response);
2593
+ if (result.error) {
2594
+ throw new Error(`MCP error (${result.error.code}): ${result.error.message}`);
2595
+ }
2596
+ if (result.result?.content) {
2597
+ const textContent = result.result.content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
2598
+ return textContent || result.result;
2599
+ }
2600
+ return result.result ?? result;
2601
+ }
2602
+ };
2603
+
2604
+ // src/app/types.ts
2605
+ var APP_AGENT_APPROVAL_ACTION = "requestApproval";
2606
+ var APP_AGENT_INPUT_ACTION = "requestInput";
2607
+
2608
+ // src/app/presentation.ts
2609
+ function isAssistantMessage(message) {
2610
+ return message.role === "assistant";
2611
+ }
2612
+ function isUserMessage(message) {
2613
+ return message.role === "user";
2614
+ }
2615
+ function isErrorMessage(message) {
2616
+ return message.role === "error";
2617
+ }
2618
+ function isToolCallMessage(message) {
2619
+ return message.role === "tool_call";
2620
+ }
2621
+ function deriveVisibleMessages(messages) {
2622
+ return messages.filter(
2623
+ (message) => isAssistantMessage(message) || isUserMessage(message) || isErrorMessage(message) || isToolCallMessage(message)
2624
+ );
2625
+ }
2626
+ function deriveConversationMessages(messages) {
2627
+ return messages.filter(
2628
+ (message) => isUserMessage(message) || isAssistantMessage(message) || isErrorMessage(message)
2629
+ );
2630
+ }
2631
+ function deriveToolMessages(messages) {
2632
+ return messages.filter(isToolCallMessage);
2633
+ }
2634
+ function getLatestAssistantMessage(messages) {
2635
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
2636
+ const message = messages[index];
2637
+ if (message && isAssistantMessage(message)) {
2638
+ return message;
2639
+ }
2640
+ }
2641
+ return null;
2642
+ }
2643
+ function getLatestUserMessage(messages) {
2644
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
2645
+ const message = messages[index];
2646
+ if (message && isUserMessage(message)) {
2647
+ return message;
2648
+ }
2649
+ }
2650
+ return null;
2651
+ }
2652
+ function getLatestToolMessage(messages) {
2653
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
2654
+ const message = messages[index];
2655
+ if (message && isToolCallMessage(message)) {
2656
+ return message;
2657
+ }
2658
+ }
2659
+ return null;
2660
+ }
2661
+ function createInlinePendingTurnState(prompt, messages) {
2662
+ return {
2663
+ prompt,
2664
+ baselineAssistantId: getLatestAssistantMessage(messages)?.id ?? null,
2665
+ baselineToolCount: deriveToolMessages(messages).length
2666
+ };
2667
+ }
2668
+ function applyUserMessageOverrides(messages, overrides) {
2669
+ return messages.map(
2670
+ (message) => message.role === "user" && overrides[message.id] ? { ...message, content: overrides[message.id] } : message
2671
+ );
2672
+ }
2673
+ function buildRenderedNodes(messages) {
2674
+ const nodes = [];
2675
+ let toolBuffer = [];
2676
+ const flushTools = (id) => {
2677
+ if (toolBuffer.length > 0) {
2678
+ nodes.push({ kind: "tools", id: `tools-${id}`, tools: toolBuffer });
2679
+ toolBuffer = [];
2680
+ }
2681
+ };
2682
+ messages.forEach((message) => {
2683
+ if (isToolCallMessage(message)) {
2684
+ toolBuffer.push(message);
2685
+ return;
2686
+ }
2687
+ if (message.role === "tool_result") {
2688
+ return;
2689
+ }
2690
+ flushTools(message.id);
2691
+ if (message.role === "user") {
2692
+ nodes.push({ kind: "user", id: message.id, content: message.content });
2693
+ return;
2694
+ }
2695
+ if (message.role === "assistant") {
2696
+ nodes.push({ kind: "assistant", id: message.id, content: message.content });
2697
+ }
2698
+ });
2699
+ if (toolBuffer.length > 0) {
2700
+ nodes.push({ kind: "tools", id: "tools-tail", tools: toolBuffer });
2701
+ }
2702
+ return nodes;
2703
+ }
2704
+ function deriveConversationStatusLabel(options) {
2705
+ const {
2706
+ isReady,
2707
+ isLoading,
2708
+ isThinking,
2709
+ streamingContent,
2710
+ hasError = false,
2711
+ hasIssue = false,
2712
+ hasAttention = false,
2713
+ readyLabel = "Ready",
2714
+ loadingLabel = "Working\u2026",
2715
+ thinkingLabel = "Thinking\u2026",
2716
+ streamingLabel = "Responding\u2026",
2717
+ attentionLabel = "Needs auth",
2718
+ issueLabel = "Needs attention",
2719
+ reconnectingLabel = "Reconnecting\u2026",
2720
+ connectingLabel = "Connecting\u2026"
2721
+ } = options;
2722
+ if (isReady) {
2723
+ if (isLoading) {
2724
+ return loadingLabel;
2725
+ }
2726
+ if (isThinking) {
2727
+ return thinkingLabel;
2728
+ }
2729
+ if (streamingContent && streamingContent.length > 0) {
2730
+ return streamingLabel;
2731
+ }
2732
+ if (hasAttention) {
2733
+ return attentionLabel;
2734
+ }
2735
+ if (hasIssue || hasError) {
2736
+ return issueLabel;
2737
+ }
2738
+ return readyLabel;
2739
+ }
2740
+ return hasIssue || hasError ? reconnectingLabel : connectingLabel;
2741
+ }
2742
+ function deriveLastTurnSummary(messages) {
2743
+ const lastUser = getLatestUserMessage(messages);
2744
+ if (!lastUser) {
2745
+ return null;
2746
+ }
2747
+ const lastUserIndex = messages.findIndex((message) => message.id === lastUser.id);
2748
+ if (lastUserIndex < 0) {
2749
+ return null;
2750
+ }
2751
+ const after = messages.slice(lastUserIndex + 1);
2752
+ const tools = deriveToolMessages(after);
2753
+ const lastToolEndedAt = tools.map((tool) => (tool.toolCallDuration ?? 0) + (tool.timestamp ? tool.timestamp.getTime() : 0)).reduce((max, value) => max === null || value > max ? value : max, null);
2754
+ const userStartedAt = lastUser.timestamp ? lastUser.timestamp.getTime() : null;
2755
+ return {
2756
+ prompt: lastUser.content.trim(),
2757
+ toolsUsed: tools.length,
2758
+ durationMs: lastToolEndedAt && userStartedAt ? Math.max(0, lastToolEndedAt - userStartedAt) : null
2759
+ };
2760
+ }
2761
+ function deriveInlineFeedState(options) {
2762
+ const {
2763
+ pendingTurn,
2764
+ toolMessages,
2765
+ latestAssistantMessage,
2766
+ streamingContent = "",
2767
+ isLoading,
2768
+ isThinking,
2769
+ maxRecentTools = 4
2770
+ } = options;
2771
+ const startIndex = pendingTurn ? Math.max(
2772
+ pendingTurn.baselineToolCount,
2773
+ toolMessages.length - maxRecentTools
2774
+ ) : Math.max(toolMessages.length - maxRecentTools, 0);
2775
+ const recentTools = toolMessages.slice(startIndex);
2776
+ const hasFreshAssistantReply = Boolean(
2777
+ latestAssistantMessage && (!pendingTurn || latestAssistantMessage.id !== pendingTurn.baselineAssistantId)
2778
+ );
2779
+ const previewText = streamingContent || (hasFreshAssistantReply ? latestAssistantMessage.content : null);
2780
+ const waitingForActivity = Boolean(pendingTurn) && recentTools.length === 0 && !streamingContent && (isLoading || isThinking);
2781
+ const isActive = Boolean(isLoading || isThinking || streamingContent.length > 0);
2782
+ return {
2783
+ isActive,
2784
+ pendingPrompt: pendingTurn?.prompt ?? null,
2785
+ recentTools,
2786
+ previewText,
2787
+ waitingForActivity
2788
+ };
2789
+ }
2790
+
2791
+ // src/app/oauth.ts
2792
+ function normalizeOptionalValue(value) {
2793
+ if (!value) {
2794
+ return void 0;
2795
+ }
2796
+ const trimmed = value.trim();
2797
+ return trimmed || void 0;
2798
+ }
2799
+ function isGatewayAuthorizeUrl(authorizationEndpoint) {
2800
+ try {
2801
+ const url = new URL(authorizationEndpoint);
2802
+ return /\/api\/v1\/gateway\/[^/]+\/authorize$/i.test(url.pathname);
2803
+ } catch {
2804
+ return false;
2805
+ }
2806
+ }
2807
+ function base64UrlEncode(bytes) {
2808
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2809
+ }
2810
+ async function randomToken(length) {
2811
+ const bytes = new Uint8Array(length);
2812
+ crypto.getRandomValues(bytes);
2813
+ return base64UrlEncode(bytes);
2814
+ }
2815
+ async function createCodeChallenge(verifier) {
2816
+ const encoder = new TextEncoder();
2817
+ const data = encoder.encode(verifier);
2818
+ const hash = await crypto.subtle.digest("SHA-256", data);
2819
+ return base64UrlEncode(new Uint8Array(hash));
2820
+ }
2821
+ function createPlatformAuthHandler(options) {
2822
+ return async (_mcpServerUrl, authConfig) => {
2823
+ if (!options.platform.auth) {
2824
+ return void 0;
2825
+ }
2826
+ const authorizationEndpoint = authConfig.authorizationEndpoint ?? authConfig.loginUrl;
2827
+ const tokenEndpoint = authConfig.tokenEndpoint ?? authConfig.tokenUrl;
2828
+ const clientId = authConfig.clientId;
2829
+ const redirectUri = authConfig.callbackUrl ?? options.oauthCallbackUrl;
2830
+ if (!authorizationEndpoint || !tokenEndpoint || !clientId || !redirectUri) {
2831
+ return void 0;
2832
+ }
2833
+ const verifier = await randomToken(48);
2834
+ const state = await randomToken(24);
2835
+ const challenge = await createCodeChallenge(verifier);
2836
+ const authorizeUrl = new URL(authorizationEndpoint);
2837
+ authorizeUrl.searchParams.set("response_type", "code");
2838
+ authorizeUrl.searchParams.set("client_id", clientId);
2839
+ authorizeUrl.searchParams.set("redirect_uri", redirectUri);
2840
+ authorizeUrl.searchParams.set("state", state);
2841
+ authorizeUrl.searchParams.set("code_challenge", challenge);
2842
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
2843
+ if (authConfig.scopes?.length) {
2844
+ authorizeUrl.searchParams.set("scope", authConfig.scopes.join(" "));
2845
+ }
2846
+ if (authConfig.resource) {
2847
+ authorizeUrl.searchParams.set("resource", authConfig.resource);
2848
+ }
2849
+ if (options.userIdentity && isGatewayAuthorizeUrl(authorizationEndpoint)) {
2850
+ const subject = normalizeOptionalValue(options.userIdentity.subject);
2851
+ const email = normalizeOptionalValue(options.userIdentity.email);
2852
+ const organizationId = normalizeOptionalValue(options.userIdentity.organizationId);
2853
+ const displayName = normalizeOptionalValue(options.userIdentity.displayName);
2854
+ if (subject) {
2855
+ authorizeUrl.searchParams.set("mcpstack_host_subject", subject);
2856
+ }
2857
+ if (email) {
2858
+ authorizeUrl.searchParams.set("mcpstack_host_email", email);
2859
+ }
2860
+ if (organizationId) {
2861
+ authorizeUrl.searchParams.set("mcpstack_host_organization_id", organizationId);
2862
+ }
2863
+ if (displayName) {
2864
+ authorizeUrl.searchParams.set("mcpstack_host_display_name", displayName);
2865
+ }
2866
+ authorizeUrl.searchParams.set("mcpstack_mismatch_policy", "block_with_switch");
2867
+ }
2868
+ const result = await options.platform.auth.openOAuthSession({
2869
+ authorizeUrl: authorizeUrl.toString(),
2870
+ redirectUri,
2871
+ preferEphemeralSession: true
2872
+ });
2873
+ if (result.type !== "success" || !result.url) {
2874
+ return void 0;
2875
+ }
2876
+ const callback = new URL(result.url);
2877
+ const returnedState = callback.searchParams.get("state");
2878
+ const code = callback.searchParams.get("code");
2879
+ if (returnedState !== state || !code) {
2880
+ const errorDescription = callback.searchParams.get("error_description");
2881
+ const errorCode = callback.searchParams.get("error");
2882
+ throw new Error(errorDescription ?? (errorCode ? `OAuth error: ${errorCode}` : "Could not complete OAuth login."));
2883
+ }
2884
+ const tokenResponse = await fetch(tokenEndpoint, {
2885
+ method: "POST",
2886
+ headers: {
2887
+ "Content-Type": "application/x-www-form-urlencoded"
2888
+ },
2889
+ body: new URLSearchParams({
2890
+ grant_type: "authorization_code",
2891
+ client_id: clientId,
2892
+ redirect_uri: redirectUri,
2893
+ code,
2894
+ code_verifier: verifier,
2895
+ ...authConfig.resource ? { resource: authConfig.resource } : {}
2896
+ }).toString()
2897
+ });
2898
+ const payload = await tokenResponse.json().catch(() => null);
2899
+ if (!tokenResponse.ok) {
2900
+ throw new Error(
2901
+ payload?.error_description ?? payload?.error ?? `OAuth sign in failed (${tokenResponse.status}).`
2902
+ );
2903
+ }
2904
+ return {
2905
+ accessToken: payload?.access_token ?? payload?.accessToken,
2906
+ refreshToken: payload?.refresh_token ?? payload?.refreshToken,
2907
+ expiresIn: payload?.expires_in ?? payload?.expiresIn,
2908
+ tokenType: payload?.token_type ?? payload?.tokenType,
2909
+ resolvedAuthConfig: { ...authConfig, callbackUrl: redirectUri }
2910
+ };
2911
+ };
2912
+ }
2913
+
2914
+ // src/app/platform.ts
2915
+ function createBrowserKeyValueStore(storage) {
2916
+ const resolvedStorage = storage ?? (() => {
2917
+ try {
2918
+ return typeof localStorage === "undefined" ? null : localStorage;
2919
+ } catch {
2920
+ return null;
2921
+ }
2922
+ })();
2923
+ return {
2924
+ getItem(key) {
2925
+ return resolvedStorage?.getItem(key) ?? null;
2926
+ },
2927
+ setItem(key, value) {
2928
+ resolvedStorage?.setItem(key, value);
2929
+ },
2930
+ removeItem(key) {
2931
+ resolvedStorage?.removeItem(key);
2932
+ }
2933
+ };
2934
+ }
2935
+ function createBrowserAppAgentPlatform(storage) {
2936
+ return {
2937
+ storage: {
2938
+ durable: createBrowserKeyValueStore(storage)
2939
+ }
2940
+ };
2941
+ }
2942
+ async function resolveStoreValue(value) {
2943
+ return await Promise.resolve(value);
2944
+ }
2945
+
2946
+ // src/app/controller.ts
2947
+ function createId(prefix) {
2948
+ return `${prefix}_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`;
2949
+ }
2950
+ function normalizeSteps(value) {
2951
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : [];
2952
+ }
2953
+ function normalizeInputFields(value) {
2954
+ if (!Array.isArray(value)) {
2955
+ return [];
2956
+ }
2957
+ return value.flatMap((entry) => {
2958
+ if (!entry || typeof entry !== "object") {
2959
+ return [];
2960
+ }
2961
+ const record = entry;
2962
+ const key = typeof record.key === "string" ? record.key.trim() : "";
2963
+ const label = typeof record.label === "string" ? record.label.trim() : "";
2964
+ const kind = typeof record.kind === "string" ? record.kind : "text";
2965
+ if (!key || !label) {
2966
+ return [];
2967
+ }
2968
+ return [{
2969
+ key,
2970
+ label,
2971
+ kind: kind === "textarea" || kind === "number" || kind === "select" || kind === "boolean" ? kind : "text",
2972
+ required: Boolean(record.required),
2973
+ placeholder: typeof record.placeholder === "string" ? record.placeholder : void 0,
2974
+ options: Array.isArray(record.options) ? record.options.flatMap((option) => {
2975
+ if (!option || typeof option !== "object") {
2976
+ return [];
2977
+ }
2978
+ const optionRecord = option;
2979
+ const optionLabel = typeof optionRecord.label === "string" ? optionRecord.label.trim() : "";
2980
+ const optionValue = typeof optionRecord.value === "string" ? optionRecord.value : "";
2981
+ return optionLabel && optionValue ? [{ label: optionLabel, value: optionValue }] : [];
2982
+ }) : void 0
2983
+ }];
2984
+ });
2985
+ }
2986
+ function isToolRoutingResetError(error) {
2987
+ return error.code === "tool_routing_error" && /tool not found/i.test(error.message);
2988
+ }
2989
+ function mapConnections(agent) {
2990
+ return agent.getMcpServers().map((server) => ({
2991
+ url: server.url,
2992
+ name: server.name,
2993
+ authStatus: server.authStatus,
2994
+ canSignOut: server.canSignOut
2995
+ }));
2996
+ }
2997
+ function normalizeConnections(connections) {
2998
+ if (!connections?.length) {
2999
+ return [];
3000
+ }
3001
+ const byUrl = /* @__PURE__ */ new Map();
3002
+ for (const connection of connections) {
3003
+ const url = connection.url?.trim();
3004
+ if (!url) {
3005
+ continue;
3006
+ }
3007
+ byUrl.set(url, {
3008
+ ...connection,
3009
+ url,
3010
+ name: connection.name?.trim() || url
3011
+ });
3012
+ }
3013
+ return Array.from(byUrl.values());
3014
+ }
3015
+ function mergeConnections(runtimeConnections, existingConnections) {
3016
+ const byUrl = /* @__PURE__ */ new Map();
3017
+ for (const connection of existingConnections) {
3018
+ byUrl.set(connection.url, connection);
3019
+ }
3020
+ for (const connection of runtimeConnections) {
3021
+ byUrl.set(connection.url, connection);
3022
+ }
3023
+ return Array.from(byUrl.values());
3024
+ }
3025
+ var AppAgentController = class {
3026
+ constructor(config) {
3027
+ this.config = config;
3028
+ this.listeners = /* @__PURE__ */ new Set();
3029
+ this.recoveredConversationIds = /* @__PURE__ */ new Set();
3030
+ this.approvalResolvers = /* @__PURE__ */ new Map();
3031
+ this.inputResolvers = /* @__PURE__ */ new Map();
3032
+ this.pendingToolCallsByAction = /* @__PURE__ */ new Map();
3033
+ this.lifecycleUnsubscribers = [];
3034
+ this.userMessageDisplayOverrides = /* @__PURE__ */ new Map();
3035
+ this.started = false;
3036
+ this.disposed = false;
3037
+ this.initializationPromise = null;
3038
+ this.pendingDisplayText = null;
3039
+ this.getSnapshot = () => this.snapshot;
3040
+ this.handleMessage = (message) => {
3041
+ if (message.role === "user" && this.pendingDisplayText) {
3042
+ this.userMessageDisplayOverrides.set(message.id, this.pendingDisplayText);
3043
+ this.pendingDisplayText = null;
3044
+ }
3045
+ this.setState((current) => ({
3046
+ ...current,
3047
+ conversation: {
3048
+ ...current.conversation,
3049
+ messages: [...current.conversation.messages, message],
3050
+ id: this.agent.getConversationId(),
3051
+ streamingContent: "",
3052
+ hasOlderMessages: this.agent.getHasOlderMessages(),
3053
+ pendingTurnSawActivity: current.conversation.pendingTurn ? true : current.conversation.pendingTurnSawActivity
3054
+ }
3055
+ }));
3056
+ void this.persistResumeRecord();
3057
+ this.finalizePendingTurnIfSettled();
3058
+ };
3059
+ this.handleContentDelta = (delta) => {
3060
+ this.setState((current) => ({
3061
+ ...current,
3062
+ conversation: {
3063
+ ...current.conversation,
3064
+ streamingContent: current.conversation.streamingContent + delta.text,
3065
+ pendingTurnSawActivity: current.conversation.pendingTurn ? true : current.conversation.pendingTurnSawActivity
3066
+ }
3067
+ }));
3068
+ };
3069
+ this.handleToolCall = (toolCall) => {
3070
+ if (toolCall.toolName === APP_AGENT_APPROVAL_ACTION || toolCall.toolName === APP_AGENT_INPUT_ACTION) {
3071
+ const queue = this.pendingToolCallsByAction.get(toolCall.toolName) ?? [];
3072
+ queue.push(toolCall.toolCallId);
3073
+ this.pendingToolCallsByAction.set(toolCall.toolName, queue);
3074
+ }
3075
+ this.setState((current) => ({
3076
+ ...current,
3077
+ conversation: {
3078
+ ...current.conversation,
3079
+ id: this.agent.getConversationId(),
3080
+ messages: [
3081
+ ...current.conversation.messages,
3082
+ {
3083
+ id: crypto.randomUUID(),
3084
+ role: "tool_call",
3085
+ content: `Calling ${toolCall.toolLabel ?? toolCall.toolName}...`,
3086
+ toolName: toolCall.toolName,
3087
+ toolLabel: toolCall.toolLabel,
3088
+ toolCallId: toolCall.toolCallId,
3089
+ timestamp: /* @__PURE__ */ new Date(),
3090
+ toolCallStatus: "calling",
3091
+ toolCallStartTime: Date.now()
3092
+ }
3093
+ ],
3094
+ pendingTurnSawActivity: current.conversation.pendingTurn ? true : current.conversation.pendingTurnSawActivity
3095
+ }
3096
+ }));
3097
+ };
3098
+ this.handleToolResult = (data) => {
3099
+ this.setState((current) => ({
3100
+ ...current,
3101
+ conversation: {
3102
+ ...current.conversation,
3103
+ messages: current.conversation.messages.map(
3104
+ (message) => message.role === "tool_call" && message.toolCallId === data.toolCallId ? {
3105
+ ...message,
3106
+ toolCallStatus: "completed",
3107
+ toolCallDuration: data.duration,
3108
+ toolResult: typeof data.result === "string" ? data.result : JSON.stringify(data.result)
3109
+ } : message
3110
+ )
3111
+ }
3112
+ }));
3113
+ this.finalizePendingTurnIfSettled();
3114
+ };
3115
+ this.handleToolError = (data) => {
3116
+ this.setState((current) => ({
3117
+ ...current,
3118
+ conversation: {
3119
+ ...current.conversation,
3120
+ messages: current.conversation.messages.map(
3121
+ (message) => message.role === "tool_call" && message.toolCallId === data.toolCallId ? {
3122
+ ...message,
3123
+ toolCallStatus: "error",
3124
+ toolCallDuration: data.duration,
3125
+ toolError: data.error
3126
+ } : message
3127
+ )
3128
+ }
3129
+ }));
3130
+ this.finalizePendingTurnIfSettled();
3131
+ };
3132
+ this.handleThinking = (thinking) => {
3133
+ this.setState((current) => ({
3134
+ ...current,
3135
+ conversation: {
3136
+ ...current.conversation,
3137
+ isThinking: thinking
3138
+ }
3139
+ }));
3140
+ this.finalizePendingTurnIfSettled();
3141
+ };
3142
+ this.handleLoading = (loading) => {
3143
+ this.setState((current) => ({
3144
+ ...current,
3145
+ conversation: {
3146
+ ...current.conversation,
3147
+ isLoading: loading,
3148
+ error: loading ? null : current.conversation.error,
3149
+ streamingContent: loading ? "" : current.conversation.streamingContent
3150
+ }
3151
+ }));
3152
+ this.finalizePendingTurnIfSettled();
3153
+ };
3154
+ this.handleError = (error) => {
3155
+ this.setState((current) => ({
3156
+ ...current,
3157
+ budget: error.budget ?? current.budget,
3158
+ conversation: {
3159
+ ...current.conversation,
3160
+ error,
3161
+ pendingTurn: null,
3162
+ pendingTurnSawActivity: false
3163
+ }
3164
+ }));
3165
+ if (isToolRoutingResetError(error)) {
3166
+ const conversationId = this.agent.getConversationId();
3167
+ if (conversationId && !this.recoveredConversationIds.has(conversationId)) {
3168
+ this.recoveredConversationIds.add(conversationId);
3169
+ void this.handleStaleConversation(error);
3170
+ return;
3171
+ }
3172
+ }
3173
+ this.setState((current) => ({
3174
+ ...current,
3175
+ conversation: {
3176
+ ...current.conversation,
3177
+ issue: {
3178
+ code: "runtime_error",
3179
+ message: error.message,
3180
+ recoverable: false
3181
+ }
3182
+ }
3183
+ }));
3184
+ };
3185
+ this.handleBudgetSnapshot = (budget) => {
3186
+ this.setState((current) => ({
3187
+ ...current,
3188
+ budget
3189
+ }));
3190
+ };
3191
+ this.handleMcpAuthStatus = () => {
3192
+ this.setState((current) => ({
3193
+ ...current,
3194
+ connections: {
3195
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3196
+ }
3197
+ }));
3198
+ };
3199
+ this.handleAudioState = (voice) => {
3200
+ this.setState((current) => ({
3201
+ ...current,
3202
+ voice
3203
+ }));
3204
+ };
3205
+ this.platform = config.platform ?? createBrowserAppAgentPlatform();
3206
+ const onAuthRequired = config.onAuthRequired ?? (!config.auth && this.platform.auth ? createPlatformAuthHandler({
3207
+ platform: this.platform,
3208
+ userIdentity: config.userIdentity,
3209
+ oauthCallbackUrl: config.oauthCallbackUrl ?? ""
3210
+ }) : void 0);
3211
+ this.agent = new McpStackAgent({
3212
+ apiKey: config.apiKey,
3213
+ agentId: config.agentId,
3214
+ agentServiceUrl: config.serviceUrl,
3215
+ oauthCallbackUrl: config.oauthCallbackUrl,
3216
+ oauthClientMetadataUrl: config.oauthClientMetadataUrl,
3217
+ getAuthToken: config.getAuthToken,
3218
+ authSessionKey: config.appSessionKey,
3219
+ auth: config.auth,
3220
+ embeddedAuth: config.userIdentity ? {
3221
+ hostIdentity: config.userIdentity,
3222
+ mismatchPolicy: "block_with_switch"
3223
+ } : void 0,
3224
+ useCookies: config.useCookies,
3225
+ onAuthRequired,
3226
+ externalUserId: config.externalUserId ?? config.userIdentity?.subject ?? config.userIdentity?.email,
3227
+ context: config.appContext,
3228
+ clientTools: this.buildClientTools(config.clientTools),
3229
+ conversationHistoryPageSize: config.conversation?.historyPageSize ?? 50,
3230
+ storage: config.storage
3231
+ });
3232
+ this.state = {
3233
+ runtime: {
3234
+ agentConfig: null
3235
+ },
3236
+ conversation: {
3237
+ id: null,
3238
+ messages: [],
3239
+ streamingContent: "",
3240
+ pendingTurn: null,
3241
+ pendingTurnSawActivity: false,
3242
+ statusLabel: "Connecting\u2026",
3243
+ resumeKey: this.getResumeStorageKey(),
3244
+ isReady: false,
3245
+ isLoading: false,
3246
+ isLoadingHistory: false,
3247
+ isThinking: false,
3248
+ hasOlderMessages: false,
3249
+ error: null,
3250
+ issue: null
3251
+ },
3252
+ connections: {
3253
+ items: normalizeConnections(config.initialConnections)
3254
+ },
3255
+ approvals: {
3256
+ pending: []
3257
+ },
3258
+ requests: {
3259
+ pending: []
3260
+ },
3261
+ feedback: {
3262
+ isSubmitting: false,
3263
+ error: null,
3264
+ lastSubmittedAt: null,
3265
+ lastFeedback: null
3266
+ },
3267
+ voice: this.agent.getAudioInputState(),
3268
+ budget: this.agent.getBudgetSnapshot()
3269
+ };
3270
+ this.recomputeDerivedState();
3271
+ this.snapshot = this.buildSnapshot();
3272
+ }
3273
+ getAgent() {
3274
+ return this.agent;
3275
+ }
3276
+ buildSnapshot() {
3277
+ const messages = applyUserMessageOverrides(
3278
+ this.state.conversation.messages,
3279
+ Object.fromEntries(this.userMessageDisplayOverrides)
3280
+ );
3281
+ const visibleMessages = deriveVisibleMessages(messages);
3282
+ const conversationMessages = deriveConversationMessages(messages);
3283
+ const toolMessages = deriveToolMessages(visibleMessages);
3284
+ const latestAssistantMessage = getLatestAssistantMessage(visibleMessages);
3285
+ const latestToolMessage = getLatestToolMessage(toolMessages);
3286
+ const latestUserMessage = getLatestUserMessage(visibleMessages);
3287
+ const lastTurn = deriveLastTurnSummary(messages);
3288
+ const renderedNodes = buildRenderedNodes(messages);
3289
+ const inlineFeed = deriveInlineFeedState({
3290
+ pendingTurn: this.state.conversation.pendingTurn,
3291
+ toolMessages,
3292
+ latestAssistantMessage: latestAssistantMessage ? { id: latestAssistantMessage.id, content: latestAssistantMessage.content } : null,
3293
+ streamingContent: this.state.conversation.streamingContent,
3294
+ isLoading: this.state.conversation.isLoading,
3295
+ isThinking: this.state.conversation.isThinking
3296
+ });
3297
+ return {
3298
+ runtime: {
3299
+ agent: this.agent,
3300
+ agentConfig: this.state.runtime.agentConfig
3301
+ },
3302
+ conversation: {
3303
+ ...this.state.conversation,
3304
+ messages,
3305
+ visibleMessages,
3306
+ conversationMessages,
3307
+ toolMessages,
3308
+ renderedNodes,
3309
+ latestAssistantMessage,
3310
+ latestToolMessage,
3311
+ latestUserMessage,
3312
+ lastTurn,
3313
+ pendingTurn: this.state.conversation.pendingTurn,
3314
+ inlineFeed
3315
+ },
3316
+ connections: {
3317
+ ...this.state.connections,
3318
+ needsAttention: this.state.connections.items.some((item) => item.authStatus === "needs_auth")
3319
+ },
3320
+ approvals: {
3321
+ pending: this.state.approvals.pending
3322
+ },
3323
+ requests: {
3324
+ pending: this.state.requests.pending
3325
+ },
3326
+ feedback: this.state.feedback,
3327
+ budget: this.state.budget,
3328
+ voice: this.state.voice
3329
+ };
3330
+ }
3331
+ subscribe(listener) {
3332
+ this.listeners.add(listener);
3333
+ return () => {
3334
+ this.listeners.delete(listener);
3335
+ };
3336
+ }
3337
+ start() {
3338
+ if (this.started || this.disposed) {
3339
+ return;
3340
+ }
3341
+ this.started = true;
3342
+ this.bindLifecycleSignals();
3343
+ this.bindRuntimeEvents();
3344
+ this.initializationPromise = this.initialize();
3345
+ }
3346
+ dispose() {
3347
+ if (this.disposed) {
3348
+ return;
3349
+ }
3350
+ this.disposed = true;
3351
+ this.started = false;
3352
+ this.agent.off("message", this.handleMessage);
3353
+ this.agent.off("content_delta", this.handleContentDelta);
3354
+ this.agent.off("tool_call", this.handleToolCall);
3355
+ this.agent.off("tool_result", this.handleToolResult);
3356
+ this.agent.off("tool_error", this.handleToolError);
3357
+ this.agent.off("thinking", this.handleThinking);
3358
+ this.agent.off("loading", this.handleLoading);
3359
+ this.agent.off("error", this.handleError);
3360
+ this.agent.off("mcp_auth_status", this.handleMcpAuthStatus);
3361
+ this.agent.off("audio_state", this.handleAudioState);
3362
+ this.lifecycleUnsubscribers.splice(0).forEach((unsubscribe) => unsubscribe());
3363
+ this.agent.cancelVoiceInput();
3364
+ this.agent.cancel();
3365
+ this.approvalResolvers.clear();
3366
+ this.inputResolvers.clear();
3367
+ this.listeners.clear();
3368
+ }
3369
+ updateDynamicConfig(config) {
3370
+ this.config = {
3371
+ ...this.config,
3372
+ ...config
3373
+ };
3374
+ this.agent.setAppContext(this.config.appContext);
3375
+ this.agent.setClientTools(this.buildClientTools(this.config.clientTools));
3376
+ }
3377
+ setAuthRequiredHandler(onAuthRequired) {
3378
+ this.config = {
3379
+ ...this.config,
3380
+ onAuthRequired
3381
+ };
3382
+ this.agent.setOnAuthRequired(onAuthRequired);
3383
+ }
3384
+ async send(prompt, options) {
3385
+ const trimmed = prompt.trim();
3386
+ if (!trimmed) {
3387
+ return;
3388
+ }
3389
+ const displayText = (options?.displayText ?? trimmed).trim() || trimmed;
3390
+ this.pendingDisplayText = displayText;
3391
+ this.setState((current) => ({
3392
+ ...current,
3393
+ conversation: {
3394
+ ...current.conversation,
3395
+ pendingTurn: createInlinePendingTurnState(displayText, current.conversation.messages),
3396
+ pendingTurnSawActivity: false,
3397
+ issue: null
3398
+ }
3399
+ }));
3400
+ try {
3401
+ await this.agent.sendMessage(trimmed);
3402
+ } catch (error) {
3403
+ this.pendingDisplayText = null;
3404
+ const message = error instanceof Error ? error.message : "Could not send message.";
3405
+ this.setState((current) => ({
3406
+ ...current,
3407
+ conversation: {
3408
+ ...current.conversation,
3409
+ pendingTurn: null,
3410
+ pendingTurnSawActivity: false,
3411
+ error: {
3412
+ code: "send_message_error",
3413
+ message
3414
+ },
3415
+ issue: {
3416
+ code: "runtime_error",
3417
+ message,
3418
+ recoverable: false
3419
+ }
3420
+ }
3421
+ }));
3422
+ throw error;
3423
+ }
3424
+ }
3425
+ cancel() {
3426
+ this.agent.cancel();
3427
+ }
3428
+ async startVoiceInput() {
3429
+ await this.agent.startVoiceInput();
3430
+ }
3431
+ async stopVoiceInput() {
3432
+ await this.agent.stopVoiceInput();
3433
+ }
3434
+ cancelVoiceInput() {
3435
+ this.agent.cancelVoiceInput();
3436
+ }
3437
+ async loadMore() {
3438
+ this.setState((current) => ({
3439
+ ...current,
3440
+ conversation: {
3441
+ ...current.conversation,
3442
+ isLoadingHistory: true
3443
+ }
3444
+ }));
3445
+ try {
3446
+ const page = await this.agent.loadOlderMessages();
3447
+ if (!page) {
3448
+ return;
3449
+ }
3450
+ this.syncFromRuntime();
3451
+ } finally {
3452
+ this.setState((current) => ({
3453
+ ...current,
3454
+ conversation: {
3455
+ ...current.conversation,
3456
+ isLoadingHistory: false
3457
+ }
3458
+ }));
3459
+ }
3460
+ }
3461
+ async resetConversation() {
3462
+ this.agent.newConversation();
3463
+ await this.clearResumeRecord();
3464
+ this.recoveredConversationIds.clear();
3465
+ this.pendingToolCallsByAction.clear();
3466
+ this.approvalResolvers.clear();
3467
+ this.inputResolvers.clear();
3468
+ this.userMessageDisplayOverrides.clear();
3469
+ this.pendingDisplayText = null;
3470
+ this.setState((current) => ({
3471
+ ...current,
3472
+ conversation: {
3473
+ ...current.conversation,
3474
+ id: null,
3475
+ messages: [],
3476
+ streamingContent: "",
3477
+ pendingTurn: null,
3478
+ pendingTurnSawActivity: false,
3479
+ hasOlderMessages: false,
3480
+ error: null,
3481
+ issue: null
3482
+ },
3483
+ approvals: {
3484
+ pending: []
3485
+ },
3486
+ requests: {
3487
+ pending: []
3488
+ }
3489
+ }));
3490
+ }
3491
+ async connect(serverUrl) {
3492
+ await this.ensureInitialized();
3493
+ const result = await this.agent.authenticate(serverUrl);
3494
+ this.setState((current) => ({
3495
+ ...current,
3496
+ connections: {
3497
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3498
+ },
3499
+ budget: this.agent.getBudgetSnapshot()
3500
+ }));
3501
+ return result;
3502
+ }
3503
+ async disconnect(serverUrl) {
3504
+ await this.agent.signOutMcpServer(serverUrl);
3505
+ this.setState((current) => ({
3506
+ ...current,
3507
+ connections: {
3508
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3509
+ }
3510
+ }));
3511
+ }
3512
+ async submitFeedback(input) {
3513
+ this.setState((current) => ({
3514
+ ...current,
3515
+ feedback: {
3516
+ ...current.feedback,
3517
+ isSubmitting: true,
3518
+ error: null
3519
+ }
3520
+ }));
3521
+ try {
3522
+ const feedback = await this.agent.submitFeedback({
3523
+ ...input,
3524
+ source: this.config.feedbackSource ?? "app-agent"
3525
+ });
3526
+ this.setState((current) => ({
3527
+ ...current,
3528
+ feedback: {
3529
+ isSubmitting: false,
3530
+ error: null,
3531
+ lastSubmittedAt: feedback.createdAt,
3532
+ lastFeedback: feedback
3533
+ }
3534
+ }));
3535
+ return feedback;
3536
+ } catch (error) {
3537
+ const message = error instanceof Error ? error.message : "Could not save feedback.";
3538
+ this.setState((current) => ({
3539
+ ...current,
3540
+ feedback: {
3541
+ ...current.feedback,
3542
+ isSubmitting: false,
3543
+ error: message
3544
+ }
3545
+ }));
3546
+ throw error;
3547
+ }
3548
+ }
3549
+ resolveApproval(id, approved) {
3550
+ const resolver = this.approvalResolvers.get(id);
3551
+ if (!resolver) {
3552
+ return;
3553
+ }
3554
+ this.approvalResolvers.delete(id);
3555
+ this.setState((current) => ({
3556
+ ...current,
3557
+ approvals: {
3558
+ pending: current.approvals.pending.filter((approval) => approval.id !== id)
3559
+ }
3560
+ }));
3561
+ resolver.resolve({ approved });
3562
+ }
3563
+ submitRequest(id, values) {
3564
+ const resolver = this.inputResolvers.get(id);
3565
+ if (!resolver) {
3566
+ return;
3567
+ }
3568
+ this.inputResolvers.delete(id);
3569
+ this.setState((current) => ({
3570
+ ...current,
3571
+ requests: {
3572
+ pending: current.requests.pending.filter((request) => request.id !== id)
3573
+ }
3574
+ }));
3575
+ resolver.resolve({ submitted: true, values });
3576
+ }
3577
+ cancelRequest(id) {
3578
+ const resolver = this.inputResolvers.get(id);
3579
+ if (!resolver) {
3580
+ return;
3581
+ }
3582
+ this.inputResolvers.delete(id);
3583
+ this.setState((current) => ({
3584
+ ...current,
3585
+ requests: {
3586
+ pending: current.requests.pending.filter((request) => request.id !== id)
3587
+ }
3588
+ }));
3589
+ resolver.resolve({ submitted: false });
3590
+ }
3591
+ async initialize() {
3592
+ try {
3593
+ const agentConfig = await this.agent.init();
3594
+ if (this.disposed) {
3595
+ return;
3596
+ }
3597
+ this.setState((current) => ({
3598
+ ...current,
3599
+ runtime: {
3600
+ agentConfig
3601
+ },
3602
+ conversation: {
3603
+ ...current.conversation,
3604
+ isReady: true
3605
+ },
3606
+ connections: {
3607
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3608
+ },
3609
+ budget: this.agent.getBudgetSnapshot()
3610
+ }));
3611
+ const resumeRecord = await this.readResumeRecord();
3612
+ if (resumeRecord && resumeRecord.agentId === this.config.agentId && resumeRecord.appSessionKey === (this.config.appSessionKey ?? null) && resumeRecord.conversationResumeVersion === agentConfig.conversationResumeVersion) {
3613
+ this.setState((current) => ({
3614
+ ...current,
3615
+ conversation: {
3616
+ ...current.conversation,
3617
+ isLoadingHistory: true
3618
+ }
3619
+ }));
3620
+ try {
3621
+ await this.agent.loadConversation(
3622
+ resumeRecord.conversationId,
3623
+ this.config.conversation?.historyPageSize ?? 50
3624
+ );
3625
+ } catch (error) {
3626
+ this.setState((current) => ({
3627
+ ...current,
3628
+ conversation: {
3629
+ ...current.conversation,
3630
+ error: {
3631
+ code: "conversation_history_error",
3632
+ message: error instanceof Error ? error.message : "Failed to load conversation history."
3633
+ }
3634
+ }
3635
+ }));
3636
+ await this.clearResumeRecord();
3637
+ } finally {
3638
+ this.syncFromRuntime();
3639
+ this.setState((current) => ({
3640
+ ...current,
3641
+ conversation: {
3642
+ ...current.conversation,
3643
+ isLoadingHistory: false
3644
+ }
3645
+ }));
3646
+ }
3647
+ } else {
3648
+ this.syncFromRuntime();
3649
+ }
3650
+ } catch (error) {
3651
+ const message = error instanceof Error && error.message.trim() ? error.message.trim() : "Failed to load agent configuration.";
3652
+ this.setState((current) => ({
3653
+ ...current,
3654
+ conversation: {
3655
+ ...current.conversation,
3656
+ error: {
3657
+ code: /api key|unauthorized|401/i.test(message) ? "agent_config_auth_error" : "agent_config_error",
3658
+ message
3659
+ },
3660
+ issue: {
3661
+ code: "config_error",
3662
+ message,
3663
+ recoverable: false
3664
+ }
3665
+ }
3666
+ }));
3667
+ }
3668
+ }
3669
+ async ensureInitialized() {
3670
+ if (this.state.runtime.agentConfig) {
3671
+ return;
3672
+ }
3673
+ this.initializationPromise ?? (this.initializationPromise = this.initialize());
3674
+ await this.initializationPromise;
3675
+ }
3676
+ bindRuntimeEvents() {
3677
+ this.agent.on("message", this.handleMessage);
3678
+ this.agent.on("content_delta", this.handleContentDelta);
3679
+ this.agent.on("tool_call", this.handleToolCall);
3680
+ this.agent.on("tool_result", this.handleToolResult);
3681
+ this.agent.on("tool_error", this.handleToolError);
3682
+ this.agent.on("thinking", this.handleThinking);
3683
+ this.agent.on("loading", this.handleLoading);
3684
+ this.agent.on("error", this.handleError);
3685
+ this.agent.on("mcp_auth_status", this.handleMcpAuthStatus);
3686
+ this.agent.on("audio_state", this.handleAudioState);
3687
+ this.agent.on("budget_snapshot", this.handleBudgetSnapshot);
3688
+ }
3689
+ async handleStaleConversation(error) {
3690
+ await this.clearResumeRecord();
3691
+ this.agent.newConversation();
3692
+ this.pendingToolCallsByAction.clear();
3693
+ this.approvalResolvers.clear();
3694
+ this.inputResolvers.clear();
3695
+ this.userMessageDisplayOverrides.clear();
3696
+ this.pendingDisplayText = null;
3697
+ this.setState((current) => ({
3698
+ ...current,
3699
+ conversation: {
3700
+ ...current.conversation,
3701
+ id: null,
3702
+ messages: [],
3703
+ streamingContent: "",
3704
+ pendingTurn: null,
3705
+ pendingTurnSawActivity: false,
3706
+ hasOlderMessages: false,
3707
+ issue: {
3708
+ code: "stale_conversation",
3709
+ message: error.message,
3710
+ recoverable: true
3711
+ }
3712
+ },
3713
+ approvals: {
3714
+ pending: []
3715
+ },
3716
+ requests: {
3717
+ pending: []
3718
+ }
3719
+ }));
3720
+ }
3721
+ bindLifecycleSignals() {
3722
+ const lifecycle = this.platform.lifecycle;
3723
+ if (!lifecycle) {
3724
+ return;
3725
+ }
3726
+ const foregroundUnsubscribe = lifecycle.onForegroundChange?.(() => {
3727
+ this.emit();
3728
+ });
3729
+ if (foregroundUnsubscribe) {
3730
+ this.lifecycleUnsubscribers.push(foregroundUnsubscribe);
3731
+ }
3732
+ const connectivityUnsubscribe = lifecycle.onConnectivityChange?.(() => {
3733
+ this.emit();
3734
+ });
3735
+ if (connectivityUnsubscribe) {
3736
+ this.lifecycleUnsubscribers.push(connectivityUnsubscribe);
3737
+ }
3738
+ }
3739
+ buildClientTools(clientTools) {
3740
+ const approvalAction = {
3741
+ description: "Ask the host app to approve a multi-step plan before you continue.",
3742
+ selection: {
3743
+ categories: ["approval"],
3744
+ alwaysInclude: true,
3745
+ risk: "medium"
3746
+ },
3747
+ parameters: {
3748
+ title: { type: "string", description: "Short title for the approval request.", required: true },
3749
+ rationale: { type: "string", description: "Optional reason for the plan." },
3750
+ steps: { type: "array", description: "Ordered steps that need approval.", required: true },
3751
+ confirmLabel: { type: "string", description: "Optional label for the approve action." },
3752
+ cancelLabel: { type: "string", description: "Optional label for the reject action." }
3753
+ },
3754
+ execute: async (params) => {
3755
+ const approvalId = createId("approval");
3756
+ const toolCallId = this.shiftPendingToolCallId(APP_AGENT_APPROVAL_ACTION);
3757
+ const approval = {
3758
+ id: approvalId,
3759
+ title: typeof params.title === "string" ? params.title : "Approval required",
3760
+ rationale: typeof params.rationale === "string" ? params.rationale : void 0,
3761
+ steps: normalizeSteps(params.steps),
3762
+ toolCallId,
3763
+ confirmLabel: typeof params.confirmLabel === "string" ? params.confirmLabel : void 0,
3764
+ cancelLabel: typeof params.cancelLabel === "string" ? params.cancelLabel : void 0
3765
+ };
3766
+ this.setState((current) => ({
3767
+ ...current,
3768
+ approvals: {
3769
+ pending: [...current.approvals.pending, approval]
3770
+ }
3771
+ }));
3772
+ return await new Promise((resolve) => {
3773
+ this.approvalResolvers.set(approvalId, { resolve });
3774
+ });
3775
+ }
3776
+ };
3777
+ return {
3778
+ ...clientTools ?? {},
3779
+ [APP_AGENT_APPROVAL_ACTION]: {
3780
+ ...approvalAction
3781
+ },
3782
+ [APP_AGENT_INPUT_ACTION]: {
3783
+ description: "Ask the host app for structured user input before you continue.",
3784
+ selection: {
3785
+ categories: ["approval"],
3786
+ alwaysInclude: true,
3787
+ risk: "medium"
3788
+ },
3789
+ parameters: {
3790
+ title: { type: "string", description: "Short title for the input request.", required: true },
3791
+ prompt: { type: "string", description: "Optional explainer shown above the fields." },
3792
+ fields: { type: "array", description: "Structured fields to collect.", required: true },
3793
+ submitLabel: { type: "string", description: "Optional submit button label." },
3794
+ cancelLabel: { type: "string", description: "Optional cancel button label." }
3795
+ },
3796
+ execute: async (params) => {
3797
+ const requestId = createId("input");
3798
+ const toolCallId = this.shiftPendingToolCallId(APP_AGENT_INPUT_ACTION);
3799
+ const request = {
3800
+ id: requestId,
3801
+ title: typeof params.title === "string" ? params.title : "Input required",
3802
+ prompt: typeof params.prompt === "string" ? params.prompt : void 0,
3803
+ fields: normalizeInputFields(params.fields),
3804
+ toolCallId,
3805
+ submitLabel: typeof params.submitLabel === "string" ? params.submitLabel : void 0,
3806
+ cancelLabel: typeof params.cancelLabel === "string" ? params.cancelLabel : void 0
3807
+ };
3808
+ this.setState((current) => ({
3809
+ ...current,
3810
+ requests: {
3811
+ pending: [...current.requests.pending, request]
3812
+ }
3813
+ }));
3814
+ return await new Promise((resolve) => {
3815
+ this.inputResolvers.set(requestId, { resolve });
3816
+ });
3817
+ }
3818
+ }
3819
+ };
3820
+ }
3821
+ shiftPendingToolCallId(actionName) {
3822
+ const queue = this.pendingToolCallsByAction.get(actionName) ?? [];
3823
+ const next = queue.shift() ?? null;
3824
+ if (queue.length === 0) {
3825
+ this.pendingToolCallsByAction.delete(actionName);
3826
+ } else {
3827
+ this.pendingToolCallsByAction.set(actionName, queue);
3828
+ }
3829
+ return next;
3830
+ }
3831
+ syncFromRuntime() {
3832
+ this.setState((current) => ({
3833
+ ...current,
3834
+ conversation: {
3835
+ ...current.conversation,
3836
+ id: this.agent.getConversationId(),
3837
+ messages: this.agent.getMessages(),
3838
+ hasOlderMessages: this.agent.getHasOlderMessages()
3839
+ },
3840
+ connections: {
3841
+ items: mergeConnections(mapConnections(this.agent), current.connections.items)
3842
+ }
3843
+ }));
3844
+ void this.persistResumeRecord();
3845
+ }
3846
+ finalizePendingTurnIfSettled() {
3847
+ const current = this.state.conversation;
3848
+ if (current.pendingTurn && current.pendingTurnSawActivity && !current.isLoading && !current.isThinking && !current.streamingContent) {
3849
+ this.setState((state) => ({
3850
+ ...state,
3851
+ conversation: {
3852
+ ...state.conversation,
3853
+ pendingTurn: null,
3854
+ pendingTurnSawActivity: false
3855
+ }
3856
+ }));
3857
+ }
3858
+ }
3859
+ getResumeStorageKey() {
3860
+ const durable = this.platform.storage?.durable;
3861
+ if (!durable) {
3862
+ return null;
3863
+ }
3864
+ const namespace = this.config.conversation?.namespace ?? "mcpstack.app-agent.resume";
3865
+ const sessionKey = this.config.appSessionKey?.trim() || "anonymous";
3866
+ return `${namespace}:${this.config.agentId}:${sessionKey}`;
3867
+ }
3868
+ async readResumeRecord() {
3869
+ const durable = this.platform.storage?.durable;
3870
+ const resumeKey = this.getResumeStorageKey();
3871
+ if (!durable || !resumeKey) {
3872
+ return null;
3873
+ }
3874
+ try {
3875
+ const raw = await resolveStoreValue(durable.getItem(resumeKey));
3876
+ if (!raw) {
3877
+ return null;
3878
+ }
3879
+ return JSON.parse(raw);
3880
+ } catch {
3881
+ return null;
3882
+ }
3883
+ }
3884
+ async persistResumeRecord() {
3885
+ const durable = this.platform.storage?.durable;
3886
+ const resumeKey = this.getResumeStorageKey();
3887
+ const conversationId = this.agent.getConversationId();
3888
+ const agentConfig = this.state.runtime.agentConfig;
3889
+ if (!durable || !resumeKey || !conversationId || !agentConfig) {
3890
+ return;
3891
+ }
3892
+ const record = {
3893
+ conversationId,
3894
+ agentId: this.config.agentId,
3895
+ appSessionKey: this.config.appSessionKey ?? null,
3896
+ conversationResumeVersion: agentConfig.conversationResumeVersion,
3897
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3898
+ };
3899
+ try {
3900
+ await resolveStoreValue(durable.setItem(resumeKey, JSON.stringify(record)));
3901
+ } catch {
3902
+ }
3903
+ }
3904
+ async clearResumeRecord() {
3905
+ const durable = this.platform.storage?.durable;
3906
+ const resumeKey = this.getResumeStorageKey();
3907
+ if (!durable || !resumeKey) {
3908
+ return;
3909
+ }
3910
+ try {
3911
+ await resolveStoreValue(durable.removeItem(resumeKey));
3912
+ } catch {
3913
+ }
3914
+ }
3915
+ setState(update) {
3916
+ if (this.disposed) {
3917
+ return;
3918
+ }
3919
+ this.state = update(this.state);
3920
+ this.recomputeDerivedState();
3921
+ this.snapshot = this.buildSnapshot();
3922
+ this.emit();
3923
+ }
3924
+ recomputeDerivedState() {
3925
+ const hasAttention = this.state.connections.items.some((item) => item.authStatus === "needs_auth");
3926
+ this.state.conversation.statusLabel = deriveConversationStatusLabel({
3927
+ isReady: this.state.conversation.isReady,
3928
+ isLoading: this.state.conversation.isLoading,
3929
+ isThinking: this.state.conversation.isThinking,
3930
+ streamingContent: this.state.conversation.streamingContent,
3931
+ hasError: this.state.conversation.error != null,
3932
+ hasIssue: this.state.conversation.issue != null,
3933
+ hasAttention
3934
+ });
3935
+ this.state.conversation.resumeKey = this.getResumeStorageKey();
3936
+ }
3937
+ emit() {
3938
+ for (const listener of this.listeners) {
3939
+ listener();
3940
+ }
3941
+ }
3942
+ };
3943
+
3944
+ // src/framework/useAppAgentBinding.tsx
3945
+ function useAppAgentBinding(config, options, auth = {}) {
3946
+ const enabled = options?.enabled ?? true;
3947
+ const disposeTimerRef = (0, import_react.useRef)(null);
3948
+ const controller = (0, import_react.useMemo)(() => new AppAgentController({
3949
+ ...config,
3950
+ onAuthRequired: auth.onAuthRequired ?? config.onAuthRequired
3951
+ }), [
3952
+ auth.onAuthRequired,
3953
+ config.agentId,
3954
+ config.apiKey,
3955
+ config.appSessionKey,
3956
+ config.auth?.appId,
3957
+ config.auth?.getToken,
3958
+ config.auth?.mode,
3959
+ config.conversation?.historyPageSize,
3960
+ config.conversation?.namespace,
3961
+ config.externalUserId,
3962
+ config.getAuthToken,
3963
+ config.oauthCallbackUrl,
3964
+ config.oauthClientMetadataUrl,
3965
+ config.onAuthRequired,
3966
+ config.platform,
3967
+ config.serviceUrl,
3968
+ config.storage,
3969
+ config.useCookies,
3970
+ config.userIdentity?.subject,
3971
+ enabled
3972
+ ]);
3973
+ (0, import_react.useEffect)(() => {
3974
+ if (disposeTimerRef.current) {
3975
+ clearTimeout(disposeTimerRef.current);
3976
+ disposeTimerRef.current = null;
3977
+ }
3978
+ return () => {
3979
+ disposeTimerRef.current = setTimeout(() => {
3980
+ controller.dispose();
3981
+ disposeTimerRef.current = null;
3982
+ }, 0);
3983
+ };
3984
+ }, [controller]);
3985
+ (0, import_react.useEffect)(() => {
3986
+ controller.updateDynamicConfig({
3987
+ appContext: config.appContext,
3988
+ clientTools: config.clientTools,
3989
+ feedbackSource: config.feedbackSource
3990
+ });
3991
+ }, [config.appContext, config.clientTools, config.feedbackSource, controller]);
3992
+ (0, import_react.useEffect)(() => {
3993
+ controller.setAuthRequiredHandler(auth.onAuthRequired ?? config.onAuthRequired);
3994
+ }, [auth.onAuthRequired, config.onAuthRequired, controller]);
3995
+ (0, import_react.useEffect)(() => {
3996
+ if (!enabled) {
3997
+ return;
3998
+ }
3999
+ controller.start();
4000
+ }, [controller, enabled]);
4001
+ const snapshot = (0, import_react.useSyncExternalStore)(
4002
+ controller.subscribe.bind(controller),
4003
+ controller.getSnapshot,
4004
+ controller.getSnapshot
4005
+ );
4006
+ return {
4007
+ controller,
4008
+ runtime: snapshot.runtime,
4009
+ conversation: {
4010
+ ...snapshot.conversation,
4011
+ loadMore: () => controller.loadMore(),
4012
+ reset: () => controller.resetConversation()
4013
+ },
4014
+ composer: {
4015
+ send: (prompt, sendOptions) => controller.send(prompt, sendOptions),
4016
+ cancel: () => controller.cancel()
4017
+ },
4018
+ connections: {
4019
+ ...snapshot.connections,
4020
+ connect: (serverUrl) => controller.connect(serverUrl),
4021
+ disconnect: (serverUrl) => controller.disconnect(serverUrl)
4022
+ },
4023
+ approvals: {
4024
+ ...snapshot.approvals,
4025
+ resolve: (id, approved) => controller.resolveApproval(id, approved)
4026
+ },
4027
+ requests: {
4028
+ ...snapshot.requests,
4029
+ submit: (id, values) => controller.submitRequest(id, values),
4030
+ cancel: (id) => controller.cancelRequest(id)
4031
+ },
4032
+ feedback: {
4033
+ ...snapshot.feedback,
4034
+ submit: (input) => controller.submitFeedback(input)
4035
+ },
4036
+ budget: snapshot.budget,
4037
+ voice: {
4038
+ ...snapshot.voice,
4039
+ start: () => controller.startVoiceInput(),
4040
+ stop: () => controller.stopVoiceInput(),
4041
+ cancel: () => controller.cancelVoiceInput()
4042
+ },
4043
+ popupAuthState: auth.popupAuthState ?? null,
4044
+ startOrRetryPopupAuth: auth.startOrRetryPopupAuth ?? (() => void 0),
4045
+ cancelPopupAuth: auth.cancelPopupAuth ?? (() => void 0)
4046
+ };
4047
+ }
4048
+
4049
+ // src/react-native/index.tsx
4050
+ var import_jsx_runtime = require("react/jsx-runtime");
4051
+ var AppAgentContext = (0, import_react2.createContext)(null);
4052
+ function useAppAgent(config, options) {
4053
+ return useAppAgentBinding(config, options);
4054
+ }
4055
+ function AppAgentProvider({
4056
+ children,
4057
+ ...config
4058
+ }) {
4059
+ const value = useAppAgent(config);
4060
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AppAgentContext.Provider, { value, children });
4061
+ }
4062
+ function useAppAgentContext() {
4063
+ const context = (0, import_react2.useContext)(AppAgentContext);
4064
+ if (!context) {
4065
+ throw new Error("useAppAgentContext must be used within an AppAgentProvider.");
4066
+ }
4067
+ return context;
4068
+ }
4069
+ // Annotate the CommonJS export names for ESM import in node:
4070
+ 0 && (module.exports = {
4071
+ AppAgentProvider,
4072
+ useAppAgent,
4073
+ useAppAgentContext
4074
+ });
4075
+ //# sourceMappingURL=index.js.map