@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,100 @@
1
+ // DSH (DeepSeek Harness), 0.2.2 or newer: `dsh headless` answers one task and exits. With --json it prints one event per line:
2
+ // the opening `session` has the id a later turn goes on in, each `step_end` has that step's tokens, and the last line, `final`,
3
+ // has the answer and why the last turn ended. A turn can end with the run still going, waiting on background work that may
4
+ // start another turn, so only `final` says it's over. A resumed session keeps the permissions it was saved with unless told
5
+ // otherwise, so they're given every time; nobody is there to approve anything, so a call that needs it is refused rather than
6
+ // left waiting. It has no desktop session to open.
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
+ import { addUsage } from "../../protocol/validate.ts";
11
+
12
+ const PRESET = { read: "read-only", edit: "workspace-write", full: "danger-full-access" };
13
+ const NOT_FINISHED = "DSH 没跑完这一轮";
14
+ const NO_RESULT = "DSH 没有完成并留下实际结果";
15
+ const WHY_NOT: Record<string, string> = {
16
+ aborted: "这一轮被中止了",
17
+ blocked: "这一轮被卡住了,没有完成",
18
+ "max-tokens": "这一轮用完了输出上限",
19
+ };
20
+
21
+ /** dsh reports each step's tokens as inputTokens / outputTokens / cacheReadTokens / cacheWriteTokens. Its inputTokens
22
+ * leave out the cache's reads and writes; `input` counts all of it, as Codex's does. */
23
+ function stepUsage(reported: any): Usage | undefined {
24
+ if (!reported || typeof reported !== "object") return undefined;
25
+ const step: Usage = {};
26
+ const count = (value: unknown) => (typeof value === "number" ? value : 0);
27
+ if (typeof reported.inputTokens === "number")
28
+ step.input = reported.inputTokens + count(reported.cacheReadTokens) + count(reported.cacheWriteTokens);
29
+ if (typeof reported.outputTokens === "number") step.output = reported.outputTokens;
30
+ if (typeof reported.cacheReadTokens === "number") step.cached = reported.cacheReadTokens;
31
+ return Object.keys(step).length ? step : undefined;
32
+ }
33
+
34
+ export default {
35
+ command: (turn) => [
36
+ turn.program ?? findProgram("dsh"),
37
+ "headless",
38
+ "--json",
39
+ "--permission-mode",
40
+ PRESET[turn.access],
41
+ "--approval-policy",
42
+ "never",
43
+ ...(turn.resume ? ["--session-id", turn.resume] : []),
44
+ turn.prompt,
45
+ ],
46
+ read(stdout, code, stderr) {
47
+ let session: string | undefined;
48
+ let final: { text?: unknown; reason?: { kind?: string; error?: { message?: string } } | null } | undefined;
49
+ let failed: string | undefined;
50
+ let usage: Usage | undefined;
51
+ for (const line of stdout.split("\n")) {
52
+ let event: any;
53
+ try {
54
+ event = JSON.parse(line);
55
+ } catch {
56
+ continue;
57
+ }
58
+ // A login shell's profile prints here too, and `null` is valid JSON.
59
+ if (!event || typeof event !== "object") continue;
60
+ if (event.type === "session" && typeof event.sessionId === "string") session = event.sessionId;
61
+ else if (event.type === "status" && event.phase === "step_end") usage = addUsage(usage, stepUsage(event.usage));
62
+ else if (event.type === "final") final = event;
63
+ // With --json a mistake in how it was started goes here and nowhere else.
64
+ else if (event.type === "error" && typeof event.message === "string") failed = event.message;
65
+ }
66
+ const reading: Reading = { ...(session && { session }), ...(usage && { usage }) };
67
+ // It has this turn's prompt in a Session that's there. From here on the work may be half done, so a later turn goes
68
+ // on in the same Session instead of starting over.
69
+ if (session) reading.started = true;
70
+ if (final) {
71
+ reading.finished = true;
72
+ const kind = final.reason?.kind;
73
+ if (kind === "completed") {
74
+ if (typeof final.text === "string" && final.text.trim()) reading.text = final.text;
75
+ else reading.error = NO_RESULT;
76
+ } else if (kind === "error") reading.error = final.reason?.error?.message || NOT_FINISHED;
77
+ else reading.error = WHY_NOT[kind ?? ""] ?? NOT_FINISHED;
78
+ } else if (code !== null) {
79
+ const why = failed || tail(stderr);
80
+ if (code !== 0) reading.error = `退出码 ${code}:${why || "没留下原因"}`;
81
+ else reading.error = why || NO_RESULT;
82
+ }
83
+ return reading;
84
+ },
85
+ check(program) {
86
+ try {
87
+ const help = execFileSync(...commandLine([program ?? findProgram("dsh"), "headless", "--help"]), {
88
+ encoding: "utf8",
89
+ timeout: 20_000,
90
+ stdio: ["ignore", "pipe", "pipe"],
91
+ });
92
+ // The options this needs came in 0.2.2, and npm's `latest` is behind that for now.
93
+ if (!help.includes("--approval-policy"))
94
+ return "DSH 版本太旧,要 0.2.2 或更新:npm install -g @deepseek-ai/dsh@next --allow-scripts=koffi,node-pty,@deepseek-ai/dsh-subprocess-local";
95
+ return null;
96
+ } catch (error) {
97
+ return `DSH 用不了:运行 dsh headless "hi" 看看(${(error as Error).message.split("\n")[0]})`;
98
+ }
99
+ },
100
+ } satisfies Adapter;
@@ -0,0 +1,243 @@
1
+ // Feishu (Lark), through the official lark-cli: it holds the app's credentials and the long connection that brings
2
+ // clicks back, so this machine needs no public address. Only one listener can hold an app's card clicks, so run this in
3
+ // one place.
4
+ // "channels": { "feishu": { "key": "…", "user": "ou_xxx" } } in config.json
5
+ // "channels": { "feishu": { "name": "飞书", "answerers": ["ou_xxx"] } } in rules.json: who may answer.
6
+ import { execFile, spawn } from "node:child_process";
7
+ import { setTimeout as wait } from "node:timers/promises";
8
+ import type { Card, ChannelContext } from "../../host/channels.ts";
9
+ import { eachLine } from "../../host/lines.ts";
10
+ import { commandLine } from "../../host/command.ts";
11
+
12
+ /** Feishu sends these values as JSON in a string, which may be empty. */
13
+ function safeJson(text: unknown): any {
14
+ if (typeof text !== "string" || !text) return null;
15
+ try {
16
+ return JSON.parse(text);
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
22
+ function outcomeOf(card: Card) {
23
+ const chosen = card.choice === null ? card.answer : card.options[card.choice];
24
+ if (card.state === "decided") return `你选了「${chosen}」,已记录,等待处理。`;
25
+ if (card.state === "done") return `你选了「${chosen}」。${card.result ? `已执行:${card.result}` : "已执行。"}`;
26
+ if (card.state === "closed" && card.kind === "ask") return `不用决定了:${card.result ?? ""}`;
27
+ return card.state === "closed" && card.result ? card.result : null;
28
+ }
29
+
30
+ /** One card, as it looks now: the options while it's open, what became of it after. */
31
+ export function render(card: Card) {
32
+ const outcome = outcomeOf(card);
33
+ // Each option is a block across the card, its words wrapping: buttons in a row, one line high, cut long options off.
34
+ const option = (label: string, index: number) => ({
35
+ tag: "interactive_container",
36
+ width: "fill",
37
+ has_border: true,
38
+ border_color: index === card.recommend ? "blue" : "grey",
39
+ corner_radius: "8px",
40
+ padding: "8px 12px 8px 12px",
41
+ behaviors: [{ type: "callback", value: { card: card.id, choice: index } }],
42
+ elements: [{ tag: "div", text: { tag: "plain_text", content: label } }],
43
+ });
44
+ const afterwards = outcome ? [{ tag: "markdown", content: `**${outcome}**` }] : [];
45
+ const noteSaid =
46
+ card.kind === "notice" && card.answer
47
+ ? [{ tag: "div", text: { tag: "plain_text", content: `处理说明:${card.answer}` } }]
48
+ : [];
49
+ const notice = card.kind === "notice";
50
+ // Both forms submit `note`; an ask uses it as the answer, a notice records it when closing the card.
51
+ const textForm = [
52
+ {
53
+ tag: "form",
54
+ name: notice ? "handling_note" : `ask_text_${card.id}`,
55
+ elements: [
56
+ {
57
+ tag: "input",
58
+ name: "note",
59
+ input_type: "multiline_text",
60
+ rows: 2,
61
+ auto_resize: true,
62
+ max_length: 1000,
63
+ label: { tag: "plain_text", content: notice ? "处理说明(可不填)" : "选项都不合适,就直接写回答" },
64
+ label_position: "top",
65
+ placeholder: {
66
+ tag: "plain_text",
67
+ content: notice
68
+ ? "比如:已回复他视频下周发;或:群发广告,不用管"
69
+ : "写好点“提交文字”;写了再点选项,文字不会带上",
70
+ },
71
+ },
72
+ {
73
+ tag: "button",
74
+ name: notice ? `handling_note_submit_${card.id}` : `ask_text_submit_${card.id}`,
75
+ form_action_type: "submit",
76
+ type: notice ? "primary" : "default",
77
+ text: { tag: "plain_text", content: notice ? "记录并结案" : "提交文字" },
78
+ },
79
+ ],
80
+ },
81
+ ];
82
+ return {
83
+ schema: "2.0",
84
+ config: { update_multi: true, enable_forward: false },
85
+ header: {
86
+ title: { tag: "plain_text", content: card.title },
87
+ // Which rule or task it came from, in every state: cards from many places reach one person.
88
+ ...(card.rule && card.rule !== card.title
89
+ ? { subtitle: { tag: "plain_text", content: `来源:${card.rule}` } }
90
+ : {}),
91
+ template: card.state === "open" ? "blue" : card.state === "closed" ? "grey" : "green",
92
+ },
93
+ body: {
94
+ elements: [
95
+ ...(card.text ? [{ tag: "markdown", content: card.text }] : []),
96
+ ...(card.state === "open"
97
+ ? [...(notice ? textForm : []), ...card.options.map(option), ...(notice ? [] : textForm)]
98
+ : [...afterwards, ...noteSaid]),
99
+ ],
100
+ },
101
+ };
102
+ }
103
+
104
+ export default async function feishu({ hub, options, log, signal }: ChannelContext) {
105
+ const program = (options.lark as string | undefined) ?? "lark-cli";
106
+ const lark = async (args: string[], input?: string) => {
107
+ const printed = await new Promise<string>((resolve, reject) => {
108
+ const child = execFile(
109
+ ...commandLine([program, ...args]),
110
+ { encoding: "utf8", timeout: 60_000, signal },
111
+ (error, stdout) => (error ? reject(error) : resolve(stdout)),
112
+ );
113
+ child.stdin!.on("error", input === undefined ? () => {} : reject);
114
+ child.stdin!.end(input);
115
+ });
116
+ const out = JSON.parse(printed);
117
+ if (out.ok === false || out.error) {
118
+ throw new Error(`lark-cli ${args.slice(0, 3).join(" ")}: ${JSON.stringify(out.error ?? out).slice(0, 300)}`);
119
+ }
120
+ return out;
121
+ };
122
+ const owner = (options.user as string | undefined) ?? (await lark(["auth", "status"], "")).identities?.user?.openId;
123
+ if (!owner) throw new Error("飞书通道要在 config.json 写 user,或者先 lark-cli auth login");
124
+
125
+ const updateMessage = (ref: string, content: string) =>
126
+ lark(["im", "messages", "patch", "--message-id", ref, "--as", "bot", "--data", "-"], JSON.stringify({ content }));
127
+
128
+ /** Sends the card's words as a new message, or hands back the one an earlier try with this key already made. */
129
+ async function sendMessage(key: string, content: string) {
130
+ const target = ["--user-id", owner, "--as", "bot", "--msg-type", "interactive"];
131
+ const once = ["--idempotency-key", key];
132
+ return (await lark(["im", "+messages-send", ...target, ...once, "--content", content])).data.message_id as string;
133
+ }
134
+
135
+ async function deliver() {
136
+ while (!signal.aborted) {
137
+ let card: Card | null;
138
+ try {
139
+ ({ card } = await hub.nextCard(50));
140
+ } catch (error) {
141
+ log(`couldn't reach the hub: ${error}`);
142
+ await new Promise((resolve) => setTimeout(resolve, 10_000));
143
+ continue;
144
+ }
145
+ if (!card) continue;
146
+ try {
147
+ const content = JSON.stringify(render(card));
148
+ let ref = card.ref;
149
+ if (ref) {
150
+ try {
151
+ await updateMessage(ref, content);
152
+ } catch (error) {
153
+ // The bot may not be the sender of the message it is told to change, and Feishu refuses that outright. An open
154
+ // card stays as it is: the hub only counts answers on the message it first heard of, whose buttons still work.
155
+ if (card.state === "open") throw error;
156
+ // A settled one has no buttons: a second card is worse than one, a card frozen at the version before the answer
157
+ // is worse than both. The key has the version so that a retry of this one makes no third.
158
+ log(`card ${card.id}: couldn't update ${ref} (${error}); sending it again`);
159
+ await sendMessage(`agent-autoloop-card-${card.id}-v${card.version}`, content);
160
+ }
161
+ // The key is the card alone, not its version: a report that got lost must not make a second message.
162
+ } else ref = await sendMessage(`agent-autoloop-card-${card.id}`, content);
163
+ await hub.delivered(card.id, card.version, ref);
164
+ } catch (error) {
165
+ log(`card ${card.id} not sent: ${error}`);
166
+ await hub.failed(card.id, card.version, String(error)).catch(() => {});
167
+ }
168
+ }
169
+ }
170
+
171
+ /** Only the owner's click on the card that was sent counts; the hub checks both. */
172
+ async function clicked(line: string) {
173
+ const event = JSON.parse(line);
174
+ const form = safeJson(event.form_value);
175
+ const value = safeJson(event.action_value);
176
+ // A form's submit button can't carry a value, so its name holds the card's number.
177
+ const named = /^handling_note_submit_(\d+)$/.exec(String(event.action_name ?? ""));
178
+ const words = /^ask_text_submit_(\d+)$/.exec(String(event.action_name ?? ""));
179
+ const cardId = Number.isInteger(value?.card)
180
+ ? value.card
181
+ : named
182
+ ? Number(named[1])
183
+ : words
184
+ ? Number(words[1])
185
+ : null;
186
+ if (!Number.isInteger(cardId)) return;
187
+ const note = typeof form?.note === "string" ? form.note : undefined;
188
+ const given: { choice?: number; by?: string; ref?: string; text?: string } = {
189
+ by: event.operator_id,
190
+ ref: event.message_id,
191
+ };
192
+ if (words) {
193
+ // An ask card's text form answers with the words alone; an empty one is no answer at all.
194
+ if (!note || !note.trim()) return;
195
+ given.text = note;
196
+ } else {
197
+ // A notice's only option is that it's been handled, so submitting its form picks it.
198
+ const choice = Number.isInteger(value?.choice) ? value.choice : form ? 0 : null;
199
+ if (choice === null) return;
200
+ given.choice = choice;
201
+ if (note !== undefined) given.text = note;
202
+ }
203
+ const answer = await hub.answer(cardId, given);
204
+ const how = words ? "text submitted" : form ? "note submitted" : "answered";
205
+ log(`card ${cardId}: ${how} by ${event.operator_id}, ${answer.changed ? "counted" : "already settled"}`);
206
+ }
207
+
208
+ async function listen() {
209
+ // Feishu can go on counting a connection that's gone (often the one from before a restart) for hours, and lark-cli
210
+ // refuses every listener until it lets go; `event status` and `event stop` only reach this computer's bus.
211
+ let refused = false;
212
+ while (!signal.aborted) {
213
+ // stdin stays open: lark-cli ends an unbounded consume when its stdin closes.
214
+ const consume = spawn(...commandLine([program, "event", "consume", "card.action.trigger", "--as", "bot"]), {
215
+ stdio: ["pipe", "pipe", "pipe"],
216
+ });
217
+ // Unheard, this would end the whole hub. A process that never started still closes, which starts it again below.
218
+ consume.on("error", (error) => log(`the click listener couldn't run: ${error}`));
219
+ const stop = () => consume.kill();
220
+ signal.addEventListener("abort", stop);
221
+ let conflict = false;
222
+ eachLine(consume.stderr, (line) => {
223
+ if (/another event bus is already connected/.test(line)) conflict = true;
224
+ log(line);
225
+ });
226
+ eachLine(consume.stdout, (line) => void clicked(line).catch((error) => log(`click not handled: ${error}`)));
227
+ await new Promise((resolve) => consume.on("close", resolve));
228
+ signal.removeEventListener("abort", stop);
229
+ if (signal.aborted) break;
230
+ if (conflict && !refused) {
231
+ log(
232
+ "飞书那边还记着这个应用的另一条事件连接,拒绝再连:在它放开之前卡片点击收不到。" +
233
+ "常见于刚重启,旧连接可能要几个小时才放开;别的电脑也在跑这个应用的监听就先停掉它。1 分钟后再试,连上前不再重复这条。",
234
+ );
235
+ }
236
+ refused = conflict;
237
+ if (!conflict) log("the click listener stopped; starting it again in 10 seconds");
238
+ await wait(conflict ? 60_000 : 10_000, undefined, { signal }).catch(() => {});
239
+ }
240
+ }
241
+
242
+ await Promise.all([deliver(), listen()]);
243
+ }
@@ -0,0 +1,33 @@
1
+ // GitHub webhooks, checked against the repository's secret and turned into events: `issues.opened`,
2
+ // `pull_request.labeled`, `issue_comment.created` and so on, the object's number as the subject. In rules.json:
3
+ // "sources": { "github": { "name": "GitHub", "adapter": "github" } }, and AGENT_AUTOLOOP_SECRET_GITHUB in secrets.env.
4
+ import { createHmac, timingSafeEqual } from "node:crypto";
5
+ import { fit } from "../../worker/contract.ts";
6
+
7
+ type Input = { headers: Record<string, string | string[] | undefined>; body: string; secret: string };
8
+
9
+ export default function github({ headers, body, secret }: Input) {
10
+ const sign = `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
11
+ const given = String(headers["x-hub-signature-256"] ?? "");
12
+ const signed = secret && given.length === sign.length && timingSafeEqual(Buffer.from(given), Buffer.from(sign));
13
+ if (!signed) throw new Error("signature");
14
+ const kind = String(headers["x-github-event"] ?? "");
15
+ if (kind === "ping") return [];
16
+ const payload = JSON.parse(body);
17
+ const object = payload.pull_request ?? payload.issue ?? payload.discussion ?? payload.release ?? null;
18
+ const type = (payload.action ? `${kind}.${payload.action}` : kind).toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
19
+ const repo = String(payload.repository?.full_name ?? "");
20
+ const number = object?.number ? `#${object.number}` : "";
21
+ return [
22
+ {
23
+ id: String(headers["x-github-delivery"] ?? ""),
24
+ type,
25
+ subject: `${repo}${number}`.replace(/[^A-Za-z0-9#._:/@-]/g, "-").slice(0, 100),
26
+ summary: fit(String(payload.comment?.body ?? object?.title ?? payload.head_commit?.message ?? ""), 200),
27
+ detail: fit(String(payload.comment?.body ?? object?.body ?? ""), 4000),
28
+ link: encodeURI(
29
+ String(payload.comment?.html_url ?? object?.html_url ?? payload.repository?.html_url ?? ""),
30
+ ).slice(0, 500),
31
+ },
32
+ ];
33
+ }
@@ -0,0 +1,32 @@
1
+ // GitLab webhooks, checked against the project's secret token and turned into events: `merge_request.open`,
2
+ // `issue.close`, `push`, `note` and so on, the object's number as the subject. In rules.json:
3
+ // "sources": { "gitlab": { "name": "GitLab", "adapter": "gitlab" } }, and AGENT_AUTOLOOP_SECRET_GITLAB in secrets.env.
4
+ import { createHash, timingSafeEqual } from "node:crypto";
5
+ import { fit } from "../../worker/contract.ts";
6
+
7
+ type Input = { headers: Record<string, string | string[] | undefined>; body: string; secret: string };
8
+
9
+ export default function gitlab({ headers, body, secret }: Input) {
10
+ const given = String(headers["x-gitlab-token"] ?? "");
11
+ const signed = secret && given.length === secret.length && timingSafeEqual(Buffer.from(given), Buffer.from(secret));
12
+ if (!signed) throw new Error("signature");
13
+ const payload = JSON.parse(body);
14
+ const kind = String(payload.object_kind ?? headers["x-gitlab-event"] ?? "");
15
+ const attributes = payload.object_attributes ?? {};
16
+ const type = (attributes.action ? `${kind}.${attributes.action}` : kind).toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
17
+ const project = payload.project ?? {};
18
+ const repo = String(project.path_with_namespace ?? project.name ?? "");
19
+ const object = kind === "note" ? (payload.merge_request ?? payload.issue ?? attributes) : attributes;
20
+ const number = object.iid ? `#${object.iid}` : "";
21
+ return [
22
+ {
23
+ // GitLab before 17.4 has no such header. The body is the same on a retry and differs between events.
24
+ id: String(headers["idempotency-key"] ?? createHash("sha256").update(body).digest("hex")),
25
+ type,
26
+ subject: `${repo}${number}`.replace(/[^A-Za-z0-9#._:/@-]/g, "-").slice(0, 100),
27
+ summary: fit(String(attributes.title ?? payload.commits?.[0]?.message ?? ""), 200),
28
+ detail: fit(String(attributes.description ?? attributes.note ?? ""), 4000),
29
+ link: encodeURI(String(attributes.url ?? project.web_url ?? "")).slice(0, 500),
30
+ },
31
+ ];
32
+ }
@@ -0,0 +1,4 @@
1
+ // OMP prints the same event protocol as pi (same lineage); only the program and the resume flag differ.
2
+ import { piLike } from "../pi/agent.ts";
3
+
4
+ export default piLike("omp", "OMP", "--resume");
@@ -0,0 +1,78 @@
1
+ // OpenCode 2, `opencode run --format json`: one event per line. step_start opens a step and names the session a later
2
+ // turn goes on in with --session; a new run names none and OpenCode makes the id. Text parts carry what it says,
3
+ // grouped by message — steps narrate tool work, so only the last message is the answer. step_finish has the step's
4
+ // tokens and price; reason "stop" closes the turn, there is no final event. It approves its own edits as it comes;
5
+ // read-only is its plan agent. A cost of 0 is what it prints for a model whose price it doesn't know, so zero stays
6
+ // missing.
7
+ import { findProgram, tail, type Adapter, type Reading, type Usage } from "../../worker/agents.ts";
8
+ import { addUsage } from "../../protocol/validate.ts";
9
+
10
+ const NO_RESULT = "OpenCode 没有完成并留下实际结果";
11
+
12
+ /** tokens are per step: input leaves out what the cache read and wrote, reasoning counts as output. */
13
+ function stepUsage(tokens: any, cost: any): Usage | undefined {
14
+ if (!tokens || typeof tokens !== "object") return undefined;
15
+ const count = (value: unknown) => (typeof value === "number" ? value : 0);
16
+ const step: Usage = {
17
+ input: count(tokens.input) + count(tokens.cache?.read) + count(tokens.cache?.write),
18
+ output: count(tokens.output) + count(tokens.reasoning),
19
+ };
20
+ if (typeof tokens.cache?.read === "number") step.cached = tokens.cache.read;
21
+ if (typeof cost === "number" && cost > 0) step.cost = cost;
22
+ return step;
23
+ }
24
+
25
+ export default {
26
+ command: (turn) => [
27
+ turn.program ?? findProgram("opencode"),
28
+ "run",
29
+ "--format",
30
+ "json",
31
+ ...(turn.access === "read" ? ["--agent", "plan"] : []),
32
+ ...(turn.model ? ["--model", turn.model] : []),
33
+ ...(turn.resume ? ["--session", turn.resume] : []),
34
+ turn.prompt,
35
+ ],
36
+ read(stdout, code, stderr) {
37
+ let session: string | undefined;
38
+ let finished = false;
39
+ let failed: string | undefined;
40
+ let usage: Usage | undefined;
41
+ const messages = new Map<string, string>();
42
+ let lastMessage = "";
43
+ for (const line of stdout.split("\n")) {
44
+ let event: any;
45
+ try {
46
+ event = JSON.parse(line);
47
+ } catch {
48
+ continue;
49
+ }
50
+ // A login shell's profile prints here too, and `null` is valid JSON.
51
+ if (!event || typeof event !== "object") continue;
52
+ if (typeof event.sessionID === "string") session = event.sessionID;
53
+ const part = event.part ?? {};
54
+ if (event.type === "text" && part.type === "text" && typeof part.messageID === "string") {
55
+ lastMessage = part.messageID;
56
+ messages.set(part.messageID, (messages.get(part.messageID) ?? "") + (part.text ?? ""));
57
+ } else if (event.type === "step_finish") {
58
+ usage = addUsage(usage, stepUsage(part.tokens, part.cost));
59
+ if (part.reason === "stop") finished = true;
60
+ } else if (event.type === "error") {
61
+ failed = typeof event.error?.message === "string" ? event.error.message : tail(JSON.stringify(event));
62
+ }
63
+ }
64
+ const reading: Reading = { ...(session && { session }), ...(usage && { usage }) };
65
+ // It has this turn's prompt in a session that's there. From here on the work may be half done.
66
+ if (session) reading.started = true;
67
+ if (finished) {
68
+ reading.finished = true;
69
+ const text = messages.get(lastMessage);
70
+ if (text?.trim()) reading.text = text;
71
+ else reading.error = failed ?? NO_RESULT;
72
+ } else if (code !== null) {
73
+ const why = failed || tail(stderr);
74
+ reading.error = code !== 0 ? `退出码 ${code}:${why || "没留下原因"}` : why || NO_RESULT;
75
+ }
76
+ return reading;
77
+ },
78
+ } satisfies Adapter;
@@ -0,0 +1,80 @@
1
+ // pi --print --mode json (and OMP, same print protocol, same lineage): one event per line. The opening `session`
2
+ // names the conversation a later turn goes on in — pi takes --session-id, OMP --resume; a new run names none and the
3
+ // program makes the id. turn_start means the prompt is in a conversation that's there. Each assistant message_end is
4
+ // one step's answer and tokens; while a message is still streaming its message_end repeats with stopReason
5
+ // "pending", so only settled messages are booked. agent_end closes the turn. Neither program has permission modes:
6
+ // access isn't enforced here. A cost of 0 is what they print for a model whose price isn't in their catalog, so zero
7
+ // stays missing.
8
+ import { findProgram, tail, type Adapter, type Reading, type Usage } from "../../worker/agents.ts";
9
+ import { addUsage } from "../../protocol/validate.ts";
10
+
11
+ /** usage is per step: input leaves out the cache's reads and writes, reasoning counts as output. */
12
+ function stepUsage(reported: any): Usage | undefined {
13
+ if (!reported || typeof reported !== "object") return undefined;
14
+ const count = (value: unknown) => (typeof value === "number" ? value : 0);
15
+ const step: Usage = {
16
+ input: count(reported.input) + count(reported.cacheRead) + count(reported.cacheWrite),
17
+ output: count(reported.output) + count(reported.reasoning),
18
+ };
19
+ if (typeof reported.cacheRead === "number") step.cached = reported.cacheRead;
20
+ const cost = reported.cost?.total;
21
+ if (typeof cost === "number" && cost > 0) step.cost = cost;
22
+ return step;
23
+ }
24
+
25
+ export function piLike(program: string, name: string, resumeFlag: string): Adapter {
26
+ const NO_RESULT = `${name} 没有完成并留下实际结果`;
27
+ return {
28
+ command: (turn) => [
29
+ turn.program ?? findProgram(program),
30
+ "--print",
31
+ "--mode",
32
+ "json",
33
+ ...(turn.model ? ["--model", turn.model] : []),
34
+ ...(turn.resume ? [resumeFlag, turn.resume] : []),
35
+ turn.prompt,
36
+ ],
37
+ read(stdout, code, stderr) {
38
+ let session: string | undefined;
39
+ let started = false;
40
+ let finished = false;
41
+ let usage: Usage | undefined;
42
+ let text: string | undefined;
43
+ for (const line of stdout.split("\n")) {
44
+ let event: any;
45
+ try {
46
+ event = JSON.parse(line);
47
+ } catch {
48
+ continue;
49
+ }
50
+ if (!event || typeof event !== "object") continue;
51
+ if (event.type === "session" && typeof event.id === "string") session = event.id;
52
+ else if (event.type === "turn_start") started = true;
53
+ else if (event.type === "message_end" && event.message?.role === "assistant") {
54
+ const message = event.message;
55
+ if (message.stopReason === "pending") continue;
56
+ usage = addUsage(usage, stepUsage(message.usage));
57
+ const said = (message.content ?? [])
58
+ .filter((part: any) => part?.type === "text" && typeof part.text === "string")
59
+ .map((part: any) => part.text)
60
+ .join("");
61
+ if (said.trim()) text = said;
62
+ } else if (event.type === "agent_end") finished = true;
63
+ }
64
+ const reading: Reading = { ...(session && { session }), ...(usage && { usage }) };
65
+ // It has this turn's prompt in a conversation that's there. From here on the work may be half done.
66
+ if (started) reading.started = true;
67
+ if (finished) {
68
+ reading.finished = true;
69
+ if (text) reading.text = text;
70
+ else reading.error = NO_RESULT;
71
+ } else if (code !== null) {
72
+ const why = tail(stderr);
73
+ reading.error = code !== 0 ? `退出码 ${code}:${why || "没留下原因"}` : why || NO_RESULT;
74
+ }
75
+ return reading;
76
+ },
77
+ } satisfies Adapter;
78
+ }
79
+
80
+ export default piLike("pi", "Pi", "--session-id");
@@ -0,0 +1,74 @@
1
+ // The smallest channel there is: anything that takes a JSON POST (a group robot in DingTalk, WeCom, Slack, Discord…).
2
+ // Words and a link, no buttons: pair it with "links": true in rules.json so the link itself can answer that one card.
3
+ // "channels": { "dingtalk": { "use": "webhook", "key": "…", "url": "https://…",
4
+ // "body": { "msgtype": "text", "text": { "content": "{text}" } } } }
5
+ import { accepted, payload } from "./templates.ts";
6
+ import type { Card, ChannelContext } from "../../host/channels.ts";
7
+
8
+ function fill(template: unknown, text: string): unknown {
9
+ if (typeof template === "string") return template.replaceAll("{text}", () => text);
10
+ if (Array.isArray(template)) return template.map((item) => fill(item, text));
11
+ if (template && typeof template === "object") {
12
+ return Object.fromEntries(Object.entries(template).map(([key, value]) => [key, fill(value, text)]));
13
+ }
14
+ return template;
15
+ }
16
+
17
+ // WeCom draws its messages as Markdown: a link or a tag in what an Agent wrote would be drawn, and could pass off a link
18
+ // of its own as the card's. Full-width look-alikes keep the words and stop the markup; bare addresses still become links.
19
+ const asWords = (text: string) => text.replaceAll("](", "](").replaceAll("<", "<");
20
+
21
+ function words(card: Card, platform = "") {
22
+ const rule = card.rule && card.rule !== card.title ? card.rule : "";
23
+ if (platform === "wecom")
24
+ card = { ...card, title: asWords(card.title), text: asWords(card.text), options: card.options.map(asWords) };
25
+ const source = rule ? `来源:${platform === "wecom" ? asWords(rule) : rule}` : "";
26
+ if (
27
+ platform === "wecom" &&
28
+ card.kind === "notice" &&
29
+ card.state === "open" &&
30
+ card.options.length === 1 &&
31
+ card.options[0] === "已处理" &&
32
+ card.link
33
+ )
34
+ return [card.title, source, card.text, `[点击处理](${card.link})`].filter(Boolean).join("\n\n");
35
+ const choices = card.options.map((option, index) => `${index + 1}. ${option}`).join("\n");
36
+ const parts = [card.title, source, card.text, ...(card.state === "open" ? [choices, card.link] : [])];
37
+ return parts.filter(Boolean).join("\n\n");
38
+ }
39
+
40
+ export default async function webhook({ hub, options, log, signal }: ChannelContext) {
41
+ while (!signal.aborted) {
42
+ let card: Card | null;
43
+ try {
44
+ ({ card } = await hub.nextCard(50));
45
+ } catch (error) {
46
+ log(`couldn't reach the hub: ${error}`);
47
+ await new Promise((resolve) => setTimeout(resolve, 10_000));
48
+ continue;
49
+ }
50
+ if (!card) continue;
51
+ // It can't change a message once sent: an update has nothing to do.
52
+ if (card.ref) {
53
+ await hub.delivered(card.id, card.version, card.ref);
54
+ continue;
55
+ }
56
+ try {
57
+ const response = await fetch(options.url as string, {
58
+ method: "POST",
59
+ headers: { "content-type": "application/json" },
60
+ body: JSON.stringify(
61
+ options.platform
62
+ ? payload(String(options.platform), words(card, String(options.platform)))
63
+ : fill(options.body ?? { text: "{text}" }, words(card)),
64
+ ),
65
+ signal: AbortSignal.timeout(30_000),
66
+ });
67
+ await accepted(String(options.platform ?? ""), response);
68
+ await hub.delivered(card.id, card.version, `sent-${card.id}`);
69
+ } catch (error) {
70
+ log(`card ${card.id} not sent: ${error}`);
71
+ await hub.failed(card.id, card.version, String(error)).catch(() => {});
72
+ }
73
+ }
74
+ }