@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,46 @@
1
+ export declare const DEFAULT_GC_DAYS = 7;
2
+ export declare const DEFAULT_CACHE_CAP_GB = 20;
3
+ export declare const DEFAULT_GC_INTERVAL_MS: number;
4
+ export interface GcOptions {
5
+ dataDir: string;
6
+ /** Default DEFAULT_GC_DAYS. Read on every sweep, so a config change applies live. */
7
+ gcDays?: () => number | undefined;
8
+ /** Default DEFAULT_CACHE_CAP_GB. */
9
+ cacheCapGb?: () => number | undefined;
10
+ /** True for a job id that is still preparing or running (its folders are kept). */
11
+ jobBusy: (id: string) => boolean;
12
+ /** True for a cache folder name a running job uses (never trimmed). */
13
+ cacheBusy: (name: string) => boolean;
14
+ /** When a finished job ended (ms); falls back to the newest mtime of its folders. */
15
+ finishedAt?: (id: string) => number | undefined;
16
+ now?: () => number;
17
+ log?: (msg: string) => void;
18
+ }
19
+ export interface GcResult {
20
+ /** Job ids whose folders were removed. */
21
+ jobs: string[];
22
+ /** Cache folder names removed. */
23
+ caches: string[];
24
+ freedBytes: number;
25
+ }
26
+ /**
27
+ * Total bytes and newest file mtime under `p` (symlinks are not followed).
28
+ * Folder mtimes are ignored (creating a folder is not use), unless there are no files.
29
+ */
30
+ export declare function treeStats(p: string): {
31
+ bytes: number;
32
+ newest: number;
33
+ };
34
+ /** One sweep. Safe to call at any time; errors on single folders are skipped. */
35
+ export declare function sweepNode(o: GcOptions): GcResult;
36
+ export interface GcSweeper {
37
+ /** Run a sweep now (also what the timer calls). */
38
+ sweep(): GcResult;
39
+ stop(): void;
40
+ }
41
+ /** Sweep every `intervalMs` (call `sweep()` yourself for one at start). */
42
+ export declare function startGcSweeper(o: GcOptions & {
43
+ intervalMs?: number;
44
+ setInterval?: (fn: () => void, ms: number) => unknown;
45
+ clearInterval?: (handle: unknown) => void;
46
+ }): GcSweeper;
@@ -0,0 +1,140 @@
1
+ // R5: the node cleans up after itself while it runs. Finished job folders
2
+ // (workspace, run dir with the log, artifacts) older than gcDays are removed,
3
+ // and caches beyond cacheCapGb are trimmed, least recently used first. The
4
+ // caller says what is in use; anything it calls busy is never touched.
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ export const DEFAULT_GC_DAYS = 7;
8
+ export const DEFAULT_CACHE_CAP_GB = 20;
9
+ export const DEFAULT_GC_INTERVAL_MS = 60 * 60_000;
10
+ const DAY_MS = 86_400_000;
11
+ const GB = 1024 ** 3;
12
+ /** Folders under dataDir that hold per-job files, keyed by job id. */
13
+ const JOB_DIRS = ["jobs", "run", "artifacts"];
14
+ function listDirs(dir) {
15
+ try {
16
+ return fs
17
+ .readdirSync(dir, { withFileTypes: true })
18
+ .filter((d) => d.isDirectory())
19
+ .map((d) => d.name);
20
+ }
21
+ catch {
22
+ return [];
23
+ }
24
+ }
25
+ /**
26
+ * Total bytes and newest file mtime under `p` (symlinks are not followed).
27
+ * Folder mtimes are ignored (creating a folder is not use), unless there are no files.
28
+ */
29
+ export function treeStats(p) {
30
+ let bytes = 0;
31
+ let newest = 0;
32
+ let newestDir = 0;
33
+ const walk = (cur) => {
34
+ let st;
35
+ try {
36
+ st = fs.lstatSync(cur);
37
+ }
38
+ catch {
39
+ return;
40
+ }
41
+ if (!st.isDirectory()) {
42
+ newest = Math.max(newest, st.mtimeMs);
43
+ bytes += st.size;
44
+ return;
45
+ }
46
+ newestDir = Math.max(newestDir, st.mtimeMs);
47
+ let entries;
48
+ try {
49
+ entries = fs.readdirSync(cur);
50
+ }
51
+ catch {
52
+ return;
53
+ }
54
+ for (const e of entries)
55
+ walk(path.join(cur, e));
56
+ };
57
+ walk(p);
58
+ return { bytes, newest: newest || newestDir };
59
+ }
60
+ function remove(p) {
61
+ try {
62
+ fs.rmSync(p, { recursive: true, force: true });
63
+ return true;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ /** One sweep. Safe to call at any time; errors on single folders are skipped. */
70
+ export function sweepNode(o) {
71
+ const now = (o.now ?? Date.now)();
72
+ const days = o.gcDays?.() ?? DEFAULT_GC_DAYS;
73
+ const capGb = o.cacheCapGb?.() ?? DEFAULT_CACHE_CAP_GB;
74
+ const result = { jobs: [], caches: [], freedBytes: 0 };
75
+ // ── finished jobs ──
76
+ const ids = new Set(JOB_DIRS.flatMap((d) => listDirs(path.join(o.dataDir, d))));
77
+ for (const id of ids) {
78
+ if (o.jobBusy(id))
79
+ continue;
80
+ const folders = JOB_DIRS.map((d) => path.join(o.dataDir, d, id)).filter((f) => fs.existsSync(f));
81
+ const stats = folders.map(treeStats);
82
+ const ended = o.finishedAt?.(id) ?? Math.max(...stats.map((s) => s.newest));
83
+ if (!(now - ended > days * DAY_MS))
84
+ continue;
85
+ // Re-check right before deleting: a job may have started meanwhile.
86
+ if (o.jobBusy(id))
87
+ continue;
88
+ let removed = false;
89
+ folders.forEach((f, i) => {
90
+ if (remove(f)) {
91
+ removed = true;
92
+ result.freedBytes += stats[i].bytes;
93
+ }
94
+ });
95
+ if (removed)
96
+ result.jobs.push(id);
97
+ }
98
+ // ── caches, least recently used first ──
99
+ const cacheRoot = path.join(o.dataDir, "cache");
100
+ const caches = listDirs(cacheRoot).map((name) => ({
101
+ name,
102
+ ...treeStats(path.join(cacheRoot, name)),
103
+ }));
104
+ let total = caches.reduce((n, c) => n + c.bytes, 0);
105
+ const cap = capGb * GB;
106
+ for (const c of caches.sort((a, b) => a.newest - b.newest)) {
107
+ if (total <= cap)
108
+ break;
109
+ if (o.cacheBusy(c.name))
110
+ continue;
111
+ if (remove(path.join(cacheRoot, c.name))) {
112
+ total -= c.bytes;
113
+ result.freedBytes += c.bytes;
114
+ result.caches.push(c.name);
115
+ }
116
+ }
117
+ if (result.jobs.length || result.caches.length) {
118
+ o.log?.(`gc: removed ${result.jobs.length} finished job(s) older than ${days} days and ` +
119
+ `${result.caches.length} cache(s) over the ${capGb} GB cap, ${(result.freedBytes / GB).toFixed(2)} GB freed`);
120
+ }
121
+ return result;
122
+ }
123
+ /** Sweep every `intervalMs` (call `sweep()` yourself for one at start). */
124
+ export function startGcSweeper(o) {
125
+ const set = o.setInterval ?? ((fn, ms) => setInterval(fn, ms));
126
+ const clear = o.clearInterval ?? ((h) => clearInterval(h));
127
+ const sweep = () => {
128
+ try {
129
+ return sweepNode(o);
130
+ }
131
+ catch (e) {
132
+ o.log?.(`gc failed: ${e.message}`);
133
+ return { jobs: [], caches: [], freedBytes: 0 };
134
+ }
135
+ };
136
+ const handle = set(sweep, o.intervalMs ?? DEFAULT_GC_INTERVAL_MS);
137
+ handle?.unref?.();
138
+ return { sweep, stop: () => clear(handle) };
139
+ }
140
+ //# sourceMappingURL=gc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gc.js","sourceRoot":"","sources":["../../../../src/core/fleet/node/gc.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,2EAA2E;AAC3E,uEAAuE;AACvE,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AACjC,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AACvC,MAAM,CAAC,MAAM,sBAAsB,GAAG,EAAE,GAAG,MAAM,CAAC;AAElD,MAAM,MAAM,GAAG,UAAU,CAAC;AAC1B,MAAM,EAAE,GAAG,IAAI,IAAI,CAAC,CAAC;AAErB,sEAAsE;AACtE,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,WAAW,CAAU,CAAC;AA0BvD,SAAS,QAAQ,CAAC,GAAW;IAC3B,IAAI,CAAC;QACH,OAAO,EAAE;aACN,WAAW,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC;aACzC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;aAC9B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC;AAED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,CAAC,CAAC;QACtB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,CAAC,CAAC,GAAG,EAAE,CAAC,cAAe,CAAW,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9C,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;QACjD,CAAC;IACH,CAAC,CAAC;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,UAAU,IAAI,sBAAsB,CAAC,CAAC;IACjE,MAA6C,EAAE,KAAK,EAAE,EAAE,CAAC;IAC1D,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;AAC9C,CAAC"}
@@ -0,0 +1,43 @@
1
+ import type { GoalHostStatus } from "../protocol.js";
2
+ import type { NodeContext, NodeRouteModule } from "./context.js";
3
+ /** Marks the module so the server can advertise the "goals" feature. */
4
+ export declare const GOAL_HOST_FEATURE = "goals";
5
+ export interface GoalHostRecord extends GoalHostStatus {
6
+ /** Workspace (repo root) on the node. */
7
+ cwd: string;
8
+ /** Holds goal.json, result.json, the goal store and run.log. */
9
+ goalDir: string;
10
+ base: string;
11
+ pid?: number;
12
+ resultBranch: string;
13
+ }
14
+ export interface GitResult {
15
+ code: number;
16
+ stdout: string;
17
+ stderr: string;
18
+ }
19
+ export type GoalGit = (cwd: string, args: string[], env?: Record<string, string>) => Promise<GitResult>;
20
+ export interface HeadlessProcess {
21
+ pid?: number;
22
+ /** Resolves with the exit code when the process ends. */
23
+ exited: Promise<number | null>;
24
+ }
25
+ export interface GoalHostOptions {
26
+ /** Start the headless Goal run (tests); default spawns the node's CLI. */
27
+ spawnHeadless?: (args: {
28
+ ctx: NodeContext;
29
+ goalDir: string;
30
+ cwd: string;
31
+ logFile: string;
32
+ env: Record<string, string>;
33
+ }) => HeadlessProcess;
34
+ /** git runner (tests); default the node's git with its own credentials. */
35
+ git?: GoalGit;
36
+ /** How often adopted runs (no child handle) are checked, ms (default 5 s). */
37
+ adoptPollMs?: number;
38
+ }
39
+ /** True for the module that serves /v1/goals (the server advertises "goals" for it). */
40
+ export declare function isGoalHostModule(module: NodeRouteModule): boolean;
41
+ export declare function createGoalHostRouteModule(options?: GoalHostOptions): NodeRouteModule & {
42
+ feature: typeof GOAL_HOST_FEATURE;
43
+ };
@@ -0,0 +1,418 @@
1
+ // GL4/GL6: whole Goals hosted on this node (feature "goals").
2
+ //
3
+ // POST /v1/goals prepares a workspace at the exact commit (+ patch), then runs
4
+ // `ezcoder goals run --headless <goal-dir>` there. The run outlives controller
5
+ // disconnects; its record is kept in <dataDir>/goals/hosted.json and re-adopted
6
+ // after a node restart (a process that died with the node becomes "lost", its
7
+ // workspace kept). When the run ends the node commits the workspace and pushes
8
+ // `ezcoder/goal/<id>` to origin with its own git credentials, so the result
9
+ // never depends on the laptop being awake.
10
+ import { spawn as nodeSpawn } from "node:child_process";
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { killProcessTree } from "../../../utils/process.js";
14
+ import { writeFileAtomic } from "./config.js";
15
+ import { allowedBaseEnv } from "./env.js";
16
+ import { isSafeId, pidAlive } from "./exec.js";
17
+ import { GIT_ALLOWED_PROTOCOLS } from "./workspace.js";
18
+ /** Marks the module so the server can advertise the "goals" feature. */
19
+ export const GOAL_HOST_FEATURE = "goals";
20
+ const MAX_LOG_TAIL = 5_000;
21
+ /** True for the module that serves /v1/goals (the server advertises "goals" for it). */
22
+ export function isGoalHostModule(module) {
23
+ return module.feature === GOAL_HOST_FEATURE;
24
+ }
25
+ function defaultGit(cwd, args, env = {}) {
26
+ return new Promise((resolve) => {
27
+ const child = nodeSpawn("git", args, {
28
+ cwd,
29
+ stdio: ["ignore", "pipe", "pipe"],
30
+ windowsHide: true,
31
+ env: {
32
+ ...process.env,
33
+ GIT_TERMINAL_PROMPT: "0",
34
+ GIT_ALLOW_PROTOCOL: GIT_ALLOWED_PROTOCOLS,
35
+ ...env,
36
+ },
37
+ });
38
+ let stdout = "";
39
+ let stderr = "";
40
+ child.stdout.on("data", (c) => (stdout += c.toString()));
41
+ child.stderr.on("data", (c) => (stderr += c.toString()));
42
+ child.on("error", (error) => resolve({ code: 1, stdout, stderr: error.message }));
43
+ child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
44
+ });
45
+ }
46
+ function defaultSpawnHeadless(args) {
47
+ const out = fs.openSync(args.logFile, "a");
48
+ const child = nodeSpawn(process.execPath, [args.ctx.cliEntry(), "goals", "run", "--headless", args.goalDir], {
49
+ cwd: args.cwd,
50
+ stdio: ["ignore", out, out],
51
+ env: { ...allowedBaseEnv(process.env), ...args.env },
52
+ // Its own process group: it keeps running if the node server restarts.
53
+ detached: process.platform !== "win32",
54
+ windowsHide: true,
55
+ });
56
+ fs.closeSync(out);
57
+ child.unref();
58
+ const exited = new Promise((resolve) => {
59
+ child.on("error", () => resolve(1));
60
+ child.on("exit", (code) => resolve(code));
61
+ });
62
+ return { pid: child.pid, exited };
63
+ }
64
+ async function readJson(req) {
65
+ const chunks = [];
66
+ let size = 0;
67
+ for await (const chunk of req) {
68
+ size += chunk.length;
69
+ if (size > 80 * 1024 * 1024)
70
+ throw new Error("request too large");
71
+ chunks.push(chunk);
72
+ }
73
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
74
+ }
75
+ function status(record) {
76
+ return {
77
+ id: record.id,
78
+ project: record.project,
79
+ state: record.state,
80
+ ...(record.summary && { summary: record.summary }),
81
+ ...(record.resultSha && { resultBranch: record.resultBranch, resultSha: record.resultSha }),
82
+ startedAt: record.startedAt,
83
+ ...(record.finishedAt && { finishedAt: record.finishedAt }),
84
+ };
85
+ }
86
+ function tail(file, lines) {
87
+ try {
88
+ const stat = fs.statSync(file);
89
+ const bytes = Math.min(stat.size, 4 * 1024 * 1024);
90
+ const fd = fs.openSync(file, "r");
91
+ const buf = Buffer.alloc(bytes);
92
+ fs.readSync(fd, buf, 0, bytes, stat.size - bytes);
93
+ fs.closeSync(fd);
94
+ return buf
95
+ .toString("utf8")
96
+ .split("\n")
97
+ .slice(-lines - 1)
98
+ .join("\n");
99
+ }
100
+ catch {
101
+ return "";
102
+ }
103
+ }
104
+ const VALID_BRANCH = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,200}$/;
105
+ export function createGoalHostRouteModule(options = {}) {
106
+ const goals = new Map();
107
+ const timers = new Set();
108
+ const finishing = new Set();
109
+ const git = options.git ?? defaultGit;
110
+ const spawnHeadless = options.spawnHeadless ?? defaultSpawnHeadless;
111
+ let stateFile;
112
+ const persist = () => {
113
+ if (!stateFile)
114
+ return;
115
+ writeFileAtomic(stateFile, JSON.stringify({ version: 1, goals: [...goals.values()] }, null, 2));
116
+ };
117
+ const owner = (id) => `goal:${id}`;
118
+ const logFile = (record) => path.join(record.goalDir, "run.log");
119
+ const appendLog = (record, line) => {
120
+ try {
121
+ fs.appendFileSync(logFile(record), `[node] ${line}\n`);
122
+ }
123
+ catch {
124
+ // the goal folder is gone; the state still says what happened
125
+ }
126
+ };
127
+ /** GL6: commit what the run left and push it as the result branch. */
128
+ async function pushResult(record) {
129
+ const cwd = record.cwd;
130
+ const identity = await git(cwd, ["config", "user.email"]);
131
+ const env = identity.code === 0 && identity.stdout.trim()
132
+ ? {}
133
+ : {
134
+ GIT_AUTHOR_NAME: "EZ Coder",
135
+ GIT_AUTHOR_EMAIL: "ezcoder@localhost",
136
+ GIT_COMMITTER_NAME: "EZ Coder",
137
+ GIT_COMMITTER_EMAIL: "ezcoder@localhost",
138
+ };
139
+ const steps = [
140
+ ["checkout", "-B", record.resultBranch],
141
+ ["add", "-A"],
142
+ ];
143
+ for (const args of steps) {
144
+ const r = await git(cwd, args, env);
145
+ if (r.code !== 0)
146
+ return `git ${args[0]} failed: ${r.stderr.trim().slice(-300)}`;
147
+ }
148
+ const staged = await git(cwd, ["diff", "--cached", "--quiet"], env);
149
+ if (staged.code !== 0) {
150
+ const commit = await git(cwd, [
151
+ "commit",
152
+ "-q",
153
+ "--no-verify",
154
+ "-m",
155
+ `EZ Coder Goal ${record.id}: ${record.summary ?? record.state}`,
156
+ ], env);
157
+ if (commit.code !== 0)
158
+ return `git commit failed: ${commit.stderr.trim().slice(-300)}`;
159
+ }
160
+ const push = await git(cwd, ["push", "--force", "origin", `HEAD:refs/heads/${record.resultBranch}`], env);
161
+ if (push.code !== 0)
162
+ return `git push failed: ${push.stderr.trim().slice(-300)}`;
163
+ const sha = await git(cwd, ["rev-parse", "HEAD"], env);
164
+ if (sha.code !== 0)
165
+ return `git rev-parse failed: ${sha.stderr.trim().slice(-300)}`;
166
+ record.resultSha = sha.stdout.trim();
167
+ return undefined;
168
+ }
169
+ /** The headless run ended (or was found ended): read its result, push, release the slot. */
170
+ async function finish(ctx, record, exitCode) {
171
+ if (record.state !== "running")
172
+ return;
173
+ let result;
174
+ try {
175
+ result = JSON.parse(fs.readFileSync(path.join(record.goalDir, "result.json"), "utf8"));
176
+ }
177
+ catch {
178
+ result = undefined;
179
+ }
180
+ if (finishing.has(record.id))
181
+ return;
182
+ finishing.add(record.id);
183
+ record.pid = undefined;
184
+ let summary = result
185
+ ? `Goal ${result.status}: ${result.summary ?? ""}`.trim()
186
+ : `The Goal run exited (code ${exitCode ?? "unknown"}) without a result; see the log.`;
187
+ record.summary = summary;
188
+ // R2: push whatever it produced, passed or not, so nothing is stranded here.
189
+ // The state stays "running" until the push is done, so a poll never sees a
190
+ // finished Goal without its result branch.
191
+ const pushError = await pushResult(record);
192
+ if (pushError) {
193
+ summary = `${summary} Could not push ${record.resultBranch}: ${pushError}. The workspace is kept at ${record.cwd}.`;
194
+ }
195
+ finishing.delete(record.id);
196
+ if (record.state !== "running")
197
+ return; // stopped meanwhile
198
+ record.summary = summary;
199
+ record.state = !pushError && result?.status === "passed" ? "done" : "failed";
200
+ record.finishedAt = new Date().toISOString();
201
+ appendLog(record, `finished: ${record.state} — ${record.summary}`);
202
+ ctx.releaseSlot(owner(record.id));
203
+ persist();
204
+ ctx.log(`goal ${record.id}: ${record.state}`);
205
+ }
206
+ function watch(ctx, record, proc) {
207
+ if (proc) {
208
+ void proc.exited.then((code) => finish(ctx, record, code));
209
+ return;
210
+ }
211
+ // Adopted after a restart: no child handle, so poll the pid.
212
+ const timer = setInterval(() => {
213
+ if (pidAlive(record.pid))
214
+ return;
215
+ clearInterval(timer);
216
+ timers.delete(timer);
217
+ void finish(ctx, record, null);
218
+ }, options.adoptPollMs ?? 5_000);
219
+ timer.unref?.();
220
+ timers.add(timer);
221
+ }
222
+ async function launch(ctx, record, req) {
223
+ try {
224
+ const cwd = path.resolve(await ctx.prepareWorkspace("agent", `goal-${record.id}`, req.source));
225
+ if (record.state !== "preparing")
226
+ return; // stopped meanwhile
227
+ record.cwd = cwd;
228
+ fs.mkdirSync(record.goalDir, { recursive: true, mode: 0o700 });
229
+ fs.writeFileSync(path.join(record.goalDir, "goal.json"), JSON.stringify(req.goal ?? {}));
230
+ const proc = spawnHeadless({
231
+ ctx,
232
+ goalDir: record.goalDir,
233
+ cwd,
234
+ logFile: logFile(record),
235
+ env: { EZ_GOALS_BASE: path.join(record.goalDir, "store") },
236
+ });
237
+ record.pid = proc.pid;
238
+ record.state = "running";
239
+ persist();
240
+ watch(ctx, record, proc);
241
+ }
242
+ catch (error) {
243
+ record.state = "failed";
244
+ record.summary = `Could not prepare the Goal workspace: ${error instanceof Error ? error.message : String(error)}`;
245
+ record.finishedAt = new Date().toISOString();
246
+ ctx.releaseSlot(owner(record.id));
247
+ persist();
248
+ }
249
+ }
250
+ return {
251
+ feature: GOAL_HOST_FEATURE,
252
+ /** Re-adopt hosted Goals from the previous node process. */
253
+ init(ctx) {
254
+ stateFile = path.join(ctx.config.dataDir, "goals", "hosted.json");
255
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true, mode: 0o700 });
256
+ let records = [];
257
+ try {
258
+ const parsed = JSON.parse(fs.readFileSync(stateFile, "utf8"));
259
+ records = Array.isArray(parsed.goals) ? parsed.goals : [];
260
+ }
261
+ catch (error) {
262
+ if (error.code !== "ENOENT") {
263
+ try {
264
+ fs.renameSync(stateFile, `${stateFile}.corrupt-${Date.now()}`);
265
+ }
266
+ catch {
267
+ // the next save replaces it
268
+ }
269
+ }
270
+ }
271
+ const rebooted = ctx.state?.rebooted() ?? true;
272
+ for (const record of records) {
273
+ if (!isSafeId(record.id) || goals.has(record.id))
274
+ continue;
275
+ goals.set(record.id, record);
276
+ if (record.state !== "running" && record.state !== "preparing")
277
+ continue;
278
+ const alive = record.state === "running" && !rebooted && pidAlive(record.pid);
279
+ if (alive) {
280
+ ctx.acquireSlot(owner(record.id), true);
281
+ watch(ctx, record);
282
+ ctx.log(`goal ${record.id}: re-adopted (running)`);
283
+ continue;
284
+ }
285
+ const finished = fs.existsSync(path.join(record.goalDir, "result.json"));
286
+ if (finished && record.state === "running") {
287
+ // It ended while the node was down: push its result now.
288
+ ctx.acquireSlot(owner(record.id), true);
289
+ void finish(ctx, record, null);
290
+ continue;
291
+ }
292
+ record.state = "lost";
293
+ record.pid = undefined;
294
+ record.finishedAt = new Date().toISOString();
295
+ record.summary = `The node restarted while the Goal ran and could not re-adopt it; its workspace is kept at ${record.cwd || record.goalDir}.`;
296
+ appendLog(record, record.summary);
297
+ }
298
+ persist();
299
+ },
300
+ activeCount() {
301
+ return [...goals.values()].filter((g) => g.state === "running" || g.state === "preparing")
302
+ .length;
303
+ },
304
+ async close() {
305
+ // The runs keep going without the server; only stop watching.
306
+ for (const timer of timers)
307
+ clearInterval(timer);
308
+ timers.clear();
309
+ },
310
+ async handle(ctx, req, res, url) {
311
+ const p = url.pathname;
312
+ if (p === "/v1/goals" && req.method === "GET") {
313
+ ctx.json(res, 200, [...goals.values()].map(status));
314
+ return true;
315
+ }
316
+ if (p === "/v1/goals" && req.method === "POST") {
317
+ let body;
318
+ try {
319
+ body = (await readJson(req));
320
+ }
321
+ catch (error) {
322
+ ctx.json(res, 400, {
323
+ error: `bad request: ${error.message}`,
324
+ code: "bad_request",
325
+ });
326
+ return true;
327
+ }
328
+ if (!isSafeId(body?.id)) {
329
+ ctx.json(res, 400, { error: "invalid id", code: "bad_request" });
330
+ return true;
331
+ }
332
+ const existing = goals.get(body.id);
333
+ if (existing && (existing.state === "preparing" || existing.state === "running")) {
334
+ ctx.json(res, 200, status(existing));
335
+ return true;
336
+ }
337
+ const source = body.source;
338
+ if (!source?.git || !/^[0-9a-f]{7,64}$/i.test(source.sha ?? "")) {
339
+ ctx.json(res, 400, { error: "source {git, sha} is required", code: "bad_request" });
340
+ return true;
341
+ }
342
+ if (source.subdir &&
343
+ (path.isAbsolute(source.subdir) || source.subdir.split(/[\\/]/).includes(".."))) {
344
+ ctx.json(res, 400, { error: "invalid subdir", code: "bad_request" });
345
+ return true;
346
+ }
347
+ const resultBranch = body.resultBranch ?? `ezcoder/goal/${body.id}`;
348
+ if (!VALID_BRANCH.test(resultBranch) || resultBranch.includes("..")) {
349
+ ctx.json(res, 400, { error: "invalid resultBranch", code: "bad_request" });
350
+ return true;
351
+ }
352
+ if (ctx.config.dockerOnly) {
353
+ ctx.json(res, 403, {
354
+ error: "This node only takes Docker work (serve --docker-only); it can't host a Goal.",
355
+ code: "docker_only",
356
+ });
357
+ return true;
358
+ }
359
+ if (!ctx.acquireSlot(owner(body.id))) {
360
+ ctx.json(res, 429, { error: "No free slot on this node", code: "busy" });
361
+ return true;
362
+ }
363
+ const record = {
364
+ id: body.id,
365
+ project: String(body.project ?? ""),
366
+ state: "preparing",
367
+ startedAt: new Date().toISOString(),
368
+ cwd: "",
369
+ goalDir: path.join(ctx.config.dataDir, "goals", body.id),
370
+ base: source.sha,
371
+ resultBranch,
372
+ };
373
+ goals.set(record.id, record);
374
+ persist();
375
+ void launch(ctx, record, body);
376
+ ctx.json(res, 200, status(record));
377
+ return true;
378
+ }
379
+ const m = /^\/v1\/goals\/([^/]+)(\/log)?$/.exec(p);
380
+ if (!m)
381
+ return false;
382
+ const record = goals.get(decodeURIComponent(m[1]));
383
+ if (!record) {
384
+ ctx.json(res, 404, { error: "no such goal" });
385
+ return true;
386
+ }
387
+ if (m[2] && req.method === "GET") {
388
+ const lines = Math.min(Math.max(Number(url.searchParams.get("tail") ?? 200) || 200, 1), MAX_LOG_TAIL);
389
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
390
+ res.end(tail(logFile(record), lines));
391
+ return true;
392
+ }
393
+ if (m[2])
394
+ return false;
395
+ if (req.method === "DELETE") {
396
+ if (record.state === "running" || record.state === "preparing") {
397
+ if (record.pid)
398
+ killProcessTree(record.pid);
399
+ record.state = "stopped";
400
+ record.pid = undefined;
401
+ record.finishedAt = new Date().toISOString();
402
+ record.summary = `Stopped by the controller; the workspace is kept at ${record.cwd || record.goalDir}.`;
403
+ appendLog(record, record.summary);
404
+ ctx.releaseSlot(owner(record.id));
405
+ persist();
406
+ }
407
+ ctx.json(res, 200, status(record));
408
+ return true;
409
+ }
410
+ if (req.method === "GET") {
411
+ ctx.json(res, 200, status(record));
412
+ return true;
413
+ }
414
+ return false;
415
+ },
416
+ };
417
+ }
418
+ //# sourceMappingURL=goals.js.map