@capybara-hq/kernel 0.1.0-rc.128 → 0.1.0-rc.129

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 (113) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +14 -0
  3. package/dist/automations/automations.service.js +15 -21
  4. package/dist/automations/effective-settings.d.ts +3 -9
  5. package/dist/automations/effective-settings.js +3 -5
  6. package/dist/automations/fire.js +0 -11
  7. package/dist/automations/grant-rules.d.ts +7 -10
  8. package/dist/automations/grant-rules.js +9 -18
  9. package/dist/automations/unattended.d.ts +1 -4
  10. package/dist/automations/unattended.js +0 -2
  11. package/dist/catalog/org-extension.controller.d.ts +1 -20
  12. package/dist/catalog/org-extension.controller.js +1 -48
  13. package/dist/catalog/org-extension.schemas.d.ts +1 -9
  14. package/dist/catalog/org-extension.schemas.js +1 -17
  15. package/dist/config/schema.d.ts +12 -0
  16. package/dist/config/schema.js +16 -0
  17. package/dist/conversations/approval-profile.d.ts +8 -1
  18. package/dist/conversations/approval-profile.js +20 -0
  19. package/dist/conversations/conversations.service.d.ts +1 -1
  20. package/dist/conversations/conversations.service.js +8 -3
  21. package/dist/conversations/events.d.ts +25 -1
  22. package/dist/conversations/events.js +7 -2
  23. package/dist/conversations/permission-profiles.controller.d.ts +4 -0
  24. package/dist/conversations/permission-profiles.schemas.d.ts +5 -0
  25. package/dist/conversations/permission-profiles.schemas.js +8 -0
  26. package/dist/conversations/permission-profiles.service.d.ts +8 -1
  27. package/dist/conversations/permission-profiles.service.js +13 -1
  28. package/dist/db/kernel-schema.d.ts +21 -0
  29. package/dist/device-access/device-access.service.d.ts +4 -1
  30. package/dist/device-access/device-access.service.js +26 -7
  31. package/dist/device-access/viewer.d.ts +3 -1
  32. package/dist/device-access/viewer.js +18 -9
  33. package/dist/errors.d.ts +6 -0
  34. package/dist/errors.js +6 -0
  35. package/dist/git/gateway.d.ts +8 -1
  36. package/dist/git/gateway.js +68 -11
  37. package/dist/git/git.module.d.ts +2 -3
  38. package/dist/git/git.module.js +4 -4
  39. package/dist/http/api.module.js +3 -3
  40. package/dist/identity/settings.d.ts +20 -5
  41. package/dist/identity/settings.js +52 -9
  42. package/dist/infra/config/kernel-config.service.js +4 -0
  43. package/dist/orgs/orgs.module.js +12 -1
  44. package/dist/orgs/orgs.schemas.js +3 -0
  45. package/dist/orgs/security-settings.service.d.ts +94 -0
  46. package/dist/orgs/security-settings.service.js +223 -0
  47. package/dist/orgs/settings.controller.d.ts +33 -0
  48. package/dist/orgs/settings.controller.js +41 -1
  49. package/dist/orgs/settings.service.d.ts +48 -63
  50. package/dist/orgs/settings.service.js +86 -103
  51. package/dist/platform/exclusions.js +1 -1
  52. package/dist/platform/operation.js +4 -0
  53. package/dist/platform/ops/admin.ops.js +18 -4
  54. package/dist/platform/ops/connectors.ops.js +2 -2
  55. package/dist/platform/ops/extensions.ops.d.ts +1 -3
  56. package/dist/platform/ops/extensions.ops.js +4 -131
  57. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  58. package/dist/platform/ops/org-settings.ops.js +76 -3
  59. package/dist/platform/ops/orgs.ops.js +2 -0
  60. package/dist/runtime/context/permission-profile.js +6 -0
  61. package/dist/runtime/subagents/dispatch.d.ts +3 -0
  62. package/dist/runtime/subagents/dispatch.js +2 -1
  63. package/dist/runtime/subagents/messages.d.ts +3 -1
  64. package/dist/runtime/subagents/messages.js +9 -6
  65. package/dist/sandbox/device-sandbox-settings.d.ts +55 -1
  66. package/dist/sandbox/device-sandbox-settings.js +64 -1
  67. package/dist/sandbox/device-sandbox.d.ts +9 -1
  68. package/dist/sandbox/device-sandbox.js +17 -2
  69. package/dist/sandbox/device-services.d.ts +26 -3
  70. package/dist/sandbox/device-services.js +95 -16
  71. package/dist/sandbox/loopback-grant-records.d.ts +3 -2
  72. package/dist/sandbox/loopback-grant-records.js +32 -5
  73. package/dist/sandbox/operation-authority.d.ts +3 -2
  74. package/dist/sandbox/operation-authority.js +21 -1
  75. package/dist/sandbox/operation-intents.js +5 -1
  76. package/dist/sandbox/permission-call-types.d.ts +2 -1
  77. package/dist/sandbox/permission-ceiling-writes.d.ts +14 -5
  78. package/dist/sandbox/permission-ceiling-writes.js +122 -13
  79. package/dist/sandbox/permission-config-publication.d.ts +10 -0
  80. package/dist/sandbox/permission-config-publication.js +27 -5
  81. package/dist/sandbox/permission-facts.d.ts +21 -2
  82. package/dist/sandbox/permission-facts.js +101 -9
  83. package/dist/sandbox/permission-transitions.d.ts +1 -1
  84. package/dist/sandbox/sandbox.service.d.ts +2 -2
  85. package/dist/sandbox/sandbox.service.js +7 -3
  86. package/dist/tools/admin-connectors.js +2 -2
  87. package/dist/tools/approvals.service.d.ts +7 -2
  88. package/dist/tools/approvals.service.js +39 -7
  89. package/dist/tools/builtin-names.d.ts +0 -6
  90. package/dist/tools/builtin-names.js +0 -11
  91. package/dist/tools/builtins/sandbox/index.d.ts +3 -5
  92. package/dist/tools/builtins/sandbox/index.js +3 -5
  93. package/dist/tools/connector-account-policies.js +7 -4
  94. package/dist/tools/connectors.controller.d.ts +0 -6
  95. package/dist/tools/connectors.schemas.d.ts +1 -8
  96. package/dist/tools/connectors.schemas.js +1 -4
  97. package/dist/tools/connectors.service.d.ts +3 -7
  98. package/dist/tools/connectors.service.js +29 -44
  99. package/dist/tools/drift.js +12 -4
  100. package/dist/tools/git-push-policy.d.ts +1 -4
  101. package/dist/tools/git-push-policy.js +4 -5
  102. package/dist/tools/org-tool-policies.d.ts +24 -0
  103. package/dist/tools/org-tool-policies.js +113 -0
  104. package/dist/tools/org-tool-switches.d.ts +5 -70
  105. package/dist/tools/org-tool-switches.js +13 -141
  106. package/dist/tools/pipeline.d.ts +11 -5
  107. package/dist/tools/pipeline.js +173 -38
  108. package/dist/tools/policy.d.ts +3 -7
  109. package/dist/tools/policy.js +29 -48
  110. package/dist/tools/registry.d.ts +5 -0
  111. package/dist/tools/registry.js +44 -13
  112. package/package.json +1 -1
  113. package/src/migrations/0212_org_security_policy.sql +234 -0
@@ -7,161 +7,38 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { createHash } from "node:crypto";
11
10
  import { extensionToolKey } from "@capybara-hq/plugin-sdk";
12
11
  import { Inject, Injectable } from "@nestjs/common";
13
- import { sql } from "kysely";
14
12
  import { extensionToolDisabled } from "../agents/definition.js";
15
- import { ApiError } from "../errors.js";
16
13
  import { ExtensionHost } from "../extensions/host.js";
17
14
  import { extensionVisibleTo } from "../extensions/org-config.js";
18
- import { audit } from "../identity/audit.js";
19
15
  import { KernelDb } from "../infra/database/kernel-db.js";
20
- import { TransactionHost } from "../infra/database/transaction-host.js";
21
- import { Transactional } from "../infra/database/transactional.decorator.js";
22
- import { OrgLock } from "../orgs/org-lock.js";
23
- /** Model-visible (English): why a turned-off extension tool is not offered. */
16
+ import { readOrgToolPolicies, readOrgToolPolicy } from "./org-tool-policies.js";
17
+ /** Model-visible reason for a tool denied by the organization. */
24
18
  export const toolTurnedOffReason = (key) => `Tool ${key} is turned off in this organization`;
25
- /** The confirm hash of a switch-off preview. */
26
- function switchOffHash(orgId, plugin, tool, agents) {
27
- return createHash("sha256")
28
- .update(JSON.stringify({ orgId, plugin, tool, agents: agents.map((a) => a.id) }))
29
- .digest("hex");
30
- }
31
- /**
32
- * Per-org switches of single extension tools (layering spec A §7, table `org_tool_switches`): an
33
- * org admin turns off one tool an extension registers (`ctx.tools.register`); it is then not
34
- * offered to any agent of the org (`ToolRegistry.forAgent`) and refused if called
35
- * (`ToolPipeline`). No row means on. A row of a tool the extension stops registering is kept and
36
- * applies again if the tool comes back. Builtin and connector tools are out of scope. Read from PG
37
- * on every use, no in-process state.
38
- */
19
+ /** Broad-deny visibility and the affected-agent preview for an extension tool. */
39
20
  let OrgToolSwitches = class OrgToolSwitches {
40
21
  kdb;
41
- txHost;
42
22
  host;
43
- orgLock;
44
- constructor(kdb, txHost, host,
45
- /** The org row lock: re-checks `org.extensions.manage` under the lock. */
46
- orgLock) {
23
+ constructor(kdb, host) {
47
24
  this.kdb = kdb;
48
- this.txHost = txHost;
49
25
  this.host = host;
50
- this.orgLock = orgLock;
51
26
  }
52
27
  get db() {
53
28
  return this.kdb.db;
54
29
  }
55
- /** The tool names `plugin` registers on this replica, in registration order. */
56
- registered(plugin) {
57
- return [
58
- ...new Set(this.host
59
- .tools()
60
- .filter((t) => t.plugin === plugin)
61
- .map((t) => t.spec.name)),
62
- ];
63
- }
64
- /**
65
- * The tools of an extension the org sees: running here and visible under plugin scope, else 404
66
- * `extension.not_found` (an invisible one is answered like an unknown one). An extension that
67
- * runs but registers no tools (a channel, a model provider) answers an empty list, not 404.
68
- */
69
- async toolsFor(orgId, plugin) {
70
- if (!this.host.current(plugin) || !(await extensionVisibleTo(this.db, orgId, plugin))) {
71
- throw new ApiError("extension.not_found", `Extension ${plugin} is not installed`);
72
- }
73
- return this.registered(plugin);
74
- }
75
- /** The stored switches of the org (all extensions, or one), `false` ones only matter. */
76
- async offRows(orgId, plugin) {
77
- let q = this.db
78
- .selectFrom("org_tool_switches")
79
- .select(["plugin", "tool"])
80
- .where("org_id", "=", orgId)
81
- .where("enabled", "=", false);
82
- if (plugin !== undefined)
83
- q = q.where("plugin", "=", plugin);
84
- return q.execute();
85
- }
86
- /** Every tool the extension registers on this replica with its switch (default on). */
87
- async list(orgId, plugin) {
88
- const tools = await this.toolsFor(orgId, plugin);
89
- const off = new Set((await this.offRows(orgId, plugin)).map((r) => r.tool));
90
- return tools.map((tool) => ({ tool, enabled: !off.has(tool) }));
91
- }
92
- /**
93
- * What turning one tool off would affect (nothing written): the agents selecting it and the
94
- * confirm hash {@link set} takes, or null when it is off already. Unknown tool -> 404
95
- * `extension.tool_not_found`.
96
- */
97
- async previewOff(orgId, plugin, tool) {
98
- const tools = await this.toolsFor(orgId, plugin);
99
- if (!tools.includes(tool)) {
100
- throw new ApiError("extension.tool_not_found", `Extension ${plugin} does not register a tool named ${tool}`);
101
- }
102
- if (await this.isToolOff(orgId, plugin, tool))
103
- return null;
104
- const affectedAgents = await this.agentsSelecting(orgId, plugin, tool);
105
- return { affectedAgents, confirm: switchOffHash(orgId, plugin, tool, affectedAgents) };
106
- }
107
- /** The model-visible keys (`plugin__<extension>__<tool>`) of the tools turned off in the org. */
108
30
  async offKeys(orgId) {
109
- return new Set((await this.offRows(orgId)).map((r) => extensionToolKey(r.plugin, r.tool)));
31
+ const rules = await readOrgToolPolicies(this.db, orgId);
32
+ return new Set(rules.filter((row) => row.policy === "deny").map((row) => row.toolKey));
110
33
  }
111
- /** Whether the org turned off this tool. */
112
34
  async isToolOff(orgId, plugin, tool) {
113
- const row = await this.db
114
- .selectFrom("org_tool_switches")
115
- .select("enabled")
116
- .where("org_id", "=", orgId)
117
- .where("plugin", "=", plugin)
118
- .where("tool", "=", tool)
119
- .executeTakeFirst();
120
- return row?.enabled === false;
35
+ return ((await readOrgToolPolicy(this.db, orgId, extensionToolKey(plugin, tool))).policy === "deny");
121
36
  }
122
- /**
123
- * Switches one tool in the org. On applies at once. Off, while the tool is on: without
124
- * `confirm` the preview (the org's agents whose current version does not turn it off) and its hash,
125
- * with the current hash the switch is written (a changed preview -> 409 `plugin.switch_stale`).
126
- * A tool the extension does not register -> 404 `extension.tool_not_found`. A change writes the
127
- * audit row `extension.tool_switched`.
128
- */
129
- async set(orgId, plugin, tool, enabled, actor, confirm) {
130
- await this.orgLock.lockAndAuthorize(orgId, actor.accountId, "org.extensions.manage");
131
- const tools = await this.toolsFor(orgId, plugin);
132
- if (!tools.includes(tool)) {
133
- throw new ApiError("extension.tool_not_found", `Extension ${plugin} does not register a tool named ${tool}`);
134
- }
135
- const from = !(await this.isToolOff(orgId, plugin, tool));
136
- if (from === enabled)
137
- return { applied: true };
138
- if (!enabled) {
139
- const affectedAgents = await this.agentsSelecting(orgId, plugin, tool);
140
- const hash = switchOffHash(orgId, plugin, tool, affectedAgents);
141
- if (confirm === undefined)
142
- return { applied: false, affectedAgents, confirm: hash };
143
- if (confirm !== hash) {
144
- throw new ApiError("plugin.switch_stale", "What switching this tool off affects has changed; review it and confirm again");
145
- }
146
- }
147
- await this.db
148
- .insertInto("org_tool_switches")
149
- .values({ org_id: orgId, plugin, tool, enabled, updated_by: actor.accountId })
150
- .onConflict((oc) => oc.columns(["org_id", "plugin", "tool"]).doUpdateSet({
151
- enabled,
152
- updated_by: actor.accountId,
153
- updated_at: sql `now()`,
154
- }))
155
- .execute();
156
- await audit(this.db, {
157
- actorAccountId: actor.accountId,
158
- ...(actor.tokenId !== undefined && { actorTokenId: actor.tokenId }),
159
- orgId,
160
- action: "extension.tool_switched",
161
- target: extensionToolKey(plugin, tool),
162
- detail: { plugin, tool, from, to: enabled, ...actor.auditDetail },
163
- });
164
- return { applied: true };
37
+ async affectedAgents(orgId, toolKey) {
38
+ const tool = this.host.tools().find((t) => extensionToolKey(t.plugin, t.spec.name) === toolKey);
39
+ if (tool === undefined || !(await extensionVisibleTo(this.db, orgId, tool.plugin)))
40
+ return [];
41
+ return this.agentsSelecting(orgId, tool.plugin, tool.spec.name);
165
42
  }
166
43
  /**
167
44
  * The org's live agents whose current version has extension tool `tool` of `plugin` on: tools
@@ -188,14 +65,9 @@ let OrgToolSwitches = class OrgToolSwitches {
188
65
  return out;
189
66
  }
190
67
  };
191
- __decorate([
192
- Transactional()
193
- ], OrgToolSwitches.prototype, "set", null);
194
68
  OrgToolSwitches = __decorate([
195
69
  Injectable(),
196
70
  __param(0, Inject(KernelDb)),
197
- __param(1, Inject(TransactionHost)),
198
- __param(2, Inject(ExtensionHost)),
199
- __param(3, Inject(OrgLock))
71
+ __param(1, Inject(ExtensionHost))
200
72
  ], OrgToolSwitches);
201
73
  export { OrgToolSwitches };
@@ -16,7 +16,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
17
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
18
  import type { KernelLogger } from "../log.js";
19
- import type { OrgRole } from "../orgs/roles.js";
19
+ import { type OrgRole } from "../orgs/roles.js";
20
20
  import { type ConversationKindForHooks, type HookRunner } from "../runtime/hook-calls.js";
21
21
  import { type SubagentParent, type WaitingFor } from "../runtime/loop.js";
22
22
  import type { DispatchArgs, DispatchOutcome } from "../runtime/subagents/dispatch.js";
@@ -35,6 +35,7 @@ import { ApprovalsService, type NetworkAskDetail } from "./approvals.service.js"
35
35
  import { Breaker } from "./breaker.js";
36
36
  import { Credentials } from "./credentials.js";
37
37
  import { ToolDrift } from "./drift.js";
38
+ import { type OrgToolPolicyRevision as OrgAskRevision } from "./org-tool-policies.js";
38
39
  import { OrgToolSwitches } from "./org-tool-switches.js";
39
40
  import { ToolOutputs } from "./outputs.js";
40
41
  import { type GrantKind } from "./policy.js";
@@ -161,10 +162,12 @@ export interface AskRequest {
161
162
  approverRole: OrgRole | null;
162
163
  /** Which rule asked (display only, written to `approval_requested.policy`). */
163
164
  policy: ApprovalPolicySource;
165
+ /** Organization policy rows that require a once-only human approval, regardless of source. */
166
+ orgAskRevisions?: readonly OrgAskRevision[];
164
167
  }
165
168
  /**
166
169
  * Which rule made a call need approval: role escalation, the agent's tool policy, the connector's
167
- * policy, a fixed ask (R3, `requiresUserInteraction`), the org's `sandboxToolPolicy`, or the tool's
170
+ * policy, a fixed ask (R3, `requiresUserInteraction`), an organization ceiling, or the tool's
168
171
  * own default.
169
172
  */
170
173
  export type ApprovalPolicySource = "agent" | "connector" | "member" | "default" | "role" | "org" | "fixed";
@@ -635,7 +638,7 @@ export declare class ToolPipeline {
635
638
  * The profile of an ask addressed to the conversation's person (profiles govern every
636
639
  * approval, R1); absent with {@link toolReview} (hand-built pipelines): every ask asks.
637
640
  */
638
- approvalProfile?: Pick<ConversationApprovalProfile, "resolve"> | undefined,
641
+ approvalProfile?: (Pick<ConversationApprovalProfile, "resolve"> & Partial<Pick<ConversationApprovalProfile, "canAdmitRecorded">>) | undefined,
639
642
  /** The review model's judgment of an ask under Approve for me (R3); absent: every ask asks. */
640
643
  toolReview?: ToolAskReviewer | undefined,
641
644
  /**
@@ -679,6 +682,9 @@ export declare class ToolPipeline {
679
682
  */
680
683
  private processCall;
681
684
  private runCall;
685
+ /** Take the organization authority before the transaction's durable start. */
686
+ private withOrgToolAdmission;
687
+ private canAdmitRecordedProfile;
682
688
  /**
683
689
  * The profile step (profiles govern every approval, R1-R3) of an ask `decide` returned for a call
684
690
  * no approval governs yet. It applies only to an ask addressed to the person (no role, the root
@@ -686,8 +692,8 @@ export declare class ToolPipeline {
686
692
  * itself require the person's interaction (D3); a call's secret fields are asked afterwards in a
687
693
  * secure input request whatever it decides (R4). Request approval asks; Auto allows; Approve for
688
694
  * me asks the review model, whose unsure answer asks the person. An `allow` or `deny` is recorded
689
- * once (`tool_ask_decided` and its audit row); a resumed call reads that record before the profile
690
- * and never calls the review model again. Anything that cannot be read asks the person (fail closed).
695
+ * once (`tool_ask_decided` and its audit row). A resumed call reuses an eligible allow or the
696
+ * recorded deny. If the ceiling invalidates an allow, the person decides instead.
691
697
  */
692
698
  private profileStep;
693
699
  /** Records an automatic decision once (R2) and announces it after the commit. */
@@ -34,6 +34,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
34
34
  import { TransactionHost, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
35
35
  import { Transactional } from "../infra/database/transactional.decorator.js";
36
36
  import { KERNEL_LOGGER } from "../infra/tokens.js";
37
+ import { roleAtLeast } from "../orgs/roles.js";
37
38
  import { UNKNOWN_RESULT_TEXT } from "../runtime/context/pairing.js";
38
39
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookScope, } from "../runtime/hook-calls.js";
39
40
  import { subagentWaitingIdemKey } from "../runtime/loop.js";
@@ -74,6 +75,7 @@ import { ToolDrift } from "./drift.js";
74
75
  import { ElicitationSession } from "./elicitation.js";
75
76
  import { loopbackGrantedNote, loopbackNotAppliedNote, loopbackPendingNote, loopbackReviewDeniedNote, planLoopbackAsk, } from "./loopback-asks.js";
76
77
  import { addressEscalationHint, blockedEventHosts, clipKept, denialHintFor, deviceAskTerms, MAX_NETWORK_ASKS_PER_RUN, NETWORK_ASK_KEPT_MAX_BYTES, networkBlockedIdemKey, otherAskPendingNote, planNetworkAsk, serviceAskedNote, serviceAskTerms, settledNetworkNotes, tooManyNote, withNetworkNotes, } from "./network-asks.js";
78
+ import { readOrgToolPolicy, } from "./org-tool-policies.js";
77
79
  import { OrgToolSwitches, toolTurnedOffReason } from "./org-tool-switches.js";
78
80
  import { renderResult, resolveOutputRefs, spillIfLarge, ToolOutputs } from "./outputs.js";
79
81
  import { createDecidePolicy } from "./policy.js";
@@ -247,6 +249,11 @@ const personalMissingText = (connectorName) => `The user has not connected ${con
247
249
  * throws an org `CredentialMissing` before any credential is presented, so the call never opens.
248
250
  */
249
251
  const ORG_MISSING_TEXT = "This connector needs to be configured by an organization admin before it can be used.";
252
+ const sameOrgAsk = (a, b) => canonicalJson(a ?? []) === canonicalJson(b ?? []);
253
+ class OrgToolPolicyChanged extends Error {
254
+ }
255
+ class OrgToolDenied extends Error {
256
+ }
250
257
  /** Optional provider: the pipeline's {@link ToolPipelineHooks} (tests). */
251
258
  export const TOOL_PIPELINE_HOOKS = Symbol("TOOL_PIPELINE_HOOKS");
252
259
  /** Review usage and hooks retain the same tree ancestry on both review routes. */
@@ -838,9 +845,7 @@ let ToolPipeline = class ToolPipeline {
838
845
  };
839
846
  const decide = hooks?.decidePolicy;
840
847
  // the default policy reads live, on the context's handle
841
- this.decide =
842
- decide ??
843
- ((tool, def, c) => createDecidePolicy(kdb.db, log.debug && { debug: log.debug.bind(log) })(tool, def, c));
848
+ this.decide = decide ?? ((tool, def, c) => createDecidePolicy(kdb.db)(tool, def, c));
844
849
  }
845
850
  /**
846
851
  * tools 节点:按顺序处理本步 assistant 消息里的全部 `tool_call`,每个调用都以一条 `tool_result` 结束
@@ -1216,8 +1221,22 @@ let ToolPipeline = class ToolPipeline {
1216
1221
  // 批准的是旧定义(等待期间工具定义变了):原批准不适用于当前定义,策略仍需审批时按新定义重新审批。
1217
1222
  // An approval binds the exact input it showed (Platform tool spec §6.3): an approved record
1218
1223
  // whose stored input differs from the call's is not used.
1224
+ const liveAsk = typeof decision === "object" && "ask" in decision ? decision.ask : undefined;
1225
+ const orgAskChanged = approval !== null &&
1226
+ (!sameOrgAsk(approval.orgAskRevisions, liveAsk?.orgAskRevisions) ||
1227
+ (liveAsk?.orgAskRevisions !== undefined &&
1228
+ (approval.toolKey !== policyKey ||
1229
+ approval.specHash !== tool.specHash ||
1230
+ approval.requestedFor !== liveAsk.requestedFor ||
1231
+ approval.approverRole !== liveAsk.approverRole ||
1232
+ canonicalJson(approval.input) !== canonicalJson(call.input ?? {}))));
1233
+ const supersedesOrgAsk = orgAskChanged ? approval?.id : undefined;
1234
+ if (orgAskChanged || approval?.status === "superseded")
1235
+ approval = null;
1219
1236
  const approvedHere = approval?.status === "approved" &&
1220
1237
  approval.specHash === tool.specHash &&
1238
+ (liveAsk?.orgAskRevisions === undefined ||
1239
+ (approval.scope === "once" && approval.decidedBy !== null)) &&
1221
1240
  canonicalJson(approval.input) === canonicalJson(call.input ?? {});
1222
1241
  const stale = approval?.status === "approved" && !approvedHere;
1223
1242
  // the profile step (profiles govern every approval, R1-R3): an ask addressed to the person
@@ -1253,12 +1272,18 @@ let ToolPipeline = class ToolPipeline {
1253
1272
  approverRole: decision.ask.approverRole,
1254
1273
  policy: decision.ask.policy,
1255
1274
  ...(callPolicy?.summary !== undefined && { summary: callPolicy.summary }),
1256
- ...(callPolicy !== null && !callPolicy.remember && { scopes: ["once"] }),
1257
- // the referenced file the approval binds by its sha256
1258
- ...((callPolicy?.file !== undefined || reviewUnsure) && {
1275
+ ...(supersedesOrgAsk !== undefined && { supersedesOrgAsk }),
1276
+ ...((decision.ask.orgAskRevisions !== undefined ||
1277
+ (callPolicy !== null && !callPolicy.remember)) && { scopes: ["once"] }),
1278
+ ...((callPolicy?.file !== undefined ||
1279
+ reviewUnsure ||
1280
+ decision.ask.orgAskRevisions !== undefined) && {
1259
1281
  detail: {
1260
1282
  ...(callPolicy?.file !== undefined && { file: callPolicy.file }),
1261
1283
  ...(reviewUnsure && { reviewUnsure: true }),
1284
+ ...(decision.ask.orgAskRevisions !== undefined && {
1285
+ orgAskRevisions: decision.ask.orgAskRevisions,
1286
+ }),
1262
1287
  },
1263
1288
  }),
1264
1289
  });
@@ -1367,6 +1392,19 @@ let ToolPipeline = class ToolPipeline {
1367
1392
  return undefined;
1368
1393
  }
1369
1394
  }
1395
+ const admit = (commit) => this.withOrgToolAdmission(ctx, tool, policyKey, call.input, approvedHere ? approval : null, auto, commit);
1396
+ const admissionError = (error) => {
1397
+ if (error instanceof OrgToolDenied || error instanceof OrgToolPolicyChanged)
1398
+ return error;
1399
+ throw error;
1400
+ };
1401
+ const changedPolicy = (error) => {
1402
+ if (error instanceof OrgToolDenied)
1403
+ return fail(deniedText(tool.key, callPolicy?.key), outKey);
1404
+ if (error instanceof OrgToolPolicyChanged)
1405
+ return this.runCall(ctx, call, resolved, attempt, resume, carried, rerun);
1406
+ throw error;
1407
+ };
1370
1408
  // `Agent` (sub-agents spec §7.1, agent map spec §4.1): no tool_call_started; one transaction
1371
1409
  // makes the dispatch durable (its marker is the subagent_dispatches row) and writes the call's
1372
1410
  // immediate result, while the sub-agent runs in the background
@@ -1376,12 +1414,17 @@ let ToolPipeline = class ToolPipeline {
1376
1414
  if (!parsed.success) {
1377
1415
  return fail("Invalid agent call: pass description and prompt, and optionally subagent_type and model.", outKey);
1378
1416
  }
1379
- const r = await dispatcher.dispatch({
1417
+ const r = await dispatcher
1418
+ .dispatch({
1380
1419
  ctx,
1381
1420
  callId: call.id,
1382
1421
  input: parsed.data,
1383
1422
  call: { toolKey: outKey, authorization, startedAt: Date.now() },
1384
- });
1423
+ admit,
1424
+ })
1425
+ .catch(admissionError);
1426
+ if (r instanceof Error)
1427
+ return changedPolicy(r);
1385
1428
  if (r.kind === "refused")
1386
1429
  return fail(r.content, outKey);
1387
1430
  if (hooks && hookBase) {
@@ -1409,16 +1452,23 @@ let ToolPipeline = class ToolPipeline {
1409
1452
  if (!parsed.success) {
1410
1453
  return fail("Invalid SendMessage call: pass to and message.", outKey);
1411
1454
  }
1412
- r = await messenger.toChild(ctx, call.id, parsed.data.to, parsed.data.message, {
1455
+ r = await messenger
1456
+ .toChild(ctx, call.id, parsed.data.to, parsed.data.message, {
1413
1457
  authorization,
1414
- });
1458
+ admit,
1459
+ })
1460
+ .catch(admissionError);
1415
1461
  }
1416
1462
  else {
1417
1463
  const parsed = HandbackInput.safeParse(input);
1418
1464
  if (!parsed.success)
1419
1465
  return fail("Invalid SubagentHandback call: pass message.", outKey);
1420
- r = await messenger.toParent(ctx, "report", parsed.data.message, call.id);
1466
+ r = await messenger
1467
+ .toParent(ctx, "report", parsed.data.message, call.id, admit)
1468
+ .catch(admissionError);
1421
1469
  }
1470
+ if (r instanceof Error)
1471
+ return changedPolicy(r);
1422
1472
  if (r.isError)
1423
1473
  return fail(r.content, outKey);
1424
1474
  const durationMs = Date.now() - t0;
@@ -1440,28 +1490,35 @@ let ToolPipeline = class ToolPipeline {
1440
1490
  !(await this.siteRetryAllowed(ctx, call.id, tool, input, rerun.site)))) {
1441
1491
  return fail("This site approval is no longer valid. The action did not run.", outKey);
1442
1492
  }
1443
- await this.deps.eventLog.append(ctx.conversationId, [
1444
- {
1445
- type: "tool_call_started",
1446
- runId: ctx.runId,
1447
- idemKey: idem.started(ctx.runId, call.id, attempt),
1448
- payload: {
1449
- step: ctx.step,
1450
- callId: call.id,
1451
- toolKey: tool.key,
1452
- specHash: tool.specHash,
1453
- ...(this.operationScoped(tool, input)
1454
- ? {
1455
- permissionInput: {
1456
- callInputHash: permissionScopeHash(call.input),
1457
- resolvedInputHash: permissionScopeHash(input),
1458
- ...(isEscalatedCall(tool.key, input) ? { sandbox: "escalated" } : {}),
1459
- },
1460
- }
1461
- : {}),
1493
+ try {
1494
+ await admit(() => this.deps.eventLog.append(ctx.conversationId, [
1495
+ {
1496
+ type: "tool_call_started",
1497
+ runId: ctx.runId,
1498
+ idemKey: idem.started(ctx.runId, call.id, attempt),
1499
+ payload: {
1500
+ step: ctx.step,
1501
+ callId: call.id,
1502
+ toolKey: tool.key,
1503
+ specHash: tool.specHash,
1504
+ ...(this.operationScoped(tool, input)
1505
+ ? {
1506
+ permissionInput: {
1507
+ callInputHash: permissionScopeHash(call.input),
1508
+ resolvedInputHash: permissionScopeHash(input),
1509
+ ...(isEscalatedCall(tool.key, input)
1510
+ ? { sandbox: "escalated" }
1511
+ : {}),
1512
+ },
1513
+ }
1514
+ : {}),
1515
+ },
1462
1516
  },
1463
- },
1464
- ]);
1517
+ ]));
1518
+ }
1519
+ catch (error) {
1520
+ return changedPolicy(error);
1521
+ }
1465
1522
  const t0 = Date.now();
1466
1523
  let outcome = await this.execute(tool, input, ctx, call.id, resume, resolved.tools, reviewedRoots,
1467
1524
  // the approval the call runs under (a Platform write reads the person's values by it)
@@ -1742,6 +1799,79 @@ let ToolPipeline = class ToolPipeline {
1742
1799
  }
1743
1800
  return undefined;
1744
1801
  }
1802
+ /** Take the organization authority before the transaction's durable start. */
1803
+ withOrgToolAdmission(ctx, tool, policyKey, input, approval, automatic, commit) {
1804
+ const locks = this.permissionLocks;
1805
+ const recheck = async () => {
1806
+ const db = this.deps.db;
1807
+ // Stabilize the recorded approver's membership before taking the authority lock.
1808
+ const member = approval?.status === "approved" &&
1809
+ approval.orgAskRevisions !== undefined &&
1810
+ approval.decidedBy !== null
1811
+ ? await db
1812
+ .selectFrom("memberships")
1813
+ .select("role")
1814
+ .where("org_id", "=", ctx.orgId)
1815
+ .where("account_id", "=", approval.decidedBy)
1816
+ .$if(locks !== undefined, (query) => query.forShare())
1817
+ .executeTakeFirst()
1818
+ : undefined;
1819
+ await locks?.acquire({ orgId: ctx.orgId }, { kind: "admit" });
1820
+ const unattended = unattendedRules(ctx.unattended);
1821
+ const current = await readOrgToolPolicy(db, ctx.orgId, tool.key, policyKey, unattended);
1822
+ if (current.policy === "deny")
1823
+ throw new OrgToolDenied();
1824
+ if (automatic !== undefined && !(await this.canAdmitRecordedProfile(ctx, automatic)))
1825
+ throw new OrgToolPolicyChanged();
1826
+ if (current.policy !== "ask")
1827
+ return;
1828
+ if (approval?.status !== "approved" ||
1829
+ approval.toolKey !== policyKey ||
1830
+ approval.specHash !== tool.specHash ||
1831
+ approval.scope !== "once" ||
1832
+ approval.decidedBy === null ||
1833
+ !sameOrgAsk(approval.orgAskRevisions, current.revisions) ||
1834
+ canonicalJson(approval.input) !== canonicalJson(input ?? {}))
1835
+ throw new OrgToolPolicyChanged();
1836
+ if (!member)
1837
+ throw new OrgToolDenied();
1838
+ if (approval.requestedFor === null) {
1839
+ if (approval.approverRole === null ||
1840
+ approval.decidedBy === ctx.accountId ||
1841
+ !roleAtLeast(member.role, approval.approverRole))
1842
+ throw new OrgToolDenied();
1843
+ }
1844
+ else {
1845
+ if (approval.decidedBy !== approval.requestedFor)
1846
+ throw new OrgToolDenied();
1847
+ if (tool.requiredRole !== undefined && !roleAtLeast(member.role, tool.requiredRole))
1848
+ throw new OrgToolPolicyChanged();
1849
+ }
1850
+ };
1851
+ return locks === undefined
1852
+ ? recheck().then(commit)
1853
+ : withTransactionFencePrelude(recheck, commit);
1854
+ }
1855
+ async canAdmitRecordedProfile(ctx, decision) {
1856
+ const profiles = this.approvalProfile;
1857
+ if (profiles?.canAdmitRecorded === undefined)
1858
+ return true;
1859
+ try {
1860
+ return await profiles.canAdmitRecorded({
1861
+ orgId: ctx.orgId,
1862
+ rootConversationId: ctx.parent?.rootConversationId ?? ctx.conversationId,
1863
+ profile: decision.source === "full-access" ? "full-access" : "approve-for-me",
1864
+ revision: decision.revision,
1865
+ });
1866
+ }
1867
+ catch (error) {
1868
+ this.deps.log.warn("cannot check a recorded profile decision; asking the person", {
1869
+ conversationId: ctx.conversationId,
1870
+ error,
1871
+ });
1872
+ return false;
1873
+ }
1874
+ }
1745
1875
  /**
1746
1876
  * The profile step (profiles govern every approval, R1-R3) of an ask `decide` returned for a call
1747
1877
  * no approval governs yet. It applies only to an ask addressed to the person (no role, the root
@@ -1749,8 +1879,8 @@ let ToolPipeline = class ToolPipeline {
1749
1879
  * itself require the person's interaction (D3); a call's secret fields are asked afterwards in a
1750
1880
  * secure input request whatever it decides (R4). Request approval asks; Auto allows; Approve for
1751
1881
  * me asks the review model, whose unsure answer asks the person. An `allow` or `deny` is recorded
1752
- * once (`tool_ask_decided` and its audit row); a resumed call reads that record before the profile
1753
- * and never calls the review model again. Anything that cannot be read asks the person (fail closed).
1882
+ * once (`tool_ask_decided` and its audit row). A resumed call reuses an eligible allow or the
1883
+ * recorded deny. If the ceiling invalidates an allow, the person decides instead.
1754
1884
  */
1755
1885
  async profileStep(ctx, call, tool, input, ask, callPolicy) {
1756
1886
  const asks = { kind: "ask", unsure: false };
@@ -1758,6 +1888,8 @@ let ToolPipeline = class ToolPipeline {
1758
1888
  const reviewer = this.toolReview;
1759
1889
  if (profiles === undefined || reviewer === undefined)
1760
1890
  return asks;
1891
+ if (ask.orgAskRevisions !== undefined)
1892
+ return asks;
1761
1893
  if (ask.approverRole !== null || ask.requestedFor === null)
1762
1894
  return asks;
1763
1895
  if (ctx.unattended != null)
@@ -1767,13 +1899,16 @@ let ToolPipeline = class ToolPipeline {
1767
1899
  return asks;
1768
1900
  if (tool.spec.annotations?.requiresUserInteraction === true)
1769
1901
  return asks;
1770
- // a decision already recorded for this call governs it whatever the profile reads now (R2: a
1771
- // resumed call reuses it; a profile change never revokes started work)
1902
+ // Reuse the decision if its profile is still eligible. A ceiling change leaves started work alone.
1772
1903
  const bindingHash = askBindingHash(ask.toolKey, ask.specHash, call.input);
1773
1904
  const idemKey = `tool_ask_decided:${ctx.runId}:${call.id}:${bindingHash}`;
1774
1905
  const recorded = await this.deps.eventLog.findByIdem(ctx.conversationId, idemKey);
1775
- if (recorded?.type === "tool_ask_decided")
1776
- return askDecisionOf(recorded);
1906
+ if (recorded?.type === "tool_ask_decided") {
1907
+ const outcome = askDecisionOf(recorded);
1908
+ if (outcome.kind === "allow" && !(await this.canAdmitRecordedProfile(ctx, outcome.decision)))
1909
+ return asks;
1910
+ return outcome;
1911
+ }
1777
1912
  const rootConversationId = ctx.parent?.rootConversationId ?? ctx.conversationId;
1778
1913
  let resolved;
1779
1914
  try {
@@ -1,5 +1,4 @@
1
1
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
- import type { KernelLogger } from "../log.js";
3
2
  import type { DecidePolicy } from "./pipeline.js";
4
3
  import type { ToolPolicy } from "./registry.js";
5
4
  export { R3_FIXED_ASK_TOOL_KEYS } from "./builtin-names.js";
@@ -52,7 +51,7 @@ export declare function connectorPolicy(input: {
52
51
  };
53
52
  /**
54
53
  * 执行时的策略判定(spec 3.6 R5:在动作执行那一刻判定)。每次调用都实时读取:
55
- * - 沙箱工具(bash / write / edit / deliver)的组织设置 `sandboxToolPolicy`(为 ask 时组织默认至少 ask);
54
+ * - The organization’s live tool and per-call ceilings; a fixed organization ask needs a human.
56
55
  * - 连接器工具的 `connector_tools.default_policy` / 状态 / 指纹(连接器或工具已不存在、停用、删除、待审核 →
57
56
  * `{ unavailable: 原因 }`,管线写「工具不可用」的事实说明,而非策略拒绝);
58
57
  * - agent 当前版本的 `toolPolicies`,与运行所用版本取更严者(负责人运行中收紧立即生效;放宽不影响已在跑的运行);
@@ -70,8 +69,7 @@ export declare function connectorPolicy(input: {
70
69
  * 结果为 `ask` 时返回审批请求,默认指向发起人本人;记住的授权把 `ask` 放行时返回 `{ grant }`(按 allow 执行)。
71
70
  *
72
71
  * An unattended run (`ctx.unattended`, not a trial run; scheduled tasks spec §7):
73
- * - a tool in the org's `forbiddenTools` (by tool key or per-call key) is denied; when the stored
74
- * list cannot be read every call is refused (`FORBIDDEN_TOOLS_UNREADABLE_ERROR`);
72
+ * - the unattended column further narrows the organization’s general tool ceiling;
75
73
  * - a Platform call that changes the agent's skills (`agents.register-skill`, ...) is an ask no
76
74
  * grant covers, even on a private agent where it would run without asking;
77
75
  * - an ask is also allowed by a task grant of the current definition (`{ grant: "task" }`), never
@@ -84,6 +82,4 @@ export declare function connectorPolicy(input: {
84
82
  * the ask (profiles govern every approval, R5): the pipeline asks for their values in a secure
85
83
  * input request after the consent. The pipeline refuses both before this in an unattended run.
86
84
  */
87
- export declare function createDecidePolicy(db: KernelSchemaDb,
88
- /** Logs (debug: once per call) when an org's stored security setting is unreadable. */
89
- log?: Pick<KernelLogger, "debug">): DecidePolicy;
85
+ export declare function createDecidePolicy(db: KernelSchemaDb): DecidePolicy;