@yuriai/web 0.2.27-beta.2 → 0.2.27-beta.6

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 (157) hide show
  1. package/README.md +9 -0
  2. package/dist/assets/{AgentAvatar-BW4Zg8bo.js → AgentAvatar-Bi1vvWPC.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +3 -0
  4. package/dist/assets/AssistantUnreadBadge-DdJyySwn.js +1 -0
  5. package/dist/assets/AssistantView-Br1iETTs.js +1 -0
  6. package/dist/assets/{DiagramView-D6wdXRzu.js → DiagramView-CI4bTtxy.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-gOsILpSk.js → FadeInOnReveal-BB4qEnAn.js} +1 -1
  8. package/dist/assets/GuiPluginSurface-CguxFUbM.js +1 -0
  9. package/dist/assets/{GuiPluginWindow-tGvc4_0g.js → GuiPluginWindow-DOJ7wuRH.js} +1 -1
  10. package/dist/assets/Icon-t2xvbAyN.js +1 -0
  11. package/dist/assets/{ImageLoadingPlaceholder-9xYbKqtf.js → ImageLoadingPlaceholder-D1L13TK0.js} +1 -1
  12. package/dist/assets/{LoadingImage-CiOcKPfb.js → LoadingImage-5rY_edNm.js} +1 -1
  13. package/dist/assets/{MarkdownRenderer-DZkP4UNr.js → MarkdownRenderer-BlGxjOei.js} +2 -2
  14. package/dist/assets/{MarkdownRendererImpl-BXzPUEEo.js → MarkdownRendererImpl-cE-0AYRg.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-B-NWd069.js → MarkstreamRendererImpl-BZyqDl82.js} +1 -1
  16. package/dist/assets/MobileDetailNavigation-tbfsMfB-.js +1 -0
  17. package/dist/assets/{MobileResizableSheet-ZL-zPa3W.js → MobileResizableSheet-BeRmT6_x.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-JSH_Y8Ps.js → MobileShareBridge-C3Equ3P_.js} +2 -2
  19. package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +2 -0
  20. package/dist/assets/{MultiRunWindow-ZPz62Aqg.js → MultiRunWindow-CAM2XPII.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-BQNoy9o1.js → OnboardingScreen-4ftRerP5.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-BwCFalSw.js → OverlayScrollbar-CF0PCvQz.js} +1 -1
  23. package/dist/assets/{SettingsView-B17qt8dh.js → SettingsView-2tk4WH7R.js} +15 -15
  24. package/dist/assets/{SettingsWindow-CIFNHb-F.js → SettingsWindow-B9zbeJaW.js} +1 -1
  25. package/dist/assets/TerminalView-DfxvTHye.js +8 -0
  26. package/dist/assets/{ToolOutputDialog-BKuVpgEu.js → ToolOutputDialog-CrjDIhru.js} +1 -1
  27. package/dist/assets/{YuriLogo-C1Ty-RTB.js → YuriLogo-QvS1ZEHi.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-DqGuzMaH.js → appThemeRegistry-Bb_DtiV9.js} +1 -1
  29. package/dist/assets/{button-DuHjvKJJ.js → button-DinGM3tu.js} +1 -1
  30. package/dist/assets/{capgoAdapter-B-tddboe.js → capgoAdapter-DufzjXRs.js} +1 -1
  31. package/dist/assets/{collapsible-B8eL5nLo.js → collapsible-Bh1GLNYV.js} +1 -1
  32. package/dist/assets/context-menu-DpbkRkk1.js +1 -0
  33. package/dist/assets/{diagram-ChoQDKzy.js → diagram-BmG-7Jb4.js} +1 -1
  34. package/dist/assets/{dialog-CVhqZux0.js → dialog-BXssfGXA.js} +1 -1
  35. package/dist/assets/es-HP_Ise0X.js +15 -0
  36. package/dist/assets/{fileMentionTouchSelection-Dd-iSIe2.js → fileMentionTouchSelection-DSl0tj2r.js} +1 -1
  37. package/dist/assets/{fileReferenceActions-BAoEu4z8.js → fileReferenceActions-CGpBSFq4.js} +1 -1
  38. package/dist/assets/fr-D0kJXJ6U.js +13 -0
  39. package/dist/assets/gitApi-Wo0IZow9.js +370 -0
  40. package/dist/assets/{gitApiHttp-DHrRqnYh.js → gitApiHttp-De9liKnG.js} +4 -4
  41. package/dist/assets/host-FR_grJxM.js +1 -0
  42. package/dist/assets/{input-E_oYiXZT.js → input-v8-rVbo-.js} +1 -1
  43. package/dist/assets/insertionBoundaries-CZz7TWJv.js +1 -0
  44. package/dist/assets/ja-BjHKXazE.js +15 -0
  45. package/dist/assets/ko-Llwnl876.js +15 -0
  46. package/dist/assets/main-Bp9HHqTr.js +2 -0
  47. package/dist/assets/main-DOwAfmxJ.js +169 -0
  48. package/dist/assets/{markdownHeightCache-heNXHdzb.js → markdownHeightCache-BVV2dktw.js} +1 -1
  49. package/dist/assets/{mcpQueries-BqKVe4Su.js → mcpQueries-BoBrB4a4.js} +1 -1
  50. package/dist/assets/miniChat-BJDgCrfF.js +2 -0
  51. package/dist/assets/mobile-GM9931J_.js +2 -0
  52. package/dist/assets/{mobileBackNavigation-DHxFQ7SY.js → mobileBackNavigation-DMSzAvb6.js} +1 -1
  53. package/dist/assets/{multirun-CPOzaEQj.js → multirun-BhWttsRQ.js} +1 -1
  54. package/dist/assets/{native-De1DIkLZ.js → native-DSvNnKAm.js} +1 -1
  55. package/dist/assets/{native-config-oauL2ekt.js → native-config-DjdrW_9n.js} +1 -1
  56. package/dist/assets/{persistence-JyLTFv27.js → persistence-CfrHIiIS.js} +1 -1
  57. package/dist/assets/pl-BOd_idqn.js +15 -0
  58. package/dist/assets/{projectMeta-YDMdD3AP.js → projectMeta-31PobC-M.js} +1 -1
  59. package/dist/assets/pt-BR-B8djxMsl.js +15 -0
  60. package/dist/assets/react-B9v0P7kT.js +1 -0
  61. package/dist/assets/{readiness-BveVUOIb.js → readiness-CYNnsekT.js} +1 -1
  62. package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +2 -0
  63. package/dist/assets/renderMobileApp-CU1ec6Ak.js +28 -0
  64. package/dist/assets/{runtimeConfig-BpcgdIV9.js → runtimeConfig-Db7yfo6L.js} +1 -1
  65. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +149 -0
  66. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +1 -0
  67. package/dist/assets/sessionLookup-DRVy7LM1.js +1 -0
  68. package/dist/assets/sortable-tabs-strip-yKyqsqut.js +1 -0
  69. package/dist/assets/speechSettingsQueries-DU25rmGc.js +4 -0
  70. package/dist/assets/src-Bckdo2XS.css +2 -0
  71. package/dist/assets/store-CUBymvAC.js +15 -0
  72. package/dist/assets/{terminalApi-B5o8UqWA.js → terminalApi-BblSkqch.js} +1 -1
  73. package/dist/assets/{textarea-DmKaqHSb.js → textarea-B39OCNPV.js} +1 -1
  74. package/dist/assets/{tooltip-DUKu4nC6.js → tooltip-d8TNN4lx.js} +1 -1
  75. package/dist/assets/{types-DRTMRW4R.js → types-BqFQhQTt.js} +1 -1
  76. package/dist/assets/{uk-CYZXWdd7.js → uk-BNd7CjVO.js} +4 -4
  77. package/dist/assets/{useAppFontEffects-BiQf6tgZ.js → useAppFontEffects-BVoVpJYO.js} +57 -55
  78. package/dist/assets/{useAssistantUIStore-C9FPlYQz.js → useAssistantUIStore-Bp6TxG5E.js} +1 -1
  79. package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +1 -0
  80. package/dist/assets/{useEffectiveDirectory-B8q00InF.js → useEffectiveDirectory-D8FFE5Yn.js} +1 -1
  81. package/dist/assets/{useFontPreferences-DMiP_Yy-.js → useFontPreferences-BFyBjtQ6.js} +1 -1
  82. package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +23 -0
  83. package/dist/assets/useUIStore-BbYD420L.js +1 -0
  84. package/dist/assets/{useWorkerHighlightedLines-B6lWNk01.js → useWorkerHighlightedLines-CPxG8Fya.js} +1 -1
  85. package/dist/assets/{vendor-codemirror-search-ZqtrPLjU.js → vendor-codemirror-search-DiPwvA-6.js} +2 -2
  86. package/dist/assets/{vendor-opencode-plugin-Bw7Q6Nv9.js → vendor-opencode-plugin-CgKz9Hcy.js} +1 -1
  87. package/dist/assets/{vendor-replit-codemirror-vim-DDj0dSVY.js → vendor-replit-codemirror-vim-DCdAdxvE.js} +3 -3
  88. package/dist/assets/zh-CN-BkTAEOZG.js +15 -0
  89. package/dist/assets/zh-TW-x8SfMzfc.js +15 -0
  90. package/dist/index.html +10 -10
  91. package/dist/mini-chat.html +10 -10
  92. package/dist/mobile.html +10 -10
  93. package/package.json +3 -3
  94. package/server/lib/assistants/DOCUMENTATION.md +30 -0
  95. package/server/lib/assistants/contact-store.js +16 -0
  96. package/server/lib/assistants/contact-store.test.js +19 -0
  97. package/server/lib/assistants/contracts.js +1 -0
  98. package/server/lib/assistants/routes.js +25 -3
  99. package/server/lib/assistants/service.js +30 -8
  100. package/server/lib/assistants/service.test.js +151 -0
  101. package/server/lib/assistants/weixin/DOCUMENTATION.md +199 -0
  102. package/server/lib/assistants/weixin/api.js +113 -0
  103. package/server/lib/assistants/weixin/api.test.js +80 -0
  104. package/server/lib/assistants/weixin/routes.js +24 -0
  105. package/server/lib/assistants/weixin/routes.test.js +71 -0
  106. package/server/lib/assistants/weixin/runtime.js +426 -0
  107. package/server/lib/assistants/weixin/runtime.test.js +500 -0
  108. package/server/lib/assistants/weixin/store.js +116 -0
  109. package/server/lib/assistants/weixin/typing.js +88 -0
  110. package/server/lib/assistants/weixin/typing.test.js +185 -0
  111. package/server/lib/opencode/DOCUMENTATION.md +2 -1
  112. package/server/lib/opencode/npm-registry.js +7 -21
  113. package/server/lib/opencode/npm-registry.test.js +36 -5
  114. package/server/lib/opencode/plugin-icon.d.ts +2 -0
  115. package/server/lib/opencode/plugin-icon.js +43 -0
  116. package/server/lib/opencode/plugin-icon.test.js +41 -0
  117. package/server/lib/opencode/plugin-routes.js +3 -1
  118. package/server/lib/opencode/plugin-routes.test.js +13 -0
  119. package/server/lib/opencode/shutdown-runtime.js +1 -1
  120. package/server/lib/opencode/shutdown-runtime.test.js +12 -0
  121. package/dist/assets/AssistantView-Cl0ZeXwr.js +0 -3
  122. package/dist/assets/GuiPluginSurface-DOZAQKX0.js +0 -1
  123. package/dist/assets/Icon-DvUDsV1z.js +0 -1
  124. package/dist/assets/MobileDetailNavigation-5U28hfYf.js +0 -1
  125. package/dist/assets/MobileTabPageHeader-Bj9MIS38.js +0 -2
  126. package/dist/assets/TerminalView-BZZ8LW4d.js +0 -8
  127. package/dist/assets/dropdown-menu.styles-DGvlOX_5.js +0 -1
  128. package/dist/assets/es-B8sAsuo5.js +0 -15
  129. package/dist/assets/fr-BPpW8T-l.js +0 -13
  130. package/dist/assets/gitApi-D43bAQh1.js +0 -10
  131. package/dist/assets/host-D1EpSUMR.js +0 -1
  132. package/dist/assets/insertionBoundaries-BQjiZAmZ.js +0 -1
  133. package/dist/assets/ja-DEoFDi7P.js +0 -15
  134. package/dist/assets/ko-B45xHN6I.js +0 -15
  135. package/dist/assets/main-C6MDfyZy.js +0 -2
  136. package/dist/assets/main-u5iQScJs.js +0 -169
  137. package/dist/assets/miniChat-Dhfn71Re.js +0 -2
  138. package/dist/assets/mobile-DSVdPfcG.js +0 -2
  139. package/dist/assets/pl-Bm3Je_AX.js +0 -15
  140. package/dist/assets/pt-BR-BiQwFHhL.js +0 -15
  141. package/dist/assets/react-CURmDhtB.js +0 -1
  142. package/dist/assets/renderElectronMiniChatApp-NC8iRPyy.js +0 -2
  143. package/dist/assets/renderMobileApp-D5ai1i6y.js +0 -28
  144. package/dist/assets/runtimeEndpointReset-ByKa_0nu.js +0 -149
  145. package/dist/assets/scheduledTaskNavigation-CZfAnPD-.js +0 -1
  146. package/dist/assets/sessionChangeSummary-D6NlE_5k.js +0 -1
  147. package/dist/assets/sessionLookup-C70EoX-V.js +0 -1
  148. package/dist/assets/sortable-tabs-strip-aKussO2c.js +0 -1
  149. package/dist/assets/speechSettingsQueries-B6qf-mCh.js +0 -4
  150. package/dist/assets/src-NKCZI3Lg.css +0 -2
  151. package/dist/assets/store-BeD2keas.js +0 -15
  152. package/dist/assets/useDesktopWindowControlsLayout-DJxNmCWb.js +0 -1
  153. package/dist/assets/useMobileNavigationStore-Bn4SaalY.js +0 -418
  154. package/dist/assets/useUIStore-DI7va1HH.js +0 -1
  155. package/dist/assets/zh-CN-CMLBHipA.js +0 -15
  156. package/dist/assets/zh-TW-CJlmnnhK.js +0 -15
  157. /package/dist/assets/{sessionChangeSummary-8C8nv-EP.css → sessionLookup-8C8nv-EP.css} +0 -0
@@ -0,0 +1,199 @@
1
+ # WeChat text channel
2
+
3
+ This Host-owned channel connects a QR-authorized personal WeChat account to one
4
+ existing Yuri Bot. It uses Tencent's public `openclaw-weixin` iLink wire reference,
5
+ not WorkBuddy OAuth/private proxy APIs, personal-WeChat hooks or the WeChat customer
6
+ service protocol. No OpenClaw runtime or new dependency is installed.
7
+
8
+ ## Ownership and UI
9
+
10
+ - `api.js`: fixed HTTPS origin, official-host validation for QR redirects, bounded
11
+ JSON decoding, lossless uint64 message IDs, separate HTTP/business errors.
12
+ - `store.js`: private SQLite binding, platform cursor, incoming dedup receipts,
13
+ ordered outgoing deliveries and process-owner lease.
14
+ - `runtime.js`: QR lifecycle, owner-only admission, bounded output reconciliation,
15
+ retry/ambiguity and shutdown. `routes.js` exposes authenticated settings only.
16
+ - `typing.js`: optional per-binding live typing state, ticket lifetime, bounded
17
+ refresh/backoff and serialized cancellation; no persisted presence or UI state.
18
+ - `assistants/service.channelPage()` is an internal bounded, ascending durable
19
+ output seam. It validates the Bot and uses the contact-store generation. It does
20
+ not expose credentials or replace the contact execution engine.
21
+ - Shared `AssistantChannelsGroup` appears last in each **saved** Bot's settings,
22
+ after scheduled tasks. One labelled **Message channels** group owns its card;
23
+ WeChat is its first channel. It is not a global setting or one search entry per
24
+ dynamic Bot. Web, desktop, hosted mobile and Capacitor configure the active Host
25
+ through `runtimeFetch`; standalone VS Code explicitly returns 501.
26
+
27
+ ## Authorization and persistence
28
+
29
+ Before opening storage or creating any timer, the runtime resolves the channel
30
+ policy from its environment. `NODE_ENV=development` or `YURI_ELECTRON_DEV=1/true`
31
+ disables WeChat by default; the web development server scripts explicitly set
32
+ `NODE_ENV=development`, including watch/HMR/full/mobile live-reload paths. An
33
+ explicit `YURI_WEIXIN_ENABLED=1/true` opts in; `0/false` or an unrecognized nonempty
34
+ value disables it in any environment. Production defaults remain enabled.
35
+
36
+ A disabled runtime does not open/create SQLite, acquire/release leases, poll,
37
+ send, infer live typing or mutate bindings. Status returns `disabled`; QR login,
38
+ verification, retry, disconnect and transfer fail with `channel_disabled` (403).
39
+ `forget` and shutdown are no-ops, so development does not erase production channel
40
+ credentials. Shared UI displays the disabled state without connection controls
41
+ and does not poll it. This gate is channel-specific, not general isolation of
42
+ assistant data; testing channels still requires an isolated data directory and
43
+ test account. Never copy production WeChat credentials into a second database.
44
+
45
+ The QR-confirmed `ilink_user_id` is the only accepted sender. Group messages,
46
+ other senders and messages without a stable platform ID never invoke tools. Each
47
+ bound account maps to exactly one Bot within the Host data directory. The account
48
+ can use that Bot's existing tools and Host permissions; the UI discloses this before
49
+ scanning. This is not a separate remote-execution sandbox.
50
+
51
+ Bindings live under `<yuriDataDir>/weixin/channel.sqlite`. The directory is 0700
52
+ and database is 0600, with SQLite secure-delete enabled. Tokens are **not encrypted
53
+ at rest**; the host OS user must protect its data directory/backups (on Windows,
54
+ OS ACLs remain necessary). They never enter settings/snapshot DTOs, transcript,
55
+ model context, URLs, logs or config sync. QR/verification data stays in memory;
56
+ route responses use `Cache-Control: no-store`, UI Query caches have zero GC retention,
57
+ and QR images are generated locally rather than sent to an external image service.
58
+
59
+ Disconnect aborts local receiving/sending, fences late completions and deletes
60
+ local credentials and pending deliveries; it does not erase Bot history or cancel
61
+ already admitted work. The public reference has no general server-side token
62
+ revocation API, so this is not a promise to revoke the platform's authorization.
63
+ Deleting a Bot also forgets its local connection. Failed revision-checked Bot
64
+ deletion leaves the connection intact.
65
+
66
+ ### Moving a connection between Yuri Bots
67
+
68
+ The current WeChat flow supports one Bot entry for a scanning WeChat user, not a
69
+ new independent entry on every scan. Multiple stored bindings represent separate
70
+ platform accounts, not evidence that one user can create multiple contacts. QR
71
+ `binded_redirect` and confirmed-account conflicts never silently steal a binding.
72
+
73
+ For an unbound target, authenticated status responses optionally list local
74
+ `transferSources` containing only the source Bot ID, display name and binding
75
+ revision (epoch). No platform account/user IDs, tokens or context tickets leave
76
+ the Host. The settings row offers an explicit two-step confirmation, including
77
+ the loss of unprocessed inbound messages and queued outgoing replies. No QR or
78
+ platform reauthorization is required to move an existing local authorization.
79
+
80
+ `POST /api/yuri/assistants/:assistantID/weixin/transfer` accepts `sourceAssistantID`,
81
+ `revision` and UI `language`. The Host requires the current lease, a live source
82
+ matching that exact epoch and an unbound target; it will not overwrite even an
83
+ expired target binding. Source/target are locked while receiving and sending are
84
+ aborted/drained, live typing is cancelled, and target QR attempts are invalidated.
85
+ Both Bots and the source epoch are revalidated after the wait. Concurrent moves,
86
+ disconnects and QR starts cannot race this boundary; stale confirmations return
87
+ `binding_changed` (409). Shutdown waits for the move before releasing storage.
88
+
89
+ One SQLite transaction moves credentials, paired owner, cursor and reply context,
90
+ assigns a new epoch, sets the target's current transcript tip and drops the source
91
+ outbox. Receipt IDs survive under the new epoch as done, with cleared text, so
92
+ platform replays cannot re-execute tools after a move or restart. Pending messages
93
+ are not reassigned to the new Bot. Histories stay with their original Bots; already
94
+ admitted tasks continue there without further WeChat synchronization. Already
95
+ submitted HTTP sends cannot be recalled. Failed validation or transaction writes
96
+ leave source credentials, cursor and queues intact and resume its receiver (an
97
+ interrupted in-flight send still has the normal uncertain-delivery semantics).
98
+
99
+ The UI invalidates the current Host's channel queries after mutations, including
100
+ the source and target, and rejects stale-runtime completions. Connection candidates
101
+ are dynamic entity rows, not global Settings search entries. A connection owned by
102
+ WorkBuddy or another Host cannot be imported: users must unlink in that application
103
+ and authorize Yuri through the platform flow. Local disconnect alone does not
104
+ promise to revoke a remote application's authorization.
105
+
106
+ ## Delivery semantics
107
+
108
+ Incoming receipt, reply context and platform cursor commit together before calling
109
+ `service.send()`. Namespaced IDs keep admission idempotent across duplicates and
110
+ restarts. Incoming and outgoing work is separate from the long-poll receiver; pending
111
+ plus admitted receipt count applies backpressure at 100, with 20 admissions per pass.
112
+ Each active account has one receiver and one outbound scheduler. The process lease
113
+ renews every 2 seconds and expires after 60 seconds; another process sharing this
114
+ data directory cannot steal a live account. After any network wait, epoch/lease
115
+ checks fence stale writes. Cross-machine copies of credentials/data are unsupported.
116
+
117
+ Binding starts at the current contact tip, so existing history/greetings are not
118
+ sent. Subsequent **public assistant replies**, including App-initiated and background
119
+ task replies, sync to the paired owner. Plain text is sent as text; current cards
120
+ become title/name text, not interactive WeChat cards or deeplinks. Internal settle
121
+ markers are omitted and failures use a safe generic message, never raw tool errors.
122
+ Media input gets a text-only explanation and never invokes tools. Generation reset
123
+ drops queued output from the previous transcript. An already submitted HTTP request
124
+ cannot be recalled, including during disconnect/reset.
125
+
126
+ Replies are split by Unicode code points into at most 3500-character segments;
127
+ stable client IDs and ordered outbox rows survive restart. This is not a server-side
128
+ exactly-once guarantee. An uncertain HTTP result is marked **delivery unknown** and
129
+ blocks later output until the owner explicitly retries. New inbound context may
130
+ unblock a known rejected reply but never automatically retries an unknown send.
131
+ Authentication expiry stays expired until new authorization; receiver network errors
132
+ retry with 1–30 second capped backoff. Users can manually retry other blocked sends.
133
+ The platform's reply-context lifetime and active-push quota are not specified here.
134
+
135
+ Contact execution itself remains process-local. A crash with an admitted request
136
+ does **not** rerun tools; recovery sends an interruption/check-status notice. A crash
137
+ between contact completion and receipt acknowledgement can conservatively produce
138
+ that notice even if some output committed. Completed receipts keep only IDs/states;
139
+ sent outbox rows clear text. Dedup metadata is retained for the binding lifetime and
140
+ removed on disconnect. There is no autonomous contact-run recovery.
141
+
142
+ Shutdown awaits channel operations before closing assistant storage. UI polling is
143
+ limited to the mounted selected Bot (2s QR, 15s connected, no background polling),
144
+ not the composer or global Bot catalog. QR generation reruns only for changed QR
145
+ content and stale runtime mutations cannot overwrite a new Host's cache.
146
+
147
+ ## Protocol and verification limits
148
+
149
+ ### Typing presence
150
+
151
+ Only live `yuri:contact-turn-start/end` events drive typing, including App-initiated
152
+ or background contact turns whose public replies also sync to WeChat. Binding or
153
+ restarting does not infer activity from persisted receipts/history, and historical
154
+ end events or streaming deltas never start an indicator. A turn already running
155
+ before binding is not backfilled. Overlapping live turn IDs share one indicator;
156
+ the last completion, error or cancellation stops it.
157
+
158
+ The Host obtains a per-user `typing_ticket` through `getconfig`, then calls
159
+ `sendtyping` with status 1 to start/refresh and 2 to cancel. This is native protocol
160
+ presence, not a placeholder text message. Successful tickets stay only in memory
161
+ for at most 24 hours, scoped to the binding epoch and paired peer. A refresh reads
162
+ the latest conversation context. Idle bindings make no typing requests. Each
163
+ active binding has at most one serial typing loop, with one refresh per 8 seconds
164
+ after the preceding request; token deltas and duplicate starts add no requests.
165
+ The cadence and cache duration are Yuri client policy, not a guarantee of WeChat's
166
+ indicator TTL. Missing/rejected tickets and request failures retry with 2–60 second
167
+ capped backoff while the live turn remains active.
168
+
169
+ Typing requests have a 5-second deadline and never block admission or text delivery.
170
+ The end event aborts a pending start/refresh, fences late configuration results and
171
+ serializes a best-effort cancellation before the next turn's start. Cancellation
172
+ uses its own deadline, not the already aborted start signal. Disconnect/deletion
173
+ retires the binding before awaiting cancellation and removing credentials; shutdown
174
+ also awaits cancellation before closing storage/releasing the process lease. A
175
+ lost lease or changed epoch cannot send/cancel presence for another owner. Tickets
176
+ and transient turn tracking are discarded on unbind, expiry or ownership loss.
177
+ Optional presence failures are not surfaced as a broken text channel. Process death
178
+ or a failed cancel cannot guarantee immediate removal in the WeChat client.
179
+
180
+ ### QR profile fields
181
+
182
+ The public QR request sends `bot_type` and `local_token_list`; neither its request
183
+ nor confirmation flow exposes nickname/avatar configuration. Do not append guessed
184
+ profile fields or alter QR payloads to claim that WeChat adopts the Yuri Bot's
185
+ profile. `base_info.bot_agent` is observability metadata, not the contact name or
186
+ avatar. There is no public profile-update endpoint in this protocol reference.
187
+
188
+ Reference: https://github.com/Tencent/openclaw-weixin/blob/main/docs/protocol.md
189
+ (protocol baseline 2.4.10; `bot_agent: Yuri`). Public source availability does not
190
+ establish third-party product admission, all-account availability, service SLA,
191
+ unlimited proactive notifications or arbitrary rich-card support.
192
+
193
+ Focused tests cover wire behavior, business errors, QR fencing, owner isolation,
194
+ dedup, restart, conflicting bindings, process lease, shutdown, generation changes,
195
+ unknown delivery, HTTP protection, confirmed moves, failed-write rollback,
196
+ cursor/dedup preservation, concurrent/stale moves, typing cancellation/stale completions,
197
+ and real contact-pipeline execution with a fake WeChat service. Real-account
198
+ QR/verification, phone-visible delivery and typing presentation still require
199
+ manual testing; mocks and builds are not evidence of platform acceptance.
@@ -0,0 +1,113 @@
1
+ import { randomBytes } from 'node:crypto';
2
+
3
+ // Wire-format reference: Tencent/openclaw-weixin (MIT), docs/protocol.md.
4
+ // This is a Yuri transport, not an OpenClaw runtime or a WorkBuddy login client.
5
+ const API_ORIGIN = 'https://ilinkai.weixin.qq.com';
6
+ const PROTOCOL_VERSION = '2.4.10';
7
+ const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
8
+
9
+ export class WeixinError extends Error {
10
+ constructor(code, { ret = null, ambiguous = false } = {}) {
11
+ super(code);
12
+ this.code = code;
13
+ this.ret = ret;
14
+ this.ambiguous = ambiguous;
15
+ }
16
+ }
17
+
18
+ export function weixinOrigin(value = API_ORIGIN) {
19
+ let url;
20
+ try { url = new URL(value.includes('://') ? value : `https://${value}`); } catch { throw new WeixinError('invalid_response'); }
21
+ if (url.protocol !== 'https:' || url.username || url.password || url.port
22
+ || !url.hostname.endsWith('.weixin.qq.com') || url.pathname !== '/' || url.search || url.hash) {
23
+ throw new WeixinError('invalid_response');
24
+ }
25
+ return url.origin;
26
+ }
27
+
28
+ export function createWeixinAPI({ fetchImpl = fetch } = {}) {
29
+ const request = async (origin, route, { token, body, signal, timeoutMs = 15_000, sending = false, allowEmpty = false } = {}) => {
30
+ const headers = {
31
+ 'Content-Type': 'application/json',
32
+ 'iLink-App-Id': 'bot',
33
+ 'iLink-App-ClientVersion': String(0x02040a),
34
+ };
35
+ if (body !== undefined) {
36
+ headers.AuthorizationType = 'ilink_bot_token';
37
+ headers['X-WECHAT-UIN'] = Buffer.from(String(randomBytes(4).readUInt32BE())).toString('base64');
38
+ }
39
+ if (token) headers.Authorization = `Bearer ${token}`;
40
+ let response;
41
+ try {
42
+ response = await fetchImpl(`${weixinOrigin(origin)}${route}`, {
43
+ method: body === undefined ? 'GET' : 'POST', headers,
44
+ ...(body === undefined ? {} : { body: JSON.stringify(token ? {
45
+ ...body, base_info: { channel_version: PROTOCOL_VERSION, bot_agent: 'Yuri' },
46
+ } : body) }),
47
+ redirect: 'error',
48
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
49
+ });
50
+ } catch {
51
+ if (signal?.aborted) throw new WeixinError('cancelled');
52
+ throw new WeixinError('network_error', { ambiguous: sending });
53
+ }
54
+ if (!response.ok) {
55
+ if (response.status === 401 || response.status === 403) throw new WeixinError('auth_expired');
56
+ throw new WeixinError('network_error', { ambiguous: sending && response.status >= 500 });
57
+ }
58
+ let text = '';
59
+ try {
60
+ if (allowEmpty && !response.body) return {};
61
+ const reader = response.body.getReader();
62
+ const chunks = [];
63
+ let size = 0;
64
+ while (true) {
65
+ const { done, value } = await reader.read();
66
+ if (done) break;
67
+ size += value.byteLength;
68
+ if (size > MAX_RESPONSE_BYTES) { await reader.cancel(); throw new Error('response_too_large'); }
69
+ chunks.push(value);
70
+ }
71
+ text = Buffer.concat(chunks).toString('utf8');
72
+ if (allowEmpty && !text.trim()) return {};
73
+ // Weixin IDs are uint64; preserve digits before JSON's number conversion.
74
+ const data = JSON.parse(text.replace(/("message_id"\s*:\s*)(\d+)(?=\s*[,}])/g, '$1"$2"'));
75
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('invalid_response');
76
+ if (data.ret === -14 || data.errcode === -14) throw new WeixinError('auth_expired');
77
+ if ((data.ret !== undefined && data.ret !== 0) || (data.errcode !== undefined && data.errcode !== 0)) {
78
+ throw new WeixinError(sending ? 'reply_unavailable' : 'upstream_error', { ret: data.ret ?? data.errcode });
79
+ }
80
+ return data;
81
+ } catch (error) {
82
+ if (error instanceof WeixinError) throw error;
83
+ throw new WeixinError('invalid_response', { ambiguous: sending });
84
+ }
85
+ };
86
+ return {
87
+ getQRCode: (signal, localTokens = []) => request(API_ORIGIN, '/ilink/bot/get_bot_qrcode?bot_type=3', {
88
+ body: { local_token_list: localTokens.slice(0, 10) }, signal,
89
+ }),
90
+ getQRStatus: (origin, qrcode, verifyCode, signal) => request(origin, `/ilink/bot/get_qrcode_status?${new URLSearchParams({
91
+ qrcode, ...(verifyCode ? { verify_code: verifyCode } : {}),
92
+ })}`, { signal, timeoutMs: 40_000 }),
93
+ getUpdates: (binding, signal) => request(binding.base_url, '/ilink/bot/getupdates', {
94
+ token: binding.token, body: { get_updates_buf: binding.cursor }, signal, timeoutMs: 40_000,
95
+ }),
96
+ getConfig: (binding, signal) => request(binding.base_url, '/ilink/bot/getconfig', {
97
+ token: binding.token, signal, timeoutMs: 5000,
98
+ body: { ilink_user_id: binding.peer_id, context_token: binding.context_token || undefined },
99
+ }),
100
+ sendTyping: (binding, ticket, status, signal) => request(binding.base_url, '/ilink/bot/sendtyping', {
101
+ token: binding.token, signal, timeoutMs: 5000, allowEmpty: true,
102
+ body: { ilink_user_id: binding.peer_id, typing_ticket: ticket, status },
103
+ }),
104
+ sendText: (binding, delivery, signal) => request(binding.base_url, '/ilink/bot/sendmessage', {
105
+ token: binding.token, signal, sending: true,
106
+ body: { msg: {
107
+ from_user_id: '', to_user_id: binding.peer_id, client_id: delivery.id,
108
+ message_type: 2, message_state: 2, context_token: binding.context_token || undefined,
109
+ item_list: [{ type: 1, text_item: { text: delivery.text } }],
110
+ } },
111
+ }),
112
+ };
113
+ }
@@ -0,0 +1,80 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createWeixinAPI, weixinOrigin } from './api.js';
3
+
4
+ const binding = { base_url: 'https://ilinkai.weixin.qq.com', token: 'test-token', peer_id: 'owner', cursor: 'cursor', context_token: 'context' };
5
+
6
+ describe('Weixin wire transport', () => {
7
+ it('uses QR POST, app headers and private local-token hints without bot authorization', async () => {
8
+ const fetchImpl = vi.fn(async () => Response.json({ qrcode: 'opaque', qrcode_img_content: 'https://example.com/qr' }));
9
+ await createWeixinAPI({ fetchImpl }).getQRCode(undefined, ['existing']);
10
+ const [url, init] = fetchImpl.mock.calls[0];
11
+ expect(url).toBe('https://ilinkai.weixin.qq.com/ilink/bot/get_bot_qrcode?bot_type=3');
12
+ expect(init.method).toBe('POST');
13
+ expect(init.headers.Authorization).toBeUndefined();
14
+ expect(init.redirect).toBe('error');
15
+ expect(JSON.parse(init.body)).toEqual({ local_token_list: ['existing'] });
16
+ });
17
+
18
+ it('preserves uint64 message IDs and passes cursor, owner and context through the text API', async () => {
19
+ const fetchImpl = vi.fn(async (url) => url.endsWith('getupdates')
20
+ ? new Response('{"ret":0,"msgs":[{"message_id":18446744073709551615}],"get_updates_buf":"next"}')
21
+ : Response.json({ ret: 0 }));
22
+ const api = createWeixinAPI({ fetchImpl });
23
+ expect((await api.getUpdates(binding)).msgs[0].message_id).toBe('18446744073709551615');
24
+ await api.sendText(binding, { id: 'delivery-id', text: '你好' });
25
+ const [, init] = fetchImpl.mock.calls[1];
26
+ expect(init.headers.Authorization).toBe('Bearer test-token');
27
+ expect(init.headers.AuthorizationType).toBe('ilink_bot_token');
28
+ expect(JSON.parse(init.body)).toMatchObject({
29
+ base_info: { bot_agent: 'Yuri' },
30
+ msg: { client_id: 'delivery-id', to_user_id: 'owner', context_token: 'context', item_list: [{ type: 1, text_item: { text: '你好' } }] },
31
+ });
32
+ });
33
+
34
+ it('does not treat HTTP 200 with a failed business code as delivered', async () => {
35
+ const api = createWeixinAPI({ fetchImpl: async () => Response.json({ ret: -2, errmsg: 'private upstream body' }) });
36
+ await expect(api.sendText(binding, { id: 'id', text: 'reply' })).rejects.toMatchObject({ code: 'reply_unavailable', ret: -2, ambiguous: false });
37
+ const expired = createWeixinAPI({ fetchImpl: async () => Response.json({ ret: -14 }) });
38
+ await expect(expired.getUpdates(binding)).rejects.toMatchObject({ code: 'auth_expired' });
39
+ });
40
+
41
+ it('requests a per-user ticket and sends start/cancel with authenticated bot metadata', async () => {
42
+ const fetchImpl = vi.fn(async (url) => url.endsWith('getconfig')
43
+ ? Response.json({ ret: 0, typing_ticket: 'test-ticket' }) : new Response(null, { status: 204 }));
44
+ const api = createWeixinAPI({ fetchImpl });
45
+ const signal = new AbortController().signal;
46
+ const config = await api.getConfig(binding, signal);
47
+ await api.sendTyping(binding, config.typing_ticket, 1, signal);
48
+ await api.sendTyping(binding, config.typing_ticket, 2);
49
+ expect(fetchImpl.mock.calls.map(([url]) => new URL(url).pathname)).toEqual([
50
+ '/ilink/bot/getconfig', '/ilink/bot/sendtyping', '/ilink/bot/sendtyping',
51
+ ]);
52
+ expect(JSON.parse(fetchImpl.mock.calls[0][1].body)).toEqual({
53
+ ilink_user_id: 'owner', context_token: 'context', base_info: { channel_version: '2.4.10', bot_agent: 'Yuri' },
54
+ });
55
+ for (const [index, status] of [[1, 1], [2, 2]]) {
56
+ const init = fetchImpl.mock.calls[index][1];
57
+ expect(init.headers.Authorization).toBe('Bearer test-token');
58
+ expect(JSON.parse(init.body)).toMatchObject({ ilink_user_id: 'owner', typing_ticket: 'test-ticket', status });
59
+ }
60
+ });
61
+
62
+ it('does not ignore failed typing business codes or accept an empty ticket response as valid JSON', async () => {
63
+ const failed = createWeixinAPI({ fetchImpl: async () => Response.json({ ret: -2 }) });
64
+ await expect(failed.sendTyping(binding, 'ticket', 1)).rejects.toMatchObject({ code: 'upstream_error' });
65
+ const empty = createWeixinAPI({ fetchImpl: async () => new Response('') });
66
+ await expect(empty.getConfig(binding)).rejects.toMatchObject({ code: 'invalid_response' });
67
+ await expect(empty.sendTyping(binding, 'ticket', 2)).resolves.toEqual({});
68
+ });
69
+
70
+ it('distinguishes uncertain send failures and never exposes upstream credentials', async () => {
71
+ const api = createWeixinAPI({ fetchImpl: async () => { throw new Error('test-token context secret'); } });
72
+ await expect(api.sendText(binding, { id: 'id', text: 'reply' })).rejects.toMatchObject({ message: 'network_error', ambiguous: true });
73
+ await expect(api.getUpdates(binding)).rejects.toMatchObject({ ambiguous: false });
74
+ });
75
+
76
+ it.each(['http://ilinkai.weixin.qq.com', 'https://evil.example', 'https://ilinkai.weixin.qq.com.evil.example',
77
+ 'https://user:password@ilinkai.weixin.qq.com', 'https://ilinkai.weixin.qq.com:8443', 'https://ilinkai.weixin.qq.com/path'])('rejects credential redirects to %s', (url) => {
78
+ expect(() => weixinOrigin(url)).toThrow('invalid_response');
79
+ });
80
+ });
@@ -0,0 +1,24 @@
1
+ const failureStatus = (code) => code === 'channel_disabled' ? 403 : code === 'not_found' ? 404
2
+ : ['account_in_use', 'already_bound', 'channel_in_use', 'binding_changed'].includes(code) ? 409
3
+ : ['network_error', 'upstream_error', 'invalid_response'].includes(code) ? 502 : 400;
4
+
5
+ /** Runs behind the Host's existing authenticated Yuri route gate. No public webhook. */
6
+ export function registerWeixinRoutes(app, runtime) {
7
+ const root = '/api/yuri/assistants/:assistantID/weixin';
8
+ const respond = (res, work) => {
9
+ res.setHeader('Cache-Control', 'no-store');
10
+ Promise.resolve().then(work).then((body) => res.json(body)).catch((error) => {
11
+ const allowed = new Set(['not_found', 'account_in_use', 'already_bound', 'channel_in_use', 'channel_disabled', 'binding_changed', 'network_error',
12
+ 'upstream_error', 'invalid_response', 'validation_error', 'auth_expired', 'cancelled']);
13
+ const code = allowed.has(error?.code) ? error.code : 'channel_error';
14
+ // Never return upstream bodies, credentials or QR-status payloads as errors.
15
+ res.status(failureStatus(code)).json({ error: code });
16
+ });
17
+ };
18
+ app.get(root, (req, res) => respond(res, () => runtime.status(req.params.assistantID)));
19
+ app.post(`${root}/login`, (req, res) => respond(res, () => runtime.startLogin(req.params.assistantID, req.body?.language)));
20
+ app.post(`${root}/verify`, (req, res) => respond(res, () => runtime.verify(req.params.assistantID, req.body?.code)));
21
+ app.post(`${root}/retry`, (req, res) => respond(res, () => runtime.retry(req.params.assistantID)));
22
+ app.post(`${root}/transfer`, (req, res) => respond(res, () => runtime.transfer(req.params.assistantID, req.body)));
23
+ app.delete(root, (req, res) => respond(res, () => runtime.disconnect(req.params.assistantID)));
24
+ }
@@ -0,0 +1,71 @@
1
+ import express from 'express';
2
+ import request from 'supertest';
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { registerWeixinRoutes } from './routes.js';
5
+ import { createWeixinRuntime } from './runtime.js';
6
+
7
+ describe('authenticated Bot WeChat routes', () => {
8
+ it('reports a disabled channel and blocks direct mutation requests, not only UI buttons', async () => {
9
+ const app = express();
10
+ app.use(express.json());
11
+ const runtime = createWeixinRuntime({ env: { NODE_ENV: 'development' } });
12
+ registerWeixinRoutes(app, runtime);
13
+ const root = '/api/yuri/assistants/bot/weixin';
14
+ const response = await request(app).get(root).expect(200);
15
+ expect(response.body).toEqual({ status: 'disabled', error: null });
16
+ for (const action of ['login', 'verify', 'retry', 'transfer']) {
17
+ const result = await request(app).post(`${root}/${action}`).send({}).expect(403);
18
+ expect(result.body).toEqual({ error: 'channel_disabled' });
19
+ }
20
+ await request(app).delete(root).expect(403);
21
+ await runtime.close();
22
+ });
23
+
24
+ it('keeps the existing authentication boundary, has explicit routes and no-store QR responses', async () => {
25
+ const app = express();
26
+ app.use(express.json());
27
+ app.use('/api/yuri', (req, res, next) => req.headers.authorization === 'Bearer test-owner' ? next() : res.sendStatus(401));
28
+ const runtime = {
29
+ status: vi.fn(() => ({ status: 'disconnected', error: null })),
30
+ startLogin: vi.fn(async () => ({ status: 'waiting', qrCode: 'https://example.com/scan', error: null })),
31
+ verify: vi.fn(() => ({ status: 'verify', error: null })),
32
+ retry: vi.fn(() => ({ status: 'connected', error: null })),
33
+ disconnect: vi.fn(() => ({ status: 'disconnected', error: null })),
34
+ transfer: vi.fn(async () => ({ status: 'connected', error: null })),
35
+ };
36
+ registerWeixinRoutes(app, runtime);
37
+ const root = '/api/yuri/assistants/bot/weixin';
38
+ await request(app).post(`${root}/login`).send({}).expect(401);
39
+ expect(runtime.startLogin).not.toHaveBeenCalled();
40
+ const response = await request(app).post(`${root}/login`).auth('test-owner', { type: 'bearer' }).send({ language: 'zh-CN' }).expect(200);
41
+ expect(response.headers['cache-control']).toBe('no-store');
42
+ expect(response.body).toMatchObject({ status: 'waiting' });
43
+ expect(runtime.startLogin).toHaveBeenCalledWith('bot', 'zh-CN');
44
+ await request(app).post(`${root}/verify`).auth('test-owner', { type: 'bearer' }).send({ code: '123456' }).expect(200);
45
+ expect(runtime.verify).toHaveBeenCalledWith('bot', '123456');
46
+ await request(app).delete(root).auth('test-owner', { type: 'bearer' }).expect(200);
47
+ expect(runtime.disconnect).toHaveBeenCalledWith('bot');
48
+ await request(app).post(`${root}/transfer`).send({ sourceAssistantID: 'old', revision: 'r1' }).expect(401);
49
+ expect(runtime.transfer).not.toHaveBeenCalled();
50
+ await request(app).post(`${root}/transfer`).auth('test-owner', { type: 'bearer' })
51
+ .send({ sourceAssistantID: 'old', revision: 'r1', language: 'zh-CN' }).expect('Cache-Control', 'no-store').expect(200);
52
+ expect(runtime.transfer).toHaveBeenCalledWith('bot', { sourceAssistantID: 'old', revision: 'r1', language: 'zh-CN' });
53
+ });
54
+
55
+ it('reports stale move confirmations as conflicts without leaking binding credentials', async () => {
56
+ const app = express();
57
+ registerWeixinRoutes(app, { transfer: () => { throw Object.assign(new Error('private-token'), { code: 'binding_changed' }); } });
58
+ const result = await request(app).post('/api/yuri/assistants/bot/weixin/transfer').expect(409);
59
+ expect(result.body).toEqual({ error: 'binding_changed' });
60
+ });
61
+
62
+ it('redacts untrusted errors and reports binding conflicts as conflicts', async () => {
63
+ const app = express();
64
+ registerWeixinRoutes(app, { status: () => { throw new Error('credential=private-token'); },
65
+ startLogin: () => { throw Object.assign(new Error('private upstream response'), { code: 'account_in_use' }); } });
66
+ const response = await request(app).get('/api/yuri/assistants/bot/weixin').expect(400);
67
+ expect(response.body).toEqual({ error: 'channel_error' });
68
+ const conflict = await request(app).post('/api/yuri/assistants/bot/weixin/login').expect(409);
69
+ expect(conflict.body).toEqual({ error: 'account_in_use' });
70
+ });
71
+ });