@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,219 @@
1
+ // Controller facade for "machines" (paired fleet nodes): what the desktop
2
+ // app's Machines panel and `ezcoder fleet add|remove|rotate-token|share-auth`
3
+ // call. Plain-words errors throughout; nothing here prints.
4
+ import fs from "node:fs";
5
+ import { getAppPaths } from "@prestyj/core";
6
+ import { clearNodeInfoCache, FleetClient, FleetClientError, normalizePairCode, } from "./client.js";
7
+ import { discoverNodes } from "./discovery.js";
8
+ import { DEFAULT_NODE_PORT, } from "./protocol.js";
9
+ import { parsePairing } from "./registry.js";
10
+ import { FleetService } from "./service.js";
11
+ function service(opts) {
12
+ return opts.svc ?? FleetService.shared();
13
+ }
14
+ /** Every paired machine with live state (D1). Offline machines show their last error. */
15
+ export async function listMachines(opts = {}) {
16
+ const nodes = await service(opts).nodes();
17
+ return nodes.map((n) => {
18
+ const i = n.info;
19
+ return {
20
+ name: n.node.name,
21
+ url: n.node.url,
22
+ online: n.online,
23
+ ...(n.incompatible ? { incompatible: n.incompatible } : {}),
24
+ ...(n.error ? { error: n.error } : {}),
25
+ ...(i
26
+ ? {
27
+ platform: i.platform,
28
+ version: i.version,
29
+ protocol: i.protocol,
30
+ load: i.load,
31
+ cpus: i.cpus,
32
+ memoryGb: i.memoryGb,
33
+ memoryFreeGb: i.memoryFreeGb,
34
+ docker: i.docker,
35
+ modelAuth: i.modelAuth,
36
+ ...(i.dockerOnly ? { dockerOnly: true } : {}),
37
+ }
38
+ : {}),
39
+ ...(n.updateNotice ? { updateNotice: n.updateNotice } : {}),
40
+ gpus: i?.gpus ?? [],
41
+ slots: i?.slots ?? 0,
42
+ slotsUsed: i?.slotsUsed ?? 0,
43
+ labels: [...new Set([...(i?.labels ?? []), ...n.node.labels])],
44
+ tls: !!n.node.fingerprint,
45
+ ourJobs: n.active,
46
+ jobs: i?.jobs ?? [],
47
+ services: i?.services ?? [],
48
+ agents: i?.agents ?? [],
49
+ };
50
+ });
51
+ }
52
+ /** Total capacity: local slots plus every online, compatible node's slots. */
53
+ export function fleetCapacity(machines, localSlots) {
54
+ const usable = machines.filter((m) => m.online && !m.incompatible);
55
+ const nodesTotal = usable.reduce((n, m) => n + m.slots, 0);
56
+ const nodesUsed = usable.reduce((n, m) => n + Math.min(m.slots, m.slotsUsed), 0);
57
+ return { local: localSlots, nodesUsed, nodesTotal, total: localSlots + nodesTotal };
58
+ }
59
+ const PAIRING_PREFIX = /^ezfleets?:\/\//i;
60
+ function hostUrl(host) {
61
+ const h = host.trim().replace(/\/+$/, "");
62
+ if (/^https?:\/\//i.test(h))
63
+ return /:\d+$/.test(h) ? h : `${h}:${DEFAULT_NODE_PORT}`;
64
+ return /:\d+$/.test(h) && !h.startsWith("[") ? `http://${h}` : `http://${h}:${DEFAULT_NODE_PORT}`;
65
+ }
66
+ /** S9: trade a short code for the pairing string, at `host` or on each tailnet node. */
67
+ async function pairingFromCode(code, opts) {
68
+ const c = normalizePairCode(code);
69
+ if (!c) {
70
+ throw new Error(`"${code.slice(0, 20)}" is neither a pairing string (ezfleet://…) nor a pairing code (like K7QM-2XPA)`);
71
+ }
72
+ const urls = opts.host
73
+ ? [hostUrl(opts.host)]
74
+ : (await (opts.discover ?? (() => discoverNodes()))().catch(() => []))
75
+ .filter((f) => !f.paired)
76
+ .map((f) => f.url);
77
+ if (!urls.length) {
78
+ throw new Error("no unpaired EZ Coder node found on the tailnet to use the code with; pass --host <address of the other machine>");
79
+ }
80
+ let last;
81
+ for (const url of urls) {
82
+ let seen;
83
+ const client = new FleetClient(url, url, undefined, {
84
+ timeoutMs: 5000,
85
+ ...opts.client,
86
+ onPeerFingerprint: (fp) => (seen = fp),
87
+ });
88
+ try {
89
+ const r = await client.pairWithCode(c);
90
+ const p = parsePairing(r.pairing);
91
+ // The certificate we just talked to must be the one the string pins (X10).
92
+ if (p.fingerprint && seen && seen !== p.fingerprint) {
93
+ throw new Error(`the machine at ${url} answered with a certificate that doesn't match its pairing string; not pairing`);
94
+ }
95
+ return p;
96
+ }
97
+ catch (e) {
98
+ last = e;
99
+ if (opts.host)
100
+ break;
101
+ }
102
+ }
103
+ throw last instanceof Error ? last : new Error(String(last));
104
+ }
105
+ /**
106
+ * Pair a machine from a pairing string or a short code (D2, S2, S9). Unless
107
+ * `offline`, refuses when the machine can't be reached, rejects the token or
108
+ * speaks an incompatible protocol; then runs its doctor and returns the report.
109
+ */
110
+ export async function addMachine(pairingOrCode, opts = {}) {
111
+ const input = pairingOrCode.trim();
112
+ if (!input)
113
+ throw new Error("no pairing string given");
114
+ const p = PAIRING_PREFIX.test(input) ? parsePairing(input) : await pairingFromCode(input, opts);
115
+ const svc = service(opts);
116
+ const warnings = [];
117
+ const client = new FleetClient(p.name, p.url, p.token, {
118
+ timeoutMs: 8000,
119
+ ...opts.client,
120
+ ...(p.fingerprint ? { fingerprint: p.fingerprint } : {}),
121
+ });
122
+ let hello;
123
+ let doctor;
124
+ if (!opts.offline) {
125
+ try {
126
+ hello = await client.handshake();
127
+ await client.info(); // the token check
128
+ }
129
+ catch (e) {
130
+ const why = e instanceof Error ? e.message : String(e);
131
+ throw new FleetClientError(`not pairing ${p.name}: ${why}. Fix that and try again, or pair anyway with --offline`, e instanceof FleetClientError ? e.code : "unreachable", e instanceof FleetClientError ? e.status : undefined, e instanceof FleetClientError ? e.update : undefined);
132
+ }
133
+ if (hello.name !== p.name) {
134
+ warnings.push(`the machine calls itself ${hello.name}; paired as ${p.name}`);
135
+ }
136
+ try {
137
+ doctor = await client.doctor(opts.repo);
138
+ }
139
+ catch (e) {
140
+ warnings.push(`couldn't run the machine's checks (${e instanceof Error ? e.message : String(e)}); run \`ezcoder node doctor\` there`);
141
+ }
142
+ }
143
+ const node = await svc.registry.add({
144
+ name: p.name,
145
+ url: p.url,
146
+ token: p.token,
147
+ labels: opts.labels ?? [],
148
+ ...(p.fingerprint ? { fingerprint: p.fingerprint } : {}),
149
+ });
150
+ clearNodeInfoCache(p.name);
151
+ return {
152
+ node,
153
+ verified: !opts.offline,
154
+ ...(hello ? { hello } : {}),
155
+ ...(doctor ? { doctor } : {}),
156
+ warnings,
157
+ };
158
+ }
159
+ /** Forget a paired machine (the machine itself keeps running). False when not paired. */
160
+ export async function removeMachine(name, opts = {}) {
161
+ const removed = await service(opts).registry.remove(name);
162
+ clearNodeInfoCache(name);
163
+ return removed;
164
+ }
165
+ async function paired(svc, name) {
166
+ const node = await svc.registry.get(name);
167
+ if (!node)
168
+ throw new Error(`no paired machine "${name}"`);
169
+ return node;
170
+ }
171
+ /**
172
+ * S4/D5: the machine issues a new token (the old one stops working at once);
173
+ * it is stored here. Returns the fresh pairing string for other controllers.
174
+ */
175
+ export async function rotateMachineToken(name, opts = {}) {
176
+ const svc = service(opts);
177
+ const r = await svc.client(await paired(svc, name)).rotateToken();
178
+ await svc.registry.setToken(name, r.token);
179
+ clearNodeInfoCache(name);
180
+ return { pairing: r.pairing };
181
+ }
182
+ /** Model credentials safe to share: provider entries, never local endpoint keys. */
183
+ export function shareableCredentials(authFile) {
184
+ const raw = JSON.parse(fs.readFileSync(authFile, "utf8"));
185
+ return Object.fromEntries(Object.entries(raw).filter(([k]) => !k.startsWith("local:")));
186
+ }
187
+ /**
188
+ * Copy this machine's model credentials to a machine (opt-in). Without `force`
189
+ * a machine that already has credentials is left alone: FleetClientError
190
+ * "exists" with a plain message.
191
+ */
192
+ export async function shareAuth(name, opts = {}) {
193
+ const svc = service(opts);
194
+ const node = await paired(svc, name);
195
+ let creds;
196
+ try {
197
+ creds = shareableCredentials(opts.authFile ?? getAppPaths().authFile);
198
+ }
199
+ catch {
200
+ creds = {};
201
+ }
202
+ const providers = Object.keys(creds);
203
+ if (!providers.length) {
204
+ throw new Error("no model credentials on this machine (run `ezcoder login` first)");
205
+ }
206
+ try {
207
+ await svc
208
+ .client(node)
209
+ .shareAuth({ credentials: creds, ...(opts.force ? { force: true } : {}) });
210
+ }
211
+ catch (e) {
212
+ if (e instanceof FleetClientError && e.code === "exists") {
213
+ throw new FleetClientError(`${name} already has its own model login, so nothing was changed. To replace it with this machine's, share again with force (\`ezcoder fleet share-auth ${name} --yes --force\`); safer: keep the node's own login`, "exists", 409);
214
+ }
215
+ throw e;
216
+ }
217
+ return { providers };
218
+ }
219
+ //# sourceMappingURL=machines.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machines.js","sourceRoot":"","sources":["../../../src/core/fleet/machines.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,4DAA4D;AAC5D,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACL,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,iBAAiB,GAElB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EACL,iBAAiB,GAQlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,YAAY,EAAgC,MAAM,eAAe,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAqD5C,SAAS,OAAO,CAAC,IAAoB;IACnC,OAAO,IAAI,CAAC,GAAG,IAAI,YAAY,CAAC,MAAM,EAAE,CAAC;AAC3C,CAAC;AAED,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,OAAuB,EAAE;IAC1D,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC;IAC1C,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAe,EAAE;QAClC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACjB,OAAO;YACL,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI;YACjB,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG;YACf,MAAM,EAAE,CAAC,CAAC,MAAM;YAChB,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3D,GAAG,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,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACrC,IAAI,KAA8B,CAAC;IACnC,IAAI,CAAC;QACH,KAAK,GAAG,oBAAoB,CAAC,IAAI,CAAC,QAAQ,IAAI,WAAW,EAAE,CAAC,QAAQ,CAAC,CAAC;IACxE,CAAC;IAAC,MAAM,CAAC;QACP,KAAK,GAAG,EAAE,CAAC;IACb,CAAC;IACD,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACrC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IACtF,CAAC;IACD,IAAI,CAAC;QACH,MAAM,GAAG;aACN,MAAM,CAAC,IAAI,CAAC;aACZ,SAAS,CAAC,EAAE,WAAW,EAAE,KAAK,EAAE,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IAC/E,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAI,CAAC,YAAY,gBAAgB,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACzD,MAAM,IAAI,gBAAgB,CACxB,GAAG,IAAI,mJAAmJ,IAAI,qDAAqD,EACnN,QAAQ,EACR,GAAG,CACJ,CAAC;QACJ,CAAC;QACD,MAAM,CAAC,CAAC;IACV,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,CAAC;AACvB,CAAC"}
@@ -9,6 +9,8 @@ export interface AgentRoutesOptions {
9
9
  }
10
10
  /** Controller env, minus anything that could carry credentials or hijack the worker. */
11
11
  export declare function safeAgentEnv(requested: Record<string, unknown> | undefined): Record<string, string>;
12
+ /** Ignored files the agent added, changed or removed since the snapshot. */
13
+ export declare function ignoredChanges(before: Record<string, string>, after: Record<string, string>): string[];
12
14
  export declare function createAgentRouteModule(options?: AgentRoutesOptions): NodeRouteModule;
13
15
  declare const agentRouteModule: NodeRouteModule;
14
16
  export { agentRouteModule };
@@ -17,7 +17,9 @@ import { createInterface } from "node:readline";
17
17
  import { promisify } from "node:util";
18
18
  import { WebSocketServer, WebSocket } from "ws";
19
19
  import { AGENT_DETACH_GRACE_MS, } from "../protocol.js";
20
- import { childSubAgentEnv } from "../../../tools/subagent-shared.js";
20
+ import { SUB_AGENT_DEPTH_ENV, childSubAgentEnv } from "../../../tools/subagent-shared.js";
21
+ import { allowedBaseEnv } from "./env.js";
22
+ import { pidAlive } from "./exec.js";
21
23
  const execFileAsync = promisify(execFile);
22
24
  export const AGENT_RESUMED_HEADER = "x-ezcoder-agent-resumed";
23
25
  /** Request body cap: a 50 MB patch is ~67 MB of base64. */
@@ -26,6 +28,10 @@ const MAX_FRAME_BYTES = 16 * 1024 * 1024;
26
28
  const DEFAULT_BUFFER_BYTES = 8 * 1024 * 1024;
27
29
  const STDERR_TAIL_CHARS = 64 * 1024;
28
30
  const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
31
+ /** Seconds a controller should wait before retrying when every slot is busy. */
32
+ const BUSY_RETRY_AFTER = "15";
33
+ /** EZ_* names the worker itself needs from the node (beyond the allow-list). */
34
+ const WORKER_EZ_ENV = [SUB_AGENT_DEPTH_ENV];
29
35
  /** Env names a controller may never set on the node (credentials, loaders, identity). */
30
36
  const BLOCKED_ENV = /(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|COOKIE|SESSION)|^(PATH|HOME|USERPROFILE|NODE_OPTIONS|NODE_PATH|LD_PRELOAD|LD_LIBRARY_PATH|DYLD_.*|SHELL|GIT_.*|SSH_.*)$/i;
31
37
  function sendFrame(socket, frame) {
@@ -74,6 +80,39 @@ async function git(cwd, args) {
74
80
  });
75
81
  return stdout.toString("latin1");
76
82
  }
83
+ /** R9: git-ignored files (recursively) with size and mtime. Cheap: no content reads. */
84
+ async function ignoredFiles(root) {
85
+ const out = {};
86
+ let listing;
87
+ try {
88
+ listing = await git(root, ["ls-files", "-z", "-o", "-i", "--exclude-standard"]);
89
+ }
90
+ catch {
91
+ return out;
92
+ }
93
+ const names = Buffer.from(listing, "latin1").toString("utf-8").split("\0").filter(Boolean);
94
+ for (const name of names.slice(0, 200_000)) {
95
+ try {
96
+ const st = await fs.lstat(path.join(root, name));
97
+ out[name] = `${st.size}:${Math.round(st.mtimeMs)}`;
98
+ }
99
+ catch {
100
+ // vanished meanwhile
101
+ }
102
+ }
103
+ return out;
104
+ }
105
+ /** Ignored files the agent added, changed or removed since the snapshot. */
106
+ export function ignoredChanges(before, after) {
107
+ const changed = new Set();
108
+ for (const [name, sig] of Object.entries(after))
109
+ if (before[name] !== sig)
110
+ changed.add(name);
111
+ for (const name of Object.keys(before))
112
+ if (!(name in after))
113
+ changed.add(name);
114
+ return [...changed].sort();
115
+ }
77
116
  function killTree(proc, signal) {
78
117
  if (proc.exitCode !== null || proc.signalCode !== null)
79
118
  return;
@@ -101,12 +140,43 @@ export function createAgentRouteModule(options = {}) {
101
140
  });
102
141
  const graceMs = options.graceMs ?? AGENT_DETACH_GRACE_MS;
103
142
  const bufferLimit = options.bufferBytes ?? DEFAULT_BUFFER_BYTES;
143
+ let stateCtx;
144
+ const toRecord = (e) => ({
145
+ id: e.id,
146
+ project: e.project,
147
+ base: e.base,
148
+ cwd: e.cwd,
149
+ root: e.root,
150
+ removeDir: e.removeDir,
151
+ sessionsDir: e.sessionsDir,
152
+ env: e.env,
153
+ createdAt: e.createdAt,
154
+ state: e.state,
155
+ ...((e.proc?.pid ?? e.pid) !== undefined && { pid: e.proc?.pid ?? e.pid }),
156
+ ...(e.exitCode !== undefined && { exitCode: e.exitCode }),
157
+ ...(e.sessionPath && { sessionPath: e.sessionPath }),
158
+ ...(e.ignoredSnapshot && { ignoredSnapshot: e.ignoredSnapshot }),
159
+ });
160
+ /** R3: mirror every agent into node state so a restart can re-adopt it. */
161
+ const persist = () => {
162
+ const state = stateCtx?.state;
163
+ if (!state)
164
+ return;
165
+ state.data.agents = [...agents.values()].map(toRecord);
166
+ try {
167
+ state.save();
168
+ }
169
+ catch (e) {
170
+ stateCtx?.log(`agents: could not save state: ${e.message}`);
171
+ }
172
+ };
104
173
  const status = (entry) => ({
105
174
  id: entry.id,
106
175
  project: entry.project,
107
176
  state: entry.state,
108
177
  cwd: entry.cwd,
109
- ...(entry.proc?.pid !== undefined && entry.state === "running" && { pid: entry.proc.pid }),
178
+ ...((entry.proc?.pid ?? entry.pid) !== undefined &&
179
+ entry.state === "running" && { pid: entry.proc?.pid ?? entry.pid }),
110
180
  ...(entry.exitCode !== undefined && { exitCode: entry.exitCode }),
111
181
  createdAt: entry.createdAt,
112
182
  });
@@ -125,14 +195,34 @@ export function createAgentRouteModule(options = {}) {
125
195
  return;
126
196
  agents.delete(entry.id);
127
197
  clearTimeout(entry.graceTimer);
128
- if (entry.proc)
129
- killTree(entry.proc, "SIGKILL");
198
+ const proc = entry.proc;
199
+ const exited = proc && proc.exitCode === null && proc.signalCode === null
200
+ ? new Promise((resolve) => {
201
+ proc.once("exit", () => resolve());
202
+ setTimeout(resolve, 5000).unref();
203
+ })
204
+ : undefined;
205
+ if (proc)
206
+ killTree(proc, "SIGKILL");
130
207
  entry.socket?.close(1000, "removed");
131
208
  entry.socket = undefined;
209
+ if (entry.adopted && entry.pid && entry.state === "running") {
210
+ try {
211
+ process.kill(-entry.pid, "SIGKILL");
212
+ }
213
+ catch {
214
+ // already gone
215
+ }
216
+ }
132
217
  ctx.releaseSlot(entry.owner);
218
+ persist();
219
+ // Windows keeps a dying process's cwd locked; wait for it, then retry.
220
+ await exited;
133
221
  for (const dir of [entry.removeDir, entry.sessionsDir]) {
134
222
  if (dir)
135
- await fs.rm(dir, { recursive: true, force: true }).catch(() => { });
223
+ await fs
224
+ .rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })
225
+ .catch(() => { });
136
226
  }
137
227
  };
138
228
  const deliver = (entry, frame) => {
@@ -186,11 +276,17 @@ export function createAgentRouteModule(options = {}) {
186
276
  const proc = spawn(process.execPath, [entryPath, "--subagent-worker"], {
187
277
  cwd: entry.cwd,
188
278
  stdio: ["pipe", "pipe", "pipe"],
189
- env: { ...childSubAgentEnv(process.env), ...entry.env },
279
+ // X6: allow-listed node env only, plus the worker's own depth marker.
280
+ env: { ...allowedBaseEnv(childSubAgentEnv(process.env), WORKER_EZ_ENV), ...entry.env },
190
281
  detached: process.platform !== "win32",
191
282
  });
192
283
  entry.proc = proc;
284
+ entry.adopted = false;
285
+ entry.pid = proc.pid;
193
286
  entry.state = "running";
287
+ // A worker takes a slot while it runs (re-taken after an earlier exit released it).
288
+ ctx.acquireSlot(entry.owner, true);
289
+ persist();
194
290
  entry.exitCode = undefined;
195
291
  entry.pendingExit = undefined;
196
292
  entry.stdinPartial = "";
@@ -201,6 +297,7 @@ export function createAgentRouteModule(options = {}) {
201
297
  const frame = JSON.parse(line);
202
298
  if (frame.type === "ack" && typeof frame.child_session_path === "string") {
203
299
  entry.sessionPath = frame.child_session_path;
300
+ persist();
204
301
  }
205
302
  }
206
303
  catch {
@@ -220,6 +317,8 @@ export function createAgentRouteModule(options = {}) {
220
317
  return;
221
318
  entry.state = code === 0 ? "exited" : "error";
222
319
  entry.exitCode = code ?? undefined;
320
+ ctx.releaseSlot(entry.owner);
321
+ persist();
223
322
  ctx.log(`agent ${entry.id}: worker exited (${code ?? signal})`);
224
323
  deliver(entry, { t: "exit", code, signal });
225
324
  };
@@ -257,6 +356,7 @@ export function createAgentRouteModule(options = {}) {
257
356
  };
258
357
  const handleAttach = (ctx, entry, socket) => {
259
358
  clearTimeout(entry.graceTimer);
359
+ tokens.set(socket, ctx.config.token);
260
360
  // A newer attach wins: the old socket is a stale connection.
261
361
  if (entry.socket && entry.socket !== socket)
262
362
  entry.socket.close(4000, "replaced");
@@ -290,10 +390,25 @@ export function createAgentRouteModule(options = {}) {
290
390
  sendFrame(socket, exit);
291
391
  return;
292
392
  }
393
+ if (entry.adopted && entry.state === "running") {
394
+ // The worker from before the node restart has no stdio bridge any more.
395
+ sendFrame(socket, {
396
+ t: "stderr",
397
+ data: "[node] the node restarted; the previous worker can't be re-attached. Its edits are still in the workspace (fetch the diff).\n",
398
+ });
399
+ sendFrame(socket, { t: "exit", code: null, signal: null });
400
+ return;
401
+ }
293
402
  if (entry.state !== "running")
294
403
  startWorker(ctx, entry);
295
404
  };
296
405
  const handleCreate = async (ctx, req, res) => {
406
+ if (ctx.config.dockerOnly) {
407
+ return ctx.json(res, 403, {
408
+ error: "this node only runs containerised work (docker-only) and does not host remote agents; use another node",
409
+ code: "docker_only",
410
+ });
411
+ }
297
412
  const body = (await readJson(req));
298
413
  if (!body || typeof body.id !== "string" || !ID_RE.test(body.id)) {
299
414
  return ctx.json(res, 400, { error: "id must match [A-Za-z0-9._-]{1,80}" });
@@ -312,8 +427,10 @@ export function createAgentRouteModule(options = {}) {
312
427
  if (existing)
313
428
  return ctx.json(res, 200, status(existing));
314
429
  const owner = `agent:${body.id}`;
315
- if (!ctx.acquireSlot(owner))
316
- return ctx.json(res, 429, { error: "No free slot on this node" });
430
+ if (!ctx.acquireSlot(owner)) {
431
+ res.setHeader("retry-after", BUSY_RETRY_AFTER);
432
+ return ctx.json(res, 429, { error: "all slots are busy", code: "busy" });
433
+ }
317
434
  let workspace;
318
435
  try {
319
436
  workspace = path.resolve(await ctx.prepareWorkspace("agent", body.id, source));
@@ -359,7 +476,9 @@ export function createAgentRouteModule(options = {}) {
359
476
  owner,
360
477
  };
361
478
  await fs.mkdir(entry.sessionsDir, { recursive: true });
479
+ entry.ignoredSnapshot = await ignoredFiles(root);
362
480
  agents.set(entry.id, entry);
481
+ persist();
363
482
  armGrace(ctx, entry);
364
483
  ctx.log(`agent ${entry.id}: workspace ready at ${cwd}`);
365
484
  ctx.json(res, 201, status(entry));
@@ -379,6 +498,11 @@ export function createAgentRouteModule(options = {}) {
379
498
  files: Buffer.from(names, "latin1").toString("utf-8").split("\0").filter(Boolean),
380
499
  base: entry.base,
381
500
  };
501
+ if (entry.ignoredSnapshot) {
502
+ const changed = ignoredChanges(entry.ignoredSnapshot, await ignoredFiles(entry.root));
503
+ if (changed.length)
504
+ body.ignoredChanged = changed;
505
+ }
382
506
  ctx.json(res, 200, body);
383
507
  }
384
508
  catch (error) {
@@ -387,8 +511,64 @@ export function createAgentRouteModule(options = {}) {
387
511
  });
388
512
  }
389
513
  };
514
+ const tokens = new WeakMap();
390
515
  return {
516
+ /** R3: re-adopt agents from the previous node process. */
517
+ init(ctx) {
518
+ stateCtx = ctx;
519
+ const records = ctx.state?.data.agents ?? [];
520
+ const rebooted = ctx.state?.rebooted() ?? true;
521
+ for (const r of records) {
522
+ if (agents.has(r.id))
523
+ continue;
524
+ const alive = r.state === "running" && !rebooted && pidAlive(r.pid);
525
+ const entry = {
526
+ ...r,
527
+ state: r.state === "running"
528
+ ? alive
529
+ ? "running"
530
+ : "error"
531
+ : r.state === "ready"
532
+ ? "ready"
533
+ : r.state,
534
+ ...(r.state === "running" && !alive && { exitCode: r.exitCode }),
535
+ buffer: [],
536
+ bufferBytes: 0,
537
+ dropped: 0,
538
+ stderrTail: "",
539
+ stdinPartial: "",
540
+ owner: `agent:${r.id}`,
541
+ adopted: alive,
542
+ ...(alive ? { pid: r.pid } : { pid: undefined }),
543
+ };
544
+ if (r.state === "running" && !alive) {
545
+ entry.stderrTail =
546
+ "[node] the node restarted and the worker stopped; its workspace is kept so the diff can still be fetched.\n";
547
+ }
548
+ if (alive)
549
+ ctx.acquireSlot(entry.owner, true);
550
+ agents.set(entry.id, entry);
551
+ // A stopped worker's edits stay until the controller fetches them and DELETEs (R2).
552
+ if (alive)
553
+ armGrace(ctx, entry);
554
+ ctx.log(`agent ${entry.id}: re-adopted (${entry.state})`);
555
+ }
556
+ persist();
557
+ },
558
+ /** S4: sockets opened with the old token are closed at once. */
559
+ tokenRotated() {
560
+ for (const entry of agents.values()) {
561
+ const socket = entry.socket;
562
+ if (socket && tokens.get(socket) !== stateCtx?.config.token) {
563
+ socket.close(4001, "token rotated");
564
+ }
565
+ }
566
+ },
567
+ activeCount() {
568
+ return [...agents.values()].filter((a) => a.state === "running").length;
569
+ },
391
570
  async handle(ctx, req, res, url) {
571
+ stateCtx ??= ctx;
392
572
  const parts = url.pathname.split("/").filter(Boolean);
393
573
  if (parts[0] !== "v1" || parts[1] !== "agents")
394
574
  return false;
@@ -429,6 +609,7 @@ export function createAgentRouteModule(options = {}) {
429
609
  return true;
430
610
  },
431
611
  upgrade(ctx, req, socket, head, url) {
612
+ stateCtx ??= ctx;
432
613
  const match = /^\/v1\/agents\/([^/]+)\/attach$/.exec(url.pathname);
433
614
  if (!match)
434
615
  return false;
@@ -447,10 +628,15 @@ export function createAgentRouteModule(options = {}) {
447
628
  async close() {
448
629
  for (const entry of agents.values()) {
449
630
  clearTimeout(entry.graceTimer);
450
- if (entry.proc)
631
+ if (entry.proc && entry.state === "running") {
451
632
  killTree(entry.proc, "SIGKILL");
633
+ // Recorded now: the exit event may land after the next node process read the state.
634
+ entry.state = "error";
635
+ entry.adopted = false;
636
+ }
452
637
  entry.socket?.close(1001, "node shutting down");
453
638
  }
639
+ persist();
454
640
  wss.close();
455
641
  },
456
642
  };