@rivus/gateway 0.22.3 → 0.23.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.
@@ -1,13 +1,13 @@
1
1
  import { Array as Array$1, Cause, Context, Effect, Exit, Fiber, Layer, Option, Result, Schema, Scope, Semaphore } from "effect";
2
2
  import { unwrapExit } from "@rivus/platform/effect";
3
- import { writeAtomicTextFile } from "@rivus/platform/persistence";
4
- import { isAbsolute, join, resolve } from "node:path";
3
+ import { createConnection } from "node:net";
5
4
  import { chmod, lstat, mkdir, open, readFile, readdir } from "node:fs/promises";
5
+ import { isAbsolute, join, resolve } from "node:path";
6
6
  import { isNodeErrorWithCode } from "@rivus/platform/filesystem";
7
- import { createConnection } from "node:net";
7
+ import { writeAtomicTextFile } from "@rivus/platform/persistence";
8
+ import { stripVTControlCharacters } from "node:util";
8
9
  import { createHash, randomBytes, randomUUID } from "node:crypto";
9
10
  import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
10
- import { stripVTControlCharacters } from "node:util";
11
11
  import { Worker } from "node:worker_threads";
12
12
  import { eastAsianWidth } from "get-east-asian-width";
13
13
  //#region src/feishu/infra/adapters/protocol/feishu-field-schemas.ts
@@ -313,7 +313,7 @@ function createTerminalSessionBindings(options) {
313
313
  };
314
314
  }
315
315
  //#endregion
316
- //#region src/terminal-session/domain/bridge/value-objects/terminal-bridge-model.ts
316
+ //#region src/terminal-session/domain/bridge/terminal-bridge-model.ts
317
317
  var TerminalTargetChangedError = class extends Error {
318
318
  constructor() {
319
319
  super("Herdr target changed; select the target again");
@@ -778,7 +778,7 @@ function buildBridge(options, ports) {
778
778
  }
779
779
  return {
780
780
  message,
781
- route: { kind: "legacy" }
781
+ route: { kind: "command" }
782
782
  };
783
783
  };
784
784
  /**
@@ -892,7 +892,7 @@ function buildBridge(options, ports) {
892
892
  kind: "work",
893
893
  work: inventoryWorkWithCurrentSelection(message, route.command, route.argument)
894
894
  };
895
- case "legacy": return {
895
+ case "command": return {
896
896
  kind: "work",
897
897
  work: commandWork(message, execute(message, watchExitRevisionOf(message)))
898
898
  };
@@ -917,7 +917,7 @@ function buildBridge(options, ports) {
917
917
  });
918
918
  }
919
919
  });
920
- /** Single-shot composition for the compatibility handlers; Router composes the
920
+ /** Single-shot composition for `handle` and `handleDetailed`; Router composes the
921
921
  * three explicit entries itself inside one withAdmission turn. */
922
922
  const admit = (message) => withAdmission(Effect.gen(function* () {
923
923
  const captured = captureInAdmission(message);
@@ -1007,395 +1007,74 @@ function makeConversationalTerminalSessionBridge(options, epoch) {
1007
1007
  });
1008
1008
  }
1009
1009
  //#endregion
1010
- //#region src/terminal-session/infra/adapters/herdr/herdr-socket-request.ts
1010
+ //#region src/terminal-session/infra/models/terminal-agent-schema.ts
1011
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).
1012
+ * File schema for the Application `TerminalAgent` snapshot, shared by every
1013
+ * terminal-session store that persists an occupant identity (bindings, conversation
1014
+ * states) so validation cannot drift between stores.
1016
1015
  */
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
- }
1016
+ const terminalAgentSchema = Schema.Struct({
1017
+ kind: Schema.Literals(["agent", "terminal"]),
1018
+ session: Schema.String,
1019
+ pane: Schema.String,
1020
+ identity: Schema.String,
1021
+ name: Schema.String,
1022
+ workspace: Schema.optional(Schema.String),
1023
+ tab: Schema.optional(Schema.String),
1024
+ title: Schema.optional(Schema.String),
1025
+ status: Schema.String,
1026
+ ready: Schema.Boolean
1027
+ });
1076
1028
  //#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
- });
1029
+ //#region src/terminal-session/infra/repository/terminal-bindings-store.ts
1030
+ const bindingSchema = Schema.Struct({
1031
+ handle: Schema.String,
1032
+ actorId: Schema.String,
1033
+ chatId: Schema.String,
1034
+ expires: Schema.optional(Schema.Number),
1035
+ agent: terminalAgentSchema
1036
+ });
1037
+ const snapshotSchema$1 = Schema.Struct({
1038
+ version: Schema.Literal(1),
1039
+ appId: Schema.String,
1040
+ bindings: Schema.Array(bindingSchema)
1041
+ });
1042
+ async function openTerminalBindingsStore(directory, appId) {
1043
+ const digest = createHash("sha256").update(appId).digest("hex");
1044
+ const filePath = join(directory, `bindings-${digest}.json`);
1045
+ const decode = (value) => {
1046
+ const snapshot = Schema.decodeUnknownSync(snapshotSchema$1)(value);
1047
+ if (snapshot.appId !== appId || snapshot.bindings.length > 1e3 || new Set(snapshot.bindings.map((binding) => binding.handle)).size !== snapshot.bindings.length || snapshot.bindings.some((binding) => !/^[a-f0-9]{12}$/.test(binding.handle) || binding.expires !== void 0 && !Number.isFinite(binding.expires))) throw new Error("Invalid terminal binding snapshot");
1048
+ return snapshot.bindings;
1049
+ };
1050
+ let initial = [];
1051
+ try {
1052
+ const raw = await readFile(filePath, "utf8");
1053
+ initial = decode(JSON.parse(raw));
1054
+ await chmod(filePath, 384);
1055
+ } catch (error) {
1056
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw new Error("Cannot restore terminal bindings", { cause: error });
1097
1057
  }
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
1058
  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
- //#region src/terminal-session/infra/models/terminal-agent-schema.ts
1332
- /**
1333
- * File schema for the Application `TerminalAgent` snapshot, shared by every
1334
- * terminal-session store that persists an occupant identity (bindings, conversation
1335
- * states) so validation cannot drift between stores.
1336
- */
1337
- const terminalAgentSchema = Schema.Struct({
1338
- kind: Schema.Literals(["agent", "terminal"]),
1339
- session: Schema.String,
1340
- pane: Schema.String,
1341
- identity: Schema.String,
1342
- name: Schema.String,
1343
- workspace: Schema.optional(Schema.String),
1344
- tab: Schema.optional(Schema.String),
1345
- title: Schema.optional(Schema.String),
1346
- status: Schema.String,
1347
- ready: Schema.Boolean
1348
- });
1349
- //#endregion
1350
- //#region src/terminal-session/infra/repository/terminal-bindings-store.ts
1351
- const bindingSchema = Schema.Struct({
1352
- handle: Schema.String,
1353
- actorId: Schema.String,
1354
- chatId: Schema.String,
1355
- expires: Schema.optional(Schema.Number),
1356
- agent: terminalAgentSchema
1357
- });
1358
- const snapshotSchema$1 = Schema.Struct({
1359
- version: Schema.Literal(1),
1360
- appId: Schema.String,
1361
- bindings: Schema.Array(bindingSchema)
1362
- });
1363
- async function openTerminalBindingsStore(directory, appId) {
1364
- const digest = createHash("sha256").update(appId).digest("hex");
1365
- const filePath = join(directory, `bindings-${digest}.json`);
1366
- const decode = (value) => {
1367
- const snapshot = Schema.decodeUnknownSync(snapshotSchema$1)(value);
1368
- if (snapshot.appId !== appId || snapshot.bindings.length > 1e3 || new Set(snapshot.bindings.map((binding) => binding.handle)).size !== snapshot.bindings.length || snapshot.bindings.some((binding) => !/^[a-f0-9]{12}$/.test(binding.handle) || binding.expires !== void 0 && !Number.isFinite(binding.expires))) throw new Error("Invalid terminal binding snapshot");
1369
- return snapshot.bindings;
1370
- };
1371
- let initial = [];
1372
- try {
1373
- const raw = await readFile(filePath, "utf8");
1374
- initial = decode(JSON.parse(raw));
1375
- await chmod(filePath, 384);
1376
- } catch (error) {
1377
- if (!isNodeErrorWithCode(error, "ENOENT")) throw new Error("Cannot restore terminal bindings", { cause: error });
1378
- }
1379
- return {
1380
- initial,
1381
- save: (bindings) => Effect.uninterruptible(Effect.tryPromise({
1382
- try: async () => {
1383
- const snapshot = {
1384
- version: 1,
1385
- appId,
1386
- bindings
1387
- };
1388
- const validated = decode(snapshot);
1389
- await writeAtomicTextFile(filePath, JSON.stringify({
1390
- ...snapshot,
1391
- bindings: validated
1392
- }), {
1393
- mode: 384,
1394
- durable: true
1395
- });
1396
- },
1397
- catch: (error) => error
1398
- }))
1059
+ initial,
1060
+ save: (bindings) => Effect.uninterruptible(Effect.tryPromise({
1061
+ try: async () => {
1062
+ const snapshot = {
1063
+ version: 1,
1064
+ appId,
1065
+ bindings
1066
+ };
1067
+ const validated = decode(snapshot);
1068
+ await writeAtomicTextFile(filePath, JSON.stringify({
1069
+ ...snapshot,
1070
+ bindings: validated
1071
+ }), {
1072
+ mode: 384,
1073
+ durable: true
1074
+ });
1075
+ },
1076
+ catch: (error) => error
1077
+ }))
1399
1078
  };
1400
1079
  }
1401
1080
  //#endregion
@@ -1560,8 +1239,7 @@ async function openTerminalConversationStates(directory, appId) {
1560
1239
  * soon as the holding process exits or crashes, so the next opener recovers
1561
1240
  * automatically and no pid-based reclamation runs. Normal stop joins all work
1562
1241
  * 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.
1242
+ * process exits.
1565
1243
  */
1566
1244
  function createDirectoryUnlessPresent(path) {
1567
1245
  return mkdir(path, {
@@ -1645,7 +1323,7 @@ async function openTerminalMessageClaims(directory, appId, platform) {
1645
1323
  catch: (error) => error
1646
1324
  })),
1647
1325
  /**
1648
- * Read-only legacy fence lookup with the exact claim digest. Existence is the
1326
+ * Read-only fence lookup with the exact claim digest. Existence is the
1649
1327
  * fence: arbitrary or invalid file contents still count as claimed. `false` is
1650
1328
  * only returned for a missing entry (ENOENT); every other I/O failure
1651
1329
  * propagates. Never creates, mutates or deletes historic files.
@@ -1818,8 +1496,10 @@ function decodeFeishuCardCallback(raw) {
1818
1496
  }
1819
1497
  //#endregion
1820
1498
  //#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)) }) }));
1499
+ const decodeImageUpload = Schema.decodeUnknownOption(Schema.Union([Schema.Struct({ image_key: Schema.NonEmptyString }), Schema.Struct({
1500
+ data: Schema.Struct({ image_key: Schema.NonEmptyString }),
1501
+ image_key: Schema.optional(Schema.Null)
1502
+ })]));
1823
1503
  const decodeMessageAck = Schema.decodeUnknownOption(Schema.Struct({ code: Schema.Literal(0) }));
1824
1504
  const decodeBotIdentity = Schema.decodeUnknownOption(Schema.Struct({
1825
1505
  code: Schema.Literal(0),
@@ -1830,26 +1510,15 @@ const decodeRawMessage = Schema.decodeUnknownOption(Schema.Struct({ msg: Schema.
1830
1510
  Schema.Number,
1831
1511
  Schema.Boolean
1832
1512
  ])) }));
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
- */
1513
+ /** Uploads one image and returns its `image_key`; any other response reports the upload as failed. */
1839
1514
  async function uploadFeishuImage(client, image) {
1840
1515
  const uploaded = await client.im.image.create({ data: {
1841
1516
  image_type: "message",
1842
1517
  image: Buffer.from(image)
1843
1518
  } });
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");
1519
+ const decoded = decodeImageUpload(uploaded);
1520
+ if (Option.isNone(decoded)) throw new Error("Feishu image upload failed");
1521
+ return "data" in decoded.value ? decoded.value.data.image_key : decoded.value.image_key;
1853
1522
  }
1854
1523
  /** Sends one message and rejects with the caller's error text unless the SDK acknowledges numeric code 0. */
1855
1524
  async function sendFeishuSdkMessage(client, message, errorMessage) {
@@ -1896,8 +1565,8 @@ const hasPiMarker = (value) => {
1896
1565
  * Classifies a raw card callback before any handler runs: Pi cards carry
1897
1566
  * `value.rivus_action`, Herdr cards carry `value.bridge === "herdr"` or the v2
1898
1567
  * 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.
1568
+ * the marker). Both markers must be refused by both sides; unmarked cards are
1569
+ * invalid and get a refresh instruction.
1901
1570
  */
1902
1571
  function classifyFeishuCardOwnership(terminal) {
1903
1572
  if (!terminal) return "unmarked";
@@ -2130,6 +1799,446 @@ function createFeishuTerminalDelivery(client, options) {
2130
1799
  };
2131
1800
  }
2132
1801
  //#endregion
1802
+ //#region src/herdr/lib/herdr-socket-frame.ts
1803
+ /**
1804
+ * Object gate for a Herdr response part, not a field reader: the callers read their
1805
+ * fields by name with their own error texts. `Schema.Record(Schema.String, Schema.Unknown)`
1806
+ * is deliberately used only as that gate; a hand-written `typeof … === "object"` guard is
1807
+ * forbidden (authoring guide, Validation).
1808
+ */
1809
+ const herdrResponseGate = Schema.Record(Schema.String, Schema.Unknown);
1810
+ function object(value) {
1811
+ if (!Schema.is(herdrResponseGate)(value)) throw new Error("Invalid Herdr response");
1812
+ return value;
1813
+ }
1814
+ function string(value) {
1815
+ if (typeof value !== "string") throw new Error("Invalid Herdr response field");
1816
+ return value;
1817
+ }
1818
+ var HerdrRequestError = class extends Error {
1819
+ code;
1820
+ constructor(code) {
1821
+ super(`Herdr error: ${code}`);
1822
+ this.code = code;
1823
+ }
1824
+ };
1825
+ const subscriptionAck = Schema.Struct({
1826
+ id: Schema.String,
1827
+ result: Schema.Struct({ type: Schema.Literal("subscription_started") })
1828
+ });
1829
+ const workerEvent = Schema.Struct({
1830
+ event: Schema.Literals([
1831
+ "pane.agent_status_changed",
1832
+ "pane_exited",
1833
+ "pane_closed"
1834
+ ]),
1835
+ data: Schema.Struct({
1836
+ pane_id: Schema.NonEmptyString,
1837
+ agent_status: Schema.optional(Schema.Literals([
1838
+ "working",
1839
+ "idle",
1840
+ "done",
1841
+ "blocked",
1842
+ "unknown"
1843
+ ]))
1844
+ })
1845
+ });
1846
+ const decodeSubscriptionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Union([subscriptionAck, workerEvent])));
1847
+ //#endregion
1848
+ //#region src/herdr/infra/adapters/herdr-socket-request.ts
1849
+ function requestHerdrSocket(path, method, params, timeoutMs, signal) {
1850
+ return new Promise((resolve, reject) => {
1851
+ const id = randomUUID();
1852
+ const socket = createConnection({ path });
1853
+ let settled = false;
1854
+ let bytes = 0;
1855
+ let buffer = "";
1856
+ function finish(error, result) {
1857
+ if (settled) return;
1858
+ settled = true;
1859
+ clearTimeout(timer);
1860
+ signal.removeEventListener("abort", abort);
1861
+ socket.removeAllListeners("connect");
1862
+ socket.removeAllListeners("data");
1863
+ socket.removeAllListeners("end");
1864
+ socket.destroy();
1865
+ if (error) reject(error);
1866
+ else resolve(result);
1867
+ }
1868
+ const onError = (error) => finish(error);
1869
+ socket.once("close", () => socket.removeListener("error", onError));
1870
+ const abort = () => finish(/* @__PURE__ */ new Error("Herdr request aborted; input may have been submitted"));
1871
+ const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("Herdr request timed out; input may have been submitted")), timeoutMs);
1872
+ signal.addEventListener("abort", abort, { once: true });
1873
+ socket.setEncoding("utf8");
1874
+ socket.on("connect", () => socket.write(`${JSON.stringify({
1875
+ id,
1876
+ method,
1877
+ params
1878
+ })}\n`));
1879
+ socket.on("error", onError);
1880
+ socket.on("end", () => finish(/* @__PURE__ */ new Error("Herdr closed without a response; outcome unknown")));
1881
+ socket.on("data", (chunk) => {
1882
+ bytes += Buffer.byteLength(chunk);
1883
+ if (bytes > 1048576) return finish(/* @__PURE__ */ new Error("Herdr response exceeds one MiB"));
1884
+ buffer += chunk;
1885
+ const newline = buffer.indexOf("\n");
1886
+ if (newline < 0) return;
1887
+ try {
1888
+ const response = object(JSON.parse(buffer.slice(0, newline)));
1889
+ if (response.id !== id) throw new Error("Herdr response identity mismatch");
1890
+ if (response.error) throw new HerdrRequestError(string(object(response.error).code));
1891
+ finish(void 0, object(response.result));
1892
+ } catch (error) {
1893
+ finish(error);
1894
+ }
1895
+ });
1896
+ if (signal.aborted) abort();
1897
+ });
1898
+ }
1899
+ async function subscribeHerdrWorker(path, paneId, timeoutMs, signal, onEvent) {
1900
+ const id = randomUUID();
1901
+ const socket = createConnection({
1902
+ path,
1903
+ signal
1904
+ });
1905
+ socket.setEncoding("utf8");
1906
+ socket.setTimeout(timeoutMs, () => socket.destroy(/* @__PURE__ */ new Error("Herdr subscription timed out")));
1907
+ socket.once("connect", () => {
1908
+ socket.write(JSON.stringify({
1909
+ id,
1910
+ method: "events.subscribe",
1911
+ params: { subscriptions: [
1912
+ {
1913
+ type: "pane.agent_status_changed",
1914
+ pane_id: paneId
1915
+ },
1916
+ { type: "pane.exited" },
1917
+ { type: "pane.closed" }
1918
+ ] }
1919
+ }) + "\n");
1920
+ });
1921
+ let accepted = false;
1922
+ let buffer = "";
1923
+ try {
1924
+ for await (const chunk of socket) {
1925
+ buffer += chunk;
1926
+ let newline = buffer.indexOf("\n");
1927
+ while (newline !== -1) {
1928
+ if (Buffer.byteLength(buffer.slice(0, newline)) > 1048576) throw new Error("Herdr event exceeds one MiB");
1929
+ const line = decodeSubscriptionLine(buffer.slice(0, newline));
1930
+ buffer = buffer.slice(newline + 1);
1931
+ newline = buffer.indexOf("\n");
1932
+ if (!accepted) {
1933
+ if (line._tag === "None" || !("id" in line.value) || line.value.id !== id) throw new Error("Herdr subscription was rejected");
1934
+ accepted = true;
1935
+ socket.setTimeout(0);
1936
+ continue;
1937
+ }
1938
+ if (line._tag === "Some" && "event" in line.value && line.value.data.pane_id === paneId) {
1939
+ const status = line.value.event === "pane.agent_status_changed" ? line.value.data.agent_status : "lost";
1940
+ if (status !== void 0 && status !== "unknown") onEvent(status);
1941
+ }
1942
+ }
1943
+ if (Buffer.byteLength(buffer) > 1048576) throw new Error("Herdr event exceeds one MiB");
1944
+ }
1945
+ } finally {
1946
+ socket.destroy();
1947
+ }
1948
+ }
1949
+ //#endregion
1950
+ //#region src/herdr/infra/adapters/herdr-socket-client.ts
1951
+ const label = Schema.optional(Schema.NullOr(Schema.String));
1952
+ const sessionSnapshot = Schema.decodeUnknownSync(Schema.Struct({ snapshot: Schema.Struct({
1953
+ protocol: Schema.Literal(22),
1954
+ panes: Schema.Array(Schema.Struct({
1955
+ pane_id: Schema.String,
1956
+ terminal_id: Schema.String,
1957
+ workspace_id: Schema.String,
1958
+ tab_id: Schema.String,
1959
+ agent: Schema.optional(Schema.NullOr(Schema.String)),
1960
+ agent_session: Schema.optional(Schema.Json),
1961
+ agent_status: Schema.String,
1962
+ label,
1963
+ terminal_title_stripped: label,
1964
+ title: label
1965
+ })),
1966
+ agents: Schema.Array(Schema.Struct({
1967
+ pane_id: Schema.String,
1968
+ terminal_id: Schema.String,
1969
+ name: label,
1970
+ launch_pending: Schema.optional(Schema.Unknown)
1971
+ })),
1972
+ workspaces: Schema.optional(Schema.Array(Schema.Struct({
1973
+ workspace_id: Schema.String,
1974
+ label: Schema.String
1975
+ }))),
1976
+ tabs: Schema.optional(Schema.Array(Schema.Struct({
1977
+ tab_id: Schema.String,
1978
+ label: Schema.String
1979
+ })))
1980
+ }) }));
1981
+ async function discoverSessions(root) {
1982
+ const uid = process.getuid?.();
1983
+ const directory = await lstat(root);
1984
+ if (!directory.isDirectory() || directory.uid !== uid || (directory.mode & 18) !== 0) throw new Error("Herdr discovery root must be an owned, non-writable directory");
1985
+ const candidates = [{
1986
+ name: "default",
1987
+ socketPath: join(root, "herdr.sock")
1988
+ }];
1989
+ const named = join(root, "sessions");
1990
+ const info = await lstat(named).catch((error) => {
1991
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
1992
+ return null;
1993
+ });
1994
+ if (info) {
1995
+ if (!info.isDirectory() || info.uid !== uid || (info.mode & 18) !== 0) throw new Error("Invalid Herdr sessions directory");
1996
+ for (const entry of (await readdir(named, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) if (entry.isDirectory()) candidates.push({
1997
+ name: entry.name,
1998
+ socketPath: join(named, entry.name, "herdr.sock")
1999
+ });
2000
+ }
2001
+ const found = [];
2002
+ for (const candidate of candidates) if (await lstat(candidate.socketPath).catch((error) => {
2003
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw error;
2004
+ return null;
2005
+ })) found.push(candidate);
2006
+ return found;
2007
+ }
2008
+ function createHerdrSocketClient(sessions, timeoutMs = 5e3, discoverSessionsIn) {
2009
+ if (!sessions.length && !discoverSessionsIn || new Set(sessions.map((s) => s.name)).size !== sessions.length) throw new Error("Herdr requires unique configured session names");
2010
+ if (discoverSessionsIn && !isAbsolute(discoverSessionsIn)) throw new Error("Herdr discovery root must be absolute");
2011
+ let configs = new Map(sessions.map((session) => [session.name, session]));
2012
+ const refresh = () => Effect.tryPromise({
2013
+ try: async () => {
2014
+ const discovered = discoverSessionsIn ? await discoverSessions(discoverSessionsIn) : [];
2015
+ const next = /* @__PURE__ */ new Map();
2016
+ const paths = /* @__PURE__ */ new Set();
2017
+ for (const config of [...sessions, ...discovered]) {
2018
+ const path = resolve(config.socketPath);
2019
+ if (paths.has(path)) continue;
2020
+ if (next.has(config.name)) throw new Error("Herdr session aliases collide");
2021
+ next.set(config.name, {
2022
+ ...config,
2023
+ socketPath: path
2024
+ });
2025
+ paths.add(path);
2026
+ }
2027
+ configs = next;
2028
+ return [...next.keys()];
2029
+ },
2030
+ catch: (error) => error
2031
+ });
2032
+ async function checkedSocket(session) {
2033
+ const config = configs.get(session);
2034
+ if (config === void 0) throw new Error("Unknown Herdr session");
2035
+ const socket = await lstat(config.socketPath);
2036
+ 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");
2037
+ return {
2038
+ path: config.socketPath,
2039
+ generation: `${socket.dev}:${socket.ino}:${socket.birthtimeMs}`
2040
+ };
2041
+ }
2042
+ const invoke = (session, method, params, deadline = timeoutMs) => Effect.tryPromise({
2043
+ try: async (signal) => {
2044
+ const { path, generation } = await checkedSocket(session);
2045
+ return {
2046
+ result: await requestHerdrSocket(path, method, params, deadline, signal),
2047
+ generation
2048
+ };
2049
+ },
2050
+ catch: (error) => error
2051
+ });
2052
+ const listSession = (session) => invoke(session, "session.snapshot", {}).pipe(Effect.flatMap(({ result, generation }) => Effect.try(() => {
2053
+ const { snapshot } = sessionSnapshot(result);
2054
+ const workspaces = new Map(snapshot.workspaces?.map((entry) => [entry.workspace_id, entry.label]));
2055
+ const tabs = new Map(snapshot.tabs?.map((entry) => [entry.tab_id, entry.label]));
2056
+ return snapshot.panes.map((value) => {
2057
+ const pane = value.pane_id;
2058
+ const terminal = value.terminal_id;
2059
+ const agent = snapshot.agents.find((item) => item.pane_id === pane && item.terminal_id === terminal);
2060
+ const kind = value.agent || "terminal";
2061
+ const workspace = value.workspace_id;
2062
+ const tab = value.tab_id;
2063
+ const title = [
2064
+ agent?.name,
2065
+ value.label,
2066
+ value.terminal_title_stripped,
2067
+ value.title
2068
+ ].find(Boolean) ?? kind;
2069
+ return {
2070
+ session,
2071
+ pane,
2072
+ identity: createHash("sha256").update(JSON.stringify([
2073
+ generation,
2074
+ session,
2075
+ pane,
2076
+ terminal,
2077
+ kind,
2078
+ value.agent_session ?? null
2079
+ ])).digest("hex"),
2080
+ kind: kind === "terminal" ? "terminal" : "agent",
2081
+ name: `${pane} / ${workspaces.get(workspace) ?? workspace} / ${tabs.get(tab) ?? tab} / ${title}`,
2082
+ workspace: workspaces.get(workspace) ?? workspace,
2083
+ tab: tabs.get(tab) ?? tab,
2084
+ title,
2085
+ status: value.agent_status,
2086
+ ready: kind !== "terminal" && agent !== void 0 && (agent.launch_pending === void 0 || agent.launch_pending === false)
2087
+ };
2088
+ });
2089
+ })));
2090
+ const resolve$1 = (agent) => refresh().pipe(Effect.flatMap(() => listSession(agent.session)), Effect.flatMap((agents) => {
2091
+ const current = agents.find((item) => item.pane === agent.pane && item.identity === agent.identity);
2092
+ return current ? Effect.succeed(current) : Effect.fail(new TerminalTargetChangedError());
2093
+ }));
2094
+ return {
2095
+ subscribeWorker: (session, paneId, onEvent) => refresh().pipe(Effect.andThen(Effect.tryPromise({
2096
+ try: async (signal) => {
2097
+ const { path } = await checkedSocket(session);
2098
+ return subscribeHerdrWorker(path, paneId, timeoutMs, signal, onEvent);
2099
+ },
2100
+ catch: (error) => error
2101
+ }))),
2102
+ invoke: (session, method, params, deadline) => refresh().pipe(Effect.flatMap(() => invoke(session, method, params, deadline))),
2103
+ list: () => refresh().pipe(Effect.flatMap((names) => Effect.all(names.map((name) => listSession(name).pipe(Effect.map((agents) => ({
2104
+ agents,
2105
+ unavailableSessions: []
2106
+ })), Effect.catch(() => Effect.succeed({
2107
+ agents: [],
2108
+ unavailableSessions: [name]
2109
+ })))), { concurrency: 4 })), Effect.map((results) => ({
2110
+ agents: results.flatMap((result) => result.agents),
2111
+ unavailableSessions: results.flatMap((result) => result.unavailableSessions)
2112
+ }))),
2113
+ inspect: resolve$1,
2114
+ read: (agent, visible) => resolve$1(agent).pipe(Effect.flatMap(() => invoke(agent.session, "pane.read", {
2115
+ pane_id: agent.pane,
2116
+ source: visible ? "visible" : "recent_unwrapped",
2117
+ format: "text",
2118
+ lines: visible ? 80 : 120
2119
+ })), Effect.flatMap(({ result }) => Effect.try(() => {
2120
+ const read = object(result.read);
2121
+ return {
2122
+ text: string(read.text),
2123
+ truncated: read.truncated === true
2124
+ };
2125
+ }))),
2126
+ prompt: (agent, text) => resolve$1(agent).pipe(Effect.catch((error) => Effect.fail(error instanceof TerminalTargetChangedError ? error : new TerminalPromptPreflightError("目标暂不可用;未提交指令。可 /exit 后重新选择。"))), Effect.flatMap((current) => {
2127
+ const verdict = evaluateTerminalWriteInput(current, true);
2128
+ return verdict.allowed ? Effect.void : Effect.fail(new TerminalPromptPreflightError(`Input rejected: ${verdict.text}`));
2129
+ }), Effect.flatMap(() => invoke(agent.session, "agent.prompt", {
2130
+ target: agent.pane,
2131
+ text
2132
+ })), Effect.asVoid)
2133
+ };
2134
+ }
2135
+ //#endregion
2136
+ //#region src/herdr/infra/adapters/terminal-text-image.ts
2137
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
2138
+ const emoji = /* @__PURE__ */ new RegExp("^\\p{RGI_Emoji}$", "v");
2139
+ const maxRows = 80;
2140
+ const maxColumns = 160;
2141
+ const maxGraphemes = 160;
2142
+ const maxLineCodeUnits = 1024;
2143
+ const maxUniqueGraphemes = 1024;
2144
+ const cellWidth = 10.8;
2145
+ const shapeWorkerUrl = new URL(`data:text/javascript,${encodeURIComponent(`
2146
+ import { parentPort, workerData } from "node:worker_threads";
2147
+ const { Resvg } = await import(workerData.resvgModuleUrl);
2148
+ parentPort.postMessage(new Resvg(workerData.svg, workerData.options).toString());
2149
+ parentPort.close();
2150
+ `)}`);
2151
+ function shapeAtlas(svg, options) {
2152
+ return new Promise((resolve, reject) => {
2153
+ const worker = new Worker(shapeWorkerUrl, { workerData: {
2154
+ svg,
2155
+ options,
2156
+ resvgModuleUrl: import.meta.resolve("@resvg/resvg-js")
2157
+ } });
2158
+ let settled = false;
2159
+ const deadline = setTimeout(() => finish(/* @__PURE__ */ new Error("Terminal image shaping timed out.")), 3e4);
2160
+ function finish(error, paths) {
2161
+ if (settled) return;
2162
+ settled = true;
2163
+ clearTimeout(deadline);
2164
+ worker.terminate().then(() => {
2165
+ worker.removeAllListeners();
2166
+ if (error) reject(error);
2167
+ else resolve(paths);
2168
+ }, (terminationError) => {
2169
+ worker.removeAllListeners();
2170
+ reject(error ?? terminationError);
2171
+ });
2172
+ }
2173
+ worker.once("message", (paths) => {
2174
+ if (typeof paths !== "string") finish(/* @__PURE__ */ new Error("Terminal image shaping returned invalid paths."));
2175
+ else finish(void 0, paths);
2176
+ });
2177
+ worker.once("error", (error) => finish(error));
2178
+ worker.once("exit", (code) => finish(/* @__PURE__ */ new Error(`Terminal image shaping exited before replying (${code}).`)));
2179
+ });
2180
+ }
2181
+ function graphemeColumns(grapheme) {
2182
+ if (emoji.test(grapheme)) return 2;
2183
+ for (const codePoint of grapheme) if (!/[\p{Mark}\p{Format}]/u.test(codePoint)) return eastAsianWidth(codePoint.codePointAt(0));
2184
+ return 0;
2185
+ }
2186
+ function renderLine(line, y, glyphs) {
2187
+ const nodes = [];
2188
+ let column = 0;
2189
+ let graphemes = 0;
2190
+ let codeUnits = 0;
2191
+ for (const { segment } of segmenter.segment(line)) {
2192
+ const columns = segment === " " ? 4 - column % 4 : graphemeColumns(segment);
2193
+ if (column + columns > maxColumns || graphemes >= maxGraphemes || codeUnits + segment.length > maxLineCodeUnits) return {
2194
+ svg: nodes.join(""),
2195
+ clipped: true
2196
+ };
2197
+ if (segment !== " " && segment !== " ") {
2198
+ let index = glyphs.get(segment);
2199
+ if (index === void 0) {
2200
+ if (glyphs.size >= maxUniqueGraphemes) throw new Error("Terminal image exceeds its unique grapheme budget.");
2201
+ index = glyphs.size;
2202
+ glyphs.set(segment, index);
2203
+ }
2204
+ nodes.push(`<g transform="translate(${24 + column * cellWidth} ${y - 20})" clip-path="url(#cell-${Math.max(1, columns)})"><use href="#terminal-glyph-${index}"/></g>`);
2205
+ }
2206
+ column += columns;
2207
+ graphemes += 1;
2208
+ codeUnits += segment.length;
2209
+ }
2210
+ return {
2211
+ svg: nodes.join(""),
2212
+ clipped: false
2213
+ };
2214
+ }
2215
+ function escapeXml(text) {
2216
+ return text.replace(/[&<>"']/g, (char) => ({
2217
+ "&": "&amp;",
2218
+ "<": "&lt;",
2219
+ ">": "&gt;",
2220
+ "\"": "&quot;",
2221
+ "'": "&apos;"
2222
+ })[char]);
2223
+ }
2224
+ async function renderTerminalTextImage(screen, fontFiles) {
2225
+ const { renderAsync } = await import("@resvg/resvg-js");
2226
+ const glyphs = /* @__PURE__ */ new Map();
2227
+ const allLines = stripVTControlCharacters(screen.text).replace(/[^\P{Cc}\n\t]/gu, "").split("\n");
2228
+ const title = renderLine(stripVTControlCharacters(screen.title).replace(/\p{Cc}/gu, ""), 30, glyphs);
2229
+ const lines = allLines.slice(0, maxRows).map((line, index) => renderLine(line, 96 + index * 24, glyphs));
2230
+ const clipped = screen.truncated || allLines.length > maxRows || title.clipped || lines.some((line) => line.clipped);
2231
+ const width = 1800;
2232
+ const height = 100 + Math.max(1, lines.length) * 24;
2233
+ const label = `Terminal text rendering | ${new Date(screen.at).toISOString()}${clipped ? " | truncated" : ""}`;
2234
+ const body = lines.map((line) => line.svg).join("");
2235
+ 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: {
2236
+ loadSystemFonts: !fontFiles?.length,
2237
+ ...fontFiles ? { fontFiles: [...fontFiles] } : {},
2238
+ defaultFontFamily: "monospace"
2239
+ } })}</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();
2240
+ }
2241
+ //#endregion
2133
2242
  //#region src/bootstrap/feishu/herdr-config.ts
2134
2243
  /** Shared Herdr field schemas for the standalone options and the embedded route config. */
2135
2244
  const herdrSessionSchema = Schema.Struct({
@@ -2374,5 +2483,5 @@ function createHerdrFeishuBridgeRuntime(options) {
2374
2483
  };
2375
2484
  }
2376
2485
  //#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 };
2486
+ export { scalarField as C, trimmedTextField as D, tolerant as E, orInvalid as S, textField as T, TerminalMessageClaimLookup as _, createHerdrSocketClient as a, INVALID as b, createFeishuTerminalDelivery as c, fetchFeishuBotOpenId as d, decodeFeishuCardCallback as f, terminalAgentSchema as g, fileTerminalSessionStores as h, standaloneHerdrOptionsSchema as i, parseFeishuTerminalAction as l, fileConversationalTerminalSessionStores as m, openHerdrBridgeStores as n, HerdrRequestError as o, decodeFeishuTerminalEvent as p, embeddedHerdrRouteSchema as r, classifyFeishuCardOwnership as s, createHerdrFeishuBridgeRuntime as t, parseFeishuTerminalMessage as u, TextContent as v, scalarText as w, chained as x, decodeFeishuTerminalText as y };
2378
2487