@awebai/oats 0.49.0 → 0.51.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/lib/servers.mjs CHANGED
@@ -26,6 +26,7 @@ import { noteRuntimeName } from "./deprecation.mjs";
26
26
  import { readWaitingClaim } from "./instance-events.mjs";
27
27
  import { withDirLock } from "./dir-lock.mjs";
28
28
  import { shellWord } from "./core.mjs";
29
+ import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
29
30
 
30
31
  const OATS_HOME_DIR = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
31
32
  export const SERVERS_FILE = () => join(OATS_HOME_DIR(), "servers.json");
@@ -921,8 +922,10 @@ export function resolveRoute(serverId, { instance, home } = {}, what = "session"
921
922
  if (home && !snap) snap = listSnapshots(serverId).find((s) => s.home && resolve(s.home) === resolve(home));
922
923
  if (instance && snap && snap.instance !== instance) throw serverError("E_HOME_MISMATCH", `--home ${home} is the saved route of ${snap.instance} on ${serverId}, not of ${instance}`);
923
924
  if (instance && !snap && home && basename(home) !== instance) throw serverError("E_HOME_MISMATCH", `--home ${home} is not the home of instance ${instance}`);
924
- const remoteHome = home || snap?.home || (instance ? instanceOnHost(serverId, instance, io).home : undefined);
925
925
  const target = snap?.target || targetOf(io.server || getServer(serverId));
926
+ // `io.beforeRoster(target)`: what a caller must establish about the host before this route asks
927
+ // it anything (a keyed attach's feature gate). It runs only when the roster is about to be read.
928
+ const remoteHome = home || snap?.home || (instance ? (io.beforeRoster?.(target), instanceOnHost(serverId, instance, io).home) : undefined);
926
929
  if (!remoteHome || !String(remoteHome).startsWith("/")) throw serverError("E_BAD_ARGS", `${what} --server needs --instance <name> or --home </absolute/remote/home>`);
927
930
  return { target, home: remoteHome, snapshot: snap };
928
931
  }
@@ -1162,11 +1165,24 @@ export function scheduleRemote(serverId, oatsArgs, io = {}) {
1162
1165
  return { envelope: envelope.ok ? { ...envelope, result: { ...envelope.result, server: serverId } } : envelope, stderr, target };
1163
1166
  }
1164
1167
 
1165
- export function attachArgv(serverId, { instance, home } = {}, io = {}) {
1168
+ export function attachArgv(serverId, { instance, home, detachKey } = {}, io = {}) {
1166
1169
  io = { ...io, serverId };
1167
- const { target, home: remoteHome } = resolveRoute(serverId, { instance, home }, "session attach", io);
1170
+ const keyed = detachKey !== undefined;
1171
+ // A detach key is checked before anything is asked of the host.
1172
+ if (keyed) requireDetachKey(detachKey);
1173
+ // A kernel without the feature ignores the flag and opens a viewer no key leaves. So with a key
1174
+ // the probe always runs, under `skipVersionCheck` (--print) too: a printed argv is run as it is.
1175
+ // A host without the feature is sent the probe and nothing else: the gate comes before a name
1176
+ // is resolved through the host's roster, and before the `session` check, whose hint reads the
1177
+ // roster too. The probe is asked once (checkRemote keeps it).
1178
+ const requireDetachKeyRemote = (target) => {
1179
+ const remote = checkRemote(target, io);
1180
+ if (!remote.features.includes(DETACH_KEY_FEATURE)) throw Object.assign(serverError("E_REMOTE_INCOMPATIBLE", `remote oats ${remote.version} at ${target.sshHost} does not advertise ${DETACH_KEY_FEATURE}; upgrade it there, or attach without --detach-key; nothing was sent`), { details: { feature: DETACH_KEY_FEATURE } });
1181
+ };
1182
+ const { target, home: remoteHome } = resolveRoute(serverId, { instance, home }, "session attach", keyed ? { ...io, beforeRoster: requireDetachKeyRemote } : io);
1183
+ if (keyed) requireDetachKeyRemote(target);
1168
1184
  if (!io.skipVersionCheck) requireSessionRemote(target, io, remoteHome);
1169
- const [bin, ...rest] = sshArgv(target, ["session", "attach", "--home", remoteHome], { control: controlUsable(target, io) });
1185
+ const [bin, ...rest] = sshArgv(target, ["session", "attach", "--home", remoteHome, ...(detachKey !== undefined ? ["--detach-key", detachKey] : [])], { control: controlUsable(target, io) });
1170
1186
  // -t: allocate a PTY; placed before `--` with the other ssh options.
1171
1187
  return { argv: [bin, "-t", ...rest], target, home: remoteHome };
1172
1188
  }
@@ -3,7 +3,41 @@ import { execFileSync, spawn } from "node:child_process";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { inspectSessionTarget } from "./session-input.mjs";
5
5
 
6
- export function prepareSessionViewer(target, { exec = execFileSync } = {}) {
6
+ /** The kernel feature of `session attach --detach-key` (docs/execution-targets.md, "Inspect,
7
+ * input and attach"): a routed attach sends the flag only to a host that advertises it. */
8
+ export const DETACH_KEY_FEATURE = "session-attach-detach-key";
9
+ /** The status of an attach its detach key ended. Answered only when the key's own binding ran. */
10
+ export const SESSION_DETACHED_EXIT = 20;
11
+ /** The closed grammar of a detach key: Control with a letter other than h, i and m, or one of
12
+ * \ ] ^ _, Meta with a lowercase letter or a digit, or F1 to F12 with at most one modifier.
13
+ * Outside it: C-i and C-m (Tab and Enter), C-h (the byte many terminals send for
14
+ * Ctrl+Backspace, and some for Backspace: not one key everywhere), Escape (C-[), the ESC + C1
15
+ * introducers (M-[, M-], M-\, M-O: a terminal's reply can arrive as one), `Any` and the mouse
16
+ * key names. A closed grammar can be widened later and never narrowed. */
17
+ const DETACH_KEY = /^(?:C-[a-gj-ln-z\\\]^_]|M-[a-z0-9]|(?:[CMS]-)?F(?:[1-9]|1[0-2]))$/;
18
+ /** Whether a value is one detach key: the local and the routed attach both ask here. */
19
+ export function isDetachKey(value) { return typeof value === "string" && DETACH_KEY.test(value); }
20
+ /** The key, or E_BAD_ARGS: called before any tmux or ssh call. */
21
+ export function requireDetachKey(value) {
22
+ if (isDetachKey(value)) return value;
23
+ throw Object.assign(new Error(`--detach-key must be one key: C-<a letter except h, i and m, or one of \\ ] ^ _>, M-<a lowercase letter or digit>, or F1 to F12 with at most one of C-, M-, S- (got ${JSON.stringify(value)})`), { code: "E_BAD_ARGS" });
24
+ }
25
+
26
+ /** The table of a viewer without a detach key: one for the whole tmux server, emptied and bound
27
+ * again by each such viewer. */
28
+ const LOCKED_TABLE = "oatsview-locked";
29
+ /** The mouse bindings of a viewer's key table, the locked one or a keyed viewer's own. */
30
+ const MOUSE_BINDINGS = [
31
+ ["WheelUpPane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -e; send-keys -M"],
32
+ ["MouseDrag1Pane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -M"],
33
+ ];
34
+ /** What a detach key runs, as ONE bind-key argument (a bare `;` argument would end bind-key and
35
+ * run the rest at once): mark the viewer session, then detach the client that pressed the key.
36
+ * A constant: no caller text is ever part of a tmux command string. */
37
+ const DETACH_BINDING = "set-option @oats-detached 1 ; detach-client";
38
+
39
+ export function prepareSessionViewer(target, { exec = execFileSync, detachKey } = {}) {
40
+ if (detachKey !== undefined) requireDetachKey(detachKey);
7
41
  if (!inspectSessionTarget(target, { exec }).present) throw new Error("session no longer exists");
8
42
  // UTF-8 mode (-u) like the shared session helper: a service without a
9
43
  // UTF-8 locale (launchd) otherwise mangles tmux output.
@@ -11,7 +45,15 @@ export function prepareSessionViewer(target, { exec = execFileSync } = {}) {
11
45
  encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "pipe"],
12
46
  }).trim();
13
47
  const viewer = `oatsview-${process.pid}-${randomUUID().slice(0, 8)}`;
14
- const cleanup = () => { try { run(["kill-session", "-t", `=${viewer}`]); } catch { /* already detached/ended */ } };
48
+ // A keyed viewer reads a table of its own, named as its session: a binding in the locked table
49
+ // would be every viewer's, and the next viewer's unbind would remove it.
50
+ const table = detachKey === undefined ? LOCKED_TABLE : viewer;
51
+ const cleanup = () => {
52
+ try { run(["kill-session", "-t", `=${viewer}`]); } catch { /* already detached/ended */ }
53
+ // A key table belongs to the tmux server and outlives the session; tmux drops it with its
54
+ // last binding.
55
+ if (table !== LOCKED_TABLE) { try { run(["unbind-key", "-a", "-q", "-T", table]); } catch { /* the server is gone */ } }
56
+ };
15
57
  try {
16
58
  const placeholder = run(["new-session", "-d", "-s", viewer, "-P", "-F", "#{window_id}"]);
17
59
  if (!/^@\d+$/.test(placeholder)) throw new Error("tmux returned no viewer window id");
@@ -20,33 +62,68 @@ export function prepareSessionViewer(target, { exec = execFileSync } = {}) {
20
62
  // One linked window prevents a stale viewer from selecting a sibling agent
21
63
  // when this agent retires. Disable window navigation in the viewer only.
22
64
  for (const name of ["prefix", "prefix2"]) run(["set-option", "-t", viewer, name, "None"]);
23
- run(["set-option", "-t", viewer, "key-table", "oatsview-locked"]);
65
+ run(["set-option", "-t", viewer, "key-table", table]);
24
66
  // The viewer shows one agent; its status line only repeats that name.
25
67
  // Session-scoped on the temporary viewer: the agents' own session and
26
68
  // the operator's tmux settings are untouched.
27
69
  run(["set-option", "-t", viewer, "status", "off"]);
28
- run(["unbind-key", "-a", "-q", "-T", "oatsview-locked"]);
29
- run(["bind-key", "-T", "oatsview-locked", "WheelUpPane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -e; send-keys -M"]);
30
- run(["bind-key", "-T", "oatsview-locked", "MouseDrag1Pane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -M"]);
70
+ run(["unbind-key", "-a", "-q", "-T", table]);
71
+ for (const binding of MOUSE_BINDINGS) run(["bind-key", "-T", table, ...binding]);
72
+ // The key is its own argv element, after the grammar admitted it.
73
+ if (detachKey !== undefined) run(["bind-key", "-T", table, detachKey, DETACH_BINDING]);
31
74
  run(["set-option", "-t", viewer, "mouse", "on"]);
32
75
  const env = { ...process.env }; delete env.TMUX;
33
- return { binary: "tmux", args: ["-u", "-S", target.socket, "attach-session", "-t", `=${viewer}`], env, cleanup };
76
+ /** Whether the detach key's binding ran: it marks the viewer session before it detaches. A
77
+ * client that left any other way (its window ended, another client detached it) left no
78
+ * mark, and a session that is gone answers nothing. The target is `=<session>:`:
79
+ * show-options reads -t as a pane, and under -q answers nothing at all for `=<session>`. */
80
+ const detached = () => {
81
+ if (detachKey === undefined) return false;
82
+ try { return run(["show-options", "-t", `=${viewer}:`, "-qv", "@oats-detached"]) === "1"; } catch { return false; }
83
+ };
84
+ return { binary: "tmux", args: ["-u", "-S", target.socket, "attach-session", "-t", `=${viewer}`], env, cleanup, detached };
34
85
  } catch (e) { cleanup(); throw e; }
35
86
  }
36
87
 
37
- export async function attachSessionTarget(target) {
38
- const viewer = prepareSessionViewer(target);
88
+ // SIGQUIT under a keyed attach. The key may be C-\, the tty's QUIT character: pressed before the
89
+ // tmux client has taken the tty, or again once the client has given it back, it reaches this
90
+ // process as SIGQUIT, whose default action ends Node before any `finally` (status 131, the viewer
91
+ // session and its table left on the server). One listener, added by the first keyed attach and
92
+ // never removed, calls whatever the attach in progress set.
93
+ let onQuit = null;
94
+ let quitHeld = false;
95
+ function holdQuit() {
96
+ if (quitHeld) return;
97
+ quitHeld = true;
98
+ process.on("SIGQUIT", () => onQuit?.());
99
+ }
100
+
101
+ /** Attach this terminal to a viewer of the target and answer the client's status, or
102
+ * SESSION_DETACHED_EXIT when `detachKey` was given and ended the attach. */
103
+ export async function attachSessionTarget(target, { detachKey } = {}) {
104
+ if (detachKey !== undefined) { requireDetachKey(detachKey); holdQuit(); }
105
+ const viewer = prepareSessionViewer(target, { detachKey });
39
106
  let child;
107
+ let quit = false;
40
108
  const stop = () => { viewer.cleanup(); child?.kill(); };
41
109
  const signals = ["SIGHUP", "SIGTERM", "SIGINT"];
42
110
  for (const sig of signals) process.on(sig, stop);
111
+ // Until the client has exited, a QUIT stops the attach as the other signals do, with status 1.
112
+ // Unless the key's binding has already run: then the client is on its way out, the QUIT is the
113
+ // key pressed again, and the attach ends as a detach.
114
+ if (detachKey !== undefined) onQuit = () => { if (viewer.detached()) return; quit = true; stop(); };
43
115
  try {
44
- return await new Promise((resolve, reject) => {
116
+ const code = await new Promise((resolve, reject) => {
45
117
  child = spawn(viewer.binary, viewer.args, { env: viewer.env, stdio: "inherit" });
46
118
  child.once("error", reject);
47
119
  child.once("exit", (code) => resolve(code ?? 1));
48
120
  });
121
+ if (quit) return 1;
122
+ return viewer.detached() ? SESSION_DETACHED_EXIT : code;
49
123
  } finally {
124
+ // The client has exited (or never started): a QUIT from here on changes nothing. One that
125
+ // arrives during the calls below waits for them, so cleanup completes and the status stands.
126
+ onQuit = null;
50
127
  for (const sig of signals) process.removeListener(sig, stop);
51
128
  viewer.cleanup();
52
129
  }
@@ -0,0 +1,234 @@
1
+ /** A capability manifest's trigger sources (`triggerSources`, #669; docs/capabilities.md "Trigger sources"):
2
+ * the use-time validator. A source is one of the capability's own commands that, at each poll, lists the
3
+ * events due now; the kernel keeps everything after that (lib/triggers.mjs).
4
+ *
5
+ * Containment (the trigger-as-gate decision): a malformed `triggerSources` never refuses the capability. This
6
+ * module is called only where a source is used — `trigger add`, a poll, `trigger test`, `trigger poll` and
7
+ * `capabilities show` — and never from manifestContractProblems, the manifest loader, discovery or the lock:
8
+ * a trigger naming a malformed source fails E_TRIGGER_SOURCE, and nothing else changes.
9
+ *
10
+ * Validity is per source: a problem inside one source disables only that source; a malformed top level (not an
11
+ * object, more than MAX_SOURCES) disables every source. docs/capability-manifest.schema.json carries the same
12
+ * closed shape; what JSON Schema cannot say (a pattern compiles, `command` names one of `commands`, a parameter
13
+ * default matches its pattern) is checked here only.
14
+ *
15
+ * Patterns compile once, with the `u` flag: the flag JSON Schema's `pattern` uses (Ajv compiles with it), so
16
+ * an author's pattern means the same in the published schema's tooling and here. Every pattern is anchored:
17
+ * it is wrapped as `^(?:…)$`, which leaves an already anchored pattern's meaning unchanged and anchors one
18
+ * like `^a|b$` whose alternatives are not. */
19
+
20
+ import { REFUSED_TEXT, safeText } from "./refused-text.mjs";
21
+
22
+ export const SOURCE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
23
+ /** A parameter value, when the parameter declares no pattern. */
24
+ export const DEFAULT_PARAM_PATTERN = "^[A-Za-z0-9._/:@ ,*-]{0,200}$";
25
+ /** A field value, when the field declares no pattern. */
26
+ export const DEFAULT_FIELD_PATTERN = "^[A-Za-z0-9._/:@-]{1,200}$";
27
+ const MAX_SOURCES = 16, MAX_EVENTS = 16, MAX_PARAMETERS = 16, MAX_FIELDS = 16, MAX_URL_HOSTS = 16, TEXT_MAX = 200;
28
+ const EVENT_RE = /^[a-z][a-z0-9_]{0,39}$/;
29
+ const NAME_RE = /^[a-zA-Z][a-zA-Z0-9_]{0,39}$/;
30
+ /** An exact lowercase hostname: no scheme, port, wildcard or trailing dot. */
31
+ const HOST_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
32
+ /** One line: no control character (C0, DEL, C1) and no line or paragraph separator. */
33
+ const ONE_LINE_RE = /^[^\p{Cc}\u2028\u2029]*$/u;
34
+ const SOURCE_KEYS = ["command", "description", "events", "parameters", "fields", "urlHosts"];
35
+ const PARAMETER_KEYS = ["required", "default", "description", "pattern"];
36
+ const FIELD_KEYS = ["pattern"];
37
+
38
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
39
+ const chars = (s) => [...s].length;
40
+ /** An RFC 6901 pointer from its reference tokens. */
41
+ const pointerOf = (...tokens) => tokens.map((t) => `/${String(t).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
42
+ const oneLine = (v) => typeof v === "string" && chars(v) <= TEXT_MAX && ONE_LINE_RE.test(v);
43
+ /** `src` compiled and anchored, or null when it does not compile. */
44
+ function compile(src) {
45
+ try { return new RegExp(`^(?:${src})$`, "u"); } catch { return null; }
46
+ }
47
+
48
+ /** Validate one source. → the normalized source, or null after pushing its problems. */
49
+ function checkSource(manifest, name, decl, problems) {
50
+ const at = (...tokens) => pointerOf("triggerSources", name, ...tokens);
51
+ const bad = (pointer, message) => problems.push({ source: name, pointer, message: `trigger source ${JSON.stringify(name)}: ${message}` });
52
+ if (!SOURCE_NAME_RE.test(name)) bad(at(), "the name must be 1 to 40 lowercase letters, digits and dashes, starting with a letter or digit");
53
+ if (!isObject(decl)) { bad(at(), "must be an object { command, events, description?, parameters?, fields?, urlHosts? }"); return null; }
54
+ for (const k of Object.keys(decl)) if (!SOURCE_KEYS.includes(k)) bad(at(k), `unknown key ${JSON.stringify(k)} (allowed: ${SOURCE_KEYS.join(", ")})`);
55
+
56
+ const commands = isObject(manifest.commands) ? manifest.commands : {};
57
+ const spec = typeof decl.command === "string" && Object.hasOwn(commands, decl.command) ? commands[decl.command] : undefined;
58
+ if (typeof decl.command !== "string" || !decl.command) bad(at("command"), "command must name one of the manifest's commands");
59
+ else if (typeof spec !== "string" || !spec.trim()) bad(at("command"), `command ${JSON.stringify(decl.command)} is not one of the manifest's commands`);
60
+
61
+ if (decl.description !== undefined && !oneLine(decl.description)) bad(at("description"), `description must be one line of at most ${TEXT_MAX} characters`);
62
+
63
+ const events = decl.events;
64
+ if (!Array.isArray(events) || events.length < 1 || events.length > MAX_EVENTS) bad(at("events"), `events must list 1 to ${MAX_EVENTS} event names`);
65
+ else {
66
+ events.forEach((e, i) => { if (typeof e !== "string" || !EVENT_RE.test(e)) bad(at("events", i), "an event name is 1 to 40 lowercase letters, digits and underscores, starting with a letter"); });
67
+ events.forEach((e, i) => { if (events.indexOf(e) !== i) bad(at("events", i), `event ${JSON.stringify(e)} is listed twice`); });
68
+ }
69
+
70
+ /** A declared pattern (or `fallback`), compiled. */
71
+ const patternAt = (value, pointer, fallback) => {
72
+ if (value === undefined) return compile(fallback);
73
+ if (typeof value !== "string" || !value) { bad(pointer, "pattern must be a non-empty regular expression"); return null; }
74
+ const re = compile(value);
75
+ if (!re) bad(pointer, `pattern ${JSON.stringify(value)} is not a valid regular expression`);
76
+ return re;
77
+ };
78
+ /** A named map (parameters, fields): at most `max` entries, each an object of `keys`. */
79
+ const namedMap = (key, max, keys, each) => {
80
+ const map = decl[key];
81
+ if (map === undefined) return {};
82
+ if (!isObject(map)) { bad(at(key), `${key} must be an object of named entries`); return null; }
83
+ const names = Object.keys(map);
84
+ if (names.length > max) bad(at(key), `at most ${max} ${key}`);
85
+ const out = {};
86
+ for (const n of names) {
87
+ if (!NAME_RE.test(n)) bad(at(key, n), `${JSON.stringify(n)} is not a valid name (a letter, then letters, digits and underscores, at most 40)`);
88
+ const entry = map[n];
89
+ if (!isObject(entry)) { bad(at(key, n), `must be an object with only ${keys.join(", ")}`); continue; }
90
+ for (const k of Object.keys(entry)) if (!keys.includes(k)) bad(at(key, n, k), `unknown key ${JSON.stringify(k)} (allowed: ${keys.join(", ")})`);
91
+ out[n] = each(n, entry);
92
+ }
93
+ return out;
94
+ };
95
+ const parameters = namedMap("parameters", MAX_PARAMETERS, PARAMETER_KEYS, (n, p) => {
96
+ if (p.required !== undefined && typeof p.required !== "boolean") bad(at("parameters", n, "required"), "required must be true or false");
97
+ if (p.description !== undefined && !oneLine(p.description)) bad(at("parameters", n, "description"), `description must be one line of at most ${TEXT_MAX} characters`);
98
+ const pattern = patternAt(p.pattern, at("parameters", n, "pattern"), DEFAULT_PARAM_PATTERN);
99
+ if (p.default !== undefined) {
100
+ if (typeof p.default !== "string" || chars(p.default) > TEXT_MAX) bad(at("parameters", n, "default"), `default must be a string of at most ${TEXT_MAX} characters`);
101
+ else if (pattern && !pattern.test(p.default)) bad(at("parameters", n, "default"), `default ${JSON.stringify(p.default)} does not match the parameter's pattern`);
102
+ }
103
+ return { required: p.required === true, default: typeof p.default === "string" ? p.default : null, description: typeof p.description === "string" ? p.description : null, pattern };
104
+ });
105
+ const fields = namedMap("fields", MAX_FIELDS, FIELD_KEYS, (n, f) => ({ pattern: patternAt(f.pattern, at("fields", n, "pattern"), DEFAULT_FIELD_PATTERN) }));
106
+
107
+ const hosts = decl.urlHosts === undefined ? [] : decl.urlHosts;
108
+ if (!Array.isArray(hosts) || hosts.length > MAX_URL_HOSTS) bad(at("urlHosts"), `urlHosts must list at most ${MAX_URL_HOSTS} hostnames`);
109
+ else hosts.forEach((h, i) => {
110
+ if (typeof h !== "string" || h.length > 253 || !HOST_RE.test(h)) bad(at("urlHosts", i), "a URL host is an exact lowercase hostname (no scheme, port or wildcard)");
111
+ else if (hosts.indexOf(h) !== i) bad(at("urlHosts", i), `host ${JSON.stringify(h)} is listed twice`);
112
+ });
113
+
114
+ if (problems.length) return null;
115
+ const [script, ...args] = spec.trim().split(/\s+/);
116
+ return { name, command: decl.command, script, args, description: decl.description ?? null, events: [...events], parameters, fields, urlHosts: [...hosts] };
117
+ }
118
+
119
+ /** A manifest's trigger sources, validated where they are used. Never throws, whatever `manifest` is.
120
+ * → { sources: { <name>: { name, command, script, args, description, events, parameters: { <p>: { required,
121
+ * default, description, pattern } }, fields: { <f>: { pattern } }, urlHosts } }, problems: [{ source, pointer,
122
+ * message }] } — `sources` holds only the well-formed sources; `source` is null for a top-level problem. */
123
+ export function triggerSourcesOf(manifest) {
124
+ const out = { sources: {}, problems: [] };
125
+ const decl = isObject(manifest) ? manifest.triggerSources : undefined;
126
+ if (decl === undefined) return out;
127
+ if (!isObject(decl)) { out.problems.push({ source: null, pointer: "/triggerSources", message: "triggerSources must be an object of named trigger sources" }); return out; }
128
+ const names = Object.keys(decl);
129
+ if (names.length > MAX_SOURCES) { out.problems.push({ source: null, pointer: "/triggerSources", message: `triggerSources declares ${names.length} sources; at most ${MAX_SOURCES}` }); return out; }
130
+ for (const name of names) {
131
+ const problems = [];
132
+ const source = checkSource(manifest, name, decl[name], problems);
133
+ if (source) out.sources[name] = source;
134
+ else out.problems.push(...problems);
135
+ }
136
+ return out;
137
+ }
138
+
139
+ // ------------------------------------------------------------ the wire (docs/capabilities.md "Trigger sources")
140
+
141
+ /** At most this many events, and skipped items, in one answer (more is `too-many-events`). */
142
+ export const MAX_ANSWER_EVENTS = 500, MAX_ANSWER_SKIPPED = 100;
143
+ /** Caps on the source's own text (§7): a skipped item's `why`, a refusal's message and code. */
144
+ export const SOURCE_TEXT_MAX = Object.freeze({ why: 200, message: 500, code: 128, invalidEvent: 200 });
145
+ const KEY_RE = /^[\x21-\x7e]{1,512}$/;
146
+ const SUBJECT_RE = /^[A-Za-z0-9._/:@-]{1,200}$/;
147
+ const URL_MAX = 500;
148
+ /** A url as it is stored and rendered: printable ASCII, no space. The URL parser alone would let a
149
+ * tab, CR or LF through (it strips them) and percent-encode the rest, while the RAW string is what
150
+ * reaches the event file and a `{url}` template. */
151
+ const URL_TEXT_RE = /^[\x21-\x7e]+$/;
152
+ /** A field value's length in code points, whatever its author's pattern admits (`.*`): the bound the
153
+ * default pattern has, and that every other text a source provides has one of. */
154
+ const FIELD_VALUE_MAX = 200;
155
+ /** A field value the kernel takes: at most FIELD_VALUE_MAX code points, no character it refuses in
156
+ * text it did not write, and then the author's pattern, which therefore never sees a longer or a
157
+ * refused string. The length is settled on UTF-16 units first (200 code points are at most 400), so
158
+ * a megabyte value is never spread to be counted. */
159
+ const fieldValueOk = (value, pattern) => typeof value === "string" && value.length <= FIELD_VALUE_MAX * 2
160
+ && (value.length <= FIELD_VALUE_MAX || [...value].length <= FIELD_VALUE_MAX) && !REFUSED_TEXT.test(value) && pattern.test(value);
161
+ const EVENT_KEYS = ["key", "subject", "event", "url", "fields"];
162
+ const SUCCESS_KEYS = ["schemaVersion", "phase", "capability", "source", "ok", "result"];
163
+ const REFUSAL_KEYS = ["schemaVersion", "phase", "capability", "source", "ok", "error"];
164
+
165
+ /** A wire failure: E_TRIGGER_POLL with its `cause` (and the source's own refusal, made safe). */
166
+ export function pollFailure(cause, message, source) {
167
+ return Object.assign(new Error(message), { code: "E_TRIGGER_POLL", details: { cause, ...(source ? { source } : {}) } });
168
+ }
169
+
170
+ /** One event's rule broken, or null when it is valid for `source` (a validated source). */
171
+ function eventProblem(source, ev) {
172
+ if (!isObject(ev)) return "shape";
173
+ if (Object.keys(ev).some((k) => !EVENT_KEYS.includes(k))) return "unknown-key";
174
+ if (typeof ev.key !== "string" || !KEY_RE.test(ev.key)) return "key";
175
+ if (typeof ev.subject !== "string" || !SUBJECT_RE.test(ev.subject)) return "subject";
176
+ if (typeof ev.event !== "string" || !source.events.includes(ev.event)) return "event";
177
+ if (ev.url !== undefined) {
178
+ if (typeof ev.url !== "string" || ev.url.length > URL_MAX || !URL_TEXT_RE.test(ev.url)) return "url";
179
+ let u; try { u = new URL(ev.url); } catch { return "url"; }
180
+ if (u.protocol !== "https:" || u.username || u.password || !source.urlHosts.includes(u.hostname.toLowerCase())) return "url";
181
+ }
182
+ if (ev.fields !== undefined) {
183
+ if (!isObject(ev.fields)) return "fields";
184
+ const names = Object.keys(ev.fields);
185
+ // Whatever its author's pattern admits (`.*`), a field value is bounded and never carries a
186
+ // character the kernel refuses: it is rendered into the task as `{fields.<name>}`.
187
+ if (names.length > MAX_FIELDS || names.some((n) => !Object.hasOwn(source.fields, n) || !fieldValueOk(ev.fields[n], source.fields[n].pattern))) return "fields";
188
+ }
189
+ return null;
190
+ }
191
+
192
+ /** Judge a source's answer (the document `runModuleCommand` decoded) against the request it was
193
+ * sent and the source's declaration; `selected` is the trigger's `on.events`.
194
+ * → { events, invalidEvents: [{ text, rule }], skipped: [{ subject, why }], filtered }:
195
+ * `events` are the valid events the trigger selects, first of each key; an invalid event is
196
+ * dropped alone; an event the source declares but the trigger does not select is counted in
197
+ * `filtered`. Throws E_TRIGGER_POLL: `result` (the envelope or its result is malformed),
198
+ * `too-many-events`, or `refused` (with the source's own code and message, made safe). */
199
+ export function judgeAnswer(doc, request, source, selected) {
200
+ const safe = safeText;
201
+ const malformed = (why) => pollFailure("result", `${request.capability}:${request.source} answered a malformed poll result: ${why}`);
202
+ if (!isObject(doc)) throw malformed("not a JSON object");
203
+ const keys = doc.ok === true ? SUCCESS_KEYS : doc.ok === false ? REFUSAL_KEYS : null;
204
+ if (!keys) throw malformed("ok must be true or false");
205
+ const extra = Object.keys(doc).filter((k) => !keys.includes(k)), missing = keys.filter((k) => !Object.hasOwn(doc, k));
206
+ if (extra.length || missing.length) throw malformed(`the envelope's keys must be exactly ${keys.join(", ")}`);
207
+ for (const k of ["schemaVersion", "phase", "capability", "source"]) if (doc[k] !== request[k]) throw malformed(`${k} must echo the request's ${JSON.stringify(request[k])}`);
208
+ if (doc.ok === false) {
209
+ const e = doc.error;
210
+ if (!isObject(e) || typeof e.code !== "string" || !e.code || (e.message !== undefined && typeof e.message !== "string") || Object.keys(e).some((k) => k !== "code" && k !== "message")) throw malformed("error must be { code, message? }");
211
+ const said = { code: safe(e.code, SOURCE_TEXT_MAX.code), ...(e.message !== undefined ? { message: safe(e.message, SOURCE_TEXT_MAX.message) } : {}) };
212
+ throw pollFailure("refused", `${request.capability}:${request.source} refused the poll`, said);
213
+ }
214
+ const res = doc.result;
215
+ if (!isObject(res) || !Array.isArray(res.events) || Object.keys(res).some((k) => k !== "events" && k !== "skipped") || (res.skipped !== undefined && !Array.isArray(res.skipped))) throw malformed("result must be { events: [...], skipped?: [...] }");
216
+ const skippedIn = res.skipped ?? [];
217
+ if (res.events.length > MAX_ANSWER_EVENTS || skippedIn.length > MAX_ANSWER_SKIPPED) throw pollFailure("too-many-events", `${request.capability}:${request.source} answered ${res.events.length} events and ${skippedIn.length} skipped (at most ${MAX_ANSWER_EVENTS} and ${MAX_ANSWER_SKIPPED})`);
218
+ const skipped = skippedIn.map((s) => {
219
+ if (!isObject(s) || typeof s.subject !== "string" || typeof s.why !== "string" || Object.keys(s).some((k) => k !== "subject" && k !== "why")) throw malformed("a skipped item must be { subject, why }");
220
+ return { subject: safe(s.subject, SOURCE_TEXT_MAX.why), why: safe(s.why, SOURCE_TEXT_MAX.why) };
221
+ });
222
+ const events = [], invalidEvents = [], seen = new Set();
223
+ let filtered = 0;
224
+ const drop = (ev, rule) => invalidEvents.push({ text: safe(JSON.stringify(ev) ?? String(ev), SOURCE_TEXT_MAX.invalidEvent), rule });
225
+ for (const ev of res.events) {
226
+ const rule = eventProblem(source, ev);
227
+ if (rule) { drop(ev, rule); continue; }
228
+ if (seen.has(ev.key)) { drop(ev, "duplicate-key"); continue; }
229
+ seen.add(ev.key);
230
+ if (!selected.includes(ev.event)) { filtered++; continue; }
231
+ events.push({ key: ev.key, subject: ev.subject, event: ev.event, ...(ev.url !== undefined ? { url: ev.url } : {}), fields: { ...(ev.fields ?? {}) } });
232
+ }
233
+ return { events, invalidEvents, skipped, filtered };
234
+ }