@sleep2agi/agent-network 2.3.0-preview.4 → 2.3.0-preview.40

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 (61) hide show
  1. package/README.md +35 -324
  2. package/dist/bin/anet.cjs +101 -0
  3. package/dist/bin/cli.d.ts +1 -0
  4. package/dist/bin/cli.js +20 -1
  5. package/dist/bin/goal-wake-log-render.d.ts +31 -0
  6. package/dist/src/batch-workdir.d.ts +9 -0
  7. package/dist/src/bootstrap-password-db.d.ts +13 -0
  8. package/dist/src/channel-attachments.d.ts +29 -0
  9. package/dist/src/channel-task-trace.d.ts +10 -0
  10. package/dist/src/claude-vendor-env.d.ts +28 -0
  11. package/dist/src/cli-args.d.ts +8 -0
  12. package/dist/src/client-task-trace.d.ts +9 -0
  13. package/dist/src/client.js +1 -1
  14. package/dist/src/codex-model-default.d.ts +6 -0
  15. package/dist/src/controlled-upload.d.ts +83 -0
  16. package/dist/src/copresence-identity.d.ts +339 -0
  17. package/dist/src/dashboard-managed-process.d.ts +35 -0
  18. package/dist/src/environ-alias.d.ts +14 -0
  19. package/dist/src/grok-attach-client.d.ts +115 -0
  20. package/dist/src/grok-copresence-disclosure.d.ts +11 -0
  21. package/dist/src/grok-copresence-profile.d.ts +65 -0
  22. package/dist/src/im/feishu/adapter.d.ts +149 -1
  23. package/dist/src/im/feishu/bridge.d.ts +9 -0
  24. package/dist/src/im/feishu/config.d.ts +31 -0
  25. package/dist/src/im/feishu/hub-upload.d.ts +88 -0
  26. package/dist/src/im/feishu/markdown-image-renderer.d.ts +61 -0
  27. package/dist/src/im/feishu/outbound-marker.d.ts +140 -0
  28. package/dist/src/im/feishu/outbound-paths.d.ts +50 -0
  29. package/dist/src/im/feishu/outbound-route.d.ts +62 -0
  30. package/dist/src/im/feishu/worker-lifecycle.d.ts +13 -0
  31. package/dist/src/im/feishu/worker.js +391 -16
  32. package/dist/src/im/types.d.ts +38 -1
  33. package/dist/src/locale-diagnostic.d.ts +12 -0
  34. package/dist/src/mock-llm.d.ts +12 -0
  35. package/dist/src/node-server.js +7 -1
  36. package/dist/src/normalize-runtime.d.ts +14 -2
  37. package/dist/src/opencode-agent-node-pair.d.ts +14 -0
  38. package/dist/src/opencode-auth-login.d.ts +43 -0
  39. package/dist/src/opencode-launch-env.d.ts +13 -0
  40. package/dist/src/opencode-owner-mode.d.ts +6 -0
  41. package/dist/src/opencode-package-binary.d.ts +21 -0
  42. package/dist/src/opencode-pin.d.ts +44 -0
  43. package/dist/src/opencode-preset.d.ts +73 -0
  44. package/dist/src/opencode-runtime-binding.d.ts +30 -0
  45. package/dist/src/opencode-safe-root.d.ts +27 -0
  46. package/dist/src/opencode-smoke-env.d.ts +1 -0
  47. package/dist/src/outbound-tool-names.d.ts +1 -0
  48. package/dist/src/owner-env-file.d.ts +2 -0
  49. package/dist/src/package-mode-preflight.d.ts +31 -0
  50. package/dist/src/primary-network.d.ts +23 -0
  51. package/dist/src/private-state.d.ts +10 -0
  52. package/dist/src/project-key.d.ts +1 -0
  53. package/dist/src/secret-shell-guidance.d.ts +3 -0
  54. package/dist/src/task-trace.d.ts +33 -0
  55. package/dist/src/tmux-attach.d.ts +8 -0
  56. package/dist/src/tmux-capability.d.ts +58 -0
  57. package/dist/src/tmux-exact-target.d.ts +34 -0
  58. package/dist/src/tmux-pane-prompt.d.ts +22 -0
  59. package/dist/src/token-cli.d.ts +13 -0
  60. package/dist/src/unsafe-package-path-reason.d.ts +17 -0
  61. package/package.json +10 -6
@@ -0,0 +1,35 @@
1
+ export type DashboardLaunchSource = "npx" | "global";
2
+ export interface DashboardLaunchRecord {
3
+ schema: 1;
4
+ port: number;
5
+ listener_pid: number;
6
+ listener_birth: string;
7
+ source: DashboardLaunchSource;
8
+ source_key: string;
9
+ recorded_at: string;
10
+ }
11
+ export type DashboardListenerDecision = {
12
+ action: "start";
13
+ } | {
14
+ action: "already_running";
15
+ pid: number;
16
+ } | {
17
+ action: "terminate_owned_stale";
18
+ pid: number;
19
+ reason: "unhealthy" | "version_changed";
20
+ } | {
21
+ action: "refuse";
22
+ reason: string;
23
+ };
24
+ export declare function isDashboardProcessCommand(command: string): boolean;
25
+ export declare function decideDashboardListener(input: {
26
+ port: number;
27
+ listenerPids: number[];
28
+ record: DashboardLaunchRecord | null;
29
+ listenerBirth: string | null;
30
+ listenerCommand: string | null;
31
+ desiredSource: DashboardLaunchSource;
32
+ desiredSourceKey: string;
33
+ healthy: boolean;
34
+ }): DashboardListenerDecision;
35
+ export declare function parseDashboardLaunchRecord(value: unknown): DashboardLaunchRecord | null;
@@ -0,0 +1,14 @@
1
+ /** Parse the environ blob (NUL-separated key=val) and return the
2
+ * COMMHUB_ALIAS value if present, else null. Exported for testing. */
3
+ export declare function parseEnvironAlias(environBlob: string): string | null;
4
+ /** Read /proc/<pid>/environ and return the COMMHUB_ALIAS value.
5
+ * Any file-read error (not-a-Linux, permission denied, race with
6
+ * process exit) returns null — caller must not fail-closed on that
7
+ * (the process is stale/gone/inaccessible, not our problem). */
8
+ export declare function readEnvironAlias(pid: number): string | null;
9
+ /** Scan /proc for pids whose COMMHUB_ALIAS env matches any of the
10
+ * target aliases. Linux-only (procfs); returns null on non-Linux or
11
+ * when /proc is unreadable — caller MUST fail-closed on null per
12
+ * the same #180 R2 fail-closed contract as findNodeProcessesByAlias.
13
+ * Self-pid + init (PID 1) are excluded. */
14
+ export declare function findEnvironAliasMatches(aliases: Iterable<string>, selfPid: number): number[] | null;
@@ -0,0 +1,115 @@
1
+ import type { Duplex } from "node:stream";
2
+ export declare const GROK_ATTACH_PROTOCOL = "anet-grok-copresence-attach";
3
+ export declare const GROK_ATTACH_PROTOCOL_VERSION = 1;
4
+ export declare const GROK_ATTACH_DEFAULT_MAX_FRAME_BYTES: number;
5
+ export declare const GROK_ATTACH_DEFAULT_MAX_BUFFER_BYTES: number;
6
+ export declare const GROK_ATTACH_DEFAULT_HANDSHAKE_TIMEOUT_MS = 5000;
7
+ export declare const GROK_ATTACH_DEFAULT_CLOSE_TIMEOUT_MS = 1000;
8
+ export type GrokAttachJsonValue = null | boolean | number | string | GrokAttachJsonValue[] | {
9
+ [key: string]: GrokAttachJsonValue;
10
+ };
11
+ export interface GrokAttachHelloFrame {
12
+ type: "hello";
13
+ protocol: typeof GROK_ATTACH_PROTOCOL;
14
+ version: typeof GROK_ATTACH_PROTOCOL_VERSION;
15
+ alias: string;
16
+ sessionId: string;
17
+ [key: string]: unknown;
18
+ }
19
+ export interface GrokAttachOutputFrame {
20
+ type: "output";
21
+ data: string;
22
+ encoding: "base64";
23
+ }
24
+ export interface GrokAttachStatusFrame {
25
+ type: "status";
26
+ status: GrokAttachJsonValue;
27
+ }
28
+ export interface GrokAttachErrorFrame {
29
+ type: "error";
30
+ code: string;
31
+ message: string;
32
+ fatal: boolean;
33
+ }
34
+ export interface GrokAttachDetachFrame {
35
+ type: "detach";
36
+ }
37
+ export type GrokAttachServerFrame = GrokAttachHelloFrame | GrokAttachOutputFrame | GrokAttachStatusFrame | GrokAttachErrorFrame | GrokAttachDetachFrame;
38
+ export interface GrokAttachInputFrame {
39
+ type: "input";
40
+ data: string;
41
+ encoding: "base64";
42
+ }
43
+ export interface GrokAttachResizeFrame {
44
+ type: "resize";
45
+ cols: number;
46
+ rows: number;
47
+ }
48
+ export type GrokAttachClientFrame = GrokAttachInputFrame | GrokAttachResizeFrame | GrokAttachDetachFrame;
49
+ export interface GrokAttachInputSource {
50
+ on(event: "data", listener: (chunk: unknown) => void): unknown;
51
+ on(event: "end", listener: () => void): unknown;
52
+ off?(event: "data" | "end", listener: (...args: any[]) => void): unknown;
53
+ removeListener?(event: "data" | "end", listener: (...args: any[]) => void): unknown;
54
+ pause?(): unknown;
55
+ resume?(): unknown;
56
+ }
57
+ export interface GrokAttachOutputSink {
58
+ write(chunk: Uint8Array): boolean | void;
59
+ columns?: number;
60
+ rows?: number;
61
+ once?(event: "drain", listener: () => void): unknown;
62
+ }
63
+ export interface GrokAttachSignalSource {
64
+ on(event: "SIGWINCH", listener: () => void): unknown;
65
+ off?(event: "SIGWINCH", listener: () => void): unknown;
66
+ removeListener?(event: "SIGWINCH", listener: () => void): unknown;
67
+ }
68
+ export interface GrokAttachSocketStat {
69
+ uid: number;
70
+ isSocket(): boolean;
71
+ isSymbolicLink(): boolean;
72
+ }
73
+ export interface GrokAttachDependencies {
74
+ lstat?: (socketPath: string) => Promise<GrokAttachSocketStat>;
75
+ getuid?: () => number | undefined;
76
+ connect?: (socketPath: string) => Duplex;
77
+ }
78
+ export interface GrokAttachClientOptions {
79
+ socketPath: string;
80
+ input: GrokAttachInputSource;
81
+ output: GrokAttachOutputSink;
82
+ signalSource?: GrokAttachSignalSource;
83
+ terminalSize?: () => {
84
+ cols: number | undefined;
85
+ rows: number | undefined;
86
+ };
87
+ maxFrameBytes?: number;
88
+ maxBufferBytes?: number;
89
+ handshakeTimeoutMs?: number;
90
+ closeTimeoutMs?: number;
91
+ detachOnInputEnd?: boolean;
92
+ onHello?: (frame: GrokAttachHelloFrame) => void;
93
+ onStatus?: (frame: GrokAttachStatusFrame) => void;
94
+ onError?: (error: Error, frame?: GrokAttachErrorFrame) => void;
95
+ onDetach?: (frame: GrokAttachDetachFrame) => void;
96
+ dependencies?: GrokAttachDependencies;
97
+ }
98
+ export type GrokAttachCloseReason = "local-detach" | "input-end" | "remote-detach" | "socket-close" | "socket-error" | "protocol-error";
99
+ export interface GrokAttachCloseInfo {
100
+ reason: GrokAttachCloseReason;
101
+ error?: Error;
102
+ }
103
+ export interface GrokAttachSession {
104
+ readonly socketPath: string;
105
+ readonly closed: Promise<GrokAttachCloseInfo>;
106
+ detach(): void;
107
+ resize(cols?: number, rows?: number): void;
108
+ }
109
+ export declare class GrokAttachRemoteError extends Error {
110
+ readonly code: string;
111
+ readonly fatal: boolean;
112
+ constructor(frame: GrokAttachErrorFrame);
113
+ }
114
+ export declare function validateGrokAttachSocket(socketPath: string, dependencies?: GrokAttachDependencies): Promise<void>;
115
+ export declare function connectGrokAttach(options: GrokAttachClientOptions): Promise<GrokAttachSession>;
@@ -0,0 +1,11 @@
1
+ export type GrokCopresenceSessionDisclosure = "configured" | "new" | "resume";
2
+ export type GrokCopresenceDisclosure = {
3
+ profile: "commhub-only" | "x-search" | "repo-read" | "invalid";
4
+ lines: readonly string[];
5
+ };
6
+ /**
7
+ * Describe only the exact tool profiles accepted by the pinned Grok TUI
8
+ * runtime. This is deliberately exact: a near-miss must never be presented as
9
+ * either reviewed capability set.
10
+ */
11
+ export declare function grokCopresenceDisclosure(tools: unknown, session?: GrokCopresenceSessionDisclosure): GrokCopresenceDisclosure;
@@ -0,0 +1,65 @@
1
+ export declare const GROK_UNIX_SOCKET_PATH_MAX_BYTES = 100;
2
+ export declare const GROK_COPRESENCE_CAPABILITY_MARKER = "ANET_CAPABILITY_GROK_COPRESENCE_V2";
3
+ export declare const GROK_PREVIEW_RESOLVER_INHERITED_ENV_KEYS: readonly ["PATH", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "LC_CTYPE", "TZ"];
4
+ export declare const GROK_AGENT_NODE_INHERITED_ENV_KEYS: readonly ["PATH", "HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "LC_CTYPE", "TZ", "SHELL", "USER", "LOGNAME", "TERM", "COLORTERM", "NO_COLOR"];
5
+ export declare const GROK_AGENT_NODE_OPTIONAL_ENV_KEYS: readonly ["GROK_BINARY", "GROK_HOME", "FLOCK_BINARY", "SETPRIV_BINARY", "UNSHARE_BINARY", "GROK_CLI_TIMEOUT_MS", "GROK_HANDSHAKE_TIMEOUT_MS", "LOG_LEVEL", "ANET_GOAL_TICK_MS", "COMMHUB_MAX_GOALS_PER_NODE"];
6
+ /** Exact environment for the long-lived agent-node parent of the Grok TUI. */
7
+ export declare function buildGrokAgentNodeEnv(parentEnv: NodeJS.ProcessEnv): Record<string, string>;
8
+ export declare function grokPreviewResolverConfigPaths(home: string): {
9
+ directory: string;
10
+ userConfig: string;
11
+ globalConfig: string;
12
+ };
13
+ /**
14
+ * npm rejects loading the same file as both user and global config. Prepare
15
+ * two distinct, empty, owner-only files without following a final symlink so
16
+ * the resolver cannot inherit a user's ordinary npmrc credentials.
17
+ */
18
+ export declare function prepareGrokPreviewResolverConfigs(home: string): void;
19
+ /** Exact environment for the short-lived npm resolver and capability probe. */
20
+ export declare function buildGrokPreviewResolverEnv(parentEnv: NodeJS.ProcessEnv, home: string): Record<string, string>;
21
+ /** Old headless-only agent-node builds already advertised grok-build-cli. */
22
+ export declare function agentNodeHelpSupportsGrokCopresence(help: string): boolean;
23
+ export interface GrokCopresenceProfileFields {
24
+ grokCopresence: boolean;
25
+ grokLeaderSocket?: string;
26
+ grokAttachSocket?: string;
27
+ }
28
+ export interface GrokSocketPathOptions {
29
+ cwd?: string;
30
+ home?: string;
31
+ xdgRuntimeDir?: string;
32
+ uid?: number;
33
+ platform?: NodeJS.Platform;
34
+ }
35
+ /**
36
+ * Allocate deterministic Unix socket paths without creating anything.
37
+ *
38
+ * Grok's workspace sandbox does not admit an otherwise owner-controlled
39
+ * XDG_RUNTIME_DIR such as /run/user/<uid>. Keep the primary sockets under the
40
+ * node's owner-bound state home, which the runtime already admits, and use a
41
+ * short private tmp path only when the Unix socket length limit requires it.
42
+ * The runtime owns directory creation and permissions; `anet node create`
43
+ * only persists the identity of the two sockets.
44
+ */
45
+ export declare function grokCopresenceSocketPaths(nodeId: string, options?: GrokSocketPathOptions): {
46
+ leaderSocket: string;
47
+ attachSocket: string;
48
+ };
49
+ export type GrokAttachTarget = {
50
+ ok: true;
51
+ socketPath: string;
52
+ } | {
53
+ ok: false;
54
+ reason: "not_grok_build_cli" | "headless" | "missing_attach_socket";
55
+ };
56
+ /**
57
+ * `anet grok attach` eligibility. The CLI is the only human join path;
58
+ * this is the shipped decision so tests can drive it without a TTY.
59
+ */
60
+ export declare function resolveGrokAttachTarget(input: {
61
+ runtime: string;
62
+ grokCopresence?: unknown;
63
+ grokAttachSocket?: unknown;
64
+ }): GrokAttachTarget;
65
+ export declare function grokBuildCliCreationFields(runtime: string, nodeId: string, headless?: boolean, options?: GrokSocketPathOptions): GrokCopresenceProfileFields | Record<string, never>;
@@ -1,12 +1,49 @@
1
+ /**
2
+ * RFC-020 §3.1 — Feishu (Lark) adapter for the IM compatibility layer.
3
+ *
4
+ * Uses `@larksuiteoapi/node-sdk` in WebSocket long-connection mode (WSClient).
5
+ * No public IP / no domain verification / no webhook signature decryption —
6
+ * the three biggest 飞书 接入 risks all live in the HTTP event-callback path,
7
+ * not in WSClient mode.
8
+ *
9
+ * Milestones:
10
+ * M1: contract scaffold.
11
+ * M2 (this file): WSClient init + EventDispatcher for `im.message.receive_v1`
12
+ * + event normalization + access whitelist gate + audit log.
13
+ * M3: outbound `im.message.create` (text), edit support (≤20/msg).
14
+ * M5: image upload / download (`im.image.create` / `im.messageResource.get`)
15
+ * + group @bot detection refined to match the bot's own open_id.
16
+ */
17
+ import * as lark from "@larksuiteoapi/node-sdk";
1
18
  import type { IMAdapter, IMAdapterHealth, IMChannelConfig, IMConversationRef, IMIngressMode, NormalizedIMEvent, NormalizedIMMessage } from "../types.js";
2
19
  type OnEventHandler = (event: NormalizedIMEvent) => Promise<void>;
20
+ export type FeishuWsClientLike = Pick<lark.WSClient, "start" | "close">;
21
+ export type FeishuWsClientFactory = (params: ConstructorParameters<typeof lark.WSClient>[0]) => FeishuWsClientLike;
22
+ type FeishuInboundHandler = (rawEvent: unknown) => Promise<unknown>;
23
+ export interface FeishuEventDispatcherLike {
24
+ register(handlers: Record<string, FeishuInboundHandler>): unknown;
25
+ }
26
+ export interface FeishuAdapterOptions {
27
+ /** @internal Avoids real bot-info HTTP calls in lifecycle tests. */
28
+ createClient?: (params: ConstructorParameters<typeof lark.Client>[0]) => lark.Client;
29
+ /** @internal Test seam; production uses the pinned Lark SDK WSClient. */
30
+ createWsClient?: FeishuWsClientFactory;
31
+ /** @internal Test seam; production uses the pinned Lark SDK dispatcher. */
32
+ createEventDispatcher?: () => FeishuEventDispatcherLike;
33
+ /** Independent outer bound in case the SDK promise/callback path stalls. */
34
+ wsReadyTimeoutMs?: number;
35
+ /** Called once when an already-ready socket exhausts reconnect attempts. */
36
+ onTerminalError?: (error: Error) => void;
37
+ }
3
38
  export declare class FeishuAdapter implements IMAdapter {
4
39
  readonly platform = "feishu";
5
40
  readonly ingressMode: IMIngressMode;
6
41
  private feishuConfig;
7
- private connectionName;
42
+ private connectionName_;
8
43
  private client;
9
44
  private wsClient;
45
+ private lifecycleGeneration;
46
+ private readonly options;
10
47
  /**
11
48
  * The bot's own open_id, resolved at init() via /open-apis/bot/v3/info.
12
49
  * Used to detect real @bot mentions (vs any mention) in group messages.
@@ -17,6 +54,24 @@ export declare class FeishuAdapter implements IMAdapter {
17
54
  /** Where to persist downloaded inbound media (M5c). */
18
55
  private mediaDir;
19
56
  private health_;
57
+ constructor(options?: FeishuAdapterOptions);
58
+ /**
59
+ * Snapshot of the current `access.allowFrom` list (from access.json).
60
+ * Used by the bridge's rate-limiter to exempt operator-vouched explicit
61
+ * sender ids from the DM flood limit (2026-06-29: Vincent's multi-turn
62
+ * heavy work was tripping the 3-msg/60s DM limit; explicit-listed
63
+ * users are already operator-trusted via the access whitelist, no
64
+ * need to also flood-limit them). Returns `[]` before `init()`. The
65
+ * wildcard `["*"]` allowlist does NOT count as "explicit" — that's
66
+ * the public-channel shape and still needs flood protection.
67
+ */
68
+ getAllowFrom(): readonly string[];
69
+ /**
70
+ * Read-only accessor used by bridge to resolve per-connection paths
71
+ * (RFC-020 §15 outbound-marker validation needs the connection name
72
+ * to build the allowed per-conversation directory prefix).
73
+ */
74
+ get connectionName(): string;
20
75
  init(config: IMChannelConfig): Promise<void>;
21
76
  start(onEvent: OnEventHandler): Promise<void>;
22
77
  stop(): Promise<void>;
@@ -26,4 +81,97 @@ export declare class FeishuAdapter implements IMAdapter {
26
81
  edit(_target: IMConversationRef, messageId: string, message: NormalizedIMMessage): Promise<void>;
27
82
  health(): IMAdapterHealth;
28
83
  }
84
+ /**
85
+ * Heuristic — does this text look like it contains markdown syntax that
86
+ * Feishu's plain-text `msg_type:"text"` would render as literal source?
87
+ * Catches the patterns Vincent's heavy work produces: tables (`|...|`
88
+ * + separator row), fenced code blocks (`` ``` ``), ATX headings (`#`),
89
+ * bold/italic (`**text**` / `*text*`), unordered/ordered lists, inline
90
+ * code (`` `code` ``), markdown links (`[label](url)`).
91
+ *
92
+ * Returns true for at least one match; the adapter then upgrades to
93
+ * `msg_type:"interactive"` with a `markdown` element. Returns false for
94
+ * plain prose so the text path stays untouched (no perf cost, no
95
+ * behavior change for non-markdown replies).
96
+ *
97
+ * Conservative — single-character matches (e.g., a `|` in prose, one
98
+ * `*` for emphasis-of-one-word that Feishu would render OK as text)
99
+ * are NOT enough to trigger. We want false-positives < false-negatives
100
+ * (a false-positive upgrade renders fine; a false-negative shows raw
101
+ * `|` and `**`).
102
+ */
103
+ export declare function looksLikeMarkdown(text: string): boolean;
104
+ /**
105
+ * Parse Feishu `message_type: "post"` content into plain text. Post
106
+ * content is a nested structure:
107
+ *
108
+ * { title?: string,
109
+ * content: Array<Array<{ tag: "text"|"img"|"a"|"at"|"emotion", ... }>>
110
+ * }
111
+ *
112
+ * Each top-level array entry is a paragraph; each paragraph is an array
113
+ * of typed segments. We flatten by:
114
+ * - prepending title (if present) as `<title>\n\n`
115
+ * - joining paragraphs with `\n\n`
116
+ * - joining segments within a paragraph in order
117
+ * - tag=text → emit segment.text as-is
118
+ * - tag=a → emit `[label](href)` (markdown link)
119
+ * - tag=at → emit `@user_name` (fallback to `@<user_id>` if no name)
120
+ * - tag=img → emit `[图片]` placeholder (actual download via maybeAttachImages)
121
+ * - tag=emotion → emit `[emoji]`
122
+ * - unknown tag → skip
123
+ *
124
+ * @internal exported for unit tests.
125
+ */
126
+ export declare function parsePostContent(rawJson: string): string;
127
+ /**
128
+ * Walk a Feishu `post` content JSON and collect all `image_key` values
129
+ * from `tag: "img"` segments. Used by `maybeAttachImages` to schedule
130
+ * downloads for every image in a 图文混排 message.
131
+ *
132
+ * @internal exported for unit tests.
133
+ */
134
+ export declare function extractPostImageKeys(rawJson: string): string[];
135
+ /**
136
+ * Sanitize a Feishu-supplied `file_name` so it's safe to append to a
137
+ * filesystem path. Strips `/`, `\`, `..`, control characters, and NUL
138
+ * bytes. Empty / all-stripped input falls back to a placeholder that
139
+ * uses the message id, so a hostile client can never write outside the
140
+ * conversation's `<mediaDir>/<convKey>/` directory.
141
+ *
142
+ * NOT a full display-safety pass — the LLM still sees the sanitized
143
+ * bytes and shouldn't render them as HTML/etc. That's a Layer above.
144
+ */
145
+ export declare function sanitizeFileName(raw: string, fallback: string): string;
146
+ /**
147
+ * Feishu text-message practical chunk threshold (RFC-020 §16).
148
+ *
149
+ * The official `im.message.create`/`reply` content limit for
150
+ * `msg_type:text` is ~30 KB JSON-encoded (`{"text":"..."}`), comfortably
151
+ * under what any reasonable bot reply produces. We chunk below that
152
+ * limit at 4000 CHARACTERS — gives a roomy safety margin for multi-byte
153
+ * UTF-8 and lets us split at paragraph boundaries cleanly. Chosen
154
+ * conservatively after Vincent 2026-06-30 ask "issue 发文字" (i.e.
155
+ * never silently fall back to PNG for "long" plain-text replies — they
156
+ * just chunk into multiple messages).
157
+ *
158
+ * Single-message ceiling, NOT a per-second rate limit (that's separate;
159
+ * RFC-020 §4.4).
160
+ */
161
+ export declare const FEISHU_TEXT_SINGLE_LIMIT = 4000;
162
+ /**
163
+ * Split a long text into chunks ≤ `maxChars`. Tries paragraph boundaries
164
+ * (`\n\n`), then line boundaries (`\n`), then word boundaries (space),
165
+ * then hard byte split. Output preserves the original text content
166
+ * (sum of chunks == original, modulo the boundary character that gets
167
+ * consumed by the split).
168
+ *
169
+ * If the input is already short enough, returns a single-element array.
170
+ */
171
+ export declare function splitTextForFeishu(text: string, maxChars: number): string[];
172
+ /**
173
+ * Lark errors may echo request/config values. Keep worker logs actionable while
174
+ * ensuring credentials and multiline payloads never cross the process boundary.
175
+ */
176
+ export declare function sanitizeFeishuWsError(rawError: unknown, appId: string, appSecret: string): Error;
29
177
  export {};
@@ -44,11 +44,20 @@ export interface FeishuBridgeOptions {
44
44
  * - stderr logger otherwise (standalone smoke debugging).
45
45
  */
46
46
  onEvent?: (event: NormalizedIMEvent) => Promise<void>;
47
+ /** Fatal WS failure after initial readiness (for worker lifecycle ownership). */
48
+ onTerminalError?: (error: Error) => void;
47
49
  }
48
50
  /** Bridge → parent: inbound IM event ready for think(). */
49
51
  export interface BridgeIncomingEnvelope {
50
52
  type: "event";
51
53
  event: NormalizedIMEvent;
54
+ /** Canonical outbound directory for this conversation (RFC-020 §15.1).
55
+ * Single source of truth — the agent-node injects this verbatim into
56
+ * the system prompt's "save files here" instruction, and the bridge
57
+ * whitelist accepts files only under this directory. Computed by the
58
+ * bridge from `event.conversation.conversationId` + `adapter
59
+ * .connectionName`. Trailing slash included. */
60
+ outboundDir?: string;
52
61
  }
53
62
  /** Parent → bridge: agent reply text for a previously-forwarded event. */
54
63
  export interface BridgeReplyEnvelope {
@@ -8,6 +8,31 @@ export interface FeishuAccessList {
8
8
  /** Feishu chat_ids the bot is permitted to listen in. */
9
9
  allowChats: string[];
10
10
  }
11
+ /**
12
+ * Outbound text-reply rendering mode (RFC-020 §16). Controls how
13
+ * `adapter.send` handles a text/markdown payload that doesn't already
14
+ * carry an `imagePath` / `files[]` (those upload routes are unaffected).
15
+ *
16
+ * - "plain" (DEFAULT): always send `msg_type:text`. Bot replies are
17
+ * fully copy-pasteable in Feishu; long replies are chunked into
18
+ * multiple text messages instead of being PNG-rendered. This is the
19
+ * correct default for issue/code/CLI bot replies where users want
20
+ * to grab the text. Vincent 2026-06-30 explicit ask: "issue 发文字".
21
+ *
22
+ * - "card": short markdown (bold, list, link, inline code) goes via
23
+ * schema 1.0 interactive card with `markdown` element — text stays
24
+ * copy-friendly + gets bolds/bullets styled. Heading/table/long
25
+ * fall back to plain text (no PNG). Suited to operators who want
26
+ * light formatting without losing copy.
27
+ *
28
+ * - "auto": preserve the pre-2026-06-30 behavior — markdown with
29
+ * headings / tables / >2000 chars is rendered to PNG via headless
30
+ * chromium (#329 path), short markdown goes to schema 1.0 card,
31
+ * plain text goes to msg_type:text. Highest fidelity at the cost
32
+ * of copy-paste. Opt-in for operators who genuinely need rendered
33
+ * tables / heading hierarchy in chat.
34
+ */
35
+ export type OutboundRenderMode = "plain" | "card" | "auto";
11
36
  export interface FeishuChannelConfig {
12
37
  appId: string;
13
38
  appSecret: string;
@@ -20,6 +45,12 @@ export interface FeishuChannelConfig {
20
45
  auditRaw: boolean;
21
46
  /** Per-task timeout in ms; default 5 min (RFC-020 §4.5). */
22
47
  taskTimeoutMs: number;
48
+ /**
49
+ * RFC-020 §16 outbound rendering mode for text replies. Default `"plain"`.
50
+ * See `OutboundRenderMode` for per-mode semantics. Channels that omit
51
+ * the field get `"plain"` — Vincent's "issue 发文字" default.
52
+ */
53
+ outboundRender: OutboundRenderMode;
23
54
  /**
24
55
  * Absolute path to the channel directory. The adapter writes downloaded
25
56
  * inbound media to `<channelDir>/media/` (M5c). Populated by the loader so
@@ -0,0 +1,88 @@
1
+ /**
2
+ * RFC-020 §17 — feishu inbound bridge → hub `/api/upload` integration.
3
+ *
4
+ * Vincent 2026-06-30: cross-machine agents (e.g. TM门户运维@toodadev2)
5
+ * delegated by the feishu-local bot can't read inbound attachments
6
+ * because the only thing they get is a host-local path that doesn't
7
+ * exist on the receiver's filesystem. #351 already wired agent-node's
8
+ * receiver to prefer `file_id` and pull via `GET /api/files/<id>` when
9
+ * present. This module is the SENDER half: the feishu bridge uploads
10
+ * each downloaded inbound file to the hub via `POST /api/upload`,
11
+ * gets back a `file_id`, and propagates it alongside the local path.
12
+ *
13
+ * Failure mode (load-bearing): every failure path returns `null` and
14
+ * the caller falls back to path-only. The bridge MUST NOT crash because
15
+ * the hub is down / overloaded / refused a 12 MiB cap. Single-host
16
+ * `agent-node` Read still works on the local path; only cross-host
17
+ * delegation degrades, no regression vs the pre-fix baseline.
18
+ *
19
+ * Concurrency cap: a single feishu message can carry many images; bursts
20
+ * to /api/upload would hammer the hub rate limit (60/hour per token).
21
+ * `uploadFilesToHubConcurrent` caps in-flight requests at `concurrency`
22
+ * (default 4) so a 20-image message takes 5 sequential rounds instead
23
+ * of 20 simultaneous open sockets + a likely rate-limit denial.
24
+ */
25
+ /**
26
+ * Hub upload limit, mirrors `server/src/uploads.ts:MAX_UPLOAD_BYTES`.
27
+ * Anything bigger is skipped at the bridge — the hub would 413 anyway.
28
+ */
29
+ export declare const HUB_UPLOAD_LIMIT_BYTES: number;
30
+ /** Default in-flight cap for `uploadFilesToHubConcurrent`. */
31
+ export declare const DEFAULT_UPLOAD_CONCURRENCY = 4;
32
+ /**
33
+ * One file uploaded to the hub. `mime` and `size` are from the local
34
+ * filesystem read; `file_id` and `path` come from the hub's response.
35
+ *
36
+ * `file_id` is the canonical cross-machine handle — receiving agent
37
+ * resolves to bytes via `GET /api/files/<file_id>`. `path` is the
38
+ * hub-machine-local absolute path the hub stored to; on the sender
39
+ * side it's purely informational (we already have the source file).
40
+ */
41
+ export interface HubUploadResult {
42
+ file_id: string;
43
+ path?: string;
44
+ mime?: string;
45
+ size?: number;
46
+ name?: string;
47
+ }
48
+ export interface HubUploadOpts {
49
+ /** Hub base URL, no trailing slash. Defaults to env. */
50
+ hubUrl: string;
51
+ /** Bearer token (ntok_ / utok_ / atok_). Defaults to env. */
52
+ authToken: string;
53
+ /** Optional MIME hint; sniffed by filename ext otherwise. */
54
+ mime?: string;
55
+ /** Optional override filename (defaults to basename(path)). */
56
+ name?: string;
57
+ /** Injectable for tests. Defaults to global fetch. */
58
+ fetch?: typeof fetch;
59
+ }
60
+ /**
61
+ * Upload one local file to `${hubUrl}/api/upload`. Returns the file
62
+ * descriptor on success, or `null` on any failure (caller falls back
63
+ * to path-only).
64
+ *
65
+ * - File must exist + be ≤ 12 MiB. Larger → skipped silently with
66
+ * a stderr warn; caller gets `null` and ships path-only.
67
+ * - Auth via `Authorization: Bearer <token>`.
68
+ * - `Content-Length` header is set by `fetch` when given a Blob body;
69
+ * the hub validates it before consuming bytes.
70
+ * - Multipart body with a single `file` field. The hub server
71
+ * reads `form.get("file")` and stores under a new file_id.
72
+ * - Any network error / non-2xx / malformed JSON response → null.
73
+ */
74
+ export declare function uploadToHub(filePath: string, opts: HubUploadOpts): Promise<HubUploadResult | null>;
75
+ /**
76
+ * Upload many files to the hub with a bounded concurrency window.
77
+ * Returns one result per input path, preserving order. A failed
78
+ * upload appears as `null` at that slot — caller composes path-only
79
+ * descriptors for those.
80
+ *
81
+ * Why this matters: one feishu post can carry an arbitrary number of
82
+ * images. Naive `Promise.all(paths.map(uploadToHub))` would open N
83
+ * simultaneous HTTPS sockets to the hub AND blow past the 60/hour
84
+ * per-token rate limit on a single message with >60 images. A
85
+ * concurrency cap of 4 means N/4 sequential rounds, predictable
86
+ * load, no head-of-line blocking on the agent's reply.
87
+ */
88
+ export declare function uploadFilesToHubConcurrent(filePaths: string[], opts: HubUploadOpts, concurrency?: number): Promise<(HubUploadResult | null)[]>;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * RFC-020 §14 — markdown → image rendering for Feishu replies.
3
+ *
4
+ * Vincent 2026-06-29 path: Feishu's `markdown` card element doesn't
5
+ * render ATX headings or GFM tables (preview.7 caught only bold / list
6
+ * / link). Rather than partially support a moving subset of card
7
+ * elements, we render structured markdown to a PNG via headless
8
+ * chromium and send it through Feishu's image API (`im:resource:upload`
9
+ * scope). Pixel-perfect fidelity, zero schema fragility, text-not-
10
+ * copyable accepted as the tradeoff for "actually renders".
11
+ *
12
+ * Hybrid route (decided in adapter.send):
13
+ * - plain text (no markdown markers) → msg_type:"text"
14
+ * - markdown WITHOUT heading / table / long → msg_type:"interactive" (schema 1.0 card with `markdown` element — keeps copy/paste for short bold/list/link replies; preview.7 path)
15
+ * - markdown WITH heading / table / long → THIS PATH (msg_type:"image" with rendered PNG)
16
+ *
17
+ * Renderer choice: `puppeteer-core` (no bundled chromium) + system
18
+ * chromium (apt install in Docker). Rationale:
19
+ * - Pure-JS canvas-layout libraries (node-canvas, @napi-rs/canvas)
20
+ * cost 4-6h of manual paragraph wrapping + table cell measurement
21
+ * + Chinese width metrics; chromium does this natively.
22
+ * - puppeteer-core (5MB) + system chromium (~100MB) is smaller than
23
+ * full puppeteer (170MB) which bundles its own chromium.
24
+ * - Headless screenshot ~500ms after warmup. Bot's heavy turn is 20-
25
+ * 70s; rendering cost is in the noise.
26
+ *
27
+ * Chromium reuse: we keep a single browser instance hot across
28
+ * renderings to avoid the ~2-3s cold-start per call. Auto-close on
29
+ * idle is a follow-up — agent-node worker lifetime is bounded.
30
+ */
31
+ import { Buffer } from "node:buffer";
32
+ /**
33
+ * Close the shared browser. Called from adapter.stop() during graceful
34
+ * worker shutdown. Subsequent render calls re-launch.
35
+ */
36
+ export declare function closeBrowser(): Promise<void>;
37
+ /**
38
+ * Render markdown text to a PNG buffer.
39
+ *
40
+ * Width is fixed at 800px (IM-friendly); height auto-fits content via
41
+ * `fullPage:true`. Returns the raw PNG bytes — caller hands them to
42
+ * `lark.im.image.create({image: Readable.from(buffer)})`.
43
+ *
44
+ * Throws on chromium launch failure or page navigation failure.
45
+ * Caller is responsible for fallback (e.g., send the raw text as a
46
+ * code block in the schema 1.0 card path).
47
+ */
48
+ export declare function renderMarkdownToPng(text: string): Promise<Buffer>;
49
+ /**
50
+ * Decide whether `renderMarkdownToPng` should be invoked for this reply
51
+ * text, vs. falling back to msg_type:"text" / msg_type:"interactive"
52
+ * (schema 1.0 card). Locked by 通信龙 3f70044c — trigger image when:
53
+ * - text contains a markdown table (Feishu card can't render)
54
+ * - text contains an ATX heading (Feishu card can't render)
55
+ * - text length > 2000 chars (image is better than scrollable text wall)
56
+ *
57
+ * Returns false for short prose, single-line plain text, and short
58
+ * markdown lists / bold / link / inline-code which DO render fine in
59
+ * the schema 1.0 `markdown` card element.
60
+ */
61
+ export declare function shouldRenderAsImage(text: string): boolean;