operon-agents-core 0.1.0-alpha.2 → 0.1.0-alpha.21

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 (289) hide show
  1. package/dist/agent/agent.d.ts +8 -7
  2. package/dist/agent/compose-hooks.d.ts +10 -1
  3. package/dist/agent/compose-hooks.js +61 -6
  4. package/dist/agent/concurrency.js +1 -1
  5. package/dist/agent/context-report.d.ts +2 -2
  6. package/dist/agent/durable-state.d.ts +22 -0
  7. package/dist/agent/durable-state.js +54 -0
  8. package/dist/agent/index.d.ts +2 -2
  9. package/dist/agent/index.js +1 -1
  10. package/dist/agent/instruction-context.d.ts +6 -6
  11. package/dist/agent/instruction-context.js +23 -23
  12. package/dist/agent/profile-builtins.js +1 -1
  13. package/dist/agent/run-support.d.ts +1 -1
  14. package/dist/agent/run-support.js +6 -5
  15. package/dist/agent/runner.d.ts +25 -22
  16. package/dist/agent/runner.js +217 -121
  17. package/dist/agent/session.d.ts +262 -156
  18. package/dist/agent/session.js +590 -418
  19. package/dist/agent/subagent-tools.js +3 -3
  20. package/dist/agent/subagent.js +28 -13
  21. package/dist/agent/toolset.d.ts +1 -0
  22. package/dist/agent/toolset.js +13 -7
  23. package/dist/agent/workflow/journal.d.ts +2 -2
  24. package/dist/agent/workflow/journal.js +2 -2
  25. package/dist/agent/workflow/manager.d.ts +1 -1
  26. package/dist/agent/workflow/manager.js +1 -1
  27. package/dist/agent/workflow/prompt.js +2 -2
  28. package/dist/agent/workflow/sandbox.d.ts +1 -1
  29. package/dist/agent/workflow/sandbox.js +1 -1
  30. package/dist/agent/workflow/tool.js +30 -43
  31. package/dist/agent/worktree.d.ts +8 -8
  32. package/dist/agent/worktree.js +15 -15
  33. package/dist/capabilities/assembler.d.ts +29 -5
  34. package/dist/capabilities/assembler.js +85 -9
  35. package/dist/capabilities/background/code-task.d.ts +43 -0
  36. package/dist/capabilities/background/code-task.js +75 -0
  37. package/dist/capabilities/background/command-task.d.ts +9 -2
  38. package/dist/capabilities/background/command-task.js +22 -6
  39. package/dist/capabilities/background/index.d.ts +6 -1
  40. package/dist/capabilities/background/index.js +26 -20
  41. package/dist/capabilities/background/manager.d.ts +57 -1
  42. package/dist/capabilities/background/manager.js +210 -45
  43. package/dist/capabilities/background/persist-disk.d.ts +1 -1
  44. package/dist/capabilities/background/persist-disk.js +1 -1
  45. package/dist/capabilities/background/persist.js +4 -2
  46. package/dist/capabilities/background/projections.d.ts +16 -0
  47. package/dist/capabilities/background/projections.js +86 -0
  48. package/dist/capabilities/background/stall-watchdog.d.ts +41 -0
  49. package/dist/capabilities/background/stall-watchdog.js +85 -0
  50. package/dist/capabilities/background/task.d.ts +8 -7
  51. package/dist/capabilities/background/tools.js +33 -7
  52. package/dist/capabilities/capability-data.d.ts +52 -0
  53. package/dist/capabilities/capability-data.js +88 -0
  54. package/dist/capabilities/capability-state.d.ts +2 -4
  55. package/dist/capabilities/capability-state.js +5 -23
  56. package/dist/capabilities/capability.d.ts +203 -38
  57. package/dist/capabilities/compaction/index.js +10 -4
  58. package/dist/capabilities/compaction/service.d.ts +20 -5
  59. package/dist/capabilities/compaction/service.js +27 -11
  60. package/dist/capabilities/goal/goal-store.d.ts +76 -12
  61. package/dist/capabilities/goal/goal-store.js +137 -53
  62. package/dist/capabilities/goal/index.d.ts +1 -1
  63. package/dist/capabilities/goal/index.js +30 -7
  64. package/dist/capabilities/index.d.ts +9 -6
  65. package/dist/capabilities/index.js +4 -3
  66. package/dist/capabilities/plan/index.js +22 -5
  67. package/dist/capabilities/plan/plan-mode.d.ts +30 -9
  68. package/dist/capabilities/plan/plan-mode.js +57 -32
  69. package/dist/capabilities/plan/tools.js +1 -1
  70. package/dist/capabilities/skills/flow-provider.js +3 -3
  71. package/dist/capabilities/skills/index.d.ts +13 -1
  72. package/dist/capabilities/skills/index.js +30 -21
  73. package/dist/capabilities/skills/parser.d.ts +2 -2
  74. package/dist/capabilities/skills/parser.js +3 -3
  75. package/dist/capabilities/skills/registry.d.ts +5 -6
  76. package/dist/capabilities/skills/registry.js +6 -9
  77. package/dist/capabilities/skills/scanner.d.ts +3 -3
  78. package/dist/capabilities/skills/scanner.js +14 -14
  79. package/dist/capabilities/skills/service.d.ts +2 -1
  80. package/dist/capabilities/skills/service.js +3 -3
  81. package/dist/capabilities/skills/skill-tool.d.ts +2 -0
  82. package/dist/capabilities/skills/skill-tool.js +1 -1
  83. package/dist/capabilities/task/index.js +2 -1
  84. package/dist/capabilities/task/persist-disk.d.ts +1 -1
  85. package/dist/capabilities/task/persist-disk.js +1 -1
  86. package/dist/capabilities/task/persist.js +1 -1
  87. package/dist/capabilities/todo/index.js +11 -6
  88. package/dist/capabilities/todo/injector.js +2 -1
  89. package/dist/capabilities/todo/todo-store.d.ts +28 -7
  90. package/dist/capabilities/todo/todo-store.js +44 -11
  91. package/dist/capabilities/todo/tools.js +8 -3
  92. package/dist/capabilities/tool-provider.d.ts +3 -3
  93. package/dist/capabilities/user-hooks/engine.d.ts +3 -3
  94. package/dist/capabilities/user-hooks/engine.js +7 -7
  95. package/dist/capabilities/user-hooks/index.js +2 -1
  96. package/dist/capabilities/workflow/index.d.ts +5 -3
  97. package/dist/capabilities/workflow/index.js +3 -2
  98. package/dist/commands/index.js +34 -32
  99. package/dist/config/index.d.ts +1 -1
  100. package/dist/config/provider-manager.js +0 -28
  101. package/dist/config/schema.d.ts +53 -4
  102. package/dist/config/schema.js +53 -1
  103. package/dist/events/events.d.ts +43 -11
  104. package/dist/events/events.js +1 -0
  105. package/dist/events/index.d.ts +2 -2
  106. package/dist/events/index.js +1 -1
  107. package/dist/events/projection.d.ts +49 -1
  108. package/dist/events/projection.js +144 -19
  109. package/dist/events/publisher.js +2 -21
  110. package/dist/home.d.ts +1 -1
  111. package/dist/home.js +1 -1
  112. package/dist/index.d.ts +3 -2
  113. package/dist/index.js +2 -1
  114. package/dist/internal.d.ts +5 -2
  115. package/dist/internal.js +5 -2
  116. package/dist/llm/define-model.d.ts +4 -0
  117. package/dist/llm/define-model.js +63 -25
  118. package/dist/llm/index.d.ts +1 -0
  119. package/dist/llm/index.js +1 -0
  120. package/dist/llm/model.d.ts +2 -0
  121. package/dist/llm/provider.d.ts +17 -0
  122. package/dist/llm/provider.js +14 -0
  123. package/dist/llm/retry.js +1 -1
  124. package/dist/loop/context.d.ts +21 -1
  125. package/dist/loop/context.js +47 -9
  126. package/dist/loop/events.d.ts +5 -1
  127. package/dist/loop/index.d.ts +2 -2
  128. package/dist/loop/index.js +1 -1
  129. package/dist/loop/interruption.d.ts +9 -4
  130. package/dist/loop/interruption.js +11 -25
  131. package/dist/loop/run-turn.d.ts +16 -3
  132. package/dist/loop/run-turn.js +13 -4
  133. package/dist/loop/steer.d.ts +78 -12
  134. package/dist/loop/steer.js +101 -38
  135. package/dist/loop/tool-call.d.ts +13 -2
  136. package/dist/loop/tool-call.js +135 -5
  137. package/dist/loop/turn-step.d.ts +13 -2
  138. package/dist/loop/turn-step.js +29 -7
  139. package/dist/loop/types.d.ts +6 -0
  140. package/dist/mcp/auth-tool.d.ts +3 -1
  141. package/dist/mcp/auth-tool.js +2 -2
  142. package/dist/mcp/capability.d.ts +13 -0
  143. package/dist/mcp/capability.js +36 -17
  144. package/dist/mcp/config-loader.d.ts +5 -5
  145. package/dist/mcp/config-loader.js +17 -17
  146. package/dist/mcp/credentials.d.ts +35 -0
  147. package/dist/mcp/credentials.js +2 -0
  148. package/dist/mcp/filter.d.ts +2 -2
  149. package/dist/mcp/index.d.ts +4 -3
  150. package/dist/mcp/index.js +1 -1
  151. package/dist/mcp/manager.d.ts +108 -6
  152. package/dist/mcp/manager.js +262 -18
  153. package/dist/mcp/oauth/callback-server.d.ts +10 -1
  154. package/dist/mcp/oauth/callback-server.js +82 -16
  155. package/dist/mcp/oauth/index.d.ts +2 -2
  156. package/dist/mcp/oauth/provider.d.ts +18 -0
  157. package/dist/mcp/oauth/provider.js +31 -1
  158. package/dist/mcp/oauth/service.d.ts +9 -3
  159. package/dist/mcp/oauth/service.js +29 -4
  160. package/dist/mcp/sdk-transport.js +1 -1
  161. package/dist/mcp/server.js +1 -1
  162. package/dist/permission/auto-approver/prompts-data.d.ts +1 -1
  163. package/dist/permission/auto-approver/prompts-data.js +1 -1
  164. package/dist/permission/manager.d.ts +5 -3
  165. package/dist/permission/manager.js +7 -3
  166. package/dist/permission/policies.d.ts +2 -2
  167. package/dist/permission/policies.js +4 -4
  168. package/dist/plugins/fields.d.ts +14 -0
  169. package/dist/plugins/fields.js +30 -0
  170. package/dist/plugins/hooks.d.ts +2 -2
  171. package/dist/plugins/hooks.js +12 -12
  172. package/dist/plugins/index.js +1 -0
  173. package/dist/plugins/manager.d.ts +8 -3
  174. package/dist/plugins/manager.js +18 -7
  175. package/dist/plugins/manifest.d.ts +2 -2
  176. package/dist/plugins/manifest.js +101 -91
  177. package/dist/plugins/marketplace.js +76 -57
  178. package/dist/plugins/store.d.ts +3 -3
  179. package/dist/plugins/store.js +6 -6
  180. package/dist/protocol/index.d.ts +1 -1
  181. package/dist/store/catalog-store.d.ts +4 -1
  182. package/dist/store/catalog-store.js +5 -1
  183. package/dist/store/checkpointing-store.d.ts +41 -0
  184. package/dist/store/checkpointing-store.js +86 -0
  185. package/dist/store/disk-store.d.ts +8 -0
  186. package/dist/store/disk-store.js +127 -5
  187. package/dist/store/index.d.ts +3 -2
  188. package/dist/store/index.js +2 -1
  189. package/dist/store/log-store.d.ts +9 -1
  190. package/dist/store/log-store.js +68 -4
  191. package/dist/store/migrate.d.ts +8 -2
  192. package/dist/store/migrate.js +9 -2
  193. package/dist/store/origin.d.ts +31 -6
  194. package/dist/store/origin.js +0 -14
  195. package/dist/store/pg.d.ts +1 -0
  196. package/dist/store/pg.js +37 -2
  197. package/dist/store/redis.d.ts +1 -0
  198. package/dist/store/redis.js +30 -0
  199. package/dist/store/repository.d.ts +13 -1
  200. package/dist/store/repository.js +45 -2
  201. package/dist/store/session-catalog.d.ts +4 -0
  202. package/dist/store/session-catalog.js +6 -0
  203. package/dist/store/storage.js +3 -0
  204. package/dist/store/store.d.ts +97 -34
  205. package/dist/store/store.js +64 -10
  206. package/dist/telemetry/appender.d.ts +43 -0
  207. package/dist/telemetry/appender.js +46 -0
  208. package/dist/telemetry/events.d.ts +142 -0
  209. package/dist/telemetry/events.js +141 -0
  210. package/dist/telemetry/index.d.ts +10 -0
  211. package/dist/telemetry/index.js +6 -0
  212. package/dist/telemetry/projection.d.ts +23 -0
  213. package/dist/telemetry/projection.js +185 -0
  214. package/dist/telemetry/redact.d.ts +20 -0
  215. package/dist/telemetry/redact.js +40 -0
  216. package/dist/telemetry/service.d.ts +49 -0
  217. package/dist/telemetry/service.js +137 -0
  218. package/dist/testing.d.ts +58 -0
  219. package/dist/testing.js +123 -0
  220. package/dist/tool/background.d.ts +9 -6
  221. package/dist/tool/background.js +7 -1
  222. package/dist/tool/builtin/ask-user-question.js +6 -5
  223. package/dist/tool/builtin/bash.d.ts +6 -0
  224. package/dist/tool/builtin/bash.js +79 -42
  225. package/dist/tool/builtin/edit.js +82 -109
  226. package/dist/tool/builtin/glob.js +13 -13
  227. package/dist/tool/builtin/grep.js +13 -13
  228. package/dist/tool/builtin/read.js +25 -15
  229. package/dist/tool/builtin/write.js +49 -33
  230. package/dist/tool/define.d.ts +14 -8
  231. package/dist/tool/define.js +8 -2
  232. package/dist/tool/{machine-base.d.ts → environment-base.d.ts} +37 -37
  233. package/dist/tool/{machine-base.js → environment-base.js} +45 -119
  234. package/dist/tool/{machine-local.d.ts → environment-local.d.ts} +9 -8
  235. package/dist/tool/{machine-local.js → environment-local.js} +60 -81
  236. package/dist/tool/{machine-null.d.ts → environment-null.d.ts} +9 -9
  237. package/dist/tool/{machine-null.js → environment-null.js} +9 -9
  238. package/dist/tool/{machine-ssh.d.ts → environment-ssh.d.ts} +33 -18
  239. package/dist/tool/{machine-ssh.js → environment-ssh.js} +118 -149
  240. package/dist/tool/{machine.d.ts → environment.d.ts} +53 -82
  241. package/dist/tool/environment.js +2 -0
  242. package/dist/tool/file-freshness.d.ts +33 -19
  243. package/dist/tool/file-freshness.js +39 -30
  244. package/dist/tool/filesystem-tools.d.ts +1 -1
  245. package/dist/tool/filesystem-tools.js +1 -1
  246. package/dist/tool/git-context.d.ts +2 -2
  247. package/dist/tool/git-context.js +8 -8
  248. package/dist/tool/index.d.ts +12 -12
  249. package/dist/tool/index.js +12 -10
  250. package/dist/tool/policies/path-access.d.ts +4 -4
  251. package/dist/tool/policies/path-access.js +12 -12
  252. package/dist/tool/questions.d.ts +8 -0
  253. package/dist/tool/search/catalog.d.ts +37 -0
  254. package/dist/tool/search/catalog.js +182 -0
  255. package/dist/tool/search/deferral.d.ts +3 -2
  256. package/dist/tool/search/loaded.d.ts +32 -0
  257. package/dist/tool/search/loaded.js +96 -0
  258. package/dist/tool/search/search-tool.d.ts +2 -6
  259. package/dist/tool/search/search-tool.js +16 -15
  260. package/dist/tool/shell-env.js +4 -0
  261. package/dist/tool/support/bash-paths.js +38 -7
  262. package/dist/tool/support/{machine-ops.d.ts → environment-ops.d.ts} +12 -14
  263. package/dist/tool/support/{machine-ops.js → environment-ops.js} +21 -2
  264. package/dist/tool/support/git-worktree.d.ts +3 -3
  265. package/dist/tool/support/git-worktree.js +6 -6
  266. package/dist/tool/support/rg-locator.d.ts +6 -6
  267. package/dist/tool/support/rg-locator.js +6 -6
  268. package/dist/tool/support/ripgrep-run.d.ts +5 -5
  269. package/dist/tool/support/ripgrep-run.js +3 -3
  270. package/dist/tool/support/tool-path.d.ts +3 -3
  271. package/dist/tool/support/tool-path.js +7 -7
  272. package/dist/tool/types.d.ts +54 -10
  273. package/dist/tool/web/fetch-url.js +1 -1
  274. package/dist/tool/web/web-search.js +1 -1
  275. package/dist/tool/workspace-spec.d.ts +3 -3
  276. package/dist/tool/workspace-spec.js +27 -27
  277. package/dist/tracing/bridge.d.ts +9 -1
  278. package/dist/tracing/bridge.js +307 -77
  279. package/dist/tracing/index.d.ts +2 -2
  280. package/dist/tracing/otel.d.ts +28 -1
  281. package/dist/tracing/otel.js +150 -38
  282. package/dist/tracing/processor.d.ts +22 -0
  283. package/dist/tracing/processor.js +2 -0
  284. package/dist/tracing/spans.d.ts +54 -0
  285. package/dist/tracing/spans.js +5 -0
  286. package/package.json +6 -2
  287. package/dist/tool/machine.js +0 -15
  288. package/dist/tool/search/activation.d.ts +0 -13
  289. package/dist/tool/search/activation.js +0 -31
@@ -1,16 +1,16 @@
1
1
  import { StringDecoder } from "node:string_decoder";
2
2
  import { posix, win32 } from "node:path";
3
- import { FileExistsError, StaleFileError, } from "./machine.js";
4
- import { fileVersionFromInfo, fileVersionsMatch, normalizeForCompare } from "./support/machine-ops.js";
5
- /** Deadline for the `readlink -f` realpath fallback (see BaseMachine.realpath). */
3
+ import {} from "./environment.js";
4
+ import { materializeModelText } from "./builtin/line-endings.js";
5
+ /** Deadline for the `readlink -f` realpath fallback (see BaseEnvironment.realpath). */
6
6
  const REALPATH_TIMEOUT_MS = 10_000;
7
7
  function codedError(message, code) {
8
8
  const error = new Error(message);
9
9
  error.code = code;
10
10
  return error;
11
11
  }
12
- /** Join with the TARGET machine's path flavour, not the host's — a local process may be
13
- * driving a posix machine (SSH / sandbox) or vice versa. */
12
+ /** Join with the TARGET environment's path flavour, not the host's — a local process may be
13
+ * driving a posix environment (SSH / sandbox) or vice versa. */
14
14
  function joinPath(pathClass, dir, name) {
15
15
  return (pathClass === "win32" ? win32 : posix).join(dir, name);
16
16
  }
@@ -72,12 +72,6 @@ async function readCapped(stream, maxBytes, onData) {
72
72
  }
73
73
  return { text: Buffer.concat(chunks).toString("utf8"), truncated };
74
74
  }
75
- function isFileMissingError(error) {
76
- if (typeof error !== "object" || error === null)
77
- return false;
78
- const code = error["code"];
79
- return code === "ENOENT" || code === "ENOTDIR";
80
- }
81
75
  async function collectStream(stream) {
82
76
  const chunks = [];
83
77
  for await (const chunk of stream) {
@@ -85,24 +79,11 @@ async function collectStream(stream) {
85
79
  }
86
80
  return Buffer.concat(chunks).toString("utf8");
87
81
  }
88
- export class BaseMachine {
89
- /** Extra workspace roots (see Machine.additionalDirs). Default: cwd only. */
82
+ export class BaseEnvironment {
83
+ /** Extra workspace roots (see Environment.additionalDirs). Default: cwd only. */
90
84
  additionalDirs() {
91
85
  return [];
92
86
  }
93
- /**
94
- * The write half of the compare-and-swap in `writeTextIfUnchanged`. Default: the same raw
95
- * write as anywhere else — correct, but a reader racing it can observe a half-written file,
96
- * and a crash mid-write leaves one behind.
97
- *
98
- * Backends that can swap a complete file into place in one indivisible step (write to a
99
- * sibling temp path, then rename over the target on the same filesystem) override this. It
100
- * is separate from `writeBytesRaw` because the extra round trip only earns its cost where
101
- * torn state is observable — which is the CAS path, not every write.
102
- */
103
- async writeBytesSwap(path, data) {
104
- await this.writeBytesRaw(path, data);
105
- }
106
87
  /** Decode with the shared contract: strict UTF-8 throws on invalid bytes (binary detection). */
107
88
  decodeText(data, options) {
108
89
  const encoding = options?.encoding ?? "utf8";
@@ -216,10 +197,25 @@ export class BaseMachine {
216
197
  signal?.removeEventListener("abort", onAbort);
217
198
  }
218
199
  }
219
- /** SIGTERM, then SIGKILL if it does not exit. Returns whether the process actually stopped. */
220
200
  /** How long SIGTERM gets before SIGKILL, and SIGKILL before we give up. Overridable so a
221
201
  * backend (or a test) can tighten it; the default matches the shell's own convention. */
222
202
  sigtermGraceMs = 5_000;
203
+ /**
204
+ * SIGTERM, then SIGKILL. Returns whether the process stopped within its grace.
205
+ *
206
+ * The SIGKILL is UNCONDITIONAL, including on the path where the process exited politely, and
207
+ * that is the whole trick. A command arrives as `sh -c '…'`, so what exits on SIGTERM is
208
+ * usually just the shell; anything it started that trapped the signal keeps running, and a
209
+ * stop that judged by the shell alone would report success over a live orphan.
210
+ *
211
+ * Sending it anyway costs nothing — the signal goes to the process GROUP, and a group with
212
+ * nothing left in it is an ESRCH we ignore. And it costs no TIME, which is the point: a
213
+ * survivor check could tell us whether the second signal is needed, but the answer only ever
214
+ * saves a syscall, while asking it needs a poll loop. Waiting out the grace before killing
215
+ * would cost real time, so we do not do that either: a child still alive after its parent
216
+ * died of SIGTERM has already declined to go quietly, and giving it another five seconds to
217
+ * reconsider is five seconds of a stopped command still holding its port.
218
+ */
223
219
  async escalatingKill(proc, graceMs = this.sigtermGraceMs) {
224
220
  try {
225
221
  await proc.kill("SIGTERM");
@@ -228,15 +224,16 @@ export class BaseMachine {
228
224
  /* already gone */
229
225
  }
230
226
  const exited = proc.wait().then(() => true, () => true);
231
- const inTime = await Promise.race([exited, sleep(graceMs).then(() => false)]);
232
- if (inTime)
233
- return true;
227
+ const stopped = await Promise.race([exited, sleep(graceMs).then(() => false)]);
234
228
  try {
235
229
  await proc.kill("SIGKILL");
236
230
  }
237
231
  catch {
238
- return proc.exitCode !== null;
232
+ /* nothing left to signal */
239
233
  }
234
+ if (stopped)
235
+ return true;
236
+ // It outlived SIGTERM, so give SIGKILL the same grace to land before giving up on it.
240
237
  return await Promise.race([exited, sleep(graceMs).then(() => false)]);
241
238
  }
242
239
  /** `spawn` has no cwd parameter; a backend without a native one runs through a subshell. */
@@ -246,101 +243,30 @@ export class BaseMachine {
246
243
  const quoted = argv.map(shellQuoteArg).join(" ");
247
244
  return ["sh", "-c", `cd ${shellQuoteArg(cwd)} && ${quoted}`];
248
245
  }
246
+ /**
247
+ * The version the last write produced, for backends that can answer without a round
248
+ * trip. Default: nothing — a remote backend would have to stat for it, and paying that
249
+ * on every write to save a content comparison on the rare write-after-write is the
250
+ * wrong trade (see WriteTextResult.version).
251
+ */
252
+ async versionAfterWrite(_path) {
253
+ return undefined;
254
+ }
249
255
  async writeText(path, data, options = {}) {
250
- const payload = options.lineEndings === "CRLF" ? data.replaceAll("\n", "\r\n") : data;
256
+ // Normalize to LF BEFORE joining with CRLF. Text that already contains `\r\n` — which a
257
+ // model's output routinely does, having just read a CRLF file — would otherwise come out
258
+ // as `\r\r\n` and corrupt the file. Same two-step as `materializeModelText`, which the
259
+ // Edit path uses; the two must not disagree about what "write this as CRLF" means.
260
+ const payload = options.lineEndings === "CRLF" ? materializeModelText(data, "crlf") : data;
251
261
  const buf = Buffer.from(payload, options.encoding ?? "utf8");
252
262
  await this.writeBytesRaw(path, buf);
253
- return { bytesWritten: buf.byteLength };
263
+ const version = await this.versionAfterWrite(path);
264
+ return { bytesWritten: buf.byteLength, ...(version !== undefined ? { version } : {}) };
254
265
  }
255
266
  /** Exact bytes through the same primitive `writeText` uses — no encoding, no CRLF rewrite. */
256
267
  async writeBytes(path, data) {
257
268
  await this.writeBytesRaw(path, data);
258
269
  }
259
- // ── Per-path write serialization ──
260
- // The same-process floor of the writeTextIfUnchanged contract: compare, write and
261
- // version stamp happen under the file's lock, so two in-process writers cannot
262
- // interleave. Clones sharing a backend (withCwd) must share this map — backends
263
- // assign `clone.pathLocks = this.pathLocks` when cloning.
264
- pathLocks = new Map();
265
- /** Key identifying "the same file" for the write lock. Backends with real path
266
- * resolution override so relative and absolute spellings share one lock. */
267
- lockKeyFor(path) {
268
- return this.normpath(path);
269
- }
270
- async withPathLock(path, body) {
271
- const key = this.lockKeyFor(path);
272
- const prev = this.pathLocks.get(key) ?? Promise.resolve();
273
- let release;
274
- const gate = new Promise((resolve) => (release = resolve));
275
- this.pathLocks.set(key, gate);
276
- await prev;
277
- try {
278
- return await body();
279
- }
280
- finally {
281
- release();
282
- // Drop the entry once no later writer has queued behind us (bounds the map).
283
- if (this.pathLocks.get(key) === gate)
284
- this.pathLocks.delete(key);
285
- }
286
- }
287
- /**
288
- * The compare half of writeTextIfUnchanged: throws unless the file still matches
289
- * `options.expected`. Shared by the base composition and by backend overrides
290
- * that re-check right before an atomic swap (SshMachine).
291
- */
292
- async assertUnchanged(path, options, encoding) {
293
- let info;
294
- try {
295
- info = await this.fileInfo(path);
296
- }
297
- catch (error) {
298
- if (!isFileMissingError(error))
299
- throw error;
300
- }
301
- if (options.expected === "must-not-exist") {
302
- if (info !== undefined)
303
- throw new FileExistsError();
304
- return;
305
- }
306
- if (info === undefined) {
307
- throw new StaleFileError("File no longer exists. Read it again before attempting to write it.");
308
- }
309
- if (fileVersionsMatch(options.expected, fileVersionFromInfo(info)))
310
- return;
311
- // mtime moved or is unavailable — review against the prior content (the
312
- // Windows false-positive fallback, also the only check on mtime-less
313
- // sandbox backends).
314
- if (options.expectedContent !== undefined) {
315
- let confirmedUnchanged = false;
316
- try {
317
- const text = this.decodeText(await this.readBytes(path), { encoding, errors: "strict" });
318
- confirmedUnchanged = normalizeForCompare(text) === options.expectedContent;
319
- }
320
- catch {
321
- confirmedUnchanged = false;
322
- }
323
- if (!confirmedUnchanged)
324
- throw new StaleFileError();
325
- return;
326
- }
327
- // The mtime moved, or one side never had one, and there is no content to review
328
- // against. Either way the file cannot be established as unchanged — refuse.
329
- throw new StaleFileError();
330
- }
331
- async writeTextIfUnchanged(path, data, options) {
332
- return await this.withPathLock(path, async () => {
333
- const encoding = options.encoding ?? "utf8";
334
- await this.assertUnchanged(path, options, encoding);
335
- const payload = options.lineEndings === "CRLF" ? data.replaceAll("\n", "\r\n") : data;
336
- const buf = Buffer.from(payload, encoding);
337
- await this.writeBytesSwap(path, buf);
338
- // Still inside the lock: the returned version must be THIS write's, not a
339
- // concurrent sibling's that landed after ours.
340
- const after = await this.fileInfo(path);
341
- return { bytesWritten: buf.byteLength, version: fileVersionFromInfo(after) };
342
- });
343
- }
344
270
  /** Deadline for the readlink fallback; a test/backend subclass may shorten it. */
345
271
  realpathTimeoutMs = REALPATH_TIMEOUT_MS;
346
272
  /**
@@ -391,4 +317,4 @@ export class BaseMachine {
391
317
  return this.normpath(path);
392
318
  }
393
319
  }
394
- //# sourceMappingURL=machine-base.js.map
320
+ //# sourceMappingURL=environment-base.js.map
@@ -1,9 +1,9 @@
1
- import { type DirEntry, type Environment, type ByteRange, type Machine, type FileInfo, type WriteFileResult, type WriteTextIfUnchangedOptions } from "./machine.ts";
2
- import { BaseMachine, type SpawnedProcess } from "./machine-base.ts";
3
- export declare function detectEnvironment(env?: NodeJS.ProcessEnv): Environment;
4
- export declare class LocalMachine extends BaseMachine {
1
+ import { type DirEntry, type OsInfo, type ByteRange, type Environment, type FileInfo, type FileVersion } from "./environment.ts";
2
+ import { BaseEnvironment, type SpawnedProcess } from "./environment-base.ts";
3
+ export declare function detectOsInfo(env?: NodeJS.ProcessEnv): OsInfo;
4
+ export declare class LocalEnvironment extends BaseEnvironment {
5
5
  readonly name = "local";
6
- readonly osEnv: Environment;
6
+ readonly osInfo: OsInfo;
7
7
  private cwd;
8
8
  private readonly extraDirs;
9
9
  constructor(cwdOrOptions?: string | {
@@ -14,7 +14,7 @@ export declare class LocalMachine extends BaseMachine {
14
14
  normpath(path: string): string;
15
15
  gethome(): string;
16
16
  getcwd(): string;
17
- withCwd(cwd: string): Machine;
17
+ withCwd(cwd: string): Environment;
18
18
  additionalDirs(): readonly string[];
19
19
  private abs;
20
20
  fileInfo(path: string, options?: {
@@ -24,12 +24,13 @@ export declare class LocalMachine extends BaseMachine {
24
24
  listDir(path: string): Promise<readonly DirEntry[]>;
25
25
  readBytes(path: string, range?: ByteRange): Promise<Buffer>;
26
26
  protected writeBytesRaw(path: string, data: Buffer): Promise<void>;
27
+ /** One stat syscall, no round trip — so the ledger keeps its mtime fast path locally. */
28
+ protected versionAfterWrite(path: string): Promise<FileVersion | undefined>;
27
29
  mkdir(path: string, options?: {
28
30
  parents?: boolean;
29
31
  existOk?: boolean;
30
32
  }): Promise<void>;
31
33
  realpath(path: string): Promise<string>;
32
- writeTextIfUnchanged(path: string, data: string, options: WriteTextIfUnchangedOptions): Promise<WriteFileResult>;
33
34
  protected spawn(argv: readonly string[], env?: Record<string, string>): Promise<SpawnedProcess>;
34
35
  }
35
- //# sourceMappingURL=machine-local.d.ts.map
36
+ //# sourceMappingURL=environment-local.d.ts.map
@@ -1,11 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
- import { chmodSync, existsSync, readFileSync, readlinkSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
- import { lstat as fsLstat, mkdir as fsMkdir, open as fsOpen, opendir, readFile, realpath as fsRealpath, stat as fsStat, writeFile } from "node:fs/promises";
2
+ import { existsSync } from "node:fs";
3
+ import { chmod as fsChmod, lstat as fsLstat, mkdir as fsMkdir, open as fsOpen, opendir, readFile, readlink as fsReadlink, realpath as fsRealpath, rename as fsRename, stat as fsStat, unlink as fsUnlink, writeFile, } from "node:fs/promises";
4
4
  import { arch, homedir, release } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
6
- import { FileExistsError, StaleFileError, } from "./machine.js";
7
- import { BaseMachine } from "./machine-base.js";
8
- import { fileVersionsMatch, normalizeForCompare } from "./support/machine-ops.js";
6
+ import {} from "./environment.js";
7
+ import { BaseEnvironment } from "./environment-base.js";
9
8
  function fileKindFromStats(s) {
10
9
  if (s.isFile())
11
10
  return "file";
@@ -25,15 +24,6 @@ function fileKindFromDirent(entry) {
25
24
  return "symlink";
26
25
  return "other";
27
26
  }
28
- function fileVersionFromStats(s) {
29
- return s.mtimeMs === 0 ? {} : { mtimeMs: s.mtimeMs };
30
- }
31
- function isMissingError(error) {
32
- if (typeof error !== "object" || error === null)
33
- return false;
34
- const code = error["code"];
35
- return code === "ENOENT" || code === "ENOTDIR";
36
- }
37
27
  function isExistsError(error) {
38
28
  if (typeof error !== "object" || error === null)
39
29
  return false;
@@ -41,11 +31,11 @@ function isExistsError(error) {
41
31
  }
42
32
  /**
43
33
  * Write `payload` so a reader sees the old file or the new one, never a half-written one:
44
- * write a sibling temp file, then rename it over the target. Synchronous throughout — this
45
- * runs inside `writeTextIfUnchanged`'s critical section, and a single `await` in here would
46
- * forfeit the atomicity that section exists for.
34
+ * write a sibling temp file, then rename it over the target. This is what makes EVERY local
35
+ * write all-or-nothing; remote backends write straight to the target instead, because there
36
+ * the same staging costs round trips on every write (see Environment.writeText).
47
37
  *
48
- * Three details are load-bearing, all of them things a plain `writeFileSync` gets for free
38
+ * Three details are load-bearing, all of them things a plain `writeFile` gets for free
49
39
  * and a rename does not:
50
40
  *
51
41
  * - A symlink is written THROUGH, not replaced. `renameSync` onto a symlink would clobber
@@ -60,10 +50,10 @@ function isExistsError(error) {
60
50
  * file is the lesser evil against no write at all, and it is what happened before this
61
51
  * function existed.
62
52
  */
63
- function writeFileAtomicSync(target, payload, encoding) {
53
+ async function writeFileAtomic(target, payload) {
64
54
  let realTarget = target;
65
55
  try {
66
- const link = readlinkSync(target);
56
+ const link = await fsReadlink(target);
67
57
  realTarget = isAbsolute(link) ? link : resolve(dirname(target), link);
68
58
  }
69
59
  catch {
@@ -71,26 +61,26 @@ function writeFileAtomicSync(target, payload, encoding) {
71
61
  }
72
62
  let mode;
73
63
  try {
74
- mode = statSync(realTarget).mode;
64
+ mode = (await fsStat(realTarget)).mode;
75
65
  }
76
66
  catch {
77
- // New file: let the umask decide, exactly as writeFileSync would.
67
+ // New file: let the umask decide, exactly as writeFile would.
78
68
  }
79
69
  const temp = `${realTarget}.tmp.${String(process.pid)}.${String(Date.now())}`;
80
70
  try {
81
- writeFileSync(temp, payload, { encoding, flush: true });
71
+ await writeFile(temp, payload, { flush: true });
82
72
  if (mode !== undefined)
83
- chmodSync(temp, mode);
84
- renameSync(temp, realTarget);
73
+ await fsChmod(temp, mode);
74
+ await fsRename(temp, realTarget);
85
75
  }
86
76
  catch {
87
77
  try {
88
- unlinkSync(temp);
78
+ await fsUnlink(temp);
89
79
  }
90
80
  catch {
91
81
  /* never created, or already gone */
92
82
  }
93
- writeFileSync(realTarget, payload, { encoding, flush: true });
83
+ await writeFile(realTarget, payload, { flush: true });
94
84
  }
95
85
  }
96
86
  function detectWindowsGitBash(env = process.env) {
@@ -111,7 +101,7 @@ function detectWindowsGitBash(env = process.env) {
111
101
  }
112
102
  return undefined;
113
103
  }
114
- export function detectEnvironment(env = process.env) {
104
+ export function detectOsInfo(env = process.env) {
115
105
  const platform = process.platform;
116
106
  const osKind = platform === "win32" ? "Windows" : platform === "darwin" ? "Darwin" : "Linux";
117
107
  const shellPath = osKind === "Windows"
@@ -125,9 +115,9 @@ export function detectEnvironment(env = process.env) {
125
115
  shellPath,
126
116
  };
127
117
  }
128
- export class LocalMachine extends BaseMachine {
118
+ export class LocalEnvironment extends BaseEnvironment {
129
119
  name = "local";
130
- osEnv = detectEnvironment();
120
+ osInfo = detectOsInfo();
131
121
  cwd;
132
122
  extraDirs;
133
123
  constructor(cwdOrOptions = process.cwd()) {
@@ -153,9 +143,9 @@ export class LocalMachine extends BaseMachine {
153
143
  getcwd() {
154
144
  return this.cwd;
155
145
  }
156
- // Session-granted extra roots survive a re-root (a worktree machine keeps its grants).
146
+ // Session-granted extra roots survive a re-root (a worktree environment keeps its grants).
157
147
  withCwd(cwd) {
158
- return new LocalMachine({ cwd: this.abs(cwd), additionalDirs: this.extraDirs });
148
+ return new LocalEnvironment({ cwd: this.abs(cwd), additionalDirs: this.extraDirs });
159
149
  }
160
150
  additionalDirs() {
161
151
  return this.extraDirs;
@@ -203,7 +193,18 @@ export class LocalMachine extends BaseMachine {
203
193
  }
204
194
  }
205
195
  async writeBytesRaw(path, data) {
206
- await writeFile(this.abs(path), data);
196
+ await writeFileAtomic(this.abs(path), data);
197
+ }
198
+ /** One stat syscall, no round trip — so the ledger keeps its mtime fast path locally. */
199
+ async versionAfterWrite(path) {
200
+ try {
201
+ const s = await fsStat(this.abs(path));
202
+ return s.mtimeMs === 0 ? {} : { mtimeMs: s.mtimeMs };
203
+ }
204
+ catch {
205
+ // The write succeeded; failing to re-stat it only costs the fast path.
206
+ return undefined;
207
+ }
207
208
  }
208
209
  async mkdir(path, options) {
209
210
  try {
@@ -224,68 +225,33 @@ export class LocalMachine extends BaseMachine {
224
225
  async realpath(path) {
225
226
  return await fsRealpath(this.abs(path));
226
227
  }
227
- async writeTextIfUnchanged(path, data, options) {
228
- const target = this.abs(path);
229
- const encoding = options.encoding ?? "utf8";
230
- const payload = options.lineEndings === "CRLF" ? data.replaceAll("\n", "\r\n") : data;
231
- // Sync critical section: no awaits between the staleness check and the write, so
232
- // no other tool call in this process can interleave (event-loop atomicity,
233
- // which edit/write rely on).
234
- let st;
235
- try {
236
- st = statSync(target);
237
- }
238
- catch (error) {
239
- if (!isMissingError(error))
240
- throw error;
241
- }
242
- if (options.expected === "must-not-exist") {
243
- if (st !== undefined)
244
- throw new FileExistsError();
245
- }
246
- else {
247
- if (st === undefined)
248
- throw new StaleFileError("File no longer exists. Read it again before attempting to write it.");
249
- if (!fileVersionsMatch(options.expected, fileVersionFromStats(st))) {
250
- if (options.expectedContent !== undefined) {
251
- let confirmedUnchanged = false;
252
- try {
253
- confirmedUnchanged = normalizeForCompare(readFileSync(target).toString(encoding)) === options.expectedContent;
254
- }
255
- catch {
256
- confirmedUnchanged = false;
257
- }
258
- if (!confirmedUnchanged)
259
- throw new StaleFileError();
260
- }
261
- else {
262
- throw new StaleFileError();
263
- }
264
- }
265
- }
266
- writeFileAtomicSync(target, payload, encoding);
267
- const after = statSync(target);
268
- // End of critical section.
269
- return { bytesWritten: Buffer.byteLength(payload, encoding), version: fileVersionFromStats(after) };
270
- }
271
228
  spawn(argv, env) {
272
229
  const [command, ...rest] = argv;
273
230
  if (command === undefined)
274
231
  return Promise.reject(new Error("spawn requires at least one argument"));
275
- // Cross-machine contract: `env` is a set of OVERRIDES layered over the ambient
232
+ // POSIX: the command leads its own process group (setsid), so a stop can signal the whole
233
+ // tree — the shell AND what it started. It also leaves the command without a controlling
234
+ // terminal, so `sudo`/`ssh` fail fast instead of reading the host's keyboard. Windows has no
235
+ // process groups to target; there the direct child is all we can signal.
236
+ const group = process.platform !== "win32";
237
+ // Cross-environment contract: `env` is a set of OVERRIDES layered over the ambient
276
238
  // environment, not a replacement — so PATH/proxy/etc. are preserved.
277
239
  const child = spawn(command, rest, {
278
240
  cwd: this.cwd,
279
241
  env: env ? { ...process.env, ...env } : process.env,
280
242
  stdio: ["pipe", "pipe", "pipe"],
243
+ detached: group,
281
244
  });
282
- return Promise.resolve(new LocalProcess(child));
245
+ return Promise.resolve(new LocalProcess(child, group));
283
246
  }
284
247
  }
285
248
  class LocalProcess {
286
249
  child;
287
- constructor(child) {
250
+ /** The child leads a process group whose id is its pid (see LocalEnvironment.spawn). */
251
+ group;
252
+ constructor(child, group) {
288
253
  this.child = child;
254
+ this.group = group;
289
255
  }
290
256
  get stdin() {
291
257
  return this.child.stdin;
@@ -310,7 +276,20 @@ class LocalProcess {
310
276
  });
311
277
  }
312
278
  async kill(signal = "SIGTERM") {
279
+ const pid = this.child.pid;
280
+ if (this.group && pid !== undefined) {
281
+ try {
282
+ // Negative pid = the whole group. It still reaches the children after the shell that
283
+ // led the group has exited, which is exactly the SIGKILL-after-SIGTERM case.
284
+ process.kill(-pid, signal);
285
+ return;
286
+ }
287
+ catch (error) {
288
+ if (error.code === "ESRCH")
289
+ return; // nothing left in the group
290
+ }
291
+ }
313
292
  this.child.kill(signal);
314
293
  }
315
294
  }
316
- //# sourceMappingURL=machine-local.js.map
295
+ //# sourceMappingURL=environment-local.js.map
@@ -1,26 +1,26 @@
1
- import type { ByteRange, DirEntry, Environment, Machine, FileInfo, RunCommandOptions, RunCommandResult } from "./machine.ts";
2
- import { BaseMachine } from "./machine-base.ts";
1
+ import type { ByteRange, DirEntry, OsInfo, Environment, FileInfo, RunCommandOptions, RunCommandResult } from "./environment.ts";
2
+ import { BaseEnvironment } from "./environment-base.ts";
3
3
  /**
4
- * An machine with no filesystem or process backing.
4
+ * An environment with no filesystem or process backing.
5
5
  *
6
- * Pure metadata (osEnv / path computation) returns neutral values so tools that
6
+ * Pure metadata (osInfo / path computation) returns neutral values so tools that
7
7
  * only inspect the environment don't crash; every actual I/O operation throws a
8
- * clear error. This is the default when a session is opened without an machine —
8
+ * clear error. This is the default when a session is opened without an environment —
9
9
  * a stateless server that forgets to omit a file tool fails LOUDLY instead of
10
10
  * silently reading the host disk.
11
11
  *
12
12
  * Note `realpath` resolves to `normpath` (pure computation, no I/O): the base
13
13
  * derivation's `readlink -f` attempt fails with the disabled error and falls back.
14
14
  */
15
- export declare class NullMachine extends BaseMachine {
15
+ export declare class NullEnvironment extends BaseEnvironment {
16
16
  readonly name = "null";
17
- readonly osEnv: Environment;
17
+ readonly osInfo: OsInfo;
18
18
  private disabled;
19
19
  pathClass(): "posix" | "win32";
20
20
  normpath(path: string): string;
21
21
  gethome(): string;
22
22
  getcwd(): string;
23
- withCwd(_cwd: string): Machine;
23
+ withCwd(_cwd: string): Environment;
24
24
  fileInfo(_path: string, _options?: {
25
25
  followSymlinks?: boolean;
26
26
  }): Promise<FileInfo>;
@@ -33,4 +33,4 @@ export declare class NullMachine extends BaseMachine {
33
33
  protected writeBytesRaw(_path: string, _data: Buffer): Promise<void>;
34
34
  run(_argv: readonly string[], _options?: RunCommandOptions): Promise<RunCommandResult>;
35
35
  }
36
- //# sourceMappingURL=machine-null.d.ts.map
36
+ //# sourceMappingURL=environment-null.d.ts.map
@@ -1,19 +1,19 @@
1
- import { BaseMachine } from "./machine-base.js";
1
+ import { BaseEnvironment } from "./environment-base.js";
2
2
  /**
3
- * An machine with no filesystem or process backing.
3
+ * An environment with no filesystem or process backing.
4
4
  *
5
- * Pure metadata (osEnv / path computation) returns neutral values so tools that
5
+ * Pure metadata (osInfo / path computation) returns neutral values so tools that
6
6
  * only inspect the environment don't crash; every actual I/O operation throws a
7
- * clear error. This is the default when a session is opened without an machine —
7
+ * clear error. This is the default when a session is opened without an environment —
8
8
  * a stateless server that forgets to omit a file tool fails LOUDLY instead of
9
9
  * silently reading the host disk.
10
10
  *
11
11
  * Note `realpath` resolves to `normpath` (pure computation, no I/O): the base
12
12
  * derivation's `readlink -f` attempt fails with the disabled error and falls back.
13
13
  */
14
- export class NullMachine extends BaseMachine {
14
+ export class NullEnvironment extends BaseEnvironment {
15
15
  name = "null";
16
- osEnv = {
16
+ osInfo = {
17
17
  osKind: "Linux",
18
18
  osArch: "unknown",
19
19
  osVersion: "0",
@@ -21,7 +21,7 @@ export class NullMachine extends BaseMachine {
21
21
  shellPath: "/bin/sh",
22
22
  };
23
23
  disabled(op) {
24
- return new Error(`NullMachine: filesystem disabled — operation "${op}" requires an machine, but none was configured for this session.`);
24
+ return new Error(`NullEnvironment: filesystem disabled — operation "${op}" requires an environment, but none was configured for this session.`);
25
25
  }
26
26
  // Path operations — pure computation, no I/O, safe to answer.
27
27
  pathClass() {
@@ -56,9 +56,9 @@ export class NullMachine extends BaseMachine {
56
56
  throw this.disabled("writeBytes");
57
57
  }
58
58
  // Command execution — refused. Overridden rather than left to the base derivation so the
59
- // error names this machine instead of reporting a missing process SPI.
59
+ // error names this environment instead of reporting a missing process SPI.
60
60
  async run(_argv, _options) {
61
61
  throw this.disabled("run");
62
62
  }
63
63
  }
64
- //# sourceMappingURL=machine-null.js.map
64
+ //# sourceMappingURL=environment-null.js.map