@capybara-hq/kernel 0.1.0-rc.62 → 0.1.0-rc.64

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 (120) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/app.d.ts +2 -0
  3. package/dist/catalog/catalog.service.d.ts +13 -0
  4. package/dist/catalog/catalog.service.js +17 -8
  5. package/dist/catalog/git-source.d.ts +8 -0
  6. package/dist/catalog/git-source.js +14 -6
  7. package/dist/catalog/marketplaces.controller.d.ts +3 -2
  8. package/dist/catalog/marketplaces.controller.js +5 -2
  9. package/dist/catalog/marketplaces.schemas.d.ts +7 -0
  10. package/dist/catalog/marketplaces.schemas.js +13 -0
  11. package/dist/catalog/marketplaces.service.d.ts +65 -11
  12. package/dist/catalog/marketplaces.service.js +208 -30
  13. package/dist/catalog/org-catalog.schemas.d.ts +1 -1
  14. package/dist/catalog/org-catalog.schemas.js +1 -1
  15. package/dist/channels/actions.d.ts +2 -5
  16. package/dist/channels/actions.js +20 -8
  17. package/dist/channels/cards.d.ts +4 -3
  18. package/dist/channels/cards.js +6 -4
  19. package/dist/channels/outbound.js +3 -2
  20. package/dist/config/schema.d.ts +2 -0
  21. package/dist/config/schema.js +22 -2
  22. package/dist/conversations/approval-profile.d.ts +30 -0
  23. package/dist/conversations/approval-profile.js +62 -0
  24. package/dist/conversations/conversations.service.js +0 -2
  25. package/dist/conversations/events.d.ts +43 -0
  26. package/dist/conversations/events.js +52 -0
  27. package/dist/conversations/permission-profiles.controller.d.ts +3 -2
  28. package/dist/conversations/permission-profiles.service.d.ts +3 -2
  29. package/dist/conversations/permission-profiles.service.js +12 -8
  30. package/dist/db/kernel-schema.d.ts +8 -2
  31. package/dist/errors.d.ts +7 -0
  32. package/dist/errors.js +7 -0
  33. package/dist/extensions/bootstrap-defaults.d.ts +24 -0
  34. package/dist/extensions/bootstrap-defaults.js +78 -0
  35. package/dist/extensions/bootstrap-extra.d.ts +74 -0
  36. package/dist/extensions/bootstrap-extra.js +131 -0
  37. package/dist/extensions/bootstrap.d.ts +77 -13
  38. package/dist/extensions/bootstrap.js +282 -48
  39. package/dist/identity/initial-passwords.controller.d.ts +8 -6
  40. package/dist/identity/initial-passwords.controller.js +13 -7
  41. package/dist/identity/initial-passwords.d.ts +22 -13
  42. package/dist/identity/initial-passwords.js +25 -29
  43. package/dist/identity/settings.d.ts +10 -0
  44. package/dist/identity/settings.js +46 -0
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.js +3 -0
  47. package/dist/kernel.module.js +3 -0
  48. package/dist/lifecycle/kernel-lifecycle.d.ts +7 -1
  49. package/dist/lifecycle/kernel-lifecycle.js +69 -16
  50. package/dist/local-devices/relay.js +3 -1
  51. package/dist/models/images.js +5 -4
  52. package/dist/platform/connector-person-fields.js +2 -2
  53. package/dist/platform/exclusions.js +4 -4
  54. package/dist/platform/method.js +1 -1
  55. package/dist/platform/operation.d.ts +9 -7
  56. package/dist/platform/operation.js +1 -1
  57. package/dist/platform/ops/accounts.ops.d.ts +1 -1
  58. package/dist/platform/ops/accounts.ops.js +3 -3
  59. package/dist/platform/ops/channels.ops.d.ts +1 -1
  60. package/dist/platform/ops/channels.ops.js +2 -2
  61. package/dist/platform/ops/connectors.ops.d.ts +2 -2
  62. package/dist/platform/ops/connectors.ops.js +8 -8
  63. package/dist/platform/ops/extensions-admin.ops.d.ts +1 -1
  64. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  65. package/dist/platform/ops/extensions.ops.d.ts +1 -1
  66. package/dist/platform/ops/extensions.ops.js +4 -4
  67. package/dist/platform/ops/marketplaces.ops.js +27 -4
  68. package/dist/platform/ops/org-plugins.ops.js +2 -2
  69. package/dist/platform/ops/orgs.ops.d.ts +1 -1
  70. package/dist/platform/ops/orgs.ops.js +3 -3
  71. package/dist/platform/ops/plugins.ops.d.ts +1 -1
  72. package/dist/platform/ops/plugins.ops.js +2 -2
  73. package/dist/platform/person-fields.d.ts +4 -3
  74. package/dist/platform/person-fields.js +6 -5
  75. package/dist/platform/sealed-inputs.d.ts +2 -2
  76. package/dist/platform/sealed-inputs.js +2 -2
  77. package/dist/platform/sealed-reveals.controller.d.ts +5 -8
  78. package/dist/platform/sealed-reveals.controller.js +8 -8
  79. package/dist/platform/sealed-reveals.d.ts +19 -17
  80. package/dist/platform/sealed-reveals.js +30 -33
  81. package/dist/runtime/context/build.js +3 -0
  82. package/dist/runtime/context/compaction.js +2 -0
  83. package/dist/runtime/waits.js +3 -2
  84. package/dist/sandbox/operation-authority.js +16 -15
  85. package/dist/sandbox/operation-intents.js +2 -2
  86. package/dist/sandbox/permission-availability.d.ts +49 -3
  87. package/dist/sandbox/permission-availability.js +61 -6
  88. package/dist/sandbox/permission-call-types.d.ts +3 -0
  89. package/dist/sandbox/permission-facts.d.ts +29 -1
  90. package/dist/sandbox/permission-facts.js +29 -6
  91. package/dist/sandbox/review/classifier.d.ts +72 -2
  92. package/dist/sandbox/review/classifier.js +113 -38
  93. package/dist/sandbox/review/index.d.ts +2 -2
  94. package/dist/sandbox/review/index.js +1 -1
  95. package/dist/sandbox/review/review.service.d.ts +1 -4
  96. package/dist/sandbox/review/review.service.js +4 -33
  97. package/dist/setup/setup-guides.service.js +1 -1
  98. package/dist/tools/approvals.service.d.ts +71 -16
  99. package/dist/tools/approvals.service.js +139 -13
  100. package/dist/tools/builtins/builtin-tools.d.ts +1 -1
  101. package/dist/tools/builtins/builtin-tools.js +12 -6
  102. package/dist/tools/builtins/platform.d.ts +15 -11
  103. package/dist/tools/builtins/platform.js +49 -39
  104. package/dist/tools/builtins/sandbox/bash.d.ts +1 -1
  105. package/dist/tools/builtins/sandbox/bash.js +32 -14
  106. package/dist/tools/builtins/sandbox/common.d.ts +12 -3
  107. package/dist/tools/builtins/sandbox/common.js +29 -5
  108. package/dist/tools/connectors.schemas.d.ts +1 -1
  109. package/dist/tools/connectors.schemas.js +1 -1
  110. package/dist/tools/pipeline.d.ts +70 -10
  111. package/dist/tools/pipeline.js +356 -48
  112. package/dist/tools/policy.d.ts +4 -3
  113. package/dist/tools/policy.js +6 -6
  114. package/dist/tools/registry.d.ts +25 -9
  115. package/dist/tools/tool-review.d.ts +113 -0
  116. package/dist/tools/tool-review.js +303 -0
  117. package/dist/tools/tools.module.js +6 -0
  118. package/package.json +4 -4
  119. package/src/migrations/0174_marketplace_managed_username.sql +4 -0
  120. package/src/migrations/0175_secure_input_kind.sql +8 -0
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  import type { ModelRef } from "../../agents/definition.js";
4
4
  import type { EventLog } from "../../conversations/event-log.js";
5
5
  import type { KernelConfigService } from "../../infra/config/kernel-config.service.js";
6
+ import type { KernelDb } from "../../infra/database/kernel-db.js";
6
7
  import { type ModelPurposesService } from "../../models/purposes.js";
7
8
  import type { ConversationKindForHooks, HookRunner } from "../../runtime/hook-calls.js";
8
9
  import type { StepLog } from "../../runtime/step-log.js";
@@ -103,6 +104,32 @@ export declare function fitReviewInput(input: ReviewClassifierInput, system: str
103
104
  contextWindow: number;
104
105
  maxOutputTokens: number;
105
106
  }): ReviewClassifierInput;
107
+ /**
108
+ * Fits one review message to the review model's context: `build` renders the message from its one
109
+ * unbounded part (`text`) and the person's messages; everything else in it is always kept. When
110
+ * the whole does not fit, `text` keeps its beginning and ends with `marker`; the person's messages
111
+ * are cut (newest end kept) only if they alone overflow the model. Shared by the command review
112
+ * and the tool review.
113
+ */
114
+ export declare function fitReviewText(build: (text: string, personMessages: string) => string, parts: {
115
+ text: string;
116
+ personMessages: string;
117
+ }, system: string, limits: {
118
+ contextWindow: number;
119
+ maxOutputTokens: number;
120
+ }, marker: string): {
121
+ text: string;
122
+ personMessages: string;
123
+ };
124
+ /** How many of the root conversation's latest person messages are read before bounding the text. */
125
+ export declare const PERSON_MESSAGES_READ = 20;
126
+ /**
127
+ * The bounded text of the root conversation's last person messages: the `user_message` text blocks
128
+ * only, never an assistant message or a tool result, newest {@link PERSON_MESSAGES_READ} read and
129
+ * bounded to `budget` estimated tokens (`sandbox.review.messageTokens`). The command review and the
130
+ * tool review read the same messages.
131
+ */
132
+ export declare function readPersonMessages(db: KernelDb["db"], rootConversationId: string, budget: number): Promise<string>;
106
133
  /** The identity facts the hook payloads need (all of them: without one, no hooks fire). */
107
134
  export interface ReviewHookFacts {
108
135
  accountId: string;
@@ -120,7 +147,8 @@ export interface ReviewClassifierDeps {
120
147
  /** Extension hooks (absent: none fire). */
121
148
  hooks?: HookRunner | undefined;
122
149
  }
123
- export interface RunClassifierArgs {
150
+ /** Who, where and how one review model call runs (the command review's and the tool review's). */
151
+ export interface ReviewModelCallArgs {
124
152
  orgId: string;
125
153
  /** The root conversation: where the person's messages are read and the usage event is written. */
126
154
  conversationId: string;
@@ -133,13 +161,55 @@ export interface RunClassifierArgs {
133
161
  /** The budget window of the run tree (agent map spec §6), when known. */
134
162
  budgetRunId?: string | undefined;
135
163
  hookFacts: ReviewHookFacts;
136
- input: ReviewClassifierInput;
137
164
  /** Called with the resolved target and final request just before it is sent (a test seam). */
138
165
  beforeSend?: ((target: ModelRef, request: ModelRequest) => Promise<void>) | undefined;
139
166
  }
167
+ export interface RunClassifierArgs extends ReviewModelCallArgs {
168
+ input: ReviewClassifierInput;
169
+ }
170
+ /** The texts of the outcomes one review subject (command, tool) reports when it cannot decide. */
171
+ export interface ReviewOutcomeTexts {
172
+ /** Names the review in log lines. */
173
+ label: string;
174
+ /** The reason of an ask after a timeout, an error or an unparseable answer. */
175
+ ask: string;
176
+ /** The reason of an allow turned into an ask because the model read a cut input. */
177
+ truncatedAsk: string;
178
+ /** Prefixes a `model.request` policy hook's reason. */
179
+ unavailablePrefix: string;
180
+ }
181
+ /** One prepared review model call: its prompt and message, already fitted to the model. */
182
+ export interface ReviewModelCall {
183
+ system: string;
184
+ message: string;
185
+ /** The message carries a cut input: an `allow` cannot cover what the model never read. */
186
+ truncated: boolean;
187
+ /** The idempotency key of the call's `usage` event. */
188
+ usageIdemKey: string;
189
+ /** The idempotency key of a `hook_denied` event (default `hook_denied_review:<run>:<call>`). */
190
+ hookDeniedIdemKey?: string | undefined;
191
+ /** The outcome texts (default the command review's). */
192
+ outcomes?: ReviewOutcomeTexts | undefined;
193
+ }
140
194
  /**
141
195
  * Runs the classifier call (see the module comment). Never throws: every failure is `ask`, and
142
196
  * `ask` is also what an answer other than an explicit `allow` / `deny` becomes.
143
197
  */
144
198
  export declare function runClassifier(deps: ReviewClassifierDeps, args: RunClassifierArgs): Promise<ClassifierAnswer>;
199
+ /**
200
+ * The limits of the model the `review` purpose resolves to in the org, or null when it has no
201
+ * usable model (logged; the caller asks without sending anything).
202
+ */
203
+ export declare function reviewModelLimits(deps: Pick<ReviewClassifierDeps, "purposes" | "log">, args: Pick<ReviewModelCallArgs, "orgId" | "conversationId" | "callId">, label: string): Promise<{
204
+ contextWindow: number;
205
+ maxOutputTokens: number;
206
+ } | null>;
207
+ /**
208
+ * Sends one prepared review call on the `review` purpose: the `model.request` policy hook, the
209
+ * call bounded by `sandbox.review.timeoutMs` and the run's signal, `model.response`, the `usage`
210
+ * event (a sent call that failed billed at its estimate), and the strict parse of the answer.
211
+ * Never throws: a hook denial, a timeout, an error or an unparseable answer is `ask`, and so is an
212
+ * `allow` on a truncated message.
213
+ */
214
+ export declare function callReviewModel(deps: ReviewClassifierDeps, args: ReviewModelCallArgs, call: ReviewModelCall): Promise<ClassifierAnswer>;
145
215
  export {};
@@ -224,31 +224,75 @@ const headroomTokens = (contextWindow) => Math.max(1024, Math.ceil(contextWindow
224
224
  * bounded by `sandbox.review.messageTokens`; they are cut only if that alone overflows the model.
225
225
  */
226
226
  export function fitReviewInput(input, system, limits) {
227
- const estimate = (text, personMessages) => estimateTokens([
228
- {
229
- role: "user",
230
- content: [{ type: "text", text: classifierMessage({ ...input, text, personMessages }) }],
231
- },
232
- ], [{ text: system, cache: false }], []);
227
+ const fitted = fitReviewText((text, personMessages) => classifierMessage({ ...input, text, personMessages }), { text: input.text, personMessages: input.personMessages }, system, limits, REVIEW_TRUNCATED_MARKER);
228
+ if (fitted.text === input.text && fitted.personMessages === input.personMessages)
229
+ return input;
230
+ return { ...input, ...fitted };
231
+ }
232
+ /**
233
+ * Fits one review message to the review model's context: `build` renders the message from its one
234
+ * unbounded part (`text`) and the person's messages; everything else in it is always kept. When
235
+ * the whole does not fit, `text` keeps its beginning and ends with `marker`; the person's messages
236
+ * are cut (newest end kept) only if they alone overflow the model. Shared by the command review
237
+ * and the tool review.
238
+ */
239
+ export function fitReviewText(build, parts, system, limits, marker) {
240
+ const estimate = (text, personMessages) => estimateTokens([{ role: "user", content: [{ type: "text", text: build(text, personMessages) }] }], [{ text: system, cache: false }], []);
233
241
  const budget = limits.contextWindow -
234
242
  Math.min(REVIEW_MAX_OUTPUT_TOKENS, limits.maxOutputTokens) -
235
243
  headroomTokens(limits.contextWindow);
236
- if (estimate(input.text, input.personMessages) <= budget)
237
- return input;
238
- // the fixed part of the message and the person's messages; the command gets the rest
239
- let personMessages = input.personMessages;
244
+ if (estimate(parts.text, parts.personMessages) <= budget)
245
+ return parts;
246
+ // the fixed part of the message and the person's messages; the unbounded text gets the rest
247
+ let personMessages = parts.personMessages;
240
248
  let available = budget - estimate("", personMessages);
241
249
  if (available < 0) {
242
250
  // a misconfigured message budget alone overflows the model: keep the newest end, half the room
243
251
  const fixed = estimate("", "");
244
- personMessages = tailToTokens(input.personMessages, Math.max(0, Math.floor((budget - fixed) / 2)));
252
+ personMessages = tailToTokens(parts.personMessages, Math.max(0, Math.floor((budget - fixed) / 2)));
245
253
  available = budget - estimate("", personMessages);
246
254
  }
247
- const commandRoom = Math.max(0, available - cost(REVIEW_TRUNCATED_MARKER));
248
- const text = cost(input.text) > commandRoom
249
- ? `${headToTokens(input.text, commandRoom)}${REVIEW_TRUNCATED_MARKER}`
250
- : input.text;
251
- return { ...input, text, personMessages };
255
+ const room = Math.max(0, available - cost(marker));
256
+ const text = cost(parts.text) > room ? `${headToTokens(parts.text, room)}${marker}` : parts.text;
257
+ return { text, personMessages };
258
+ }
259
+ /* ---------------------------------------------------------------------------------------------- *
260
+ * Reading the person's messages
261
+ * ---------------------------------------------------------------------------------------------- */
262
+ /** How many of the root conversation's latest person messages are read before bounding the text. */
263
+ export const PERSON_MESSAGES_READ = 20;
264
+ /** The text blocks of a `user_message` payload (its images, documents and attachments are skipped). */
265
+ function textOfUserMessage(payload) {
266
+ const content = payload?.content;
267
+ if (!Array.isArray(content))
268
+ return "";
269
+ return content
270
+ .flatMap((b) => {
271
+ if (b === null || typeof b !== "object")
272
+ return [];
273
+ const block = b;
274
+ return block.type === "text" && typeof block.text === "string" ? [block.text] : [];
275
+ })
276
+ .join("\n")
277
+ .trim();
278
+ }
279
+ /**
280
+ * The bounded text of the root conversation's last person messages: the `user_message` text blocks
281
+ * only, never an assistant message or a tool result, newest {@link PERSON_MESSAGES_READ} read and
282
+ * bounded to `budget` estimated tokens (`sandbox.review.messageTokens`). The command review and the
283
+ * tool review read the same messages.
284
+ */
285
+ export async function readPersonMessages(db, rootConversationId, budget) {
286
+ const rows = await db
287
+ .selectFrom("conversation_events")
288
+ .select("payload")
289
+ .where("conversation_id", "=", rootConversationId)
290
+ .where("type", "=", "user_message")
291
+ .orderBy("seq", "desc")
292
+ .limit(PERSON_MESSAGES_READ)
293
+ .execute();
294
+ const texts = rows.map((r) => textOfUserMessage(r.payload)).filter((t) => t !== "");
295
+ return boundMessages(texts, budget);
252
296
  }
253
297
  /* ---------------------------------------------------------------------------------------------- *
254
298
  * The call
@@ -261,6 +305,13 @@ class ReviewDenied extends Error {
261
305
  this.reason = reason;
262
306
  }
263
307
  }
308
+ /** The command review's outcome texts. */
309
+ const COMMAND_REVIEW_OUTCOMES = {
310
+ label: "command review classifier",
311
+ ask: REVIEW_ASK_REASON,
312
+ truncatedAsk: REVIEW_TRUNCATED_ASK_REASON,
313
+ unavailablePrefix: REVIEW_UNAVAILABLE_PREFIX,
314
+ };
264
315
  const textOf = (content) => content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
265
316
  const errorCodeOf = (err) => {
266
317
  const cause = err instanceof PurposeAttemptError ? err.cause : err;
@@ -271,23 +322,47 @@ const errorCodeOf = (err) => {
271
322
  * `ask` is also what an answer other than an explicit `allow` / `deny` becomes.
272
323
  */
273
324
  export async function runClassifier(deps, args) {
274
- const { input } = args;
325
+ const { input, ...callArgs } = args;
275
326
  const system = reviewSystemPrompt(input.tag);
276
327
  // fit the command and messages to the model the call will use (as `chat` resolves it)
277
- let limits;
328
+ const limits = await reviewModelLimits(deps, args, COMMAND_REVIEW_OUTCOMES.label);
329
+ if (limits === null)
330
+ return { decision: "ask", reason: REVIEW_ASK_REASON };
331
+ const fitted = fitReviewInput(input, system, limits);
332
+ return callReviewModel(deps, callArgs, {
333
+ system,
334
+ message: classifierMessage(fitted),
335
+ truncated: fitted.text !== input.text,
336
+ usageIdemKey: `usage_review:${args.runId}:${args.callId}`,
337
+ });
338
+ }
339
+ /**
340
+ * The limits of the model the `review` purpose resolves to in the org, or null when it has no
341
+ * usable model (logged; the caller asks without sending anything).
342
+ */
343
+ export async function reviewModelLimits(deps, args, label) {
278
344
  try {
279
- limits = await deps.purposes.chatLimits(args.orgId, REVIEW_PURPOSE);
345
+ return await deps.purposes.chatLimits(args.orgId, REVIEW_PURPOSE);
280
346
  }
281
347
  catch (err) {
282
348
  // no usable purpose model: fail closed without sending anything
283
- deps.log.warn("command review classifier has no usable model", {
349
+ deps.log.warn(`${label} has no usable model`, {
284
350
  conversationId: args.conversationId,
285
351
  callId: args.callId,
286
352
  err,
287
353
  });
288
- return { decision: "ask", reason: REVIEW_ASK_REASON };
354
+ return null;
289
355
  }
290
- const fitted = fitReviewInput(input, system, limits);
356
+ }
357
+ /**
358
+ * Sends one prepared review call on the `review` purpose: the `model.request` policy hook, the
359
+ * call bounded by `sandbox.review.timeoutMs` and the run's signal, `model.response`, the `usage`
360
+ * event (a sent call that failed billed at its estimate), and the strict parse of the answer.
361
+ * Never throws: a hook denial, a timeout, an error or an unparseable answer is `ask`, and so is an
362
+ * `allow` on a truncated message.
363
+ */
364
+ export async function callReviewModel(deps, args, call) {
365
+ const outcomes = call.outcomes ?? COMMAND_REVIEW_OUTCOMES;
291
366
  const scope = hookScope(deps.hooks, {
292
367
  ...(args.hookFacts.conversationKind !== undefined && {
293
368
  conversationKind: args.hookFacts.conversationKind,
@@ -317,8 +392,8 @@ export async function runClassifier(deps, args) {
317
392
  let out;
318
393
  try {
319
394
  out = await deps.purposes.chat(args.orgId, REVIEW_PURPOSE, {
320
- system: [{ text: system, cache: false }],
321
- messages: [{ role: "user", content: [{ type: "text", text: classifierMessage(fitted) }] }],
395
+ system: [{ text: call.system, cache: false }],
396
+ messages: [{ role: "user", content: [{ type: "text", text: call.message }] }],
322
397
  tools: [],
323
398
  toolChoice: "none",
324
399
  maxOutputTokens: REVIEW_MAX_OUTPUT_TOKENS,
@@ -328,7 +403,7 @@ export async function runClassifier(deps, args) {
328
403
  if (base && deps.hooks?.has("model.request")) {
329
404
  const verdict = await deps.hooks.run("model.request", { ...base, request: hookRequestOf(request, deps.log) }, signal);
330
405
  if (!verdict.allowed) {
331
- await recordDenial(deps, args, verdict);
406
+ await recordDenial(deps, args, call, outcomes, verdict);
332
407
  throw new ReviewDenied(verdict.reason);
333
408
  }
334
409
  }
@@ -339,14 +414,14 @@ export async function runClassifier(deps, args) {
339
414
  }
340
415
  catch (err) {
341
416
  observe(deps, hookBase, sent, null, err, args.signal);
342
- deps.log.warn("command review classifier call failed", {
417
+ deps.log.warn(`${outcomes.label} call failed`, {
343
418
  conversationId: args.conversationId,
344
419
  callId: args.callId,
345
420
  err,
346
421
  });
347
422
  // a sent call is billed: its estimated usage is logged like a successful one's
348
423
  if (err instanceof PurposeAttemptError) {
349
- await logUsage(deps, args, {
424
+ await logUsage(deps, args, call.usageIdemKey, {
350
425
  provider: err.provider,
351
426
  model: err.model,
352
427
  usage: {
@@ -357,19 +432,19 @@ export async function runClassifier(deps, args) {
357
432
  },
358
433
  });
359
434
  }
360
- const reason = err instanceof ReviewDenied ? `${REVIEW_UNAVAILABLE_PREFIX}${err.reason}` : REVIEW_ASK_REASON;
435
+ const reason = err instanceof ReviewDenied ? `${outcomes.unavailablePrefix}${err.reason}` : outcomes.ask;
361
436
  return { decision: "ask", reason };
362
437
  }
363
438
  observe(deps, hookBase, sent, out, null, args.signal);
364
- await logUsage(deps, args, out);
439
+ await logUsage(deps, args, call.usageIdemKey, out);
365
440
  const answer = parseReviewAnswer(textOf(out.content)) ?? {
366
441
  decision: "ask",
367
- reason: REVIEW_ASK_REASON,
442
+ reason: outcomes.ask,
368
443
  };
369
- // the model saw only the beginning of the command: its allow cannot cover the part it never read
444
+ // the model saw only the beginning of the input: its allow cannot cover the part it never read
370
445
  // (hardening spec R8); its deny or ask stands
371
- if (answer.decision === "allow" && fitted.text !== input.text) {
372
- return { decision: "ask", reason: REVIEW_TRUNCATED_ASK_REASON };
446
+ if (answer.decision === "allow" && call.truncated) {
447
+ return { decision: "ask", reason: outcomes.truncatedAsk };
373
448
  }
374
449
  return answer;
375
450
  }
@@ -379,11 +454,11 @@ export async function runClassifier(deps, args) {
379
454
  * counts on its parent run's `subagent_tokens_used`, in the same transaction
380
455
  * ({@link appendCounted}, as the `WebFetch` extraction does).
381
456
  */
382
- async function logUsage(deps, args, u) {
457
+ async function logUsage(deps, args, idemKey, u) {
383
458
  const event = {
384
459
  type: "usage",
385
460
  ...(args.runId !== "" && { runId: args.runId }),
386
- idemKey: `usage_review:${args.runId}:${args.callId}`,
461
+ idemKey,
387
462
  payload: {
388
463
  step: args.step,
389
464
  provider: u.provider,
@@ -406,14 +481,14 @@ async function logUsage(deps, args, u) {
406
481
  * Records a `model.request` denial of the classifier call: the `hook_denied` event (the call's step
407
482
  * and `callId`) with its `hook.denied` audit row (`detail.purpose: "review"`), in one transaction.
408
483
  */
409
- async function recordDenial(deps, args, verdict) {
484
+ async function recordDenial(deps, args, call, outcomes, verdict) {
410
485
  const site = {
411
486
  orgId: args.orgId,
412
487
  conversationId: args.conversationId,
413
488
  runId: args.runId,
414
489
  accountId: args.hookFacts.accountId,
415
490
  ...(args.hookFacts.agentId !== undefined && { agentId: args.hookFacts.agentId }),
416
- idemKey: `hook_denied_review:${args.runId}:${args.callId}`,
491
+ idemKey: call.hookDeniedIdemKey ?? `hook_denied_review:${args.runId}:${args.callId}`,
417
492
  };
418
493
  const event = hookDeniedEvent(site, "model.request", verdict, {
419
494
  step: args.step,
@@ -422,7 +497,7 @@ async function recordDenial(deps, args, verdict) {
422
497
  });
423
498
  const entry = hookDeniedAudit(site, event.payload, verdict);
424
499
  entry.detail = { ...entry.detail, purpose: REVIEW_PURPOSE };
425
- deps.log.warn("command review blocked by a policy hook", {
500
+ deps.log.warn(`${outcomes.label} blocked by a policy hook`, {
426
501
  conversationId: args.conversationId,
427
502
  callId: args.callId,
428
503
  plugin: verdict.plugin,
@@ -4,8 +4,8 @@
4
4
  * auto mode (and for the file writes outside the workspace). Only the service touches the database,
5
5
  * a model or a lock; the parser and the table are pure.
6
6
  */
7
- export type { ClassifierAnswer, ReviewClassifierDeps, ReviewClassifierInput, ReviewHookFacts, RunClassifierArgs, } from "./classifier.js";
8
- export { boundMessages, classifierMessage, fitReviewInput, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, reviewSystemPrompt, runClassifier, } from "./classifier.js";
7
+ export type { ClassifierAnswer, ReviewClassifierDeps, ReviewClassifierInput, ReviewHookFacts, ReviewModelCall, ReviewModelCallArgs, ReviewOutcomeTexts, RunClassifierArgs, } from "./classifier.js";
8
+ export { boundMessages, callReviewModel, classifierMessage, fitReviewInput, fitReviewText, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, readPersonMessages, reviewModelLimits, reviewSystemPrompt, runClassifier, } from "./classifier.js";
9
9
  export type { CommandReview, ReviewCall, ReviewInput, ReviewVerdict } from "./review.service.js";
10
10
  export { CommandReviewService, REVIEW_REASONS, } from "./review.service.js";
11
11
  export { parseCommand, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
@@ -4,7 +4,7 @@
4
4
  * auto mode (and for the file writes outside the workspace). Only the service touches the database,
5
5
  * a model or a lock; the parser and the table are pure.
6
6
  */
7
- export { boundMessages, classifierMessage, fitReviewInput, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, reviewSystemPrompt, runClassifier, } from "./classifier.js";
7
+ export { boundMessages, callReviewModel, classifierMessage, fitReviewInput, fitReviewText, newReviewTag, parseReviewAnswer, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, readPersonMessages, reviewModelLimits, reviewSystemPrompt, runClassifier, } from "./classifier.js";
8
8
  export { CommandReviewService, REVIEW_REASONS, } from "./review.service.js";
9
9
  export { parseCommand, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
10
10
  export { applySessionGrants, isSessionGrantableRule } from "./types.js";
@@ -174,9 +174,6 @@ export declare class CommandReviewService implements CommandReview {
174
174
  * whoever runs it (hardening spec R1).
175
175
  */
176
176
  private writtenInTree;
177
- /**
178
- * The bounded text of the root conversation's last person messages: the `user_message` text blocks
179
- * only, never an assistant message or a tool result. `sandbox.review.messageTokens` caps it.
180
- */
177
+ /** The bounded text of the root conversation's last person messages ({@link readPersonMessages}). */
181
178
  private personMessages;
182
179
  }
@@ -16,7 +16,7 @@ import { KERNEL_LOGGER } from "../../infra/tokens.js";
16
16
  import { ModelPurposesService } from "../../models/purposes.js";
17
17
  import { StepLog } from "../../runtime/step-log.js";
18
18
  import { generateImagePaths } from "../../tools/builtins/image/paths.js";
19
- import { boundMessages, newReviewTag, REVIEW_ASK_REASON, REVIEW_PURPOSE, runClassifier, } from "./classifier.js";
19
+ import { newReviewTag, REVIEW_ASK_REASON, REVIEW_PURPOSE, readPersonMessages, runClassifier, } from "./classifier.js";
20
20
  import { approverForCrossing, crossingOfCandidate, ESCALATION_RETRY_HINT, escalationAskReason, isCredentialConsentRule, } from "./permission-candidate.js";
21
21
  export { escalationAskReason, quotedJustification } from "./permission-candidate.js";
22
22
  import { reviewRules, reviewWrite, writtenPaths } from "./rules.js";
@@ -56,8 +56,6 @@ const REVIEWED_TOOLS = new Set(["Bash", "Write", "Edit", "GenerateImage"]);
56
56
  const WRITE_TOOLS = new Set(["Write", "Edit", "GenerateImage"]);
57
57
  /** How many of a conversation tree's latest assistant messages the review reads for its writes. */
58
58
  const WRITTEN_EVENTS_READ = 200;
59
- /** How many of the root conversation's latest person messages are read before bounding the text. */
60
- const PERSON_MESSAGES_READ = 20;
61
59
  const allow = (reason, rule) => ({
62
60
  decision: "allow",
63
61
  by: "rule",
@@ -524,21 +522,9 @@ let CommandReviewService = class CommandReviewService {
524
522
  }
525
523
  return [...written];
526
524
  }
527
- /**
528
- * The bounded text of the root conversation's last person messages: the `user_message` text blocks
529
- * only, never an assistant message or a tool result. `sandbox.review.messageTokens` caps it.
530
- */
531
- async personMessages(conversationId) {
532
- const rows = await this.db
533
- .selectFrom("conversation_events")
534
- .select("payload")
535
- .where("conversation_id", "=", conversationId)
536
- .where("type", "=", "user_message")
537
- .orderBy("seq", "desc")
538
- .limit(PERSON_MESSAGES_READ)
539
- .execute();
540
- const texts = rows.map((r) => textOfUserMessage(r.payload)).filter((t) => t !== "");
541
- return boundMessages(texts, this.config.get().sandbox.review.messageTokens);
525
+ /** The bounded text of the root conversation's last person messages ({@link readPersonMessages}). */
526
+ personMessages(conversationId) {
527
+ return readPersonMessages(this.db, conversationId, this.config.get().sandbox.review.messageTokens);
542
528
  }
543
529
  };
544
530
  CommandReviewService = __decorate([
@@ -567,21 +553,6 @@ function toolCallsOf(payload) {
567
553
  return [{ name: block.name, input: block.input, command: input.command }];
568
554
  });
569
555
  }
570
- /** The text blocks of a `user_message` payload (its images, documents and attachments are skipped). */
571
- function textOfUserMessage(payload) {
572
- const content = payload?.content;
573
- if (!Array.isArray(content))
574
- return "";
575
- return content
576
- .flatMap((b) => {
577
- if (b === null || typeof b !== "object")
578
- return [];
579
- const block = b;
580
- return block.type === "text" && typeof block.text === "string" ? [block.text] : [];
581
- })
582
- .join("\n")
583
- .trim();
584
- }
585
556
  /** The command of a validated `Bash` input, or null when it has none (the tool will refuse it). */
586
557
  function commandOf(input) {
587
558
  const command = input?.command;
@@ -279,7 +279,7 @@ let SetupGuidesService = class SetupGuidesService {
279
279
  target: g.target,
280
280
  hash: g.hash,
281
281
  webPath,
282
- handover: `Secrets (tokens, signing secrets, client secrets) are typed by the person into their fields on ${webPath}; never ask for one in the conversation. A secret field a write takes as a person field is typed on the Platform confirmation card instead. Connecting a personal account is connectors.connect (a Connect button for the person); confirming the app was updated is the person's statement on the card of channels.guide-ack or connectors.guide-ack.`,
282
+ handover: `Secrets (tokens, signing secrets, client secrets) are typed by the person into their fields on ${webPath}; never ask for one in the conversation. A secret field a write takes as a person field is typed in the Platform tool's secure input request instead. Connecting a personal account is connectors.connect (a Connect button for the person); confirming the app was updated is the person's statement on the card of channels.guide-ack or connectors.guide-ack.`,
283
283
  };
284
284
  }
285
285
  };
@@ -27,9 +27,10 @@ export type ApprovalStatus = "pending" | "approved" | "denied" | "expired" | "ca
27
27
  export type ApprovalScope = "once" | "session" | "always";
28
28
  /**
29
29
  * What an approval asks: a tool call, the device owner about refused network hosts, the actor about
30
- * a git push the gateway held, or a person about a command the review held (auto mode spec §5.4).
30
+ * a git push the gateway held, a person about a command the review held (auto mode spec §5.4), or
31
+ * the person for a call's secret fields (`secure_input`; profiles govern every approval, R4).
31
32
  */
32
- export type ApprovalKind = "tool" | "network" | "git" | "command";
33
+ export type ApprovalKind = "tool" | "network" | "git" | "command" | "secure_input";
33
34
  /**
34
35
  * The formatted `tool_result` of a command an ask kept (≤ 16 KB; larger output already archived),
35
36
  * and the display-only fields the pipeline writes with it when the ask settles.
@@ -156,8 +157,9 @@ export interface ApprovalRecord {
156
157
  /** A command review ask's facts; null for any other kind. */
157
158
  command: CommandAskDetail | null;
158
159
  /**
159
- * A tool ask with person fields (platform web parity spec §4.2): the secret fields the person
160
- * enters on the card, as specs (path, label, schema node), never values. Absent otherwise.
160
+ * A secure input request (kind `secure_input`; platform web parity spec §4.2, profiles govern
161
+ * every approval R4): the secret fields the person enters, as specs (path, label, schema node),
162
+ * never values. Absent otherwise.
161
163
  */
162
164
  personFields?: PersonFieldSpec[];
163
165
  /** The card's target name with {@link personFields} ("Anthropic: deployment config"). */
@@ -175,6 +177,11 @@ export interface ApprovalRecord {
175
177
  * then ends without running tells the agent to have them rotated.
176
178
  */
177
179
  leakedFields?: string[];
180
+ /**
181
+ * A tool ask the review model could not decide under Approve for me (profiles govern every
182
+ * approval, R3): the card says it is the person's call. Absent otherwise.
183
+ */
184
+ reviewUnsure?: true;
178
185
  toolKey: string;
179
186
  specHash: string;
180
187
  connectorId: string | null;
@@ -226,7 +233,10 @@ export interface CommandAskInput {
226
233
  /** The call's attempt (default: after its other approvals, as a network ask takes it). */
227
234
  attempt?: number;
228
235
  }
229
- /** The record without an ask's kept command result (what routes and cards may show). */
236
+ /**
237
+ * The record without an ask's kept command result (what routes and cards may show). A secure
238
+ * input request shows its fields and target, never the call's input it binds.
239
+ */
230
240
  export declare function publicRecord(r: ApprovalRecord): ApprovalPublicRecord;
231
241
  /** 审批详情(列表与详情接口返回)。 */
232
242
  export interface ApprovalView extends ApprovalPublicRecord {
@@ -285,14 +295,47 @@ export interface ApprovalRequestInput {
285
295
  };
286
296
  /** The scopes the decider may choose; unset: derived (see {@link ApprovalRecord.scopes}). */
287
297
  scopes?: ApprovalScope[];
288
- /**
289
- * A tool ask's person fields and their target (specs only, no values) and the file it takes
290
- * (stored in `detail`).
291
- */
292
- detail?: Omit<ToolAskDetail, "personFields" | "target"> & Partial<Pick<ToolAskDetail, "personFields" | "target">>;
298
+ /** The file a tool ask's call takes and the review's unsure mark (stored in `detail`). */
299
+ detail?: ToolAskDetail;
293
300
  }
294
- /** A tool ask's `detail`: the person fields the card asks for and the target they belong to. */
301
+ /**
302
+ * A secure input request (profiles govern every approval, R4), made by the tool pipeline once the
303
+ * call's own consent is settled: the person enters the call's secret fields on the web.
304
+ */
305
+ export interface SecureInputRequestInput {
306
+ /** The call's attempt (after its other approvals). */
307
+ attempt: number;
308
+ orgId: string;
309
+ conversationId: string;
310
+ runId: string;
311
+ /** The call's step (written to `approval_requested`). */
312
+ step: number;
313
+ callId: string;
314
+ /** The call's policy key. */
315
+ toolKey: string;
316
+ specHash: string;
317
+ connectorId: string | null;
318
+ /** The raw call input, stored for binding only (never shown). */
319
+ input: unknown;
320
+ /** The run's person: the only one who may submit or cancel. */
321
+ requestedFor: string;
322
+ /** What the values are for ("Anthropic: deployment config"). */
323
+ target: {
324
+ zh: string;
325
+ en: string;
326
+ };
327
+ /** The secret fields to enter (1 to {@link SECURE_INPUT_MAX_FIELDS}), specs only. */
328
+ personFields: PersonFieldSpec[];
329
+ }
330
+ /** A tool ask's `detail`: the file its call takes and whether the review was unsure. */
295
331
  export interface ToolAskDetail {
332
+ /** The file the call takes in place of an upload (its sha256 is what the approval binds). */
333
+ file?: FileCardDetail;
334
+ /** The review model could not decide the ask under Approve for me (R3). */
335
+ reviewUnsure?: true;
336
+ }
337
+ /** A secure input request's `detail`: the fields the person enters and their target. */
338
+ export interface SecureInputDetail {
296
339
  personFields: PersonFieldSpec[];
297
340
  target: {
298
341
  zh: string;
@@ -300,8 +343,6 @@ export interface ToolAskDetail {
300
343
  };
301
344
  /** The paths whose entered value the decision refused as leaked (written by the decision). */
302
345
  leakedFields?: string[];
303
- /** The file the call takes in place of an upload (its sha256 is what the approval binds). */
304
- file?: FileCardDetail;
305
346
  }
306
347
  export interface DecisionInput {
307
348
  decision: "approve" | "deny";
@@ -426,6 +467,17 @@ export declare class ApprovalsService {
426
467
  */
427
468
  request(input: ApprovalRequestInput): Promise<ApprovalRecord>;
428
469
  private requestIn;
470
+ /**
471
+ * A secure input request (profiles govern every approval, R4): a pending approval of kind
472
+ * `secure_input` asking `requestedFor` for the call's secret fields, expiring like a tool
473
+ * approval, and its `approval_requested` (the display-only `secureInput`: the target and the
474
+ * field paths), in one transaction. It carries no consent: scopes `["once"]`, and Submit is a
475
+ * decision `approve` with the values, Cancel a `deny`. The raw call input is stored for binding
476
+ * only and shown nowhere. Idempotent per (run, call, attempt); an attempt already held by
477
+ * another kind is refused.
478
+ */
479
+ requestSecureInput(input: SecureInputRequestInput): Promise<ApprovalRecord>;
480
+ private requestSecureInputIn;
429
481
  /**
430
482
  * A network ask (network ask-to-allow spec §6.2): a pending approval of kind `network` for the
431
483
  * device owner, expiring like a tool approval (`tools.approvalTimeoutHours`), and its
@@ -500,9 +552,10 @@ export declare class ApprovalsService {
500
552
  private displayNameOf;
501
553
  private decideIn;
502
554
  /**
503
- * A tool ask's decision in its own transaction. With person fields, a leak refusal commits the
504
- * leaked paths in `detail.leakedFields` and returns them (the caller refuses after the commit,
505
- * the approval still pending); the same transaction cannot both keep that write and throw.
555
+ * A tool ask's or a secure input's decision in its own transaction. For a secure input, a leak
556
+ * refusal commits the leaked paths in `detail.leakedFields` and returns them (the caller refuses
557
+ * after the commit, the request still pending); the same transaction cannot both keep that write
558
+ * and throw.
506
559
  */
507
560
  private decideToolIn;
508
561
  /**
@@ -549,6 +602,8 @@ export declare class ApprovalsService {
549
602
  describe(id: string): Promise<ApprovalView | null>;
550
603
  /** 某个工具调用最近一次的工具审批(attempt 最大者,网络询问除外);没有则返回 null。 */
551
604
  forCall(runId: string, callId: string): Promise<ApprovalRecord | null>;
605
+ /** The latest secure input request of a tool call (highest attempt); null when it has none. */
606
+ secureInputForCall(runId: string, callId: string): Promise<ApprovalRecord | null>;
552
607
  /** The network ask of a tool call (at most one per call); null when it has none. */
553
608
  networkForCall(runId: string, callId: string): Promise<ApprovalRecord | null>;
554
609
  /** The git push ask of a tool call (at most one per call); null when it has none. */