@capybara-hq/kernel 0.1.0-rc.53 → 0.1.0-rc.55

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 (190) hide show
  1. package/dist/admin/admin.schemas.d.ts +11 -1
  2. package/dist/catalog/catalog.module.js +1 -1
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/catalog/requests.service.d.ts +5 -5
  5. package/dist/catalog/requests.service.js +9 -9
  6. package/dist/channels/cards.d.ts +4 -3
  7. package/dist/channels/cards.js +25 -16
  8. package/dist/channels/phrases.d.ts +15 -4
  9. package/dist/channels/phrases.js +15 -1
  10. package/dist/config/load.d.ts +26 -7
  11. package/dist/config/load.js +60 -9
  12. package/dist/config/permission-migration.d.ts +17 -9
  13. package/dist/config/permission-migration.js +60 -9
  14. package/dist/config/schema.d.ts +15 -1
  15. package/dist/config/schema.js +66 -11
  16. package/dist/conversations/events.d.ts +247 -5
  17. package/dist/conversations/events.js +127 -16
  18. package/dist/conversations/permission-profiles.controller.d.ts +12 -2
  19. package/dist/conversations/permission-profiles.service.d.ts +12 -2
  20. package/dist/conversations/permission-profiles.service.js +11 -4
  21. package/dist/db/kernel-schema.d.ts +18 -2
  22. package/dist/devices/device-projects.service.d.ts +1 -1
  23. package/dist/devices/device-projects.service.js +6 -6
  24. package/dist/devices/devices.controller.d.ts +10 -8
  25. package/dist/devices/devices.controller.js +14 -18
  26. package/dist/devices/devices.schemas.d.ts +5 -5
  27. package/dist/devices/devices.schemas.js +5 -5
  28. package/dist/devices/devices.service.d.ts +188 -175
  29. package/dist/devices/devices.service.js +284 -292
  30. package/dist/devices/dto.d.ts +43 -23
  31. package/dist/devices/dto.js +45 -49
  32. package/dist/devices/project-rules.d.ts +0 -10
  33. package/dist/devices/project-rules.js +0 -5
  34. package/dist/errors.d.ts +43 -19
  35. package/dist/errors.js +43 -19
  36. package/dist/evals/reconstruct.d.ts +12 -3
  37. package/dist/evals/reconstruct.js +10 -6
  38. package/dist/evals/recorded-permission-context.d.ts +6 -4
  39. package/dist/evals/recorded-permission-context.js +15 -9
  40. package/dist/evals/run-replay.d.ts +6 -1
  41. package/dist/evals/run-replay.js +7 -2
  42. package/dist/evals/worker.js +3 -1
  43. package/dist/http/api.module.js +8 -0
  44. package/dist/http/app.js +9 -0
  45. package/dist/http/meta.controller.d.ts +33 -0
  46. package/dist/http/meta.controller.js +72 -0
  47. package/dist/identity/app-auth.controller.d.ts +25 -0
  48. package/dist/identity/app-auth.controller.js +64 -0
  49. package/dist/identity/app-auth.d.ts +66 -0
  50. package/dist/identity/app-auth.js +203 -0
  51. package/dist/identity/app-auth.schemas.d.ts +47 -0
  52. package/dist/identity/app-auth.schemas.js +43 -0
  53. package/dist/identity/identity.module.d.ts +1 -1
  54. package/dist/identity/identity.module.js +4 -1
  55. package/dist/identity/settings.d.ts +45 -18
  56. package/dist/identity/settings.js +151 -51
  57. package/dist/infra/config/kernel-config.service.d.ts +1 -1
  58. package/dist/infra/config/kernel-config.service.js +19 -5
  59. package/dist/infra/outbox/registry.d.ts +14 -0
  60. package/dist/infra/outbox/registry.js +15 -0
  61. package/dist/infra/throttler/named-throttlers.d.ts +3 -2
  62. package/dist/infra/throttler/named-throttlers.js +14 -2
  63. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  64. package/dist/local-devices/device-auth.controller.js +1 -1
  65. package/dist/local-devices/device-auth.d.ts +4 -4
  66. package/dist/local-devices/device-auth.js +1 -1
  67. package/dist/local-devices/device-policy.service.d.ts +18 -9
  68. package/dist/local-devices/device-policy.service.js +21 -61
  69. package/dist/local-devices/device-routes.d.ts +3 -1
  70. package/dist/local-devices/device-routes.js +15 -4
  71. package/dist/local-devices/instance-bindings.js +5 -2
  72. package/dist/local-devices/local-device-gateway.d.ts +2 -2
  73. package/dist/local-devices/local-device-gateway.js +3 -3
  74. package/dist/local-devices/local-device-provider.d.ts +4 -4
  75. package/dist/local-devices/local-device-provider.js +23 -9
  76. package/dist/local-devices/local-devices.module.d.ts +1 -1
  77. package/dist/local-devices/local-devices.module.js +1 -1
  78. package/dist/local-devices/machines.d.ts +40 -16
  79. package/dist/local-devices/machines.js +89 -61
  80. package/dist/local-devices/owner-report.d.ts +16 -14
  81. package/dist/local-devices/owner-report.js +24 -30
  82. package/dist/local-devices/owner-reports.js +26 -8
  83. package/dist/local-devices/policy-summary.d.ts +25 -44
  84. package/dist/local-devices/policy-summary.js +26 -71
  85. package/dist/local-devices/relay.d.ts +6 -6
  86. package/dist/local-devices/relay.js +10 -8
  87. package/dist/net/public-address.d.ts +1 -1
  88. package/dist/net/public-address.js +5 -2
  89. package/dist/orgs/device-network-setting.d.ts +82 -0
  90. package/dist/orgs/device-network-setting.js +142 -0
  91. package/dist/orgs/settings.service.d.ts +103 -66
  92. package/dist/orgs/settings.service.js +201 -137
  93. package/dist/overrides.d.ts +5 -1
  94. package/dist/overrides.js +2 -0
  95. package/dist/platform/exclusions.js +24 -1
  96. package/dist/platform/operation.js +2 -2
  97. package/dist/platform/ops/admin.ops.js +20 -11
  98. package/dist/platform/ops/devices.ops.js +70 -5
  99. package/dist/platform/ops/org-settings.ops.js +10 -6
  100. package/dist/platform/ops/orgs.ops.js +2 -1
  101. package/dist/platform/ops/platform-icons.ops.d.ts +14 -0
  102. package/dist/platform/ops/platform-icons.ops.js +117 -0
  103. package/dist/platform/platform-ops.module.d.ts +2 -1
  104. package/dist/platform/platform-ops.module.js +3 -0
  105. package/dist/platform/route-schemas.js +3 -0
  106. package/dist/runtime/context/permission-profile.d.ts +17 -8
  107. package/dist/runtime/context/permission-profile.js +126 -45
  108. package/dist/runtime/maintenance.d.ts +5 -2
  109. package/dist/runtime/maintenance.js +15 -4
  110. package/dist/runtime/permission-context.service.d.ts +1 -1
  111. package/dist/runtime/permission-context.service.js +5 -3
  112. package/dist/runtime/project/knowledge.d.ts +5 -4
  113. package/dist/runtime/project/knowledge.js +2 -1
  114. package/dist/runtime/project/knowledge.service.js +16 -13
  115. package/dist/sandbox/cloud-permission-snapshot.js +22 -3
  116. package/dist/sandbox/device-sandbox-settings.d.ts +230 -0
  117. package/dist/sandbox/device-sandbox-settings.js +470 -0
  118. package/dist/sandbox/device-sandbox.d.ts +187 -0
  119. package/dist/sandbox/device-sandbox.js +236 -0
  120. package/dist/sandbox/held-operations.js +15 -7
  121. package/dist/sandbox/modes.d.ts +49 -24
  122. package/dist/sandbox/modes.js +27 -19
  123. package/dist/sandbox/operation-authority-types.d.ts +6 -5
  124. package/dist/sandbox/operation-authority-types.js +7 -8
  125. package/dist/sandbox/operation-authority.d.ts +23 -9
  126. package/dist/sandbox/operation-authority.js +179 -97
  127. package/dist/sandbox/permission-auto-grants.d.ts +42 -0
  128. package/dist/sandbox/permission-auto-grants.js +145 -0
  129. package/dist/sandbox/permission-call-grants.d.ts +12 -4
  130. package/dist/sandbox/permission-call-grants.js +84 -35
  131. package/dist/sandbox/permission-call-grants.module.js +10 -3
  132. package/dist/sandbox/permission-call-types.d.ts +39 -5
  133. package/dist/sandbox/permission-ceiling-writes.d.ts +29 -3
  134. package/dist/sandbox/permission-ceiling-writes.js +38 -4
  135. package/dist/sandbox/permission-config-publication.d.ts +44 -2
  136. package/dist/sandbox/permission-config-publication.js +230 -59
  137. package/dist/sandbox/permission-context-types.d.ts +2 -2
  138. package/dist/sandbox/permission-facts.d.ts +144 -15
  139. package/dist/sandbox/permission-facts.js +258 -70
  140. package/dist/sandbox/permission-runtime-reports.d.ts +5 -4
  141. package/dist/sandbox/permission-runtime-reports.js +19 -29
  142. package/dist/sandbox/review/classifier.d.ts +8 -0
  143. package/dist/sandbox/review/classifier.js +10 -0
  144. package/dist/sandbox/review/permission-candidate.d.ts +69 -5
  145. package/dist/sandbox/review/permission-candidate.js +153 -30
  146. package/dist/sandbox/review/review.service.d.ts +19 -3
  147. package/dist/sandbox/review/review.service.js +59 -11
  148. package/dist/sandbox/review/rules.js +23 -3
  149. package/dist/sandbox/sandbox.service.d.ts +29 -11
  150. package/dist/sandbox/sandbox.service.js +51 -26
  151. package/dist/skills/invoke.js +3 -2
  152. package/dist/themes/platform-icon-objects.d.ts +51 -0
  153. package/dist/themes/platform-icon-objects.js +113 -0
  154. package/dist/themes/platform-icon-public.controller.d.ts +17 -0
  155. package/dist/themes/platform-icon-public.controller.js +58 -0
  156. package/dist/themes/platform-icon.controller.d.ts +22 -0
  157. package/dist/themes/platform-icon.controller.js +65 -0
  158. package/dist/themes/platform-icon.schemas.d.ts +48 -0
  159. package/dist/themes/platform-icon.schemas.js +53 -0
  160. package/dist/themes/platform-icon.service.d.ts +83 -0
  161. package/dist/themes/platform-icon.service.js +301 -0
  162. package/dist/themes/themes.module.d.ts +4 -1
  163. package/dist/themes/themes.module.js +9 -4
  164. package/dist/tools/approvals.service.d.ts +26 -116
  165. package/dist/tools/approvals.service.js +42 -346
  166. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  167. package/dist/tools/builtins/sandbox/bash.js +80 -28
  168. package/dist/tools/builtins/sandbox/common.d.ts +39 -14
  169. package/dist/tools/builtins/sandbox/common.js +47 -24
  170. package/dist/tools/builtins/sandbox/deliver.js +7 -4
  171. package/dist/tools/builtins/skill-load.d.ts +2 -2
  172. package/dist/tools/builtins/skill-load.js +4 -3
  173. package/dist/tools/device-op-resolver.d.ts +4 -10
  174. package/dist/tools/device-op-resolver.js +8 -19
  175. package/dist/tools/network-asks.d.ts +52 -15
  176. package/dist/tools/network-asks.js +55 -25
  177. package/dist/tools/pipeline.d.ts +26 -14
  178. package/dist/tools/pipeline.js +144 -61
  179. package/dist/tools/registry.d.ts +6 -0
  180. package/dist/tools/tools.module.js +1 -1
  181. package/package.json +4 -4
  182. package/src/migrations/0164_platform_icons.sql +10 -0
  183. package/src/migrations/0165_device_network_columns.sql +50 -0
  184. package/src/migrations/0166_permission_grant_full_access.sql +17 -0
  185. package/src/migrations/0167_device_network_backfill.sql +32 -0
  186. package/src/migrations/0168_binding_installed_connection.sql +6 -0
  187. package/dist/orgs/cloud-network-setting.d.ts +0 -33
  188. package/dist/orgs/cloud-network-setting.js +0 -47
  189. package/dist/sandbox/platform-full-access.d.ts +0 -110
  190. package/dist/sandbox/platform-full-access.js +0 -198
@@ -8,7 +8,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { isDeepStrictEqual } from "node:util";
12
11
  import { connectorToolKey, parseToolKey, validateAllowHost, } from "@capybara-hq/plugin-sdk";
13
12
  import { Inject, Injectable, Optional } from "@nestjs/common";
14
13
  import { sql } from "kysely";
@@ -21,22 +20,19 @@ import { clipText } from "../extensions/hooks.js";
21
20
  import { audit } from "../identity/audit.js";
22
21
  import { sha256Hex } from "../identity/hash.js";
23
22
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
24
- import { afterCommit } from "../infra/database/after-commit.js";
25
23
  import { KernelDb } from "../infra/database/kernel-db.js";
26
- import { TransactionHost, withOrderedLocks, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
24
+ import { TransactionHost, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
27
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
28
26
  import { KernelEvents } from "../infra/events/kernel-events.js";
29
27
  import { LockService } from "../infra/lock/lock.service.js";
30
28
  import { WithLock } from "../infra/lock/with-lock.decorator.js";
31
- import { DevicePolicyService, } from "../local-devices/device-policy.service.js";
32
- import { pendingPolicyOpsOf } from "../local-devices/policy-summary.js";
33
29
  import { ORG_ROLES, roleAtLeast } from "../orgs/roles.js";
34
30
  import { RunResume } from "../runtime/run-jobs.js";
35
31
  import { rootConversationOf } from "../runtime/subagents/child.js";
36
32
  import { PermissionAuthorityLock } from "../sandbox/permission-authority-lock.js";
37
33
  import { PermissionCallGrants } from "../sandbox/permission-call-grants.js";
38
34
  import { isSessionGrantableRule } from "../sandbox/review/types.js";
39
- import { deviceNotFound, SandboxService } from "../sandbox/sandbox.service.js";
35
+ import { SandboxService } from "../sandbox/sandbox.service.js";
40
36
  import { readScheduleSettings } from "../schedules/effective-settings.js";
41
37
  import { GIT_GRANT_SPEC_HASH, gitGrantRefusal, gitPushGrantKey, grantRefusalOf, NETWORK_GRANT_PREFIX, NETWORK_GRANT_SPEC_HASH, networkGrantRefusal, normalizeGitRepo, } from "../schedules/grant-rules.js";
42
38
  import { ScheduledTaskStore } from "../schedules/store.js";
@@ -81,25 +77,24 @@ const NETWORK_ASK_SPEC_HASH = "network";
81
77
  export const GIT_ASK_TOOL_KEY = "Bash";
82
78
  /** The spec hash of a git ask (no tool definition is approved). */
83
79
  const GIT_ASK_SPEC_HASH = "git";
84
- /** The tool key a command ask is recorded under (a command runs in `Bash`; a write under `Write`). */
80
+ /**
81
+ * The tool key a command ask is recorded under (a command runs in `Bash`; a write under `Write`, a
82
+ * read under `Read`).
83
+ */
85
84
  export const COMMAND_ASK_TOOL_KEY = "Bash";
86
85
  /** The spec hash of a command ask (no tool definition is approved). */
87
86
  const COMMAND_ASK_SPEC_HASH = "command";
88
87
  /** The tool key a file-write ask is recorded under. */
89
88
  export const COMMAND_WRITE_TOOL_KEY = "Write";
89
+ /** The tool key a file-read ask is recorded under. */
90
+ export const COMMAND_READ_TOOL_KEY = "Read";
91
+ /** The tool key of a command ask of `kind`. */
92
+ const commandAskToolKey = (kind) => kind === "write"
93
+ ? COMMAND_WRITE_TOOL_KEY
94
+ : kind === "read"
95
+ ? COMMAND_READ_TOOL_KEY
96
+ : COMMAND_ASK_TOOL_KEY;
90
97
  const notFound = () => new ApiError("approval.not_found", "Approval not found");
91
- /**
92
- * A decision refused before it wrote anything (the ask closed, expired or is not the account's to
93
- * decide): the device op's outcome is still recorded in the same transaction.
94
- */
95
- const refusedBeforeWrite = (e) => e instanceof ApiError &&
96
- (e.code === "approval.already_decided" || e.code === "approval.not_found");
97
- /** A pending network ask's reason when its device change got no answer (`detail.attempt`). */
98
- const UNCONFIRMED_ATTEMPT = "The device did not confirm the change to its network rules; its next connection tells whether it took effect.";
99
- /** A pending network ask's reason when the device applied it but its chooser cannot decide. */
100
- const APPLIED_UNDECIDED_ATTEMPT = "The device allowed it, but the person who chose this can no longer decide this request.";
101
- /** A pending network ask's reason when its device change failed without a message. */
102
- const NOT_APPLIED_ATTEMPT = "The device did not apply the change to its network rules.";
103
98
  const iso = (v) => new Date(v).toISOString();
104
99
  const isRole = (v) => v !== null && ORG_ROLES.includes(v);
105
100
  /** The scopes of an approval without stored ones: a role escalation is approved only once. */
@@ -168,7 +163,6 @@ let ApprovalsService = class ApprovalsService {
168
163
  txHost;
169
164
  schedules;
170
165
  registry;
171
- policies;
172
166
  lockService;
173
167
  sandbox;
174
168
  resumes;
@@ -177,12 +171,7 @@ let ApprovalsService = class ApprovalsService {
177
171
  constructor(db, config, eventLog, events, txHost, schedules,
178
172
  /** A trial approval is kept only for a tool the task may hold as a grant (its agent's tools). */
179
173
  registry,
180
- /**
181
- * 「这台设备一直允许」 records the device change's intent, sends the `policy` op, then records
182
- * its outcome with the decision.
183
- */
184
- policies,
185
- /** One decision of a network ask at a time, across replicas (the op is sent before the transaction). */
174
+ /** One decision of a network ask at a time, across replicas. */
186
175
  lockService,
187
176
  /** A trial run's 「这次允许」 becomes a task grant only within the org's egress. */
188
177
  sandbox,
@@ -195,7 +184,6 @@ let ApprovalsService = class ApprovalsService {
195
184
  this.txHost = txHost;
196
185
  this.schedules = schedules;
197
186
  this.registry = registry;
198
- this.policies = policies;
199
187
  this.lockService = lockService;
200
188
  this.sandbox = sandbox;
201
189
  this.resumes = resumes;
@@ -291,8 +279,8 @@ let ApprovalsService = class ApprovalsService {
291
279
  if (hosts.some((h) => h.host.length === 0 || h.host.length > NETWORK_HOST_MAX_CHARS)) {
292
280
  throw new Error("a network ask's host is 1 to 255 characters");
293
281
  }
294
- if (input.scopes.length === 0 || !input.scopes.includes("once")) {
295
- throw new Error('a network ask offers at least "once"');
282
+ if (input.scopes.length !== 1 || input.scopes[0] !== "once") {
283
+ throw new Error('a network ask offers exactly "once"');
296
284
  }
297
285
  const { record, toSeq } = await this.requestNetworkIn(input);
298
286
  if (toSeq !== null)
@@ -563,7 +551,7 @@ let ApprovalsService = class ApprovalsService {
563
551
  attempt: input.attempt ?? Number(last?.attempt ?? 0) + 1,
564
552
  kind: "command",
565
553
  detail: JSON.stringify(detail),
566
- tool_key: detail.kind === "write" ? COMMAND_WRITE_TOOL_KEY : COMMAND_ASK_TOOL_KEY,
554
+ tool_key: commandAskToolKey(detail.kind),
567
555
  spec_hash: COMMAND_ASK_SPEC_HASH,
568
556
  connector_id: null,
569
557
  input: JSON.stringify({}),
@@ -608,6 +596,11 @@ let ApprovalsService = class ApprovalsService {
608
596
  }
609
597
  : {}),
610
598
  kind: detail.kind,
599
+ // the profile the call was reviewed under: the card words the ask from it, never from
600
+ // the kernel's English reason
601
+ ...(detail.permissionCandidate && {
602
+ profile: detail.permissionCandidate.binding.profile,
603
+ }),
611
604
  // the approval's detail holds the whole command; the event is display only and clamped
612
605
  command: clipText(detail.command, COMMAND_ASK_TEXT_MAX_CHARS),
613
606
  ...(detail.path !== undefined && { path: detail.path }),
@@ -707,13 +700,9 @@ let ApprovalsService = class ApprovalsService {
707
700
  * A network ask's decision (network ask-to-allow spec §5.2), one at a time per ask across
708
701
  * replicas: only the device owner (`requested_for`) decides, in a signed-in session (a personal
709
702
  * access token is refused; the route already refuses service and embed tokens); the allowed
710
- * hosts are a subset of those asked. 「这台设备一直允许」 goes through the device change's intent
711
- * ({@link decideAlways}): when the device cannot be reached or lacks the feature the decision is
712
- * recorded as a run grant with the reason, and when the device refuses (its owner takes no
713
- * remote grants) as `always` with outcome `refused` and nothing granted; the decision and the
714
- * op's outcome are one transaction. Every decision resumes the run in its transaction and is
715
- * announced after the commit; a change the device applied after the ask closed is audited
716
- * (`late`) and answered with a 409 that says so.
703
+ * hosts are a subset of those asked. The decision is a run grant only (`once`): under device
704
+ * protocol 4 the deployment never adds a host to a local device, so `always` is refused. Every
705
+ * decision resumes the run in its transaction and is announced after the commit.
717
706
  */
718
707
  async decideNetwork(orgId, id, accountId, body, actorTokenId, via) {
719
708
  const row = await this.db
@@ -757,8 +746,11 @@ let ApprovalsService = class ApprovalsService {
757
746
  let network;
758
747
  if (body.decision === "approve") {
759
748
  const scope = body.scope ?? "once";
760
- if (scope === "session" || !ask.scopes.includes(scope)) {
761
- throw new ApiError("approval.scope_not_allowed", `Scope "${scope}" is not allowed for this approval; allowed: ${ask.scopes.join(", ")}`);
749
+ // a run grant only (approval-only profiles, device protocol 4): the deployment never widens
750
+ // a local device's sandbox allowlist, its owner adds hosts on the machine, so `always` is
751
+ // refused, also for an ask made before that still listing it
752
+ if (scope !== "once" || !ask.scopes.includes(scope)) {
753
+ throw new ApiError("approval.scope_not_allowed", `Scope "${scope}" is not allowed for this approval; allowed: once`);
762
754
  }
763
755
  const unknown = (body.hosts ?? []).filter((h) => !asked.includes(h));
764
756
  if (unknown.length > 0) {
@@ -774,13 +766,6 @@ let ApprovalsService = class ApprovalsService {
774
766
  ]);
775
767
  }
776
768
  network = { wanted: granted, granted, outcome: "once", via };
777
- if (scope === "always") {
778
- const decided = await this.decideAlways(orgId, ask, accountId, body, granted, via);
779
- // null: the resolver decided it as this owner meanwhile (announced by its commit)
780
- if (decided.toSeq !== null)
781
- await this.announceDecided(decided.record, decided.toSeq);
782
- return decided.record;
783
- }
784
769
  }
785
770
  else {
786
771
  if (body.hosts !== undefined) {
@@ -899,273 +884,6 @@ let ApprovalsService = class ApprovalsService {
899
884
  rootConversationId: await rootConversationOf(this.db.db, conversationId),
900
885
  };
901
886
  }
902
- /**
903
- * 「这台设备一直允许」 (transactional outbox spec §7): the intent of the device change (naming the
904
- * ask) is recorded, the `policy` op sent (no transaction open), then {@link settleNetworkOp}
905
- * decides the ask and records the op's outcome in one transaction. When nothing could be sent
906
- * (the device is offline, deleted, or its program lacks the feature) the decision is a run
907
- * grant with the reason. The device's answer decides: applied → `always`; refused → `always`
908
- * with outcome `refused`, nothing granted; no answer → a run grant (`once_fallback`, `offline`)
909
- * while the op stays `unknown` for the machine's next hello or the resolver. A device that
910
- * reconnects during the call and reports the op applied lets the resolver approve the ask as
911
- * this owner first: that decision is returned (`toSeq` null: already announced), never a 409;
912
- * when it granted other hosts than this call's (another of the owner's changes) and this call's
913
- * change was not confirmed, `approval.already_decided` says so. A device deleted during the
914
- * call is `device.not_found` (the op recorded unknown).
915
- */
916
- async decideAlways(orgId, ask, accountId, body, granted, via) {
917
- const detail = ask.detail;
918
- const accountName = (await this.displayNameOf(accountId)) ?? accountId;
919
- let begun;
920
- try {
921
- begun = await this.policies.begin({
922
- orgId,
923
- deviceId: detail.deviceId,
924
- change: { add: granted },
925
- source: { approvalId: ask.id, accountId, accountName, via },
926
- });
927
- }
928
- catch (e) {
929
- // the device was deleted meanwhile: nothing to write to, the run cannot go on there either
930
- if (!(e instanceof ApiError && e.code === "device.not_found"))
931
- throw e;
932
- begun = { outcome: { applied: false, reason: "offline", message: e.message } };
933
- }
934
- if ("outcome" in begun) {
935
- // nothing was sent: a run grant with the reason
936
- const fallback = begun.outcome.applied ? "offline" : begun.outcome.reason;
937
- return this.decideIn(orgId, ask.id, accountId, body, undefined, {
938
- wanted: granted,
939
- granted,
940
- outcome: "once_fallback",
941
- fallback,
942
- via,
943
- });
944
- }
945
- const { intent } = begun;
946
- const sent = await this.policies.send(intent);
947
- if (sent.notFound) {
948
- // deleted during the call: nothing to grant on, the run cannot go on there either
949
- await this.settleOpOnly({ machineId: intent.machineId, opId: intent.opId }, sent.result);
950
- throw deviceNotFound();
951
- }
952
- const network = sent.result.outcome === "applied"
953
- ? { wanted: granted, granted, outcome: "always", via }
954
- : sent.result.outcome === "refused"
955
- ? // the device's owner takes no remote grants: nothing is allowed, not even this run
956
- { wanted: granted, granted: [], outcome: "refused", fallback: "refused", via }
957
- : { wanted: granted, granted, outcome: "once_fallback", fallback: "offline", via };
958
- const settled = await this.settleNetworkOpOrdered(orgId, ask.id, accountId, body, network, {
959
- machineId: intent.machineId,
960
- opId: intent.opId,
961
- result: sent.result,
962
- });
963
- if ("decided" in settled)
964
- return settled.decided;
965
- if (settled.closed.code === "approval.already_decided" && !settled.late) {
966
- // the machine reconnected mid-call and reported the op: the resolver approved it as this
967
- // owner, with this change; it is their decision, not a conflict
968
- const now = await this.db
969
- .selectFrom("approvals")
970
- .selectAll()
971
- .where("id", "=", ask.id)
972
- .executeTakeFirst();
973
- const record = now === undefined ? null : toRecord(now);
974
- if (record?.status === "approved" &&
975
- record.detail?.outcome === "always" &&
976
- record.decidedBy === accountId) {
977
- const stored = [...(record.detail.grantedHosts ?? [])].sort();
978
- if (isDeepStrictEqual(stored, [...granted].sort()))
979
- return { record, toSeq: null };
980
- // approved by another of this owner's changes (other hosts), and this call's change was
981
- // not confirmed by the device: never report it as done
982
- throw new ApiError("approval.already_decided", `The request was already approved to always allow ${stored.join(", ") || "no hosts"}; ` +
983
- `the device did not confirm allowing ${granted.join(", ")}.`);
984
- }
985
- }
986
- // the device took the hosts, but a reply, the expiry or a stop closed the ask meanwhile: the
987
- // change stands (the owner chose it), audited late in the settle transaction, and said
988
- if (settled.late && settled.closed.code === "approval.already_decided") {
989
- throw new ApiError("approval.already_decided", `The device now allows ${granted.join(", ")}; the request had already closed.`);
990
- }
991
- throw settled.closed;
992
- }
993
- /** Records only the op's outcome, in its own transaction (the ask is left as it is). */
994
- async settleOpOnly(op, result) {
995
- await this.policies.settleIn(op, result);
996
- }
997
- /**
998
- * {@link settleNetworkOp} with the device's permission authority lock as its ordered prelude
999
- * (`DevicePolicyService.lockMachineDevice`): the global order puts it before the ask's
1000
- * conversation row, as a fenced device writer of the same tree takes it (device project writes).
1001
- */
1002
- settleNetworkOpOrdered(orgId, id, accountId, body, network, op) {
1003
- return withOrderedLocks(() => this.policies.lockMachineDevice(op.machineId), () => this.settleNetworkOp(orgId, id, accountId, body, network, op));
1004
- }
1005
- /**
1006
- * The resolve transaction of a network ask's device change: the ask decided as `network` says
1007
- * ({@link decideTx}: lock order conversation → approval → run), then the op's outcome recorded
1008
- * (`DevicePolicyService.settleIn`: the machine's row). When the ask closed meanwhile (a reply,
1009
- * the expiry, a stop) only the op's outcome is recorded, and a change the device applied is
1010
- * audited `device.network_allowed` with `late: true` in the same transaction.
1011
- */
1012
- async settleNetworkOp(orgId, id, accountId, body, network, op) {
1013
- let decided;
1014
- try {
1015
- decided = await this.decideTx(orgId, id, accountId, body, undefined, network);
1016
- }
1017
- catch (e) {
1018
- // refused before any write (closed, expired, gone): the op's outcome is recorded anyway
1019
- if (!refusedBeforeWrite(e))
1020
- throw e;
1021
- const late = await this.settleClosedIn(id, op, network.via);
1022
- return { closed: e, late };
1023
- }
1024
- await this.policies.settleIn(op, op.result);
1025
- return { decided };
1026
- }
1027
- /**
1028
- * The op's outcome for an ask that is no longer pending (in the caller's transaction): recorded,
1029
- * and a change the device applied audited `device.network_allowed` `late` (the change stands:
1030
- * the owner chose it; no inverse change is sent). True when it was audited late. `undecided`:
1031
- * the ask is still pending but the op's account can no longer decide it; the allow is audited
1032
- * without `late` (it is not after the ask) and the caller gives the ask the reason.
1033
- */
1034
- async settleClosedIn(approvalId, op, via, undecided = false) {
1035
- const pendingOp = await this.pendingOpOf(op.machineId, op.opId);
1036
- const out = await this.policies.settleIn(op, op.result);
1037
- if (out === null || pendingOp === null || op.result.outcome !== "applied")
1038
- return false;
1039
- const row = await this.db
1040
- .selectFrom("approvals")
1041
- .selectAll()
1042
- .where("id", "=", approvalId)
1043
- .executeTakeFirst();
1044
- if (!row)
1045
- return false;
1046
- const ask = toRecord(row);
1047
- if (ask.detail === null)
1048
- return false;
1049
- await audit(this.db.db, {
1050
- actorAccountId: pendingOp.source.accountId,
1051
- orgId: ask.orgId,
1052
- action: "device.network_allowed",
1053
- target: ask.detail.deviceId,
1054
- detail: {
1055
- approvalId: ask.id,
1056
- deviceId: ask.detail.deviceId,
1057
- hosts: pendingOp.add,
1058
- scope: "always",
1059
- outcome: "always",
1060
- ...(undecided ? { undecided: true } : { late: true }),
1061
- by: pendingOp.source.accountId,
1062
- via,
1063
- conversationId: ask.conversationId,
1064
- runId: ask.runId,
1065
- },
1066
- });
1067
- return true;
1068
- }
1069
- /** The live intent `opId` on machine `machineId` (null: settled already, or expired). */
1070
- async pendingOpOf(machineId, opId) {
1071
- const r = await this.db
1072
- .selectFrom("device_machines")
1073
- .select("pending_policy_ops")
1074
- .where("id", "=", machineId)
1075
- .executeTakeFirst();
1076
- const op = pendingPolicyOpsOf(r?.pending_policy_ops).find((o) => o.id === opId);
1077
- return op === undefined || op.until <= Date.now() ? null : op;
1078
- }
1079
- /**
1080
- * The `device-op-resolve` job's outcome of an op that answers network ask `op.source.approvalId`
1081
- * (transactional outbox spec §7.4), in the resolver's transaction: under the ask's locks
1082
- * (conversation, then the approval) the op is read again (settled meanwhile: nothing to do).
1083
- * Applied, and the ask still pending → approved `always` by the op's account (`via` as it
1084
- * asked), the run resumed in this transaction as every decision does; the ask closed → audited
1085
- * `late`; still pending but the op's account can no longer decide it → the allow audited (not
1086
- * late) and the ask left pending with `applied_undecided`. Not applied (refused, never received,
1087
- * interrupted) or still unknown → the op's outcome recorded and the ask left pending with the
1088
- * reason (`detail.attempt`) and an `approval_updated` event so the card shows it: no person is
1089
- * there to fall back to a run grant (D2). The caller locked the machine's device first
1090
- * (`DevicePolicyService.lockMachineDevice`, before the ask's conversation row).
1091
- */
1092
- async settleFromResolver(ref, result) {
1093
- const t = this.db.db;
1094
- const op = { machineId: ref.machineId, opId: ref.opId, result };
1095
- if (!(await this.lockConversationOf(ref.approvalId))) {
1096
- await this.policies.settleIn(op, result);
1097
- return;
1098
- }
1099
- const row = await t
1100
- .selectFrom("approvals")
1101
- .selectAll()
1102
- .select(sql `expires_at <= now()`.as("expired"))
1103
- .where("id", "=", ref.approvalId)
1104
- .forUpdate()
1105
- .executeTakeFirst();
1106
- const pendingOp = await this.pendingOpOf(ref.machineId, ref.opId);
1107
- if (row === undefined || pendingOp === null) {
1108
- await this.policies.settleIn(op, result);
1109
- return;
1110
- }
1111
- const ask = toRecord(row);
1112
- const open = ask.status === "pending" && !row.expired && ask.kind === "network";
1113
- const via = pendingOp.source.via;
1114
- if (result.outcome === "applied") {
1115
- if (!open) {
1116
- await this.settleClosedIn(ask.id, op, via);
1117
- return;
1118
- }
1119
- let decided;
1120
- try {
1121
- decided = await this.decideTx(ask.orgId, ask.id, pendingOp.source.accountId, { decision: "approve", scope: "always" }, undefined, { wanted: pendingOp.add, granted: pendingOp.add, outcome: "always", via });
1122
- }
1123
- catch (e) {
1124
- // the op's account may no longer decide it: the change stands, the ask waits with why
1125
- if (!refusedBeforeWrite(e))
1126
- throw e;
1127
- if (await this.settleClosedIn(ask.id, op, via, true)) {
1128
- await this.attemptIn(ask, ref.opId, {
1129
- outcome: "applied_undecided",
1130
- message: APPLIED_UNDECIDED_ATTEMPT,
1131
- });
1132
- }
1133
- return;
1134
- }
1135
- await this.policies.settleIn(op, result);
1136
- afterCommit(() => this.announceDecided(decided.record, decided.toSeq));
1137
- return;
1138
- }
1139
- const out = await this.policies.settleIn(op, result);
1140
- if (out === null || !open || ask.detail === null)
1141
- return;
1142
- await this.attemptIn(ask, ref.opId, result.outcome === "unknown"
1143
- ? { outcome: "unknown", message: UNCONFIRMED_ATTEMPT }
1144
- : { outcome: "failed", message: out.applied ? NOT_APPLIED_ATTEMPT : out.message });
1145
- }
1146
- /**
1147
- * A pending network ask's reason (`detail.attempt`) and its `approval_updated` event (one per
1148
- * op and outcome), in the caller's transaction with the ask locked; notified after the commit.
1149
- */
1150
- async attemptIn(ask, opId, attempt) {
1151
- if (ask.detail === null)
1152
- return;
1153
- await this.db.db
1154
- .updateTable("approvals")
1155
- .set({ detail: JSON.stringify({ ...ask.detail, attempt }) })
1156
- .where("id", "=", ask.id)
1157
- .execute();
1158
- const written = await this.eventLog.appendIn(ask.conversationId, [
1159
- {
1160
- type: "approval_updated",
1161
- runId: ask.runId,
1162
- idemKey: `approval_updated:${ask.id}:${opId}:${attempt.outcome}`,
1163
- payload: { approvalId: ask.id, callId: ask.callId },
1164
- },
1165
- ]);
1166
- const toSeq = Math.max(...written.map((e) => e.seq));
1167
- afterCommit(() => this.eventLog.notify(ask.conversationId, toSeq));
1168
- }
1169
887
  /** The owner of a live device of the org (null: none, deleted, or of another org). */
1170
888
  async deviceOwnerOf(orgId, deviceId) {
1171
889
  const d = await this.db
@@ -1264,9 +982,7 @@ let ApprovalsService = class ApprovalsService {
1264
982
  ? (command.scope ?? "once")
1265
983
  : network === undefined
1266
984
  ? (body.scope ?? "once")
1267
- : network.outcome === "always" || network.outcome === "refused"
1268
- ? "always"
1269
- : "once";
985
+ : "once";
1270
986
  // 按角色升级的批准只对这一次有效:授权记在发起人名下会让其以后绕过角色要求
1271
987
  if (scope !== null && scope !== "once" && before.requestedFor === null) {
1272
988
  throw new ApiError("validation_failed", 'Only scope "once" is allowed for role-escalated approvals', [{ path: "scope", message: 'Only "once" is allowed for role-escalated approvals' }]);
@@ -1293,13 +1009,11 @@ let ApprovalsService = class ApprovalsService {
1293
1009
  deny_reason: reason ?? null,
1294
1010
  ...(network?.outcome != null &&
1295
1011
  before.detail !== null && {
1296
- // what took effect; run grants read grantedHosts (an always grant's hosts are on
1297
- // the device's policy already, so it carries them harmlessly)
1012
+ // what took effect; run grants read grantedHosts
1298
1013
  detail: JSON.stringify({
1299
1014
  ...before.detail,
1300
1015
  grantedHosts: network.granted,
1301
1016
  outcome: network.outcome,
1302
- ...(network.fallback !== undefined && { fallback: network.fallback }),
1303
1017
  }),
1304
1018
  }),
1305
1019
  ...(git?.outcome != null &&
@@ -1377,13 +1091,12 @@ let ApprovalsService = class ApprovalsService {
1377
1091
  command === undefined) {
1378
1092
  await this.keepTrialGrant(before, accountId);
1379
1093
  }
1380
- // 「这次允许」 of a push in a trial run: the task's grant for that repository; a standing
1094
+ // "Allow once" of a push in a trial run: the task's grant for that repository; a standing
1381
1095
  // allow needs none (the member's policy already allows it)
1382
1096
  if (git?.outcome === "once")
1383
1097
  await this.keepTrialGitGrant(before, accountId);
1384
- // 「这次允许」 in a trial run (also an 「一直允许」 the device could not take): the task's
1385
- // grants; one the device took needs none (network ask-to-allow spec §8.1)
1386
- if (network?.outcome === "once" || network?.outcome === "once_fallback") {
1098
+ // "Allow once" in a trial run: the task's grants (network ask-to-allow spec §8.1)
1099
+ if (network?.outcome === "once") {
1387
1100
  await this.keepTrialNetworkGrant(before, accountId, network.granted);
1388
1101
  }
1389
1102
  const written = await this.eventLog.appendIn(before.conversationId, [
@@ -1416,7 +1129,6 @@ let ApprovalsService = class ApprovalsService {
1416
1129
  ...(approved && refused.length > 0 && { refused }),
1417
1130
  scope,
1418
1131
  outcome: approved ? network.outcome : "denied",
1419
- ...(network.fallback !== undefined && { fallback: network.fallback }),
1420
1132
  by: accountId,
1421
1133
  via: network.via,
1422
1134
  conversationId: before.conversationId,
@@ -2107,21 +1819,6 @@ __decorate([
2107
1819
  __decorate([
2108
1820
  WithLock({ key: "network-ask-#{1}", ttl: 60_000, waitTimeout: 45_000 })
2109
1821
  ], ApprovalsService.prototype, "decideNetwork", null);
2110
- __decorate([
2111
- Transactional()
2112
- ], ApprovalsService.prototype, "settleOpOnly", null);
2113
- __decorate([
2114
- Transactional()
2115
- ], ApprovalsService.prototype, "settleNetworkOp", null);
2116
- __decorate([
2117
- Transactional({ propagation: "mandatory" })
2118
- ], ApprovalsService.prototype, "settleClosedIn", null);
2119
- __decorate([
2120
- Transactional({ propagation: "mandatory" })
2121
- ], ApprovalsService.prototype, "settleFromResolver", null);
2122
- __decorate([
2123
- Transactional({ propagation: "mandatory" })
2124
- ], ApprovalsService.prototype, "attemptIn", null);
2125
1822
  __decorate([
2126
1823
  Transactional({ propagation: "requires_new" })
2127
1824
  ], ApprovalsService.prototype, "decideIn", null);
@@ -2164,13 +1861,12 @@ ApprovalsService = __decorate([
2164
1861
  __param(4, Inject(TransactionHost)),
2165
1862
  __param(5, Inject(ScheduledTaskStore)),
2166
1863
  __param(6, Inject(ToolRegistry)),
2167
- __param(7, Inject(DevicePolicyService)),
2168
- __param(8, Inject(LockService)),
2169
- __param(9, Inject(SandboxService)),
2170
- __param(10, Inject(RunResume)),
1864
+ __param(7, Inject(LockService)),
1865
+ __param(8, Inject(SandboxService)),
1866
+ __param(9, Inject(RunResume)),
1867
+ __param(10, Optional()),
1868
+ __param(10, Inject(PermissionAuthorityLock)),
2171
1869
  __param(11, Optional()),
2172
- __param(11, Inject(PermissionAuthorityLock)),
2173
- __param(12, Optional()),
2174
- __param(12, Inject(PermissionCallGrants))
1870
+ __param(11, Inject(PermissionCallGrants))
2175
1871
  ], ApprovalsService);
2176
1872
  export { ApprovalsService };
@@ -39,15 +39,28 @@ export declare function formatExec(r: ExecResult, seconds: number, budgetClamped
39
39
  */
40
40
  export declare function runInBackgroundManaged(deps: SandboxToolDeps, ctx: BuiltinCallContext, input: BashInput): Promise<BuiltinResult>;
41
41
  /**
42
- * Whether a finished command failed in a way the OS sandbox may have caused: a host the device
43
- * refused (`network.blocked`) or a sandbox-specific message, and no credential or auth failure.
42
+ * How a finished command failed in a way the OS sandbox may have caused: `network` for a host the
43
+ * device refused (`network.blocked`), the proxy's refusal or a direct connect to a closed address;
44
+ * `other` for a sandbox-specific message; null when neither, or on a credential or auth failure.
44
45
  */
46
+ export declare const sandboxDenial: (r: ExecResult) => "network" | "other" | null;
47
+ /** Whether a finished command failed in a way the OS sandbox may have caused ({@link sandboxDenial}). */
45
48
  export declare const sandboxDenied: (r: ExecResult) => boolean;
49
+ /**
50
+ * The line a restricted `Bash` result ends with when the OS sandbox may have denied it: what the
51
+ * sandbox closes, then either the invitation to retry escalated (this device and org allow running
52
+ * outside the sandbox) or why that is not possible here and who can change it (the per-layer
53
+ * escalation refusal). Empty for an escalated call, a call without escalation facts, or no signal.
54
+ */
55
+ export declare function sandboxDenialHint(r: ExecResult, escalation: {
56
+ escalation?: "available" | "escalated";
57
+ refusal?: string;
58
+ }): string;
46
59
  /**
47
60
  * {@link SCOPE_DENIED_TOOL_TEXT} followed by {@link ESCALATION_RETRY_HINT}, written out as a literal
48
61
  * for the tool design check (a unit test keeps the two copies equal).
49
62
  */
50
- export declare const SCOPE_DENIED_ESCALATION_TEXT = "This operation reaches outside what this conversation's permission profile allows on the device (a path outside the directories it may read or write, or a host it may not reach), so it did not run. Keep the call inside the working directory and the directories already granted, or ask the user to grant the directory or choose a broader permission profile, then retry. 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.";
63
+ export declare const SCOPE_DENIED_ESCALATION_TEXT = "This operation reaches outside what this conversation's permission profile allows on the device (a path outside the directories it may read or write, or a host it may not reach), so it did not run. Keep the call inside the working directory and the directories already granted, or ask the user to grant the directory or choose a broader permission profile, then retry. If this command must reach outside the sandbox, retry the same Bash call with sandbox: \"escalated\" and justification: one sentence saying why; this conversation's permission profile decides whether it may run outside the sandbox for this call only (the user, the review model, or Full access within this device's limits).";
51
64
  /** 内置工具 `Bash`:在本对话的沙箱里执行命令。 */
52
65
  export declare function sandboxBashTool(deps: SandboxToolDeps): BuiltinTool;
53
66
  export {};