@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
@@ -1,6 +1,8 @@
1
+ import { isIP } from "node:net";
1
2
  import path from "node:path";
2
- import { validateAllowHost } from "@capybara-hq/plugin-sdk";
3
+ import { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS, validateAllowHost, } from "@capybara-hq/plugin-sdk";
3
4
  import { ApiError } from "../../errors.js";
5
+ import { HIDDEN_FORMAT_RE } from "../../text.js";
4
6
  import { generateImagePaths } from "../../tools/builtins/image/paths.js";
5
7
  import { coversHost } from "../modes.js";
6
8
  import { hostsWithinOuter, permissionScopeHash } from "../permission-facts.js";
@@ -39,13 +41,182 @@ export function normalizePermissionExpansion(value, base) {
39
41
  export function permissionCandidateHash(candidate) {
40
42
  return permissionScopeHash(candidate);
41
43
  }
42
- /** Extract proposals from the actual validated call. Parsing proposes reach; it never grants it. */
43
- export function buildPermissionCandidate(call, facts) {
44
+ /** The `Bash` `sandbox` value that asks to run this one call outside the OS sandbox. */
45
+ export const SANDBOX_ESCALATED = "escalated";
46
+ /** The longest justification an escalated call may give (the tool schema says the same). */
47
+ export const ESCALATION_JUSTIFICATION_MAX_CHARS = 500;
48
+ /** A background escalation's sentence (empty for a foreground one), for the reason and the review. */
49
+ export function escalationBackgroundText(escalation) {
50
+ if (escalation.background !== true)
51
+ return "";
52
+ const limit = escalation.maxSeconds !== undefined
53
+ ? `, at most ${Math.ceil(escalation.maxSeconds / 60)} minutes`
54
+ : "";
55
+ return ` It starts a background process that keeps running outside the sandbox until it exits or is stopped${limit}.`;
56
+ }
57
+ /**
58
+ * The agent's justification as one quoted line: line breaks and other control characters become
59
+ * spaces, bidi and other hidden format characters are removed (ZWNJ / ZWJ stay), spaces collapse.
60
+ * It is the agent's text inside a reason written in the kernel's voice, so it is always quoted.
61
+ */
62
+ export function quotedJustification(text) {
63
+ const clean = text
64
+ .replace(HIDDEN_FORMAT_RE, "")
65
+ .replace(/\p{Cc}/gu, " ")
66
+ .replace(/\s+/g, " ")
67
+ .trim();
68
+ return `"${clean}"`;
69
+ }
70
+ /**
71
+ * What an ask about a per-call sandbox escalation tells the person (and the review model): the
72
+ * crossing, that a background start keeps running outside the sandbox (and for how long at most),
73
+ * the agent's quoted justification and, when the command is also sensitive, that consent too.
74
+ */
75
+ export const escalationAskReason = (escalation, sensitive) => `Run this command outside the sandbox for this call only (full access to the device's files and network).${escalationBackgroundText(escalation)} Justification (from the agent): ${quotedJustification(escalation.justification)}${sensitive ? ` It is also a sensitive command: ${sensitive}` : ""}`;
76
+ /** The length of a justification as the tool schema counts it: Unicode code points. */
77
+ export const justificationLength = (text) => [...text].length;
78
+ /** An escalated call whose justification is over the limit: refused before any review. */
79
+ export const ESCALATION_JUSTIFICATION_TOO_LONG_TEXT = 'This Bash call asked to run outside the sandbox (sandbox: "escalated") with a justification longer than 500 characters, so it did not run. Retry with a justification of one short sentence saying why this command must run outside the sandbox.';
80
+ /** Whether a validated call asks to run outside the OS sandbox (only `Bash` can). */
81
+ export const isEscalatedCall = (toolKey, input) => toolKey === "Bash" &&
82
+ input?.sandbox === SANDBOX_ESCALATED;
83
+ /** An escalated call without a usable justification: refused before any review. */
84
+ export const ESCALATION_JUSTIFICATION_MISSING_TEXT = 'This Bash call asked to run outside the sandbox (sandbox: "escalated") without a justification, so it did not run. Retry with justification: one sentence saying why this command must run outside the sandbox, or call Bash without sandbox to run it in the sandbox.';
85
+ /** Why an escalation cannot be reviewed: an unattended run (no one can approve it). */
86
+ export const ESCALATION_UNATTENDED_WHY = "this is an unattended run (a scheduled task) where no one can approve running outside the sandbox";
87
+ /** Why an escalation cannot be reviewed: the device, org or platform forbids Full access. */
88
+ export const ESCALATION_CEILING_WHY = "running commands outside the sandbox is not allowed on this device (its owner, the organization or the platform has not allowed Full access)";
89
+ /** Why an escalation cannot be reviewed: the runtime cannot run Full access now. */
90
+ export const escalationRuntimeWhy = (reason) => `this device cannot run commands outside its sandbox now (${reason.replace(/\.$/, "")})`;
91
+ /** What the model gets when its escalated call cannot be reviewed, with what works instead. */
92
+ export const escalationRefusedText = (why, workingRoot) => `This Bash call asked to run outside the sandbox, but ${why}, so it did not run. Call Bash without sandbox: "escalated" to run the command inside the sandbox (inside ${workingRoot} and the directories already granted), or ask the user to run it themselves or to allow Full access on this device.`;
93
+ /**
94
+ * Appended to a refusal of a restricted `Bash` call (the sandbox or the restricted scope stopped
95
+ * it) when this device and org allow running outside the sandbox: the model may retry the same
96
+ * call escalated, and the profile's approver decides.
97
+ */
98
+ export const ESCALATION_RETRY_HINT = ' If this command must reach outside the sandbox, retry the same Bash call with sandbox: "escalated" and justification: one sentence saying why; the user or the review model decides whether it may run outside the sandbox for this call only.';
99
+ export const approverForProfile = (profile) => profile === "request-approval"
100
+ ? "person"
101
+ : profile === "approve-for-me"
102
+ ? "review-model"
103
+ : "none";
104
+ /** The paths a local device never opens to restricted work, relative to `~`. */
105
+ const OWNER_DENIED_PATHS = [...DEVICE_DENIED_SECRET_PATHS, DEVICE_DEFAULT_STATE_PATH];
106
+ /**
107
+ * The owner-denied path (as `~/…`) that `target` is at or under for one of `homes`, if any: the
108
+ * device refuses such a root to every restricted grant, so no approval could make it run.
109
+ */
110
+ function ownerDeniedPath(target, homes) {
111
+ for (const home of homes)
112
+ for (const denied of OWNER_DENIED_PATHS)
113
+ if (withinDirectory(target, path.posix.join(home, denied.slice(2))))
114
+ return denied;
115
+ return undefined;
116
+ }
117
+ const ownerDeniedText = (denied, target) => `${target} is under ${denied}, which the device never opens to this conversation's permission profile (a credential location or the device's own state), so this call cannot be approved and did not run. Ask the user to provide what is needed from it, or to choose Full access for this conversation if it must be used there.`;
118
+ /**
119
+ * A background escalation's disclosure: it starts a process that keeps running outside the
120
+ * sandbox until it exits or is stopped, at most the task's deadline (the requested timeout
121
+ * lowered to the background maximum, as the launch computes it). Empty for a foreground call.
122
+ */
123
+ function backgroundOf(input, maxSeconds) {
124
+ const i = input;
125
+ if (i?.run_in_background !== true)
126
+ return {};
127
+ if (maxSeconds === undefined || !(maxSeconds > 0))
128
+ return { background: true };
129
+ const maxMs = maxSeconds * 1000;
130
+ const requested = typeof i.timeout === "number" && i.timeout > 0 ? i.timeout : maxMs;
131
+ return {
132
+ background: true,
133
+ maxSeconds: Math.max(1, Math.ceil(Math.min(requested, maxMs) / 1000)),
134
+ };
135
+ }
136
+ /** The exact call binding of a candidate: server identity from the facts, the call's own digests. */
137
+ function bindingOf(call, facts) {
138
+ return {
139
+ orgId: facts.orgId,
140
+ rootConversationId: facts.rootConversationId,
141
+ conversationId: facts.conversationId,
142
+ deviceId: facts.deviceId,
143
+ accountId: facts.accountId,
144
+ runId: facts.runId,
145
+ callId: facts.callId,
146
+ profile: facts.profile,
147
+ profileRevision: facts.profileRevision,
148
+ scopeRevision: facts.scopeRevision,
149
+ authorityRevision: facts.authorityRevision,
150
+ toolKey: call.toolKey,
151
+ specHash: call.specHash,
152
+ callInputHash: permissionScopeHash(call.rawInput),
153
+ resolvedInputHash: permissionScopeHash(call.validatedInput),
154
+ };
155
+ }
156
+ /**
157
+ * Extract proposals from the actual validated call. Parsing proposes reach; it never grants it.
158
+ * `homes` are the owner's home candidates (the machine's home, the workspace's home prefix): a
159
+ * call reaching an owner-denied path under one is refused, never proposed.
160
+ */
161
+ export function buildPermissionCandidate(call, facts, homes = [], opts = {}) {
162
+ const homeRoots = [
163
+ ...new Set(homes.filter((h) => typeof h === "string" && h.startsWith("/") && h !== "/" && path.posix.normalize(h) === h)),
164
+ ];
165
+ const refuseDenied = (target) => {
166
+ const denied = ownerDeniedPath(target, homeRoots);
167
+ if (denied)
168
+ throw new Error(ownerDeniedText(denied, target));
169
+ };
44
170
  const input = call.validatedInput;
171
+ // a per-call sandbox escalation: one Bash call with full execution, never a directory or host
172
+ // expansion; Full access already runs every call that way, so there it asks for nothing more
173
+ if (isEscalatedCall(call.toolKey, input)) {
174
+ // no approver (Full access): granted for this call within the ceiling, never past it. Full
175
+ // access runs every call outside the sandbox today, so there is no grant to issue (until the
176
+ // profile-semantics refactor keeps the sandbox under every profile)
177
+ if (approverForProfile(facts.profile) === "none")
178
+ return facts.escalationRefusal
179
+ ? {
180
+ kind: "unsupported",
181
+ code: "escalation-unavailable",
182
+ message: escalationRefusedText(facts.escalationRefusal, facts.workingRoot),
183
+ }
184
+ : { kind: "in-scope" };
185
+ const justification = input.justification;
186
+ if (typeof justification !== "string" || justification.trim() === "")
187
+ return {
188
+ kind: "unsupported",
189
+ code: "escalation-unavailable",
190
+ message: ESCALATION_JUSTIFICATION_MISSING_TEXT,
191
+ };
192
+ if (justificationLength(justification) > ESCALATION_JUSTIFICATION_MAX_CHARS)
193
+ return {
194
+ kind: "unsupported",
195
+ code: "escalation-unavailable",
196
+ message: ESCALATION_JUSTIFICATION_TOO_LONG_TEXT,
197
+ };
198
+ if (facts.unattended || facts.escalationRefusal)
199
+ return {
200
+ kind: "unsupported",
201
+ code: "escalation-unavailable",
202
+ message: escalationRefusedText(facts.unattended ? ESCALATION_UNATTENDED_WHY : facts.escalationRefusal, facts.workingRoot),
203
+ };
204
+ const candidate = {
205
+ binding: bindingOf(call, facts),
206
+ permissionScope: { readDirectories: [], writeDirectories: [], hosts: [] },
207
+ scopeKind: "sandbox-escalation",
208
+ escalation: { justification, ...backgroundOf(input, opts.backgroundMaxSeconds) },
209
+ };
210
+ return {
211
+ kind: "proposal",
212
+ candidate: Object.freeze({ ...candidate, candidateHash: permissionCandidateHash(candidate) }),
213
+ };
214
+ }
45
215
  let targetPath;
46
216
  const reads = [], writes = [], hosts = [];
47
217
  const proposeDirectory = (value, write) => {
48
218
  const normalized = directory(path.posix.resolve(facts.workingRoot, value));
219
+ refuseDenied(normalized);
49
220
  const base = write ? facts.baseWriteDirectories : facts.baseReadDirectories;
50
221
  if (!base.some((root) => withinDirectory(normalized, root)))
51
222
  (write ? writes : reads).push(normalized);
@@ -60,11 +231,17 @@ export function buildPermissionCandidate(call, facts) {
60
231
  try {
61
232
  if (targets.length > 0) {
62
233
  const write = call.toolKey !== "Read", base = write ? facts.baseWriteDirectories : facts.baseReadDirectories;
63
- const resolved = targets.map((target) => {
234
+ for (const target of targets)
64
235
  if (target.length > 4096 || /[\0*?[\]{}]/.test(target))
65
236
  throw new Error("Invalid target path");
66
- return path.posix.resolve(facts.workingRoot, target);
67
- });
237
+ // a `..` segment proposes nothing: the file tools refuse that path shape themselves. A `.`
238
+ // segment is normalized lexically like any other spelling (`/outside/./x` is `/outside/x`)
239
+ if (targets.some((target) => target.split("/").some((segment) => segment === "..")))
240
+ return { kind: "in-scope" };
241
+ const resolved = targets.map((target) => path.posix.resolve(facts.workingRoot, target));
242
+ // inside the base scope too: the credential consent it would get could never run there
243
+ for (const target of resolved)
244
+ refuseDenied(target);
68
245
  for (const target of resolved) {
69
246
  if (!base.some((root) => withinDirectory(target, root))) {
70
247
  proposeDirectory(path.posix.dirname(target), write);
@@ -84,6 +261,9 @@ export function buildPermissionCandidate(call, facts) {
84
261
  if (!/^https?:\/\//i.test(word))
85
262
  continue;
86
263
  const url = new URL(word);
264
+ // an IP literal is no grantable host: nothing is proposed, the enforced network decides
265
+ if (isIP(url.hostname.replace(/^\[|\]$/g, "")) !== 0)
266
+ continue;
87
267
  if (url.username ||
88
268
  url.password ||
89
269
  url.hostname.includes("*") ||
@@ -104,26 +284,13 @@ export function buildPermissionCandidate(call, facts) {
104
284
  if ((!facts.broadProjectReach && (reads.length || writes.length)) ||
105
285
  hosts.some((host) => facts.policy.network.kind !== "open-public" &&
106
286
  !facts.policy.network.hosts.some((pattern) => coversHost(pattern, host))))
107
- throw new Error("The requested expansion exceeds current owner or organization limits");
108
- const { orgId, rootConversationId, conversationId, deviceId, accountId, runId, callId, profile, profileRevision, scopeRevision, authorityRevision, } = facts;
287
+ throw new Error(`This call needs access outside the working directory ${facts.workingRoot} (${[
288
+ ...writes,
289
+ ...reads,
290
+ ...hosts,
291
+ ].join(", ")}), which the device owner's or the organization's limits do not allow, so it did not run. Keep the call inside ${facts.workingRoot}, or ask the user to have the device's limits widened.`);
109
292
  const candidate = {
110
- binding: {
111
- orgId,
112
- rootConversationId,
113
- conversationId,
114
- deviceId,
115
- accountId,
116
- runId,
117
- callId,
118
- profile,
119
- profileRevision,
120
- scopeRevision,
121
- authorityRevision,
122
- toolKey: call.toolKey,
123
- specHash: call.specHash,
124
- callInputHash: permissionScopeHash(call.rawInput),
125
- resolvedInputHash: permissionScopeHash(call.validatedInput),
126
- },
293
+ binding: bindingOf(call, facts),
127
294
  permissionScope,
128
295
  ...(targetPath ? { targetPath } : {}),
129
296
  scopeKind: "directories-and-hosts",
@@ -8,6 +8,7 @@ import { ModelPurposesService } from "../../models/purposes.js";
8
8
  import type { ConversationKindForHooks } from "../../runtime/hook-calls.js";
9
9
  import { StepLog } from "../../runtime/step-log.js";
10
10
  import type { PermissionCandidate } from "../permission-call-types.js";
11
+ export { escalationAskReason, quotedJustification } from "./permission-candidate.js";
11
12
  /**
12
13
  * The command review the tool pipeline calls (auto mode spec §5): stage 1 the pure rule table, stage
13
14
  * 2 the classifier on the `review` model purpose for the `unsure` hits, then the conversation's
@@ -30,6 +31,11 @@ export interface ReviewVerdict {
30
31
  export interface ReviewInput {
31
32
  permissionProfile?: PermissionProfile;
32
33
  permissionCandidate?: PermissionCandidate;
34
+ /**
35
+ * A restricted `Bash` call on a device and org whose ceiling allows running outside the sandbox:
36
+ * a refusal of its outside reach tells the model it may retry with `sandbox: "escalated"`.
37
+ */
38
+ escalationAvailable?: boolean;
33
39
  orgId: string;
34
40
  /**
35
41
  * The root conversation of the run's tree: where the person's messages (the classifier's bounded
@@ -115,6 +121,18 @@ export declare class CommandReviewService implements CommandReview {
115
121
  host: Pick<ExtensionHost, "hooks" | "current"> | undefined);
116
122
  private get db();
117
123
  review(input: ReviewInput & ReviewCall): Promise<ReviewVerdict>;
124
+ /**
125
+ * The permission review of a managed call (permission operation contract, policy order), after
126
+ * the fixed denies: Full access has no discretionary review; Request approval and Approve for me
127
+ * keep the sensitive-command consent (the fixed asks: sudo, credentials, persistent changes,
128
+ * force push, ...), which comes before any reach. A call with neither a consent ask nor a
129
+ * proposed expansion runs under the enforced base scope with no review. Otherwise Request
130
+ * approval asks the person and Approve for me asks the review model (an ask when it is not
131
+ * configured, unsure or failing; its deny is never an approval). The scope asks of the rules
132
+ * (a write or link outside the workspace) are not consent: the proposed expansion carries them,
133
+ * and without one the enforced scope decides. An ask keeps its rule id.
134
+ */
135
+ private decidePermission;
118
136
  private decide;
119
137
  /** Whether a `review` model purpose is mapped and usable in the organization. */
120
138
  private classifierMapped;
@@ -17,8 +17,24 @@ import { ModelPurposesService } from "../../models/purposes.js";
17
17
  import { StepLog } from "../../runtime/step-log.js";
18
18
  import { generateImagePaths } from "../../tools/builtins/image/paths.js";
19
19
  import { boundMessages, newReviewTag, REVIEW_ASK_REASON, REVIEW_PURPOSE, runClassifier, } from "./classifier.js";
20
+ import { approverForProfile, ESCALATION_RETRY_HINT, escalationAskReason, } from "./permission-candidate.js";
21
+ export { escalationAskReason, quotedJustification } from "./permission-candidate.js";
20
22
  import { reviewRules, reviewWrite, writtenPaths } from "./rules.js";
21
23
  import { applySessionGrants, isSessionGrantableRule, } from "./types.js";
24
+ /**
25
+ * The rule asks about reach, not consent: a write or a link outside the workspace. On the managed
26
+ * route the enforced scope and a proposed expansion decide them.
27
+ */
28
+ const SCOPE_ASK_RULES = new Set(["ask.outside-write", "ask.outside-link"]);
29
+ /** The consent a file read keeps: reading a credential file or SSH keys. */
30
+ const CREDENTIAL_READ_RULES = new Set(["ask.secret-file", "ask.ssh"]);
31
+ /**
32
+ * Every ask about an escalation keeps its statement first: an ask the review model made, or one
33
+ * the review fell back to (failed, unparseable, truncated), adds its own reason after it.
34
+ */
35
+ const withEscalation = (statement, reason) => reason === statement ? statement : `${statement} Review: ${reason}`;
36
+ /** What an ask about a proposed expansion tells the person. */
37
+ const EXPANSION_ASK_REASON = "Approve the exact proposed directory and host access for this call. File-only grants are not supported: directory approval covers its descendants; otherwise choose an in-project path.";
22
38
  /** The reasons the service itself answers with (the rule table's own reasons come from its hits). */
23
39
  export const REVIEW_REASONS = {
24
40
  /** The tool is not one the review covers. */
@@ -95,9 +111,142 @@ let CommandReviewService = class CommandReviewService {
95
111
  toolKey: input.toolKey,
96
112
  err,
97
113
  });
98
- return { decision: "ask", by: "rule", reason: REVIEW_ASK_REASON, rule: null };
114
+ const escalation = input.permissionCandidate?.scopeKind === "sandbox-escalation"
115
+ ? input.permissionCandidate.escalation
116
+ : undefined;
117
+ return {
118
+ decision: "ask",
119
+ by: "rule",
120
+ reason: escalation
121
+ ? withEscalation(escalationAskReason(escalation), REVIEW_ASK_REASON)
122
+ : REVIEW_ASK_REASON,
123
+ rule: null,
124
+ };
99
125
  }
100
126
  }
127
+ /**
128
+ * The permission review of a managed call (permission operation contract, policy order), after
129
+ * the fixed denies: Full access has no discretionary review; Request approval and Approve for me
130
+ * keep the sensitive-command consent (the fixed asks: sudo, credentials, persistent changes,
131
+ * force push, ...), which comes before any reach. A call with neither a consent ask nor a
132
+ * proposed expansion runs under the enforced base scope with no review. Otherwise Request
133
+ * approval asks the person and Approve for me asks the review model (an ask when it is not
134
+ * configured, unsure or failing; its deny is never an approval). The scope asks of the rules
135
+ * (a write or link outside the workspace) are not consent: the proposed expansion carries them,
136
+ * and without one the enforced scope decides. An ask keeps its rule id.
137
+ */
138
+ async decidePermission(input, result, facts) {
139
+ // no approver (Full access): nothing discretionary is asked; a crossing the candidate names is
140
+ // granted for this call within the ceiling the candidate builder already checked
141
+ const approver = approverForProfile(input.permissionProfile ?? "approve-for-me");
142
+ if (approver === "none")
143
+ return allow("Current Full access covers discretionary review.", null);
144
+ const escalation = input.permissionCandidate?.scopeKind === "sandbox-escalation"
145
+ ? input.permissionCandidate.escalation
146
+ : undefined;
147
+ // a command writing or linking outside the working directory with no proposal (only a
148
+ // literal `cd <dir>` proposes a command's directory): no approval could let the enforced scope
149
+ // run it, so it is refused now with what works instead
150
+ const commandScopeHit = facts.kind === "command" && !input.permissionCandidate
151
+ ? result.hits.find((h) => h.outcome === "ask" && SCOPE_ASK_RULES.has(h.id))
152
+ : undefined;
153
+ if (commandScopeHit)
154
+ return {
155
+ decision: "deny",
156
+ by: "rule",
157
+ rule: commandScopeHit.id,
158
+ reason: `${commandScopeHit.reason.replace(/[.;]?\s*this needs approval\.?$/i, "")}, which this conversation's permission profile does not reach, and a command's own outside write cannot be approved inside the sandbox; write the file with Write or Edit (its directory can be approved), run the command after a literal \`cd\` into that directory, or keep it inside ${facts.workspace}${input.escalationAvailable ? `; ${ESCALATION_RETRY_HINT.trim().replace(/^If/, "if")}` : ""}`,
159
+ };
160
+ // the consent cases: the fixed asks and the unsure findings (an interpreter's inline code, an
161
+ // unparsed or uncovered line), which keep the profile's review. A read keeps only the
162
+ // credential reads: the write rules (persistence, shell config) are no consent for a read
163
+ const consentHits = result.hits.filter((h) => facts.kind === "read"
164
+ ? h.outcome === "ask" && CREDENTIAL_READ_RULES.has(h.id)
165
+ : (h.outcome === "ask" && !SCOPE_ASK_RULES.has(h.id)) || h.outcome === "unsure");
166
+ let consent;
167
+ let granted;
168
+ if (consentHits.length > 0) {
169
+ // a session grant covers its own class only, and only while the person is there to have
170
+ // given it (hardening spec R4, R6)
171
+ const grants = input.attended
172
+ ? await this.grantedRules(await facts.rootOf())
173
+ : new Set();
174
+ const after = applySessionGrants({ outcome: "ask", hits: consentHits }, (rule) => grants.has(rule));
175
+ if (after.outcome === "ask" || after.outcome === "unsure")
176
+ consent = after.hit;
177
+ else
178
+ granted = after.hit;
179
+ }
180
+ const candidate = input.permissionCandidate;
181
+ if (!consent && !candidate) {
182
+ if (granted)
183
+ return allow(REVIEW_REASONS.sessionGrant, granted.id);
184
+ // the rule table's allow, when it has one, says why; the enforced scope covers the rest
185
+ const allowed = result.outcome === "allow" ? decidingHit(result.hits, "allow") : undefined;
186
+ return allowed
187
+ ? allow(allowed.reason, allowed.id)
188
+ : allow("The enforced operation scope covers this call without expansion.", null);
189
+ }
190
+ const scopeHit = facts.kind === "read"
191
+ ? undefined
192
+ : result.hits.find((h) => h.outcome === "ask" && SCOPE_ASK_RULES.has(h.id));
193
+ const rule = consent?.id ?? (candidate ? (scopeHit?.id ?? null) : null);
194
+ // an escalation's one ask states both what it crosses and any sensitive consent it carries
195
+ const reason = escalation
196
+ ? escalationAskReason(escalation, consent?.reason)
197
+ : (consent?.reason ??
198
+ (scopeHit?.reason ? `${scopeHit.reason} ${EXPANSION_ASK_REASON}` : EXPANSION_ASK_REASON));
199
+ const ask = { decision: "ask", by: "rule", rule, reason };
200
+ if (approver === "person")
201
+ return ask;
202
+ if (!(await this.classifierMapped(input.orgId)))
203
+ return ask;
204
+ const answer = await runClassifier({
205
+ purposes: this.purposes,
206
+ eventLog: this.eventLog,
207
+ stepLog: this.stepLog,
208
+ config: this.config,
209
+ log: this.log,
210
+ hooks: this.host?.hooks,
211
+ }, {
212
+ orgId: input.orgId,
213
+ conversationId: input.conversationId,
214
+ runId: input.runId,
215
+ step: input.step,
216
+ callId: input.callId,
217
+ signal: input.signal,
218
+ ...(input.parentRunId !== undefined && {
219
+ parentRunId: input.parentRunId,
220
+ ...(input.budgetRunId !== undefined && { budgetRunId: input.budgetRunId }),
221
+ }),
222
+ hookFacts: {
223
+ accountId: input.accountId,
224
+ agentId: input.agentId,
225
+ agentVersion: input.agentVersion,
226
+ conversationKind: input.conversationKind,
227
+ parent: input.parent,
228
+ },
229
+ input: {
230
+ mode: input.mode,
231
+ kind: facts.kind,
232
+ text: facts.target,
233
+ cwd: facts.workspace,
234
+ ruleHits: result.hits,
235
+ personMessages: await this.personMessages(await facts.rootOf()),
236
+ tag: newReviewTag(),
237
+ ...(candidate ? { permissionCandidate: candidate } : {}),
238
+ },
239
+ beforeSend: input.beforeSend,
240
+ });
241
+ // the review model's ask still shows the rule the person is asked about
242
+ if (answer.decision === "ask")
243
+ return {
244
+ ...ask,
245
+ by: "classifier",
246
+ reason: escalation ? withEscalation(reason, answer.reason) : answer.reason,
247
+ };
248
+ return { decision: answer.decision, by: "classifier", reason: answer.reason, rule: null };
249
+ }
101
250
  async decide(input) {
102
251
  // not a reviewed tool, a sandbox-mode write (the tools stay root-confined), or no device: the
103
252
  // tool call proceeds and fails on its own if it cannot
@@ -151,17 +300,14 @@ let CommandReviewService = class CommandReviewService {
151
300
  rule: hit?.id ?? null,
152
301
  };
153
302
  }
154
- if (input.permissionProfile === "full-access")
155
- return allow("Current Full access covers discretionary review.", null);
156
- if (input.permissionProfile && !input.permissionCandidate)
157
- return allow("The enforced operation scope covers this call without expansion.", null);
158
- if (input.permissionProfile === "request-approval")
159
- return {
160
- decision: "ask",
161
- by: "rule",
162
- rule: null,
163
- reason: "Approve the exact proposed directory and host access for this call. File-only grants are not supported: directory approval covers its descendants; otherwise choose an in-project path.",
164
- };
303
+ // the activated permission review has its own order after the fixed denies
304
+ if (input.permissionProfile)
305
+ return this.decidePermission(input, result, {
306
+ kind: input.toolKey === "Read" ? "read" : isWrite ? "write" : "command",
307
+ target,
308
+ workspace,
309
+ rootOf,
310
+ });
165
311
  if (result.outcome === "allow" && !input.permissionCandidate) {
166
312
  return allow(hit?.reason ?? "The command review allows this command.", hit?.id ?? null);
167
313
  }