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,7 +1,9 @@
1
+ import { taskToSubagentRecord, taskToWorkflowSnapshot } from "./projections.js";
1
2
  import { randomBytes } from "node:crypto";
2
3
  import { StringDecoder } from "node:string_decoder";
3
4
  import { errorMessage } from "../../loop/errors.js";
4
5
  import { reduceHistory } from "../../store/index.js";
6
+ import { STALL_THRESHOLD_MS, startStallWatchdog } from "./stall-watchdog.js";
5
7
  import { CommandBackgroundTask } from "./command-task.js";
6
8
  import { QuestionBackgroundTask } from "./question-task.js";
7
9
  import { SwappableSink } from "./swappable-sink.js";
@@ -143,11 +145,11 @@ function textSnapshot(text, maxBytes) {
143
145
  */
144
146
  async function tailFileSnapshot(file, maxBytes) {
145
147
  try {
146
- const size = (await file.machine.fileInfo(file.path)).size;
148
+ const size = (await file.environment.fileInfo(file.path)).size;
147
149
  const windowBytes = Math.min(maxBytes, size);
148
150
  if (windowBytes === 0)
149
151
  return { content: "", sizeBytes: size, contentBytes: 0, truncated: size > 0 };
150
- const bytes = await file.machine.readBytes(file.path, { offset: size - windowBytes, length: windowBytes });
152
+ const bytes = await file.environment.readBytes(file.path, { offset: size - windowBytes, length: windowBytes });
151
153
  const aligned = bytes.subarray(utf8AlignStart(bytes));
152
154
  return {
153
155
  content: aligned.toString("utf-8"),
@@ -157,7 +159,7 @@ async function tailFileSnapshot(file, maxBytes) {
157
159
  };
158
160
  }
159
161
  catch {
160
- // The file may have been removed or its Machine may no longer be reachable. Empty is the
162
+ // The file may have been removed or its Environment may no longer be reachable. Empty is the
161
163
  // honest snapshot; the task metadata still preserves the canonical location.
162
164
  return emptyOutputSnapshot();
163
165
  }
@@ -165,62 +167,103 @@ async function tailFileSnapshot(file, maxBytes) {
165
167
  /** How often a WATCHED output file is checked for new bytes. Only ticks while someone is
166
168
  * attached with a live tap; a detached task nobody is looking at costs nothing. */
167
169
  const FOLLOW_INTERVAL_MS = 1_000;
170
+ /** Longest a WATCHED file waits between checks once its output has gone quiet. */
171
+ const FOLLOW_QUIET_MAX_INTERVAL_MS = 5_000;
168
172
  /** How long a foreground run must last before the user is offered "move to background". */
169
173
  const DETACHABLE_AFTER_MS = 2_000;
170
174
  /**
171
175
  * Tail an output file for a watcher, reading only what was appended since the last tick — so
172
176
  * a tick costs what was WRITTEN, not what the file has accumulated. A decoder spans ticks
173
177
  * because a multi-byte character can straddle two reads.
178
+ *
179
+ * A tick is not free on a remote environment: no vendor file API takes a byte range, so reading an
180
+ * increment means running `tail -c +N | base64` over there — a whole process tree per tick, even
181
+ * for the ticks that find nothing. So once the output goes quiet the follower stops reading and
182
+ * starts ASKING (one `fileInfo`, which the sandbox backends answer with a metadata call rather
183
+ * than a command), at an interval that backs off while the silence lasts. Output that is
184
+ * actually flowing is read straight away at the base interval — the probe would be pure
185
+ * overhead there, and the watcher is a human waiting to see the next line.
174
186
  */
175
- function followOutputFile(file, emit) {
187
+ function followOutputFile(file, emit, timing = {}) {
188
+ const baseIntervalMs = timing.intervalMs ?? FOLLOW_INTERVAL_MS;
189
+ const maxIntervalMs = Math.max(baseIntervalMs, timing.quietMaxIntervalMs ?? FOLLOW_QUIET_MAX_INTERVAL_MS);
176
190
  const decoder = new StringDecoder("utf8");
177
191
  let offset = 0;
178
- let inFlight;
179
192
  let stopped = false;
180
- const pump = async () => {
181
- // Serialize: a slow read must not let the next tick re-read the same bytes.
182
- if (inFlight !== undefined)
183
- return await inFlight;
184
- inFlight = (async () => {
185
- try {
186
- const bytes = await file.machine.readBytes(file.path, { offset });
187
- if (bytes.byteLength > 0) {
188
- offset += bytes.byteLength;
189
- const text = decoder.write(bytes);
190
- if (text.length > 0)
191
- emit(text);
193
+ /** Set by the last pass that came back empty-handed: the next one probes before reading. */
194
+ let quiet = false;
195
+ let intervalMs = baseIntervalMs;
196
+ let timer;
197
+ /** Nothing new: wait longer before looking again, up to the ceiling. */
198
+ const backOff = () => {
199
+ quiet = true;
200
+ intervalMs = Math.min(intervalMs * 2, maxIntervalMs);
201
+ };
202
+ const pass = async (probe) => {
203
+ try {
204
+ if (probe) {
205
+ // Not created yet, or no bigger than what we have already consumed — either way there
206
+ // is nothing to read, and the expensive part never runs.
207
+ const { size } = await file.environment.fileInfo(file.path);
208
+ if (size <= offset) {
209
+ backOff();
210
+ return;
192
211
  }
193
212
  }
194
- catch {
195
- // Not created yet (the redirect is part of the command) or gone after a kill. The
196
- // live tap is best-effort; the command's own result is what settles the task.
213
+ const bytes = await file.environment.readBytes(file.path, { offset });
214
+ if (bytes.byteLength === 0) {
215
+ backOff();
216
+ return;
197
217
  }
198
- })();
199
- try {
200
- await inFlight;
218
+ offset += bytes.byteLength;
219
+ quiet = false;
220
+ intervalMs = baseIntervalMs;
221
+ const text = decoder.write(bytes);
222
+ if (text.length > 0)
223
+ emit(text);
201
224
  }
202
- finally {
203
- inFlight = undefined;
225
+ catch {
226
+ // Not created yet (the redirect is part of the command) or gone after a kill. The
227
+ // live tap is best-effort; the command's own result is what settles the task.
228
+ backOff();
204
229
  }
205
230
  };
206
- const timer = setInterval(() => void pump(), FOLLOW_INTERVAL_MS);
207
- if (typeof timer.unref === "function")
208
- timer.unref();
231
+ // One pass at a time, in order: two overlapping reads would take the same bytes twice, and
232
+ // the drain must see everything the passes before it left. `pass` never rejects.
233
+ let queue = Promise.resolve();
234
+ const pump = (probe) => {
235
+ queue = queue.then(() => pass(probe));
236
+ return queue;
237
+ };
238
+ const schedule = () => {
239
+ if (stopped)
240
+ return;
241
+ timer = setTimeout(() => {
242
+ void pump(quiet).finally(schedule);
243
+ }, intervalMs);
244
+ if (typeof timer.unref === "function")
245
+ timer.unref();
246
+ };
247
+ schedule();
248
+ const halt = () => {
249
+ stopped = true;
250
+ if (timer !== undefined)
251
+ clearTimeout(timer);
252
+ timer = undefined;
253
+ };
209
254
  return {
210
255
  async drain() {
211
256
  if (stopped)
212
257
  return;
213
- stopped = true;
214
- clearInterval(timer);
215
- await pump();
258
+ halt();
259
+ // Read outright: the command has ended, so a probe would only add a round trip before
260
+ // the read that has to happen anyway.
261
+ await pump(false);
216
262
  const tail = decoder.end();
217
263
  if (tail.length > 0)
218
264
  emit(tail);
219
265
  },
220
- stop() {
221
- stopped = true;
222
- clearInterval(timer);
223
- },
266
+ stop: halt,
224
267
  };
225
268
  }
226
269
  export class BackgroundManager {
@@ -248,9 +291,13 @@ export class BackgroundManager {
248
291
  unsubscribeConsumption;
249
292
  /** Serialize the whole task store, including the KV backend's shared task index. */
250
293
  persistenceChain = Promise.resolve();
294
+ stallDetection;
295
+ outputFollow;
251
296
  constructor(options = {}) {
252
297
  this.maxRunningTasks = options.maxRunningTasks;
253
298
  this.now = options.now ?? Date.now;
299
+ this.stallDetection = options.stallDetection ?? {};
300
+ this.outputFollow = options.outputFollow ?? {};
254
301
  }
255
302
  attach(runtime) {
256
303
  this.steer = runtime.steer;
@@ -358,7 +405,7 @@ export class BackgroundManager {
358
405
  async runCommandAttached(start, command, description, options) {
359
406
  const task = new CommandBackgroundTask(start, command, description, {
360
407
  logPath: options.logPath,
361
- machine: options.machine,
408
+ environment: options.environment,
362
409
  parentAddress: options.parentAddress,
363
410
  toolCallId: options.toolCallId,
364
411
  });
@@ -369,6 +416,7 @@ export class BackgroundManager {
369
416
  onLive: options.onLive,
370
417
  onDetachable: options.onDetachable,
371
418
  getExitCode: () => task.exitCode,
419
+ stopUnconfirmed: () => task.stopUnconfirmed,
372
420
  });
373
421
  }
374
422
  /**
@@ -403,7 +451,7 @@ export class BackgroundManager {
403
451
  ? followOutputFile(task.outputLocation, (chunk) => {
404
452
  if (!detached)
405
453
  opts.onLive?.(chunk);
406
- })
454
+ }, this.outputFollow)
407
455
  : undefined;
408
456
  sink.setDownstream({
409
457
  settle: async (settlement) => {
@@ -413,7 +461,7 @@ export class BackgroundManager {
413
461
  return true;
414
462
  },
415
463
  });
416
- // Aborting IS the whole stop protocol: a command task forwards the signal to `machine.run`,
464
+ // Aborting IS the whole stop protocol: a command task forwards the signal to `environment.run`,
417
465
  // where SIGTERM → grace → SIGKILL escalation lives (the layer that can actually kill).
418
466
  const kill = (why) => {
419
467
  if (cause === undefined)
@@ -477,10 +525,15 @@ export class BackgroundManager {
477
525
  return { kind: "detached", taskId: outcome.taskId };
478
526
  }
479
527
  let status = outcome.settlement.status === "paused" ? "failed" : outcome.settlement.status;
528
+ // A stop the backend could not confirm settles the TASK as failed; to the foreground caller
529
+ // it is still the timeout or interrupt it asked for, flagged as possibly still running.
530
+ const stillRunning = cause !== undefined && opts.stopUnconfirmed?.() === true;
531
+ if (stillRunning)
532
+ status = "killed";
480
533
  // The task reports a plain "killed" on abort; distinguish a foreground timeout.
481
534
  if (status === "killed" && cause === "timeout")
482
535
  status = "timed_out";
483
- return { kind: "settled", status, exitCode: opts.getExitCode?.() ?? null };
536
+ return { kind: "settled", status, exitCode: opts.getExitCode?.() ?? null, ...(stillRunning ? { stillRunning: true } : {}) };
484
537
  }
485
538
  finally {
486
539
  follow?.stop();
@@ -521,6 +574,7 @@ export class BackgroundManager {
521
574
  });
522
575
  this.emitStarted(this.toInfo(entry));
523
576
  void this.persistLive(entry);
577
+ this.watchForStall(entry);
524
578
  return taskId;
525
579
  }
526
580
  registerTask(task) {
@@ -558,8 +612,45 @@ export class BackgroundManager {
558
612
  });
559
613
  });
560
614
  this.emitStarted(this.toInfo(entry));
615
+ this.watchForStall(entry);
561
616
  return taskId;
562
617
  }
618
+ /**
619
+ * Background commands only: a foreground one has a timeout and a watching user, and other
620
+ * kinds have no terminal prompt to get stuck on. Started once the task is in the background —
621
+ * a detached run starts watching at the moment it detaches.
622
+ */
623
+ watchForStall(entry) {
624
+ const location = entry.task.outputLocation;
625
+ if (entry.task.kind !== "process" || location?.kind !== "file" || TERMINAL_STATUSES.has(entry.status))
626
+ return;
627
+ entry.stopStallWatch = startStallWatchdog(location, (tail) => this.steerStalled(entry, tail), this.stallDetection);
628
+ }
629
+ /**
630
+ * Tell the model a background command looks stuck on a prompt. Not a settle — the task is
631
+ * still running — so it goes out as a plain notice rather than a `background_done`, which the
632
+ * settle-notification ledger and the UI would read as the task having ended.
633
+ */
634
+ steerStalled(entry, tail) {
635
+ if (this.steer === undefined || TERMINAL_STATUSES.has(entry.status))
636
+ return;
637
+ const quietSeconds = Math.round((this.stallDetection.thresholdMs ?? STALL_THRESHOLD_MS) / 1000);
638
+ const body = [
639
+ "[system: automated event, NOT a message from the user. The output below is the command's, not the user's.]",
640
+ `Background task ${entry.taskId} ("${entry.task.description}") appears to be waiting for interactive input: its output has not changed for ${String(quietSeconds)}s and the last line looks like a prompt.`,
641
+ "",
642
+ "Last output:",
643
+ tail,
644
+ "",
645
+ "Commands get no terminal and an empty stdin, so nothing can answer the prompt. Stop this task with BackgroundStop and re-run the command with its input supplied up front (e.g. `printf 'y\\n' | command`) or a non-interactive flag if one exists.",
646
+ ].join("\n");
647
+ this.steer.steer(body, {
648
+ kind: "extension",
649
+ extensionId: "background",
650
+ metadata: { taskId: entry.taskId, event: "waiting_for_input" },
651
+ channel: "follow_up",
652
+ });
653
+ }
563
654
  /** The durable projection of a task. The output's address comes from the task itself and is
564
655
  * never reconstructed from an id. */
565
656
  toPersisted(entry) {
@@ -604,6 +695,7 @@ export class BackgroundManager {
604
695
  const valid = (task.kind === "process" && kind === "file") ||
605
696
  (task.kind === "agent" && kind === "conversation") ||
606
697
  (task.kind === "workflow" && kind === "workflow-run") ||
698
+ (task.kind === "code" && kind === "file") ||
607
699
  (task.kind === "question" && kind === undefined);
608
700
  if (!valid) {
609
701
  throw new Error(`Background ${task.kind} tasks require their canonical durable output location.`);
@@ -641,6 +733,59 @@ export class BackgroundManager {
641
733
  }
642
734
  return undefined;
643
735
  }
736
+ /**
737
+ * Past BACKGROUND workflow runs, newest first. A FOREGROUND workflow is a plain `Workflow`
738
+ * tool call — its record is the conversation plus its journal shard — so it is not a task and
739
+ * is not listed here (its shard stays resumable by runId).
740
+ */
741
+ listWorkflows() {
742
+ const runs = [];
743
+ for (const info of this.list(false)) {
744
+ const snap = taskToWorkflowSnapshot(info);
745
+ if (snap !== undefined)
746
+ runs.push(snap);
747
+ }
748
+ runs.sort((a, b) => (a.startedAt < b.startedAt ? 1 : a.startedAt > b.startedAt ? -1 : 0));
749
+ return runs;
750
+ }
751
+ /** One background workflow run by runId, or undefined if this ledger has never seen it. */
752
+ getWorkflow(runId) {
753
+ return this.listWorkflows().find((run) => run.runId === runId);
754
+ }
755
+ /**
756
+ * The background subagents in this ledger (live + reconciled ghosts). Foreground subagents are
757
+ * plain `Agent` tool calls, so they are not here — same reason as `listWorkflows`.
758
+ */
759
+ listSubagents() {
760
+ const records = [];
761
+ for (const info of this.list(false)) {
762
+ const record = taskToSubagentRecord(info);
763
+ if (record !== undefined)
764
+ records.push(record);
765
+ }
766
+ return records;
767
+ }
768
+ /**
769
+ * Reconcile orphaned work and report it as subagents: `reconcile()` writes the terminal status
770
+ * back, and each reclassified subagent gets a warning on the session's sink so a host does not
771
+ * have to poll for it. Returns the lost subagents (resume any with `Agent(resume="<id>", …)`).
772
+ */
773
+ async reconcileSubagents() {
774
+ const lost = [];
775
+ for (const info of await this.reconcile()) {
776
+ const record = taskToSubagentRecord(info);
777
+ if (record === undefined)
778
+ continue;
779
+ lost.push(record);
780
+ await this.events?.emit({
781
+ type: "warning",
782
+ address: "main",
783
+ sessionId: this.sessionId,
784
+ message: `Background subagent "${record.agentId}" (${record.type}) was running when the previous process exited; marked lost. Resume with Agent(resume="${record.agentId}", ...).`,
785
+ });
786
+ }
787
+ return lost;
788
+ }
644
789
  list(activeOnly = true, limit) {
645
790
  const result = [];
646
791
  for (const entry of this.tasks.values()) {
@@ -705,7 +850,7 @@ export class BackgroundManager {
705
850
  return emptyOutputSnapshot();
706
851
  try {
707
852
  const records = [];
708
- for await (const record of store.readRecords({ address }))
853
+ for await (const record of store.readRecords({ address, fromCheckpoint: true }))
709
854
  records.push(record);
710
855
  const { messages } = reduceHistory(records);
711
856
  // The agent's answer is the last thing it said. Tool calls and their results are steps
@@ -759,7 +904,7 @@ export class BackgroundManager {
759
904
  // A question's answer is persisted on the task record itself, so it survives the process.
760
905
  if (ghost.kind === "question" && ghost.answer !== undefined)
761
906
  return textSnapshot(ghost.answer, limit);
762
- // A process ghost knows its output path but not the machine it lived on — the Machine is a
907
+ // A process ghost knows its output path but not the environment it lived on — the Environment is a
763
908
  // live handle, not a serialisable one. The tool surfaces `output_path` for a `Read`.
764
909
  return emptyOutputSnapshot();
765
910
  }
@@ -783,14 +928,14 @@ export class BackgroundManager {
783
928
  return { content: "", nextCursor: from, followable: false };
784
929
  const file = location;
785
930
  try {
786
- const bytes = await file.machine.readBytes(file.path, { offset: from, length: Math.max(0, Math.trunc(maxBytes)) });
931
+ const bytes = await file.environment.readBytes(file.path, { offset: from, length: Math.max(0, Math.trunc(maxBytes)) });
787
932
  // Leave a trailing partial sequence behind and advance the cursor only past what was
788
933
  // decodable: the next tick re-reads those bytes and completes the character.
789
934
  const whole = bytes.subarray(0, utf8AlignEnd(bytes));
790
935
  return { content: whole.toString("utf-8"), nextCursor: from + whole.byteLength, followable: true };
791
936
  }
792
937
  catch {
793
- // Gone after cleanup or the Machine is temporarily unreachable.
938
+ // Gone after cleanup or the Environment is temporarily unreachable.
794
939
  return { content: "", nextCursor: from, followable: true };
795
940
  }
796
941
  }
@@ -835,15 +980,25 @@ export class BackgroundManager {
835
980
  const results = await Promise.all(ids.map((id) => this.stop(id, reason)));
836
981
  return results.filter((info) => info !== undefined);
837
982
  }
838
- async wait(taskId, timeoutMs = 30_000) {
983
+ /**
984
+ * Settle when the task reaches a terminal status, the timeout elapses, or `signal` aborts —
985
+ * whichever comes first. Returns the task's status either way; the caller compares it against
986
+ * the terminal set to tell "it finished" from "I stopped waiting".
987
+ *
988
+ * `signal` matters because the timeout can be up to an hour: without it a blocking waiter
989
+ * outlives the turn that started it, and the loop's post-abort grace window has to shoot the
990
+ * tool down with a synthetic error instead of letting it return cleanly.
991
+ */
992
+ async wait(taskId, timeoutMs = 30_000, signal) {
839
993
  const entry = this.tasks.get(taskId);
840
994
  if (!entry)
841
995
  return undefined;
842
- if (TERMINAL_STATUSES.has(entry.status)) {
996
+ if (TERMINAL_STATUSES.has(entry.status) || signal?.aborted === true) {
843
997
  return this.toInfo(entry);
844
998
  }
845
999
  let terminalWaiter;
846
1000
  let timeout;
1001
+ let onAbort;
847
1002
  try {
848
1003
  await Promise.race([
849
1004
  new Promise((resolve) => {
@@ -853,11 +1008,19 @@ export class BackgroundManager {
853
1008
  new Promise((resolve) => {
854
1009
  timeout = setTimeout(resolve, timeoutMs);
855
1010
  }),
1011
+ new Promise((resolve) => {
1012
+ if (signal === undefined)
1013
+ return; // never settles — leaves the race to the other two
1014
+ onAbort = resolve;
1015
+ signal.addEventListener("abort", onAbort, { once: true });
1016
+ }),
856
1017
  ]);
857
1018
  }
858
1019
  finally {
859
1020
  if (timeout !== undefined)
860
1021
  clearTimeout(timeout);
1022
+ if (onAbort !== undefined)
1023
+ signal?.removeEventListener("abort", onAbort);
861
1024
  if (terminalWaiter !== undefined) {
862
1025
  const index = entry.waiters.indexOf(terminalWaiter);
863
1026
  if (index !== -1)
@@ -867,6 +1030,8 @@ export class BackgroundManager {
867
1030
  return this.toInfo(entry);
868
1031
  }
869
1032
  async settleTask(entry, settlement) {
1033
+ entry.stopStallWatch?.();
1034
+ entry.stopStallWatch = undefined;
870
1035
  if (TERMINAL_STATUSES.has(entry.status)) {
871
1036
  if (entry.status === "killed" && settlement.status === "killed") {
872
1037
  entry.endedAt = Math.max(this.now(), (entry.endedAt ?? 0) + 1);
@@ -2,7 +2,7 @@ import { type BackgroundTaskPersistence, type PersistedTask } from "./persist.ts
2
2
  /**
3
3
  * Disk-directory task store: `<sessionDir>/tasks/<id>/state.json`, one directory per
4
4
  * task. Co-located under the SessionStore's own home (next to `agents/`
5
- * and `blobs/`), so it inherits the session's durability and stays off the Machine
5
+ * and `blobs/`), so it inherits the session's durability and stays off the Environment
6
6
  * sandbox. Writes are atomic (temp + rename) so a crash mid-write never leaves a torn file.
7
7
  */
8
8
  export declare class DiskBackgroundTaskPersistence implements BackgroundTaskPersistence {
@@ -7,7 +7,7 @@ const ID_RE = /^[A-Za-z0-9_-]+$/;
7
7
  /**
8
8
  * Disk-directory task store: `<sessionDir>/tasks/<id>/state.json`, one directory per
9
9
  * task. Co-located under the SessionStore's own home (next to `agents/`
10
- * and `blobs/`), so it inherits the session's durability and stays off the Machine
10
+ * and `blobs/`), so it inherits the session's durability and stays off the Environment
11
11
  * sandbox. Writes are atomic (temp + rename) so a crash mid-write never leaves a torn file.
12
12
  */
13
13
  export class DiskBackgroundTaskPersistence {
@@ -3,7 +3,7 @@ import { TERMINAL_STATUSES } from "./task.js";
3
3
  export function isPersistedTaskTerminal(status) {
4
4
  return TERMINAL_STATUSES.has(status);
5
5
  }
6
- const TASK_KINDS = new Set(["process", "agent", "question", "workflow"]);
6
+ const TASK_KINDS = new Set(["process", "agent", "question", "workflow", "code"]);
7
7
  const STATUSES = new Set([
8
8
  "running",
9
9
  "completed",
@@ -42,6 +42,8 @@ export function isValidPersistedTask(value) {
42
42
  return false;
43
43
  if (o["kind"] === "process" && o["outputRef"]?.kind !== "file")
44
44
  return false;
45
+ if (o["kind"] === "code" && o["outputRef"]?.kind !== "file")
46
+ return false;
45
47
  if (o["kind"] === "agent" && o["outputRef"]?.kind !== "conversation")
46
48
  return false;
47
49
  if (o["kind"] === "workflow" && o["outputRef"]?.kind !== "workflow-run")
@@ -70,7 +72,7 @@ function isValidOutputRef(value) {
70
72
  // ── SessionStore KV backend ──────────────────────────────────────────────────
71
73
  //
72
74
  // Works on every SessionStore backend (disk/pg/redis/memory): status lives in KV state,
73
- // mirroring how cron persists its registry (`cron/persist.ts`). Kept off the Machine
75
+ // mirroring how cron persists its registry (`cron/persist.ts`). Kept off the Environment
74
76
  // for the same reason cron is — bookkeeping must be readable with no workspace attached and
75
77
  // must sit outside the space agent-run code can touch. One index key + one key per task
76
78
  // (tasks carry a large output tail elsewhere, so unlike cron they are not one whole blob).
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Background task → the two discovery views over it.
3
+ *
4
+ * A background subagent and a background workflow are both rows in the same task ledger; what
5
+ * tells them apart is `kind` plus the fields that kind fills in. These projections live next to
6
+ * the ledger rather than in the session facade, so a caller reading the ledger by any route sees
7
+ * the same rows.
8
+ */
9
+ import type { BackgroundTaskInfo } from "./task.ts";
10
+ import type { SubagentRecord } from "../../agent/subagent.ts";
11
+ import type { WorkflowSnapshot } from "../../agent/workflow/snapshot.ts";
12
+ /** The subagent view of a task, or undefined when the task is not a backgrounded subagent. */
13
+ export declare function taskToSubagentRecord(info: BackgroundTaskInfo): SubagentRecord | undefined;
14
+ /** The workflow view of a task, or undefined when the task is not a backgrounded workflow run. */
15
+ export declare function taskToWorkflowSnapshot(info: BackgroundTaskInfo): WorkflowSnapshot | undefined;
16
+ //# sourceMappingURL=projections.d.ts.map
@@ -0,0 +1,86 @@
1
+ const SUBAGENT_STATUS_SET = new Set([
2
+ "running",
3
+ "completed",
4
+ "error",
5
+ "cancelled",
6
+ "paused",
7
+ "lost",
8
+ ]);
9
+ const WORKFLOW_STATUS_SET = new Set([
10
+ "running",
11
+ "completed",
12
+ "failed",
13
+ "aborted",
14
+ ]);
15
+ /** Map a background task status to the finer subagent status, preferring the run's own
16
+ * `agentStatus` (e.g. "paused") when it reported one. */
17
+ function subagentStatusFromTask(status, agentStatus) {
18
+ if (agentStatus !== undefined && SUBAGENT_STATUS_SET.has(agentStatus))
19
+ return agentStatus;
20
+ switch (status) {
21
+ case "completed":
22
+ return "completed";
23
+ case "killed":
24
+ return "cancelled";
25
+ case "paused":
26
+ return "paused";
27
+ case "lost":
28
+ return "lost";
29
+ case "running":
30
+ return "running";
31
+ default:
32
+ return "error"; // failed / timed_out
33
+ }
34
+ }
35
+ /** Map a background task status to the workflow discovery status, preferring the run's own
36
+ * `runStatus` (e.g. "failed") when it reported one. */
37
+ function workflowStatusFromTask(status, runStatus) {
38
+ if (runStatus !== undefined && WORKFLOW_STATUS_SET.has(runStatus))
39
+ return runStatus;
40
+ switch (status) {
41
+ case "completed":
42
+ return "completed";
43
+ case "killed":
44
+ case "lost":
45
+ return "aborted";
46
+ case "running":
47
+ return "running";
48
+ default:
49
+ return "failed"; // failed / timed_out
50
+ }
51
+ }
52
+ /** The subagent view of a task, or undefined when the task is not a backgrounded subagent. */
53
+ export function taskToSubagentRecord(info) {
54
+ if (info.kind !== "agent" || info.agentId === undefined)
55
+ return undefined;
56
+ if (info.outputRef?.kind !== "conversation")
57
+ return undefined;
58
+ const address = info.outputRef.address;
59
+ return {
60
+ agentId: info.agentId,
61
+ type: info.subagentType ?? "unknown",
62
+ address,
63
+ description: info.description,
64
+ background: true,
65
+ taskId: info.taskId,
66
+ createdAt: info.startedAt,
67
+ status: subagentStatusFromTask(info.status, info.agentStatus),
68
+ updatedAt: info.endedAt ?? info.startedAt,
69
+ };
70
+ }
71
+ /** The workflow view of a task, or undefined when the task is not a backgrounded workflow run. */
72
+ export function taskToWorkflowSnapshot(info) {
73
+ if (info.kind !== "workflow" || info.runId === undefined)
74
+ return undefined;
75
+ return {
76
+ runId: info.runId,
77
+ workflowName: info.workflowName ?? "unknown",
78
+ description: info.description,
79
+ status: workflowStatusFromTask(info.status, info.runStatus),
80
+ background: true,
81
+ taskId: info.taskId,
82
+ startedAt: new Date(info.startedAt).toISOString(),
83
+ endedAt: info.endedAt !== null ? new Date(info.endedAt).toISOString() : undefined,
84
+ };
85
+ }
86
+ //# sourceMappingURL=projections.js.map
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Noticing a background command that is stuck on an interactive prompt.
3
+ *
4
+ * Commands get no terminal and an empty stdin, so a `(y/n)` or `Press Enter` can never be
5
+ * answered — the task just sits there until someone stops it, and the model, which is not
6
+ * watching the log, has no reason to look. This watches for exactly that shape: output that
7
+ * stopped growing AND a last line that reads as a prompt. A command that is merely slow (a long
8
+ * build, `git log -S`) goes quiet too, but its last line is not a question, so it stays silent.
9
+ *
10
+ * Mirrors Claude Code's background-shell watchdog (same threshold, same patterns, plus npx's
11
+ * install prompt).
12
+ */
13
+ import type { Environment } from "../../tool/environment.ts";
14
+ /**
15
+ * How often a watched log is checked for growth.
16
+ *
17
+ * A background task is otherwise notification-driven — nobody reads its output until it ends or
18
+ * is asked for — so this is the one recurring cost it carries, on every running task, for the
19
+ * whole of its life. A check is one `fileInfo`: a metadata call on the backends that have one,
20
+ * but still a `stat(1)` command on those that do not. Sampling at a third of the threshold keeps
21
+ * that rare while still noticing a stuck prompt within {@link STALL_THRESHOLD_MS} of it
22
+ * appearing, at worst one interval later.
23
+ */
24
+ export declare const STALL_CHECK_INTERVAL_MS = 15000;
25
+ /** How long output must stay unchanged before the tail is inspected. */
26
+ export declare const STALL_THRESHOLD_MS = 45000;
27
+ export declare function looksLikePrompt(tail: string): boolean;
28
+ export interface StallWatchdogTiming {
29
+ readonly checkIntervalMs?: number;
30
+ readonly thresholdMs?: number;
31
+ }
32
+ /**
33
+ * Watch a task's log file; call `onStall` once, with the log's tail, when it looks stuck on a
34
+ * prompt. Returns the function that stops watching. Every check costs one `fileInfo`; the tail
35
+ * is read only after the threshold passes, and only once per quiet period.
36
+ */
37
+ export declare function startStallWatchdog(file: {
38
+ readonly environment: Environment;
39
+ readonly path: string;
40
+ }, onStall: (tail: string) => void, timing?: StallWatchdogTiming): () => void;
41
+ //# sourceMappingURL=stall-watchdog.d.ts.map