@markus-global/cli 0.11.3 → 0.12.0-rc.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.
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.js +5 -1
- package/dist/backend.js.map +1 -1
- package/dist/commands/approval-card.d.ts +53 -0
- package/dist/commands/approval-card.d.ts.map +1 -0
- package/dist/commands/approval-card.js +43 -0
- package/dist/commands/approval-card.js.map +1 -0
- package/dist/commands/auth.d.ts.map +1 -1
- package/dist/commands/auth.js +11 -5
- package/dist/commands/auth.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +7 -5
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/model.d.ts.map +1 -1
- package/dist/commands/model.js +6 -4
- package/dist/commands/model.js.map +1 -1
- package/dist/commands/outbound.d.ts +76 -0
- package/dist/commands/outbound.d.ts.map +1 -0
- package/dist/commands/outbound.js +80 -0
- package/dist/commands/outbound.js.map +1 -0
- package/dist/commands/start.d.ts +124 -2
- package/dist/commands/start.d.ts.map +1 -1
- package/dist/commands/start.js +718 -82
- package/dist/commands/start.js.map +1 -1
- package/dist/index.js +5 -20
- package/dist/index.js.map +1 -1
- package/dist/markus.mjs +112615 -103125
- package/dist/web-ui/assets/AsyncState-BebkDWbq.js +1 -0
- package/dist/web-ui/assets/{CommentInput-DN3Cichs.js → CommentInput-BRZWIC3U.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-CjHOyYgJ.js → ContentRenderer-PGP8H_Zz.js} +2 -2
- package/dist/web-ui/assets/DeliverableShareModal-CcigVYGz.js +1 -0
- package/dist/web-ui/assets/Deliverables-CQwXaCA4.js +3 -0
- package/dist/web-ui/assets/{Notifications-CCsdBfdg.js → Notifications-BvHJCIRG.js} +1 -1
- package/dist/web-ui/assets/Search-BA-aXh7i.js +1 -0
- package/dist/web-ui/assets/SendToChat-CAfyKhpq.js +1 -0
- package/dist/web-ui/assets/Settings-icFp6tNI.js +8 -0
- package/dist/web-ui/assets/{Store-BWi97VP9.js → Store-DKwOcmMu.js} +1 -1
- package/dist/web-ui/assets/Switch-C7lFnHA7.js +1 -0
- package/dist/web-ui/assets/Team-DyqXLZ-X.js +84 -0
- package/dist/web-ui/assets/Work-BXGrda4S.js +12 -0
- package/dist/web-ui/assets/{arc-Cg0-C295.js → arc-Dnk6N-Zc.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BctEHNLp.js → architectureDiagram-3BPJPVTR-CV8JIXXD.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-hxr2ZwOV.js → blockDiagram-GPEHLZMM-D9pKmrXH.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-CfIRo1GE.js → c4Diagram-AAUBKEIU-Q26HvIpY.js} +1 -1
- package/dist/web-ui/assets/channel-BZs6ereM.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-T0bENsqX.js → chunk-2J33WTMH-BSjFVwnx.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-ChLLkyYx.js → chunk-4BX2VUAB-BZXv4MQp.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-BD3ENYp9.js → chunk-55IACEB6-CeKd3oeJ.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-BAes4atE.js → chunk-727SXJPM-DP1tSQo5.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-FymM7gfT.js → chunk-AQP2D5EJ-DqEncn7j.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-N5sRT0m9.js → chunk-FMBD7UC4-tuDUJ9Xx.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-BSjS3JyS.js → chunk-ND2GUHAM-DoC8aLWB.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-Dkwitdbr.js → chunk-QZHKN3VN-74zpvcgs.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C9JIxJeJ.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C9JIxJeJ.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-BLuYATCK.js → cose-bilkent-S5V4N54A-DjYUalC1.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-DGLiqiH2.js → dagre-BM42HDAG-oSewacE8.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-Cq_GnNKs.js → diagram-2AECGRRQ-C1fiWe46.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-CHNz-2dA.js → diagram-5GNKFQAL-9G_q6hCa.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-D8eKa7jh.js → diagram-KO2AKTUF-CSm-lJp-.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-RkDgQcLr.js → diagram-LMA3HP47-BTAORcHx.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-LqxQrIwa.js → diagram-OG6HWLK6-DbcCkDfo.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-Be-Qo_ag.js → docx-preview-DjqdA44x.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-BX0zZgYQ.js → erDiagram-TEJ5UH35-DFa-B8-u.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-DKnfIFA4.js → flowDiagram-I6XJVG4X-WCTnaK9M.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-DjBURmY-.js → ganttDiagram-6RSMTGT7-DbW1CoJJ.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BvSi7SvS.js → gitGraphDiagram-PVQCEYII-1faDfO29.js} +1 -1
- package/dist/web-ui/assets/index-B8h1PPzP.js +883 -0
- package/dist/web-ui/assets/index-DD3NMntN.css +1 -0
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CwtIgim2.js → infoDiagram-5YYISTIA-DfXKP4tQ.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-CWhXJfSa.js → ishikawaDiagram-YF4QCWOH-D6FOsFQ5.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-DN9rorlL.js → journeyDiagram-JHISSGLW-DXpxntIF.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-Burf5FE8.js → kanban-definition-UN3LZRKU-Dt7FBCF3.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-Dx4rzlyC.js → mermaid.core-sTcSUoRD.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DqZ21Siw.js → mindmap-definition-RKZ34NQL-CvOU23ga.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-C_4ksu-T.js → pieDiagram-4H26LBE5-DUedtXVj.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-Dl6Rjg1X.js → quadrantDiagram-W4KKPZXB-CqpHHRca.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-CzmWi02d.js → requirementDiagram-4Y6WPE33-CKZYvVDJ.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-D8K7e8we.js → sankeyDiagram-5OEKKPKP-gZ0nzDfs.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-1z9rqtVx.js → sequenceDiagram-3UESZ5HK-DN3XdBkW.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-nneYkkHa.js → stateDiagram-AJRCARHV-BvtafGxO.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-B2nWDV5R.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-D6GmLlRi.js → timeline-definition-PNZ67QCA-BrR919lp.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-TVefhiCa.js → vennDiagram-CIIHVFJN-B7CTm4yM.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-BgUuAeiM.js → wardley-L42UT6IY-CyqFngx_.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CyJ_l94o.js → wardleyDiagram-YWT4CUSO-BCqEPBJ5.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-kajbbx7a.js → xychartDiagram-2RQKCTM6-BmT6Cmz-.js} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/docs/README.md +1 -0
- package/docs/architecture/architecture.md +1 -1
- package/docs/architecture/configuration-model.md +156 -0
- package/docs/architecture/messaging-gateway.md +1043 -0
- package/docs/architecture/notification-delivery.md +273 -0
- package/docs/design/remote-access-contract.md +445 -0
- package/docs/guides/development.md +1 -1
- package/docs/guides/guide.md +4 -2
- package/docs/guides/remote-access.md +147 -214
- package/docs/handoff/approval-tri-state-handoff.md +69 -0
- package/docs/handoff/remote-access-handoff.md +160 -0
- package/docs/records/agent-platform-friction-2026-10.md +102 -2
- package/package.json +1 -1
- package/dist/web-ui/assets/DeliverableShareModal-CBSvxB-X.js +0 -1
- package/dist/web-ui/assets/Deliverables-BaAF4-w0.js +0 -3
- package/dist/web-ui/assets/Search-BiBdevAU.js +0 -1
- package/dist/web-ui/assets/Settings-CawBnWuy.js +0 -8
- package/dist/web-ui/assets/Team-CfUDkdc3.js +0 -84
- package/dist/web-ui/assets/Work-DrIXOW-P.js +0 -12
- package/dist/web-ui/assets/channel-DAQ2Rbxq.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BZyCVtJb.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BZyCVtJb.js +0 -1
- package/dist/web-ui/assets/index-D8vskks7.js +0 -882
- package/dist/web-ui/assets/index-DEN_qReg.css +0 -1
- package/dist/web-ui/assets/modelCapabilities-DDtCBZ6o.js +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C-hpzcms.js +0 -1
|
@@ -0,0 +1,1043 @@
|
|
|
1
|
+
# Messaging Gateway
|
|
2
|
+
|
|
3
|
+
**Status:** implemented.
|
|
4
|
+
**Related:** `packages/comms/docs/platform-manifest.md` (type contract + "how to add a
|
|
5
|
+
platform"), issue #340.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Problem & goals
|
|
10
|
+
|
|
11
|
+
The comms layer today can *connect* a platform but cannot *express* how a platform
|
|
12
|
+
maps onto the organisation. The owner's requirement, stated plainly:
|
|
13
|
+
|
|
14
|
+
1. Markus must expose **one generic in/out gateway** with a unified abstraction over
|
|
15
|
+
three kinds of channel: an **agent's main session**, a **group chat**, and
|
|
16
|
+
**notifications**.
|
|
17
|
+
2. A single external platform may host **many bots**, each mapped to a different
|
|
18
|
+
internal agent. (e.g. 10 agents on Markus, 5 bots on Feishu + 5 on Telegram.)
|
|
19
|
+
3. **Default**: bind the **Secretary** agent, and route **all notifications** through
|
|
20
|
+
that same channel.
|
|
21
|
+
4. The user can **rebind** any of it, or **create a new bot** and bind it elsewhere.
|
|
22
|
+
5. Common capabilities must be abstracted and provided uniformly; **platform-unique
|
|
23
|
+
capabilities must also be supportable** without polluting the core.
|
|
24
|
+
|
|
25
|
+
Non-goal for this document: implementing every platform capability. The document
|
|
26
|
+
fixes the *model*; capabilities land behind it incrementally.
|
|
27
|
+
|
|
28
|
+
## 2. Current state & root causes
|
|
29
|
+
|
|
30
|
+
A read-only baseline scan (evidence with `file:line`) found four single sources of
|
|
31
|
+
truth and four multi-point implementations:
|
|
32
|
+
|
|
33
|
+
| Concern | Today | Verdict |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| Which platforms exist / their fields | `PLATFORM_MANIFESTS`, `AGENT_BINDING_FIELD` (`comms/src/platforms/registry.ts`) | **single source ✓** |
|
|
36
|
+
| Wire format of an inbound message | `Message` (`shared/src/types/message.ts:11-23`) | **single source ✓** |
|
|
37
|
+
| Persistence | `integrations` table (`storage/src/sqlite-storage.ts:650`) | **single source ✓** |
|
|
38
|
+
| Binding resolution | router snapshot at startup **and** live DB re-read per message | **two writers ✗** |
|
|
39
|
+
| Inbound dispatch (Feishu) | `MessageRouter.routeIncomingMessage` **and** `handleFeishuUserMessage` | **two paths ✗** |
|
|
40
|
+
| Credential write | generic `savePlatform` **and** QR-register writing the repo directly | **two writers ✗** |
|
|
41
|
+
| Outbound notification | `FeishuNotifier` only | **one platform ✗** |
|
|
42
|
+
|
|
43
|
+
Concrete defects this causes:
|
|
44
|
+
|
|
45
|
+
- **D1 — one platform, one bot.** `integrations` is keyed `(org, platform)`. There is
|
|
46
|
+
no way to hold two Telegram bots, so "N agents ↔ M bots" is unrepresentable.
|
|
47
|
+
- **D2 — binding is platform-level only.** `bindAgentToChannel` exists
|
|
48
|
+
(`comms/src/router.ts:25`) but production never calls it; startup only calls
|
|
49
|
+
`bindPlatformAgent`. Group-chat-level binding is unreachable.
|
|
50
|
+
- **D3 — no session isolation.** `Message` carries no session field; the router never
|
|
51
|
+
injects one; the Feishu live path calls `getOrCreateMainSession(...)`
|
|
52
|
+
(`org-manager/src/api-server.ts:2889`). **Every Feishu user shares one session.**
|
|
53
|
+
- **D4 — two Feishu inbound paths.** Both can be live at once ⇒ a message is handled
|
|
54
|
+
twice, in two different sessions (one with thinking-card/reaction UX, one without).
|
|
55
|
+
- **D5 — outbound is Feishu-only.** `hitl-service.notify` (`hitl-service.ts:476`) is a
|
|
56
|
+
platform-agnostic notification record, but the only subscriber is `FeishuNotifier`.
|
|
57
|
+
Telegram/Slack/Discord/WhatsApp users never receive approvals or input requests.
|
|
58
|
+
- **D6 — unbound behaviour disagrees.** Feishu falls back to the Secretary
|
|
59
|
+
(`api-server.ts:2780`); the router logs a warning and **drops** (`router.ts:115`).
|
|
60
|
+
- **D7 — `sendAsAgent` ignores `agentId`** (`router.ts:105`): "send as this agent"
|
|
61
|
+
does not exist.
|
|
62
|
+
|
|
63
|
+
**Root cause (one sentence):** *the concept of "a bot instance" does not exist in the
|
|
64
|
+
code.* Everything above follows from conflating **platform** with **bot identity**.
|
|
65
|
+
|
|
66
|
+
## 3. Industry patterns → our decisions
|
|
67
|
+
|
|
68
|
+
Sources: matterbridge, Matrix Application Services, Microsoft Bot Framework,
|
|
69
|
+
Chatwoot, Mattermost/Zulip, Slack multi-workspace, Nylas grants, Twilio Conversations.
|
|
70
|
+
Full notes: `research/gateway-patterns.md`.
|
|
71
|
+
|
|
72
|
+
| Concern | Industry pattern | Our decision |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| Bot identity | matterbridge: `account` prefix = protocol, *more instances = more accounts*; Nylas: one account = one `grant`; Slack: per-`team_id` token | **First-class `BotInstance`** — `platform ≠ instance`. One instance = one credential set + one namespace. |
|
|
75
|
+
| Channel | `Channels[channel+account]`; Matrix room alias; BF `conversation` | **`ChannelRef { instanceId, nativeId, kind }`**, `kind ∈ {main, group, notification}` |
|
|
76
|
+
| Binding | BF per-conversation state; Chatwoot `Inbox → AgentBot` | **Layered, nearest-wins:** global → platform → instance → channel. Record *which level matched*. |
|
|
77
|
+
| Threads | parent-id + LRU cache; Nylas threads | **Canonical conversation key ↔ native ids**, both directions |
|
|
78
|
+
| Outbound | BF `ConversationReference` for proactive send | **`OutboundDispatcher`** consuming HITL + EventBus, rendering per capability |
|
|
79
|
+
| Platform extras | matterbridge `Extra` + Tengo escape hatch; BF `channelData` | Core knows the **minimal common set**; unique features ride in `extra` behind declared **capabilities**. |
|
|
80
|
+
| Fallback | some bridges silently drop | **Never silently drop.** Fallback chain ends at the global default (Secretary). |
|
|
81
|
+
|
|
82
|
+
**Learned caution:** matterbridge inlined protocol special-cases into its core and
|
|
83
|
+
later had to bolt on a scripting escape hatch. **We will not inline platform quirks
|
|
84
|
+
into the router** — capabilities + `extra` from day one.
|
|
85
|
+
|
|
86
|
+
## 4. Target model
|
|
87
|
+
|
|
88
|
+
Four entities, three of them new:
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
BotInstance one configured bot on one platform (id, platform, label,
|
|
92
|
+
credentials, capabilities, enabled) ← NEW
|
|
93
|
+
ChannelRef { instanceId, nativeId, kind } ← NEW
|
|
94
|
+
kind ∈ { main, dm, group, notification }
|
|
95
|
+
Binding (scope, agentId) scope ∈ { global, platform,
|
|
96
|
+
instance, channel } ← NEW (replaces agentId field)
|
|
97
|
+
ConversationKey canonical id ↔ (instanceId, nativeId) ← NEW
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Relationships:
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
organisation
|
|
104
|
+
└── platform "telegram"
|
|
105
|
+
├── instance "sales-bot" ──binding──▶ agent "Sales"
|
|
106
|
+
│ ├── main (DM with owner) ──▶ Sales main session
|
|
107
|
+
│ ├── group "team-a" ──▶ Sales session #a
|
|
108
|
+
│ └── notification (owner DM) ──▶ Sales notification sink
|
|
109
|
+
└── instance "ops-bot" ──binding──▶ agent "Secretary"
|
|
110
|
+
└── …
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`platform` is a **manifest** (declared capabilities + field schema + adapter
|
|
114
|
+
factory). `instance` is a **configuration** of that manifest with credentials.
|
|
115
|
+
Adding a platform = one manifest; adding a bot = one instance row. Neither touches
|
|
116
|
+
the router.
|
|
117
|
+
|
|
118
|
+
### 4.1 Worked example (what "instance" vs "group" actually means)
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
platform "feishu"
|
|
122
|
+
├── instance "销售助手" (one self-built app you created in the Feishu console)
|
|
123
|
+
│ ├── group "销售一群" ──binding──▶ agent "Sales"
|
|
124
|
+
│ └── group "销售二群" ──binding──▶ agent "Sales"
|
|
125
|
+
└── instance "通用助手" (a second app, second bot identity)
|
|
126
|
+
├── group "产品群" ──binding──▶ agent "Product"
|
|
127
|
+
├── group "运营群" ──binding──▶ agent "Ops"
|
|
128
|
+
└── dm "老板的单聊" ──binding──▶ agent "Secretary" (kind=main)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- **instance** = one concrete bot you created and configured (credentials, avatar).
|
|
132
|
+
"5 bots on Feishu" = 5 instances.
|
|
133
|
+
- **group / dm** = a *channel inside* an instance — the place messages actually
|
|
134
|
+
arrive. A single bot (instance) can sit in many groups at once.
|
|
135
|
+
- **binding is per channel, not per instance.** That is the whole point:
|
|
136
|
+
*one bot can serve five groups, each answered by a different agent.*
|
|
137
|
+
- Therefore the many-to-many is **agent ↔ channel**: one agent serves many
|
|
138
|
+
channels; one instance fans out to many agents by channel. Binding an *instance*
|
|
139
|
+
to an agent is just shorthand for "all its channels default to this agent".
|
|
140
|
+
|
|
141
|
+
### 4.2 `BotInstance` — the registry concept
|
|
142
|
+
|
|
143
|
+
The tables express the model; the registry puts the concept **into the running
|
|
144
|
+
system**, so "one platform may host many bots" is true of the **connections**, not
|
|
145
|
+
just of the rows.
|
|
146
|
+
|
|
147
|
+
**The type** (`packages/comms/src/platforms/instance.ts`):
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
interface BotInstance {
|
|
151
|
+
id: string; // stable, unique per bot (bi_…; the implicit
|
|
152
|
+
// legacy bot uses the platform id — see below)
|
|
153
|
+
platform: string; // manifest id
|
|
154
|
+
label: string; // human label, unique per (org, platform, label)
|
|
155
|
+
config: Record<string, unknown>; // resolved credentials + platform fields
|
|
156
|
+
capabilities: PlatformCapabilities; // from the manifest, optionally narrowed
|
|
157
|
+
enabled: boolean; // whether startup should connect it
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`platform` is the **manifest** (declarative: fields, capabilities, adapter
|
|
162
|
+
factory). An **instance** is one *configuration* of that manifest with
|
|
163
|
+
credentials. Adding a platform = one manifest; adding a bot = one instance row.
|
|
164
|
+
**Neither touches the router** — the router is generic over instances.
|
|
165
|
+
|
|
166
|
+
**Identity.** A bot connection is keyed by `instanceId`, never by platform.
|
|
167
|
+
`MessageRouter.registerAdapter(adapter, instanceId?)` defaults `instanceId` to
|
|
168
|
+
`adapter.platform`, which is byte-for-byte the "one implicit bot per platform"
|
|
169
|
+
behaviour of every build before bot instances existed; a real instance row registers
|
|
170
|
+
under its own `id` (`bi_…`). Two rows of the same platform therefore occupy two distinct slots
|
|
171
|
+
and connect on two distinct credential sets — keying adapters by instance instead
|
|
172
|
+
of by platform is what makes "2 Telegram bots at once" *structurally* possible
|
|
173
|
+
rather than a silent overwrite.
|
|
174
|
+
|
|
175
|
+
**Startup traversal** (`connectConfiguredPlatforms`) is dual-read, matching §5.2
|
|
176
|
+
step 4:
|
|
177
|
+
|
|
178
|
+
1. for each manifest, take its `platform_instances` rows **when any exist** — one
|
|
179
|
+
adapter per row, connected with that row's config; a row switched off
|
|
180
|
+
(`enabled = false`) or whose required fields do not resolve is skipped;
|
|
181
|
+
2. a platform with **no** instance row falls back to the legacy path (the
|
|
182
|
+
`integrations` row + `markus.json` + env) and registers a single implicit
|
|
183
|
+
instance whose id **is** the platform id — the legacy behaviour, so a migrated
|
|
184
|
+
install and an unmigrated one connect identically.
|
|
185
|
+
|
|
186
|
+
`PlatformStartupResult.id` is therefore the instance id: the platform id for the
|
|
187
|
+
implicit legacy bot, the `platform_instances.id` for a real row. Callers that need
|
|
188
|
+
the platform read `label` (the manifest name, disambiguated by the instance label)
|
|
189
|
+
— outbound routing is a separate concern (§7).
|
|
190
|
+
|
|
191
|
+
**Instances own connection.** Which agent answers an inbound message (instance /
|
|
192
|
+
channel scope, nearest-wins) and which session it lands in are §6's responsibility —
|
|
193
|
+
this layer only decides *which credentials connect*.
|
|
194
|
+
|
|
195
|
+
### 4.3 Startup: consuming the registry
|
|
196
|
+
|
|
197
|
+
`markus start` walks `PLATFORM_MANIFESTS` × the persisted instances of each
|
|
198
|
+
platform, and for every enabled bot does **factory → register → connect**
|
|
199
|
+
(`connectConfiguredPlatforms()` in `packages/cli/src/commands/start.ts`). The
|
|
200
|
+
hand-written `if (feishuAppId && feishuAppSecret)` block is gone and `start.ts` no
|
|
201
|
+
longer imports `FeishuAdapter` at all.
|
|
202
|
+
|
|
203
|
+
The invariant this buys:
|
|
204
|
+
|
|
205
|
+
> **Adding a platform must not require editing `start.ts`.**
|
|
206
|
+
|
|
207
|
+
`packages/cli/test/commands-start-platforms.test.ts` pins it end to end: it
|
|
208
|
+
registers an extra manifest the source code has never heard of and asserts that its
|
|
209
|
+
adapter connected.
|
|
210
|
+
|
|
211
|
+
**Config resolution is a merge, and the merge is load-bearing.** Per platform id,
|
|
212
|
+
fields resolve first-hit-wins from three sources:
|
|
213
|
+
|
|
214
|
+
| Source | Example | Notes |
|
|
215
|
+
|---|---|---|
|
|
216
|
+
| Stored row | `integrations.feishu.appId` | Keyed by `manifest.id`; written only by `savePlatform` (§5.4). |
|
|
217
|
+
| Config file | `markus.json` → `integrations.<id>` | Read-only bootstrap default (§5.4). |
|
|
218
|
+
| Environment | `FEISHU_APP_ID` | Derived generically as `<PLATFORM_ID>_<SNAKE_CASE_FIELD_KEY>` — the same variables the old hand-written block read, but for *every* field of *every* platform, with no per-platform table. |
|
|
219
|
+
|
|
220
|
+
Precedence is **row > file > env**, and it is not a convenience: on a real install
|
|
221
|
+
the Feishu row holds only `{connectionMode, notifyOnApproval, …}` while
|
|
222
|
+
`appId`/`appSecret` still live in `markus.json`, so an instance row is a *partial*
|
|
223
|
+
config. Any later code that treats a row as self-sufficient (an "is this instance
|
|
224
|
+
usable?" check, for instance) must re-apply this merge.
|
|
225
|
+
|
|
226
|
+
**Enablement is decided from configuration only**, never from reachability:
|
|
227
|
+
`defaultEnabled: true` platforms are always attempted; otherwise every field marked
|
|
228
|
+
`required` must have resolved to a non-empty value. A platform that declares no
|
|
229
|
+
required field stays off until something is supplied — it is never silently switched
|
|
230
|
+
on. Values are coerced by the declared field type; empty strings count as "not
|
|
231
|
+
configured"; `select` fields are stored comma-joined.
|
|
232
|
+
|
|
233
|
+
**Two things are deliberately *not* taken from the manifest at runtime:**
|
|
234
|
+
|
|
235
|
+
- `field.default` — the type contract defines it as "the value the form starts from
|
|
236
|
+
when nothing is stored yet", i.e. a *form* concern. Runtime defaults belong to the
|
|
237
|
+
adapter (`FeishuClient` falls back to `https://open.feishu.cn`). Keeping the roles
|
|
238
|
+
separate means a form default can never silently change connect-time behaviour —
|
|
239
|
+
precisely the trap §6.5 describes, where `wsMode` defaulting to `false` silently
|
|
240
|
+
selected webhook mode on a desktop install that has no public URL.
|
|
241
|
+
- Anything beyond the declared type coercion — adapters own their own parsing.
|
|
242
|
+
|
|
243
|
+
**Failure semantics.** One platform failing to connect never blocks startup: it is
|
|
244
|
+
caught, logged at `WARN` and skipped, and the others still connect. Enablement came
|
|
245
|
+
from configuration, so a *misconfigured* platform is still attempted — and now
|
|
246
|
+
reported as failed. That last part is a fix, not a restatement: the old code printed
|
|
247
|
+
`OK` even when Feishu had failed, because `MessageRouter.connectAll()` swallows
|
|
248
|
+
connect errors internally and the surrounding `try/catch` therefore never fired. The
|
|
249
|
+
outcome now comes from the adapter's authoritative `isConnected()`, and the progress
|
|
250
|
+
text is generated from the adapters that actually connected.
|
|
251
|
+
|
|
252
|
+
## 5. Data model & migration
|
|
253
|
+
|
|
254
|
+
Replace the `(org, platform)`-keyed `integrations` row with two tables:
|
|
255
|
+
|
|
256
|
+
```sql
|
|
257
|
+
platform_instances(
|
|
258
|
+
id TEXT PRIMARY KEY, -- bi_…
|
|
259
|
+
org_id TEXT NOT NULL,
|
|
260
|
+
platform TEXT NOT NULL, -- 'telegram' | 'feishu' | …
|
|
261
|
+
label TEXT NOT NULL,
|
|
262
|
+
config TEXT, -- JSON: credentials + platform fields
|
|
263
|
+
capabilities TEXT, -- JSON: resolved from manifest, may be narrowed
|
|
264
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
265
|
+
last_verified_at TEXT, last_error TEXT,
|
|
266
|
+
UNIQUE(org_id, platform, label)
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
channel_bindings(
|
|
270
|
+
id TEXT PRIMARY KEY,
|
|
271
|
+
org_id TEXT NOT NULL,
|
|
272
|
+
scope TEXT NOT NULL, -- 'global' | 'platform' | 'instance' | 'channel'
|
|
273
|
+
instance_id TEXT, -- NULL for global/platform scope
|
|
274
|
+
native_id TEXT, -- NULL unless scope='channel'
|
|
275
|
+
kind TEXT, -- NULL unless scope='channel'
|
|
276
|
+
agent_id TEXT NOT NULL,
|
|
277
|
+
created_at TEXT NOT NULL,
|
|
278
|
+
UNIQUE(org_id, scope, instance_id, native_id)
|
|
279
|
+
)
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### 5.1 Backward compatibility (hard requirement)
|
|
283
|
+
|
|
284
|
+
We already have many existing installs. The migration therefore MUST be:
|
|
285
|
+
|
|
286
|
+
- **Additive.** New tables are *added*; the existing `integrations` table is **not**
|
|
287
|
+
altered or dropped in this release. An older binary reading the same DB keeps
|
|
288
|
+
working (forward-compatible file, not a breaking rewrite).
|
|
289
|
+
- **Idempotent.** Runs on every startup; re-running is a no-op (`INSERT … WHERE NOT
|
|
290
|
+
EXISTS` / `INSERT OR IGNORE`), never duplicates rows, never overwrites user edits.
|
|
291
|
+
- **Non-destructive.** Nothing is deleted. `config` blobs (credentials) are copied
|
|
292
|
+
verbatim — **never re-serialised** through a lossy path — so a user's existing
|
|
293
|
+
Feishu app secretly keeps working after the upgrade.
|
|
294
|
+
- **Fail-safe.** If migration throws, the app still starts and the **old read path
|
|
295
|
+
still serves**; new features degrade to "unavailable", never to "data lost".
|
|
296
|
+
- **Reversible.** The migration is a pure addition; rollback = ignore the new tables
|
|
297
|
+
(one release of dual-read keeps both worlds valid).
|
|
298
|
+
|
|
299
|
+
### 5.2 Migration steps (one-shot, run at startup)
|
|
300
|
+
|
|
301
|
+
1. For every existing `integrations` row, `INSERT OR IGNORE` one `platform_instances`
|
|
302
|
+
row with `label = 'default'`, `config` copied **byte-for-byte**.
|
|
303
|
+
2. If that row had a non-empty `agentId`, insert an `instance`-scope binding for it.
|
|
304
|
+
3. If no binding exists at all afterwards, insert the **global default → Secretary**.
|
|
305
|
+
4. **Dual-read window:** readers prefer the new tables; if a platform has no
|
|
306
|
+
`platform_instances` row yet (migration not run, or a row the user just added),
|
|
307
|
+
fall back to the legacy `integrations` row. Writers go to the new tables only.
|
|
308
|
+
5. Old table is retained read-only for one release, then dropped in a *later*
|
|
309
|
+
migration (not this one).
|
|
310
|
+
|
|
311
|
+
`markus.json` stays a **read-only bootstrap** (unchanged policy); the DB is the
|
|
312
|
+
single writer.
|
|
313
|
+
|
|
314
|
+
**Verification is on real data, not fixtures:** before/after screenshots of a copy of
|
|
315
|
+
an actual pre-upgrade DB (a user with Feishu configured), asserting the instance row,
|
|
316
|
+
credential blob and binding all survive and the old read path is unaffected.
|
|
317
|
+
|
|
318
|
+
### 5.3 Implementation contract
|
|
319
|
+
|
|
320
|
+
**Schema (created on every open, additive).** Both tables are created with
|
|
321
|
+
`CREATE TABLE IF NOT EXISTS` inside the existing `SCHEMA_SQL`, so they appear on
|
|
322
|
+
fresh installs and on upgrade without altering any existing table. Physical
|
|
323
|
+
columns match §5, plus `created_at` / `updated_at` for parity with every other
|
|
324
|
+
table:
|
|
325
|
+
|
|
326
|
+
- `platform_instances` — `UNIQUE(org_id, platform, label)`. `label` is
|
|
327
|
+
`NOT NULL`, so the unique index is total (no `NULL`-distinctness hole) and
|
|
328
|
+
`INSERT OR IGNORE` is a real de-duplicator.
|
|
329
|
+
- `channel_bindings` — `UNIQUE(org_id, scope, instance_id, native_id)`. SQLite
|
|
330
|
+
treats `NULL` as **distinct** in a unique index, so this index alone does **not**
|
|
331
|
+
de-duplicate `global` / `platform` bindings (whose `instance_id` and `native_id`
|
|
332
|
+
are `NULL`). The migration therefore also guards those inserts with an explicit
|
|
333
|
+
`WHERE NOT EXISTS`, and no caller may rely on the index to enforce "one global
|
|
334
|
+
binding per org".
|
|
335
|
+
|
|
336
|
+
**One-shot migration** (`migrateMessagingGateway(db)`), invoked from `openSqlite`
|
|
337
|
+
behind `PRAGMA user_version`:
|
|
338
|
+
|
|
339
|
+
1. Every `integrations` row → `INSERT OR IGNORE` a `platform_instances` row with
|
|
340
|
+
`label = 'default'`. The `config` column is copied **byte-for-byte from the raw
|
|
341
|
+
SQL string** — it is never `JSON.parse`d and re-`stringify`d, so a user's
|
|
342
|
+
credential blob survives unchanged. The id is deterministic
|
|
343
|
+
(`bi_<org>_<platform>_<label>`), so a re-run is a no-op rather than a new row.
|
|
344
|
+
2. The row's `config.agentId` (parsed read-only, never re-serialised) → an
|
|
345
|
+
`instance`-scope binding `(org, 'instance', instance_id, NULL, NULL, agentId)`.
|
|
346
|
+
3. If an org ends up with **no** binding at all, insert `global → Secretary`
|
|
347
|
+
(resolved through the shared Secretary predicate below). Scoped to orgs that had
|
|
348
|
+
at least one `integrations` row — the migration is about upgrading existing
|
|
349
|
+
installs, not about inventing configuration for untouched ones.
|
|
350
|
+
4. `PRAGMA user_version` is bumped to `3` **only after** the migration succeeds.
|
|
351
|
+
|
|
352
|
+
**Fail-safe.** The whole call is wrapped in `try/catch`; a throw is logged and
|
|
353
|
+
`openSqlite` continues, so the app still starts and the legacy read path keeps
|
|
354
|
+
serving (`user_version` is *not* advanced, so the migration retries next start).
|
|
355
|
+
Every step is independently idempotent, so a retry after a partial failure cannot
|
|
356
|
+
duplicate or corrupt rows.
|
|
357
|
+
|
|
358
|
+
**Dual-read window.** Readers prefer the new tables and fall back to the legacy
|
|
359
|
+
`integrations` row when a platform has no `platform_instances` row yet; writers
|
|
360
|
+
target the new tables only. The storage layer ships the primitive for this
|
|
361
|
+
(`resolveInstanceConfig`), and the consumers resolve through it (§4.3, §6.1).
|
|
362
|
+
|
|
363
|
+
**Single source of truth for "who is the Secretary".** The predicate and the
|
|
364
|
+
preference order that the notification default depends on now live in
|
|
365
|
+
`@markus/shared` (`isSecretaryLikeAgent` / `pickOrgSecretary`); `OrgService` calls
|
|
366
|
+
the same functions. The migration uses them too, so "which agent is the Secretary"
|
|
367
|
+
has exactly one implementation.
|
|
368
|
+
|
|
369
|
+
### 5.4 Credentials: one writer, one reader, never echoed
|
|
370
|
+
|
|
371
|
+
Credentials had **two writers** — the Feishu QR `register` extension wrote
|
|
372
|
+
`markus.json`, while runtime preferences went to the SQLite `integrations` row — and
|
|
373
|
+
the notifier bootstrap read `markus.json` directly with a hard-coded
|
|
374
|
+
`orgId: 'default'`. The row is now both the writer and the reader:
|
|
375
|
+
|
|
376
|
+
- **One writer.** `savePlatform` writes the row; the QR `register` extension merges
|
|
377
|
+
`appId`/`appSecret` into it instead of calling `saveConfig(...)`. `markus.json` is
|
|
378
|
+
demoted to a **read-only bootstrap default** — never written.
|
|
379
|
+
- **One reader.** Every consumer resolves through `resolvePlatformConfig(orgId, id)`
|
|
380
|
+
(row → bootstrap) and takes the org id from storage rather than a literal.
|
|
381
|
+
- **No `GET` returns a secret.** The invariant is asserted across the whole surface
|
|
382
|
+
(`/api/settings/integrations*`), not just the generic endpoint: for every GET the
|
|
383
|
+
response body must not contain a configured secret's plaintext. The test uses a
|
|
384
|
+
**canary** secret value, so re-introducing a leak fails loudly.
|
|
385
|
+
- **Masked values do not clear data.** A client that re-submits the masked
|
|
386
|
+
placeholder leaves the stored secret untouched.
|
|
387
|
+
|
|
388
|
+
## 6. Routing & session isolation
|
|
389
|
+
|
|
390
|
+
### 6.1 One resolution point
|
|
391
|
+
|
|
392
|
+
```ts
|
|
393
|
+
resolveInboundTarget(message): { instanceId, agentId, conversationKey, matchedScope }
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
Order — **nearest wins**, and the matched scope is recorded (observability, not
|
|
397
|
+
guesswork):
|
|
398
|
+
|
|
399
|
+
1. explicit `agentId` on the message (Web UI sets it)
|
|
400
|
+
2. `channel` scope — `(instanceId, nativeId)`
|
|
401
|
+
3. `instance` scope — the bot's default agent
|
|
402
|
+
4. `platform` scope
|
|
403
|
+
5. `global` scope — **the default binding (Secretary)**
|
|
404
|
+
|
|
405
|
+
Because step 5 always resolves, the router **never silently drops** (fixes D6): an
|
|
406
|
+
unbound platform falls through to the Secretary and logs the level that matched.
|
|
407
|
+
|
|
408
|
+
### 6.2 Session isolation
|
|
409
|
+
|
|
410
|
+
Each `(instanceId, nativeId, kind)` maps to a **stable canonical conversation key**.
|
|
411
|
+
The gateway is the only place that decides a conversation's identity, and it passes
|
|
412
|
+
it to the agent as an explicit session hint — the same contract the Web UI already
|
|
413
|
+
uses (`channelKey` / `sessionHint` in `core/src/agent.ts`).
|
|
414
|
+
|
|
415
|
+
Policy (default):
|
|
416
|
+
|
|
417
|
+
| `kind` | Meaning | Session mapping | Why |
|
|
418
|
+
|---|---|---|---|
|
|
419
|
+
| `main` | the channel *designated* as the agent's home | the agent's **main session** | continuity — the owner's DM with a bot *is* that agent's home conversation |
|
|
420
|
+
| `dm` | a 1:1 chat with an external user | **own session per external user** | two different people must not share one context |
|
|
421
|
+
| `group` | a group chat | **own session per group** | see below |
|
|
422
|
+
| `notification` | out-only sink | none (inbound ignored) | a notification is a destination, not a conversation |
|
|
423
|
+
|
|
424
|
+
**Why a group is its own session** — three reasons, in order of severity:
|
|
425
|
+
|
|
426
|
+
1. **Access isolation.** Group A and group B have different members. Sharing one
|
|
427
|
+
session means the agent can answer a question in B using content it only saw in
|
|
428
|
+
A. That is a data leak dressed up as "context".
|
|
429
|
+
2. **Correctness.** Two unrelated conversations interleaved in one context make the
|
|
430
|
+
agent confuse participants, decisions and topics.
|
|
431
|
+
3. **Cost.** A shared session grows without bound; N groups × M messages is N×M of
|
|
432
|
+
context, all paid for on every turn.
|
|
433
|
+
|
|
434
|
+
`main` is a **designation**, not a native platform type: at most one channel per
|
|
435
|
+
instance is marked as the agent's home. Everything else isolates by default. A group
|
|
436
|
+
may be *re-pointed* to `main` (opt-in) for users who explicitly want one continuous
|
|
437
|
+
context — but the default is isolation, because the default must be safe.
|
|
438
|
+
|
|
439
|
+
The old Feishu live path (`handleFeishuUserMessage`) and its
|
|
440
|
+
`getOrCreateMainSession` call are **deleted** — one inbound path, one session
|
|
441
|
+
decision (fixes D3, D4).
|
|
442
|
+
|
|
443
|
+
### 6.3 Implementation contract
|
|
444
|
+
|
|
445
|
+
> §6.1/§6.2 are one executable decision point rather than prose. It does **not**
|
|
446
|
+
delete the legacy Feishu path (§6.5); it makes the router path a single resolver
|
|
447
|
+
plus real session isolation, so nothing else has to decide routing again.
|
|
448
|
+
|
|
449
|
+
**One resolution point.** `resolveInboundTarget(envelope, lookup)` is a pure
|
|
450
|
+
function returning `{ instanceId, agentId, conversationKey, matchedScope, kind }`
|
|
451
|
+
or `undefined` when **nothing at all** is bound. Levels, nearest wins, with the
|
|
452
|
+
winning level recorded for observability:
|
|
453
|
+
|
|
454
|
+
| # | `matchedScope` | Source |
|
|
455
|
+
|---|---|---|
|
|
456
|
+
| 1 | `explicit` | `agentId` carried by the message (Web UI sets it) |
|
|
457
|
+
| 2 | `channel` | `channel_bindings` row `(scope='channel', instance_id, native_id)` |
|
|
458
|
+
| 3 | `instance` | `channel_bindings` row `(scope='instance', instance_id)` |
|
|
459
|
+
| 4 | `platform` | the binding on the platform's **`label='default'` instance** |
|
|
460
|
+
| 5 | `global` | `channel_bindings` row `scope='global'` (else the live Secretary) |
|
|
461
|
+
|
|
462
|
+
**`platform` needs no new column.** The design (§4/§5/§6.1) lists `platform` as a
|
|
463
|
+
scope, but a `platform`-scope row (`instance_id` and `native_id` both `NULL`)
|
|
464
|
+
cannot express *which* platform it applies to, and nothing in the product writes
|
|
465
|
+
one (the UI binds instances / channels / the global target — never a platform).
|
|
466
|
+
Rather than add a column no writer fills, level 4 is **realised as the platform's
|
|
467
|
+
default instance binding** — precisely the row the migration produces out of the
|
|
468
|
+
legacy platform-level `agentId` (`label='default'`). So "the whole platform
|
|
469
|
+
defaults to agent X" is expressed the way the migration already expresses it, and
|
|
470
|
+
the scope stays a single source of truth (no dual storage, no in-band platform
|
|
471
|
+
name). Level 4 fires when a message has no instance-specific binding — including
|
|
472
|
+
messages from adapters that never set `instanceId` (the legacy shape), which is
|
|
473
|
+
exactly when a platform-wide default should apply.
|
|
474
|
+
|
|
475
|
+
**Never silently drop (fixes D6).** Level 5 is terminal in practice: the `global`
|
|
476
|
+
row is seeded to the Secretary by the migration, and the DB-backed lookup falls
|
|
477
|
+
back to the live Secretary (shared `pickOrgSecretary` predicate) when no `global`
|
|
478
|
+
row exists. The only "drop" left is an org with **no** Secretary and **no**
|
|
479
|
+
binding — which is logged loudly with an actionable hint, never silently.
|
|
480
|
+
|
|
481
|
+
**Session isolation (fixes D3).** `conversationKeyOf({instanceId, nativeId, kind})`
|
|
482
|
+
is a pure, collision-free canonical key (`im:<instanceId>:<kind>:<uri(nativeId)>`,
|
|
483
|
+
parts percent-encoded so `:` can never be ambiguous). It is handed to the agent as
|
|
484
|
+
the existing **`channelKey`** contract (`core/src/agent.ts` maps it to the memory
|
|
485
|
+
session `channel_<key>_<agentId>`), so dm/group isolation reuses machinery that
|
|
486
|
+
already works for Web UI group chats:
|
|
487
|
+
|
|
488
|
+
| `kind` | Session |
|
|
489
|
+
|---|---|
|
|
490
|
+
| `main` | the bound agent's own main session (`MAIN_CONVERSATION_KEY`, no per-channel key) |
|
|
491
|
+
| `dm` | own session per native conversation (per external user) |
|
|
492
|
+
| `group` | own session per native conversation (per group) |
|
|
493
|
+
| `notification` | **inbound ignored** (a destination, not a conversation) |
|
|
494
|
+
|
|
495
|
+
A `channel`-scope binding whose own `kind='main'` *designates* that channel as the
|
|
496
|
+
agent's home (design §6.2) — the resolver then returns `MAIN_CONVERSATION_KEY` so
|
|
497
|
+
continuity with the agent's main session is opt-in, and isolation stays the default.
|
|
498
|
+
|
|
499
|
+
**`sendAsAgent` stops dropping `agentId` (fixes D7).** The agent identity is
|
|
500
|
+
forwarded to the adapter's send (`SendOptions.agentId`) instead of being discarded.
|
|
501
|
+
|
|
502
|
+
**Single path, bootstrap fallback.** The router resolves through this one function.
|
|
503
|
+
Its binding source is a lookup port; production injects a DB-backed one (the single
|
|
504
|
+
writer) and the in-memory maps populated from `markus.json` remain a read-only
|
|
505
|
+
**bootstrap** fallback (§5.2), consulted only when the DB has no answer. No inbound
|
|
506
|
+
message is ever routed by a second, independent decision.
|
|
507
|
+
|
|
508
|
+
### 6.4 Acknowledgement deadlines
|
|
509
|
+
|
|
510
|
+
Some platforms demand an ACK inside a hard window (Discord 3 s; Feishu card
|
|
511
|
+
callbacks 3 s; Slack Socket Mode 3 s). The gateway normalises this: the inbound
|
|
512
|
+
transport mints an `AckHandle` for the event, **acks it before the agent turn
|
|
513
|
+
starts**, and hands the `Message` to the handler without awaiting it. The real
|
|
514
|
+
reply is delivered out-of-band (today through the adapter, by the
|
|
515
|
+
`OutboundDispatcher`). The platform's read loop therefore never
|
|
516
|
+
blocks on an agent turn.
|
|
517
|
+
|
|
518
|
+
Implemented in `packages/comms/src/gateway/ack.ts`:
|
|
519
|
+
|
|
520
|
+
```ts
|
|
521
|
+
interface AckHandle { ack(): void; readonly acked: boolean; }
|
|
522
|
+
createAck(send: () => void): AckHandle // idempotent — a second call is a no-op
|
|
523
|
+
createDeadlineAck(deadlineMs, send): AckHandle // auto-acks if nobody did in time
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
Idempotence matters: a transport that acks on receipt *and* arms a deadline would
|
|
527
|
+
otherwise send the ACK twice, which several platforms treat as an error. The
|
|
528
|
+
Slack Socket Mode transport proves the invariant end-to-end (exactly one
|
|
529
|
+
`{envelope_id}` per envelope, even when the handler is slow).
|
|
530
|
+
|
|
531
|
+
### 6.5 Retiring the legacy Feishu path
|
|
532
|
+
|
|
533
|
+
**The defect.** Two independent Feishu inbound receivers ran in the same
|
|
534
|
+
process: the comms `FeishuAdapter` (the gateway path) and `FeishuNotifier` — an
|
|
535
|
+
org-manager class that opened its **own** long connection with the official
|
|
536
|
+
`@larksuiteoapi/node-sdk` `WSClient` and re-implemented routing, session choice,
|
|
537
|
+
card streaming and notification fan-out. A live Feishu message could therefore be
|
|
538
|
+
handled twice, and its session/agent decision was made by whichever receiver
|
|
539
|
+
fired — two writers for one fact.
|
|
540
|
+
|
|
541
|
+
**Why the notifier was the one that actually worked.** The adapter's `wsMode`
|
|
542
|
+
branch spoke a *fictional* protocol (`POST /open-apis/ws/v1/apps/{id}/subscribe`
|
|
543
|
+
plus a JSON `{type:'heartbeat'}`); Feishu's real long connection is the SDK's
|
|
544
|
+
framed `WSClient`. And the manifest `wsMode` field defaults to `false` (manifest
|
|
545
|
+
`field.default` is a *form* default and is deliberately never applied to adapter
|
|
546
|
+
config), so a real install resolved `wsMode` falsy and the adapter came up in
|
|
547
|
+
**webhook** mode — which needs a public URL that a desktop install does not have.
|
|
548
|
+
So the only functional receiver was the notifier. Deleting it without first giving
|
|
549
|
+
the adapter a real receiver would have *broken* Feishu inbound, not merged it.
|
|
550
|
+
|
|
551
|
+
**The fix — one receiver, owned by the adapter.** The long connection belongs to
|
|
552
|
+
the platform-integration layer, so the official `Lark.WSClient` + `EventDispatcher`
|
|
553
|
+
move **into `FeishuAdapter`**:
|
|
554
|
+
|
|
555
|
+
- `connect()` uses the long connection **by default** (this is the adapter's own
|
|
556
|
+
runtime default, per §3 — the manifest default is not overridden, it is simply
|
|
557
|
+
not consulted). `wsMode === false` opts into the webhook server for
|
|
558
|
+
deployments that do have a public URL.
|
|
559
|
+
- `im.message.receive_v1` → `Message` → the adapter's registered handlers (the
|
|
560
|
+
router, §6.1). `card.action.trigger` → the adapter's **action port** (below).
|
|
561
|
+
- The adapter now reports `instanceId` and `channelKind` (`dm` for `p2p`, else
|
|
562
|
+
`group`) on every inbound message, so §6.2's isolation is driven by real data
|
|
563
|
+
instead of the legacy shape.
|
|
564
|
+
- `@larksuiteoapi/node-sdk` is a dependency of `packages/comms`.
|
|
565
|
+
|
|
566
|
+
**Card actions are not a conversation.** An approval button tap is a HITL state
|
|
567
|
+
transition, not an agent turn, so it must not be fed to the agent handler. The
|
|
568
|
+
`CommAdapter` contract gains an optional **action port** (`onAction`), the router
|
|
569
|
+
wires it to a single injected `actionHandler`, and the wiring layer (`cli`)
|
|
570
|
+
resolves it — verifying the signed action ref (§7.4) when present, otherwise the
|
|
571
|
+
raw `approval_id`, then calling `hitlService.respondToApproval`. One inbound
|
|
572
|
+
funnel, but two *kinds* of inbound (message vs action) with an explicit decision
|
|
573
|
+
point each.
|
|
574
|
+
|
|
575
|
+
**A tap must leave visible evidence, so the card is rewritten in place.** An
|
|
576
|
+
interactive card is a one-shot message — the platform never edits it for us — so a
|
|
577
|
+
tap that only records the decision leaves the tapper staring at a card that looks
|
|
578
|
+
untouched (the "clicked approve and nothing happened" defect). After the decision
|
|
579
|
+
is recorded, the wiring layer calls `router.updateResolvedCard(platform,
|
|
580
|
+
instanceId, messageId, resolution)`: the adapter re-renders the same card with its
|
|
581
|
+
action row replaced by a status line (`✅ 已批准` / `❌ 已驳回`, actor, time) and the
|
|
582
|
+
header recoloured by outcome. The message id comes from the action itself
|
|
583
|
+
(Feishu `context.open_message_id`, carried on `InboundAction.messageId`), and the
|
|
584
|
+
title/body are re-read from the approval record — never scraped back out of the
|
|
585
|
+
card. Two contract rules make this safe: the capability is **optional** on
|
|
586
|
+
`CommAdapter` (a platform that cannot edit messages simply omits it, and
|
|
587
|
+
`updateResolvedCard` returns `false` rather than throwing), and it is
|
|
588
|
+
**best-effort** (a failed rewrite is logged, never rolls back a decision that is
|
|
589
|
+
already recorded).
|
|
590
|
+
|
|
591
|
+
**What is deleted.** `packages/org-manager/src/feishu-notifier.ts` in full; the
|
|
592
|
+
`handleFeishuUserMessage` method and its `getOrCreateMainSession` call (the
|
|
593
|
+
session choice is now the resolver's, §6.1); the notifier's outbound duties (the
|
|
594
|
+
`OutboundDispatcher` owns them, §7); the api-server init/stop/config-sync wiring;
|
|
595
|
+
and now-dead `startWSClient`/`stopWSClient` on `FeishuApiClient`.
|
|
596
|
+
|
|
597
|
+
**Honest residual.** The notifier's **rich agent-response card streaming**
|
|
598
|
+
(thinking → tool calls → done, patched into one Feishu card) has no equivalent in
|
|
599
|
+
the gateway: the request/reply path returns text. That is a *platform capability*
|
|
600
|
+
(card streaming), not routing, and belongs with a future capability slice — it is
|
|
601
|
+
recorded as a known limitation rather than silently dropped.
|
|
602
|
+
|
|
603
|
+
### 6.6 The channel → agent binding is one source
|
|
604
|
+
|
|
605
|
+
**The defect.** `MessageRouter.bindAgentToChannel()` had **zero callers**
|
|
606
|
+
repo-wide, so `agentChannelMap` was permanently empty and "multi-platform binding"
|
|
607
|
+
did not exist. It was worse than merely unused: there were **two independent Feishu
|
|
608
|
+
inbound paths**, and the live one consulted no binding at all.
|
|
609
|
+
|
|
610
|
+
| Path | Entry | Target | State before this work |
|
|
611
|
+
|---|---|---|---|
|
|
612
|
+
| A. gateway | `FeishuAdapter` → router | `agentChannelMap` lookup → empty → **dropped at `log.debug`** | dead unless a webhook was configured |
|
|
613
|
+
| B. legacy notifier | its own Lark `WSClient` → api-server | **hard-coded org Secretary** | live for QR-registered apps |
|
|
614
|
+
|
|
615
|
+
The consequence shaped the fix: populating the map alone would have had **no
|
|
616
|
+
observable effect** on the live path, and adding a lookup to the live path required
|
|
617
|
+
knowing that the live path was B. The root cause was never the empty map — it was
|
|
618
|
+
that **the channel→agent decision had no single source**.
|
|
619
|
+
|
|
620
|
+
**Resolution order, first hit wins**, now read by every inbound path:
|
|
621
|
+
|
|
622
|
+
1. `message.agentId` — set by the adapter (Web UI sets it explicitly; unchanged).
|
|
623
|
+
2. an explicit **channel** binding (`bindAgentToChannel`).
|
|
624
|
+
3. the **instance** binding.
|
|
625
|
+
4. the **platform** binding (`bindPlatformAgent`) — defined as *the platform's
|
|
626
|
+
`label='default'` instance binding*. `channel_bindings` has no `platform` column,
|
|
627
|
+
so no writer could create such a row; this avoids inventing a row shape nothing
|
|
628
|
+
can write. A true per-platform row needs the column **and** a writer first.
|
|
629
|
+
5. the org **Secretary** — so an unbound inbound is never dropped.
|
|
630
|
+
|
|
631
|
+
**Unbound inbound is loud.** `routeIncomingMessage` logs at `warn` with the
|
|
632
|
+
platform, the channel and an actionable hint (which config field or method to set)
|
|
633
|
+
instead of the previous `debug` "…skipping message".
|
|
634
|
+
|
|
635
|
+
**Binding semantics later work must not silently change:**
|
|
636
|
+
|
|
637
|
+
- A `channel`-scope binding with `kind = 'main'` designates the agent's home
|
|
638
|
+
conversation; `kind = 'notification'` makes inbound on that channel ignored.
|
|
639
|
+
- The binding is **authoritative over the adapter's `channelKind`**.
|
|
640
|
+
- One binding source, two writers, applied at startup by
|
|
641
|
+
`applyPersistedPlatformBindings` — and no platform name appears anywhere in the
|
|
642
|
+
loader.
|
|
643
|
+
|
|
644
|
+
## 7. Outbound & notifications
|
|
645
|
+
|
|
646
|
+
### 7.1 The failure mode we must avoid
|
|
647
|
+
|
|
648
|
+
A notification route must **not** depend on the producing agent being bound to an
|
|
649
|
+
external channel. A user will bind a handful of important agents — never all of
|
|
650
|
+
them — so any design that delivers "to the agent's bound channel" **leaks every
|
|
651
|
+
unbound agent's notifications**. Guaranteed delivery is the requirement; smart
|
|
652
|
+
routing is an optimisation layered on top of it.
|
|
653
|
+
|
|
654
|
+
**Prior art, as a negative example: Multica** (`multica-ai/multica`, same problem
|
|
655
|
+
space). Its notification layer is **inbox-only — there is no outbound channel at
|
|
656
|
+
all** (issue #1020). Humans must open the product to discover that a decision is
|
|
657
|
+
waiting, which is exactly the "missed notification" failure in its purest form.
|
|
658
|
+
Also worth noting: **agents have no inbox** in Multica; the inbox is per human
|
|
659
|
+
member. Two things are worth borrowing: its **severity split** (`info` vs
|
|
660
|
+
`action_required`) and its **subscription-based** recipient model (you are notified
|
|
661
|
+
about what you watch). Full notes: `research/multica-notifications.md`.
|
|
662
|
+
|
|
663
|
+
### 7.2 Unified outbound
|
|
664
|
+
|
|
665
|
+
```
|
|
666
|
+
hitlService.notify() ─┐
|
|
667
|
+
EventBus (task:*, …) ─┼─▶ OutboundDispatcher ─▶ resolve target(s) ─▶ render ─▶ send
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
- **`OutboundMessage`** — the only shape renderers consume: `{ title, body,
|
|
671
|
+
severity, actions[], attachments[], replyRef?, origin{agentId, taskId} }`.
|
|
672
|
+
- **Severity drives routing, not content**: `action_required` (approvals, input
|
|
673
|
+
requests, failures) is pushed immediately; `info` may be batched or digested.
|
|
674
|
+
- **Renderers** degrade by capability — an interactive card where supported (Feishu
|
|
675
|
+
interactive, Slack Block Kit, Discord components, Telegram inline keyboard),
|
|
676
|
+
Markdown where supported, plain text otherwise. **A platform without buttons shows
|
|
677
|
+
the same content as text** — a notification is never lost because a feature is
|
|
678
|
+
missing.
|
|
679
|
+
- **Approvals round-trip**: an action click carries a signed reference (mirroring
|
|
680
|
+
the existing card-action `approval_id`); the inbound side resolves it to the
|
|
681
|
+
pending approval, so the user never sees an internal id.
|
|
682
|
+
|
|
683
|
+
### 7.3 Notification routing — an ordered walk that ends loudly
|
|
684
|
+
|
|
685
|
+
A notification resolves its destination by walking the chain, **first hit wins**.
|
|
686
|
+
The full design (model, fidelity, preference enforcement, tests) is
|
|
687
|
+
`notification-delivery.md`; in brief:
|
|
688
|
+
|
|
689
|
+
1. **agent** — the producing agent's **own conversation**. An explicit
|
|
690
|
+
`kind = 'notification'` binding wins; otherwise the agent's own channel is used.
|
|
691
|
+
(The agent's channel *is* its notification target — routing and notification
|
|
692
|
+
cannot disagree, because they read the same row.)
|
|
693
|
+
2. **instance (declared)** — the instance's **declared destination**, read from
|
|
694
|
+
`platform_instances.config` through the manifest's `notifyTarget` annotation (a
|
|
695
|
+
group chat the bot was added to). Binding-independent, so it is the reliable
|
|
696
|
+
terminus even on a fresh install. `RepoNotifyTargetLookup.instanceTarget` is the
|
|
697
|
+
one reader.
|
|
698
|
+
3. **instance (fallback)** — the instance's `notifyAgentId` → that agent's own
|
|
699
|
+
conversation (best-effort).
|
|
700
|
+
4. **global** — the **Secretary's own conversation**, else any global-scope binding
|
|
701
|
+
with a native id.
|
|
702
|
+
5. **no terminus** — the dispatcher reports `{ delivered: false, reason:
|
|
703
|
+
'no-notify-target' }` (one log line, surfaced in Settings): a **visible**
|
|
704
|
+
undelivered state, never a silent drop.
|
|
705
|
+
|
|
706
|
+
Unlike the earlier three-level sketch, level "always exists" is **not** assumed. An
|
|
707
|
+
install with no destination and no addressable Secretary binding produces the loud
|
|
708
|
+
undelivered state above; the Settings notification panel is what configures level 2.
|
|
709
|
+
This satisfies the requirement — "everything goes through the Secretary channel by
|
|
710
|
+
default, but I can point a specific bot elsewhere" — **without** ever regressing
|
|
711
|
+
into "the agent wasn't bound, so the notification vanished".
|
|
712
|
+
|
|
713
|
+
> **Why level 1 accepts a non-marker binding.** The migration seeds routing
|
|
714
|
+
> bindings with `kind = NULL` — at migration time there is no way to know *which*
|
|
715
|
+
> conversation should receive notifications, so no row can honestly claim the
|
|
716
|
+
> marker. Requiring `kind = 'notification'` would therefore leave levels 1 and 4
|
|
717
|
+
> dead on **every migrated install**, i.e. notifications *would* be isolated — the
|
|
718
|
+
> exact defect this design removes. Preference order instead makes an explicit
|
|
719
|
+
> choice made in Settings supreme while guaranteeing a terminus.
|
|
720
|
+
|
|
721
|
+
Every forwarded message carries `origin{agentId, taskId}`, and the body is prefixed
|
|
722
|
+
with the producing agent's name at the single delivery point so that one busy
|
|
723
|
+
Secretary channel stays readable while aggregating the whole org.
|
|
724
|
+
|
|
725
|
+
Optional (later): per-severity targets (`action_required` → an urgent channel).
|
|
726
|
+
|
|
727
|
+
### 7.4 Implementation contract
|
|
728
|
+
|
|
729
|
+
The pieces, and the one job each has. Everything below is pure or a port, so the
|
|
730
|
+
whole outbound chain is unit-testable without a platform, a database or a timer.
|
|
731
|
+
|
|
732
|
+
```
|
|
733
|
+
packages/comms/src/gateway/
|
|
734
|
+
outbound.ts OutboundMessage — the only shape renderers consume, + signed action refs
|
|
735
|
+
notify-route.ts resolveNotifyTarget() — the three-level walk (agent → instance → global)
|
|
736
|
+
render.ts renderOutbound() — capability-driven degradation
|
|
737
|
+
dispatcher.ts OutboundDispatcher — HITL/EventBus in, resolve → render → send out
|
|
738
|
+
notify-lookup.ts RepoNotifyTargetLookup — the lookup port backed by channel_bindings
|
|
739
|
+
router-sink.ts RouterOutboundSink — the sink port backed by the adapter router
|
|
740
|
+
```
|
|
741
|
+
|
|
742
|
+
**`OutboundMessage`** is the single outbound shape. `severity ∈ {action_required,
|
|
743
|
+
info}` drives *routing and timing*, never content: `action_required` (approvals,
|
|
744
|
+
input requests, failures) is pushed immediately; `info` is delivered immediately
|
|
745
|
+
by default and may be **digested** (buffered and flushed as one summary) when the
|
|
746
|
+
deployment opts in. A digest never swallows an `action_required`: it is flushed
|
|
747
|
+
first, then the urgent message goes on its own.
|
|
748
|
+
|
|
749
|
+
**Three-level notify routing** (`resolveNotifyTarget(orgId, origin, lookup)`) walks
|
|
750
|
+
`agent → instance → global` and stops at the first hit, recording which level
|
|
751
|
+
matched. The lookup (`RepoNotifyTargetLookup`) supplies each level from
|
|
752
|
+
`platform_instances.config` (the instance's declared destination, then its
|
|
753
|
+
`notifyAgentId` fallback) and from `channel_bindings` (the agent's and the
|
|
754
|
+
global/Secretary rows). A notification can never be orphaned *by "the agent was not
|
|
755
|
+
bound"*. If no level yields an addressable terminus the dispatcher logs loudly and
|
|
756
|
+
reports `delivered: false` — it never pretends success. **Designed state, not a gap:**
|
|
757
|
+
a bot with no group destination and no addressable Secretary binding is simply
|
|
758
|
+
**unconfigured**; the Settings notification panel is what configures level 2, and the
|
|
759
|
+
undelivered state is the loud signal to do so (`notification-delivery.md` §2).
|
|
760
|
+
|
|
761
|
+
**Action refs are signed, and the signing key is derived automatically.** An
|
|
762
|
+
approval notification's action refs are opaque signed tokens
|
|
763
|
+
(`signActionRef`/`verifyActionRef`, base64url payload + `sha256` HMAC,
|
|
764
|
+
constant-time compare) — the internal approval id never leaves in the clear. Both
|
|
765
|
+
halves of the contract call the *same* resolver, `resolveActionSecret()`
|
|
766
|
+
(`@markus/shared`): an explicit `MARKUS_ACTION_SECRET` env var wins; otherwise a
|
|
767
|
+
random secret is generated once and persisted at `~/.markus/action-secret` (0600),
|
|
768
|
+
exactly like `resolveJwtSecret` / `resolveGatewaySecret`. **The operator never
|
|
769
|
+
configures it** — signing a card ref is a defence-in-depth backstop against a
|
|
770
|
+
forged or replayed tap, not a concept a user should have to understand. Signing is
|
|
771
|
+
*not* the trust boundary: the inbound webhook / long-connection is authenticated by
|
|
772
|
+
the platform itself (Feishu `verificationToken` / `encryptKey`). If the resolver
|
|
773
|
+
ever returned different values on the two sides, a legitimate tap would fail
|
|
774
|
+
verification and resolve to nothing — hence one resolver, not two env reads.
|
|
775
|
+
|
|
776
|
+
**Capability degradation** is a total function: `cards|buttons → 'card'`,
|
|
777
|
+
`markdown → 'markdown'`, otherwise `'text'`. The plain-text projection always
|
|
778
|
+
exists and always carries the action labels **and their refs** — a platform
|
|
779
|
+
without buttons renders the same content as text rather than dropping it.
|
|
780
|
+
|
|
781
|
+
**Approval round-trip.** An action carries `ref`, an HMAC-signed opaque token over
|
|
782
|
+
`{approvalId, actionId, taskId?}` (`signActionRef` / `verifyActionRef`). The
|
|
783
|
+
internal approval id never leaves the process: the outbound side signs it, the
|
|
784
|
+
inbound side verifies and resolves it back to the pending approval. Forging or
|
|
785
|
+
tampering with a ref fails verification (returns `undefined`) instead of resolving
|
|
786
|
+
to the wrong approval.
|
|
787
|
+
|
|
788
|
+
**Sink / lookup ports.** `OutboundSink` exposes `capabilities(target)` +
|
|
789
|
+
`send(target, rendered)`; `NotifyTargetLookup` exposes `agentTarget` /
|
|
790
|
+
`instanceTarget` / `globalTarget`. Production binds them to the router and to
|
|
791
|
+
`channel_bindings` respectively; tests bind them to fakes. No module here imports
|
|
792
|
+
`org-manager` or `core` — the dispatcher consumes HITL notifications and EventBus
|
|
793
|
+
events through **structural** interfaces (`{ onNotification }`, `{ on }`).
|
|
794
|
+
|
|
795
|
+
## 8. Capability model
|
|
796
|
+
|
|
797
|
+
Each manifest declares what its platform can do; the core only ever reads this
|
|
798
|
+
table. Proposed shape:
|
|
799
|
+
|
|
800
|
+
```ts
|
|
801
|
+
capabilities: {
|
|
802
|
+
inbound: 'socket' | 'webhook' | 'polling'
|
|
803
|
+
outbound: Array<'text'|'markdown'|'rich'|'buttons'|'cards'|'media'
|
|
804
|
+
|'reaction'|'edit'|'delete'|'thread'|'replyRef'|'ephemeral'>
|
|
805
|
+
group: boolean
|
|
806
|
+
notify: boolean
|
|
807
|
+
interactiveCallback: boolean
|
|
808
|
+
ackDeadlineMs?: number // e.g. 3000 on Discord / Feishu cards
|
|
809
|
+
}
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
### 8.1 As implemented
|
|
813
|
+
|
|
814
|
+
The proposal above **re-types** `inbound` / `outbound` (boolean → union / array).
|
|
815
|
+
That is a wire-shape change: the Settings UI (`PlatformCard`) reads
|
|
816
|
+
`caps.inbound` / `caps.outbound` as booleans and the Settings API already ships
|
|
817
|
+
them that way, so a rename would silently blank those chips and break every
|
|
818
|
+
existing consumer for zero functional gain. The implemented model is therefore
|
|
819
|
+
**additive**: the v1 booleans stay exactly as they were, and the gateway-era
|
|
820
|
+
facts (the *how*, not just the *whether*) are added as optional fields.
|
|
821
|
+
|
|
822
|
+
```ts
|
|
823
|
+
type InboundMode = 'webhook' | 'socket' | 'polling' | 'gateway';
|
|
824
|
+
|
|
825
|
+
interface PlatformCapabilities {
|
|
826
|
+
// v1 — unchanged; the UI and Settings API read these.
|
|
827
|
+
inbound: boolean;
|
|
828
|
+
outbound: boolean;
|
|
829
|
+
threads: boolean;
|
|
830
|
+
cards?: boolean;
|
|
831
|
+
|
|
832
|
+
// The transport facts, read by core; no consumer branches on a platform id.
|
|
833
|
+
inboundModes?: InboundMode[]; // how inbound can arrive; undefined ⇒ unknown
|
|
834
|
+
defaultInboundMode?: InboundMode; // the mode used when config expresses no choice
|
|
835
|
+
requiresPublicUrl?: boolean; // true iff every declared mode needs a public URL
|
|
836
|
+
ackDeadlineMs?: number; // platform ack window for one inbound event (ms)
|
|
837
|
+
extra?: Record<string, string | number | boolean | string[]>;
|
|
838
|
+
}
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
Three rules keep this a *table* and not a branch:
|
|
842
|
+
|
|
843
|
+
1. **`inboundModes` is the single declaration of transport.** Nothing outside a
|
|
844
|
+
manifest may write `if (platform === 'slack')` to decide socket-vs-webhook.
|
|
845
|
+
`activeInboundMode(capabilities, config)` is the one pure function that reads the
|
|
846
|
+
config + the table and names the live mode. **It is consumed at runtime**: the
|
|
847
|
+
Feishu and Slack adapters call it in `connect()` instead of reading
|
|
848
|
+
`config.wsMode` / `config.socketMode` directly, and the platform's default
|
|
849
|
+
transport is declared in the table (`defaultInboundMode`), not in the adapter.
|
|
850
|
+
Precedence: explicit `socketMode/wsMode: true` → socket; explicit
|
|
851
|
+
`socketMode/wsMode: false` → webhook; `pollingEnabled: true` → polling;
|
|
852
|
+
then `defaultInboundMode`; then `gateway`; then `webhook`.
|
|
853
|
+
2. **`requiresPublicUrl` answers the question users actually ask** ("do I need a
|
|
854
|
+
public URL?"). It is declared, not inferred at each call site. Slack declares
|
|
855
|
+
`false` because Socket Mode is available; Telegram `false` because of long
|
|
856
|
+
polling; Discord `false` (gateway); Feishu `false` (WebSocket mode); WhatsApp
|
|
857
|
+
`true` (webhook only).
|
|
858
|
+
3. **`extra` is where a platform's unique abilities live** — Slack Block
|
|
859
|
+
Kit / modals / shortcuts, Discord slash commands / forum channels, Feishu
|
|
860
|
+
scan-to-create app, WhatsApp templates. Core never inlines these; a client that
|
|
861
|
+
wants to *show* them reads `extra` off the manifest.
|
|
862
|
+
|
|
863
|
+
Platform capabilities observed in research (full matrices in
|
|
864
|
+
`research/platform-*.md`):
|
|
865
|
+
|
|
866
|
+
| | Feishu | Telegram | Slack | Discord | WhatsApp |
|
|
867
|
+
|---|---|---|---|---|---|
|
|
868
|
+
| inbound | socket / webhook | polling / webhook | socket / events | gateway (ws) | webhook |
|
|
869
|
+
| rich out | cards, post | markdown | blocks | components, embeds | limited (template) |
|
|
870
|
+
| buttons | ✓ | inline kb | ✓ | ✓ | ✓ (interactive) |
|
|
871
|
+
| group | ✓ (needs @) | ✓ (needs @) | ✓ (needs invite) | ✓ (guild) | **limited** |
|
|
872
|
+
| thread | ✓ topic | ✓ forum | ✓ | ✓ | ✗ |
|
|
873
|
+
| notify | ✓ | ✓ | ✓ | ✓ | ✓ (24 h window) |
|
|
874
|
+
|
|
875
|
+
Unique capabilities worth exposing (not inlining): Feishu **scan-to-create app**,
|
|
876
|
+
message cards, topics, urgent; Telegram **forum topics**, inline queries; Slack
|
|
877
|
+
**Block Kit / modals / shortcuts**; Discord **slash commands, threads, forum
|
|
878
|
+
channels**; WhatsApp **approved templates + 24 h session window**.
|
|
879
|
+
|
|
880
|
+
## 9. UI
|
|
881
|
+
|
|
882
|
+
The Integrations page becomes an **instance list** rather than a platform list:
|
|
883
|
+
|
|
884
|
+
- Collapsed row = **icon + instance label + bound agent + status** (unchanged style).
|
|
885
|
+
- Expanded = guided setup (steps + scan where the platform supports it, e.g. Feishu)
|
|
886
|
+
→ credentials → **agent binding** (searchable picker, already built) →
|
|
887
|
+
**group bindings** (multi-select from the bot's known chats) → **notification
|
|
888
|
+
target**.
|
|
889
|
+
- **"Add bot"** creates a second instance of the same platform.
|
|
890
|
+
- Unknown platforms still render with zero UI code (manifest-driven) — the existing
|
|
891
|
+
regression guard stays green.
|
|
892
|
+
|
|
893
|
+
### 9.1 Implementation contract
|
|
894
|
+
|
|
895
|
+
> §9 is the actual page. It was once a **platform list**, because a platform could
|
|
896
|
+
> physically hold one bot; it is now an **instance list**. The
|
|
897
|
+
> interesting decisions are about *not* growing a second form implementation.
|
|
898
|
+
|
|
899
|
+
**One form, N instances.** Nothing about a platform config changed — same manifest
|
|
900
|
+
fields, same secret masking, same required-field rule. So `InstanceCard` does not
|
|
901
|
+
re-implement them: `instanceAsPlatform(instance)` adapts the instance into the
|
|
902
|
+
`PlatformStatus` that the existing `PlatformCard` already renders, and the card is
|
|
903
|
+
reused with `hideHeader`. The adapter is the *single* place the two shapes meet;
|
|
904
|
+
`PlatformCard` never learns what an instance is.
|
|
905
|
+
|
|
906
|
+
**One fact, one writer.** Four facts, four writers, no overlap:
|
|
907
|
+
|
|
908
|
+
| Fact | Writer | Notes |
|
|
909
|
+
|---|---|---|
|
|
910
|
+
| credential fields + `agentId` | the platform card's Save | adapted to the instance endpoint |
|
|
911
|
+
| `notifyAgentId` | the routing Save | instance config, not a binding |
|
|
912
|
+
| per-chat bindings (`channel_bindings`) | the routing Save | `PUT …/channels` |
|
|
913
|
+
| instance existence (`id`, `label`) | "Add bot" | `POST …/instances` |
|
|
914
|
+
|
|
915
|
+
Because the API validates a save **as a whole** (a required field missing from the
|
|
916
|
+
body is a 400), a routing-only save replays the instance's *stored* values
|
|
917
|
+
alongside `notifyAgentId` (`buildRoutingPayload`). Stored **secrets are never
|
|
918
|
+
replayed** — their absence is what the server reads as "unchanged", so a routing
|
|
919
|
+
save cannot blank a stored credential.
|
|
920
|
+
|
|
921
|
+
**The bound agent is one fact.** It lives on the instance row, but the form reads
|
|
922
|
+
it through the manifest's agent field (`AGENT_BINDING_FIELD.key === 'agentId'`).
|
|
923
|
+
`instanceAsPlatform` feeds the column into that field, so the picker can never show
|
|
924
|
+
"unbound" for a bot that is demonstrably bound — the failure mode that would make
|
|
925
|
+
two storage locations for one fact visible to a user.
|
|
926
|
+
|
|
927
|
+
**Unknown platform = zero UI code.** `InstancesSection` derives its groups from the
|
|
928
|
+
manifest **catalog** unioned with the platforms that already have bots
|
|
929
|
+
(`visiblePlatformIds`) — so a platform the registry dropped keeps its bots visible
|
|
930
|
+
and deletable instead of vanishing. Nothing in the front-end names a platform; the
|
|
931
|
+
guard renders `mattermost` (absent from the front-end entirely) and asserts every
|
|
932
|
+
manifest-typed field appears.
|
|
933
|
+
|
|
934
|
+
**Retired.** `IntegrationsSection.tsx` (the platform list) is deleted, not left
|
|
935
|
+
alongside: two UIs writing the same settings would be the same
|
|
936
|
+
"one fact, two writers" defect this programme exists to remove. Its zero-UI-code
|
|
937
|
+
guard moved to `test/instancesSection.test.tsx`, where it is strictly stronger
|
|
938
|
+
(the unknown platform now has a *bot*).
|
|
939
|
+
|
|
940
|
+
**A half-assigned route is not a save.** Ticking a chat defaults it to the bot's own
|
|
941
|
+
agent (the common case). Ticking a chat on a bot with **no** default agent holds the
|
|
942
|
+
save and names the problem rather than silently writing a binding with no agent or
|
|
943
|
+
quietly dropping the chat the user just ticked.
|
|
944
|
+
|
|
945
|
+
### 9.2 The Settings surface (API + UI contract)
|
|
946
|
+
|
|
947
|
+
The endpoints are platform-parameterised, so one implementation serves every
|
|
948
|
+
platform, Feishu included:
|
|
949
|
+
|
|
950
|
+
| Method | Path | Notes |
|
|
951
|
+
|---|---|---|
|
|
952
|
+
| `GET` | `/api/settings/integrations` | Every platform as a manifest-shaped object. |
|
|
953
|
+
| `GET` | `/api/settings/integrations/:platform` | One platform, not wrapped; non-secret values are also flattened onto the top level so callers written against the legacy Feishu-only shape keep working. |
|
|
954
|
+
| `PUT` | `/api/settings/integrations/:platform` | Validate against the manifest's `required` fields, then write the row. |
|
|
955
|
+
| `POST` | `/api/settings/integrations/:platform/test` | Probes the **stored** credentials; an empty body is valid. |
|
|
956
|
+
|
|
957
|
+
The Feishu-specific extensions (`/register`, `/register/status`, `/chats`,
|
|
958
|
+
`/test-message`, notification rules) are kept verbatim for backward compatibility;
|
|
959
|
+
new platforms use the generic surface only.
|
|
960
|
+
|
|
961
|
+
**Response shape.** `{ id, label, docsUrl, capabilities, fields[], enabled,
|
|
962
|
+
connected, hasConfig, values{…}, secrets{ key: { hasValue } } }` — `values` carries
|
|
963
|
+
the non-secret fields, `secrets` carries presence only.
|
|
964
|
+
|
|
965
|
+
**Secret semantics.** `secret: true` fields are never returned in plaintext: on read
|
|
966
|
+
the key carries a mask plus `hasValue`; on write, `''` or the mask means *leave
|
|
967
|
+
unchanged*, so a form that round-trips the mask cannot overwrite the real secret.
|
|
968
|
+
The invariant is asserted across **every** `GET` under
|
|
969
|
+
`/api/settings/integrations*` with a canary secret value.
|
|
970
|
+
|
|
971
|
+
**UI.** One card per bot instance, and every field is rendered from
|
|
972
|
+
`manifest.fields` (text / number / boolean / select / secret), so adding a platform
|
|
973
|
+
adds no UI code. Platform-specific extras (Feishu's notification preferences and QR
|
|
974
|
+
flow, for instance) live in an **extras slot** the manifest names, and each field has
|
|
975
|
+
exactly one writer — the part of the card that owns it — so two save paths cannot
|
|
976
|
+
fight over the same value.
|
|
977
|
+
|
|
978
|
+
## 10. Module map
|
|
979
|
+
|
|
980
|
+
Where each responsibility lives. The code is the truth; this is the index.
|
|
981
|
+
|
|
982
|
+
| Path | Responsibility |
|
|
983
|
+
|---|---|
|
|
984
|
+
| `packages/comms/src/platforms/registry.ts` | `PLATFORM_MANIFESTS` — the platform data: fields, capabilities, `createAdapter()`. Type contract and "how to add a platform": `packages/comms/docs/platform-manifest.md`. |
|
|
985
|
+
| `packages/comms/src/platforms/instance.ts` | `BotInstance` — one configured bot of a platform. |
|
|
986
|
+
| `packages/comms/src/gateway/inbound.ts` | `resolveInboundTarget()` — the single inbound resolution point (§6.1), plus `MatchedScope`. |
|
|
987
|
+
| `packages/comms/src/gateway/conversation-key.ts` | `conversationKey()` / `MAIN_CONVERSATION_KEY` / `isInboundIgnored()` — session isolation (§6.2). |
|
|
988
|
+
| `packages/comms/src/gateway/ack.ts` | `createAck()` and the deadline-driven `createDeadlineAck()` (§6.4). |
|
|
989
|
+
| `packages/comms/src/gateway/outbound.ts` | `OutboundMessage` + signed action refs (`signActionRef` / `verifyActionRef`). |
|
|
990
|
+
| `packages/comms/src/gateway/render.ts`, `src/render/markdown.ts` | Capability-driven rendering; per-platform markdown dialects. |
|
|
991
|
+
| `packages/comms/src/gateway/dispatcher.ts` | `OutboundDispatcher` + the `OutboundSink` / `NotificationSource` ports (§7.2). |
|
|
992
|
+
| `packages/comms/src/gateway/notify-route.ts` | `resolveNotifyTarget()` — the three-level walk (§7.3). |
|
|
993
|
+
| `packages/comms/src/gateway/notify-lookup.ts`, `repo-binding-lookup.ts` | The lookup ports over `channel_bindings` / instance rows, and the bindings loader. |
|
|
994
|
+
| `packages/comms/src/gateway/router-sink.ts` | `RouterOutboundSink` — the sink port backed by the adapter router. |
|
|
995
|
+
| `packages/comms/src/gateway/connection-test.ts` | The Settings "test connection" probe. |
|
|
996
|
+
| `packages/comms/src/net/http.ts` | `httpFetch` + failure classification, injectable for tests. |
|
|
997
|
+
| `packages/comms/src/slack/socket.ts` | Slack Socket Mode transport (no public URL needed). |
|
|
998
|
+
| `packages/storage/src/*` | `platform_instances` / `channel_bindings` repositories and their migration (§5). |
|
|
999
|
+
| `packages/org-manager/src/api-server.ts` | The Settings API and `resolvePlatformConfig()` (§5.4, §9.2). |
|
|
1000
|
+
| `packages/cli/src/commands/start.ts` | Assembly: walk manifests × instances, register, connect (§4.3). |
|
|
1001
|
+
| `packages/web-ui/src/components/integrations/*` | The instance cards, rendered from `manifest.fields` (§9). |
|
|
1002
|
+
|
|
1003
|
+
## 11. Known limitations & residual risk
|
|
1004
|
+
|
|
1005
|
+
What this work does **not** claim.
|
|
1006
|
+
|
|
1007
|
+
**Cannot be verified on this machine** (no credentials, no public URL):
|
|
1008
|
+
|
|
1009
|
+
- Real-service connectivity for Slack (`xapp-…`), Telegram and Discord. The Slack
|
|
1010
|
+
evidence is a real-WebSocket loopback with a local server playing Slack; Discord
|
|
1011
|
+
gateway sessions and Telegram long polling against live services are unproven.
|
|
1012
|
+
- Every webhook path (Slack / WhatsApp / Discord) needs a public URL, which a
|
|
1013
|
+
desktop install does not have.
|
|
1014
|
+
- `connected` has a real source only for Feishu.
|
|
1015
|
+
|
|
1016
|
+
**Therefore Slack, WhatsApp and Discord are marked `devOnly` in the registry**:
|
|
1017
|
+
their adapters and manifests stay in the tree (unit-tested, and exercised in
|
|
1018
|
+
development), but a production build does not offer them in Settings. The gate is
|
|
1019
|
+
presentation-only and lives in one place — `visiblePlatformIds`, driven by
|
|
1020
|
+
`import.meta.env.DEV` — so promoting a platform after live verification is a
|
|
1021
|
+
one-line flag flip, pinned by `platform-registry.test.ts` (see
|
|
1022
|
+
`packages/comms/docs/platform-manifest.md` → *Development-only platforms*).
|
|
1023
|
+
|
|
1024
|
+
**Deliberately not delivered:**
|
|
1025
|
+
|
|
1026
|
+
- Slack `slash_commands` / `interactive` envelopes are ACKed and logged, not
|
|
1027
|
+
projected into agent turns.
|
|
1028
|
+
- The legacy notifier's **rich agent-response card streaming** has no equivalent in
|
|
1029
|
+
the gateway — the request/reply path returns text (§6.5).
|
|
1030
|
+
- `getOrCreateMainSession` / `MAIN_CONVERSATION_KEY` and the DB main session (`cs_*`)
|
|
1031
|
+
remain two facts.
|
|
1032
|
+
|
|
1033
|
+
**`MARKUS_ACTION_SECRET` is derived, not configured.** It is resolved through
|
|
1034
|
+
`resolveActionSecret()` — an explicit env var when set, otherwise a random secret
|
|
1035
|
+
generated once at `~/.markus/action-secret`. Nothing in the product surfaces it.
|
|
1036
|
+
Independently, an install whose Secretary has no addressable binding has no
|
|
1037
|
+
terminus: the dispatcher reports it as undeliverable rather than swallowing it
|
|
1038
|
+
(§7.3), and the Settings notification destination is what configures it.
|
|
1039
|
+
|
|
1040
|
+
**Operational trap found, not fixed here (pre-existing):** `initSqliteStorage`
|
|
1041
|
+
swallows *all* errors and returns `null`, so a repository-wiring programming error
|
|
1042
|
+
degrades silently to memory-only mode instead of failing loudly.
|
|
1043
|
+
|