@capybara-hq/kernel 0.1.0-rc.49 → 0.1.0-rc.50

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 (128) hide show
  1. package/dist/admin/admin.schemas.d.ts +0 -6
  2. package/dist/background/launch.d.ts +7 -61
  3. package/dist/background/launch.js +8 -133
  4. package/dist/background/poll.job.d.ts +19 -23
  5. package/dist/background/poll.job.js +30 -66
  6. package/dist/background/render.d.ts +9 -0
  7. package/dist/background/render.js +19 -0
  8. package/dist/background/session.d.ts +3 -66
  9. package/dist/background/session.js +3 -114
  10. package/dist/background/stop.d.ts +26 -33
  11. package/dist/background/stop.js +59 -90
  12. package/dist/background/store.d.ts +26 -60
  13. package/dist/background/store.js +23 -108
  14. package/dist/background/tasks.service.d.ts +9 -29
  15. package/dist/background/tasks.service.js +18 -115
  16. package/dist/catalog/marketplaces.service.d.ts +1 -1
  17. package/dist/channels/cards.d.ts +3 -0
  18. package/dist/channels/cards.js +29 -2
  19. package/dist/channels/phrases.d.ts +35 -0
  20. package/dist/channels/phrases.js +32 -0
  21. package/dist/config/load.d.ts +3 -10
  22. package/dist/config/load.js +26 -21
  23. package/dist/config/schema.js +3 -3
  24. package/dist/conversations/events.d.ts +45 -2
  25. package/dist/conversations/events.js +44 -4
  26. package/dist/db/kernel-schema.d.ts +9 -4
  27. package/dist/devices/devices.service.js +1 -1
  28. package/dist/devices/errors.d.ts +5 -0
  29. package/dist/devices/errors.js +5 -0
  30. package/dist/devices/project-rules.d.ts +2 -2
  31. package/dist/errors.d.ts +9 -11
  32. package/dist/errors.js +9 -11
  33. package/dist/identity/settings.d.ts +4 -17
  34. package/dist/identity/settings.js +9 -32
  35. package/dist/infra/config/kernel-config.service.js +2 -9
  36. package/dist/infra/outbox/registry.d.ts +13 -0
  37. package/dist/infra/outbox/registry.js +8 -0
  38. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  39. package/dist/local-devices/device-auth.controller.js +1 -1
  40. package/dist/local-devices/device-auth.d.ts +4 -3
  41. package/dist/local-devices/device-auth.js +1 -1
  42. package/dist/local-devices/device-policy.service.d.ts +6 -6
  43. package/dist/local-devices/device-routes.d.ts +4 -2
  44. package/dist/local-devices/device-routes.js +7 -6
  45. package/dist/local-devices/instance-bindings.d.ts +4 -4
  46. package/dist/local-devices/instance-bindings.js +2 -2
  47. package/dist/local-devices/local-device-gateway.d.ts +12 -12
  48. package/dist/local-devices/local-device-gateway.js +94 -129
  49. package/dist/local-devices/local-device-provider.d.ts +19 -87
  50. package/dist/local-devices/local-device-provider.js +43 -158
  51. package/dist/local-devices/local-devices.module.d.ts +4 -5
  52. package/dist/local-devices/local-devices.module.js +6 -9
  53. package/dist/local-devices/machines.d.ts +6 -6
  54. package/dist/local-devices/machines.js +4 -4
  55. package/dist/local-devices/owner-report.d.ts +3 -3
  56. package/dist/local-devices/owner-report.js +4 -4
  57. package/dist/local-devices/owner-reports.js +2 -2
  58. package/dist/local-devices/policy-summary.js +2 -2
  59. package/dist/local-devices/relay.d.ts +12 -25
  60. package/dist/local-devices/relay.js +17 -31
  61. package/dist/orgs/settings.controller.d.ts +1 -4
  62. package/dist/orgs/settings.controller.js +3 -3
  63. package/dist/orgs/settings.service.d.ts +7 -21
  64. package/dist/orgs/settings.service.js +16 -40
  65. package/dist/overrides.d.ts +3 -3
  66. package/dist/platform/ops/admin.ops.js +6 -8
  67. package/dist/platform/ops/org-settings.ops.js +4 -4
  68. package/dist/platform/ops/orgs.ops.js +0 -1
  69. package/dist/runtime/maintenance.d.ts +1 -1
  70. package/dist/runtime/maintenance.js +7 -1
  71. package/dist/runtime/run-steps.js +2 -2
  72. package/dist/sandbox/held-operations.d.ts +7 -0
  73. package/dist/sandbox/held-operations.js +25 -1
  74. package/dist/sandbox/leases.d.ts +6 -3
  75. package/dist/sandbox/leases.js +16 -10
  76. package/dist/sandbox/legacy-retirement.d.ts +0 -19
  77. package/dist/sandbox/legacy-retirement.js +6 -37
  78. package/dist/sandbox/managed-device-context.d.ts +12 -0
  79. package/dist/sandbox/managed-device-context.js +49 -1
  80. package/dist/sandbox/modes.d.ts +9 -8
  81. package/dist/sandbox/modes.js +4 -15
  82. package/dist/sandbox/operation-authority-types.d.ts +18 -1
  83. package/dist/sandbox/operation-authority-types.js +20 -1
  84. package/dist/sandbox/operation-authority.d.ts +14 -0
  85. package/dist/sandbox/operation-authority.js +120 -18
  86. package/dist/sandbox/operation-intents.d.ts +43 -0
  87. package/dist/sandbox/operation-intents.js +107 -4
  88. package/dist/sandbox/operation-reconcile.job.d.ts +12 -1
  89. package/dist/sandbox/operation-reconcile.job.js +53 -6
  90. package/dist/sandbox/permission-call-grants.d.ts +4 -0
  91. package/dist/sandbox/permission-call-grants.js +32 -3
  92. package/dist/sandbox/permission-call-types.d.ts +27 -2
  93. package/dist/sandbox/permission-ceiling-writes.js +2 -1
  94. package/dist/sandbox/permission-context-types.d.ts +2 -2
  95. package/dist/sandbox/permission-context-types.js +2 -2
  96. package/dist/sandbox/permission-facts.js +10 -2
  97. package/dist/sandbox/platform-full-access.d.ts +8 -26
  98. package/dist/sandbox/platform-full-access.js +8 -20
  99. package/dist/sandbox/review/classifier.d.ts +2 -2
  100. package/dist/sandbox/review/classifier.js +18 -5
  101. package/dist/sandbox/review/permission-candidate.d.ts +59 -3
  102. package/dist/sandbox/review/permission-candidate.js +192 -25
  103. package/dist/sandbox/review/review.service.d.ts +18 -0
  104. package/dist/sandbox/review/review.service.js +158 -12
  105. package/dist/sandbox/sandbox.service.d.ts +71 -47
  106. package/dist/sandbox/sandbox.service.js +234 -133
  107. package/dist/tools/approvals.service.d.ts +6 -1
  108. package/dist/tools/approvals.service.js +10 -0
  109. package/dist/tools/builtins/builtin-tools.d.ts +1 -4
  110. package/dist/tools/builtins/builtin-tools.js +13 -18
  111. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  112. package/dist/tools/builtins/sandbox/bash.js +92 -270
  113. package/dist/tools/builtins/sandbox/common.d.ts +15 -9
  114. package/dist/tools/builtins/sandbox/common.js +55 -19
  115. package/dist/tools/builtins/sandbox/device-owner.d.ts +13 -0
  116. package/dist/tools/builtins/sandbox/device-owner.js +14 -0
  117. package/dist/tools/builtins/sandbox/task-list.js +2 -2
  118. package/dist/tools/builtins/sandbox/task-output.d.ts +14 -57
  119. package/dist/tools/builtins/sandbox/task-output.js +88 -210
  120. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -2
  121. package/dist/tools/builtins/sandbox/task-stop.js +15 -26
  122. package/dist/tools/pipeline.d.ts +31 -2
  123. package/dist/tools/pipeline.js +273 -43
  124. package/dist/tools/registry.d.ts +7 -0
  125. package/package.json +4 -4
  126. package/src/migrations/0162_permission_call_escalation.sql +9 -0
  127. package/dist/background/status.d.ts +0 -35
  128. package/dist/background/status.js +0 -57
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { ToolError, validateInputForm, validateToolDisplay, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
+ import { backgroundMaxSeconds } from "../background/launch.js";
12
13
  import { EventLog } from "../conversations/event-log.js";
13
14
  import { COMMAND_ASK_MAX_CHARS, COMMAND_ASK_TEXT_MAX_CHARS, ToolViewSchema, } from "../conversations/events.js";
14
15
  import { ConversationDevices } from "../devices/conversation-devices.js";
@@ -40,19 +41,22 @@ import { orgHostOutsideCeiling } from "../sandbox/modes.js";
40
41
  import { SandboxOperationAuthority } from "../sandbox/operation-authority.js";
41
42
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
42
43
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
44
+ import { PERMISSION_CONTEXT_ACTIVATION, permissionContextActive, } from "../sandbox/permission-context-types.js";
43
45
  import { permissionScopeHash } from "../sandbox/permission-facts.js";
44
46
  import { isSessionGrantableRule, } from "../sandbox/review/index.js";
45
- import { buildPermissionCandidate } from "../sandbox/review/permission-candidate.js";
47
+ import { buildPermissionCandidate, ESCALATION_RETRY_HINT, ESCALATION_UNATTENDED_WHY, escalationRefusedText, isEscalatedCall, } from "../sandbox/review/permission-candidate.js";
46
48
  import { CommandReviewService } from "../sandbox/review/review.service.js";
49
+ import { SandboxService } from "../sandbox/sandbox.service.js";
47
50
  import { appendMissingGrant, connectionGrantKey, UNATTENDED_CONNECTION_ERROR, UNATTENDED_ELICITATION_NOTE, UNATTENDED_QUESTION_ERROR, unattendedFails, unattendedRunOf, } from "../schedules/unattended.js";
48
51
  import { skillLoadOfferedIn } from "../skills/catalog.js";
49
52
  import { ApprovalsService, } from "./approvals.service.js";
50
53
  import { Breaker, breakerOpenMessage } from "./breaker.js";
51
- import { SEND_MESSAGE, SUBAGENT_HANDBACK, TOOL_SEARCH } from "./builtin-names.js";
54
+ import { BUILTIN, SEND_MESSAGE, SUBAGENT_HANDBACK, TOOL_SEARCH } from "./builtin-names.js";
52
55
  import { AGENT_TOOL, AgentToolInput } from "./builtins/agent.js";
53
56
  import { HandbackInput } from "./builtins/handback.js";
54
57
  import { generateImagePaths } from "./builtins/image/paths.js";
55
58
  import { DEVICE_CODE_PATTERN, deviceCodeIdemKey, GITHUB_DEVICE_LOGIN_URL, } from "./builtins/sandbox/device-code.js";
59
+ import { DEVICE_OF_ANOTHER_ACCOUNT_TEXT } from "./builtins/sandbox/device-owner.js";
56
60
  import { SendMessageInput } from "./builtins/send-message.js";
57
61
  import { isAlwaysLoaded, notLoadedText } from "./builtins/tool-search.js";
58
62
  import { canonicalJson } from "./canonical-json.js";
@@ -190,6 +194,50 @@ const isReviewedCall = (toolKey, input) => REVIEWED_TOOL_KEYS.has(toolKey) &&
190
194
  (toolKey !== "GenerateImage" || generateImagePaths(input).length > 0);
191
195
  /** The paths a reviewed write writes: `file_path`, or every path of a `GenerateImage` call. */
192
196
  const writePathsOf = (toolKey, input) => toolKey === "GenerateImage" ? generateImagePaths(input) : [textField(input, "file_path")];
197
+ /**
198
+ * A call that needs reach beyond the working directory on a device whose permission support is
199
+ * not verified: no approval could let admission run it, so nothing is offered.
200
+ */
201
+ export const PERMISSION_SUPPORT_UNVERIFIED_TEXT = "This call needs access outside the working directory, but this device's permission support is not verified yet, so only paths inside the working directory work now. Keep the call inside the working directory, or retry once the device is ready.";
202
+ /**
203
+ * The managed builtins whose review depends on the device's facts (a proposed reach or a
204
+ * sensitive command): their first call starts the device before it is reviewed. The others start
205
+ * it only when they run (a Skill without scripts never does).
206
+ */
207
+ const REVIEWED_ON_FACTS = new Set([
208
+ BUILTIN.Bash,
209
+ BUILTIN.Read,
210
+ BUILTIN.Write,
211
+ BUILTIN.Edit,
212
+ BUILTIN.GenerateImage,
213
+ ]);
214
+ /** The refusals of a permission review that end the call (fail closed), not the run. */
215
+ const FAIL_CLOSED_CODES = new Set([
216
+ "forbidden",
217
+ "conflict",
218
+ "conversation.not_found",
219
+ ]);
220
+ /** What the model gets when the permission check of its call refused (fail closed). */
221
+ export const permissionCheckFailedText = (why) => `The permission check for this call could not be completed (${why.replace(/\.$/, "")}), so it did not run. Retry the call once; if it fails again, ask the user to check the conversation's permission profile or to approve the call again.`;
222
+ /** The builtins whose device entry is the managed operation route once activated. */
223
+ const MANAGED_OPERATION_TOOLS = new Set([
224
+ BUILTIN.Bash,
225
+ BUILTIN.Read,
226
+ BUILTIN.Write,
227
+ BUILTIN.Edit,
228
+ BUILTIN.Glob,
229
+ BUILTIN.Grep,
230
+ BUILTIN.Deliver,
231
+ BUILTIN.FetchAttachment,
232
+ BUILTIN.Skill,
233
+ BUILTIN.GenerateImage,
234
+ ]);
235
+ /**
236
+ * Whether a managed builtin's call enters the device: every call of the device tools, a
237
+ * `GenerateImage` call only with `file_path` (one without writes nothing into the device, so it
238
+ * takes neither the device-owner guard nor the permission review: image generation spec §5.3).
239
+ */
240
+ const entersDevice = (toolKey, input) => toolKey !== BUILTIN.GenerateImage || generateImagePaths(input).length > 0;
193
241
  /** Whether the review holds a shell command or a file write, for the texts and the ask's detail. */
194
242
  const reviewKindOf = (toolKey) => toolKey === "Bash" ? "command" : "write";
195
243
  /**
@@ -345,6 +393,7 @@ let ToolPipeline = class ToolPipeline {
345
393
  permissionAuthority;
346
394
  permissionGrants;
347
395
  permissionLocks;
396
+ sandboxes;
348
397
  decide;
349
398
  deps;
350
399
  constructor(kdb, eventLog,
@@ -357,13 +406,24 @@ let ToolPipeline = class ToolPipeline {
357
406
  /** The command review (auto mode spec §5.4); absent in hand-built pipelines. */
358
407
  review,
359
408
  /** The reviewed call's device facts; absent in hand-built pipelines. */
360
- devices, permissionAuthority, permissionGrants, permissionLocks) {
409
+ devices, permissionAuthority, permissionGrants, permissionLocks,
410
+ /** The paired activation gate: on, the managed builtins take the permission review. */
411
+ activation,
412
+ /** Starts a cloud device before its first managed call is reviewed (absent: never). */
413
+ sandboxes) {
361
414
  this.config = config;
362
415
  this.txHost = txHost;
363
416
  this.permissionAuthority = permissionAuthority;
364
417
  this.permissionGrants = permissionGrants;
365
418
  this.permissionLocks = permissionLocks;
419
+ this.sandboxes = sandboxes;
366
420
  this.deps = {
421
+ // the builtins that enter a device on the managed operation route once activated (common.ts
422
+ // `inToolSandbox`, `inSandboxPreparation`): their review is the permission review, whose
423
+ // approvals issue the exact call grants admission reads; dormant, none (the command review)
424
+ permissionOperations: permissionContextActive(activation)
425
+ ? MANAGED_OPERATION_TOOLS
426
+ : new Set(),
367
427
  get db() {
368
428
  return kdb.db;
369
429
  },
@@ -701,7 +761,11 @@ let ToolPipeline = class ToolPipeline {
701
761
  return fail(reviewed.content, outKey);
702
762
  }
703
763
  review = reviewed.review;
704
- const reviewedRoots = { workingRoot: reviewed.workingRoot, against: reviewed.reviewedAgainst };
764
+ const reviewedRoots = {
765
+ workingRoot: reviewed.workingRoot,
766
+ against: reviewed.reviewedAgainst,
767
+ ...(reviewed.sandboxEscalation !== undefined && { escalation: reviewed.sandboxEscalation }),
768
+ };
705
769
  if (reviewed.commandAsk !== undefined)
706
770
  authorization = approvalAuthorization(reviewed.commandAsk);
707
771
  // tool.preExecute after policy and approval, before tool_call_started (F10)
@@ -839,11 +903,12 @@ let ToolPipeline = class ToolPipeline {
839
903
  callId: call.id,
840
904
  toolKey: tool.key,
841
905
  specHash: tool.specHash,
842
- ...(this.operationScoped(tool)
906
+ ...(this.operationScoped(tool, input)
843
907
  ? {
844
908
  permissionInput: {
845
909
  callInputHash: permissionScopeHash(call.input),
846
910
  resolvedInputHash: permissionScopeHash(input),
911
+ ...(isEscalatedCall(tool.key, input) ? { sandbox: "escalated" } : {}),
847
912
  },
848
913
  }
849
914
  : {}),
@@ -854,6 +919,13 @@ let ToolPipeline = class ToolPipeline {
854
919
  let outcome = await this.execute(tool, input, ctx, call.id, resume, resolved.tools, reviewedRoots);
855
920
  const durationMs = Date.now() - t0;
856
921
  await this.deps.hooks?.afterExecute?.(ctx.runId, call.id);
922
+ // the record says a call ran outside the sandbox only when admission gave it that scope
923
+ if (review !== undefined && isEscalatedCall(tool.key, input)) {
924
+ const { sandbox: _asked, ...rest } = review;
925
+ review = (await this.admittedOutsideSandbox(ctx.runId, call.id))
926
+ ? { ...rest, sandbox: "escalated" }
927
+ : rest;
928
+ }
857
929
  // scheduled tasks spec §7, `fail` mode: no one answers an input request or connects an app
858
930
  if (unattendedFails(ctx.unattended) && ctx.unattended != null) {
859
931
  if (outcome.kind === "input_required") {
@@ -999,8 +1071,33 @@ let ToolPipeline = class ToolPipeline {
999
1071
  * asked is the whole truth on a resume: the call is never reviewed twice.
1000
1072
  */
1001
1073
  async reviewCall(ctx, call, tool, input) {
1002
- if (this.operationScoped(tool)) {
1003
- const scoped = await this.reviewPermissionCall(ctx, call, tool, input);
1074
+ // a device tool of a run another account triggered never uses the owner's device: refused
1075
+ // here, with no review and no review model call (the tools refuse it the same way)
1076
+ if (this.operationScoped(tool, input) && ctx.ownerAccountId !== ctx.accountId)
1077
+ return {
1078
+ kind: "result",
1079
+ content: DEVICE_OF_ANOTHER_ACCOUNT_TEXT,
1080
+ review: denyRecord("rule", null, "The run's account is not the conversation's owner"),
1081
+ };
1082
+ if (this.operationScoped(tool, input)) {
1083
+ let scoped;
1084
+ try {
1085
+ scoped = await this.reviewPermissionCall(ctx, call, tool, input);
1086
+ }
1087
+ catch (error) {
1088
+ // fail closed: a permission evidence conflict or an owner check that refuses while the
1089
+ // call is asked about, reviewed or matched to its grant is a refusal of this call, never a
1090
+ // run error and never a run of it
1091
+ if (!(error instanceof ApiError) || !FAIL_CLOSED_CODES.has(error.code))
1092
+ throw error;
1093
+ this.deps.log.warn("permission review refused the call", {
1094
+ conversationId: ctx.conversationId,
1095
+ callId: call.id,
1096
+ err: error,
1097
+ });
1098
+ const content = permissionCheckFailedText(error.message);
1099
+ return { kind: "result", content, review: denyRecord("rule", null, error.message) };
1100
+ }
1004
1101
  if (scoped)
1005
1102
  return scoped;
1006
1103
  }
@@ -1144,11 +1241,28 @@ let ToolPipeline = class ToolPipeline {
1144
1241
  }
1145
1242
  return { kind: "wait", wait: approvalWait(ask) };
1146
1243
  }
1147
- operationScoped(tool) {
1148
- return tool.source.kind === "builtin" && this.deps.permissionOperations?.has(tool.key) === true;
1244
+ /**
1245
+ * Whether this call takes the managed route's permission review: a managed builtin once
1246
+ * activated ({@link MANAGED_OPERATION_TOOLS}) whose call enters the device ({@link entersDevice}).
1247
+ */
1248
+ operationScoped(tool, input) {
1249
+ return (tool.source.kind === "builtin" &&
1250
+ this.deps.permissionOperations?.has(tool.key) === true &&
1251
+ entersDevice(tool.key, input));
1149
1252
  }
1150
- /** This branch is unreachable for production legacy handlers until the caller cutover. */
1253
+ /**
1254
+ * The permission review of a managed call, with the escalation state a continued restricted
1255
+ * `Bash` call carries to its tool (its sandbox hints: retry with `sandbox: "escalated"` only
1256
+ * where this device and org allow it).
1257
+ */
1151
1258
  async reviewPermissionCall(ctx, call, tool, input) {
1259
+ const note = {};
1260
+ const outcome = await this.reviewPermissionCallWith(ctx, call, tool, input, note);
1261
+ return outcome?.kind === "continue" && note.escalation !== undefined
1262
+ ? { ...outcome, sandboxEscalation: note.escalation }
1263
+ : outcome;
1264
+ }
1265
+ async reviewPermissionCallWith(ctx, call, tool, input, note) {
1152
1266
  if (!this.permissionAuthority ||
1153
1267
  !this.permissionGrants ||
1154
1268
  !this.permissionLocks ||
@@ -1163,36 +1277,103 @@ let ToolPipeline = class ToolPipeline {
1163
1277
  const device = await this.deps.devices.reviewFacts(ctx.orgId, ctx.parent?.rootConversationId ?? ctx.conversationId, ctx.conversationId);
1164
1278
  if (!device)
1165
1279
  return null;
1280
+ // a run another account triggered never uses the owner's device (the tool refuses it): there
1281
+ // is no permission authority of that account here to review against
1282
+ if (ctx.accountId !== device.ownerAccountId)
1283
+ return null;
1166
1284
  const use = {
1167
1285
  orgId: ctx.orgId,
1168
1286
  deviceId: device.deviceId,
1169
1287
  holderConversationId: ctx.conversationId,
1170
1288
  actor: { accountId: ctx.accountId, conversationId: ctx.conversationId, runId: ctx.runId },
1171
1289
  };
1172
- const facts = await this.permissionAuthority.previewCall(use, { runId: ctx.runId, callId: call.id }, ctx.signal);
1173
- if (facts.availability.state !== "supported" || facts.unattended)
1290
+ const preview = () => this.permissionAuthority.previewCall(use, { runId: ctx.runId, callId: call.id }, ctx.signal);
1291
+ let facts = await preview();
1292
+ // the facts first: a device not yet started (or not yet probed) whose review depends on them
1293
+ // is started under the normal lifecycle lease, which records a cloud instance's permission
1294
+ // evidence or a local one's installed binding, and read again
1295
+ if (facts.availability.state === "unprobed" &&
1296
+ !facts.unattended &&
1297
+ this.sandboxes &&
1298
+ REVIEWED_ON_FACTS.has(tool.key)) {
1299
+ try {
1300
+ await this.sandboxes.ensureRunning(use, ctx.signal);
1301
+ facts = await preview();
1302
+ }
1303
+ catch (err) {
1304
+ // a start that fails leaves the facts unverified (the conservative branch below); the
1305
+ // tool's own entry reports the device's state
1306
+ ctx.signal.throwIfAborted();
1307
+ this.deps.log.warn("cannot start the device before its review; reviewing unverified", {
1308
+ conversationId: ctx.conversationId,
1309
+ deviceId: device.deviceId,
1310
+ err,
1311
+ });
1312
+ }
1313
+ }
1314
+ if (facts.unattended) {
1315
+ // an unattended run never runs a call outside the sandbox: no one could approve it
1316
+ if (isEscalatedCall(tool.key, input)) {
1317
+ const content = escalationRefusedText(ESCALATION_UNATTENDED_WHY, facts.workingRoot);
1318
+ return { kind: "result", content, review: denyRecord("rule", null, content) };
1319
+ }
1174
1320
  return null;
1321
+ }
1322
+ if (facts.availability.state !== "supported") {
1323
+ // still unverified: the conservative command review decides (Full access too), but a call
1324
+ // that needs more reach is refused now: admission could never run what an approval allowed
1325
+ if (facts.profile === "full-access")
1326
+ return null;
1327
+ const unverified = buildPermissionCandidate({ toolKey: tool.key, specHash: tool.specHash, rawInput: call.input, validatedInput: input }, facts, [device.home, device.deviceHome], { backgroundMaxSeconds: backgroundMaxSeconds(this.config.get()) });
1328
+ if (unverified.kind === "in-scope")
1329
+ return null;
1330
+ const content = unverified.kind === "proposal" ? PERMISSION_SUPPORT_UNVERIFIED_TEXT : unverified.message;
1331
+ return { kind: "result", content, review: denyRecord("rule", null, content) };
1332
+ }
1175
1333
  if (tool.key === "Bash" && textField(input, "command").length > COMMAND_ASK_MAX_CHARS)
1176
1334
  return {
1177
1335
  kind: "result",
1178
1336
  content: commandTooLongText(textField(input, "command").length),
1179
1337
  review: denyRecord("rule", null, "The command exceeds the review limit"),
1180
1338
  };
1181
- const built = facts.profile === "full-access"
1339
+ const escalated = isEscalatedCall(tool.key, input);
1340
+ // the escalation state the tool's hints read: only a restricted Bash call on a device and
1341
+ // org whose ceiling allows running outside the sandbox
1342
+ if (tool.key === "Bash" && facts.profile !== "full-access" && !facts.escalationRefusal)
1343
+ note.escalation = escalated ? "escalated" : "available";
1344
+ const built = facts.profile === "full-access" && !escalated
1182
1345
  ? { kind: "in-scope" }
1183
1346
  : buildPermissionCandidate({
1184
1347
  toolKey: tool.key,
1185
1348
  specHash: tool.specHash,
1186
1349
  rawInput: call.input,
1187
1350
  validatedInput: input,
1188
- }, facts);
1189
- if (built.kind === "unsupported")
1190
- return {
1191
- kind: "result",
1192
- content: built.message,
1193
- review: denyRecord("rule", null, built.message),
1194
- };
1351
+ }, facts, [device.home, device.deviceHome], { backgroundMaxSeconds: backgroundMaxSeconds(this.config.get()) });
1352
+ if (built.kind === "unsupported") {
1353
+ // a Bash reach the restricted scope cannot grant: retrying outside the sandbox may
1354
+ const content = note.escalation === "available"
1355
+ ? `${built.message}${ESCALATION_RETRY_HINT}`
1356
+ : built.message;
1357
+ return { kind: "result", content, review: denyRecord("rule", null, content) };
1358
+ }
1195
1359
  const candidate = built.kind === "proposal" ? built.candidate : undefined;
1360
+ // a sensitive-command consent the person settled (no proposed reach): the call runs under
1361
+ // the base scope it was asked under; the approval adds nothing
1362
+ if (previous &&
1363
+ previous.status !== "superseded" &&
1364
+ !candidate &&
1365
+ !previous.command?.permissionCandidate) {
1366
+ const settled = this.settledCommandAsk(previous, tool.key);
1367
+ // the root the person approved is carried only while the device still runs in the mode
1368
+ // recorded with the ask (B-18: the judged root stays the one recorded)
1369
+ if (settled.kind === "continue" &&
1370
+ settled.workingRoot !== undefined &&
1371
+ (device.mode !== previous.command?.mode ||
1372
+ carriedRoot({ workspace: device.workspace, workingRoot: settled.workingRoot }) ===
1373
+ undefined))
1374
+ return { ...settled, workingRoot: undefined };
1375
+ return settled;
1376
+ }
1196
1377
  if (previous &&
1197
1378
  previous.status !== "superseded" &&
1198
1379
  candidate &&
@@ -1214,8 +1395,9 @@ let ToolPipeline = class ToolPipeline {
1214
1395
  rootConversationId: facts.rootConversationId,
1215
1396
  }, { kind: "admit" }), () => this.findPermissionGrant(candidate));
1216
1397
  if (existingGrant) {
1217
- if (permissionScopeHash(existingGrant.expansion) !==
1218
- permissionScopeHash(candidate.permissionScope))
1398
+ if (existingGrant.scopeKind !== candidate.scopeKind ||
1399
+ permissionScopeHash(existingGrant.expansion) !==
1400
+ permissionScopeHash(candidate.permissionScope))
1219
1401
  return {
1220
1402
  kind: "result",
1221
1403
  content: "This call already has different permission evidence; submit a new call with the intended directory scope.",
@@ -1225,15 +1407,17 @@ let ToolPipeline = class ToolPipeline {
1225
1407
  kind: "continue",
1226
1408
  workingRoot: carriedRoot(device),
1227
1409
  reviewedAgainst: facts.workingRoot,
1410
+ // the evidence's real source: the person's approval or the review model's allow
1228
1411
  review: {
1229
1412
  decision: "allow",
1230
- by: "classifier",
1413
+ by: existingGrant.source === "human" ? "person" : "classifier",
1231
1414
  rule: null,
1232
1415
  reason: "The exact current call already has approved permission evidence.",
1233
1416
  profile: facts.profile,
1234
1417
  profileRevision: facts.profileRevision,
1235
1418
  scopeRevision: facts.scopeRevision,
1236
- decisionSource: "review-model",
1419
+ decisionSource: existingGrant.source === "human" ? "human" : "review-model",
1420
+ ...(candidate.escalation ? { sandbox: "escalated" } : {}),
1237
1421
  },
1238
1422
  };
1239
1423
  }
@@ -1259,6 +1443,7 @@ let ToolPipeline = class ToolPipeline {
1259
1443
  ...(ctx.conversationKind ? { conversationKind: ctx.conversationKind } : {}),
1260
1444
  permissionProfile: facts.profile,
1261
1445
  ...(candidate ? { permissionCandidate: candidate } : {}),
1446
+ ...(note.escalation === "available" ? { escalationAvailable: true } : {}),
1262
1447
  });
1263
1448
  if (candidate && facts.profile === "approve-for-me") {
1264
1449
  await withTransactionFencePrelude(() => permissionLocks.acquire({
@@ -1286,15 +1471,22 @@ let ToolPipeline = class ToolPipeline {
1286
1471
  review: {
1287
1472
  ...allowRecord(verdict),
1288
1473
  ...provenance,
1289
- decisionSource: facts.profile === "full-access" ? "full-access" : candidate ? "review-model" : "scope",
1474
+ decisionSource: facts.profile === "full-access"
1475
+ ? "full-access"
1476
+ : verdict.by === "classifier"
1477
+ ? "review-model"
1478
+ : "scope",
1479
+ // the review model's allow issued this call's escalation grant: it runs unsandboxed
1480
+ ...(candidate?.escalation && verdict.by === "classifier"
1481
+ ? { sandbox: "escalated" }
1482
+ : {}),
1290
1483
  },
1291
1484
  };
1292
- if (!candidate)
1293
- return {
1294
- kind: "result",
1295
- content: "Current permission review could not decide; retry with an explicit bounded directory or host.",
1296
- review: denyRecord(verdict.by, verdict.rule, verdict.reason),
1297
- };
1485
+ // an ask: the sensitive-command consent (no proposed reach: approved, the call runs under the
1486
+ // base scope) or the displayed expansion (approved, the call's grant is issued)
1487
+ const kind = reviewKindOf(tool.key);
1488
+ // every path the call writes (a GenerateImage call's suffixed paths, comma-separated)
1489
+ const filePaths = kind === "write" ? writePathsOf(tool.key, input).filter(Boolean) : [];
1298
1490
  const ask = await this.deps.approvals.requestCommand({
1299
1491
  orgId: ctx.orgId,
1300
1492
  conversationId: ctx.conversationId,
@@ -1302,26 +1494,54 @@ let ToolPipeline = class ToolPipeline {
1302
1494
  step: ctx.step,
1303
1495
  callId: call.id,
1304
1496
  requestedFor: ctx.accountId,
1305
- scopes: ["once"],
1497
+ // `session` only for a consent rule class with no expansion (a grant is per call)
1498
+ scopes: !candidate && isSessionGrantableRule(verdict.rule) ? ["once", "session"] : ["once"],
1306
1499
  detail: {
1307
1500
  deviceId: device.deviceId,
1308
1501
  deviceName: device.deviceName,
1309
1502
  mode: device.mode,
1310
- kind: reviewKindOf(tool.key),
1503
+ kind,
1311
1504
  command: tool.key === "Bash" ? textField(input, "command") : tool.key,
1312
1505
  rule: verdict.rule,
1313
- reason: verdict.reason,
1506
+ reason: clipText(verdict.reason, COMMAND_ASK_TEXT_MAX_CHARS),
1314
1507
  workingRoot: facts.workingRoot,
1315
- permissionCandidate: candidate,
1316
- permissionScope: candidate.permissionScope,
1317
- candidateHash: candidate.candidateHash,
1318
- ...(candidate.targetPath
1319
- ? { targetPath: candidate.targetPath, path: candidate.targetPath }
1320
- : {}),
1508
+ ...(candidate
1509
+ ? {
1510
+ permissionCandidate: candidate,
1511
+ permissionScope: candidate.permissionScope,
1512
+ candidateHash: candidate.candidateHash,
1513
+ ...(candidate.targetPath
1514
+ ? { targetPath: candidate.targetPath, path: candidate.targetPath }
1515
+ : {}),
1516
+ ...(candidate.escalation ? { escalation: candidate.escalation } : {}),
1517
+ }
1518
+ : filePaths.length > 0
1519
+ ? {
1520
+ path: clipText(filePaths.map((p) => pathAgainstWorkingRoot(p, facts.workingRoot)).join(", "), 4096),
1521
+ }
1522
+ : {}),
1321
1523
  },
1322
1524
  });
1323
1525
  return { kind: "wait", wait: approvalWait(ask) };
1324
1526
  }
1527
+ /**
1528
+ * Whether an execution of this call was admitted outside the sandbox under a restricted profile
1529
+ * (a per-call escalation's full reach): an intent past admission, or one revoked after dispatch.
1530
+ */
1531
+ async admittedOutsideSandbox(runId, callId) {
1532
+ const rows = await this.deps.db
1533
+ .selectFrom("sandbox_operation_intents")
1534
+ .select(["scope", "state", "outcome_unknown"])
1535
+ .where("run_id", "=", runId)
1536
+ .where("call_id", "=", callId)
1537
+ .where("method", "in", ["exec", "backgroundStart"])
1538
+ .execute();
1539
+ return rows.some((r) => {
1540
+ const scope = r.scope;
1541
+ const admitted = r.state === "revoked" ? r.outcome_unknown : r.state !== "pending";
1542
+ return admitted && scope.profile !== "full-access" && scope.filesystem?.kind === "device";
1543
+ });
1544
+ }
1325
1545
  findPermissionGrant(candidate) {
1326
1546
  if (!this.permissionGrants)
1327
1547
  throw new Error("Permission grants are unavailable");
@@ -1339,14 +1559,16 @@ let ToolPipeline = class ToolPipeline {
1339
1559
  ...candidate,
1340
1560
  outcome: verdict.decision,
1341
1561
  reason: verdict.reason,
1342
- decisionSource: "review-model",
1562
+ // the review model only for its own verdict: a fixed rule's deny, a rule ask (the review
1563
+ // model unmapped or not consulted) and the fail-closed ask are the rules'
1564
+ decisionSource: verdict.by === "classifier" ? "review-model" : "rule",
1343
1565
  },
1344
1566
  },
1345
1567
  ]);
1346
1568
  const event = events[0];
1347
1569
  if (!event)
1348
1570
  throw new Error("The review event was not recorded");
1349
- if (verdict.decision === "allow")
1571
+ if (verdict.decision === "allow" && verdict.by === "classifier")
1350
1572
  await this.permissionGrants.issueLocked(candidate, {
1351
1573
  source: "review-model",
1352
1574
  reviewEventSeq: event.seq,
@@ -1385,7 +1607,9 @@ let ToolPipeline = class ToolPipeline {
1385
1607
  */
1386
1608
  personAllowRecord(ask) {
1387
1609
  const binding = ask.command?.permissionCandidate?.binding;
1610
+ const escalated = ask.command?.permissionCandidate?.scopeKind === "sandbox-escalation";
1388
1611
  return {
1612
+ ...(escalated ? { sandbox: "escalated" } : {}),
1389
1613
  ...(binding
1390
1614
  ? {
1391
1615
  profile: binding.profile,
@@ -1620,6 +1844,8 @@ let ToolPipeline = class ToolPipeline {
1620
1844
  // and the root it was judged against, workspace included (B-18, the managed route)
1621
1845
  ...(tool.source.kind === "builtin" &&
1622
1846
  reviewedAgainstRoot !== undefined && { reviewedAgainstRoot }),
1847
+ ...(tool.source.kind === "builtin" &&
1848
+ reviewed?.escalation !== undefined && { sandboxEscalation: reviewed.escalation }),
1623
1849
  // a sub-agent works in its root conversation's sandbox (spec §10.1, at every depth)
1624
1850
  ...(tool.source.kind === "builtin" &&
1625
1851
  ctx.parent !== undefined && { sandboxConversationId: ctx.parent.rootConversationId }),
@@ -2078,6 +2304,10 @@ ToolPipeline = __decorate([
2078
2304
  __param(23, Optional()),
2079
2305
  __param(23, Inject(PermissionCallGrants)),
2080
2306
  __param(24, Optional()),
2081
- __param(24, Inject(PermissionAuthorityLock))
2307
+ __param(24, Inject(PermissionAuthorityLock)),
2308
+ __param(25, Optional()),
2309
+ __param(25, Inject(PERMISSION_CONTEXT_ACTIVATION)),
2310
+ __param(26, Optional()),
2311
+ __param(26, Inject(SandboxService))
2082
2312
  ], ToolPipeline);
2083
2313
  export { ToolPipeline };
@@ -65,6 +65,13 @@ export interface BuiltinCallContext extends ToolCallContext {
65
65
  * runs. Absent for a call the review does not cover.
66
66
  */
67
67
  reviewedAgainstRoot?: string;
68
+ /**
69
+ * A reviewed `Bash` call under a restricted profile (per-call sandbox escalation): `escalated`
70
+ * when this call was approved to run outside the OS sandbox, `available` when it runs sandboxed
71
+ * but could be retried with `sandbox: "escalated"` on this device. Absent otherwise (Full access,
72
+ * an unattended run, a device or org that forbids it): no escalation hint is given.
73
+ */
74
+ sandboxEscalation?: "available" | "escalated";
68
75
  /** The parent run of a sub-agent's run (absent for a top-level run). */
69
76
  parentRunId?: string;
70
77
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.49",
3
+ "version": "0.1.0-rc.50",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -65,7 +65,7 @@
65
65
  "yaml": "^2.9.1",
66
66
  "yauzl": "3.4.0",
67
67
  "zod": "^4.6.7",
68
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.35"
68
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.36"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -74,8 +74,8 @@
74
74
  "@types/ws": "^8.18.2",
75
75
  "@types/yauzl": "3.4.0",
76
76
  "ws": "^8.22.0",
77
- "@capybara-hq/device": "0.1.0-rc.14",
78
- "@capybara-hq/testing": "0.1.0-rc.27"
77
+ "@capybara-hq/device": "0.1.0-rc.15",
78
+ "@capybara-hq/testing": "0.1.0-rc.28"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc -b"
@@ -0,0 +1,9 @@
1
+ -- Per-call sandbox escalation (approval profiles design, "Per-call sandbox escalation"): a call
2
+ -- grant may run one Bash call outside the OS sandbox; its justification is part of the evidence.
3
+ ALTER TABLE permission_call_grants ADD COLUMN IF NOT EXISTS escalation jsonb;
4
+ ALTER TABLE permission_call_grants DROP CONSTRAINT IF EXISTS permission_call_grants_scope_kind_check;
5
+ ALTER TABLE permission_call_grants ADD CONSTRAINT permission_call_grants_scope_kind_check
6
+ CHECK (scope_kind IN ('directories-and-hosts', 'sandbox-escalation'));
7
+ ALTER TABLE permission_call_grants DROP CONSTRAINT IF EXISTS permission_call_grants_escalation_check;
8
+ ALTER TABLE permission_call_grants ADD CONSTRAINT permission_call_grants_escalation_check
9
+ CHECK ((scope_kind = 'sandbox-escalation') = (escalation IS NOT NULL));
@@ -1,35 +0,0 @@
1
- import type { BackgroundFinish } from "./finish.js";
2
- import type { BackgroundTaskRow } from "./store.js";
3
- /** What the poll exec reports for one task. */
4
- export interface TaskReport {
5
- /** The exit file's code; null while there is none. */
6
- exitCode: number | null;
7
- /**
8
- * Whether the session still has a process: `pgrep -s <sid>` (`-g` on macOS), or, for a task whose command
9
- * exited, whether its leftover processes could not be confirmed killed.
10
- */
11
- alive: boolean;
12
- /** The last lines (decoded), read when the task exited or no process was left. */
13
- lastLines: string;
14
- }
15
- /**
16
- * The poll exec of one sandbox: for every task one line `<id> <exit code or -> <1|0> <tail or ->`.
17
- * Liveness is asked before the exit file: a task ending in between is seen by its exit file, never
18
- * as a task without process and exit file. A task whose command exited while its session still has
19
- * processes (it left `server &` running) has the session killed in the same exec (so under the
20
- * caller's lease), and is reported without a process once the session was confirmed empty: the
21
- * task ends when its command exits, and nothing of it runs on untracked. The tail (base64) is read
22
- * only for a task that exited or has no process left. Relative to the workspace root.
23
- */
24
- export declare function pollScript(tasks: {
25
- id: string;
26
- sid: string;
27
- }[]): string;
28
- /** Parses {@link pollScript}'s output; a task missing from it is absent from the map. */
29
- export declare function parsePollOutput(stdout: string): Map<string, TaskReport>;
30
- /**
31
- * How a polled task ends, or null while it runs (spec §4.3). A task whose command exited but whose
32
- * leftover processes could not be confirmed killed ({@link pollScript}) stays running: the next
33
- * poll kills them again before it finishes.
34
- */
35
- export declare function polledAs(task: BackgroundTaskRow, r: TaskReport, now: Date): BackgroundFinish | null;