@saltpub/agent-autoloop 0.0.0-stage → 0.1.2

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 (171) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/INSTALL.md +118 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +264 -0
  5. package/README.md +260 -2
  6. package/SECURITY.md +48 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/backup.js +144 -0
  9. package/dist/cli/explain.js +84 -0
  10. package/dist/cli/main.js +1016 -0
  11. package/dist/cli/mcp.js +151 -0
  12. package/dist/cli/runs.js +40 -0
  13. package/dist/cli/spend.js +21 -0
  14. package/dist/cli/status.js +304 -0
  15. package/dist/cli/try.js +6 -0
  16. package/dist/cli/uninstall.js +84 -0
  17. package/dist/cli/update.js +65 -0
  18. package/dist/cli/why.js +115 -0
  19. package/dist/host/background-launcher.js +12 -0
  20. package/dist/host/background.js +24 -0
  21. package/dist/host/channels.js +4 -0
  22. package/dist/host/command.js +98 -0
  23. package/dist/host/config.js +37 -0
  24. package/dist/host/files.js +22 -0
  25. package/dist/host/home.js +5 -0
  26. package/dist/host/http.js +43 -0
  27. package/dist/host/launcher.js +188 -0
  28. package/dist/host/lines.js +15 -0
  29. package/dist/host/node-path.js +33 -0
  30. package/dist/host/npm.js +28 -0
  31. package/dist/host/plugins.js +26 -0
  32. package/dist/host/program.js +14 -0
  33. package/dist/host/runtime.js +179 -0
  34. package/dist/host/server.js +159 -0
  35. package/dist/host/service.js +325 -0
  36. package/dist/host/state.js +203 -0
  37. package/dist/host/up.js +162 -0
  38. package/dist/host/update.js +286 -0
  39. package/dist/host/version.js +81 -0
  40. package/dist/kernel/card-page.js +54 -0
  41. package/dist/kernel/credentials.js +16 -0
  42. package/dist/kernel/cron.js +135 -0
  43. package/dist/kernel/decide.js +826 -0
  44. package/dist/kernel/due.js +73 -0
  45. package/dist/kernel/errors.js +9 -0
  46. package/dist/kernel/evolve.js +264 -0
  47. package/dist/kernel/http.js +357 -0
  48. package/dist/kernel/query.js +202 -0
  49. package/dist/kernel/rules.js +20 -0
  50. package/dist/kernel/store.js +52 -0
  51. package/dist/plugins/acp/agent.js +32 -0
  52. package/dist/plugins/acp/bridge.js +204 -0
  53. package/dist/plugins/claude/agent.js +113 -0
  54. package/dist/plugins/codex/agent.js +105 -0
  55. package/dist/plugins/command/agent.js +25 -0
  56. package/dist/plugins/delivery/action.js +25 -0
  57. package/dist/plugins/delivery/agent.js +13 -0
  58. package/dist/plugins/delivery/delivery.js +388 -0
  59. package/dist/plugins/delivery/github.js +201 -0
  60. package/dist/plugins/delivery/handoff.js +50 -0
  61. package/dist/plugins/delivery/input.js +47 -0
  62. package/dist/plugins/delivery/poll.js +72 -0
  63. package/dist/plugins/delivery/project.js +144 -0
  64. package/dist/plugins/delivery/review-ledger.js +82 -0
  65. package/dist/plugins/delivery/review-policy.js +99 -0
  66. package/dist/plugins/delivery/review.js +280 -0
  67. package/dist/plugins/delivery/run.js +204 -0
  68. package/dist/plugins/desktop/channel.js +94 -0
  69. package/dist/plugins/dsh/agent.js +116 -0
  70. package/dist/plugins/feishu/channel.js +245 -0
  71. package/dist/plugins/github/source.js +30 -0
  72. package/dist/plugins/gitlab/source.js +30 -0
  73. package/dist/plugins/omp/agent.js +3 -0
  74. package/dist/plugins/opencode/agent.js +88 -0
  75. package/dist/plugins/pi/agent.js +92 -0
  76. package/dist/plugins/webhook/channel.js +70 -0
  77. package/dist/plugins/webhook/templates.js +34 -0
  78. package/dist/plugins/xiaojiu/channel.js +410 -0
  79. package/dist/plugins/zcode/agent.js +102 -0
  80. package/dist/protocol/client.js +56 -0
  81. package/dist/protocol/conformance.js +184 -0
  82. package/dist/protocol/job.js +1 -0
  83. package/dist/protocol/rules.js +230 -0
  84. package/dist/protocol/schema.js +70 -0
  85. package/dist/protocol/schema.json +985 -0
  86. package/dist/protocol/validate.js +150 -0
  87. package/dist/worker/agents.js +47 -0
  88. package/dist/worker/contract.js +178 -0
  89. package/dist/worker/run.js +52 -0
  90. package/dist/worker/usage.js +45 -0
  91. package/dist/worker/windows.ps1 +48 -0
  92. package/dist/worker/worker.js +595 -0
  93. package/docs/architecture.en.svg +178 -0
  94. package/docs/architecture.svg +178 -0
  95. package/docs/auto-update.md +53 -0
  96. package/docs/plugins.md +139 -0
  97. package/docs/protocol.md +582 -0
  98. package/docs/state-machines.md +77 -0
  99. package/examples/channel.sh +15 -0
  100. package/examples/plugins/hello-agent/agent.ts +40 -0
  101. package/examples/plugins/hello-channel/channel.ts +54 -0
  102. package/examples/plugins/hello-source/source.ts +19 -0
  103. package/examples/recipes/browser-handoff/README.md +44 -0
  104. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  105. package/examples/recipes/browser-handoff/browser.json +10 -0
  106. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  107. package/examples/recipes/browser-handoff/rules.json +19 -0
  108. package/examples/recipes/feedback/README.md +34 -0
  109. package/examples/recipes/feedback/SKILL.md +22 -0
  110. package/examples/recipes/feedback/event.json +8 -0
  111. package/examples/recipes/feedback/rules.json +37 -0
  112. package/examples/recipes/feishu-brief/README.md +28 -0
  113. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  114. package/examples/recipes/feishu-brief/collect.ts +164 -0
  115. package/examples/recipes/feishu-brief/rules.json +57 -0
  116. package/examples/recipes/feishu-brief/sources.json +13 -0
  117. package/examples/recipes/github-issues/README.md +17 -0
  118. package/examples/recipes/github-issues/SKILL.md +18 -0
  119. package/examples/recipes/github-issues/rules.json +30 -0
  120. package/examples/recipes/inbox-triage/README.md +36 -0
  121. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  122. package/examples/recipes/inbox-triage/collect.ts +191 -0
  123. package/examples/recipes/inbox-triage/rules.json +57 -0
  124. package/examples/recipes/inbox-triage/sources.json +8 -0
  125. package/examples/recipes/morning-brief/README.md +17 -0
  126. package/examples/recipes/morning-brief/SKILL.md +17 -0
  127. package/examples/recipes/morning-brief/rules.json +16 -0
  128. package/examples/recipes/ops-alerts/README.md +18 -0
  129. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  130. package/examples/recipes/ops-alerts/restart.sh +5 -0
  131. package/examples/recipes/ops-alerts/rules.json +29 -0
  132. package/examples/recipes/website-watch/README.md +26 -0
  133. package/examples/recipes/website-watch/SKILL.md +19 -0
  134. package/examples/recipes/website-watch/check.ts +86 -0
  135. package/examples/recipes/website-watch/rules.json +56 -0
  136. package/examples/recipes/website-watch/site.json +6 -0
  137. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  138. package/examples/watch-github-issues.sh +23 -0
  139. package/examples/worker.sh +18 -0
  140. package/package.json +55 -4
  141. package/plugins/acp/agent.ts +31 -0
  142. package/plugins/acp/bridge.ts +190 -0
  143. package/plugins/claude/agent.ts +121 -0
  144. package/plugins/codex/agent.ts +103 -0
  145. package/plugins/command/agent.ts +25 -0
  146. package/plugins/delivery/action.ts +29 -0
  147. package/plugins/delivery/action.yml +28 -0
  148. package/plugins/delivery/agent.ts +15 -0
  149. package/plugins/delivery/delivery.ts +408 -0
  150. package/plugins/delivery/github.ts +207 -0
  151. package/plugins/delivery/handoff.ts +72 -0
  152. package/plugins/delivery/input.ts +55 -0
  153. package/plugins/delivery/poll.ts +65 -0
  154. package/plugins/delivery/project.ts +161 -0
  155. package/plugins/delivery/review-ledger.ts +90 -0
  156. package/plugins/delivery/review-policy.ts +126 -0
  157. package/plugins/delivery/review.ts +324 -0
  158. package/plugins/delivery/run.ts +219 -0
  159. package/plugins/desktop/channel.ts +100 -0
  160. package/plugins/dsh/agent.ts +100 -0
  161. package/plugins/feishu/channel.ts +243 -0
  162. package/plugins/github/source.ts +33 -0
  163. package/plugins/gitlab/source.ts +32 -0
  164. package/plugins/omp/agent.ts +4 -0
  165. package/plugins/opencode/agent.ts +78 -0
  166. package/plugins/pi/agent.ts +80 -0
  167. package/plugins/webhook/channel.ts +74 -0
  168. package/plugins/webhook/templates.ts +32 -0
  169. package/plugins/xiaojiu/channel.ts +426 -0
  170. package/plugins/zcode/agent.ts +96 -0
  171. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,32 @@
1
+ // Vendor message formats: links are listed in protocol.md so the fields can be checked against their owning APIs.
2
+ function wecomMarkdown(text: string) {
3
+ return text.replace(/https?:\/\/[^\s;,。]+/g, (url, offset, source) =>
4
+ source.slice(Math.max(0, offset - 2), offset) === "](" ? url : `[打开链接](${url})`,
5
+ );
6
+ }
7
+
8
+ export function payload(platform: string, text: string): object {
9
+ if (platform === "discord" && [...text].length > 2000) throw new Error("Discord 消息超过 2000 个字,请缩短卡片");
10
+ const markdown = platform === "wecom" ? wecomMarkdown(text) : "";
11
+ if (platform === "wecom" && Buffer.byteLength(markdown) > 2048) throw new Error("企微消息超过 2048 字节,请缩短卡片");
12
+ switch (platform) {
13
+ case "dingtalk":
14
+ return { msgtype: "text", text: { content: text }, at: { isAtAll: false } };
15
+ case "wecom":
16
+ return { msgtype: "markdown", markdown: { content: markdown } };
17
+ case "slack":
18
+ return { text, mrkdwn: false, unfurl_links: false, unfurl_media: false };
19
+ case "discord":
20
+ return { content: text, allowed_mentions: { parse: [] } };
21
+ default:
22
+ throw new Error(`没有这个 Webhook 模板:${platform}`);
23
+ }
24
+ }
25
+
26
+ export async function accepted(platform: string, response: Response) {
27
+ if (!response.ok) throw new Error(`返回 ${response.status}`);
28
+ if (platform === "dingtalk" || platform === "wecom") {
29
+ const result = await response.json();
30
+ if (result.errcode !== 0) throw new Error(`发送失败:${result.errmsg ?? result.errcode}`);
31
+ } else if (platform === "slack" && (await response.text()).trim() !== "ok") throw new Error("Slack 没有确认收到消息");
32
+ }
@@ -0,0 +1,426 @@
1
+ // Xiaojiu (4399 IM) over its REST API. Without a webhook it posts words and a link — pair it with "links": true in
2
+ // rules.json so the link itself can answer that one card. With a webhook it posts card messages whose buttons come back
3
+ // as `card_action_trigger` callbacks; there is no signature, so the path has to be unguessable, reachable only through
4
+ // HTTPS in front of it, and the clicker has to be in this channel's answerers. Several bots may share one listener: the
5
+ // callback's header.appId decides which channel answers. The send API has no idempotency key, so a lost delivery report
6
+ // can make a second message. Card messages are updated in place from the session the send response or the click carries;
7
+ // markdown bodies cannot be patched, so those only report the new version. API contract: https://im-document.4399om.com
8
+ // config.json: "channels": { "xiaojiu": { "use": "xiaojiu", "key": "…", "appId": "…", "appSecret": "…",
9
+ // "session": "<snSessionId>" } } — or "staffNo": "GZ1234" for a private chat
10
+ // optional "webhook": { "listen": "0.0.0.0:9700", "path": "/xiaojiu/<unguessable>" }
11
+ // rules.json: "channels": { "xiaojiu": { "name": "小九", "links": true, "answerers": ["GZ1234"] } }
12
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
13
+ import type { Card, ChannelContext } from "../../host/channels.ts";
14
+
15
+ // The platform's business code for "too fast": the manual says to wait and try again.
16
+ const RATE_LIMITED = 4029;
17
+ // The platform keeps retrying a callback it can't deliver, so a body that big is a mistake, not a message.
18
+ const WEBHOOK_BODY_LIMIT = 256 * 1024;
19
+
20
+ function words(card: Card) {
21
+ const source = card.rule && card.rule !== card.title ? `来源:${card.rule}` : "";
22
+ const choices = card.options.map((option, index) => `${index + 1}. ${option}`).join("\n");
23
+ const parts = [card.title, source, card.text, ...(card.state === "open" ? [choices, card.link] : [])];
24
+ return parts.filter(Boolean).join("\n\n");
25
+ }
26
+
27
+ function delay(milliseconds: number) {
28
+ const { promise, resolve } = Promise.withResolvers<void>();
29
+ setTimeout(resolve, milliseconds);
30
+ return promise;
31
+ }
32
+
33
+ type Click = { card: number; choice?: number; by: string; ref: string; session?: string };
34
+ type Route = {
35
+ appId: string;
36
+ path: string;
37
+ log: (line: string) => void;
38
+ answer: (click: Click) => Promise<void>;
39
+ };
40
+ type Listener = { server: Server; url: string; routes: Set<Route> };
41
+
42
+ // A listener is per `webhook.listen`, not per channel: one bot per route, several routes on one port. Bots that share a
43
+ // port and a path are told apart by header.appId, which is the only thing the callback says about which app it came to.
44
+ const listeners = new Map<string, Promise<Listener>>();
45
+
46
+ function parseListen(value: string) {
47
+ const match = /^\[([0-9a-fA-F:.]+)\]:([0-9]+)$/.exec(value) ?? /^([^:\s]+):([0-9]+)$/.exec(value);
48
+ if (!match) throw new Error(`webhook.listen 要写成 主机:端口(IPv6 用 [地址]:端口):${value}`);
49
+ const port = Number(match[2]);
50
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
51
+ throw new Error(`webhook.listen 的端口要在 1 到 65535 之间:${value}`);
52
+ }
53
+ return { host: match[1], port };
54
+ }
55
+
56
+ function bind(listen: string): Promise<Listener> {
57
+ const { host, port } = parseListen(listen);
58
+ const { promise, resolve, reject } = Promise.withResolvers<Listener>();
59
+ const server = createServer();
60
+ const listener: Listener = { server, url: "", routes: new Set() };
61
+ server.on("request", (request, response) => {
62
+ void handleRequest(request, response, listener).catch(() =>
63
+ reply(response, 500, { error: "internal server error" }),
64
+ );
65
+ });
66
+ server.once("error", reject);
67
+ server.listen(port, host, () => {
68
+ server.off("error", reject);
69
+ server.on("error", (error) => {
70
+ for (const route of listener.routes) route.log(`webhook 出错:${error}`);
71
+ });
72
+ const address = server.address();
73
+ if (!address || typeof address === "string") {
74
+ server.close();
75
+ reject(new Error("webhook 没有绑定到 TCP"));
76
+ return;
77
+ }
78
+ const shown = address.address.includes(":") ? `[${address.address}]` : address.address;
79
+ listener.url = `http://${shown}:${address.port}`;
80
+ resolve(listener);
81
+ });
82
+ return promise;
83
+ }
84
+
85
+ async function joinWebhook(
86
+ options: { listen?: unknown; path?: unknown },
87
+ appId: string,
88
+ log: (line: string) => void,
89
+ answer: (click: Click) => Promise<void>,
90
+ ) {
91
+ const listen = typeof options.listen === "string" ? options.listen.trim() : "";
92
+ const path = typeof options.path === "string" ? options.path.trim() : "";
93
+ if (!listen) throw new Error("webhook.listen 要写 主机:端口");
94
+ if (!path.startsWith("/") || /\s/.test(path)) throw new Error(`webhook.path 要以 / 开头、不含空白:${path}`);
95
+ let pending = listeners.get(listen);
96
+ if (!pending) {
97
+ pending = bind(listen);
98
+ listeners.set(listen, pending);
99
+ pending.catch(() => listeners.delete(listen));
100
+ }
101
+ const listener = await pending;
102
+ if ([...listener.routes].some((route) => route.appId === appId && route.path === path)) {
103
+ throw new Error(`webhook 已经有 appId ${appId} 在 ${path}`);
104
+ }
105
+ const route: Route = { appId, path, log, answer };
106
+ listener.routes.add(route);
107
+ log(`webhook 在 ${listener.url}${path} 收卡片回答(appId ${appId})`);
108
+ return async () => {
109
+ listener.routes.delete(route);
110
+ if (listener.routes.size) return;
111
+ listeners.delete(listen);
112
+ const { promise, resolve } = Promise.withResolvers<void>();
113
+ listener.server.close(() => resolve());
114
+ await promise;
115
+ };
116
+ }
117
+
118
+ async function handleRequest(request: IncomingMessage, response: ServerResponse, listener: Listener) {
119
+ try {
120
+ if (request.method !== "POST") return reply(response, 405, { error: "method not allowed" });
121
+ const contentType = request.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
122
+ if (contentType !== "application/json") {
123
+ return reply(response, 415, { error: "content-type must be application/json" });
124
+ }
125
+ const body = await readJson(request);
126
+ const header = record(body)?.header;
127
+ const appId = text(record(header)?.appId);
128
+ const pathname = new URL(request.url ?? "/", "http://webhook.local").pathname;
129
+ const route = [...listener.routes].find((candidate) => candidate.path === pathname && candidate.appId === appId);
130
+ if (!route) {
131
+ const known = [...listener.routes].some((candidate) => candidate.path === pathname);
132
+ return reply(response, known ? 403 : 404, { error: known ? "this appId isn't this path's bot" : "not found" });
133
+ }
134
+ if (text(record(header)?.type) !== "card_action_trigger") return reply(response, 200, { ok: true });
135
+ const click = cardClick(body);
136
+ if (!click) {
137
+ route.log("xiaojiu 回调里没有能回答卡片的按钮信息,已忽略");
138
+ return reply(response, 200, { ok: true });
139
+ }
140
+ try {
141
+ await route.answer(click);
142
+ return reply(response, 200, { ok: true });
143
+ } catch (error) {
144
+ // A refused click would be refused again: retrying it just multiplies the logs. A hub that blinked gets retried.
145
+ const status = record(error)?.status;
146
+ route.log(`卡片 ${click.card} 的回答没转成:${error}`);
147
+ return reply(response, typeof status === "number" && status >= 400 && status < 500 ? 200 : 500, {
148
+ error: "answer not taken",
149
+ });
150
+ }
151
+ } catch (error) {
152
+ if (error instanceof BadRequest) return reply(response, error.status, { error: error.message });
153
+ return reply(response, 500, { error: "internal server error" });
154
+ }
155
+ }
156
+
157
+ class BadRequest extends Error {
158
+ readonly status: number;
159
+ constructor(status: number, message: string) {
160
+ super(message);
161
+ this.status = status;
162
+ }
163
+ }
164
+
165
+ async function readJson(request: IncomingMessage) {
166
+ const chunks: Buffer[] = [];
167
+ let size = 0;
168
+ for await (const chunk of request) {
169
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
170
+ size += buffer.length;
171
+ if (size > WEBHOOK_BODY_LIMIT) throw new BadRequest(413, "request body too large");
172
+ chunks.push(buffer);
173
+ }
174
+ if (!chunks.length) throw new BadRequest(400, "request body is required");
175
+ try {
176
+ return JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
177
+ } catch {
178
+ throw new BadRequest(400, "invalid JSON body");
179
+ }
180
+ }
181
+
182
+ function record(value: unknown) {
183
+ return value !== null && typeof value === "object" && !Array.isArray(value)
184
+ ? (value as Record<string, unknown>)
185
+ : undefined;
186
+ }
187
+
188
+ function text(value: unknown) {
189
+ return typeof value === "string" && value.length > 0 ? value : undefined;
190
+ }
191
+
192
+ /** The platform names a sent message's id differently across versions; every click names it msgId. */
193
+ function messageIdOf(envelope: unknown) {
194
+ const data = record(record(envelope)?.data);
195
+ const nested = record(data?.message);
196
+ return (
197
+ text(data?.msgId) ??
198
+ text(data?.messageId) ??
199
+ text(data?.message_id) ??
200
+ text(data?.id) ??
201
+ text(nested?.msgId) ??
202
+ text(nested?.messageId) ??
203
+ text(nested?.message_id) ??
204
+ text(nested?.id)
205
+ );
206
+ }
207
+
208
+ function reply(response: ServerResponse, status: number, body: unknown) {
209
+ response.writeHead(status, {
210
+ "content-type": "application/json; charset=utf-8",
211
+ "cache-control": "no-store",
212
+ "x-content-type-options": "nosniff",
213
+ });
214
+ response.end(JSON.stringify(body));
215
+ }
216
+
217
+ /** The button we drew carries the card and the option; the platform brings back who pressed it and which message. */
218
+ function cardClick(body: unknown): Click | null {
219
+ const event = record(record(body)?.event);
220
+ const operator = record(event?.operator);
221
+ const userId = record(operator?.userId);
222
+ const ref = text(event?.msgId) ?? text(event?.messageId);
223
+ const by = text(userId?.staffNo) ?? text(operator?.staffNo) ?? text(userId?.staffId) ?? text(operator?.staffId);
224
+ let value: unknown = record(event?.action)?.value;
225
+ if (typeof value === "string") {
226
+ try {
227
+ value = JSON.parse(value);
228
+ } catch {
229
+ return null;
230
+ }
231
+ }
232
+ const picked = record(value);
233
+ const card = picked?.card;
234
+ const choice = picked?.choice;
235
+ const session = text(event?.snSessionId);
236
+ if (typeof card !== "number" || !Number.isInteger(card) || !ref || !by) return null;
237
+ if (choice !== undefined && (typeof choice !== "number" || !Number.isInteger(choice))) return null;
238
+ return { card, ...(typeof choice === "number" ? { choice } : {}), by, ref, ...(session ? { session } : {}) };
239
+ }
240
+
241
+ /** What became of the card, shown in place of its buttons once it is settled. */
242
+ function outcome(card: Card) {
243
+ if (card.state === "open") return "";
244
+ if (card.kind === "notice") {
245
+ if (card.result) return card.answer ? `${card.result}:${card.answer}` : card.result;
246
+ return card.answer ?? "";
247
+ }
248
+ const chosen = card.choice === null ? card.answer : card.options[card.choice];
249
+ return [chosen ? `已选择:${chosen}` : "", card.result ? `结果:${card.result}` : ""].filter(Boolean).join("\n\n");
250
+ }
251
+
252
+ /** A card message: the title in the header, the words in the body, one button per option while it is open. */
253
+ function cardMessage(card: Card) {
254
+ const source = card.rule && card.rule !== card.title ? `来源:${card.rule}` : "";
255
+ const body = [source, card.text, outcome(card), card.state === "open" ? card.link : null]
256
+ .filter(Boolean)
257
+ .join("\n\n");
258
+ const elements: Record<string, unknown>[] = body ? [{ tag: "markdown", content: body }] : [];
259
+ if (card.state === "open") {
260
+ const buttons: Record<string, unknown>[] = card.options.map((option, index) => ({
261
+ tag: "button",
262
+ name: `option-${index}`,
263
+ text: { tag: "plain_text", content: option },
264
+ value: { card: card.id, choice: index },
265
+ }));
266
+ if (card.kind === "notice") {
267
+ buttons.push({
268
+ tag: "button",
269
+ name: "handled",
270
+ text: { tag: "plain_text", content: "已处理" },
271
+ value: { card: card.id },
272
+ });
273
+ }
274
+ if (buttons.length) elements.push({ tag: "hr" }, { tag: "action", actions: buttons });
275
+ }
276
+ if (!elements.length) elements.push({ tag: "markdown", content: card.title });
277
+ return {
278
+ config: {},
279
+ i18n_header: { zh_cn: { title: { tag: "plain_text", content: card.title } } },
280
+ i18n_elements: { zh_cn: elements },
281
+ };
282
+ }
283
+
284
+ export default async function xiaojiu({ hub, options, log, signal }: ChannelContext) {
285
+ const base = ((options.baseUrl as string | undefined) ?? "https://messenger-api.4399om.com").replace(/\/$/, "");
286
+ const appId = options.appId as string | undefined;
287
+ const appSecret = options.appSecret as string | undefined;
288
+ const session = options.session as string | undefined;
289
+ const staffNo = options.staffNo as string | undefined;
290
+ const webhook = options.webhook as { listen?: unknown; path?: unknown } | undefined;
291
+ if (!appId || !appSecret || (!session && !staffNo)) {
292
+ throw new Error("xiaojiu 通道要在 config.json 写 appId、appSecret,以及 session(群会话)或 staffNo(私聊工号)");
293
+ }
294
+
295
+ // A token lasts expires_in seconds, ask again a minute early, and once more when a call answers 401.
296
+ let cached: { value: string; until: number } | null = null;
297
+ async function clientToken(fresh = false): Promise<string> {
298
+ if (!fresh && cached && Date.now() < cached.until) return cached.value;
299
+ const query = new URLSearchParams({
300
+ grant_type: "client_credentials",
301
+ client_id: appId!,
302
+ client_secret: appSecret!,
303
+ });
304
+ const response = await fetch(`${base}/oauth2/client_token?${query}`, { signal: AbortSignal.timeout(30_000) });
305
+ const envelope = record(await response.json().catch(() => null));
306
+ const data = record(envelope?.data);
307
+ if (envelope?.code !== 200 || typeof data?.client_token !== "string") {
308
+ throw new Error(`xiaojiu 取令牌失败:${JSON.stringify(envelope ?? response.status).slice(0, 300)}`);
309
+ }
310
+ cached = { value: data.client_token, until: Date.now() + (Number(data.expires_in) - 60) * 1000 };
311
+ return cached.value;
312
+ }
313
+
314
+ async function post(path: string, body: unknown): Promise<unknown> {
315
+ let refreshed = false;
316
+ for (let tried = 0; ; tried++) {
317
+ const response = await fetch(`${base}${path}`, {
318
+ method: "POST",
319
+ headers: {
320
+ authorization: `Bearer ${await clientToken(refreshed)}`,
321
+ "content-type": "application/json; charset=utf-8",
322
+ },
323
+ body: JSON.stringify(body),
324
+ signal: AbortSignal.timeout(30_000),
325
+ });
326
+ const envelope = record(await response.json().catch(() => null));
327
+ const code = typeof envelope?.code === "number" ? envelope.code : response.status;
328
+ if (code === 401 && !refreshed) {
329
+ refreshed = true;
330
+ continue;
331
+ }
332
+ if (code === RATE_LIMITED && tried < 3) {
333
+ await delay(Math.min(2000, 200 * 2 ** tried));
334
+ continue;
335
+ }
336
+ if (code !== 200)
337
+ throw new Error(`xiaojiu ${path}: ${JSON.stringify(envelope ?? response.status).slice(0, 300)}`);
338
+ return envelope;
339
+ }
340
+ }
341
+
342
+ // Where each card message lives: the platform's message id -> its session, learned when we sent it.
343
+ const locations = new Map<string, string>();
344
+ let lastSession = session;
345
+
346
+ const leave = webhook
347
+ ? await joinWebhook(webhook, appId, log, (click) => {
348
+ // The hub wakes this channel's next card before the answer's response comes back, so record where the message
349
+ // lives first. Who may answer is the hub's call; the session names the conversation either way.
350
+ if (click.session) {
351
+ if (!locations.has(click.ref)) locations.set(click.ref, click.session);
352
+ lastSession ??= click.session;
353
+ }
354
+ return hub.answer(click.card, {
355
+ ...(click.choice === undefined ? {} : { choice: click.choice }),
356
+ by: click.by,
357
+ ref: click.ref,
358
+ });
359
+ })
360
+ : null;
361
+
362
+ try {
363
+ while (!signal.aborted) {
364
+ let card: Card | null;
365
+ try {
366
+ ({ card } = await hub.nextCard(50));
367
+ } catch (error) {
368
+ log(`couldn't reach the hub: ${error}`);
369
+ await delay(10_000);
370
+ continue;
371
+ }
372
+ if (!card) continue;
373
+ if (card.ref) {
374
+ const at = locations.get(card.ref) ?? lastSession;
375
+ if (webhook && at) {
376
+ try {
377
+ await post(`/open/im/v1/messages/${encodeURIComponent(at)}/${encodeURIComponent(card.ref)}/update`, {
378
+ msgType: "card",
379
+ title: card.title,
380
+ content: JSON.stringify(cardMessage(card)),
381
+ });
382
+ await hub.delivered(card.id, card.version, card.ref);
383
+ } catch (error) {
384
+ log(`card ${card.id} not updated: ${error}`);
385
+ await hub.failed(card.id, card.version, String(error)).catch(() => {});
386
+ }
387
+ } else {
388
+ await hub.delivered(card.id, card.version, card.ref);
389
+ }
390
+ continue;
391
+ }
392
+ try {
393
+ const envelope = await post(
394
+ "/open/im/v2/messages",
395
+ webhook
396
+ ? {
397
+ ...(session ? { snSessionId: session } : { receiveId: staffNo }),
398
+ msgType: "card",
399
+ title: card.title,
400
+ content: JSON.stringify(cardMessage(card)),
401
+ }
402
+ : {
403
+ ...(session ? { snSessionId: session } : { receiveId: staffNo }),
404
+ msgType: "markdown",
405
+ content: JSON.stringify({ md: words(card) }),
406
+ },
407
+ );
408
+ // The platform answers with the id it gave the message; a click names that same id, so it is the ref.
409
+ const data = record(record(envelope)?.data);
410
+ const sent = messageIdOf(envelope) ?? "";
411
+ const sentSession = text(data?.snSessionId);
412
+ if (webhook && !sent) throw new Error("发送卡片后没拿到 msgId:按钮的回答对不上这张卡片");
413
+ if (webhook && sentSession) {
414
+ locations.set(sent, sentSession);
415
+ lastSession = sentSession;
416
+ }
417
+ await hub.delivered(card.id, card.version, webhook ? sent : `sent-${card.id}`);
418
+ } catch (error) {
419
+ log(`card ${card.id} not sent: ${error}`);
420
+ await hub.failed(card.id, card.version, String(error)).catch(() => {});
421
+ }
422
+ }
423
+ } finally {
424
+ await leave?.();
425
+ }
426
+ }
@@ -0,0 +1,96 @@
1
+ // ZCode: the CLI bundle that ships with the desktop app, run headless. `-p` answers one prompt and prints one JSON
2
+ // object at the end: sessionId, response, and the tokens its provider used. A resumed turn passes --resume sess_…,
3
+ // and ZCode's own modes are the access setting: plan reads, edit lets it work, yolo doesn't ask at all.
4
+ //
5
+ // The object is written once at the end, so a run that dies leaves no session id. It counts as started as soon as its
6
+ // process is running; the one failure that may start a fresh session is a resume id ZCode doesn't know.
7
+ import { execFileSync } from "node:child_process";
8
+ import { commandLine } from "../../host/command.ts";
9
+ import { findProgram, tail, type Adapter, type Reading, type Usage } from "../../worker/agents.ts";
10
+
11
+ const MODE = { read: "plan", edit: "edit", full: "yolo" } as const;
12
+
13
+ /** The Windows package is a .cjs bundle: node has to start it, not the platform. A native launcher is used as it is. */
14
+ function launch(program: string) {
15
+ return /\.(?:cjs|mjs|js)$/i.test(program) ? [process.execPath, program] : [program];
16
+ }
17
+
18
+ /** The last complete JSON object in what it printed; the answer may come after a warning line. */
19
+ function lastJsonObject(text: string): any {
20
+ try {
21
+ const value = JSON.parse(text);
22
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
23
+ } catch {}
24
+ const end = text.lastIndexOf("}");
25
+ if (end < 0) return null;
26
+ // lastIndexOf with -1 still finds a brace at 0, so stop after trying the start of the text.
27
+ for (let start = text.lastIndexOf("{", end); start >= 0; start = start ? text.lastIndexOf("{", start - 1) : -1) {
28
+ try {
29
+ const value = JSON.parse(text.slice(start, end + 1));
30
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
31
+ } catch {}
32
+ }
33
+ return null;
34
+ }
35
+
36
+ /** The provider's per-turn tokens. `inputTokens` already includes what came from its cache, as Codex's does. */
37
+ function usageOf(value: any): Usage | undefined {
38
+ const raw = value?.usage;
39
+ if (!raw || typeof raw !== "object") return undefined;
40
+ const usage: Usage = {};
41
+ for (const [from, to] of [
42
+ ["inputTokens", "input"],
43
+ ["outputTokens", "output"],
44
+ ["cacheReadTokens", "cached"],
45
+ ] as const) {
46
+ if (typeof raw[from] === "number") usage[to] = raw[from];
47
+ }
48
+ return Object.keys(usage).length ? usage : undefined;
49
+ }
50
+
51
+ export default {
52
+ command: (turn) => [
53
+ ...launch(turn.program ?? findProgram("zcode")),
54
+ "--mode",
55
+ MODE[turn.access],
56
+ "--surface",
57
+ "terminal",
58
+ "--no-color",
59
+ "--json",
60
+ ...(turn.resume ? ["--resume", turn.resume] : []),
61
+ "-p",
62
+ turn.prompt,
63
+ ],
64
+ read(stdout, code, stderr): Reading {
65
+ const value = lastJsonObject(stdout);
66
+ if (value) {
67
+ const session = typeof value.sessionId === "string" && value.sessionId ? value.sessionId : undefined;
68
+ const usage = usageOf(value);
69
+ const text = typeof value.response === "string" ? value.response : "";
70
+ if (code !== null && code !== 0) {
71
+ return { session, usage, started: true, error: tail(stderr) || `退出码 ${code}:ZCode 没跑完这一轮` };
72
+ }
73
+ if (!text.trim()) return { session, usage, started: true, error: "ZCode 没有完成并留下实际结果" };
74
+ return { text, session, usage, started: true, finished: true };
75
+ }
76
+ if (code === null) return { started: true };
77
+ const said = tail(stderr);
78
+ // A session id the CLI doesn't know is the one case where a new one is right. Anything else that got this far may
79
+ // have done work, so it stays in the session it was told to go on in.
80
+ const lost = /session not found/i.test(said);
81
+ if (!said && code === 0) return { started: true, error: "ZCode 没有完成并留下实际结果" };
82
+ return { started: !lost, error: said || `退出码 ${code}:没留下原因` };
83
+ },
84
+ check(program) {
85
+ try {
86
+ execFileSync(...commandLine([...launch(program ?? findProgram("zcode")), "version"]), {
87
+ encoding: "utf8",
88
+ timeout: 20_000,
89
+ stdio: ["ignore", "pipe", "pipe"],
90
+ });
91
+ return null;
92
+ } catch (error) {
93
+ return `ZCode 用不了:用 zcode -p "hi" 跑一次看看(${(error as Error).message.split("\n")[0]})`;
94
+ }
95
+ },
96
+ } satisfies Adapter;