@capybara-hq/kernel 0.1.0-rc.2 → 0.1.0-rc.4

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 (312) hide show
  1. package/dist/admin/admin.controller.d.ts +9 -4
  2. package/dist/admin/admin.controller.js +13 -4
  3. package/dist/admin/extensions.controller.d.ts +8 -1
  4. package/dist/admin/extensions.controller.js +22 -2
  5. package/dist/agents/agent-lookup.d.ts +3 -0
  6. package/dist/agents/agent-lookup.js +20 -2
  7. package/dist/agents/agent-profile.service.d.ts +29 -0
  8. package/dist/agents/agent-profile.service.js +117 -0
  9. package/dist/agents/agents.controller.d.ts +93 -3
  10. package/dist/agents/agents.controller.js +114 -4
  11. package/dist/agents/agents.module.js +6 -2
  12. package/dist/agents/agents.service.d.ts +13 -5
  13. package/dist/agents/agents.service.js +49 -13
  14. package/dist/agents/definition.d.ts +35 -8
  15. package/dist/agents/definition.js +203 -17
  16. package/dist/agents/instruction-files.d.ts +60 -0
  17. package/dist/agents/instruction-files.js +111 -0
  18. package/dist/agents/models.controller.d.ts +9 -3
  19. package/dist/agents/models.controller.js +19 -4
  20. package/dist/agents/profile.d.ts +96 -0
  21. package/dist/agents/profile.js +51 -0
  22. package/dist/agents/readiness.controller.d.ts +26 -0
  23. package/dist/agents/readiness.controller.js +56 -0
  24. package/dist/agents/templates.js +20 -5
  25. package/dist/background/background.controller.d.ts +38 -0
  26. package/dist/background/background.controller.js +87 -0
  27. package/dist/background/background.module.d.ts +10 -0
  28. package/dist/background/background.module.js +32 -0
  29. package/dist/background/finish.d.ts +43 -0
  30. package/dist/background/finish.js +94 -0
  31. package/dist/background/launch-lock.d.ts +14 -0
  32. package/dist/background/launch-lock.js +39 -0
  33. package/dist/background/launch.d.ts +36 -0
  34. package/dist/background/launch.js +70 -0
  35. package/dist/background/poll.job.d.ts +53 -0
  36. package/dist/background/poll.job.js +182 -0
  37. package/dist/background/render.d.ts +23 -0
  38. package/dist/background/render.js +48 -0
  39. package/dist/background/session.d.ts +37 -0
  40. package/dist/background/session.js +66 -0
  41. package/dist/background/status.d.ts +35 -0
  42. package/dist/background/status.js +57 -0
  43. package/dist/background/stop.d.ts +62 -0
  44. package/dist/background/stop.js +225 -0
  45. package/dist/background/store.d.ts +150 -0
  46. package/dist/background/store.js +351 -0
  47. package/dist/background/store.module.d.ts +6 -0
  48. package/dist/background/store.module.js +22 -0
  49. package/dist/background/tasks.service.d.ts +67 -0
  50. package/dist/background/tasks.service.js +186 -0
  51. package/dist/background/wake-rules.d.ts +57 -0
  52. package/dist/background/wake-rules.js +83 -0
  53. package/dist/background/wake.d.ts +28 -0
  54. package/dist/background/wake.js +57 -0
  55. package/dist/catalog/catalog-content.js +4 -1
  56. package/dist/catalog/claude/agents.js +15 -10
  57. package/dist/catalog/marketplaces.service.d.ts +1 -1
  58. package/dist/catalog/plugin-import.js +1 -1
  59. package/dist/catalog/plugin-upgrade.js +1 -1
  60. package/dist/channels/cards.d.ts +8 -2
  61. package/dist/channels/cards.js +17 -9
  62. package/dist/channels/connections.service.d.ts +16 -1
  63. package/dist/channels/connections.service.js +38 -4
  64. package/dist/channels/threads.d.ts +5 -0
  65. package/dist/channels/threads.js +8 -0
  66. package/dist/config/schema.d.ts +18 -0
  67. package/dist/config/schema.js +104 -2
  68. package/dist/conversations/access.js +2 -0
  69. package/dist/conversations/artifacts.d.ts +1 -1
  70. package/dist/conversations/artifacts.js +1 -1
  71. package/dist/conversations/attachments.service.d.ts +30 -0
  72. package/dist/conversations/attachments.service.js +130 -5
  73. package/dist/conversations/conversations.controller.d.ts +36 -5
  74. package/dist/conversations/conversations.controller.js +62 -12
  75. package/dist/conversations/conversations.module.js +3 -0
  76. package/dist/conversations/conversations.service.d.ts +44 -2
  77. package/dist/conversations/conversations.service.js +140 -12
  78. package/dist/conversations/event-log.d.ts +12 -1
  79. package/dist/conversations/event-log.js +29 -1
  80. package/dist/conversations/events.d.ts +81 -3
  81. package/dist/conversations/events.js +83 -16
  82. package/dist/conversations/queue.d.ts +3 -1
  83. package/dist/conversations/queue.js +13 -2
  84. package/dist/conversations/queue.service.js +3 -1
  85. package/dist/conversations/titles.d.ts +7 -0
  86. package/dist/conversations/titles.js +15 -0
  87. package/dist/db/kernel-schema.d.ts +60 -4
  88. package/dist/db/pool.d.ts +5 -0
  89. package/dist/db/pool.js +3 -0
  90. package/dist/errors.d.ts +8 -0
  91. package/dist/errors.js +8 -0
  92. package/dist/evals/recorded-tools.d.ts +27 -1
  93. package/dist/evals/recorded-tools.js +85 -10
  94. package/dist/evals/run-replay.d.ts +10 -2
  95. package/dist/evals/run-replay.js +49 -12
  96. package/dist/evals/step-replay.js +12 -6
  97. package/dist/evals/trajectory.d.ts +2 -2
  98. package/dist/evals/trajectory.js +1 -1
  99. package/dist/extensions/admin-ops.js +2 -0
  100. package/dist/extensions/admin-view.d.ts +3 -1
  101. package/dist/extensions/admin-view.js +10 -2
  102. package/dist/extensions/blobs.js +1 -0
  103. package/dist/extensions/config-issues.d.ts +13 -1
  104. package/dist/extensions/config-issues.js +22 -5
  105. package/dist/extensions/config-json-schema.d.ts +43 -7
  106. package/dist/extensions/config-json-schema.js +124 -58
  107. package/dist/extensions/deployment-config-store.d.ts +6 -0
  108. package/dist/extensions/deployment-config.d.ts +50 -3
  109. package/dist/extensions/deployment-config.js +125 -28
  110. package/dist/extensions/display-name.d.ts +22 -0
  111. package/dist/extensions/display-name.js +77 -0
  112. package/dist/extensions/extensions.module.js +6 -0
  113. package/dist/extensions/host.d.ts +26 -1
  114. package/dist/extensions/host.js +82 -9
  115. package/dist/extensions/org-config.controller.d.ts +11 -3
  116. package/dist/extensions/org-config.controller.js +14 -6
  117. package/dist/extensions/org-config.d.ts +6 -0
  118. package/dist/extensions/org-config.js +12 -13
  119. package/dist/extensions/package.d.ts +14 -1
  120. package/dist/extensions/package.js +51 -2
  121. package/dist/extensions/permission-view.d.ts +3 -0
  122. package/dist/extensions/point-defaults.controller.d.ts +34 -0
  123. package/dist/extensions/point-defaults.controller.js +71 -0
  124. package/dist/extensions/point-defaults.d.ts +64 -0
  125. package/dist/extensions/point-defaults.js +206 -0
  126. package/dist/extensions/registry.d.ts +1 -1
  127. package/dist/extensions/registry.js +2 -0
  128. package/dist/http/api.module.js +8 -0
  129. package/dist/http/nest-logger.d.ts +6 -5
  130. package/dist/http/nest-logger.js +24 -10
  131. package/dist/identity/auth.controller.js +9 -5
  132. package/dist/identity/cookies.d.ts +20 -5
  133. package/dist/identity/cookies.js +44 -6
  134. package/dist/identity/me.controller.d.ts +5 -1
  135. package/dist/identity/me.controller.js +12 -3
  136. package/dist/identity/sessions.d.ts +12 -0
  137. package/dist/identity/sessions.js +45 -0
  138. package/dist/identity/settings.js +1 -1
  139. package/dist/index.d.ts +1 -1
  140. package/dist/infra/config/kernel-config.service.js +6 -0
  141. package/dist/infra/database/database.module.js +1 -0
  142. package/dist/infra/events/kernel-events.d.ts +8 -0
  143. package/dist/infra/lifecycle/process-guards.js +4 -0
  144. package/dist/infra/logging/logging.module.d.ts +4 -2
  145. package/dist/infra/logging/logging.module.js +24 -6
  146. package/dist/infra/queue/redis-connection.d.ts +6 -0
  147. package/dist/infra/queue/redis-connection.js +7 -0
  148. package/dist/infra/redis/redis.module.js +6 -2
  149. package/dist/infra/tokens.d.ts +6 -1
  150. package/dist/infra/tokens.js +6 -1
  151. package/dist/lifecycle/kernel-lifecycle.js +5 -0
  152. package/dist/log.d.ts +13 -1
  153. package/dist/log.js +93 -17
  154. package/dist/models/purposes.d.ts +23 -0
  155. package/dist/models/purposes.js +31 -10
  156. package/dist/orgs/offboarding.d.ts +3 -1
  157. package/dist/orgs/offboarding.js +26 -16
  158. package/dist/orgs/settings.service.d.ts +7 -2
  159. package/dist/orgs/settings.service.js +15 -4
  160. package/dist/roles/worker.module.js +6 -0
  161. package/dist/runtime/context/build.d.ts +15 -13
  162. package/dist/runtime/context/build.js +45 -27
  163. package/dist/runtime/context/claude-tools.d.ts +3 -1
  164. package/dist/runtime/context/claude-tools.js +12 -12
  165. package/dist/runtime/context/compaction.js +4 -0
  166. package/dist/runtime/context/legacy-text.d.ts +22 -0
  167. package/dist/runtime/context/legacy-text.js +37 -0
  168. package/dist/runtime/context/skills.d.ts +29 -11
  169. package/dist/runtime/context/skills.js +37 -30
  170. package/dist/runtime/langgraph-loop.js +3 -2
  171. package/dist/runtime/loop.d.ts +5 -4
  172. package/dist/runtime/maintenance.d.ts +4 -2
  173. package/dist/runtime/maintenance.js +17 -5
  174. package/dist/runtime/model-call.d.ts +17 -1
  175. package/dist/runtime/model-call.js +4 -3
  176. package/dist/runtime/providers.d.ts +6 -0
  177. package/dist/runtime/providers.js +8 -0
  178. package/dist/runtime/run-finish.d.ts +1 -1
  179. package/dist/runtime/run-queue.d.ts +28 -5
  180. package/dist/runtime/run-queue.js +131 -35
  181. package/dist/runtime/run-worker.d.ts +2 -2
  182. package/dist/runtime/run-worker.js +20 -7
  183. package/dist/runtime/runtime.module.js +8 -3
  184. package/dist/runtime/step-log.d.ts +6 -0
  185. package/dist/runtime/step-log.js +16 -2
  186. package/dist/runtime/subagents/definition.d.ts +1 -6
  187. package/dist/runtime/subagents/definition.js +14 -13
  188. package/dist/runtime/subagents/dispatch.d.ts +2 -2
  189. package/dist/runtime/subagents/dispatch.js +2 -2
  190. package/dist/runtime/subagents/org-agents.js +2 -1
  191. package/dist/runtime/subagents/roster.d.ts +1 -1
  192. package/dist/runtime/subagents/roster.js +1 -1
  193. package/dist/runtime/subagents/skill-fork.d.ts +2 -2
  194. package/dist/runtime/subagents/skill-fork.js +2 -2
  195. package/dist/runtime/subagents/subagents.service.d.ts +3 -3
  196. package/dist/runtime/subagents/subagents.service.js +3 -3
  197. package/dist/runtime/usage-report.d.ts +2 -1
  198. package/dist/runtime/usage-report.js +2 -1
  199. package/dist/runtime/waits.d.ts +13 -7
  200. package/dist/runtime/waits.js +42 -16
  201. package/dist/sandbox/sandbox.module.js +6 -1
  202. package/dist/sandbox/sandbox.service.d.ts +61 -3
  203. package/dist/sandbox/sandbox.service.js +141 -7
  204. package/dist/skills/catalog.d.ts +4 -4
  205. package/dist/skills/catalog.js +4 -4
  206. package/dist/skills/changes.service.d.ts +2 -2
  207. package/dist/skills/changes.service.js +5 -4
  208. package/dist/skills/invocation-keys.d.ts +1 -1
  209. package/dist/skills/invocation-keys.js +1 -1
  210. package/dist/skills/invoke.d.ts +1 -1
  211. package/dist/skills/invoke.js +5 -4
  212. package/dist/tools/approvals.service.d.ts +6 -0
  213. package/dist/tools/approvals.service.js +21 -1
  214. package/dist/tools/builtin-names.d.ts +91 -0
  215. package/dist/tools/builtin-names.js +143 -0
  216. package/dist/tools/builtins/agent.d.ts +7 -7
  217. package/dist/tools/builtins/agent.js +7 -11
  218. package/dist/tools/builtins/ask-user.d.ts +1 -1
  219. package/dist/tools/builtins/ask-user.js +2 -2
  220. package/dist/tools/builtins/builtin-tools.d.ts +17 -3
  221. package/dist/tools/builtins/builtin-tools.js +36 -4
  222. package/dist/tools/builtins/read-tool-output.d.ts +1 -1
  223. package/dist/tools/builtins/read-tool-output.js +2 -2
  224. package/dist/tools/builtins/sandbox/bash.d.ts +4 -4
  225. package/dist/tools/builtins/sandbox/bash.js +259 -29
  226. package/dist/tools/builtins/sandbox/common.d.ts +30 -7
  227. package/dist/tools/builtins/sandbox/common.js +9 -5
  228. package/dist/tools/builtins/sandbox/deliver.d.ts +1 -1
  229. package/dist/tools/builtins/sandbox/deliver.js +12 -12
  230. package/dist/tools/builtins/sandbox/edit.d.ts +1 -1
  231. package/dist/tools/builtins/sandbox/edit.js +41 -30
  232. package/dist/tools/builtins/sandbox/file-state.d.ts +34 -0
  233. package/dist/tools/builtins/sandbox/file-state.js +34 -0
  234. package/dist/tools/builtins/sandbox/glob-match.d.ts +1 -1
  235. package/dist/tools/builtins/sandbox/glob-match.js +1 -1
  236. package/dist/tools/builtins/sandbox/glob.d.ts +1 -1
  237. package/dist/tools/builtins/sandbox/glob.js +4 -4
  238. package/dist/tools/builtins/sandbox/grep.d.ts +7 -4
  239. package/dist/tools/builtins/sandbox/grep.js +147 -30
  240. package/dist/tools/builtins/sandbox/index.d.ts +3 -1
  241. package/dist/tools/builtins/sandbox/index.js +7 -1
  242. package/dist/tools/builtins/sandbox/read.d.ts +2 -2
  243. package/dist/tools/builtins/sandbox/read.js +21 -14
  244. package/dist/tools/builtins/sandbox/task-output.d.ts +63 -0
  245. package/dist/tools/builtins/sandbox/task-output.js +304 -0
  246. package/dist/tools/builtins/sandbox/task-stop.d.ts +10 -0
  247. package/dist/tools/builtins/sandbox/task-stop.js +112 -0
  248. package/dist/tools/builtins/sandbox/write.d.ts +1 -1
  249. package/dist/tools/builtins/sandbox/write.js +37 -33
  250. package/dist/tools/builtins/skill-load.d.ts +3 -3
  251. package/dist/tools/builtins/skill-load.js +32 -16
  252. package/dist/tools/builtins/skill-write.d.ts +4 -4
  253. package/dist/tools/builtins/skill-write.js +10 -10
  254. package/dist/tools/builtins/tool-search.d.ts +13 -9
  255. package/dist/tools/builtins/tool-search.js +25 -14
  256. package/dist/tools/builtins/web/errors.d.ts +8 -0
  257. package/dist/tools/builtins/web/errors.js +53 -0
  258. package/dist/tools/builtins/web/extract.d.ts +62 -0
  259. package/dist/tools/builtins/web/extract.js +267 -0
  260. package/dist/tools/builtins/web/fetch.d.ts +55 -0
  261. package/dist/tools/builtins/web/fetch.js +174 -0
  262. package/dist/tools/builtins/web/index.d.ts +13 -0
  263. package/dist/tools/builtins/web/index.js +12 -0
  264. package/dist/tools/builtins/web/page-cache.d.ts +25 -0
  265. package/dist/tools/builtins/web/page-cache.js +77 -0
  266. package/dist/tools/builtins/web/search.d.ts +25 -0
  267. package/dist/tools/builtins/web/search.js +209 -0
  268. package/dist/tools/builtins/web/url.d.ts +17 -0
  269. package/dist/tools/builtins/web/url.js +43 -0
  270. package/dist/tools/connectors.service.js +4 -4
  271. package/dist/tools/display-names.d.ts +9 -0
  272. package/dist/tools/display-names.js +24 -0
  273. package/dist/tools/drift.js +5 -5
  274. package/dist/tools/elicitation.js +1 -1
  275. package/dist/tools/info.d.ts +20 -4
  276. package/dist/tools/info.js +55 -32
  277. package/dist/tools/legacy-data.d.ts +34 -0
  278. package/dist/tools/legacy-data.js +76 -0
  279. package/dist/tools/legacy-keys.d.ts +51 -0
  280. package/dist/tools/legacy-keys.js +115 -0
  281. package/dist/tools/naming.d.ts +1 -5
  282. package/dist/tools/naming.js +1 -7
  283. package/dist/tools/oauth/flow-paths.d.ts +1 -1
  284. package/dist/tools/oauth/flow-paths.js +1 -1
  285. package/dist/tools/outputs.js +1 -1
  286. package/dist/tools/pipeline.d.ts +13 -7
  287. package/dist/tools/pipeline.js +112 -39
  288. package/dist/tools/policy.d.ts +1 -14
  289. package/dist/tools/policy.js +13 -19
  290. package/dist/tools/questions.controller.d.ts +1 -1
  291. package/dist/tools/questions.controller.js +1 -1
  292. package/dist/tools/questions.service.d.ts +1 -1
  293. package/dist/tools/registry.d.ts +38 -24
  294. package/dist/tools/registry.js +54 -47
  295. package/dist/tools/resources.d.ts +1 -1
  296. package/dist/tools/resources.js +1 -1
  297. package/dist/tools/tools.module.js +13 -1
  298. package/dist/tools/validate.js +1 -1
  299. package/package.json +3 -3
  300. package/src/migrations/0063_tool_keys_claude_code.sql +220 -0
  301. package/src/migrations/0064_account_last_org.sql +7 -0
  302. package/src/migrations/0065_conversation_archive.sql +8 -0
  303. package/src/migrations/0066_extension_display_name.sql +4 -0
  304. package/src/migrations/0067_agent_profiles.sql +20 -0
  305. package/src/migrations/0068_agent_avatar_uploads.sql +7 -0
  306. package/src/migrations/0069_attachments_agent_idx.sql +3 -0
  307. package/src/migrations/0070_background_tasks.sql +37 -0
  308. package/src/migrations/0071_background_tasks_reserve.sql +6 -0
  309. package/src/migrations/0072_background_tasks_stopping.sql +5 -0
  310. package/src/migrations/0073_org_extension_point_defaults.sql +11 -0
  311. package/dist/tools/builtins/sandbox/names.d.ts +0 -7
  312. package/dist/tools/builtins/sandbox/names.js +0 -20
@@ -1,25 +1,27 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { viewPath } from "../../view.js";
3
3
  import { checkPath, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, } from "./common.js";
4
+ import { normalizeSandboxPath, recordedFile } from "./file-state.js";
4
5
  /** 不给 `limit` 时一次读的行数。 */
5
6
  const DEFAULT_LIMIT = 2000;
6
7
  /** 单行最多显示的字符数(更长的截断并注明)。 */
7
8
  const MAX_LINE_CHARS = 2000;
8
- /** 最多读出的字节数(更大的文件只读开头,并说明用 sandbox_bash 读其余部分)。 */
9
+ /** 最多读出的字节数(更大的文件只读开头,并说明用 Bash 读其余部分)。 */
9
10
  export const READ_MAX_BYTES = 10 * 1024 * 1024;
10
11
  const SPEC = {
11
- name: "sandbox_read",
12
+ name: "Read",
12
13
  // Display only (the tool row; not in the fingerprint, never sent to the model).
13
- keyArgs: ["path"],
14
+ keyArgs: ["file_path"],
14
15
  description: "Read a text file from this conversation's sandbox, with line numbers. Use it to look at " +
15
16
  "source code, data files, logs and files the user attached (under /workspace/attachments). " +
16
17
  "Paths are absolute, under /workspace, /skills or /tmp. Lines are numbered from 1; pass " +
17
- "offset and limit to read part of a long file. Binary files are not shown; use sandbox_bash " +
18
- "to inspect them. Do not use it to list directories; use sandbox_glob instead.",
18
+ "offset and limit to read part of a long file. Binary files are not shown; use Bash " +
19
+ "to inspect them. Do not use it to list directories; use Glob instead. Read a file before you " +
20
+ "write it: Write and Edit fail on a file you have not read, or one changed since you read it.",
19
21
  inputSchema: {
20
22
  type: "object",
21
23
  properties: {
22
- path: {
24
+ file_path: {
23
25
  type: "string",
24
26
  minLength: 1,
25
27
  description: 'Absolute path of the file, e.g. "/workspace/src/main.py".',
@@ -35,13 +37,13 @@ const SPEC = {
35
37
  description: `Maximum number of lines to read. Default ${DEFAULT_LIMIT}.`,
36
38
  },
37
39
  },
38
- required: ["path"],
40
+ required: ["file_path"],
39
41
  additionalProperties: false,
40
42
  },
41
43
  annotations: { readOnlyHint: true },
42
44
  };
43
- const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with sandbox_glob.`;
44
- const isDirectory = (path) => `${clip(path, 200)} is a directory; use sandbox_glob to list its files.`;
45
+ const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with Glob.`;
46
+ const isDirectory = (path) => `${clip(path, 200)} is a directory; use Glob to list its files.`;
45
47
  const pastEnd = (offset, total) => `offset ${offset} is past the end of the file (${total} lines); pass an offset of at most ${total}.`;
46
48
  /** The file's lines (a final newline does not start another line). */
47
49
  function fileLines(text) {
@@ -70,7 +72,7 @@ export function numberLines(text, offset, limit) {
70
72
  }
71
73
  return out.join("\n");
72
74
  }
73
- /** 内置工具 `sandbox_read`:读沙箱里的文本文件(只读,组织策略为 ask 时也不审批)。 */
75
+ /** 内置工具 `Read`:读沙箱里的文本文件(只读,组织策略为 ask 时也不审批)。 */
74
76
  export function sandboxReadTool(deps) {
75
77
  return {
76
78
  spec: SPEC,
@@ -79,7 +81,7 @@ export function sandboxReadTool(deps) {
79
81
  timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
80
82
  async run(input, ctx) {
81
83
  const { offset = 1, limit = DEFAULT_LIMIT } = input;
82
- const path = checkPath(input.path);
84
+ const path = checkPath(input.file_path, "file_path");
83
85
  const { value, notices } = await inSandbox(deps, ctx, async ({ h, p, signal }) => {
84
86
  const st = await p.stat(h, path, signal);
85
87
  if (st === null)
@@ -95,7 +97,7 @@ export function sandboxReadTool(deps) {
95
97
  // display only: the line range shown on the row
96
98
  let range = {};
97
99
  if (looksBinary(value.data)) {
98
- text = `Binary file (${value.size} bytes); use sandbox_bash to inspect it (for example file or xxd).`;
100
+ text = `Binary file (${value.size} bytes); use Bash to inspect it (for example file or xxd).`;
99
101
  }
100
102
  else if (value.data.byteLength === 0) {
101
103
  text = "(empty file)";
@@ -108,13 +110,18 @@ export function sandboxReadTool(deps) {
108
110
  toLine: Math.min(fileLines(decoded).length, offset - 1 + limit),
109
111
  };
110
112
  if (value.truncated) {
111
- text += `\n[Only the first ${READ_MAX_BYTES} bytes of this ${value.size}-byte file were read; use sandbox_bash (e.g. sed -n or tail) for the rest.]`;
113
+ text += `\n[Only the first ${READ_MAX_BYTES} bytes of this ${value.size}-byte file were read; use Bash (e.g. sed -n or tail) for the rest.]`;
112
114
  }
113
115
  }
114
116
  return {
115
117
  content: [{ type: "text", text: withNotices(notices, text) }],
116
118
  display: display(`读取 ${clip(path, 180)}`, `Read ${clip(path, 180)}`),
117
- view: { kind: "read", path: viewPath(path), ...range },
119
+ view: {
120
+ kind: "read",
121
+ path: viewPath(path),
122
+ ...range,
123
+ file: recordedFile(normalizeSandboxPath(path), value.data, value.size),
124
+ },
118
125
  };
119
126
  },
120
127
  };
@@ -0,0 +1,63 @@
1
+ import { type SandboxHandle } from "@capybara-hq/plugin-sdk";
2
+ import type { BackgroundTaskRow } from "../../../background/store.js";
3
+ import type { IfRunningResult, SandboxService, TaggedProvider } from "../../../sandbox/sandbox.service.js";
4
+ import type { BuiltinCallContext, BuiltinTool } from "../../registry.js";
5
+ import { type SandboxToolDeps } from "./common.js";
6
+ /** How long `TaskOutput` waits with `block` when `timeout` is not given (ms). */
7
+ export declare const TASK_OUTPUT_DEFAULT_TIMEOUT_MS = 30000;
8
+ /** The longest `TaskOutput` wait (ms). */
9
+ export declare const TASK_OUTPUT_MAX_TIMEOUT_MS = 600000;
10
+ /** How often a blocking `TaskOutput` checks the task (each check a short exec of its own). */
11
+ export declare const TASK_CHECK_INTERVAL_MS = 2000;
12
+ /** What `TaskOutput` and `TaskStop` work with. */
13
+ export interface TaskEnv {
14
+ store: NonNullable<SandboxToolDeps["background"]>;
15
+ tasks: NonNullable<SandboxToolDeps["tasks"]>;
16
+ ifRunning: SandboxService["ifRunning"];
17
+ }
18
+ /** The task tools' dependencies; throws the tool's error when they are missing. */
19
+ export declare function taskEnv(deps: SandboxToolDeps): TaskEnv;
20
+ /**
21
+ * The task `id` when it belongs to the calling conversation; a task of another conversation (a
22
+ * sub-agent's, when called from its parent) is not found, the same as an unknown id.
23
+ */
24
+ export declare function ownedTask(env: TaskEnv, ctx: BuiltinCallContext, id: string): Promise<BackgroundTaskRow>;
25
+ /** `ifRunning` on the task's own sandbox instance; sandbox errors become the tools' errors. */
26
+ export declare function onTaskInstance<T>(env: TaskEnv, task: BackgroundTaskRow, fn: (p: TaggedProvider, h: SandboxHandle, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<IfRunningResult<T>>;
27
+ /**
28
+ * The task's status line: `Status: running (2m05s)`, `Status: failed, exit code 3, after 4m12s`,
29
+ * `Status: stopped after 1m00s`, `Status: lost (the sandbox was suspended) after 3s`.
30
+ */
31
+ export declare function statusLine(task: BackgroundTaskRow, now?: Date): string;
32
+ /** The absolute path of the task's output file, as the model sees it. */
33
+ export declare const outputFile: (task: BackgroundTaskRow) => string;
34
+ /** Why the output cannot be read: the task's sandbox instance is not running. */
35
+ export declare function unavailableText(task: BackgroundTaskRow, r: IfRunningResult<unknown>): string;
36
+ /**
37
+ * The exec that checks and reads task `t` (relative to `/workspace`): for a running task first
38
+ * its status line (the poller's, {@link pollScript}: liveness, then the exit file), then
39
+ * `size <bytes>` and `out <base64>`, at most `cap` bytes of the output from byte `offset` on.
40
+ * The file is never read whole: `tail -c +<offset+1> | head -c <cap>`. Without `read` only the
41
+ * status line.
42
+ */
43
+ export declare function taskReadScript(t: {
44
+ id: string;
45
+ sid: string | null;
46
+ running: boolean;
47
+ }, offset: number, cap: number, read?: boolean): string;
48
+ /**
49
+ * The bytes of `buf` up to its last whole UTF-8 character: a character cut by the read's cap is
50
+ * left for the next read.
51
+ */
52
+ export declare function wholeUtf8Length(buf: Uint8Array): number;
53
+ /**
54
+ * Built-in `TaskOutput` (spec 2026-11-05-background-bash-design §2.2): a task's status and the
55
+ * output since this conversation's last read of it. Every check is a short exec through
56
+ * `SandboxService.ifRunning` on the task's own sandbox instance: it never creates or resumes a
57
+ * sandbox, so a suspended or rebuilt one means the task is lost (its output unavailable). With
58
+ * `block`, checks every {@link TASK_CHECK_INTERVAL_MS}, each under a lease of its own, until the
59
+ * task ends or the wait (at most `timeout` and the run's time left) is over; the checks only
60
+ * detect the end, and the one read that makes the result finishes the task (reported). The output
61
+ * read is capped at `tools.outputSpillChars` bytes; the pipeline spills the result beyond that.
62
+ */
63
+ export declare function taskOutputTool(deps: SandboxToolDeps): BuiltinTool;
@@ -0,0 +1,304 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import { isSandboxGoneError, ToolError, } from "@capybara-hq/plugin-sdk";
3
+ import { TASK_ID_RE, TASKS_DIR } from "../../../background/launch.js";
4
+ import { formatElapsed, lostReasonText } from "../../../background/render.js";
5
+ import { SID_RE } from "../../../background/session.js";
6
+ import { parsePollOutput, polledAs, pollScript, } from "../../../background/status.js";
7
+ import { notRunningAs, RECREATED } from "../../../background/stop.js";
8
+ import { clip, display, mapSandboxError, noSandboxError, runTimeLeftMs, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, } from "./common.js";
9
+ /** How long `TaskOutput` waits with `block` when `timeout` is not given (ms). */
10
+ export const TASK_OUTPUT_DEFAULT_TIMEOUT_MS = 30_000;
11
+ /** The longest `TaskOutput` wait (ms). */
12
+ export const TASK_OUTPUT_MAX_TIMEOUT_MS = 600_000;
13
+ /** How often a blocking `TaskOutput` checks the task (each check a short exec of its own). */
14
+ export const TASK_CHECK_INTERVAL_MS = 2000;
15
+ /** The time limit of one check or read exec. */
16
+ const READ_EXEC_TIMEOUT_MS = 30_000;
17
+ const SPEC = {
18
+ name: "TaskOutput",
19
+ // Display only (the tool row; not in the fingerprint, never sent to the model).
20
+ keyArgs: ["task_id"],
21
+ description: "Read the status and output of a background task started with Bash and run_in_background. " +
22
+ "The result has the status (running, completed, failed, stopped, timed out or lost), the " +
23
+ "exit code and the elapsed time, then the output the task wrote since the last TaskOutput " +
24
+ "call for it. With block (the default) it waits until the task finishes or timeout " +
25
+ "milliseconds pass, checking every 2 seconds; prefer this over sleeping in Bash. Each call " +
26
+ "returns a bounded slice of new output; the task's whole output file (its path is in the Bash " +
27
+ "result) can also be read with Read. You are told when a task finishes, so there is no need " +
28
+ "to poll for that.",
29
+ inputSchema: {
30
+ type: "object",
31
+ properties: {
32
+ task_id: {
33
+ type: "string",
34
+ minLength: 1,
35
+ description: "The id of the background task (bt_...) that Bash returned.",
36
+ },
37
+ block: {
38
+ type: "boolean",
39
+ description: "Whether to wait for the task to finish. Default true.",
40
+ },
41
+ timeout: {
42
+ type: "number",
43
+ minimum: 0,
44
+ maximum: TASK_OUTPUT_MAX_TIMEOUT_MS,
45
+ description: `Milliseconds to wait at most when block is true. Default ${TASK_OUTPUT_DEFAULT_TIMEOUT_MS}, at most ${TASK_OUTPUT_MAX_TIMEOUT_MS}; never past the run's own time limit.`,
46
+ },
47
+ },
48
+ required: ["task_id"],
49
+ additionalProperties: false,
50
+ },
51
+ };
52
+ /** The task tools' dependencies; throws the tool's error when they are missing. */
53
+ export function taskEnv(deps) {
54
+ if (!deps.sandbox.available)
55
+ throw noSandboxError();
56
+ const { background, tasks } = deps;
57
+ if (!background || !tasks || !deps.sandbox.ifRunning) {
58
+ throw new ToolError("Background tasks are not available here; use Bash without run_in_background instead.");
59
+ }
60
+ return { store: background, tasks, ifRunning: deps.sandbox.ifRunning.bind(deps.sandbox) };
61
+ }
62
+ const notFound = (id) => new ToolError(`No background task ${clip(id, 40)} in this conversation. Pass a task id that Bash with run_in_background returned in this conversation.`);
63
+ /**
64
+ * The task `id` when it belongs to the calling conversation; a task of another conversation (a
65
+ * sub-agent's, when called from its parent) is not found, the same as an unknown id.
66
+ */
67
+ export async function ownedTask(env, ctx, id) {
68
+ if (!TASK_ID_RE.test(id))
69
+ throw notFound(id);
70
+ const task = await env.store.get(id);
71
+ if (!task || task.conversationId !== ctx.conversationId)
72
+ throw notFound(id);
73
+ return task;
74
+ }
75
+ /** `ifRunning` on the task's own sandbox instance; sandbox errors become the tools' errors. */
76
+ export async function onTaskInstance(env, task, fn, signal) {
77
+ try {
78
+ return await env.ifRunning(task.sandboxConversationId, { createdAt: task.sandboxCreatedAt }, fn, signal);
79
+ }
80
+ catch (e) {
81
+ throw mapSandboxError(e);
82
+ }
83
+ }
84
+ /**
85
+ * The task's status line: `Status: running (2m05s)`, `Status: failed, exit code 3, after 4m12s`,
86
+ * `Status: stopped after 1m00s`, `Status: lost (the sandbox was suspended) after 3s`.
87
+ */
88
+ export function statusLine(task, now = new Date()) {
89
+ const end = task.status === "running" ? now : (task.finishedAt ?? now);
90
+ const elapsed = formatElapsed(end.getTime() - task.startedAt.getTime());
91
+ if (task.status === "running")
92
+ return `Status: running (${elapsed})`;
93
+ let s = `Status: ${task.status === "timed_out" ? "timed out" : task.status}`;
94
+ if (task.lostReason !== null)
95
+ s += ` (${lostReasonText(task.lostReason)})`;
96
+ if (task.exitCode !== null)
97
+ return `${s}, exit code ${task.exitCode}, after ${elapsed}`;
98
+ return `${s} after ${elapsed}`;
99
+ }
100
+ /** The absolute path of the task's output file, as the model sees it. */
101
+ export const outputFile = (task) => `/workspace/${task.outputPath}`;
102
+ /** Why the output cannot be read: the task's sandbox instance is not running. */
103
+ export function unavailableText(task, r) {
104
+ if (r.kind === "not_running" && r.status === "suspended") {
105
+ return `[Output unavailable: the sandbox is suspended. Read ${outputFile(task)} resumes it and reads what the task wrote.]`;
106
+ }
107
+ return "[Output unavailable: the sandbox that ran this task is gone, and its output with it.]";
108
+ }
109
+ // ---- reading a task ----
110
+ /**
111
+ * The exec that checks and reads task `t` (relative to `/workspace`): for a running task first
112
+ * its status line (the poller's, {@link pollScript}: liveness, then the exit file), then
113
+ * `size <bytes>` and `out <base64>`, at most `cap` bytes of the output from byte `offset` on.
114
+ * The file is never read whole: `tail -c +<offset+1> | head -c <cap>`. Without `read` only the
115
+ * status line.
116
+ */
117
+ export function taskReadScript(t, offset, cap, read = true) {
118
+ if (!TASK_ID_RE.test(t.id))
119
+ throw new Error(`invalid background task id: ${t.id}`);
120
+ const lines = [];
121
+ if (t.running && t.sid !== null)
122
+ lines.push(pollScript([{ id: t.id, sid: t.sid }]));
123
+ if (read) {
124
+ const f = `${TASKS_DIR}/${t.id}.out`;
125
+ const from = Math.max(0, Math.floor(offset)) + 1;
126
+ const n = Math.max(1, Math.floor(cap));
127
+ lines.push(`s=$({ wc -c < ${f}; } 2>/dev/null | tr -d ' '); echo "size \${s:-0}"`);
128
+ lines.push(`printf 'out '; { tail -c +${from} ${f} 2>/dev/null | head -c ${n} | base64 | tr -d '\\n'; }; echo`);
129
+ }
130
+ return lines.join("\n");
131
+ }
132
+ function parseRead(id, stdout) {
133
+ const size = /^size ([0-9]+)$/m.exec(stdout);
134
+ const out = /^out ?([A-Za-z0-9+/=]*)$/m.exec(stdout);
135
+ return {
136
+ report: parsePollOutput(stdout).get(id),
137
+ size: size ? Number(size[1]) : 0,
138
+ data: Buffer.from(out?.[1] ?? "", "base64"),
139
+ };
140
+ }
141
+ /**
142
+ * The bytes of `buf` up to its last whole UTF-8 character: a character cut by the read's cap is
143
+ * left for the next read.
144
+ */
145
+ export function wholeUtf8Length(buf) {
146
+ let i = buf.length - 1;
147
+ let back = 0;
148
+ while (i >= 0 && back < 3 && (buf[i] & 0xc0) === 0x80) {
149
+ i--;
150
+ back++;
151
+ }
152
+ if (i < 0)
153
+ return buf.length;
154
+ const b = buf[i];
155
+ const need = b >= 0xf0 ? 4 : b >= 0xe0 ? 3 : b >= 0xc0 ? 2 : 1;
156
+ return i + need > buf.length ? i : buf.length;
157
+ }
158
+ /** Checks (and with `read`, reads) the task in its sandbox instance; never creates or resumes one. */
159
+ async function look(env, task, read, signal) {
160
+ if (task.sid !== null && !SID_RE.test(task.sid)) {
161
+ throw new Error(`invalid background task session: ${task.sid}`);
162
+ }
163
+ const script = taskReadScript({ id: task.id, sid: task.sid, running: task.status === "running" }, read?.offset ?? 0, read?.cap ?? 1, read !== null);
164
+ const maxBytes = Math.ceil((read?.cap ?? 0) / 3) * 4 + 64 * 1024;
165
+ return onTaskInstance(env, task, async (p, h, sig) => {
166
+ const r = await p.exec(h, {
167
+ command: script,
168
+ cwd: "/workspace",
169
+ timeoutMs: READ_EXEC_TIMEOUT_MS,
170
+ maxOutputBytes: maxBytes,
171
+ signal: sig,
172
+ });
173
+ if (r.exitCode !== 0 || r.truncated) {
174
+ throw new ToolError(`Background task ${task.id} could not be read (exit ${r.exitCode}${r.truncated ? ", output truncated" : ""}); retry TaskOutput, or Read ${outputFile(task)}.`);
175
+ }
176
+ return parseRead(task.id, r.stdout);
177
+ }, signal);
178
+ }
179
+ /**
180
+ * How `seen` shows the running `task` ended (an exit file, no process left, its sandbox instance
181
+ * not running), or null while it runs (or when the row is no longer running).
182
+ */
183
+ function endOf(task, seen) {
184
+ if (task.status !== "running")
185
+ return null;
186
+ if (seen.kind === "not_running") {
187
+ return { to: notRunningAs(seen.status, seen.status === "suspended"), lastLines: "" };
188
+ }
189
+ if (seen.kind === "other_instance")
190
+ return { to: RECREATED, lastLines: "" };
191
+ const r = seen.value.report;
192
+ const to = r ? polledAs(task, r, new Date()) : null;
193
+ return to === null ? null : { to, lastLines: r?.lastLines ?? "" };
194
+ }
195
+ /**
196
+ * Finishes the task as `end` says, marked reported: called only once nothing can fail before the
197
+ * result reaches the model, so a reported finish is one the model saw. A task a stop claimed is
198
+ * left to the stop. Returns the task's row afterwards.
199
+ */
200
+ async function settle(env, task, end) {
201
+ if (end === null)
202
+ return task;
203
+ await env.tasks.finisher.finish(task, end.to, end.lastLines, true, { unclaimed: true });
204
+ return (await env.store.get(task.id)) ?? task;
205
+ }
206
+ /** {@link look}, with a `SandboxGoneError` from the exec as null (the instance is gone). */
207
+ async function lookOrGone(env, task, read, signal) {
208
+ try {
209
+ return await look(env, task, read, signal);
210
+ }
211
+ catch (e) {
212
+ if (isSandboxGoneError(e))
213
+ return null;
214
+ throw e;
215
+ }
216
+ }
217
+ /**
218
+ * Built-in `TaskOutput` (spec 2026-11-05-background-bash-design §2.2): a task's status and the
219
+ * output since this conversation's last read of it. Every check is a short exec through
220
+ * `SandboxService.ifRunning` on the task's own sandbox instance: it never creates or resumes a
221
+ * sandbox, so a suspended or rebuilt one means the task is lost (its output unavailable). With
222
+ * `block`, checks every {@link TASK_CHECK_INTERVAL_MS}, each under a lease of its own, until the
223
+ * task ends or the wait (at most `timeout` and the run's time left) is over; the checks only
224
+ * detect the end, and the one read that makes the result finishes the task (reported). The output
225
+ * read is capped at `tools.outputSpillChars` bytes; the pipeline spills the result beyond that.
226
+ */
227
+ export function taskOutputTool(deps) {
228
+ return {
229
+ spec: SPEC,
230
+ defaultPolicy: "allow",
231
+ unavailable: unavailableWhenNoSandbox(deps),
232
+ timeoutMs: (input) => {
233
+ const { block, timeout } = input;
234
+ const wait = block === false
235
+ ? 0
236
+ : Math.min(timeout ?? TASK_OUTPUT_DEFAULT_TIMEOUT_MS, TASK_OUTPUT_MAX_TIMEOUT_MS);
237
+ return wait + sandboxBaseTimeoutMs(deps.config.get());
238
+ },
239
+ async run(input, ctx) {
240
+ const { task_id, block = true, timeout } = input;
241
+ const env = taskEnv(deps);
242
+ let task = await ownedTask(env, ctx, task_id);
243
+ if (block && task.status === "running") {
244
+ const wait = Math.max(0, Math.min(timeout ?? TASK_OUTPUT_DEFAULT_TIMEOUT_MS, TASK_OUTPUT_MAX_TIMEOUT_MS, runTimeLeftMs(ctx.runDeadline)));
245
+ const until = Date.now() + wait;
246
+ // no check right before the final read: the loop ends when the wait does
247
+ while (task.status === "running" && Date.now() < until) {
248
+ if (task.sandboxCreatedAt !== null) {
249
+ const seen = await lookOrGone(env, task, null, ctx.signal);
250
+ if (seen === null || endOf(task, seen) !== null)
251
+ break;
252
+ }
253
+ const left = until - Date.now();
254
+ if (left <= 0)
255
+ break;
256
+ await sleep(Math.min(TASK_CHECK_INTERVAL_MS, left), undefined, { signal: ctx.signal });
257
+ task = (await env.store.get(task.id)) ?? task;
258
+ }
259
+ }
260
+ if (task.sandboxCreatedAt === null) {
261
+ // a reservation still launching, or a launch that failed: nothing ran
262
+ return result(task, [
263
+ statusLine(task),
264
+ task.status === "running"
265
+ ? "[The task is still starting; no output yet.]"
266
+ : "[No output: the command never started.]",
267
+ ]);
268
+ }
269
+ const offset = task.readOffset;
270
+ const cap = deps.config.get().tools.outputSpillChars;
271
+ const seen = await lookOrGone(env, task, { offset, cap }, ctx.signal);
272
+ if (seen === null) {
273
+ return result(task, [statusLine(task), unavailableText(task, { kind: "other_instance" })]);
274
+ }
275
+ const end = endOf(task, seen);
276
+ if (seen.kind !== "ran") {
277
+ task = await settle(env, task, end);
278
+ return result(task, [statusLine(task), unavailableText(task, seen)]);
279
+ }
280
+ const { data, size } = seen.value;
281
+ // an ended task's output is complete: only a read cut by the cap can end inside a character
282
+ const ended = task.status !== "running" || end !== null;
283
+ const used = ended && data.length < cap ? data.length : wholeUtf8Length(data);
284
+ if (used > 0)
285
+ await env.store.advanceOffset(task.id, offset + used);
286
+ task = await settle(env, task, end);
287
+ const parts = [];
288
+ const more = size - (offset + used);
289
+ if (more > 0) {
290
+ parts.push(`[${more} more bytes of output after this; call TaskOutput again to read them, or Read ${outputFile(task)}.]`);
291
+ }
292
+ parts.push(used === 0 ? "[No new output.]" : data.subarray(0, used).toString("utf8"));
293
+ return result(task, [statusLine(task), ...parts]);
294
+ },
295
+ };
296
+ }
297
+ function result(task, lines) {
298
+ const d = clip(task.description, 120);
299
+ return {
300
+ content: [{ type: "text", text: lines.join("\n") }],
301
+ isError: false,
302
+ display: display(`读取后台任务输出:${d}`, `Read background task output: ${d}`),
303
+ };
304
+ }
@@ -0,0 +1,10 @@
1
+ import type { BuiltinTool } from "../../registry.js";
2
+ import { type SandboxToolDeps } from "./common.js";
3
+ /**
4
+ * Built-in `TaskStop` (spec 2026-11-05-background-bash-design §2.3): stops one of this
5
+ * conversation's background tasks through `BackgroundTaskStopper` (SIGTERM to its session, SIGKILL
6
+ * after 5 s, never creating or resuming a sandbox). A task that had already finished is not an
7
+ * error; a reservation still launching, or a task another stop already claimed, is reported as
8
+ * stopping. A stop that failed leaves the task running and is an error the model can retry.
9
+ */
10
+ export declare function taskStopTool(deps: SandboxToolDeps): BuiltinTool;
@@ -0,0 +1,112 @@
1
+ import { ToolError } from "@capybara-hq/plugin-sdk";
2
+ import { decodeTail, tailCommand } from "../../../background/session.js";
3
+ import { clip, display, mapSandboxError, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, } from "./common.js";
4
+ import { onTaskInstance, ownedTask, statusLine, taskEnv } from "./task-output.js";
5
+ /** The time limit of reading a stopped task's last lines. */
6
+ const TAIL_EXEC_TIMEOUT_MS = 10_000;
7
+ const SPEC = {
8
+ name: "TaskStop",
9
+ // Display only (the tool row; not in the fingerprint, never sent to the model).
10
+ keyArgs: ["task_id"],
11
+ description: "Stop a background task started with Bash and run_in_background: every process of the task " +
12
+ "gets SIGTERM, then SIGKILL after 5 seconds. The result has the final status and the last " +
13
+ "lines of output. Stopping a task that has already finished is not an error; the result says " +
14
+ "so. A conversation can stop only its own tasks.",
15
+ inputSchema: {
16
+ type: "object",
17
+ properties: {
18
+ task_id: {
19
+ type: "string",
20
+ minLength: 1,
21
+ description: "The id of the background task (bt_...) that Bash returned.",
22
+ },
23
+ },
24
+ required: ["task_id"],
25
+ additionalProperties: false,
26
+ },
27
+ };
28
+ /** The task's last 20 lines, read from its own sandbox instance; null when that is not running. */
29
+ async function lastLinesOf(env, task, signal) {
30
+ if (task.sandboxCreatedAt === null)
31
+ return null;
32
+ try {
33
+ const r = await onTaskInstance(env, task, async (p, h, sig) => {
34
+ const res = await p.exec(h, {
35
+ command: tailCommand(task.id),
36
+ cwd: "/workspace",
37
+ timeoutMs: TAIL_EXEC_TIMEOUT_MS,
38
+ maxOutputBytes: 64 * 1024,
39
+ signal: sig,
40
+ });
41
+ return res.exitCode === 0 ? decodeTail(res.stdout) : null;
42
+ }, signal);
43
+ return r.kind === "ran" ? r.value : null;
44
+ }
45
+ catch {
46
+ // the task is stopped either way; only its last lines are missing
47
+ return null;
48
+ }
49
+ }
50
+ /** The result text: what happened, the status line and the last lines. */
51
+ async function ended(env, task, what, signal) {
52
+ const lines = await lastLinesOf(env, task, signal);
53
+ const tail = task.sandboxCreatedAt === null
54
+ ? "[No output: the command never started.]"
55
+ : lines === null
56
+ ? "[Last lines unavailable: the sandbox that ran this task is not running.]"
57
+ : lines === ""
58
+ ? "[No output.]"
59
+ : `Last lines:\n${lines.replace(/\n$/, "")}`;
60
+ return text(task, `Background task ${task.id} ("${task.description}") ${what}.\n${statusLine(task)}\n${tail}`);
61
+ }
62
+ function text(task, body) {
63
+ const d = clip(task.description, 120);
64
+ return {
65
+ content: [{ type: "text", text: body }],
66
+ isError: false,
67
+ display: display(`停止后台任务:${d}`, `Stop background task: ${d}`),
68
+ };
69
+ }
70
+ /**
71
+ * Built-in `TaskStop` (spec 2026-11-05-background-bash-design §2.3): stops one of this
72
+ * conversation's background tasks through `BackgroundTaskStopper` (SIGTERM to its session, SIGKILL
73
+ * after 5 s, never creating or resuming a sandbox). A task that had already finished is not an
74
+ * error; a reservation still launching, or a task another stop already claimed, is reported as
75
+ * stopping. A stop that failed leaves the task running and is an error the model can retry.
76
+ */
77
+ export function taskStopTool(deps) {
78
+ return {
79
+ spec: SPEC,
80
+ defaultPolicy: "allow",
81
+ unavailable: unavailableWhenNoSandbox(deps),
82
+ timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
83
+ async run(input, ctx) {
84
+ const { task_id } = input;
85
+ const env = taskEnv(deps);
86
+ const task = await ownedTask(env, ctx, task_id);
87
+ if (task.status !== "running") {
88
+ return ended(env, task, "had already finished", ctx.signal);
89
+ }
90
+ let after;
91
+ try {
92
+ after = await env.tasks.stopper.stop(task, "tool", ctx.signal);
93
+ }
94
+ catch (e) {
95
+ const mapped = mapSandboxError(e);
96
+ if (mapped instanceof ToolError)
97
+ throw mapped;
98
+ const why = e instanceof Error ? e.message : String(e);
99
+ throw new ToolError(`Background task ${task.id} could not be stopped (${clip(why, 300)}); it keeps running. Retry TaskStop, or check the sandbox with Bash.`);
100
+ }
101
+ if (after.status === "running") {
102
+ return text(after, `Background task ${after.id} ("${after.description}") is stopping: it is still starting, or another stop is in progress. Call TaskOutput to see when it has ended.`);
103
+ }
104
+ const what = after.status === "stopped"
105
+ ? "was stopped"
106
+ : after.status === "lost"
107
+ ? "is lost"
108
+ : "had already finished";
109
+ return ended(env, after, what, ctx.signal);
110
+ },
111
+ };
112
+ }
@@ -1,4 +1,4 @@
1
1
  import type { BuiltinTool } from "../../registry.js";
2
2
  import { type SandboxToolDeps } from "./common.js";
3
- /** 内置工具 `sandbox_write`:整文件写入。 */
3
+ /** 内置工具 `Write`:整文件写入。 */
4
4
  export declare function sandboxWriteTool(deps: SandboxToolDeps): BuiltinTool;