@dudko.dev/agent-web-ui 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +78 -6
  2. package/dist/{chunk-UNIXGP4N.js → chunk-627OXMFG.js} +2 -0
  3. package/dist/{chunk-G7LQTOA2.js → chunk-NHU6WQM5.js} +61 -6
  4. package/dist/controller.cjs +621 -20
  5. package/dist/controller.d.cts +110 -3
  6. package/dist/controller.d.ts +110 -3
  7. package/dist/controller.js +575 -17
  8. package/dist/index.cjs +81 -14
  9. package/dist/index.d.cts +28 -10
  10. package/dist/index.d.ts +28 -10
  11. package/dist/index.js +27 -8
  12. package/dist/{labels-DH1ESUtm.d.ts → labels-CCPL7t17.d.ts} +8 -1
  13. package/dist/{labels-CmiTBLWD.d.cts → labels-ipy-ydkp.d.cts} +8 -1
  14. package/dist/locales/be.cjs +2 -0
  15. package/dist/locales/be.js +1 -1
  16. package/dist/locales/bg.cjs +2 -0
  17. package/dist/locales/bg.js +1 -1
  18. package/dist/locales/ca.cjs +2 -0
  19. package/dist/locales/ca.js +1 -1
  20. package/dist/locales/cs.cjs +2 -0
  21. package/dist/locales/cs.js +1 -1
  22. package/dist/locales/da.cjs +2 -0
  23. package/dist/locales/da.js +1 -1
  24. package/dist/locales/de.cjs +2 -0
  25. package/dist/locales/de.js +1 -1
  26. package/dist/locales/el.cjs +2 -0
  27. package/dist/locales/el.js +1 -1
  28. package/dist/locales/en.cjs +2 -0
  29. package/dist/locales/en.js +1 -1
  30. package/dist/locales/es-419.cjs +2 -0
  31. package/dist/locales/es-419.js +1 -1
  32. package/dist/locales/es.cjs +2 -0
  33. package/dist/locales/es.js +1 -1
  34. package/dist/locales/fi.cjs +2 -0
  35. package/dist/locales/fi.js +1 -1
  36. package/dist/locales/fr-CA.cjs +2 -0
  37. package/dist/locales/fr-CA.js +1 -1
  38. package/dist/locales/fr.cjs +2 -0
  39. package/dist/locales/fr.js +1 -1
  40. package/dist/locales/gn.cjs +2 -0
  41. package/dist/locales/gn.js +1 -1
  42. package/dist/locales/hr.cjs +2 -0
  43. package/dist/locales/hr.js +1 -1
  44. package/dist/locales/ht.cjs +2 -0
  45. package/dist/locales/ht.js +1 -1
  46. package/dist/locales/hu.cjs +2 -0
  47. package/dist/locales/hu.js +1 -1
  48. package/dist/locales/index.cjs +2 -0
  49. package/dist/locales/index.js +1 -1
  50. package/dist/locales/it.cjs +2 -0
  51. package/dist/locales/it.js +1 -1
  52. package/dist/locales/nb.cjs +2 -0
  53. package/dist/locales/nb.js +1 -1
  54. package/dist/locales/nl.cjs +2 -0
  55. package/dist/locales/nl.js +1 -1
  56. package/dist/locales/pl.cjs +2 -0
  57. package/dist/locales/pl.js +1 -1
  58. package/dist/locales/pt-BR.cjs +2 -0
  59. package/dist/locales/pt-BR.js +1 -1
  60. package/dist/locales/pt.cjs +2 -0
  61. package/dist/locales/pt.js +1 -1
  62. package/dist/locales/qu.cjs +2 -0
  63. package/dist/locales/qu.js +1 -1
  64. package/dist/locales/ro.cjs +2 -0
  65. package/dist/locales/ro.js +1 -1
  66. package/dist/locales/ru.cjs +2 -0
  67. package/dist/locales/ru.js +1 -1
  68. package/dist/locales/sk.cjs +2 -0
  69. package/dist/locales/sk.js +1 -1
  70. package/dist/locales/sq.cjs +2 -0
  71. package/dist/locales/sq.js +1 -1
  72. package/dist/locales/sr-Latn.cjs +2 -0
  73. package/dist/locales/sr-Latn.js +1 -1
  74. package/dist/locales/sr.cjs +2 -0
  75. package/dist/locales/sr.js +1 -1
  76. package/dist/locales/sv.cjs +2 -0
  77. package/dist/locales/sv.js +1 -1
  78. package/dist/locales/tr.cjs +2 -0
  79. package/dist/locales/tr.js +1 -1
  80. package/dist/locales/uk.cjs +2 -0
  81. package/dist/locales/uk.js +1 -1
  82. package/dist/markdown.cjs +36 -0
  83. package/dist/markdown.d.cts +27 -1
  84. package/dist/markdown.d.ts +27 -1
  85. package/dist/markdown.js +33 -0
  86. package/dist/mcp-app.cjs +1 -4
  87. package/dist/mcp-app.js +1 -2
  88. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import {
2
+ agentCoreIfLoaded,
2
3
  agentStateReducer,
3
4
  agentStatusOf,
4
5
  askUserWith,
@@ -8,24 +9,563 @@ import {
8
9
  errMessage,
9
10
  followOtherTabs,
10
11
  lessonsOf,
12
+ loadAgentCore,
11
13
  pendingApprovalsOf,
12
14
  questionTimeoutOf,
13
15
  remoteAnswerOf
14
- } from "./chunk-G7LQTOA2.js";
16
+ } from "./chunk-NHU6WQM5.js";
17
+
18
+ // src/remote-controller.ts
19
+ var createSseParser = (onFrame, onRetry) => {
20
+ let buffer = "";
21
+ let data = [];
22
+ let id;
23
+ let sawCr = false;
24
+ const line = (text) => {
25
+ if (text === "") {
26
+ if (data.length > 0) onFrame({ ...id !== void 0 ? { id } : {}, data: data.join("\n") });
27
+ data = [];
28
+ id = void 0;
29
+ return;
30
+ }
31
+ if (text.startsWith(":")) return;
32
+ const colon = text.indexOf(":");
33
+ const field = colon < 0 ? text : text.slice(0, colon);
34
+ let value = colon < 0 ? "" : text.slice(colon + 1);
35
+ if (value.startsWith(" ")) value = value.slice(1);
36
+ if (field === "data") data.push(value);
37
+ else if (field === "id" && !value.includes("\0")) id = value;
38
+ else if (field === "retry" && /^\d+$/.test(value)) onRetry?.(Number(value));
39
+ };
40
+ return {
41
+ push: (chunk) => {
42
+ let text = buffer + chunk;
43
+ buffer = "";
44
+ if (sawCr && text.startsWith("\n")) text = text.slice(1);
45
+ sawCr = false;
46
+ let start = 0;
47
+ for (let i = 0; i < text.length; i += 1) {
48
+ const c = text[i];
49
+ if (c !== "\n" && c !== "\r") continue;
50
+ line(text.slice(start, i));
51
+ if (c === "\r") {
52
+ if (i + 1 === text.length) sawCr = true;
53
+ else if (text[i + 1] === "\n") i += 1;
54
+ }
55
+ start = i + 1;
56
+ }
57
+ buffer = text.slice(start);
58
+ }
59
+ };
60
+ };
61
+ var parseRemoteCursor = (raw) => {
62
+ const m = typeof raw === "string" ? /^(\d+):(\d+):(\d+)$/.exec(raw.trim()) : null;
63
+ return m ? { turn: Number(m[1]), attempt: Number(m[2]), seq: Number(m[3]) } : void 0;
64
+ };
65
+ var compareCursors = (a, b) => a.turn - b.turn || a.attempt - b.attempt || a.seq - b.seq;
66
+ var remoteEventScope = (event) => {
67
+ const step = event.step?.id;
68
+ if (event.type.startsWith("step.") && typeof step === "string") return `step:${step}`;
69
+ if (event.type === "final" || event.type.startsWith("final.")) return "final";
70
+ if (event.type.startsWith("plan.") || event.type === "replan.decision") return "plan";
71
+ return void 0;
72
+ };
73
+ var remoteEventOf = (event) => {
74
+ if (event.type === "error" && typeof event.error !== "string") {
75
+ const err = event.error;
76
+ return {
77
+ ...event,
78
+ error: typeof err?.message === "string" ? err.message : "error"
79
+ };
80
+ }
81
+ return event;
82
+ };
83
+ var emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, totalTokens: 0 });
84
+ var newMessageId = () => globalThis.crypto?.randomUUID?.() ?? `m-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
85
+ var GatewayError = class extends Error {
86
+ constructor(status, code, message) {
87
+ super(message);
88
+ this.status = status;
89
+ this.code = code;
90
+ this.name = "GatewayError";
91
+ }
92
+ status;
93
+ code;
94
+ };
95
+ var createInitialRemoteSnapshot = (options = {}) => snapshotOf({ ...createInitialAgentState(), status: "ready" }, options.sessionId ?? "", /* @__PURE__ */ new Set());
96
+ var snapshotOf = (state, sessionId, answering) => Object.freeze({
97
+ ...state,
98
+ isRunning: state.status === "running",
99
+ isReady: state.status === "ready",
100
+ // A request answered here waits for the stream to say so: not offered twice meanwhile.
101
+ pendingApprovals: state.approvals.filter(
102
+ (a) => a.status === "pending" && !a.remote && !answering.has(a.id)
103
+ ),
104
+ pendingQuestions: [],
105
+ // The server's policy decides; a view hides the switch for a remote agent.
106
+ approvalMode: "ask-writes",
107
+ sessionId
108
+ });
109
+ var createRemoteAgentController = (options) => {
110
+ const base = options.baseUrl.replace(/\/+$/, "");
111
+ const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
112
+ const minWait = Math.max(0, options.reconnect?.minMs ?? 1e3);
113
+ const maxWait = Math.max(minWait, options.reconnect?.maxMs ?? 3e4);
114
+ const maxEvents = options.maxEvents;
115
+ let disposed = false;
116
+ let sessionId = options.sessionId?.trim() || void 0;
117
+ let state = { ...createInitialAgentState(), status: "ready" };
118
+ let snapshot;
119
+ const listeners = /* @__PURE__ */ new Set();
120
+ const answering = /* @__PURE__ */ new Set();
121
+ const changed = () => {
122
+ snapshot = void 0;
123
+ for (const listener of [...listeners]) {
124
+ try {
125
+ listener();
126
+ } catch (err) {
127
+ queueMicrotask(() => {
128
+ throw err;
129
+ });
130
+ }
131
+ }
132
+ };
133
+ const apply = (action) => {
134
+ if (disposed) return;
135
+ const next = agentStateReducer(state, action);
136
+ if (next === state) return;
137
+ state = next;
138
+ changed();
139
+ };
140
+ let turn;
141
+ let turnIds = [];
142
+ let turnFinal = false;
143
+ let waiting = [];
144
+ const runs = /* @__PURE__ */ new Map();
145
+ const fold = (action, attempt = 0, scope) => {
146
+ if (turn) {
147
+ if (scope !== void 0 && turn.entries.some((e) => e.scope === scope && e.attempt < attempt)) {
148
+ turn.entries = turn.entries.filter((e) => !(e.scope === scope && e.attempt < attempt));
149
+ let s = turn.start;
150
+ for (const e of turn.entries) s = agentStateReducer(s, e.action);
151
+ state = s;
152
+ changed();
153
+ }
154
+ turn.entries.push({ action, attempt, ...scope !== void 0 ? { scope } : {} });
155
+ }
156
+ apply(action);
157
+ if (action.type === "event" && !disposed) tell(action.event);
158
+ };
159
+ const tell = (e) => {
160
+ try {
161
+ options.onEvent?.(e);
162
+ } catch {
163
+ }
164
+ };
165
+ const event = (e) => ({
166
+ type: "event",
167
+ event: e,
168
+ maxEvents,
169
+ at: Date.now()
170
+ });
171
+ const queueShown = () => {
172
+ for (const w of waiting) fold(event({ type: "message.queued", id: w.id, text: w.text }));
173
+ };
174
+ const endTurn = (body) => {
175
+ const status = body.status;
176
+ const text = typeof body.text === "string" ? body.text : "";
177
+ if (status === "completed") {
178
+ if (!turnFinal && text) fold(event({ type: "final", text }));
179
+ } else if (status === "stopped") {
180
+ fold(event({ type: "stopped" }));
181
+ } else if (status === "failed") {
182
+ const error = typeof body.error === "string" && body.error ? body.error : "the turn failed";
183
+ fold(event({ type: "error", phase: "run", error }));
184
+ }
185
+ const result = status === "failed" ? void 0 : {
186
+ runId: typeof body.runId === "string" ? body.runId : "",
187
+ goal: state.goal ?? "",
188
+ final: state.finalText || text,
189
+ plan: state.plan ?? { thought: "", steps: [] },
190
+ trace: [],
191
+ steps: state.steps.length,
192
+ applied: 0,
193
+ stopped: status === "stopped",
194
+ usage: body.usage ?? state.usage ?? emptyUsage(),
195
+ skills: []
196
+ };
197
+ for (const id of turnIds) {
198
+ const done = runs.get(id);
199
+ runs.delete(id);
200
+ done?.(result);
201
+ }
202
+ turn = void 0;
203
+ turnIds = [];
204
+ turnFinal = false;
205
+ answering.clear();
206
+ apply({ type: "status", status: waiting.length > 0 ? "running" : "ready" });
207
+ };
208
+ const onFrame = (frame) => {
209
+ let parsed;
210
+ try {
211
+ parsed = JSON.parse(frame.data);
212
+ } catch {
213
+ return;
214
+ }
215
+ const raw = parsed?.event;
216
+ if (!raw || typeof raw !== "object" || typeof raw.type !== "string") return;
217
+ const cursor2 = parseRemoteCursor(frame.id);
218
+ const attempt = cursor2?.attempt ?? 0;
219
+ const shown = remoteEventOf(raw);
220
+ if (raw.type === "turn.started") {
221
+ const ids = Array.isArray(raw.messageIds) ? raw.messageIds.filter((x) => typeof x === "string") : [];
222
+ waiting = waiting.filter((w) => !ids.includes(w.id));
223
+ turnIds = ids;
224
+ turnFinal = false;
225
+ apply({ type: "status", status: "running" });
226
+ turn = { number: cursor2?.turn ?? 0, start: state, entries: [] };
227
+ const goal = typeof raw.input === "string" ? raw.input : "";
228
+ fold(event({ type: "run.start", goal }));
229
+ queueShown();
230
+ } else if (raw.type === "turn.ended") {
231
+ endTurn(raw);
232
+ } else if (raw.type === "tool.approval-resolved" && raw.parked === true) {
233
+ } else {
234
+ if (raw.type === "tool.approval-resolved" && typeof raw.id === "string") {
235
+ answering.delete(raw.id);
236
+ }
237
+ if (raw.type === "final") turnFinal = true;
238
+ fold(event(shown), attempt, remoteEventScope(raw));
239
+ }
240
+ if (raw.type === "turn.started" || raw.type === "turn.ended") tell(shown);
241
+ };
242
+ const headersFor = async (extra) => {
243
+ const given = typeof options.headers === "function" ? await options.headers() : options.headers;
244
+ const headers = new Headers(given ?? {});
245
+ for (const [k, v] of Object.entries(extra)) headers.set(k, v);
246
+ return headers;
247
+ };
248
+ const request = async (path, init, signal) => {
249
+ const res = await doFetch(`${base}${path}`, {
250
+ method: init.method,
251
+ headers: await headersFor({
252
+ ...init.body !== void 0 ? { "content-type": "application/json" } : {},
253
+ ...init.headers
254
+ }),
255
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
256
+ credentials: options.credentials ?? "same-origin",
257
+ ...signal ? { signal } : {}
258
+ });
259
+ if (!res.ok) {
260
+ let code;
261
+ let message = `the agent's server answered ${res.status}`;
262
+ try {
263
+ const body = await res.json();
264
+ if (typeof body?.error?.code === "string") code = body.error.code;
265
+ if (typeof body?.error?.message === "string") message = body.error.message;
266
+ } catch {
267
+ }
268
+ throw new GatewayError(res.status, code, message);
269
+ }
270
+ return res;
271
+ };
272
+ const post = async (path, body) => {
273
+ const res = await request(path, { method: "POST", body });
274
+ try {
275
+ return await res.json();
276
+ } catch {
277
+ return void 0;
278
+ }
279
+ };
280
+ const sayError = (err) => fold(event({ type: "error", phase: "execute", error: errMessage(err) }));
281
+ let streamAbort;
282
+ let retryTimer;
283
+ let cursor;
284
+ let lastCursor;
285
+ let wait = minWait;
286
+ let serverRetry = 0;
287
+ let streamGeneration = 0;
288
+ const closeStream = () => {
289
+ streamGeneration += 1;
290
+ streamAbort?.abort();
291
+ streamAbort = void 0;
292
+ if (retryTimer !== void 0) clearTimeout(retryTimer);
293
+ retryTimer = void 0;
294
+ };
295
+ const scheduleReconnect = (generation) => {
296
+ if (disposed || generation !== streamGeneration || retryTimer !== void 0) return;
297
+ const delay = Math.min(maxWait, Math.max(wait, serverRetry));
298
+ wait = Math.min(maxWait, Math.max(minWait, wait * 2) || minWait);
299
+ retryTimer = setTimeout(() => {
300
+ retryTimer = void 0;
301
+ if (generation === streamGeneration) void openStream(generation);
302
+ }, delay);
303
+ };
304
+ const openStream = async (generation = streamGeneration) => {
305
+ const sid = sessionId;
306
+ if (disposed || !sid || generation !== streamGeneration || streamAbort) return;
307
+ const ac = new AbortController();
308
+ streamAbort = ac;
309
+ const decoder = new TextDecoder();
310
+ let cancelBody;
311
+ try {
312
+ const res = await request(
313
+ `/sessions/${encodeURIComponent(sid)}/events`,
314
+ {
315
+ method: "GET",
316
+ headers: { accept: "text/event-stream", ...cursor ? { "last-event-id": cursor } : {} }
317
+ },
318
+ ac.signal
319
+ );
320
+ const reader = res.body?.getReader();
321
+ if (!reader) throw new Error("the event stream has no body");
322
+ cancelBody = () => void reader.cancel().catch(() => {
323
+ });
324
+ if (ac.signal.aborted) cancelBody();
325
+ else ac.signal.addEventListener("abort", cancelBody, { once: true });
326
+ const parser = createSseParser(
327
+ (frame) => {
328
+ if (generation !== streamGeneration) return;
329
+ const at = parseRemoteCursor(frame.id);
330
+ if (at && lastCursor && compareCursors(at, lastCursor) <= 0) return;
331
+ if (at) lastCursor = at;
332
+ if (frame.id) cursor = frame.id;
333
+ wait = minWait;
334
+ onFrame(frame);
335
+ },
336
+ (ms) => {
337
+ serverRetry = ms;
338
+ }
339
+ );
340
+ for (; ; ) {
341
+ const { done, value } = await reader.read();
342
+ if (done || generation !== streamGeneration) break;
343
+ parser.push(decoder.decode(value, { stream: true }));
344
+ }
345
+ } catch (err) {
346
+ if (generation === streamGeneration && !disposed) {
347
+ if (err instanceof GatewayError && err.status === 404) {
348
+ forgetSession();
349
+ return;
350
+ }
351
+ if (err instanceof GatewayError && (err.status === 400 || err.status === 401 || err.status === 403)) {
352
+ sayError(err);
353
+ }
354
+ }
355
+ } finally {
356
+ if (cancelBody) ac.signal.removeEventListener("abort", cancelBody);
357
+ if (streamAbort === ac) streamAbort = void 0;
358
+ }
359
+ scheduleReconnect(generation);
360
+ };
361
+ const setSession = (next) => {
362
+ if (next === sessionId) return;
363
+ sessionId = next;
364
+ snapshot = void 0;
365
+ changed();
366
+ try {
367
+ options.onSessionId?.(next);
368
+ } catch {
369
+ }
370
+ };
371
+ const forgetSession = () => {
372
+ closeStream();
373
+ cursor = void 0;
374
+ lastCursor = void 0;
375
+ turn = void 0;
376
+ turnIds = [];
377
+ setSession(void 0);
378
+ };
379
+ const run = async (goal, runOptions) => {
380
+ if (disposed || state.status === "running") return void 0;
381
+ if (runOptions?.images?.length || runOptions?.files?.length) {
382
+ sayError(new Error("this agent takes text only: attachments are not sent"));
383
+ return void 0;
384
+ }
385
+ const text = goal.trim() ? goal : runOptions?.label ?? "";
386
+ if (!text.trim()) return void 0;
387
+ const id = newMessageId();
388
+ const shown = runOptions?.label?.trim() ? runOptions.label : text;
389
+ apply({ type: "status", status: "running" });
390
+ apply({ type: "submitted", goal: shown });
391
+ waiting.push({ id, text });
392
+ const ended = new Promise((resolve) => runs.set(id, resolve));
393
+ try {
394
+ await sendMessage(id, text);
395
+ } catch (err) {
396
+ runs.delete(id);
397
+ waiting = waiting.filter((w) => w.id !== id);
398
+ fold(event({ type: "stopped" }));
399
+ apply({ type: "status", status: "ready" });
400
+ apply({ type: "undelivered", texts: [...state.undelivered, text] });
401
+ sayError(err);
402
+ return void 0;
403
+ }
404
+ return ended;
405
+ };
406
+ const sendMessage = async (id, text) => {
407
+ const sid = sessionId;
408
+ if (sid) {
409
+ try {
410
+ await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id });
411
+ return;
412
+ } catch (err) {
413
+ const gone = err instanceof GatewayError && (err.status === 404 || err.status === 409 && err.code === "session_ended");
414
+ if (!gone || sessionId !== sid) throw err;
415
+ forgetSession();
416
+ }
417
+ }
418
+ const made = await post("/sessions", { message: text, id });
419
+ if (disposed) return;
420
+ if (typeof made?.sessionId !== "string")
421
+ throw new Error("the agent’s server started no session");
422
+ closeStream();
423
+ cursor = void 0;
424
+ lastCursor = void 0;
425
+ wait = minWait;
426
+ setSession(made.sessionId);
427
+ void openStream();
428
+ };
429
+ const send = (text) => {
430
+ const clean = typeof text === "string" ? text.trim() : "";
431
+ if (disposed || state.status !== "running" || !clean || !sessionId) return false;
432
+ const id = newMessageId();
433
+ waiting.push({ id, text: clean });
434
+ fold(event({ type: "message.queued", id, text: clean }));
435
+ void post(`/sessions/${encodeURIComponent(sessionId)}/messages`, { text: clean, id }).catch(
436
+ (err) => {
437
+ waiting = waiting.filter((w) => w.id !== id);
438
+ fold({ type: "undelivered", texts: [...state.undelivered, clean], keepQueued: true });
439
+ sayError(err);
440
+ }
441
+ );
442
+ return true;
443
+ };
444
+ const stop = () => {
445
+ if (disposed || !sessionId || state.status !== "running") return;
446
+ const sid = sessionId;
447
+ const left = waiting.map((w) => w.text);
448
+ waiting = [];
449
+ for (const [id, done] of runs) if (!turnIds.includes(id)) runs.delete(id), done(void 0);
450
+ if (left.length > 0) fold({ type: "undelivered", texts: [...state.undelivered, ...left] });
451
+ if (!turn) {
452
+ fold(event({ type: "stopped" }));
453
+ apply({ type: "status", status: "ready" });
454
+ }
455
+ void post(`/sessions/${encodeURIComponent(sid)}/stop`, {}).catch(sayError);
456
+ };
457
+ const answer = (id, body) => {
458
+ const sid = sessionId;
459
+ if (disposed || !sid || answering.has(id)) return;
460
+ if (!state.approvals.some((a) => a.id === id && a.status === "pending")) return;
461
+ answering.add(id);
462
+ changed();
463
+ void post(`/sessions/${encodeURIComponent(sid)}/answers/${encodeURIComponent(id)}`, body).catch(
464
+ (err) => {
465
+ if (err instanceof GatewayError && err.status === 409) return;
466
+ answering.delete(id);
467
+ changed();
468
+ sayError(err);
469
+ }
470
+ );
471
+ };
472
+ const approve = (id, _opts) => {
473
+ void _opts;
474
+ answer(id, { approved: true });
475
+ };
476
+ const deny = (id, reason) => answer(id, { approved: false, ...reason ? { reason: reason.slice(0, 2e3) } : {} });
477
+ const reset = () => {
478
+ if (disposed) return;
479
+ for (const [id, done] of runs) runs.delete(id), done(void 0);
480
+ waiting = [];
481
+ answering.clear();
482
+ forgetSession();
483
+ apply({ type: "reset" });
484
+ apply({ type: "status", status: "ready" });
485
+ };
486
+ const loadChat = (chat) => {
487
+ if (disposed) return;
488
+ const next = chat.sessionId?.trim();
489
+ if (!next || next === sessionId) return;
490
+ reset();
491
+ setSession(next);
492
+ void openStream();
493
+ };
494
+ const dispose = () => {
495
+ if (disposed) return;
496
+ disposed = true;
497
+ closeStream();
498
+ for (const [id, done] of runs) runs.delete(id), done(void 0);
499
+ listeners.clear();
500
+ };
501
+ if (sessionId) void openStream();
502
+ const notAvailable = (what) => async () => {
503
+ throw new Error(`${what} is not available for an agent on a server`);
504
+ };
505
+ return {
506
+ getSnapshot: () => snapshot ??= snapshotOf(state, sessionId ?? "", answering),
507
+ subscribe: (listener) => {
508
+ if (disposed) return () => {
509
+ };
510
+ listeners.add(listener);
511
+ return () => {
512
+ listeners.delete(listener);
513
+ };
514
+ },
515
+ // A server agent's configuration is the server's.
516
+ update: () => {
517
+ },
518
+ dispose,
519
+ get agent() {
520
+ return void 0;
521
+ },
522
+ get disposed() {
523
+ return disposed;
524
+ },
525
+ run,
526
+ stop,
527
+ stopRemote: () => {
528
+ },
529
+ send,
530
+ sendRemote: () => false,
531
+ stopSubagent: () => false,
532
+ forgetSkill: async () => false,
533
+ sendUndelivered: () => {
534
+ const texts = state.undelivered;
535
+ if (disposed || texts.length === 0 || state.status === "running") return;
536
+ apply({ type: "undelivered", texts: [] });
537
+ void run(texts.join("\n\n"));
538
+ },
539
+ discardUndelivered: () => apply({ type: "undelivered", texts: [] }),
540
+ reset,
541
+ // Opens the stream again at once (after the network came back, say).
542
+ reload: () => {
543
+ if (disposed || !sessionId) return;
544
+ if (retryTimer !== void 0) clearTimeout(retryTimer);
545
+ retryTimer = void 0;
546
+ wait = minWait;
547
+ void openStream();
548
+ },
549
+ approve,
550
+ deny,
551
+ answerQuestion: () => false,
552
+ setApprovalMode: () => {
553
+ },
554
+ approveAppToolCall: notAvailable("An app’s tool call"),
555
+ sampleForApp: notAvailable("An app’s sampling"),
556
+ compact: async () => void 0,
557
+ loadChat
558
+ };
559
+ };
15
560
 
16
561
  // src/controller.ts
17
- import * as core from "@dudko.dev/agent-web";
18
- import {
19
- createAgent,
20
- createRunControl
21
- } from "@dudko.dev/agent-web";
22
562
  var dbNameOf = (store) => {
23
563
  const name = store?.dbName;
24
564
  return typeof name === "string" && name ? name : void 0;
25
565
  };
26
566
  var modeOf = (config) => config.toolApproval?.mode ?? "autopilot";
27
567
  var pageAppToolGrants = /* @__PURE__ */ new Set();
28
- var snapshotOf = (state, extra) => {
568
+ var snapshotOf2 = (state, extra) => {
29
569
  const remoteRunning = state.remote?.running === true;
30
570
  return Object.freeze({
31
571
  ...state,
@@ -40,7 +580,7 @@ var snapshotOf = (state, extra) => {
40
580
  sessionId: extra.sessionId
41
581
  });
42
582
  };
43
- var createInitialAgentSnapshot = (config) => snapshotOf(createInitialAgentState(), {
583
+ var createInitialAgentSnapshot = (config) => snapshotOf2(createInitialAgentState(), {
44
584
  sessionId: config.sessionId ?? "default",
45
585
  pendingQuestions: [],
46
586
  approvalMode: modeOf(config)
@@ -128,7 +668,7 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
128
668
  cancelled = true;
129
669
  };
130
670
  setBuildStatus({ status: "initializing" });
131
- createAgent(built).then((next) => {
671
+ loadAgentCore().then((core) => core.createAgent(built)).then((next) => {
132
672
  if (cancelled) return;
133
673
  next.setToolApprovalMode(mode);
134
674
  agent = next;
@@ -149,11 +689,22 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
149
689
  const syncWatch = () => {
150
690
  const db = options.watch !== false && config.sessionLock !== "off" ? dbNameOf(config.memory) : void 0;
151
691
  if (watched && watched.db === db && watched.sessionId === sessionId) return;
692
+ const core = agentCoreIfLoaded();
693
+ if (db && !core) {
694
+ loadAgentCore().then(
695
+ () => {
696
+ if (!disposed) syncWatch();
697
+ },
698
+ () => {
699
+ }
700
+ );
701
+ return;
702
+ }
152
703
  closeWatch();
153
704
  watched = { db, sessionId };
154
- const watchSession2 = core.watchSession;
155
- if (!db || typeof watchSession2 !== "function") return;
156
- watch = watchSession2({
705
+ const watchSession = core?.watchSession;
706
+ if (!db || typeof watchSession !== "function") return;
707
+ watch = watchSession({
157
708
  dbName: db,
158
709
  sessionId,
159
710
  onEvent: (event) => {
@@ -187,7 +738,7 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
187
738
  unfollowSkills?.();
188
739
  skillsDb = { db };
189
740
  unfollowSkills = followOtherTabs(
190
- core,
741
+ loadAgentCore,
191
742
  db,
192
743
  (change) => change.kind === "skills",
193
744
  () => {
@@ -200,10 +751,11 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
200
751
  };
201
752
  const run = async (goal, runOptions) => {
202
753
  const current = agent;
203
- if (disposed || !current || abort) return void 0;
754
+ const core = agentCoreIfLoaded();
755
+ if (disposed || !current || abort || !core) return void 0;
204
756
  const controller = new AbortController();
205
757
  abort = controller;
206
- const runControl = createRunControl();
758
+ const runControl = core.createRunControl();
207
759
  control = runControl;
208
760
  let left = [];
209
761
  let stopped = false;
@@ -437,7 +989,7 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
437
989
  syncWatch();
438
990
  syncSkills();
439
991
  return {
440
- getSnapshot: () => snapshot ??= snapshotOf(state, { sessionId, pendingQuestions, approvalMode }),
992
+ getSnapshot: () => snapshot ??= snapshotOf2(state, { sessionId, pendingQuestions, approvalMode }),
441
993
  subscribe: (listener) => {
442
994
  if (disposed) return () => {
443
995
  };
@@ -477,5 +1029,11 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
477
1029
  };
478
1030
  export {
479
1031
  createAgentController,
480
- createInitialAgentSnapshot
1032
+ createInitialAgentSnapshot,
1033
+ createInitialRemoteSnapshot,
1034
+ createRemoteAgentController,
1035
+ createSseParser,
1036
+ parseRemoteCursor,
1037
+ remoteEventOf,
1038
+ remoteEventScope
481
1039
  };