@capybara-hq/kernel 0.1.0-rc.57 → 0.1.0-rc.58

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 (72) hide show
  1. package/dist/admin/extensions.controller.d.ts +2 -10
  2. package/dist/admin/extensions.controller.js +2 -24
  3. package/dist/admin/extensions.schemas.d.ts +21 -0
  4. package/dist/admin/extensions.schemas.js +37 -0
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/catalog/org-extension-switch.d.ts +3 -1
  7. package/dist/catalog/org-extension-switch.js +12 -5
  8. package/dist/catalog/org-extension.controller.d.ts +2 -21
  9. package/dist/catalog/org-extension.controller.js +1 -38
  10. package/dist/catalog/org-extension.schemas.d.ts +31 -0
  11. package/dist/catalog/org-extension.schemas.js +65 -0
  12. package/dist/channels/actions.js +2 -0
  13. package/dist/channels/cards.d.ts +8 -0
  14. package/dist/channels/cards.js +18 -0
  15. package/dist/channels/outbound.js +8 -1
  16. package/dist/channels/phrases.d.ts +10 -0
  17. package/dist/channels/phrases.js +10 -0
  18. package/dist/conversations/conversations.module.js +4 -0
  19. package/dist/conversations/events.d.ts +1 -0
  20. package/dist/conversations/events.js +5 -0
  21. package/dist/conversations/leak-check.d.ts +26 -0
  22. package/dist/conversations/leak-check.js +69 -0
  23. package/dist/ctx/secrets.d.ts +5 -0
  24. package/dist/ctx/secrets.js +5 -0
  25. package/dist/db/kernel-schema.d.ts +15 -0
  26. package/dist/errors.d.ts +9 -0
  27. package/dist/errors.js +9 -0
  28. package/dist/extensions/deployment-config.d.ts +6 -2
  29. package/dist/extensions/deployment-config.js +35 -23
  30. package/dist/extensions/org-config.d.ts +2 -0
  31. package/dist/extensions/org-config.js +1 -0
  32. package/dist/extensions/org-overrides.d.ts +2 -0
  33. package/dist/extensions/org-overrides.js +3 -2
  34. package/dist/identity/initial-passwords.job.d.ts +3 -2
  35. package/dist/identity/initial-passwords.job.js +9 -5
  36. package/dist/platform/exclusions.js +1 -41
  37. package/dist/platform/method.js +1 -0
  38. package/dist/platform/operation.d.ts +30 -2
  39. package/dist/platform/operation.js +1 -1
  40. package/dist/platform/ops/extensions-admin.ops.d.ts +15 -2
  41. package/dist/platform/ops/extensions-admin.ops.js +153 -5
  42. package/dist/platform/ops/extensions.ops.d.ts +19 -5
  43. package/dist/platform/ops/extensions.ops.js +285 -10
  44. package/dist/platform/ops/person-inputs.d.ts +35 -0
  45. package/dist/platform/ops/person-inputs.js +79 -0
  46. package/dist/platform/ops/plugins.ops.d.ts +2 -0
  47. package/dist/platform/ops/plugins.ops.js +30 -17
  48. package/dist/platform/parity.d.ts +6 -2
  49. package/dist/platform/parity.js +38 -1
  50. package/dist/platform/person-fields.d.ts +103 -0
  51. package/dist/platform/person-fields.js +381 -0
  52. package/dist/platform/platform.module.d.ts +3 -3
  53. package/dist/platform/platform.module.js +6 -5
  54. package/dist/platform/sealed-inputs.d.ts +44 -0
  55. package/dist/platform/sealed-inputs.js +116 -0
  56. package/dist/runtime/waits.js +8 -2
  57. package/dist/tools/approvals.controller.d.ts +1 -0
  58. package/dist/tools/approvals.controller.js +19 -0
  59. package/dist/tools/approvals.service.d.ts +50 -1
  60. package/dist/tools/approvals.service.js +118 -10
  61. package/dist/tools/builtins/builtin-tools.d.ts +3 -0
  62. package/dist/tools/builtins/builtin-tools.js +31 -9
  63. package/dist/tools/builtins/platform.d.ts +20 -0
  64. package/dist/tools/builtins/platform.js +174 -15
  65. package/dist/tools/pipeline.d.ts +24 -2
  66. package/dist/tools/pipeline.js +80 -17
  67. package/dist/tools/policy.d.ts +3 -0
  68. package/dist/tools/policy.js +6 -0
  69. package/dist/tools/registry.d.ts +22 -0
  70. package/dist/tools/tools.module.js +3 -0
  71. package/package.json +4 -4
  72. package/src/migrations/0169_platform_sealed_inputs.sql +23 -0
@@ -4,6 +4,8 @@ import { availability, PLATFORM_UNAVAILABLE_OFF, } from "../../platform/availabi
4
4
  import { errorRoleOf, errorsFor, nextStepFor, OPERATION_ERROR_NEXT, resolveNext, sentence, toToolError, } from "../../platform/errors.js";
5
5
  import { PLATFORM_METHOD } from "../../platform/method.js";
6
6
  import { OPERATION_ID, operationDomain, PRECHECK_TIMEOUT_MS, } from "../../platform/operation.js";
7
+ import { planPersonFields } from "../../platform/person-fields.js";
8
+ import { SealedInputsExpiredError } from "../../platform/sealed-inputs.js";
7
9
  import { BUILTIN } from "../builtin-names.js";
8
10
  /**
9
11
  * The `Platform` builtin (Platform tool spec §3–§6): one tool through which an agent discovers and
@@ -18,6 +20,11 @@ import { BUILTIN } from "../builtin-names.js";
18
20
  * waited).
19
21
  * - An `ApiError` gets the next step the operation declares for its code and the actor's role.
20
22
  * - The actor, the agent and the conversation come from the runtime context, never from input.
23
+ * - A write with person fields (platform web parity spec §4: `op.personFields`) is planned at the
24
+ * policy step: a secret in `values` is denied before the card, and the asked fields go to the
25
+ * card through {@link CallPolicy.personFields} (never remembered). The approved call reads the
26
+ * person's sealed values through `personInputs` and its result names each entered path, never a
27
+ * value.
21
28
  * - Results are JSON text; a list an operation returns is capped at {@link LIST_MAX} entries.
22
29
  */
23
30
  /** The most entries of a list in one result (operations that page return `next`). */
@@ -152,6 +159,25 @@ const missingText = (action, field, what) => `Action ${action} needs "${field}":
152
159
  const invalidParamsText = (id, problems) => `Invalid params for ${id}: ${problems}. Call describe with operation "${id}" for its input schema and an example, then call again.`;
153
160
  const unavailableOpText = (id, reason) => `Operation ${id} is unavailable, so do not call it again as is: ${reason}`;
154
161
  const precheckText = (id, code, message, next) => `Operation ${id} cannot run now: ${code}: ${sentence(message)} ${next ?? OPERATION_ERROR_NEXT}`;
162
+ const secretRecordText = (id, path, target) => `Operation ${id} cannot run now: platform.secret_record_web_only: \`${path}\` is a secret record, which the confirmation card cannot ask for. Tell the person to enter it on the web page of ${target}.`;
163
+ /** Model-visible: the person's values expired before the approved call ran (spec §4.3). */
164
+ export const PERSON_INPUTS_EXPIRED_TEXT = "The values the person entered expired before they were applied; call the operation again.";
165
+ /** Model-visible: an approved call with person fields that has no approval to read them by. */
166
+ const personInputsMissingText = (id) => `Operation ${id} needs values the person enters on the confirmation card, and this call ran without one; call the operation again.`;
167
+ /**
168
+ * Model-visible: the person-field plan refused an approved call when it resumed (the target's
169
+ * secret fields changed while the card waited); `message` is the plan's English refusal.
170
+ */
171
+ const personRefusedText = (id, message) => `Operation ${id} cannot run as approved: ${message} Correct the params, then call the operation again.`;
172
+ /**
173
+ * Model-visible: the fields to enter differ between the card the person confirmed, the values they
174
+ * sealed and the call as it runs now.
175
+ */
176
+ const PERSON_FIELDS_CHANGED_TEXT = "The target changed after the person confirmed (the fields to enter differ); call the operation again.";
177
+ /** Model-visible result line: the approved call's operation never applied the person's values. */
178
+ const unusedValuesText = (id) => `The values the person entered were not used by ${id}.`;
179
+ /** The result line of one field the person entered (never its value). */
180
+ const enteredLine = (path) => `\`${path}\`: entered by the person`;
155
181
  const outputRefText = (id) => `Operation ${id} writes, and its params hold a {"$output": ...} reference, which the person confirming would see instead of the content. Pass the content inline in params and call again.`;
156
182
  /** Whether a value holds a `{"$output": …}` reference anywhere (the pipeline's form). */
157
183
  function hasOutputRef(v) {
@@ -200,6 +226,7 @@ const confirmCtx = (ctx, errorRole) => ({
200
226
  agentId: ctx.agentId,
201
227
  conversationId: ctx.conversationId,
202
228
  runId: ctx.runId,
229
+ ...(ctx.callId !== undefined && { callId: ctx.callId }),
203
230
  signal: new AbortController().signal,
204
231
  errorRole,
205
232
  });
@@ -247,22 +274,36 @@ export function platformTool(deps) {
247
274
  return deny(outputRefText(op.id));
248
275
  }
249
276
  const role = errorRoleOf(f);
277
+ const octx = confirmCtx(ctx, role);
278
+ let personFields;
279
+ try {
280
+ personFields = await personFieldsOf(op, params, octx);
281
+ }
282
+ catch (e) {
283
+ if (e instanceof PersonFieldsRefused)
284
+ return deny(e.message);
285
+ // a target that cannot be read (gone, not allowed) is the write's own error
286
+ return deny(toToolError(e, (code) => nextStepFor(op.errors, code, role)).message);
287
+ }
250
288
  const failed = await precheckOf(op, params, ctx, role, deps.precheckTimeoutMs ?? PRECHECK_TIMEOUT_MS, deps.log);
251
289
  if (failed !== null) {
252
290
  const next = resolveNext(failed.next, role) ?? nextStepFor(op.errors, failed.code, role);
253
291
  return deny(precheckText(op.id, failed.code, failed.message, next));
254
292
  }
255
- const octx = confirmCtx(ctx, role);
256
293
  const [cls, summary] = await Promise.all([
257
294
  classOf(op, params, octx),
258
- summaryOf(op, params, octx),
295
+ summaryOf(op, params, op.personFields === undefined
296
+ ? octx
297
+ : { ...octx, personAsk: personFields?.fields.map((f) => f.path) ?? [] }),
259
298
  ]);
260
299
  return {
261
300
  key,
262
301
  policy: "ask",
263
- // org / platform writes are confirmed every time (spec §6.2)
264
- remember: cls === "personal" && op.rememberable !== false,
302
+ // org / platform writes are confirmed every time (spec §6.2); so is a write with person
303
+ // fields, whatever its class (spec §4.2, R6)
304
+ remember: personFields === null && cls === "personal" && op.rememberable !== false,
265
305
  summary,
306
+ ...(personFields !== null && { personFields }),
266
307
  };
267
308
  }
268
309
  async function run(raw, ctx) {
@@ -343,25 +384,97 @@ export function platformTool(deps) {
343
384
  if (!verdict.ok)
344
385
  throw new ToolError(unavailableOpText(op.id, verdict.reason));
345
386
  const role = errorRoleOf(f);
387
+ const octx = {
388
+ orgId: ctx.orgId,
389
+ actorAccountId: ctx.accountId,
390
+ agentId: ctx.agentId,
391
+ conversationId: ctx.conversationId,
392
+ runId: ctx.runId ?? null,
393
+ callId: ctx.callId,
394
+ signal: ctx.signal,
395
+ errorRole: role,
396
+ };
397
+ /** The paths whose values the handler applied (the result's lines). */
398
+ let entered = [];
399
+ /** Whether the handler called `personInputs.apply` (once at most). */
400
+ let applied = false;
346
401
  let result;
347
402
  try {
348
- result = await op.run(params, {
349
- orgId: ctx.orgId,
350
- actorAccountId: ctx.accountId,
351
- agentId: ctx.agentId,
352
- conversationId: ctx.conversationId,
353
- runId: ctx.runId ?? null,
354
- callId: ctx.callId,
355
- signal: ctx.signal,
356
- errorRole: role,
357
- });
403
+ const person = await personFieldsOf(op, params, octx);
404
+ // what the card showed (the approval's stored specs) binds what runs: the run-time plan
405
+ // must ask exactly those fields, and the sealed values must carry exactly them
406
+ const approvalId = ctx.approvalId;
407
+ const shown = approvalId === undefined ||
408
+ deps.approvalPersonPaths === undefined ||
409
+ ctx.runId === undefined
410
+ ? null
411
+ : await deps.approvalPersonPaths(approvalId, {
412
+ orgId: ctx.orgId,
413
+ runId: ctx.runId,
414
+ callId: ctx.callId,
415
+ });
416
+ if (person === null && shown !== null)
417
+ throw new PersonFieldsChanged();
418
+ if (person !== null) {
419
+ const sealed = deps.sealed;
420
+ if (approvalId === undefined || sealed === undefined) {
421
+ throw new ToolError(personInputsMissingText(op.id));
422
+ }
423
+ // an approval made before the call had person fields (the target changed since)
424
+ if (shown === null)
425
+ throw new PersonFieldsChanged();
426
+ const asked = person.fields.map((p) => p.path);
427
+ if (!sameSet(asked, shown))
428
+ throw new PersonFieldsChanged();
429
+ octx.personInputs = {
430
+ paths: shown,
431
+ apply: (fn) => {
432
+ if (applied)
433
+ throw new Error("personInputs.apply called twice");
434
+ applied = true;
435
+ // the person who typed the values is the run's trigger account, the approval's
436
+ // `requested_for` (a role escalation is refused before the card, R5)
437
+ return sealed.consume(approvalId, ctx.accountId, async (values) => {
438
+ // a throw here rolls the row's delete back: nothing is applied
439
+ if (!sameSet(Object.keys(values), shown) || !sameSet(asked, shown)) {
440
+ throw new PersonFieldsChanged();
441
+ }
442
+ const out = await fn(values);
443
+ entered = Object.keys(values).sort();
444
+ return out;
445
+ });
446
+ },
447
+ };
448
+ }
449
+ result = await op.run(params, octx);
358
450
  }
359
451
  catch (e) {
452
+ if (e instanceof SealedInputsExpiredError)
453
+ throw new ToolError(PERSON_INPUTS_EXPIRED_TEXT);
454
+ if (e instanceof PersonFieldsChanged)
455
+ throw new ToolError(PERSON_FIELDS_CHANGED_TEXT);
456
+ if (e instanceof PersonFieldsRefused)
457
+ throw new ToolError(personRefusedText(op.id, e.message));
360
458
  // a service refusal after the approval (a race the precheck could not see) still names the
361
459
  // next step for this actor (Review Focus 2)
362
460
  throw toToolError(e, (code) => nextStepFor(op.errors, code, role));
363
461
  }
364
- return json(asResult(result), { zh: `调用平台操作 ${op.id}`, en: `Called ${op.id}` });
462
+ const summary = { zh: `调用平台操作 ${op.id}`, en: `Called ${op.id}` };
463
+ const lines = entered.map(enteredLine);
464
+ if (octx.personInputs !== undefined && !applied) {
465
+ // an operation bug: the person typed values the write never used (they expire unread)
466
+ deps.log?.warn("platform operation did not use the person's values", { operation: op.id });
467
+ lines.push(unusedValuesText(op.id));
468
+ }
469
+ if (lines.length === 0)
470
+ return json(asResult(result), summary);
471
+ return {
472
+ content: [
473
+ { type: "text", text: JSON.stringify(asResult(result)) },
474
+ { type: "text", text: lines.join("\n") },
475
+ ],
476
+ display: { summary },
477
+ };
365
478
  }
366
479
  function read(topic) {
367
480
  if (topic === undefined || topic === "") {
@@ -386,6 +499,52 @@ export function platformTool(deps) {
386
499
  },
387
500
  };
388
501
  }
502
+ /** A person-field plan that refuses the call (model-visible English). */
503
+ class PersonFieldsRefused extends Error {
504
+ }
505
+ /** The fields to enter differ from what the person confirmed ({@link PERSON_FIELDS_CHANGED_TEXT}). */
506
+ class PersonFieldsChanged extends Error {
507
+ }
508
+ const sameSet = (a, b) => {
509
+ const sa = new Set(a);
510
+ const sb = new Set(b);
511
+ return sa.size === sb.size && [...sa].every((x) => sb.has(x));
512
+ };
513
+ /** The `askPerson` / `clearSecrets` of a validated input (both default to [] in the schema). */
514
+ const pathsOf = (params, key) => {
515
+ const v = params?.[key];
516
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
517
+ };
518
+ /**
519
+ * The person fields one call asks for (spec §4.1): `op.personFields` planned against the input's
520
+ * `values`, `askPerson` and `clearSecrets`. Null when the operation has none or the plan asks for
521
+ * nothing. Throws {@link PersonFieldsRefused} with the plan's refusal, or with
522
+ * `platform.secret_record_web_only` when `askPerson` / `clearSecrets` names a secret record the card
523
+ * cannot ask for (ruling R1); an error reading the target propagates.
524
+ */
525
+ async function personFieldsOf(op, params, ctx) {
526
+ if (op.personFields === undefined)
527
+ return null;
528
+ const target = await op.personFields(params, ctx);
529
+ const askPerson = pathsOf(params, "askPerson");
530
+ const clearSecrets = pathsOf(params, "clearSecrets");
531
+ const records = new Set(target.recordOnly ?? []);
532
+ const record = [...askPerson, ...clearSecrets].find((p) => records.has(p));
533
+ if (record !== undefined) {
534
+ throw new PersonFieldsRefused(secretRecordText(op.id, record, target.target.en));
535
+ }
536
+ const values = params?.values;
537
+ const plan = planPersonFields(target, {
538
+ ...(typeof values === "object" &&
539
+ values !== null &&
540
+ !Array.isArray(values) && { values: values }),
541
+ askPerson,
542
+ clearSecrets,
543
+ });
544
+ if (!plan.ok)
545
+ throw new PersonFieldsRefused(plan.message);
546
+ return plan.ask.length === 0 ? null : { target: target.target, fields: plan.ask };
547
+ }
389
548
  /**
390
549
  * The class of one write: `confirmFor` when the operation has one (the target decides), else
391
550
  * `confirm`. A `confirmFor` that throws counts as `org`: never remembered.
@@ -44,6 +44,13 @@ export declare const approvalDeniedText: (reason: string | null) => string;
44
44
  export declare const approvalExpiredText: (hours: number) => string;
45
45
  /** 等待审批期间 run 被中止。 */
46
46
  export declare const APPROVAL_CANCELLED_TEXT = "The run was stopped while waiting for approval.";
47
+ /** A person field refused on the approval card as leaked, for a call that then did not run. */
48
+ export declare const leakedOnCardText: (path: string) => string;
49
+ /**
50
+ * A call that ended without running: its text, then the leaked-on-card line per person field the
51
+ * approval card refused as leaked (`detail.leakedFields`), so the agent has the key rotated.
52
+ */
53
+ export declare const withLeakedOnCard: (text: string, leakedFields: readonly string[] | undefined) => string;
47
54
  /** What the review held: a shell command, a file write, or a file read outside the scope. */
48
55
  export type ReviewKind = "command" | "write" | "read";
49
56
  /**
@@ -78,6 +85,16 @@ export declare const INPUT_SKIPPED_TEXT = "The user did not provide the requeste
78
85
  export declare const TOO_MANY_INPUT_REQUESTS_TEXT = "Tool requested user input too many times.";
79
86
  /** run 已被中止 / 到达截止时间,调用尚未开始执行。 */
80
87
  export declare const RUN_STOPPED_TEXT = "The run was stopped before this tool call was executed.";
88
+ /**
89
+ * A call with person fields in an unattended run (ruling R6): no person is there to type the
90
+ * values on the card.
91
+ */
92
+ export declare const PERSON_FIELDS_UNATTENDED_TEXT = "This write needs the person to enter values on the web; it cannot run unattended.";
93
+ /**
94
+ * A call with person fields whose ask would go to a role instead of the person (ruling R5): only the
95
+ * person the run works for may type the values, and they lack the role.
96
+ */
97
+ export declare 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.";
81
98
  /** 调用执行中 run 被中止 / 到达截止时间。 */
82
99
  export declare const RUN_STOPPED_DURING_TEXT = "The run was stopped while this tool call was running; its outcome is unknown. Verify before retrying.";
83
100
  /**
@@ -458,7 +475,10 @@ export declare class ToolPipeline {
458
475
  * 或找不到 model_call 时返回 null(不做加载检查)。已加载集合由此从日志得出,不放进程内存。
459
476
  */
460
477
  private sentTools;
461
- /** A decided approval other than approved → the model's text; still pending → null (wait). */
478
+ /**
479
+ * A decided approval other than approved → the model's text; still pending → null (wait). A
480
+ * person field refused on the card as leaked is named, so the agent has the key rotated.
481
+ */
462
482
  private refusalText;
463
483
  /**
464
484
  * A handler returned `input_required`: past the round limit, an invalid form
@@ -476,7 +496,9 @@ export declare class ToolPipeline {
476
496
  against?: string | undefined;
477
497
  escalation?: "available" | "escalated" | undefined;
478
498
  escalationRefusal?: string | undefined;
479
- }): Promise<ExecOutcome>;
499
+ },
500
+ /** The approved approval of this call, matching its definition and input (builtins only). */
501
+ approvalId?: string): Promise<ExecOutcome>;
480
502
  private executeConnector;
481
503
  /** 抛出的错误 → 给模型的结果:ToolError 的消息原样(插件约定为英文、可操作),其他只给错误类名。 */
482
504
  private thrown;
@@ -48,7 +48,7 @@ import { isSessionGrantableRule, } from "../sandbox/review/index.js";
48
48
  import { approverForCrossing, buildPermissionCandidate, crossingOfCandidate, ESCALATION_RETRY_HINT, ESCALATION_UNATTENDED_WHY, escalationRefusedText, isEscalatedCall, } from "../sandbox/review/permission-candidate.js";
49
49
  import { CommandReviewService } from "../sandbox/review/review.service.js";
50
50
  import { SandboxService } from "../sandbox/sandbox.service.js";
51
- import { appendMissingGrant, connectionGrantKey, UNATTENDED_CONNECTION_ERROR, UNATTENDED_ELICITATION_NOTE, UNATTENDED_QUESTION_ERROR, unattendedFails, unattendedRunOf, } from "../schedules/unattended.js";
51
+ import { appendMissingGrant, connectionGrantKey, UNATTENDED_CONNECTION_ERROR, UNATTENDED_ELICITATION_NOTE, UNATTENDED_QUESTION_ERROR, unattendedFails, unattendedRules, unattendedRunOf, } from "../schedules/unattended.js";
52
52
  import { skillLoadOfferedIn } from "../skills/catalog.js";
53
53
  import { ApprovalsService, } from "./approvals.service.js";
54
54
  import { Breaker, breakerOpenMessage } from "./breaker.js";
@@ -85,6 +85,15 @@ export const approvalDeniedText = (reason) => reason === null ? APPROVAL_DENIED_
85
85
  export const approvalExpiredText = (hours) => `Approval timed out after ${hours}h; treated as denied.`;
86
86
  /** 等待审批期间 run 被中止。 */
87
87
  export const APPROVAL_CANCELLED_TEXT = "The run was stopped while waiting for approval.";
88
+ /** A person field refused on the approval card as leaked, for a call that then did not run. */
89
+ export const leakedOnCardText = (path) => `The person's \`${path}\` appeared in the conversation earlier and was refused as leaked; ask them to rotate it.`;
90
+ /**
91
+ * A call that ended without running: its text, then the leaked-on-card line per person field the
92
+ * approval card refused as leaked (`detail.leakedFields`), so the agent has the key rotated.
93
+ */
94
+ export const withLeakedOnCard = (text, leakedFields) => leakedFields === undefined || leakedFields.length === 0
95
+ ? text
96
+ : [text, ...leakedFields.map(leakedOnCardText)].join("\n");
88
97
  /**
89
98
  * The command review's deny text (auto mode spec §5.4, P-D12): the model-visible reason and what it
90
99
  * can do instead. `kind` says whether a shell command, a file write or a file read was held.
@@ -128,6 +137,16 @@ export const INPUT_SKIPPED_TEXT = "The user did not provide the requested input
128
137
  export const TOO_MANY_INPUT_REQUESTS_TEXT = "Tool requested user input too many times.";
129
138
  /** run 已被中止 / 到达截止时间,调用尚未开始执行。 */
130
139
  export const RUN_STOPPED_TEXT = "The run was stopped before this tool call was executed.";
140
+ /**
141
+ * A call with person fields in an unattended run (ruling R6): no person is there to type the
142
+ * values on the card.
143
+ */
144
+ export const PERSON_FIELDS_UNATTENDED_TEXT = "This write needs the person to enter values on the web; it cannot run unattended.";
145
+ /**
146
+ * A call with person fields whose ask would go to a role instead of the person (ruling R5): only the
147
+ * person the run works for may type the values, and they lack the role.
148
+ */
149
+ 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.";
131
150
  /** 调用执行中 run 被中止 / 到达截止时间。 */
132
151
  export const RUN_STOPPED_DURING_TEXT = "The run was stopped while this tool call was running; its outcome is unknown. Verify before retrying.";
133
152
  /** The fixed result of a call whose input request was skipped by a message (spec §7.1). */
@@ -707,6 +726,7 @@ let ToolPipeline = class ToolPipeline {
707
726
  agentId: ctx.agentId,
708
727
  conversationId: ctx.conversationId,
709
728
  runId: ctx.runId,
729
+ callId: call.id,
710
730
  rawInput: call.input,
711
731
  signal: ctx.signal,
712
732
  })) ?? null;
@@ -715,7 +735,13 @@ let ToolPipeline = class ToolPipeline {
715
735
  return fail(callPolicy.denyReason, outKey);
716
736
  }
717
737
  const policyKey = callPolicy?.key ?? tool.key;
718
- const decision = await this.decide(tool, ctx.agent, {
738
+ // person fields (platform web parity spec §4.2, R6): the person types values on the card, so an
739
+ // unattended run (a trial run has its creator there) cannot make the call at all
740
+ const personFields = callPolicy?.personFields;
741
+ if (personFields !== undefined && unattendedRules(ctx.unattended)) {
742
+ return fail(PERSON_FIELDS_UNATTENDED_TEXT, outKey);
743
+ }
744
+ let decision = await this.decide(tool, ctx.agent, {
719
745
  orgId: ctx.orgId,
720
746
  accountId: ctx.accountId,
721
747
  agentId: ctx.agentId,
@@ -740,6 +766,26 @@ let ToolPipeline = class ToolPipeline {
740
766
  if (typeof decision === "object" && "unavailable" in decision) {
741
767
  return fail(unavailableText(tool.key, decision.unavailable), outKey);
742
768
  }
769
+ if (personFields !== undefined) {
770
+ // R6: always the person's own card, never a grant or an `allow` (the default policy already
771
+ // asks for them; this holds for any decision)
772
+ if (decision === "allow" || "grant" in decision) {
773
+ decision = {
774
+ ask: {
775
+ toolKey: policyKey,
776
+ specHash: tool.specHash,
777
+ connectorId: tool.source.kind === "connector" ? tool.source.connectorId : null,
778
+ requestedFor: ctx.accountId,
779
+ approverRole: null,
780
+ policy: "fixed",
781
+ },
782
+ };
783
+ }
784
+ // R5: only the person the run works for types the values; a role escalation cannot ask them
785
+ if ("ask" in decision && decision.ask.requestedFor === null) {
786
+ return fail(PERSON_FIELDS_ROLE_TEXT, outKey);
787
+ }
788
+ }
743
789
  // 该调用已有审批(续跑)→ 按审批结果;没有且策略为 ask → 建审批并等待
744
790
  // (不写 tool_call_started:此时尚未开始执行)。
745
791
  let approval = await this.deps.approvals.forCall(ctx.runId, call.id);
@@ -766,7 +812,13 @@ let ToolPipeline = class ToolPipeline {
766
812
  approverRole: decision.ask.approverRole,
767
813
  policy: decision.ask.policy,
768
814
  ...(callPolicy?.summary !== undefined && { summary: callPolicy.summary }),
769
- ...(callPolicy !== null && !callPolicy.remember && { scopes: ["once"] }),
815
+ ...((personFields !== undefined || (callPolicy !== null && !callPolicy.remember)) && {
816
+ scopes: ["once"],
817
+ }),
818
+ // the specs of the asked fields, never a value (the card draws its inputs from them)
819
+ ...(personFields !== undefined && {
820
+ detail: { personFields: personFields.fields, target: personFields.target },
821
+ }),
770
822
  });
771
823
  }
772
824
  if (approval && approval.status !== "approved") {
@@ -949,7 +1001,9 @@ let ToolPipeline = class ToolPipeline {
949
1001
  },
950
1002
  ]);
951
1003
  const t0 = Date.now();
952
- let outcome = await this.execute(tool, input, ctx, call.id, resume, resolved.tools, reviewedRoots);
1004
+ let outcome = await this.execute(tool, input, ctx, call.id, resume, resolved.tools, reviewedRoots,
1005
+ // the approval the call runs under (a Platform write reads the person's values by it)
1006
+ approval?.status === "approved" && approvedHere ? approval.id : undefined);
953
1007
  const durationMs = Date.now() - t0;
954
1008
  await this.deps.hooks?.afterExecute?.(ctx.runId, call.id);
955
1009
  // the record says a call ran outside the sandbox only when admission gave it that scope
@@ -1851,19 +1905,25 @@ let ToolPipeline = class ToolPipeline {
1851
1905
  }
1852
1906
  return null;
1853
1907
  }
1854
- /** A decided approval other than approved → the model's text; still pending → null (wait). */
1908
+ /**
1909
+ * A decided approval other than approved → the model's text; still pending → null (wait). A
1910
+ * person field refused on the card as leaked is named, so the agent has the key rotated.
1911
+ */
1855
1912
  refusalText(a) {
1856
- switch (a.status) {
1857
- case "denied":
1858
- return approvalDeniedText(a.denyReason);
1859
- case "expired":
1860
- // 按该审批实际的等待时长(创建到到期),不读当前配置(配置可热更新)
1861
- return approvalExpiredText(approvalHours(a));
1862
- case "cancelled":
1863
- return APPROVAL_CANCELLED_TEXT;
1864
- default:
1865
- return null;
1866
- }
1913
+ const text = (() => {
1914
+ switch (a.status) {
1915
+ case "denied":
1916
+ return approvalDeniedText(a.denyReason);
1917
+ case "expired":
1918
+ // Use the approval's own wait (creation to expiry), not the current config: it can be hot-reloaded
1919
+ return approvalExpiredText(approvalHours(a));
1920
+ case "cancelled":
1921
+ return APPROVAL_CANCELLED_TEXT;
1922
+ default:
1923
+ return null;
1924
+ }
1925
+ })();
1926
+ return text === null ? null : withLeakedOnCard(text, a.leakedFields);
1867
1927
  }
1868
1928
  /**
1869
1929
  * A handler returned `input_required`: past the round limit, an invalid form
@@ -1906,7 +1966,9 @@ let ToolPipeline = class ToolPipeline {
1906
1966
  * 带 `tools.timeoutMs` 超时与 run 的中止信号(合并后传给处理函数 / 连接器,不响应信号的也按时结束)。
1907
1967
  * 熔断只作用于连接器工具(键为组织 × 连接器)。
1908
1968
  */
1909
- async execute(tool, input, ctx, callId, resume, stepTools, reviewed) {
1969
+ async execute(tool, input, ctx, callId, resume, stepTools, reviewed,
1970
+ /** The approved approval of this call, matching its definition and input (builtins only). */
1971
+ approvalId) {
1910
1972
  const reviewedWorkingRoot = reviewed?.workingRoot;
1911
1973
  const reviewedAgainstRoot = reviewed?.against;
1912
1974
  if (tool.source.kind === "connector") {
@@ -1934,6 +1996,7 @@ let ToolPipeline = class ToolPipeline {
1934
1996
  }),
1935
1997
  ...(tool.source.kind === "builtin" &&
1936
1998
  ctx.deadline !== undefined && { runDeadline: ctx.deadline }),
1999
+ ...(tool.source.kind === "builtin" && approvalId !== undefined && { approvalId }),
1937
2000
  // a reviewed call runs in the working root its review judged (project root spec §4.3)
1938
2001
  ...(tool.source.kind === "builtin" &&
1939
2002
  reviewedWorkingRoot !== undefined && { reviewedWorkingRoot }),
@@ -78,6 +78,9 @@ export declare function connectorPolicy(input: {
78
78
  * for a fixed ask, a role escalation or a connector tool whose definition changed;
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
+ *
82
+ * A call with person fields (`CallPolicy.personFields`) is a fixed ask: no grant or agent
83
+ * `allow` lets it through (ruling R6). The pipeline refuses it before this in an unattended run.
81
84
  */
82
85
  export declare function createDecidePolicy(db: KernelSchemaDb,
83
86
  /** Logs (debug: once per call) when an org's stored security setting is unreadable. */
@@ -101,6 +101,9 @@ export function connectorPolicy(input) {
101
101
  * for a fixed ask, a role escalation or a connector tool whose definition changed;
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
+ *
105
+ * A call with person fields (`CallPolicy.personFields`) is a fixed ask: no grant or agent
106
+ * `allow` lets it through (ruling R6). The pipeline refuses it before this in an unattended run.
104
107
  */
105
108
  export function createDecidePolicy(db,
106
109
  /** Logs (debug: once per call) when an org's stored security setting is unreadable. */
@@ -249,7 +252,10 @@ log) {
249
252
  tool.source.kind === "builtin" &&
250
253
  tool.key === BUILTIN.Platform &&
251
254
  changesAgentSkills(policyKey);
255
+ // person fields (platform web parity spec §4.2, R6): the person types values on the card, so
256
+ // the call asks every time, outside every grant, and no agent `allow` lifts it
252
257
  const fixedAsk = unattendedSkillChange ||
258
+ call?.personFields !== undefined ||
253
259
  isFixedAsk(tool) ||
254
260
  (call !== null && !call.remember && (call.policy !== "allow" || agentOverride !== undefined));
255
261
  const input = {
@@ -7,6 +7,7 @@ import { ExtensionRegistry } from "../extensions/registry.js";
7
7
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
8
8
  import { KernelDb } from "../infra/database/kernel-db.js";
9
9
  import type { OrgRole } from "../orgs/roles.js";
10
+ import type { PersonFieldSpec } from "../platform/person-fields.js";
10
11
  import type { ConversationKindForHooks } from "../runtime/hook-calls.js";
11
12
  import type { ExecutionClaim } from "../runtime/run-execution.js";
12
13
  import { BuiltinTools } from "./builtins/builtin-tools.js";
@@ -95,6 +96,12 @@ export interface BuiltinCallContext extends ToolCallContext {
95
96
  agentVersion?: number;
96
97
  conversationKind?: ConversationKindForHooks;
97
98
  parent?: HookParentScope;
99
+ /**
100
+ * The approval the call runs under: set only when an approved approval of this call, matching
101
+ * its definition and input, let it through (absent for a grant or a policy allow). A `Platform`
102
+ * call with person fields reads the person's sealed values by it.
103
+ */
104
+ approvalId?: string;
98
105
  }
99
106
  /** One image the builtin `Read` stored for a call (`tool_result.media`, vision-read design §1.2). */
100
107
  export type ToolResultMedia = NonNullable<EventPayload<"tool_result">["media"]>[number];
@@ -177,6 +184,8 @@ export interface CallPolicyContext {
177
184
  conversationId: string;
178
185
  /** Null outside a run (a builtin called directly). */
179
186
  runId: string | null;
187
+ /** The tool call being decided (a call id is unique within its run). Absent outside the pipeline. */
188
+ callId?: string;
180
189
  /**
181
190
  * The call's input as the model sent it, before `{"$output": id}` references were resolved
182
191
  * (the approval card shows this form). Absent outside the pipeline.
@@ -205,6 +214,19 @@ export interface CallPolicy {
205
214
  };
206
215
  /** With `policy: "deny"`: the actionable English reason returned as the tool error. */
207
216
  denyReason?: string;
217
+ /**
218
+ * The secret fields the person enters on the approval card for this call (platform web parity
219
+ * spec §4.2): only the asked ones, specs without values. The pipeline always asks for such a
220
+ * call (never a grant or an `allow`; ruling R6), refuses it in an unattended run and when the ask
221
+ * would go to a role instead of the person, and stores the fields in the approval's `detail`.
222
+ */
223
+ personFields?: {
224
+ target: {
225
+ zh: string;
226
+ en: string;
227
+ };
228
+ fields: PersonFieldSpec[];
229
+ };
208
230
  }
209
231
  export type ToolPolicy = "allow" | "ask" | "deny";
210
232
  export interface ResolvedTool {
@@ -9,6 +9,7 @@ import { BackgroundModule } from "../background/background.module.js";
9
9
  import { ConversationAccessModule } from "../conversations/access.js";
10
10
  import { AttachmentsModule } from "../conversations/attachments.module.js";
11
11
  import { EventLogModule } from "../conversations/event-log.js";
12
+ import { ConversationLeakCheckModule } from "../conversations/leak-check.js";
12
13
  import { DevicesModule } from "../devices/devices.module.js";
13
14
  import { ExtensionsModule } from "../extensions/extensions.module.js";
14
15
  import { QueueModule } from "../infra/queue/queue.module.js";
@@ -66,6 +67,8 @@ ToolsModule = __decorate([
66
67
  PermissionAuthorityModule,
67
68
  OperationAuthorityModule,
68
69
  EventLogModule,
70
+ // the approval decision's leak check of a person's card values
71
+ ConversationLeakCheckModule,
69
72
  AttachmentsModule,
70
73
  ExtensionsModule,
71
74
  StorageModule,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.57",
3
+ "version": "0.1.0-rc.58",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.41"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.42"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -75,8 +75,8 @@
75
75
  "@types/ws": "^8.18.2",
76
76
  "@types/yauzl": "3.4.0",
77
77
  "ws": "^8.22.0",
78
- "@capybara-hq/device": "0.1.0-rc.20",
79
- "@capybara-hq/testing": "0.1.0-rc.29"
78
+ "@capybara-hq/testing": "0.1.0-rc.29",
79
+ "@capybara-hq/device": "0.1.0-rc.22"
80
80
  },
81
81
  "scripts": {
82
82
  "build": "tsc -b"
@@ -0,0 +1,23 @@
1
+ -- Platform web parity (spec 2026-11-19-platform-web-parity-design.md §4.3): values a person types on
2
+ -- an approval card for a Platform call's secret fields, sealed until the resumed call consumes them
3
+ -- once. Expand-only.
4
+ --
5
+ -- One row per approval, written in the decision's transaction. The values are one JSON object
6
+ -- sealed with the master keyring (AES-256-GCM, AAD = approval id plus the sorted field paths in
7
+ -- `paths`, so a row whose paths are altered fails to unwrap). Only the recipient (the person who
8
+ -- typed them) may consume the row; the resumed call deletes it in the transaction that applies the
9
+ -- write, and the hourly cleanup job drops rows past expires_at (15 minutes after the decision).
10
+ CREATE TABLE IF NOT EXISTS capybara.platform_sealed_inputs (
11
+ approval_id text PRIMARY KEY REFERENCES capybara.approvals(id) ON DELETE CASCADE,
12
+ recipient_account_id text NOT NULL REFERENCES capybara.accounts(id) ON DELETE CASCADE,
13
+ conversation_id text NOT NULL REFERENCES capybara.conversations(id) ON DELETE CASCADE,
14
+ run_id text NOT NULL,
15
+ call_id text NOT NULL,
16
+ paths text[] NOT NULL,
17
+ master_key_id text NOT NULL,
18
+ ciphertext bytea NOT NULL,
19
+ expires_at timestamptz NOT NULL,
20
+ created_at timestamptz NOT NULL DEFAULT now()
21
+ );
22
+ CREATE INDEX IF NOT EXISTS platform_sealed_inputs_expires_idx
23
+ ON capybara.platform_sealed_inputs (expires_at);