@capybara-hq/kernel 0.1.0-rc.3 → 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 (226) 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 +10 -0
  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 +30 -7
  14. package/dist/agents/definition.d.ts +4 -0
  15. package/dist/agents/definition.js +10 -0
  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 +1 -1
  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/claude/agents.js +2 -0
  56. package/dist/catalog/marketplaces.service.d.ts +1 -1
  57. package/dist/catalog/plugin-import.js +1 -1
  58. package/dist/catalog/plugin-upgrade.js +1 -1
  59. package/dist/channels/cards.js +1 -1
  60. package/dist/channels/connections.service.d.ts +16 -1
  61. package/dist/channels/connections.service.js +38 -4
  62. package/dist/channels/threads.d.ts +5 -0
  63. package/dist/channels/threads.js +8 -0
  64. package/dist/config/schema.d.ts +18 -0
  65. package/dist/config/schema.js +102 -0
  66. package/dist/conversations/access.js +2 -0
  67. package/dist/conversations/attachments.service.d.ts +30 -0
  68. package/dist/conversations/attachments.service.js +130 -5
  69. package/dist/conversations/conversations.controller.d.ts +36 -5
  70. package/dist/conversations/conversations.controller.js +62 -12
  71. package/dist/conversations/conversations.module.js +3 -0
  72. package/dist/conversations/conversations.service.d.ts +44 -2
  73. package/dist/conversations/conversations.service.js +140 -12
  74. package/dist/conversations/event-log.d.ts +1 -1
  75. package/dist/conversations/event-log.js +10 -1
  76. package/dist/conversations/events.d.ts +58 -0
  77. package/dist/conversations/events.js +57 -2
  78. package/dist/conversations/queue.d.ts +3 -1
  79. package/dist/conversations/queue.js +13 -2
  80. package/dist/conversations/queue.service.js +3 -1
  81. package/dist/conversations/titles.d.ts +7 -0
  82. package/dist/conversations/titles.js +15 -0
  83. package/dist/db/kernel-schema.d.ts +58 -2
  84. package/dist/db/pool.d.ts +5 -0
  85. package/dist/db/pool.js +3 -0
  86. package/dist/errors.d.ts +8 -0
  87. package/dist/errors.js +8 -0
  88. package/dist/evals/run-replay.d.ts +5 -2
  89. package/dist/evals/run-replay.js +30 -7
  90. package/dist/evals/step-replay.js +12 -6
  91. package/dist/evals/trajectory.js +1 -1
  92. package/dist/extensions/admin-ops.js +2 -0
  93. package/dist/extensions/admin-view.d.ts +3 -1
  94. package/dist/extensions/admin-view.js +10 -2
  95. package/dist/extensions/blobs.js +1 -0
  96. package/dist/extensions/config-issues.d.ts +13 -1
  97. package/dist/extensions/config-issues.js +22 -5
  98. package/dist/extensions/config-json-schema.d.ts +43 -7
  99. package/dist/extensions/config-json-schema.js +124 -58
  100. package/dist/extensions/deployment-config-store.d.ts +6 -0
  101. package/dist/extensions/deployment-config.d.ts +50 -3
  102. package/dist/extensions/deployment-config.js +125 -28
  103. package/dist/extensions/display-name.d.ts +22 -0
  104. package/dist/extensions/display-name.js +77 -0
  105. package/dist/extensions/extensions.module.js +6 -0
  106. package/dist/extensions/host.d.ts +26 -1
  107. package/dist/extensions/host.js +82 -9
  108. package/dist/extensions/org-config.controller.d.ts +11 -3
  109. package/dist/extensions/org-config.controller.js +14 -6
  110. package/dist/extensions/org-config.d.ts +6 -0
  111. package/dist/extensions/org-config.js +12 -13
  112. package/dist/extensions/package.d.ts +14 -1
  113. package/dist/extensions/package.js +51 -2
  114. package/dist/extensions/permission-view.d.ts +3 -0
  115. package/dist/extensions/point-defaults.controller.d.ts +34 -0
  116. package/dist/extensions/point-defaults.controller.js +71 -0
  117. package/dist/extensions/point-defaults.d.ts +64 -0
  118. package/dist/extensions/point-defaults.js +206 -0
  119. package/dist/extensions/registry.d.ts +1 -1
  120. package/dist/extensions/registry.js +2 -0
  121. package/dist/http/api.module.js +8 -0
  122. package/dist/http/nest-logger.d.ts +6 -5
  123. package/dist/http/nest-logger.js +24 -10
  124. package/dist/identity/auth.controller.js +9 -5
  125. package/dist/identity/cookies.d.ts +20 -5
  126. package/dist/identity/cookies.js +44 -6
  127. package/dist/identity/me.controller.d.ts +5 -1
  128. package/dist/identity/me.controller.js +12 -3
  129. package/dist/identity/sessions.d.ts +12 -0
  130. package/dist/identity/sessions.js +45 -0
  131. package/dist/index.d.ts +1 -1
  132. package/dist/infra/config/kernel-config.service.js +6 -0
  133. package/dist/infra/database/database.module.js +1 -0
  134. package/dist/infra/events/kernel-events.d.ts +8 -0
  135. package/dist/infra/lifecycle/process-guards.js +4 -0
  136. package/dist/infra/logging/logging.module.d.ts +4 -2
  137. package/dist/infra/logging/logging.module.js +24 -6
  138. package/dist/infra/queue/redis-connection.d.ts +6 -0
  139. package/dist/infra/queue/redis-connection.js +7 -0
  140. package/dist/infra/redis/redis.module.js +6 -2
  141. package/dist/infra/tokens.d.ts +6 -1
  142. package/dist/infra/tokens.js +6 -1
  143. package/dist/log.d.ts +13 -1
  144. package/dist/log.js +93 -17
  145. package/dist/models/purposes.d.ts +23 -0
  146. package/dist/models/purposes.js +31 -10
  147. package/dist/orgs/offboarding.d.ts +3 -1
  148. package/dist/orgs/offboarding.js +26 -16
  149. package/dist/orgs/settings.service.d.ts +5 -0
  150. package/dist/orgs/settings.service.js +13 -2
  151. package/dist/roles/worker.module.js +6 -0
  152. package/dist/runtime/context/build.d.ts +9 -7
  153. package/dist/runtime/context/build.js +27 -19
  154. package/dist/runtime/context/claude-tools.d.ts +2 -1
  155. package/dist/runtime/context/claude-tools.js +5 -4
  156. package/dist/runtime/context/compaction.js +4 -0
  157. package/dist/runtime/langgraph-loop.js +3 -2
  158. package/dist/runtime/loop.d.ts +4 -3
  159. package/dist/runtime/maintenance.d.ts +4 -2
  160. package/dist/runtime/maintenance.js +17 -5
  161. package/dist/runtime/model-call.d.ts +17 -1
  162. package/dist/runtime/model-call.js +3 -2
  163. package/dist/runtime/providers.d.ts +6 -0
  164. package/dist/runtime/providers.js +8 -0
  165. package/dist/runtime/run-queue.d.ts +25 -2
  166. package/dist/runtime/run-queue.js +129 -33
  167. package/dist/runtime/run-worker.js +16 -3
  168. package/dist/runtime/runtime.module.js +8 -3
  169. package/dist/runtime/step-log.d.ts +6 -0
  170. package/dist/runtime/step-log.js +16 -2
  171. package/dist/runtime/subagents/definition.js +3 -1
  172. package/dist/runtime/usage-report.d.ts +2 -1
  173. package/dist/runtime/usage-report.js +2 -1
  174. package/dist/runtime/waits.d.ts +8 -2
  175. package/dist/runtime/waits.js +37 -11
  176. package/dist/sandbox/sandbox.module.js +6 -1
  177. package/dist/sandbox/sandbox.service.d.ts +61 -3
  178. package/dist/sandbox/sandbox.service.js +141 -7
  179. package/dist/tools/approvals.service.js +2 -0
  180. package/dist/tools/builtin-names.d.ts +20 -2
  181. package/dist/tools/builtin-names.js +29 -2
  182. package/dist/tools/builtins/builtin-tools.d.ts +15 -1
  183. package/dist/tools/builtins/builtin-tools.js +34 -2
  184. package/dist/tools/builtins/sandbox/bash.d.ts +1 -1
  185. package/dist/tools/builtins/sandbox/bash.js +230 -3
  186. package/dist/tools/builtins/sandbox/common.d.ts +27 -4
  187. package/dist/tools/builtins/sandbox/common.js +7 -3
  188. package/dist/tools/builtins/sandbox/deliver.js +1 -1
  189. package/dist/tools/builtins/sandbox/index.d.ts +2 -0
  190. package/dist/tools/builtins/sandbox/index.js +6 -0
  191. package/dist/tools/builtins/sandbox/task-output.d.ts +63 -0
  192. package/dist/tools/builtins/sandbox/task-output.js +304 -0
  193. package/dist/tools/builtins/sandbox/task-stop.d.ts +10 -0
  194. package/dist/tools/builtins/sandbox/task-stop.js +112 -0
  195. package/dist/tools/builtins/web/errors.d.ts +8 -0
  196. package/dist/tools/builtins/web/errors.js +53 -0
  197. package/dist/tools/builtins/web/extract.d.ts +62 -0
  198. package/dist/tools/builtins/web/extract.js +267 -0
  199. package/dist/tools/builtins/web/fetch.d.ts +55 -0
  200. package/dist/tools/builtins/web/fetch.js +174 -0
  201. package/dist/tools/builtins/web/index.d.ts +13 -0
  202. package/dist/tools/builtins/web/index.js +12 -0
  203. package/dist/tools/builtins/web/page-cache.d.ts +25 -0
  204. package/dist/tools/builtins/web/page-cache.js +77 -0
  205. package/dist/tools/builtins/web/search.d.ts +25 -0
  206. package/dist/tools/builtins/web/search.js +209 -0
  207. package/dist/tools/builtins/web/url.d.ts +17 -0
  208. package/dist/tools/builtins/web/url.js +43 -0
  209. package/dist/tools/oauth/flow-paths.d.ts +1 -1
  210. package/dist/tools/oauth/flow-paths.js +1 -1
  211. package/dist/tools/pipeline.js +15 -0
  212. package/dist/tools/registry.d.ts +22 -3
  213. package/dist/tools/registry.js +26 -11
  214. package/dist/tools/tools.module.js +12 -0
  215. package/dist/tools/validate.js +1 -1
  216. package/package.json +3 -3
  217. package/src/migrations/0064_account_last_org.sql +7 -0
  218. package/src/migrations/0065_conversation_archive.sql +8 -0
  219. package/src/migrations/0066_extension_display_name.sql +4 -0
  220. package/src/migrations/0067_agent_profiles.sql +20 -0
  221. package/src/migrations/0068_agent_avatar_uploads.sql +7 -0
  222. package/src/migrations/0069_attachments_agent_idx.sql +3 -0
  223. package/src/migrations/0070_background_tasks.sql +37 -0
  224. package/src/migrations/0071_background_tasks_reserve.sql +6 -0
  225. package/src/migrations/0072_background_tasks_stopping.sql +5 -0
  226. package/src/migrations/0073_org_extension_point_defaults.sql +11 -0
@@ -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
+ }
@@ -0,0 +1,8 @@
1
+ /** Which web tool is calling its provider (it names the provider in some texts). */
2
+ export type WebToolKind = "search" | "fetch";
3
+ /**
4
+ * Rethrows a web provider's failure for the tool pipeline: a `WebProviderError` becomes a
5
+ * `ToolError` with its kind's fixed text; anything else is rethrown unchanged (the pipeline's
6
+ * generic failure, which names only the error class, never the provider's message).
7
+ */
8
+ export declare function webToolError(e: unknown, tool: WebToolKind): never;
@@ -0,0 +1,53 @@
1
+ import { ToolError, WebProviderError } from "@capybara-hq/plugin-sdk";
2
+ const KINDS = new Set([
3
+ "not_found",
4
+ "blocked",
5
+ "auth",
6
+ "rate_limited",
7
+ "unavailable",
8
+ "invalid",
9
+ ]);
10
+ /**
11
+ * The kind of a provider's `WebProviderError`, or undefined for any other error. Matched by name
12
+ * as well as by class, so an extension bundled with its own copy of the class still maps.
13
+ */
14
+ function providerErrorKind(e) {
15
+ if (!(e instanceof Error))
16
+ return undefined;
17
+ if (!(e instanceof WebProviderError) && e.name !== "WebProviderError")
18
+ return undefined;
19
+ const kind = e.kind;
20
+ return typeof kind === "string" && KINDS.has(kind) ? kind : undefined;
21
+ }
22
+ /**
23
+ * The fixed model-visible text of a provider error kind (web tools spec §4.2): providers never
24
+ * write model-visible text.
25
+ */
26
+ function providerErrorText(kind, tool) {
27
+ const provider = tool === "search" ? "web search" : "web fetch";
28
+ switch (kind) {
29
+ case "auth":
30
+ return `The ${provider} provider rejected its credentials; ask an org admin to check the provider's configuration.`;
31
+ case "rate_limited":
32
+ return `The ${provider} provider is rate limiting this org; retry in a minute or continue without it.`;
33
+ case "not_found":
34
+ return "No results or page found; check the query or URL and retry.";
35
+ case "blocked":
36
+ return "The site refused the provider; use another source.";
37
+ case "unavailable":
38
+ return "The web provider is unavailable right now; retry later or continue without it.";
39
+ case "invalid":
40
+ return "The provider rejected the request; check the query or URL and retry.";
41
+ }
42
+ }
43
+ /**
44
+ * Rethrows a web provider's failure for the tool pipeline: a `WebProviderError` becomes a
45
+ * `ToolError` with its kind's fixed text; anything else is rethrown unchanged (the pipeline's
46
+ * generic failure, which names only the error class, never the provider's message).
47
+ */
48
+ export function webToolError(e, tool) {
49
+ const kind = providerErrorKind(e);
50
+ if (kind === undefined)
51
+ throw e;
52
+ throw new ToolError(providerErrorText(kind, tool));
53
+ }
@@ -0,0 +1,62 @@
1
+ import { type Logger, type WebFetchPage } from "@capybara-hq/plugin-sdk";
2
+ import type { EventLog } from "../../../conversations/event-log.js";
3
+ import type { KernelConfigService } from "../../../infra/config/kernel-config.service.js";
4
+ import { type ModelPurposesService } from "../../../models/purposes.js";
5
+ import { type HookRunner } from "../../../runtime/hook-calls.js";
6
+ import type { StepLog } from "../../../runtime/step-log.js";
7
+ import type { UsageReporter } from "../../../runtime/usage-report.js";
8
+ import type { BuiltinCallContext } from "../../registry.js";
9
+ /**
10
+ * The `WebFetch` extraction call (web tools spec §5): the fetched page and the model's prompt go to
11
+ * the `web_fetch` model purpose (unmapped → the calling conversation's current chat model, a
12
+ * sub-agent's call: the sub-agent's), and only its answer comes back. One call, no tools, output
13
+ * capped at `web.fetch.maxAnswerTokens`. The page sits between a random per-call tag the system
14
+ * prompt names, so page text cannot close it or fake the prompt; it is cut to fit the purpose
15
+ * model's context window ({@link fitPage}). It fires `model.request` (a policy denial is the tool error
16
+ * {@link WEB_FETCH_DENIED_TEXT}, logged as any hook denial) and `model.response` like the title
17
+ * call; its tokens are a `usage` event with `purpose: "web_fetch"` and the call id, reported, and
18
+ * counted on the parent run of a sub-agent. The page itself is never stored and never returned:
19
+ * a failure is the tool error {@link WEB_FETCH_EXTRACT_FAILED_TEXT}. The call is not model-visible
20
+ * to the agent (its result is the recorded `tool_result`), so replays never make it.
21
+ */
22
+ /**
23
+ * The fixed start of the extraction call's system prompt (model-facing, English; a core constant).
24
+ * The prompt sent is {@link webFetchSystemPrompt}, which adds the call's page tag.
25
+ */
26
+ export declare const WEB_FETCH_SYSTEM_PROMPT: string;
27
+ /** The system prompt of one extraction call: {@link WEB_FETCH_SYSTEM_PROMPT} naming its page tag. */
28
+ export declare function webFetchSystemPrompt(tag: string): string;
29
+ /** The tool error when the extraction call fails (the page is never returned instead). */
30
+ export declare const WEB_FETCH_EXTRACT_FAILED_TEXT = "Could not extract an answer from the page; retry, or try another URL.";
31
+ /** The tool error when a `model.request` policy hook denies the extraction call. */
32
+ export declare const WEB_FETCH_DENIED_TEXT = "An org policy blocked reading this page; continue without it or ask the user.";
33
+ /** What {@link extractAnswer} needs. */
34
+ export interface WebFetchExtractDeps {
35
+ purposes: Pick<ModelPurposesService, "chat" | "chatLimits">;
36
+ eventLog: Pick<EventLog, "append" | "notify" | "latestOfType">;
37
+ stepLog: Pick<StepLog, "appendCounted" | "appendAudited">;
38
+ config: Pick<KernelConfigService, "get">;
39
+ log: Pick<Logger, "warn">;
40
+ /** Extension hooks (absent: none fire). */
41
+ hooks?: HookRunner | undefined;
42
+ usageReport?: Pick<UsageReporter, "enqueue"> | undefined;
43
+ }
44
+ /**
45
+ * The user message of the extraction call: the URL, then the page (title, markdown) between
46
+ * `<tag>` and `</tag>`, then the prompt.
47
+ */
48
+ export declare function extractionMessage(page: WebFetchPage, prompt: string, tag: string): string;
49
+ /**
50
+ * The page cut so the extraction request fits the purpose model's context (web tools spec §4.2):
51
+ * system prompt + message + answer cap + headroom within `contextWindow`, by the kernel's
52
+ * `estimateTokens`. A cut page ends with {@link TRUNCATED_MARKER}; one that fits is unchanged.
53
+ */
54
+ export declare function fitPage(page: WebFetchPage, prompt: string, tag: string, system: string, limits: {
55
+ contextWindow: number;
56
+ answerTokens: number;
57
+ }): WebFetchPage;
58
+ /**
59
+ * Answers `prompt` from `page` with one call on the `web_fetch` purpose (see the module comment).
60
+ * Returns the answer text; throws a {@link ToolError} on a denial or a failure.
61
+ */
62
+ export declare function extractAnswer(deps: WebFetchExtractDeps, ctx: BuiltinCallContext, page: WebFetchPage, prompt: string): Promise<string>;