@dudko.dev/agent-web-ui 0.0.3 → 0.0.4
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/README.md +55 -2
- package/dist/{chunk-UNIXGP4N.js → chunk-627OXMFG.js} +2 -0
- package/dist/controller.cjs +560 -5
- package/dist/controller.d.cts +110 -3
- package/dist/controller.d.ts +110 -3
- package/dist/controller.js +555 -4
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -0
- package/dist/{labels-DH1ESUtm.d.ts → labels-BJMtk5Fw.d.ts} +2 -0
- package/dist/{labels-CmiTBLWD.d.cts → labels-B_y8F1GW.d.cts} +2 -0
- package/dist/locales/be.cjs +2 -0
- package/dist/locales/be.js +1 -1
- package/dist/locales/bg.cjs +2 -0
- package/dist/locales/bg.js +1 -1
- package/dist/locales/ca.cjs +2 -0
- package/dist/locales/ca.js +1 -1
- package/dist/locales/cs.cjs +2 -0
- package/dist/locales/cs.js +1 -1
- package/dist/locales/da.cjs +2 -0
- package/dist/locales/da.js +1 -1
- package/dist/locales/de.cjs +2 -0
- package/dist/locales/de.js +1 -1
- package/dist/locales/el.cjs +2 -0
- package/dist/locales/el.js +1 -1
- package/dist/locales/en.cjs +2 -0
- package/dist/locales/en.js +1 -1
- package/dist/locales/es-419.cjs +2 -0
- package/dist/locales/es-419.js +1 -1
- package/dist/locales/es.cjs +2 -0
- package/dist/locales/es.js +1 -1
- package/dist/locales/fi.cjs +2 -0
- package/dist/locales/fi.js +1 -1
- package/dist/locales/fr-CA.cjs +2 -0
- package/dist/locales/fr-CA.js +1 -1
- package/dist/locales/fr.cjs +2 -0
- package/dist/locales/fr.js +1 -1
- package/dist/locales/gn.cjs +2 -0
- package/dist/locales/gn.js +1 -1
- package/dist/locales/hr.cjs +2 -0
- package/dist/locales/hr.js +1 -1
- package/dist/locales/ht.cjs +2 -0
- package/dist/locales/ht.js +1 -1
- package/dist/locales/hu.cjs +2 -0
- package/dist/locales/hu.js +1 -1
- package/dist/locales/index.cjs +2 -0
- package/dist/locales/index.js +1 -1
- package/dist/locales/it.cjs +2 -0
- package/dist/locales/it.js +1 -1
- package/dist/locales/nb.cjs +2 -0
- package/dist/locales/nb.js +1 -1
- package/dist/locales/nl.cjs +2 -0
- package/dist/locales/nl.js +1 -1
- package/dist/locales/pl.cjs +2 -0
- package/dist/locales/pl.js +1 -1
- package/dist/locales/pt-BR.cjs +2 -0
- package/dist/locales/pt-BR.js +1 -1
- package/dist/locales/pt.cjs +2 -0
- package/dist/locales/pt.js +1 -1
- package/dist/locales/qu.cjs +2 -0
- package/dist/locales/qu.js +1 -1
- package/dist/locales/ro.cjs +2 -0
- package/dist/locales/ro.js +1 -1
- package/dist/locales/ru.cjs +2 -0
- package/dist/locales/ru.js +1 -1
- package/dist/locales/sk.cjs +2 -0
- package/dist/locales/sk.js +1 -1
- package/dist/locales/sq.cjs +2 -0
- package/dist/locales/sq.js +1 -1
- package/dist/locales/sr-Latn.cjs +2 -0
- package/dist/locales/sr-Latn.js +1 -1
- package/dist/locales/sr.cjs +2 -0
- package/dist/locales/sr.js +1 -1
- package/dist/locales/sv.cjs +2 -0
- package/dist/locales/sv.js +1 -1
- package/dist/locales/tr.cjs +2 -0
- package/dist/locales/tr.js +1 -1
- package/dist/locales/uk.cjs +2 -0
- package/dist/locales/uk.js +1 -1
- package/dist/markdown.cjs +36 -0
- package/dist/markdown.d.cts +27 -1
- package/dist/markdown.d.ts +27 -1
- package/dist/markdown.js +33 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -76,8 +76,8 @@ not install this package itself: `@dudko.dev/agent-web-react` depends on it.
|
|
|
76
76
|
| `@dudko.dev/agent-web-ui/mcp-app-sandbox` | the MCP Apps sandbox page for a SERVER (a Worker, Node, Deno, Bun): the page, its headers, a `Request` → `Response` handler | nothing |
|
|
77
77
|
| `@dudko.dev/agent-web-ui/pipeline` | the pipeline editor's logic: the reducer of a pipeline run, the editing helpers, the code generator, the editor's strings | the core |
|
|
78
78
|
| `@dudko.dev/agent-web-ui/canvas` | the generic canvas's maths (viewport, curves, hit tests, layout order) and its strings | nothing |
|
|
79
|
-
| `@dudko.dev/agent-web-ui/controller` | the agent as a store any front end wraps: `createAgentController` (see [Controller](#controller)) | the core (its `createAgent`) |
|
|
80
|
-
| `@dudko.dev/agent-web-ui/markdown` | the answers' Markdown as a tree any front end draws: the parser, the parser of an answer still being written, `safeHref`, the renderer's helpers (see [Markdown](#markdown)) | nothing |
|
|
79
|
+
| `@dudko.dev/agent-web-ui/controller` | the agent as a store any front end wraps: `createAgentController`, and `createRemoteAgentController` for an agent on a server (see [Controller](#controller)) | the core (its `createAgent`) |
|
|
80
|
+
| `@dudko.dev/agent-web-ui/markdown` | the answers' Markdown as a tree any front end draws: the parser, the parser of an answer still being written, `safeHref`, the link allowlist, the renderer's helpers (see [Markdown](#markdown)) | nothing |
|
|
81
81
|
| `@dudko.dev/agent-web-ui/locales` | the chat's labels in your language, loaded on demand: `loadAgentLabels(tag)`, the list of tags, `labelsFromCatalog` | nothing |
|
|
82
82
|
| `@dudko.dev/agent-web-ui/locales/<tag>` | one language's labels (`labels`) and its catalog (`catalog`) | nothing |
|
|
83
83
|
| `@dudko.dev/agent-web-ui/styles.css` | the chat's stylesheet | - |
|
|
@@ -191,6 +191,53 @@ allow.onclick = () => chat.approve(chat.getSnapshot().pendingApprovals[0].id)
|
|
|
191
191
|
// when the view goes away: off(); chat.dispose()
|
|
192
192
|
```
|
|
193
193
|
|
|
194
|
+
### An agent on a server
|
|
195
|
+
|
|
196
|
+
`createRemoteAgentController(options)` is the same store for an agent that runs on a SERVER - the
|
|
197
|
+
swarm's gateway (`examples/swarm*` in the repository: Temporal + Postgres, Cloudflare, Google
|
|
198
|
+
Cloud, AWS - one HTTP API). The same snapshot and the same methods, so any view of the controller
|
|
199
|
+
draws it unchanged; nothing of the agent is in the page (no model, no key, no tool).
|
|
200
|
+
|
|
201
|
+
```js
|
|
202
|
+
import { createRemoteAgentController } from '@dudko.dev/agent-web-ui/controller'
|
|
203
|
+
|
|
204
|
+
const chat = createRemoteAgentController({
|
|
205
|
+
baseUrl: 'https://support.example.com/agent',
|
|
206
|
+
headers: async () => ({ authorization: `Bearer ${await visitorToken()}` }), // or credentials: 'include'
|
|
207
|
+
sessionId: sessionStorage.getItem('chat') ?? undefined,
|
|
208
|
+
onSessionId: (id) => (id ? sessionStorage.setItem('chat', id) : sessionStorage.removeItem('chat')),
|
|
209
|
+
})
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
- `run(text)` - the first message `POST /sessions`, the next ones `POST /sessions/:id/messages`
|
|
213
|
+
(each with an id: a retried POST is harmless); shown at once, its turn takes its place. Resolves
|
|
214
|
+
with the turn's result, `undefined` when it failed (the error said, the words back in
|
|
215
|
+
`undelivered`). Text only: images or files are refused in words.
|
|
216
|
+
- The turn streams in from `GET /sessions/:id/events` (SSE read through `fetch`, so `headers` can
|
|
217
|
+
carry a token), folded by the same reducer - the server's agent emits the core's events, the
|
|
218
|
+
swarm's `turn.started` / `turn.ended` frame each turn. A dropped stream is opened again with
|
|
219
|
+
`Last-Event-ID` after `reconnect.minMs` (default 1 s, or the gateway's `retry:`), doubled up to
|
|
220
|
+
`reconnect.maxMs` (30 s); a frame resets it. A later attempt's copy of a step, the answer or the
|
|
221
|
+
plan replaces the earlier one (`remoteEventScope`): delivery is at-least-once.
|
|
222
|
+
- `sessionId` - a session to continue: its stream is replayed, the transcript comes back. 404:
|
|
223
|
+
forgotten; 409 `session_ended`: the next message starts a new one. `onSessionId` is told every
|
|
224
|
+
change.
|
|
225
|
+
- `pendingApprovals` - a call the server's policy asks about parks the turn; `approve(id)` /
|
|
226
|
+
`deny(id, reason)` post `{ approved }` to `POST /sessions/:id/answers/:requestId` (no
|
|
227
|
+
`remember`: every call is decided on its own on a server). `stop()` is
|
|
228
|
+
`POST /sessions/:id/stop`. `send(text)` while a turn runs posts a message that waits in `queued`
|
|
229
|
+
for its own turn.
|
|
230
|
+
- Not available, answered as before an agent exists: `agent` (`undefined`), `answerQuestion`,
|
|
231
|
+
`stopSubagent`, `sendRemote`, `forgetSkill` (`false`), `compact` (`undefined`),
|
|
232
|
+
`approveAppToolCall` / `sampleForApp` (throw), `setApprovalMode`, `stopRemote`, `update` (do
|
|
233
|
+
nothing). `reset()` forgets the session; `loadChat({ sessionId })` opens another; `reload()` opens
|
|
234
|
+
the stream again now. `dispose()` closes the stream and clears the reconnect timer.
|
|
235
|
+
- `createInitialRemoteSnapshot({ sessionId })` is its snapshot before one exists. `createSseParser`,
|
|
236
|
+
`parseRemoteCursor`, `remoteEventScope` and `remoteEventOf` are its pure parts.
|
|
237
|
+
|
|
238
|
+
The React package's `useRemoteAgent` / `<RemoteAgentProvider>` and the element's `backend`
|
|
239
|
+
attribute are this controller.
|
|
240
|
+
|
|
194
241
|
## Labels
|
|
195
242
|
|
|
196
243
|
`defaultLabels` is every string the chat shows; counted phrases are functions so that languages
|
|
@@ -240,6 +287,12 @@ It is a security boundary for a host - the text is the model's:
|
|
|
240
287
|
are refused; a whole code span that is one carries `path`. A renderer draws it as a control that
|
|
241
288
|
opens the file in the page, never as `<a href>`. A link's words hold no link of their own.
|
|
242
289
|
- **No picture** is loaded from an answer: `` is its `!` and a link (or a file link).
|
|
290
|
+
- **A link allowlist**, for a chat that should link only to its own sites (opt-in, a renderer's
|
|
291
|
+
`linkAllowed`): `linkHostAllowed(href, hosts)` / `linkPolicyOf(hosts)` - each entry `host` or
|
|
292
|
+
`host/path`; `http(s)` only, the host exactly (no subdomain, no look-alike), no user, password or
|
|
293
|
+
port, a path entry a prefix by whole segments after the URL parser's normalisation.
|
|
294
|
+
`parseLinkHosts(attribute)` reads a list separated by blanks or commas; a malformed entry empties
|
|
295
|
+
it (no link kept - never every link).
|
|
243
296
|
- **Linear on any text**: one pass for code spans, lookups for brackets and destinations, one
|
|
244
297
|
opener stack per kind of emphasis, list nesting bounded - long runs of `*`, `_`, `[`, backticks,
|
|
245
298
|
`>`, `|` or ever-deeper lists cost what plain text does (`tests/markdown.test.ts` times them).
|
|
@@ -55,6 +55,8 @@ var labelsFromCatalog = (tag, catalog) => {
|
|
|
55
55
|
planned: t("planned"),
|
|
56
56
|
replanned: (_mode, reason) => t("replanned", { reason }),
|
|
57
57
|
placeholder: t("placeholder"),
|
|
58
|
+
// The catalogs' placeholder names no attachment: the same words for a text-only box.
|
|
59
|
+
placeholderTextOnly: t("placeholder"),
|
|
58
60
|
placeholderBusy: t("placeholderBusy"),
|
|
59
61
|
message: t("message"),
|
|
60
62
|
commands: t("commands"),
|
package/dist/controller.cjs
CHANGED
|
@@ -31,7 +31,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var controller_exports = {};
|
|
32
32
|
__export(controller_exports, {
|
|
33
33
|
createAgentController: () => createAgentController,
|
|
34
|
-
createInitialAgentSnapshot: () => createInitialAgentSnapshot
|
|
34
|
+
createInitialAgentSnapshot: () => createInitialAgentSnapshot,
|
|
35
|
+
createInitialRemoteSnapshot: () => createInitialRemoteSnapshot,
|
|
36
|
+
createRemoteAgentController: () => createRemoteAgentController,
|
|
37
|
+
createSseParser: () => createSseParser,
|
|
38
|
+
parseRemoteCursor: () => parseRemoteCursor,
|
|
39
|
+
remoteEventOf: () => remoteEventOf,
|
|
40
|
+
remoteEventScope: () => remoteEventScope
|
|
35
41
|
});
|
|
36
42
|
module.exports = __toCommonJS(controller_exports);
|
|
37
43
|
var core = __toESM(require("@dudko.dev/agent-web"), 1);
|
|
@@ -1426,6 +1432,549 @@ var followOtherTabs = (core2, dbName, accept, settle, ms = 100) => {
|
|
|
1426
1432
|
};
|
|
1427
1433
|
var remoteAnswerOf = (ok, stillWatching) => ok ? "taken" : stillWatching ? "refused" : "unknown";
|
|
1428
1434
|
|
|
1435
|
+
// src/remote-controller.ts
|
|
1436
|
+
var createSseParser = (onFrame, onRetry) => {
|
|
1437
|
+
let buffer = "";
|
|
1438
|
+
let data = [];
|
|
1439
|
+
let id;
|
|
1440
|
+
let sawCr = false;
|
|
1441
|
+
const line = (text) => {
|
|
1442
|
+
if (text === "") {
|
|
1443
|
+
if (data.length > 0) onFrame({ ...id !== void 0 ? { id } : {}, data: data.join("\n") });
|
|
1444
|
+
data = [];
|
|
1445
|
+
id = void 0;
|
|
1446
|
+
return;
|
|
1447
|
+
}
|
|
1448
|
+
if (text.startsWith(":")) return;
|
|
1449
|
+
const colon = text.indexOf(":");
|
|
1450
|
+
const field = colon < 0 ? text : text.slice(0, colon);
|
|
1451
|
+
let value = colon < 0 ? "" : text.slice(colon + 1);
|
|
1452
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
1453
|
+
if (field === "data") data.push(value);
|
|
1454
|
+
else if (field === "id" && !value.includes("\0")) id = value;
|
|
1455
|
+
else if (field === "retry" && /^\d+$/.test(value)) onRetry?.(Number(value));
|
|
1456
|
+
};
|
|
1457
|
+
return {
|
|
1458
|
+
push: (chunk) => {
|
|
1459
|
+
let text = buffer + chunk;
|
|
1460
|
+
buffer = "";
|
|
1461
|
+
if (sawCr && text.startsWith("\n")) text = text.slice(1);
|
|
1462
|
+
sawCr = false;
|
|
1463
|
+
let start = 0;
|
|
1464
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
1465
|
+
const c = text[i];
|
|
1466
|
+
if (c !== "\n" && c !== "\r") continue;
|
|
1467
|
+
line(text.slice(start, i));
|
|
1468
|
+
if (c === "\r") {
|
|
1469
|
+
if (i + 1 === text.length) sawCr = true;
|
|
1470
|
+
else if (text[i + 1] === "\n") i += 1;
|
|
1471
|
+
}
|
|
1472
|
+
start = i + 1;
|
|
1473
|
+
}
|
|
1474
|
+
buffer = text.slice(start);
|
|
1475
|
+
}
|
|
1476
|
+
};
|
|
1477
|
+
};
|
|
1478
|
+
var parseRemoteCursor = (raw) => {
|
|
1479
|
+
const m = typeof raw === "string" ? /^(\d+):(\d+):(\d+)$/.exec(raw.trim()) : null;
|
|
1480
|
+
return m ? { turn: Number(m[1]), attempt: Number(m[2]), seq: Number(m[3]) } : void 0;
|
|
1481
|
+
};
|
|
1482
|
+
var compareCursors = (a, b) => a.turn - b.turn || a.attempt - b.attempt || a.seq - b.seq;
|
|
1483
|
+
var remoteEventScope = (event) => {
|
|
1484
|
+
const step = event.step?.id;
|
|
1485
|
+
if (event.type.startsWith("step.") && typeof step === "string") return `step:${step}`;
|
|
1486
|
+
if (event.type === "final" || event.type.startsWith("final.")) return "final";
|
|
1487
|
+
if (event.type.startsWith("plan.") || event.type === "replan.decision") return "plan";
|
|
1488
|
+
return void 0;
|
|
1489
|
+
};
|
|
1490
|
+
var remoteEventOf = (event) => {
|
|
1491
|
+
if (event.type === "error" && typeof event.error !== "string") {
|
|
1492
|
+
const err = event.error;
|
|
1493
|
+
return {
|
|
1494
|
+
...event,
|
|
1495
|
+
error: typeof err?.message === "string" ? err.message : "error"
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
return event;
|
|
1499
|
+
};
|
|
1500
|
+
var emptyUsage2 = () => ({ inputTokens: 0, outputTokens: 0, totalTokens: 0 });
|
|
1501
|
+
var newMessageId = () => globalThis.crypto?.randomUUID?.() ?? `m-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
1502
|
+
var GatewayError = class extends Error {
|
|
1503
|
+
constructor(status, code, message) {
|
|
1504
|
+
super(message);
|
|
1505
|
+
this.status = status;
|
|
1506
|
+
this.code = code;
|
|
1507
|
+
this.name = "GatewayError";
|
|
1508
|
+
}
|
|
1509
|
+
status;
|
|
1510
|
+
code;
|
|
1511
|
+
};
|
|
1512
|
+
var createInitialRemoteSnapshot = (options = {}) => snapshotOf({ ...createInitialAgentState(), status: "ready" }, options.sessionId ?? "", /* @__PURE__ */ new Set());
|
|
1513
|
+
var snapshotOf = (state, sessionId, answering) => Object.freeze({
|
|
1514
|
+
...state,
|
|
1515
|
+
isRunning: state.status === "running",
|
|
1516
|
+
isReady: state.status === "ready",
|
|
1517
|
+
// A request answered here waits for the stream to say so: not offered twice meanwhile.
|
|
1518
|
+
pendingApprovals: state.approvals.filter(
|
|
1519
|
+
(a) => a.status === "pending" && !a.remote && !answering.has(a.id)
|
|
1520
|
+
),
|
|
1521
|
+
pendingQuestions: [],
|
|
1522
|
+
// The server's policy decides; a view hides the switch for a remote agent.
|
|
1523
|
+
approvalMode: "ask-writes",
|
|
1524
|
+
sessionId
|
|
1525
|
+
});
|
|
1526
|
+
var createRemoteAgentController = (options) => {
|
|
1527
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
1528
|
+
const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
|
|
1529
|
+
const minWait = Math.max(0, options.reconnect?.minMs ?? 1e3);
|
|
1530
|
+
const maxWait = Math.max(minWait, options.reconnect?.maxMs ?? 3e4);
|
|
1531
|
+
const maxEvents = options.maxEvents;
|
|
1532
|
+
let disposed = false;
|
|
1533
|
+
let sessionId = options.sessionId?.trim() || void 0;
|
|
1534
|
+
let state = { ...createInitialAgentState(), status: "ready" };
|
|
1535
|
+
let snapshot;
|
|
1536
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1537
|
+
const answering = /* @__PURE__ */ new Set();
|
|
1538
|
+
const changed = () => {
|
|
1539
|
+
snapshot = void 0;
|
|
1540
|
+
for (const listener of [...listeners]) {
|
|
1541
|
+
try {
|
|
1542
|
+
listener();
|
|
1543
|
+
} catch (err) {
|
|
1544
|
+
queueMicrotask(() => {
|
|
1545
|
+
throw err;
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
};
|
|
1550
|
+
const apply = (action) => {
|
|
1551
|
+
if (disposed) return;
|
|
1552
|
+
const next = agentStateReducer(state, action);
|
|
1553
|
+
if (next === state) return;
|
|
1554
|
+
state = next;
|
|
1555
|
+
changed();
|
|
1556
|
+
};
|
|
1557
|
+
let turn;
|
|
1558
|
+
let turnIds = [];
|
|
1559
|
+
let turnFinal = false;
|
|
1560
|
+
let waiting = [];
|
|
1561
|
+
const runs = /* @__PURE__ */ new Map();
|
|
1562
|
+
const fold = (action, attempt = 0, scope) => {
|
|
1563
|
+
if (turn) {
|
|
1564
|
+
if (scope !== void 0 && turn.entries.some((e) => e.scope === scope && e.attempt < attempt)) {
|
|
1565
|
+
turn.entries = turn.entries.filter((e) => !(e.scope === scope && e.attempt < attempt));
|
|
1566
|
+
let s = turn.start;
|
|
1567
|
+
for (const e of turn.entries) s = agentStateReducer(s, e.action);
|
|
1568
|
+
state = s;
|
|
1569
|
+
changed();
|
|
1570
|
+
}
|
|
1571
|
+
turn.entries.push({ action, attempt, ...scope !== void 0 ? { scope } : {} });
|
|
1572
|
+
}
|
|
1573
|
+
apply(action);
|
|
1574
|
+
if (action.type === "event" && !disposed) tell(action.event);
|
|
1575
|
+
};
|
|
1576
|
+
const tell = (e) => {
|
|
1577
|
+
try {
|
|
1578
|
+
options.onEvent?.(e);
|
|
1579
|
+
} catch {
|
|
1580
|
+
}
|
|
1581
|
+
};
|
|
1582
|
+
const event = (e) => ({
|
|
1583
|
+
type: "event",
|
|
1584
|
+
event: e,
|
|
1585
|
+
maxEvents,
|
|
1586
|
+
at: Date.now()
|
|
1587
|
+
});
|
|
1588
|
+
const queueShown = () => {
|
|
1589
|
+
for (const w of waiting) fold(event({ type: "message.queued", id: w.id, text: w.text }));
|
|
1590
|
+
};
|
|
1591
|
+
const endTurn = (body) => {
|
|
1592
|
+
const status = body.status;
|
|
1593
|
+
const text = typeof body.text === "string" ? body.text : "";
|
|
1594
|
+
if (status === "completed") {
|
|
1595
|
+
if (!turnFinal && text) fold(event({ type: "final", text }));
|
|
1596
|
+
} else if (status === "stopped") {
|
|
1597
|
+
fold(event({ type: "stopped" }));
|
|
1598
|
+
} else if (status === "failed") {
|
|
1599
|
+
const error = typeof body.error === "string" && body.error ? body.error : "the turn failed";
|
|
1600
|
+
fold(event({ type: "error", phase: "run", error }));
|
|
1601
|
+
}
|
|
1602
|
+
const result = status === "failed" ? void 0 : {
|
|
1603
|
+
runId: typeof body.runId === "string" ? body.runId : "",
|
|
1604
|
+
goal: state.goal ?? "",
|
|
1605
|
+
final: state.finalText || text,
|
|
1606
|
+
plan: state.plan ?? { thought: "", steps: [] },
|
|
1607
|
+
trace: [],
|
|
1608
|
+
steps: state.steps.length,
|
|
1609
|
+
applied: 0,
|
|
1610
|
+
stopped: status === "stopped",
|
|
1611
|
+
usage: body.usage ?? state.usage ?? emptyUsage2(),
|
|
1612
|
+
skills: []
|
|
1613
|
+
};
|
|
1614
|
+
for (const id of turnIds) {
|
|
1615
|
+
const done = runs.get(id);
|
|
1616
|
+
runs.delete(id);
|
|
1617
|
+
done?.(result);
|
|
1618
|
+
}
|
|
1619
|
+
turn = void 0;
|
|
1620
|
+
turnIds = [];
|
|
1621
|
+
turnFinal = false;
|
|
1622
|
+
answering.clear();
|
|
1623
|
+
apply({ type: "status", status: waiting.length > 0 ? "running" : "ready" });
|
|
1624
|
+
};
|
|
1625
|
+
const onFrame = (frame) => {
|
|
1626
|
+
let parsed;
|
|
1627
|
+
try {
|
|
1628
|
+
parsed = JSON.parse(frame.data);
|
|
1629
|
+
} catch {
|
|
1630
|
+
return;
|
|
1631
|
+
}
|
|
1632
|
+
const raw = parsed?.event;
|
|
1633
|
+
if (!raw || typeof raw !== "object" || typeof raw.type !== "string") return;
|
|
1634
|
+
const cursor2 = parseRemoteCursor(frame.id);
|
|
1635
|
+
const attempt = cursor2?.attempt ?? 0;
|
|
1636
|
+
const shown = remoteEventOf(raw);
|
|
1637
|
+
if (raw.type === "turn.started") {
|
|
1638
|
+
const ids = Array.isArray(raw.messageIds) ? raw.messageIds.filter((x) => typeof x === "string") : [];
|
|
1639
|
+
waiting = waiting.filter((w) => !ids.includes(w.id));
|
|
1640
|
+
turnIds = ids;
|
|
1641
|
+
turnFinal = false;
|
|
1642
|
+
apply({ type: "status", status: "running" });
|
|
1643
|
+
turn = { number: cursor2?.turn ?? 0, start: state, entries: [] };
|
|
1644
|
+
const goal = typeof raw.input === "string" ? raw.input : "";
|
|
1645
|
+
fold(event({ type: "run.start", goal }));
|
|
1646
|
+
queueShown();
|
|
1647
|
+
} else if (raw.type === "turn.ended") {
|
|
1648
|
+
endTurn(raw);
|
|
1649
|
+
} else if (raw.type === "tool.approval-resolved" && raw.parked === true) {
|
|
1650
|
+
} else {
|
|
1651
|
+
if (raw.type === "tool.approval-resolved" && typeof raw.id === "string") {
|
|
1652
|
+
answering.delete(raw.id);
|
|
1653
|
+
}
|
|
1654
|
+
if (raw.type === "final") turnFinal = true;
|
|
1655
|
+
fold(event(shown), attempt, remoteEventScope(raw));
|
|
1656
|
+
}
|
|
1657
|
+
if (raw.type === "turn.started" || raw.type === "turn.ended") tell(shown);
|
|
1658
|
+
};
|
|
1659
|
+
const headersFor = async (extra) => {
|
|
1660
|
+
const given = typeof options.headers === "function" ? await options.headers() : options.headers;
|
|
1661
|
+
const headers = new Headers(given ?? {});
|
|
1662
|
+
for (const [k, v] of Object.entries(extra)) headers.set(k, v);
|
|
1663
|
+
return headers;
|
|
1664
|
+
};
|
|
1665
|
+
const request = async (path, init, signal) => {
|
|
1666
|
+
const res = await doFetch(`${base}${path}`, {
|
|
1667
|
+
method: init.method,
|
|
1668
|
+
headers: await headersFor({
|
|
1669
|
+
...init.body !== void 0 ? { "content-type": "application/json" } : {},
|
|
1670
|
+
...init.headers
|
|
1671
|
+
}),
|
|
1672
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
1673
|
+
credentials: options.credentials ?? "same-origin",
|
|
1674
|
+
...signal ? { signal } : {}
|
|
1675
|
+
});
|
|
1676
|
+
if (!res.ok) {
|
|
1677
|
+
let code;
|
|
1678
|
+
let message = `the agent's server answered ${res.status}`;
|
|
1679
|
+
try {
|
|
1680
|
+
const body = await res.json();
|
|
1681
|
+
if (typeof body?.error?.code === "string") code = body.error.code;
|
|
1682
|
+
if (typeof body?.error?.message === "string") message = body.error.message;
|
|
1683
|
+
} catch {
|
|
1684
|
+
}
|
|
1685
|
+
throw new GatewayError(res.status, code, message);
|
|
1686
|
+
}
|
|
1687
|
+
return res;
|
|
1688
|
+
};
|
|
1689
|
+
const post = async (path, body) => {
|
|
1690
|
+
const res = await request(path, { method: "POST", body });
|
|
1691
|
+
try {
|
|
1692
|
+
return await res.json();
|
|
1693
|
+
} catch {
|
|
1694
|
+
return void 0;
|
|
1695
|
+
}
|
|
1696
|
+
};
|
|
1697
|
+
const sayError = (err) => fold(event({ type: "error", phase: "execute", error: errMessage(err) }));
|
|
1698
|
+
let streamAbort;
|
|
1699
|
+
let retryTimer;
|
|
1700
|
+
let cursor;
|
|
1701
|
+
let lastCursor;
|
|
1702
|
+
let wait = minWait;
|
|
1703
|
+
let serverRetry = 0;
|
|
1704
|
+
let streamGeneration = 0;
|
|
1705
|
+
const closeStream = () => {
|
|
1706
|
+
streamGeneration += 1;
|
|
1707
|
+
streamAbort?.abort();
|
|
1708
|
+
streamAbort = void 0;
|
|
1709
|
+
if (retryTimer !== void 0) clearTimeout(retryTimer);
|
|
1710
|
+
retryTimer = void 0;
|
|
1711
|
+
};
|
|
1712
|
+
const scheduleReconnect = (generation) => {
|
|
1713
|
+
if (disposed || generation !== streamGeneration || retryTimer !== void 0) return;
|
|
1714
|
+
const delay = Math.min(maxWait, Math.max(wait, serverRetry));
|
|
1715
|
+
wait = Math.min(maxWait, Math.max(minWait, wait * 2) || minWait);
|
|
1716
|
+
retryTimer = setTimeout(() => {
|
|
1717
|
+
retryTimer = void 0;
|
|
1718
|
+
if (generation === streamGeneration) void openStream(generation);
|
|
1719
|
+
}, delay);
|
|
1720
|
+
};
|
|
1721
|
+
const openStream = async (generation = streamGeneration) => {
|
|
1722
|
+
const sid = sessionId;
|
|
1723
|
+
if (disposed || !sid || generation !== streamGeneration || streamAbort) return;
|
|
1724
|
+
const ac = new AbortController();
|
|
1725
|
+
streamAbort = ac;
|
|
1726
|
+
const decoder = new TextDecoder();
|
|
1727
|
+
let cancelBody;
|
|
1728
|
+
try {
|
|
1729
|
+
const res = await request(
|
|
1730
|
+
`/sessions/${encodeURIComponent(sid)}/events`,
|
|
1731
|
+
{
|
|
1732
|
+
method: "GET",
|
|
1733
|
+
headers: { accept: "text/event-stream", ...cursor ? { "last-event-id": cursor } : {} }
|
|
1734
|
+
},
|
|
1735
|
+
ac.signal
|
|
1736
|
+
);
|
|
1737
|
+
const reader = res.body?.getReader();
|
|
1738
|
+
if (!reader) throw new Error("the event stream has no body");
|
|
1739
|
+
cancelBody = () => void reader.cancel().catch(() => {
|
|
1740
|
+
});
|
|
1741
|
+
if (ac.signal.aborted) cancelBody();
|
|
1742
|
+
else ac.signal.addEventListener("abort", cancelBody, { once: true });
|
|
1743
|
+
const parser = createSseParser(
|
|
1744
|
+
(frame) => {
|
|
1745
|
+
if (generation !== streamGeneration) return;
|
|
1746
|
+
const at = parseRemoteCursor(frame.id);
|
|
1747
|
+
if (at && lastCursor && compareCursors(at, lastCursor) <= 0) return;
|
|
1748
|
+
if (at) lastCursor = at;
|
|
1749
|
+
if (frame.id) cursor = frame.id;
|
|
1750
|
+
wait = minWait;
|
|
1751
|
+
onFrame(frame);
|
|
1752
|
+
},
|
|
1753
|
+
(ms) => {
|
|
1754
|
+
serverRetry = ms;
|
|
1755
|
+
}
|
|
1756
|
+
);
|
|
1757
|
+
for (; ; ) {
|
|
1758
|
+
const { done, value } = await reader.read();
|
|
1759
|
+
if (done || generation !== streamGeneration) break;
|
|
1760
|
+
parser.push(decoder.decode(value, { stream: true }));
|
|
1761
|
+
}
|
|
1762
|
+
} catch (err) {
|
|
1763
|
+
if (generation === streamGeneration && !disposed) {
|
|
1764
|
+
if (err instanceof GatewayError && err.status === 404) {
|
|
1765
|
+
forgetSession();
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
if (err instanceof GatewayError && (err.status === 400 || err.status === 401 || err.status === 403)) {
|
|
1769
|
+
sayError(err);
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
} finally {
|
|
1773
|
+
if (cancelBody) ac.signal.removeEventListener("abort", cancelBody);
|
|
1774
|
+
if (streamAbort === ac) streamAbort = void 0;
|
|
1775
|
+
}
|
|
1776
|
+
scheduleReconnect(generation);
|
|
1777
|
+
};
|
|
1778
|
+
const setSession = (next) => {
|
|
1779
|
+
if (next === sessionId) return;
|
|
1780
|
+
sessionId = next;
|
|
1781
|
+
snapshot = void 0;
|
|
1782
|
+
changed();
|
|
1783
|
+
try {
|
|
1784
|
+
options.onSessionId?.(next);
|
|
1785
|
+
} catch {
|
|
1786
|
+
}
|
|
1787
|
+
};
|
|
1788
|
+
const forgetSession = () => {
|
|
1789
|
+
closeStream();
|
|
1790
|
+
cursor = void 0;
|
|
1791
|
+
lastCursor = void 0;
|
|
1792
|
+
turn = void 0;
|
|
1793
|
+
turnIds = [];
|
|
1794
|
+
setSession(void 0);
|
|
1795
|
+
};
|
|
1796
|
+
const run = async (goal, runOptions) => {
|
|
1797
|
+
if (disposed || state.status === "running") return void 0;
|
|
1798
|
+
if (runOptions?.images?.length || runOptions?.files?.length) {
|
|
1799
|
+
sayError(new Error("this agent takes text only: attachments are not sent"));
|
|
1800
|
+
return void 0;
|
|
1801
|
+
}
|
|
1802
|
+
const text = goal.trim() ? goal : runOptions?.label ?? "";
|
|
1803
|
+
if (!text.trim()) return void 0;
|
|
1804
|
+
const id = newMessageId();
|
|
1805
|
+
const shown = runOptions?.label?.trim() ? runOptions.label : text;
|
|
1806
|
+
apply({ type: "status", status: "running" });
|
|
1807
|
+
apply({ type: "submitted", goal: shown });
|
|
1808
|
+
waiting.push({ id, text });
|
|
1809
|
+
const ended = new Promise((resolve) => runs.set(id, resolve));
|
|
1810
|
+
try {
|
|
1811
|
+
await sendMessage(id, text);
|
|
1812
|
+
} catch (err) {
|
|
1813
|
+
runs.delete(id);
|
|
1814
|
+
waiting = waiting.filter((w) => w.id !== id);
|
|
1815
|
+
fold(event({ type: "stopped" }));
|
|
1816
|
+
apply({ type: "status", status: "ready" });
|
|
1817
|
+
apply({ type: "undelivered", texts: [...state.undelivered, text] });
|
|
1818
|
+
sayError(err);
|
|
1819
|
+
return void 0;
|
|
1820
|
+
}
|
|
1821
|
+
return ended;
|
|
1822
|
+
};
|
|
1823
|
+
const sendMessage = async (id, text) => {
|
|
1824
|
+
const sid = sessionId;
|
|
1825
|
+
if (sid) {
|
|
1826
|
+
try {
|
|
1827
|
+
await post(`/sessions/${encodeURIComponent(sid)}/messages`, { text, id });
|
|
1828
|
+
return;
|
|
1829
|
+
} catch (err) {
|
|
1830
|
+
const gone = err instanceof GatewayError && (err.status === 404 || err.status === 409 && err.code === "session_ended");
|
|
1831
|
+
if (!gone || sessionId !== sid) throw err;
|
|
1832
|
+
forgetSession();
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
const made = await post("/sessions", { message: text, id });
|
|
1836
|
+
if (disposed) return;
|
|
1837
|
+
if (typeof made?.sessionId !== "string")
|
|
1838
|
+
throw new Error("the agent’s server started no session");
|
|
1839
|
+
closeStream();
|
|
1840
|
+
cursor = void 0;
|
|
1841
|
+
lastCursor = void 0;
|
|
1842
|
+
wait = minWait;
|
|
1843
|
+
setSession(made.sessionId);
|
|
1844
|
+
void openStream();
|
|
1845
|
+
};
|
|
1846
|
+
const send = (text) => {
|
|
1847
|
+
const clean = typeof text === "string" ? text.trim() : "";
|
|
1848
|
+
if (disposed || state.status !== "running" || !clean || !sessionId) return false;
|
|
1849
|
+
const id = newMessageId();
|
|
1850
|
+
waiting.push({ id, text: clean });
|
|
1851
|
+
fold(event({ type: "message.queued", id, text: clean }));
|
|
1852
|
+
void post(`/sessions/${encodeURIComponent(sessionId)}/messages`, { text: clean, id }).catch(
|
|
1853
|
+
(err) => {
|
|
1854
|
+
waiting = waiting.filter((w) => w.id !== id);
|
|
1855
|
+
fold({ type: "undelivered", texts: [...state.undelivered, clean], keepQueued: true });
|
|
1856
|
+
sayError(err);
|
|
1857
|
+
}
|
|
1858
|
+
);
|
|
1859
|
+
return true;
|
|
1860
|
+
};
|
|
1861
|
+
const stop = () => {
|
|
1862
|
+
if (disposed || !sessionId || state.status !== "running") return;
|
|
1863
|
+
const sid = sessionId;
|
|
1864
|
+
const left = waiting.map((w) => w.text);
|
|
1865
|
+
waiting = [];
|
|
1866
|
+
for (const [id, done] of runs) if (!turnIds.includes(id)) runs.delete(id), done(void 0);
|
|
1867
|
+
if (left.length > 0) fold({ type: "undelivered", texts: [...state.undelivered, ...left] });
|
|
1868
|
+
if (!turn) {
|
|
1869
|
+
fold(event({ type: "stopped" }));
|
|
1870
|
+
apply({ type: "status", status: "ready" });
|
|
1871
|
+
}
|
|
1872
|
+
void post(`/sessions/${encodeURIComponent(sid)}/stop`, {}).catch(sayError);
|
|
1873
|
+
};
|
|
1874
|
+
const answer = (id, body) => {
|
|
1875
|
+
const sid = sessionId;
|
|
1876
|
+
if (disposed || !sid || answering.has(id)) return;
|
|
1877
|
+
if (!state.approvals.some((a) => a.id === id && a.status === "pending")) return;
|
|
1878
|
+
answering.add(id);
|
|
1879
|
+
changed();
|
|
1880
|
+
void post(`/sessions/${encodeURIComponent(sid)}/answers/${encodeURIComponent(id)}`, body).catch(
|
|
1881
|
+
(err) => {
|
|
1882
|
+
if (err instanceof GatewayError && err.status === 409) return;
|
|
1883
|
+
answering.delete(id);
|
|
1884
|
+
changed();
|
|
1885
|
+
sayError(err);
|
|
1886
|
+
}
|
|
1887
|
+
);
|
|
1888
|
+
};
|
|
1889
|
+
const approve = (id, _opts) => {
|
|
1890
|
+
void _opts;
|
|
1891
|
+
answer(id, { approved: true });
|
|
1892
|
+
};
|
|
1893
|
+
const deny = (id, reason) => answer(id, { approved: false, ...reason ? { reason: reason.slice(0, 2e3) } : {} });
|
|
1894
|
+
const reset = () => {
|
|
1895
|
+
if (disposed) return;
|
|
1896
|
+
for (const [id, done] of runs) runs.delete(id), done(void 0);
|
|
1897
|
+
waiting = [];
|
|
1898
|
+
answering.clear();
|
|
1899
|
+
forgetSession();
|
|
1900
|
+
apply({ type: "reset" });
|
|
1901
|
+
apply({ type: "status", status: "ready" });
|
|
1902
|
+
};
|
|
1903
|
+
const loadChat = (chat) => {
|
|
1904
|
+
if (disposed) return;
|
|
1905
|
+
const next = chat.sessionId?.trim();
|
|
1906
|
+
if (!next || next === sessionId) return;
|
|
1907
|
+
reset();
|
|
1908
|
+
setSession(next);
|
|
1909
|
+
void openStream();
|
|
1910
|
+
};
|
|
1911
|
+
const dispose = () => {
|
|
1912
|
+
if (disposed) return;
|
|
1913
|
+
disposed = true;
|
|
1914
|
+
closeStream();
|
|
1915
|
+
for (const [id, done] of runs) runs.delete(id), done(void 0);
|
|
1916
|
+
listeners.clear();
|
|
1917
|
+
};
|
|
1918
|
+
if (sessionId) void openStream();
|
|
1919
|
+
const notAvailable = (what) => async () => {
|
|
1920
|
+
throw new Error(`${what} is not available for an agent on a server`);
|
|
1921
|
+
};
|
|
1922
|
+
return {
|
|
1923
|
+
getSnapshot: () => snapshot ??= snapshotOf(state, sessionId ?? "", answering),
|
|
1924
|
+
subscribe: (listener) => {
|
|
1925
|
+
if (disposed) return () => {
|
|
1926
|
+
};
|
|
1927
|
+
listeners.add(listener);
|
|
1928
|
+
return () => {
|
|
1929
|
+
listeners.delete(listener);
|
|
1930
|
+
};
|
|
1931
|
+
},
|
|
1932
|
+
// A server agent's configuration is the server's.
|
|
1933
|
+
update: () => {
|
|
1934
|
+
},
|
|
1935
|
+
dispose,
|
|
1936
|
+
get agent() {
|
|
1937
|
+
return void 0;
|
|
1938
|
+
},
|
|
1939
|
+
get disposed() {
|
|
1940
|
+
return disposed;
|
|
1941
|
+
},
|
|
1942
|
+
run,
|
|
1943
|
+
stop,
|
|
1944
|
+
stopRemote: () => {
|
|
1945
|
+
},
|
|
1946
|
+
send,
|
|
1947
|
+
sendRemote: () => false,
|
|
1948
|
+
stopSubagent: () => false,
|
|
1949
|
+
forgetSkill: async () => false,
|
|
1950
|
+
sendUndelivered: () => {
|
|
1951
|
+
const texts = state.undelivered;
|
|
1952
|
+
if (disposed || texts.length === 0 || state.status === "running") return;
|
|
1953
|
+
apply({ type: "undelivered", texts: [] });
|
|
1954
|
+
void run(texts.join("\n\n"));
|
|
1955
|
+
},
|
|
1956
|
+
discardUndelivered: () => apply({ type: "undelivered", texts: [] }),
|
|
1957
|
+
reset,
|
|
1958
|
+
// Opens the stream again at once (after the network came back, say).
|
|
1959
|
+
reload: () => {
|
|
1960
|
+
if (disposed || !sessionId) return;
|
|
1961
|
+
if (retryTimer !== void 0) clearTimeout(retryTimer);
|
|
1962
|
+
retryTimer = void 0;
|
|
1963
|
+
wait = minWait;
|
|
1964
|
+
void openStream();
|
|
1965
|
+
},
|
|
1966
|
+
approve,
|
|
1967
|
+
deny,
|
|
1968
|
+
answerQuestion: () => false,
|
|
1969
|
+
setApprovalMode: () => {
|
|
1970
|
+
},
|
|
1971
|
+
approveAppToolCall: notAvailable("An app’s tool call"),
|
|
1972
|
+
sampleForApp: notAvailable("An app’s sampling"),
|
|
1973
|
+
compact: async () => void 0,
|
|
1974
|
+
loadChat
|
|
1975
|
+
};
|
|
1976
|
+
};
|
|
1977
|
+
|
|
1429
1978
|
// src/controller.ts
|
|
1430
1979
|
var dbNameOf = (store) => {
|
|
1431
1980
|
const name = store?.dbName;
|
|
@@ -1433,7 +1982,7 @@ var dbNameOf = (store) => {
|
|
|
1433
1982
|
};
|
|
1434
1983
|
var modeOf = (config) => config.toolApproval?.mode ?? "autopilot";
|
|
1435
1984
|
var pageAppToolGrants = /* @__PURE__ */ new Set();
|
|
1436
|
-
var
|
|
1985
|
+
var snapshotOf2 = (state, extra) => {
|
|
1437
1986
|
const remoteRunning = state.remote?.running === true;
|
|
1438
1987
|
return Object.freeze({
|
|
1439
1988
|
...state,
|
|
@@ -1448,7 +1997,7 @@ var snapshotOf = (state, extra) => {
|
|
|
1448
1997
|
sessionId: extra.sessionId
|
|
1449
1998
|
});
|
|
1450
1999
|
};
|
|
1451
|
-
var createInitialAgentSnapshot = (config) =>
|
|
2000
|
+
var createInitialAgentSnapshot = (config) => snapshotOf2(createInitialAgentState(), {
|
|
1452
2001
|
sessionId: config.sessionId ?? "default",
|
|
1453
2002
|
pendingQuestions: [],
|
|
1454
2003
|
approvalMode: modeOf(config)
|
|
@@ -1845,7 +2394,7 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
|
|
|
1845
2394
|
syncWatch();
|
|
1846
2395
|
syncSkills();
|
|
1847
2396
|
return {
|
|
1848
|
-
getSnapshot: () => snapshot ??=
|
|
2397
|
+
getSnapshot: () => snapshot ??= snapshotOf2(state, { sessionId, pendingQuestions, approvalMode }),
|
|
1849
2398
|
subscribe: (listener) => {
|
|
1850
2399
|
if (disposed) return () => {
|
|
1851
2400
|
};
|
|
@@ -1886,5 +2435,11 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
|
|
|
1886
2435
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1887
2436
|
0 && (module.exports = {
|
|
1888
2437
|
createAgentController,
|
|
1889
|
-
createInitialAgentSnapshot
|
|
2438
|
+
createInitialAgentSnapshot,
|
|
2439
|
+
createInitialRemoteSnapshot,
|
|
2440
|
+
createRemoteAgentController,
|
|
2441
|
+
createSseParser,
|
|
2442
|
+
parseRemoteCursor,
|
|
2443
|
+
remoteEventOf,
|
|
2444
|
+
remoteEventScope
|
|
1890
2445
|
});
|