@cotal-ai/web 0.138.2 → 0.139.0
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/web/assets/AgentPage-CpDkKMSj.js +1 -0
- package/dist/web/assets/FailedTip-DfF85PmB.js +1 -0
- package/dist/web/assets/bash-CLZ0U2zV.js +1 -0
- package/dist/web/assets/characters-BsW4RWhl.js +9 -0
- package/dist/web/assets/controller-D_lQfVDy.js +70 -0
- package/dist/web/assets/core-Bfff_dYO.js +12 -0
- package/dist/web/assets/diff-woXpYk--.js +1 -0
- package/dist/web/assets/dist-BB9Crw5c.js +1 -0
- package/dist/web/assets/dist-DktEa9vr.js +1 -0
- package/dist/web/assets/engine-javascript-C30F4iNc.js +141 -0
- package/dist/web/assets/index-DQdr6c2w.css +1 -0
- package/dist/web/assets/index-Dfeh4Ewy.js +13 -0
- package/dist/web/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/dist/web/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/dist/web/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/dist/web/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/dist/web/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/dist/web/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/dist/web/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/dist/web/assets/javascript-BgS3c2Ky.js +1 -0
- package/dist/web/assets/json-qhed-kSA.js +1 -0
- package/dist/web/assets/markdown-BYOwaDjH.js +1 -0
- package/dist/web/assets/python-gzcpVVnB.js +1 -0
- package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/web/assets/typescript-bsJCZSQ-.js +1 -0
- package/dist/web/assets/yaml-rwi0_p6S.js +1 -0
- package/dist/web/bundle-licenses.json +389 -0
- package/dist/web/index.html +9 -513
- package/dist/web/theme-boot.js +8 -0
- package/dist/web.d.ts +312 -21
- package/dist/web.d.ts.map +1 -1
- package/dist/web.js +647 -121
- package/dist/web.js.map +1 -1
- package/package.json +30 -6
- package/dist/web/agui-frame.js +0 -210
- package/dist/web/app.js +0 -1428
- package/dist/web/event-order.js +0 -283
- package/dist/web/graph.html +0 -225
- package/dist/web/graph.js +0 -868
- package/dist/web/harness.js +0 -46
- package/dist/web/md.js +0 -31
- package/dist/web/parts.js +0 -114
- package/dist/web/presence-ages.js +0 -33
- package/dist/web/presence.js +0 -17
- package/dist/web/snapshot.js +0 -99
- package/dist/web/vendor/marked.umd.js +0 -79
- package/dist/web/vendor/purify.min.js +0 -3
- package/dist/web/vendor/vendor-manifest.json +0 -18
package/dist/web.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
3
|
import { createServer } from "node:http";
|
|
4
|
-
import { closeSync, fstatSync, openSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { closeSync, existsSync, fchmodSync, fstatSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { dirname, join } from "node:path";
|
|
7
|
-
import { CotalEndpoint, deliveryOf, isEventChannel, parseSubject, spacePrefix, mintCreds, newIdentity, clearChannel, assertValidChannel, hardenPrivate, openPrivateAppend, writePrivateRecord, } from "@cotal-ai/core";
|
|
6
|
+
import { basename, dirname, extname, join } from "node:path";
|
|
7
|
+
import { CotalEndpoint, deliveryOf, eventChannel, eventChannelPrincipal, isEventChannel, isPermissionDenied, parsePrincipalKey, parseSubject, principalKey, spacePrefix, credsClaims, mintCreds, mintLifecycleUid, newIdentity, clearChannel, assertValidChannel, hardenPrivate, mentionsIn, openPrivateAppend, writePrivateRecord, } from "@cotal-ai/core";
|
|
8
8
|
import { c, connectOrExit, inputDisabledByFlag, localProcessPath, parsePid, probeLiveness, probeWebReadiness, webBoundUrl as boundUrl, readPidfile, readWebSession, removePidPair, userViewAuth, userViewAuthOrExit, WEB_PIDFILE, WEB_READINESS_HEADER, WEB_READINESS_PATH, WEB_SESSION_FILE, writeIdentityPin, } from "@cotal-ai/workspace";
|
|
9
9
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
10
10
|
/** The dashboard's default port and its branded address. The server binds loopback
|
|
@@ -235,53 +235,70 @@ function releasePid(path) {
|
|
|
235
235
|
// Unreadable or locked: leaving a record this process cannot prove is its own is the safe error.
|
|
236
236
|
}
|
|
237
237
|
}
|
|
238
|
-
// Message bodies render markdown via marked + DOMPurify (parse + sanitize). Their browser builds are
|
|
239
|
-
// copied into dist/web/vendor at build time (scripts/copy-vendor.mjs) and served from the dashboard's
|
|
240
|
-
// OWN files, so a published/seeded copy is self-contained and never reaches into node_modules at
|
|
241
|
-
// runtime — which is what lets web ship as a bundled first-party extension, seeded like the connectors.
|
|
242
|
-
const jsType = "text/javascript; charset=utf-8";
|
|
243
238
|
/** The one condition name for "the membership read did not answer", shared by the HTTP body and the
|
|
244
239
|
* SSE event so a browser matches ONE token and a test asserts the same token the server emits.
|
|
245
|
-
* Exported
|
|
240
|
+
* Exported so a test asserts the token the server emits rather than a restated copy. */
|
|
246
241
|
export const MEMBERSHIP_READ_FAILED = "membership-read-failed";
|
|
247
|
-
/**
|
|
248
|
-
*
|
|
249
|
-
|
|
250
|
-
"
|
|
251
|
-
"
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
"
|
|
255
|
-
// Registers an `ag-ui.frame` renderer into the map `parts.js` consults. Served to both pages: a
|
|
256
|
-
// frame is as likely to arrive on the graph's detail row as in the console body, and a kind that
|
|
257
|
-
// draws on one page and shows a marker on the other is worse than one that shows a marker on both.
|
|
258
|
-
"/agui-frame.js": { path: join(here, "web/agui-frame.js"), type: jsType },
|
|
259
|
-
// The shape-B bootstrap: this page taps live before it reads history, so a frame's `seq` order has
|
|
260
|
-
// to be imposed by the consumer. Served to `/` only. The graph page reads the backfill into
|
|
261
|
-
// transient glow and "recently active" buffers and keeps no feed a live arrival appends to, so it
|
|
262
|
-
// has no merge to order; giving it the machine anyway would imply an ordering guarantee on a
|
|
263
|
-
// surface where nothing consumes one.
|
|
264
|
-
"/event-order.js": { path: join(here, "web/event-order.js"), type: jsType },
|
|
265
|
-
// Keep-last-good + the refusal guard, shared by BOTH pages so they cannot disagree about what a
|
|
266
|
-
// failed poll does to what is already on screen. Served to `/` and `/graph` alike: the wipe was
|
|
267
|
-
// measured on the graph page and the corrupted feed on the console page, and one page keeping its
|
|
268
|
-
// snapshot while the other drops it is the state this file exists to prevent.
|
|
269
|
-
"/snapshot.js": { path: join(here, "web/snapshot.js"), type: jsType },
|
|
270
|
-
"/md.js": { path: join(here, "web/md.js"), type: jsType },
|
|
271
|
-
"/presence-ages.js": { path: join(here, "web/presence-ages.js"), type: jsType },
|
|
272
|
-
"/presence.js": { path: join(here, "web/presence.js"), type: jsType },
|
|
273
|
-
"/app.js": { path: join(here, "web/app.js"), type: jsType },
|
|
274
|
-
"/graph": { path: join(here, "web/graph.html"), type: "text/html; charset=utf-8" },
|
|
275
|
-
"/graph.js": { path: join(here, "web/graph.js"), type: jsType },
|
|
276
|
-
"/vendor/marked.umd.js": { path: join(here, "web/vendor/marked.umd.js"), type: jsType },
|
|
277
|
-
"/vendor/purify.min.js": { path: join(here, "web/vendor/purify.min.js"), type: jsType },
|
|
242
|
+
/** Content types for the files a client build contains. A file of any other type is not served,
|
|
243
|
+
* so a stray file dropped into the build directory never becomes a route. */
|
|
244
|
+
const CLIENT_TYPES = {
|
|
245
|
+
".js": "text/javascript; charset=utf-8",
|
|
246
|
+
".css": "text/css; charset=utf-8",
|
|
247
|
+
".woff2": "font/woff2",
|
|
248
|
+
".svg": "image/svg+xml",
|
|
249
|
+
".png": "image/png",
|
|
278
250
|
};
|
|
251
|
+
/** The answer when the client build is missing: the server keeps serving the API and says what to
|
|
252
|
+
* do instead of serving nothing. It speaks to both readers who can meet it: in a source checkout
|
|
253
|
+
* the page has not been built yet, while an installed package always ships its page, so there the
|
|
254
|
+
* install itself is broken. */
|
|
255
|
+
export const CLIENT_NOT_BUILT = "the dashboard client is not built. In a source checkout, run `pnpm --filter @cotal-ai/web build`. " +
|
|
256
|
+
"An installed @cotal-ai/web always ships its client, so this is a broken install: reinstall it with `cotal ext seed --force`.";
|
|
257
|
+
/** The classic script the page loads in its head, before the stylesheet, to put the saved theme on
|
|
258
|
+
* the root element before anything is drawn (`client/src/lib/themeBoot.ts`, written by the build). */
|
|
259
|
+
export const THEME_BOOT = "theme-boot.js";
|
|
260
|
+
/** The client build as an allow-list, read once at startup: the page at `/` (and `/graph`, so an
|
|
261
|
+
* old link opens the app), the theme boot script at `/theme-boot.js`, and the files directly inside
|
|
262
|
+
* `assets/`. Nothing else under `dir` is reachable, and no request path is ever joined onto the
|
|
263
|
+
* filesystem. The boot script's name carries no hash, so unlike the assets it is not cached for good. */
|
|
264
|
+
export function clientAssets(dir) {
|
|
265
|
+
const routes = new Map();
|
|
266
|
+
const index = join(dir, "index.html");
|
|
267
|
+
if (!existsSync(index))
|
|
268
|
+
return routes;
|
|
269
|
+
const page = { path: index, type: "text/html; charset=utf-8", immutable: false };
|
|
270
|
+
routes.set("/", page);
|
|
271
|
+
routes.set("/graph", page);
|
|
272
|
+
const boot = join(dir, THEME_BOOT);
|
|
273
|
+
if (existsSync(boot))
|
|
274
|
+
routes.set(`/${THEME_BOOT}`, { path: boot, type: CLIENT_TYPES[".js"], immutable: false });
|
|
275
|
+
const assets = join(dir, "assets");
|
|
276
|
+
if (!existsSync(assets))
|
|
277
|
+
return routes;
|
|
278
|
+
for (const entry of readdirSync(assets, { withFileTypes: true })) {
|
|
279
|
+
const type = entry.isFile() ? CLIENT_TYPES[extname(entry.name)] : undefined;
|
|
280
|
+
if (type)
|
|
281
|
+
routes.set(`/assets/${entry.name}`, { path: join(assets, entry.name), type, immutable: true });
|
|
282
|
+
}
|
|
283
|
+
return routes;
|
|
284
|
+
}
|
|
285
|
+
/** The answer to a static request: the file when the build has it, a 503 naming the build command
|
|
286
|
+
* when the build is missing and the page is asked for, otherwise a 404. A pure function of the
|
|
287
|
+
* route map and the path, so the 503 is testable without a server. */
|
|
288
|
+
export function clientResponse(routes, path) {
|
|
289
|
+
const file = routes.get(path);
|
|
290
|
+
if (file)
|
|
291
|
+
return { status: 200, file };
|
|
292
|
+
if (routes.size === 0 && (path === "/" || path === "/graph"))
|
|
293
|
+
return { status: 503, body: { error: CLIENT_NOT_BUILT } };
|
|
294
|
+
return { status: 404 };
|
|
295
|
+
}
|
|
279
296
|
/** The channels this dashboard LISTS and BACKFILLS: chat only.
|
|
280
297
|
*
|
|
281
298
|
* WHY AN AGENT'S EVENT CHANNEL IS NOT ONE OF THEM. `listChannels()` derives a row from every
|
|
282
299
|
* retained concrete subject and the chat stream caps per subject rather than by age, so the list
|
|
283
300
|
* grows by one row per agent that has ever run and those rows never age out. Unfiltered, the channel
|
|
284
|
-
* sidebar is buried under machine streams, the graph
|
|
301
|
+
* sidebar is buried under machine streams, the client's graph grows a hub node for each, and
|
|
285
302
|
* `/api/activity` merges every event channel into a global top-N that a human reading chat did not
|
|
286
303
|
* ask for, and pays to move those messages across the link first. That is a cost that scales with
|
|
287
304
|
* the number of agents ever run, which is the wrong axis entirely.
|
|
@@ -294,11 +311,12 @@ export const PAGE = {
|
|
|
294
311
|
* surfaces share this classifier rather than each spelling the convention, so they cannot disagree
|
|
295
312
|
* about what a channel is.
|
|
296
313
|
*
|
|
297
|
-
* WHAT IS NOT FILTERED, DELIBERATELY, IN TWO PLACES. The live SSE tap still
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
*
|
|
314
|
+
* WHAT IS NOT FILTERED, DELIBERATELY, IN TWO PLACES. The live SSE tap still receives frames, and
|
|
315
|
+
* sends each one as an `agent-frame` only to the feeds watching that agent (see {@link classifyTap}
|
|
316
|
+
* and {@link SessionWatchers}), never as a `message` to every browser and never dropped for a
|
|
317
|
+
* watcher. And `/api/channels/<name>/history` still serves an event channel
|
|
318
|
+
* when a caller names one, because that route answers a question about a channel the caller already
|
|
319
|
+
* identified; a filter there would mean the dashboard could render a frame it could never fetch. */
|
|
302
320
|
export function chatOnly(rows) {
|
|
303
321
|
return rows.filter((row) => !isEventChannel(row.channel));
|
|
304
322
|
}
|
|
@@ -382,13 +400,19 @@ export class BadRequest extends Error {
|
|
|
382
400
|
* 400 by fixing its payload would loop forever on a size it never learns is the problem. */
|
|
383
401
|
export class PayloadTooLarge extends Error {
|
|
384
402
|
}
|
|
385
|
-
/**
|
|
403
|
+
/** A post the broker, or the operator's connection to it, refused. Neither the caller's fault nor
|
|
404
|
+
* this server's, so the frame answers 502 with the broker's own message, escaped by
|
|
405
|
+
* {@link escapeForOperator}. */
|
|
406
|
+
export class BrokerRefused extends Error {
|
|
407
|
+
}
|
|
408
|
+
/** The most a request body may weigh before a body route refuses to keep reading it.
|
|
386
409
|
*
|
|
387
|
-
*
|
|
388
|
-
* to dotted `[A-Za-z0-9_-]` segments that the wire will carry as a subject. The dashboard's
|
|
389
|
-
* delete sends about sixty bytes. 8 KiB is therefore not a guess at a working size, it is two
|
|
410
|
+
* The delete route's body has one field, a channel name, and `assertValidChannel` bounds a usable
|
|
411
|
+
* name to dotted `[A-Za-z0-9_-]` segments that the wire will carry as a subject. The dashboard's
|
|
412
|
+
* own delete sends about sixty bytes. 8 KiB is therefore not a guess at a working size, it is two
|
|
390
413
|
* orders of magnitude ABOVE any name the broker would accept, chosen so that no legitimate
|
|
391
|
-
* caller can meet it and an abusive one meets it immediately.
|
|
414
|
+
* caller can meet it and an abusive one meets it immediately. The send route shares the cap, so a
|
|
415
|
+
* post's text is bounded by it too.
|
|
392
416
|
*
|
|
393
417
|
* MEASURED, before this existed, against the shipped route over a local broker with a raw socket
|
|
394
418
|
* rather than `fetch`, because `fetch` hides how much of the body actually left the client:
|
|
@@ -396,6 +420,8 @@ export class PayloadTooLarge extends Error {
|
|
|
396
420
|
* peak RSS +1.39 GB, 1022 ms. The read was unbounded and ran to completion before the route
|
|
397
421
|
* formed an opinion, so the refusal was the expensive part rather than the cheap one. */
|
|
398
422
|
const MAX_BODY_BYTES = 8 * 1024;
|
|
423
|
+
/** The only routes that read a request body. Every other route refuses an announced body. */
|
|
424
|
+
const BODY_ROUTES = new Set(["/api/channel/delete", "/api/send"]);
|
|
399
425
|
/** Codepoints `JSON.stringify` leaves RAW that PRODUCE NO GLYPH OF THEIR OWN, or that reorder the
|
|
400
426
|
* text around them, stated as Unicode PROPERTIES rather than as a hand list. That wording is
|
|
401
427
|
* narrower than "change what a reader sees" on purpose, and the narrowing is a review finding:
|
|
@@ -474,6 +500,15 @@ export function quoteForOperator(value) {
|
|
|
474
500
|
return out;
|
|
475
501
|
});
|
|
476
502
|
}
|
|
503
|
+
/** Every codepoint {@link quoteForOperator} escapes, the C0 controls included, without its quotes. */
|
|
504
|
+
const UNREADABLE = new RegExp(`[\\u0000-\\u001f]|${INVISIBLE_AFTER_JSON.source}`, "gu");
|
|
505
|
+
/** Escapes a message someone else wrote, keeping its wording. A broker refusal names the subject it
|
|
506
|
+
* refused, and a DM subject carries a recipient id taken from another agent's presence card, so the
|
|
507
|
+
* message reaches the 502 body and the operator's line as untrusted text. Each codepoint the quoter
|
|
508
|
+
* escapes leaves as its escape; the rest, quotes included, stays as the broker wrote it. */
|
|
509
|
+
export function escapeForOperator(text) {
|
|
510
|
+
return text.replace(UNREADABLE, (ch) => quoteForOperator(ch).slice(1, -1));
|
|
511
|
+
}
|
|
477
512
|
/** The channel name out of the path. A percent escape the decoder cannot read is the caller having
|
|
478
513
|
* typed a bad one, so it is refused as a bad request like any other malformed input. Left as a
|
|
479
514
|
* bare `URIError` it reached the request frame unrecognised and was reported as a server fault,
|
|
@@ -511,11 +546,14 @@ function canonicalChannel(name) {
|
|
|
511
546
|
`and a name the wire would rewrite would address a different channel than it names`);
|
|
512
547
|
}
|
|
513
548
|
}
|
|
514
|
-
/** The
|
|
515
|
-
*
|
|
516
|
-
*
|
|
517
|
-
|
|
518
|
-
|
|
549
|
+
/** The most messages one read may ask for. A route reads up to `limit` messages and holds them all
|
|
550
|
+
* before it answers, so a limit with no ceiling lets one request make the server read a stream's
|
|
551
|
+
* whole retained history. The dashboard asks for at most 500. */
|
|
552
|
+
export const MAX_HISTORY_LIMIT = 2000;
|
|
553
|
+
/** The `limit` out of the query. The ceiling refusal is reachable only through the digits-only test
|
|
554
|
+
* above it, so its value cannot carry anything the quoter would escape today. It quotes anyway:
|
|
555
|
+
* the guarantee that a refusal renders its input unambiguously should hold because the quoting site
|
|
556
|
+
* holds it, not because a regex two lines up stays exactly as narrow as it is this morning.
|
|
519
557
|
*
|
|
520
558
|
* THE LIMIT, PARSED ONCE, because three routes each re-deriving
|
|
521
559
|
* `query.get("limit") ? Number(...) : N` is how they came to disagree about the same parameter.
|
|
@@ -531,7 +569,8 @@ function canonicalChannel(name) {
|
|
|
531
569
|
* ?limit=2.5 silently truncated to 2.
|
|
532
570
|
* ?limit=" 5" accepted as 5, because `Number()` trims whitespace.
|
|
533
571
|
*
|
|
534
|
-
* So the accepted form is the narrow one: a plain run of digits
|
|
572
|
+
* So the accepted form is the narrow one: a plain run of digits no larger than
|
|
573
|
+
* {@link MAX_HISTORY_LIMIT}. `0` keeps
|
|
535
574
|
* meaning zero, which is what it already did and what a caller expects; an absent or empty
|
|
536
575
|
* parameter keeps meaning the route's own default, the one shape the old parse got right.
|
|
537
576
|
*
|
|
@@ -544,11 +583,253 @@ export function historyLimit(query, fallback) {
|
|
|
544
583
|
return fallback;
|
|
545
584
|
if (!/^[0-9]+$/.test(raw))
|
|
546
585
|
throw new BadRequest(`limit must be a whole number of messages, received ${quoteForOperator(raw)}`);
|
|
586
|
+
// The ceiling also covers a run of digits too long for a double to count exactly: every such
|
|
587
|
+
// number is far above it.
|
|
547
588
|
const n = Number(raw);
|
|
548
|
-
if (
|
|
549
|
-
throw new BadRequest(`limit ${quoteForOperator(raw)} is
|
|
589
|
+
if (n > MAX_HISTORY_LIMIT)
|
|
590
|
+
throw new BadRequest(`limit ${quoteForOperator(raw)} is above the most this server reads at once, ${MAX_HISTORY_LIMIT} messages`);
|
|
550
591
|
return n;
|
|
551
592
|
}
|
|
593
|
+
/** An agent id out of a path segment: decoded, and a principal key, or a BadRequest naming it.
|
|
594
|
+
*
|
|
595
|
+
* The id is the roster's `card.id`, which is `principalKey(owner, actor).key` by construction, so
|
|
596
|
+
* the agent is named by its principal and never by a display name: two live agents with one name
|
|
597
|
+
* never share a session. The answer's `id` is rebuilt from the parsed tokens rather than passed
|
|
598
|
+
* through, so the id a route acts on is the one the event channel is formed from. */
|
|
599
|
+
export function agentIdFromPath(raw) {
|
|
600
|
+
let decoded;
|
|
601
|
+
try {
|
|
602
|
+
decoded = decodeURIComponent(raw);
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
throw new BadRequest(`agent id ${quoteForOperator(raw)} is not valid percent-encoded text`);
|
|
606
|
+
}
|
|
607
|
+
const principal = parsePrincipalKey(decoded);
|
|
608
|
+
if (principal === null)
|
|
609
|
+
throw new BadRequest(`agent id ${quoteForOperator(decoded)} is not an agent id: <owner>.<actor>, each of [A-Za-z0-9_]`);
|
|
610
|
+
return { id: principalKey(principal.owner, principal.actor).key, ...principal };
|
|
611
|
+
}
|
|
612
|
+
/** What the live tap does with one message. A chat message on a principal-shaped event channel is an
|
|
613
|
+
* agent frame for `principalKey(owner, actor).key`; everything else goes out as today's `message`.
|
|
614
|
+
*
|
|
615
|
+
* WHY FRAMES LEAVE THE BROADCAST. The observer taps `chat.>`, and an agent's event channel is a
|
|
616
|
+
* chat channel, so this one subscription receives every agent's frames. A NATS wildcard cannot
|
|
617
|
+
* exclude a sub-tree, so the observer still receives them; what changes is who it forwards them to.
|
|
618
|
+
* Sent as `message` to every browser, each frame cost every open dashboard a write whether or not
|
|
619
|
+
* anyone was reading that agent. As `agent-frame` it reaches only the feeds watching that agent.
|
|
620
|
+
*
|
|
621
|
+
* The agent is the event channel's principal, the same derivation the chat-only filter reads, so a
|
|
622
|
+
* near-miss name such as `events.standup` stays an ordinary `message`. The channel is the one the
|
|
623
|
+
* broker policed, taken from the subject, never the payload's own claim.
|
|
624
|
+
*
|
|
625
|
+
* A FRAME FROM ANYONE BUT THE AGENT IS DROPPED, and dropped rather than sent on as a `message`. The
|
|
626
|
+
* subject's sender is the verified publisher, and a frame is that agent's only when the agent
|
|
627
|
+
* published it. On a mesh where another principal may write the channel (an open mesh, or a grant
|
|
628
|
+
* wider than the agent's own), a forged frame would otherwise read as the agent's session, and
|
|
629
|
+
* falling through to `message` would hand it to every browser instead. */
|
|
630
|
+
export function classifyTap(subject, msg) {
|
|
631
|
+
const mode = deliveryOf(subject);
|
|
632
|
+
if (!mode || !msg)
|
|
633
|
+
return null;
|
|
634
|
+
// senderId is the subject's sender token, the *verified* publisher (the server policed who could
|
|
635
|
+
// publish it), vs the advisory `from` in the payload.
|
|
636
|
+
const parsed = parseSubject(subject);
|
|
637
|
+
const senderId = parsed?.sender;
|
|
638
|
+
// The channel the broker actually POLICED, taken from the subject rather than the payload: a
|
|
639
|
+
// publish grant is per-channel (`chat.<owner>.<actor>.<ch>`), so this token is covered by the
|
|
640
|
+
// minted grant, while `msg.channel` is publisher-supplied and backed by nothing.
|
|
641
|
+
//
|
|
642
|
+
// Gated on kind, and the gate is load-bearing rather than defensive: `rest` is the channel only
|
|
643
|
+
// on the chat plane. On `inst` it is the RECIPIENT (`subjects.ts:599`) and on `svc` the route
|
|
644
|
+
// (`:603`), so forwarding it ungated would label a DM's recipient as a channel.
|
|
645
|
+
const channel = parsed?.kind === "chat" ? parsed.rest : undefined;
|
|
646
|
+
const agent = channel === undefined ? null : eventChannelPrincipal(channel);
|
|
647
|
+
if (agent !== null) {
|
|
648
|
+
const id = principalKey(agent.owner, agent.actor).key;
|
|
649
|
+
if (senderId !== id)
|
|
650
|
+
return null;
|
|
651
|
+
return { event: "agent-frame", agent: id, data: { id, msg } };
|
|
652
|
+
}
|
|
653
|
+
return { event: "message", data: { mode, senderId, channel, msg } };
|
|
654
|
+
}
|
|
655
|
+
/** The most bytes a feed may have waiting to be sent before the server gives up on it. A browser on
|
|
656
|
+
* a slow link, watching a busy agent, cannot take frames as fast as the tap produces them, and
|
|
657
|
+
* every byte it has not taken waits in this process. Past this the feed is told why and ended, and
|
|
658
|
+
* the browser's own reconnect opens a fresh one, watches again and reads the gap from history. */
|
|
659
|
+
export const MAX_FEED_BUFFER_BYTES = 1_048_576;
|
|
660
|
+
/** Each cold feed and the unsent bytes its opening snapshots left behind. A feed is cold from a
|
|
661
|
+
* snapshot write that leaves bytes unsent until its response emits `drain`, or a live write finds
|
|
662
|
+
* nothing unsent, and is warm after. A feed that has gone is dropped with its response. */
|
|
663
|
+
const coldFeeds = new WeakMap();
|
|
664
|
+
/** The feed's opening state has drained: from here on a live event is held to the ceiling alone. */
|
|
665
|
+
function warmFeed(res) {
|
|
666
|
+
coldFeeds.delete(res);
|
|
667
|
+
}
|
|
668
|
+
/** Writes one SSE event to a feed. A feed that has ended takes nothing more.
|
|
669
|
+
*
|
|
670
|
+
* A live event is checked against the backlog the feed already holds, measured BEFORE the write:
|
|
671
|
+
* when more than `ceiling` bytes are still unsent, the feed is told so with one `overflow` event
|
|
672
|
+
* `{ reason }` and ended, and the event is not written. Measuring after the write would end a feed
|
|
673
|
+
* for one event larger than the ceiling on its own, such as a single long chat message, which would
|
|
674
|
+
* disconnect every dashboard at once. So one large event over an empty backlog is written, and the
|
|
675
|
+
* feed ends only when it is in fact behind.
|
|
676
|
+
*
|
|
677
|
+
* A snapshot is never checked. Its unsent bytes are not live traffic the feed fell behind on, so
|
|
678
|
+
* while they drain (the feed is cold) a live event is allowed them on top of the ceiling: on a slow
|
|
679
|
+
* link a roster over the ceiling would otherwise end the feed at its first live event, and every
|
|
680
|
+
* reconnect would end the same way. The allowance goes when the opening state has drained, so a
|
|
681
|
+
* cold feed still has a bound, its opening bytes plus the ceiling plus one event. */
|
|
682
|
+
export function writeFeed(res, event, data, kind = "live", ceiling = MAX_FEED_BUFFER_BYTES) {
|
|
683
|
+
if (res.writableEnded)
|
|
684
|
+
return;
|
|
685
|
+
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
686
|
+
if (kind === "snapshot") {
|
|
687
|
+
res.write(frame);
|
|
688
|
+
if (res.writableLength > 0) {
|
|
689
|
+
if (!coldFeeds.has(res))
|
|
690
|
+
res.once?.("drain", () => warmFeed(res));
|
|
691
|
+
coldFeeds.set(res, res.writableLength);
|
|
692
|
+
}
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
if (res.writableLength === 0)
|
|
696
|
+
warmFeed(res);
|
|
697
|
+
const allowance = coldFeeds.get(res) ?? 0;
|
|
698
|
+
if (res.writableLength > ceiling + allowance) {
|
|
699
|
+
const reason = `this feed fell more than ${ceiling} bytes behind, so the server closed it; reconnect to resume`;
|
|
700
|
+
res.write(`event: overflow\ndata: ${JSON.stringify({ reason })}\n\n`);
|
|
701
|
+
res.end();
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
res.write(frame);
|
|
705
|
+
}
|
|
706
|
+
/** Writes a new feed's opening state through `send`, every write a snapshot: `hello` first, so a
|
|
707
|
+
* browser can watch an agent before the roster arrives, then the roster and the presence view, then
|
|
708
|
+
* the membership seed once it is read, or its refusal when the read fails. Resolves when the seed
|
|
709
|
+
* is written. */
|
|
710
|
+
export function writeOpening(send, state) {
|
|
711
|
+
send("hello", { feed: state.feed }, "snapshot");
|
|
712
|
+
send("roster", state.roster, "snapshot");
|
|
713
|
+
send("presence-view", state.presenceView, "snapshot");
|
|
714
|
+
return state.membership()
|
|
715
|
+
.then((m) => send("membership", m, "snapshot"))
|
|
716
|
+
.catch((e) => send(MEMBERSHIP_READ_FAILED, { reason: e.message }, "snapshot"));
|
|
717
|
+
}
|
|
718
|
+
/** The most agents one feed may watch at once. A watch is a row in a map this process holds for as
|
|
719
|
+
* long as the feed is open, and the id is the caller's, so without a ceiling one browser could
|
|
720
|
+
* grow that map without bound by asking for ids nobody runs. The dashboard watches the agent whose
|
|
721
|
+
* session is open, in the panel and the centre, so it never comes near this. */
|
|
722
|
+
export const MAX_WATCHES_PER_FEED = 64;
|
|
723
|
+
/** Which feeds watch which agent. A feed is counted once per agent however many times it asks.
|
|
724
|
+
*
|
|
725
|
+
* This is the refcount behind "subscribe on demand": the tap already receives every frame, so an
|
|
726
|
+
* agent with no watcher costs no browser anything, and an agent leaves the map with its last
|
|
727
|
+
* watcher. Both directions are kept so `drop` touches only the agents its feed held, and so the
|
|
728
|
+
* per-feed ceiling is a lookup rather than a scan. */
|
|
729
|
+
export class SessionWatchers {
|
|
730
|
+
perFeed;
|
|
731
|
+
byAgent = new Map();
|
|
732
|
+
byFeed = new Map();
|
|
733
|
+
constructor(perFeed = MAX_WATCHES_PER_FEED) {
|
|
734
|
+
this.perFeed = perFeed;
|
|
735
|
+
}
|
|
736
|
+
/** Throws a BadRequest when the feed already watches `perFeed` other agents. */
|
|
737
|
+
watch(agent, feed) {
|
|
738
|
+
const held = this.byFeed.get(feed) ?? new Set();
|
|
739
|
+
if (!held.has(agent) && held.size >= this.perFeed)
|
|
740
|
+
throw new BadRequest(`this feed already watches ${this.perFeed} agents, the most one feed may watch at once`);
|
|
741
|
+
const feeds = this.byAgent.get(agent) ?? [];
|
|
742
|
+
if (!feeds.includes(feed))
|
|
743
|
+
feeds.push(feed);
|
|
744
|
+
this.byAgent.set(agent, feeds);
|
|
745
|
+
held.add(agent);
|
|
746
|
+
this.byFeed.set(feed, held);
|
|
747
|
+
}
|
|
748
|
+
unwatch(agent, feed) {
|
|
749
|
+
const feeds = this.byAgent.get(agent);
|
|
750
|
+
if (feeds !== undefined) {
|
|
751
|
+
const rest = feeds.filter((f) => f !== feed);
|
|
752
|
+
if (rest.length === 0)
|
|
753
|
+
this.byAgent.delete(agent);
|
|
754
|
+
else
|
|
755
|
+
this.byAgent.set(agent, rest);
|
|
756
|
+
}
|
|
757
|
+
const held = this.byFeed.get(feed);
|
|
758
|
+
if (held !== undefined) {
|
|
759
|
+
held.delete(agent);
|
|
760
|
+
if (held.size === 0)
|
|
761
|
+
this.byFeed.delete(feed);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
/** A feed closed: forget every watch it held. */
|
|
765
|
+
drop(feed) {
|
|
766
|
+
for (const agent of [...(this.byFeed.get(feed) ?? [])])
|
|
767
|
+
this.unwatch(agent, feed);
|
|
768
|
+
}
|
|
769
|
+
targets(agent) {
|
|
770
|
+
return [...(this.byAgent.get(agent) ?? [])];
|
|
771
|
+
}
|
|
772
|
+
/** Agents with at least one watcher. An agent with none is absent, not zero. */
|
|
773
|
+
agents() {
|
|
774
|
+
return [...this.byAgent.keys()];
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
/** The events read ran past its deadline. Its own type, so the route can tell it from a refusal
|
|
778
|
+
* (an answer) and from any other failure (a 503 with the reason). */
|
|
779
|
+
export class AgentEventsLate extends Error {
|
|
780
|
+
}
|
|
781
|
+
/** One agent's newest frames within the deadline. Reads `limit + 1` from `events.<owner>.<actor>`
|
|
782
|
+
* with `channelHistory` and answers the newest `limit`, oldest first, with `more` when one more
|
|
783
|
+
* existed. A permission denial (`isPermissionDenied` from core) is an answer, `{ refused }` with the
|
|
784
|
+
* broker's own text and the grant command for this mesh. The deadline throws `AgentEventsLate`; any
|
|
785
|
+
* other failure rethrows.
|
|
786
|
+
*
|
|
787
|
+
* SENDER-CHECKED LIKE THE LIVE FEED. The read names the agent as `publisher`, so it filters on the
|
|
788
|
+
* agent's own subject, `chat.<owner>.<actor>.events.<owner>.<actor>`, and a frame whose subject
|
|
789
|
+
* names another sender is never read. That is the check `classifyTap` makes on a live frame, so a
|
|
790
|
+
* session's history and its live frames hold the same frames. Like that check, it is as strong as
|
|
791
|
+
* the mesh's publish permissions: on an open mesh any raw NATS client can publish on this subject.
|
|
792
|
+
*
|
|
793
|
+
* BOUNDED TWICE. The caller's `limit` is already capped at {@link MAX_HISTORY_LIMIT}, so one read
|
|
794
|
+
* holds at most one more message than that, and the read races the same deadline its siblings do,
|
|
795
|
+
* with the signal handed down so a late read stops its pull and drops its consumer.
|
|
796
|
+
*
|
|
797
|
+
* `channelHistory`, not the mediated `readHistory`: the mediated read caps a page at 200 and has
|
|
798
|
+
* no cursor, and this is the same credential the channel history route already reads with. */
|
|
799
|
+
export async function agentEventsPage(source, agent, limit, grantFor, deadlineMs = AGGREGATION_DEADLINE_MS) {
|
|
800
|
+
const channel = eventChannel(agent);
|
|
801
|
+
const clock = deadline(deadlineMs);
|
|
802
|
+
try {
|
|
803
|
+
const publisher = { owner: agent.owner, actor: agent.actor };
|
|
804
|
+
const page = await within(source.channelHistory(channel, { limit: limit + 1, signal: clock.signal, publisher }), clock.until);
|
|
805
|
+
if (page === LATE)
|
|
806
|
+
throw new AgentEventsLate(`${channel}: the read did not finish within ${deadlineMs}ms`);
|
|
807
|
+
const more = page.length > limit;
|
|
808
|
+
// Not `slice(-limit)`: at a limit of 0 that is `slice(-0)`, the whole page.
|
|
809
|
+
return { frames: more ? page.slice(page.length - limit) : page, more };
|
|
810
|
+
}
|
|
811
|
+
catch (e) {
|
|
812
|
+
if (e instanceof AgentEventsLate)
|
|
813
|
+
throw e;
|
|
814
|
+
if (isPermissionDenied(e)) {
|
|
815
|
+
const grant = grantFor(channel, agent.owner);
|
|
816
|
+
return { refused: e instanceof Error ? e.message : String(e), ...(grant === undefined ? {} : { grant }) };
|
|
817
|
+
}
|
|
818
|
+
throw e;
|
|
819
|
+
}
|
|
820
|
+
finally {
|
|
821
|
+
clock.done();
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
/** The command that lets a reader see one agent's event channel, as `docs/connect-claude.md` gives
|
|
825
|
+
* it for each kind of mesh, or nothing on an open mesh, where there is no grant to give. */
|
|
826
|
+
export function eventsGrantFor(mode) {
|
|
827
|
+
if (mode === "user")
|
|
828
|
+
return (channel, owner) => `cotal actor grant <reader> --owner ${owner} --scope '' --allow-subscribe '${channel}' --allow-publish ''`;
|
|
829
|
+
if (mode === "static")
|
|
830
|
+
return (channel) => `cotal mint watcher --profile agent --allow-subscribe '${channel}' --provision`;
|
|
831
|
+
return () => undefined;
|
|
832
|
+
}
|
|
552
833
|
/** The all-activity backfill: recent chat history merged with DM history, oldest-first by `ts`,
|
|
553
834
|
* capped, and BOUNDED.
|
|
554
835
|
*
|
|
@@ -656,15 +937,181 @@ export async function activityBackfill(ep, limit, deadlineMs = AGGREGATION_DEADL
|
|
|
656
937
|
clock.done();
|
|
657
938
|
}
|
|
658
939
|
}
|
|
659
|
-
/**
|
|
660
|
-
*
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
*
|
|
940
|
+
/** Why posting is off on a dashboard started with `--creds`: the file is the only credential it
|
|
941
|
+
* holds, and it has no seed to mint an operator from. */
|
|
942
|
+
export const POST_OFF_CREDS = "This dashboard was started with --creds, which can only read.";
|
|
943
|
+
/** Why posting is off on a per-user sign-in mesh. */
|
|
944
|
+
export const POST_OFF_USER = "Posting from the dashboard isn't available on a sign-in mesh yet. Use cotal send.";
|
|
945
|
+
/** Why posting is off on a dashboard run as a service: the service holds a read-only credential. */
|
|
946
|
+
export const POST_OFF_SERVICE = "This dashboard runs as a read-only service. Use cotal send.";
|
|
947
|
+
/** The operator credential's lifetime: 24 days. Core arms a reconnect fence with one `setTimeout`
|
|
948
|
+
* at the credential's expiry, and Node caps a timer at 2^31-1 ms (about 24.8 days), so a longer
|
|
949
|
+
* credential turns library reconnect off 1 ms after every connect. */
|
|
950
|
+
export const OPERATOR_TTL_SECONDS = 24 * 24 * 3600;
|
|
951
|
+
/** The posting decision. `--creds` wins: a raw credential file is all such a dashboard holds. */
|
|
952
|
+
export function postCapability(creds, userMode) {
|
|
953
|
+
if (creds !== undefined)
|
|
954
|
+
return { mode: "off", reason: POST_OFF_CREDS };
|
|
955
|
+
if (userMode)
|
|
956
|
+
return { mode: "off", reason: POST_OFF_USER };
|
|
957
|
+
return { mode: "participant" };
|
|
958
|
+
}
|
|
959
|
+
/** Mints the operator for a static-auth mesh with one new identity. Called once, from
|
|
960
|
+
* {@link connectWithoutSeed}, so every post the process makes carries that one `from.id` and an
|
|
961
|
+
* agent's replies land in one DM thread. With `consume: false` the uid names no broker resources,
|
|
962
|
+
* so it needs no provisioning. */
|
|
963
|
+
export async function mintOperatorCred(auth) {
|
|
964
|
+
const creds = await mintCreds(auth, newIdentity(), "operator", { expiresInSeconds: OPERATOR_TTL_SECONDS });
|
|
965
|
+
const exp = credsClaims(creds).exp;
|
|
966
|
+
if (exp === undefined)
|
|
967
|
+
throw new Error("the operator credential was minted without an expiry");
|
|
968
|
+
return { creds, lifecycleUid: mintLifecycleUid(), expiresAt: exp * 1000 };
|
|
969
|
+
}
|
|
970
|
+
/** What `ensure()` rejects with once the poster has stopped. */
|
|
971
|
+
export const POSTER_STOPPED = "the dashboard is shutting down, so it no longer posts";
|
|
972
|
+
/** Why a post is refused once the operator credential has expired. */
|
|
973
|
+
export const POST_OFF_EXPIRED = "The operator credential expired. Restart cotal web to post again.";
|
|
974
|
+
/** `POST /api/send`: posts the body `{kind: "msg", channel, text}` to one channel, or
|
|
975
|
+
* `{kind: "dm", to, text}` to one roster member, as the operator. Separate from the handler so the
|
|
976
|
+
* refusals that need a stopped or expired poster can be driven with one.
|
|
977
|
+
*
|
|
978
|
+
* The body is read before any refusal, so the size cap bounds what a refused post costs: a reply
|
|
979
|
+
* written over an unread body leaves Node draining the rest of it to keep the connection. Every
|
|
980
|
+
* check runs before the poster starts, so a refused post never puts the operator on the roster.
|
|
981
|
+
* Throws `PayloadTooLarge`, `BadRequest` and `BrokerRefused` for the request frame to answer. */
|
|
982
|
+
export async function sendAsOperator(post, poster, onRoster, readRequest) {
|
|
983
|
+
const read = await readRequest().then((value) => ({ value }), (e) => {
|
|
984
|
+
if (e instanceof PayloadTooLarge)
|
|
985
|
+
throw e;
|
|
986
|
+
return undefined;
|
|
987
|
+
});
|
|
988
|
+
if (post.mode === "off")
|
|
989
|
+
return { status: 403, body: { error: post.reason } };
|
|
990
|
+
if (!poster)
|
|
991
|
+
throw new Error("posting is on but no operator poster was built");
|
|
992
|
+
if (poster.expired())
|
|
993
|
+
return { status: 403, body: { error: POST_OFF_EXPIRED } };
|
|
994
|
+
const body = read?.value;
|
|
995
|
+
if (typeof body !== "object" || body === null || Array.isArray(body))
|
|
996
|
+
throw new BadRequest("the request body must be a JSON object");
|
|
997
|
+
const { kind, channel, to, text: raw } = body;
|
|
998
|
+
const text = typeof raw === "string" ? raw.trim() : "";
|
|
999
|
+
if (!text)
|
|
1000
|
+
throw new BadRequest("text required");
|
|
1001
|
+
let target;
|
|
1002
|
+
if (kind === "msg") {
|
|
1003
|
+
if (typeof channel !== "string")
|
|
1004
|
+
throw new BadRequest("channel required");
|
|
1005
|
+
const name = canonicalChannel(channel);
|
|
1006
|
+
if (name.includes("*") || name.includes(">"))
|
|
1007
|
+
throw new BadRequest(`${quoteForOperator(name)} is not one channel`);
|
|
1008
|
+
target = { channel: name };
|
|
1009
|
+
}
|
|
1010
|
+
else if (kind === "dm") {
|
|
1011
|
+
if (typeof to !== "string")
|
|
1012
|
+
throw new BadRequest("to required");
|
|
1013
|
+
if (!onRoster(to))
|
|
1014
|
+
throw new BadRequest(`no agent with id ${quoteForOperator(to)} is on the roster`);
|
|
1015
|
+
target = { to };
|
|
1016
|
+
}
|
|
1017
|
+
else
|
|
1018
|
+
throw new BadRequest('kind must be "msg" or "dm"');
|
|
1019
|
+
let sender;
|
|
1020
|
+
try {
|
|
1021
|
+
sender = await poster.ensure();
|
|
1022
|
+
}
|
|
1023
|
+
catch (e) {
|
|
1024
|
+
const why = e instanceof Error ? e.message : String(e);
|
|
1025
|
+
if (why === POSTER_STOPPED)
|
|
1026
|
+
return { status: 503, body: { error: why } };
|
|
1027
|
+
throw new BrokerRefused(escapeForOperator(why));
|
|
1028
|
+
}
|
|
1029
|
+
const refused = (e) => {
|
|
1030
|
+
throw new BrokerRefused(escapeForOperator(e instanceof Error ? e.message : String(e)));
|
|
1031
|
+
};
|
|
1032
|
+
if ("channel" in target) {
|
|
1033
|
+
const msg = await sender.multicast(text, { channel: target.channel, mentions: mentionsIn(text) }).catch(refused);
|
|
1034
|
+
return { status: 200, body: { ok: true, id: msg.id, operatorId: sender.card.id } };
|
|
1035
|
+
}
|
|
1036
|
+
const { msg, ack } = await sender.unicastAttributed(target.to, text).catch(refused);
|
|
1037
|
+
return { status: 200, body: { ok: true, id: msg.id, operatorId: sender.card.id, seq: ack.seq } };
|
|
1038
|
+
}
|
|
1039
|
+
/** Builds the operator poster: a presence-registering endpoint with the card
|
|
1040
|
+
* `{ name: "operator", role: "operator", kind: "endpoint" }`, on the static operator credential
|
|
1041
|
+
* when there is one. The id is fixed here. The credential names it on a static mesh, and an open
|
|
1042
|
+
* mesh pins one, so a start retried after a failure keeps it. */
|
|
1043
|
+
export function operatorPoster(target, operator) {
|
|
1044
|
+
const card = { ...(operator ? {} : { id: randomUUID().replace(/-/g, "") }), name: "operator", role: "operator", kind: "endpoint" };
|
|
1045
|
+
const build = () => {
|
|
1046
|
+
const e = new CotalEndpoint({
|
|
1047
|
+
space: target.space,
|
|
1048
|
+
servers: target.server,
|
|
1049
|
+
tls: target.tls,
|
|
1050
|
+
...(operator ? { creds: operator.creds, lifecycleUid: operator.lifecycleUid } : {}),
|
|
1051
|
+
card,
|
|
1052
|
+
channels: [],
|
|
1053
|
+
consume: false,
|
|
1054
|
+
registerPresence: true,
|
|
1055
|
+
watchPresence: false,
|
|
1056
|
+
});
|
|
1057
|
+
e.on("error", (err) => console.error(c.red("! operator: " + err.message)));
|
|
1058
|
+
e.on("warning", (err) => console.error(c.yellow("! operator: " + err.message)));
|
|
1059
|
+
return e;
|
|
1060
|
+
};
|
|
1061
|
+
let endpoint = build();
|
|
1062
|
+
let live;
|
|
1063
|
+
let starting;
|
|
1064
|
+
let closed = false;
|
|
1065
|
+
const start = async () => {
|
|
1066
|
+
const e = endpoint;
|
|
1067
|
+
try {
|
|
1068
|
+
await e.start();
|
|
1069
|
+
}
|
|
1070
|
+
catch (err) {
|
|
1071
|
+
// Dropped quietly, the way the console drops a peer that never started, and stopped before
|
|
1072
|
+
// the next post may start its successor, so this one's offline record cannot land after the
|
|
1073
|
+
// successor's online one.
|
|
1074
|
+
e.removeAllListeners("error");
|
|
1075
|
+
e.removeAllListeners("warning");
|
|
1076
|
+
e.on("error", () => { });
|
|
1077
|
+
await e.stop().catch(() => undefined);
|
|
1078
|
+
endpoint = build();
|
|
1079
|
+
starting = undefined;
|
|
1080
|
+
throw err;
|
|
1081
|
+
}
|
|
1082
|
+
if (closed) {
|
|
1083
|
+
await e.stop();
|
|
1084
|
+
throw new Error(POSTER_STOPPED);
|
|
1085
|
+
}
|
|
1086
|
+
return (live = e);
|
|
1087
|
+
};
|
|
1088
|
+
return {
|
|
1089
|
+
operatorId: () => (operator || live ? endpoint.card.id : undefined),
|
|
1090
|
+
ensure() {
|
|
1091
|
+
if (closed)
|
|
1092
|
+
return Promise.reject(new Error(POSTER_STOPPED));
|
|
1093
|
+
starting ??= start();
|
|
1094
|
+
return starting;
|
|
1095
|
+
},
|
|
1096
|
+
expired: () => operator !== undefined && Date.now() >= operator.expiresAt,
|
|
1097
|
+
async stop() {
|
|
1098
|
+
closed = true;
|
|
1099
|
+
await starting?.catch(() => undefined);
|
|
1100
|
+
await live?.stop();
|
|
1101
|
+
},
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
/** Connects the dashboard and spends the account seed on its two write creds: the channel-purger
|
|
1105
|
+
* for channel delete, and the operator the dashboard posts as. The dashboard is a loopback HTTP
|
|
1106
|
+
* process and the seed can mint ANY identity or role, so the seed is bound only inside this
|
|
1107
|
+
* function and a request handler in {@link web} that reaches for it fails to compile. A narrowed
|
|
1108
|
+
* copy made inside `web()` would leave the full value in the handlers' scope beside it. Resolves
|
|
1109
|
+
* `undefined` in a parent that hands off to a `--detach` child. The mints come last, after that
|
|
1110
|
+
* hand-off and the pidfile claim, because the purger has no expiry and the operator lives 24 days,
|
|
1111
|
+
* and a process that detaches or is refused must not mint creds it then drops. `--creds` and open
|
|
1112
|
+
* meshes have no seed and purge with the connection's own creds; user mode mints a purger view
|
|
1113
|
+
* per delete instead. Posting is decided here too, and the operator poster built, so the operator
|
|
1114
|
+
* credential stays in this scope with the seed. An open mesh posts with no credential. */
|
|
668
1115
|
async function connectWithoutSeed(raw, values, host, port) {
|
|
669
1116
|
const { auth, ...conn } = await connectOrExit(values, "admin");
|
|
670
1117
|
const detachedRoot = process.env[DETACHED_ROOT_ENV];
|
|
@@ -683,12 +1130,18 @@ async function connectWithoutSeed(raw, values, host, port) {
|
|
|
683
1130
|
process.once("exit", () => releasePid(pidPath));
|
|
684
1131
|
}
|
|
685
1132
|
const purgeCreds = !user && auth ? await mintCreds(auth, newIdentity(), "channel-purger") : conn.creds;
|
|
686
|
-
|
|
1133
|
+
const post = postCapability(values.creds, user !== undefined);
|
|
1134
|
+
const operator = post.mode === "participant" && auth ? await mintOperatorCred(auth) : undefined;
|
|
1135
|
+
// The operator the dashboard posts as. Built here so its credential never enters `web()`'s scope,
|
|
1136
|
+
// where the request handlers are, and so its id is fixed for the process. It starts on the first
|
|
1137
|
+
// post, so it is not on the roster before then.
|
|
1138
|
+
const poster = post.mode === "participant" ? operatorPoster({ space: conn.space, server: conn.server, tls: conn.tls }, operator) : undefined;
|
|
1139
|
+
return { conn, user, pidPath, purgeCreds, post, poster };
|
|
687
1140
|
}
|
|
688
1141
|
/** A live observability dashboard for a space, served over HTTP + SSE. A read-only
|
|
689
|
-
* observer endpoint (invisible to peers) feeds the
|
|
690
|
-
* and a live message stream
|
|
691
|
-
* to a different host explicitly. */
|
|
1142
|
+
* observer endpoint (invisible to peers) feeds the React client in `dist/web` presence, channel
|
|
1143
|
+
* history and a live message stream, with no manager required. Bound to loopback unless the
|
|
1144
|
+
* operator opts in to a different host explicitly. */
|
|
692
1145
|
export async function web(args, lifecycle) {
|
|
693
1146
|
const values = args.values;
|
|
694
1147
|
// Validate the exposure coordinates before connecting to the broker or claiming local artifacts.
|
|
@@ -703,11 +1156,12 @@ export async function web(args, lifecycle) {
|
|
|
703
1156
|
// "channel-purger" view per action, so each destructive click is a fresh ledger check, and
|
|
704
1157
|
// `cotal actor revoke` kills the dashboard live (eviction) while a scope edit bites at the next
|
|
705
1158
|
// refresh.
|
|
706
|
-
const started = lifecycle
|
|
1159
|
+
const started = lifecycle
|
|
1160
|
+
? { conn: lifecycle.connection, user: undefined, pidPath: undefined, purgeCreds: undefined, post: { mode: "off", reason: POST_OFF_SERVICE }, poster: undefined }
|
|
707
1161
|
: await connectWithoutSeed(args.raw, values, host, port);
|
|
708
1162
|
if (!started)
|
|
709
1163
|
return;
|
|
710
|
-
const { conn, user, pidPath, purgeCreds } = started;
|
|
1164
|
+
const { conn, user, pidPath, purgeCreds, post, poster } = started;
|
|
711
1165
|
const { server, space } = conn;
|
|
712
1166
|
const sessionPath = !lifecycle && conn.root ? localProcessPath(WEB_SESSION_FILE, { root: conn.root, space }) : undefined;
|
|
713
1167
|
// Observer: never registers presence, never consumes an inbox — invisible to peers.
|
|
@@ -733,18 +1187,23 @@ export async function web(args, lifecycle) {
|
|
|
733
1187
|
ep.on("warning", (e) => console.error(c.yellow(lifecycle ? `! native dashboard endpoint reported a warning (${errorClassForLog(e)}); diagnostic body omitted` : "! " + e.message)));
|
|
734
1188
|
await ep.start();
|
|
735
1189
|
// The dashboard does not yet have a manager/session-store observer. Carry the absence as data so
|
|
736
|
-
//
|
|
1190
|
+
// the client can say so honestly without deriving progress from the heartbeat.
|
|
737
1191
|
const rosterSnapshot = () => ep.getRoster().map((presence) => ({
|
|
738
1192
|
...presence,
|
|
739
1193
|
progress: presence.status === "working" ? { kind: "unknown" } : undefined,
|
|
740
1194
|
}));
|
|
741
1195
|
const clients = new Set();
|
|
742
|
-
const send = (res, event, data) => res
|
|
1196
|
+
const send = (res, event, data, kind) => writeFeed(res, event, data, kind);
|
|
743
1197
|
const broadcast = (event, data) => {
|
|
744
1198
|
for (const res of clients)
|
|
745
1199
|
if (!res.writableEnded)
|
|
746
1200
|
send(res, event, data);
|
|
747
1201
|
};
|
|
1202
|
+
// Each open feed by the id its `hello` named, so a watch request can say which feed it is for.
|
|
1203
|
+
// A feed leaves this map, and every watch it held, when its connection closes.
|
|
1204
|
+
const feeds = new Map();
|
|
1205
|
+
const watchers = new SessionWatchers();
|
|
1206
|
+
const grantFor = eventsGrantFor(user ? "user" : conn.creds ? "static" : "open");
|
|
748
1207
|
// Presence changes → push the whole roster; the client just re-renders it.
|
|
749
1208
|
// Trailing-edge debounce: a stall-recovery replay is one burst of N keys, and pushing
|
|
750
1209
|
// per key would empty-to-fill the online-only sidebar once per key. Settle first.
|
|
@@ -787,27 +1246,27 @@ export async function web(args, lifecycle) {
|
|
|
787
1246
|
// allows exactly the MESSAGING plane (SPEC 13.9/13.11: chat + inst + svc, enumerated — never
|
|
788
1247
|
// the space-wide `>`, which would also plain-subscribe the v0.4 endpoint request rails), so
|
|
789
1248
|
// the tap is one subscription per plane.
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
1249
|
+
//
|
|
1250
|
+
// An agent's frames go only to the feeds watching that agent, and to none when nobody watches;
|
|
1251
|
+
// they are never broadcast as `message` (see `classifyTap`). Everything else is broadcast.
|
|
1252
|
+
const onTap = (subject, tapped) => {
|
|
1253
|
+
const verdict = classifyTap(subject, tapped);
|
|
1254
|
+
if (verdict === null)
|
|
793
1255
|
return;
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
// value was already parsed on the line above and was being dropped.
|
|
802
|
-
//
|
|
803
|
-
// Gated on kind, and the gate is load-bearing rather than defensive: `rest` is the channel only
|
|
804
|
-
// on the chat plane. On `inst` it is the RECIPIENT (`subjects.ts:599`) and on `svc` the route
|
|
805
|
-
// (`:603`), so forwarding it ungated would label a DM's recipient as a channel.
|
|
806
|
-
const channel = parsed?.kind === "chat" ? parsed.rest : undefined;
|
|
1256
|
+
if (verdict.event === "agent-frame") {
|
|
1257
|
+
for (const res of watchers.targets(verdict.agent))
|
|
1258
|
+
if (!res.writableEnded)
|
|
1259
|
+
send(res, "agent-frame", verdict.data);
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
const { mode, senderId, channel, msg } = verdict.data;
|
|
807
1263
|
broadcast("message", { mode, senderId, channel, msg });
|
|
808
1264
|
};
|
|
809
1265
|
for (const plane of ["chat", "inst", "svc"])
|
|
810
1266
|
ep.tap(onTap, { subject: `${spacePrefix(space)}.${plane}.>` });
|
|
1267
|
+
// The client build sits beside the compiled server in `dist/web`. Run from source, as the smokes
|
|
1268
|
+
// run it, the server lives in `src`, so the page is read from the package's `dist/web` instead.
|
|
1269
|
+
const client = clientAssets(join(here, basename(here) === "src" ? "../dist/web" : "web"));
|
|
811
1270
|
const gate = makeAuthGate(port, host);
|
|
812
1271
|
const handleRequest = async (req, res) => {
|
|
813
1272
|
const path = (req.url ?? "/").split("?")[0];
|
|
@@ -840,12 +1299,12 @@ export async function web(args, lifecycle) {
|
|
|
840
1299
|
});
|
|
841
1300
|
return void res.end();
|
|
842
1301
|
}
|
|
843
|
-
//
|
|
844
|
-
//
|
|
845
|
-
//
|
|
1302
|
+
// Only the `BODY_ROUTES` read a request body. Refuse an announced body before dispatch
|
|
1303
|
+
// everywhere else, so the next no-body route inherits the same bound instead of silently
|
|
1304
|
+
// letting Node drain an upload the handler will never inspect.
|
|
846
1305
|
const declared = Number(req.headers["content-length"]);
|
|
847
1306
|
const announcedBody = declared > 0 || req.headers["transfer-encoding"] !== undefined;
|
|
848
|
-
const noBodyRoute = path
|
|
1307
|
+
const noBodyRoute = !BODY_ROUTES.has(path) || req.method !== "POST";
|
|
849
1308
|
if (noBodyRoute && announcedBody)
|
|
850
1309
|
throw noBody(path, declared);
|
|
851
1310
|
if (path === "/feed") {
|
|
@@ -855,20 +1314,31 @@ export async function web(args, lifecycle) {
|
|
|
855
1314
|
connection: "keep-alive",
|
|
856
1315
|
});
|
|
857
1316
|
clients.add(res);
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
void
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
.
|
|
866
|
-
|
|
867
|
-
|
|
1317
|
+
// The feed's opening state, written as snapshots: a big mesh's roster may be larger than the
|
|
1318
|
+
// ceiling on its own, and holding it to the ceiling would end every new feed at once.
|
|
1319
|
+
const feed = randomUUID();
|
|
1320
|
+
feeds.set(feed, res);
|
|
1321
|
+
void writeOpening((event, data, kind) => send(res, event, data, kind), {
|
|
1322
|
+
feed,
|
|
1323
|
+
roster: rosterSnapshot(),
|
|
1324
|
+
presenceView: ep.presenceView(),
|
|
1325
|
+
membership: () => ep.readMembership(),
|
|
1326
|
+
});
|
|
1327
|
+
// Both ends, because either can end a feed: the browser going away closes the request, and
|
|
1328
|
+
// an overflow ends the response while the socket may stay open. Forgetting twice is harmless.
|
|
1329
|
+
const forget = () => {
|
|
1330
|
+
clients.delete(res);
|
|
1331
|
+
feeds.delete(feed);
|
|
1332
|
+
watchers.drop(res);
|
|
1333
|
+
};
|
|
1334
|
+
req.on("close", forget);
|
|
1335
|
+
res.on("close", forget);
|
|
868
1336
|
return;
|
|
869
1337
|
}
|
|
870
|
-
if (path === WEB_READINESS_PATH)
|
|
871
|
-
|
|
1338
|
+
if (path === WEB_READINESS_PATH) {
|
|
1339
|
+
const operatorId = poster?.operatorId();
|
|
1340
|
+
return json(res, { space, pid: process.pid, post, channelDeleteSupported: lifecycle === undefined, ...(operatorId ? { operatorId } : {}) });
|
|
1341
|
+
}
|
|
872
1342
|
if (path === "/api/roster")
|
|
873
1343
|
return json(res, rosterSnapshot());
|
|
874
1344
|
if (path === "/api/membership") {
|
|
@@ -960,8 +1430,8 @@ export async function web(args, lifecycle) {
|
|
|
960
1430
|
// named 503 lets the open channel keep the messages it already has and say they are stale,
|
|
961
1431
|
// which beats a page that arrives after the reader gave up. Measured on a modelled link
|
|
962
1432
|
// before this existed: 11360ms here, on a link where `/api/dms` already refused at 8005ms.
|
|
963
|
-
// The
|
|
964
|
-
// channel holding the view open indefinitely.
|
|
1433
|
+
// The client re-reads this route for the open channel on every poll, so an unbounded read
|
|
1434
|
+
// here is one slow channel holding the view open indefinitely.
|
|
965
1435
|
const clock = deadline(AGGREGATION_DEADLINE_MS);
|
|
966
1436
|
try {
|
|
967
1437
|
const page = await within(ep.channelHistory(name, { limit, signal: clock.signal }).catch((e) => {
|
|
@@ -978,8 +1448,52 @@ export async function web(args, lifecycle) {
|
|
|
978
1448
|
clock.done();
|
|
979
1449
|
}
|
|
980
1450
|
}
|
|
981
|
-
//
|
|
982
|
-
//
|
|
1451
|
+
// One agent's session: watch and unwatch its live frames on one feed, and read its history.
|
|
1452
|
+
// `<id>` is the roster id, `<owner>.<actor>`, percent-encoded, so a raw `/` never belongs to it.
|
|
1453
|
+
if (path.startsWith("/api/agents/")) {
|
|
1454
|
+
const rest = path.slice("/api/agents/".length);
|
|
1455
|
+
const cut = rest.lastIndexOf("/");
|
|
1456
|
+
const action = cut === -1 ? "" : rest.slice(cut + 1);
|
|
1457
|
+
if ((action === "watch" || action === "unwatch") && req.method === "POST") {
|
|
1458
|
+
// No body, so these stay out of `BODY_ROUTES`, and they change no mesh state: a watch is a
|
|
1459
|
+
// row in this process's map, which the feed's close removes.
|
|
1460
|
+
const agent = agentIdFromPath(rest.slice(0, cut));
|
|
1461
|
+
const feedId = query.get("feed");
|
|
1462
|
+
if (!feedId)
|
|
1463
|
+
throw new BadRequest("feed required: the id the feed's hello event named");
|
|
1464
|
+
const feed = feeds.get(feedId);
|
|
1465
|
+
if (feed === undefined)
|
|
1466
|
+
throw new BadRequest(`feed ${quoteForOperator(feedId)} is not an open feed`);
|
|
1467
|
+
if (action === "watch")
|
|
1468
|
+
watchers.watch(agent.id, feed);
|
|
1469
|
+
else
|
|
1470
|
+
watchers.unwatch(agent.id, feed);
|
|
1471
|
+
res.writeHead(204).end();
|
|
1472
|
+
return;
|
|
1473
|
+
}
|
|
1474
|
+
if (action === "events") {
|
|
1475
|
+
// A read, so GET only. Any other method is named as refused, never answered as a read.
|
|
1476
|
+
if (req.method !== "GET") {
|
|
1477
|
+
res.writeHead(405, { "content-type": "application/json", allow: "GET" });
|
|
1478
|
+
return void res.end(JSON.stringify({ error: "GET only" }));
|
|
1479
|
+
}
|
|
1480
|
+
const agent = agentIdFromPath(rest.slice(0, cut));
|
|
1481
|
+
const limit = historyLimit(query, 200);
|
|
1482
|
+
// BOUNDED LIKE ITS SIBLINGS, with their wording: a late read and a failed one are 503s
|
|
1483
|
+
// that say which, while a refusal is an answer the session view shows as it came.
|
|
1484
|
+
try {
|
|
1485
|
+
return json(res, await agentEventsPage(ep, agent, limit, grantFor));
|
|
1486
|
+
}
|
|
1487
|
+
catch (e) {
|
|
1488
|
+
if (e instanceof AgentEventsLate)
|
|
1489
|
+
return json(res, { error: `${agent.id} events: the read did not finish within ${AGGREGATION_DEADLINE_MS}ms` }, 503);
|
|
1490
|
+
return json(res, { error: `${agent.id} events: the read failed: ${e instanceof Error ? e.message : String(e)}` }, 503);
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
// Delete a channel and its content. A write path, so it's POST-gated. The client reaches it
|
|
1495
|
+
// only through the controller's `deleteChannel`; nothing in the phase 1 shell calls that yet, and the operator's confirm
|
|
1496
|
+
// arrives with the phase 2 UI. Purges with the
|
|
983
1497
|
// channel-purger cred minted at startup (auth mode), the connection creds (open / --creds) or a
|
|
984
1498
|
// per-delete channel-purger view (user mode), never the account seed. A wildcard / missing
|
|
985
1499
|
// channel is a 400.
|
|
@@ -1019,17 +1533,28 @@ export async function web(args, lifecycle) {
|
|
|
1019
1533
|
return;
|
|
1020
1534
|
}
|
|
1021
1535
|
}
|
|
1022
|
-
|
|
1023
|
-
if (
|
|
1536
|
+
// Post as the operator: a message to one channel, or a DM to one roster member.
|
|
1537
|
+
if (path === "/api/send" && req.method === "POST") {
|
|
1538
|
+
const answer = await sendAsOperator(post, poster, (id) => ep.getRoster().some((p) => p.card.id === id), () => readBody(req));
|
|
1539
|
+
return json(res, answer.body, answer.status);
|
|
1540
|
+
}
|
|
1541
|
+
const answer = clientResponse(client, path);
|
|
1542
|
+
if (answer.status === 200) {
|
|
1543
|
+
const { file } = answer;
|
|
1024
1544
|
// Read before the status line: a read that throws after `writeHead` reaches the catch below
|
|
1025
1545
|
// with the 200 already sent, and the browser runs an empty file as a success.
|
|
1026
1546
|
const body = readFileSync(file.path);
|
|
1027
|
-
//
|
|
1028
|
-
//
|
|
1029
|
-
res.writeHead(200, {
|
|
1547
|
+
// The page revalidates on every load so a `cotal` upgrade's new client is picked up; the
|
|
1548
|
+
// hashed assets never change under their name, so they cache for good.
|
|
1549
|
+
res.writeHead(200, {
|
|
1550
|
+
"content-type": file.type,
|
|
1551
|
+
"cache-control": file.immutable ? "public, max-age=31536000, immutable" : "no-cache",
|
|
1552
|
+
});
|
|
1030
1553
|
res.end(body);
|
|
1031
1554
|
return;
|
|
1032
1555
|
}
|
|
1556
|
+
if (answer.status === 503)
|
|
1557
|
+
return json(res, answer.body, 503);
|
|
1033
1558
|
res.writeHead(404).end("not found");
|
|
1034
1559
|
};
|
|
1035
1560
|
// A route handler talks to the broker, so ANY of them can reject — a JetStream request that
|
|
@@ -1042,9 +1567,9 @@ export async function web(args, lifecycle) {
|
|
|
1042
1567
|
const httpServer = createServer((req, res) => {
|
|
1043
1568
|
void handleRequest(req, res).catch((e) => {
|
|
1044
1569
|
const why = e instanceof Error ? e.message : String(e);
|
|
1045
|
-
// A caller error and a server fault are different facts and must not share a status
|
|
1046
|
-
// malformed query
|
|
1047
|
-
const status = e instanceof PayloadTooLarge ? 413 : e instanceof BadRequest ? 400 : 500;
|
|
1570
|
+
// A caller error and a server fault are different facts and must not share a status. Before
|
|
1571
|
+
// this split, a malformed query read in the log exactly like the dashboard breaking.
|
|
1572
|
+
const status = e instanceof PayloadTooLarge ? 413 : e instanceof BadRequest ? 400 : e instanceof BrokerRefused ? 502 : 500;
|
|
1048
1573
|
const caller = status < 500;
|
|
1049
1574
|
console.error(c[caller ? "yellow" : "red"](lifecycle ? `native dashboard request ${caller ? "refused" : "failed"}; diagnostic body omitted` : `${caller ? "~" : "!"} ${req.method ?? "GET"} ${requestTargetForLog(req, gate.launchToken)} ${caller ? "refused" : "failed"}: ${why}`));
|
|
1050
1575
|
if (res.headersSent)
|
|
@@ -1152,6 +1677,7 @@ export async function web(args, lifecycle) {
|
|
|
1152
1677
|
await new Promise((resolve, reject) => httpServer.close((error) => error ? reject(error) : resolve()));
|
|
1153
1678
|
else
|
|
1154
1679
|
httpServer.close();
|
|
1680
|
+
await poster?.stop().catch(reportEndpoint);
|
|
1155
1681
|
await ep.stop();
|
|
1156
1682
|
if (pidPath)
|
|
1157
1683
|
releasePid(pidPath);
|