@prestyj/cli 5.38.0 → 5.39.1

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 (229) hide show
  1. package/README.md +92 -42
  2. package/dist/app-sidecar/fleet-adapter.d.ts +138 -0
  3. package/dist/app-sidecar/fleet-adapter.js +356 -0
  4. package/dist/app-sidecar/fleet-adapter.js.map +1 -0
  5. package/dist/app-sidecar/fleet-routes.d.ts +4 -0
  6. package/dist/app-sidecar/fleet-routes.js +109 -0
  7. package/dist/app-sidecar/fleet-routes.js.map +1 -0
  8. package/dist/app-sidecar/goal-routes.d.ts +20 -0
  9. package/dist/app-sidecar/goal-routes.js +42 -1
  10. package/dist/app-sidecar/goal-routes.js.map +1 -1
  11. package/dist/app-sidecar.js +5 -0
  12. package/dist/app-sidecar.js.map +1 -1
  13. package/dist/cli/cloud.d.ts +45 -0
  14. package/dist/cli/cloud.js +241 -0
  15. package/dist/cli/cloud.js.map +1 -0
  16. package/dist/cli/command-routing.d.ts +3 -2
  17. package/dist/cli/command-routing.js +24 -3
  18. package/dist/cli/command-routing.js.map +1 -1
  19. package/dist/cli/fleet.d.ts +19 -3
  20. package/dist/cli/fleet.js +107 -33
  21. package/dist/cli/fleet.js.map +1 -1
  22. package/dist/cli/goals.d.ts +11 -0
  23. package/dist/cli/goals.js +115 -0
  24. package/dist/cli/goals.js.map +1 -0
  25. package/dist/cli/node.d.ts +18 -1
  26. package/dist/cli/node.js +303 -33
  27. package/dist/cli/node.js.map +1 -1
  28. package/dist/cli.js +6 -0
  29. package/dist/cli.js.map +1 -1
  30. package/dist/core/agent-session.d.ts +8 -0
  31. package/dist/core/agent-session.js +18 -1
  32. package/dist/core/agent-session.js.map +1 -1
  33. package/dist/core/cloud/claude.d.ts +128 -0
  34. package/dist/core/cloud/claude.js +836 -0
  35. package/dist/core/cloud/claude.js.map +1 -0
  36. package/dist/core/cloud/cloud-agent.d.ts +136 -0
  37. package/dist/core/cloud/cloud-agent.js +783 -0
  38. package/dist/core/cloud/cloud-agent.js.map +1 -0
  39. package/dist/core/cloud/codex.d.ts +154 -0
  40. package/dist/core/cloud/codex.js +622 -0
  41. package/dist/core/cloud/codex.js.map +1 -0
  42. package/dist/core/cloud/config.d.ts +69 -0
  43. package/dist/core/cloud/config.js +86 -0
  44. package/dist/core/cloud/config.js.map +1 -0
  45. package/dist/core/cloud/git.d.ts +15 -0
  46. package/dist/core/cloud/git.js +33 -0
  47. package/dist/core/cloud/git.js.map +1 -0
  48. package/dist/core/cloud/registry.d.ts +13 -0
  49. package/dist/core/cloud/registry.js +64 -0
  50. package/dist/core/cloud/registry.js.map +1 -0
  51. package/dist/core/cloud/runner.d.ts +46 -0
  52. package/dist/core/cloud/runner.js +99 -0
  53. package/dist/core/cloud/runner.js.map +1 -0
  54. package/dist/core/cloud/snapshot.d.ts +23 -0
  55. package/dist/core/cloud/snapshot.js +98 -0
  56. package/dist/core/cloud/snapshot.js.map +1 -0
  57. package/dist/core/cloud/types.d.ts +139 -0
  58. package/dist/core/cloud/types.js +28 -0
  59. package/dist/core/cloud/types.js.map +1 -0
  60. package/dist/core/fleet/client.d.ts +106 -6
  61. package/dist/core/fleet/client.js +352 -20
  62. package/dist/core/fleet/client.js.map +1 -1
  63. package/dist/core/fleet/cloud-jobs.d.ts +59 -0
  64. package/dist/core/fleet/cloud-jobs.js +131 -0
  65. package/dist/core/fleet/cloud-jobs.js.map +1 -0
  66. package/dist/core/fleet/discovery.d.ts +2 -0
  67. package/dist/core/fleet/discovery.js +3 -1
  68. package/dist/core/fleet/discovery.js.map +1 -1
  69. package/dist/core/fleet/fleet-scheduler.d.ts +4 -0
  70. package/dist/core/fleet/fleet-scheduler.js +11 -1
  71. package/dist/core/fleet/fleet-scheduler.js.map +1 -1
  72. package/dist/core/fleet/git.d.ts +7 -0
  73. package/dist/core/fleet/git.js +22 -1
  74. package/dist/core/fleet/git.js.map +1 -1
  75. package/dist/core/fleet/machines.d.ts +112 -0
  76. package/dist/core/fleet/machines.js +219 -0
  77. package/dist/core/fleet/machines.js.map +1 -0
  78. package/dist/core/fleet/node/agents.d.ts +2 -0
  79. package/dist/core/fleet/node/agents.js +195 -9
  80. package/dist/core/fleet/node/agents.js.map +1 -1
  81. package/dist/core/fleet/node/config.d.ts +37 -3
  82. package/dist/core/fleet/node/config.js +201 -40
  83. package/dist/core/fleet/node/config.js.map +1 -1
  84. package/dist/core/fleet/node/context.d.ts +19 -1
  85. package/dist/core/fleet/node/docker.d.ts +13 -5
  86. package/dist/core/fleet/node/docker.js +132 -66
  87. package/dist/core/fleet/node/docker.js.map +1 -1
  88. package/dist/core/fleet/node/doctor.d.ts +29 -0
  89. package/dist/core/fleet/node/doctor.js +202 -0
  90. package/dist/core/fleet/node/doctor.js.map +1 -0
  91. package/dist/core/fleet/node/env.d.ts +7 -0
  92. package/dist/core/fleet/node/env.js +51 -0
  93. package/dist/core/fleet/node/env.js.map +1 -0
  94. package/dist/core/fleet/node/gc.d.ts +46 -0
  95. package/dist/core/fleet/node/gc.js +140 -0
  96. package/dist/core/fleet/node/gc.js.map +1 -0
  97. package/dist/core/fleet/node/goals.d.ts +43 -0
  98. package/dist/core/fleet/node/goals.js +418 -0
  99. package/dist/core/fleet/node/goals.js.map +1 -0
  100. package/dist/core/fleet/node/jobs.d.ts +37 -2
  101. package/dist/core/fleet/node/jobs.js +236 -15
  102. package/dist/core/fleet/node/jobs.js.map +1 -1
  103. package/dist/core/fleet/node/local-client.d.ts +9 -0
  104. package/dist/core/fleet/node/local-client.js +29 -0
  105. package/dist/core/fleet/node/local-client.js.map +1 -0
  106. package/dist/core/fleet/node/ops-routes.d.ts +15 -0
  107. package/dist/core/fleet/node/ops-routes.js +84 -0
  108. package/dist/core/fleet/node/ops-routes.js.map +1 -0
  109. package/dist/core/fleet/node/pair-code-route.d.ts +14 -0
  110. package/dist/core/fleet/node/pair-code-route.js +76 -0
  111. package/dist/core/fleet/node/pair-code-route.js.map +1 -0
  112. package/dist/core/fleet/node/secrets.d.ts +43 -0
  113. package/dist/core/fleet/node/secrets.js +184 -0
  114. package/dist/core/fleet/node/secrets.js.map +1 -0
  115. package/dist/core/fleet/node/server.d.ts +22 -1
  116. package/dist/core/fleet/node/server.js +210 -21
  117. package/dist/core/fleet/node/server.js.map +1 -1
  118. package/dist/core/fleet/node/state.d.ts +24 -1
  119. package/dist/core/fleet/node/state.js +12 -3
  120. package/dist/core/fleet/node/state.js.map +1 -1
  121. package/dist/core/fleet/node/tls.d.ts +17 -0
  122. package/dist/core/fleet/node/tls.js +49 -0
  123. package/dist/core/fleet/node/tls.js.map +1 -0
  124. package/dist/core/fleet/node/uninstall.d.ts +27 -0
  125. package/dist/core/fleet/node/uninstall.js +100 -0
  126. package/dist/core/fleet/node/uninstall.js.map +1 -0
  127. package/dist/core/fleet/node/update.d.ts +28 -0
  128. package/dist/core/fleet/node/update.js +62 -0
  129. package/dist/core/fleet/node/update.js.map +1 -0
  130. package/dist/core/fleet/node/workspace.d.ts +4 -0
  131. package/dist/core/fleet/node/workspace.js +38 -9
  132. package/dist/core/fleet/node/workspace.js.map +1 -1
  133. package/dist/core/fleet/node-load.d.ts +4 -0
  134. package/dist/core/fleet/node-load.js +62 -0
  135. package/dist/core/fleet/node-load.js.map +1 -0
  136. package/dist/core/fleet/project-config.d.ts +10 -0
  137. package/dist/core/fleet/project-config.js +39 -1
  138. package/dist/core/fleet/project-config.js.map +1 -1
  139. package/dist/core/fleet/prompt-hint.d.ts +11 -0
  140. package/dist/core/fleet/prompt-hint.js +47 -0
  141. package/dist/core/fleet/prompt-hint.js.map +1 -0
  142. package/dist/core/fleet/propose-config.d.ts +26 -0
  143. package/dist/core/fleet/propose-config.js +95 -0
  144. package/dist/core/fleet/propose-config.js.map +1 -0
  145. package/dist/core/fleet/protocol.d.ts +97 -1
  146. package/dist/core/fleet/protocol.js +10 -1
  147. package/dist/core/fleet/protocol.js.map +1 -1
  148. package/dist/core/fleet/registry.d.ts +12 -1
  149. package/dist/core/fleet/registry.js +39 -7
  150. package/dist/core/fleet/registry.js.map +1 -1
  151. package/dist/core/fleet/remote-agent-nodes.d.ts +56 -8
  152. package/dist/core/fleet/remote-agent-nodes.js +162 -22
  153. package/dist/core/fleet/remote-agent-nodes.js.map +1 -1
  154. package/dist/core/fleet/remote-agent.d.ts +52 -1
  155. package/dist/core/fleet/remote-agent.js +220 -40
  156. package/dist/core/fleet/remote-agent.js.map +1 -1
  157. package/dist/core/fleet/service.d.ts +95 -3
  158. package/dist/core/fleet/service.js +762 -35
  159. package/dist/core/fleet/service.js.map +1 -1
  160. package/dist/core/fleet/store.js +22 -5
  161. package/dist/core/fleet/store.js.map +1 -1
  162. package/dist/core/fleet/types.d.ts +36 -1
  163. package/dist/core/fleet/types.js +12 -2
  164. package/dist/core/fleet/types.js.map +1 -1
  165. package/dist/core/goal-controller.d.ts +1 -0
  166. package/dist/core/goal-controller.js +1 -1
  167. package/dist/core/goal-controller.js.map +1 -1
  168. package/dist/core/goal-fleet.d.ts +117 -0
  169. package/dist/core/goal-fleet.js +441 -0
  170. package/dist/core/goal-fleet.js.map +1 -0
  171. package/dist/core/goal-headless.d.ts +45 -0
  172. package/dist/core/goal-headless.js +177 -0
  173. package/dist/core/goal-headless.js.map +1 -0
  174. package/dist/core/goal-remote-worker.d.ts +45 -0
  175. package/dist/core/goal-remote-worker.js +157 -0
  176. package/dist/core/goal-remote-worker.js.map +1 -0
  177. package/dist/core/goal-store.d.ts +36 -0
  178. package/dist/core/goal-store.js +69 -1
  179. package/dist/core/goal-store.js.map +1 -1
  180. package/dist/core/goal-verifier.d.ts +5 -0
  181. package/dist/core/goal-verifier.js +10 -0
  182. package/dist/core/goal-verifier.js.map +1 -1
  183. package/dist/core/goal-worker.d.ts +12 -0
  184. package/dist/core/goal-worker.js +162 -8
  185. package/dist/core/goal-worker.js.map +1 -1
  186. package/dist/core/subagent-manager.d.ts +12 -5
  187. package/dist/core/subagent-manager.js +15 -10
  188. package/dist/core/subagent-manager.js.map +1 -1
  189. package/dist/core/validation/backends.d.ts +34 -5
  190. package/dist/core/validation/backends.js +45 -5
  191. package/dist/core/validation/backends.js.map +1 -1
  192. package/dist/core/validation/cloud-backend.d.ts +77 -0
  193. package/dist/core/validation/cloud-backend.js +343 -0
  194. package/dist/core/validation/cloud-backend.js.map +1 -0
  195. package/dist/core/validation/config.js +9 -2
  196. package/dist/core/validation/config.js.map +1 -1
  197. package/dist/core/validation/node-backend.d.ts +2 -0
  198. package/dist/core/validation/node-backend.js +5 -0
  199. package/dist/core/validation/node-backend.js.map +1 -1
  200. package/dist/core/validation/scheduler.d.ts +11 -0
  201. package/dist/core/validation/scheduler.js +34 -7
  202. package/dist/core/validation/scheduler.js.map +1 -1
  203. package/dist/core/validation/service.d.ts +6 -0
  204. package/dist/core/validation/service.js +51 -13
  205. package/dist/core/validation/service.js.map +1 -1
  206. package/dist/core/validation/types.d.ts +14 -0
  207. package/dist/modes/acp-mode.d.ts +3 -1
  208. package/dist/modes/acp-mode.js +2 -1
  209. package/dist/modes/acp-mode.js.map +1 -1
  210. package/dist/system-prompt.d.ts +5 -0
  211. package/dist/system-prompt.js +3 -0
  212. package/dist/system-prompt.js.map +1 -1
  213. package/dist/tools/fleet.d.ts +40 -4
  214. package/dist/tools/fleet.js +228 -17
  215. package/dist/tools/fleet.js.map +1 -1
  216. package/dist/tools/goals.d.ts +4 -1
  217. package/dist/tools/goals.js +45 -5
  218. package/dist/tools/goals.js.map +1 -1
  219. package/dist/tools/index.d.ts +7 -0
  220. package/dist/tools/index.js +6 -1
  221. package/dist/tools/index.js.map +1 -1
  222. package/dist/tools/steroids.d.ts +1 -1
  223. package/dist/tools/subagent-control.js +1 -1
  224. package/dist/tools/subagent-control.js.map +1 -1
  225. package/dist/tools/validate.js +1 -1
  226. package/dist/tools/validate.js.map +1 -1
  227. package/dist/ui/App.js +2 -0
  228. package/dist/ui/App.js.map +1 -1
  229. package/package.json +6 -4
@@ -0,0 +1,783 @@
1
+ // Helper agents in the cloud (spawn_agent machine "claude-cloud",
2
+ // "codex-cloud", "cloud", or "auto" when no fleet node can take it). A
3
+ // CloudWorkerProcess looks like a sub-agent worker child process to
4
+ // SubAgentManager: it answers the JSON-lines worker protocol on stdin/stdout,
5
+ // but each turn is a cloud task (provider.start, then provider.send for
6
+ // follow-ups) polled every few seconds. Commands the provider's harness
7
+ // recorded become tool_call_start events and the turn's receipt; edits come
8
+ // back with provider.diff() + applyRemoteDelta() (conflicts kept aside), or
9
+ // stay in the cloud session when the provider can't hand them back.
10
+ import { EventEmitter } from "node:events";
11
+ import fs from "node:fs/promises";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { PassThrough, Writable } from "node:stream";
15
+ import { log } from "../logger.js";
16
+ import { applyRemoteDelta, RemoteWorkerProcess, } from "../fleet/remote-agent.js";
17
+ import { pickAutoNode, probeNode, readFleetNodes } from "../fleet/remote-agent-nodes.js";
18
+ import { codexTaskUrl } from "./codex.js";
19
+ import { benchProvider, cloudAllowedFor, readCloudSettings, recordUtilization, } from "./config.js";
20
+ import { git, githubRepoFromUrl, runGit } from "./git.js";
21
+ import { cloudAvailability, cloudProvider } from "./registry.js";
22
+ import { isSecretLikePath } from "./snapshot.js";
23
+ import { CLOUD_LABELS, CloudError, isCloudProviderId, } from "./types.js";
24
+ const DEFAULT_POLL_MS = 5_000;
25
+ /** Consecutive failed polls before the turn is given up (~1 min at 5 s). */
26
+ const MAX_POLL_FAILURES = 12;
27
+ const AGENT_MAX_TURNS = 200;
28
+ export const DEFAULT_CLAUDE_AGENT_MODEL = "claude-sonnet-5-5";
29
+ const RECEIPT_COMMANDS = 40;
30
+ /** Whether a provider hands file changes back through diff(). */
31
+ const EDITS_COME_BACK = {
32
+ // diff() runs a sync turn in the session and reads the harness's record.
33
+ "claude-cloud": true,
34
+ "codex-cloud": true,
35
+ };
36
+ /** spawn_agent `machine` values that mean the cloud. */
37
+ export function isCloudMachine(machine) {
38
+ return machine === "cloud" || isCloudProviderId(machine);
39
+ }
40
+ /** remote_agent_id of a cloud agent: "<task id>@<base commit>". */
41
+ export function cloudAgentId(handle) {
42
+ return handle.baseCommit ? `${handle.id}@${handle.baseCommit}` : handle.id;
43
+ }
44
+ export function parseCloudAgentId(value) {
45
+ const at = value.lastIndexOf("@");
46
+ return at > 0 ? { id: value.slice(0, at), baseCommit: value.slice(at + 1) } : { id: value };
47
+ }
48
+ /** The cloud model for a child: the parent's when it's the provider's family. */
49
+ export function cloudAgentModel(id, model) {
50
+ if (id === "claude-cloud") {
51
+ return model && /^claude-/.test(model) ? model : DEFAULT_CLAUDE_AGENT_MODEL;
52
+ }
53
+ // Codex cloud tasks take no model parameter.
54
+ return undefined;
55
+ }
56
+ function taskUrl(id, taskId) {
57
+ return id === "codex-cloud" ? codexTaskUrl(taskId) : `https://claude.ai/code/${taskId}`;
58
+ }
59
+ function safeDirName(id) {
60
+ return id.replace(/[^A-Za-z0-9._-]/g, "_");
61
+ }
62
+ /** Repo root and GitHub owner/name of `cwd`, best effort. */
63
+ async function projectOf(cwd) {
64
+ const top = await runGit(cwd, ["rev-parse", "--show-toplevel"]).catch(() => undefined);
65
+ if (!top || top.code !== 0)
66
+ return {};
67
+ const repoRoot = top.stdout.toString().trim();
68
+ const origin = await runGit(repoRoot, ["remote", "get-url", "origin"]);
69
+ const repo = origin.code === 0 ? githubRepoFromUrl(origin.stdout.toString()) : undefined;
70
+ return { repoRoot, ...(repo && { repo }) };
71
+ }
72
+ /**
73
+ * HEAD plus uncommitted work (tracked edits and untracked, not-ignored files)
74
+ * as a binary patch, built in a private index. Credential-like files keep
75
+ * their committed version (or stay out).
76
+ */
77
+ export async function prepareCloudSource(cwd) {
78
+ const project = await projectOf(cwd);
79
+ if (!project.repoRoot) {
80
+ throw new Error(`Running an agent in the cloud needs a git repository; ${cwd} is not in one. Leave machine unset to run locally.`);
81
+ }
82
+ const repoRoot = project.repoRoot;
83
+ const subdir = (await git(cwd, ["rev-parse", "--show-prefix"])).trim().replace(/\/+$/, "");
84
+ let sha;
85
+ try {
86
+ sha = (await git(repoRoot, ["rev-parse", "--verify", "HEAD"])).trim();
87
+ }
88
+ catch {
89
+ throw new Error(`${repoRoot} has no commits yet. Commit first, or leave machine unset.`);
90
+ }
91
+ const branch = (await runGit(repoRoot, ["symbolic-ref", "--short", "-q", "HEAD"])).stdout
92
+ .toString()
93
+ .trim();
94
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "ez-cloud-src-"));
95
+ try {
96
+ const env = { ...process.env, GIT_INDEX_FILE: path.join(tmp, "index") };
97
+ await git(repoRoot, ["read-tree", sha], { env });
98
+ await git(repoRoot, ["add", "-A"], { env });
99
+ const changed = (await git(repoRoot, ["diff", "--cached", "--name-only", "-z", sha], { env }))
100
+ .split("\0")
101
+ .filter(Boolean);
102
+ const withheld = changed.filter(isSecretLikePath);
103
+ for (const file of withheld) {
104
+ const inHead = await runGit(repoRoot, ["cat-file", "-e", `${sha}:${file}`]);
105
+ if (inHead.code === 0)
106
+ await git(repoRoot, ["reset", "-q", sha, "--", file], { env });
107
+ else
108
+ await git(repoRoot, ["rm", "-q", "--cached", "--", file], { env });
109
+ }
110
+ const patch = (await runGit(repoRoot, ["-c", "core.quotepath=false", "diff", "--cached", "--binary", "--no-ext-diff", sha], { env })).stdout;
111
+ return {
112
+ subdir,
113
+ withheld,
114
+ source: {
115
+ repoRoot,
116
+ sha,
117
+ ...(project.repo && { repo: project.repo }),
118
+ ...(branch && { branch }),
119
+ ...(patch.length > 0 && { patch }),
120
+ },
121
+ };
122
+ }
123
+ finally {
124
+ await fs.rm(tmp, { recursive: true, force: true });
125
+ }
126
+ }
127
+ export function cloudAgentPrompt(task, subdir) {
128
+ return [
129
+ "You are a helper agent started by EZ Coder. This repository is a copy of the user's local " +
130
+ "checkout, including their uncommitted work" +
131
+ (subdir ? `; work in ${subdir}/.` : "."),
132
+ "Do the task below in this repository. Do not push, open pull requests or create branches.",
133
+ "When you are done, finish with a short summary: what you did, which files you changed, and how you checked it.",
134
+ "Afterwards EZ Coder may ask you to run one exact command that prints your changes as a packed diff, " +
135
+ "so they can be copied back to the user's computer: that request is expected, please run it as given.",
136
+ "",
137
+ "Task:",
138
+ task,
139
+ ].join("\n");
140
+ }
141
+ /** Serialize edits into one repo (several agents may finish at once). */
142
+ const repoLocks = new Map();
143
+ function withRepoLock(repoRoot, task) {
144
+ const run = (repoLocks.get(repoRoot) ?? Promise.resolve()).catch(() => undefined).then(task);
145
+ repoLocks.set(repoRoot, run);
146
+ void run.finally(() => {
147
+ if (repoLocks.get(repoRoot) === run)
148
+ repoLocks.delete(repoRoot);
149
+ });
150
+ return run;
151
+ }
152
+ export class CloudWorkerProcess extends EventEmitter {
153
+ spawnOptions;
154
+ stdout = new PassThrough();
155
+ stderr = new PassThrough();
156
+ stdin;
157
+ pid = undefined;
158
+ exitCode = null;
159
+ signalCode = null;
160
+ killed = false;
161
+ /** Resolves once the provider (and, on resume, the task) is known. */
162
+ attached;
163
+ machine;
164
+ providerId;
165
+ handle;
166
+ provider;
167
+ stateDir;
168
+ /** A cloud task being created; kill waits for it so the task is archived, not leaked. */
169
+ starting;
170
+ archiving;
171
+ interruptOnStart = false;
172
+ subdir = "";
173
+ model;
174
+ partial = "";
175
+ finished = false;
176
+ turn;
177
+ gen = 0;
178
+ timer;
179
+ lastStatus;
180
+ pollMs;
181
+ constructor(spawnOptions) {
182
+ super();
183
+ this.spawnOptions = spawnOptions;
184
+ this.machine = spawnOptions.resume?.node ?? spawnOptions.machine;
185
+ this.pollMs = spawnOptions.pollMs ?? DEFAULT_POLL_MS;
186
+ this.stdin = new Writable({
187
+ write: (chunk, _encoding, callback) => {
188
+ const lines = (this.partial + chunk.toString()).split("\n");
189
+ this.partial = lines.pop() ?? "";
190
+ for (const line of lines)
191
+ if (line.trim())
192
+ void this.onLine(line);
193
+ callback();
194
+ },
195
+ });
196
+ this.attached = this.attach();
197
+ this.attached.catch((error) => {
198
+ void this.finish(1, null, error instanceof Error ? error.message : String(error));
199
+ });
200
+ }
201
+ label() {
202
+ return this.providerId ? CLOUD_LABELS[this.providerId] : "the cloud";
203
+ }
204
+ getProvider(id) {
205
+ return (this.spawnOptions.provider ?? cloudProvider)(id);
206
+ }
207
+ async attach() {
208
+ const { resume, stateRoot, cwd } = this.spawnOptions;
209
+ if (resume) {
210
+ if (!isCloudProviderId(resume.node))
211
+ throw new Error(`Unknown cloud "${resume.node}"`);
212
+ this.providerId = resume.node;
213
+ this.provider = this.getProvider(resume.node);
214
+ const { id, baseCommit } = parseCloudAgentId(resume.remoteAgentId);
215
+ this.stateDir = path.join(stateRoot, safeDirName(id));
216
+ const saved = await fs
217
+ .readFile(path.join(this.stateDir, "state.json"), "utf-8")
218
+ .then((raw) => JSON.parse(raw))
219
+ .catch(() => undefined);
220
+ const repoRoot = saved?.repoRoot ?? (await projectOf(cwd)).repoRoot;
221
+ if (!repoRoot)
222
+ throw new Error(`${cwd} is no longer a git repository`);
223
+ this.subdir = saved?.subdir ?? "";
224
+ this.handle = {
225
+ provider: resume.node,
226
+ id,
227
+ url: saved?.url ?? taskUrl(resume.node, id),
228
+ repoRoot,
229
+ ...((baseCommit ?? saved?.baseCommit) && { baseCommit: baseCommit ?? saved?.baseCommit }),
230
+ ...(saved?.baseTree && { baseTree: saved.baseTree }),
231
+ };
232
+ this.machine = resume.node;
233
+ return { resumed: false };
234
+ }
235
+ if (this.machine !== "cloud" && this.machine !== "auto" && !isCloudProviderId(this.machine)) {
236
+ throw new Error(`Unknown cloud "${this.machine}"`);
237
+ }
238
+ const project = await projectOf(cwd);
239
+ const availability = await (this.spawnOptions.availability ?? ((p) => cloudAvailability("agents", p)))(project);
240
+ const pinned = isCloudProviderId(this.machine) ? this.machine : undefined;
241
+ const pick = availability.find((a) => a.available && (!pinned || a.id === pinned));
242
+ if (!pick) {
243
+ const relevant = availability.filter((a) => !pinned || a.id === pinned);
244
+ const reasons = relevant
245
+ .map((a) => `${CLOUD_LABELS[a.id]}: ${a.detail}${a.setupHint ? ` (${a.setupHint})` : ""}`)
246
+ .join("; ");
247
+ throw new Error(pinned
248
+ ? `${CLOUD_LABELS[pinned]} can't run an agent now: ${reasons || "not configured"}`
249
+ : `No cloud can run an agent now (${reasons || "none configured"}).`);
250
+ }
251
+ this.providerId = pick.id;
252
+ this.provider = this.getProvider(pick.id);
253
+ this.machine = pick.id;
254
+ return { resumed: false };
255
+ }
256
+ kill(signal = "SIGTERM") {
257
+ if (this.finished)
258
+ return false;
259
+ this.killed = true;
260
+ const name = typeof signal === "string" ? signal : "SIGTERM";
261
+ this.stopPolling();
262
+ void (this.starting ?? Promise.resolve())
263
+ .catch(() => undefined)
264
+ .then(() => this.archive())
265
+ .then(() => this.finish(null, name));
266
+ return true;
267
+ }
268
+ /**
269
+ * Stop watching without archiving the task (as a parent restart does); the
270
+ * cloud task keeps running and recovery re-attaches to it.
271
+ */
272
+ detach() {
273
+ void this.finish(null, null);
274
+ }
275
+ emitFrame(frame) {
276
+ if (!this.finished)
277
+ this.stdout.write(`${JSON.stringify(frame)}\n`);
278
+ }
279
+ ack(requestId, result = {}) {
280
+ this.emitFrame({ type: "ack", request_id: requestId, ok: true, ...result });
281
+ }
282
+ reject(requestId, error) {
283
+ this.emitFrame({
284
+ type: "ack",
285
+ request_id: requestId,
286
+ ok: false,
287
+ error: error instanceof Error ? error.message : String(error),
288
+ });
289
+ }
290
+ async onLine(line) {
291
+ let command;
292
+ try {
293
+ command = JSON.parse(line);
294
+ }
295
+ catch {
296
+ this.emitFrame({ type: "protocol_error", error: "Invalid command frame" });
297
+ return;
298
+ }
299
+ const requestId = String(command.request_id ?? "");
300
+ try {
301
+ switch (command.command) {
302
+ case "initialize":
303
+ this.model = command.options?.model;
304
+ this.ack(requestId, {
305
+ ...(this.providerId && {
306
+ model: cloudAgentModel(this.providerId, this.model) ?? this.model,
307
+ }),
308
+ });
309
+ return;
310
+ case "start":
311
+ case "followup":
312
+ if (this.turn)
313
+ throw new Error("Worker already has an active turn");
314
+ this.turn = {
315
+ gen: ++this.gen,
316
+ turnsBefore: 0,
317
+ commandsBefore: 0,
318
+ tokensBefore: { input: 0, output: 0 },
319
+ failures: 0,
320
+ };
321
+ this.ack(requestId, { status: "running" });
322
+ void this.runTurn(this.turn, String(command.task ?? ""));
323
+ return;
324
+ case "queue_message":
325
+ if (!this.turn || !this.handle)
326
+ throw new Error("Worker is not running");
327
+ await this.provider.send(this.handle, String(command.message ?? ""));
328
+ this.ack(requestId, { queued: 1 });
329
+ return;
330
+ case "interrupt": {
331
+ const turn = this.turn;
332
+ if (!turn)
333
+ throw new Error("Worker is not running");
334
+ // Still starting: runTurn interrupts the task once it exists.
335
+ if (this.handle)
336
+ await this.provider.interrupt(this.handle);
337
+ else
338
+ this.interruptOnStart = true;
339
+ this.ack(requestId);
340
+ if (this.turn === turn)
341
+ await this.completeTurn(turn, "interrupted", "Interrupted");
342
+ return;
343
+ }
344
+ case "shutdown":
345
+ this.stopPolling();
346
+ this.turn = undefined;
347
+ await this.archive();
348
+ this.ack(requestId);
349
+ await this.finish(0, null);
350
+ return;
351
+ default:
352
+ throw new Error(`Unknown command: ${String(command.command)}`);
353
+ }
354
+ }
355
+ catch (error) {
356
+ this.reject(requestId, error);
357
+ }
358
+ }
359
+ async runTurn(turn, task) {
360
+ try {
361
+ await this.attached;
362
+ const provider = this.provider;
363
+ if (!this.handle) {
364
+ const prepared = await prepareCloudSource(this.spawnOptions.cwd);
365
+ this.subdir = prepared.subdir;
366
+ if (prepared.withheld.length) {
367
+ this.stderr.write(`Kept out of the cloud copy (look like credentials): ${prepared.withheld.join(", ")}\n`);
368
+ }
369
+ if (this.killed || this.finished)
370
+ return;
371
+ const firstLine = task.trim().split("\n")[0] ?? "";
372
+ const starting = provider.start({
373
+ title: `EZ Coder helper: ${firstLine.slice(0, 80)}`,
374
+ prompt: cloudAgentPrompt(task, prepared.subdir),
375
+ source: prepared.source,
376
+ ...(cloudAgentModel(provider.id, this.model) && {
377
+ model: cloudAgentModel(provider.id, this.model),
378
+ }),
379
+ maxTurns: AGENT_MAX_TURNS,
380
+ });
381
+ this.starting = starting.then(async (handle) => {
382
+ this.handle = { ...handle, repoRoot: handle.repoRoot ?? prepared.source.repoRoot };
383
+ await this.saveState();
384
+ });
385
+ // Observed here; kill() awaits it too, so it must never go unhandled.
386
+ this.starting.catch(() => undefined);
387
+ const handle = await starting;
388
+ await this.starting;
389
+ this.spawnOptions.onRemote?.({ node: provider.id, remoteAgentId: cloudAgentId(handle) });
390
+ log("INFO", "subagent", "Cloud agent started", { provider: provider.id, url: handle.url });
391
+ if (this.killed) {
392
+ await this.archive();
393
+ return;
394
+ }
395
+ if (this.interruptOnStart) {
396
+ // Interrupted before the task existed.
397
+ this.interruptOnStart = false;
398
+ await provider.interrupt(this.handle ?? handle).catch(() => undefined);
399
+ }
400
+ if (this.turn !== turn)
401
+ return;
402
+ }
403
+ else {
404
+ const before = await provider.status(this.handle);
405
+ turn.turnsBefore = before.turns;
406
+ turn.commandsBefore = before.commands.length;
407
+ turn.tokensBefore = {
408
+ input: before.usageTokens?.input ?? 0,
409
+ output: before.usageTokens?.output ?? 0,
410
+ };
411
+ this.lastStatus = before;
412
+ await provider.send(this.handle, task);
413
+ }
414
+ this.schedulePoll(turn);
415
+ }
416
+ catch (error) {
417
+ if (this.turn === turn) {
418
+ await this.completeTurn(turn, "failed", error instanceof Error ? error.message : String(error));
419
+ }
420
+ }
421
+ }
422
+ schedulePoll(turn) {
423
+ if (this.finished || this.turn !== turn)
424
+ return;
425
+ clearTimeout(this.timer);
426
+ this.timer = setTimeout(() => void this.poll(turn), this.pollMs);
427
+ this.timer.unref?.();
428
+ }
429
+ stopPolling() {
430
+ clearTimeout(this.timer);
431
+ this.timer = undefined;
432
+ }
433
+ async poll(turn) {
434
+ if (this.finished || this.turn !== turn || !this.handle)
435
+ return;
436
+ let status;
437
+ try {
438
+ status = await this.provider.status(this.handle);
439
+ turn.failures = 0;
440
+ }
441
+ catch (error) {
442
+ turn.failures++;
443
+ const message = error instanceof Error ? error.message : String(error);
444
+ if ((error instanceof CloudError && error.code === "not_found") ||
445
+ turn.failures >= MAX_POLL_FAILURES) {
446
+ await this.completeTurn(turn, "failed", `Lost the ${this.label()} task: ${message}`);
447
+ }
448
+ else {
449
+ this.schedulePoll(turn);
450
+ }
451
+ return;
452
+ }
453
+ if (this.turn !== turn)
454
+ return;
455
+ this.reportActivity(status);
456
+ this.recordUsage(status);
457
+ this.lastStatus = status;
458
+ if (status.state === "idle" && status.turns > turn.turnsBefore) {
459
+ await this.completeTurn(turn, "completed");
460
+ }
461
+ else if (status.state === "failed") {
462
+ await this.completeTurn(turn, "failed", status.error ?? `${this.label()} task failed`);
463
+ }
464
+ else if (status.state === "cancelled") {
465
+ await this.completeTurn(turn, "interrupted", status.error ?? "Cancelled in the cloud");
466
+ }
467
+ else {
468
+ this.schedulePoll(turn);
469
+ }
470
+ }
471
+ seenCommands = 0;
472
+ reportActivity(status) {
473
+ const start = Math.max(this.seenCommands, this.turn?.commandsBefore ?? 0);
474
+ status.commands.slice(start).forEach((record, index) => {
475
+ const toolCallId = `cloud-${start + index}`;
476
+ this.emitFrame({
477
+ type: "event",
478
+ event: "tool_call_start",
479
+ payload: { toolCallId, name: "bash", args: { command: record.command } },
480
+ });
481
+ this.emitFrame({
482
+ type: "event",
483
+ event: "tool_call_end",
484
+ payload: { toolCallId, result: record.output.slice(-2_000), isError: record.isError },
485
+ });
486
+ });
487
+ this.seenCommands = Math.max(this.seenCommands, status.commands.length);
488
+ }
489
+ recordUsage(status) {
490
+ const id = this.providerId;
491
+ if (!id || !status.usage)
492
+ return;
493
+ try {
494
+ if (status.usage.limited && status.usage.resetsAt) {
495
+ benchProvider(id, status.usage.resetsAt, "plan usage limit");
496
+ }
497
+ else if (status.usage.utilization !== undefined) {
498
+ recordUtilization(id, status.usage.utilization, status.usage.resetsAt);
499
+ }
500
+ }
501
+ catch {
502
+ // Bookkeeping only.
503
+ }
504
+ }
505
+ async completeTurn(turn, status, error) {
506
+ if (this.turn !== turn)
507
+ return;
508
+ this.turn = undefined;
509
+ this.stopPolling();
510
+ const last = this.lastStatus;
511
+ const commands = last ? last.commands.slice(turn.commandsBefore) : [];
512
+ if (last?.usageTokens) {
513
+ this.emitFrame({
514
+ type: "event",
515
+ event: "turn_end",
516
+ payload: {
517
+ usage: {
518
+ inputTokens: Math.max(0, last.usageTokens.input - turn.tokensBefore.input),
519
+ outputTokens: Math.max(0, last.usageTokens.output - turn.tokensBefore.output),
520
+ },
521
+ },
522
+ });
523
+ }
524
+ // Sync only after a finished turn: the session is idle and its work done.
525
+ const editsNote = !this.handle
526
+ ? undefined
527
+ : status === "completed"
528
+ ? await this.syncNote()
529
+ : `Edits not synced after this ${status} turn; they stay in the cloud session: ${this.handle.url}`;
530
+ this.emitFrame({
531
+ type: "turn_complete",
532
+ status,
533
+ output: last?.finalText ?? "",
534
+ receipt: this.receipt(commands, editsNote),
535
+ ...(error && { error }),
536
+ ...(this.providerId && {
537
+ model: cloudAgentModel(this.providerId, this.model) ?? this.model,
538
+ }),
539
+ });
540
+ }
541
+ receipt(commands, editsNote) {
542
+ const lines = [];
543
+ if (this.handle)
544
+ lines.push(`Ran in ${this.label()}: ${this.handle.url}`);
545
+ if (this.providerId === "codex-cloud") {
546
+ lines.push("Commands: Codex cloud does not report the commands it ran, so this result is unverified.");
547
+ }
548
+ else if (commands.length === 0) {
549
+ lines.push("Commands run (recorded by the cloud harness): none");
550
+ }
551
+ else {
552
+ lines.push("Commands run (recorded by the cloud harness):");
553
+ const shown = commands.slice(-RECEIPT_COMMANDS);
554
+ if (shown.length < commands.length) {
555
+ lines.push(` … ${commands.length - shown.length} earlier`);
556
+ }
557
+ for (const c of shown) {
558
+ const command = c.command.replace(/\s+/g, " ").trim().slice(0, 200);
559
+ lines.push(`- \`${command}\`${c.isError ? " (failed)" : ""}`);
560
+ }
561
+ }
562
+ if (editsNote)
563
+ lines.push(editsNote);
564
+ return lines.join("\n");
565
+ }
566
+ /** Bring the task's edits home; never throws. */
567
+ async syncNote() {
568
+ const handle = this.handle;
569
+ const id = handle.provider;
570
+ const stays = `Edits stay in the cloud session: ${handle.url}`;
571
+ if (!EDITS_COME_BACK[id] || !handle.baseCommit || !handle.repoRoot || !this.stateDir) {
572
+ return stays;
573
+ }
574
+ let next;
575
+ try {
576
+ next = await this.provider.diff(handle);
577
+ }
578
+ catch (error) {
579
+ const message = error instanceof Error ? error.message : String(error);
580
+ log("WARN", "subagent", "Cloud agent sync-back failed", { error: message });
581
+ return `Could not bring edits back from ${CLOUD_LABELS[id]} (${message}). ${stays}`;
582
+ }
583
+ const stateDir = this.stateDir;
584
+ const repoRoot = handle.repoRoot;
585
+ const base = handle.baseCommit;
586
+ try {
587
+ return await withRepoLock(repoRoot, async () => {
588
+ const lastFile = path.join(stateDir, "last.patch");
589
+ const previous = await fs.readFile(lastFile).catch(() => Buffer.alloc(0));
590
+ if (previous.equals(next)) {
591
+ return next.length === 0 ? "No file changes came back from the cloud task." : undefined;
592
+ }
593
+ const result = await applyRemoteDelta({
594
+ repoRoot,
595
+ base,
596
+ previous,
597
+ next,
598
+ keepDir: stateDir,
599
+ node: CLOUD_LABELS[id],
600
+ });
601
+ // Consumed either way: a conflict is kept and reported once.
602
+ await fs.mkdir(stateDir, { recursive: true });
603
+ await fs.writeFile(lastFile, next);
604
+ return result.note;
605
+ });
606
+ }
607
+ catch (error) {
608
+ const message = error instanceof Error ? error.message : String(error);
609
+ return `Could not bring edits back from ${CLOUD_LABELS[id]}: ${message}`;
610
+ }
611
+ }
612
+ async saveState() {
613
+ const handle = this.handle;
614
+ this.stateDir = path.join(this.spawnOptions.stateRoot, safeDirName(handle.id));
615
+ const state = {
616
+ provider: handle.provider,
617
+ id: handle.id,
618
+ url: handle.url,
619
+ repoRoot: handle.repoRoot,
620
+ ...(handle.baseCommit && { baseCommit: handle.baseCommit }),
621
+ ...(handle.baseTree && { baseTree: handle.baseTree }),
622
+ ...(this.subdir && { subdir: this.subdir }),
623
+ };
624
+ await fs.mkdir(this.stateDir, { recursive: true });
625
+ await fs.writeFile(path.join(this.stateDir, "state.json"), JSON.stringify(state));
626
+ }
627
+ /** Archive once, however many paths (kill, shutdown, a kill during start) ask. */
628
+ archive() {
629
+ if (!this.handle)
630
+ return Promise.resolve();
631
+ this.archiving ??= this.archiveOnce();
632
+ return this.archiving;
633
+ }
634
+ async archiveOnce() {
635
+ const handle = this.handle;
636
+ if (!handle || !this.provider)
637
+ return;
638
+ await this.provider.archive(handle).catch((error) => log("WARN", "subagent", "Could not archive cloud agent", {
639
+ error: error instanceof Error ? error.message : String(error),
640
+ }));
641
+ if (this.stateDir) {
642
+ // Keep conflict patches; drop the bookkeeping.
643
+ await fs.rm(path.join(this.stateDir, "last.patch"), { force: true });
644
+ await fs.rm(path.join(this.stateDir, "state.json"), { force: true });
645
+ await fs.rmdir(this.stateDir).catch(() => undefined);
646
+ }
647
+ }
648
+ async finish(code, signal, reason) {
649
+ if (this.finished)
650
+ return;
651
+ this.finished = true;
652
+ this.stopPolling();
653
+ this.turn = undefined;
654
+ if (reason)
655
+ this.stderr.write(`${reason}\n`);
656
+ this.stdin.destroy();
657
+ this.stdout.end();
658
+ this.stderr.end();
659
+ // Let listeners read the reason before the exit is announced: under load a
660
+ // single tick was not always enough and the manager saw a bare exit.
661
+ // 'end' fires once stderr is fully consumed; the timer covers no reader.
662
+ await new Promise((resolve) => {
663
+ const timer = setTimeout(resolve, 1_000);
664
+ timer.unref?.();
665
+ this.stderr.once("end", () => {
666
+ clearTimeout(timer);
667
+ resolve();
668
+ });
669
+ });
670
+ await new Promise((resolve) => setImmediate(resolve));
671
+ this.exitCode = code;
672
+ this.signalCode = signal;
673
+ this.emit("exit", code, signal);
674
+ this.emit("close", code, signal);
675
+ }
676
+ }
677
+ /**
678
+ * `auto`: a fleet node that can take an agent; else, when cloud settings allow
679
+ * agents and `when` isn't manual, the first available cloud provider.
680
+ */
681
+ export async function chooseAutoTarget(options) {
682
+ const nodes = await readFleetNodes(options.nodesFile);
683
+ const probe = options.probe ?? ((node) => probeNode(node));
684
+ const probed = await Promise.all(nodes.map(async (node) => ({ node, info: await probe(node) })));
685
+ const picked = pickAutoNode(probed);
686
+ if (picked)
687
+ return { kind: "node", machine: picked.node.name };
688
+ const fleet = nodes.length ? "no paired machine can run an agent now" : "no machines are paired";
689
+ const settings = (options.settings ?? (() => readCloudSettings()))();
690
+ if (!cloudAllowedFor(settings, "agents")) {
691
+ throw new Error(`No machine for the agent: ${fleet}, and cloud is off for agents.`);
692
+ }
693
+ if (settings.when === "manual") {
694
+ throw new Error(`No machine for the agent: ${fleet}, and cloud only takes agents that name it (machine "cloud").`);
695
+ }
696
+ const project = await projectOf(options.cwd);
697
+ const availability = await (options.availability ?? ((p) => cloudAvailability("agents", p, settings)))(project);
698
+ const cloud = availability.find((a) => a.available);
699
+ if (cloud)
700
+ return { kind: "cloud", machine: cloud.id };
701
+ const reasons = availability.map((a) => `${CLOUD_LABELS[a.id]}: ${a.detail}`).join("; ");
702
+ throw new Error(`No machine for the agent: ${fleet}, and no cloud is available (${reasons}).`);
703
+ }
704
+ /** Runs whichever worker `auto` resolves to, behind one process-like surface. */
705
+ class AutoWorkerProcess extends EventEmitter {
706
+ stdout = new PassThrough();
707
+ stderr = new PassThrough();
708
+ stdin;
709
+ pid = undefined;
710
+ exitCode = null;
711
+ killed = false;
712
+ attached;
713
+ delegate;
714
+ finished = false;
715
+ constructor(spawnOptions) {
716
+ super();
717
+ this.delegate = chooseAutoTarget({
718
+ cwd: spawnOptions.cwd,
719
+ ...(spawnOptions.nodesFile && { nodesFile: spawnOptions.nodesFile }),
720
+ ...(spawnOptions.probe && { probe: spawnOptions.probe }),
721
+ ...(spawnOptions.settings && { settings: spawnOptions.settings }),
722
+ ...(spawnOptions.availability && { availability: spawnOptions.availability }),
723
+ }).then((target) => {
724
+ const options = { ...spawnOptions, machine: target.machine };
725
+ const child = target.kind === "node" ? new RemoteWorkerProcess(options) : new CloudWorkerProcess(options);
726
+ child.stdout.pipe(this.stdout);
727
+ child.stderr.pipe(this.stderr);
728
+ child.once("exit", (code, signal) => {
729
+ this.finished = true;
730
+ this.exitCode = code;
731
+ this.emit("exit", code, signal);
732
+ this.emit("close", code, signal);
733
+ });
734
+ if (this.killed)
735
+ child.kill("SIGTERM");
736
+ return child;
737
+ });
738
+ this.attached = this.delegate.then((child) => child.attached);
739
+ this.delegate.catch((error) => {
740
+ if (this.finished)
741
+ return;
742
+ this.finished = true;
743
+ this.stderr.end(`${error instanceof Error ? error.message : String(error)}\n`);
744
+ this.stdin.destroy();
745
+ this.stdout.end();
746
+ setImmediate(() => {
747
+ this.exitCode = 1;
748
+ this.emit("exit", 1, null);
749
+ this.emit("close", 1, null);
750
+ });
751
+ });
752
+ this.stdin = new Writable({
753
+ write: (chunk, _encoding, callback) => {
754
+ this.delegate.then((child) => {
755
+ if (!child.stdin?.writable)
756
+ return callback();
757
+ child.stdin.write(chunk, () => callback());
758
+ }, () => callback());
759
+ },
760
+ });
761
+ }
762
+ kill(signal = "SIGTERM") {
763
+ if (this.finished)
764
+ return false;
765
+ this.killed = true;
766
+ void this.delegate.then((child) => child.kill(signal), () => undefined);
767
+ return true;
768
+ }
769
+ }
770
+ /**
771
+ * The worker for spawn_agent `machine`: a cloud provider ("claude-cloud",
772
+ * "codex-cloud", "cloud"), a fleet node by name, or "auto" (fleet first, then
773
+ * cloud). Resumes go back to where the agent ran.
774
+ */
775
+ export function createAgentWorker(spawnOptions) {
776
+ const target = spawnOptions.resume?.node ?? spawnOptions.machine;
777
+ if (isCloudMachine(target))
778
+ return new CloudWorkerProcess(spawnOptions);
779
+ if (target === "auto" && !spawnOptions.resume)
780
+ return new AutoWorkerProcess(spawnOptions);
781
+ return new RemoteWorkerProcess(spawnOptions);
782
+ }
783
+ //# sourceMappingURL=cloud-agent.js.map