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

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 (133) hide show
  1. package/dist/agents/agent-lookup.js +10 -2
  2. package/dist/agents/agents.service.js +19 -6
  3. package/dist/agents/definition.d.ts +31 -8
  4. package/dist/agents/definition.js +193 -17
  5. package/dist/agents/templates.js +19 -4
  6. package/dist/catalog/catalog-content.js +4 -1
  7. package/dist/catalog/claude/agents.js +13 -10
  8. package/dist/catalog/marketplaces.service.d.ts +1 -1
  9. package/dist/channels/cards.d.ts +8 -2
  10. package/dist/channels/cards.js +16 -8
  11. package/dist/config/schema.js +2 -2
  12. package/dist/conversations/artifacts.d.ts +1 -1
  13. package/dist/conversations/artifacts.js +1 -1
  14. package/dist/conversations/event-log.d.ts +11 -0
  15. package/dist/conversations/event-log.js +19 -0
  16. package/dist/conversations/events.d.ts +23 -3
  17. package/dist/conversations/events.js +26 -14
  18. package/dist/db/kernel-schema.d.ts +2 -2
  19. package/dist/evals/recorded-tools.d.ts +27 -1
  20. package/dist/evals/recorded-tools.js +85 -10
  21. package/dist/evals/run-replay.d.ts +5 -0
  22. package/dist/evals/run-replay.js +19 -5
  23. package/dist/evals/trajectory.d.ts +2 -2
  24. package/dist/identity/settings.js +1 -1
  25. package/dist/lifecycle/kernel-lifecycle.js +5 -0
  26. package/dist/orgs/settings.service.d.ts +2 -2
  27. package/dist/orgs/settings.service.js +2 -2
  28. package/dist/runtime/context/build.d.ts +6 -6
  29. package/dist/runtime/context/build.js +18 -8
  30. package/dist/runtime/context/claude-tools.d.ts +2 -1
  31. package/dist/runtime/context/claude-tools.js +9 -10
  32. package/dist/runtime/context/legacy-text.d.ts +22 -0
  33. package/dist/runtime/context/legacy-text.js +37 -0
  34. package/dist/runtime/context/skills.d.ts +29 -11
  35. package/dist/runtime/context/skills.js +37 -30
  36. package/dist/runtime/loop.d.ts +1 -1
  37. package/dist/runtime/model-call.js +1 -1
  38. package/dist/runtime/run-finish.d.ts +1 -1
  39. package/dist/runtime/run-queue.d.ts +3 -3
  40. package/dist/runtime/run-queue.js +2 -2
  41. package/dist/runtime/run-worker.d.ts +2 -2
  42. package/dist/runtime/run-worker.js +4 -4
  43. package/dist/runtime/subagents/definition.d.ts +1 -6
  44. package/dist/runtime/subagents/definition.js +11 -12
  45. package/dist/runtime/subagents/dispatch.d.ts +2 -2
  46. package/dist/runtime/subagents/dispatch.js +2 -2
  47. package/dist/runtime/subagents/org-agents.js +2 -1
  48. package/dist/runtime/subagents/roster.d.ts +1 -1
  49. package/dist/runtime/subagents/roster.js +1 -1
  50. package/dist/runtime/subagents/skill-fork.d.ts +2 -2
  51. package/dist/runtime/subagents/skill-fork.js +2 -2
  52. package/dist/runtime/subagents/subagents.service.d.ts +3 -3
  53. package/dist/runtime/subagents/subagents.service.js +3 -3
  54. package/dist/runtime/waits.d.ts +5 -5
  55. package/dist/runtime/waits.js +5 -5
  56. package/dist/skills/catalog.d.ts +4 -4
  57. package/dist/skills/catalog.js +4 -4
  58. package/dist/skills/changes.service.d.ts +2 -2
  59. package/dist/skills/changes.service.js +5 -4
  60. package/dist/skills/invocation-keys.d.ts +1 -1
  61. package/dist/skills/invocation-keys.js +1 -1
  62. package/dist/skills/invoke.d.ts +1 -1
  63. package/dist/skills/invoke.js +5 -4
  64. package/dist/tools/approvals.service.d.ts +6 -0
  65. package/dist/tools/approvals.service.js +19 -1
  66. package/dist/tools/builtin-names.d.ts +73 -0
  67. package/dist/tools/builtin-names.js +116 -0
  68. package/dist/tools/builtins/agent.d.ts +7 -7
  69. package/dist/tools/builtins/agent.js +7 -11
  70. package/dist/tools/builtins/ask-user.d.ts +1 -1
  71. package/dist/tools/builtins/ask-user.js +2 -2
  72. package/dist/tools/builtins/builtin-tools.d.ts +2 -2
  73. package/dist/tools/builtins/builtin-tools.js +2 -2
  74. package/dist/tools/builtins/read-tool-output.d.ts +1 -1
  75. package/dist/tools/builtins/read-tool-output.js +2 -2
  76. package/dist/tools/builtins/sandbox/bash.d.ts +5 -5
  77. package/dist/tools/builtins/sandbox/bash.js +31 -28
  78. package/dist/tools/builtins/sandbox/common.d.ts +3 -3
  79. package/dist/tools/builtins/sandbox/common.js +2 -2
  80. package/dist/tools/builtins/sandbox/deliver.d.ts +1 -1
  81. package/dist/tools/builtins/sandbox/deliver.js +11 -11
  82. package/dist/tools/builtins/sandbox/edit.d.ts +1 -1
  83. package/dist/tools/builtins/sandbox/edit.js +41 -30
  84. package/dist/tools/builtins/sandbox/file-state.d.ts +34 -0
  85. package/dist/tools/builtins/sandbox/file-state.js +34 -0
  86. package/dist/tools/builtins/sandbox/glob-match.d.ts +1 -1
  87. package/dist/tools/builtins/sandbox/glob-match.js +1 -1
  88. package/dist/tools/builtins/sandbox/glob.d.ts +1 -1
  89. package/dist/tools/builtins/sandbox/glob.js +4 -4
  90. package/dist/tools/builtins/sandbox/grep.d.ts +7 -4
  91. package/dist/tools/builtins/sandbox/grep.js +147 -30
  92. package/dist/tools/builtins/sandbox/index.d.ts +1 -1
  93. package/dist/tools/builtins/sandbox/index.js +1 -1
  94. package/dist/tools/builtins/sandbox/read.d.ts +2 -2
  95. package/dist/tools/builtins/sandbox/read.js +21 -14
  96. package/dist/tools/builtins/sandbox/write.d.ts +1 -1
  97. package/dist/tools/builtins/sandbox/write.js +37 -33
  98. package/dist/tools/builtins/skill-load.d.ts +3 -3
  99. package/dist/tools/builtins/skill-load.js +32 -16
  100. package/dist/tools/builtins/skill-write.d.ts +4 -4
  101. package/dist/tools/builtins/skill-write.js +10 -10
  102. package/dist/tools/builtins/tool-search.d.ts +13 -9
  103. package/dist/tools/builtins/tool-search.js +25 -14
  104. package/dist/tools/connectors.service.js +4 -4
  105. package/dist/tools/display-names.d.ts +9 -0
  106. package/dist/tools/display-names.js +24 -0
  107. package/dist/tools/drift.js +5 -5
  108. package/dist/tools/elicitation.js +1 -1
  109. package/dist/tools/info.d.ts +20 -4
  110. package/dist/tools/info.js +55 -32
  111. package/dist/tools/legacy-data.d.ts +34 -0
  112. package/dist/tools/legacy-data.js +76 -0
  113. package/dist/tools/legacy-keys.d.ts +51 -0
  114. package/dist/tools/legacy-keys.js +115 -0
  115. package/dist/tools/naming.d.ts +1 -5
  116. package/dist/tools/naming.js +1 -7
  117. package/dist/tools/outputs.js +1 -1
  118. package/dist/tools/pipeline.d.ts +13 -7
  119. package/dist/tools/pipeline.js +97 -39
  120. package/dist/tools/policy.d.ts +1 -14
  121. package/dist/tools/policy.js +13 -19
  122. package/dist/tools/questions.controller.d.ts +1 -1
  123. package/dist/tools/questions.controller.js +1 -1
  124. package/dist/tools/questions.service.d.ts +1 -1
  125. package/dist/tools/registry.d.ts +16 -21
  126. package/dist/tools/registry.js +29 -37
  127. package/dist/tools/resources.d.ts +1 -1
  128. package/dist/tools/resources.js +1 -1
  129. package/dist/tools/tools.module.js +1 -1
  130. package/package.json +2 -2
  131. package/src/migrations/0063_tool_keys_claude_code.sql +220 -0
  132. package/dist/tools/builtins/sandbox/names.d.ts +0 -7
  133. package/dist/tools/builtins/sandbox/names.js +0 -20
@@ -4,18 +4,18 @@ import { isValidArtifactName } from "../../../conversations/events.js";
4
4
  import { ApiError } from "../../../errors.js";
5
5
  import { checkPath, clip, display, inSandbox, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, } from "./common.js";
6
6
  const SPEC = {
7
- name: "sandbox_deliver",
7
+ name: "Deliver",
8
8
  // Display only (the tool row; not in the fingerprint, never sent to the model).
9
- keyArgs: ["path"],
9
+ keyArgs: ["file_path"],
10
10
  description: "Deliver a file from this conversation's sandbox to the user as a downloadable artifact. Use " +
11
11
  "it when the user should receive a file you produced (a report, chart, spreadsheet, archive " +
12
12
  "and so on); files that stay in the sandbox are not visible to the user. Delivers one file " +
13
- "per call; archive a directory first (e.g. zip -r with sandbox_bash). The file size is " +
13
+ "per call; archive a directory first (e.g. tar -czf with Bash). The file size is " +
14
14
  "limited (100 MB by default). Do not use it for intermediate files the user does not need.",
15
15
  inputSchema: {
16
16
  type: "object",
17
17
  properties: {
18
- path: {
18
+ file_path: {
19
19
  type: "string",
20
20
  minLength: 1,
21
21
  description: 'Absolute path of the file in the sandbox, e.g. "/workspace/out/report.pdf".',
@@ -24,10 +24,10 @@ const SPEC = {
24
24
  type: "string",
25
25
  minLength: 1,
26
26
  maxLength: MEDIA_NAME_MAX_CHARS,
27
- description: 'File name shown to the user, e.g. "Q3 report.pdf". Default: the file name in path.',
27
+ description: 'File name shown to the user, e.g. "Q3 report.pdf". Default: the file name in file_path.',
28
28
  },
29
29
  },
30
- required: ["path"],
30
+ required: ["file_path"],
31
31
  additionalProperties: false,
32
32
  },
33
33
  };
@@ -71,9 +71,9 @@ export function contentTypeFor(name) {
71
71
  const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
72
72
  return CONTENT_TYPES[ext] ?? "application/octet-stream";
73
73
  }
74
- const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with sandbox_glob.`;
75
- const isDirectory = (path) => `${clip(path, 200)} is a directory; deliver one file, e.g. archive the directory first with sandbox_bash (zip -r) and retry.`;
76
- const tooLarge = (path, size, max) => `File ${clip(path, 200)} is ${size} bytes, over the delivery limit of ${max} bytes; compress or split it with sandbox_bash and retry.`;
74
+ const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with Glob.`;
75
+ const isDirectory = (path) => `${clip(path, 200)} is a directory; deliver one file, e.g. archive the directory first with Bash (tar -czf) and retry.`;
76
+ const tooLarge = (path, size, max) => `File ${clip(path, 200)} is ${size} bytes, over the delivery limit of ${max} bytes; compress or split it with Bash and retry.`;
77
77
  const BAD_NAME = "name must not contain control characters, / or \\; pass a plain file name such as report.pdf.";
78
78
  /** 默认产物名:路径的文件名部分,过长时保留末尾(扩展名)截到 255 个 UTF-16 单元以内。 */
79
79
  function defaultName(path) {
@@ -90,7 +90,7 @@ function defaultName(path) {
90
90
  const NO_STORAGE = "File storage is not configured in this deployment, so files cannot be delivered; ask an administrator, or provide the result in your reply instead.";
91
91
  /** 「工具不可用」提醒里的原因(内核在后面补句号)。 */
92
92
  const NO_STORAGE_REASON = NO_STORAGE.slice(0, -1);
93
- /** 内置工具 `sandbox_deliver`:把沙箱里的文件存进对象存储,写 `artifact_created`,用户可下载。 */
93
+ /** 内置工具 `Deliver`:把沙箱里的文件存进对象存储,写 `artifact_created`,用户可下载。 */
94
94
  export function sandboxDeliverTool(deps) {
95
95
  return {
96
96
  spec: SPEC,
@@ -102,7 +102,7 @@ export function sandboxDeliverTool(deps) {
102
102
  // 存储在调用前就核对:不为一个交付不了的文件去 stat / 读沙箱
103
103
  if (!deps.storage.available)
104
104
  throw new ToolError(NO_STORAGE);
105
- const path = checkPath(input.path);
105
+ const path = checkPath(input.file_path, "file_path");
106
106
  const given = input.name?.trim();
107
107
  // 与 artifact_created 的 schema 同一规则,在上传前检查(不合法的名字不会在写事件时才失败)
108
108
  if (given !== undefined && (!isValidArtifactName(given) || /[/\\]/.test(given))) {
@@ -1,4 +1,4 @@
1
1
  import type { BuiltinTool } from "../../registry.js";
2
2
  import { type SandboxToolDeps } from "./common.js";
3
- /** 内置工具 `sandbox_edit`:按精确文本替换。 */
3
+ /** 内置工具 `Edit`:按精确文本替换。 */
4
4
  export declare function sandboxEditTool(deps: SandboxToolDeps): BuiltinTool;
@@ -1,40 +1,42 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { lineDiff, viewPath } from "../../view.js";
3
3
  import { checkWritable, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, withPathLease, } from "./common.js";
4
- /** 可编辑的最大文件(字节):更大的用 sandbox_bash 处理。 */
4
+ import { assertReadAndUnchanged, fileStateOf, normalizeSandboxPath, recordedFile, } from "./file-state.js";
5
+ import { READ_MAX_BYTES } from "./read.js";
6
+ /** 可编辑的最大文件(字节):更大的用 Bash 处理。 */
5
7
  const EDIT_MAX_BYTES = 10 * 1024 * 1024;
6
8
  const SPEC = {
7
- name: "sandbox_edit",
9
+ name: "Edit",
8
10
  // Display only (the tool row; not in the fingerprint, never sent to the model).
9
- keyArgs: ["path"],
10
- description: "Edit a text file in this conversation's sandbox by replacing exact text. oldText must match " +
11
- "the file exactly (including whitespace and indentation) and, unless replaceAll is true, occur " +
12
- "exactly once; include enough surrounding lines to make it unique. Read the file with " +
13
- "sandbox_read first. Use sandbox_write to create a file or replace all of it.",
11
+ keyArgs: ["file_path"],
12
+ description: "Edit a text file in this conversation's sandbox by replacing exact text. old_string must match " +
13
+ "the file exactly (including whitespace and indentation) and, unless replace_all is true, occur " +
14
+ "exactly once; include enough surrounding lines to make it unique. Read the file first; " +
15
+ "editing a file you have not read, or one changed since you read it, fails. Use Write to create a file or replace all of it.",
14
16
  inputSchema: {
15
17
  type: "object",
16
18
  properties: {
17
- path: {
19
+ file_path: {
18
20
  type: "string",
19
21
  minLength: 1,
20
22
  description: 'Absolute path of the file, e.g. "/workspace/src/app.py".',
21
23
  },
22
- oldText: { type: "string", minLength: 1, description: "The exact text to replace." },
23
- newText: { type: "string", description: "The replacement text." },
24
- replaceAll: {
24
+ old_string: { type: "string", minLength: 1, description: "The exact text to replace." },
25
+ new_string: { type: "string", description: "The replacement text." },
26
+ replace_all: {
25
27
  type: "boolean",
26
- description: "Replace every occurrence of oldText instead of exactly one. Default false.",
28
+ description: "Replace every occurrence of old_string instead of exactly one. Default false.",
27
29
  },
28
30
  },
29
- required: ["path", "oldText", "newText"],
31
+ required: ["file_path", "old_string", "new_string"],
30
32
  additionalProperties: false,
31
33
  },
32
34
  };
33
- const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with sandbox_glob, or use sandbox_write to create it.`;
34
- const notText = (path) => `${clip(path, 200)} is a directory, a binary file or larger than ${EDIT_MAX_BYTES} bytes; use sandbox_bash to change it.`;
35
- const SAME_TEXT = "oldText and newText are the same; pass the text you want to change and its replacement.";
36
- const noMatch = (path) => `oldText was not found in ${clip(path, 200)}; call sandbox_read and pass the exact text, including whitespace.`;
37
- const ambiguous = (n) => `oldText occurs ${n} times; pass more surrounding text to make it unique, or pass replaceAll: true.`;
35
+ const notFound = (path) => `File not found: ${clip(path, 200)}. Check the path with Glob, or use Write to create it.`;
36
+ const notText = (path) => `${clip(path, 200)} is a directory, a binary file or larger than ${EDIT_MAX_BYTES} bytes; use Bash to change it.`;
37
+ const SAME_TEXT = "old_string and new_string are the same; pass the text you want to change and its replacement.";
38
+ const noMatch = (path) => `old_string was not found in ${clip(path, 200)}; call Read and pass the exact text, including whitespace.`;
39
+ const ambiguous = (n) => `old_string occurs ${n} times; pass more surrounding text to make it unique, or pass replace_all: true.`;
38
40
  /** 出现次数(不重叠)。 */
39
41
  function occurrences(text, sub) {
40
42
  let n = 0;
@@ -42,7 +44,7 @@ function occurrences(text, sub) {
42
44
  n++;
43
45
  return n;
44
46
  }
45
- /** 内置工具 `sandbox_edit`:按精确文本替换。 */
47
+ /** 内置工具 `Edit`:按精确文本替换。 */
46
48
  export function sandboxEditTool(deps) {
47
49
  return {
48
50
  spec: SPEC,
@@ -50,9 +52,9 @@ export function sandboxEditTool(deps) {
50
52
  unavailable: unavailableWhenNoSandbox(deps),
51
53
  timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
52
54
  async run(input, ctx) {
53
- const { oldText, newText, replaceAll = false } = input;
54
- const path = checkWritable(input.path);
55
- if (oldText === newText)
55
+ const { old_string, new_string, replace_all = false } = input;
56
+ const path = checkWritable(input.file_path);
57
+ if (old_string === new_string)
56
58
  throw new ToolError(SAME_TEXT);
57
59
  const { value: edit, notices } = await inSandbox(deps, ctx, ({ h, p, signal }) =>
58
60
  // read, replace, write: one holder at a time per file
@@ -67,18 +69,26 @@ export function sandboxEditTool(deps) {
67
69
  throw new ToolError(notFound(path));
68
70
  if (got.truncated || looksBinary(got.data))
69
71
  throw new ToolError(notText(path));
72
+ await assertReadAndUnchanged(deps, ctx.conversationId, path, fileStateOf(got.data, st.size));
70
73
  const text = new TextDecoder().decode(got.data);
71
- const count = occurrences(text, oldText);
74
+ const count = occurrences(text, old_string);
72
75
  if (count === 0)
73
76
  throw new ToolError(noMatch(path));
74
- if (count > 1 && !replaceAll)
77
+ if (count > 1 && !replace_all)
75
78
  throw new ToolError(ambiguous(count));
76
- // 用函数形式替换:newText 里的 `$&` 等不被当成替换模式
77
- const next = replaceAll
78
- ? text.split(oldText).join(newText)
79
- : text.replace(oldText, () => newText);
80
- await p.writeFile(h, path, new TextEncoder().encode(next), signal);
81
- return { n: replaceAll ? count : 1, before: text, after: next };
79
+ // 用函数形式替换:new_string 里的 `$&` 等不被当成替换模式
80
+ const next = replace_all
81
+ ? text.split(old_string).join(new_string)
82
+ : text.replace(old_string, () => new_string);
83
+ const nextBytes = new TextEncoder().encode(next);
84
+ await p.writeFile(h, path, nextBytes, signal);
85
+ return {
86
+ n: replace_all ? count : 1,
87
+ before: text,
88
+ after: next,
89
+ // over the bytes the next Write / Edit reads back (Read's limit), as Read records it
90
+ file: recordedFile(normalizeSandboxPath(path), nextBytes.subarray(0, READ_MAX_BYTES), nextBytes.byteLength),
91
+ };
82
92
  }));
83
93
  const { n } = edit;
84
94
  const text = `Edited ${path}: replaced ${n} occurrence${n === 1 ? "" : "s"}.`;
@@ -91,6 +101,7 @@ export function sandboxEditTool(deps) {
91
101
  path: viewPath(path),
92
102
  created: false,
93
103
  ...lineDiff(edit.before, edit.after),
104
+ file: edit.file,
94
105
  },
95
106
  };
96
107
  },
@@ -0,0 +1,34 @@
1
+ import type { EventLog } from "../../../conversations/event-log.js";
2
+ /**
3
+ * Read before `Write` / `Edit` (tool naming spec §4.5). The state of a file as a `Read`, `Write` or
4
+ * `Edit` saw or left it is recorded in the display-only `tool_result.view.file`; before writing,
5
+ * the tools compare the latest recorded state of the path in this conversation's log with the
6
+ * content they read anyway. Nothing lives in process memory, so every replica decides the same.
7
+ */
8
+ export interface FileState {
9
+ /** The file's full size in bytes. */
10
+ size: number;
11
+ /** sha256 (hex) of the bytes handled: the first bytes only for a file over `Read`'s byte limit. */
12
+ sha256: string;
13
+ }
14
+ /** What the tools put into `view.file`: the state plus the full normalized path (never cut). */
15
+ export interface RecordedFile extends FileState {
16
+ path: string;
17
+ }
18
+ export declare const NOT_READ_TEXT = "File has not been read yet. Read it first before writing to it.";
19
+ export declare const MODIFIED_TEXT = "File has been modified since it was read, either by the user or by another command. Read it again before writing to it.";
20
+ /** The state of `bytes`, the bytes handled of a file whose full size is `fullSize`. */
21
+ export declare function fileStateOf(bytes: Uint8Array, fullSize: number): FileState;
22
+ /** The `view.file` value for a file at `path` (already normalized). */
23
+ export declare function recordedFile(path: string, bytes: Uint8Array, fullSize: number): RecordedFile;
24
+ /** POSIX-normalized absolute path (`/workspace/./a.txt` and `/workspace/a.txt` are one file). */
25
+ export declare function normalizeSandboxPath(path: string): string;
26
+ /** The latest recorded state of `path` in the conversation's log; null when it was never recorded. */
27
+ export declare function lastFileState(log: Pick<EventLog, "latestFileState">, conversationId: string, path: string): Promise<FileState | null>;
28
+ /**
29
+ * Throws the model-visible error unless the conversation read (or wrote) the file and it is
30
+ * unchanged: `current` is the state of the content the caller just read.
31
+ */
32
+ export declare function assertReadAndUnchanged(deps: {
33
+ eventLog: Pick<EventLog, "latestFileState">;
34
+ }, conversationId: string, path: string, current: FileState): Promise<void>;
@@ -0,0 +1,34 @@
1
+ import { createHash } from "node:crypto";
2
+ import { posix } from "node:path";
3
+ import { ToolError } from "@capybara-hq/plugin-sdk";
4
+ export const NOT_READ_TEXT = "File has not been read yet. Read it first before writing to it.";
5
+ export const MODIFIED_TEXT = "File has been modified since it was read, either by the user or by another command. Read it again before writing to it.";
6
+ /** The state of `bytes`, the bytes handled of a file whose full size is `fullSize`. */
7
+ export function fileStateOf(bytes, fullSize) {
8
+ return { size: fullSize, sha256: createHash("sha256").update(bytes).digest("hex") };
9
+ }
10
+ /** The `view.file` value for a file at `path` (already normalized). */
11
+ export function recordedFile(path, bytes, fullSize) {
12
+ return { path, ...fileStateOf(bytes, fullSize) };
13
+ }
14
+ /** POSIX-normalized absolute path (`/workspace/./a.txt` and `/workspace/a.txt` are one file). */
15
+ export function normalizeSandboxPath(path) {
16
+ const n = posix.normalize(path);
17
+ return n.length > 1 && n.endsWith("/") ? n.slice(0, -1) : n;
18
+ }
19
+ /** The latest recorded state of `path` in the conversation's log; null when it was never recorded. */
20
+ export async function lastFileState(log, conversationId, path) {
21
+ return log.latestFileState(conversationId, normalizeSandboxPath(path));
22
+ }
23
+ /**
24
+ * Throws the model-visible error unless the conversation read (or wrote) the file and it is
25
+ * unchanged: `current` is the state of the content the caller just read.
26
+ */
27
+ export async function assertReadAndUnchanged(deps, conversationId, path, current) {
28
+ const seen = await lastFileState(deps.eventLog, conversationId, path);
29
+ if (seen === null)
30
+ throw new ToolError(NOT_READ_TEXT);
31
+ if (seen.size !== current.size || seen.sha256 !== current.sha256) {
32
+ throw new ToolError(MODIFIED_TEXT);
33
+ }
34
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 线性时间的 glob 匹配(sandbox_glob 用;模式由模型给出,不能编译成会回溯爆炸的正则)。
2
+ * 线性时间的 glob 匹配(Glob 用;模式由模型给出,不能编译成会回溯爆炸的正则)。
3
3
  *
4
4
  * 语法:路径按 `/` 分段;整段 `**` 跨任意层目录(含零层);段内 `*` 匹配任意个字符(不跨 `/`),`?` 一个字符,
5
5
  * `[abc]` / `[a-z]` / `[!x]`(或 `[^x]`)字符类,`{a,b}` 二选一(可嵌套,展开后最多 {@link MAX_ALTERNATIVES} 个);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 线性时间的 glob 匹配(sandbox_glob 用;模式由模型给出,不能编译成会回溯爆炸的正则)。
2
+ * 线性时间的 glob 匹配(Glob 用;模式由模型给出,不能编译成会回溯爆炸的正则)。
3
3
  *
4
4
  * 语法:路径按 `/` 分段;整段 `**` 跨任意层目录(含零层);段内 `*` 匹配任意个字符(不跨 `/`),`?` 一个字符,
5
5
  * `[abc]` / `[a-z]` / `[!x]`(或 `[^x]`)字符类,`{a,b}` 二选一(可嵌套,展开后最多 {@link MAX_ALTERNATIVES} 个);
@@ -1,4 +1,4 @@
1
1
  import type { BuiltinTool } from "../../registry.js";
2
2
  import { type SandboxToolDeps } from "./common.js";
3
- /** 内置工具 `sandbox_glob`:按文件名模式找文件(只读)。 */
3
+ /** 内置工具 `Glob`:按文件名模式找文件(只读)。 */
4
4
  export declare function sandboxGlobTool(deps: SandboxToolDeps): BuiltinTool;
@@ -6,14 +6,14 @@ const MAX_RESULTS = 1000;
6
6
  /** `find` 输出的上限(字节)。 */
7
7
  const MAX_FIND_BYTES = 8 * 1024 * 1024;
8
8
  const SPEC = {
9
- name: "sandbox_glob",
9
+ name: "Glob",
10
10
  // Display only (the tool row; not in the fingerprint, never sent to the model).
11
11
  keyArgs: ["pattern"],
12
12
  description: "Find files by name pattern in this conversation's sandbox. Use it to list files and to " +
13
13
  'locate files by name, e.g. pattern "**/*.py" for all Python files. The pattern is matched ' +
14
14
  "against paths relative to path (default /workspace): * matches within one directory, ** " +
15
15
  "matches across directories, ? matches one character, {a,b} matches either. Returns absolute " +
16
- "paths sorted by name, up to 1000. To search file contents, use sandbox_grep.",
16
+ "paths sorted by name, up to 1000. To search file contents, use Grep.",
17
17
  inputSchema: {
18
18
  type: "object",
19
19
  properties: {
@@ -36,7 +36,7 @@ const SPEC = {
36
36
  const ABSOLUTE_PATTERN = 'The pattern must be relative to path; pass the directory in path and a relative pattern such as "**/*.py".';
37
37
  const notDirectory = (path) => `${clip(path, 200)} is not a directory; pass an existing directory in path (default /workspace).`;
38
38
  const FIND_FAILED = "Listing files did not finish in time; pass a narrower path or pattern and retry.";
39
- /** 内置工具 `sandbox_glob`:按文件名模式找文件(只读)。 */
39
+ /** 内置工具 `Glob`:按文件名模式找文件(只读)。 */
40
40
  export function sandboxGlobTool(deps) {
41
41
  return {
42
42
  spec: SPEC,
@@ -84,7 +84,7 @@ export function sandboxGlobTool(deps) {
84
84
  .map((rel) => `${base}/${rel}`)
85
85
  .filter((abs) => abs !== SYNC_MARKER)
86
86
  .sort()
87
- // 文件名里的换行显示为 `\n`(与 sandbox_grep 一致),一行一个文件
87
+ // 文件名里的换行显示为 `\n`(与 Grep 一致),一行一个文件
88
88
  .map((abs) => abs.replace(/\n/g, "\\n")));
89
89
  });
90
90
  const shown = files.slice(0, MAX_RESULTS);
@@ -1,9 +1,12 @@
1
1
  import type { BuiltinTool } from "../../registry.js";
2
2
  import { type SandboxToolDeps } from "./common.js";
3
3
  /**
4
- * 解析 `grep -nH --null` 的输出:每条为 `<文件名>\0<行号>:<行>\n`(文件名可能含换行,行本身不含)。
5
- * 返回 `<绝对路径>:<行号>:<行>`;文件名里的换行显示为 `\n`。最后一条不完整(输出被截断)时丢掉。
4
+ * Parses the output of `grep -H --null` (with `-n` when `numbered`): each entry is
5
+ * `<file name>\0<line number>:<line>\n` (the file name may contain newlines, the line does not).
6
+ * Returns `<absolute path>:<line number>:<line>`; context lines (`<line number>-<line>`, only with
7
+ * `-A/-B/-C`) become `<absolute path>-<line number>-<line>`, and the `--` group separator is kept.
8
+ * A newline in a file name shows as `\n`. An incomplete last entry (truncated output) is dropped.
6
9
  */
7
- export declare function parseGrepNull(stdout: string, base: string): string[];
8
- /** 内置工具 `sandbox_grep`:按正则搜文件内容(只读)。 */
10
+ export declare function parseGrepNull(stdout: string, base: string, numbered?: boolean): string[];
11
+ /** 内置工具 `Grep`:按正则搜文件内容(只读)。 */
9
12
  export declare function sandboxGrepTool(deps: SandboxToolDeps): BuiltinTool;
@@ -1,20 +1,28 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { checkPath, clip, display, inSandbox, SYNC_MARKER, sandboxBaseTimeoutMs, searchTimeoutMs, shellQuote, unavailableWhenNoSandbox, withNotices, } from "./common.js";
3
- /** 最多返回的匹配行数。 */
3
+ /** The most output entries (lines, files or counts) returned in one call, whatever `head_limit` says. */
4
4
  const MAX_MATCHES = 500;
5
+ /** `head_limit` when the model gives none. */
6
+ const DEFAULT_HEAD_LIMIT = 250;
5
7
  /** 每个匹配行最多显示的字符数。 */
6
8
  const MAX_LINE_CHARS = 500;
7
9
  /** grep 输出的上限(字节)。 */
8
10
  const MAX_GREP_BYTES = 4 * 1024 * 1024;
11
+ const MODES = ["content", "files_with_matches", "count"];
9
12
  const SPEC = {
10
- name: "sandbox_grep",
13
+ name: "Grep",
11
14
  // Display only (the tool row; not in the fingerprint, never sent to the model).
12
15
  keyArgs: ["pattern", "path"],
13
16
  description: "Search file contents in this conversation's sandbox with a regular expression (POSIX " +
14
17
  "extended, as grep -E). Use it to find where something is defined or mentioned. Searches path " +
15
18
  "(a file, or a directory recursively; default /workspace), skipping binary files; glob limits " +
16
- 'the files searched by name, e.g. "*.py". Returns matching lines as <path>:<line>:<text>, up ' +
17
- "to 500. To find files by name, use sandbox_glob.",
19
+ 'the files searched by name, e.g. "*.py". output_mode picks what comes back: ' +
20
+ '"files_with_matches" (default) lists the paths of files that match, "content" returns the ' +
21
+ "matching lines as <path>:<line>:<text> (with -A, -B or -C lines of context around them), " +
22
+ '"count" returns <path>:<number of matching lines> per file. -n (line numbers) and the context ' +
23
+ "options apply only to content mode. head_limit caps the entries returned (default 250; " +
24
+ "0 = up to 500); pass offset to skip entries and page through more. To find files by " +
25
+ "name, use Glob.",
18
26
  inputSchema: {
19
27
  type: "object",
20
28
  properties: {
@@ -33,24 +41,66 @@ const SPEC = {
33
41
  minLength: 1,
34
42
  description: 'Only search files whose name matches this glob, e.g. "*.md".',
35
43
  },
36
- ignoreCase: { type: "boolean", description: "Case-insensitive match. Default false." },
44
+ "-i": { type: "boolean", description: "Case-insensitive match. Default false." },
45
+ output_mode: {
46
+ type: "string",
47
+ enum: [...MODES],
48
+ description: 'What to return: "files_with_matches" (file paths, default), "content" (matching lines) or "count" (matching lines per file).',
49
+ },
50
+ "-n": {
51
+ type: "boolean",
52
+ description: "Show line numbers in content mode. Default true.",
53
+ },
54
+ "-A": {
55
+ type: "integer",
56
+ minimum: 0,
57
+ description: "Lines of context after each match (content mode).",
58
+ },
59
+ "-B": {
60
+ type: "integer",
61
+ minimum: 0,
62
+ description: "Lines of context before each match (content mode).",
63
+ },
64
+ "-C": {
65
+ type: "integer",
66
+ minimum: 0,
67
+ description: "Lines of context before and after each match (content mode).",
68
+ },
69
+ head_limit: {
70
+ type: "integer",
71
+ minimum: 0,
72
+ description: `Return at most this many entries (lines, files or counts, by mode). Default ${DEFAULT_HEAD_LIMIT}; 0 = up to ${MAX_MATCHES}.`,
73
+ },
74
+ offset: {
75
+ type: "integer",
76
+ minimum: 0,
77
+ description: "Skip this many entries before returning (for paging). Default 0.",
78
+ },
37
79
  },
38
80
  required: ["pattern"],
39
81
  additionalProperties: false,
40
82
  },
41
83
  annotations: { readOnlyHint: true },
42
84
  };
43
- const notFound = (path) => `${clip(path, 200)} does not exist; check the path with sandbox_glob.`;
85
+ const notFound = (path) => `${clip(path, 200)} does not exist; check the path with Glob.`;
44
86
  const failed = (stderr) => `grep failed: ${clip(stderr, 300)}. Check the pattern (POSIX extended regular expression) and retry.`;
45
87
  const GREP_TIMEOUT = "The search did not finish in time; pass a narrower path or a glob and retry.";
46
88
  /**
47
- * 解析 `grep -nH --null` 的输出:每条为 `<文件名>\0<行号>:<行>\n`(文件名可能含换行,行本身不含)。
48
- * 返回 `<绝对路径>:<行号>:<行>`;文件名里的换行显示为 `\n`。最后一条不完整(输出被截断)时丢掉。
89
+ * Parses the output of `grep -H --null` (with `-n` when `numbered`): each entry is
90
+ * `<file name>\0<line number>:<line>\n` (the file name may contain newlines, the line does not).
91
+ * Returns `<absolute path>:<line number>:<line>`; context lines (`<line number>-<line>`, only with
92
+ * `-A/-B/-C`) become `<absolute path>-<line number>-<line>`, and the `--` group separator is kept.
93
+ * A newline in a file name shows as `\n`. An incomplete last entry (truncated output) is dropped.
49
94
  */
50
- export function parseGrepNull(stdout, base) {
95
+ export function parseGrepNull(stdout, base, numbered = true) {
51
96
  const out = [];
52
97
  let pos = 0;
53
98
  for (;;) {
99
+ if (stdout.startsWith("--\n", pos)) {
100
+ out.push("--");
101
+ pos += 3;
102
+ continue;
103
+ }
54
104
  const nul = stdout.indexOf("\0", pos);
55
105
  if (nul === -1)
56
106
  break;
@@ -59,12 +109,45 @@ export function parseGrepNull(stdout, base) {
59
109
  break;
60
110
  const raw = stdout.slice(pos, nul);
61
111
  const name = (raw.startsWith("./") ? raw.slice(2) : raw).replace(/\n/g, "\\n");
62
- out.push(`${base}/${name}:${stdout.slice(nul + 1, nl)}`);
112
+ const rest = stdout.slice(nul + 1, nl);
113
+ out.push(numbered && /^\d+-/.test(rest) ? `${base}/${name}-${rest}` : `${base}/${name}:${rest}`);
63
114
  pos = nl + 1;
64
115
  }
65
116
  return out;
66
117
  }
67
- /** 内置工具 `sandbox_grep`:按正则搜文件内容(只读)。 */
118
+ const displayName = (raw) => (raw.startsWith("./") ? raw.slice(2) : raw).replace(/\n/g, "\\n");
119
+ /** `grep -l --null` output: the matching files, each followed by NUL. */
120
+ function parseFileList(stdout, base) {
121
+ const parts = stdout.split("\0");
122
+ // the last part is empty, or an incomplete name when the output was truncated: dropped
123
+ parts.pop();
124
+ return parts.filter((n) => n !== "").map((n) => `${base}/${displayName(n)}`);
125
+ }
126
+ /**
127
+ * `grep -c` output as `<path>:<count>` for the files with at least one matching line. GNU grep
128
+ * with `--null` writes `<file>\0<count>\n`; other implementations write `<file>:<count>`.
129
+ */
130
+ function parseCounts(stdout, base) {
131
+ const out = [];
132
+ if (stdout.includes("\0")) {
133
+ for (const l of parseGrepNull(stdout, base, false)) {
134
+ if (!l.endsWith(":0"))
135
+ out.push(l);
136
+ }
137
+ return out;
138
+ }
139
+ for (const line of stdout.split("\n")) {
140
+ const i = line.lastIndexOf(":");
141
+ if (i <= 0)
142
+ continue;
143
+ const count = line.slice(i + 1);
144
+ if (count === "0" || !/^\d+$/.test(count))
145
+ continue;
146
+ out.push(`${base}/${displayName(line.slice(0, i))}:${count}`);
147
+ }
148
+ return out;
149
+ }
150
+ /** 内置工具 `Grep`:按正则搜文件内容(只读)。 */
68
151
  export function sandboxGrepTool(deps) {
69
152
  return {
70
153
  spec: SPEC,
@@ -73,8 +156,11 @@ export function sandboxGrepTool(deps) {
73
156
  timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
74
157
  async run(input, ctx) {
75
158
  const startedAt = Date.now();
76
- const { pattern, glob, ignoreCase = false } = input;
77
- const path = checkPath(input.path ?? "/workspace");
159
+ const g = input;
160
+ const { pattern, glob } = g;
161
+ const mode = g.output_mode ?? "files_with_matches";
162
+ const numbered = g["-n"] ?? true;
163
+ const path = checkPath(g.path ?? "/workspace");
78
164
  const { value, notices } = await inSandbox(deps, ctx, async ({ h, p, signal }) => {
79
165
  const st = await p.stat(h, path, signal);
80
166
  if (st === null)
@@ -83,10 +169,22 @@ export function sandboxGrepTool(deps) {
83
169
  const slash = path.lastIndexOf("/");
84
170
  const cwd = st.isDir ? path : path.slice(0, slash) || "/";
85
171
  const target = st.isDir ? "." : path.slice(slash + 1);
172
+ const base = cwd === "/" ? "" : cwd;
173
+ // GNU grep options (`-l`, `-c`, `-n`, `-A/-B/-C`, `--null`): the sandbox images are Debian
174
+ const modeFlags = mode === "files_with_matches"
175
+ ? ["-rlIE", "--null"]
176
+ : mode === "count"
177
+ ? ["-rcHIE", "--null"]
178
+ : [numbered ? "-rnHIE" : "-rHIE", "--null"];
179
+ const context = mode === "content"
180
+ ? ["-A", "-B", "-C"].flatMap((f) => g[f] !== undefined ? [f, String(g[f])] : [])
181
+ : [];
86
182
  const command = [
87
183
  // --null:文件名后跟 NUL 而不是 `:`,文件名里有换行或冒号也能解析
88
- "grep -rnHIE --null",
89
- ...(ignoreCase ? ["-i"] : []),
184
+ "grep",
185
+ ...modeFlags,
186
+ ...(g["-i"] === true ? ["-i"] : []),
187
+ ...context,
90
188
  ...(glob !== undefined ? [`--include=${shellQuote(glob)}`] : []),
91
189
  "-e",
92
190
  shellQuote(pattern),
@@ -103,27 +201,46 @@ export function sandboxGrepTool(deps) {
103
201
  if (r.timedOut || r.exitCode === null)
104
202
  throw new ToolError(GREP_TIMEOUT);
105
203
  if (r.exitCode === 1)
106
- return { lines: [], warning: null };
107
- const all = parseGrepNull(r.stdout, cwd === "/" ? "" : cwd);
108
- const lines = all.filter((l) => !l.startsWith(`${SYNC_MARKER}:`));
204
+ return { entries: [], warning: null };
205
+ const all = mode === "files_with_matches"
206
+ ? parseFileList(r.stdout, base)
207
+ : mode === "count"
208
+ ? parseCounts(r.stdout, base)
209
+ : parseGrepNull(r.stdout, base, numbered);
210
+ const entries = all.filter((l) => l !== SYNC_MARKER &&
211
+ !l.startsWith(`${SYNC_MARKER}:`) &&
212
+ !l.startsWith(`${SYNC_MARKER}-`));
109
213
  // 退出码 2 = 有错误(如个别文件不可读);有输出时照常返回(可能为空:只匹配到隐藏的标记文件)并附上说明
110
214
  if (r.exitCode !== 0 && all.length === 0)
111
215
  throw new ToolError(failed(r.stderr));
112
216
  const warning = r.exitCode !== 0 ? clip(r.stderr, 300) : null;
113
- return { lines, warning };
217
+ return { entries, warning };
114
218
  });
115
- const { lines, warning } = value;
116
- const shown = lines
117
- .slice(0, MAX_MATCHES)
118
- .map((l) => (l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}…` : l));
219
+ const { entries, warning } = value;
220
+ const total = entries.length;
221
+ const offset = g.offset ?? 0;
222
+ const headLimit = g.head_limit === undefined ? DEFAULT_HEAD_LIMIT : g.head_limit;
223
+ const limit = headLimit === 0 ? MAX_MATCHES : Math.min(headLimit, MAX_MATCHES);
224
+ const page = entries.slice(offset, offset + limit);
225
+ const shown = page.map((l) => l.length > MAX_LINE_CHARS ? `${l.slice(0, MAX_LINE_CHARS)}…` : l);
119
226
  const note = warning !== null ? `\n[grep also reported errors: ${warning}]` : "";
120
- const text = (lines.length === 0
121
- ? `No matches for ${pattern} in ${path}.`
122
- : shown.join("\n") +
123
- (lines.length > MAX_MATCHES
124
- ? `\n[Showing the first ${MAX_MATCHES} of ${lines.length} matching lines; use a narrower pattern, path or glob.]`
125
- : "")) + note;
126
- const n = lines.length;
227
+ let text;
228
+ if (total === 0) {
229
+ text = `No matches for ${pattern} in ${path}.${note}`;
230
+ }
231
+ else if (page.length === 0) {
232
+ text = `No more results (${total} total).${note}`;
233
+ }
234
+ else {
235
+ const end = offset + page.length;
236
+ text =
237
+ shown.join("\n") +
238
+ (end < total
239
+ ? `\n[Showing entries ${offset + 1}–${end} of ${total}; pass offset=${end} to continue, or use a narrower pattern, path or glob.]`
240
+ : "") +
241
+ note;
242
+ }
243
+ const n = total;
127
244
  return {
128
245
  content: [{ type: "text", text: withNotices(notices, text) }],
129
246
  display: display(`搜索 ${clip(pattern, 120)}(${n} 处)`, `Searched for ${clip(pattern, 120)} (${n} match${n === 1 ? "" : "es"})`),
@@ -1,9 +1,9 @@
1
1
  import type { BuiltinTool } from "../../registry.js";
2
2
  import type { SandboxToolDeps } from "./common.js";
3
+ export { SANDBOX_ASK_TOOL_NAMES, SANDBOX_TOOL_NAMES } from "../../builtin-names.js";
3
4
  export { BASH_SPILL_CHARS, formatExec } from "./bash.js";
4
5
  export { assignAttachmentNames, RUN_DEADLINE_MARGIN_MS, runTimeLeftMs, SANDBOX_RECREATED_NOTICE, SANDBOX_SETUP_MARGIN_MS, SANDBOX_STARTED_NOTICE, SANDBOX_UNAVAILABLE_REASON, type SandboxToolDeps, sandboxBaseTimeoutMs, searchTimeoutMs, shellQuote, } from "./common.js";
5
6
  export { compileGlob, GlobPatternError, MAX_GLOB_STARS } from "./glob-match.js";
6
- export { SANDBOX_ASK_TOOL_NAMES, SANDBOX_TOOL_NAMES } from "./names.js";
7
7
  /**
8
8
  * 沙箱内置工具(M5 T8):bash / read / write / edit / glob / grep / deliver,都在本对话的沙箱上执行
9
9
  * (`SandboxService.withSandbox`),执行前同步附件到 `/workspace/attachments`。没有沙箱提供方时报不可用。
@@ -5,10 +5,10 @@ import { sandboxGlobTool } from "./glob.js";
5
5
  import { sandboxGrepTool } from "./grep.js";
6
6
  import { sandboxReadTool } from "./read.js";
7
7
  import { sandboxWriteTool } from "./write.js";
8
+ export { SANDBOX_ASK_TOOL_NAMES, SANDBOX_TOOL_NAMES } from "../../builtin-names.js";
8
9
  export { BASH_SPILL_CHARS, formatExec } from "./bash.js";
9
10
  export { assignAttachmentNames, RUN_DEADLINE_MARGIN_MS, runTimeLeftMs, SANDBOX_RECREATED_NOTICE, SANDBOX_SETUP_MARGIN_MS, SANDBOX_STARTED_NOTICE, SANDBOX_UNAVAILABLE_REASON, sandboxBaseTimeoutMs, searchTimeoutMs, shellQuote, } from "./common.js";
10
11
  export { compileGlob, GlobPatternError, MAX_GLOB_STARS } from "./glob-match.js";
11
- export { SANDBOX_ASK_TOOL_NAMES, SANDBOX_TOOL_NAMES } from "./names.js";
12
12
  /**
13
13
  * 沙箱内置工具(M5 T8):bash / read / write / edit / glob / grep / deliver,都在本对话的沙箱上执行
14
14
  * (`SandboxService.withSandbox`),执行前同步附件到 `/workspace/attachments`。没有沙箱提供方时报不可用。