@sleep2agi/agent-network 2.3.0-preview.2 → 2.3.0-preview.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,140 @@
1
+ /**
2
+ * RFC-020 §15 — agent→bridge outbound file protocol.
3
+ *
4
+ * 2026-06-29 Vincent UAT: agent generated a PDF via reportlab + wrote it
5
+ * to `/work/feishu-attachments/<conv>/x.pdf`, then in text asked Vincent
6
+ * "I'm not sure if the system will auto-attach this — try another way?"
7
+ * The bridge has `adapter.send({files})` since #329, but no protocol
8
+ * told the agent how to signal "dispatch this file to the user".
9
+ *
10
+ * Convention: in its final reply, the agent emits one
11
+ *
12
+ * [[send-file:/abs/path]]
13
+ *
14
+ * marker per file (one per line, end of reply). The bridge:
15
+ *
16
+ * 1. extracts every `[[send-file:...]]` token,
17
+ * 2. strips them from the user-visible text,
18
+ * 3. validates each path against an allowed-outbound-root whitelist
19
+ * (`/work/feishu-attachments/<conn>/<chat>/` — same per-conversation
20
+ * directory the LLM has Write access to under Layer B),
21
+ * 4. checks the file exists, is non-empty, and ≤ 30 MB (Feishu file_v1
22
+ * upper bound),
23
+ * 5. magic-byte sniffs to choose `image_key` vs `file_key` upload route,
24
+ * 6. dispatches each file via `adapter.send({files:[...]})`,
25
+ * 7. emits a friendly fallback if validation fails — never the raw error.
26
+ *
27
+ * Pure module — no I/O, no IM SDK calls. The parser returns the cleaned
28
+ * text + a structured list of file requests; bridge.ts is responsible
29
+ * for filesystem checks and dispatching.
30
+ */
31
+ /**
32
+ * One outbound-file request parsed from an agent reply.
33
+ *
34
+ * - `raw`: the bytes between `[[send-file:` and `]]`, before any
35
+ * normalization. Kept for stderr forensic.
36
+ * - `normalized`: lexical-normalized absolute path (quote-strip, `..`
37
+ * collapse, `//` collapse, `./` resolution against cwd). The
38
+ * `validatedAbsolute` field is set later by the bridge after the
39
+ * realpath / whitelist / exists check.
40
+ */
41
+ export interface OutboundFileRequest {
42
+ raw: string;
43
+ normalized: string;
44
+ }
45
+ export interface MarkerParseResult {
46
+ /** Reply text with all `[[send-file:...]]` markers removed + adjacent
47
+ * whitespace collapsed. May be empty (file-only reply). */
48
+ cleanedText: string;
49
+ /** Files in source order. Caller-side validation happens after. */
50
+ files: OutboundFileRequest[];
51
+ }
52
+ /**
53
+ * Lexically normalize a path token from the marker. NOT a full
54
+ * symlink/realpath resolver — bridge does that after this returns.
55
+ *
56
+ * - Trim leading / trailing whitespace.
57
+ * - Strip one layer of matching quotes (`"/x"` / `'/x'` → `/x`).
58
+ * - `.` and `..` segments collapse via `path.posix.normalize`.
59
+ * - Repeated `/` collapse.
60
+ *
61
+ * Returns an absolute path or the empty string if the input cannot be
62
+ * interpreted as an absolute path token (caller drops empties).
63
+ */
64
+ export declare function normalizeMarkerPath(raw: string): string;
65
+ /**
66
+ * Parse an agent reply into cleaned text + outbound-file requests.
67
+ *
68
+ * Empty / null input returns `{cleanedText: "", files: []}` so callers
69
+ * can safely pipe through without defensive checks.
70
+ *
71
+ * Marker-only reply (no surrounding text) returns `cleanedText: ""` —
72
+ * caller should NOT send an empty text message in that case; they only
73
+ * dispatch the files.
74
+ *
75
+ * Multiple markers on one reply are all captured. Adjacent whitespace
76
+ * around stripped markers is collapsed (no double blank lines).
77
+ */
78
+ export declare function parseOutboundMarkers(reply: string | null | undefined): MarkerParseResult;
79
+ export { OUTBOUND_ROOT, feishuConvKey, feishuOutboundDir } from "./outbound-paths.js";
80
+ /**
81
+ * Validate a normalized absolute path against the per-conversation
82
+ * whitelist + size + existence checks. Returns null on success or a
83
+ * Chinese user-friendly reason on failure (the same string can be
84
+ * surfaced as a fallback text reply when ALL files fail validation).
85
+ *
86
+ * Filesystem-touching — bridge calls this AFTER `parseOutboundMarkers`.
87
+ *
88
+ * Two API shapes accepted (overload):
89
+ *
90
+ * 1. **Preferred**: caller passes `expectedDir` — the precomputed
91
+ * `/work/feishu-attachments/<connectionName>/<convKey>/` value
92
+ * from `feishuOutboundDir`. This guarantees what the agent was
93
+ * TOLD to use (via cli.ts prompt injection) matches what we
94
+ * ACCEPT here — no second algorithm.
95
+ *
96
+ * 2. **Legacy**: caller passes `connectionName` + `convKey`. We
97
+ * compute the prefix here via the same helper. Kept for the
98
+ * single-arg unit-test ergonomics + backwards-compat (the old
99
+ * bridge wire-up shape).
100
+ *
101
+ * Params:
102
+ * - p: normalized absolute path candidate
103
+ * - expectedDir: precomputed whitelist directory (trailing `/`)
104
+ * OR
105
+ * - convKey + connectionName: legacy two-piece form
106
+ * - statFn: optional override for tests (defaults to fs.statSync)
107
+ * - realpathFn: optional override for tests (defaults to fs.realpathSync)
108
+ *
109
+ * The whitelist check uses literal `.startsWith(expectedDir)` — the
110
+ * trailing slash on `expectedDir` ensures `oc_abc/` doesn't accept
111
+ * paths under `oc_abc_evil/`.
112
+ */
113
+ export interface ValidateOpts {
114
+ p: string;
115
+ /** Precomputed prefix (with trailing `/`). Preferred over convKey+connectionName. */
116
+ expectedDir?: string;
117
+ convKey?: string;
118
+ connectionName?: string;
119
+ statFn?: (p: string) => {
120
+ size: number;
121
+ };
122
+ realpathFn?: (p: string) => string;
123
+ }
124
+ export declare function validateOutboundPath(opts: ValidateOpts): string | null;
125
+ /**
126
+ * Magic-byte sniffer — picks `image` vs `file` upload route. Reads the
127
+ * first 16 bytes only; safe to call before commitment. Returns:
128
+ *
129
+ * - "image" when the bytes are a PNG / JPG / GIF / WebP / BMP signature
130
+ * (Feishu image_v1 supports these natively, with chat inline render).
131
+ * - "file" otherwise (PDF, TXT, audio, video, archive, …).
132
+ *
133
+ * Caller supplies a Buffer (bridge reads via fs.openSync + readSync).
134
+ */
135
+ export declare function sniffFileKind(buf: Buffer): "image" | "file";
136
+ /**
137
+ * User-facing fallback message when ALL marker validations fail and the
138
+ * stripped text is empty (would leave the user with no reply at all).
139
+ */
140
+ export declare const ALL_FILES_FAILED_FALLBACK = "[\u6587\u4EF6\u9644\u4EF6\u53D1\u9001\u5931\u8D25] \u6211\u51C6\u5907\u597D\u4E86\u6587\u4EF6\u4F46\u5206\u53D1\u65F6\u51FA\u4E86\u95EE\u9898\u2014\u2014\u7A0D\u540E\u518D\u8BD5\u6216\u6362\u79CD\u65B9\u5F0F\u3002";
@@ -0,0 +1,50 @@
1
+ /**
2
+ * RFC-020 §15.1 — feishu outbound/attachment path helpers (SHARED).
3
+ *
4
+ * Single source of truth for `/work/feishu-attachments/<conn>/<convKey>/`
5
+ * naming. Used by:
6
+ *
7
+ * - `adapter.ts` inbound `downloadImage` (subdir for received images),
8
+ * - `bridge.ts` outbound marker whitelist (where the agent may write),
9
+ * - `worker.ts` outbound envelope (the concrete path injected into the
10
+ * agent's prompt, so what we tell the agent matches what we accept).
11
+ *
12
+ * 2026-06-29 Vincent UAT: prior to this module, the inbound downloader
13
+ * used `conversationId.replace(/[^a-zA-Z0-9_-]/g, "_")` and the outbound
14
+ * bridge whitelist used `sender.id` for DMs / `chatId` for groups. The
15
+ * two algorithms diverged — agent learned the inbound oc_<chat>/ layout
16
+ * from incoming attachments, then wrote outbound files to the same
17
+ * oc_<chat>/ subdir, but the bridge required ou_<userid>/. Every PDF
18
+ * generated by the bot was rejected. This module unifies on
19
+ * `conversationId` (the open_chat_id assigned by Feishu — present for
20
+ * DMs and groups equally).
21
+ */
22
+ /**
23
+ * Sanitize a raw Feishu conversation id (`oc_<hex>` / occasionally
24
+ * `om_<id>` for DMs) into a filesystem-safe segment. Identical to the
25
+ * adapter.ts inbound download path policy — DO NOT CHANGE without also
26
+ * migrating any on-disk attachments under the old key.
27
+ *
28
+ * The regex strips anything outside `[A-Za-z0-9_-]`, replacing with `_`.
29
+ * Falsy / non-string input returns the empty string; caller is
30
+ * responsible for substituting a fallback (the empty key would resolve
31
+ * to `/work/feishu-attachments/<conn>//` which the path-prefix
32
+ * whitelist rejects cleanly).
33
+ */
34
+ export declare function feishuConvKey(rawId: string | undefined | null): string;
35
+ /**
36
+ * Compute the canonical per-conversation directory for outbound file
37
+ * dispatch + inbound attachment downloads. Trailing slash included so
38
+ * `.startsWith(...)` whitelist checks are unambiguous about the
39
+ * conversation boundary (no `oc_abc` matching `oc_abc_x`).
40
+ *
41
+ * Example:
42
+ * feishuOutboundDir("feishu-local", "oc_9a7eedbba275a87999f7ee2cfb10f4cb")
43
+ * → "/work/feishu-attachments/feishu-local/oc_9a7eedbba275a87999f7ee2cfb10f4cb/"
44
+ */
45
+ export declare function feishuOutboundDir(connectionName: string, rawConvId: string | undefined | null): string;
46
+ /**
47
+ * The fixed prefix root used as a sanity check by the marker validator.
48
+ * Useful for tests + for `validateOutboundPath` defense-in-depth.
49
+ */
50
+ export declare const OUTBOUND_ROOT = "/work/feishu-attachments";
@@ -0,0 +1,62 @@
1
+ /**
2
+ * RFC-020 §16.1 — feishu outbound route decision (pure helper).
3
+ *
4
+ * Single source of truth for the `adapter.send` decision tree that
5
+ * picks among text / interactive card / image (rendered PNG) / file /
6
+ * imagePath outputs. Extracted into a pure module so the production
7
+ * call site AND the unit tests can bind the same function — previously
8
+ * the test mirrored the decision tree in a sibling `pickRoute` helper,
9
+ * which would drift silently if the production tree changed.
10
+ *
11
+ * Inputs are the minimal data the decision needs:
12
+ *
13
+ * - `text` / `imagePath` / `files` — payload from `NormalizedIMMessage`
14
+ * - `forceTextOnly` — caption-mode hint (RFC-020 §15.2)
15
+ * - `mode` — channel-config `outboundRender` (`"plain"` / `"card"` /
16
+ * `"auto"`, RFC-020 §16)
17
+ *
18
+ * Outputs the chosen `route` plus a short `reason` string for log /
19
+ * debug. The CALLER (adapter.send) actually performs the upload /
20
+ * render side-effects keyed on the route — this function does no I/O.
21
+ *
22
+ * Behavior contract (mirrors adapter.send line-for-line, locked by
23
+ * `feishu-outbound-render-mode.test.ts`):
24
+ *
25
+ * 1. `imagePath` set → `image_upload`
26
+ * 2. `files[0].path` set → `file_upload`
27
+ * 3. `forceTextOnly` true → `text`
28
+ * 4. mode "plain" → `text` (always)
29
+ * 5. mode "card" → `card_short_md` iff `looksLikeMarkdown(text)` AND
30
+ * NOT `shouldRenderAsImage(text)`; else `text`
31
+ * 6. mode "auto" → `image_render` iff `shouldRenderAsImage(text)`;
32
+ * else `card_short_md` iff `looksLikeMarkdown(text)`; else `text`
33
+ * 7. unknown mode (defensive default-default) → `text`
34
+ *
35
+ * The production switch in adapter.send may add the actual upload /
36
+ * render / lark API calls keyed on the route, but the route itself
37
+ * is decided HERE. To change the decision, change this file.
38
+ */
39
+ export type OutboundRoute = "image_upload" | "file_upload" | "text" | "card_short_md" | "image_render";
40
+ export interface RouteInput {
41
+ text?: string;
42
+ imagePath?: string;
43
+ files?: {
44
+ name: string;
45
+ path?: string;
46
+ }[];
47
+ forceTextOnly?: boolean;
48
+ /** `outboundRender` from the channel config. Defaults to "plain" when
49
+ * absent so a caller that doesn't read the config still gets the
50
+ * "Vincent default" behavior. */
51
+ mode?: "plain" | "card" | "auto";
52
+ }
53
+ export interface RouteDecision {
54
+ route: OutboundRoute;
55
+ reason: string;
56
+ }
57
+ /**
58
+ * Decide the outbound route for a `NormalizedIMMessage` (or a subset
59
+ * of its fields). Pure — no I/O, no SDK calls; safe to call from tests
60
+ * directly.
61
+ */
62
+ export declare function resolveOutboundRoute(input: RouteInput): RouteDecision;