@rivus/gateway 0.23.0 → 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.
@@ -1,13 +1,13 @@
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 { createConnection } from "node:net";
4
- import { chmod, lstat, mkdir, open, readFile, readdir } from "node:fs/promises";
5
- import { isAbsolute, join, resolve } from "node:path";
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
7
  import { writeAtomicTextFile } from "@rivus/platform/persistence";
8
- import { stripVTControlCharacters } from "node:util";
9
- import { createHash, randomBytes, randomUUID } from "node:crypto";
8
+ import { createHash, randomBytes } from "node:crypto";
10
9
  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,49 +313,6 @@ function createTerminalSessionBindings(options) {
313
313
  };
314
314
  }
315
315
  //#endregion
316
- //#region src/terminal-session/domain/bridge/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");
@@ -1635,6 +1592,7 @@ function parseFeishuTerminalAction(terminal, menuChats) {
1635
1592
  ...selection === void 0 ? {} : { selection }
1636
1593
  } : null;
1637
1594
  }
1595
+ /** @internal */
1638
1596
  function renderTerminalMenu(menu) {
1639
1597
  const plain = (content) => ({
1640
1598
  tag: "plain_text",
@@ -1799,340 +1757,6 @@ function createFeishuTerminalDelivery(client, options) {
1799
1757
  };
1800
1758
  }
1801
1759
  //#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
1760
  //#region src/herdr/infra/adapters/terminal-text-image.ts
2137
1761
  const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
2138
1762
  const emoji = /* @__PURE__ */ new RegExp("^\\p{RGI_Emoji}$", "v");
@@ -2483,5 +2107,5 @@ function createHerdrFeishuBridgeRuntime(options) {
2483
2107
  };
2484
2108
  }
2485
2109
  //#endregion
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 };
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 };
2487
2111