@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
@@ -22,6 +22,47 @@ const WORD_END = new Set([" ", "\t", "\n", "\r", "|", "&", ";", "<", ">", "(", "
22
22
  const isDigit = (c) => c >= "0" && c <= "9";
23
23
  const isAlphaNum = (c) => /[A-Za-z0-9]/.test(c);
24
24
  /** The public parser: the parsed command, or null when the tokenizer is not confident. */
25
+ /** `git config` options that only read (the long-standing spelling). */
26
+ const GIT_CONFIG_READ_OPTIONS = new Set([
27
+ "--get",
28
+ "--get-all",
29
+ "--get-regexp",
30
+ "--get-urlmatch",
31
+ "--get-color",
32
+ "--get-colorbool",
33
+ "-l",
34
+ "--list",
35
+ ]);
36
+ /** `git config` options that change the file whatever else the line says. */
37
+ const GIT_CONFIG_WRITE_OPTIONS = new Set([
38
+ "--add",
39
+ "--unset",
40
+ "--unset-all",
41
+ "--replace-all",
42
+ "--rename-section",
43
+ "--remove-section",
44
+ "-e",
45
+ "--edit",
46
+ ]);
47
+ /**
48
+ * `git config --global` / `--system` that changes the user's or the system's config file: a value
49
+ * set, an `--unset`, an edit, a section rename (`git config [--global] name value`, the subcommands
50
+ * `set` / `unset` / `edit` / `rename-section` / `remove-section`). Reading it (`--get…`, `--list`,
51
+ * `get`, `list`) changes nothing; plain `git config --list` already prints the global values.
52
+ */
53
+ function gitConfigChangesUserFile(args) {
54
+ if (args[0] !== "config")
55
+ return false;
56
+ const rest = args.slice(1);
57
+ if (!hasArg(rest, "--global", "--system"))
58
+ return false;
59
+ if (rest.some((a) => GIT_CONFIG_WRITE_OPTIONS.has(a)))
60
+ return true;
61
+ const sub = rest.find((a) => !a.startsWith("-"));
62
+ if (sub === "get" || sub === "list")
63
+ return false;
64
+ return !rest.some((a) => GIT_CONFIG_READ_OPTIONS.has(a));
65
+ }
25
66
  export function parseCommand(command) {
26
67
  const parsed = parseDetailed(command);
27
68
  return parsed.ok ? { commands: parsed.value } : null;
@@ -763,7 +804,8 @@ function unwrapOneLevel(commands) {
763
804
  function isDynamicScript(script) {
764
805
  return script.includes("$(") || script.includes("`") || /\$\{?[A-Za-z_]/.test(script);
765
806
  }
766
- function homeOf(workspace) {
807
+ /** The home directory a path lies in by its `/home/<u>`, `/Users/<u>` or `/root` prefix, or null. */
808
+ export function homeOf(workspace) {
767
809
  const parts = workspace.split("/").filter((p) => p.length > 0);
768
810
  if ((parts[0] === "home" || parts[0] === "Users") && parts.length >= 2)
769
811
  return `/${parts[0]}/${parts[1]}`;
@@ -773,11 +815,25 @@ function homeOf(workspace) {
773
815
  }
774
816
  function resolveFacts(facts) {
775
817
  const workspace = normalizePath(facts.workspace);
818
+ const derived = homeOf(workspace);
819
+ // the home of the device's own workspace: a project outside every home keeps protecting it
820
+ const device = facts.deviceHome?.startsWith("/") ? normalizePath(facts.deviceHome) : null;
821
+ const deviceHome = device === null || device === "/" ? null : device;
822
+ // an implausible reported home (`/`, or an ancestor of a derived home such as `/Users`) would
823
+ // make every path a home path: it is ignored and only the derived homes are used
824
+ const given = facts.home?.startsWith("/") ? normalizePath(facts.home) : null;
825
+ const reported = given === null ||
826
+ given === "/" ||
827
+ [derived, deviceHome].some((d) => d !== null && isAncestor(given, d))
828
+ ? null
829
+ : given;
776
830
  const cwd = facts.cwd === undefined ? workspace : normalizePath(facts.cwd);
777
831
  return {
778
832
  workspace,
779
833
  cwd,
780
- home: homeOf(workspace),
834
+ // the owner's home as the pipeline knows it (the machine's), else the workspace's prefix
835
+ home: reported ?? derived ?? deviceHome,
836
+ homes: [...new Set([reported, derived, deviceHome].filter((h) => h !== null))],
781
837
  written: new Set((facts.written ?? []).map((p) => p.endsWith("/**") ? `${normalizePath(p.slice(0, -3))}/**` : normalizePath(p))),
782
838
  };
783
839
  }
@@ -861,24 +917,34 @@ function tildeForm(path, facts) {
861
917
  }
862
918
  return path;
863
919
  }
864
- /** Case-folded spelling for the secret-path judgement. */
920
+ /** Case-folded spelling for the home-level judgements. */
865
921
  const foldCase = (value) => value.toLowerCase();
866
922
  /**
867
- * `tildeForm` for the secret-path judgement. macOS's default file system is case-insensitive, so
868
- * `/USERS/me/.SSH` names the same file as `/Users/me/.ssh`; folding the comparison only widens what
869
- * is judged secret. Workspace containment keeps the exact spelling.
923
+ * Every spelling of `path` the home-level rules (secrets, shell and editor rc files, persistence,
924
+ * the device's files) judge: its `~` form against each of {@link ResolvedFacts.homes} it lies in,
925
+ * then the path itself. macOS's default file system is case-insensitive, so `/USERS/me/.SSH` names
926
+ * the same file as `/Users/me/.ssh`: the home is matched case-folded and the rules compare the
927
+ * case-folded forms ({@link foldedForms}), which only widens what they catch. Workspace containment
928
+ * keeps the exact spelling.
870
929
  */
871
- function tildeFormFolded(path, facts) {
872
- if (facts.home === null)
873
- return path;
874
- const home = foldCase(facts.home);
930
+ function homeForms(path, facts) {
875
931
  const folded = foldCase(path);
876
- if (folded === home)
877
- return "~";
878
- if (folded.startsWith(`${home}/`))
879
- return `~${path.slice(facts.home.length)}`;
880
- return path;
932
+ const out = [];
933
+ for (const h of facts.homes) {
934
+ const home = foldCase(h);
935
+ if (folded === home)
936
+ out.push("~");
937
+ // a root home keeps the path's own leading slash: `/.ssh/x` is `~/.ssh/x`, never `~.ssh/x`
938
+ else if (home === "/")
939
+ out.push(`~${path}`);
940
+ else if (folded.startsWith(`${home}/`))
941
+ out.push(`~${path.slice(h.length)}`);
942
+ }
943
+ out.push(path);
944
+ return out;
881
945
  }
946
+ /** {@link homeForms}, case-folded: what the home-level rules compare against lowercase patterns. */
947
+ const foldedForms = (path, facts) => homeForms(path, facts).map(foldCase);
882
948
  const TMP_ROOTS = ["/tmp", "/private/tmp", "/var/tmp", "/var/folders", "/private/var/folders"];
883
949
  const tmpRootOf = (path) => TMP_ROOTS.some((root) => inside(path, root));
884
950
  const SECRET_HOME_PATHS = [
@@ -896,6 +962,7 @@ const SECRET_HOME_PATHS = [
896
962
  "~/.vault-token",
897
963
  "~/.terraform.d/credentials.tfrc.json",
898
964
  "~/.config/op",
965
+ "~/.gnupg",
899
966
  "~/.bash_history",
900
967
  "~/.zsh_history",
901
968
  "~/.sh_history",
@@ -1082,9 +1149,11 @@ function isSecretPattern(path, facts) {
1082
1149
  if (tail.length >= 2 && last !== undefined && segmentMatches(last, "environ"))
1083
1150
  return true;
1084
1151
  }
1085
- const t = tildeFormFolded(path, facts);
1086
- if (t.startsWith("~/"))
1087
- return isSecretHomePath(t.slice(2).split("/"));
1152
+ // every home the path lies in is tried; none matching falls through to the checks below
1153
+ for (const t of homeForms(path, facts)) {
1154
+ if (t.startsWith("~/") && isSecretHomePath(t.slice(2).split("/")))
1155
+ return true;
1156
+ }
1088
1157
  // `/home/<pattern>/…` never becomes `~/…`: the user segment is the pattern, so judge only the
1089
1158
  // literal suffix behind it.
1090
1159
  const [root, user, ...suffix] = absolute;
@@ -1111,7 +1180,7 @@ function isSecretPattern(path, facts) {
1111
1180
  // the workspace is under `/root`; from another home, `/root/…` is another user's and stays
1112
1181
  // allowed (as the literal `/root/.netrc` does), so it must not turn a `/Users/me` workspace's
1113
1182
  // `/*/.ssh/id_rsa` into a hit.
1114
- const rootHit = (facts.home === null || facts.home === "/root") &&
1183
+ const rootHit = (facts.homes.length === 0 || facts.homes.includes("/root")) &&
1115
1184
  user !== undefined &&
1116
1185
  segmentMatches(root, "root") &&
1117
1186
  isSecretHomePath([user, ...suffix]);
@@ -1121,32 +1190,49 @@ function isSecretPattern(path, facts) {
1121
1190
  return false;
1122
1191
  }
1123
1192
  function isSecretPath(path, facts) {
1193
+ if (isHomeSecretPath(path, facts))
1194
+ return true;
1195
+ const base = baseName(path).toLowerCase();
1196
+ return base.startsWith(".env") && !inside(path, facts.workspace);
1197
+ }
1198
+ /** {@link isSecretPath} without `.env*`: the secrets judged wherever they lie. */
1199
+ function isHomeSecretPath(path, facts) {
1124
1200
  if (PROC_ENVIRON.test(path))
1125
1201
  return true;
1126
1202
  // A glob or brace is what the shell expands before the command runs: the path is a secret when
1127
1203
  // it can expand to one, so `cat ~/.netr?` is the same read as `cat ~/.netrc`.
1128
1204
  if (hasPattern(path) && isSecretPattern(path, facts))
1129
1205
  return true;
1130
- const t = foldCase(tildeFormFolded(path, facts));
1131
- if (SECRET_HOME_PATHS.some((secret) => t === secret || t.startsWith(`${secret}/`)))
1132
- return true;
1133
- const base = baseName(path).toLowerCase();
1134
- return base.startsWith(".env") && !inside(path, facts.workspace);
1206
+ return foldedForms(path, facts).some((t) => SECRET_HOME_PATHS.some((secret) => t === secret || t.startsWith(`${secret}/`)));
1207
+ }
1208
+ /**
1209
+ * A home-level sensitive path (auto mode spec §5.2: shell rc files, `~/.ssh`, `~/.gitconfig`,
1210
+ * launch agents, crontab and the secret paths), judged by its absolute path against the owner's
1211
+ * home. These rules apply whether or not the path is inside the workspace fact: the workspace's
1212
+ * exemption covers ordinary files only, so a project at the owner's home (project root spec
1213
+ * §4.3) never makes `~/.bashrc` an ordinary write. (`.env*` stays a secret only outside the
1214
+ * workspace: {@link isSecretPath}.)
1215
+ */
1216
+ function isHomeLevelSensitive(path, facts) {
1217
+ return isHomeSecretPath(path, facts) || isPersistencePath(path, facts);
1135
1218
  }
1136
1219
  function isPersistencePath(path, facts) {
1137
- const t = tildeForm(path, facts);
1138
- if (t === "~/.gitconfig" || t.startsWith("~/.gitconfig."))
1220
+ return foldedForms(path, facts).some((t) => isPersistenceForm(t, facts)) || isGitHook(path);
1221
+ }
1222
+ /** One case-folded {@link homeForms} spelling of a persistence path (patterns in lowercase). */
1223
+ function isPersistenceForm(t, facts) {
1224
+ if (isGitConfigForm(t))
1139
1225
  return true;
1140
1226
  if (/^~\/\.(bashrc|bash_profile|bash_login|profile|zshrc|zshenv|zprofile|zlogin|tcshrc|cshrc|kshrc)$/.test(t)) {
1141
1227
  return true;
1142
1228
  }
1143
1229
  if (t === "~/.config/fish/config.fish" || t.startsWith("~/.config/fish/conf.d/"))
1144
1230
  return true;
1145
- if (t === "~/.ssh" || t.startsWith("~/.ssh/"))
1231
+ if (isEditorOrLogoutRc(t) || isRunLaterHomePath(t, facts))
1146
1232
  return true;
1147
- if (t.startsWith("~/Library/LaunchAgents") || t.startsWith("~/Library/LaunchDaemons"))
1233
+ if (t === "~/.ssh" || t.startsWith("~/.ssh/"))
1148
1234
  return true;
1149
- if (t.startsWith("/Library/LaunchAgents") || t.startsWith("/Library/LaunchDaemons"))
1235
+ if (isLaunchForm(t))
1150
1236
  return true;
1151
1237
  if ([
1152
1238
  "/etc/profile",
@@ -1161,10 +1247,12 @@ function isPersistencePath(path, facts) {
1161
1247
  }
1162
1248
  if (t === "/etc/crontab" || t.startsWith("/var/spool/cron") || t.startsWith("/etc/cron."))
1163
1249
  return true;
1164
- if (t.startsWith("~/.config/systemd"))
1165
- return true;
1166
- return isGitHook(path);
1250
+ return t.startsWith("~/.config/systemd");
1167
1251
  }
1252
+ /** The global git configuration: `~/.gitconfig` (and its lock / backups) or `~/.config/git/config`. */
1253
+ const isGitConfigForm = (t) => t === "~/.gitconfig" || t.startsWith("~/.gitconfig.") || t === "~/.config/git/config";
1254
+ /** A launch agent or daemon, the owner's or the machine's. */
1255
+ const isLaunchForm = (t) => /^(~|)\/library\/launch(agents|daemons)/.test(t);
1168
1256
  const DEVICE_DIRS = [
1169
1257
  "~/.config/capybara-device",
1170
1258
  "~/.capybara-device",
@@ -1174,13 +1262,18 @@ const DEVICE_DIRS = [
1174
1262
  "/var/lib/capybara-device",
1175
1263
  ];
1176
1264
  function isDevicePath(path, facts) {
1177
- const t = tildeForm(path, facts);
1178
- if (DEVICE_DIRS.some((dir) => t === dir || t.startsWith(`${dir}/`)))
1265
+ const dirs = DEVICE_DIRS.map(foldCase);
1266
+ if (foldedForms(path, facts).some((t) => dirs.some((d) => t === d || t.startsWith(`${d}/`)))) {
1179
1267
  return true;
1268
+ }
1180
1269
  // The device binary, its unit file and its launch agent anywhere on disk.
1181
- return isDeviceIdentifier(baseName(t));
1270
+ return isDeviceIdentifier(baseName(path));
1182
1271
  }
1183
- const isGitHook = (path) => path.includes("/.git/hooks/") || path.endsWith("/.git/hooks");
1272
+ /** A git hook, in any letter case (a case-insensitive file system names the same directory). */
1273
+ const isGitHook = (path) => {
1274
+ const p = foldCase(path);
1275
+ return p.includes("/.git/hooks/") || p.endsWith("/.git/hooks");
1276
+ };
1184
1277
  function looksLikePath(token) {
1185
1278
  if (token.length === 0 || token === "-" || token.startsWith("-"))
1186
1279
  return false;
@@ -3956,8 +4049,7 @@ function destroyTargetsOf(inv) {
3956
4049
  }
3957
4050
  function isDangerousDelete(resolved, ctx) {
3958
4051
  const base = globBase(resolved);
3959
- const t = tildeForm(base, ctx.facts);
3960
- if (t === "/" || t === "~" || t === "~/")
4052
+ if (base === "/" || homeForms(base, ctx.facts).some((t) => t === "~" || t === "~/"))
3961
4053
  return true;
3962
4054
  // the workspace root itself and every directory above it (hardening spec R2)
3963
4055
  return base === ctx.facts.workspace || isAncestor(base, ctx.facts.workspace);
@@ -4002,17 +4094,40 @@ const CONFIG_REASONS = {
4002
4094
  "ask.ssh": "Changes or prints SSH keys or configuration; this needs approval.",
4003
4095
  "ask.secret-file": "Prints, copies or changes a credential file; this needs approval each time.",
4004
4096
  };
4005
- /** The grant class of a secret or persistence path. */
4097
+ /** Logout and editor rc files: read by a program the person starts later, like a shell rc file. */
4098
+ function isEditorOrLogoutRc(t) {
4099
+ if (/^~\/\.(bash_logout|zlogout|logout|vimrc|gvimrc|exrc|nanorc|emacs)$/.test(t))
4100
+ return true;
4101
+ return t.startsWith("~/.vim/") || t.startsWith("~/.config/nvim/") || t.startsWith("~/.emacs.d/");
4102
+ }
4103
+ /**
4104
+ * Home locations whose files run later without the person asking: PATH shims (`~/.local/bin`,
4105
+ * `~/bin`, `~/.cargo/bin`),
4106
+ * desktop autostart entries, and the device's own work directory `~/capybara-device` (other
4107
+ * conversations' background task scripts live there). The work directory counts only when the
4108
+ * workspace is not inside it: a free conversation's workspace is a directory of it.
4109
+ */
4110
+ function isRunLaterHomePath(t, facts) {
4111
+ const under = (dir) => t === dir || t.startsWith(`${dir}/`);
4112
+ if (RUN_LATER_HOME_DIRS.some(under))
4113
+ return true;
4114
+ return (under("~/capybara-device") &&
4115
+ !foldedForms(facts.workspace, facts).some((w) => w.startsWith("~/capybara-device/")));
4116
+ }
4117
+ /** PATH shims and desktop autostart entries in the home (case-folded). */
4118
+ const RUN_LATER_HOME_DIRS = ["~/.local/bin", "~/bin", "~/.cargo/bin", "~/.config/autostart"];
4119
+ /** The grant class of a secret or persistence path (judged on every case-folded home spelling). */
4006
4120
  function configClassOf(path, facts) {
4007
- const t = tildeForm(path, facts);
4008
- if (t === "~/.ssh" || t.startsWith("~/.ssh/"))
4121
+ const forms = foldedForms(path, facts);
4122
+ if (forms.some((t) => t === "~/.ssh" || t.startsWith("~/.ssh/")))
4009
4123
  return "ask.ssh";
4010
4124
  if (isGitHook(path) ||
4011
- /^(~|)\/Library\/Launch(Agents|Daemons)/.test(t) ||
4012
- t === "/etc/crontab" ||
4013
- t.startsWith("/var/spool/cron") ||
4014
- t.startsWith("/etc/cron.") ||
4015
- t.startsWith("~/.config/systemd")) {
4125
+ forms.some((t) => isLaunchForm(t) ||
4126
+ t === "/etc/crontab" ||
4127
+ t.startsWith("/var/spool/cron") ||
4128
+ t.startsWith("/etc/cron.") ||
4129
+ t.startsWith("~/.config/systemd") ||
4130
+ isRunLaterHomePath(t, facts))) {
4016
4131
  return "ask.persistence";
4017
4132
  }
4018
4133
  return isPersistencePath(path, facts) ? "ask.shell-config" : "ask.secret-file";
@@ -4046,9 +4161,7 @@ function configMatches(ctx) {
4046
4161
  }
4047
4162
  if (inv.program === "ssh-keygen")
4048
4163
  add("ask.ssh", command, "Changes ~/.ssh; this needs approval.");
4049
- if (inv.program === "git" &&
4050
- inv.args[0] === "config" &&
4051
- hasArg(inv.args.slice(1), "--global", "--system")) {
4164
+ if (inv.program === "git" && gitConfigChangesUserFile(inv.args)) {
4052
4165
  add("ask.shell-config", command, "Changes ~/.gitconfig; this needs approval.");
4053
4166
  }
4054
4167
  if (inv.program === "security" && inv.args.some((a) => KEYCHAIN_DUMP.test(a))) {
@@ -4104,19 +4217,23 @@ function linkSources(inv, command, ctx) {
4104
4217
  return out;
4105
4218
  }
4106
4219
  /**
4107
- * What a link would expose (hardening spec R3): a credential, SSH, persistence or device path, or
4108
- * the home directory or `/` itself (a link to them reaches every secret under them) is
4109
- * `sensitive`; anything else outside the workspace and temporary files is `outside`.
4220
+ * What a link would expose (hardening spec R3): a credential, SSH, persistence or device path, and
4221
+ * the home directory or `/` itself (a link to them reaches every secret under them), is
4222
+ * `sensitive` wherever it lies, inside the workspace too (a project at the owner's home makes the
4223
+ * home the workspace: project root spec §4.3); a parent of the workspace is `sensitive` outside
4224
+ * it; anything else outside the workspace and temporary files is `outside`.
4110
4225
  */
4111
4226
  function linkClass(path, ctx) {
4227
+ if (isHomeLevelSensitive(path, ctx.facts) || isDevicePath(path, ctx.facts))
4228
+ return "sensitive";
4229
+ // the home directory and `/` themselves reach every secret under them, whatever the workspace
4230
+ const base = globBase(path);
4231
+ if (base === "/" || homeForms(base, ctx.facts).some((t) => t === "~"))
4232
+ return "sensitive";
4112
4233
  if (inside(path, ctx.facts.workspace) || tmpRootOf(path))
4113
4234
  return null;
4114
- if (isSecretPath(path, ctx.facts) ||
4115
- isPersistencePath(path, ctx.facts) ||
4116
- isDevicePath(path, ctx.facts) ||
4117
- isDangerousDelete(path, ctx)) {
4235
+ if (isDangerousDelete(path, ctx))
4118
4236
  return "sensitive";
4119
- }
4120
4237
  return "outside";
4121
4238
  }
4122
4239
  const RULES = [
@@ -4239,7 +4356,7 @@ const RULES = [
4239
4356
  return false;
4240
4357
  if (inv.args[0] === "push" && gitPushKind(inv.args.slice(1)) !== null)
4241
4358
  return false;
4242
- if (inv.args[0] === "config" && hasArg(inv.args.slice(1), "--global", "--system"))
4359
+ if (gitConfigChangesUserFile(inv.args))
4243
4360
  return false;
4244
4361
  return true;
4245
4362
  });
@@ -5112,9 +5229,10 @@ export function reviewRules(command, facts) {
5112
5229
  return { outcome: strictest(hits), hits };
5113
5230
  }
5114
5231
  /**
5115
- * The same table for a file-tool write: workspace and tmp writes pass; the device's own files are
5116
- * denied; git hooks, shell rc files and secret files ask; anything else outside asks to write
5117
- * outside.
5232
+ * The same table for a file-tool write: the device's own files are denied; git hooks and
5233
+ * home-level sensitive paths (shell rc files, SSH, launch agents, credentials) ask wherever they
5234
+ * lie, inside the workspace too; other workspace and tmp writes pass; a `.env*` file outside the
5235
+ * workspace asks; anything else outside asks to write outside.
5118
5236
  */
5119
5237
  export function reviewWrite(path, facts) {
5120
5238
  const resolved = resolveFacts(facts);
@@ -5155,6 +5273,11 @@ export function reviewWrite(path, facts) {
5155
5273
  ],
5156
5274
  };
5157
5275
  }
5276
+ // home-level sensitive paths ask wherever they lie, inside the workspace fact too
5277
+ if (isHomeLevelSensitive(absolute, resolved)) {
5278
+ const id = configClassOf(absolute, resolved);
5279
+ return { outcome: "ask", hits: [{ id, outcome: "ask", reason: CONFIG_REASONS[id] }] };
5280
+ }
5158
5281
  if (inside(absolute, resolved.workspace)) {
5159
5282
  return {
5160
5283
  outcome: "allow",
@@ -5179,7 +5302,7 @@ export function reviewWrite(path, facts) {
5179
5302
  ],
5180
5303
  };
5181
5304
  }
5182
- if (isPersistencePath(absolute, resolved) || isSecretPath(absolute, resolved)) {
5305
+ if (isSecretPath(absolute, resolved)) {
5183
5306
  const id = configClassOf(absolute, resolved);
5184
5307
  return { outcome: "ask", hits: [{ id, outcome: "ask", reason: CONFIG_REASONS[id] }] };
5185
5308
  }
@@ -44,6 +44,20 @@ export interface ReviewFacts {
44
44
  attended: boolean;
45
45
  /** The directory the command runs in; default: the workspace. */
46
46
  cwd?: string;
47
+ /**
48
+ * The owner's home directory, which `~` and the home-level sensitive paths (shell rc files,
49
+ * SSH, credentials) are judged against. The pipeline passes it from the machine (or the device's
50
+ * workspace), never from a project root, so a project outside the home keeps every home rule
51
+ * (project root spec §4.3). Absent or null: derived from the workspace's `/home/<u>`,
52
+ * `/Users/<u>` or `/root` prefix.
53
+ */
54
+ home?: string | null;
55
+ /**
56
+ * The home prefix of the device's own workspace (`homeOf` of it), judged beside `home` and the
57
+ * working root's prefix: a project outside every home (`/opt/app`) with an implausible reported
58
+ * home (`/`) still protects the real home. Absent or null: none.
59
+ */
60
+ deviceHome?: string | null;
47
61
  /**
48
62
  * Absolute paths this conversation's own tool calls wrote (`Write` / `Edit`, and the write
49
63
  * targets of its earlier `Bash` lines): running one of them with an interpreter is not a
@@ -41,6 +41,13 @@ export interface SandboxUseContext {
41
41
  holderConversationId: string;
42
42
  /** Passed with every `exec` (audit and attribution). */
43
43
  actor: SandboxActor;
44
+ /**
45
+ * A use that tells the model nothing (the run-start read of a bound project): it does not mark
46
+ * the holder as having seen the instance, so the holder's next ordinary use still learns that
47
+ * the instance started, restarted or had its files reset ({@link SandboxUseInfo}); what this use
48
+ * itself caused (a creation, a rebuild) is kept for that next use.
49
+ */
50
+ silent?: true;
44
51
  }
45
52
  export type { SandboxProviderEntry } from "./providers.js";
46
53
  type Row = Selectable<DeviceInstancesTable>;
@@ -213,7 +220,7 @@ export declare class SandboxService {
213
220
  private readonly background;
214
221
  constructor(db: KernelDb,
215
222
  /** The record of the instance each holder last used (`capk:sandbox-seen:…`). */
216
- redis: Pick<Redis, "set">, leases: SandboxLeases,
223
+ redis: Pick<Redis, "set" | "getdel">, leases: SandboxLeases,
217
224
  /** The providers (read at every call: providers are ready after the extension load). */
218
225
  providers: Pick<SandboxProviders, "cloud" | "forName">, config: Pick<KernelConfigService, "get" | "fieldSource">, log: Pick<KernelLogger, "info" | "warn">,
219
226
  /** Background tasks lost while their process may live on (killed after a resume). */
@@ -375,6 +382,14 @@ export declare class SandboxService {
375
382
  * machine: until a new login, which resets the row). A failed write only logs.
376
383
  */
377
384
  private filesGone;
385
+ /**
386
+ * A silent use ({@link SandboxUseContext.silent}) of `holder`: the seen record is left alone, so
387
+ * the holder's next ordinary use compares against the instance it last saw itself (and learns
388
+ * of a restart or a files reset since); a creation or rebuild this use caused is kept
389
+ * (`capk:sandbox-notice:<env>:<holder>`, merged with an earlier one for the same instance, same
390
+ * TTL as the seen record) for {@link seenBy} to tell. Best effort: a Redis error only logs.
391
+ */
392
+ private deferNotice;
378
393
  /**
379
394
  * Records that `holder` uses the instance of `e` (`capk:sandbox-seen:<env>:<holder>` =
380
395
  * `<created_at>:<fs_resets>`, with a TTL of the inactivity destruction plus a day). When the
@@ -44,6 +44,26 @@ const EXCLUSIVE_WAIT_MS = 10 * 60_000;
44
44
  const PENDING_KILL_TIMEOUT_MS = 30_000;
45
45
  /** A background task's session id as `echo $!` printed it; anything else is never put in a command. */
46
46
  const SID_RE = /^[1-9][0-9]{0,9}$/;
47
+ const noticeKey = (deviceId, holder) => `capk:sandbox-notice:${deviceId}:${holder}`;
48
+ /** A stored {@link DeferredNotice}, or null (none, or not one). */
49
+ function parseDeferred(raw) {
50
+ if (raw === null)
51
+ return null;
52
+ try {
53
+ const v = JSON.parse(raw);
54
+ if (typeof v.seen !== "string")
55
+ return null;
56
+ return {
57
+ seen: v.seen,
58
+ fresh: v.fresh === true,
59
+ restarted: v.restarted === true,
60
+ filesReset: v.filesReset === true,
61
+ };
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
47
67
  /** The signal of one provider call in maintenance: aborted on timeout or when the lease is lost. */
48
68
  const opSignal = (lease) => AbortSignal.any([lease.signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]);
49
69
  /** The provider-side name of a device's file system and instance. */
@@ -599,7 +619,8 @@ let SandboxService = class SandboxService {
599
619
  // decides the shared fast path only (read again before each shared lease is used): the
600
620
  // exclusive path reads it again under the lease
601
621
  const want = () => this.wantedLimits(ctx, p);
602
- let e = await this.seenBy(env, holder, await this.enter(ctx, p, signal, null, want));
622
+ const seen = (x) => ctx.silent ? this.deferNotice(env, holder, x) : this.seenBy(env, holder, x);
623
+ let e = await seen(await this.enter(ctx, p, signal, null, want));
603
624
  try {
604
625
  try {
605
626
  return await this.runAs(e, ctx, p, fn, signal);
@@ -613,7 +634,7 @@ let SandboxService = class SandboxService {
613
634
  const gone = { handle: e.handle, createdAt: e.createdAt };
614
635
  const prev = e;
615
636
  await this.leave(env, prev);
616
- e = await this.seenBy(env, holder, await this.enter(ctx, p, signal, gone, want));
637
+ e = await seen(await this.enter(ctx, p, signal, gone, want));
617
638
  // a reset seen on the first try still has to be told (it covers the restart)
618
639
  const info = prev.info.filesReset
619
640
  ? { fresh: true, restarted: false, filesReset: true }
@@ -670,6 +691,43 @@ let SandboxService = class SandboxService {
670
691
  }
671
692
  return deviceFilesLost(p.plugin === LOCAL_PROVIDER);
672
693
  }
694
+ /**
695
+ * A silent use ({@link SandboxUseContext.silent}) of `holder`: the seen record is left alone, so
696
+ * the holder's next ordinary use compares against the instance it last saw itself (and learns
697
+ * of a restart or a files reset since); a creation or rebuild this use caused is kept
698
+ * (`capk:sandbox-notice:<env>:<holder>`, merged with an earlier one for the same instance, same
699
+ * TTL as the seen record) for {@link seenBy} to tell. Best effort: a Redis error only logs.
700
+ */
701
+ async deferNotice(deviceId, holder, e) {
702
+ if (!e.info.fresh && !e.info.restarted && e.info.filesReset !== true)
703
+ return e;
704
+ try {
705
+ const ttl = (this.config.get().sandbox.limits.destroyAfterInactiveDays + 1) * 86_400;
706
+ const seen = `${e.createdAt}:${e.fsResets}`;
707
+ const key = noticeKey(deviceId, holder);
708
+ const mine = {
709
+ seen,
710
+ fresh: e.info.fresh,
711
+ restarted: e.info.restarted,
712
+ filesReset: e.info.filesReset === true,
713
+ };
714
+ // swapped in, then merged with an earlier silent use's notice for the same instance
715
+ const prev = parseDeferred(await this.redis.set(key, JSON.stringify(mine), "EX", ttl, "GET"));
716
+ if (prev !== null && prev.seen === seen) {
717
+ const merged = {
718
+ seen,
719
+ fresh: mine.fresh || prev.fresh,
720
+ restarted: mine.restarted || prev.restarted,
721
+ filesReset: mine.filesReset || prev.filesReset,
722
+ };
723
+ await this.redis.set(key, JSON.stringify(merged), "EX", ttl);
724
+ }
725
+ }
726
+ catch (err) {
727
+ this.log.warn("cannot keep the sandbox notice of a silent use", { deviceId, holder, err });
728
+ }
729
+ return e;
730
+ }
673
731
  /**
674
732
  * Records that `holder` uses the instance of `e` (`capk:sandbox-seen:<env>:<holder>` =
675
733
  * `<created_at>:<fs_resets>`, with a TTL of the inactivity destruction plus a day). When the
@@ -679,10 +737,24 @@ let SandboxService = class SandboxService {
679
737
  * (sandbox-docker's volumes are named after the device). Best effort: a Redis error only
680
738
  * logs.
681
739
  */
682
- async seenBy(deviceId, holder, e) {
740
+ async seenBy(deviceId, holder, entered) {
741
+ let e = entered;
683
742
  try {
684
743
  const ttl = (this.config.get().sandbox.limits.destroyAfterInactiveDays + 1) * 86_400;
685
744
  const seen = `${e.createdAt}:${e.fsResets}`;
745
+ // what a silent use of this holder caused on this same instance is told now
746
+ const deferred = parseDeferred(await this.redis.getdel(noticeKey(deviceId, holder)));
747
+ if (deferred !== null && deferred.seen === seen) {
748
+ e = {
749
+ ...e,
750
+ info: e.info.filesReset === true || deferred.filesReset
751
+ ? { fresh: e.info.fresh || deferred.fresh, restarted: false, filesReset: true }
752
+ : {
753
+ fresh: e.info.fresh || deferred.fresh,
754
+ restarted: e.info.restarted || deferred.restarted,
755
+ },
756
+ };
757
+ }
686
758
  const prev = await this.redis.set(`capk:sandbox-seen:${deviceId}:${holder}`, seen, "EX", ttl, "GET");
687
759
  if (prev !== null && prev !== seen) {
688
760
  // `<createdAt>:<fsResets>`: another reset count means the files were reset since; another
@@ -118,7 +118,12 @@ export declare function skillLoadOffered(latest: Extract<ConversationEvent, {
118
118
  * with `skill`), so an agent whose skills are all manual-only can still copy an invoked skill's
119
119
  * files. Derived from the log, so a replay recomputes it.
120
120
  */
121
- invoked?: boolean): boolean;
121
+ invoked?: boolean,
122
+ /**
123
+ * Project root spec §4.5: the log recorded a bound project with skills (`hasProjectSkills`),
124
+ * which `Skill` loads as `project:<name>`. Derived from the log, never taken back.
125
+ */
126
+ projectSkills?: boolean): boolean;
122
127
  /** Whether `events` hold a person's skill invocation (a `user_message` with `skill`). */
123
128
  export declare const hasInvocation: (events: readonly ConversationEvent[]) => boolean;
124
129
  /** {@link skillLoadOffered} for a conversation, read from the database. */
@@ -17,6 +17,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
17
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
18
  import { KERNEL_LOGGER } from "../infra/tokens.js";
19
19
  import { CLAUDE_CODE_TOOL_MAP } from "../runtime/context/claude-tools.js";
20
+ import { PROJECT_SKILL_PREFIX, SKILL_NAME_MAX_CHARS } from "../runtime/context/project-root.js";
20
21
  import { catalogLine, sameSnapshot, } from "../runtime/context/skills.js";
21
22
  import { runEndedIn } from "../runtime/run-status.js";
22
23
  import { agentOwnSkillIds, agentSkills, builtinSkillIds, builtinSkillPlugins, } from "./usable.js";
@@ -191,8 +192,13 @@ export function skillLoadOffered(latest,
191
192
  * with `skill`), so an agent whose skills are all manual-only can still copy an invoked skill's
192
193
  * files. Derived from the log, so a replay recomputes it.
193
194
  */
194
- invoked = false) {
195
- return latest !== undefined || invoked;
195
+ invoked = false,
196
+ /**
197
+ * Project root spec §4.5: the log recorded a bound project with skills (`hasProjectSkills`),
198
+ * which `Skill` loads as `project:<name>`. Derived from the log, never taken back.
199
+ */
200
+ projectSkills = false) {
201
+ return latest !== undefined || invoked || projectSkills;
196
202
  }
197
203
  /** Whether `events` hold a person's skill invocation (a `user_message` with `skill`). */
198
204
  export const hasInvocation = (events) => events.some((e) => e.type === "user_message" && e.payload.skill !== undefined);
@@ -204,8 +210,16 @@ export async function skillLoadOfferedIn(db, eventLog, conversationId) {
204
210
  .selectFrom("conversation_events")
205
211
  .select("seq")
206
212
  .where("conversation_id", "=", conversationId)
207
- .where("type", "=", "user_message")
208
- .where(sql `payload -> 'skill' IS NOT NULL`)
213
+ .where((eb) => eb.or([
214
+ eb.and([eb("type", "=", "user_message"), sql `payload -> 'skill' IS NOT NULL`]),
215
+ // a project with a skill Skill can be called with (hasProjectSkills: `project:<name>`
216
+ // within the schema's cap; skill names are ASCII, so characters are UTF-16 code units)
217
+ eb.and([
218
+ eb("type", "=", "project_root"),
219
+ sql `EXISTS (SELECT 1 FROM jsonb_array_elements(payload -> 'skills') s
220
+ WHERE length(${PROJECT_SKILL_PREFIX}::text || (s ->> 'name')) <= ${SKILL_NAME_MAX_CHARS})`,
221
+ ]),
222
+ ]))
209
223
  .limit(1)
210
224
  .executeTakeFirst();
211
225
  return row !== undefined;