@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,111 @@
1
+ /**
2
+ * Internal seams of the harness layer. A run driver (`run-driver.ts`) composes a `Workspace`
3
+ * (where the harness works: an OpenShell sandbox, or a host temp clone for the stub) with a
4
+ * `HarnessBackend` (how one harness is started, streamed, steered and interrupted). Contract
5
+ * types only; nothing here names an AI SDK, OpenShell or vendor type.
6
+ */
7
+ import type { ErrorBody, OutputData } from "../../contract/index.js";
8
+ /** One process seen in a workspace (`ps`), used for the after-cancel checks. */
9
+ export interface Proc {
10
+ pid: number;
11
+ ppid: number;
12
+ args: string;
13
+ }
14
+ /** Commits brought back to the host. */
15
+ export interface Collected {
16
+ branch: string;
17
+ commit: string;
18
+ /** Number of commits on the branch beyond the run's base commit. */
19
+ commits: number;
20
+ /** Those commits as full SHAs in the host repository, oldest first. */
21
+ shas: string[];
22
+ }
23
+ /** Where a harness runs for one run. Every method is safe to call after `destroy` fails. */
24
+ export interface Workspace {
25
+ /** Absolute path of the run's working tree, as the harness sees it. */
26
+ readonly workdir: string;
27
+ /** Live processes (empty where the workspace cannot list them). */
28
+ processes(): Promise<Proc[]>;
29
+ /** Force-kill processes by pid. */
30
+ kill(pids: readonly number[]): Promise<void>;
31
+ /** Commit every change in the working tree; returns the commit count beyond the base. */
32
+ commitAll(message: string): Promise<number>;
33
+ /** Bring the run's commits to the host branch `runs/<id>`; null when there are none. */
34
+ collect(): Promise<Collected | null>;
35
+ /**
36
+ * What an operator needs to find a workspace that is kept after the run: its name and how to
37
+ * get the run's work out of it. Absent or null where the workspace cannot outlive the run (the
38
+ * stub's temp clone), which is then destroyed on every path.
39
+ */
40
+ retention?(): {
41
+ sandbox: string;
42
+ recover: string;
43
+ } | null;
44
+ /** Let go of the workspace without deleting it (close local handles). Called instead of `destroy` when it is kept. */
45
+ keep?(): Promise<void>;
46
+ /** Release the workspace (delete the sandbox). Idempotent. */
47
+ destroy(): Promise<void>;
48
+ }
49
+ export interface WorkspaceFactory<W extends Workspace = Workspace> {
50
+ open(signal: AbortSignal): Promise<W>;
51
+ }
52
+ /** What a turn reports while it runs. */
53
+ export type TurnEvent = {
54
+ type: "output";
55
+ data: OutputData;
56
+ } | {
57
+ type: "error";
58
+ error: ErrorBody;
59
+ };
60
+ /** How a turn ended, as the harness's own authority reports it. */
61
+ export type TurnOutcome = {
62
+ kind: "completed";
63
+ summary?: string;
64
+ } | {
65
+ kind: "failed";
66
+ error: ErrorBody;
67
+ } | {
68
+ kind: "interrupted";
69
+ };
70
+ export interface TurnHandle {
71
+ /** Output while the turn runs; ends when the turn has ended. */
72
+ readonly events: AsyncIterable<TurnEvent>;
73
+ /** Resolves once the turn has ended (after `events` ends). */
74
+ readonly outcome: Promise<TurnOutcome>;
75
+ /** Deliver a user message into the running turn. Throws when the turn cannot take it. */
76
+ steer(text: string): Promise<void>;
77
+ /** Ask the harness to stop the turn. */
78
+ interrupt(): Promise<void>;
79
+ }
80
+ export interface HarnessSession {
81
+ startTurn(task: string): Promise<TurnHandle>;
82
+ /** End the harness (its server or bridge); the workspace stays. Idempotent. */
83
+ close(): Promise<void>;
84
+ }
85
+ /** Side channel for diagnostics a backend wants on the run's log. */
86
+ export type Sink = (event: TurnEvent) => void;
87
+ export interface HarnessBackend<W extends Workspace = Workspace> {
88
+ open(workspace: W, signal: AbortSignal, sink: Sink): Promise<HarnessSession>;
89
+ }
90
+ /** What the driver observed about processes around a cancel (also kept for tests). */
91
+ export interface StopReport {
92
+ /** New processes (not in the pre-harness baseline) right after the turn stopped. */
93
+ afterInterrupt: Proc[];
94
+ /** New processes after the harness itself was closed. */
95
+ afterClose: Proc[];
96
+ /** Pids the driver force-killed because they outlived the harness. */
97
+ killed: number[];
98
+ /** New processes after the kill (must be empty). */
99
+ remaining: Proc[];
100
+ /**
101
+ * Why a listing above could not be taken, by field. A field named here is empty because the
102
+ * check could not look, not because nothing was running.
103
+ */
104
+ listingFailed: {
105
+ afterInterrupt?: string;
106
+ afterClose?: string;
107
+ remaining?: string;
108
+ };
109
+ /** Whether the workspace was destroyed. */
110
+ destroyed: boolean;
111
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/harness/common/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,43 @@
1
+ export declare const CLAUDE_MODELS: readonly ["haiku", "sonnet", "opus"];
2
+ export type ClaudeModel = (typeof CLAUDE_MODELS)[number];
3
+ /** Days a sandbox is kept when a completed turn's commit or collect failed (owner decision: 7). */
4
+ export declare const DEFAULT_RETAIN_FAILED_SANDBOX_DAYS = 7;
5
+ export declare const MAX_RETAIN_FAILED_SANDBOX_DAYS = 90;
6
+ export interface HarnessConfig {
7
+ gateway: {
8
+ endpoint: string;
9
+ tlsDir: string | null;
10
+ name: string | null;
11
+ };
12
+ openshellBin: string;
13
+ dockerBin: string;
14
+ image: string;
15
+ sandboxPrefix: string;
16
+ ref: string;
17
+ identity: {
18
+ name: string;
19
+ email: string;
20
+ };
21
+ claudeCode: {
22
+ providers: string[];
23
+ model: ClaudeModel;
24
+ };
25
+ opencode: {
26
+ providers: string[];
27
+ model: string;
28
+ baseUrl: string;
29
+ keyEnv: string;
30
+ port: number;
31
+ };
32
+ /** Days a sandbox holding uncollected work is kept; 0 keeps nothing. */
33
+ retainFailedSandboxDays: number;
34
+ stub: boolean;
35
+ /** The config file that was read, or null. */
36
+ file: string | null;
37
+ }
38
+ export declare class HarnessConfigError extends Error {
39
+ readonly name = "HarnessConfigError";
40
+ }
41
+ type Env = Readonly<Record<string, string | undefined>>;
42
+ export declare function loadHarnessConfig(env?: Env): HarnessConfig;
43
+ export {};
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Harness configuration: where the sandbox gateway is, which image and credential providers a
3
+ * run uses, and each harness's model. Read from environment variables, then an optional JSON
4
+ * file, then the defaults below (environment wins over the file, the file over defaults).
5
+ *
6
+ * OWNER REVIEW: every key and default here is a decision. Defaults match the D1 probe
7
+ * (docs/d0/probe.md) and the gateway running on the fleet host.
8
+ *
9
+ * | JSON key (file) | Environment variable | Default |
10
+ * | ---------------------- | ------------------------------------ | ----------------------------------------- |
11
+ * | (the file itself) | CULTURE_AGENTS_HARNESS_CONFIG | $XDG_CONFIG_HOME/culture-agents/harness.json (~/.config when XDG_CONFIG_HOME is unset); a missing file is fine |
12
+ * | gateway.endpoint | CULTURE_AGENTS_GATEWAY_ENDPOINT | https://127.0.0.1:17670 (local OpenShell gateway) |
13
+ * | gateway.tlsDir | CULTURE_AGENTS_GATEWAY_TLS_DIR | $OPENSHELL_LOCAL_TLS_DIR, else unset (the harness is then unavailable) |
14
+ * | gateway.name | CULTURE_AGENTS_GATEWAY_NAME | unset: the `openshell` CLI's default gateway (used by `collect`) |
15
+ * | openshellBin | CULTURE_AGENTS_OPENSHELL_BIN | openshell (on PATH; `collect` runs `sandbox ssh-config`) |
16
+ * | dockerBin | CULTURE_AGENTS_DOCKER_BIN | docker (availability check: the image exists locally) |
17
+ * | image | CULTURE_AGENTS_RUN_IMAGE | culture-agents-run:dev (built by core/image/build.sh) |
18
+ * | sandboxPrefix | CULTURE_AGENTS_SANDBOX_PREFIX | ca- (1-9 of [a-z0-9-], starting with a letter) |
19
+ * | ref | CULTURE_AGENTS_RUN_REF | HEAD (the host repository commit a run starts from) |
20
+ * | identity.name / .email | CULTURE_AGENTS_COMMIT_NAME / _EMAIL | culture-agents run / runs@culture-agents.invalid (never the operator's) |
21
+ * | claudeCode.providers | CULTURE_AGENTS_CLAUDE_PROVIDERS | claude-sub (comma-separated provider names on the gateway) |
22
+ * | claudeCode.model | CULTURE_AGENTS_CLAUDE_MODEL | haiku (one of haiku, sonnet, opus: the AI SDK adapter's model ids) |
23
+ * | opencode.providers | CULTURE_AGENTS_OPENCODE_PROVIDERS | lobes |
24
+ * | opencode.model | CULTURE_AGENTS_OPENCODE_MODEL | gateway/worker (`<provider id>/<model id>` in the generated OpenCode config) |
25
+ * | opencode.baseUrl | CULTURE_AGENTS_OPENCODE_BASE_URL | http://host.openshell.internal:8001/v1 (the model gateway as a sandbox sees it) |
26
+ * | opencode.keyEnv | CULTURE_AGENTS_OPENCODE_KEY_ENV | LOBES_GATEWAY_KEY (sandbox variable holding the provider placeholder; never a value) |
27
+ * | opencode.port | CULTURE_AGENTS_OPENCODE_PORT | 4096 (port of `opencode serve` inside the sandbox) |
28
+ * | retainFailedSandboxDays | CULTURE_AGENTS_RETAIN_FAILED_SANDBOX_DAYS | 7 (days a sandbox is kept when a completed turn's work could not be brought to the host; 0 to 90, 0 keeps nothing) |
29
+ * | stub | CULTURE_AGENTS_HARNESS_STUB | false; "1"/"true" lists the harness-neutral `stub` harness |
30
+ *
31
+ * No credential value is ever read here: providers are referenced by name and keys by the
32
+ * name of the variable that holds OpenShell's placeholder inside the sandbox.
33
+ *
34
+ * Every value that later reaches a command line or a generated file is validated here: names
35
+ * cannot look like options, `opencode.keyEnv` must be a variable NAME (so a pasted key is refused
36
+ * rather than written into the sandbox's OpenCode config), and `opencode.baseUrl` must be an
37
+ * http(s) URL without credentials. Messages never echo `keyEnv` or a URL's userinfo.
38
+ */
39
+ import { readFileSync } from "node:fs";
40
+ import { homedir } from "node:os";
41
+ import { join } from "node:path";
42
+ import { RETAIN_FAILED_SANDBOX_DAYS } from "../worker/driver.js";
43
+ export const CLAUDE_MODELS = ["haiku", "sonnet", "opus"];
44
+ /** Days a sandbox is kept when a completed turn's commit or collect failed (owner decision: 7). */
45
+ export const DEFAULT_RETAIN_FAILED_SANDBOX_DAYS = RETAIN_FAILED_SANDBOX_DAYS;
46
+ export const MAX_RETAIN_FAILED_SANDBOX_DAYS = 90;
47
+ /** An environment variable name. */
48
+ const ENV_NAME = /^[A-Za-z_]\w*$/;
49
+ /** A provider or gateway name: a plain word, never option-like, at most 63 characters. */
50
+ const PLAIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
51
+ /** A container image reference (registry, path, tag, digest): never option-like, no spaces or shell characters. */
52
+ const IMAGE_REF = /^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/;
53
+ /** A git revision: never option-like, no whitespace or control characters. */
54
+ const GIT_REV = /^[^-\s\x00-\x08\x0e-\x1f\x7f][^\s\x00-\x08\x0e-\x1f\x7f]{0,254}$/; // eslint-disable-line no-control-regex
55
+ export class HarnessConfigError extends Error {
56
+ name = "HarnessConfigError";
57
+ }
58
+ function configPath(env) {
59
+ const explicit = env["CULTURE_AGENTS_HARNESS_CONFIG"];
60
+ if (explicit)
61
+ return explicit;
62
+ return join(env["XDG_CONFIG_HOME"] || join(env["HOME"] || homedir(), ".config"), "culture-agents", "harness.json");
63
+ }
64
+ function readFile(path, explicit) {
65
+ let raw;
66
+ try {
67
+ raw = readFileSync(path, "utf8");
68
+ }
69
+ catch (err) {
70
+ if (!explicit && err.code === "ENOENT")
71
+ return null;
72
+ throw new HarnessConfigError(`cannot read harness config ${path}: ${err.message}`);
73
+ }
74
+ try {
75
+ const value = JSON.parse(raw);
76
+ if (value === null || typeof value !== "object" || Array.isArray(value))
77
+ throw new Error("not a JSON object");
78
+ return value;
79
+ }
80
+ catch (err) {
81
+ throw new HarnessConfigError(`harness config ${path} is invalid: ${err.message}`);
82
+ }
83
+ }
84
+ function pick(file, path) {
85
+ let cur = file;
86
+ for (const key of path.split(".")) {
87
+ if (cur === null || typeof cur !== "object")
88
+ return undefined;
89
+ cur = cur[key];
90
+ }
91
+ return cur;
92
+ }
93
+ function isPlainHttpUrl(value) {
94
+ let url;
95
+ try {
96
+ url = new URL(value);
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ return (url.protocol === "http:" || url.protocol === "https:") && url.hostname !== "" && url.username === "" && url.password === "";
102
+ }
103
+ export function loadHarnessConfig(env = process.env) {
104
+ const path = configPath(env);
105
+ const file = readFile(path, Boolean(env["CULTURE_AGENTS_HARNESS_CONFIG"]));
106
+ const str = (envName, key, fallback) => {
107
+ const fromEnv = env[envName];
108
+ if (fromEnv !== undefined && fromEnv !== "")
109
+ return fromEnv;
110
+ const fromFile = pick(file, key);
111
+ if (fromFile === undefined || fromFile === null)
112
+ return fallback;
113
+ if (typeof fromFile !== "string" || fromFile === "")
114
+ throw new HarnessConfigError(`${key} must be a non-empty string`);
115
+ return fromFile;
116
+ };
117
+ const optional = (envName, key, fallback) => {
118
+ const value = str(envName, key, "");
119
+ return value === "" ? fallback : value;
120
+ };
121
+ /** A number from the environment (a decimal string) or the file (a JSON number or a decimal string); NaN when it is neither. */
122
+ const num = (envName, key, fallback) => {
123
+ const fromEnv = env[envName];
124
+ const raw = fromEnv !== undefined && fromEnv !== "" ? fromEnv : pick(file, key);
125
+ if (raw === undefined || raw === null)
126
+ return fallback;
127
+ if (typeof raw === "number")
128
+ return raw;
129
+ return typeof raw === "string" && /^\d+(\.\d+)?$/.test(raw.trim()) ? Number(raw) : Number.NaN;
130
+ };
131
+ const matching = (value, pattern, key, what) => {
132
+ if (!pattern.test(value))
133
+ throw new HarnessConfigError(`${key} must be ${what}`);
134
+ return value;
135
+ };
136
+ const list = (envName, key, fallback) => {
137
+ const fromEnv = env[envName];
138
+ const raw = fromEnv !== undefined && fromEnv !== "" ? fromEnv.split(",") : (pick(file, key) ?? fallback);
139
+ if (!Array.isArray(raw) || raw.some((v) => typeof v !== "string" || !PLAIN_NAME.test(v.trim()))) {
140
+ throw new HarnessConfigError(`${key} must be a list of provider names (letters, digits, '.', '_' and '-', starting with a letter or digit)`);
141
+ }
142
+ return raw.map((v) => v.trim());
143
+ };
144
+ const model = str("CULTURE_AGENTS_CLAUDE_MODEL", "claudeCode.model", "haiku");
145
+ if (!CLAUDE_MODELS.includes(model)) {
146
+ throw new HarnessConfigError(`claudeCode.model must be one of ${CLAUDE_MODELS.join(", ")}`);
147
+ }
148
+ const port = num("CULTURE_AGENTS_OPENCODE_PORT", "opencode.port", 4096);
149
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
150
+ throw new HarnessConfigError("opencode.port must be a TCP port");
151
+ const ocModel = str("CULTURE_AGENTS_OPENCODE_MODEL", "opencode.model", "gateway/worker");
152
+ if (!/^[^/\s]+\/[^\s]+$/.test(ocModel))
153
+ throw new HarnessConfigError("opencode.model must be <provider id>/<model id>");
154
+ const prefix = str("CULTURE_AGENTS_SANDBOX_PREFIX", "sandboxPrefix", "ca-");
155
+ if (!/^[a-z][a-z0-9-]{0,8}$/.test(prefix))
156
+ throw new HarnessConfigError("sandboxPrefix must be 1-9 of [a-z0-9-], starting with a letter");
157
+ // A value here is written into the sandbox's OpenCode config as `{env:<name>}`; anything but a name is refused unseen.
158
+ const keyEnv = str("CULTURE_AGENTS_OPENCODE_KEY_ENV", "opencode.keyEnv", "LOBES_GATEWAY_KEY");
159
+ if (!ENV_NAME.test(keyEnv))
160
+ throw new HarnessConfigError("opencode.keyEnv must be the NAME of an environment variable (letters, digits and '_'), never a key value");
161
+ const baseUrl = str("CULTURE_AGENTS_OPENCODE_BASE_URL", "opencode.baseUrl", "http://host.openshell.internal:8001/v1");
162
+ if (!isPlainHttpUrl(baseUrl))
163
+ throw new HarnessConfigError("opencode.baseUrl must be an http or https URL without a user name or password");
164
+ const gatewayName = optional("CULTURE_AGENTS_GATEWAY_NAME", "gateway.name", null);
165
+ if (gatewayName !== null)
166
+ matching(gatewayName, PLAIN_NAME, "gateway.name", "a gateway name (letters, digits, '.', '_' and '-', starting with a letter or digit)");
167
+ const retainDays = num("CULTURE_AGENTS_RETAIN_FAILED_SANDBOX_DAYS", "retainFailedSandboxDays", DEFAULT_RETAIN_FAILED_SANDBOX_DAYS);
168
+ if (!(retainDays >= 0 && retainDays <= MAX_RETAIN_FAILED_SANDBOX_DAYS)) {
169
+ throw new HarnessConfigError(`retainFailedSandboxDays must be a number from 0 to ${MAX_RETAIN_FAILED_SANDBOX_DAYS} (0 keeps nothing)`);
170
+ }
171
+ const stubRaw = env["CULTURE_AGENTS_HARNESS_STUB"] ?? pick(file, "stub");
172
+ return {
173
+ gateway: {
174
+ endpoint: str("CULTURE_AGENTS_GATEWAY_ENDPOINT", "gateway.endpoint", "https://127.0.0.1:17670"),
175
+ tlsDir: optional("CULTURE_AGENTS_GATEWAY_TLS_DIR", "gateway.tlsDir", env["OPENSHELL_LOCAL_TLS_DIR"] || null),
176
+ name: gatewayName,
177
+ },
178
+ openshellBin: str("CULTURE_AGENTS_OPENSHELL_BIN", "openshellBin", "openshell"),
179
+ dockerBin: str("CULTURE_AGENTS_DOCKER_BIN", "dockerBin", "docker"),
180
+ image: matching(str("CULTURE_AGENTS_RUN_IMAGE", "image", "culture-agents-run:dev"), IMAGE_REF, "image", "an image reference of letters, digits and ._/:@- that does not start with '-'"),
181
+ sandboxPrefix: prefix,
182
+ ref: matching(str("CULTURE_AGENTS_RUN_REF", "ref", "HEAD"), GIT_REV, "ref", "a git revision without whitespace that does not start with '-'"),
183
+ identity: {
184
+ name: str("CULTURE_AGENTS_COMMIT_NAME", "identity.name", "culture-agents run"),
185
+ email: str("CULTURE_AGENTS_COMMIT_EMAIL", "identity.email", "runs@culture-agents.invalid"),
186
+ },
187
+ claudeCode: { providers: list("CULTURE_AGENTS_CLAUDE_PROVIDERS", "claudeCode.providers", ["claude-sub"]), model: model },
188
+ opencode: {
189
+ providers: list("CULTURE_AGENTS_OPENCODE_PROVIDERS", "opencode.providers", ["lobes"]),
190
+ model: ocModel,
191
+ baseUrl,
192
+ keyEnv,
193
+ port,
194
+ },
195
+ retainFailedSandboxDays: retainDays,
196
+ stub: stubRaw === true || stubRaw === "1" || stubRaw === "true",
197
+ file: file === null ? null : path,
198
+ };
199
+ }
200
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/harness/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AAEjE,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AAGlE,mGAAmG;AACnG,MAAM,CAAC,MAAM,kCAAkC,GAAG,0BAA0B,CAAC;AAC7E,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAEjD,oCAAoC;AACpC,MAAM,QAAQ,GAAG,gBAAgB,CAAC;AAClC,0FAA0F;AAC1F,MAAM,UAAU,GAAG,mCAAmC,CAAC;AACvD,mHAAmH;AACnH,MAAM,SAAS,GAAG,uCAAuC,CAAC;AAC1D,8EAA8E;AAC9E,MAAM,OAAO,GAAG,kEAAkE,CAAC,CAAC,uCAAuC;AAmB3H,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IACzB,IAAI,GAAG,oBAAoB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AAC;YACrF,KAAK,EAAE,OAAO;YACd,OAAO;YACP,MAAM;YACN,IAAI;SACL;QACD,uBAAuB,EAAE,UAAU;QACnC,IAAI,EAAE,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,GAAG,IAAI,OAAO,KAAK,MAAM;QAC/D,IAAI,EAAE,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KAClC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,21 @@
1
+ import type { Capabilities } from "../contract/index.js";
2
+ import type { HarnessConfig } from "./config.js";
3
+ export { HarnessConfigError, loadHarnessConfig } from "./config.js";
4
+ export type { HarnessConfig } from "./config.js";
5
+ export { UnsupportedCapabilityError, assertSupported, refusalFor } from "./common/capabilities.js";
6
+ export type { ControlCapability } from "./common/capabilities.js";
7
+ export { guardDriver } from "./common/guard.js";
8
+ export type { GuardedDriver } from "./common/guard.js";
9
+ export interface HarnessEntry {
10
+ id: string;
11
+ /** The capability document, with availability checked now. */
12
+ capabilities(): Promise<Capabilities>;
13
+ driver: {
14
+ /** Absolute path of the compiled driver module exporting `createDriver`. */
15
+ module: string;
16
+ /** JSON-serializable options for `createDriver` (written to the run directory). */
17
+ options: Record<string, unknown>;
18
+ };
19
+ }
20
+ export declare function listHarnesses(config: HarnessConfig): HarnessEntry[];
21
+ export declare function getHarness(config: HarnessConfig, id: string): HarnessEntry | undefined;
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The harness registry: which harnesses this core can drive, their capability documents, and
3
+ * the driver module plus JSON options the worker loads for a run (`driver.json`). Harness-neutral:
4
+ * nothing exported here carries an AI SDK, OpenShell or vendor type, and importing this module
5
+ * loads no driver (drivers are loaded by path, in the worker process).
6
+ *
7
+ * Harnesses: `claude-code` (AI SDK HarnessAgent + Claude Code adapter, in an OpenShell sandbox),
8
+ * `opencode` (OpenCode v2's own server API, in an OpenShell sandbox), and `stub` (in-process, no
9
+ * sandbox; listed only when `config.stub` is true).
10
+ */
11
+ import { fileURLToPath } from "node:url";
12
+ import { checkSandboxHarness } from "./availability.js";
13
+ import { capabilityDocument } from "./common/capabilities.js";
14
+ import { claudeCodeCore, CLAUDE_CODE_TRANSPORT } from "./claude-code/capabilities.js";
15
+ import { openCodeCore, OPENCODE_TRANSPORT } from "./opencode/capabilities.js";
16
+ import { stubCore, STUB_TRANSPORT } from "./stub/index.js";
17
+ export { HarnessConfigError, loadHarnessConfig } from "./config.js";
18
+ export { UnsupportedCapabilityError, assertSupported, refusalFor } from "./common/capabilities.js";
19
+ export { guardDriver } from "./common/guard.js";
20
+ const modulePath = (rel) => fileURLToPath(new URL(rel, import.meta.url));
21
+ function sandboxSettings(config, providers) {
22
+ return {
23
+ gateway: { ...config.gateway },
24
+ openshellBin: config.openshellBin,
25
+ image: config.image,
26
+ providers: [...providers],
27
+ sandboxPrefix: config.sandboxPrefix,
28
+ ref: config.ref,
29
+ identity: { ...config.identity },
30
+ retainFailedSandboxDays: config.retainFailedSandboxDays,
31
+ };
32
+ }
33
+ async function sandboxDoc(config, providers, input, versionOf) {
34
+ const check = await checkSandboxHarness(config, providers);
35
+ return capabilityDocument({
36
+ ...input,
37
+ available: check.available,
38
+ version: versionOf(check.labels),
39
+ extension: { image: config.image, providers, ...(check.reasons.length > 0 ? { unavailable: check.reasons } : {}) },
40
+ });
41
+ }
42
+ export function listHarnesses(config) {
43
+ const claudeProviders = [...config.claudeCode.providers];
44
+ const openCodeProviders = [...config.opencode.providers];
45
+ const entries = [
46
+ {
47
+ id: "claude-code",
48
+ capabilities: () => sandboxDoc(config, claudeProviders, { harness: "claude-code", transport: CLAUDE_CODE_TRANSPORT, core: claudeCodeCore() }, (l) => {
49
+ const cli = l["dev.culture.agents.claude-code"];
50
+ const adapter = l["dev.culture.agents.harness-claude-code"];
51
+ if (!cli)
52
+ return null;
53
+ return adapter ? `${cli} (AI SDK adapter ${adapter})` : cli;
54
+ }),
55
+ driver: {
56
+ module: modulePath("./claude-code/index.js"),
57
+ options: { sandbox: sandboxSettings(config, claudeProviders), model: config.claudeCode.model },
58
+ },
59
+ },
60
+ {
61
+ id: "opencode",
62
+ capabilities: () => sandboxDoc(config, openCodeProviders, { harness: "opencode", transport: OPENCODE_TRANSPORT, core: openCodeCore() }, (l) => l["dev.culture.agents.opencode"] ?? null),
63
+ driver: {
64
+ module: modulePath("./opencode/index.js"),
65
+ options: {
66
+ sandbox: sandboxSettings(config, openCodeProviders),
67
+ opencode: {
68
+ model: config.opencode.model,
69
+ baseUrl: config.opencode.baseUrl,
70
+ keyEnv: config.opencode.keyEnv,
71
+ port: config.opencode.port,
72
+ },
73
+ },
74
+ },
75
+ },
76
+ ];
77
+ if (config.stub) {
78
+ entries.push({
79
+ id: "stub",
80
+ capabilities: async () => capabilityDocument({ harness: "stub", available: true, version: "stub-1", transport: STUB_TRANSPORT, core: stubCore() }),
81
+ driver: { module: modulePath("./stub/index.js"), options: { ref: config.ref, identity: { ...config.identity } } },
82
+ });
83
+ }
84
+ return entries;
85
+ }
86
+ export function getHarness(config, id) {
87
+ return listHarnesses(config).find((entry) => entry.id === id);
88
+ }
89
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/harness/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAwB,MAAM,0BAA0B,CAAC;AAEpF,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEtF,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAE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AAU,CAAC,qBAAqB,CAAC;gBACzC,OAAO,EAAE;oBACP,OAAO,EAAE,eAAe,CAAC,MAAM,EAAE,iBAAiB,CAAC;oBACnD,QAAQ,EAAE;wBACR,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,KAAK;wBAC5B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO;wBAChC,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAM;wBAC9B,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;qBAC3B;iBACF;aACF;SACF;KACF,CAAC;IACF,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC;YACX,EAAE,EAAE,MAAM;YACV,YAAY,EAAE,KAAK,IAAI,EAAE,CACvB,kBAAkB,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,cAAc,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,CAAC;YAC1H,MAAM,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,iBAAiB,CAAC,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,EAAE,EAAE;SAClH,CAAC,CAAC;IACL,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,MAAqB,EAAE,EAAU;IAC1D,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AAChE,CAAC"}
@@ -0,0 +1,37 @@
1
+ import type { RunSandbox } from "../../sandbox/index.js";
2
+ import type { HarnessBackend, HarnessSession, Sink, Workspace } from "../common/types.js";
3
+ import { type FetchLike } from "./client.js";
4
+ import { type TurnTiming } from "./turn.js";
5
+ /** JSON-serializable OpenCode settings (part of the driver options). */
6
+ export interface OpenCodeSettings {
7
+ /** `<provider id>/<model id>`. */
8
+ model: string;
9
+ /** OpenAI-compatible base URL of the model gateway as the sandbox sees it. */
10
+ baseUrl: string;
11
+ /** Sandbox variable holding OpenShell's placeholder for the gateway key. */
12
+ keyEnv: string;
13
+ port: number;
14
+ /** Absolute path of the OpenCode binary in the image (the path the gateway profile allows). */
15
+ binary?: string;
16
+ startTimeoutMs?: number;
17
+ /** Live-test recording: a file that receives every raw server event. */
18
+ tap?: string;
19
+ }
20
+ /** A workspace that exposes its sandbox (the real one, or a test double). */
21
+ export interface SandboxBacked extends Workspace {
22
+ readonly sandbox: Pick<RunSandbox, "home" | "spawn" | "writeFile" | "endpoint">;
23
+ }
24
+ export declare const CONFIG_PATH = ".culture-agents/opencode.json";
25
+ /** The OpenCode config for the model gateway. The key is a `{env:...}` reference, never a value. */
26
+ export declare function openCodeConfig(settings: OpenCodeSettings): Record<string, unknown>;
27
+ /** How long `opencode serve` may take to report that it listens. */
28
+ export declare const START_TIMEOUT_MS = 30000;
29
+ /** How long opening the port forward to the server may take. */
30
+ export declare const FORWARD_TIMEOUT_MS = 30000;
31
+ export declare class OpenCodeBackend<W extends SandboxBacked> implements HarnessBackend<W> {
32
+ private readonly settings;
33
+ private readonly fetchImpl?;
34
+ private readonly timing;
35
+ constructor(settings: OpenCodeSettings, fetchImpl?: FetchLike | undefined, timing?: TurnTiming);
36
+ open(workspace: W, signal: AbortSignal, sink: Sink): Promise<HarnessSession>;
37
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * OpenCode v2 driven through its own server API. In the run's sandbox the backend writes an
3
+ * OpenCode config for the model gateway, starts `opencode serve` in the cloned repository with a
4
+ * per-run password, reaches it through the sandbox's port forward, and creates one session at
5
+ * the clone with the configured model. Closing the backend ends the server process.
6
+ */
7
+ import { randomBytes } from "node:crypto";
8
+ import { posix } from "node:path";
9
+ import { withTimeout } from "../../sandbox/timeout.js";
10
+ import { errorMessage, within } from "../common/queue.js";
11
+ import { tapWriter } from "../common/text.js";
12
+ import { MAX_STREAM_UNIT, OpenCodeClient } from "./client.js";
13
+ import { drain, waitForLine } from "./lines.js";
14
+ import { OPENCODE_CALL_TIMEOUT_MS, startOpenCodeTurn } from "./turn.js";
15
+ export const CONFIG_PATH = ".culture-agents/opencode.json";
16
+ /** The OpenCode config for the model gateway. The key is a `{env:...}` reference, never a value. */
17
+ export function openCodeConfig(settings) {
18
+ // The file is written inside the sandbox: only a variable name may go in, so a key value cannot (the message does not echo it).
19
+ if (!ENV_NAME.test(settings.keyEnv))
20
+ throw new Error("the OpenCode key setting must be the name of an environment variable, never a key value");
21
+ const [providerId, ...rest] = settings.model.split("/");
22
+ const modelId = rest.join("/");
23
+ return {
24
+ provider: {
25
+ [providerId]: {
26
+ npm: "@ai-sdk/openai-compatible",
27
+ name: "Local model gateway",
28
+ options: { baseURL: settings.baseUrl, apiKey: `{env:${settings.keyEnv}}` },
29
+ models: { [modelId]: { name: modelId, tool_call: true, reasoning: true } },
30
+ },
31
+ },
32
+ model: settings.model,
33
+ small_model: settings.model,
34
+ autoupdate: false,
35
+ share: "disabled",
36
+ };
37
+ }
38
+ /** A single quote inside a single-quoted shell word: close the word, an escaped quote, open it again. */
39
+ const ESCAPED_QUOTE = String.raw `'\''`;
40
+ const shq = (s) => `'${s.replaceAll("'", ESCAPED_QUOTE)}'`;
41
+ /** How long `opencode serve` may take to report that it listens. */
42
+ export const START_TIMEOUT_MS = 30_000;
43
+ /** How long opening the port forward to the server may take. */
44
+ export const FORWARD_TIMEOUT_MS = 30_000;
45
+ const ENV_NAME = /^[A-Za-z_]\w*$/;
46
+ export class OpenCodeBackend {
47
+ settings;
48
+ fetchImpl;
49
+ timing;
50
+ constructor(settings, fetchImpl, timing = {}) {
51
+ this.settings = settings;
52
+ this.fetchImpl = fetchImpl;
53
+ this.timing = timing;
54
+ }
55
+ async open(workspace, signal, sink) {
56
+ const sb = workspace.sandbox;
57
+ const s = this.settings;
58
+ const configPath = posix.join(sb.home, CONFIG_PATH);
59
+ await sb.writeFile(configPath, new TextEncoder().encode(JSON.stringify(openCodeConfig(s), null, 2)), { signal });
60
+ const password = randomBytes(24).toString("base64url");
61
+ const binary = s.binary ?? "/usr/local/bin/opencode";
62
+ if (!Number.isInteger(s.port) || s.port < 1 || s.port > 65535)
63
+ throw new Error("the OpenCode port must be a TCP port");
64
+ const proc = await sb.spawn(`exec ${shq(binary)} serve --hostname 127.0.0.1 --port ${s.port}`, {
65
+ cwd: workspace.workdir,
66
+ env: { OPENCODE_CONFIG: configPath, OPENCODE_SERVER_PASSWORD: password },
67
+ signal,
68
+ });
69
+ const closer = new AbortController();
70
+ let closed = null;
71
+ const close = () => (closed ??= (async () => {
72
+ closer.abort();
73
+ await proc.cancel().catch(() => undefined);
74
+ })());
75
+ try {
76
+ const stdout = [];
77
+ const stderr = [];
78
+ let overlong = false;
79
+ const lines = {
80
+ onOverlong: () => {
81
+ if (overlong)
82
+ return;
83
+ overlong = true;
84
+ sink({ type: "output", data: { channel: "diagnostic", text: `opencode serve printed a line over ${MAX_STREAM_UNIT} characters; it was dropped` } });
85
+ },
86
+ };
87
+ drain(proc.stderr, stderr, lines);
88
+ const ready = await within(s.startTimeoutMs ?? START_TIMEOUT_MS, waitForLine(proc.stdout, /server listening on /, stdout, lines), signal);
89
+ signal.throwIfAborted();
90
+ if (!ready)
91
+ throw new Error(`opencode serve did not report listening: ${[...stdout, ...stderr].slice(-5).join(" | ").slice(0, 800)}`);
92
+ const ep = await withTimeout("forwarding the OpenCode server's port", FORWARD_TIMEOUT_MS, () => sb.endpoint(s.port), signal);
93
+ const client = new OpenCodeClient(`http://${ep.host}:${ep.port}`, password, this.fetchImpl);
94
+ const [providerID, ...rest] = s.model.split("/");
95
+ const session = await withTimeout("creating the OpenCode session", this.timing.callMs ?? OPENCODE_CALL_TIMEOUT_MS, (bound) => client.createSession({ directory: workspace.workdir, providerID: providerID, modelID: rest.join("/") }, bound), signal);
96
+ void proc.wait().then(({ exitCode }) => {
97
+ if (!closer.signal.aborted)
98
+ sink({ type: "error", error: { code: "internal", message: `opencode serve exited (${exitCode}): ${stderr.slice(-3).join(" | ").slice(0, 500)}`, retryable: false } });
99
+ });
100
+ return {
101
+ startTurn: (task) => {
102
+ const tap = tapWriter(s.tap);
103
+ return startOpenCodeTurn(client, session.id, task, closer.signal, sink, tap ? { ...this.timing, tap } : this.timing);
104
+ },
105
+ close,
106
+ };
107
+ }
108
+ catch (err) {
109
+ await close();
110
+ throw new Error(`could not start OpenCode: ${errorMessage(err)}`);
111
+ }
112
+ }
113
+ }
114
+ //# sourceMappingURL=backend.js.map