@rivus/gateway 0.22.3 → 0.24.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.
@@ -0,0 +1,13 @@
1
+ //#region src/automation/domain/automation-occurrence/errors.ts
2
+ var RivusAutomationFailure = class extends Error {
3
+ name = "RivusAutomationFailure";
4
+ code;
5
+ constructor(code, message = code, options) {
6
+ if (typeof code !== "string" || !/^[A-Z][A-Z0-9_]{0,63}$/.test(code)) throw new TypeError("Automation failure code must match ^[A-Z][A-Z0-9_]{0,63}$");
7
+ super(message, options);
8
+ this.code = code;
9
+ }
10
+ };
11
+ //#endregion
12
+ export { RivusAutomationFailure as t };
13
+
@@ -1,11 +1,11 @@
1
+ import { c as evaluateTerminalWriteInput, o as TerminalPromptPreflightError, s as TerminalTargetChangedError } from "./herdr-socket-client.js";
1
2
  import { Array as Array$1, Cause, Context, Effect, Exit, Fiber, Layer, Option, Result, Schema, Scope, Semaphore } from "effect";
2
3
  import { unwrapExit } from "@rivus/platform/effect";
3
- import { writeAtomicTextFile } from "@rivus/platform/persistence";
4
- import { isAbsolute, join, resolve } from "node:path";
5
- import { chmod, lstat, mkdir, open, readFile, readdir } from "node:fs/promises";
4
+ import { chmod, lstat, mkdir, open, readFile } from "node:fs/promises";
5
+ import { isAbsolute, join } from "node:path";
6
6
  import { isNodeErrorWithCode } from "@rivus/platform/filesystem";
7
- import { createConnection } from "node:net";
8
- import { createHash, randomBytes, randomUUID } from "node:crypto";
7
+ import { writeAtomicTextFile } from "@rivus/platform/persistence";
8
+ import { createHash, randomBytes } from "node:crypto";
9
9
  import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
10
10
  import { stripVTControlCharacters } from "node:util";
11
11
  import { Worker } from "node:worker_threads";
@@ -313,49 +313,6 @@ function createTerminalSessionBindings(options) {
313
313
  };
314
314
  }
315
315
  //#endregion
316
- //#region src/terminal-session/domain/bridge/value-objects/terminal-bridge-model.ts
317
- var TerminalTargetChangedError = class extends Error {
318
- constructor() {
319
- super("Herdr target changed; select the target again");
320
- }
321
- };
322
- /** A final target check refused before the prompt RPC was invoked. */
323
- var TerminalPromptPreflightError = class extends Error {
324
- constructor(text) {
325
- super(text);
326
- }
327
- };
328
- const terminalWriteRefusalText = {
329
- "read-only": "Terminal input is disabled for this deployment.",
330
- terminal: "目标为只读终端面板,不能接收指令。",
331
- "not-ready": "目标尚未完成启动,暂不接收指令;请刷新状态。",
332
- busy: "目标正在执行任务,暂不接收新指令。",
333
- blocked: "目标正在等待处理(如审批或提问),不会代替你处理;未提交指令。",
334
- "unknown-status": "目标状态未知,请刷新确认后再发送。"
335
- };
336
- /**
337
- * Shared gate for every Herdr write path (locked text, /herdr send, form submit).
338
- * Herdr reports the same input-awaiting agent as `done` before it is focused and
339
- * `idle` afterwards, so both statuses admit a ready agent; everything else refuses
340
- * with a specific reason and no PTY input. Availability and status are evaluated
341
- * before the deployment read-only flag so an offline, replaced or busy target keeps
342
- * reporting its own reason instead of a generic disabled notice.
343
- */
344
- function evaluateTerminalWriteInput(agent, writable) {
345
- const refused = (refusal) => ({
346
- allowed: false,
347
- refusal,
348
- text: terminalWriteRefusalText[refusal]
349
- });
350
- if (agent.kind !== "agent") return refused("terminal");
351
- if (!agent.ready) return refused("not-ready");
352
- if (agent.status === "working") return refused("busy");
353
- if (agent.status === "blocked") return refused("blocked");
354
- if (agent.status !== "idle" && agent.status !== "done") return refused("unknown-status");
355
- if (!writable) return refused("read-only");
356
- return { allowed: true };
357
- }
358
- //#endregion
359
316
  //#region src/terminal-session/application/use-cases/terminal-session-bridge.ts
360
317
  function buildBridge(options, ports) {
361
318
  if (!options.actors.length || !options.chats.length) throw new Error("Explicit actor and chat allowlists required");
@@ -778,7 +735,7 @@ function buildBridge(options, ports) {
778
735
  }
779
736
  return {
780
737
  message,
781
- route: { kind: "legacy" }
738
+ route: { kind: "command" }
782
739
  };
783
740
  };
784
741
  /**
@@ -892,7 +849,7 @@ function buildBridge(options, ports) {
892
849
  kind: "work",
893
850
  work: inventoryWorkWithCurrentSelection(message, route.command, route.argument)
894
851
  };
895
- case "legacy": return {
852
+ case "command": return {
896
853
  kind: "work",
897
854
  work: commandWork(message, execute(message, watchExitRevisionOf(message)))
898
855
  };
@@ -917,7 +874,7 @@ function buildBridge(options, ports) {
917
874
  });
918
875
  }
919
876
  });
920
- /** Single-shot composition for the compatibility handlers; Router composes the
877
+ /** Single-shot composition for `handle` and `handleDetailed`; Router composes the
921
878
  * three explicit entries itself inside one withAdmission turn. */
922
879
  const admit = (message) => withAdmission(Effect.gen(function* () {
923
880
  const captured = captureInAdmission(message);
@@ -1007,327 +964,6 @@ function makeConversationalTerminalSessionBridge(options, epoch) {
1007
964
  });
1008
965
  }
1009
966
  //#endregion
1010
- //#region src/terminal-session/infra/adapters/herdr/herdr-socket-request.ts
1011
- /**
1012
- * Object gate for a Herdr response part, not a field reader: the callers read their
1013
- * fields by name with their own error texts. `Schema.Record(Schema.String, Schema.Unknown)`
1014
- * is deliberately used only as that gate; a hand-written `typeof … === "object"` guard is
1015
- * forbidden (authoring guide, Validation).
1016
- */
1017
- const herdrResponseGate = Schema.Record(Schema.String, Schema.Unknown);
1018
- function object(value) {
1019
- if (!Schema.is(herdrResponseGate)(value)) throw new Error("Invalid Herdr response");
1020
- return value;
1021
- }
1022
- function string(value) {
1023
- if (typeof value !== "string") throw new Error("Invalid Herdr response field");
1024
- return value;
1025
- }
1026
- function requestHerdrSocket(path, method, params, timeoutMs, signal) {
1027
- return new Promise((resolve, reject) => {
1028
- const id = randomUUID();
1029
- const socket = createConnection({ path });
1030
- let settled = false;
1031
- let bytes = 0;
1032
- let buffer = "";
1033
- function finish(error, result) {
1034
- if (settled) return;
1035
- settled = true;
1036
- clearTimeout(timer);
1037
- signal.removeEventListener("abort", abort);
1038
- socket.removeAllListeners("connect");
1039
- socket.removeAllListeners("data");
1040
- socket.removeAllListeners("end");
1041
- socket.destroy();
1042
- if (error) reject(error);
1043
- else resolve(result);
1044
- }
1045
- const onError = (error) => finish(error);
1046
- socket.once("close", () => socket.removeListener("error", onError));
1047
- const abort = () => finish(/* @__PURE__ */ new Error("Herdr request aborted; input may have been submitted"));
1048
- const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("Herdr request timed out; input may have been submitted")), timeoutMs);
1049
- signal.addEventListener("abort", abort, { once: true });
1050
- socket.setEncoding("utf8");
1051
- socket.on("connect", () => socket.write(`${JSON.stringify({
1052
- id,
1053
- method,
1054
- params
1055
- })}\n`));
1056
- socket.on("error", onError);
1057
- socket.on("end", () => finish(/* @__PURE__ */ new Error("Herdr closed without a response; outcome unknown")));
1058
- socket.on("data", (chunk) => {
1059
- bytes += Buffer.byteLength(chunk);
1060
- if (bytes > 1048576) return finish(/* @__PURE__ */ new Error("Herdr response exceeds one MiB"));
1061
- buffer += chunk;
1062
- const newline = buffer.indexOf("\n");
1063
- if (newline < 0) return;
1064
- try {
1065
- const response = object(JSON.parse(buffer.slice(0, newline)));
1066
- if (response.id !== id) throw new Error("Herdr response identity mismatch");
1067
- if (response.error) throw new Error(`Herdr error: ${string(object(response.error).code)}`);
1068
- finish(void 0, object(response.result));
1069
- } catch (error) {
1070
- finish(error);
1071
- }
1072
- });
1073
- if (signal.aborted) abort();
1074
- });
1075
- }
1076
- //#endregion
1077
- //#region src/terminal-session/infra/adapters/herdr/herdr-socket-client.ts
1078
- async function discoverSessions(root) {
1079
- const uid = process.getuid?.();
1080
- const directory = await lstat(root);
1081
- if (!directory.isDirectory() || directory.uid !== uid || (directory.mode & 18) !== 0) throw new Error("Herdr discovery root must be an owned, non-writable directory");
1082
- const candidates = [{
1083
- name: "default",
1084
- socketPath: join(root, "herdr.sock")
1085
- }];
1086
- const named = join(root, "sessions");
1087
- const info = await lstat(named).catch((error) => {
1088
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
1089
- return null;
1090
- });
1091
- if (info) {
1092
- if (!info.isDirectory() || info.uid !== uid || (info.mode & 18) !== 0) throw new Error("Invalid Herdr sessions directory");
1093
- for (const entry of (await readdir(named, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) if (entry.isDirectory()) candidates.push({
1094
- name: entry.name,
1095
- socketPath: join(named, entry.name, "herdr.sock")
1096
- });
1097
- }
1098
- const found = [];
1099
- for (const candidate of candidates) if (await lstat(candidate.socketPath).catch((error) => {
1100
- if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
1101
- return null;
1102
- })) found.push(candidate);
1103
- return found;
1104
- }
1105
- function createHerdrSocketClient(sessions, timeoutMs = 5e3, discoverSessionsIn) {
1106
- if (!sessions.length && !discoverSessionsIn || new Set(sessions.map((s) => s.name)).size !== sessions.length) throw new Error("Herdr requires unique configured session names");
1107
- if (discoverSessionsIn && !isAbsolute(discoverSessionsIn)) throw new Error("Herdr discovery root must be absolute");
1108
- let configs = new Map(sessions.map((session) => [session.name, session]));
1109
- const refresh = () => Effect.tryPromise({
1110
- try: async () => {
1111
- const discovered = discoverSessionsIn ? await discoverSessions(discoverSessionsIn) : [];
1112
- const next = /* @__PURE__ */ new Map();
1113
- const paths = /* @__PURE__ */ new Set();
1114
- for (const config of [...sessions, ...discovered]) {
1115
- const path = resolve(config.socketPath);
1116
- if (paths.has(path)) continue;
1117
- if (next.has(config.name)) throw new Error("Herdr session aliases collide");
1118
- next.set(config.name, {
1119
- ...config,
1120
- socketPath: path
1121
- });
1122
- paths.add(path);
1123
- }
1124
- configs = next;
1125
- return [...next.keys()];
1126
- },
1127
- catch: (error) => error
1128
- });
1129
- const invoke = (session, method, params) => Effect.tryPromise({
1130
- try: async (signal) => {
1131
- const config = configs.get(session);
1132
- if (!config) throw new Error("Unknown Herdr session");
1133
- const socket = await lstat(config.socketPath);
1134
- if (!socket.isSocket() || (socket.mode & 63) !== 0 || socket.uid !== process.getuid?.()) throw new Error("Herdr socket must be private and owned by the current user");
1135
- return {
1136
- result: await requestHerdrSocket(config.socketPath, method, params, timeoutMs, signal),
1137
- generation: `${socket.dev}:${socket.ino}:${socket.birthtimeMs}`
1138
- };
1139
- },
1140
- catch: (error) => error
1141
- });
1142
- const listSession = (session) => invoke(session, "session.snapshot", {}).pipe(Effect.flatMap(({ result, generation }) => Effect.try(() => {
1143
- const snapshot = object(result.snapshot);
1144
- if (snapshot.protocol !== 20 && snapshot.protocol !== 22 || !Array.isArray(snapshot.panes) || !Array.isArray(snapshot.agents)) throw new Error("Herdr protocol 20 or 22 session snapshot required");
1145
- const agents = snapshot.agents.map(object);
1146
- const labels = (values, key) => new Map((Array.isArray(values) ? values : []).map((item) => {
1147
- const entry = object(item);
1148
- return [string(entry[key]), string(entry.label)];
1149
- }));
1150
- const workspaces = labels(snapshot.workspaces, "workspace_id");
1151
- const tabs = labels(snapshot.tabs, "tab_id");
1152
- return snapshot.panes.map((entry) => {
1153
- const value = object(entry);
1154
- const pane = string(value.pane_id);
1155
- const terminal = string(value.terminal_id);
1156
- const agent = agents.find((item) => item.pane_id === pane && item.terminal_id === terminal);
1157
- const kind = typeof value.agent === "string" && value.agent ? value.agent : "terminal";
1158
- const workspace = string(value.workspace_id);
1159
- const tab = string(value.tab_id);
1160
- const title = [
1161
- agent?.name,
1162
- value.label,
1163
- value.terminal_title_stripped,
1164
- value.title
1165
- ].find((item) => typeof item === "string" && item.length > 0) ?? kind;
1166
- return {
1167
- session,
1168
- pane,
1169
- identity: createHash("sha256").update(JSON.stringify([
1170
- generation,
1171
- session,
1172
- pane,
1173
- terminal,
1174
- kind,
1175
- value.agent_session ?? null
1176
- ])).digest("hex"),
1177
- kind: kind === "terminal" ? "terminal" : "agent",
1178
- name: `${pane} / ${workspaces.get(workspace) ?? workspace} / ${tabs.get(tab) ?? tab} / ${title}`,
1179
- workspace: workspaces.get(workspace) ?? workspace,
1180
- tab: tabs.get(tab) ?? tab,
1181
- title,
1182
- status: string(value.agent_status),
1183
- ready: kind !== "terminal" && agent !== void 0 && (agent.launch_pending === void 0 || agent.launch_pending === false)
1184
- };
1185
- });
1186
- })));
1187
- const resolve$1 = (agent) => refresh().pipe(Effect.flatMap(() => listSession(agent.session)), Effect.flatMap((agents) => {
1188
- const current = agents.find((item) => item.pane === agent.pane && item.identity === agent.identity);
1189
- return current ? Effect.succeed(current) : Effect.fail(new TerminalTargetChangedError());
1190
- }));
1191
- return {
1192
- list: () => refresh().pipe(Effect.flatMap((names) => Effect.all(names.map((name) => listSession(name).pipe(Effect.map((agents) => ({
1193
- agents,
1194
- unavailableSessions: []
1195
- })), Effect.catch(() => Effect.succeed({
1196
- agents: [],
1197
- unavailableSessions: [name]
1198
- })))), { concurrency: 4 })), Effect.map((results) => ({
1199
- agents: results.flatMap((result) => result.agents),
1200
- unavailableSessions: results.flatMap((result) => result.unavailableSessions)
1201
- }))),
1202
- inspect: resolve$1,
1203
- read: (agent, visible) => resolve$1(agent).pipe(Effect.flatMap(() => invoke(agent.session, "pane.read", {
1204
- pane_id: agent.pane,
1205
- source: visible ? "visible" : "recent_unwrapped",
1206
- format: "text",
1207
- lines: visible ? 80 : 120
1208
- })), Effect.flatMap(({ result }) => Effect.try(() => {
1209
- const read = object(result.read);
1210
- return {
1211
- text: string(read.text),
1212
- truncated: read.truncated === true
1213
- };
1214
- }))),
1215
- prompt: (agent, text) => resolve$1(agent).pipe(Effect.catch((error) => Effect.fail(error instanceof TerminalTargetChangedError ? error : new TerminalPromptPreflightError("目标暂不可用;未提交指令。可 /exit 后重新选择。"))), Effect.flatMap((current) => {
1216
- const verdict = evaluateTerminalWriteInput(current, true);
1217
- return verdict.allowed ? Effect.void : Effect.fail(new TerminalPromptPreflightError(`Input rejected: ${verdict.text}`));
1218
- }), Effect.flatMap(() => invoke(agent.session, "agent.prompt", {
1219
- target: agent.pane,
1220
- text
1221
- })), Effect.asVoid)
1222
- };
1223
- }
1224
- //#endregion
1225
- //#region src/terminal-session/infra/adapters/herdr/terminal-text-image.ts
1226
- const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1227
- const emoji = /* @__PURE__ */ new RegExp("^\\p{RGI_Emoji}$", "v");
1228
- const maxRows = 80;
1229
- const maxColumns = 160;
1230
- const maxGraphemes = 160;
1231
- const maxLineCodeUnits = 1024;
1232
- const maxUniqueGraphemes = 1024;
1233
- const cellWidth = 10.8;
1234
- const shapeWorkerUrl = new URL(`data:text/javascript,${encodeURIComponent(`
1235
- import { parentPort, workerData } from "node:worker_threads";
1236
- const { Resvg } = await import(workerData.resvgModuleUrl);
1237
- parentPort.postMessage(new Resvg(workerData.svg, workerData.options).toString());
1238
- parentPort.close();
1239
- `)}`);
1240
- function shapeAtlas(svg, options) {
1241
- return new Promise((resolve, reject) => {
1242
- const worker = new Worker(shapeWorkerUrl, { workerData: {
1243
- svg,
1244
- options,
1245
- resvgModuleUrl: import.meta.resolve("@resvg/resvg-js")
1246
- } });
1247
- let settled = false;
1248
- const deadline = setTimeout(() => finish(/* @__PURE__ */ new Error("Terminal image shaping timed out.")), 3e4);
1249
- function finish(error, paths) {
1250
- if (settled) return;
1251
- settled = true;
1252
- clearTimeout(deadline);
1253
- worker.terminate().then(() => {
1254
- worker.removeAllListeners();
1255
- if (error) reject(error);
1256
- else resolve(paths);
1257
- }, (terminationError) => {
1258
- worker.removeAllListeners();
1259
- reject(error ?? terminationError);
1260
- });
1261
- }
1262
- worker.once("message", (paths) => {
1263
- if (typeof paths !== "string") finish(/* @__PURE__ */ new Error("Terminal image shaping returned invalid paths."));
1264
- else finish(void 0, paths);
1265
- });
1266
- worker.once("error", (error) => finish(error));
1267
- worker.once("exit", (code) => finish(/* @__PURE__ */ new Error(`Terminal image shaping exited before replying (${code}).`)));
1268
- });
1269
- }
1270
- function graphemeColumns(grapheme) {
1271
- if (emoji.test(grapheme)) return 2;
1272
- for (const codePoint of grapheme) if (!/[\p{Mark}\p{Format}]/u.test(codePoint)) return eastAsianWidth(codePoint.codePointAt(0));
1273
- return 0;
1274
- }
1275
- function renderLine(line, y, glyphs) {
1276
- const nodes = [];
1277
- let column = 0;
1278
- let graphemes = 0;
1279
- let codeUnits = 0;
1280
- for (const { segment } of segmenter.segment(line)) {
1281
- const columns = segment === " " ? 4 - column % 4 : graphemeColumns(segment);
1282
- if (column + columns > maxColumns || graphemes >= maxGraphemes || codeUnits + segment.length > maxLineCodeUnits) return {
1283
- svg: nodes.join(""),
1284
- clipped: true
1285
- };
1286
- if (segment !== " " && segment !== " ") {
1287
- let index = glyphs.get(segment);
1288
- if (index === void 0) {
1289
- if (glyphs.size >= maxUniqueGraphemes) throw new Error("Terminal image exceeds its unique grapheme budget.");
1290
- index = glyphs.size;
1291
- glyphs.set(segment, index);
1292
- }
1293
- nodes.push(`<g transform="translate(${24 + column * cellWidth} ${y - 20})" clip-path="url(#cell-${Math.max(1, columns)})"><use href="#terminal-glyph-${index}"/></g>`);
1294
- }
1295
- column += columns;
1296
- graphemes += 1;
1297
- codeUnits += segment.length;
1298
- }
1299
- return {
1300
- svg: nodes.join(""),
1301
- clipped: false
1302
- };
1303
- }
1304
- function escapeXml(text) {
1305
- return text.replace(/[&<>"']/g, (char) => ({
1306
- "&": "&amp;",
1307
- "<": "&lt;",
1308
- ">": "&gt;",
1309
- "\"": "&quot;",
1310
- "'": "&apos;"
1311
- })[char]);
1312
- }
1313
- async function renderTerminalTextImage(screen, fontFiles) {
1314
- const { renderAsync } = await import("@resvg/resvg-js");
1315
- const glyphs = /* @__PURE__ */ new Map();
1316
- const allLines = stripVTControlCharacters(screen.text).replace(/[^\P{Cc}\n\t]/gu, "").split("\n");
1317
- const title = renderLine(stripVTControlCharacters(screen.title).replace(/\p{Cc}/gu, ""), 30, glyphs);
1318
- const lines = allLines.slice(0, maxRows).map((line, index) => renderLine(line, 96 + index * 24, glyphs));
1319
- const clipped = screen.truncated || allLines.length > maxRows || title.clipped || lines.some((line) => line.clipped);
1320
- const width = 1800;
1321
- const height = 100 + Math.max(1, lines.length) * 24;
1322
- const label = `Terminal text rendering | ${new Date(screen.at).toISOString()}${clipped ? " | truncated" : ""}`;
1323
- const body = lines.map((line) => line.svg).join("");
1324
- return (await renderAsync(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><defs>${[1, 2].map((columns) => `<clipPath id="cell-${columns}"><rect width="${columns * cellWidth}" height="24"/></clipPath>`).join("")}<clipPath id="label"><rect width="1752" height="24"/></clipPath>${await shapeAtlas(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="24"><g fill="#e5e7eb" font-family="monospace" font-size="18" xml:space="preserve">${[...glyphs].map(([glyph, index]) => `<g id="terminal-glyph-${index}"><text x="0" y="20">${escapeXml(glyph)}</text></g>`).join("")}<g id="terminal-label" fill="#94a3b8"><text x="0" y="20">${escapeXml(label)}</text></g></g></svg>`, { font: {
1325
- loadSystemFonts: !fontFiles?.length,
1326
- ...fontFiles ? { fontFiles: [...fontFiles] } : {},
1327
- defaultFontFamily: "monospace"
1328
- } })}</defs><rect width="100%" height="100%" fill="#101827"/>${title.svg}<g transform="translate(24 38)" clip-path="url(#label)"><use href="#terminal-label"/></g>${body}</svg>`, { font: { loadSystemFonts: false } })).asPng();
1329
- }
1330
- //#endregion
1331
967
  //#region src/terminal-session/infra/models/terminal-agent-schema.ts
1332
968
  /**
1333
969
  * File schema for the Application `TerminalAgent` snapshot, shared by every
@@ -1560,8 +1196,7 @@ async function openTerminalConversationStates(directory, appId) {
1560
1196
  * soon as the holding process exits or crashes, so the next opener recovers
1561
1197
  * automatically and no pid-based reclamation runs. Normal stop joins all work
1562
1198
  * before `close` releases the lock; a stopped-late holder keeps it until that
1563
- * process exits. The legacy `bridge.lock` pid file is never read again; an operator
1564
- * may delete a leftover one.
1199
+ * process exits.
1565
1200
  */
1566
1201
  function createDirectoryUnlessPresent(path) {
1567
1202
  return mkdir(path, {
@@ -1645,7 +1280,7 @@ async function openTerminalMessageClaims(directory, appId, platform) {
1645
1280
  catch: (error) => error
1646
1281
  })),
1647
1282
  /**
1648
- * Read-only legacy fence lookup with the exact claim digest. Existence is the
1283
+ * Read-only fence lookup with the exact claim digest. Existence is the
1649
1284
  * fence: arbitrary or invalid file contents still count as claimed. `false` is
1650
1285
  * only returned for a missing entry (ENOENT); every other I/O failure
1651
1286
  * propagates. Never creates, mutates or deletes historic files.
@@ -1818,8 +1453,10 @@ function decodeFeishuCardCallback(raw) {
1818
1453
  }
1819
1454
  //#endregion
1820
1455
  //#region src/feishu/infra/adapters/client/feishu-sdk-message-client.ts
1821
- const decodeRootImageKey = Schema.decodeUnknownOption(Schema.Struct({ image_key: Schema.optional(Schema.NullOr(Schema.String)) }));
1822
- const decodeNestedImageKey = Schema.decodeUnknownOption(Schema.Struct({ data: Schema.Struct({ image_key: Schema.optional(Schema.NullOr(Schema.NonEmptyString)) }) }));
1456
+ const decodeImageUpload = Schema.decodeUnknownOption(Schema.Union([Schema.Struct({ image_key: Schema.NonEmptyString }), Schema.Struct({
1457
+ data: Schema.Struct({ image_key: Schema.NonEmptyString }),
1458
+ image_key: Schema.optional(Schema.Null)
1459
+ })]));
1823
1460
  const decodeMessageAck = Schema.decodeUnknownOption(Schema.Struct({ code: Schema.Literal(0) }));
1824
1461
  const decodeBotIdentity = Schema.decodeUnknownOption(Schema.Struct({
1825
1462
  code: Schema.Literal(0),
@@ -1830,26 +1467,15 @@ const decodeRawMessage = Schema.decodeUnknownOption(Schema.Struct({ msg: Schema.
1830
1467
  Schema.Number,
1831
1468
  Schema.Boolean
1832
1469
  ])) }));
1833
- /**
1834
- * Uploads one image and returns its `image_key`. Both legacy response shapes are
1835
- * accepted (root `image_key` and nested `data.image_key`); a root empty string
1836
- * blocks the nested fallback, only a null or missing root key may fall back, and
1837
- * a non-string root key rejects instead of being sent.
1838
- */
1470
+ /** Uploads one image and returns its `image_key`; any other response reports the upload as failed. */
1839
1471
  async function uploadFeishuImage(client, image) {
1840
1472
  const uploaded = await client.im.image.create({ data: {
1841
1473
  image_type: "message",
1842
1474
  image: Buffer.from(image)
1843
1475
  } });
1844
- const rootKey = Option.map(decodeRootImageKey(uploaded), (decoded) => decoded.image_key);
1845
- if (Option.isNone(rootKey)) throw new Error("Feishu image upload failed");
1846
- if (rootKey.value !== null && rootKey.value !== void 0) {
1847
- if (rootKey.value === "") throw new Error("Feishu image upload failed");
1848
- return rootKey.value;
1849
- }
1850
- const nestedKey = Option.map(decodeNestedImageKey(uploaded), (decoded) => decoded.data.image_key);
1851
- if (Option.isSome(nestedKey) && typeof nestedKey.value === "string") return nestedKey.value;
1852
- throw new Error("Feishu image upload failed");
1476
+ const decoded = decodeImageUpload(uploaded);
1477
+ if (Option.isNone(decoded)) throw new Error("Feishu image upload failed");
1478
+ return "data" in decoded.value ? decoded.value.data.image_key : decoded.value.image_key;
1853
1479
  }
1854
1480
  /** Sends one message and rejects with the caller's error text unless the SDK acknowledges numeric code 0. */
1855
1481
  async function sendFeishuSdkMessage(client, message, errorMessage) {
@@ -1896,8 +1522,8 @@ const hasPiMarker = (value) => {
1896
1522
  * Classifies a raw card callback before any handler runs: Pi cards carry
1897
1523
  * `value.rivus_action`, Herdr cards carry `value.bridge === "herdr"` or the v2
1898
1524
  * form name (a submit button cannot carry a value, so its explicit v2 name is
1899
- * the marker). Both markers must be refused by both sides; unmarked legacy
1900
- * cards are invalid and get a refresh instruction.
1525
+ * the marker). Both markers must be refused by both sides; unmarked cards are
1526
+ * invalid and get a refresh instruction.
1901
1527
  */
1902
1528
  function classifyFeishuCardOwnership(terminal) {
1903
1529
  if (!terminal) return "unmarked";
@@ -1966,6 +1592,7 @@ function parseFeishuTerminalAction(terminal, menuChats) {
1966
1592
  ...selection === void 0 ? {} : { selection }
1967
1593
  } : null;
1968
1594
  }
1595
+ /** @internal */
1969
1596
  function renderTerminalMenu(menu) {
1970
1597
  const plain = (content) => ({
1971
1598
  tag: "plain_text",
@@ -2130,6 +1757,112 @@ function createFeishuTerminalDelivery(client, options) {
2130
1757
  };
2131
1758
  }
2132
1759
  //#endregion
1760
+ //#region src/herdr/infra/adapters/terminal-text-image.ts
1761
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1762
+ const emoji = /* @__PURE__ */ new RegExp("^\\p{RGI_Emoji}$", "v");
1763
+ const maxRows = 80;
1764
+ const maxColumns = 160;
1765
+ const maxGraphemes = 160;
1766
+ const maxLineCodeUnits = 1024;
1767
+ const maxUniqueGraphemes = 1024;
1768
+ const cellWidth = 10.8;
1769
+ const shapeWorkerUrl = new URL(`data:text/javascript,${encodeURIComponent(`
1770
+ import { parentPort, workerData } from "node:worker_threads";
1771
+ const { Resvg } = await import(workerData.resvgModuleUrl);
1772
+ parentPort.postMessage(new Resvg(workerData.svg, workerData.options).toString());
1773
+ parentPort.close();
1774
+ `)}`);
1775
+ function shapeAtlas(svg, options) {
1776
+ return new Promise((resolve, reject) => {
1777
+ const worker = new Worker(shapeWorkerUrl, { workerData: {
1778
+ svg,
1779
+ options,
1780
+ resvgModuleUrl: import.meta.resolve("@resvg/resvg-js")
1781
+ } });
1782
+ let settled = false;
1783
+ const deadline = setTimeout(() => finish(/* @__PURE__ */ new Error("Terminal image shaping timed out.")), 3e4);
1784
+ function finish(error, paths) {
1785
+ if (settled) return;
1786
+ settled = true;
1787
+ clearTimeout(deadline);
1788
+ worker.terminate().then(() => {
1789
+ worker.removeAllListeners();
1790
+ if (error) reject(error);
1791
+ else resolve(paths);
1792
+ }, (terminationError) => {
1793
+ worker.removeAllListeners();
1794
+ reject(error ?? terminationError);
1795
+ });
1796
+ }
1797
+ worker.once("message", (paths) => {
1798
+ if (typeof paths !== "string") finish(/* @__PURE__ */ new Error("Terminal image shaping returned invalid paths."));
1799
+ else finish(void 0, paths);
1800
+ });
1801
+ worker.once("error", (error) => finish(error));
1802
+ worker.once("exit", (code) => finish(/* @__PURE__ */ new Error(`Terminal image shaping exited before replying (${code}).`)));
1803
+ });
1804
+ }
1805
+ function graphemeColumns(grapheme) {
1806
+ if (emoji.test(grapheme)) return 2;
1807
+ for (const codePoint of grapheme) if (!/[\p{Mark}\p{Format}]/u.test(codePoint)) return eastAsianWidth(codePoint.codePointAt(0));
1808
+ return 0;
1809
+ }
1810
+ function renderLine(line, y, glyphs) {
1811
+ const nodes = [];
1812
+ let column = 0;
1813
+ let graphemes = 0;
1814
+ let codeUnits = 0;
1815
+ for (const { segment } of segmenter.segment(line)) {
1816
+ const columns = segment === " " ? 4 - column % 4 : graphemeColumns(segment);
1817
+ if (column + columns > maxColumns || graphemes >= maxGraphemes || codeUnits + segment.length > maxLineCodeUnits) return {
1818
+ svg: nodes.join(""),
1819
+ clipped: true
1820
+ };
1821
+ if (segment !== " " && segment !== " ") {
1822
+ let index = glyphs.get(segment);
1823
+ if (index === void 0) {
1824
+ if (glyphs.size >= maxUniqueGraphemes) throw new Error("Terminal image exceeds its unique grapheme budget.");
1825
+ index = glyphs.size;
1826
+ glyphs.set(segment, index);
1827
+ }
1828
+ nodes.push(`<g transform="translate(${24 + column * cellWidth} ${y - 20})" clip-path="url(#cell-${Math.max(1, columns)})"><use href="#terminal-glyph-${index}"/></g>`);
1829
+ }
1830
+ column += columns;
1831
+ graphemes += 1;
1832
+ codeUnits += segment.length;
1833
+ }
1834
+ return {
1835
+ svg: nodes.join(""),
1836
+ clipped: false
1837
+ };
1838
+ }
1839
+ function escapeXml(text) {
1840
+ return text.replace(/[&<>"']/g, (char) => ({
1841
+ "&": "&amp;",
1842
+ "<": "&lt;",
1843
+ ">": "&gt;",
1844
+ "\"": "&quot;",
1845
+ "'": "&apos;"
1846
+ })[char]);
1847
+ }
1848
+ async function renderTerminalTextImage(screen, fontFiles) {
1849
+ const { renderAsync } = await import("@resvg/resvg-js");
1850
+ const glyphs = /* @__PURE__ */ new Map();
1851
+ const allLines = stripVTControlCharacters(screen.text).replace(/[^\P{Cc}\n\t]/gu, "").split("\n");
1852
+ const title = renderLine(stripVTControlCharacters(screen.title).replace(/\p{Cc}/gu, ""), 30, glyphs);
1853
+ const lines = allLines.slice(0, maxRows).map((line, index) => renderLine(line, 96 + index * 24, glyphs));
1854
+ const clipped = screen.truncated || allLines.length > maxRows || title.clipped || lines.some((line) => line.clipped);
1855
+ const width = 1800;
1856
+ const height = 100 + Math.max(1, lines.length) * 24;
1857
+ const label = `Terminal text rendering | ${new Date(screen.at).toISOString()}${clipped ? " | truncated" : ""}`;
1858
+ const body = lines.map((line) => line.svg).join("");
1859
+ return (await renderAsync(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><defs>${[1, 2].map((columns) => `<clipPath id="cell-${columns}"><rect width="${columns * cellWidth}" height="24"/></clipPath>`).join("")}<clipPath id="label"><rect width="1752" height="24"/></clipPath>${await shapeAtlas(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="24"><g fill="#e5e7eb" font-family="monospace" font-size="18" xml:space="preserve">${[...glyphs].map(([glyph, index]) => `<g id="terminal-glyph-${index}"><text x="0" y="20">${escapeXml(glyph)}</text></g>`).join("")}<g id="terminal-label" fill="#94a3b8"><text x="0" y="20">${escapeXml(label)}</text></g></g></svg>`, { font: {
1860
+ loadSystemFonts: !fontFiles?.length,
1861
+ ...fontFiles ? { fontFiles: [...fontFiles] } : {},
1862
+ defaultFontFamily: "monospace"
1863
+ } })}</defs><rect width="100%" height="100%" fill="#101827"/>${title.svg}<g transform="translate(24 38)" clip-path="url(#label)"><use href="#terminal-label"/></g>${body}</svg>`, { font: { loadSystemFonts: false } })).asPng();
1864
+ }
1865
+ //#endregion
2133
1866
  //#region src/bootstrap/feishu/herdr-config.ts
2134
1867
  /** Shared Herdr field schemas for the standalone options and the embedded route config. */
2135
1868
  const herdrSessionSchema = Schema.Struct({
@@ -2374,5 +2107,5 @@ function createHerdrFeishuBridgeRuntime(options) {
2374
2107
  };
2375
2108
  }
2376
2109
  //#endregion
2377
- export { scalarText as C, trimmedTextField as E, scalarField as S, tolerant as T, TextContent as _, classifyFeishuCardOwnership as a, chained as b, parseFeishuTerminalMessage as c, decodeFeishuTerminalEvent as d, fileConversationalTerminalSessionStores as f, TerminalMessageClaimLookup as g, createHerdrSocketClient as h, standaloneHerdrOptionsSchema as i, fetchFeishuBotOpenId as l, terminalAgentSchema as m, openHerdrBridgeStores as n, createFeishuTerminalDelivery as o, fileTerminalSessionStores as p, embeddedHerdrRouteSchema as r, parseFeishuTerminalAction as s, createHerdrFeishuBridgeRuntime as t, decodeFeishuCardCallback as u, decodeFeishuTerminalText as v, textField as w, orInvalid as x, INVALID as y };
2110
+ export { textField as C, scalarText as S, trimmedTextField as T, decodeFeishuTerminalText as _, classifyFeishuCardOwnership as a, orInvalid as b, parseFeishuTerminalMessage as c, decodeFeishuTerminalEvent as d, fileConversationalTerminalSessionStores as f, TextContent as g, TerminalMessageClaimLookup as h, standaloneHerdrOptionsSchema as i, fetchFeishuBotOpenId as l, terminalAgentSchema as m, openHerdrBridgeStores as n, createFeishuTerminalDelivery as o, fileTerminalSessionStores as p, embeddedHerdrRouteSchema as r, parseFeishuTerminalAction as s, createHerdrFeishuBridgeRuntime as t, decodeFeishuCardCallback as u, INVALID as v, tolerant as w, scalarField as x, chained as y };
2378
2111