@capybara-hq/kernel 0.1.0-rc.32 → 0.1.0-rc.33

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 (85) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/inbound.d.ts +0 -25
  3. package/dist/channels/inbound.js +26 -1
  4. package/dist/channels/phrases.d.ts +28 -0
  5. package/dist/channels/phrases.js +28 -0
  6. package/dist/conversations/conversations.controller.d.ts +4 -1
  7. package/dist/conversations/conversations.controller.js +14 -2
  8. package/dist/conversations/conversations.service.d.ts +43 -3
  9. package/dist/conversations/conversations.service.js +93 -19
  10. package/dist/conversations/event-log.d.ts +3 -3
  11. package/dist/conversations/event-log.js +3 -3
  12. package/dist/conversations/events.d.ts +24 -0
  13. package/dist/conversations/events.js +69 -0
  14. package/dist/db/kernel-schema.d.ts +20 -0
  15. package/dist/devices/conversation-devices.d.ts +57 -3
  16. package/dist/devices/conversation-devices.js +63 -11
  17. package/dist/devices/device-projects.service.d.ts +162 -0
  18. package/dist/devices/device-projects.service.js +503 -0
  19. package/dist/devices/devices.controller.d.ts +15 -2
  20. package/dist/devices/devices.controller.js +60 -3
  21. package/dist/devices/devices.module.js +15 -2
  22. package/dist/devices/devices.schemas.js +9 -1
  23. package/dist/devices/dto.d.ts +31 -0
  24. package/dist/devices/dto.js +38 -1
  25. package/dist/devices/working-root.d.ts +41 -0
  26. package/dist/devices/working-root.js +50 -0
  27. package/dist/errors.d.ts +39 -0
  28. package/dist/errors.js +39 -0
  29. package/dist/evals/run-replay.d.ts +9 -1
  30. package/dist/evals/run-replay.js +15 -1
  31. package/dist/local-devices/local-device-provider.d.ts +37 -1
  32. package/dist/local-devices/local-device-provider.js +33 -0
  33. package/dist/local-devices/machines.d.ts +2 -1
  34. package/dist/local-devices/machines.js +4 -1
  35. package/dist/local-devices/policy-summary.js +1 -0
  36. package/dist/local-devices/relay.d.ts +2 -0
  37. package/dist/local-devices/relay.js +3 -1
  38. package/dist/local-devices/targets.d.ts +6 -1
  39. package/dist/local-devices/targets.js +14 -0
  40. package/dist/overrides.d.ts +4 -0
  41. package/dist/overrides.js +2 -0
  42. package/dist/platform/ops/agent-skills.ops.js +2 -1
  43. package/dist/platform/ops/devices.ops.d.ts +3 -1
  44. package/dist/platform/ops/devices.ops.js +136 -3
  45. package/dist/runtime/context/build.d.ts +3 -0
  46. package/dist/runtime/context/build.js +14 -0
  47. package/dist/runtime/context/compaction.js +2 -0
  48. package/dist/runtime/context/project-root.d.ts +43 -0
  49. package/dist/runtime/context/project-root.js +85 -0
  50. package/dist/runtime/model-call.js +25 -1
  51. package/dist/runtime/project/knowledge.d.ts +129 -0
  52. package/dist/runtime/project/knowledge.js +248 -0
  53. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  54. package/dist/runtime/project/knowledge.service.js +288 -0
  55. package/dist/runtime/run-worker.d.ts +5 -0
  56. package/dist/runtime/run-worker.js +27 -6
  57. package/dist/runtime/runtime.module.js +7 -0
  58. package/dist/sandbox/review/review.service.d.ts +14 -2
  59. package/dist/sandbox/review/review.service.js +2 -0
  60. package/dist/sandbox/review/rules.d.ts +6 -4
  61. package/dist/sandbox/review/rules.js +185 -62
  62. package/dist/sandbox/review/types.d.ts +14 -0
  63. package/dist/sandbox/sandbox.service.d.ts +16 -1
  64. package/dist/sandbox/sandbox.service.js +75 -3
  65. package/dist/skills/catalog.d.ts +6 -1
  66. package/dist/skills/catalog.js +18 -4
  67. package/dist/skills/invoke.d.ts +64 -2
  68. package/dist/skills/invoke.js +214 -6
  69. package/dist/skills/skills.module.js +5 -0
  70. package/dist/tools/approvals.service.d.ts +6 -0
  71. package/dist/tools/builtins/sandbox/bash.js +19 -4
  72. package/dist/tools/builtins/sandbox/common.d.ts +36 -6
  73. package/dist/tools/builtins/sandbox/common.js +69 -8
  74. package/dist/tools/builtins/sandbox/edit.js +2 -2
  75. package/dist/tools/builtins/sandbox/glob.js +3 -2
  76. package/dist/tools/builtins/sandbox/grep.js +2 -1
  77. package/dist/tools/builtins/sandbox/read.js +3 -3
  78. package/dist/tools/builtins/sandbox/write.js +2 -2
  79. package/dist/tools/builtins/skill-load.d.ts +47 -2
  80. package/dist/tools/builtins/skill-load.js +160 -2
  81. package/dist/tools/pipeline.d.ts +1 -1
  82. package/dist/tools/pipeline.js +53 -8
  83. package/dist/tools/registry.d.ts +6 -0
  84. package/package.json +2 -2
  85. package/src/migrations/0133_project_root.sql +30 -0
@@ -1,7 +1,7 @@
1
1
  import { DEFAULT_SANDBOX_ROOTS, ToolError, } from "@capybara-hq/plugin-sdk";
2
2
  import { backgroundMaxSeconds, LAUNCH_EXEC_TIMEOUT_MS, launchScript, newTaskId, startedText, taskOutputPath, taskSidPath, } from "../../../background/launch.js";
3
3
  import { KILL_SESSION_TIMEOUT_MS, killSession, SID_RE } from "../../../background/session.js";
4
- import { clip, display, inSandbox, mapSandboxError, noSandboxError, runBudgetNote, runTimeLeftMs, sandboxBaseTimeoutMs, sandboxConversationOf, unavailableWhenNoSandbox, withNotices, } from "./common.js";
4
+ import { clip, display, inSandbox, mapSandboxError, noSandboxError, runBudgetNote, runTimeLeftMs, sandboxBaseTimeoutMs, sandboxConversationOf, shellQuote, unavailableWhenNoSandbox, withNotices, } from "./common.js";
5
5
  import { parseDeviceCode } from "./device-code.js";
6
6
  /** The command timeout in seconds when `timeout` is not given, at most `sandbox.limits.maxCommandSeconds`. */
7
7
  export const BASH_DEFAULT_TIMEOUT_SECONDS = 120;
@@ -208,7 +208,8 @@ async function runInBackground(deps, ctx, input) {
208
208
  let launch;
209
209
  let notices;
210
210
  try {
211
- ({ value: launch, notices } = await inSandbox(deps, ctx, async ({ h, roots, p, signal }) => {
211
+ ({ value: launch, notices } = await inSandbox(deps, ctx, async (s) => {
212
+ const { h, roots, p, signal } = s;
212
213
  workspace = roots.workspace;
213
214
  // right after the launch a process may fork while it is killed: killSession repeats
214
215
  const kill = (sid) => killSession(p, h, sid);
@@ -227,7 +228,9 @@ async function runInBackground(deps, ctx, input) {
227
228
  let r;
228
229
  try {
229
230
  r = await p.exec(h, {
230
- command: launchScript(id, input.command, seconds),
231
+ // the launch keeps its task files under the workspace (`.capybara/tasks`, where
232
+ // TaskOutput and TaskStop find them); the command itself starts in the working root
233
+ command: launchScript(id, inWorkingRoot(input.command, s), seconds),
231
234
  cwd: roots.workspace,
232
235
  timeoutMs: LAUNCH_EXEC_TIMEOUT_MS,
233
236
  maxOutputBytes: LAUNCH_MAX_OUTPUT_BYTES,
@@ -331,6 +334,17 @@ async function runInBackground(deps, ctx, input) {
331
334
  display: display(`后台运行命令:${shown}`, `Started in the background: ${shown}`),
332
335
  };
333
336
  }
337
+ /**
338
+ * A background command's script, started in the conversation's working root: the launch itself
339
+ * runs in the workspace (its task files live under `.capybara/tasks` there), so for a bound
340
+ * project the script first changes into the project's root, and ends (exit 1) without running the
341
+ * command when it cannot.
342
+ */
343
+ function inWorkingRoot(command, s) {
344
+ if (s.workingRoot === s.roots.workspace)
345
+ return command;
346
+ return `cd -- ${shellQuote(s.workingRoot)} || exit 1\n${command}`;
347
+ }
334
348
  /** 内置工具 `Bash`:在本对话的沙箱里执行命令。 */
335
349
  export function sandboxBashTool(deps) {
336
350
  return {
@@ -370,7 +384,8 @@ export function sandboxBashTool(deps) {
370
384
  deviceId = s.deviceId;
371
385
  return s.p.exec(s.h, {
372
386
  command,
373
- cwd: s.roots.workspace,
387
+ // the working root: a bound project's root, else the workspace
388
+ cwd: s.workingRoot,
374
389
  timeoutMs: ms,
375
390
  maxOutputBytes: MAX_OUTPUT_BYTES,
376
391
  signal: s.signal,
@@ -6,7 +6,7 @@ import type { KernelConfig } from "../../../config/schema.js";
6
6
  import type { ChildAgent } from "../../../conversations/agent-tree.js";
7
7
  import type { AttachmentsService } from "../../../conversations/attachments.service.js";
8
8
  import type { EventLog } from "../../../conversations/event-log.js";
9
- import { type ConversationDevices } from "../../../devices/conversation-devices.js";
9
+ import { type ConversationDevices, type WorkingFacts } from "../../../devices/conversation-devices.js";
10
10
  import type { KernelConfigService } from "../../../infra/config/kernel-config.service.js";
11
11
  import type { SandboxMode } from "../../../sandbox/modes.js";
12
12
  import { type HeldProvider, type SandboxService } from "../../../sandbox/sandbox.service.js";
@@ -23,9 +23,10 @@ export interface SandboxToolDeps {
23
23
  /**
24
24
  * The device a call enters: the root conversation's, checked for its owner every call.
25
25
  * `usableNow` (absent in test stubs: only the cloud provider counts) tells a listing whether a
26
- * conversation's device can run without a cloud provider (ruling R8).
26
+ * conversation's device can run without a cloud provider (ruling R8). `workingFacts` (absent
27
+ * in test stubs: free mode) gives what decides the working root, read as the review reads it.
27
28
  */
28
- devices: Pick<ConversationDevices, "forTool"> & Partial<Pick<ConversationDevices, "usableNow" | "modeLevel">>;
29
+ devices: Pick<ConversationDevices, "forTool"> & Partial<Pick<ConversationDevices, "usableNow" | "modeLevel" | "workingFacts">>;
29
30
  /** Background `Bash` tasks; absent in test stubs, where `run_in_background` is refused. */
30
31
  background?: Pick<BackgroundTaskStore, "reserve" | "markStarted" | "failLaunch" | "finishStoppedLaunch" | "releaseStop" | "get" | "advanceOffset" | "runningOwnedBy" | "finishedOwnedBy">;
31
32
  /**
@@ -69,11 +70,20 @@ export interface SandboxSession {
69
70
  h: SandboxHandle;
70
71
  /** The instance's roots: every path the call builds or checks is under one of them. */
71
72
  roots: SandboxRoots;
73
+ /**
74
+ * The conversation's working root ({@link workingRootOf}): the bound project's root, else
75
+ * `roots.workspace`. `Bash` runs here, `Glob` / `Grep` search here by default and a relative
76
+ * file-tool path resolves against it; it never changes what {@link checkToolPath} accepts.
77
+ */
78
+ workingRoot: string;
72
79
  p: HeldProvider;
73
80
  signal: AbortSignal;
74
81
  }
75
- /** This conversation's first use of its device (in the instance's workspace). */
76
- export declare const sandboxStartedNotice: (roots: SandboxRoots) => string;
82
+ /**
83
+ * This conversation's first use of its device. The working directory is the instance's workspace,
84
+ * or a bound project's root (`workingRoot`, project root spec §4.3).
85
+ */
86
+ export declare const sandboxStartedNotice: (roots: SandboxRoots, workingRoot?: string) => string;
77
87
  /** {@link sandboxStartedNotice} of an instance with the default roots. */
78
88
  export declare const SANDBOX_STARTED_NOTICE: string;
79
89
  /** A new instance came up on the device's kept files. */
@@ -180,8 +190,21 @@ export declare function checkPath(path: string, roots: SandboxRoots, field?: str
180
190
  * outside the workspace); sandbox mode keeps the roots ({@link checkPath}).
181
191
  */
182
192
  export declare function checkToolPath(path: string, s: Pick<SandboxSession, "roots" | "mode">, field?: string): string;
193
+ /**
194
+ * The shape checks of a file tool's path before the call enters its device: an absolute path gets
195
+ * {@link checkPathShape}; a relative one (resolved against the working root inside,
196
+ * {@link resolveToolPath}) must not start with `~` (never expanded) and must pass the same shape
197
+ * checks (no control characters, no empty or `..` segments).
198
+ */
199
+ export declare function checkFilePathShape(path: string, field?: string): void;
200
+ /**
201
+ * A file tool's path made absolute: a relative path (shape-checked by {@link checkFilePathShape})
202
+ * resolves against the session's working root, `.` segments dropped; an absolute one is kept.
203
+ * The result still goes through {@link checkToolPath}.
204
+ */
205
+ export declare function resolveToolPath(path: string, s: Pick<SandboxSession, "workingRoot">): string;
183
206
  /** {@link checkToolPath} for a writing tool: the skills directory stays read-only in both modes. */
184
- export declare function checkToolWritable(path: string, s: Pick<SandboxSession, "roots" | "mode">): string;
207
+ export declare function checkToolWritable(path: string, s: Pick<SandboxSession, "roots" | "mode" | "workingRoot">): string;
185
208
  /** POSIX shell 单引号转义。 */
186
209
  export declare function shellQuote(s: string): string;
187
210
  /**
@@ -215,6 +238,13 @@ export declare function inSandbox<T>(deps: SandboxToolDeps, ctx: BuiltinCallCont
215
238
  value: T;
216
239
  notices: string[];
217
240
  }>;
241
+ /**
242
+ * The working root of a call: the project root exactly as the review decides it (from the same
243
+ * {@link WorkingFacts}); when that falls back to the device's workspace, the held instance's own
244
+ * workspace (`workspace`), where the call really runs. Every session built outside `inSandbox` (a
245
+ * person's project skill invocation) takes its working root from here too.
246
+ */
247
+ export declare function sessionWorkingRoot(working: WorkingFacts | null, mode: SandboxMode, workspace: string): string;
218
248
  /** The conversation whose device a call uses (the root conversation's for a sub-agent). */
219
249
  export declare const sandboxConversationOf: (ctx: BuiltinCallContext) => string;
220
250
  /**
@@ -1,5 +1,6 @@
1
1
  import { DEFAULT_SANDBOX_ROOTS, DeviceProtocolError, isFileSystemGoneError, isSandboxGoneError, ToolError, validateSandboxPath, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
2
  import { ANONYMOUS_NO_DEVICE, } from "../../../devices/conversation-devices.js";
3
+ import { workingRootOf } from "../../../devices/working-root.js";
3
4
  import { ApiError } from "../../../errors.js";
4
5
  import { AUTO_MODE_NOT_ALLOWED_TEXT } from "../../../local-devices/local-device-provider.js";
5
6
  import { devicePathsChange } from "../../../runtime/context/device-paths.js";
@@ -7,8 +8,13 @@ import { SandboxPathBusyError } from "../../../sandbox/leases.js";
7
8
  import { SandboxLockLostError, } from "../../../sandbox/sandbox.service.js";
8
9
  import { SandboxProviderUnreachableError } from "../../../sandbox/unreachable.js";
9
10
  // ---- 模型可见文案(英文) ----
10
- /** This conversation's first use of its device (in the instance's workspace). */
11
- export const sandboxStartedNotice = (roots) => `Device started (first use in this conversation); the working directory is ${roots.workspace}, shared with the device's other conversations.`;
11
+ /**
12
+ * This conversation's first use of its device. The working directory is the instance's workspace,
13
+ * or a bound project's root (`workingRoot`, project root spec §4.3).
14
+ */
15
+ export const sandboxStartedNotice = (roots, workingRoot = roots.workspace) => workingRoot === roots.workspace
16
+ ? `Device started (first use in this conversation); the working directory is ${roots.workspace}, shared with the device's other conversations.`
17
+ : `Device started (first use in this conversation); the working directory is ${workingRoot}, the project's root, on a device shared with other conversations.`;
12
18
  /** {@link sandboxStartedNotice} of an instance with the default roots. */
13
19
  export const SANDBOX_STARTED_NOTICE = sandboxStartedNotice(DEFAULT_SANDBOX_ROOTS);
14
20
  /** A new instance came up on the device's kept files. */
@@ -162,9 +168,42 @@ export function checkToolPath(path, s, field = "path") {
162
168
  checkPathShape(path, field);
163
169
  return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
164
170
  }
171
+ /**
172
+ * The shape checks of a file tool's path before the call enters its device: an absolute path gets
173
+ * {@link checkPathShape}; a relative one (resolved against the working root inside,
174
+ * {@link resolveToolPath}) must not start with `~` (never expanded) and must pass the same shape
175
+ * checks (no control characters, no empty or `..` segments).
176
+ */
177
+ export function checkFilePathShape(path, field = "file_path") {
178
+ if (path.startsWith("/")) {
179
+ checkPathShape(path, field);
180
+ return;
181
+ }
182
+ const errors = path.startsWith("~")
183
+ ? ["~ is not expanded"]
184
+ : path === "" || path === "."
185
+ ? ["path must name a file"]
186
+ : validateSandboxPathShape(`/${path}`);
187
+ if (errors.length > 0) {
188
+ throw new ToolError(`Invalid ${field} "${clip(path, 200)}": ${errors.join("; ")}. Pass an absolute path, or a path relative to the working directory without '..' segments.`);
189
+ }
190
+ }
191
+ /**
192
+ * A file tool's path made absolute: a relative path (shape-checked by {@link checkFilePathShape})
193
+ * resolves against the session's working root, `.` segments dropped; an absolute one is kept.
194
+ * The result still goes through {@link checkToolPath}.
195
+ */
196
+ export function resolveToolPath(path, s) {
197
+ if (path.startsWith("/"))
198
+ return path;
199
+ const segments = path.split("/").filter((seg) => seg !== "" && seg !== ".");
200
+ if (segments.length === 0)
201
+ return s.workingRoot;
202
+ return `${s.workingRoot === "/" ? "" : s.workingRoot}/${segments.join("/")}`;
203
+ }
165
204
  /** {@link checkToolPath} for a writing tool: the skills directory stays read-only in both modes. */
166
205
  export function checkToolWritable(path, s) {
167
- const p = checkToolPath(path, s, "file_path");
206
+ const p = checkToolPath(resolveToolPath(path, s), s, "file_path");
168
207
  if (p === s.roots.skills || p.startsWith(`${s.roots.skills}/`)) {
169
208
  const where = s.mode === "auto"
170
209
  ? "pass another path instead"
@@ -402,8 +441,16 @@ export function mapSandboxError(e, log) {
402
441
  export async function inSandbox(deps, ctx, fn) {
403
442
  try {
404
443
  const deviceId = await deps.devices.forTool(ctx.orgId, sandboxConversationOf(ctx));
405
- // the mode once per call: the path checks follow it and the device_paths event records it
406
- const level = (await deps.devices.modeLevel?.(ctx.orgId, deviceId)) ?? null;
444
+ // the mode once per call: the path checks follow it and the device_paths event records it;
445
+ // the working facts (workspace, home, project snapshot) are read as the review reads them
446
+ // a call the review covered runs in the working root it was reviewed against: never read again
447
+ const reviewed = ctx.reviewedWorkingRoot;
448
+ const [level, working] = await Promise.all([
449
+ deps.devices.modeLevel?.(ctx.orgId, deviceId) ?? null,
450
+ reviewed !== undefined
451
+ ? null
452
+ : (deps.devices.workingFacts?.(ctx.orgId, sandboxConversationOf(ctx), ctx.conversationId, deviceId) ?? null),
453
+ ]);
407
454
  return await deps.sandbox.withSandbox({
408
455
  orgId: ctx.orgId,
409
456
  deviceId,
@@ -417,22 +464,24 @@ export async function inSandbox(deps, ctx, fn) {
417
464
  },
418
465
  }, async (h, p, info, signal) => {
419
466
  // unknown mode: the strict (sandbox) path checks stay (fail closed)
467
+ const mode = level?.mode ?? "sandbox";
420
468
  const s = {
421
469
  deviceId,
422
- mode: level?.mode ?? "sandbox",
470
+ mode,
423
471
  h,
424
472
  roots: info.roots,
473
+ workingRoot: reviewed ?? sessionWorkingRoot(working, mode, info.roots.workspace),
425
474
  p,
426
475
  signal,
427
476
  };
428
- await recordDevicePaths(deps, ctx, info.roots, level);
477
+ await recordDevicePaths(deps, ctx, info.roots, level ?? null);
429
478
  const notices = [];
430
479
  if (info.filesReset)
431
480
  notices.push(sandboxFilesResetNotice(info.roots));
432
481
  else if (info.restarted)
433
482
  notices.push(SANDBOX_RESTARTED_NOTICE);
434
483
  else if (info.fresh)
435
- notices.push(sandboxStartedNotice(info.roots));
484
+ notices.push(sandboxStartedNotice(info.roots, s.workingRoot));
436
485
  const { copied, failures } = await syncAttachments(deps, ctx, s);
437
486
  if (copied.length > 0) {
438
487
  notices.push(`Attachments copied into the sandbox: ${copied.join(", ")}.`);
@@ -461,6 +510,18 @@ async function recordDevicePaths(deps, ctx, roots, level) {
461
510
  if (change)
462
511
  await deps.eventLog.append(ctx.conversationId, [change]);
463
512
  }
513
+ /**
514
+ * The working root of a call: the project root exactly as the review decides it (from the same
515
+ * {@link WorkingFacts}); when that falls back to the device's workspace, the held instance's own
516
+ * workspace (`workspace`), where the call really runs. Every session built outside `inSandbox` (a
517
+ * person's project skill invocation) takes its working root from here too.
518
+ */
519
+ export function sessionWorkingRoot(working, mode, workspace) {
520
+ if (working === null)
521
+ return workspace;
522
+ const root = workingRootOf(working.project, { mode, ...working });
523
+ return root === working.workspace ? workspace : root;
524
+ }
464
525
  /** The conversation whose device a call uses (the root conversation's for a sub-agent). */
465
526
  export const sandboxConversationOf = (ctx) => ctx.sandboxConversationId ?? ctx.conversationId;
466
527
  /**
@@ -1,6 +1,6 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { lineDiff, viewPath } from "../../view.js";
3
- import { checkPathShape, checkToolWritable, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, withPathLease, } from "./common.js";
3
+ import { checkFilePathShape, checkToolWritable, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, withPathLease, } from "./common.js";
4
4
  import { assertReadAndUnchanged, FileGuardError, fileStateOf, guardResult, keepGuardRefusal, normalizeSandboxPath, recordedFile, } from "./file-state.js";
5
5
  import { READ_MAX_BYTES } from "./read.js";
6
6
  /** 可编辑的最大文件(字节):更大的用 Bash 处理。 */
@@ -56,7 +56,7 @@ export function sandboxEditTool(deps) {
56
56
  const { old_string, new_string, replace_all = false } = input;
57
57
  if (old_string === new_string)
58
58
  throw new ToolError(SAME_TEXT);
59
- checkPathShape(input.file_path, "file_path");
59
+ checkFilePathShape(input.file_path);
60
60
  let path = "";
61
61
  // a read-before-write refusal is the guard working: a result with the guard view
62
62
  const ran = await inSandbox(deps, ctx, (s) => {
@@ -64,10 +64,11 @@ export function sandboxGlobTool(deps) {
64
64
  let dir = "";
65
65
  const { value: files, notices } = await inSandbox(deps, ctx, async (s) => {
66
66
  const { h, p, signal } = s;
67
- dir = checkToolPath(input.path ?? s.roots.workspace, s);
67
+ // default: the working root (a bound project's root, else the workspace)
68
+ dir = checkToolPath(input.path ?? s.workingRoot, s);
68
69
  const st = await p.stat(h, dir, signal);
69
70
  if (!st?.isDir)
70
- throw new ToolError(notDirectory(dir, s.roots.workspace));
71
+ throw new ToolError(notDirectory(dir, s.workingRoot));
71
72
  const r = await p.exec(h, {
72
73
  command: "find . -type f -print0",
73
74
  cwd: dir,
@@ -165,7 +165,8 @@ export function sandboxGrepTool(deps) {
165
165
  let path = "";
166
166
  const { value, notices } = await inSandbox(deps, ctx, async (s) => {
167
167
  const { h, p, signal } = s;
168
- path = checkToolPath(g.path ?? s.roots.workspace, s);
168
+ // default: the working root (a bound project's root, else the workspace)
169
+ path = checkToolPath(g.path ?? s.workingRoot, s);
169
170
  const st = await p.stat(h, path, signal);
170
171
  if (st === null)
171
172
  throw new ToolError(notFound(path));
@@ -1,6 +1,6 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { viewPath } from "../../view.js";
3
- import { checkPathShape, checkToolPath, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, } from "./common.js";
3
+ import { checkFilePathShape, checkToolPath, clip, display, inSandbox, looksBinary, resolveToolPath, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, } from "./common.js";
4
4
  import { normalizeSandboxPath, recordedFile } from "./file-state.js";
5
5
  /** 不给 `limit` 时一次读的行数。 */
6
6
  const DEFAULT_LIMIT = 2000;
@@ -83,11 +83,11 @@ export function sandboxReadTool(deps) {
83
83
  timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
84
84
  async run(input, ctx) {
85
85
  const { offset = 1, limit = DEFAULT_LIMIT } = input;
86
- checkPathShape(input.file_path, "file_path");
86
+ checkFilePathShape(input.file_path);
87
87
  let path = "";
88
88
  const { value, notices } = await inSandbox(deps, ctx, async (s) => {
89
89
  const { h, p, signal } = s;
90
- path = checkToolPath(input.file_path, s, "file_path");
90
+ path = checkToolPath(resolveToolPath(input.file_path, s), s, "file_path");
91
91
  const st = await p.stat(h, path, signal);
92
92
  if (st === null)
93
93
  throw new ToolError(notFound(path));
@@ -1,6 +1,6 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { lineDiff, TOOL_VIEW_DIFF_MAX_BYTES, viewPath } from "../../view.js";
3
- import { checkPathShape, checkToolWritable, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, withPathLease, } from "./common.js";
3
+ import { checkFilePathShape, checkToolWritable, clip, display, inSandbox, looksBinary, sandboxBaseTimeoutMs, unavailableWhenNoSandbox, withNotices, withPathLease, } from "./common.js";
4
4
  import { assertReadAndUnchanged, FileGuardError, fileStateOf, guardResult, keepGuardRefusal, normalizeSandboxPath, recordedFile, } from "./file-state.js";
5
5
  import { READ_MAX_BYTES } from "./read.js";
6
6
  const SPEC = {
@@ -44,7 +44,7 @@ export function sandboxWriteTool(deps) {
44
44
  timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
45
45
  async run(input, ctx) {
46
46
  const data = new TextEncoder().encode(input.content);
47
- checkPathShape(input.file_path, "file_path");
47
+ checkFilePathShape(input.file_path);
48
48
  let path = "";
49
49
  // a read-before-write refusal is the guard working: a result with the guard view
50
50
  const ran = await inSandbox(deps, ctx, (s) => {
@@ -1,9 +1,9 @@
1
- import { type ObjectStore } from "@capybara-hq/plugin-sdk";
1
+ import { type ObjectStore, skillInvocation } from "@capybara-hq/plugin-sdk";
2
2
  import type { EventLog } from "../../conversations/event-log.js";
3
3
  import type { KernelSchemaDb, SkillManifest } from "../../db/kernel-schema.js";
4
4
  import { type CatalogSkill } from "../../runtime/context/skills.js";
5
5
  import type { BuiltinCallContext, BuiltinTool } from "../registry.js";
6
- import { type SandboxToolDeps } from "./sandbox/common.js";
6
+ import { type SandboxSession, type SandboxToolDeps } from "./sandbox/common.js";
7
7
  /**
8
8
  * Builtin tool `Skill` (M5 T14, ruling M17): resolves the name against the latest skills catalog
9
9
  * snapshot in the log to an id and version, and returns that version's SKILL.md body and file list
@@ -60,5 +60,50 @@ export declare function findSkillVersion(db: KernelSchemaDb, ctx: Pick<BuiltinCa
60
60
  manifest: SkillManifest;
61
61
  object_prefix: string;
62
62
  } | undefined>;
63
+ /** A digest of the right shape for the renderer; only inside the sentinel directory. */
64
+ export declare const PROJECT_DIR_DIGEST = "000000000000";
65
+ /** Why a project skill's SKILL.md could not be used (each caller phrases it for its reader). */
66
+ export type ProjectSkillProblem = {
67
+ kind: "outside_mode";
68
+ path: string;
69
+ mode: string;
70
+ } | {
71
+ kind: "gone";
72
+ path: string;
73
+ } | {
74
+ kind: "read_failed";
75
+ path: string;
76
+ why: string;
77
+ } | {
78
+ kind: "invalid";
79
+ path: string;
80
+ why: string;
81
+ };
82
+ /** {@link readProjectSkill}'s refusal: the problem, for the model's or the person's text. */
83
+ export declare class ProjectSkillReadError extends Error {
84
+ readonly problem: ProjectSkillProblem;
85
+ constructor(problem: ProjectSkillProblem);
86
+ }
87
+ /** A project skill's SKILL.md as read on the device. */
88
+ export interface ProjectSkillFile {
89
+ /** The skill's directory on the device (`${CLAUDE_SKILL_DIR}`). */
90
+ dir: string;
91
+ /** Its SKILL.md. */
92
+ path: string;
93
+ /** The body after the frontmatter, trimmed. */
94
+ body: string;
95
+ invocation: ReturnType<typeof skillInvocation>;
96
+ /** The file was cut at {@link SKILL_MD_MAX_BYTES}. */
97
+ truncated: boolean;
98
+ }
99
+ /**
100
+ * Reads `<root>/.agents/skills/<name>/SKILL.md` in `s` (the device's mode now, as `Read` checks a
101
+ * path: a mode narrowed since the run start reads nothing) and parses it; its name must be its
102
+ * directory's. Shared by `Skill` and a person's invocation (`SkillInvoker`), so both read a
103
+ * project skill the same way. A problem with the file or its path throws
104
+ * {@link ProjectSkillReadError}; the sandbox's own failures (offline, lost files, ...) and an abort
105
+ * are rethrown as they are.
106
+ */
107
+ export declare function readProjectSkill(s: SandboxSession, root: string, bare: string, signal?: AbortSignal): Promise<ProjectSkillFile>;
63
108
  /** 内置工具 `Skill`(见文件头)。 */
64
109
  export declare function skillLoadTool(deps: SkillLoadDeps): BuiltinTool;
@@ -1,15 +1,17 @@
1
1
  import { createHash } from "node:crypto";
2
- import { parseSkillMd, renderSkillBody, SKILL_ENTRY_FILE, SKILL_INVOCATION_LIMITS, SKILLS_SANDBOX_ROOT, skillDigest, skillSandboxDir, skillSandboxPath, ToolError, } from "@capybara-hq/plugin-sdk";
2
+ import { parseSkillMd, renderSkillBody, SKILL_ENTRY_FILE, SKILL_INVOCATION_LIMITS, SKILLS_SANDBOX_ROOT, skillDigest, skillInvocation, skillSandboxDir, skillSandboxPath, ToolError, } from "@capybara-hq/plugin-sdk";
3
3
  import { sql } from "kysely";
4
4
  import { normalizeStoredDefinition } from "../../agents/definition.js";
5
5
  import { ApiError } from "../../errors.js";
6
+ import { callableProjectSkills, projectSkillName, projectSkillOf, } from "../../runtime/context/project-root.js";
6
7
  import { latestInvocation } from "../../runtime/context/skills.js";
8
+ import { PROJECT_SKILLS_DIR, SKILL_MD_MAX_BYTES } from "../../runtime/project/knowledge.js";
7
9
  import { dispatchOfChildRun } from "../../runtime/subagents/child.js";
8
10
  import { resolveSkillForkType } from "../../runtime/subagents/roster.js";
9
11
  import { invocationOf, resolveSkills } from "../../skills/catalog.js";
10
12
  import { PLATFORM_SOURCE, skillFileStore } from "../../skills/usable.js";
11
13
  import { AGENT_TOOL, SANDBOX_TOOL_NAMES } from "../builtin-names.js";
12
- import { clip, display, inSandbox, sandboxBaseTimeoutMs, sandboxConversationOf, sandboxUsable, withNotices, withPathLease, } from "./sandbox/common.js";
14
+ import { checkToolPath, clip, display, inSandbox, mapSandboxError, sandboxBaseTimeoutMs, sandboxConversationOf, sandboxUsable, withNotices, withPathLease, } from "./sandbox/common.js";
13
15
  /**
14
16
  * Builtin tool `Skill` (M5 T14, ruling M17): resolves the name against the latest skills catalog
15
17
  * snapshot in the log to an id and version, and returns that version's SKILL.md body and file list
@@ -378,6 +380,158 @@ async function forkLine(db, ctx, fork, plugin) {
378
380
  const type = await resolveSkillForkType(db, ctx.orgId, agent.definition, fork.agent, plugin);
379
381
  return type.inRoster ? forkAvailableText(type.agentType) : FORK_UNAVAILABLE_TEXT;
380
382
  }
383
+ // ---- project skills (project root spec §4.5) ----
384
+ /** Stands in for the skills root while a project skill renders, then becomes its directory. */
385
+ const PROJECT_DIR_SENTINEL = "\u0000project-skill-root";
386
+ /** A digest of the right shape for the renderer; only inside the sentinel directory. */
387
+ export const PROJECT_DIR_DIGEST = "000000000000";
388
+ const NO_PROJECT_TEXT = (asked) => `Skill "${clip(asked, 80)}" is a project skill, but this conversation has no project; call Skill with a name from the skills list instead.`;
389
+ const projectUnavailableText = (asked, message) => `Skill "${clip(asked, 80)}" cannot be loaded: the project is not available this run. ${message} Call Skill only with names from the skills list, or do the task without the project's skills.`;
390
+ const notInProject = (asked, project, names) => {
391
+ const shown = names.slice(0, MAX_LISTED_NAMES);
392
+ const more = names.length > shown.length ? ", …" : "";
393
+ return `Skill "${clip(asked, 80)}" is not one of the skills of the project "${project}"; call Skill with one of the project's skills (${shown.length === 0 ? "it lists none" : `${shown.join(", ")}${more}`}).`;
394
+ };
395
+ const projectOutsideModeText = (asked, path, mode) => `Skill "${asked}" cannot be loaded: ${path} is outside what the device can read in ${mode} mode now. Ask the user to switch the device to auto mode, or do the task without the skill.`;
396
+ const projectFileGoneText = (asked, path) => `Skill "${asked}" cannot be loaded: ${path} is no longer on the device. Check the project's .agents/skills directory with Glob or Read, or do the task without the skill.`;
397
+ const projectReadFailedText = (asked, path, why) => `Skill "${asked}" cannot be loaded: reading ${path} on the device failed (${clip(why, 300)}). Retry once; if it fails again, do the task without the skill.`;
398
+ const projectParseText = (asked, path, why) => `Skill "${asked}" cannot be loaded: ${path} is not a valid SKILL.md (${clip(why, 300)}). Ask the user to fix it, or do the task without the skill.`;
399
+ /** {@link readProjectSkill}'s refusal: the problem, for the model's or the person's text. */
400
+ export class ProjectSkillReadError extends Error {
401
+ problem;
402
+ constructor(problem) {
403
+ super(`project skill ${problem.kind}: ${problem.path}`);
404
+ this.problem = problem;
405
+ }
406
+ }
407
+ /**
408
+ * Reads `<root>/.agents/skills/<name>/SKILL.md` in `s` (the device's mode now, as `Read` checks a
409
+ * path: a mode narrowed since the run start reads nothing) and parses it; its name must be its
410
+ * directory's. Shared by `Skill` and a person's invocation (`SkillInvoker`), so both read a
411
+ * project skill the same way. A problem with the file or its path throws
412
+ * {@link ProjectSkillReadError}; the sandbox's own failures (offline, lost files, ...) and an abort
413
+ * are rethrown as they are.
414
+ */
415
+ export async function readProjectSkill(s, root, bare, signal = s.signal) {
416
+ const dir = `${root}/${PROJECT_SKILLS_DIR}/${bare}`;
417
+ const path = `${dir}/${SKILL_ENTRY_FILE}`;
418
+ try {
419
+ checkToolPath(path, s);
420
+ }
421
+ catch (e) {
422
+ if (!(e instanceof ToolError))
423
+ throw e;
424
+ throw new ProjectSkillReadError({ kind: "outside_mode", path, mode: s.mode });
425
+ }
426
+ let read;
427
+ try {
428
+ read = await s.p.readFile(s.h, path, { maxBytes: SKILL_MD_MAX_BYTES, signal: s.signal });
429
+ }
430
+ catch (e) {
431
+ if (mapSandboxError(e, undefined) !== e || signal.aborted || s.signal.aborted)
432
+ throw e;
433
+ throw new ProjectSkillReadError({
434
+ kind: "read_failed",
435
+ path,
436
+ why: e instanceof Error ? e.message : String(e),
437
+ });
438
+ }
439
+ if (read === null)
440
+ throw new ProjectSkillReadError({ kind: "gone", path });
441
+ let parsed;
442
+ try {
443
+ parsed = parseSkillMd(new TextDecoder("utf-8", { fatal: true }).decode(read.data), {
444
+ invocationKeys: false,
445
+ });
446
+ }
447
+ catch {
448
+ throw new ProjectSkillReadError({ kind: "invalid", path, why: "it is not UTF-8 text" });
449
+ }
450
+ if ("errors" in parsed) {
451
+ throw new ProjectSkillReadError({ kind: "invalid", path, why: parsed.errors.join("; ") });
452
+ }
453
+ if (parsed.name !== bare) {
454
+ throw new ProjectSkillReadError({
455
+ kind: "invalid",
456
+ path,
457
+ why: `its name "${clip(parsed.name, 80)}" is not its directory's`,
458
+ });
459
+ }
460
+ return {
461
+ dir,
462
+ path,
463
+ body: parsed.body.trim(),
464
+ invocation: skillInvocation(parsed.frontmatter),
465
+ truncated: read.truncated,
466
+ };
467
+ }
468
+ /** The model's text for a {@link ProjectSkillProblem} of `Skill`. */
469
+ function projectProblemText(asked, p) {
470
+ switch (p.kind) {
471
+ case "outside_mode":
472
+ return projectOutsideModeText(asked, p.path, p.mode);
473
+ case "gone":
474
+ return projectFileGoneText(asked, p.path);
475
+ case "read_failed":
476
+ return projectReadFailedText(asked, p.path, p.why);
477
+ case "invalid":
478
+ return projectParseText(asked, p.path, p.why);
479
+ }
480
+ }
481
+ /**
482
+ * `Skill` for `project:<name>`: resolved from the latest `project_root` of the calling
483
+ * conversation (a sub-agent's is the copy of its root's its run start recorded), then
484
+ * `<root>/.agents/skills/<name>/SKILL.md` is read through the conversation's device
485
+ * ({@link readProjectSkill}) and its body rendered (args, `${CLAUDE_SKILL_DIR}` = the skill's
486
+ * directory on the device). Nothing is copied: the skill's other files are already in the project.
487
+ * The result is an ordinary tool result in the log, so a replay renders it as recorded and never
488
+ * reads the device.
489
+ */
490
+ async function loadProjectSkill(deps, ctx, asked, bare, args) {
491
+ // the caller's own log: a sub-agent's run start copied its root's snapshot there, so what the
492
+ // child was shown is what it can load (the working root still follows the root conversation)
493
+ const latest = await deps.eventLog.latestOfType(ctx.conversationId, "project_root");
494
+ if (latest?.type !== "project_root")
495
+ throw new ToolError(NO_PROJECT_TEXT(asked));
496
+ const project = latest.payload;
497
+ if (project.unavailable !== undefined) {
498
+ throw new ToolError(projectUnavailableText(asked, project.unavailable.message));
499
+ }
500
+ const skills = callableProjectSkills(project);
501
+ if (!skills.some((s) => s.name === bare)) {
502
+ throw new ToolError(notInProject(asked, project.project, skills.map((s) => projectSkillName(s.name))));
503
+ }
504
+ const r = await inSandbox(deps, ctx, async (s) => {
505
+ try {
506
+ return await readProjectSkill(s, project.root, bare, ctx.signal);
507
+ }
508
+ catch (e) {
509
+ if (e instanceof ProjectSkillReadError) {
510
+ throw new ToolError(projectProblemText(asked, e.problem));
511
+ }
512
+ throw e;
513
+ }
514
+ });
515
+ const file = r.value;
516
+ let instructions;
517
+ try {
518
+ instructions = renderSkillBody(file.body, file.invocation, args ?? "", bare, PROJECT_DIR_DIGEST, PROJECT_DIR_SENTINEL).replaceAll(skillSandboxDir(bare, PROJECT_DIR_DIGEST, PROJECT_DIR_SENTINEL), file.dir);
519
+ }
520
+ catch (e) {
521
+ if (!(e instanceof RangeError))
522
+ throw e;
523
+ throw new ToolError(`Skill "${asked}" cannot be rendered: ${e.message}; check the args against the skill's placeholders and retry with shorter args.`);
524
+ }
525
+ const text = [
526
+ `Loaded project skill "${asked}" from ${file.path}${file.truncated ? " (cut at 1 MiB)" : ""}.`,
527
+ `Its other files, if any, are in ${file.dir}/ on the device; use them there.`,
528
+ `<skill name="${asked}">\n${instructions}\n</skill>`,
529
+ ].join("\n\n");
530
+ return {
531
+ content: [{ type: "text", text: withNotices(r.notices, text) }],
532
+ display: display(`加载项目技能 ${asked}`, `Loaded project skill ${asked}`),
533
+ };
534
+ }
381
535
  /** 内置工具 `Skill`(见文件头)。 */
382
536
  export function skillLoadTool(deps) {
383
537
  return {
@@ -387,6 +541,10 @@ export function skillLoadTool(deps) {
387
541
  timeoutMs: () => sandboxBaseTimeoutMs(deps.config.get()),
388
542
  async run(input, ctx) {
389
543
  const { skill: asked, args } = input;
544
+ // project root spec §4.5: the prefix is the project's, never a plugin's qualified name
545
+ const bare = projectSkillOf(asked);
546
+ if (bare !== undefined)
547
+ return loadProjectSkill(deps, ctx, asked, bare, args);
390
548
  const snap = await deps.eventLog.latestOfType(ctx.conversationId, "skills_catalog");
391
549
  const skills = snap?.payload.skills ?? [];
392
550
  let entry = findEntry(skills, asked);
@@ -426,7 +426,7 @@ export declare class ToolPipeline {
426
426
  * 带 `tools.timeoutMs` 超时与 run 的中止信号(合并后传给处理函数 / 连接器,不响应信号的也按时结束)。
427
427
  * 熔断只作用于连接器工具(键为组织 × 连接器)。
428
428
  */
429
- execute(tool: ResolvedTool, input: unknown, ctx: ToolStepContext, callId: string, resume?: ToolResume, stepTools?: readonly ResolvedTool[]): Promise<ExecOutcome>;
429
+ execute(tool: ResolvedTool, input: unknown, ctx: ToolStepContext, callId: string, resume?: ToolResume, stepTools?: readonly ResolvedTool[], reviewedWorkingRoot?: string): Promise<ExecOutcome>;
430
430
  private executeConnector;
431
431
  /** 抛出的错误 → 给模型的结果:ToolError 的消息原样(插件约定为英文、可操作),其他只给错误类名。 */
432
432
  private thrown;