@culture.dev/agents 0.0.0-stage → 0.15.0

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 (290) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +59 -2
  3. package/dist/contract-schemas/agent.json +128 -0
  4. package/dist/contract-schemas/allowlist.json +25 -0
  5. package/dist/contract-schemas/api.json +501 -0
  6. package/dist/contract-schemas/capabilities.json +208 -0
  7. package/dist/contract-schemas/common.json +123 -0
  8. package/dist/contract-schemas/control-action.json +279 -0
  9. package/dist/contract-schemas/error.json +269 -0
  10. package/dist/contract-schemas/event.json +316 -0
  11. package/dist/contract-schemas/run.json +336 -0
  12. package/dist/contract-schemas/session.json +77 -0
  13. package/dist/contract-schemas/version.json +22 -0
  14. package/dist/src/contract/api.d.ts +41 -0
  15. package/dist/src/contract/api.js +35 -0
  16. package/dist/src/contract/api.js.map +1 -0
  17. package/dist/src/contract/errors.d.ts +21 -0
  18. package/dist/src/contract/errors.js +25 -0
  19. package/dist/src/contract/errors.js.map +1 -0
  20. package/dist/src/contract/generated/agent.d.ts +31 -0
  21. package/dist/src/contract/generated/agent.js +3 -0
  22. package/dist/src/contract/generated/agent.js.map +1 -0
  23. package/dist/src/contract/generated/allowlist.d.ts +10 -0
  24. package/dist/src/contract/generated/allowlist.js +3 -0
  25. package/dist/src/contract/generated/allowlist.js.map +1 -0
  26. package/dist/src/contract/generated/capabilities.d.ts +46 -0
  27. package/dist/src/contract/generated/capabilities.js +3 -0
  28. package/dist/src/contract/generated/capabilities.js.map +1 -0
  29. package/dist/src/contract/generated/common.d.ts +40 -0
  30. package/dist/src/contract/generated/common.js +3 -0
  31. package/dist/src/contract/generated/common.js.map +1 -0
  32. package/dist/src/contract/generated/control-action.d.ts +73 -0
  33. package/dist/src/contract/generated/control-action.js +3 -0
  34. package/dist/src/contract/generated/control-action.js.map +1 -0
  35. package/dist/src/contract/generated/error.d.ts +25 -0
  36. package/dist/src/contract/generated/error.js +3 -0
  37. package/dist/src/contract/generated/error.js.map +1 -0
  38. package/dist/src/contract/generated/event.d.ts +80 -0
  39. package/dist/src/contract/generated/event.js +3 -0
  40. package/dist/src/contract/generated/event.js.map +1 -0
  41. package/dist/src/contract/generated/index.d.ts +81 -0
  42. package/dist/src/contract/generated/index.js +3 -0
  43. package/dist/src/contract/generated/index.js.map +1 -0
  44. package/dist/src/contract/generated/run.d.ts +63 -0
  45. package/dist/src/contract/generated/run.js +3 -0
  46. package/dist/src/contract/generated/run.js.map +1 -0
  47. package/dist/src/contract/generated/session.d.ts +12 -0
  48. package/dist/src/contract/generated/session.js +3 -0
  49. package/dist/src/contract/generated/session.js.map +1 -0
  50. package/dist/src/contract/generated/version.d.ts +9 -0
  51. package/dist/src/contract/generated/version.js +3 -0
  52. package/dist/src/contract/generated/version.js.map +1 -0
  53. package/dist/src/contract/ids.d.ts +36 -0
  54. package/dist/src/contract/ids.js +85 -0
  55. package/dist/src/contract/ids.js.map +1 -0
  56. package/dist/src/contract/index.d.ts +17 -0
  57. package/dist/src/contract/index.js +13 -0
  58. package/dist/src/contract/index.js.map +1 -0
  59. package/dist/src/contract/run-state.d.ts +13 -0
  60. package/dist/src/contract/run-state.js +24 -0
  61. package/dist/src/contract/run-state.js.map +1 -0
  62. package/dist/src/contract/schemas.d.ts +18 -0
  63. package/dist/src/contract/schemas.js +37 -0
  64. package/dist/src/contract/schemas.js.map +1 -0
  65. package/dist/src/contract/validate.d.ts +17 -0
  66. package/dist/src/contract/validate.js +68 -0
  67. package/dist/src/contract/validate.js.map +1 -0
  68. package/dist/src/daemon/allowlist.d.ts +23 -0
  69. package/dist/src/daemon/allowlist.js +57 -0
  70. package/dist/src/daemon/allowlist.js.map +1 -0
  71. package/dist/src/daemon/daemon.d.ts +31 -0
  72. package/dist/src/daemon/daemon.js +141 -0
  73. package/dist/src/daemon/daemon.js.map +1 -0
  74. package/dist/src/daemon/errors.d.ts +14 -0
  75. package/dist/src/daemon/errors.js +26 -0
  76. package/dist/src/daemon/errors.js.map +1 -0
  77. package/dist/src/daemon/harness-catalog.d.ts +11 -0
  78. package/dist/src/daemon/harness-catalog.js +21 -0
  79. package/dist/src/daemon/harness-catalog.js.map +1 -0
  80. package/dist/src/daemon/http.d.ts +15 -0
  81. package/dist/src/daemon/http.js +76 -0
  82. package/dist/src/daemon/http.js.map +1 -0
  83. package/dist/src/daemon/lock.d.ts +47 -0
  84. package/dist/src/daemon/lock.js +167 -0
  85. package/dist/src/daemon/lock.js.map +1 -0
  86. package/dist/src/daemon/main.d.ts +32 -0
  87. package/dist/src/daemon/main.js +204 -0
  88. package/dist/src/daemon/main.js.map +1 -0
  89. package/dist/src/daemon/paths.d.ts +29 -0
  90. package/dist/src/daemon/paths.js +26 -0
  91. package/dist/src/daemon/paths.js.map +1 -0
  92. package/dist/src/daemon/ports.d.ts +58 -0
  93. package/dist/src/daemon/ports.js +2 -0
  94. package/dist/src/daemon/ports.js.map +1 -0
  95. package/dist/src/daemon/routes.d.ts +15 -0
  96. package/dist/src/daemon/routes.js +259 -0
  97. package/dist/src/daemon/routes.js.map +1 -0
  98. package/dist/src/daemon/sse.d.ts +8 -0
  99. package/dist/src/daemon/sse.js +56 -0
  100. package/dist/src/daemon/sse.js.map +1 -0
  101. package/dist/src/harness/availability.d.ts +9 -0
  102. package/dist/src/harness/availability.js +52 -0
  103. package/dist/src/harness/availability.js.map +1 -0
  104. package/dist/src/harness/claude-code/agent.d.ts +4 -0
  105. package/dist/src/harness/claude-code/agent.js +33 -0
  106. package/dist/src/harness/claude-code/agent.js.map +1 -0
  107. package/dist/src/harness/claude-code/backend.d.ts +48 -0
  108. package/dist/src/harness/claude-code/backend.js +83 -0
  109. package/dist/src/harness/claude-code/backend.js.map +1 -0
  110. package/dist/src/harness/claude-code/capabilities.d.ts +7 -0
  111. package/dist/src/harness/claude-code/capabilities.js +11 -0
  112. package/dist/src/harness/claude-code/capabilities.js.map +1 -0
  113. package/dist/src/harness/claude-code/index.d.ts +15 -0
  114. package/dist/src/harness/claude-code/index.js +20 -0
  115. package/dist/src/harness/claude-code/index.js.map +1 -0
  116. package/dist/src/harness/claude-code/map.d.ts +30 -0
  117. package/dist/src/harness/claude-code/map.js +108 -0
  118. package/dist/src/harness/claude-code/map.js.map +1 -0
  119. package/dist/src/harness/common/capabilities.d.ts +34 -0
  120. package/dist/src/harness/common/capabilities.js +60 -0
  121. package/dist/src/harness/common/capabilities.js.map +1 -0
  122. package/dist/src/harness/common/guard.d.ts +18 -0
  123. package/dist/src/harness/common/guard.js +31 -0
  124. package/dist/src/harness/common/guard.js.map +1 -0
  125. package/dist/src/harness/common/processes.d.ts +21 -0
  126. package/dist/src/harness/common/processes.js +46 -0
  127. package/dist/src/harness/common/processes.js.map +1 -0
  128. package/dist/src/harness/common/queue.d.ts +20 -0
  129. package/dist/src/harness/common/queue.js +76 -0
  130. package/dist/src/harness/common/queue.js.map +1 -0
  131. package/dist/src/harness/common/run-driver.d.ts +88 -0
  132. package/dist/src/harness/common/run-driver.js +317 -0
  133. package/dist/src/harness/common/run-driver.js.map +1 -0
  134. package/dist/src/harness/common/sandbox-workspace.d.ts +72 -0
  135. package/dist/src/harness/common/sandbox-workspace.js +155 -0
  136. package/dist/src/harness/common/sandbox-workspace.js.map +1 -0
  137. package/dist/src/harness/common/text.d.ts +9 -0
  138. package/dist/src/harness/common/text.js +49 -0
  139. package/dist/src/harness/common/text.js.map +1 -0
  140. package/dist/src/harness/common/types.d.ts +111 -0
  141. package/dist/src/harness/common/types.js +2 -0
  142. package/dist/src/harness/common/types.js.map +1 -0
  143. package/dist/src/harness/config.d.ts +43 -0
  144. package/dist/src/harness/config.js +200 -0
  145. package/dist/src/harness/config.js.map +1 -0
  146. package/dist/src/harness/index.d.ts +21 -0
  147. package/dist/src/harness/index.js +89 -0
  148. package/dist/src/harness/index.js.map +1 -0
  149. package/dist/src/harness/opencode/backend.d.ts +37 -0
  150. package/dist/src/harness/opencode/backend.js +114 -0
  151. package/dist/src/harness/opencode/backend.js.map +1 -0
  152. package/dist/src/harness/opencode/capabilities.d.ts +8 -0
  153. package/dist/src/harness/opencode/capabilities.js +11 -0
  154. package/dist/src/harness/opencode/capabilities.js.map +1 -0
  155. package/dist/src/harness/opencode/client.d.ts +70 -0
  156. package/dist/src/harness/opencode/client.js +189 -0
  157. package/dist/src/harness/opencode/client.js.map +1 -0
  158. package/dist/src/harness/opencode/index.d.ts +13 -0
  159. package/dist/src/harness/opencode/index.js +19 -0
  160. package/dist/src/harness/opencode/index.js.map +1 -0
  161. package/dist/src/harness/opencode/lines.d.ts +14 -0
  162. package/dist/src/harness/opencode/lines.js +99 -0
  163. package/dist/src/harness/opencode/lines.js.map +1 -0
  164. package/dist/src/harness/opencode/map.d.ts +13 -0
  165. package/dist/src/harness/opencode/map.js +84 -0
  166. package/dist/src/harness/opencode/map.js.map +1 -0
  167. package/dist/src/harness/opencode/turn.d.ts +23 -0
  168. package/dist/src/harness/opencode/turn.js +143 -0
  169. package/dist/src/harness/opencode/turn.js.map +1 -0
  170. package/dist/src/harness/reclaim.d.ts +13 -0
  171. package/dist/src/harness/reclaim.js +18 -0
  172. package/dist/src/harness/reclaim.js.map +1 -0
  173. package/dist/src/harness/stub/backend.d.ts +11 -0
  174. package/dist/src/harness/stub/backend.js +125 -0
  175. package/dist/src/harness/stub/backend.js.map +1 -0
  176. package/dist/src/harness/stub/index.d.ts +18 -0
  177. package/dist/src/harness/stub/index.js +21 -0
  178. package/dist/src/harness/stub/index.js.map +1 -0
  179. package/dist/src/harness/stub/workspace.d.ts +29 -0
  180. package/dist/src/harness/stub/workspace.js +92 -0
  181. package/dist/src/harness/stub/workspace.js.map +1 -0
  182. package/dist/src/index.d.ts +2 -0
  183. package/dist/src/index.js +3 -0
  184. package/dist/src/index.js.map +1 -0
  185. package/dist/src/runs/agents.d.ts +10 -0
  186. package/dist/src/runs/agents.js +49 -0
  187. package/dist/src/runs/agents.js.map +1 -0
  188. package/dist/src/runs/control.d.ts +31 -0
  189. package/dist/src/runs/control.js +105 -0
  190. package/dist/src/runs/control.js.map +1 -0
  191. package/dist/src/runs/index.d.ts +8 -0
  192. package/dist/src/runs/index.js +7 -0
  193. package/dist/src/runs/index.js.map +1 -0
  194. package/dist/src/runs/ports.d.ts +31 -0
  195. package/dist/src/runs/ports.js +5 -0
  196. package/dist/src/runs/ports.js.map +1 -0
  197. package/dist/src/runs/scan.d.ts +38 -0
  198. package/dist/src/runs/scan.js +149 -0
  199. package/dist/src/runs/scan.js.map +1 -0
  200. package/dist/src/runs/service.d.ts +70 -0
  201. package/dist/src/runs/service.js +239 -0
  202. package/dist/src/runs/service.js.map +1 -0
  203. package/dist/src/sandbox/harness-session.d.ts +11 -0
  204. package/dist/src/sandbox/harness-session.js +170 -0
  205. package/dist/src/sandbox/harness-session.js.map +1 -0
  206. package/dist/src/sandbox/host-command.d.ts +19 -0
  207. package/dist/src/sandbox/host-command.js +41 -0
  208. package/dist/src/sandbox/host-command.js.map +1 -0
  209. package/dist/src/sandbox/index.d.ts +11 -0
  210. package/dist/src/sandbox/index.js +15 -0
  211. package/dist/src/sandbox/index.js.map +1 -0
  212. package/dist/src/sandbox/naming.d.ts +49 -0
  213. package/dist/src/sandbox/naming.js +106 -0
  214. package/dist/src/sandbox/naming.js.map +1 -0
  215. package/dist/src/sandbox/openshell-client.d.ts +81 -0
  216. package/dist/src/sandbox/openshell-client.js +49 -0
  217. package/dist/src/sandbox/openshell-client.js.map +1 -0
  218. package/dist/src/sandbox/policy.d.ts +26 -0
  219. package/dist/src/sandbox/policy.js +100 -0
  220. package/dist/src/sandbox/policy.js.map +1 -0
  221. package/dist/src/sandbox/run-sandbox.d.ts +38 -0
  222. package/dist/src/sandbox/run-sandbox.js +247 -0
  223. package/dist/src/sandbox/run-sandbox.js.map +1 -0
  224. package/dist/src/sandbox/run-sandboxes.d.ts +18 -0
  225. package/dist/src/sandbox/run-sandboxes.js +225 -0
  226. package/dist/src/sandbox/run-sandboxes.js.map +1 -0
  227. package/dist/src/sandbox/timeout.d.ts +12 -0
  228. package/dist/src/sandbox/timeout.js +39 -0
  229. package/dist/src/sandbox/timeout.js.map +1 -0
  230. package/dist/src/sandbox/types.d.ts +125 -0
  231. package/dist/src/sandbox/types.js +15 -0
  232. package/dist/src/sandbox/types.js.map +1 -0
  233. package/dist/src/sandbox/worktree.d.ts +72 -0
  234. package/dist/src/sandbox/worktree.js +157 -0
  235. package/dist/src/sandbox/worktree.js.map +1 -0
  236. package/dist/src/store/derive.d.ts +39 -0
  237. package/dist/src/store/derive.js +68 -0
  238. package/dist/src/store/derive.js.map +1 -0
  239. package/dist/src/store/event-log.d.ts +79 -0
  240. package/dist/src/store/event-log.js +202 -0
  241. package/dist/src/store/event-log.js.map +1 -0
  242. package/dist/src/store/files.d.ts +51 -0
  243. package/dist/src/store/files.js +103 -0
  244. package/dist/src/store/files.js.map +1 -0
  245. package/dist/src/store/index.d.ts +15 -0
  246. package/dist/src/store/index.js +11 -0
  247. package/dist/src/store/index.js.map +1 -0
  248. package/dist/src/store/liveness.d.ts +61 -0
  249. package/dist/src/store/liveness.js +150 -0
  250. package/dist/src/store/liveness.js.map +1 -0
  251. package/dist/src/store/run-store.d.ts +67 -0
  252. package/dist/src/store/run-store.js +211 -0
  253. package/dist/src/store/run-store.js.map +1 -0
  254. package/dist/src/util/sequence.d.ts +58 -0
  255. package/dist/src/util/sequence.js +119 -0
  256. package/dist/src/util/sequence.js.map +1 -0
  257. package/dist/src/worker/control.d.ts +60 -0
  258. package/dist/src/worker/control.js +205 -0
  259. package/dist/src/worker/control.js.map +1 -0
  260. package/dist/src/worker/delivery.d.ts +17 -0
  261. package/dist/src/worker/delivery.js +43 -0
  262. package/dist/src/worker/delivery.js.map +1 -0
  263. package/dist/src/worker/driver.d.ts +88 -0
  264. package/dist/src/worker/driver.js +6 -0
  265. package/dist/src/worker/driver.js.map +1 -0
  266. package/dist/src/worker/fake-driver.d.ts +65 -0
  267. package/dist/src/worker/fake-driver.js +123 -0
  268. package/dist/src/worker/fake-driver.js.map +1 -0
  269. package/dist/src/worker/index.d.ts +15 -0
  270. package/dist/src/worker/index.js +11 -0
  271. package/dist/src/worker/index.js.map +1 -0
  272. package/dist/src/worker/main.d.ts +1 -0
  273. package/dist/src/worker/main.js +57 -0
  274. package/dist/src/worker/main.js.map +1 -0
  275. package/dist/src/worker/retained.d.ts +13 -0
  276. package/dist/src/worker/retained.js +40 -0
  277. package/dist/src/worker/retained.js.map +1 -0
  278. package/dist/src/worker/run-loop.d.ts +63 -0
  279. package/dist/src/worker/run-loop.js +325 -0
  280. package/dist/src/worker/run-loop.js.map +1 -0
  281. package/dist/src/worker/spawn.d.ts +68 -0
  282. package/dist/src/worker/spawn.js +201 -0
  283. package/dist/src/worker/spawn.js.map +1 -0
  284. package/image/Dockerfile +81 -0
  285. package/image/build.sh +62 -0
  286. package/image/pnpm-shim.sh +25 -0
  287. package/package.json +54 -4
  288. package/policy/profiles/culture-agents-claude-subscription.yaml +59 -0
  289. package/policy/profiles/culture-agents-local-gateway.yaml +49 -0
  290. package/policy/run-sandbox.policy.json +10 -0
@@ -0,0 +1,57 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import { validate } from "../contract/index.js";
3
+ /**
4
+ * Read and validate the allow-list file. A missing file is an empty list; a file that does not validate
5
+ * (or cannot be read or parsed) also counts as empty and is reported through `status` (README: authorization).
6
+ */
7
+ export function loadAllowlist(path) {
8
+ let text;
9
+ try {
10
+ text = readFileSync(path, "utf8");
11
+ }
12
+ catch (e) {
13
+ const code = e.code;
14
+ if (code === "ENOENT")
15
+ return { path, status: "missing", entries: [], detail: null };
16
+ return { path, status: "unreadable", entries: [], detail: e.message };
17
+ }
18
+ let parsed;
19
+ try {
20
+ parsed = JSON.parse(text);
21
+ }
22
+ catch (e) {
23
+ return { path, status: "invalid", entries: [], detail: `not valid JSON: ${e.message}` };
24
+ }
25
+ const result = validate("allowlist", parsed);
26
+ if (!result.ok) {
27
+ const first = result.issues[0];
28
+ return { path, status: "invalid", entries: [], detail: `${first?.path || "(root)"}: ${first?.message ?? "invalid"}` };
29
+ }
30
+ return { path, status: "ok", entries: result.value.entries, detail: null };
31
+ }
32
+ /** Canonical (realpath) form of a repository path, or null when it cannot be resolved. */
33
+ export function canonicalRepo(repo) {
34
+ try {
35
+ return realpathSync(repo);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ /**
42
+ * Exact match of agent, harness and canonical repo against the entries. Entry repos are canonicalized
43
+ * the same way; there are no wildcards. Returns the request's canonical repo on a match, else null.
44
+ */
45
+ export function matchAllowlist(entries, request) {
46
+ const repo = canonicalRepo(request.repo);
47
+ if (repo === null)
48
+ return null;
49
+ for (const entry of entries) {
50
+ if (entry.agent_id !== request.agent_id || entry.harness !== request.harness)
51
+ continue;
52
+ if ((canonicalRepo(entry.repo) ?? entry.repo) === repo)
53
+ return repo;
54
+ }
55
+ return null;
56
+ }
57
+ //# sourceMappingURL=allowlist.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allowlist.js","sourceRoot":"","sources":["../../../src/daemon/allowlist.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAsC,MAAM,sBAAsB,CAAC;AAcpF;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,IAAI,IAAY,CAAC;IACjB,IAAI,CAAC;QACH,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACpC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,IAAI,GAAI,CAA2B,CAAC,IAAI,CAAC;QAC/C,IAAI,IAAI,KAAK,QAAQ;YAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QACrF,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,EA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O,IAAI,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,IAAI,KAAK,CAAC,QAAQ,KAAK,OAAO,CAAC,QAAQ,IAAI,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,OAAO;YAAE,SAAS;QACvF,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;IACtE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,31 @@
1
+ import { type AllowlistState } from "./allowlist.js";
2
+ import { type DaemonPaths } from "./paths.js";
3
+ import type { RunService } from "./ports.js";
4
+ export interface DaemonOptions {
5
+ service: RunService;
6
+ /** This host's node name (the `<node>` of local agents). */
7
+ node: string;
8
+ env?: Record<string, string | undefined>;
9
+ /** Allow-list file; defaults to the user config dir. */
10
+ allowlistPath?: string;
11
+ now?: () => Date;
12
+ /** Idle SSE keepalive interval; the contract requires 15 s or less. */
13
+ keepaliveMs?: number;
14
+ }
15
+ export interface Daemon {
16
+ readonly paths: DaemonPaths;
17
+ /** Current allow-list state (re-read from disk), for a `doctor` check. */
18
+ allowlistState(): AllowlistState;
19
+ /** Stop serving, end streams, remove the socket and info file, release the lock. Idempotent. */
20
+ stop(): Promise<void>;
21
+ }
22
+ /** The longest Unix socket path every supported platform accepts (`sun_path` less its terminator), in bytes. */
23
+ export declare const MAX_SOCKET_PATH_BYTES = 107;
24
+ /** One stderr line for an `error` event of a server that is already listening; it must never be unhandled. */
25
+ export declare function logServerError(what: string): (error: unknown) => void;
26
+ /**
27
+ * Start the daemon: take the single-instance lock, clear a stale socket, bind it owner-only, publish
28
+ * the instance info. Throws `LockHeldError` when another core runs. Order matters: lock, then unlink,
29
+ * then bind.
30
+ */
31
+ export declare function startDaemon(options: DaemonOptions): Promise<Daemon>;
@@ -0,0 +1,141 @@
1
+ import { chmodSync, lstatSync, mkdirSync, rmSync, statSync, unlinkSync } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import { apiVersion } from "../contract/index.js";
4
+ import { version as coreVersion } from "../index.js";
5
+ import { loadAllowlist } from "./allowlist.js";
6
+ import { sendError } from "./http.js";
7
+ import { acquireLock, removeInstanceInfo, writeInstanceInfo } from "./lock.js";
8
+ import { resolveAllowlistPath, resolvePaths } from "./paths.js";
9
+ import { handle } from "./routes.js";
10
+ /** Create the socket directory (mode 0700) and refuse one that someone else could use. */
11
+ function prepareDirectory(paths) {
12
+ const uid = process.getuid?.();
13
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
14
+ const st = lstatSync(paths.dir);
15
+ if (!st.isDirectory())
16
+ throw new Error(`${paths.dir} is not a directory; remove it or set CULTURE_AGENTS_SOCKET.`);
17
+ if (uid !== undefined && st.uid !== uid)
18
+ throw new Error(`${paths.dir} is owned by another user; refusing to place the control socket there.`);
19
+ // Only tighten directories this daemon derives itself; an overridden location may be shared on purpose.
20
+ if (!paths.overridden && (st.mode & 0o077) !== 0)
21
+ chmodSync(paths.dir, 0o700);
22
+ }
23
+ /** Remove a leftover socket file. Call only while holding the lock: nothing else can be serving it. */
24
+ function removeStaleSocket(path) {
25
+ let st;
26
+ try {
27
+ st = lstatSync(path);
28
+ }
29
+ catch (e) {
30
+ if (e.code === "ENOENT")
31
+ return;
32
+ throw e;
33
+ }
34
+ if (!st.isSocket())
35
+ throw new Error(`${path} exists and is not a socket; refusing to remove it.`);
36
+ unlinkSync(path);
37
+ }
38
+ /** The longest Unix socket path every supported platform accepts (`sun_path` less its terminator), in bytes. */
39
+ export const MAX_SOCKET_PATH_BYTES = 107;
40
+ /** One stderr line for an `error` event of a server that is already listening; it must never be unhandled. */
41
+ export function logServerError(what) {
42
+ return (error) => {
43
+ process.stderr.write(`culture-agents core: ${what} reported an error: ${error instanceof Error ? error.message : String(error)}\n`);
44
+ };
45
+ }
46
+ const asError = (error) => (error instanceof Error ? error : new Error(String(error)));
47
+ /** Bind the control socket owner-only (0600). The process umask is restored on every path out. */
48
+ function listen(server, path) {
49
+ const bytes = Buffer.byteLength(path);
50
+ if (bytes > MAX_SOCKET_PATH_BYTES) {
51
+ return Promise.reject(new Error(`the control socket path is ${bytes} bytes, but a Unix socket path can be at most ${MAX_SOCKET_PATH_BYTES} bytes (${path}); set CULTURE_AGENTS_SOCKET to a shorter path.`));
52
+ }
53
+ return new Promise((resolve, reject) => {
54
+ const previous = process.umask(0o177); // socket is created 0600
55
+ let restored = false;
56
+ const settle = (error) => {
57
+ if (!restored)
58
+ process.umask(previous);
59
+ restored = true;
60
+ server.off("error", settle);
61
+ if (error === undefined)
62
+ resolve();
63
+ else
64
+ reject(asError(error));
65
+ };
66
+ server.once("error", settle);
67
+ try {
68
+ server.listen(path, () => settle());
69
+ }
70
+ catch (e) {
71
+ settle(e); // `listen` can also throw instead of emitting `error`
72
+ }
73
+ });
74
+ }
75
+ /**
76
+ * Start the daemon: take the single-instance lock, clear a stale socket, bind it owner-only, publish
77
+ * the instance info. Throws `LockHeldError` when another core runs. Order matters: lock, then unlink,
78
+ * then bind.
79
+ */
80
+ export async function startDaemon(options) {
81
+ const env = options.env ?? process.env;
82
+ const paths = resolvePaths(env);
83
+ const allowlistPath = options.allowlistPath ?? resolveAllowlistPath(env);
84
+ prepareDirectory(paths);
85
+ const lock = await acquireLock(paths);
86
+ const shutdown = new AbortController();
87
+ const ctx = {
88
+ service: options.service,
89
+ allowlist: () => loadAllowlist(allowlistPath),
90
+ node: options.node,
91
+ coreVersion,
92
+ now: options.now ?? (() => new Date()),
93
+ keepaliveMs: Math.max(1, options.keepaliveMs ?? 15_000), // never a zero-delay interval
94
+ shutdown: shutdown.signal,
95
+ };
96
+ const server = createServer((req, res) => {
97
+ handle(ctx, req, res).catch((e) => sendError(res, e));
98
+ });
99
+ let bound = false;
100
+ try {
101
+ removeStaleSocket(paths.socket);
102
+ removeInstanceInfo(paths);
103
+ await listen(server, paths.socket);
104
+ bound = true;
105
+ // From here on an `error` event has no one waiting for it: log it instead of crashing the core.
106
+ server.on("error", logServerError("the control socket server"));
107
+ chmodSync(paths.socket, 0o600);
108
+ if ((statSync(paths.socket).mode & 0o777) !== 0o600)
109
+ throw new Error(`could not set ${paths.socket} to mode 0600`);
110
+ writeInstanceInfo(paths, { pid: process.pid, api_version: apiVersion, socket: paths.socket });
111
+ }
112
+ catch (e) {
113
+ server.close();
114
+ // Still under the lock: a socket this start bound is ours to remove, so no stale file is left.
115
+ if (bound)
116
+ rmSync(paths.socket, { force: true });
117
+ await lock.release();
118
+ throw e;
119
+ }
120
+ let stopped = null;
121
+ const stop = () => {
122
+ stopped ??= (async () => {
123
+ shutdown.abort();
124
+ await new Promise((resolve) => {
125
+ server.close(() => resolve());
126
+ server.closeAllConnections();
127
+ });
128
+ try {
129
+ unlinkSync(paths.socket);
130
+ }
131
+ catch {
132
+ /* already removed by close */
133
+ }
134
+ removeInstanceInfo(paths);
135
+ await lock.release();
136
+ })();
137
+ return stopped;
138
+ };
139
+ return { paths, allowlistState: () => ctx.allowlist(), stop };
140
+ }
141
+ //# sourceMappingURL=daemon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daemon.js","sourceRoot":"","sources":["../../../src/daemon/daemon.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,YAAY,EAAe,MAAM,WAAW,CAAC;AAEtD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,aAAa,EAAuB,MAAM,gBAAgB,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,iBAAiB,EAAiB,MAAM,WAAW,CAAC;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;QACjD,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;QACrB,MAAM,CAAC,CAAC;IACV,CAAC;IAED,IAAI,OAAO,GAAyB,IAAI,CAAC;IACzC,MAAM,IAAI,GAAG,GAAkB,EAAE;QAC/B,OAAO,KAAK,CAAC,KAAK,IAAI,EAAE;YACtB,QAAQ,CAAC,KAAK,EAAE,CAAC;YACjB,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;gBAClC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;gBAC9B,MAAM,CAAC,mBAAmB,EAAE,CAAC;YAC/B,CAAC,CAAC,CAAC;YACH,IAAI,CAAC;gBACH,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC3B,CAAC;YAAC,MAAM,CAAC;gBACP,8BAA8B;YAChC,CAAC;YACD,kBAAkB,CAAC,KAAK,CAAC,CAAC;YAC1B,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;QACvB,CAAC,CAAC,EAAE,CAAC;QACL,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;IACF,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,SAAS,EAAE,EAAE,IAAI,EAAE,CAAC;AAChE,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { type ErrorBody, type ErrorCode } from "../contract/index.js";
2
+ /** Extra fields an error body may carry (contract/error.json). */
3
+ export type ErrorExtras = Partial<Omit<ErrorBody, "code" | "message" | "retryable">> & {
4
+ retryable?: boolean;
5
+ };
6
+ /** A typed contract error. Thrown by the server and by `RunService` implementations; rendered as an `error.json` body. */
7
+ export declare class ControlError extends Error {
8
+ readonly body: ErrorBody;
9
+ constructor(code: ErrorCode, message: string, extras?: ErrorExtras);
10
+ }
11
+ export declare function invalid(message: string, field?: string): ControlError;
12
+ export declare function notFound(message: string, extras?: ErrorExtras): ControlError;
13
+ export declare function unsupported(capability: NonNullable<ErrorBody["capability"]>, message: string): ControlError;
14
+ export declare function unavailable(message: string): ControlError;
@@ -0,0 +1,26 @@
1
+ import { retryableFor } from "../contract/index.js";
2
+ /** A typed contract error. Thrown by the server and by `RunService` implementations; rendered as an `error.json` body. */
3
+ export class ControlError extends Error {
4
+ body;
5
+ constructor(code, message, extras = {}) {
6
+ super(message);
7
+ this.name = "ControlError";
8
+ const { retryable, ...rest } = extras;
9
+ // `conflict` is the only code whose retryable flag varies; callers must say which.
10
+ const fixed = retryableFor(code);
11
+ this.body = { code, message, retryable: fixed ?? retryable ?? false, ...rest };
12
+ }
13
+ }
14
+ export function invalid(message, field) {
15
+ return new ControlError("invalid", message, field === undefined ? {} : { field });
16
+ }
17
+ export function notFound(message, extras = {}) {
18
+ return new ControlError("not_found", message, extras);
19
+ }
20
+ export function unsupported(capability, message) {
21
+ return new ControlError("unsupported", message, { capability });
22
+ }
23
+ export function unavailable(message) {
24
+ return new ControlError("unavailable", message);
25
+ }
26
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/daemon/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAkC,MAAM,sBAAsB,CAAC;AAKpF,0HAA0H;AAC1H,MAAM,OAAO,YAAa,SAAQ,KAAK;IAC5B,IAAI,CAAY;IAEzB,YAAY,IAAe,EAAE,OAAe,EAAE,SAAsB,EAAE;QACpE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC3B,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;QACtC,mFAAmF;QACnF,MAAM,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,IAAI,SAAS,IAAI,KAAK,EAAE,GAAG,IAAI,EAAE,CAAC;IACjF,CAAC;CACF;AAED,MAAM,UAAU,OAAO,CAAC,OAAe,EAAE,KAAc;IACrD,OAAO,IAAI,YAAY,CAAC,SAAS,EAAE,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,OAAe,EAAE,SAAsB,EAAE;IAChE,OAAO,IAAI,YAAY,CAAC,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,UAAgD,EAAE,OAAe;IAC3F,OAAO,IAAI,YAAY,CAAC,aAAa,EAAE,OAAO,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,OAAO,IAAI,YAAY,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAClD,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The real harness registry as the run service's `HarnessCatalog` port. It lives in `daemon/`
3
+ * so that `runs/` never imports a harness module, and it is loaded only by the daemon's bin
4
+ * target (`main.ts`): `main()` itself keeps the empty catalog unless a catalog is passed.
5
+ */
6
+ import { type HarnessConfig } from "../harness/index.js";
7
+ import type { HarnessCatalog } from "../runs/ports.js";
8
+ /** A catalog over the registry for one configuration. Capability documents are measured per call. */
9
+ export declare function registryCatalog(config: HarnessConfig): HarnessCatalog;
10
+ /** Load the harness configuration and build the catalog; throws `HarnessConfigError` on a bad configuration. */
11
+ export declare function loadRegistryCatalog(env?: Readonly<Record<string, string | undefined>>): HarnessCatalog;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The real harness registry as the run service's `HarnessCatalog` port. It lives in `daemon/`
3
+ * so that `runs/` never imports a harness module, and it is loaded only by the daemon's bin
4
+ * target (`main.ts`): `main()` itself keeps the empty catalog unless a catalog is passed.
5
+ */
6
+ import { listHarnesses, loadHarnessConfig } from "../harness/index.js";
7
+ /** A catalog over the registry for one configuration. Capability documents are measured per call. */
8
+ export function registryCatalog(config) {
9
+ const entries = listHarnesses(config);
10
+ return {
11
+ list: () => entries,
12
+ get: (id) => entries.find((entry) => entry.id === id),
13
+ // Loaded on first use: the gateway client is not part of the daemon's start-up.
14
+ reclaim: async (finishedRunIds) => (await import("../harness/reclaim.js")).reclaimSandboxes(config, finishedRunIds),
15
+ };
16
+ }
17
+ /** Load the harness configuration and build the catalog; throws `HarnessConfigError` on a bad configuration. */
18
+ export function loadRegistryCatalog(env = process.env) {
19
+ return registryCatalog(loadHarnessConfig(env));
20
+ }
21
+ //# sourceMappingURL=harness-catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"harness-catalog.js","sourceRoot":"","sources":["../../../src/daemon/harness-catalog.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAsB,MAAM,qBAAqB,CAAC;AAG3F,qGAAqG;AACrG,MAAM,UAAU,eAAe,CAAC,MAAqB;IACnD,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;IACtC,OAAO;QACL,IAAI,EAAE,GAAG,EAAE,CAAC,OAAO;QACnB,GAAG,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC;QACrD,gFAAgF;QAChF,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC,gBAAgB,CAAC,MAAM,EAAE,cAAc,CAAC;KACpH,CAAC;AACJ,CAAC;AAED,gHAAgH;AAChH,MAAM,UAAU,mBAAmB,CAAC,MAAoD,OAAO,CAAC,GAAG;IACjG,OAAO,eAAe,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC;AACjD,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { type SchemaName } from "../contract/index.js";
3
+ /** Read and parse a JSON request body; an empty, oversized or malformed body is `invalid`. */
4
+ export declare function readJsonBody(req: IncomingMessage): Promise<unknown>;
5
+ /** Validate a body against its contract schema; the first violation becomes an `invalid` error. */
6
+ export declare function checkBody<N extends SchemaName>(name: N, value: unknown): void;
7
+ /**
8
+ * Send a success body after validating it against its response schema. A body that does not validate is
9
+ * a core bug: it is reported as `internal` and never sent (README: the CLI must not pass on invalid payloads).
10
+ */
11
+ export declare function sendJson(res: ServerResponse, status: number, schema: SchemaName, payload: unknown): void;
12
+ /** Send a typed error. Anything that is not a `ControlError` becomes `internal` without leaking details. */
13
+ export declare function sendError(res: ServerResponse, error: unknown): void;
14
+ /** One SSE message: id, event, single-line data, blank line (README: attach). */
15
+ export declare function sseFrame(cursor: number, kind: string, data: unknown): string;
@@ -0,0 +1,76 @@
1
+ import { httpStatusFor, validate } from "../contract/index.js";
2
+ import { ControlError, invalid } from "./errors.js";
3
+ const MAX_BODY_BYTES = 1024 * 1024;
4
+ /** Read and parse a JSON request body; an empty, oversized or malformed body is `invalid`. */
5
+ export async function readJsonBody(req) {
6
+ const chunks = [];
7
+ let size = 0;
8
+ for await (const chunk of req) {
9
+ const buf = chunk;
10
+ size += buf.length;
11
+ if (size > MAX_BODY_BYTES)
12
+ throw invalid("Request body is larger than 1 MiB.");
13
+ chunks.push(buf);
14
+ }
15
+ const text = Buffer.concat(chunks).toString("utf8");
16
+ if (text.trim() === "")
17
+ throw invalid("Request body is required and must be a JSON object.");
18
+ try {
19
+ return JSON.parse(text);
20
+ }
21
+ catch {
22
+ throw invalid("Request body is not valid JSON.");
23
+ }
24
+ }
25
+ /** Validate a body against its contract schema; the first violation becomes an `invalid` error. */
26
+ export function checkBody(name, value) {
27
+ const result = validate(name, value);
28
+ if (result.ok)
29
+ return;
30
+ const first = result.issues[0];
31
+ const where = first?.path ? first.path : "(root)";
32
+ throw invalid(`Request body does not match the contract at ${where}: ${first?.message ?? "invalid"}.`, first?.path || undefined);
33
+ }
34
+ function write(res, status, payload) {
35
+ const text = JSON.stringify(payload);
36
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(text) });
37
+ res.end(text);
38
+ }
39
+ /**
40
+ * Send a success body after validating it against its response schema. A body that does not validate is
41
+ * a core bug: it is reported as `internal` and never sent (README: the CLI must not pass on invalid payloads).
42
+ */
43
+ export function sendJson(res, status, schema, payload) {
44
+ const result = validate(schema, payload);
45
+ if (!result.ok) {
46
+ const first = result.issues[0];
47
+ process.stderr.write(`culture-agents core: response for ${schema} failed validation at ${first?.path ?? ""}: ${first?.message ?? ""}\n`);
48
+ throw new ControlError("internal", "The core produced a response that does not match the contract.");
49
+ }
50
+ write(res, status, payload);
51
+ }
52
+ /** Send a typed error. Anything that is not a `ControlError` becomes `internal` without leaking details. */
53
+ export function sendError(res, error) {
54
+ let body;
55
+ if (error instanceof ControlError)
56
+ body = error.body;
57
+ else {
58
+ process.stderr.write(`culture-agents core: unexpected failure: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
59
+ body = { code: "internal", message: "The core hit an unexpected failure.", retryable: false };
60
+ }
61
+ let payload = { error: body };
62
+ if (!validate("error", payload).ok) {
63
+ payload = { error: { code: "internal", message: "The core produced an invalid error body.", retryable: false } };
64
+ body = payload.error;
65
+ }
66
+ if (res.headersSent) {
67
+ res.destroy();
68
+ return;
69
+ }
70
+ write(res, httpStatusFor(body.code), payload);
71
+ }
72
+ /** One SSE message: id, event, single-line data, blank line (README: attach). */
73
+ export function sseFrame(cursor, kind, data) {
74
+ return `id: ${cursor}\nevent: ${kind}\ndata: ${JSON.stringify(data)}\n\n`;
75
+ }
76
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/daemon/http.ts"],"names":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AAI,GAAG,KAAK,CAAC,IAAI,CAAC;SAChD,CAAC;QACJ,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,4CAA4C,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC9I,IAAI,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,qCAAqC,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAChG,CAAC;IACD,IAAI,OAAO,GAAY,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACvC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,EAAE,CAAC;QACnC,OAAO,GAAG,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,0CAA0C,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,CAAC;QACjH,IAAI,GAAI,OAAgC,CAAC,KAAK,CAAC;IACjD,CAAC;IACD,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;QACpB,GAAG,CAAC,OAAO,EAAE,CAAC;QACd,OAAO;IACT,CAAC;IACD,KAAK,CAAC,GAAG,EAAE,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;AAChD,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,QAAQ,CAAC,MAAc,EAAE,IAAY,EAAE,IAAa;IAClE,OAAO,OAAO,MAAM,YAAY,IAAI,WAAW,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC;AAC5E,CAAC"}
@@ -0,0 +1,47 @@
1
+ import type { DaemonPaths } from "./paths.js";
2
+ /**
3
+ * Single-instance lock.
4
+ *
5
+ * Mechanism (Linux): the lock is a listening socket in the abstract Unix namespace, named after a hash
6
+ * of the lock path. Only one socket can listen on a name, so `listen` failing with EADDRINUSE means
7
+ * another core holds the lock. The kernel destroys an abstract socket when the last descriptor to it
8
+ * closes, which includes the exit of a process killed with SIGKILL. A dead core therefore can never
9
+ * leave a stuck lock, and no cleanup, pid probing or timeout is needed to take over. The lock is taken
10
+ * before the real socket is bound, and a stale socket file is removed only while it is held.
11
+ *
12
+ * Fallback (platforms without abstract sockets): an exclusively created pid file, treated as stale
13
+ * when its pid is not alive. This is best-effort (a reused pid reads as a live holder).
14
+ *
15
+ * The abstract namespace has no file permissions, so another local user could occupy the name and make
16
+ * start fail closed (denial of service only); it grants them no access to the control socket.
17
+ */
18
+ export interface HeldLock {
19
+ release(): Promise<void>;
20
+ }
21
+ /** What a second instance reads to name the running one. */
22
+ export interface InstanceInfo {
23
+ pid: number;
24
+ api_version: string;
25
+ socket: string;
26
+ }
27
+ /** Another core holds the lock. `info` is null when its info file could not be read in time. */
28
+ export declare class LockHeldError extends Error {
29
+ readonly info: InstanceInfo | null;
30
+ constructor(paths: DaemonPaths, info: InstanceInfo | null);
31
+ }
32
+ /** Take the exclusive lock, or throw `LockHeldError` naming the running instance. */
33
+ export declare function acquireLock(paths: DaemonPaths): Promise<HeldLock>;
34
+ /** Publish pid and API version for second instances (atomic replace). Call only while holding the lock. */
35
+ export declare function writeInstanceInfo(paths: DaemonPaths, info: InstanceInfo): void;
36
+ export declare function removeInstanceInfo(paths: DaemonPaths): void;
37
+ /**
38
+ * Read the running instance's info. The holder removes a dead predecessor's file and writes its own
39
+ * right after taking the lock, so retry briefly while the file is missing or names a dead pid.
40
+ */
41
+ export declare function readInstanceInfo(paths: DaemonPaths, attempts?: number, delayMs?: number): Promise<InstanceInfo | null>;
42
+ /**
43
+ * A second lock, on the run store itself. The instance lock above is keyed on the socket path, so
44
+ * two cores given different sockets would otherwise both serve one state directory: each with its
45
+ * own submit queue, and both settling the same orphaned run. Keyed on the directory's real path.
46
+ */
47
+ export declare function acquireStateLock(stateDir: string): Promise<HeldLock>;
@@ -0,0 +1,167 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { createServer } from "node:net";
4
+ import { join } from "node:path";
5
+ import { again, finish, stepUntil } from "../util/sequence.js";
6
+ /** Another core holds the lock. `info` is null when its info file could not be read in time. */
7
+ export class LockHeldError extends Error {
8
+ info;
9
+ constructor(paths, info) {
10
+ super(info
11
+ ? `culture-agents core is already running (pid ${info.pid}, socket ${info.socket}); stop it first.`
12
+ : `culture-agents core is already running (pid unknown) on socket ${paths.socket}; stop it first.`);
13
+ this.name = "LockHeldError";
14
+ this.info = info;
15
+ }
16
+ }
17
+ const LINUX = process.platform === "linux";
18
+ function abstractName(lockPath) {
19
+ return `\0culture-agents-lock-${createHash("sha256").update(lockPath).digest("hex").slice(0, 40)}`;
20
+ }
21
+ function listenAbstract(name) {
22
+ return new Promise((resolve, reject) => {
23
+ const server = createServer((socket) => socket.destroy());
24
+ server.once("error", reject);
25
+ server.listen({ path: name }, () => {
26
+ server.off("error", reject);
27
+ // The lock is held for the life of the process; a later `error` event must never be unhandled.
28
+ server.on("error", (error) => {
29
+ process.stderr.write(`culture-agents core: the instance lock socket reported an error: ${error.message}\n`);
30
+ });
31
+ resolve(server);
32
+ });
33
+ });
34
+ }
35
+ function pidAlive(pid) {
36
+ try {
37
+ process.kill(pid, 0);
38
+ return true;
39
+ }
40
+ catch (e) {
41
+ return e.code === "EPERM";
42
+ }
43
+ }
44
+ function acquirePidFile(path) {
45
+ for (let attempt = 0; attempt < 2; attempt++) {
46
+ try {
47
+ const fd = openSync(path, "wx", 0o600);
48
+ writeFileSync(fd, String(process.pid));
49
+ closeSync(fd);
50
+ return {
51
+ release: () => {
52
+ safeUnlink(path);
53
+ return Promise.resolve();
54
+ },
55
+ };
56
+ }
57
+ catch (e) {
58
+ if (e.code !== "EEXIST")
59
+ throw e;
60
+ const pid = Number.parseInt(readFileSafe(path) ?? "", 10);
61
+ if (Number.isInteger(pid) && pidAlive(pid))
62
+ return null;
63
+ safeUnlink(path);
64
+ }
65
+ }
66
+ return null;
67
+ }
68
+ function readFileSafe(path) {
69
+ try {
70
+ return readFileSync(path, "utf8");
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ function safeUnlink(path) {
77
+ try {
78
+ unlinkSync(path);
79
+ }
80
+ catch {
81
+ /* already gone */
82
+ }
83
+ }
84
+ /** Take the exclusive lock, or throw `LockHeldError` naming the running instance. */
85
+ export async function acquireLock(paths) {
86
+ if (LINUX) {
87
+ try {
88
+ const server = await listenAbstract(abstractName(paths.lock));
89
+ return { release: () => new Promise((resolve) => server.close(() => resolve())) };
90
+ }
91
+ catch (e) {
92
+ if (e.code !== "EADDRINUSE")
93
+ throw e;
94
+ }
95
+ }
96
+ else {
97
+ const held = acquirePidFile(paths.lock);
98
+ if (held)
99
+ return held;
100
+ }
101
+ throw new LockHeldError(paths, await readInstanceInfo(paths));
102
+ }
103
+ /** Publish pid and API version for second instances (atomic replace). Call only while holding the lock. */
104
+ export function writeInstanceInfo(paths, info) {
105
+ const tmp = `${paths.info}.${process.pid}.tmp`;
106
+ writeFileSync(tmp, `${JSON.stringify(info)}\n`, { mode: 0o600 });
107
+ renameSync(tmp, paths.info);
108
+ }
109
+ export function removeInstanceInfo(paths) {
110
+ safeUnlink(paths.info);
111
+ }
112
+ /**
113
+ * Read the running instance's info. The holder removes a dead predecessor's file and writes its own
114
+ * right after taking the lock, so retry briefly while the file is missing or names a dead pid.
115
+ */
116
+ export function readInstanceInfo(paths, attempts = 20, delayMs = 25) {
117
+ let tried = 0;
118
+ // Every failed read is followed by the delay, the last one too, as a second instance expects.
119
+ return stepUntil(() => {
120
+ if (tried >= attempts)
121
+ return finish(null);
122
+ tried += 1;
123
+ const info = liveInstanceInfo(paths);
124
+ return info ? finish(info) : again(delayMs);
125
+ });
126
+ }
127
+ /** The info file's content when it parses and names a live pid. */
128
+ function liveInstanceInfo(paths) {
129
+ const text = readFileSafe(paths.info);
130
+ if (!text)
131
+ return null;
132
+ try {
133
+ const info = JSON.parse(text);
134
+ if (Number.isInteger(info.pid) && pidAlive(info.pid))
135
+ return info;
136
+ }
137
+ catch {
138
+ /* partially written; retry */
139
+ }
140
+ return null;
141
+ }
142
+ /**
143
+ * A second lock, on the run store itself. The instance lock above is keyed on the socket path, so
144
+ * two cores given different sockets would otherwise both serve one state directory: each with its
145
+ * own submit queue, and both settling the same orphaned run. Keyed on the directory's real path.
146
+ */
147
+ export async function acquireStateLock(stateDir) {
148
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
149
+ const real = realpathSync(stateDir);
150
+ const taken = new Error(`another culture-agents core already uses the state directory ${real}; stop it first, or set CULTURE_AGENTS_STATE_DIR.`);
151
+ if (LINUX) {
152
+ try {
153
+ const server = await listenAbstract(abstractName(`state:${real}`));
154
+ return { release: () => new Promise((resolve) => server.close(() => resolve())) };
155
+ }
156
+ catch (e) {
157
+ if (e.code !== "EADDRINUSE")
158
+ throw e;
159
+ throw taken;
160
+ }
161
+ }
162
+ const held = acquirePidFile(join(real, "core.lock"));
163
+ if (held)
164
+ return held;
165
+ throw taken;
166
+ }
167
+ //# sourceMappingURL=lock.js.map