@capybara-hq/kernel 0.1.0-rc.31 → 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 (104) 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/ctx/create-ctx.d.ts +26 -4
  15. package/dist/ctx/create-ctx.js +54 -34
  16. package/dist/db/kernel-schema.d.ts +20 -0
  17. package/dist/devices/conversation-devices.d.ts +57 -3
  18. package/dist/devices/conversation-devices.js +63 -11
  19. package/dist/devices/device-projects.service.d.ts +162 -0
  20. package/dist/devices/device-projects.service.js +503 -0
  21. package/dist/devices/devices.controller.d.ts +15 -2
  22. package/dist/devices/devices.controller.js +60 -3
  23. package/dist/devices/devices.module.js +15 -2
  24. package/dist/devices/devices.schemas.js +9 -1
  25. package/dist/devices/dto.d.ts +31 -0
  26. package/dist/devices/dto.js +38 -1
  27. package/dist/devices/working-root.d.ts +41 -0
  28. package/dist/devices/working-root.js +50 -0
  29. package/dist/errors.d.ts +39 -0
  30. package/dist/errors.js +39 -0
  31. package/dist/evals/run-replay.d.ts +9 -1
  32. package/dist/evals/run-replay.js +15 -1
  33. package/dist/extensions/permission-set.d.ts +7 -6
  34. package/dist/extensions/permission-set.js +9 -6
  35. package/dist/extensions/permission-view.d.ts +4 -4
  36. package/dist/extensions/permission-view.js +10 -5
  37. package/dist/http/app.d.ts +8 -2
  38. package/dist/http/app.js +12 -2
  39. package/dist/http/plugin-dispatch.d.ts +55 -18
  40. package/dist/http/plugin-dispatch.js +124 -29
  41. package/dist/http/plugin-route-access.d.ts +56 -0
  42. package/dist/http/plugin-route-access.js +192 -0
  43. package/dist/identity/auth.guard.d.ts +26 -12
  44. package/dist/identity/auth.guard.js +62 -33
  45. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  46. package/dist/infra/throttler/named-throttlers.js +16 -0
  47. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  48. package/dist/infra/throttler/throttler.guard.js +2 -1
  49. package/dist/kernel.module.js +3 -0
  50. package/dist/local-devices/local-device-provider.d.ts +37 -1
  51. package/dist/local-devices/local-device-provider.js +33 -0
  52. package/dist/local-devices/machines.d.ts +2 -1
  53. package/dist/local-devices/machines.js +4 -1
  54. package/dist/local-devices/policy-summary.js +1 -0
  55. package/dist/local-devices/relay.d.ts +2 -0
  56. package/dist/local-devices/relay.js +3 -1
  57. package/dist/local-devices/targets.d.ts +6 -1
  58. package/dist/local-devices/targets.js +14 -0
  59. package/dist/overrides.d.ts +7 -0
  60. package/dist/overrides.js +4 -0
  61. package/dist/platform/ops/agent-skills.ops.js +2 -1
  62. package/dist/platform/ops/devices.ops.d.ts +3 -1
  63. package/dist/platform/ops/devices.ops.js +136 -3
  64. package/dist/runtime/context/build.d.ts +3 -0
  65. package/dist/runtime/context/build.js +14 -0
  66. package/dist/runtime/context/compaction.js +2 -0
  67. package/dist/runtime/context/project-root.d.ts +43 -0
  68. package/dist/runtime/context/project-root.js +85 -0
  69. package/dist/runtime/model-call.js +25 -1
  70. package/dist/runtime/project/knowledge.d.ts +129 -0
  71. package/dist/runtime/project/knowledge.js +248 -0
  72. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  73. package/dist/runtime/project/knowledge.service.js +288 -0
  74. package/dist/runtime/run-worker.d.ts +5 -0
  75. package/dist/runtime/run-worker.js +27 -6
  76. package/dist/runtime/runtime.module.js +7 -0
  77. package/dist/sandbox/review/review.service.d.ts +14 -2
  78. package/dist/sandbox/review/review.service.js +2 -0
  79. package/dist/sandbox/review/rules.d.ts +6 -4
  80. package/dist/sandbox/review/rules.js +185 -62
  81. package/dist/sandbox/review/types.d.ts +14 -0
  82. package/dist/sandbox/sandbox.service.d.ts +16 -1
  83. package/dist/sandbox/sandbox.service.js +75 -3
  84. package/dist/skills/catalog.d.ts +6 -1
  85. package/dist/skills/catalog.js +18 -4
  86. package/dist/skills/invoke.d.ts +64 -2
  87. package/dist/skills/invoke.js +214 -6
  88. package/dist/skills/skills.module.js +5 -0
  89. package/dist/tools/approvals.service.d.ts +6 -0
  90. package/dist/tools/builtins/sandbox/bash.js +19 -4
  91. package/dist/tools/builtins/sandbox/common.d.ts +36 -6
  92. package/dist/tools/builtins/sandbox/common.js +69 -8
  93. package/dist/tools/builtins/sandbox/edit.js +2 -2
  94. package/dist/tools/builtins/sandbox/glob.js +3 -2
  95. package/dist/tools/builtins/sandbox/grep.js +2 -1
  96. package/dist/tools/builtins/sandbox/read.js +3 -3
  97. package/dist/tools/builtins/sandbox/write.js +2 -2
  98. package/dist/tools/builtins/skill-load.d.ts +47 -2
  99. package/dist/tools/builtins/skill-load.js +160 -2
  100. package/dist/tools/pipeline.d.ts +1 -1
  101. package/dist/tools/pipeline.js +53 -8
  102. package/dist/tools/registry.d.ts +6 -0
  103. package/package.json +3 -3
  104. package/src/migrations/0133_project_root.sql +30 -0
@@ -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;
@@ -12,6 +12,7 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { EventLog } from "../conversations/event-log.js";
13
13
  import { COMMAND_ASK_MAX_CHARS, COMMAND_ASK_TEXT_MAX_CHARS, ToolViewSchema, } from "../conversations/events.js";
14
14
  import { ConversationDevices } from "../devices/conversation-devices.js";
15
+ import { pathAgainstWorkingRoot } from "../devices/working-root.js";
15
16
  import { ApiError } from "../errors.js";
16
17
  import { EffectiveConfigs, NEEDS_CONFIG_REASON } from "../extensions/effective-config.js";
17
18
  import { clipText } from "../extensions/hooks.js";
@@ -179,6 +180,14 @@ export const TOOL_PIPELINE_HOOKS = Symbol("TOOL_PIPELINE_HOOKS");
179
180
  const REVIEWED_TOOL_KEYS = new Set(["Bash", "Write", "Edit"]);
180
181
  /** Whether the review holds a shell command or a file write, for the texts and the ask's detail. */
181
182
  const reviewKindOf = (toolKey) => toolKey === "Bash" ? "command" : "write";
183
+ /**
184
+ * The working root a reviewed call carries to its tool: a project root only. In free mode the
185
+ * reviewed root is the recorded workspace, which may be stale; the tool then maps it to the held
186
+ * instance's own workspace as it always has.
187
+ */
188
+ const carriedRoot = (facts) => facts.workingRoot !== undefined && facts.workingRoot !== facts.workspace
189
+ ? facts.workingRoot
190
+ : undefined;
182
191
  /** The review record of an allowed call. */
183
192
  const allowRecord = (v) => ({
184
193
  decision: "allow",
@@ -688,6 +697,7 @@ let ToolPipeline = class ToolPipeline {
688
697
  return fail(reviewed.content, outKey);
689
698
  }
690
699
  review = reviewed.review;
700
+ const reviewedWorkingRoot = reviewed.workingRoot;
691
701
  if (reviewed.commandAsk !== undefined)
692
702
  authorization = approvalAuthorization(reviewed.commandAsk);
693
703
  // tool.preExecute after policy and approval, before tool_call_started (F10)
@@ -824,7 +834,7 @@ let ToolPipeline = class ToolPipeline {
824
834
  },
825
835
  ]);
826
836
  const t0 = Date.now();
827
- let outcome = await this.execute(tool, input, ctx, call.id, resume, resolved.tools);
837
+ let outcome = await this.execute(tool, input, ctx, call.id, resume, resolved.tools, reviewedWorkingRoot);
828
838
  const durationMs = Date.now() - t0;
829
839
  await this.deps.hooks?.afterExecute?.(ctx.runId, call.id);
830
840
  // scheduled tasks spec §7, `fail` mode: no one answers an input request or connects an app
@@ -979,9 +989,23 @@ let ToolPipeline = class ToolPipeline {
979
989
  if (!REVIEWED_TOOL_KEYS.has(tool.key))
980
990
  return { kind: "continue" };
981
991
  const asked = await this.deps.approvals.commandForCall(ctx.runId, call.id);
982
- if (asked !== null)
983
- return this.settledCommandAsk(asked, tool.key);
984
992
  const rootConversationId = ctx.parent?.rootConversationId ?? ctx.conversationId;
993
+ if (asked !== null) {
994
+ const settled = this.settledCommandAsk(asked, tool.key);
995
+ // an approved call runs in the root it was reviewed against only while the device still runs
996
+ // in the mode recorded with the ask; otherwise the tool decides its working root afresh. A
997
+ // judged root that is the recorded workspace (free mode) is not carried either
998
+ // ({@link carriedRoot}): the tool maps it to the held instance's workspace as always
999
+ if (settled.kind === "continue" && settled.workingRoot !== undefined) {
1000
+ const now = await devices.reviewFacts(ctx.orgId, rootConversationId, ctx.conversationId);
1001
+ if (now === null ||
1002
+ now.mode !== asked.command?.mode ||
1003
+ carriedRoot({ workspace: now.workspace, workingRoot: settled.workingRoot }) === undefined) {
1004
+ return { ...settled, workingRoot: undefined };
1005
+ }
1006
+ }
1007
+ return settled;
1008
+ }
985
1009
  const facts = await devices.reviewFacts(ctx.orgId, rootConversationId, ctx.conversationId);
986
1010
  if (facts === null)
987
1011
  return { kind: "continue" }; // no device: the tool fails on its own
@@ -1007,7 +1031,12 @@ let ToolPipeline = class ToolPipeline {
1007
1031
  toolKey: tool.key,
1008
1032
  input,
1009
1033
  mode: facts.mode,
1010
- workspace: facts.workspace,
1034
+ // the working root: a bound project's root, where commands start and writes need no ask
1035
+ workspace: facts.workingRoot,
1036
+ // the owner's home, never the project root: the home-level rules stay where they were
1037
+ home: facts.home,
1038
+ // and the device workspace's home, so a project outside every home still protects it
1039
+ deviceHome: facts.deviceHome,
1011
1040
  attended,
1012
1041
  step: ctx.step,
1013
1042
  callId: call.id,
@@ -1026,7 +1055,7 @@ let ToolPipeline = class ToolPipeline {
1026
1055
  ...(ctx.conversationKind !== undefined && { conversationKind: ctx.conversationKind }),
1027
1056
  });
1028
1057
  if (verdict.decision === "allow") {
1029
- return { kind: "continue", review: allowRecord(verdict) };
1058
+ return { kind: "continue", review: allowRecord(verdict), workingRoot: carriedRoot(facts) };
1030
1059
  }
1031
1060
  if (verdict.decision === "deny") {
1032
1061
  return {
@@ -1052,9 +1081,17 @@ let ToolPipeline = class ToolPipeline {
1052
1081
  kind,
1053
1082
  // the whole command the approval covers (the event keeps a clamped copy for display)
1054
1083
  command,
1055
- ...(kind === "write" && { path: clipText(textField(input, "file_path"), 4096) }),
1084
+ // a relative path as it will be written: resolved against the working root
1085
+ ...(kind === "write" && {
1086
+ path: clipText(facts.workingRoot === undefined
1087
+ ? textField(input, "file_path")
1088
+ : pathAgainstWorkingRoot(textField(input, "file_path"), facts.workingRoot), 4096),
1089
+ }),
1056
1090
  rule: verdict.rule,
1057
1091
  reason: clipText(verdict.reason, COMMAND_ASK_TEXT_MAX_CHARS),
1092
+ // the root the review judged, always (the workspace in free mode): the approved call runs
1093
+ // against what the person approved, not a later snapshot
1094
+ ...(facts.workingRoot !== undefined && { workingRoot: facts.workingRoot }),
1058
1095
  };
1059
1096
  let ask;
1060
1097
  try {
@@ -1093,7 +1130,12 @@ let ToolPipeline = class ToolPipeline {
1093
1130
  if (ask.status === "pending")
1094
1131
  return { kind: "wait", wait: approvalWait(ask) };
1095
1132
  if (ask.status === "approved") {
1096
- return { kind: "continue", commandAsk: ask, review: this.personAllowRecord(ask) };
1133
+ return {
1134
+ kind: "continue",
1135
+ commandAsk: ask,
1136
+ review: this.personAllowRecord(ask),
1137
+ workingRoot: ask.command?.workingRoot,
1138
+ };
1097
1139
  }
1098
1140
  if (ask.status === "denied") {
1099
1141
  const reason = ask.denyReason;
@@ -1315,7 +1357,7 @@ let ToolPipeline = class ToolPipeline {
1315
1357
  * 带 `tools.timeoutMs` 超时与 run 的中止信号(合并后传给处理函数 / 连接器,不响应信号的也按时结束)。
1316
1358
  * 熔断只作用于连接器工具(键为组织 × 连接器)。
1317
1359
  */
1318
- async execute(tool, input, ctx, callId, resume, stepTools) {
1360
+ async execute(tool, input, ctx, callId, resume, stepTools, reviewedWorkingRoot) {
1319
1361
  if (tool.source.kind === "connector") {
1320
1362
  return this.executeConnector(tool, tool.source, input, ctx, resume);
1321
1363
  }
@@ -1338,6 +1380,9 @@ let ToolPipeline = class ToolPipeline {
1338
1380
  ...(tool.source.kind === "builtin" && { runId: ctx.runId }),
1339
1381
  ...(tool.source.kind === "builtin" &&
1340
1382
  ctx.deadline !== undefined && { runDeadline: ctx.deadline }),
1383
+ // a reviewed call runs in the working root its review judged (project root spec §4.3)
1384
+ ...(tool.source.kind === "builtin" &&
1385
+ reviewedWorkingRoot !== undefined && { reviewedWorkingRoot }),
1341
1386
  // a sub-agent works in its root conversation's sandbox (spec §10.1, at every depth)
1342
1387
  ...(tool.source.kind === "builtin" &&
1343
1388
  ctx.parent !== undefined && { sandboxConversationId: ctx.parent.rootConversationId }),
@@ -50,6 +50,12 @@ export interface BuiltinCallContext extends ToolCallContext {
50
50
  * default when absent).
51
51
  */
52
52
  sandboxConversationId?: string;
53
+ /**
54
+ * The working root the command review judged this call against (project root spec §4.3): a
55
+ * sandbox tool runs there instead of reading the working root again, so it executes exactly what
56
+ * was reviewed. Absent for a call the review does not cover.
57
+ */
58
+ reviewedWorkingRoot?: string;
53
59
  /** The parent run of a sub-agent's run (absent for a top-level run). */
54
60
  parentRunId?: string;
55
61
  /**