@dudko.dev/agent-web-react 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -68,24 +68,24 @@ var patchStep = (steps, id, fn) => steps.map((s) => s.id === id ? fn(s) : s);
68
68
  var patchApproval = (approvals, id, fn) => approvals.map((a) => a.id === id ? fn(a) : a);
69
69
  var patchSubagent = (subagents, id, fn) => subagents.map((s) => s.id === id ? fn(s) : s);
70
70
  var runningStepId = (steps) => [...steps].reverse().find((s) => s.status === "running")?.id;
71
- var applySubagentEvent = (view2, event) => {
71
+ var applySubagentEvent = (view, event) => {
72
72
  switch (event.type) {
73
73
  case "step.start":
74
74
  return {
75
- ...view2,
76
- steps: view2.steps + 1,
75
+ ...view,
76
+ steps: view.steps + 1,
77
77
  activity: `step ${event.index}/${event.total}: ${event.step.description}`
78
78
  };
79
79
  case "step.tool-call":
80
- return { ...view2, toolCalls: view2.toolCalls + 1, activity: `\u2192 ${event.name}` };
80
+ return { ...view, toolCalls: view.toolCalls + 1, activity: `\u2192 ${event.name}` };
81
81
  case "final.text-delta":
82
- return { ...view2, text: view2.text + event.delta, activity: "writing the answer" };
82
+ return { ...view, text: view.text + event.delta, activity: "writing the answer" };
83
83
  case "final":
84
- return { ...view2, text: event.text };
84
+ return { ...view, text: event.text };
85
85
  case "usage":
86
- return { ...view2, usage: addUsage(view2.usage, event.usage) };
86
+ return { ...view, usage: addUsage(view.usage, event.usage) };
87
87
  default:
88
- return view2;
88
+ return view;
89
89
  }
90
90
  };
91
91
  var finalizeAssistant = (messages, content, extra = {}) => {
@@ -151,7 +151,7 @@ var applyEvent = (state, event, ctx) => {
151
151
  case "plan.step-added":
152
152
  return state;
153
153
  case "step.start": {
154
- const view2 = {
154
+ const view = {
155
155
  id: event.step.id,
156
156
  index: event.index,
157
157
  total: event.total,
@@ -162,7 +162,7 @@ var applyEvent = (state, event, ctx) => {
162
162
  status: "running",
163
163
  blocked: false
164
164
  };
165
- return { ...state, steps: [...state.steps, view2] };
165
+ return { ...state, steps: [...state.steps, view] };
166
166
  }
167
167
  case "step.reasoning-delta":
168
168
  return {
@@ -952,665 +952,6 @@ var useCredentials = (store) => {
952
952
  return { store: resolved, setKey, removeKey, hasKey, version };
953
953
  };
954
954
 
955
- // src/hooks/use-mcp.ts
956
- import { useCallback as useCallback6, useEffect as useEffect5, useRef as useRef4, useState as useState6 } from "react";
957
- var OAUTH_UNSUPPORTED = "The installed @dudko.dev/agent-web has no MCP OAuth support. Upgrade the core to a version exporting BrowserOAuthProvider, or use a static Authorization header.";
958
- var PENDING_KEY = "agent-web-react:mcp:pending";
959
- var OAUTH_KEY = "agent-web-react:mcp:oauth";
960
- var PENDING_TTL_MS = 10 * 60 * 1e3;
961
- var modulePromise;
962
- var loadMcp = () => {
963
- modulePromise ??= import("@dudko.dev/agent-web/mcp").then((m) => m).catch((err) => {
964
- modulePromise = void 0;
965
- throw err;
966
- });
967
- return modulePromise;
968
- };
969
- var describeMcpResult = (result) => {
970
- if (!result) return { status: "error", error: "The connector returned no result for the server" };
971
- if (result.connected) return { status: "connected" };
972
- if (result.needsAuthorization) return { status: "needs-authorization" };
973
- return { status: "error", error: result.error ?? "Could not connect to the MCP server" };
974
- };
975
- var OAUTH_PARAMS = ["code", "state", "error", "error_description", "iss"];
976
- var readCallbackParams = (href) => {
977
- const target = href ?? (typeof globalThis.location !== "undefined" ? globalThis.location.href : void 0);
978
- if (!target) return void 0;
979
- let url;
980
- try {
981
- url = new URL(target);
982
- } catch {
983
- return void 0;
984
- }
985
- const params = new URLSearchParams(url.search);
986
- const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
987
- const q = hash.indexOf("?");
988
- if (q >= 0) {
989
- for (const [k, v] of new URLSearchParams(hash.slice(q + 1))) {
990
- if (!params.has(k)) params.set(k, v);
991
- }
992
- }
993
- const code = params.get("code") ?? void 0;
994
- const error = params.get("error") ?? void 0;
995
- if (!code && !error) return void 0;
996
- return {
997
- code,
998
- state: params.get("state") ?? void 0,
999
- error,
1000
- errorDescription: params.get("error_description") ?? void 0
1001
- };
1002
- };
1003
- var stripOAuthParams = (href) => {
1004
- const url = new URL(href);
1005
- for (const key of OAUTH_PARAMS) url.searchParams.delete(key);
1006
- const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
1007
- const q = hash.indexOf("?");
1008
- if (q >= 0) {
1009
- const params = new URLSearchParams(hash.slice(q + 1));
1010
- for (const key of OAUTH_PARAMS) params.delete(key);
1011
- const rest = params.toString();
1012
- url.hash = rest ? `${hash.slice(0, q)}?${rest}` : hash.slice(0, q);
1013
- }
1014
- return url.toString();
1015
- };
1016
- var claimedCallbacks = /* @__PURE__ */ new Set();
1017
- var claimOAuthCallback = (callback) => {
1018
- const key = `${callback.code ?? ""}|${callback.state ?? ""}|${callback.error ?? ""}`;
1019
- if (claimedCallbacks.has(key)) return false;
1020
- claimedCallbacks.add(key);
1021
- return true;
1022
- };
1023
- var readRecord = (key) => {
1024
- try {
1025
- const raw = globalThis.localStorage?.getItem(key);
1026
- return raw ? JSON.parse(raw) : void 0;
1027
- } catch {
1028
- return void 0;
1029
- }
1030
- };
1031
- var writeRecord = (key, value) => {
1032
- try {
1033
- if (value) globalThis.localStorage?.setItem(key, JSON.stringify(value));
1034
- else globalThis.localStorage?.removeItem(key);
1035
- } catch {
1036
- }
1037
- };
1038
- var defaultRedirectUrl = () => typeof globalThis.location === "undefined" ? "" : `${globalThis.location.origin}${globalThis.location.pathname}`;
1039
- var isUnauthorizedError = (err, mod) => {
1040
- if (!(err instanceof Error)) return false;
1041
- if (mod?.UnauthorizedError && err instanceof mod.UnauthorizedError) return true;
1042
- return err.constructor?.name === "UnauthorizedError";
1043
- };
1044
- var watchAuthorization = (tools, mod, onUnauthorized) => {
1045
- const entries = Object.entries(tools).map(([name, value]) => {
1046
- const tool = value;
1047
- if (typeof tool.execute !== "function") return [name, value];
1048
- const execute = tool.execute.bind(tool);
1049
- const watched = (args, options) => {
1050
- try {
1051
- const out = execute(args, options);
1052
- if (out && typeof out.then === "function") {
1053
- return out.then(void 0, (err) => {
1054
- if (isUnauthorizedError(err, mod)) onUnauthorized();
1055
- throw err;
1056
- });
1057
- }
1058
- return out;
1059
- } catch (err) {
1060
- if (isUnauthorizedError(err, mod)) onUnauthorized();
1061
- throw err;
1062
- }
1063
- };
1064
- return [name, { ...value, execute: watched }];
1065
- });
1066
- return Object.fromEntries(entries);
1067
- };
1068
- var useMcp = (options = {}) => {
1069
- const [status, setStatus] = useState6("idle");
1070
- const [tools, setTools] = useState6(void 0);
1071
- const [catalog, setCatalog] = useState6([]);
1072
- const [error, setError] = useState6(void 0);
1073
- const [authorizationUrl, setAuthorizationUrl] = useState6(void 0);
1074
- const [oauthSupported, setOauthSupported] = useState6(void 0);
1075
- const [completingAuthorization, setCompletingAuthorization] = useState6(
1076
- () => readCallbackParams() !== void 0
1077
- );
1078
- const connectionRef = useRef4(void 0);
1079
- const providerRef = useRef4(void 0);
1080
- const epochRef = useRef4(0);
1081
- const optionsRef = useRef4(options);
1082
- optionsRef.current = options;
1083
- const closeConnection = useCallback6(async () => {
1084
- const open = connectionRef.current;
1085
- connectionRef.current = void 0;
1086
- if (open) await open.close().catch(() => {
1087
- });
1088
- }, []);
1089
- const checkOAuthSupport = useCallback6(async () => {
1090
- try {
1091
- const mod = await loadMcp();
1092
- const supported = typeof mod.BrowserOAuthProvider === "function";
1093
- setOauthSupported(supported);
1094
- return supported;
1095
- } catch {
1096
- setOauthSupported(false);
1097
- return false;
1098
- }
1099
- }, []);
1100
- const connect = useCallback6(
1101
- async (opts) => {
1102
- const epoch = ++epochRef.current;
1103
- const current = () => epochRef.current === epoch;
1104
- await closeConnection();
1105
- if (!current()) return;
1106
- setStatus("connecting");
1107
- setError(void 0);
1108
- setAuthorizationUrl(void 0);
1109
- setTools(void 0);
1110
- setCatalog([]);
1111
- try {
1112
- const mod = await loadMcp();
1113
- setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
1114
- const name = opts.name ?? "mcp";
1115
- let authProvider;
1116
- if (opts.oauth) {
1117
- if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
1118
- const oauth = typeof opts.oauth === "object" ? opts.oauth : {};
1119
- const record = {
1120
- url: opts.url,
1121
- name,
1122
- redirectUrl: oauth.redirectUrl ?? defaultRedirectUrl(),
1123
- scope: oauth.scope,
1124
- clientName: oauth.clientName ?? optionsRef.current.clientName,
1125
- startedAt: Date.now()
1126
- };
1127
- authProvider = new mod.BrowserOAuthProvider({
1128
- serverUrl: record.url,
1129
- redirectUrl: record.redirectUrl,
1130
- clientName: record.clientName,
1131
- scope: record.scope
1132
- });
1133
- providerRef.current = authProvider;
1134
- writeRecord(PENDING_KEY, record);
1135
- writeRecord(OAUTH_KEY, record);
1136
- } else {
1137
- providerRef.current = void 0;
1138
- }
1139
- const connection = await mod.connectMcpHttp(
1140
- {
1141
- [name]: {
1142
- url: opts.url,
1143
- headers: opts.oauth ? void 0 : opts.headers,
1144
- authProvider
1145
- }
1146
- },
1147
- { clientName: optionsRef.current.clientName, onLog: optionsRef.current.onLog }
1148
- );
1149
- if (!current()) {
1150
- await connection.close().catch(() => {
1151
- });
1152
- return;
1153
- }
1154
- const outcome = describeMcpResult(connection.results[0]);
1155
- if (outcome.status !== "connected") {
1156
- await connection.close().catch(() => {
1157
- });
1158
- if (outcome.status === "needs-authorization") {
1159
- const url = authProvider?.authorizationUrl;
1160
- setAuthorizationUrl(url ? String(url) : void 0);
1161
- setStatus("needs-authorization");
1162
- return;
1163
- }
1164
- throw new Error(outcome.error);
1165
- }
1166
- connectionRef.current = connection;
1167
- writeRecord(PENDING_KEY, void 0);
1168
- setTools(
1169
- watchAuthorization(connection.tools, mod, () => {
1170
- if (!current()) return;
1171
- const url = providerRef.current?.authorizationUrl;
1172
- if (url) setAuthorizationUrl(String(url));
1173
- setStatus("needs-authorization");
1174
- })
1175
- );
1176
- setCatalog(connection.catalog);
1177
- setStatus("connected");
1178
- } catch (err) {
1179
- if (!current()) return;
1180
- setError(err instanceof Error ? err.message : String(err));
1181
- setStatus("error");
1182
- }
1183
- },
1184
- [closeConnection]
1185
- );
1186
- const disconnect = useCallback6(async () => {
1187
- epochRef.current++;
1188
- await closeConnection();
1189
- setTools(void 0);
1190
- setCatalog([]);
1191
- setAuthorizationUrl(void 0);
1192
- setError(void 0);
1193
- setStatus("idle");
1194
- }, [closeConnection]);
1195
- const authorize = useCallback6(() => {
1196
- if (authorizationUrl && typeof globalThis.location !== "undefined") {
1197
- globalThis.location.href = authorizationUrl;
1198
- }
1199
- }, [authorizationUrl]);
1200
- const forgetAuthorization = useCallback6(async () => {
1201
- const record = readRecord(OAUTH_KEY);
1202
- writeRecord(PENDING_KEY, void 0);
1203
- writeRecord(OAUTH_KEY, void 0);
1204
- let provider = providerRef.current;
1205
- if (!provider && record) {
1206
- const mod = await loadMcp().catch(() => void 0);
1207
- if (mod?.BrowserOAuthProvider) {
1208
- provider = new mod.BrowserOAuthProvider({
1209
- serverUrl: record.url,
1210
- redirectUrl: record.redirectUrl,
1211
- clientName: record.clientName,
1212
- scope: record.scope
1213
- });
1214
- }
1215
- }
1216
- await provider?.reset().catch(() => {
1217
- });
1218
- providerRef.current = void 0;
1219
- await disconnect();
1220
- }, [disconnect]);
1221
- useEffect5(() => {
1222
- const callback = readCallbackParams();
1223
- if (!callback) {
1224
- setCompletingAuthorization(false);
1225
- return;
1226
- }
1227
- const pending = readRecord(PENDING_KEY);
1228
- const fresh = pending !== void 0 && (pending.startedAt === void 0 || Date.now() - pending.startedAt < PENDING_TTL_MS);
1229
- if (!pending || !fresh) {
1230
- if (pending) writeRecord(PENDING_KEY, void 0);
1231
- setCompletingAuthorization(false);
1232
- return;
1233
- }
1234
- if (!claimOAuthCallback(callback)) {
1235
- setCompletingAuthorization(false);
1236
- return;
1237
- }
1238
- if (typeof globalThis.history !== "undefined") {
1239
- globalThis.history.replaceState(null, "", stripOAuthParams(globalThis.location.href));
1240
- }
1241
- void (async () => {
1242
- try {
1243
- const mod = await loadMcp();
1244
- setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
1245
- if (!mod.BrowserOAuthProvider || !mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED);
1246
- const provider = new mod.BrowserOAuthProvider({
1247
- serverUrl: pending.url,
1248
- redirectUrl: pending.redirectUrl ?? defaultRedirectUrl(),
1249
- clientName: pending.clientName,
1250
- scope: pending.scope
1251
- });
1252
- providerRef.current = provider;
1253
- await mod.finishMcpOAuth(provider, callback);
1254
- writeRecord(PENDING_KEY, void 0);
1255
- setCompletingAuthorization(false);
1256
- await connect({ url: pending.url, name: pending.name, oauth: true });
1257
- } catch (err) {
1258
- writeRecord(PENDING_KEY, void 0);
1259
- setError(err instanceof Error ? err.message : String(err));
1260
- setStatus("error");
1261
- } finally {
1262
- setCompletingAuthorization(false);
1263
- }
1264
- })();
1265
- }, [connect]);
1266
- useEffect5(
1267
- () => () => {
1268
- epochRef.current++;
1269
- void closeConnection();
1270
- },
1271
- [closeConnection]
1272
- );
1273
- return {
1274
- status,
1275
- tools,
1276
- catalog,
1277
- error,
1278
- authorizationUrl,
1279
- oauthSupported,
1280
- completingAuthorization,
1281
- connect,
1282
- disconnect,
1283
- authorize,
1284
- forgetAuthorization,
1285
- checkOAuthSupport
1286
- };
1287
- };
1288
-
1289
- // src/hooks/use-mcp-servers.ts
1290
- import { useCallback as useCallback7, useEffect as useEffect6, useMemo as useMemo3, useRef as useRef5, useState as useState7 } from "react";
1291
- var DEFAULT_KEY = "agent-web-react:mcp-servers";
1292
- var sanitize = (s) => s.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 32) || "mcp";
1293
- var view = (s, patch = {}) => ({
1294
- name: s.name,
1295
- url: s.url,
1296
- auth: s.auth,
1297
- status: "idle",
1298
- catalog: [],
1299
- ...patch
1300
- });
1301
- var useMcpServers = (options = {}) => {
1302
- const storageKey = options.storageKey ?? DEFAULT_KEY;
1303
- const pendingKey = `${storageKey}:pending`;
1304
- const persist = options.persist !== false;
1305
- const [servers, setServers] = useState7(
1306
- () => persist ? (readRecord(storageKey) ?? []).map((s) => view(s)) : []
1307
- );
1308
- const [oauthSupported, setOauthSupported] = useState7(void 0);
1309
- const [completingAuthorization, setCompleting] = useState7(
1310
- () => readCallbackParams() !== void 0 && readRecord(pendingKey) !== void 0
1311
- );
1312
- const [toolsVersion, setToolsVersion] = useState7(0);
1313
- const liveRef = useRef5(/* @__PURE__ */ new Map());
1314
- const specsRef = useRef5(/* @__PURE__ */ new Map());
1315
- if (specsRef.current.size === 0 && servers.length > 0) {
1316
- for (const s of servers)
1317
- specsRef.current.set(s.name, { name: s.name, url: s.url, auth: s.auth });
1318
- }
1319
- const optionsRef = useRef5(options);
1320
- optionsRef.current = options;
1321
- const unmountedRef = useRef5(false);
1322
- const saveList = useCallback7(() => {
1323
- if (!persist) return;
1324
- writeRecord(storageKey, [...specsRef.current.values()]);
1325
- }, [persist, storageKey]);
1326
- const patch = useCallback7((name, p) => {
1327
- if (unmountedRef.current) return;
1328
- setServers((list) => list.map((s) => s.name === name ? { ...s, ...p } : s));
1329
- }, []);
1330
- const live = (name) => {
1331
- let l = liveRef.current.get(name);
1332
- if (!l) {
1333
- l = { epoch: 0 };
1334
- liveRef.current.set(name, l);
1335
- }
1336
- return l;
1337
- };
1338
- const closeServer = useCallback7(async (name) => {
1339
- const l = liveRef.current.get(name);
1340
- if (!l) return;
1341
- l.epoch += 1;
1342
- const open = l.connection;
1343
- l.connection = void 0;
1344
- if (l.tools) {
1345
- l.tools = void 0;
1346
- setToolsVersion((v) => v + 1);
1347
- }
1348
- if (open) await open.close().catch(() => {
1349
- });
1350
- }, []);
1351
- const providerFor = (mod, spec) => {
1352
- if (!mod.BrowserOAuthProvider) throw new Error(OAUTH_UNSUPPORTED);
1353
- return new mod.BrowserOAuthProvider({
1354
- serverUrl: spec.url,
1355
- redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
1356
- clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
1357
- scope: spec.oauth?.scope
1358
- });
1359
- };
1360
- const connectServer = useCallback7(
1361
- async (name) => {
1362
- const spec = specsRef.current.get(name);
1363
- if (!spec) return;
1364
- await closeServer(name);
1365
- const l = live(name);
1366
- const epoch = ++l.epoch;
1367
- const current = () => !unmountedRef.current && l.epoch === epoch;
1368
- if (spec.auth === "bearer" && !l.token) {
1369
- patch(name, { status: "idle", error: "Enter the bearer token to connect." });
1370
- return;
1371
- }
1372
- patch(name, {
1373
- status: "connecting",
1374
- error: void 0,
1375
- authorizationUrl: void 0,
1376
- catalog: []
1377
- });
1378
- try {
1379
- const mod = await loadMcp();
1380
- setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
1381
- let provider;
1382
- if (spec.auth === "oauth") {
1383
- provider = providerFor(mod, spec);
1384
- l.provider = provider;
1385
- }
1386
- const connection = await mod.connectMcpHttp(
1387
- {
1388
- [name]: {
1389
- url: spec.url,
1390
- headers: spec.auth === "bearer" && l.token ? { Authorization: `Bearer ${l.token}` } : void 0,
1391
- authProvider: provider,
1392
- connectTimeoutMs: optionsRef.current.connectTimeoutMs
1393
- }
1394
- },
1395
- {
1396
- clientName: optionsRef.current.clientName,
1397
- onLog: optionsRef.current.onLog,
1398
- connectTimeoutMs: optionsRef.current.connectTimeoutMs
1399
- }
1400
- );
1401
- if (!current()) {
1402
- await connection.close().catch(() => {
1403
- });
1404
- return;
1405
- }
1406
- const outcome = describeMcpResult(connection.results[0]);
1407
- if (outcome.status !== "connected") {
1408
- await connection.close().catch(() => {
1409
- });
1410
- if (outcome.status === "needs-authorization") {
1411
- const url = provider?.authorizationUrl;
1412
- patch(name, {
1413
- status: "needs-authorization",
1414
- authorizationUrl: url ? String(url) : void 0
1415
- });
1416
- return;
1417
- }
1418
- throw new Error(outcome.error);
1419
- }
1420
- l.connection = connection;
1421
- l.tools = watchAuthorization(connection.tools, mod, () => {
1422
- if (!current()) return;
1423
- const url = l.provider?.authorizationUrl;
1424
- patch(name, {
1425
- status: "needs-authorization",
1426
- authorizationUrl: url ? String(url) : void 0
1427
- });
1428
- });
1429
- setToolsVersion((v) => v + 1);
1430
- patch(name, { status: "connected", catalog: connection.catalog });
1431
- } catch (err) {
1432
- if (!current()) return;
1433
- patch(name, { status: "error", error: err instanceof Error ? err.message : String(err) });
1434
- }
1435
- },
1436
- // eslint-disable-next-line react-hooks/exhaustive-deps
1437
- [closeServer, patch, pendingKey]
1438
- );
1439
- const add = useCallback7(
1440
- async (input) => {
1441
- let name = sanitize(input.name);
1442
- const taken = specsRef.current.get(name);
1443
- if (taken && taken.url !== input.url) {
1444
- let n = 2;
1445
- while (specsRef.current.has(`${name}_${n}`)) n += 1;
1446
- name = `${name}_${n}`;
1447
- }
1448
- const spec = {
1449
- name,
1450
- url: input.url,
1451
- auth: input.auth ?? "none",
1452
- ...input.oauth ? { oauth: input.oauth } : {}
1453
- };
1454
- specsRef.current.set(name, spec);
1455
- live(name).token = input.auth === "bearer" ? input.token : void 0;
1456
- setServers(
1457
- (list) => list.some((s) => s.name === name) ? list.map((s) => s.name === name ? view(spec) : s) : [...list, view(spec)]
1458
- );
1459
- saveList();
1460
- await connectServer(name);
1461
- return name;
1462
- },
1463
- [connectServer, saveList]
1464
- );
1465
- const remove = useCallback7(
1466
- async (name) => {
1467
- await closeServer(name);
1468
- liveRef.current.delete(name);
1469
- specsRef.current.delete(name);
1470
- saveList();
1471
- setServers((list) => list.filter((s) => s.name !== name));
1472
- },
1473
- [closeServer, saveList]
1474
- );
1475
- const reconnect = useCallback7(
1476
- async (name, token) => {
1477
- if (token !== void 0) live(name).token = token;
1478
- await connectServer(name);
1479
- },
1480
- [connectServer]
1481
- );
1482
- const authorize = useCallback7(
1483
- (name) => {
1484
- const url = servers.find((s) => s.name === name)?.authorizationUrl;
1485
- const spec = specsRef.current.get(name);
1486
- if (!url || !spec || typeof globalThis.location === "undefined") return;
1487
- const pending = {
1488
- name,
1489
- url: spec.url,
1490
- redirectUrl: spec.oauth?.redirectUrl ?? defaultRedirectUrl(),
1491
- scope: spec.oauth?.scope,
1492
- clientName: spec.oauth?.clientName ?? optionsRef.current.clientName,
1493
- startedAt: Date.now()
1494
- };
1495
- writeRecord(pendingKey, pending);
1496
- globalThis.location.href = url;
1497
- },
1498
- [servers, pendingKey]
1499
- );
1500
- const forgetAuthorization = useCallback7(
1501
- async (name) => {
1502
- const spec = specsRef.current.get(name);
1503
- const l = liveRef.current.get(name);
1504
- let provider = l?.provider;
1505
- if (!provider && spec?.auth === "oauth") {
1506
- const mod = await loadMcp().catch(() => void 0);
1507
- if (mod?.BrowserOAuthProvider) provider = providerFor(mod, spec);
1508
- }
1509
- await provider?.reset().catch(() => {
1510
- });
1511
- if (l) l.provider = void 0;
1512
- const pending = readRecord(pendingKey);
1513
- if (pending?.name === name) writeRecord(pendingKey, void 0);
1514
- await closeServer(name);
1515
- patch(name, { status: "idle", authorizationUrl: void 0, catalog: [], error: void 0 });
1516
- },
1517
- // eslint-disable-next-line react-hooks/exhaustive-deps
1518
- [closeServer, patch, pendingKey]
1519
- );
1520
- const checkOAuthSupport = useCallback7(async () => {
1521
- try {
1522
- const mod = await loadMcp();
1523
- const supported = typeof mod.BrowserOAuthProvider === "function";
1524
- setOauthSupported(supported);
1525
- return supported;
1526
- } catch {
1527
- setOauthSupported(false);
1528
- return false;
1529
- }
1530
- }, []);
1531
- useEffect6(() => {
1532
- unmountedRef.current = false;
1533
- const callback = readCallbackParams();
1534
- const pending = readRecord(pendingKey);
1535
- const fresh = pending !== void 0 && Date.now() - pending.startedAt < PENDING_TTL_MS;
1536
- const ours = Boolean(callback && pending && fresh && claimOAuthCallback(callback));
1537
- if (callback && pending && !fresh) writeRecord(pendingKey, void 0);
1538
- if (ours && typeof globalThis.history !== "undefined") {
1539
- globalThis.history.replaceState(null, "", stripOAuthParams(globalThis.location.href));
1540
- }
1541
- const autoConnect = optionsRef.current.autoConnect !== false;
1542
- void (async () => {
1543
- if (ours && pending && callback) {
1544
- try {
1545
- const mod = await loadMcp();
1546
- setOauthSupported(typeof mod.BrowserOAuthProvider === "function");
1547
- if (!mod.finishMcpOAuth) throw new Error(OAUTH_UNSUPPORTED);
1548
- const spec = specsRef.current.get(pending.name) ?? {
1549
- name: pending.name,
1550
- url: pending.url,
1551
- auth: "oauth"
1552
- };
1553
- if (!specsRef.current.has(spec.name)) {
1554
- specsRef.current.set(spec.name, spec);
1555
- setServers((list) => [...list, view(spec)]);
1556
- saveList();
1557
- }
1558
- const provider = providerFor(mod, {
1559
- ...spec,
1560
- oauth: {
1561
- redirectUrl: pending.redirectUrl,
1562
- scope: pending.scope,
1563
- clientName: pending.clientName
1564
- }
1565
- });
1566
- live(spec.name).provider = provider;
1567
- await mod.finishMcpOAuth(provider, callback);
1568
- writeRecord(pendingKey, void 0);
1569
- } catch (err) {
1570
- writeRecord(pendingKey, void 0);
1571
- patch(pending.name, {
1572
- status: "error",
1573
- error: err instanceof Error ? err.message : String(err)
1574
- });
1575
- }
1576
- }
1577
- setCompleting(false);
1578
- if (autoConnect || ours) {
1579
- await Promise.all(
1580
- [...specsRef.current.keys()].filter((name) => autoConnect || name === pending?.name).map((name) => connectServer(name))
1581
- );
1582
- }
1583
- })();
1584
- return () => {
1585
- unmountedRef.current = true;
1586
- for (const name of liveRef.current.keys()) void closeServer(name);
1587
- };
1588
- }, []);
1589
- const tools = useMemo3(() => {
1590
- const merged = {};
1591
- for (const l of liveRef.current.values()) if (l.tools) Object.assign(merged, l.tools);
1592
- return merged;
1593
- }, [toolsVersion]);
1594
- const catalog = useMemo3(
1595
- () => servers.filter((s) => s.status === "connected").flatMap((s) => s.catalog),
1596
- [servers]
1597
- );
1598
- return {
1599
- servers,
1600
- tools,
1601
- catalog,
1602
- connectedCount: servers.filter((s) => s.status === "connected").length,
1603
- completingAuthorization,
1604
- oauthSupported,
1605
- checkOAuthSupport,
1606
- add,
1607
- remove,
1608
- reconnect,
1609
- authorize,
1610
- forgetAuthorization
1611
- };
1612
- };
1613
-
1614
955
  // src/hooks/use-webllm-model.ts
1615
956
  import {
1616
957
  createWebLLMModel,
@@ -1621,21 +962,21 @@ import {
1621
962
  } from "@dudko.dev/agent-web";
1622
963
 
1623
964
  // src/hooks/use-local-model.ts
1624
- import { useCallback as useCallback8, useRef as useRef6, useState as useState8 } from "react";
965
+ import { useCallback as useCallback6, useRef as useRef4, useState as useState6 } from "react";
1625
966
  var keyOf = (id, tokens) => tokens ? `${id}@${tokens}` : id;
1626
967
  var useLocalModel = (modelId, engine, options) => {
1627
- const [loaded, setLoaded] = useState8(void 0);
1628
- const [pending, setPending] = useState8();
1629
- const [failure, setFailure] = useState8();
1630
- const engineRef = useRef6(engine);
968
+ const [loaded, setLoaded] = useState6(void 0);
969
+ const [pending, setPending] = useState6();
970
+ const [failure, setFailure] = useState6();
971
+ const engineRef = useRef4(engine);
1631
972
  engineRef.current = engine;
1632
- const loadedRef = useRef6(void 0);
1633
- const inflightRef = useRef6(
973
+ const loadedRef = useRef4(void 0);
974
+ const inflightRef = useRef4(
1634
975
  void 0
1635
976
  );
1636
977
  const windowTokens = options?.contextWindowTokens;
1637
978
  const key = keyOf(modelId, windowTokens);
1638
- const seqRef = useRef6(0);
979
+ const seqRef = useRef4(0);
1639
980
  const setHeld = (next) => {
1640
981
  loadedRef.current = next;
1641
982
  setLoaded(next);
@@ -1646,7 +987,7 @@ var useLocalModel = (modelId, engine, options) => {
1646
987
  } catch {
1647
988
  }
1648
989
  };
1649
- const load = useCallback8(() => {
990
+ const load = useCallback6(() => {
1650
991
  const id = modelId;
1651
992
  if (loadedRef.current?.key === key) return Promise.resolve(loadedRef.current.model);
1652
993
  if (inflightRef.current?.key === key) return inflightRef.current.promise;
@@ -1698,7 +1039,7 @@ var useLocalModel = (modelId, engine, options) => {
1698
1039
  inflightRef.current = { key, promise };
1699
1040
  return promise;
1700
1041
  }, [modelId, key]);
1701
- const unload = useCallback8(async () => {
1042
+ const unload = useCallback6(async () => {
1702
1043
  seqRef.current++;
1703
1044
  inflightRef.current = void 0;
1704
1045
  setPending(void 0);
@@ -1760,7 +1101,7 @@ var createWebLLMEngine = (options) => {
1760
1101
  };
1761
1102
 
1762
1103
  // src/labels.tsx
1763
- import { createContext, useContext, useMemo as useMemo4 } from "react";
1104
+ import { createContext, useContext, useMemo as useMemo3 } from "react";
1764
1105
 
1765
1106
  // src/composer.ts
1766
1107
  var parseSlash = (text) => {
@@ -1985,12 +1326,12 @@ var mergeLabels = (base2, over) => {
1985
1326
  var LabelsContext = createContext(defaultLabels);
1986
1327
  var AgentLabelsProvider = ({ labels, children }) => {
1987
1328
  const parent = useContext(LabelsContext);
1988
- const value = useMemo4(() => mergeLabels(parent, labels), [parent, labels]);
1329
+ const value = useMemo3(() => mergeLabels(parent, labels), [parent, labels]);
1989
1330
  return /* @__PURE__ */ jsx(LabelsContext.Provider, { value, children });
1990
1331
  };
1991
1332
  var useLabels = (over) => {
1992
1333
  const ctx = useContext(LabelsContext);
1993
- return useMemo4(() => mergeLabels(ctx, over), [ctx, over]);
1334
+ return useMemo3(() => mergeLabels(ctx, over), [ctx, over]);
1994
1335
  };
1995
1336
 
1996
1337
  // src/image-resize.ts
@@ -2058,10 +1399,10 @@ var useAgentContext = () => {
2058
1399
  var useOptionalAgentContext = () => useContext2(AgentContext);
2059
1400
 
2060
1401
  // src/components/AgentChat.tsx
2061
- import { useEffect as useEffect9, useRef as useRef9, useState as useState11 } from "react";
1402
+ import { useEffect as useEffect7, useRef as useRef7, useState as useState9 } from "react";
2062
1403
 
2063
1404
  // src/components/AgentComposer.tsx
2064
- import { useEffect as useEffect7, useLayoutEffect, useMemo as useMemo5, useRef as useRef7, useState as useState9 } from "react";
1405
+ import { useEffect as useEffect5, useLayoutEffect, useMemo as useMemo4, useRef as useRef5, useState as useState7 } from "react";
2065
1406
 
2066
1407
  // src/components/icons.tsx
2067
1408
  import { jsx as jsx3, jsxs } from "react/jsx-runtime";
@@ -2140,9 +1481,9 @@ var thinkingDefaults = (l) => [
2140
1481
  var MODES = ["autopilot", "ask-writes", "ask-all", "read-only"];
2141
1482
  var ModeIcon = ({ mode }) => mode === "autopilot" ? /* @__PURE__ */ jsx4(BoltIcon, { size: 14 }) : mode === "read-only" ? /* @__PURE__ */ jsx4(EyeIcon, { size: 14 }) : /* @__PURE__ */ jsx4(ShieldIcon, { size: 14 });
2142
1483
  var attachSeq = 0;
2143
- var useIsoLayoutEffect = typeof window === "undefined" ? useEffect7 : useLayoutEffect;
1484
+ var useIsoLayoutEffect = typeof window === "undefined" ? useEffect5 : useLayoutEffect;
2144
1485
  var useMenuPlacement = (open, anchor, align) => {
2145
- const [style, setStyle] = useState9();
1486
+ const [style, setStyle] = useState7();
2146
1487
  useIsoLayoutEffect(() => {
2147
1488
  if (!open) return;
2148
1489
  const place = () => {
@@ -2217,19 +1558,19 @@ var AgentComposer = ({
2217
1558
  const L = useLabels(labelsOverride);
2218
1559
  const MODE_CHIP = L.modes;
2219
1560
  const DEFAULT_THINKING = thinkingDefaults(L);
2220
- const [text, setText] = useState9("");
2221
- const [pending, setPending] = useState9([]);
2222
- const [menu, setMenu] = useState9(void 0);
2223
- const [active, setActive] = useState9(0);
2224
- const [dismissed, setDismissed] = useState9(() => /* @__PURE__ */ new Set());
2225
- const [attachError, setAttachError] = useState9();
2226
- const [dragging, setDragging] = useState9(false);
2227
- const rootRef = useRef7(null);
2228
- const modelRef = useRef7(null);
2229
- const modeRef = useRef7(null);
2230
- const [dropRect, setDropRect] = useState9();
2231
- const [compactBar, setCompactBar] = useState9(false);
2232
- useEffect7(() => {
1561
+ const [text, setText] = useState7("");
1562
+ const [pending, setPending] = useState7([]);
1563
+ const [menu, setMenu] = useState7(void 0);
1564
+ const [active, setActive] = useState7(0);
1565
+ const [dismissed, setDismissed] = useState7(() => /* @__PURE__ */ new Set());
1566
+ const [attachError, setAttachError] = useState7();
1567
+ const [dragging, setDragging] = useState7(false);
1568
+ const rootRef = useRef5(null);
1569
+ const modelRef = useRef5(null);
1570
+ const modeRef = useRef5(null);
1571
+ const [dropRect, setDropRect] = useState7();
1572
+ const [compactBar, setCompactBar] = useState7(false);
1573
+ useEffect5(() => {
2233
1574
  const el = rootRef.current;
2234
1575
  if (!el || typeof ResizeObserver === "undefined") return;
2235
1576
  const ro = new ResizeObserver(
@@ -2238,8 +1579,8 @@ var AgentComposer = ({
2238
1579
  ro.observe(el);
2239
1580
  return () => ro.disconnect();
2240
1581
  }, [compactWidth]);
2241
- const fileRef = useRef7(null);
2242
- const inputRef = useRef7(null);
1582
+ const fileRef = useRef5(null);
1583
+ const inputRef = useRef5(null);
2243
1584
  const busy = agent.isRunning;
2244
1585
  const ready = agent.isReady && !disabled;
2245
1586
  const caps = agent.agent?.capabilities;
@@ -2248,10 +1589,10 @@ var AgentComposer = ({
2248
1589
  onFinal: (heard) => setText((t) => t.trim() ? `${t.trimEnd()} ${heard}` : heard)
2249
1590
  });
2250
1591
  const showMic = speech !== false && stt.supported;
2251
- const [startedAt, setStartedAt] = useState9();
2252
- const [now, setNow] = useState9(() => Date.now());
2253
- const [lastElapsed, setLastElapsed] = useState9();
2254
- useEffect7(() => {
1592
+ const [startedAt, setStartedAt] = useState7();
1593
+ const [now, setNow] = useState7(() => Date.now());
1594
+ const [lastElapsed, setLastElapsed] = useState7();
1595
+ useEffect5(() => {
2255
1596
  if (!busy) {
2256
1597
  if (startedAt !== void 0) setLastElapsed(Date.now() - startedAt);
2257
1598
  setStartedAt(void 0);
@@ -2264,7 +1605,7 @@ var AgentComposer = ({
2264
1605
  return () => clearInterval(id);
2265
1606
  }, [busy]);
2266
1607
  const elapsed = startedAt !== void 0 ? now - startedAt : lastElapsed;
2267
- const allCommands = useMemo5(() => {
1608
+ const allCommands = useMemo4(() => {
2268
1609
  const out = [];
2269
1610
  if (builtinCommands) {
2270
1611
  out.push(
@@ -2344,8 +1685,8 @@ var AgentComposer = ({
2344
1685
  const commandsStyle = useMenuPlacement(paletteOpen, rootRef, "stretch");
2345
1686
  const modelStyle = useMenuPlacement(menu === "model", modelRef, "left");
2346
1687
  const modeStyle = useMenuPlacement(menu === "mode", modeRef, "right");
2347
- useEffect7(() => setActive(0), [text, menu]);
2348
- useEffect7(() => {
1688
+ useEffect5(() => setActive(0), [text, menu]);
1689
+ useEffect5(() => {
2349
1690
  if (!menu) return;
2350
1691
  const onDown = (e) => {
2351
1692
  if (!rootRef.current?.contains(e.target)) setMenu(void 0);
@@ -2438,9 +1779,9 @@ var AgentComposer = ({
2438
1779
  e.preventDefault();
2439
1780
  void addFiles(pasted);
2440
1781
  };
2441
- const addFilesRef = useRef7(addFiles);
1782
+ const addFilesRef = useRef5(addFiles);
2442
1783
  addFilesRef.current = addFiles;
2443
- useEffect7(() => {
1784
+ useEffect5(() => {
2444
1785
  if (attachments === false) return;
2445
1786
  const target = dropZone === "window" ? globalThis.window : dropZone === "self" ? rootRef.current : dropZone.current;
2446
1787
  if (!target) return;
@@ -3064,7 +2405,7 @@ var ContextMeter = ({
3064
2405
  };
3065
2406
 
3066
2407
  // src/components/FilesPanel.tsx
3067
- import { Fragment as Fragment3, useEffect as useEffect8, useRef as useRef8, useState as useState10 } from "react";
2408
+ import { Fragment as Fragment3, useEffect as useEffect6, useRef as useRef6, useState as useState8 } from "react";
3068
2409
  import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
3069
2410
  var PREVIEW_CHARS = 2e4;
3070
2411
  var FilesPanel = ({
@@ -3081,9 +2422,9 @@ var FilesPanel = ({
3081
2422
  }) => {
3082
2423
  const L = useLabels(labels);
3083
2424
  const fs = useVirtualFiles(vfs, prefix);
3084
- const [preview, setPreview] = useState10();
3085
- const inputRef = useRef8(null);
3086
- useEffect8(() => {
2425
+ const [preview, setPreview] = useState8();
2426
+ const inputRef = useRef6(null);
2427
+ useEffect6(() => {
3087
2428
  if (preview && !fs.files.some((f) => f.path === preview.path)) setPreview(void 0);
3088
2429
  }, [fs.files, preview]);
3089
2430
  const open = async (f) => {
@@ -3537,7 +2878,7 @@ var AgentChatInner = ({
3537
2878
  }
3538
2879
  const L = useLabels();
3539
2880
  const external = isHistoryHook(history) ? history : void 0;
3540
- const [ownStore] = useState11(
2881
+ const [ownStore] = useState9(
3541
2882
  () => history instanceof ChatHistoryStore ? history : new ChatHistoryStore()
3542
2883
  );
3543
2884
  const own = useChatHistory(agent, {
@@ -3545,9 +2886,9 @@ var AgentChatInner = ({
3545
2886
  enabled: Boolean(history) && !external
3546
2887
  });
3547
2888
  const chats = history ? external ?? own : void 0;
3548
- const rootRef = useRef9(null);
3549
- const [narrow, setNarrow] = useState11(void 0);
3550
- useEffect9(() => {
2889
+ const rootRef = useRef7(null);
2890
+ const [narrow, setNarrow] = useState9(void 0);
2891
+ useEffect7(() => {
3551
2892
  const el = rootRef.current;
3552
2893
  if (!el || typeof ResizeObserver === "undefined") return setNarrow(false);
3553
2894
  const measure = () => setNarrow(el.getBoundingClientRect().width < narrowWidth);
@@ -3556,9 +2897,9 @@ var AgentChatInner = ({
3556
2897
  ro.observe(el);
3557
2898
  return () => ro.disconnect();
3558
2899
  }, [narrowWidth]);
3559
- const [historyChoice, setHistoryOpen] = useState11(defaultHistoryOpen);
2900
+ const [historyChoice, setHistoryOpen] = useState9(defaultHistoryOpen);
3560
2901
  const historyOpen = historyChoice ?? narrow === false;
3561
- const [filesOpen, setFilesOpen] = useState11(defaultFilesOpen);
2902
+ const [filesOpen, setFilesOpen] = useState9(defaultFilesOpen);
3562
2903
  const toggleHistory = () => {
3563
2904
  setHistoryOpen(!historyOpen);
3564
2905
  if (narrow && !historyOpen) setFilesOpen(false);
@@ -3567,13 +2908,13 @@ var AgentChatInner = ({
3567
2908
  setFilesOpen((o) => !o);
3568
2909
  if (narrow && !filesOpen) setHistoryOpen(false);
3569
2910
  };
3570
- const bodyRef = useRef9(null);
3571
- const stickRef = useRef9(true);
3572
- useEffect9(() => {
2911
+ const bodyRef = useRef7(null);
2912
+ const stickRef = useRef7(true);
2913
+ useEffect7(() => {
3573
2914
  const el = bodyRef.current;
3574
2915
  if (el && stickRef.current) el.scrollTop = el.scrollHeight;
3575
2916
  }, [agent.messages, agent.steps, agent.finalText, agent.modelLoad, agent.pendingApprovals]);
3576
- const [compacting, setCompacting] = useState11(false);
2917
+ const [compacting, setCompacting] = useState9(false);
3577
2918
  const compact = () => {
3578
2919
  setCompacting(true);
3579
2920
  void agent.compact().finally(() => setCompacting(false));
@@ -3758,7 +3099,7 @@ var AgentChatInner = ({
3758
3099
  };
3759
3100
 
3760
3101
  // src/components/Composer.tsx
3761
- import { useState as useState12 } from "react";
3102
+ import { useState as useState10 } from "react";
3762
3103
  import { jsx as jsx13, jsxs as jsxs12 } from "react/jsx-runtime";
3763
3104
  var Composer = ({
3764
3105
  onSubmit,
@@ -3768,7 +3109,7 @@ var Composer = ({
3768
3109
  placeholder = "Ask the agent to do something\u2026",
3769
3110
  className
3770
3111
  }) => {
3771
- const [text, setText] = useState12("");
3112
+ const [text, setText] = useState10("");
3772
3113
  const submit = () => {
3773
3114
  const value = text.trim();
3774
3115
  if (!value || busy || disabled) return;
@@ -3881,7 +3222,7 @@ var ApprovalModeSwitch = ({
3881
3222
  );
3882
3223
 
3883
3224
  // src/components/ApiKeyForm.tsx
3884
- import { useEffect as useEffect10, useState as useState13 } from "react";
3225
+ import { useEffect as useEffect8, useState as useState11 } from "react";
3885
3226
  import { jsx as jsx16, jsxs as jsxs14 } from "react/jsx-runtime";
3886
3227
  var ApiKeyForm = ({
3887
3228
  credentials,
@@ -3891,10 +3232,10 @@ var ApiKeyForm = ({
3891
3232
  onChange,
3892
3233
  className
3893
3234
  }) => {
3894
- const [value, setValue] = useState13("");
3895
- const [present, setPresent] = useState13(false);
3896
- const [busy, setBusy] = useState13(false);
3897
- useEffect10(() => {
3235
+ const [value, setValue] = useState11("");
3236
+ const [present, setPresent] = useState11(false);
3237
+ const [busy, setBusy] = useState11(false);
3238
+ useEffect8(() => {
3898
3239
  let active = true;
3899
3240
  credentials.hasKey(credentialRef).then((has) => {
3900
3241
  if (active) setPresent(has);
@@ -4034,7 +3375,6 @@ export {
4034
3375
  attachmentKindOf,
4035
3376
  attachmentRefusal,
4036
3377
  chatTitle,
4037
- claimOAuthCallback,
4038
3378
  createAgent2 as createAgent,
4039
3379
  createFileTools,
4040
3380
  createInitialAgentState,
@@ -4044,11 +3384,9 @@ export {
4044
3384
  defaultLabels,
4045
3385
  defineSkill,
4046
3386
  defineTool,
4047
- describeMcpResult,
4048
3387
  downscaleImage,
4049
3388
  filterCommands,
4050
3389
  formatElapsed,
4051
- isUnauthorizedError,
4052
3390
  isWebGPUAvailable2 as isWebGPUAvailable,
4053
3391
  loadSkillFromUrl,
4054
3392
  markReadOnly,
@@ -4058,9 +3396,7 @@ export {
4058
3396
  parseSkillMarkdown,
4059
3397
  parseSlash,
4060
3398
  preloadWebLLMModel2 as preloadWebLLMModel,
4061
- readCallbackParams,
4062
3399
  serveSubagentWorker,
4063
- stripOAuthParams,
4064
3400
  supportsImages,
4065
3401
  supportsPdf,
4066
3402
  unloadWebLLMModel2 as unloadWebLLMModel,
@@ -4071,8 +3407,6 @@ export {
4071
3407
  useCredentials,
4072
3408
  useLabels,
4073
3409
  useLocalModel,
4074
- useMcp,
4075
- useMcpServers,
4076
3410
  useOptionalAgentContext,
4077
3411
  useSpeechToText,
4078
3412
  useVirtualFiles,