@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
package/README.md CHANGED
@@ -1,3 +1,261 @@
1
- # Temporary Holding Version
1
+ # Agent Autoloop
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **让你的命令行 Agent 在后台自己接活、自己跟进到底;平时不烦你,遇到拿不准的事才发卡片找你拍板。**
4
+
5
+ **中文** | [English](README.en.md)
6
+
7
+ [上手](#上手) · [场景模板](#拿来即用的场景模板) · [插件](#插件体系四个方向都能自由替换) · [内核](#内核的四个机制) · [文档](#更多文档)
8
+
9
+ ![架构图](docs/architecture.svg)
10
+
11
+ ## 它解决什么问题?
12
+
13
+ 平时我们用 Claude Code、Codex 这类命令行 Agent,大多是“人守着终端用”:你输一句话,盯着它跑,等它问你下一步;一旦关掉窗口或者人走开,事情就断了。
14
+
15
+ **Agent Autoloop** 是一个极轻量的自动化中台。它把任务调度做成一个零外部依赖的**内核**,把事件来源、Agent、通知通道,甚至代码上线流水线全部拆成可随时插拔的**插件**。
16
+
17
+ - **一台电脑、一条命令就能跑。** 装在你的 Windows、Mac 或 Linux 上,不用买云服务器,也不用开放公网端口。
18
+ - **一行配置接新 Agent。** 不需要 SDK,也不需要改 Agent 源码,能接收提示词并打印最后一条回复的命令行工具都能接。
19
+ - **没有后台界面。** 需要你拍板时把卡片推到飞书、钉钉、企微、Slack、Discord 或桌面通知;想看全局进展,敲一行命令。
20
+
21
+ ## 上手
22
+
23
+ 支持 Windows、macOS 和 Linux。需要 Node 24 或更新(自带 npm),以及一个已经登录的命令行 Agent,不需要 GitHub 账号。也可以把[安装说明](INSTALL.md)交给你的 Agent。
24
+
25
+ ```bash
26
+ npm install -g @saltpub/agent-autoloop
27
+ agent-autoloop init
28
+ ```
29
+
30
+ 安装和 `agent-autoloop update` 都装 npm 上的最新版本,那是通过了全部检查的版本。装好以后自动检查更新:新版本先在旁边试跑,等手上的活做完,下次启动换上;起不来就退回上一版。见[自动更新](docs/auto-update.md)。
31
+
32
+ 装好后用你本机的 Agent 真实走一遍“提问 → 退出等回复 → 拍板 → 接着干完”:
33
+
34
+ ```bash
35
+ agent-autoloop try
36
+ ```
37
+
38
+ 下面是在终端里的真实输出:
39
+
40
+ ```text
41
+ 事件发出去了,Agent 开始干活……
42
+
43
+ Agent 结束了这一轮,问了你一个问题。它现在不占进程、不花 Token。
44
+
45
+ 【等你决定】#1 试跑:选一个颜色
46
+ 这是一次试跑,选哪个都行。
47
+ 1. 蓝色
48
+ 2. 绿色
49
+ 回答:agent-autoloop answer 1 <序号>
50
+ 答完运行 agent-autoloop status,能看到它接着把活干完。
51
+ ```
52
+
53
+ 交互终端里直接输入数字回车;非交互终端运行 `agent-autoloop answer 1 2` 选择“绿色”。再跑 `agent-autoloop status`,就能看到它接上刚才的会话并显示“你选了绿色,试跑通过”,还有今天和最近 7 天的轮数、Token 和费用([统计口径](skills/agent-autoloop/SKILL.md#看情况回答))。
54
+
55
+ ## 一件事怎么转起来
56
+
57
+ 编号和上面的架构图一一对应:
58
+
59
+ 1. **新事件进来。** 早上 9 点的定时任务、GitHub 上新提的 Issue、业务系统报的错,都变成一条标准事件送进内核。
60
+ 2. **按规则派活。** 内核照你写的规则,决定交给哪个 Agent、去哪个目录干。同一件事排队时又来的消息,会合并成一轮处理。
61
+ 3. **干完一轮就退出。** Agent 把结果写在最后一条回复里,进程直接退出。
62
+ 4. **拿不准才问你。** 碰到删数据、停服、花钱、对外发消息这类事,内核通过飞书或桌面通知发一张卡片给你。等你回复期间,它不占后台进程,也不消耗 Token。
63
+ 5. **点一下,接着干。** 你选完,它接上原来的对话,把剩下的活干完。
64
+
65
+ 能自己搞定的事走图上方的自动闭环:直接办完,或者约个时间(比如半小时后)再醒来复查,全程不打扰你。
66
+
67
+ ## 日常怎么配?
68
+
69
+ ### 写一份规则(`rules.json`)
70
+
71
+ 不需要写胶水代码。打开 `~/.agent-autoloop/rules.json`,在 `rules` 里写清楚**什么事、交给谁、在哪个目录干**。`to` 填 `agents` 里已有的名字。比如每天早上 9 点写早报:
72
+
73
+ ```json
74
+ {
75
+ "name": "早报",
76
+ "when": { "cron": "0 9 * * *" },
77
+ "to": "codex",
78
+ "cwd": "~/notes",
79
+ "prompt": "整理昨天的笔记和提交,写今天的早报。"
80
+ }
81
+ ```
82
+
83
+ 外部事件写法一样,只是要先接好来源。比如有人提新 Issue 时交给 Codex,先按[说明](skills/agent-autoloop/SKILL.md#接一个事件插件)在 `sources` 里登记 `github`:
84
+
85
+ ```json
86
+ {
87
+ "name": "处理 issue",
88
+ "when": { "source": "github", "types": ["issues.opened"] },
89
+ "to": "codex",
90
+ "cwd": "~/code/app",
91
+ "skill": "handle-issue",
92
+ "parallel": 3
93
+ }
94
+ ```
95
+
96
+ `agent-autoloop pause <规则>`、`resume <规则>` 暂停和恢复一条规则,暂停期间到点不跑、来事件不接也不排队,恢复后不自动补跑;恢复时会列出暂停期间跳过的事件,照着给出的 `agent-autoloop replay <规则> --since <时间>` 一次补跑,每条只补一次。`agent-autoloop run <规则>` 立即跑一轮。这些记在中台的日志里,不改 `rules.json`。`agent-autoloop runs [规则]` 列出做完的轮次,`--before <第几轮>` 往前翻,拿到编号再用 `agent-autoloop why <第几轮>` 看来龙去脉。
97
+
98
+ 保存后几秒内自动生效,可以运行 `agent-autoloop check` 检查,`agent-autoloop check <文件>` 检查一份草稿,不碰正在跑的中台;`agent-autoloop rules explain [文件]` 看生效的规则和下次定时(也可以指定一份草稿),`agent-autoloop emit <类型> --dry-run` 预演一条事件会派给谁(不连接中台、不写日志)。就算改错了,或者文件被删、读不到,系统也会继续按旧规则跑,并发卡片提醒你。
99
+
100
+ ### Agent 怎么跟中台配合?
101
+
102
+ 中台对 Agent 只有一个约定:**在最后一条回复里交代结果**。事情办完了,正常输出一句结论就行。需要向你请示时,在回复末尾附一段 `agent-autoloop` 代码块:
103
+
104
+ ````text
105
+ 订单已经核对完毕,库存充足。
106
+
107
+ ```agent-autoloop
108
+ {
109
+ "ask": [{
110
+ "title": "怎么发货?",
111
+ "text": "两种方式今天都能发出。",
112
+ "options": ["快递", "自提"],
113
+ "key": "shipping"
114
+ }]
115
+ }
116
+ ```
117
+ ````
118
+
119
+ 除了提问(`ask`),还能发通知(`notice`)、关闭已解决的卡片(`resolve`)、预约复查(`later`)和触发新事件(`events`)。通告不需要回答,但结案时可以顺手写一句处理说明,这句话会留在卡片上;只是告诉一声的通告标成 `fyi`,不带按钮。万一 JSON 写错了,中台只让它在原会话里重写最后这段回复,不会把已经干完的业务重做一遍;重写也失败时,保留原结论并通知你回执没有生效(通用命令没有会话,直接走这一步)。接着旧会话跑也一样:会话接不上才开新的;接上了、干到一半断了,就算没跑成,过几分钟回到原会话重试,不开新会话重做。同一事项的新事件默认开新会话;规则写 `"resume": true` 就接着上一轮的会话。
120
+
121
+ ## 拿来即用的场景模板
122
+
123
+ 每套模板都提供示例规则和启用说明。
124
+
125
+ | 想做什么 | 已经封装好的流程 |
126
+ | ------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
127
+ | [每日早报](examples/recipes/morning-brief/README.md) | 默认每天 8 点整理本地笔记和 Git 提交,写入 `briefs/YYYY-MM-DD.md` |
128
+ | [跟进 GitHub Issue](examples/recipes/github-issues/README.md) | 每 5 分钟查新 Issue,在本地改代码并通知你查看;不提交、不推送、不回复 Issue |
129
+ | [线上告警排查](examples/recipes/ops-alerts/README.md) | 接收报错、对照代码查原因,需要重启时发卡片询问,回答后继续 |
130
+ | [用户反馈处理](examples/recipes/feedback/README.md) | 重读反馈当前状态、修复、交付核实、准备回复;需要决定时飞书问你,回答后继续 |
131
+ | [网站巡检](examples/recipes/website-watch/README.md) | 每 5 分钟检查状态和关键内容,首次异常交给 Agent,持续异常不重复通知,恢复后更新原卡片 |
132
+ | [飞书周报与业务摘要](examples/recipes/feishu-brief/README.md) | 周日 18 点按你的权限读汇报和指定表格,生成本地摘要;飞书只发简短摘要,完整稿留在本机 |
133
+ | [收件箱分诊](examples/recipes/inbox-triage/README.md) | 默认每天 8 点读过去 24 小时的未读邮件,写成清单和回复草稿;不发送、不改邮箱状态 |
134
+ | [PR 自动交付](skills/agent-autoloop/SKILL.md#交付流水线) | 打上 `deliver` 标签后,审查、等 CI、合并、等发布并核对线上版本 |
135
+
136
+ **启用:** 打开对应说明。模板带任务 Skill 时,把它放进所用 Agent 的 skills 目录。把示例规则合入 `~/.agent-autoloop/rules.json`,替换电脑名和路径,再运行 `agent-autoloop check`。
137
+
138
+ 反馈处理、网站巡检、飞书摘要和收件箱分诊默认使用北京时间,只发给本人的飞书私聊。样例数据都是虚构的;脚本和回执只用本地 HTTP 与假飞书 CLI 验证过,没有在真实账号上跑过完整业务。
139
+
140
+ 更多模板:[Claude 委托 Codex 处理网页](examples/recipes/browser-handoff/README.md)、[每周代码清理](examples/skills/weekly-sweep/SKILL.md)。
141
+
142
+ ## 插件体系:四个方向都能自由替换
143
+
144
+ 内置插件随程序安装,填好配置即可启用;第三方插件用 `agent-autoloop add <git 地址>` 安装。
145
+
146
+ | 方向 | 内置 | 配置 |
147
+ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
148
+ | **事件**:怎么发现新活 | [GitHub Webhook](plugins/github/source.ts)、[GitLab Webhook](plugins/gitlab/source.ts)、[HTTP 接口](docs/protocol.md#来源把世界变成事件)、[定时规则](skills/agent-autoloop/SKILL.md#改规则)、[Issue 轮询脚本](examples/watch-github-issues.sh) | [说明](skills/agent-autoloop/SKILL.md#接一个事件插件) |
149
+ | **Agent**:谁来干活 | [Claude Code](plugins/claude/agent.ts)、[Codex](plugins/codex/agent.ts)、[OpenCode](plugins/opencode/agent.ts)、[pi](plugins/pi/agent.ts)、[OMP](plugins/omp/agent.ts)、[ACP](plugins/acp/agent.ts)、[DeepSeek Harness](plugins/dsh/agent.ts)、[ZCode](plugins/zcode/agent.ts)、[通用命令](plugins/command/agent.ts) | [说明](skills/agent-autoloop/SKILL.md#接一个-agent) |
150
+ | **通道**:去哪找你拍板 | [桌面通知](plugins/desktop/channel.ts)(默认开启)、[飞书](plugins/feishu/channel.ts)、[钉钉 / 企微 / Slack / Discord](plugins/webhook/templates.ts) | [说明](skills/agent-autoloop/SKILL.md#接一个通道) |
151
+ | **交付**:把 CI/CD 也做成插件 | [`delivery`](plugins/delivery/delivery.ts) | [说明](skills/agent-autoloop/SKILL.md#交付流水线) |
152
+
153
+ **实测情况:** Claude Code、Codex 和 ACP(官方 Codex ACP 适配器)跑通了多轮问答和跨进程会话续接;OpenCode(2.2.7)、pi 和 OMP 跑通了多轮问答、会话续接和用量统计;ZCode 跑通了提问、回答后接回原会话;飞书跑通了发送、按钮回调和卡片更新;四种 Webhook 模板只在本地模拟服务上验证过,GitLab Webhook 按官方文档的格式测试,没连过真实 GitLab。这些文字通道靠回答链接拍板,要把 `hub.publicUrl` 配成手机或电脑能打开的地址。
154
+
155
+ **内置 Agent 走第三方网关。** Claude Code、Codex 要接第三方模型服务,或者启动前要先设好环境变量,写一个设好变量再启动它的小脚本,在 Agent 里写 `"program": "脚本路径"`,会话续接和用量统计照旧,见[说明](skills/agent-autoloop/SKILL.md#接一个-agent)。
156
+
157
+ **其他命令行 Agent 一行接入。** 设置 `use: "command"` 并传入命令数组,`{prompt}` 作为独立参数传递,不会被当成 shell 代码执行。下面的命令整理自各家官方文档,我们还没有逐个跑过:
158
+
159
+ | Agent | 接入命令 |
160
+ | --------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
161
+ | [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/cli-help.md#dsh-headless) 旧版(内置插件要 0.2.2 或更新) | `dsh --profile headless {prompt}` |
162
+ | [OpenClaw](https://docs.openclaw.ai/cli/agent) | `openclaw agent exec {prompt}` |
163
+ | [Hermes](https://hermes-agent.nousresearch.com/docs/user-guide/cli) | `hermes chat -Q -q {prompt}` |
164
+ | [Cursor](https://cursor.com/docs/cli/reference/parameters) | `agent -p --trust {prompt}` |
165
+ | [WorkBuddy / CodeBuddy](https://www.codebuddy.ai/docs/cli/headless) | `codebuddy -p {prompt}` |
166
+
167
+ OpenClaw 的 `agent exec` 每次默认最多跑 600 秒,到点就算失败;要跑更久的,在命令里加 `--timeout <秒>`(`0` 不限时)。
168
+
169
+ 会说 ACP 的 Agent 用 `use: "acp"` 接,还能接着原来的会话做:[Gemini CLI](https://geminicli.com/docs/cli/acp-mode/) 写 `"command": ["gemini", "--acp"]`,[OpenCode](https://opencode.ai/docs/acp) 写 `"command": ["opencode", "acp"]`,Antigravity 写 `"command": ["agy", "acp"]`。Gemini CLI 0.67.0 和 OpenCode 1.1.2 已经跑通 ACP 握手,多轮问答和会话续接还没跑过;Antigravity(agy 1.5.5)在 Windows 上跑通了多轮问答和会话续接。OpenCode 另有内置插件,走 `run --format json`,会话续接和用量统计都有。
170
+
171
+ **交付流水线。** 配好交付规则后,给 GitHub PR 打上 `deliver` 标签后,它会自己跟进到上线:**审代码 → 等 CI → 合并 PR → 等部署 → 核对线上版本**。审查可以按写代码的 Agent 指定,也可以让多个项目共用一份策略。审查和交付配置只从 `main` 读取,绝不在接单电脑上检出或运行 PR 里的代码;排队、并发和重试直接复用内核。
172
+
173
+ **写自己的插件。** 从 [Agent](examples/plugins/hello-agent/agent.ts)、[通道](examples/plugins/hello-channel/channel.ts)、[事件](examples/plugins/hello-source/source.ts) 三个可运行的最小模板开始,见[插件开发说明](docs/plugins.md)。要让 Agent 操作网页,先看[浏览器接入](docs/plugins.md#浏览器接入)。命令行和 [MCP](skills/agent-autoloop/SKILL.md#mcp-与密钥撤销) 也能查看和回答卡片。
174
+
175
+ ## 内核的四个机制
176
+
177
+ 内核没有运行时依赖。它不读系统时钟、不用随机数、不向外发请求,插件主动连进来,账号凭据留在各自的插件里;同样的输入永远得出同样的结果。它把四个计算机领域的成熟做法用到了命令行 Agent 上:
178
+
179
+ - **挂起零消耗**:等你拍板时进程直接退出,等待状态存在数据库里,Agent 不用一直挂着。你三天没回,这三天就没有 Agent 进程在跑、不花 Token,只有很轻的中台在后台等着;你一回答,它接着原来的对话继续干。
180
+ - **事件溯源**:所有状态都从一条只追加的日志算出来,日志和索引在同一个事务里写进磁盘,写完才应答。进程被强杀,已经确认的事不丢(整机断电没有单独测过);任何一轮为什么跑、结果是什么,一条命令就能查清;数据格式变了就从日志重建,不用写迁移脚本。
181
+ - **指令数据分离**:思路和 SQL 参数化一样。Issue 的标题和正文等外部文字只作为资料放进文件,不拼进提示词,提示词里只有校验过字符的类型、编号和链接;用哪个 Agent、在哪个目录、什么权限,只由你本机的规则决定,事件里带 `cwd`、`agent`、`access` 字段会被直接拒收。
182
+ - **跳数熔断**:思路和网络包的 TTL 一样。Agent 交回的事件会再派给 Agent,层数一路累加,经过人工提问和定时复查也不清零,Agent 自己改不了;超过 8 层就只记录、不再派活,并发一张卡片告诉你。
183
+
184
+ ### 自己跑一遍
185
+
186
+ Windows 用 `npm run test:windows` 和 `node scripts/install-smoke-windows.ts`,运行共用行为测试与原生进程、安装检查;Unix shell 测试仍在 Linux/macOS 上跑。
187
+
188
+ 在程序目录 `~/.agent-autoloop/app` 下运行:
189
+
190
+ | 验证什么 | 命令 |
191
+ | ------------------------------------------------------- | --------------------------------- |
192
+ | 任何一轮的来龙去脉 | `agent-autoloop why 1` |
193
+ | 20 万步模拟断网、丢包、崩溃和重复提交,一个种子就能复现 | `node sim/random.ts 24301 200000` |
194
+ | 强杀进程 1000 次,已确认的记录一条不丢 | `node sim/crash.ts 1000 12648430` |
195
+ | 下面的性能数字 | `npm run benchmark` |
196
+
197
+ ```text
198
+ 第 1 轮 · 演示
199
+ 11-03 20:47:25 规则版本 #1
200
+ 11-03 20:47:25 触发事件:来源 local · 类型 demo.start · 对象 example
201
+ 11-03 20:47:25 local 领取(演示程序)
202
+ 11-03 20:47:25 结束:演示完成
203
+ ```
204
+
205
+ ### 实测性能
206
+
207
+ Apple M5 Pro、24 GB、Node 24.21.0。写入逐条提交,事务落盘后才应答。
208
+
209
+ | 指标 | 实测 |
210
+ | ---------------------------- | ------------: |
211
+ | 冷启动 | 88.78 ms |
212
+ | 空闲内存 | 59.94 MB RSS |
213
+ | 1000 个同时等待的长轮询 | 170.49 MB RSS |
214
+ | 持久化写入 | 2394 条/秒 |
215
+ | 派活 p99 | 1.82 ms |
216
+ | 排队 5000 时被挡下的心跳 p99 | 1.66 ms |
217
+ | 110 万条事实时的启动 | 99.8 ms |
218
+ | 运行时依赖 | 0 |
219
+
220
+ 历史变大后,状态汇总会变慢,日志和索引也继续占磁盘;格式变化后的首次启动要从日志全量重建,110 万条用时 43.1 秒。[完整数据和测法](docs/protocol.md#历史增长实测)。
221
+
222
+ ## 用量与合规说明
223
+
224
+ 中台直接调用你本机已经安装并登录好的命令行工具,不会读取或转存你的账号凭据。模型调用消耗算在你自己的账号名下,额度和使用范围遵循各家模型厂商的服务条款。
225
+
226
+ 在高频自动化场景下,各家厂商通常更建议使用 API Key(个人订阅额度主要是为日常人工交互设计的,详见 [Anthropic](https://code.claude.com/docs/en/legal-and-compliance) 与 [OpenAI](https://learn.chatgpt.com/docs/auth) 的官方说明)。如果你用它对外提供服务,请使用 API Key。本项目为独立开源项目,与上述厂商无隶属或背书关系。
227
+
228
+ ## 更多文档
229
+
230
+ - [安装说明](INSTALL.md)
231
+ - [规则与交付流水线配置手册](skills/agent-autoloop/SKILL.md)
232
+ - [如何编写插件](docs/plugins.md)
233
+ - [完整通信协议](docs/protocol.md)
234
+ - [安全边界说明](SECURITY.md)
235
+ - [参与贡献与交流](CONTRIBUTING.md)
236
+ - [项目开发约定](AGENTS.md)
237
+
238
+ <details>
239
+ <summary><strong>仓库目录</strong></summary>
240
+
241
+ | 位置 | 放什么 |
242
+ | -------------------------------------------------------- | --------------------------------------------------------------------------------- |
243
+ | `kernel/` | 内核:决策、事实日志、状态投影、到期任务、规则匹配、接口行为与卡片表单 |
244
+ | `host/` | 运行外壳:Node HTTP、文件与 SQLite 连接、时钟、配置、状态汇总、后台服务和插件加载 |
245
+ | `protocol/` | 通信格式、JSON Schema、输入校验、HTTP 客户端和一致性检查 |
246
+ | `worker/` | 接单程序:领活、运行 Agent、心跳与停止、读取和提交回执 |
247
+ | `cli/`、`bin/` | 用户命令及启动入口,包括状态、回答、`why`、MCP、更新与卸载 |
248
+ | `plugins/` | 内置 Agent、事件、通道和交付插件 |
249
+ | `examples/recipes/` | 完整场景:规则、任务 Skill 和启用说明 |
250
+ | `examples/plugins/`、`examples/skills/`、`examples/*.sh` | 最小插件模板、独立任务手册和 Shell 示例 |
251
+ | `skills/agent-autoloop/` | 中台的正式配置与操作手册,安装时链接到 `~/.agents/skills` 供 Agent 使用 |
252
+ | `docs/` | 通信协议、插件开发说明与中英文架构图 |
253
+ | `tests/`、`sim/` | 日常行为测试,以及模拟、穷举、强杀和变异检查 |
254
+ | `scripts/`、`.github/workflows/` | 性能与真机验证、安装冒烟脚本,以及 Windows / Linux / macOS CI |
255
+ | 根目录文档与 `package.json` | 中英文 README、安装说明、安全边界、开发约定、许可证与 npm 发布信息 |
256
+
257
+ 读代码可以从 `bin/agent-autoloop.ts` → `cli/main.ts` 开始,再按功能进入 `host/`、`worker/` 或 `plugins/`;内核设计先看[协议](docs/protocol.md)。同名文件分属不同层:`host/http.ts` 转换 Node 请求,`kernel/http.ts` 定义接口行为;`protocol/rules.ts` 校验输入,`kernel/rules.ts` 定义规则类型和匹配。
258
+
259
+ </details>
260
+
261
+ [MIT License](LICENSE)
package/SECURITY.md ADDED
@@ -0,0 +1,48 @@
1
+ # 安全
2
+
3
+ 发现安全问题,请用 GitHub 的 [Security Advisories](https://github.com/KKKKhazix/agent-autoloop/security/advisories/new) 私下告诉我,不要开公开的 issue。
4
+
5
+ 这个入口打不开时,只在 Issue 中说明“需要私密联系维护者报告安全问题”,等维护者安排私密渠道;不要贴漏洞细节、密钥或业务资料。
6
+
7
+ 私密报告请提供受影响的提交版本、运行环境、最少复现步骤和可能影响,日志与截图先脱敏。目前在最新 `main` 上验证和修复安全问题,修复随下一次 npm 发布到用户手上,严重的问题单独发一个小版本,没有单独维护的长期支持分支,也不承诺固定响应时间。
8
+
9
+ ## 边界
10
+
11
+ - 中台默认只听本机。要对外,前面放一个做 HTTPS 的反向代理。
12
+ - 中台启动时在 macOS/Linux 把数据目录设为 `0700`,Windows 用受保护的 ACL 只保留当前账号与 SYSTEM,已有目录也会修正;数据库、事件正文和运行输出因此不向其他系统用户开放。Codex 的 Windows 沙箱会给用户目录下的文件夹加上它的账号的读权限,数据目录也在内;中台启动时收回,在那之前沙箱里的命令能读到主密钥和配置里的密钥。插件另外给每轮的 `context.json` 加这个读权限。这不隔离同一系统账号下的进程。
13
+ - 事件决定不了交给谁、在哪个目录、用哪个 Skill、给什么权限,这些只由 `rules.json` 决定。别人写的标题和正文不进提示词,只放进标明“是资料”的文件;提示词里只有校验过字符的类型、编号和链接。这挡不住所有提示注入:Agent 还是会读到别人写的话。所以默认权限是 `edit`,给 `full` 之前想清楚这个 Agent 能碰到什么。`askFirst` 是写进提示词的要求,Agent 不照做,中台也拦不住;真正挡得住的是 `access` 和 Agent 自己的沙箱。
14
+ - `access` 由专用 Agent 插件映射到 CLI 权限;`command` 不替任意程序限制权限。普通 Agent 的 `read` 不等于读不到这台电脑上的密钥。要隔离密钥,用单独的系统账号或容器。
15
+ - 普通访问密钥只存 SHA-256,另有本机 `master.key` 推导轮次和卡片链接的 token。`master.key` 为空或不完整时中台拒绝启动,不会拿它签链接,也不会自己换一把新的。接单程序不通过提示词、资料或环境变量传递中台凭据;同一系统账号下能读哪些文件仍由 Agent 沙箱决定。回执能影响的范围见 `docs/protocol.md`。
16
+ - 卡片链接谁拿到谁就能回答这一张卡片,从卡片创建起 7 天内有效,过期后也不再显示卡片内容,只发给配了 `"links": true` 的通道。
17
+ - 本项目只启动你自己安装、自己登录的官方命令行工具,不接触、不保存、不中转它们的登录凭据。
18
+ - 浏览器能力由 Agent 自己的工具配置提供;专用入口只从可信规则或 Skill 取得,不从事件正文取命令。中台不自动授予浏览器权限或接管桌面会话。需本人恢复的连接或验证用 `ask` 交回,保留未验收项。
19
+
20
+ ## 插件与交付
21
+
22
+ 插件是安装者信任的本地代码,安装目录的同名插件优先;`agent-autoloop add` 只克隆,不运行安装脚本,但之后加载入口就会执行它。事件不能指定插件、仓库、命令或权限。
23
+
24
+ ACP 的授权依赖 Agent 遵守协议,规范允许它不询问就执行,`access` 只管它主动来问的操作。桥接只按结构化工具种类、编辑路径与一次性选项作决定,不提供文件或终端服务。MCP 使用本机已有身份,只提供协议列出的那些操作;它不区分调用方,都按本人记录,不要配进接单程序启动的 CLI 的用户级配置,否则一轮能自己回答自己的卡片。撤销密钥立即终止其长轮询和日志订阅;轮次 token 独立。
25
+
26
+ 交付只接受规则指定仓库内的分支到 main。项目设置、审查要求、替换审查命令均读 main;PR 只下载 Git 对象,生成文字差异,不检出、不运行 PR 的代码、测试、配置或 hooks;审查看不到内容的章鱼合并直接报问题,不放行。默认 Codex 禁用用户配置与记忆,只读隔离的快照。自定义审查命令由项目管理者负责提供同等权限约束。
27
+
28
+ 按写代码的 Agent 定审查器时,来源只认 可信 main 配置(项目的 `review.trusted` 或共用策略的 `trusted_submitters`)列出的 GitHub 账号在该提交上写的 `delivery-agent/<PR 编号>` 状态;PR 说明、标签、分支名,以及其他账号(包括 PR 自己的工作流)写的状态都不算,列了 `agents` 却没有 `trusted` 的设置不接受。声明是可信账号自己报的,插件不核对改动实际由谁写:能用这个账号写状态的程序都能报任何一个名字。免审的改动只在碰到 `review.xhigh` 的路径或要求只审查时才会被审,所以发信、钱、权限、发布这类路径要写进 `review.xhigh`。
29
+
30
+ 审查成功状态只在同一提交的完整检查通过后写入;PR 正文只承载可见的审查记录,实际认可的轮次需要本机 GitHub 登录账号在提交上写入的凭据;处理说明可以编辑;合并前再次核对提交、目标分支、标签和 main,等待检查期间新增 `deliver-review` 也会阻止合并,清标签只成功一部分时重试也不会合并只审查的 PR。项目仍需在 GitHub 配好自身合并规则,插件不能代替平台权限。带 `deliver` 标签的已合并 PR 只继续核实 Ship 与健康版本,不重复合并。健康 URL 默认要求 HTTPS,只有显式测试开关允许 HTTP 127.0.0.1;跳转和不合格的版本不能证明上线。
31
+
32
+ 桌面通知的正文包含 Agent 写的卡片标题,只作为参数传给 `osascript` 或 `notify-send`,放在 `--` 之后,不拼进脚本。Webhook 模板没有外部幂等保证;发送成功但报告丢失可能重复。链接回答是持有即授权,不能把链接发到公开位置。飞书应用只能保留一个卡片事件监听;本仓库测试只使用假 CLI。
33
+
34
+ ## 场景资料
35
+
36
+ 公开模板只包含虚构数据、示例域名和占位标识。反馈内容、网页响应与飞书资料都不能指定命令、目录、权限或收件人;反馈的现状与决定从可信业务接口重新读取。飞书汇报和表格用本人身份读取,不能换成机器人身份补齐看不到的数据。摘要输入保存在本人私有目录,完整读取后才替换,通知不携带敏感正文。
37
+
38
+ 通道接收人属于整个中台,规则不能单独挑收件人。处理私人反馈和汇报的中台应只连接本人可见的通道;不要把它们接到共享群。新增接入沿用用户自己的身份与授权,不复制内部部署配置、密钥或业务日志。
39
+
40
+ 浏览器交接模板的命令数组、目标网址和允许操作来自本人的可信配置,按参数传递,不把任务文字交给 shell 解释。允许操作是给 Agent 的任务范围,不是额外的系统沙箱;实际工具和账号权限仍由既有运行环境决定。会话编号只用入口实际返回的值;中断或结果不明先核实,不盲目重复有副作用的网页操作。模板不修改应用内部状态、不自动启动新的账号授权,也不打包某台电脑的浏览器修复脚本。
41
+
42
+ ## 日志与恢复
43
+
44
+ 门的权限、通道回答人和原消息、轮次 token 的范围、重复回执与卡片回答都有行为和一致性检查。`sim/invariants.ts` 是模拟与穷举共用的不变量;夜间检查另外对真实 SQLite 进程做 SIGKILL。范围是进程崩溃和有限场景,不等同于断电恢复证明或完整安全审计。
45
+
46
+ `kernel/` 不读时钟、不取随机数。判断、事实追加和 `evolve` 更新投影在同一 WAL + FULL 事务里完成,提交后才应答。正常启动复用带游标和编号高水位的投影;格式指纹变化时从日志逐条重建,不改变旧事实。`agent-autoloop why 42` 查一轮的事件、规则和回执;`GET /v1/stream?after=42` 供本人客户端按序号续读。备份用 `agent-autoloop backup [目录]`,中台运行时也能做;恢复用 `agent-autoloop restore <目录>`,要先停中台。规则写了 `resume` 时,一轮读到的资料会留在会话里,后面的轮次还看得到,事件里别人写的字也在其中;没写 `parallel` 时,这条规则的所有事件共用一个会话。来源不可信的规则不要这样配。
47
+
48
+ 备份里有主密钥、配置里的密钥和 `secrets.env`,macOS/Linux 上目录权限 0700、文件 0600,Windows 上继承只允许本人和 SYSTEM 的目录 ACL,要和密钥一样保管。恢复时这些文件和规则都会被替换。手工备份要一起保留 `hub.db` 和受相同访问限制的 `master.key`;后者推导轮次和卡片链接的 token。普通访问密钥只保存哈希;卡片链接查找索引也只保存 token 的哈希。
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env -S node --disable-warning=ExperimentalWarning
2
+ import "../cli/main.js";
@@ -0,0 +1,144 @@
1
+ // `backup` and `restore`: the database, the key that signs card links, and the files that say what this machine is.
2
+ // A backup is taken while the hub runs; a restore needs it stopped, because it replaces the file that is open.
3
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { backup as copyPages, DatabaseSync } from "node:sqlite";
6
+ import { privateDirectory } from "../host/files.js";
7
+ const DB = "hub.db";
8
+ const KEY = "master.key";
9
+ const FILES = [KEY, "config.json", "rules.json", "secrets.env"];
10
+ const KEY_SHAPE = /^[A-Za-z0-9_-]{43}$/;
11
+ /**
12
+ * A copy as of one point, WAL and all, of a database that may be in use. It copies pages because VACUUM INTO rebuilds the
13
+ * indexes, and the hub's call functions only the hub has.
14
+ */
15
+ async function copyDatabase(from, to) {
16
+ const source = new DatabaseSync(from);
17
+ try {
18
+ await copyPages(source, to);
19
+ }
20
+ finally {
21
+ source.close();
22
+ }
23
+ chmodSync(to, 0o600);
24
+ }
25
+ /** Writes a backup folder nothing exists in yet: the database first, then whichever of the files are there. */
26
+ export async function backup(home, target) {
27
+ const database = path.join(home, DB);
28
+ if (!existsSync(database))
29
+ throw new Error("还没装好:先运行 agent-autoloop init");
30
+ if (existsSync(target) && readdirSync(target).length)
31
+ throw new Error(`备份目录不是空的:${target}`);
32
+ privateDirectory(target);
33
+ await copyDatabase(database, path.join(target, DB));
34
+ const files = [DB];
35
+ for (const name of FILES) {
36
+ const from = path.join(home, name);
37
+ if (!existsSync(from))
38
+ continue;
39
+ copyFileSync(from, path.join(target, name));
40
+ chmodSync(path.join(target, name), 0o600);
41
+ files.push(name);
42
+ }
43
+ return { target, files };
44
+ }
45
+ function readableBackup(source) {
46
+ const database = path.join(source, DB);
47
+ const key = path.join(source, KEY);
48
+ if (!existsSync(database) || !existsSync(key))
49
+ throw new Error(`这个目录不像备份:缺 ${DB} 或 ${KEY}`);
50
+ if (!KEY_SHAPE.test(readFileSync(key, "utf8").trim()))
51
+ throw new Error("备份里的 master.key 坏了");
52
+ let result;
53
+ let tables = 0;
54
+ try {
55
+ const check = new DatabaseSync(database);
56
+ try {
57
+ // Not integrity_check: that one evaluates the indexes too, and so needs the hub's functions.
58
+ result = Object.values(check.prepare("PRAGMA quick_check").get() ?? {})[0];
59
+ // An empty file passes quick_check: SQLite reads it as a database with nothing in it, and restoring one would put a
60
+ // home in place that has no tables at all.
61
+ tables = check.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE type = 'table'").get().n;
62
+ }
63
+ finally {
64
+ check.close();
65
+ }
66
+ }
67
+ catch { }
68
+ if (result !== "ok")
69
+ throw new Error("备份里的 hub.db 读不出来");
70
+ if (!tables)
71
+ throw new Error("备份里的 hub.db 是空库");
72
+ }
73
+ /** Whether anything has the database open, a hub between requests included: only then is this lock out of reach. */
74
+ function inUse(database) {
75
+ if (!existsSync(database))
76
+ return false;
77
+ const db = new DatabaseSync(database);
78
+ try {
79
+ db.exec("PRAGMA busy_timeout=0; PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; COMMIT;");
80
+ return false;
81
+ }
82
+ catch (error) {
83
+ // One that can't be read at all isn't in use: that may be why it's being restored.
84
+ return /locked/.test(String(error));
85
+ }
86
+ finally {
87
+ db.close();
88
+ }
89
+ }
90
+ /** Puts a backup back in place, keeping what it replaced. */
91
+ export async function restore(home, source) {
92
+ if (inUse(path.join(home, DB))) {
93
+ throw new Error("中台还在跑:先停掉它(例如 agent-autoloop service remove,或手动停服务),再恢复");
94
+ }
95
+ readableBackup(source);
96
+ privateDirectory(home);
97
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
98
+ const staged = path.join(home, `restore-new-${stamp}`);
99
+ const safety = path.join(home, `restore-before-${stamp}`);
100
+ // The backup is gathered beside the home first, and only then swapped in. While pages are being copied nothing in the home
101
+ // has moved, so a restore killed in the middle of the copy (a SIGKILL, a power cut) leaves the old database where it was.
102
+ mkdirSync(staged, { mode: 0o700 });
103
+ try {
104
+ await copyDatabase(path.join(source, DB), path.join(staged, DB));
105
+ for (const name of FILES.filter((name) => existsSync(path.join(source, name)))) {
106
+ copyFileSync(path.join(source, name), path.join(staged, name));
107
+ chmodSync(path.join(staged, name), 0o600);
108
+ }
109
+ }
110
+ catch (error) {
111
+ rmSync(staged, { recursive: true, force: true });
112
+ throw error;
113
+ }
114
+ // The WAL belongs to the file that's leaving: a stale one next to the restored database would be applied to it. A file the
115
+ // backup doesn't have stays as it is.
116
+ const replaced = [DB, `${DB}-wal`, `${DB}-shm`, ...FILES.filter((name) => existsSync(path.join(staged, name)))];
117
+ mkdirSync(safety, { mode: 0o700 });
118
+ try {
119
+ for (const name of replaced) {
120
+ const from = path.join(home, name);
121
+ if (existsSync(from))
122
+ renameSync(from, path.join(safety, name));
123
+ }
124
+ for (const name of replaced) {
125
+ const from = path.join(staged, name);
126
+ if (existsSync(from))
127
+ renameSync(from, path.join(home, name));
128
+ }
129
+ }
130
+ catch (error) {
131
+ // Half a restore is worse than none: everything goes back as it was, the WAL with its database. This covers the moves
132
+ // out of the home too, which used to sit outside the rollback.
133
+ for (const name of readdirSync(safety)) {
134
+ rmSync(path.join(home, name), { force: true });
135
+ renameSync(path.join(safety, name), path.join(home, name));
136
+ }
137
+ rmSync(safety, { recursive: true, force: true });
138
+ throw error;
139
+ }
140
+ finally {
141
+ rmSync(staged, { recursive: true, force: true });
142
+ }
143
+ return { safety };
144
+ }
@@ -0,0 +1,84 @@
1
+ // `rules explain` and `emit --dry-run`: what this machine's rules file says, without asking a hub or writing a fact.
2
+ import { describeCron, nextRun, parseCron } from "../kernel/cron.js";
3
+ import { cronOf, eventRule, typeMatches } from "../kernel/rules.js";
4
+ import { parseRules } from "../protocol/rules.js";
5
+ import { parseEvent } from "../protocol/validate.js";
6
+ const localZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
7
+ const clock = (zone) => ({ timeZone: zone, month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
8
+ const when = (rule, rules, now) => eventRule(rule)
9
+ ? `来源 ${rule.when.source} · ${rule.when.types.join("、")}`
10
+ : `定时 ${describeCron(cronOf(rule))}(下次 ${new Date(nextRun(parseCron(cronOf(rule)), now, rules.timezone)).toLocaleString("zh-CN", clock(rules.timezone))})`;
11
+ function details(rule, rules, now) {
12
+ const parts = [when(rule, rules, now), `→ ${rule.to}`, rule.cwd];
13
+ if (rule.parallel)
14
+ parts.push(`并发 ${rule.parallel}`);
15
+ if (rule.maxActive)
16
+ parts.push(`本规则最多同时 ${rule.maxActive} 轮`);
17
+ if (rule.channels?.length)
18
+ parts.push(`只发 ${rule.channels.join("、")}`);
19
+ if (rule.resume)
20
+ parts.push("接着上一轮的会话");
21
+ if (rule.title)
22
+ parts.push(`会话标题 ${rule.title}`);
23
+ if (rule.group !== rule.name)
24
+ parts.push(`组 ${rule.group}`);
25
+ if (rule.tell !== "needed")
26
+ parts.push(`通知 ${rule.tell}`);
27
+ if (rule.skill)
28
+ parts.push("有 Skill");
29
+ if (rule.prompt)
30
+ parts.push("有 Prompt");
31
+ if (rule.emits)
32
+ parts.push(`可发 ${rule.emits.source} ${rule.emits.types.join("、")}`);
33
+ return parts.join(" · ");
34
+ }
35
+ /** The rules as this machine would run them, one line per thing an owner asks about. */
36
+ export function explainRules(text, now = Date.now(), zone = localZone()) {
37
+ const rules = parseRules(text, now, zone);
38
+ const lines = [
39
+ `时区 ${rules.timezone};先问你:${rules.askFirst.join("、")};${rules.rules.length} 条规则`,
40
+ `来源:${Object.entries(rules.sources)
41
+ .map(([id, source]) => `${id}(${source.name})`)
42
+ .join("、")}`,
43
+ `Agent:${Object.entries(rules.agents)
44
+ .map(([id, agent]) => {
45
+ const limit = agent.maxActive ? `,最多同时 ${agent.maxActive} 轮` : "";
46
+ return `${id}(${agent.name},${agent.worker},权限 ${agent.access}${limit})`;
47
+ })
48
+ .join("、")}`,
49
+ ];
50
+ if (Object.keys(rules.channels).length)
51
+ lines.push(`通道:${Object.entries(rules.channels)
52
+ .map(([id, channel]) => {
53
+ const answerers = channel.answerers?.length ? `,回答人 ${channel.answerers.join("、")}` : "";
54
+ return `${id}(${channel.name}${answerers}${channel.links ? ",带链接" : ""})`;
55
+ })
56
+ .join("、")}`);
57
+ if (rules.defaultChannels)
58
+ lines.push(`没写 channels 的卡片和通知默认只发 ${rules.defaultChannels.join("、")}`);
59
+ lines.push("规则:");
60
+ for (const rule of rules.rules)
61
+ lines.push(` ${rule.name}:${details(rule, rules, now)}`);
62
+ for (const task of rules.elsewhere) {
63
+ const answers = task.cwd ? `;问你的,回答后交给 ${rules.agents[task.to].name} 在 ${task.cwd} 接着做` : "";
64
+ lines.push(` ${task.name}:在别处(${task.where})${describeCron(task.cron)}${answers}`);
65
+ }
66
+ return lines;
67
+ }
68
+ /** What a source event would be handed to, by the rules file alone: no hub, no log, no key. */
69
+ export function previewEvent(text, source, event, now = Date.now(), zone = localZone()) {
70
+ const rules = parseRules(text, now, zone);
71
+ const parsed = parseEvent(event);
72
+ const lines = [`事件:${source} ${parsed.type}${parsed.subject ? ` ${parsed.subject}` : ""}`];
73
+ if (!rules.sources[source])
74
+ lines.push(`来源 ${source} 没有登记在 rules.json 的 sources 里`);
75
+ const matched = rules.rules.filter((rule) => eventRule(rule) && rule.when.source === source && typeMatches(rule.when.types, parsed.type));
76
+ if (!matched.length) {
77
+ lines.push("没有规则接这条事件;真发出去会记成「没有规则接的事件」。");
78
+ return lines;
79
+ }
80
+ lines.push("会派给:");
81
+ for (const rule of matched)
82
+ lines.push(` ${rule.name} → ${rule.to} · ${rule.cwd}`);
83
+ return lines;
84
+ }