@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,204 @@
1
+ // A turn run over the Agent Client Protocol: a process of its own that talks to the ACP agent on stdio and prints what
2
+ // the worker's adapter reads, one JSON object per line.
3
+ import { spawn } from "node:child_process";
4
+ import { existsSync, lstatSync, realpathSync } from "node:fs";
5
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
6
+ import { commandLine } from "../../host/command.js";
7
+ import { eachLine } from "../../host/lines.js";
8
+ import { versionName } from "../../host/version.js";
9
+ /** The agent said no, as opposed to going away, saying nothing, or having what was asked for in use. */
10
+ class Refused extends Error {
11
+ }
12
+ const isLink = (file) => {
13
+ try {
14
+ return lstatSync(file).isSymbolicLink();
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ };
20
+ /**
21
+ * Where a path really is, though it may not be there yet; null if it goes through a link with nothing at the end of it.
22
+ * Writing through one creates what it points at, so it can't count as a new file where the link is.
23
+ */
24
+ function resolved(file) {
25
+ if (existsSync(file))
26
+ return realpathSync(file);
27
+ const folder = resolved(dirname(file));
28
+ if (folder === null)
29
+ return null;
30
+ const path = resolve(folder, basename(file));
31
+ return isLink(path) ? null : path;
32
+ }
33
+ export function permission(turn, params) {
34
+ const tool = params.toolCall ?? {};
35
+ const inside = (location) => {
36
+ if (typeof location.path !== "string" || !isAbsolute(location.path))
37
+ return false;
38
+ const target = resolved(location.path);
39
+ if (target === null)
40
+ return false;
41
+ const path = relative(realpathSync(turn.cwd), target);
42
+ return path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
43
+ };
44
+ const editsInside = turn.access === "edit" && tool.kind === "edit" && tool.locations?.length > 0 && tool.locations.every(inside);
45
+ const allowed = turn.access === "full" || tool.kind === "read" || tool.kind === "search" || editsInside;
46
+ const option = params.options?.find((option) => option.kind === (allowed ? "allow_once" : "reject_once"));
47
+ return option ? { outcome: "selected", optionId: option.optionId } : { outcome: "cancelled" };
48
+ }
49
+ export async function bridge(turn) {
50
+ if (!turn.command?.length)
51
+ throw new Error("ACP 要在 command 写启动命令");
52
+ // The last go may have done its work in this session, so whatever breaks now says nothing about whether a new session
53
+ // would do it again. Only the agent's own no takes this back; see goOn.
54
+ if (turn.resume)
55
+ console.log(JSON.stringify({ session: turn.resume, started: true }));
56
+ const [program, args] = commandLine(turn.command);
57
+ const child = spawn(program, args, { cwd: turn.cwd, stdio: ["pipe", "pipe", "inherit"], windowsHide: true });
58
+ const pending = new Map();
59
+ let next = 0;
60
+ let session = "";
61
+ let collecting = false;
62
+ let text = "";
63
+ let message;
64
+ let boundary = false;
65
+ const send = (body) => child.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...body }) + "\n");
66
+ const fail = (error) => {
67
+ for (const request of pending.values())
68
+ request.reject(error);
69
+ pending.clear();
70
+ };
71
+ child.on("error", fail);
72
+ child.on("exit", (code) => fail(new Error(`ACP 在交回结果前退出:${code}`)));
73
+ child.stdin.on("error", fail);
74
+ const toolCalls = new Map();
75
+ /** All that's been said of a tool call. A message may give only its id; a field left out or null changes nothing. */
76
+ const toolCall = (said) => {
77
+ const fields = Object.entries(said ?? {}).filter(([, value]) => value !== null && value !== undefined);
78
+ const known = { ...toolCalls.get(said?.toolCallId), ...Object.fromEntries(fields) };
79
+ if (said?.toolCallId)
80
+ toolCalls.set(said.toolCallId, known);
81
+ return known;
82
+ };
83
+ const onUpdate = (update) => {
84
+ if (["tool_call", "tool_call_update"].includes(update.sessionUpdate))
85
+ toolCall(update);
86
+ if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") {
87
+ // An id says which message this is. Only with none does what came in between have to tell.
88
+ if (update.messageId ? update.messageId !== message : boundary)
89
+ text = "";
90
+ message = update.messageId;
91
+ boundary = false;
92
+ text += update.content.text;
93
+ }
94
+ else if (["tool_call", "agent_thought_chunk", "user_message_chunk"].includes(update.sessionUpdate) ||
95
+ (update.sessionUpdate === "tool_call_update" && ["completed", "failed"].includes(update.status))) {
96
+ boundary = true;
97
+ }
98
+ };
99
+ const onLine = (line) => {
100
+ const incoming = JSON.parse(line);
101
+ if (incoming.method === "session/update" && collecting && incoming.params?.sessionId === session) {
102
+ onUpdate(incoming.params.update);
103
+ }
104
+ else if (incoming.method && incoming.id !== undefined) {
105
+ const { id, method, params } = incoming;
106
+ if (method === "session/request_permission" && params?.sessionId === session) {
107
+ send({ id, result: { outcome: permission(turn, { ...params, toolCall: toolCall(params.toolCall) }) } });
108
+ }
109
+ else
110
+ send({ id, error: { code: -32601, message: "不支持这个方法" } });
111
+ }
112
+ else if (pending.has(incoming.id)) {
113
+ const request = pending.get(incoming.id);
114
+ pending.delete(incoming.id);
115
+ if (incoming.error) {
116
+ // Open somewhere else just now isn't a no to the session: a new one would do its work again. The reason and not
117
+ // the code, which is generic: another agent's no under it has to stay a no, or it would never get a new session.
118
+ const inUse = incoming.error.data?.reason === "thread_active_writer";
119
+ request.reject(new (inUse ? Error : Refused)(incoming.error.message));
120
+ }
121
+ else
122
+ request.resolve(incoming.result);
123
+ }
124
+ };
125
+ let over = false;
126
+ eachLine(child.stdout, (line) => {
127
+ if (over)
128
+ return;
129
+ try {
130
+ onLine(line);
131
+ }
132
+ catch (error) {
133
+ fail(error);
134
+ }
135
+ },
136
+ // An agent that dies ends its output first, and its exit says more. One still there after this has hung up on us.
137
+ () => setTimeout(() => fail(new Error("ACP 在交回结果前关掉了输出")), 1000).unref());
138
+ const rpc = (method, params) => new Promise((resolve, reject) => {
139
+ const id = ++next;
140
+ pending.set(id, { resolve, reject });
141
+ send({ id, method, params });
142
+ });
143
+ const goOn = async (can) => {
144
+ const method = can?.loadSession ? "session/load" : can?.sessionCapabilities?.resume ? "session/resume" : null;
145
+ try {
146
+ if (!method)
147
+ throw new Refused("这个 ACP Agent 不支持恢复会话");
148
+ await rpc(method, { sessionId: session, cwd: turn.cwd, mcpServers: [] });
149
+ }
150
+ catch (error) {
151
+ if (error instanceof Refused)
152
+ console.log(JSON.stringify({ started: false }));
153
+ throw error;
154
+ }
155
+ };
156
+ const stop = () => child.kill("SIGTERM");
157
+ process.on("SIGTERM", stop);
158
+ try {
159
+ const clientInfo = { name: "agent-autoloop", version: versionName() };
160
+ const init = await rpc("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo });
161
+ if (init.protocolVersion !== 1)
162
+ throw new Error(`不支持 ACP 版本 ${init.protocolVersion}`);
163
+ if (turn.resume) {
164
+ session = turn.resume;
165
+ await goOn(init.agentCapabilities);
166
+ }
167
+ else {
168
+ const { sessionId } = await rpc("session/new", { cwd: turn.cwd, mcpServers: [] });
169
+ if (typeof sessionId !== "string" || !sessionId)
170
+ throw new Error("ACP 没有返回会话编号");
171
+ session = sessionId;
172
+ }
173
+ // Before the prompt goes: the agent can start on it at once, and this has to be there if the bridge is killed then.
174
+ console.log(JSON.stringify({ session, started: true }));
175
+ collecting = true;
176
+ const prompt = [{ type: "text", text: turn.prompt }];
177
+ const result = await rpc("session/prompt", { sessionId: session, prompt });
178
+ if (result.stopReason !== "end_turn")
179
+ throw new Error(`ACP 没有完成这一轮:${result.stopReason}`);
180
+ // end_turn with nothing said is not a turn that stopped early: an agent whose model refused answers this way, and the
181
+ // old reason quoted "end_turn" back as if it had failed, leaving no cause to look for.
182
+ if (!text.trim())
183
+ throw new Error("ACP 说这一轮结束了,但没有回文字");
184
+ console.log(JSON.stringify({ session, text, finished: true }));
185
+ }
186
+ catch (error) {
187
+ // Now and not on the way out: the agent, or what it left holding its output, can keep this process here for good,
188
+ // and this is what lets the worker end it.
189
+ console.log(JSON.stringify({ session: session || undefined, finished: true, error: error.message }));
190
+ throw error;
191
+ }
192
+ finally {
193
+ over = true;
194
+ process.removeListener("SIGTERM", stop);
195
+ child.stdin.end();
196
+ child.kill("SIGTERM");
197
+ }
198
+ }
199
+ if (import.meta.main) {
200
+ bridge(JSON.parse(process.argv[2])).catch((error) => {
201
+ console.error(error.message);
202
+ process.exitCode = 1;
203
+ });
204
+ }
@@ -0,0 +1,113 @@
1
+ // Claude Code: the user's own, installed and signed in by them. This only ever runs the official program.
2
+ import { execFileSync } from "node:child_process";
3
+ import { commandLine } from "../../host/command.js";
4
+ import { existsSync, readdirSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import path from "node:path";
7
+ import { findProgram, tail } from "../../worker/agents.js";
8
+ import { readMessage, receiptBlock } from "../../worker/contract.js";
9
+ const PERMISSIONS = { read: "plan", edit: "acceptEdits", full: "bypassPermissions" };
10
+ /** The newest Claude Code the desktop app ships, for those without a separate install. */
11
+ export function inTheApp() {
12
+ const root = path.join(homedir(), "Library/Application Support/Claude/claude-code");
13
+ if (!existsSync(root))
14
+ return [];
15
+ // The app keeps its own files, such as auto-update-state.json, beside the version folders.
16
+ const folders = (at) => readdirSync(at, { withFileTypes: true })
17
+ .filter((entry) => entry.isDirectory())
18
+ .map((entry) => entry.name);
19
+ const oldestFirst = folders(root).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
20
+ return oldestFirst.reverse().flatMap((version) => {
21
+ const builds = folders(path.join(root, version));
22
+ return builds.map((build) => path.join(root, version, build, "claude.app/Contents/MacOS/claude"));
23
+ });
24
+ }
25
+ export default {
26
+ command: (turn) => [
27
+ turn.program ?? findProgram("claude", inTheApp),
28
+ "-p",
29
+ turn.prompt,
30
+ ...(turn.resume ? ["--resume", turn.resume] : ["--session-id", turn.session]),
31
+ // As it goes: with "json" nothing comes out until the end, and a turn cut short leaves no sign it ever started.
32
+ "--output-format",
33
+ "stream-json",
34
+ "--verbose",
35
+ ...(turn.model ? ["--model", turn.model] : []),
36
+ ...(turn.effort ? ["--effort", turn.effort] : []),
37
+ "--permission-mode",
38
+ PERMISSIONS[turn.access],
39
+ "--add-dir",
40
+ turn.folder,
41
+ // Entering a worktree moves the whole transcript under the worktree's project folder (still so on 2.1.317): --resume
42
+ // finds it, but the desktop app, opening the session link from the run's folder, showed only its first message.
43
+ "--disallowedTools=EnterWorktree,ExitWorktree",
44
+ ],
45
+ read(stdout, code, stderr) {
46
+ const messages = stdout.split("\n").flatMap((line) => {
47
+ try {
48
+ // With "json" and verbose on in its settings, every message comes as one array on a single line.
49
+ return [JSON.parse(line)].flat();
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ });
55
+ const result = messages.findLast((message) => message?.type === "result");
56
+ const session = messages.findLast((message) => message?.session_id)?.session_id;
57
+ const started = result?.num_turns > 0 || messages.some((message) => message?.type === "assistant" || message?.subtype === "init");
58
+ const known = { ...(session && { session }), ...(started && { started }) };
59
+ // Each turn ends in a result, and a background task brings it back for another when it ends. Only one that's left
60
+ // nothing to come back for is its answer, unless it has exited by itself: then it was its last word.
61
+ const later = messages.slice(messages.lastIndexOf(result) + 1);
62
+ const another = later.some((message) => ["assistant", "user"].includes(message?.type) || message?.subtype === "init");
63
+ const tasks = messages.findLast((message) => message?.subtype === "background_tasks_changed")?.tasks ?? [];
64
+ if (!result || another || (tasks.length && code !== 0)) {
65
+ // Its messages are what it was doing, not what went wrong.
66
+ return code === null
67
+ ? known
68
+ : { ...known, error: tail(stderr || (messages.length ? "" : stdout)) || "没留下结果" };
69
+ }
70
+ // Its input_tokens leave out what was read from or written to the cache; `input` counts all of it, as Codex's does.
71
+ const usage = result.usage
72
+ ? {
73
+ input: (result.usage.input_tokens ?? 0) +
74
+ (result.usage.cache_read_input_tokens ?? 0) +
75
+ (result.usage.cache_creation_input_tokens ?? 0),
76
+ output: result.usage.output_tokens ?? 0,
77
+ cached: result.usage.cache_read_input_tokens ?? 0,
78
+ }
79
+ : undefined;
80
+ // Resumed, it goes on counting the price from the session so far, though its tokens start again.
81
+ const sessionUsage = result.total_cost_usd === undefined ? undefined : { cost: result.total_cost_usd };
82
+ const said = String(result.result ?? "");
83
+ // A background task that ends after its answer calls the run back for another turn, and that turn's word replaces the
84
+ // one that carried its receipt. What it asked of the hub is still what it wants, so the words stay the last turn's and
85
+ // the receipt is carried along: dropped, the card it asked for never exists and the work looks untouched.
86
+ // One it wrote wrongly is its own and is written again; only a turn with no receipt at all keeps the earlier one.
87
+ const own = readMessage(said);
88
+ const carried = own.receipt === undefined && own.problem === undefined
89
+ ? messages
90
+ .slice(0, messages.lastIndexOf(result))
91
+ .filter((message) => message?.type === "result")
92
+ .map((message) => receiptBlock(String(message.result ?? "")))
93
+ .findLast((block) => block !== undefined)
94
+ : undefined;
95
+ const text = carried === undefined ? said : `${said}\n\n${carried}`;
96
+ if (result.is_error || result.subtype !== "success") {
97
+ const error = said.split("\n")[0] || result.errors?.[0] || result.subtype || "没留下结果";
98
+ return { ...known, usage, sessionUsage, finished: true, error };
99
+ }
100
+ return { text, ...known, usage, sessionUsage, finished: true };
101
+ },
102
+ link: (session) => `claude://resume?session=${session}`,
103
+ check(given) {
104
+ try {
105
+ const program = given ?? findProgram("claude", inTheApp);
106
+ const status = JSON.parse(execFileSync(...commandLine([program, "auth", "status"]), { encoding: "utf8", timeout: 20_000 }));
107
+ return status.loggedIn ? null : "Claude Code 没有登录:运行 claude auth login";
108
+ }
109
+ catch (error) {
110
+ return `Claude Code 用不了:${error.message.split("\n")[0]}`;
111
+ }
112
+ },
113
+ };
@@ -0,0 +1,105 @@
1
+ // Codex: the user's own, installed and signed in by them. A run is a `codex exec` in the background; its thread is kept
2
+ // on disk, so a retry or an answer can go on in it, and the link opens it in the app.
3
+ import { execFileSync } from "node:child_process";
4
+ import { commandLine, powershell, psQuote } from "../../host/command.js";
5
+ import { findProgram, tail } from "../../worker/agents.js";
6
+ const SANDBOX = { read: "read-only", edit: "workspace-write", full: "danger-full-access" };
7
+ export const IN_THE_APP = [
8
+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex",
9
+ "/Applications/Codex.app/Contents/Resources/codex",
10
+ ];
11
+ export default {
12
+ command: (turn) => {
13
+ // The elevated Windows sandbox runs as CodexSandboxUsers. Share only the supplied data, never the run token or key.
14
+ if (process.platform === "win32" && turn.contextFile)
15
+ powershell(`
16
+ try { $sid = ([Security.Principal.NTAccount]::new($env:COMPUTERNAME, 'CodexSandboxUsers')).Translate([Security.Principal.SecurityIdentifier]) }
17
+ catch [Security.Principal.IdentityNotMappedException] { return }
18
+ $file = ${psQuote(turn.contextFile)}
19
+ # Gone between being written and this run, or a path that never was: nothing to share.
20
+ if (-not [IO.File]::Exists($file)) { return }
21
+ $acl = [IO.File]::GetAccessControl($file)
22
+ $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, 'Read', 'Allow'))
23
+ [IO.File]::SetAccessControl($file, $acl)
24
+ `);
25
+ return [
26
+ turn.program ?? findProgram("codex", () => IN_THE_APP),
27
+ "exec",
28
+ ...(turn.resume ? ["resume"] : []),
29
+ "--json",
30
+ "--skip-git-repo-check",
31
+ ...(turn.model ? ["-m", turn.model] : []),
32
+ ...(turn.effort ? ["-c", `model_reasoning_effort="${turn.effort}"`] : []),
33
+ // Unset, a run takes the tier in ~/.codex/config.toml, a file the Codex app shares: "priority" is its Fast.
34
+ ...(turn.tier ? ["-c", `service_tier="${turn.tier}"`] : []),
35
+ // As config, because `codex exec resume` takes no -s.
36
+ "-c",
37
+ `sandbox_mode="${SANDBOX[turn.access]}"`,
38
+ "-c",
39
+ 'approval_policy="never"',
40
+ ...(turn.resume ? [turn.resume] : []),
41
+ "本轮通过后台 codex exec 运行,不要假定桌面应用的浏览器连接已带到本轮。" +
42
+ "网页操作使用本轮实际可用的浏览器工具,或使用规则或 Skill 中已明确配置的浏览器入口。" +
43
+ "沿用该入口的会话,只交网页步骤,业务处理和中台回执仍由本轮负责;没有可用入口或需要本人恢复连接时,按待你处理的约定交回。\n\n" +
44
+ turn.prompt,
45
+ ];
46
+ },
47
+ read(stdout, code, stderr) {
48
+ const seen = {};
49
+ for (const line of stdout.split("\n")) {
50
+ let event;
51
+ try {
52
+ event = JSON.parse(line);
53
+ }
54
+ catch {
55
+ continue;
56
+ }
57
+ // A login shell's profile prints here too, and `null` is valid JSON.
58
+ if (!event)
59
+ continue;
60
+ if (event.type === "thread.started")
61
+ seen.session = event.thread_id;
62
+ else if (event.type === "turn.started")
63
+ seen.started = true;
64
+ else if (event.type === "item.completed" && event.item?.type === "agent_message")
65
+ seen.text = event.item.text;
66
+ else if (event.type === "turn.completed") {
67
+ seen.completed = seen.finished = true;
68
+ // A reconnect is announced as an error event and then got over — it fell back to another transport and carried
69
+ // on — so it isn't how the turn ended. A finished run was redone twelve times over one of these.
70
+ delete seen.error;
71
+ const { input_tokens = 0, output_tokens = 0, cached_input_tokens = 0 } = event.usage ?? {};
72
+ seen.sessionUsage = { input: input_tokens, output: output_tokens, cached: cached_input_tokens };
73
+ }
74
+ else if (event.type === "turn.failed") {
75
+ seen.finished = true;
76
+ seen.error = event.error?.message || "Codex 没跑完这一轮";
77
+ }
78
+ else if (event.type === "error")
79
+ seen.error = event.message;
80
+ }
81
+ const { completed, ...reading } = seen;
82
+ // Only a finished turn's last message is its answer; before that it's only as far as it had got.
83
+ if (!completed)
84
+ delete reading.text;
85
+ if (code !== null && !completed && !reading.error)
86
+ reading.error = tail(stderr) || "Codex 没有完成并留下实际结果";
87
+ if (completed && !reading.text?.trim())
88
+ reading.error = "Codex 没有完成并留下实际结果";
89
+ return reading;
90
+ },
91
+ link: (session) => `codex://threads/${session}`,
92
+ check(program) {
93
+ try {
94
+ execFileSync(...commandLine([program ?? findProgram("codex", () => IN_THE_APP), "login", "status"]), {
95
+ encoding: "utf8",
96
+ timeout: 20_000,
97
+ stdio: ["ignore", "pipe", "pipe"],
98
+ });
99
+ return null;
100
+ }
101
+ catch (error) {
102
+ return `Codex 没有登录或用不了:运行 codex login(${error.message.split("\n")[0]})`;
103
+ }
104
+ },
105
+ };
@@ -0,0 +1,25 @@
1
+ // Anything with a print mode: its command line in rules.json, its last message on stdout. A script is an agent too, and
2
+ // a plain command needn't take the prompt at all: it finds what it needs through the environment (AGENT_AUTOLOOP_CONTEXT).
3
+ import { tail } from "../../worker/agents.js";
4
+ const PLACEHOLDER = /\{(prompt|model|effort|cwd|context)\}/g;
5
+ export default {
6
+ // One pass, with a function: the prompt is what someone asked for, so a {cwd} or a $& inside those words is not a
7
+ // placeholder of its own and must arrive as written.
8
+ command: (turn) => {
9
+ const values = {
10
+ prompt: turn.prompt,
11
+ model: turn.model ?? "",
12
+ effort: turn.effort ?? "",
13
+ cwd: turn.cwd,
14
+ context: turn.contextFile,
15
+ };
16
+ return (turn.command ?? []).map((part) => part.replace(PLACEHOLDER, (_, name) => values[name]));
17
+ },
18
+ read(stdout, code, stderr) {
19
+ if (code === null)
20
+ return {};
21
+ if (code !== 0)
22
+ return { error: `退出码 ${code}:${tail(stderr || stdout) || "没留下原因"}` };
23
+ return { text: stdout };
24
+ },
25
+ };
@@ -0,0 +1,25 @@
1
+ // The Ship step's question, as a GitHub Action: does this commit need releasing, and has main already moved past it?
2
+ // Runs from a copy in the project, so it imports nothing beyond this folder's project.ts.
3
+ import { appendFileSync } from "node:fs";
4
+ import { git, liveRelease, readMainSettings, releaseRequired } from "./project.js";
5
+ export function decideShip(target, main, live, required) {
6
+ return { release: !live || required(live.sha, target), superseded: main !== target && required(target, main) };
7
+ }
8
+ if (import.meta.main) {
9
+ const root = process.cwd();
10
+ const target = process.env.INPUT_TARGET || process.env.GITHUB_SHA;
11
+ if (!target || !/^[a-f0-9]{40}$/.test(target))
12
+ throw new Error("发布目标要是完整提交编号");
13
+ git(root, "fetch", "origin", "main");
14
+ const main = git(root, "rev-parse", "origin/main");
15
+ const config = readMainSettings(root, process.env.INPUT_TEST_LOCAL_HEALTH === "true", target);
16
+ const live = await liveRelease(config);
17
+ const decision = decideShip(target, main, live, (base, head) => releaseRequired(root, base, head, config.internal));
18
+ const output = Object.entries(decision)
19
+ .map(([key, value]) => `${key}=${value}\n`)
20
+ .join("");
21
+ if (process.env.GITHUB_OUTPUT)
22
+ appendFileSync(process.env.GITHUB_OUTPUT, output);
23
+ else
24
+ process.stdout.write(output);
25
+ }
@@ -0,0 +1,13 @@
1
+ // The delivery as an agent: its process is run.ts, and what it prints is read the way any plain command's output is.
2
+ import { stablePath } from "../../host/node-path.js";
3
+ import { sibling } from "../../host/program.js";
4
+ import command from "../command/agent.js";
5
+ export default {
6
+ command: (turn) => [
7
+ stablePath(process.execPath),
8
+ "--disable-warning=ExperimentalWarning",
9
+ sibling(import.meta.dirname, "run.ts"),
10
+ ...(turn.command ?? []),
11
+ ],
12
+ read: command.read,
13
+ };