@capybara-hq/kernel 0.1.0-rc.63 → 0.1.0-rc.65

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 (92) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/catalog/org-catalog.schemas.d.ts +1 -1
  3. package/dist/catalog/org-catalog.schemas.js +1 -1
  4. package/dist/channels/actions.d.ts +2 -5
  5. package/dist/channels/actions.js +20 -8
  6. package/dist/channels/cards.d.ts +4 -3
  7. package/dist/channels/cards.js +6 -4
  8. package/dist/channels/outbound.js +3 -2
  9. package/dist/config/schema.js +1 -1
  10. package/dist/conversations/approval-profile.d.ts +30 -0
  11. package/dist/conversations/approval-profile.js +62 -0
  12. package/dist/conversations/conversations.service.js +0 -2
  13. package/dist/conversations/events.d.ts +46 -2
  14. package/dist/conversations/events.js +55 -2
  15. package/dist/conversations/permission-profiles.controller.d.ts +3 -2
  16. package/dist/conversations/permission-profiles.service.d.ts +3 -2
  17. package/dist/conversations/permission-profiles.service.js +12 -8
  18. package/dist/db/kernel-schema.d.ts +4 -2
  19. package/dist/identity/initial-passwords.controller.d.ts +8 -6
  20. package/dist/identity/initial-passwords.controller.js +13 -7
  21. package/dist/identity/initial-passwords.d.ts +22 -13
  22. package/dist/identity/initial-passwords.js +25 -29
  23. package/dist/local-devices/relay.js +3 -1
  24. package/dist/models/images.js +5 -4
  25. package/dist/platform/connector-person-fields.js +2 -2
  26. package/dist/platform/exclusions.js +4 -4
  27. package/dist/platform/method.js +1 -1
  28. package/dist/platform/operation.d.ts +9 -7
  29. package/dist/platform/operation.js +1 -1
  30. package/dist/platform/ops/accounts.ops.d.ts +1 -1
  31. package/dist/platform/ops/accounts.ops.js +3 -3
  32. package/dist/platform/ops/channels.ops.d.ts +1 -1
  33. package/dist/platform/ops/channels.ops.js +2 -2
  34. package/dist/platform/ops/connectors.ops.d.ts +2 -2
  35. package/dist/platform/ops/connectors.ops.js +8 -8
  36. package/dist/platform/ops/extensions-admin.ops.d.ts +1 -1
  37. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  38. package/dist/platform/ops/extensions.ops.d.ts +1 -1
  39. package/dist/platform/ops/extensions.ops.js +4 -4
  40. package/dist/platform/ops/org-plugins.ops.js +2 -2
  41. package/dist/platform/ops/orgs.ops.d.ts +1 -1
  42. package/dist/platform/ops/orgs.ops.js +3 -3
  43. package/dist/platform/ops/plugins.ops.d.ts +1 -1
  44. package/dist/platform/ops/plugins.ops.js +2 -2
  45. package/dist/platform/person-fields.d.ts +4 -3
  46. package/dist/platform/person-fields.js +6 -5
  47. package/dist/platform/sealed-inputs.d.ts +2 -2
  48. package/dist/platform/sealed-inputs.js +2 -2
  49. package/dist/platform/sealed-reveals.controller.d.ts +5 -8
  50. package/dist/platform/sealed-reveals.controller.js +8 -8
  51. package/dist/platform/sealed-reveals.d.ts +19 -17
  52. package/dist/platform/sealed-reveals.js +30 -33
  53. package/dist/runtime/context/build.js +3 -0
  54. package/dist/runtime/context/compaction.js +2 -0
  55. package/dist/runtime/waits.js +3 -2
  56. package/dist/sandbox/operation-authority.js +16 -15
  57. package/dist/sandbox/operation-intents.js +2 -2
  58. package/dist/sandbox/permission-availability.d.ts +49 -3
  59. package/dist/sandbox/permission-availability.js +61 -6
  60. package/dist/sandbox/permission-call-types.d.ts +3 -0
  61. package/dist/sandbox/permission-facts.d.ts +29 -1
  62. package/dist/sandbox/permission-facts.js +30 -6
  63. package/dist/sandbox/permission-runtime-reports.js +1 -0
  64. package/dist/sandbox/review/classifier.d.ts +72 -2
  65. package/dist/sandbox/review/classifier.js +113 -38
  66. package/dist/sandbox/review/index.d.ts +2 -2
  67. package/dist/sandbox/review/index.js +1 -1
  68. package/dist/sandbox/review/review.service.d.ts +1 -4
  69. package/dist/sandbox/review/review.service.js +4 -33
  70. package/dist/setup/setup-guides.service.js +1 -1
  71. package/dist/tools/approvals.service.d.ts +71 -16
  72. package/dist/tools/approvals.service.js +139 -13
  73. package/dist/tools/builtins/builtin-tools.d.ts +1 -1
  74. package/dist/tools/builtins/builtin-tools.js +12 -6
  75. package/dist/tools/builtins/platform.d.ts +15 -11
  76. package/dist/tools/builtins/platform.js +49 -39
  77. package/dist/tools/builtins/sandbox/bash.d.ts +1 -1
  78. package/dist/tools/builtins/sandbox/bash.js +32 -14
  79. package/dist/tools/builtins/sandbox/common.d.ts +12 -3
  80. package/dist/tools/builtins/sandbox/common.js +29 -5
  81. package/dist/tools/connectors.schemas.d.ts +1 -1
  82. package/dist/tools/connectors.schemas.js +1 -1
  83. package/dist/tools/pipeline.d.ts +70 -10
  84. package/dist/tools/pipeline.js +359 -49
  85. package/dist/tools/policy.d.ts +4 -3
  86. package/dist/tools/policy.js +6 -6
  87. package/dist/tools/registry.d.ts +25 -9
  88. package/dist/tools/tool-review.d.ts +113 -0
  89. package/dist/tools/tool-review.js +303 -0
  90. package/dist/tools/tools.module.js +6 -0
  91. package/package.json +3 -3
  92. package/src/migrations/0175_secure_input_kind.sql +8 -0
@@ -9,7 +9,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { ToolError, validateInputForm, validateToolDisplay, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
+ import { sql } from "kysely";
12
13
  import { backgroundMaxSeconds } from "../background/launch.js";
14
+ import { ConversationApprovalProfile } from "../conversations/approval-profile.js";
13
15
  import { EventLog } from "../conversations/event-log.js";
14
16
  import { COMMAND_ASK_MAX_CHARS, COMMAND_ASK_TEXT_MAX_CHARS, ToolViewSchema, } from "../conversations/events.js";
15
17
  import { ConversationDevices } from "../devices/conversation-devices.js";
@@ -56,6 +58,7 @@ import { BUILTIN, SEND_MESSAGE, SUBAGENT_HANDBACK, TOOL_SEARCH } from "./builtin
56
58
  import { AGENT_TOOL, AgentToolInput } from "./builtins/agent.js";
57
59
  import { HandbackInput } from "./builtins/handback.js";
58
60
  import { generateImagePaths } from "./builtins/image/paths.js";
61
+ import { admissionUnavailableText } from "./builtins/sandbox/common.js";
59
62
  import { DEVICE_CODE_PATTERN, deviceCodeIdemKey, GITHUB_DEVICE_LOGIN_URL, } from "./builtins/sandbox/device-code.js";
60
63
  import { DEVICE_OF_ANOTHER_ACCOUNT_TEXT } from "./builtins/sandbox/device-owner.js";
61
64
  import { SendMessageInput } from "./builtins/send-message.js";
@@ -72,6 +75,7 @@ import { QuestionsService } from "./questions.service.js";
72
75
  import { redactDeep, redactorFor } from "./redact.js";
73
76
  import { ToolRegistry, } from "./registry.js";
74
77
  import { runResourceTool } from "./resources.js";
78
+ import { ToolAskReview } from "./tool-review.js";
75
79
  import { validateInput } from "./validate.js";
76
80
  // ---- 模型可见文案(英文) ----
77
81
  /** 审批被拒绝。 */
@@ -149,11 +153,22 @@ export const PERSON_FIELDS_UNATTENDED_TEXT = "This write needs the person to ent
149
153
  export const PERSON_FIELDS_ROLE_TEXT = "This write needs the person you work for to enter values; they lack the role. Ask an admin to do it on the web.";
150
154
  /**
151
155
  * A call only the person may confirm (`CallPolicy.personOnly`: its result is shown once to the
152
- * approver) in an unattended run: nobody is there to approve and read it.
156
+ * run's person) in an unattended run: nobody is there to read it.
153
157
  */
154
- export const PERSON_ONLY_UNATTENDED_TEXT = "This write shows its result once, on the web, to the person who approves it; it cannot run unattended.";
158
+ export const PERSON_ONLY_UNATTENDED_TEXT = "This write shows its result once, on the web, to the person you work for, and no one is there to read it; it cannot run unattended.";
155
159
  /** A call only the person may confirm whose ask would go to a role instead of the person. */
156
- export const PERSON_ONLY_ROLE_TEXT = "This write shows its result once to the person you work for, who must approve it; they lack the role. Ask an admin to do it on the web.";
160
+ export const PERSON_ONLY_ROLE_TEXT = "This write shows its result once to the person you work for, so it runs only for them, and they lack the role. Ask an admin to do it on the web.";
161
+ /**
162
+ * The review model declined, under Approve for me, a call whose approval would have gone to the
163
+ * person (profiles govern every approval, R3): nothing ran.
164
+ */
165
+ export const toolReviewDeniedText = (reason) => `The review model declined this call for the person (Approve for me): ${reason} Nothing ran. Tell the person what you wanted to do and why; they can do it themselves, or switch this conversation to Request approval and approve it when you call again.`;
166
+ /** The reason recorded when Auto runs an approval addressed to the person (R2). */
167
+ export const TOOL_AUTO_REASON = "Auto runs approvals addressed to the person without asking.";
168
+ /** The person cancelled the secure input request of a call with person fields (R4): nothing ran. */
169
+ export const secureInputCancelledText = (id) => `The person cancelled secure input ${id}, so nothing ran. Never ask for the value in the conversation; call the operation again only if the person asks for it.`;
170
+ /** A secure input request expired unanswered (R4): nothing ran. */
171
+ export const secureInputExpiredText = (id, hours) => `Secure input ${id} expired after ${hours} h without the person submitting it, so nothing ran. Call the operation again if it is still needed.`;
157
172
  /** 调用执行中 run 被中止 / 到达截止时间。 */
158
173
  export const RUN_STOPPED_DURING_TEXT = "The run was stopped while this tool call was running; its outcome is unknown. Verify before retrying.";
159
174
  /** The fixed result of a call whose input request was skipped by a message (spec §7.1). */
@@ -310,6 +325,26 @@ const textField = (input, field) => {
310
325
  const v = input?.[field];
311
326
  return typeof v === "string" ? v : "";
312
327
  };
328
+ /**
329
+ * The binding of an automatic decision (R2): the first 16 hex chars of the sha256 of the policy
330
+ * key, the definition and the raw input, as an approval binds them.
331
+ */
332
+ const askBindingHash = (policyKey, specHash, rawInput) => sha256Hex(canonicalJson([policyKey, specHash, rawInput ?? {}])).slice(0, 16);
333
+ /** The profile step's outcome from a recorded automatic decision. */
334
+ const askDecisionOf = (event) => {
335
+ const p = event.payload;
336
+ return p.outcome === "deny"
337
+ ? { kind: "deny", reason: p.reason }
338
+ : {
339
+ kind: "allow",
340
+ decision: {
341
+ source: p.decisionSource,
342
+ revision: p.profileRevision,
343
+ seq: event.seq,
344
+ ...(p.fileSha256 !== undefined && { fileSha256: p.fileSha256 }),
345
+ },
346
+ };
347
+ };
313
348
  const approvalAuthorization = (a) => ({
314
349
  approvalId: a.id,
315
350
  approvedByAccountId: a.decidedBy,
@@ -443,6 +478,8 @@ let ToolPipeline = class ToolPipeline {
443
478
  autoGrants;
444
479
  permissionLocks;
445
480
  sandboxes;
481
+ approvalProfile;
482
+ toolReview;
446
483
  decide;
447
484
  deps;
448
485
  constructor(kdb, eventLog,
@@ -461,7 +498,14 @@ let ToolPipeline = class ToolPipeline {
461
498
  /** The paired activation gate: on, the managed builtins take the permission review. */
462
499
  activation,
463
500
  /** Starts a cloud device before its first managed call is reviewed (absent: never). */
464
- sandboxes) {
501
+ sandboxes,
502
+ /**
503
+ * The profile of an ask addressed to the conversation's person (profiles govern every
504
+ * approval, R1); absent with {@link toolReview} (hand-built pipelines): every ask asks.
505
+ */
506
+ approvalProfile,
507
+ /** The review model's judgment of an ask under Approve for me (R3); absent: every ask asks. */
508
+ toolReview) {
465
509
  this.config = config;
466
510
  this.txHost = txHost;
467
511
  this.permissionAuthority = permissionAuthority;
@@ -469,6 +513,8 @@ let ToolPipeline = class ToolPipeline {
469
513
  this.autoGrants = autoGrants;
470
514
  this.permissionLocks = permissionLocks;
471
515
  this.sandboxes = sandboxes;
516
+ this.approvalProfile = approvalProfile;
517
+ this.toolReview = toolReview;
472
518
  this.deps = {
473
519
  // the builtins that enter a device on the managed operation route once activated (common.ts
474
520
  // `inToolSandbox`, `inSandboxPreparation`): their review is the permission review, whose
@@ -698,7 +744,9 @@ let ToolPipeline = class ToolPipeline {
698
744
  keys = keys.filter((k) => isAlwaysLoaded(k) || sent.has(k));
699
745
  }
700
746
  keys.sort();
701
- return fail(unknownToolText(call.name, keys, keys.includes(TOOL_SEARCH)));
747
+ // In ToolSearch mode a name the model has not loaded (a catalog tool, or one it misspelled) is
748
+ // the protocol asking it to search, not a failure: the row reads neutral like `not_loaded`.
749
+ return fail(unknownToolText(call.name, keys, keys.includes(TOOL_SEARCH)), call.name, resolved.toolSearch === true ? { kind: "not_loaded" } : undefined);
702
750
  }
703
751
  const outKey = tool.key;
704
752
  // ToolSearch 模式下,模型只能调用请求里带了完整定义的工具:目录里有、但发出本次调用的请求没加载 →
@@ -742,12 +790,13 @@ let ToolPipeline = class ToolPipeline {
742
790
  return fail(callPolicy.denyReason, outKey);
743
791
  }
744
792
  const policyKey = callPolicy?.key ?? tool.key;
745
- // person fields (platform web parity spec §4.2, R6): the person types values on the card, so an
746
- // unattended run (a trial run has its creator there) cannot make the call at all
793
+ // person fields (platform web parity spec §4.2; profiles govern every approval R4, R5): the
794
+ // person types the values in a secure input request, so an unattended run (a trial run has its
795
+ // creator there) cannot make the call at all
747
796
  const personFields = callPolicy?.personFields;
748
- // a call whose result is shown once to its approver asks the person the same way
749
- const personOnly = personFields !== undefined || callPolicy?.personOnly === true;
750
- if (personOnly && unattendedRules(ctx.unattended)) {
797
+ // a call whose result is shown once to the run's person is refused there the same way
798
+ const personOnly = callPolicy?.personOnly === true;
799
+ if ((personFields !== undefined || personOnly) && unattendedRules(ctx.unattended)) {
751
800
  return fail(personFields !== undefined ? PERSON_FIELDS_UNATTENDED_TEXT : PERSON_ONLY_UNATTENDED_TEXT, outKey);
752
801
  }
753
802
  let decision = await this.decide(tool, ctx.agent, {
@@ -775,10 +824,11 @@ let ToolPipeline = class ToolPipeline {
775
824
  if (typeof decision === "object" && "unavailable" in decision) {
776
825
  return fail(unavailableText(tool.key, decision.unavailable), outKey);
777
826
  }
778
- if (personOnly) {
779
- // R6: always the person's own card, never a grant or an `allow` (the default policy already
780
- // asks for them; this holds for any decision)
781
- if (decision === "allow" || "grant" in decision) {
827
+ if (personOnly || personFields !== undefined) {
828
+ // R6: a call only the person may confirm is always their own ask, never a grant or an
829
+ // `allow` (the default policy already asks for them; this holds for any decision). Person
830
+ // fields no longer force the consent (R5): it follows the call's policy, grants and profile
831
+ if (personOnly && (decision === "allow" || "grant" in decision)) {
782
832
  decision = {
783
833
  ask: {
784
834
  toolKey: policyKey,
@@ -790,8 +840,9 @@ let ToolPipeline = class ToolPipeline {
790
840
  },
791
841
  };
792
842
  }
793
- // R5: only the person the run works for types the values; a role escalation cannot ask them
794
- if ("ask" in decision && decision.ask.requestedFor === null) {
843
+ // R5: only the person the run works for types the values or reads the result; a role
844
+ // escalation cannot ask them
845
+ if (typeof decision === "object" && "ask" in decision && decision.ask.requestedFor === null) {
795
846
  return fail(personFields !== undefined ? PERSON_FIELDS_ROLE_TEXT : PERSON_ONLY_ROLE_TEXT, outKey);
796
847
  }
797
848
  }
@@ -805,9 +856,26 @@ let ToolPipeline = class ToolPipeline {
805
856
  approval.specHash === tool.specHash &&
806
857
  canonicalJson(approval.input) === canonicalJson(call.input ?? {});
807
858
  const stale = approval?.status === "approved" && !approvedHere;
859
+ // the profile step (profiles govern every approval, R1-R3): an ask addressed to the person
860
+ // with no approval governing the call yet is decided by the conversation's profile
861
+ let auto;
862
+ let reviewUnsure = false;
808
863
  if ((!approval || stale) && typeof decision === "object" && "ask" in decision) {
864
+ const step = await this.profileStep(ctx, call, tool, input, decision.ask, callPolicy);
865
+ if (step.kind === "deny")
866
+ return fail(toolReviewDeniedText(step.reason), outKey);
867
+ if (step.kind === "allow")
868
+ auto = step.decision;
869
+ else
870
+ reviewUnsure = step.unsure;
871
+ }
872
+ if ((!approval || stale) &&
873
+ auto === undefined &&
874
+ typeof decision === "object" &&
875
+ "ask" in decision) {
809
876
  approval = await this.deps.approvals.request({
810
- attempt: (approval?.attempt ?? 0) + 1,
877
+ // after every earlier request of the call, whatever its kind (attempts share one key)
878
+ attempt: (await this.lastAttempt(ctx.runId, call.id)) + 1,
811
879
  orgId: ctx.orgId,
812
880
  conversationId: ctx.conversationId,
813
881
  runId: ctx.runId,
@@ -821,18 +889,12 @@ let ToolPipeline = class ToolPipeline {
821
889
  approverRole: decision.ask.approverRole,
822
890
  policy: decision.ask.policy,
823
891
  ...(callPolicy?.summary !== undefined && { summary: callPolicy.summary }),
824
- ...((personFields !== undefined || (callPolicy !== null && !callPolicy.remember)) && {
825
- scopes: ["once"],
826
- }),
827
- // the specs of the asked fields, never a value (the card draws its inputs from them), and
892
+ ...(callPolicy !== null && !callPolicy.remember && { scopes: ["once"] }),
828
893
  // the referenced file the approval binds by its sha256
829
- ...((personFields !== undefined || callPolicy?.file !== undefined) && {
894
+ ...((callPolicy?.file !== undefined || reviewUnsure) && {
830
895
  detail: {
831
- ...(personFields !== undefined && {
832
- personFields: personFields.fields,
833
- target: personFields.target,
834
- }),
835
896
  ...(callPolicy?.file !== undefined && { file: callPolicy.file }),
897
+ ...(reviewUnsure && { reviewUnsure: true }),
836
898
  },
837
899
  }),
838
900
  });
@@ -844,9 +906,23 @@ let ToolPipeline = class ToolPipeline {
844
906
  // 走到这里即放行:在(与当前定义一致的)审批下执行,否则是授权或策略放行
845
907
  let authorization = approval?.status === "approved" && approvedHere
846
908
  ? approvalAuthorization(approval)
847
- : typeof decision === "object" && "grant" in decision
848
- ? { grant: decision.grant }
849
- : { policy: "allow" };
909
+ : auto !== undefined
910
+ ? { decisionSource: auto.source, profileRevision: auto.revision, decisionSeq: auto.seq }
911
+ : typeof decision === "object" && "grant" in decision
912
+ ? { grant: decision.grant }
913
+ : { policy: "allow" };
914
+ // the secure input (profiles govern every approval, R4): once the call's consent is settled
915
+ // (approved here, a grant, an allow or the profile's decision), the person enters the call's
916
+ // secret fields under every profile, before the command review
917
+ let secureInputId;
918
+ if (personFields !== undefined) {
919
+ const secured = await this.secureInput(ctx, call, tool, policyKey, personFields);
920
+ if (secured.kind === "wait")
921
+ return secured.wait;
922
+ if (secured.kind === "refused")
923
+ return fail(secured.text, outKey);
924
+ secureInputId = secured.id;
925
+ }
850
926
  // Auto mode spec §5.1: the command review, after argument validation and the tool policy (and
851
927
  // its approval), before the plugin hooks and `tool_call_started`. A deny ends the call here; an
852
928
  // ask parks the run on the command approval (attended) or is a deny at once (unattended). An
@@ -1019,7 +1095,16 @@ let ToolPipeline = class ToolPipeline {
1019
1095
  const t0 = Date.now();
1020
1096
  let outcome = await this.execute(tool, input, ctx, call.id, resume, resolved.tools, reviewedRoots,
1021
1097
  // the approval the call runs under (a Platform write reads the person's values by it)
1022
- approval?.status === "approved" && approvedHere ? approval.id : undefined);
1098
+ approval?.status === "approved" && approvedHere ? approval.id : undefined,
1099
+ // or the automatic decision and the file bytes it was bound to (R7)
1100
+ auto === undefined
1101
+ ? undefined
1102
+ : {
1103
+ source: auto.source,
1104
+ ...(auto.fileSha256 !== undefined && { fileSha256: auto.fileSha256 }),
1105
+ },
1106
+ // and the submitted secure input holding the person's values
1107
+ secureInputId);
1023
1108
  const durationMs = Date.now() - t0;
1024
1109
  await this.deps.hooks?.afterExecute?.(ctx.runId, call.id);
1025
1110
  // the record says a call ran outside the sandbox only when admission gave it that scope
@@ -1171,6 +1256,151 @@ let ToolPipeline = class ToolPipeline {
1171
1256
  }
1172
1257
  return undefined;
1173
1258
  }
1259
+ /**
1260
+ * The profile step (profiles govern every approval, R1-R3) of an ask `decide` returned for a call
1261
+ * no approval governs yet. It applies only to an ask addressed to the person (no role, the root
1262
+ * conversation's own owner), in an attended interactive chat, and for a tool that does not
1263
+ * itself require the person's interaction (D3); a call's secret fields are asked afterwards in a
1264
+ * secure input request whatever it decides (R4). Request approval asks; Auto allows; Approve for
1265
+ * me asks the review model, whose unsure answer asks the person. An `allow` or `deny` is recorded
1266
+ * once (`tool_ask_decided` and its audit row); a resumed call reads that record before the profile
1267
+ * and never calls the review model again. Anything that cannot be read asks the person (fail closed).
1268
+ */
1269
+ async profileStep(ctx, call, tool, input, ask, callPolicy) {
1270
+ const asks = { kind: "ask", unsure: false };
1271
+ const profiles = this.approvalProfile;
1272
+ const reviewer = this.toolReview;
1273
+ if (profiles === undefined || reviewer === undefined)
1274
+ return asks;
1275
+ if (ask.approverRole !== null || ask.requestedFor === null)
1276
+ return asks;
1277
+ if (ctx.unattended != null)
1278
+ return asks;
1279
+ if (tool.spec.annotations?.requiresUserInteraction === true)
1280
+ return asks;
1281
+ // a decision already recorded for this call governs it whatever the profile reads now (R2: a
1282
+ // resumed call reuses it; a profile change never revokes started work)
1283
+ const bindingHash = askBindingHash(ask.toolKey, ask.specHash, call.input);
1284
+ const idemKey = `tool_ask_decided:${ctx.runId}:${call.id}:${bindingHash}`;
1285
+ const recorded = await this.deps.eventLog.findByIdem(ctx.conversationId, idemKey);
1286
+ if (recorded?.type === "tool_ask_decided")
1287
+ return askDecisionOf(recorded);
1288
+ const rootConversationId = ctx.parent?.rootConversationId ?? ctx.conversationId;
1289
+ let resolved;
1290
+ try {
1291
+ resolved = await profiles.resolve({
1292
+ orgId: ctx.orgId,
1293
+ rootConversationId,
1294
+ requestedFor: ask.requestedFor,
1295
+ });
1296
+ }
1297
+ catch (err) {
1298
+ this.deps.log.warn("cannot read the conversation's permission profile; asking the person", {
1299
+ conversationId: ctx.conversationId,
1300
+ callId: call.id,
1301
+ err,
1302
+ });
1303
+ return asks;
1304
+ }
1305
+ if (resolved === null || resolved.profile === "request-approval")
1306
+ return asks;
1307
+ let decision;
1308
+ if (resolved.profile === "full-access") {
1309
+ decision = { outcome: "allow", reason: TOOL_AUTO_REASON, source: "full-access" };
1310
+ }
1311
+ else {
1312
+ const parent = ctx.parent;
1313
+ const verdict = await reviewer.review({
1314
+ orgId: ctx.orgId,
1315
+ rootConversationId,
1316
+ conversationId: ctx.conversationId,
1317
+ runId: ctx.runId,
1318
+ step: ctx.step,
1319
+ callId: call.id,
1320
+ accountId: ctx.accountId,
1321
+ signal: ctx.signal,
1322
+ toolKey: ask.toolKey,
1323
+ title: tool.spec.title ?? null,
1324
+ summary: callPolicy?.summary ?? null,
1325
+ input,
1326
+ inputSchema: tool.spec.inputSchema,
1327
+ // a sub-agent's review counts on its parent run, as the command review's does
1328
+ ...(parent !== undefined && {
1329
+ parentRunId: parent.runId,
1330
+ ...(parent.budgetRunId !== undefined && { budgetRunId: parent.budgetRunId }),
1331
+ }),
1332
+ hookFacts: {
1333
+ accountId: ctx.accountId,
1334
+ agentId: ctx.agentId,
1335
+ agentVersion: ctx.agentVersion,
1336
+ conversationKind: ctx.conversationKind,
1337
+ parent: parent === undefined
1338
+ ? undefined
1339
+ : {
1340
+ conversationId: parent.conversationId,
1341
+ runId: parent.runId,
1342
+ callId: parent.callId,
1343
+ },
1344
+ },
1345
+ });
1346
+ if (verdict.decision === "ask")
1347
+ return { kind: "ask", unsure: true };
1348
+ decision = { outcome: verdict.decision, reason: verdict.reason, source: "review-model" };
1349
+ }
1350
+ const fileSha256 = callPolicy?.file?.sha256;
1351
+ const event = await this.recordAskDecision(ctx, idemKey, {
1352
+ step: ctx.step,
1353
+ callId: call.id,
1354
+ toolKey: ask.toolKey,
1355
+ specHash: ask.specHash,
1356
+ bindingHash,
1357
+ outcome: decision.outcome,
1358
+ decisionSource: decision.source,
1359
+ reason: decision.reason,
1360
+ profileRevision: resolved.revision,
1361
+ ...(fileSha256 !== undefined && { fileSha256 }),
1362
+ });
1363
+ return askDecisionOf(event);
1364
+ }
1365
+ /** Records an automatic decision once (R2) and announces it after the commit. */
1366
+ async recordAskDecision(ctx, idemKey, payload) {
1367
+ const { event, fresh } = await this.recordAskDecisionIn(ctx, idemKey, payload);
1368
+ if (fresh)
1369
+ await this.deps.eventLog.notify(ctx.conversationId, event.seq);
1370
+ return event;
1371
+ }
1372
+ /**
1373
+ * The `tool_ask_decided` event and, when this call wrote it, its audit row
1374
+ * `tool.ask_auto_decided`, in one transaction: a retry or another replica returns the recorded
1375
+ * event and audits nothing (every automatic decision is audited exactly once).
1376
+ */
1377
+ async recordAskDecisionIn(ctx, idemKey, payload) {
1378
+ const report = await this.deps.eventLog.appendInReport(ctx.conversationId, [
1379
+ { type: "tool_ask_decided", runId: ctx.runId, idemKey, payload },
1380
+ ]);
1381
+ const event = report.events[0];
1382
+ if (event?.type !== "tool_ask_decided")
1383
+ throw new Error("The ask decision was not recorded");
1384
+ const fresh = report.fresh[0] === true;
1385
+ if (fresh) {
1386
+ await audit(this.deps.db, {
1387
+ actorAccountId: ctx.accountId,
1388
+ orgId: ctx.orgId,
1389
+ action: "tool.ask_auto_decided",
1390
+ target: ctx.conversationId,
1391
+ detail: {
1392
+ callId: payload.callId,
1393
+ runId: ctx.runId,
1394
+ toolKey: payload.toolKey,
1395
+ outcome: payload.outcome,
1396
+ decisionSource: payload.decisionSource,
1397
+ profileRevision: payload.profileRevision,
1398
+ reason: payload.reason,
1399
+ },
1400
+ });
1401
+ }
1402
+ return { event, fresh };
1403
+ }
1174
1404
  /**
1175
1405
  * The command review of one call (auto mode spec §5.1, §5.4), after argument validation and the
1176
1406
  * tool policy (and its approval), before the plugin hooks and execution. The device facts come
@@ -1439,7 +1669,12 @@ let ToolPipeline = class ToolPipeline {
1439
1669
  const unverified = buildPermissionCandidate({ toolKey: tool.key, specHash: tool.specHash, rawInput: call.input, validatedInput: input }, facts, [device.home, device.deviceHome], { backgroundMaxSeconds: backgroundMaxSeconds(this.config.get()) });
1440
1670
  if (unverified.kind === "in-scope")
1441
1671
  return null;
1442
- const content = unverified.kind === "proposal" ? PERMISSION_SUPPORT_UNVERIFIED_TEXT : unverified.message;
1672
+ // a device that cannot run scoped work at all says why (R9); one not checked yet says that
1673
+ const content = unverified.kind !== "proposal"
1674
+ ? unverified.message
1675
+ : facts.availability.state === "unsupported"
1676
+ ? admissionUnavailableText(facts.availability.cause ?? { kind: "runtime" })
1677
+ : PERMISSION_SUPPORT_UNVERIFIED_TEXT;
1443
1678
  return { kind: "result", content, review: denyRecord("rule", null, content) };
1444
1679
  }
1445
1680
  if (tool.key === "Bash" && textField(input, "command").length > COMMAND_ASK_MAX_CHARS)
@@ -1922,24 +2157,86 @@ let ToolPipeline = class ToolPipeline {
1922
2157
  return null;
1923
2158
  }
1924
2159
  /**
1925
- * A decided approval other than approved → the model's text; still pending → null (wait). A
1926
- * person field refused on the card as leaked is named, so the agent has the key rotated.
2160
+ * The secure input of a call with person fields (R4): the latest request of the call, bound like
2161
+ * an approval to the definition and the raw input it was made for. None, or a submitted one made
2162
+ * for another definition or input, asks again; a pending one waits. A cancel, an expiry or a
2163
+ * stopped run ends the call with nothing run; a submitted one returns its id, which the tool
2164
+ * reads the sealed values by. The request goes to the run's person, who alone may submit it.
2165
+ */
2166
+ async secureInput(ctx, call, tool, policyKey, personFields) {
2167
+ let si = await this.deps.approvals.secureInputForCall(ctx.runId, call.id);
2168
+ const current = si !== null &&
2169
+ si.specHash === tool.specHash &&
2170
+ canonicalJson(si.input) === canonicalJson(call.input ?? {});
2171
+ // only a submitted request is re-asked when stale: a pending one keeps waiting (the person
2172
+ // still sees and may submit it; the stale check then asks again), and a cancelled or expired
2173
+ // one ends the call, as a decided approval keeps governing its call
2174
+ if (si === null || (si.status === "approved" && !current)) {
2175
+ si = await this.deps.approvals.requestSecureInput({
2176
+ attempt: (await this.lastAttempt(ctx.runId, call.id)) + 1,
2177
+ orgId: ctx.orgId,
2178
+ conversationId: ctx.conversationId,
2179
+ runId: ctx.runId,
2180
+ step: ctx.step,
2181
+ callId: call.id,
2182
+ toolKey: policyKey,
2183
+ specHash: tool.specHash,
2184
+ connectorId: tool.source.kind === "connector" ? tool.source.connectorId : null,
2185
+ input: call.input,
2186
+ requestedFor: ctx.accountId,
2187
+ target: personFields.target,
2188
+ personFields: personFields.fields,
2189
+ });
2190
+ }
2191
+ switch (si.status) {
2192
+ case "pending":
2193
+ return { kind: "wait", wait: approvalWait(si) };
2194
+ case "approved":
2195
+ return { kind: "submitted", id: si.id };
2196
+ case "denied":
2197
+ return {
2198
+ kind: "refused",
2199
+ text: withLeakedOnCard(secureInputCancelledText(si.id), si.leakedFields),
2200
+ };
2201
+ case "expired":
2202
+ // the request's own wait (creation to expiry), not the current config
2203
+ return {
2204
+ kind: "refused",
2205
+ text: withLeakedOnCard(secureInputExpiredText(si.id, approvalHours(si)), si.leakedFields),
2206
+ };
2207
+ default:
2208
+ return {
2209
+ kind: "refused",
2210
+ text: withLeakedOnCard(APPROVAL_CANCELLED_TEXT, si.leakedFields),
2211
+ };
2212
+ }
2213
+ }
2214
+ /** The highest attempt of any approval of the call, of every kind (0: none yet). */
2215
+ async lastAttempt(runId, callId) {
2216
+ const row = await this.deps.db
2217
+ .selectFrom("approvals")
2218
+ .select(sql `max(attempt)`.as("attempt"))
2219
+ .where("run_id", "=", runId)
2220
+ .where("call_id", "=", callId)
2221
+ .executeTakeFirst();
2222
+ return Number(row?.attempt ?? 0);
2223
+ }
2224
+ /**
2225
+ * A decided tool approval other than approved → the model's text; still pending → null (wait).
2226
+ * A tool approval takes no values (a secure input does), so it never names leaked fields.
1927
2227
  */
1928
2228
  refusalText(a) {
1929
- const text = (() => {
1930
- switch (a.status) {
1931
- case "denied":
1932
- return approvalDeniedText(a.denyReason);
1933
- case "expired":
1934
- // Use the approval's own wait (creation to expiry), not the current config: it can be hot-reloaded
1935
- return approvalExpiredText(approvalHours(a));
1936
- case "cancelled":
1937
- return APPROVAL_CANCELLED_TEXT;
1938
- default:
1939
- return null;
1940
- }
1941
- })();
1942
- return text === null ? null : withLeakedOnCard(text, a.leakedFields);
2229
+ switch (a.status) {
2230
+ case "denied":
2231
+ return approvalDeniedText(a.denyReason);
2232
+ case "expired":
2233
+ // Use the approval's own wait (creation to expiry), not the current config: it can be hot-reloaded
2234
+ return approvalExpiredText(approvalHours(a));
2235
+ case "cancelled":
2236
+ return APPROVAL_CANCELLED_TEXT;
2237
+ default:
2238
+ return null;
2239
+ }
1943
2240
  }
1944
2241
  /**
1945
2242
  * A handler returned `input_required`: past the round limit, an invalid form
@@ -1984,7 +2281,11 @@ let ToolPipeline = class ToolPipeline {
1984
2281
  */
1985
2282
  async execute(tool, input, ctx, callId, resume, stepTools, reviewed,
1986
2283
  /** The approved approval of this call, matching its definition and input (builtins only). */
1987
- approvalId) {
2284
+ approvalId,
2285
+ /** The automatic decision the call runs under instead of an approval (builtins only, R2). */
2286
+ decision,
2287
+ /** The submitted secure input request of this call (builtins only, R4). */
2288
+ secureInputId) {
1988
2289
  const reviewedWorkingRoot = reviewed?.workingRoot;
1989
2290
  const reviewedAgainstRoot = reviewed?.against;
1990
2291
  if (tool.source.kind === "connector") {
@@ -2013,6 +2314,8 @@ let ToolPipeline = class ToolPipeline {
2013
2314
  ...(tool.source.kind === "builtin" &&
2014
2315
  ctx.deadline !== undefined && { runDeadline: ctx.deadline }),
2015
2316
  ...(tool.source.kind === "builtin" && approvalId !== undefined && { approvalId }),
2317
+ ...(tool.source.kind === "builtin" && decision !== undefined && { decision }),
2318
+ ...(tool.source.kind === "builtin" && secureInputId !== undefined && { secureInputId }),
2016
2319
  // a reviewed call runs in the working root its review judged (project root spec §4.3)
2017
2320
  ...(tool.source.kind === "builtin" &&
2018
2321
  reviewedWorkingRoot !== undefined && { reviewedWorkingRoot }),
@@ -2440,6 +2743,9 @@ let ToolPipeline = class ToolPipeline {
2440
2743
  __decorate([
2441
2744
  Transactional({ propagation: "mandatory" })
2442
2745
  ], ToolPipeline.prototype, "stopOpenAgentCalls", null);
2746
+ __decorate([
2747
+ Transactional()
2748
+ ], ToolPipeline.prototype, "recordAskDecisionIn", null);
2443
2749
  __decorate([
2444
2750
  Transactional()
2445
2751
  ], ToolPipeline.prototype, "findPermissionGrant", null);
@@ -2489,6 +2795,10 @@ ToolPipeline = __decorate([
2489
2795
  __param(26, Optional()),
2490
2796
  __param(26, Inject(PERMISSION_CONTEXT_ACTIVATION)),
2491
2797
  __param(27, Optional()),
2492
- __param(27, Inject(SandboxService))
2798
+ __param(27, Inject(SandboxService)),
2799
+ __param(28, Optional()),
2800
+ __param(28, Inject(ConversationApprovalProfile)),
2801
+ __param(29, Optional()),
2802
+ __param(29, Inject(ToolAskReview))
2493
2803
  ], ToolPipeline);
2494
2804
  export { ToolPipeline };
@@ -79,9 +79,10 @@ export declare function connectorPolicy(input: {
79
79
  * - in `fail` mode an ask still left is refused (`{ refused, missingGrant }`, no approval), and
80
80
  * `AskUserQuestion` is refused; in `wait` mode both ask the creator as in an attended run.
81
81
  *
82
- * A call with person fields (`CallPolicy.personFields`) or one only the person may confirm
83
- * (`CallPolicy.personOnly`) is a fixed ask: no grant or agent `allow` lets it through (ruling R6).
84
- * The pipeline refuses it before this in an unattended run.
82
+ * A call only the person may confirm (`CallPolicy.personOnly`) is a fixed ask: no grant or agent
83
+ * `allow` lets it through (ruling R6). Person fields (`CallPolicy.personFields`) no longer force
84
+ * the ask (profiles govern every approval, R5): the pipeline asks for their values in a secure
85
+ * input request after the consent. The pipeline refuses both before this in an unattended run.
85
86
  */
86
87
  export declare function createDecidePolicy(db: KernelSchemaDb,
87
88
  /** Logs (debug: once per call) when an org's stored security setting is unreadable. */
@@ -102,9 +102,10 @@ export function connectorPolicy(input) {
102
102
  * - in `fail` mode an ask still left is refused (`{ refused, missingGrant }`, no approval), and
103
103
  * `AskUserQuestion` is refused; in `wait` mode both ask the creator as in an attended run.
104
104
  *
105
- * A call with person fields (`CallPolicy.personFields`) or one only the person may confirm
106
- * (`CallPolicy.personOnly`) is a fixed ask: no grant or agent `allow` lets it through (ruling R6).
107
- * The pipeline refuses it before this in an unattended run.
105
+ * A call only the person may confirm (`CallPolicy.personOnly`) is a fixed ask: no grant or agent
106
+ * `allow` lets it through (ruling R6). Person fields (`CallPolicy.personFields`) no longer force
107
+ * the ask (profiles govern every approval, R5): the pipeline asks for their values in a secure
108
+ * input request after the consent. The pipeline refuses both before this in an unattended run.
108
109
  */
109
110
  export function createDecidePolicy(db,
110
111
  /** Logs (debug: once per call) when an org's stored security setting is unreadable. */
@@ -253,10 +254,9 @@ log) {
253
254
  tool.source.kind === "builtin" &&
254
255
  tool.key === BUILTIN.Platform &&
255
256
  changesAgentSkills(policyKey);
256
- // person fields (platform web parity spec §4.2, R6): the person types values on the card, so
257
- // the call asks every time, outside every grant, and no agent `allow` lifts it
257
+ // a call only the person may confirm (its result is shown to them once, R6) asks every time,
258
+ // outside every grant, and no agent `allow` lifts it
258
259
  const fixedAsk = unattendedSkillChange ||
259
- call?.personFields !== undefined ||
260
260
  call?.personOnly === true ||
261
261
  isFixedAsk(tool) ||
262
262
  (call !== null && !call.remember && (call.policy !== "allow" || agentOverride !== undefined));