@rivus/gateway 0.21.2 → 0.22.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.
Files changed (31) hide show
  1. package/README.md +4 -1
  2. package/assets/audio-transcriber/fetch-model.mjs +63 -70
  3. package/assets/audio-transcriber/transcribe.mjs +38 -47
  4. package/assets/installation-policy.json +4 -3
  5. package/dist/bootstrap/feishu.d.ts +7 -2
  6. package/dist/bootstrap/feishu.js +19195 -17153
  7. package/dist/bootstrap/herdr-feishu.d.ts +1 -7
  8. package/dist/bootstrap/herdr-feishu.js +23 -12
  9. package/dist/chunks/automation-presentation.js +58 -60
  10. package/dist/chunks/feishu-receive-message.js +113 -0
  11. package/dist/chunks/herdr-feishu-runtime.js +1027 -642
  12. package/dist/chunks/public.d.ts +278 -0
  13. package/dist/chunks/public2.d.ts +10 -0
  14. package/dist/chunks/rivus-deployment-cli-process.d.ts +127 -455
  15. package/dist/chunks/rivus-home-deployment-env.js +1342 -1781
  16. package/dist/chunks/rivus-node-entrypoint.js +4349 -4063
  17. package/dist/index.d.ts +23 -11
  18. package/dist/mcp.d.ts +10 -9
  19. package/dist/mcp.js +43 -43
  20. package/package.json +15 -11
  21. package/templates/a-share-briefing-analysis.mjs +32 -34
  22. package/templates/a-share-briefing-renderer.mjs +175 -186
  23. package/templates/a-share-index-evidence.mjs +50 -54
  24. package/templates/a-share-market-briefing.mjs +37 -39
  25. package/templates/a-share-overseas-evidence.mjs +35 -39
  26. package/templates/a-share-policy-evidence.mjs +90 -96
  27. package/templates/a-share-sector-evidence.mjs +32 -35
  28. package/templates/acp-stdio-proxy.mjs +21 -22
  29. package/templates/current-weather.mjs +56 -58
  30. package/templates/html-drive-tools.mjs +130 -141
  31. package/templates/rivus-agents.plugin.mjs +55 -57
@@ -1,13 +1,140 @@
1
- import { Array as Array$1, Effect, Fiber, Result, Schema, Semaphore } from "effect";
2
- import { isAbsolute, join, resolve } from "node:path";
3
- import { chmod, lstat, mkdir, open, readFile, readdir, unlink } from "node:fs/promises";
4
- import { createHash, randomBytes, randomUUID } from "node:crypto";
1
+ import { Array as Array$1, Cause, Context, Effect, Exit, Fiber, Layer, Option, Result, Schema, Scope, Semaphore } from "effect";
2
+ import { unwrapExit } from "@rivus/platform/effect";
5
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";
6
+ import { isNodeErrorWithCode } from "@rivus/platform/filesystem";
6
7
  import { createConnection } from "node:net";
8
+ import { acquireProcessLock } from "@rivus/agent-kit-collab/process-lock";
9
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
7
10
  import { stripVTControlCharacters } from "node:util";
8
11
  import { Worker } from "node:worker_threads";
9
12
  import { eastAsianWidth } from "get-east-asian-width";
10
- //#region src/core/application/terminal-session/conversation-mode.ts
13
+ //#region src/feishu/infra/adapters/protocol/feishu-field-schemas.ts
14
+ /**
15
+ * Feishu content is read tolerantly: a field whose value has the wrong type is
16
+ * treated as absent, so the next fallback field or the default applies.
17
+ */
18
+ function tolerant(schema) {
19
+ return Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeed(Option.none()))));
20
+ }
21
+ /** Marks a value that is present but has the wrong type. JSON cannot produce a symbol. */
22
+ const INVALID = Symbol("invalid Feishu field");
23
+ /** A value that decodes as `schema` or as INVALID; for array items and fields whose presence matters. */
24
+ function orInvalid(schema) {
25
+ return Schema.Union([schema, Schema.UniqueSymbol(INVALID)]).pipe(Schema.catchDecoding(() => Effect.succeed(Option.some(INVALID))));
26
+ }
27
+ /**
28
+ * A field read with `a ?? b`: `null` or `undefined` falls through to the next
29
+ * field like an absent one, but any other value of the wrong type stops the
30
+ * chain as INVALID.
31
+ */
32
+ function chained(schema) {
33
+ return Schema.optionalKey(orInvalid(Schema.Union([
34
+ schema,
35
+ Schema.Null,
36
+ Schema.Undefined
37
+ ])));
38
+ }
39
+ const textField = tolerant(Schema.String);
40
+ const scalarField = tolerant(Schema.Union([
41
+ Schema.String,
42
+ Schema.Number,
43
+ Schema.Boolean
44
+ ]));
45
+ /** A trimmed, non-empty identifier; a blank or non-string value is absent. */
46
+ const trimmedTextField = tolerant(Schema.Trim.check(Schema.isNonEmpty()));
47
+ function scalarText(value) {
48
+ return value === void 0 ? void 0 : String(value);
49
+ }
50
+ //#endregion
51
+ //#region src/feishu/infra/adapters/protocol/feishu-text-content.ts
52
+ /** The text-message content object shared by the full content decoder and the lightweight terminal-text entry. */
53
+ const TextContent = Schema.Struct({ text: textField });
54
+ const decodeTextContent = Schema.decodeUnknownOption(Schema.fromJsonString(TextContent));
55
+ /**
56
+ * Decode only the terminal text from a text message's raw content. It preserves the full decoder's text-message
57
+ * behavior without importing the other message types or the Markdown walker: invalid JSON, a non-object/scalar/array
58
+ * value, and a missing or non-string `text` return `undefined`; an empty string stays `""`; the `@_user_N` prefix is
59
+ * left for the terminal parser.
60
+ */
61
+ function decodeFeishuTerminalText(content) {
62
+ const decoded = decodeTextContent(content);
63
+ return Option.isSome(decoded) ? decoded.value.text : void 0;
64
+ }
65
+ //#endregion
66
+ //#region src/terminal-session/application/ports.ts
67
+ var TerminalSessionPort = class extends Context.Service()("@rivus/gateway/terminal-session/TerminalSessionPort") {};
68
+ var TerminalBindingStore = class extends Context.Service()("@rivus/gateway/terminal-session/TerminalBindingStore") {};
69
+ var ConversationStateStore = class extends Context.Service()("@rivus/gateway/terminal-session/ConversationStateStore") {};
70
+ var TerminalMessageClaims = class extends Context.Service()("@rivus/gateway/terminal-session/TerminalMessageClaims") {};
71
+ var TerminalMessageClaimLookup = class extends Context.Service()("@rivus/gateway/terminal-session/TerminalMessageClaimLookup") {};
72
+ //#endregion
73
+ //#region src/terminal-session/application/services/terminal-session-bindings.ts
74
+ var TerminalBindingPersistenceError = class extends Error {
75
+ constructor(cause) {
76
+ super("Terminal binding snapshot could not be saved", { cause });
77
+ }
78
+ };
79
+ function createTerminalSessionBindings(options) {
80
+ let bindings = new Map((options.store?.initial ?? []).map((entry) => [entry.handle, entry]));
81
+ const serial = Semaphore.makeUnsafe(1);
82
+ const commit = (candidate) => Effect.gen(function* () {
83
+ if (options.store) yield* options.store.save([...candidate.values()]).pipe(Effect.mapError((cause) => new TerminalBindingPersistenceError(cause)));
84
+ bindings = candidate;
85
+ });
86
+ const insert = (candidate, entry) => {
87
+ candidate.delete(entry.handle);
88
+ candidate.set(entry.handle, entry);
89
+ if (candidate.size > 1e3) candidate.delete(candidate.keys().next().value);
90
+ return entry;
91
+ };
92
+ const fresh = (candidate, message, agent, expires) => {
93
+ let handle = options.newHandle();
94
+ while (candidate.has(handle)) handle = options.newHandle();
95
+ return insert(candidate, {
96
+ handle,
97
+ actorId: message.actorId,
98
+ chatId: message.chatId,
99
+ agent,
100
+ ...expires === void 0 ? {} : { expires }
101
+ });
102
+ };
103
+ return {
104
+ lookup: (handle, message) => serial.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
105
+ const binding = bindings.get(handle);
106
+ if (!binding) return { kind: "missing" };
107
+ if (binding.actorId !== message.actorId || binding.chatId !== message.chatId) return { kind: "unauthorized" };
108
+ const candidate = new Map(bindings);
109
+ insert(candidate, binding);
110
+ yield* commit(candidate);
111
+ return {
112
+ kind: "found",
113
+ binding
114
+ };
115
+ }))),
116
+ selections: (message, agents) => serial.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
117
+ const candidate = new Map(bindings);
118
+ const selected = agents.map((agent) => {
119
+ const existing = [...candidate.values()].find((entry) => entry.expires === void 0 && entry.actorId === message.actorId && entry.chatId === message.chatId && entry.agent.session === agent.session && entry.agent.pane === agent.pane && entry.agent.identity === agent.identity);
120
+ return existing ? insert(candidate, {
121
+ ...existing,
122
+ agent
123
+ }) : fresh(candidate, message, agent);
124
+ });
125
+ if (agents.length) yield* commit(candidate);
126
+ return selected;
127
+ }))),
128
+ form: (message, agent, expires) => serial.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
129
+ const candidate = new Map(bindings);
130
+ const binding = fresh(candidate, message, agent, expires);
131
+ yield* commit(candidate);
132
+ return binding;
133
+ })))
134
+ };
135
+ }
136
+ //#endregion
137
+ //#region src/terminal-session/application/services/conversation-mode.ts
11
138
  const stateKey = (actorId, chatId) => `${actorId}\u0000${chatId}`;
12
139
  /**
13
140
  * Conversation mode state machine (normal/selection/locked per authorized
@@ -186,71 +313,7 @@ function createConversationMode(options) {
186
313
  };
187
314
  }
188
315
  //#endregion
189
- //#region src/core/application/terminal-session/terminal-session-bindings.ts
190
- var TerminalBindingPersistenceError = class extends Error {
191
- constructor(cause) {
192
- super("Terminal binding snapshot could not be saved", { cause });
193
- }
194
- };
195
- function createTerminalSessionBindings(options) {
196
- let bindings = new Map((options.store?.initial ?? []).map((entry) => [entry.handle, entry]));
197
- const serial = Semaphore.makeUnsafe(1);
198
- const commit = (candidate) => Effect.gen(function* () {
199
- if (options.store) yield* options.store.save([...candidate.values()]).pipe(Effect.mapError((cause) => new TerminalBindingPersistenceError(cause)));
200
- bindings = candidate;
201
- });
202
- const insert = (candidate, entry) => {
203
- candidate.delete(entry.handle);
204
- candidate.set(entry.handle, entry);
205
- if (candidate.size > 1e3) candidate.delete(candidate.keys().next().value);
206
- return entry;
207
- };
208
- const fresh = (candidate, message, agent, expires) => {
209
- let handle = options.newHandle();
210
- while (candidate.has(handle)) handle = options.newHandle();
211
- return insert(candidate, {
212
- handle,
213
- actorId: message.actorId,
214
- chatId: message.chatId,
215
- agent,
216
- ...expires === void 0 ? {} : { expires }
217
- });
218
- };
219
- return {
220
- lookup: (handle, message) => serial.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
221
- const binding = bindings.get(handle);
222
- if (!binding) return { kind: "missing" };
223
- if (binding.actorId !== message.actorId || binding.chatId !== message.chatId) return { kind: "unauthorized" };
224
- const candidate = new Map(bindings);
225
- insert(candidate, binding);
226
- yield* commit(candidate);
227
- return {
228
- kind: "found",
229
- binding
230
- };
231
- }))),
232
- selections: (message, agents) => serial.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
233
- const candidate = new Map(bindings);
234
- const selected = agents.map((agent) => {
235
- const existing = [...candidate.values()].find((entry) => entry.expires === void 0 && entry.actorId === message.actorId && entry.chatId === message.chatId && entry.agent.session === agent.session && entry.agent.pane === agent.pane && entry.agent.identity === agent.identity);
236
- return existing ? insert(candidate, {
237
- ...existing,
238
- agent
239
- }) : fresh(candidate, message, agent);
240
- });
241
- if (agents.length) yield* commit(candidate);
242
- return selected;
243
- }))),
244
- form: (message, agent, expires) => serial.withPermits(1)(Effect.uninterruptible(Effect.gen(function* () {
245
- const candidate = new Map(bindings);
246
- const binding = fresh(candidate, message, agent, expires);
247
- yield* commit(candidate);
248
- return binding;
249
- })))
250
- };
251
- }
252
- //#endregion
253
- //#region src/core/application/terminal-session/terminal-session-bridge.ts
316
+ //#region src/terminal-session/domain/bridge/value-objects/terminal-bridge-model.ts
254
317
  var TerminalTargetChangedError = class extends Error {
255
318
  constructor() {
256
319
  super("Herdr target changed; select the target again");
@@ -292,17 +355,19 @@ function evaluateTerminalWriteInput(agent, writable) {
292
355
  if (!writable) return refused("read-only");
293
356
  return { allowed: true };
294
357
  }
295
- function createTerminalSessionBridge(options) {
358
+ //#endregion
359
+ //#region src/terminal-session/application/use-cases/terminal-session-bridge.ts
360
+ function buildBridge(options, ports) {
296
361
  if (!options.actors.length || !options.chats.length) throw new Error("Explicit actor and chat allowlists required");
297
362
  const bindings = createTerminalSessionBindings({
298
363
  newHandle: options.newHandle,
299
- store: options.bindings
364
+ store: ports.bindings
300
365
  });
301
- const mode = options.conversation ? createConversationMode({
302
- epoch: options.conversation.epoch,
303
- states: options.conversation.states,
366
+ const mode = ports.conversation ? createConversationMode({
367
+ epoch: ports.conversation.epoch,
368
+ states: ports.conversation.states,
304
369
  bindings,
305
- sessions: options.sessions,
370
+ sessions: ports.sessions,
306
371
  now: options.now
307
372
  }) : void 0;
308
373
  const watches = /* @__PURE__ */ new Map();
@@ -327,6 +392,8 @@ function createTerminalSessionBridge(options) {
327
392
  };
328
393
  const frozenReply = (message) => reply(message, "会话状态暂不可用(保存未确认);本条未处理,也未转发。");
329
394
  const capacityReply = (message) => reply(message, "会话状态名额已满(64),请先 /exit 其他会话后再进入。");
395
+ const admission = Semaphore.makeUnsafe(1);
396
+ const withAdmission = (work) => admission.withPermits(1)(work);
330
397
  const runCapturedSend = (message, agent, text) => Effect.gen(function* () {
331
398
  const targetChanged = () => withAdmission(mode.markLockedStale(message.actorId, message.chatId, {
332
399
  identity: agent.identity,
@@ -340,7 +407,7 @@ function createTerminalSessionBridge(options) {
340
407
  kind: "reply",
341
408
  reply: frozenReply(message)
342
409
  };
343
- const inspected = yield* options.sessions.inspect(agent).pipe(Effect.result);
410
+ const inspected = yield* ports.sessions.inspect(agent).pipe(Effect.result);
344
411
  if (Result.isFailure(inspected)) {
345
412
  if (inspected.failure instanceof TerminalTargetChangedError) return yield* targetChanged();
346
413
  return {
@@ -357,7 +424,7 @@ function createTerminalSessionBridge(options) {
357
424
  kind: "reply",
358
425
  reply: frozenReply(message)
359
426
  };
360
- return yield* options.sessions.prompt(agent, text).pipe(Effect.map(() => ({
427
+ return yield* ports.sessions.prompt(agent, text).pipe(Effect.map(() => ({
361
428
  kind: "reply",
362
429
  reply: reply(message, "指令已提交一次;尚未确认 agent 已处理或完成,请查看输出。")
363
430
  })), Effect.catch((error) => error instanceof TerminalTargetChangedError ? targetChanged() : Effect.succeed({
@@ -379,12 +446,12 @@ function createTerminalSessionBridge(options) {
379
446
  }
380
447
  });
381
448
  const refreshDetail = (message, agent, text) => Effect.gen(function* () {
382
- const current = yield* options.sessions.inspect(agent);
449
+ const current = yield* ports.sessions.inspect(agent);
383
450
  const [selected] = yield* bindings.selections(message, [current]);
384
451
  return detail(message, current, selected.handle, text);
385
452
  });
386
453
  const inventory = (message, command, argument = "", notice, issued) => Effect.gen(function* () {
387
- const { agents, unavailableSessions } = yield* options.sessions.list();
454
+ const { agents, unavailableSessions } = yield* ports.sessions.list();
388
455
  const page = Math.max(0, Math.min(Math.floor(Number(argument) || 0), Math.max(0, Math.ceil(agents.length / 20) - 1)));
389
456
  const visible = command === "menu" ? agents.slice(page * 20, (page + 1) * 20) : agents;
390
457
  const choices = (yield* bindings.selections(message, visible)).map(({ agent, handle }) => ({
@@ -493,14 +560,14 @@ function createTerminalSessionBridge(options) {
493
560
  return detail(message, binding.agent, selected.handle, removed ? "已取消关注;agent 仍在运行。" : "当前没有关注此会话。");
494
561
  }
495
562
  if (command === "open" || command === "compose" || command === "refresh") {
496
- const current = yield* options.sessions.inspect(binding.agent);
563
+ const current = yield* ports.sessions.inspect(binding.agent);
497
564
  const verdict = writable(current);
498
565
  if (verdict.allowed) return yield* form(message, current);
499
566
  const [selected] = yield* bindings.selections(message, [current]);
500
567
  return detail(message, current, selected.handle, `${verdict.text}请刷新状态后再试。`);
501
568
  }
502
569
  if (command === "read" || command === "screen") {
503
- const read = yield* options.sessions.read(binding.agent, command === "screen");
570
+ const read = yield* ports.sessions.read(binding.agent, command === "screen");
504
571
  const title = `${handle} | ${binding.agent.name}`;
505
572
  const at = options.now();
506
573
  return command === "screen" ? {
@@ -514,7 +581,7 @@ function createTerminalSessionBridge(options) {
514
581
  }
515
582
  if (command === "send" || command === "submit") {
516
583
  if (command === "submit") {
517
- if (binding.expires === void 0 || !(yield* options.claim({
584
+ if (binding.expires === void 0 || !(yield* ports.claim({
518
585
  ...message,
519
586
  id: `form:${handle}`
520
587
  }))) return yield* refreshDetail(message, binding.agent, "此表单已提交或失效,请查看输出;新指令请重新打开输入框。");
@@ -527,19 +594,19 @@ function createTerminalSessionBridge(options) {
527
594
  if (command === "submit") return yield* refreshDetail(message, binding.agent, "指令需为 1–1000 个字符,且不能包含终端控制字符;请点击“发下一条指令”重新填写。");
528
595
  return reply(message, "Use /herdr send HANDLE -- TEXT (1–8000 characters, no terminal control characters).");
529
596
  }
530
- const current = yield* options.sessions.inspect(binding.agent);
597
+ const current = yield* ports.sessions.inspect(binding.agent);
531
598
  const [selected] = yield* bindings.selections(message, [current]);
532
599
  const verdict = writable(current);
533
600
  if (!verdict.allowed) return detail(message, current, selected.handle, `Input rejected: ${verdict.text}`);
534
601
  if (command === "submit" && binding.expires <= options.now()) return yield* form(message, current, text);
535
602
  if (mode?.isFrozen()) return detail(message, current, selected.handle, frozenReply(message).text);
536
- return yield* options.sessions.prompt(binding.agent, text).pipe(Effect.as(detail(message, current, selected.handle, "指令已提交一次;尚未确认 agent 已处理或完成,请查看输出。")), Effect.catch((error) => error instanceof TerminalTargetChangedError ? Effect.fail(error) : Effect.succeed(detail(message, current, selected.handle, error instanceof TerminalPromptPreflightError ? error.message : "提交结果不确定(uncertain),不会自动重试。请先查看输出,确认后再发送新指令。"))));
603
+ return yield* ports.sessions.prompt(binding.agent, text).pipe(Effect.as(detail(message, current, selected.handle, "指令已提交一次;尚未确认 agent 已处理或完成,请查看输出。")), Effect.catch((error) => error instanceof TerminalTargetChangedError ? Effect.fail(error) : Effect.succeed(detail(message, current, selected.handle, error instanceof TerminalPromptPreflightError ? error.message : "提交结果不确定(uncertain),不会自动重试。请先查看输出,确认后再发送新指令。"))));
537
604
  }
538
605
  if (command === "watch") {
539
606
  for (const [key, watch] of watches) if (watch.expires <= options.now()) watches.delete(key);
540
607
  const key = watchKey(message, binding.agent);
541
608
  if (!watches.has(key) && watches.size >= 8) return detail(message, binding.agent, handle, "已达到 8 个关注目标,请先取消其他关注。");
542
- const current = yield* options.sessions.inspect(binding.agent);
609
+ const current = yield* ports.sessions.inspect(binding.agent);
543
610
  if (!isCurrent()) return null;
544
611
  const [selected] = yield* bindings.selections(message, [current]);
545
612
  if (!isCurrent()) return null;
@@ -555,8 +622,6 @@ function createTerminalSessionBridge(options) {
555
622
  return reply(message, "Unknown command; use /herdr help.");
556
623
  }).pipe(Effect.catch((error) => isCurrent() ? recover(message, binding, error) : Effect.succeed(null)), Effect.map((result) => isCurrent() ? result : null));
557
624
  };
558
- const admission = Semaphore.makeUnsafe(1);
559
- const withAdmission = (work) => admission.withPermits(1)(work);
560
625
  const inventoryWork = (message, run) => ({
561
626
  kind: "inventory",
562
627
  message,
@@ -732,7 +797,7 @@ function createTerminalSessionBridge(options) {
732
797
  kind: "done",
733
798
  result: { kind: "consumed" }
734
799
  };
735
- if (!(yield* options.claim(message))) return {
800
+ if (!(yield* ports.claim(message))) return {
736
801
  kind: "done",
737
802
  result: { kind: "consumed" }
738
803
  };
@@ -881,7 +946,7 @@ function createTerminalSessionBridge(options) {
881
946
  if (watches.get(key) === watch) watches.delete(key);
882
947
  continue;
883
948
  }
884
- const current = yield* options.sessions.inspect(watch.binding.agent).pipe(Effect.map((agent) => ({
949
+ const current = yield* ports.sessions.inspect(watch.binding.agent).pipe(Effect.map((agent) => ({
885
950
  status: agent.status,
886
951
  failed: false
887
952
  })), Effect.catch((error) => Effect.succeed({
@@ -913,358 +978,49 @@ function createTerminalSessionBridge(options) {
913
978
  })
914
979
  };
915
980
  }
916
- //#endregion
917
- //#region src/adapters/feishu/terminal-session/feishu-terminal-session.ts
918
- function parseFeishuTerminalMessage(event) {
919
- if (!event || typeof event !== "object") return null;
920
- const value = event;
921
- const message = value.message;
922
- if (value.sender?.sender_type !== "user" || !value.sender.sender_id?.open_id || !message?.message_id || !message.chat_id || message.message_type !== "text") return null;
923
- try {
924
- const content = JSON.parse(message.content ?? "{}");
925
- if (!content || typeof content !== "object" || !("text" in content) || typeof content.text !== "string") return null;
926
- const sentAt = Number(message.create_time);
927
- if (!Number.isFinite(sentAt)) return null;
928
- return {
929
- id: message.message_id,
930
- actorId: value.sender.sender_id.open_id,
931
- chatId: message.chat_id,
932
- sentAt,
933
- text: content.text.replace(/^@_user_\d+\s*/, "")
981
+ function makeBridge(options, conversation) {
982
+ return Effect.gen(function* () {
983
+ const claims = yield* TerminalMessageClaims;
984
+ const ports = {
985
+ bindings: yield* TerminalBindingStore,
986
+ claim: (message) => claims.claim(message),
987
+ conversation,
988
+ sessions: yield* TerminalSessionPort
934
989
  };
935
- } catch {
936
- return null;
937
- }
990
+ return yield* Effect.try({
991
+ catch: (error) => error,
992
+ try: () => buildBridge(options, ports)
993
+ });
994
+ });
938
995
  }
939
- async function deliverTerminalBridgeReply(reply, delivery, render) {
940
- if (reply.menu && delivery.sendCard) return delivery.sendCard(reply.chatId, renderTerminalMenu({
941
- ...reply.menu,
942
- ...reply.menu.kind === "recovery" ? { notice: reply.text } : {}
943
- }));
944
- if (!reply.screen) return delivery.sendText(reply.chatId, reply.text);
945
- try {
946
- await delivery.sendImage(reply.chatId, await render(reply.screen));
947
- } catch {
948
- await delivery.sendText(reply.chatId, `${reply.text} | ${new Date(reply.screen.at).toISOString()}${reply.screen.truncated || reply.screen.text.length > 12e3 ? " | truncated(已截断)" : ""}\n图片暂不可用,以下是终端文字:\n${reply.screen.text.slice(-12e3)}`);
949
- }
996
+ /** The standalone bridge: commands only, no conversation mode. */
997
+ function makeTerminalSessionBridge(options) {
998
+ return makeBridge(options, void 0);
950
999
  }
951
- const V2_FORM_NAME = /^rivus_herdr_v2_submit_([a-f0-9]{12})$/;
952
- const HANDLE_PATTERN = /^[a-f0-9]{12}$/;
953
- /**
954
- * Issued selection credential carried verbatim from the rendered row; the
955
- * schema rejects malformed payloads instead of trusting typeof checks.
956
- */
957
- const selectionCredentialSchema = Schema.Struct({
958
- epoch: Schema.Trimmed.check(Schema.isNonEmpty()),
959
- generation: Schema.Number.check(Schema.makeFilter((generation) => Number.isSafeInteger(generation) && generation >= 0)),
960
- actorId: Schema.Trimmed.check(Schema.isNonEmpty()),
961
- chatId: Schema.Trimmed.check(Schema.isNonEmpty()),
962
- handle: Schema.String.check(Schema.makeFilter((handle) => HANDLE_PATTERN.test(handle)))
963
- });
964
- /** Flattened (or pre-flattened) card callback envelope as the SDK hands it to handlers. */
965
- const cardActionEventSchema = Schema.Struct({
966
- event_id: Schema.optional(Schema.String),
967
- create_time: Schema.optional(Schema.String),
968
- operator: Schema.optional(Schema.Struct({
969
- open_id: Schema.optional(Schema.String),
970
- operator_id: Schema.optional(Schema.Struct({ open_id: Schema.optional(Schema.String) }))
971
- })),
972
- event_key: Schema.optional(Schema.String),
973
- context: Schema.optional(Schema.Struct({ open_chat_id: Schema.optional(Schema.String) })),
974
- action: Schema.optional(Schema.Struct({
975
- tag: Schema.optional(Schema.String),
976
- name: Schema.optional(Schema.String),
977
- value: Schema.optional(Schema.Struct({
978
- bridge: Schema.optional(Schema.Literal("herdr")),
979
- rivus_action: Schema.optional(Schema.String),
980
- command: Schema.optional(Schema.String),
981
- handle: Schema.optional(Schema.String.check(Schema.makeFilter((handle) => HANDLE_PATTERN.test(handle)))),
982
- page: Schema.optional(Schema.Number),
983
- selection: Schema.optional(selectionCredentialSchema)
984
- })),
985
- form_value: Schema.optional(Schema.Struct({ prompt: Schema.optional(Schema.String) }))
986
- }))
987
- });
988
- const decodeCardActionEvent = (event) => {
989
- try {
990
- return Schema.decodeUnknownSync(cardActionEventSchema)(event);
991
- } catch {
992
- return;
993
- }
994
- };
995
- /** The wrapped v2 envelope shape: the card callback lives under `event`. */
996
- const eventEnvelopeSchema = Schema.Struct({ event: Schema.Record(Schema.String, Schema.Unknown) });
997
- const decodeEventEnvelope = Schema.decodeUnknownSync(eventEnvelopeSchema);
998
- /**
999
- * Card callbacks arrive either flattened by the SDK (action at top level) or
1000
- * wrapped under `event` (Pi intake shape); both carry the same payload.
1001
- */
1002
- const readCardEnvelope = (event) => {
1003
- const flat = decodeCardActionEvent(event);
1004
- if (flat !== void 0 && (flat.action !== void 0 || flat.event_key !== void 0 || flat.operator !== void 0)) return flat;
1005
- let inner;
1006
- try {
1007
- inner = decodeEventEnvelope(event).event;
1008
- } catch {
1009
- return flat;
1010
- }
1011
- return decodeCardActionEvent(inner);
1012
- };
1013
- const hasPiMarker = (value) => {
1014
- const rivusAction = value?.value?.rivus_action;
1015
- return rivusAction !== void 0 && rivusAction.length > 0;
1016
- };
1000
+ /** The embedded bridge with conversation mode; `epoch` invalidates cards issued by an earlier run. */
1001
+ function makeConversationalTerminalSessionBridge(options, epoch) {
1002
+ return Effect.gen(function* () {
1003
+ return yield* makeBridge(options, {
1004
+ epoch,
1005
+ states: yield* ConversationStateStore
1006
+ });
1007
+ });
1008
+ }
1009
+ //#endregion
1010
+ //#region src/terminal-session/infra/adapters/herdr/herdr-socket-request.ts
1017
1011
  /**
1018
- * Classifies a raw card callback before any handler runs: Pi cards carry
1019
- * `value.rivus_action`, Herdr cards carry `value.bridge === "herdr"` or the v2
1020
- * form name (a submit button cannot carry a value, so its explicit v2 name is
1021
- * the marker). Both markers must be refused by both sides; unmarked legacy
1022
- * cards are invalid and get a refresh instruction.
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).
1023
1016
  */
1024
- function classifyFeishuCardOwnership(event) {
1025
- const decoded = readCardEnvelope(event);
1026
- if (!decoded) return "unmarked";
1027
- const pi = hasPiMarker(decoded.action);
1028
- const herdr = decoded.action?.value?.bridge === "herdr" || V2_FORM_NAME.test(decoded.action?.name ?? "");
1029
- if (pi && herdr) return "conflict";
1030
- if (pi) return "pi";
1031
- return herdr ? "herdr" : "unmarked";
1032
- }
1033
- function parseFeishuTerminalAction(event, menuChats) {
1034
- const decoded = readCardEnvelope(event);
1035
- if (!decoded) return null;
1036
- const actorId = decoded.operator?.open_id ?? decoded.operator?.operator_id?.open_id;
1037
- if (!actorId || !decoded.event_id || !decoded.create_time) return null;
1038
- let text;
1039
- let chatId;
1040
- let selection;
1041
- if (decoded.event_key) {
1042
- if (!["herdr_list", "herdr_help"].includes(decoded.event_key)) return null;
1043
- chatId = menuChats[actorId];
1044
- text = decoded.event_key === "herdr_list" ? "/herdr menu" : "/herdr help";
1045
- } else {
1046
- chatId = decoded.context?.open_chat_id;
1047
- const action = decoded.action;
1048
- const form = V2_FORM_NAME.exec(action?.name ?? "");
1049
- if (form) {
1050
- if (hasPiMarker(action) || action?.form_value?.prompt === void 0) return null;
1051
- text = `/herdr submit ${form[1]} -- ${action.form_value.prompt}`;
1052
- } else {
1053
- if (action?.tag !== "button" || action.value?.bridge !== "herdr" || hasPiMarker(action)) return null;
1054
- const command = action.value.command;
1055
- if (command === "use" || command === "select") {
1056
- const handle = action.value.handle;
1057
- const credential = action.value.selection;
1058
- if (handle === void 0 || credential === void 0 || credential.handle !== handle) return null;
1059
- text = `/herdr use ${handle}`;
1060
- selection = credential;
1061
- } else if (command === "menu") {
1062
- const page = action.value.page ?? 0;
1063
- if (!Number.isSafeInteger(page) || page < 0) return null;
1064
- text = `/herdr menu ${page}`;
1065
- } else {
1066
- if (command === void 0 || ![
1067
- "open",
1068
- "refresh",
1069
- "compose",
1070
- "read",
1071
- "screen",
1072
- "watch",
1073
- "unwatch"
1074
- ].includes(command)) return null;
1075
- const handle = action.value.handle;
1076
- if (handle === void 0) return null;
1077
- text = `/herdr ${command} ${handle}`;
1078
- }
1079
- }
1080
- }
1081
- const sentAt = Number(decoded.create_time) / (decoded.event_key ? 1 : 1e3);
1082
- if (!Number.isFinite(sentAt)) return null;
1083
- return chatId ? {
1084
- id: `action:${decoded.event_id}`,
1085
- actorId,
1086
- chatId,
1087
- sentAt,
1088
- text,
1089
- ...selection === void 0 ? {} : { selection }
1090
- } : null;
1091
- }
1092
- function renderTerminalMenu(menu) {
1093
- const plain = (content) => ({
1094
- tag: "plain_text",
1095
- content
1096
- });
1097
- const button = (label, command, handle, page, selection) => ({
1098
- tag: "button",
1099
- text: plain(label),
1100
- type: "default",
1101
- behaviors: [{
1102
- type: "callback",
1103
- value: {
1104
- bridge: "herdr",
1105
- command,
1106
- handle,
1107
- page,
1108
- ...selection === void 0 ? {} : { selection }
1109
- }
1110
- }]
1111
- });
1112
- const rowButton = (label, agent) => agent.selection === void 0 ? button(label, "open", agent.handle) : button(label, "use", agent.handle, void 0, agent.selection);
1113
- const status = (agent) => {
1114
- if (agent.status === "unavailable") return "离线/暂不可用";
1115
- if (agent.kind === "terminal") return "终端只读";
1116
- if (agent.ready && ["idle", "done"].includes(agent.status)) return "等待输入";
1117
- return {
1118
- working: "执行中",
1119
- blocked: "等待处理",
1120
- idle: "空闲,尚未确认可输入",
1121
- done: "运行已结束,请刷新确认",
1122
- unknown: "状态未知"
1123
- }[agent.status] ?? "暂不可输入";
1124
- };
1125
- const elements = [];
1126
- if (menu.notice) elements.push({
1127
- tag: "div",
1128
- text: plain(menu.notice)
1129
- });
1130
- if (menu.kind === "list") {
1131
- elements.push({
1132
- tag: "markdown",
1133
- content: `**选择会话** · 第 ${(menu.page ?? 0) + 1}/${menu.pages ?? 1} 页`
1134
- });
1135
- const groups = Array$1.groupBy(menu.agents, (agent) => `${agent.session} / ${agent.workspace ?? "会话"}`);
1136
- for (const [group, agents] of Object.entries(groups)) {
1137
- elements.push({
1138
- tag: "div",
1139
- text: plain(group)
1140
- });
1141
- for (const agent of agents) elements.push(rowButton(`${agent.pane} · ${agent.tab ? agent.tab + " / " : ""}${agent.title ?? agent.name} · ${status(agent)}`.slice(0, 100), agent));
1142
- }
1143
- if (menu.unavailableSessions?.length) elements.push({
1144
- tag: "div",
1145
- text: plain(`以下 session 无法读取,列表不完整:${menu.unavailableSessions.join(", ")}`)
1146
- });
1147
- if (!menu.agents.length) elements.push({
1148
- tag: "markdown",
1149
- content: "当前没有可用会话。"
1150
- });
1151
- if ((menu.page ?? 0) > 0) elements.push(button("上一页", "menu", void 0, menu.page - 1));
1152
- if ((menu.page ?? 0) + 1 < (menu.pages ?? 1)) elements.push(button("下一页", "menu", void 0, menu.page + 1));
1153
- } else if (menu.kind === "recovery") {
1154
- if (menu.agents[0]) elements.push(button("刷新原会话", "refresh", menu.agents[0].handle));
1155
- } else {
1156
- const agent = menu.agents[0];
1157
- elements.push({
1158
- tag: "div",
1159
- text: plain(`目标:${agent.session} / ${agent.name}\n状态:${status(agent)}`)
1160
- });
1161
- if (menu.kind === "form") {
1162
- elements.push({
1163
- tag: "form",
1164
- name: "herdr_prompt",
1165
- elements: [{
1166
- tag: "input",
1167
- name: "prompt",
1168
- required: true,
1169
- input_type: "multiline_text",
1170
- max_length: 1e3,
1171
- ...menu.draft === void 0 ? {} : { default_value: menu.draft },
1172
- placeholder: plain("输入要交给此 agent 的指令"),
1173
- label: plain("指令内容")
1174
- }, {
1175
- tag: "button",
1176
- name: `rivus_herdr_v2_submit_${agent.handle}`,
1177
- text: plain("发送"),
1178
- type: "primary_filled",
1179
- form_action_type: "submit"
1180
- }]
1181
- });
1182
- elements.push({
1183
- tag: "markdown",
1184
- content: "每个表单只提交一次;提交后可通过“看输出”核对执行结果。"
1185
- });
1186
- } else {
1187
- const verdict = evaluateTerminalWriteInput(agent, menu.writable);
1188
- if (verdict.allowed) elements.push(button("发下一条指令", "compose", agent.handle));
1189
- else elements.push({
1190
- tag: "div",
1191
- text: plain(menu.writable && agent.kind === "agent" ? `${verdict.text}请查看输出,或刷新状态后再试。` : "此会话为只读模式。")
1192
- });
1193
- }
1194
- elements.push(button("关注状态", "watch", agent.handle), button("取消关注", "unwatch", agent.handle), button("看画面", "screen", agent.handle), button("看输出", "read", agent.handle), button("刷新当前会话", "refresh", agent.handle));
1195
- }
1196
- elements.push(button("刷新会话列表", "menu"));
1197
- return {
1198
- schema: "2.0",
1199
- config: {
1200
- width_mode: "default",
1201
- enable_forward: false
1202
- },
1203
- header: {
1204
- title: plain(menu.kind === "form" ? "向会话发送指令" : "Herdr 会话"),
1205
- template: "blue"
1206
- },
1207
- body: { elements }
1208
- };
1209
- }
1210
- function createFeishuTerminalDelivery(client, options) {
1211
- const refuseWhenStopped = () => {
1212
- if (options?.isStopped?.() === true) throw new Error("Herdr runtime is stopped; delivery refused");
1213
- };
1214
- return {
1215
- sendCard: async (chatId, card) => {
1216
- refuseWhenStopped();
1217
- if ((await client.im.message.create({
1218
- params: { receive_id_type: "chat_id" },
1219
- data: {
1220
- receive_id: chatId,
1221
- msg_type: "interactive",
1222
- content: JSON.stringify(card)
1223
- }
1224
- })).code !== 0) throw new Error("Feishu card delivery failed");
1225
- },
1226
- sendText: async (chatId, text) => {
1227
- refuseWhenStopped();
1228
- if ((await client.im.message.create({
1229
- params: { receive_id_type: "chat_id" },
1230
- data: {
1231
- receive_id: chatId,
1232
- msg_type: "text",
1233
- content: JSON.stringify({ text })
1234
- }
1235
- })).code !== 0) throw new Error("Feishu text delivery failed");
1236
- },
1237
- sendImage: async (chatId, bytes) => {
1238
- refuseWhenStopped();
1239
- const value = await client.im.image.create({ data: {
1240
- image_type: "message",
1241
- image: Buffer.from(bytes)
1242
- } });
1243
- const imageKey = value?.image_key ?? value?.data?.image_key;
1244
- if (!imageKey) throw new Error("Feishu image upload failed");
1245
- refuseWhenStopped();
1246
- if ((await client.im.message.create({
1247
- params: { receive_id_type: "chat_id" },
1248
- data: {
1249
- receive_id: chatId,
1250
- msg_type: "image",
1251
- content: JSON.stringify({ image_key: imageKey })
1252
- }
1253
- })).code !== 0) throw new Error("Feishu image delivery failed");
1254
- }
1255
- };
1256
- }
1257
- //#endregion
1258
- //#region src/adapters/herdr/session/herdr-socket-request.ts
1259
- const responseRecord = Schema.Record(Schema.String, Schema.Unknown);
1260
- const isResponseRecord = Schema.is(responseRecord);
1261
- const isString = Schema.is(Schema.String);
1262
- function object(value) {
1263
- if (!isResponseRecord(value)) throw new Error("Invalid Herdr response");
1264
- return value;
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;
1265
1021
  }
1266
1022
  function string(value) {
1267
- if (!isString(value)) throw new Error("Invalid Herdr response field");
1023
+ if (typeof value !== "string") throw new Error("Invalid Herdr response field");
1268
1024
  return value;
1269
1025
  }
1270
1026
  function requestHerdrSocket(path, method, params, timeoutMs, signal) {
@@ -1274,9 +1030,7 @@ function requestHerdrSocket(path, method, params, timeoutMs, signal) {
1274
1030
  let settled = false;
1275
1031
  let bytes = 0;
1276
1032
  let buffer = "";
1277
- const onError = (error) => finish(error);
1278
- socket.once("close", () => socket.removeListener("error", onError));
1279
- const finish = (error, result) => {
1033
+ function finish(error, result) {
1280
1034
  if (settled) return;
1281
1035
  settled = true;
1282
1036
  clearTimeout(timer);
@@ -1287,7 +1041,9 @@ function requestHerdrSocket(path, method, params, timeoutMs, signal) {
1287
1041
  socket.destroy();
1288
1042
  if (error) reject(error);
1289
1043
  else resolve(result);
1290
- };
1044
+ }
1045
+ const onError = (error) => finish(error);
1046
+ socket.once("close", () => socket.removeListener("error", onError));
1291
1047
  const abort = () => finish(/* @__PURE__ */ new Error("Herdr request aborted; input may have been submitted"));
1292
1048
  const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("Herdr request timed out; input may have been submitted")), timeoutMs);
1293
1049
  signal.addEventListener("abort", abort, { once: true });
@@ -1318,7 +1074,34 @@ function requestHerdrSocket(path, method, params, timeoutMs, signal) {
1318
1074
  });
1319
1075
  }
1320
1076
  //#endregion
1321
- //#region src/adapters/herdr/session/herdr-socket-client.ts
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
+ }
1322
1105
  function createHerdrSocketClient(sessions, timeoutMs = 5e3, discoverSessionsIn) {
1323
1106
  if (!sessions.length && !discoverSessionsIn || new Set(sessions.map((s) => s.name)).size !== sessions.length) throw new Error("Herdr requires unique configured session names");
1324
1107
  if (discoverSessionsIn && !isAbsolute(discoverSessionsIn)) throw new Error("Herdr discovery root must be absolute");
@@ -1438,53 +1221,133 @@ function createHerdrSocketClient(sessions, timeoutMs = 5e3, discoverSessionsIn)
1438
1221
  })), Effect.asVoid)
1439
1222
  };
1440
1223
  }
1441
- async function discoverSessions(root) {
1442
- const directory = await lstat(root);
1443
- if (!directory.isDirectory() || directory.uid !== process.getuid?.() || (directory.mode & 18) !== 0) throw new Error("Herdr discovery root must be an owned, non-writable directory");
1444
- const candidates = [{
1445
- name: "default",
1446
- socketPath: join(root, "herdr.sock")
1447
- }];
1448
- const named = join(root, "sessions");
1449
- const info = await lstat(named).catch((error) => {
1450
- if (error.code === "ENOENT") return null;
1451
- throw error;
1452
- });
1453
- if (info) {
1454
- if (!info.isDirectory() || info.uid !== process.getuid?.() || (info.mode & 18) !== 0) throw new Error("Invalid Herdr sessions directory");
1455
- for (const entry of (await readdir(named, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) if (entry.isDirectory()) candidates.push({
1456
- name: entry.name,
1457
- socketPath: join(named, entry.name, "herdr.sock")
1458
- });
1459
- }
1460
- const found = [];
1461
- for (const candidate of candidates) if (await lstat(candidate.socketPath).catch((error) => {
1462
- if (error.code === "ENOENT") return null;
1463
- throw error;
1464
- })) found.push(candidate);
1465
- return found;
1466
- }
1467
1224
  //#endregion
1468
- //#region src/adapters/outbound/persistence/terminal-session/terminal-agent-schema.ts
1469
- /**
1470
- * File schema for the Application `TerminalAgent` snapshot, shared by every
1471
- * terminal-session store that persists an occupant identity (bindings, conversation
1472
- * states) so validation cannot drift between stores.
1473
- */
1474
- const terminalAgentSchema = Schema.Struct({
1475
- kind: Schema.Literals(["agent", "terminal"]),
1476
- session: Schema.String,
1477
- pane: Schema.String,
1478
- identity: Schema.String,
1479
- name: Schema.String,
1480
- workspace: Schema.optional(Schema.String),
1481
- tab: Schema.optional(Schema.String),
1482
- title: Schema.optional(Schema.String),
1483
- status: Schema.String,
1484
- ready: Schema.Boolean
1485
- });
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
+ });
1486
1349
  //#endregion
1487
- //#region src/adapters/outbound/persistence/terminal-session/terminal-bindings-store.ts
1350
+ //#region src/terminal-session/infra/repository/terminal-bindings-store.ts
1488
1351
  const bindingSchema = Schema.Struct({
1489
1352
  handle: Schema.String,
1490
1353
  actorId: Schema.String,
@@ -1492,7 +1355,7 @@ const bindingSchema = Schema.Struct({
1492
1355
  expires: Schema.optional(Schema.Number),
1493
1356
  agent: terminalAgentSchema
1494
1357
  });
1495
- const snapshotSchema = Schema.Struct({
1358
+ const snapshotSchema$1 = Schema.Struct({
1496
1359
  version: Schema.Literal(1),
1497
1360
  appId: Schema.String,
1498
1361
  bindings: Schema.Array(bindingSchema)
@@ -1501,7 +1364,7 @@ async function openTerminalBindingsStore(directory, appId) {
1501
1364
  const digest = createHash("sha256").update(appId).digest("hex");
1502
1365
  const filePath = join(directory, `bindings-${digest}.json`);
1503
1366
  const decode = (value) => {
1504
- const snapshot = Schema.decodeUnknownSync(snapshotSchema)(value);
1367
+ const snapshot = Schema.decodeUnknownSync(snapshotSchema$1)(value);
1505
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");
1506
1369
  return snapshot.bindings;
1507
1370
  };
@@ -1511,7 +1374,7 @@ async function openTerminalBindingsStore(directory, appId) {
1511
1374
  initial = decode(JSON.parse(raw));
1512
1375
  await chmod(filePath, 384);
1513
1376
  } catch (error) {
1514
- if (error.code !== "ENOENT") throw new Error("Cannot restore terminal bindings", { cause: error });
1377
+ if (!isNodeErrorWithCode(error, "ENOENT")) throw new Error("Cannot restore terminal bindings", { cause: error });
1515
1378
  }
1516
1379
  return {
1517
1380
  initial,
@@ -1536,28 +1399,182 @@ async function openTerminalBindingsStore(directory, appId) {
1536
1399
  };
1537
1400
  }
1538
1401
  //#endregion
1539
- //#region src/adapters/outbound/persistence/terminal-session/terminal-message-claims.ts
1540
- const isErrnoCode = Schema.Struct({ code: Schema.String });
1402
+ //#region src/terminal-session/infra/repository/terminal-conversation-states.ts
1403
+ const modeStateSchema = Schema.Union([Schema.Struct({
1404
+ kind: Schema.Literal("selection"),
1405
+ actorId: Schema.String,
1406
+ chatId: Schema.String,
1407
+ since: Schema.Number
1408
+ }), Schema.Struct({
1409
+ kind: Schema.Literal("locked"),
1410
+ actorId: Schema.String,
1411
+ chatId: Schema.String,
1412
+ since: Schema.Number,
1413
+ handle: Schema.String,
1414
+ agent: terminalAgentSchema,
1415
+ stale: Schema.Boolean
1416
+ })]);
1417
+ const snapshotSchema = Schema.Struct({
1418
+ version: Schema.Literal(1),
1419
+ appId: Schema.String,
1420
+ states: Schema.Array(modeStateSchema)
1421
+ });
1422
+ const decodeSnapshot = Schema.decodeUnknownSync(snapshotSchema);
1423
+ function assertStateCollection(states) {
1424
+ if (states.length > 64) throw new Error("Conversation state snapshot exceeds capacity");
1425
+ if (new Set(states.map((state) => `${state.actorId}\u0000${state.chatId}`)).size !== states.length) throw new Error("Conversation state snapshot contains duplicate conversations");
1426
+ }
1427
+ function assertPrivateDirectory(info) {
1428
+ if (info.isSymbolicLink() || !info.isDirectory()) throw new Error("Conversation state directory is not a regular directory");
1429
+ if (info.uid !== process.getuid?.() || (info.mode & 63) !== 0) throw new Error("Unsafe conversation state directory permissions or owner");
1430
+ }
1431
+ function assertPrivateFile(info, label) {
1432
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error(`${label} is not a regular file`);
1433
+ if (info.uid !== process.getuid?.() || (info.mode & 127) !== 0) throw new Error(`Unsafe ${label} permissions or owner`);
1434
+ }
1435
+ /**
1436
+ * Versioned per-app conversation mode snapshot (selection/locked states) with a
1437
+ * durable initialization marker.
1438
+ *
1439
+ * Lock ownership: the caller must already hold the shared state-directory lifetime
1440
+ * lock (`openTerminalMessageClaims`) for this directory and keep it for the
1441
+ * store's lifetime; this factory never acquires a lock, releases one, or opens a
1442
+ * connection. The lock is released by the kernel when its holder exits or crashes;
1443
+ * an interrupted initialization or a snapshot missing after initialization still
1444
+ * refuses startup (fail closed) instead of erasing modes.
1445
+ */
1446
+ async function openTerminalConversationStates(directory, appId) {
1447
+ assertPrivateDirectory(await lstat(directory));
1448
+ const digest = createHash("sha256").update(appId).digest("hex");
1449
+ const snapshotPath = join(directory, `conversation-states-${digest}.json`);
1450
+ const markerPath = join(directory, `.conversation-states-initialized-${digest}`);
1451
+ const safeFile = async (path, label) => {
1452
+ const info = await lstat(path);
1453
+ if (!info.isFile()) throw new Error(`${label} is not a regular file`);
1454
+ assertPrivateFile(info, label);
1455
+ };
1456
+ const readStates = async () => {
1457
+ await safeFile(snapshotPath, "Conversation state snapshot");
1458
+ let snapshot;
1459
+ try {
1460
+ snapshot = decodeSnapshot(JSON.parse(await readFile(snapshotPath, "utf8")));
1461
+ } catch (error) {
1462
+ throw new Error("Cannot restore conversation states", { cause: error });
1463
+ }
1464
+ if (snapshot.appId !== appId) throw new Error("Conversation state snapshot belongs to another app");
1465
+ const states = snapshot.states;
1466
+ assertStateCollection(states);
1467
+ return states;
1468
+ };
1469
+ const durableSyncDirectory = async () => {
1470
+ const handle = await open(directory, "r");
1471
+ try {
1472
+ await handle.sync();
1473
+ } finally {
1474
+ await handle.close();
1475
+ }
1476
+ };
1477
+ const createMarker = async () => {
1478
+ const marker = await open(markerPath, "wx", 384);
1479
+ try {
1480
+ await marker.writeFile(JSON.stringify({
1481
+ version: 1,
1482
+ appId
1483
+ }));
1484
+ await marker.sync();
1485
+ await durableSyncDirectory();
1486
+ await marker.close();
1487
+ } catch (error) {
1488
+ await marker.close().catch(() => void 0);
1489
+ throw error;
1490
+ }
1491
+ };
1492
+ const markerStat = await lstat(markerPath).catch((error) => {
1493
+ if (isNodeErrorWithCode(error, "ENOENT")) return;
1494
+ throw error;
1495
+ });
1496
+ if (markerStat !== void 0) {
1497
+ if (!markerStat.isFile()) throw new Error("Conversation state initialization marker is not a regular file");
1498
+ assertPrivateFile(markerStat, "Conversation state initialization marker");
1499
+ }
1500
+ const snapshotStat = await lstat(snapshotPath).catch((error) => {
1501
+ if (isNodeErrorWithCode(error, "ENOENT")) return;
1502
+ throw error;
1503
+ });
1504
+ let initial;
1505
+ if (markerStat === void 0 && snapshotStat === void 0) {
1506
+ await createMarker();
1507
+ initial = [];
1508
+ await writeAtomicTextFile(snapshotPath, JSON.stringify({
1509
+ version: 1,
1510
+ appId,
1511
+ states: []
1512
+ }), {
1513
+ mode: 384,
1514
+ durable: true
1515
+ });
1516
+ } else {
1517
+ if (markerStat === void 0) throw new Error("Conversation state initialization is ambiguous; refusing startup");
1518
+ if (snapshotStat === void 0) throw new Error("Conversation state snapshot is missing after initialization");
1519
+ initial = await readStates();
1520
+ await writeAtomicTextFile(snapshotPath, JSON.stringify({
1521
+ version: 1,
1522
+ appId,
1523
+ states: initial
1524
+ }), {
1525
+ mode: 384,
1526
+ durable: true
1527
+ });
1528
+ }
1529
+ return {
1530
+ initial,
1531
+ save: (states) => Effect.uninterruptible(Effect.tryPromise({
1532
+ try: async () => {
1533
+ assertStateCollection(states);
1534
+ const validated = decodeSnapshot({
1535
+ version: 1,
1536
+ appId,
1537
+ states
1538
+ });
1539
+ await writeAtomicTextFile(snapshotPath, JSON.stringify({
1540
+ version: 1,
1541
+ appId,
1542
+ states: validated.states
1543
+ }), {
1544
+ mode: 384,
1545
+ durable: true
1546
+ });
1547
+ },
1548
+ catch: (error) => error
1549
+ }))
1550
+ };
1551
+ }
1552
+ //#endregion
1553
+ //#region src/terminal-session/infra/repository/terminal-message-claims.ts
1541
1554
  /**
1542
1555
  * Exclusive state-directory lifetime lock plus durable source-message and form
1543
1556
  * claims. The caller owns the lock for the store's lifetime: every terminal-session
1544
1557
  * or routing store in the same directory must be opened while this lock is held and
1545
- * must never acquire its own duplicate. Normal stop joins all work before `close`
1546
- * releases the lock; a crashed process leaves the lock on disk and recovery is
1547
- * manual — never an automatic PID/age-based steal. An operator may remove the lock
1548
- * only after the previous owner is verified stopped.
1558
+ * must never acquire its own duplicate. The lock is an exclusive kernel lock on
1559
+ * `bridge.process-lock` (opened as a SQLite database): the kernel releases it as
1560
+ * soon as the holding process exits or crashes, so the next opener recovers
1561
+ * automatically and no pid-based reclamation runs. Normal stop joins all work
1562
+ * 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.
1549
1565
  */
1550
1566
  function createDirectoryUnlessPresent(path) {
1551
1567
  return mkdir(path, {
1552
1568
  recursive: false,
1553
1569
  mode: 448
1554
1570
  }).then(() => void 0, (error) => {
1555
- if (!(Schema.is(isErrnoCode)(error) && error.code === "EEXIST")) throw error;
1571
+ if (!isNodeErrorWithCode(error, "EEXIST")) throw error;
1556
1572
  });
1557
1573
  }
1558
- async function openTerminalMessageClaims(directory, appId) {
1574
+ async function openTerminalMessageClaims(directory, appId, platform) {
1575
+ const uid = process.getuid?.();
1559
1576
  if (await lstat(join(directory, "..")).then(() => false, (error) => {
1560
- if (Schema.is(isErrnoCode)(error) && error.code === "ENOENT") return true;
1577
+ if (isNodeErrorWithCode(error, "ENOENT")) return true;
1561
1578
  throw error;
1562
1579
  })) throw new Error(`State directory parent does not exist: provision the deployment directory before starting (${join(directory, "..")})`);
1563
1580
  const parentInfo = await lstat(join(directory, ".."));
@@ -1565,25 +1582,23 @@ async function openTerminalMessageClaims(directory, appId) {
1565
1582
  await createDirectoryUnlessPresent(directory);
1566
1583
  const directoryInfo = await lstat(directory);
1567
1584
  if (directoryInfo.isSymbolicLink() || !directoryInfo.isDirectory()) throw new Error("Claims state directory is not a regular directory");
1568
- if (directoryInfo.uid !== process.getuid?.() || (directoryInfo.mode & 63) !== 0) throw new Error("Unsafe claims state directory permissions or owner");
1585
+ if (directoryInfo.uid !== uid || (directoryInfo.mode & 63) !== 0) throw new Error("Unsafe claims state directory permissions or owner");
1569
1586
  const parentHandle = await open(join(directory, ".."), "r");
1570
1587
  try {
1571
1588
  await parentHandle.sync();
1572
1589
  } finally {
1573
1590
  await parentHandle.close();
1574
1591
  }
1575
- const lockPath = join(directory, "bridge.lock");
1576
- const lock = await open(lockPath, "wx", 384);
1577
- await lock.writeFile(JSON.stringify({
1578
- pid: process.pid,
1579
- appId
1580
- }));
1592
+ const lockPath = join(directory, "bridge.process-lock");
1593
+ const acquired = await acquireProcessLock(platform, lockPath);
1594
+ if (!acquired.ok) throw new Error("the terminal bridge state directory is already held by another process");
1595
+ const lock = acquired.value;
1581
1596
  const claims = join(directory, "claims");
1582
1597
  try {
1583
1598
  await createDirectoryUnlessPresent(claims);
1584
1599
  const claimsInfo = await lstat(claims);
1585
1600
  if (claimsInfo.isSymbolicLink() || !claimsInfo.isDirectory()) throw new Error("Claims directory is not a regular directory");
1586
- if (claimsInfo.uid !== process.getuid?.() || (claimsInfo.mode & 63) !== 0) throw new Error("Unsafe claims directory permissions or owner");
1601
+ if (claimsInfo.uid !== uid || (claimsInfo.mode & 63) !== 0) throw new Error("Unsafe claims directory permissions or owner");
1587
1602
  const folder = await open(directory, "r");
1588
1603
  try {
1589
1604
  await folder.sync();
@@ -1591,8 +1606,7 @@ async function openTerminalMessageClaims(directory, appId) {
1591
1606
  await folder.close();
1592
1607
  }
1593
1608
  } catch (error) {
1594
- await lock.close().catch(() => void 0);
1595
- await unlink(lockPath);
1609
+ await lock.release().catch(() => void 0);
1596
1610
  throw error;
1597
1611
  }
1598
1612
  const claimPath = (messageId) => {
@@ -1606,7 +1620,7 @@ async function openTerminalMessageClaims(directory, appId) {
1606
1620
  try {
1607
1621
  file = await open(claimPath(message.id), "wx", 384);
1608
1622
  } catch (error) {
1609
- if (Schema.is(isErrnoCode)(error) && error.code === "EEXIST") return false;
1623
+ if (isNodeErrorWithCode(error, "EEXIST")) return false;
1610
1624
  throw error;
1611
1625
  }
1612
1626
  try {
@@ -1642,177 +1656,548 @@ async function openTerminalMessageClaims(directory, appId) {
1642
1656
  await lstat(claimPath(messageId));
1643
1657
  return true;
1644
1658
  } catch (error) {
1645
- if (Schema.is(isErrnoCode)(error) && error.code === "ENOENT") return false;
1659
+ if (isNodeErrorWithCode(error, "ENOENT")) return false;
1646
1660
  throw error;
1647
1661
  }
1648
1662
  },
1649
1663
  catch: (error) => error
1650
1664
  }),
1651
1665
  close: async () => {
1652
- await lock.close();
1653
- if (JSON.parse(await readFile(lockPath, "utf8")).pid === process.pid) await unlink(lockPath);
1666
+ await lock.release();
1654
1667
  }
1655
1668
  };
1656
1669
  }
1657
1670
  //#endregion
1658
- //#region src/bootstrap/feishu/herdr-config.ts
1659
- /** Shared Herdr field schemas for the standalone options and the embedded route config. */
1660
- const herdrSessionSchema = Schema.Struct({
1661
- name: Schema.Trimmed.check(Schema.isNonEmpty()),
1662
- socketPath: Schema.String.check(Schema.makeFilter(isAbsolute))
1663
- });
1664
- const nonEmptyStringArray = Schema.NonEmptyArray(Schema.Trimmed.check(Schema.isNonEmpty()));
1665
- const stringRecord = Schema.Record(Schema.String, Schema.Trimmed.check(Schema.isNonEmpty()));
1666
- const absolutePath = Schema.String.check(Schema.makeFilter(isAbsolute));
1667
- const optionalAbsolutePathArray = Schema.optional(Schema.Array(Schema.String.check(Schema.makeFilter(isAbsolute))));
1668
- const sharedHerdrFields = {
1669
- appId: Schema.Trimmed.check(Schema.isNonEmpty()),
1670
- sessions: Schema.optional(Schema.Array(herdrSessionSchema)),
1671
- discoverSessionsIn: Schema.optional(Schema.String.check(Schema.makeFilter(isAbsolute))),
1672
- allowedActors: nonEmptyStringArray,
1673
- allowedChats: nonEmptyStringArray,
1674
- menuChats: Schema.optional(stringRecord),
1675
- stateDirectory: absolutePath,
1676
- writable: Schema.optional(Schema.Boolean),
1677
- fontFiles: optionalAbsolutePathArray
1671
+ //#region src/terminal-session/infra/factories/file-terminal-session-stores.ts
1672
+ function fileTerminalMessageClaims(options) {
1673
+ return Layer.effectContext(Effect.acquireRelease(Effect.tryPromise({
1674
+ catch: (error) => error,
1675
+ try: () => openTerminalMessageClaims(options.directory, options.appId, options.platform)
1676
+ }), (claims) => Effect.promise(() => claims.close())).pipe(Effect.map((claims) => Context.make(TerminalMessageClaims, { claim: claims.claim }).pipe(Context.add(TerminalMessageClaimLookup, { hasClaim: claims.hasClaim })))));
1677
+ }
1678
+ function fileTerminalBindingStore(options) {
1679
+ return Layer.effect(TerminalBindingStore, Effect.tryPromise({
1680
+ catch: (error) => error,
1681
+ try: () => openTerminalBindingsStore(options.directory, options.appId)
1682
+ }));
1683
+ }
1684
+ function fileConversationStateStore(options) {
1685
+ return Layer.effect(ConversationStateStore, Effect.tryPromise({
1686
+ catch: (error) => error,
1687
+ try: () => openTerminalConversationStates(options.directory, options.appId)
1688
+ }));
1689
+ }
1690
+ /**
1691
+ * The bridge's stores over one state directory. The claims store is built first and takes the directory's process
1692
+ * lock; the binding store opens while it is held. The lock is released when the scope the Layer is built in closes,
1693
+ * including when a later store fails to open.
1694
+ */
1695
+ function fileTerminalSessionStores(options) {
1696
+ return fileTerminalBindingStore(options).pipe(Layer.provideMerge(fileTerminalMessageClaims(options)));
1697
+ }
1698
+ /** `fileTerminalSessionStores` plus the conversation states, opened last while the lock is held. */
1699
+ function fileConversationalTerminalSessionStores(options) {
1700
+ return fileConversationStateStore(options).pipe(Layer.provideMerge(fileTerminalSessionStores(options)));
1701
+ }
1702
+ //#endregion
1703
+ //#region src/feishu/infra/adapters/intake/feishu-card-callback.ts
1704
+ const cardActionEventFields = {
1705
+ action: tolerant(Schema.Struct({ value: tolerant(Schema.Struct({
1706
+ interaction_id: trimmedTextField,
1707
+ option_id: trimmedTextField,
1708
+ resolution: tolerant(Schema.Literals([
1709
+ "approve",
1710
+ "reject",
1711
+ "select"
1712
+ ])),
1713
+ rivus_action: tolerant(Schema.Literals(["resolve_interaction", "cancel_run"])),
1714
+ run_id: trimmedTextField,
1715
+ session_key: trimmedTextField
1716
+ })) })),
1717
+ context: tolerant(Schema.Struct({ open_message_id: trimmedTextField })),
1718
+ /** Any truthy type other than the trigger is unsupported; an object or array is reported without its text. */
1719
+ event_type: Schema.optionalKey(orInvalid(Schema.Union([
1720
+ Schema.String,
1721
+ Schema.Number,
1722
+ Schema.Boolean,
1723
+ Schema.Null,
1724
+ Schema.Undefined
1725
+ ]))),
1726
+ operator: tolerant(Schema.Struct({
1727
+ open_id: trimmedTextField,
1728
+ tenant_key: trimmedTextField
1729
+ })),
1730
+ token: trimmedTextField
1678
1731
  };
1679
- const standaloneHerdrOptionsSchema = Schema.Struct({
1680
- ...sharedHerdrFields,
1681
- appSecret: Schema.Trimmed.check(Schema.isNonEmpty())
1732
+ const CardActionEvent = Schema.Struct(cardActionEventFields);
1733
+ /** The event may arrive wrapped in an `event` envelope or flat at the payload root. */
1734
+ const CardActionPayload = Schema.Struct({
1735
+ ...cardActionEventFields,
1736
+ event: chained(CardActionEvent)
1682
1737
  });
1683
- const embeddedHerdrRouteSchema = Schema.Struct({ ...sharedHerdrFields });
1684
- //#endregion
1685
- //#region src/adapters/herdr/rendering/terminal-text-image.ts
1686
- const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1687
- const emoji = /* @__PURE__ */ new RegExp("^\\p{RGI_Emoji}$", "v");
1688
- const maxRows = 80;
1689
- const maxColumns = 160;
1690
- const maxGraphemes = 160;
1691
- const maxLineCodeUnits = 1024;
1692
- const maxUniqueGraphemes = 1024;
1693
- const cellWidth = 10.8;
1694
- const shapeWorkerUrl = new URL(`data:text/javascript,${encodeURIComponent(`
1695
- import { parentPort, workerData } from "node:worker_threads";
1696
- const { Resvg } = await import(workerData.resvgModuleUrl);
1697
- parentPort.postMessage(new Resvg(workerData.svg, workerData.options).toString());
1698
- parentPort.close();
1699
- `)}`);
1700
- async function renderTerminalTextImage(screen, fontFiles) {
1701
- const { renderAsync } = await import("@resvg/resvg-js");
1702
- const glyphs = /* @__PURE__ */ new Map();
1703
- const allLines = stripVTControlCharacters(screen.text).replace(/[^\P{Cc}\n\t]/gu, "").split("\n");
1704
- const title = renderLine(stripVTControlCharacters(screen.title).replace(/\p{Cc}/gu, ""), 30, glyphs);
1705
- const lines = allLines.slice(0, maxRows).map((line, index) => renderLine(line, 96 + index * 24, glyphs));
1706
- const clipped = screen.truncated || allLines.length > maxRows || title.clipped || lines.some((line) => line.clipped);
1707
- const width = 1800;
1708
- const height = 100 + Math.max(1, lines.length) * 24;
1709
- const label = `Terminal text rendering | ${new Date(screen.at).toISOString()}${clipped ? " | truncated" : ""}`;
1710
- const body = lines.map((line) => line.svg).join("");
1711
- 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: {
1712
- loadSystemFonts: !fontFiles?.length,
1713
- ...fontFiles ? { fontFiles: [...fontFiles] } : {},
1714
- defaultFontFamily: "monospace"
1715
- } })}</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();
1716
- }
1717
- function shapeAtlas(svg, options) {
1718
- return new Promise((resolve, reject) => {
1719
- const worker = new Worker(shapeWorkerUrl, { workerData: {
1720
- svg,
1721
- options,
1722
- resvgModuleUrl: import.meta.resolve("@resvg/resvg-js")
1723
- } });
1724
- let settled = false;
1725
- const deadline = setTimeout(() => finish(/* @__PURE__ */ new Error("Terminal image shaping timed out.")), 3e4);
1726
- function finish(error, paths) {
1727
- if (settled) return;
1728
- settled = true;
1729
- clearTimeout(deadline);
1730
- worker.terminate().then(() => {
1731
- worker.removeAllListeners();
1732
- if (error) reject(error);
1733
- else resolve(paths);
1734
- }, (terminationError) => {
1735
- worker.removeAllListeners();
1736
- reject(error ?? terminationError);
1737
- });
1738
- }
1739
- worker.once("message", (paths) => {
1740
- if (typeof paths !== "string") finish(/* @__PURE__ */ new Error("Terminal image shaping returned invalid paths."));
1741
- else finish(void 0, paths);
1742
- });
1743
- worker.once("error", (error) => finish(error));
1744
- worker.once("exit", (code) => finish(/* @__PURE__ */ new Error(`Terminal image shaping exited before replying (${code}).`)));
1738
+ const decodeCardActionPayload = Schema.decodeUnknownOption(CardActionPayload);
1739
+ const HANDLE_PATTERN = /^[a-f0-9]{12}$/;
1740
+ /**
1741
+ * Issued selection credential carried verbatim from the rendered row; the
1742
+ * schema rejects malformed payloads instead of trusting typeof checks.
1743
+ */
1744
+ const selectionCredentialSchema = Schema.Struct({
1745
+ epoch: Schema.Trimmed.check(Schema.isNonEmpty()),
1746
+ generation: Schema.Number.check(Schema.makeFilter((generation) => Number.isSafeInteger(generation) && generation >= 0)),
1747
+ actorId: Schema.Trimmed.check(Schema.isNonEmpty()),
1748
+ chatId: Schema.Trimmed.check(Schema.isNonEmpty()),
1749
+ handle: Schema.String.check(Schema.makeFilter((handle) => HANDLE_PATTERN.test(handle)))
1750
+ });
1751
+ /** Flattened (or pre-flattened) card callback envelope as the SDK hands it to handlers. */
1752
+ const cardActionEventSchema = Schema.Struct({
1753
+ event_id: Schema.optional(Schema.String),
1754
+ create_time: Schema.optional(Schema.String),
1755
+ operator: Schema.optional(Schema.Struct({
1756
+ open_id: Schema.optional(Schema.String),
1757
+ operator_id: Schema.optional(Schema.Struct({ open_id: Schema.optional(Schema.String) }))
1758
+ })),
1759
+ event_key: Schema.optional(Schema.String),
1760
+ context: Schema.optional(Schema.Struct({ open_chat_id: Schema.optional(Schema.String) })),
1761
+ action: Schema.optional(Schema.Struct({
1762
+ tag: Schema.optional(Schema.String),
1763
+ name: Schema.optional(Schema.String),
1764
+ value: Schema.optional(Schema.Struct({
1765
+ bridge: Schema.optional(Schema.Literal("herdr")),
1766
+ rivus_action: Schema.optional(Schema.String),
1767
+ command: Schema.optional(Schema.String),
1768
+ handle: Schema.optional(Schema.String.check(Schema.makeFilter((handle) => HANDLE_PATTERN.test(handle)))),
1769
+ page: Schema.optional(Schema.Number),
1770
+ selection: Schema.optional(selectionCredentialSchema)
1771
+ })),
1772
+ form_value: Schema.optional(Schema.Struct({ prompt: Schema.optional(Schema.String) }))
1773
+ }))
1774
+ });
1775
+ const decodeCardActionEvent = (event) => {
1776
+ try {
1777
+ return Schema.decodeUnknownSync(cardActionEventSchema)(event);
1778
+ } catch {
1779
+ return;
1780
+ }
1781
+ };
1782
+ /**
1783
+ * Object gate for the wrapped v2 envelope, not a field reader. The flat view is tried first and wins when it
1784
+ * carries an ownership marker. If `event` is absent or not an object, this gate fails and the caller keeps the flat
1785
+ * result (which may be `undefined`); if `event` is an object, the inner callback is decoded below and an invalid
1786
+ * inner field fails instead of falling back to the flat view.
1787
+ *
1788
+ * `Schema.Record(Schema.String, Schema.Unknown)` is deliberately used only as an object gate here: the inner shape
1789
+ * is decoded by `decodeCardActionEvent`, its values are never read, and 3.11 forbids a hand-written
1790
+ * `typeof … === "object"` guard.
1791
+ */
1792
+ const eventEnvelopeSchema = Schema.Struct({ event: Schema.Record(Schema.String, Schema.Unknown) });
1793
+ const decodeEventEnvelope = Schema.decodeUnknownSync(eventEnvelopeSchema);
1794
+ /**
1795
+ * Card callbacks arrive either flattened by the SDK (action at top level) or
1796
+ * wrapped under `event` (Pi intake shape); both carry the same payload.
1797
+ */
1798
+ function decodeFeishuTerminalEvent(event) {
1799
+ const flat = decodeCardActionEvent(event);
1800
+ if (flat !== void 0 && (flat.action !== void 0 || flat.event_key !== void 0 || flat.operator !== void 0)) return flat;
1801
+ let inner;
1802
+ try {
1803
+ inner = decodeEventEnvelope(event).event;
1804
+ } catch {
1805
+ return flat;
1806
+ }
1807
+ return decodeCardActionEvent(inner);
1808
+ }
1809
+ /** Decode the raw callback once for both consumers: the tolerant Pi command view and the strict Herdr terminal
1810
+ * view. The previous entry's envelope selection is preserved verbatim. */
1811
+ function decodeFeishuCardCallback(raw) {
1812
+ const root = Option.getOrElse(decodeCardActionPayload(raw), () => ({}));
1813
+ const envelope = root.event;
1814
+ return {
1815
+ command: envelope === void 0 || envelope === null ? root : envelope === INVALID ? {} : envelope,
1816
+ terminal: decodeFeishuTerminalEvent(raw)
1817
+ };
1818
+ }
1819
+ //#endregion
1820
+ //#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)) }) }));
1823
+ const decodeMessageAck = Schema.decodeUnknownOption(Schema.Struct({ code: Schema.Literal(0) }));
1824
+ const decodeBotIdentity = Schema.decodeUnknownOption(Schema.Struct({
1825
+ code: Schema.Literal(0),
1826
+ bot: Schema.Struct({ open_id: Schema.NonEmptyString })
1827
+ }));
1828
+ const decodeRawMessage = Schema.decodeUnknownOption(Schema.Struct({ msg: Schema.optional(Schema.Union([
1829
+ Schema.String,
1830
+ Schema.Number,
1831
+ Schema.Boolean
1832
+ ])) }));
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
+ */
1839
+ async function uploadFeishuImage(client, image) {
1840
+ const uploaded = await client.im.image.create({ data: {
1841
+ image_type: "message",
1842
+ image: Buffer.from(image)
1843
+ } });
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");
1853
+ }
1854
+ /** Sends one message and rejects with the caller's error text unless the SDK acknowledges numeric code 0. */
1855
+ async function sendFeishuSdkMessage(client, message, errorMessage) {
1856
+ const result = await client.im.message.create({
1857
+ params: { receive_id_type: "chat_id" },
1858
+ data: message
1745
1859
  });
1860
+ if (Option.isNone(decodeMessageAck(result))) throw new Error(errorMessage);
1746
1861
  }
1747
- function renderLine(line, y, glyphs) {
1748
- const nodes = [];
1749
- let column = 0;
1750
- let graphemes = 0;
1751
- let codeUnits = 0;
1752
- for (const { segment } of segmenter.segment(line)) {
1753
- const columns = segment === " " ? 4 - column % 4 : graphemeColumns(segment);
1754
- if (column + columns > maxColumns || graphemes >= maxGraphemes || codeUnits + segment.length > maxLineCodeUnits) return {
1755
- svg: nodes.join(""),
1756
- clipped: true
1757
- };
1758
- if (segment !== " " && segment !== " ") {
1759
- let index = glyphs.get(segment);
1760
- if (index === void 0) {
1761
- if (glyphs.size >= maxUniqueGraphemes) throw new Error("Terminal image exceeds its unique grapheme budget.");
1762
- index = glyphs.size;
1763
- glyphs.set(segment, index);
1862
+ async function fetchFeishuBotOpenId(client) {
1863
+ const response = await client.request({
1864
+ method: "GET",
1865
+ url: "/open-apis/bot/v3/info"
1866
+ });
1867
+ const identity = decodeBotIdentity(response);
1868
+ if (Option.isNone(identity)) {
1869
+ const raw = Option.getOrUndefined(Option.map(decodeRawMessage(response), (decoded) => decoded.msg));
1870
+ throw new Error(`Feishu bot identity lookup failed: ${raw ?? "response missing bot.open_id"}`);
1871
+ }
1872
+ return identity.value.bot.open_id;
1873
+ }
1874
+ //#endregion
1875
+ //#region src/feishu/infra/adapters/terminal-session/feishu-terminal-session.ts
1876
+ function parseFeishuTerminalMessage(event, text) {
1877
+ const message = event.message;
1878
+ const actorId = event.sender?.sender_id?.open_id;
1879
+ if (event.sender?.sender_type !== "user" || !actorId || message.message_type !== "text" || text === void 0) return null;
1880
+ const sentAt = Number(message.create_time);
1881
+ if (!Number.isFinite(sentAt)) return null;
1882
+ return {
1883
+ id: message.message_id,
1884
+ actorId,
1885
+ chatId: message.chat_id,
1886
+ sentAt,
1887
+ text: text.replace(/^@_user_\d+\s*/, "")
1888
+ };
1889
+ }
1890
+ const V2_FORM_NAME = /^rivus_herdr_v2_submit_([a-f0-9]{12})$/;
1891
+ const hasPiMarker = (value) => {
1892
+ const rivusAction = value?.value?.rivus_action;
1893
+ return rivusAction !== void 0 && rivusAction.length > 0;
1894
+ };
1895
+ /**
1896
+ * Classifies a raw card callback before any handler runs: Pi cards carry
1897
+ * `value.rivus_action`, Herdr cards carry `value.bridge === "herdr"` or the v2
1898
+ * 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.
1901
+ */
1902
+ function classifyFeishuCardOwnership(terminal) {
1903
+ if (!terminal) return "unmarked";
1904
+ const pi = hasPiMarker(terminal.action);
1905
+ const herdr = terminal.action?.value?.bridge === "herdr" || V2_FORM_NAME.test(terminal.action?.name ?? "");
1906
+ if (pi && herdr) return "conflict";
1907
+ if (pi) return "pi";
1908
+ return herdr ? "herdr" : "unmarked";
1909
+ }
1910
+ function parseFeishuTerminalAction(terminal, menuChats) {
1911
+ const decoded = terminal;
1912
+ if (!decoded) return null;
1913
+ const actorId = decoded.operator?.open_id ?? decoded.operator?.operator_id?.open_id;
1914
+ if (!actorId || !decoded.event_id || !decoded.create_time) return null;
1915
+ let text;
1916
+ let chatId;
1917
+ let selection;
1918
+ if (decoded.event_key) {
1919
+ if (!["herdr_list", "herdr_help"].includes(decoded.event_key)) return null;
1920
+ chatId = menuChats[actorId];
1921
+ text = decoded.event_key === "herdr_list" ? "/herdr menu" : "/herdr help";
1922
+ } else {
1923
+ chatId = decoded.context?.open_chat_id;
1924
+ const action = decoded.action;
1925
+ const form = V2_FORM_NAME.exec(action?.name ?? "");
1926
+ if (form) {
1927
+ if (hasPiMarker(action) || action?.form_value?.prompt === void 0) return null;
1928
+ text = `/herdr submit ${form[1]} -- ${action.form_value.prompt}`;
1929
+ } else {
1930
+ if (action?.tag !== "button" || action.value?.bridge !== "herdr" || hasPiMarker(action)) return null;
1931
+ const command = action.value.command;
1932
+ if (command === "use" || command === "select") {
1933
+ const handle = action.value.handle;
1934
+ const credential = action.value.selection;
1935
+ if (handle === void 0 || credential === void 0 || credential.handle !== handle) return null;
1936
+ text = `/herdr use ${handle}`;
1937
+ selection = credential;
1938
+ } else if (command === "menu") {
1939
+ const page = action.value.page ?? 0;
1940
+ if (!Number.isSafeInteger(page) || page < 0) return null;
1941
+ text = `/herdr menu ${page}`;
1942
+ } else {
1943
+ if (command === void 0 || ![
1944
+ "open",
1945
+ "refresh",
1946
+ "compose",
1947
+ "read",
1948
+ "screen",
1949
+ "watch",
1950
+ "unwatch"
1951
+ ].includes(command)) return null;
1952
+ const handle = action.value.handle;
1953
+ if (handle === void 0) return null;
1954
+ text = `/herdr ${command} ${handle}`;
1764
1955
  }
1765
- nodes.push(`<g transform="translate(${24 + column * cellWidth} ${y - 20})" clip-path="url(#cell-${Math.max(1, columns)})"><use href="#terminal-glyph-${index}"/></g>`);
1766
1956
  }
1767
- column += columns;
1768
- graphemes += 1;
1769
- codeUnits += segment.length;
1770
1957
  }
1958
+ const sentAt = Number(decoded.create_time) / (decoded.event_key ? 1 : 1e3);
1959
+ if (!Number.isFinite(sentAt)) return null;
1960
+ return chatId ? {
1961
+ id: `action:${decoded.event_id}`,
1962
+ actorId,
1963
+ chatId,
1964
+ sentAt,
1965
+ text,
1966
+ ...selection === void 0 ? {} : { selection }
1967
+ } : null;
1968
+ }
1969
+ function renderTerminalMenu(menu) {
1970
+ const plain = (content) => ({
1971
+ tag: "plain_text",
1972
+ content
1973
+ });
1974
+ const button = (label, command, handle, page, selection) => ({
1975
+ tag: "button",
1976
+ text: plain(label),
1977
+ type: "default",
1978
+ behaviors: [{
1979
+ type: "callback",
1980
+ value: {
1981
+ bridge: "herdr",
1982
+ command,
1983
+ handle,
1984
+ page,
1985
+ ...selection === void 0 ? {} : { selection }
1986
+ }
1987
+ }]
1988
+ });
1989
+ const rowButton = (label, agent) => agent.selection === void 0 ? button(label, "open", agent.handle) : button(label, "use", agent.handle, void 0, agent.selection);
1990
+ const status = (agent) => {
1991
+ if (agent.status === "unavailable") return "离线/暂不可用";
1992
+ if (agent.kind === "terminal") return "终端只读";
1993
+ if (agent.ready && ["idle", "done"].includes(agent.status)) return "等待输入";
1994
+ return {
1995
+ working: "执行中",
1996
+ blocked: "等待处理",
1997
+ idle: "空闲,尚未确认可输入",
1998
+ done: "运行已结束,请刷新确认",
1999
+ unknown: "状态未知"
2000
+ }[agent.status] ?? "暂不可输入";
2001
+ };
2002
+ const elements = [];
2003
+ if (menu.notice) elements.push({
2004
+ tag: "div",
2005
+ text: plain(menu.notice)
2006
+ });
2007
+ if (menu.kind === "list") {
2008
+ elements.push({
2009
+ tag: "markdown",
2010
+ content: `**选择会话** · 第 ${(menu.page ?? 0) + 1}/${menu.pages ?? 1} 页`
2011
+ });
2012
+ const groups = Array$1.groupBy(menu.agents, (agent) => `${agent.session} / ${agent.workspace ?? "会话"}`);
2013
+ for (const [group, agents] of Object.entries(groups)) {
2014
+ elements.push({
2015
+ tag: "div",
2016
+ text: plain(group)
2017
+ });
2018
+ for (const agent of agents) elements.push(rowButton(`${agent.pane} · ${agent.tab ? agent.tab + " / " : ""}${agent.title ?? agent.name} · ${status(agent)}`.slice(0, 100), agent));
2019
+ }
2020
+ if (menu.unavailableSessions?.length) elements.push({
2021
+ tag: "div",
2022
+ text: plain(`以下 session 无法读取,列表不完整:${menu.unavailableSessions.join(", ")}`)
2023
+ });
2024
+ if (!menu.agents.length) elements.push({
2025
+ tag: "markdown",
2026
+ content: "当前没有可用会话。"
2027
+ });
2028
+ if ((menu.page ?? 0) > 0) elements.push(button("上一页", "menu", void 0, menu.page - 1));
2029
+ if ((menu.page ?? 0) + 1 < (menu.pages ?? 1)) elements.push(button("下一页", "menu", void 0, menu.page + 1));
2030
+ } else if (menu.kind === "recovery") {
2031
+ if (menu.agents[0]) elements.push(button("刷新原会话", "refresh", menu.agents[0].handle));
2032
+ } else {
2033
+ const agent = menu.agents[0];
2034
+ elements.push({
2035
+ tag: "div",
2036
+ text: plain(`目标:${agent.session} / ${agent.name}\n状态:${status(agent)}`)
2037
+ });
2038
+ if (menu.kind === "form") {
2039
+ elements.push({
2040
+ tag: "form",
2041
+ name: "herdr_prompt",
2042
+ elements: [{
2043
+ tag: "input",
2044
+ name: "prompt",
2045
+ required: true,
2046
+ input_type: "multiline_text",
2047
+ max_length: 1e3,
2048
+ ...menu.draft === void 0 ? {} : { default_value: menu.draft },
2049
+ placeholder: plain("输入要交给此 agent 的指令"),
2050
+ label: plain("指令内容")
2051
+ }, {
2052
+ tag: "button",
2053
+ name: `rivus_herdr_v2_submit_${agent.handle}`,
2054
+ text: plain("发送"),
2055
+ type: "primary_filled",
2056
+ form_action_type: "submit"
2057
+ }]
2058
+ });
2059
+ elements.push({
2060
+ tag: "markdown",
2061
+ content: "每个表单只提交一次;提交后可通过“看输出”核对执行结果。"
2062
+ });
2063
+ } else {
2064
+ const verdict = evaluateTerminalWriteInput(agent, menu.writable);
2065
+ if (verdict.allowed) elements.push(button("发下一条指令", "compose", agent.handle));
2066
+ else elements.push({
2067
+ tag: "div",
2068
+ text: plain(menu.writable && agent.kind === "agent" ? `${verdict.text}请查看输出,或刷新状态后再试。` : "此会话为只读模式。")
2069
+ });
2070
+ }
2071
+ elements.push(button("关注状态", "watch", agent.handle), button("取消关注", "unwatch", agent.handle), button("看画面", "screen", agent.handle), button("看输出", "read", agent.handle), button("刷新当前会话", "refresh", agent.handle));
2072
+ }
2073
+ elements.push(button("刷新会话列表", "menu"));
1771
2074
  return {
1772
- svg: nodes.join(""),
1773
- clipped: false
2075
+ schema: "2.0",
2076
+ config: {
2077
+ width_mode: "default",
2078
+ enable_forward: false
2079
+ },
2080
+ header: {
2081
+ title: plain(menu.kind === "form" ? "向会话发送指令" : "Herdr 会话"),
2082
+ template: "blue"
2083
+ },
2084
+ body: { elements }
1774
2085
  };
1775
2086
  }
1776
- function graphemeColumns(grapheme) {
1777
- if (emoji.test(grapheme)) return 2;
1778
- for (const codePoint of grapheme) if (!/[\p{Mark}\p{Format}]/u.test(codePoint)) return eastAsianWidth(codePoint.codePointAt(0));
1779
- return 0;
2087
+ async function deliverTerminalBridgeReply(reply, delivery, render) {
2088
+ if (reply.menu && delivery.sendCard) return delivery.sendCard(reply.chatId, renderTerminalMenu({
2089
+ ...reply.menu,
2090
+ ...reply.menu.kind === "recovery" ? { notice: reply.text } : {}
2091
+ }));
2092
+ if (!reply.screen) return delivery.sendText(reply.chatId, reply.text);
2093
+ try {
2094
+ await delivery.sendImage(reply.chatId, await render(reply.screen));
2095
+ } catch {
2096
+ await delivery.sendText(reply.chatId, `${reply.text} | ${new Date(reply.screen.at).toISOString()}${reply.screen.truncated || reply.screen.text.length > 12e3 ? " | truncated(已截断)" : ""}\n图片暂不可用,以下是终端文字:\n${reply.screen.text.slice(-12e3)}`);
2097
+ }
1780
2098
  }
1781
- function escapeXml(text) {
1782
- return text.replace(/[&<>"']/g, (char) => ({
1783
- "&": "&amp;",
1784
- "<": "&lt;",
1785
- ">": "&gt;",
1786
- "\"": "&quot;",
1787
- "'": "&apos;"
1788
- })[char]);
2099
+ function createFeishuTerminalDelivery(client, options) {
2100
+ const refuseWhenStopped = () => {
2101
+ if (options?.isStopped?.() === true) throw new Error("Herdr runtime is stopped; delivery refused");
2102
+ };
2103
+ return {
2104
+ sendCard: async (chatId, card) => {
2105
+ refuseWhenStopped();
2106
+ await sendFeishuSdkMessage(client, {
2107
+ receive_id: chatId,
2108
+ msg_type: "interactive",
2109
+ content: JSON.stringify(card)
2110
+ }, "Feishu card delivery failed");
2111
+ },
2112
+ sendText: async (chatId, text) => {
2113
+ refuseWhenStopped();
2114
+ await sendFeishuSdkMessage(client, {
2115
+ receive_id: chatId,
2116
+ msg_type: "text",
2117
+ content: JSON.stringify({ text })
2118
+ }, "Feishu text delivery failed");
2119
+ },
2120
+ sendImage: async (chatId, bytes) => {
2121
+ refuseWhenStopped();
2122
+ const imageKey = await uploadFeishuImage(client, bytes);
2123
+ refuseWhenStopped();
2124
+ await sendFeishuSdkMessage(client, {
2125
+ receive_id: chatId,
2126
+ msg_type: "image",
2127
+ content: JSON.stringify({ image_key: imageKey })
2128
+ }, "Feishu image delivery failed");
2129
+ }
2130
+ };
1789
2131
  }
1790
2132
  //#endregion
2133
+ //#region src/bootstrap/feishu/herdr-config.ts
2134
+ /** Shared Herdr field schemas for the standalone options and the embedded route config. */
2135
+ const herdrSessionSchema = Schema.Struct({
2136
+ name: Schema.Trimmed.check(Schema.isNonEmpty()),
2137
+ socketPath: Schema.String.check(Schema.makeFilter(isAbsolute))
2138
+ });
2139
+ const nonEmptyStringArray = Schema.NonEmptyArray(Schema.Trimmed.check(Schema.isNonEmpty()));
2140
+ const stringRecord = Schema.Record(Schema.String, Schema.Trimmed.check(Schema.isNonEmpty()));
2141
+ const absolutePath = Schema.String.check(Schema.makeFilter(isAbsolute));
2142
+ const optionalAbsolutePathArray = Schema.optional(Schema.Array(Schema.String.check(Schema.makeFilter(isAbsolute))));
2143
+ const sharedHerdrFields = {
2144
+ appId: Schema.Trimmed.check(Schema.isNonEmpty()),
2145
+ sessions: Schema.optional(Schema.Array(herdrSessionSchema)),
2146
+ discoverSessionsIn: Schema.optional(Schema.String.check(Schema.makeFilter(isAbsolute))),
2147
+ allowedActors: nonEmptyStringArray,
2148
+ allowedChats: nonEmptyStringArray,
2149
+ menuChats: Schema.optional(stringRecord),
2150
+ stateDirectory: absolutePath,
2151
+ writable: Schema.optional(Schema.Boolean),
2152
+ fontFiles: optionalAbsolutePathArray
2153
+ };
2154
+ const standaloneHerdrOptionsSchema = Schema.Struct({
2155
+ ...sharedHerdrFields,
2156
+ appSecret: Schema.Trimmed.check(Schema.isNonEmpty())
2157
+ });
2158
+ const embeddedHerdrRouteSchema = Schema.Struct({ ...sharedHerdrFields });
2159
+ //#endregion
1791
2160
  //#region src/bootstrap/herdr-feishu-runtime.ts
1792
2161
  const QUEUE_LIMIT = 32;
1793
2162
  const WATCH_INTERVAL_MS = 5e3;
1794
2163
  const STOP_TIMEOUT_MS = 1e4;
1795
2164
  /**
2165
+ * Builds the bridge's store Layer in a scope this bootstrap owns. `close` closes that scope, which releases the state
2166
+ * directory lock; a failed build closes it before the original error is rethrown.
2167
+ */
2168
+ async function openHerdrBridgeStores(stores) {
2169
+ const scope = Scope.makeUnsafe();
2170
+ const close = () => Effect.runPromiseExit(Scope.close(scope, Exit.void)).then(unwrapExit);
2171
+ const built = await Effect.runPromiseExit(Layer.buildWithScope(stores, scope));
2172
+ if (Exit.isFailure(built)) {
2173
+ await close().catch(() => void 0);
2174
+ throw Cause.squash(built.cause);
2175
+ }
2176
+ return {
2177
+ close,
2178
+ context: built.value
2179
+ };
2180
+ }
2181
+ /**
1796
2182
  * Connection-less Herdr bridge core shared by the standalone entrypoint and the
1797
2183
  * embedded single-WebSocket route. Owns the bounded serial work queue, the
1798
2184
  * watch loop, every admitted network promise and the claims-store lifetime.
1799
2185
  */
1800
2186
  function createHerdrFeishuBridgeRuntime(options) {
1801
2187
  let stopped = false;
1802
- const bridge = createTerminalSessionBridge({
1803
- sessions: {
1804
- ...options.sessions,
1805
- prompt: (agent, text) => stopped ? Effect.fail(/* @__PURE__ */ new Error("Herdr runtime is stopped; prompt refused")) : options.sessions.prompt(agent, text)
1806
- },
2188
+ const settings = {
1807
2189
  actors: options.actors,
1808
2190
  chats: options.chats,
1809
2191
  writable: options.writable,
1810
2192
  now: options.now ?? Date.now,
1811
- newHandle: options.newHandle ?? (() => randomBytes(6).toString("hex")),
1812
- claim: options.claim,
1813
- ...options.bindings === void 0 ? {} : { bindings: options.bindings },
1814
- ...options.conversation === void 0 ? {} : { conversation: options.conversation }
1815
- });
2193
+ newHandle: options.newHandle ?? (() => randomBytes(6).toString("hex"))
2194
+ };
2195
+ const conversation = options.conversation;
2196
+ const ports = Layer.mergeAll(Layer.succeed(TerminalSessionPort, {
2197
+ ...options.sessions,
2198
+ prompt: (agent, text) => stopped ? Effect.fail(/* @__PURE__ */ new Error("Herdr runtime is stopped; prompt refused")) : options.sessions.prompt(agent, text)
2199
+ }), Layer.succeedContext(options.stores));
2200
+ const bridge = unwrapExit(Effect.runSyncExit((conversation === void 0 ? makeTerminalSessionBridge(settings) : makeConversationalTerminalSessionBridge(settings, conversation.epoch).pipe(Effect.provideContext(conversation.stores))).pipe(Effect.provide(ports))));
1816
2201
  let pending = 0;
1817
2202
  let tail = Promise.resolve();
1818
2203
  let watchTimer;
@@ -1989,5 +2374,5 @@ function createHerdrFeishuBridgeRuntime(options) {
1989
2374
  };
1990
2375
  }
1991
2376
  //#endregion
1992
- export { openTerminalBindingsStore as a, classifyFeishuCardOwnership as c, parseFeishuTerminalMessage as d, openTerminalMessageClaims as i, createFeishuTerminalDelivery as l, embeddedHerdrRouteSchema as n, terminalAgentSchema as o, standaloneHerdrOptionsSchema as r, createHerdrSocketClient as s, createHerdrFeishuBridgeRuntime as t, parseFeishuTerminalAction as u };
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 };
1993
2378