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

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 (86) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/catalog/org-catalog.controller.d.ts +0 -5
  3. package/dist/catalog/org-catalog.controller.js +3 -17
  4. package/dist/catalog/org-catalog.schemas.d.ts +43 -0
  5. package/dist/catalog/org-catalog.schemas.js +43 -2
  6. package/dist/catalog/plugin-install.d.ts +2 -0
  7. package/dist/catalog/plugin-install.js +3 -3
  8. package/dist/channels/channels.schemas.d.ts +3 -0
  9. package/dist/channels/channels.schemas.js +8 -0
  10. package/dist/channels/connections.service.d.ts +17 -2
  11. package/dist/channels/connections.service.js +30 -5
  12. package/dist/channels/outbound.js +17 -0
  13. package/dist/conversations/events.d.ts +34 -0
  14. package/dist/conversations/events.js +24 -0
  15. package/dist/ctx/secrets.d.ts +8 -1
  16. package/dist/ctx/secrets.js +14 -1
  17. package/dist/db/kernel-schema.d.ts +19 -0
  18. package/dist/devices/working-root.d.ts +2 -3
  19. package/dist/errors.d.ts +10 -0
  20. package/dist/errors.js +10 -0
  21. package/dist/http/api.module.js +6 -0
  22. package/dist/identity/initial-passwords.job.d.ts +3 -3
  23. package/dist/identity/initial-passwords.job.js +7 -5
  24. package/dist/orgs/invitations.controller.d.ts +3 -11
  25. package/dist/orgs/invitations.controller.js +9 -10
  26. package/dist/orgs/invitations.service.d.ts +12 -2
  27. package/dist/orgs/invitations.service.js +14 -7
  28. package/dist/orgs/members.service.d.ts +12 -2
  29. package/dist/orgs/members.service.js +10 -8
  30. package/dist/orgs/orgs.controller.d.ts +4 -12
  31. package/dist/orgs/orgs.controller.js +10 -10
  32. package/dist/orgs/orgs.schemas.d.ts +26 -0
  33. package/dist/orgs/orgs.schemas.js +22 -0
  34. package/dist/platform/connector-person-fields.d.ts +67 -0
  35. package/dist/platform/connector-person-fields.js +129 -0
  36. package/dist/platform/exclusions.js +5 -100
  37. package/dist/platform/operation.d.ts +31 -0
  38. package/dist/platform/operation.js +3 -3
  39. package/dist/platform/ops/accounts.ops.js +1 -0
  40. package/dist/platform/ops/channels.ops.d.ts +10 -3
  41. package/dist/platform/ops/channels.ops.js +223 -5
  42. package/dist/platform/ops/connectors.ops.d.ts +22 -4
  43. package/dist/platform/ops/connectors.ops.js +664 -13
  44. package/dist/platform/ops/org-plugins.ops.d.ts +15 -2
  45. package/dist/platform/ops/org-plugins.ops.js +323 -4
  46. package/dist/platform/ops/orgs.ops.d.ts +40 -3
  47. package/dist/platform/ops/orgs.ops.js +293 -12
  48. package/dist/platform/ops/person-inputs.d.ts +30 -0
  49. package/dist/platform/ops/person-inputs.js +50 -0
  50. package/dist/platform/ops/plugins.ops.d.ts +1 -1
  51. package/dist/platform/ops/plugins.ops.js +6 -6
  52. package/dist/platform/parity.d.ts +3 -2
  53. package/dist/platform/parity.js +40 -15
  54. package/dist/platform/person-fields.d.ts +20 -4
  55. package/dist/platform/person-fields.js +27 -5
  56. package/dist/platform/platform.module.d.ts +2 -1
  57. package/dist/platform/platform.module.js +5 -3
  58. package/dist/platform/route-schemas.js +2 -0
  59. package/dist/platform/sealed-reveals.controller.d.ts +20 -0
  60. package/dist/platform/sealed-reveals.controller.js +48 -0
  61. package/dist/platform/sealed-reveals.d.ts +52 -0
  62. package/dist/platform/sealed-reveals.js +153 -0
  63. package/dist/runtime/project/knowledge.js +24 -19
  64. package/dist/sandbox/permission-facts.d.ts +5 -1
  65. package/dist/sandbox/permission-facts.js +8 -2
  66. package/dist/setup/setup-guides.service.d.ts +5 -0
  67. package/dist/setup/setup-guides.service.js +2 -1
  68. package/dist/tools/approvals.service.js +1 -1
  69. package/dist/tools/builtins/platform.js +48 -8
  70. package/dist/tools/connectors.controller.d.ts +6 -7
  71. package/dist/tools/connectors.controller.js +4 -44
  72. package/dist/tools/connectors.schemas.d.ts +170 -1
  73. package/dist/tools/connectors.schemas.js +82 -3
  74. package/dist/tools/connectors.service.d.ts +16 -6
  75. package/dist/tools/connectors.service.js +39 -24
  76. package/dist/tools/oauth/oauth.controller.d.ts +3 -6
  77. package/dist/tools/oauth/oauth.controller.js +3 -12
  78. package/dist/tools/oauth/oauth.schemas.d.ts +14 -0
  79. package/dist/tools/oauth/oauth.schemas.js +27 -0
  80. package/dist/tools/pipeline.d.ts +7 -0
  81. package/dist/tools/pipeline.js +13 -4
  82. package/dist/tools/policy.d.ts +3 -2
  83. package/dist/tools/policy.js +4 -2
  84. package/dist/tools/registry.d.ts +7 -0
  85. package/package.json +4 -4
  86. package/src/migrations/0170_platform_sealed_reveals.sql +27 -0
@@ -16,10 +16,19 @@ export declare const PERSON_FIELDS_MAX = 32;
16
16
  export interface PersonFieldSpec {
17
17
  /** Dot path from the schema root (R1). */
18
18
  path: string;
19
- /** From the node's `title` / `x-ui.label`, else the path. */
20
- label: string;
21
- /** From the node's `description` / `x-ui.help`. */
22
- description?: string;
19
+ /**
20
+ * The card label in both languages: from the node's `title` / `x-ui.label` (a localized hint
21
+ * gives its `zh`; a plain string serves both), else the path.
22
+ */
23
+ label: {
24
+ zh: string;
25
+ en: string;
26
+ };
27
+ /** From the node's `description` / `x-ui.help`, in both languages as {@link label}. */
28
+ description?: {
29
+ zh: string;
30
+ en: string;
31
+ };
23
32
  /**
24
33
  * The node's `x-ui` widget is a textarea (or JSON) editor. `checkConfigUi` forbids widgets on
25
34
  * secret nodes of extension schemas, so their rows are single-line (JSON pastes fine into a
@@ -63,6 +72,13 @@ export declare function secretFieldsOf(jsonSchema: unknown, stored: ReadonlySet<
63
72
  fields: PersonFieldSpec[];
64
73
  recordOnly: string[];
65
74
  };
75
+ /**
76
+ * A refusal of a call's person fields (model-visible English, never a value): thrown by the plan,
77
+ * or by an operation's `personFields` for an input the plan cannot see (a dynamic record such as
78
+ * the install's `extensionConfig`). The tool denies the call with the message before the card.
79
+ */
80
+ export declare class PersonFieldsRefused extends Error {
81
+ }
66
82
  /** The plan of one call: the fields the card asks for and the secrets to clear, or a refusal. */
67
83
  export type PersonFieldPlan = {
68
84
  ok: true;
@@ -139,10 +139,25 @@ function hintText(v) {
139
139
  return v.en;
140
140
  return undefined;
141
141
  }
142
+ /** The Chinese text of a localized hint (`{ zh, en }`); a plain string has none. */
143
+ function hintZh(v) {
144
+ return isObj(v) && typeof v.zh === "string" && v.zh !== "" ? v.zh : undefined;
145
+ }
146
+ /**
147
+ * A text in both languages from hints in order of preference: the first English text, and the
148
+ * first Chinese text of a localized hint, else the English one (a plain `title` is often the
149
+ * English of an `x-ui.label` that also carries `zh`).
150
+ */
151
+ function bilingual(hints) {
152
+ const en = hints.map(hintText).find((t) => t !== undefined);
153
+ if (en === undefined)
154
+ return undefined;
155
+ return { zh: hints.map(hintZh).find((t) => t !== undefined) ?? en, en };
156
+ }
142
157
  function fieldOf(node, shape, path, required, isSet) {
143
158
  const hints = isObj(shape["x-ui"]) ? shape["x-ui"] : isObj(node["x-ui"]) ? node["x-ui"] : {};
144
- const label = hintText(shape.title) ?? hintText(node.title) ?? hintText(hints.label) ?? path;
145
- const description = hintText(shape.description) ?? hintText(node.description) ?? hintText(hints.help);
159
+ const label = bilingual([shape.title, node.title, hints.label]) ?? { zh: path, en: path };
160
+ const description = bilingual([shape.description, node.description, hints.help]);
146
161
  const spec = {
147
162
  path,
148
163
  label,
@@ -227,6 +242,13 @@ export function secretFieldsOf(jsonSchema, stored) {
227
242
  const asked = new Set(fields.map((f) => f.path));
228
243
  return { fields, recordOnly: [...recordOnly].filter((p) => !asked.has(p)) };
229
244
  }
245
+ /**
246
+ * A refusal of a call's person fields (model-visible English, never a value): thrown by the plan,
247
+ * or by an operation's `personFields` for an input the plan cannot see (a dynamic record such as
248
+ * the install's `extensionConfig`). The tool denies the call with the message before the card.
249
+ */
250
+ export class PersonFieldsRefused extends Error {
251
+ }
230
252
  /**
231
253
  * Every (dot path, leaf value) pair of `values`, keyed by dot path or nesting objects: own
232
254
  * properties only, plain objects descended, arrays, scalars and null leaves.
@@ -369,13 +391,13 @@ function validatorOf(schema) {
369
391
  */
370
392
  export function checkPersonValue(spec, value) {
371
393
  if (Buffer.byteLength(value, "utf8") > PERSON_FIELD_MAX_BYTES) {
372
- return `${spec.label} is longer than 16 KiB.`;
394
+ return `${spec.label.en} is longer than 16 KiB.`;
373
395
  }
374
396
  if (value === "")
375
- return `${spec.label} is empty.`;
397
+ return `${spec.label.en} is empty.`;
376
398
  const validate = validatorOf(spec.schema);
377
399
  if (validate === null || validate(value))
378
400
  return null;
379
401
  const problems = (validate.errors ?? []).map((e) => e.message ?? "is invalid");
380
- return `${spec.label} ${[...new Set(problems)].join("; ")}.`;
402
+ return `${spec.label.en} ${[...new Set(problems)].join("; ")}.`;
381
403
  }
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The `Platform` tool's core (Platform tool spec §3, §6, §7): the operation registry, the actor
3
- * facts, the agent docs and the sealed person inputs (platform web parity spec §4.3). It imports
3
+ * facts, the agent docs, the sealed person inputs (platform web parity spec §4.3) and the sealed
4
+ * reveals (invitation links, §7.2). It imports
4
5
  * no domain module (ruling P2), so `ToolsModule` can import it without a cycle; domain providers
5
6
  * register their operations into `PlatformOperations` from `onModuleInit`.
6
7
  */
@@ -9,9 +9,11 @@ import { PlatformActor } from "./actor.js";
9
9
  import { AgentDocs } from "./agent-docs.js";
10
10
  import { PlatformOperations } from "./registry.js";
11
11
  import { SealedInputs } from "./sealed-inputs.js";
12
+ import { SealedReveals } from "./sealed-reveals.js";
12
13
  /**
13
14
  * The `Platform` tool's core (Platform tool spec §3, §6, §7): the operation registry, the actor
14
- * facts, the agent docs and the sealed person inputs (platform web parity spec §4.3). It imports
15
+ * facts, the agent docs, the sealed person inputs (platform web parity spec §4.3) and the sealed
16
+ * reveals (invitation links, §7.2). It imports
15
17
  * no domain module (ruling P2), so `ToolsModule` can import it without a cycle; domain providers
16
18
  * register their operations into `PlatformOperations` from `onModuleInit`.
17
19
  */
@@ -19,8 +21,8 @@ let PlatformModule = class PlatformModule {
19
21
  };
20
22
  PlatformModule = __decorate([
21
23
  Module({
22
- providers: [PlatformOperations, PlatformActor, AgentDocs, SealedInputs],
23
- exports: [PlatformOperations, PlatformActor, AgentDocs, SealedInputs],
24
+ providers: [PlatformOperations, PlatformActor, AgentDocs, SealedInputs, SealedReveals],
25
+ exports: [PlatformOperations, PlatformActor, AgentDocs, SealedInputs, SealedReveals],
24
26
  })
25
27
  ], PlatformModule);
26
28
  export { PlatformModule };
@@ -34,6 +34,7 @@ import { PLATFORM_ICON_ROUTES } from "../themes/platform-icon.schemas.js";
34
34
  import { THEME_ROUTES } from "../themes/themes.schemas.js";
35
35
  import { APPROVAL_ROUTES } from "../tools/approvals.schemas.js";
36
36
  import { CONNECTOR_ROUTES } from "../tools/connectors.schemas.js";
37
+ import { OAUTH_ROUTES } from "../tools/oauth/oauth.schemas.js";
37
38
  import { UI_ROUTES } from "../ui/ui.schemas.js";
38
39
  /**
39
40
  * Every route a Platform operation mirrors, from the exported `<domain>.schemas.ts` next to each
@@ -48,6 +49,7 @@ export const ROUTE_SCHEMAS = [
48
49
  ...ADMIN_CATALOG_ROUTES,
49
50
  ...MARKETPLACE_ROUTES,
50
51
  ...CONNECTOR_ROUTES,
52
+ ...OAUTH_ROUTES,
51
53
  ...COMPONENT_SCOPE_ROUTES,
52
54
  ...ORG_EXTENSION_ROUTES,
53
55
  ...CONVERSATION_ROUTES,
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+ import { type Principal } from "../identity/principal.js";
3
+ import { type OrgContext } from "../orgs/org.guard.js";
4
+ import { SealedReveals } from "./sealed-reveals.js";
5
+ declare const ApprovalParams: z.ZodObject<{
6
+ approvalId: z.ZodString;
7
+ }, z.core.$strip>;
8
+ /**
9
+ * The link of an invitation an org admin's agent created (platform web parity spec §7.2): shown
10
+ * once, on the web, to the person who approved the `orgs.invite` call. A POST because reading
11
+ * consumes it.
12
+ */
13
+ export declare class SealedRevealsController {
14
+ private readonly reveals;
15
+ constructor(reveals: SealedReveals);
16
+ reveal(principal: Principal, org: OrgContext, params: z.infer<typeof ApprovalParams>): Promise<{
17
+ url: string;
18
+ }>;
19
+ }
20
+ export {};
@@ -0,0 +1,48 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Controller, HttpCode, Inject, Post } from "@nestjs/common";
11
+ import { z } from "zod";
12
+ import { CurrentPrincipal, requireUser, SessionOnly, } from "../identity/principal.js";
13
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
14
+ import { ZParam } from "../infra/validation/zod-params.js";
15
+ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
16
+ import { SealedReveals } from "./sealed-reveals.js";
17
+ const ApprovalParams = z.object({ approvalId: z.string().min(1).max(100) });
18
+ class ApprovalParamsDto extends createZodDto(ApprovalParams, "InvitationLinkParams") {
19
+ }
20
+ /**
21
+ * The link of an invitation an org admin's agent created (platform web parity spec §7.2): shown
22
+ * once, on the web, to the person who approved the `orgs.invite` call. A POST because reading
23
+ * consumes it.
24
+ */
25
+ let SealedRevealsController = class SealedRevealsController {
26
+ reveals;
27
+ constructor(reveals) {
28
+ this.reveals = reveals;
29
+ }
30
+ async reveal(principal, org, params) {
31
+ const p = requireUser(principal);
32
+ return this.reveals.reveal(org.orgId, params.approvalId, p.account.id);
33
+ }
34
+ };
35
+ __decorate([
36
+ Post(),
37
+ HttpCode(200),
38
+ OrgAction("org.invitations.manage"),
39
+ SessionOnly(),
40
+ __param(0, CurrentPrincipal()),
41
+ __param(1, CurrentOrg()),
42
+ __param(2, ZParam(ApprovalParamsDto))
43
+ ], SealedRevealsController.prototype, "reveal", null);
44
+ SealedRevealsController = __decorate([
45
+ Controller("api/v1/orgs/:orgId/approvals/:approvalId/invitation-link"),
46
+ __param(0, Inject(SealedReveals))
47
+ ], SealedRevealsController);
48
+ export { SealedRevealsController };
@@ -0,0 +1,52 @@
1
+ import { type Keyring } from "../ctx/secrets.js";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
+ import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import { TransactionHost } from "../infra/database/transaction-host.js";
6
+ /**
7
+ * How long a sealed invitation link waits for its reader, like a generated initial password: the
8
+ * approving person reads it right after the call runs; one never read expires (revoke the
9
+ * invitation and invite again).
10
+ */
11
+ export declare const SEALED_REVEAL_TTL_MS: number;
12
+ /** The tool key of the approval an invitation link belongs to. */
13
+ export declare const INVITE_TOOL_KEY = "Platform:orgs.invite";
14
+ /** Where a sealed value is delivered: the approved tool call and the person who approved. */
15
+ export interface SealedRevealDelivery {
16
+ conversationId: string;
17
+ /** The run of the call: a call id is unique only within its run. */
18
+ runId: string;
19
+ callId: string;
20
+ /** The account that may read it: the actor who confirmed the call. */
21
+ recipientAccountId: string;
22
+ }
23
+ /** The web path of an invitation link (apps/web `invitePath`). */
24
+ export declare const invitationPath: (token: string) => string;
25
+ /**
26
+ * Values a Platform call makes that only the person who approved the call may read (platform web
27
+ * parity spec §7.2, plan ruling R10): the token of an invitation an org admin's agent created. The
28
+ * token never reaches the model, the tool result, the event log, the audit or a log line: it is
29
+ * sealed with the master keyring in the creation's transaction and read once, on the web, by the
30
+ * person who approved the call, like the generated initial password (`InitialPasswords`).
31
+ */
32
+ export declare class SealedReveals {
33
+ private readonly db;
34
+ readonly txHost: TransactionHost;
35
+ private readonly keyring;
36
+ private readonly config;
37
+ constructor(db: KernelDb, txHost: TransactionHost, keyring: Keyring, config: KernelConfigService);
38
+ /** Seals an invitation's token for `to`, in the caller's (the creation's) transaction. */
39
+ sealIn(orgId: string, invitationId: string, token: string, to: SealedRevealDelivery): Promise<void>;
40
+ /**
41
+ * The link of the invitation an approved `orgs.invite` call created, read once by the person who
42
+ * approved it (`approvalId` in `orgId`, decided by `accountId`), then deleted. Anything else (not
43
+ * that person, not approved, not run yet, read already, expired, the invitation no longer
44
+ * pending) is `invitation.link_unavailable`, saying nothing about which. Audits the read
45
+ * (without the token). The URL is absolute under `http.publicUrl`, else the web path.
46
+ */
47
+ reveal(orgId: string, approvalId: string, accountId: string): Promise<{
48
+ url: string;
49
+ }>;
50
+ }
51
+ /** Deletes the sealed reveals past `expires_at`; returns how many. */
52
+ export declare function deleteExpiredSealedReveals(db: KernelSchemaDb): Promise<number>;
@@ -0,0 +1,153 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { platformSealedRevealAad as aadOf } from "../ctx/secrets.js";
13
+ import { ApiError } from "../errors.js";
14
+ import { audit } from "../identity/audit.js";
15
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { TransactionHost } from "../infra/database/transaction-host.js";
18
+ import { Transactional } from "../infra/database/transactional.decorator.js";
19
+ import { KEYRING } from "../infra/tokens.js";
20
+ /**
21
+ * How long a sealed invitation link waits for its reader, like a generated initial password: the
22
+ * approving person reads it right after the call runs; one never read expires (revoke the
23
+ * invitation and invite again).
24
+ */
25
+ export const SEALED_REVEAL_TTL_MS = 24 * 60 * 60 * 1000;
26
+ /** The tool key of the approval an invitation link belongs to. */
27
+ export const INVITE_TOOL_KEY = "Platform:orgs.invite";
28
+ /** The web path of an invitation link (apps/web `invitePath`). */
29
+ export const invitationPath = (token) => `/invite/${encodeURIComponent(token)}`;
30
+ /**
31
+ * Values a Platform call makes that only the person who approved the call may read (platform web
32
+ * parity spec §7.2, plan ruling R10): the token of an invitation an org admin's agent created. The
33
+ * token never reaches the model, the tool result, the event log, the audit or a log line: it is
34
+ * sealed with the master keyring in the creation's transaction and read once, on the web, by the
35
+ * person who approved the call, like the generated initial password (`InitialPasswords`).
36
+ */
37
+ let SealedReveals = class SealedReveals {
38
+ db;
39
+ txHost;
40
+ keyring;
41
+ config;
42
+ constructor(db, txHost, keyring, config) {
43
+ this.db = db;
44
+ this.txHost = txHost;
45
+ this.keyring = keyring;
46
+ this.config = config;
47
+ }
48
+ /** Seals an invitation's token for `to`, in the caller's (the creation's) transaction. */
49
+ async sealIn(orgId, invitationId, token, to) {
50
+ const plain = Buffer.from(token, "utf8");
51
+ const { data, masterKeyId } = this.keyring.wrap(plain, aadOf(invitationId));
52
+ plain.fill(0);
53
+ await this.db
54
+ .insertInto("platform_sealed_reveals")
55
+ .values({
56
+ id: invitationId,
57
+ kind: "invitation_link",
58
+ org_id: orgId,
59
+ recipient_account_id: to.recipientAccountId,
60
+ conversation_id: to.conversationId,
61
+ run_id: to.runId,
62
+ call_id: to.callId,
63
+ master_key_id: masterKeyId,
64
+ ciphertext: data,
65
+ // the DB clock, the same one reveal and the cleanup compare against
66
+ expires_at: sql `now() + make_interval(secs => ${SEALED_REVEAL_TTL_MS / 1000})`,
67
+ })
68
+ .execute();
69
+ }
70
+ /**
71
+ * The link of the invitation an approved `orgs.invite` call created, read once by the person who
72
+ * approved it (`approvalId` in `orgId`, decided by `accountId`), then deleted. Anything else (not
73
+ * that person, not approved, not run yet, read already, expired, the invitation no longer
74
+ * pending) is `invitation.link_unavailable`, saying nothing about which. Audits the read
75
+ * (without the token). The URL is absolute under `http.publicUrl`, else the web path.
76
+ */
77
+ async reveal(orgId, approvalId, accountId) {
78
+ const unavailable = () => new ApiError("invitation.link_unavailable", "No invitation link to show: it was shown already, has expired, the invitation is no longer pending, or it was not created by a call you approved");
79
+ const approval = await this.db
80
+ .selectFrom("approvals")
81
+ .select(["conversation_id", "run_id", "call_id", "tool_key", "status", "decided_by"])
82
+ .where("id", "=", approvalId)
83
+ .where("org_id", "=", orgId)
84
+ .executeTakeFirst();
85
+ if (approval === undefined ||
86
+ approval.tool_key !== INVITE_TOOL_KEY ||
87
+ approval.status !== "approved" ||
88
+ approval.decided_by !== accountId) {
89
+ throw unavailable();
90
+ }
91
+ // exactly the row of this approval's call, for a still pending invitation: deleted as read
92
+ const row = await this.db
93
+ .deleteFrom("platform_sealed_reveals")
94
+ .where("kind", "=", "invitation_link")
95
+ .where("org_id", "=", orgId)
96
+ .where("conversation_id", "=", approval.conversation_id)
97
+ .where("run_id", "=", approval.run_id)
98
+ .where("call_id", "=", approval.call_id)
99
+ .where("recipient_account_id", "=", accountId)
100
+ .where("expires_at", ">", sql `now()`)
101
+ .where((eb) => eb.exists(eb
102
+ .selectFrom("invitations")
103
+ .select("invitations.id")
104
+ .whereRef("invitations.id", "=", "platform_sealed_reveals.id")
105
+ .where("invitations.accepted_at", "is", null)
106
+ .where("invitations.revoked_at", "is", null)
107
+ .where(sql `invitations.expires_at > now()`)))
108
+ .returning(["id", "master_key_id", "ciphertext"])
109
+ .executeTakeFirst();
110
+ if (row === undefined)
111
+ throw unavailable();
112
+ let token;
113
+ try {
114
+ token = this.keyring
115
+ .unwrap(row.master_key_id, Buffer.from(row.ciphertext), aadOf(row.id))
116
+ .toString("utf8");
117
+ }
118
+ catch {
119
+ throw unavailable();
120
+ }
121
+ await audit(this.db.db, {
122
+ actorAccountId: accountId,
123
+ orgId,
124
+ action: "org.invitation.link_shown",
125
+ target: row.id,
126
+ detail: { approvalId },
127
+ });
128
+ const base = this.config.get().http.publicUrl?.replace(/\/+$/, "") ?? "";
129
+ return { url: `${base}${invitationPath(token)}` };
130
+ }
131
+ };
132
+ __decorate([
133
+ Transactional({ propagation: "mandatory" })
134
+ ], SealedReveals.prototype, "sealIn", null);
135
+ __decorate([
136
+ Transactional()
137
+ ], SealedReveals.prototype, "reveal", null);
138
+ SealedReveals = __decorate([
139
+ Injectable(),
140
+ __param(0, Inject(KernelDb)),
141
+ __param(1, Inject(TransactionHost)),
142
+ __param(2, Inject(KEYRING)),
143
+ __param(3, Inject(KernelConfigService))
144
+ ], SealedReveals);
145
+ export { SealedReveals };
146
+ /** Deletes the sealed reveals past `expires_at`; returns how many. */
147
+ export async function deleteExpiredSealedReveals(db) {
148
+ const r = await db
149
+ .deleteFrom("platform_sealed_reveals")
150
+ .where("expires_at", "<=", sql `now()`)
151
+ .executeTakeFirst();
152
+ return Number(r.numDeletedRows);
153
+ }
@@ -121,25 +121,30 @@ export async function readProjectKnowledge(files, target, opts = {}) {
121
121
  return cannot(projectUnavailable.notDirectory(root));
122
122
  const out = { project, root, skills: [] };
123
123
  const agentsMd = `${root}/AGENTS.md`;
124
- try {
125
- const read = await files.readFile(agentsMd, AGENTS_MD_MAX_BYTES);
126
- // none: a project with skills only, nothing to say (spec §4.7)
127
- if (read !== null) {
128
- const capped = capAgentsMd(decoder.decode(read.data), read.truncated);
129
- out.agentsMd = capped.text;
130
- if (capped.cut)
131
- out.agentsMdTruncated = true;
132
- }
133
- }
134
- catch (e) {
135
- if (r.fatal(e))
136
- throw e;
137
- r.log("project AGENTS.md could not be read; left out this run", {
138
- path: agentsMd,
139
- reason: messageOf(e),
140
- });
141
- }
142
- const skills = await readSkills(files, root, r);
124
+ // each read is a device round trip of its own: AGENTS.md and the skills go at the same time
125
+ const [, skills] = await Promise.all([
126
+ (async () => {
127
+ try {
128
+ const read = await files.readFile(agentsMd, AGENTS_MD_MAX_BYTES);
129
+ // none: a project with skills only, nothing to say (spec §4.7)
130
+ if (read !== null) {
131
+ const capped = capAgentsMd(decoder.decode(read.data), read.truncated);
132
+ out.agentsMd = capped.text;
133
+ if (capped.cut)
134
+ out.agentsMdTruncated = true;
135
+ }
136
+ }
137
+ catch (e) {
138
+ if (r.fatal(e))
139
+ throw e;
140
+ r.log("project AGENTS.md could not be read; left out this run", {
141
+ path: agentsMd,
142
+ reason: messageOf(e),
143
+ });
144
+ }
145
+ })(),
146
+ readSkills(files, root, r),
147
+ ]);
143
148
  out.skills = skills.skills;
144
149
  if (skills.truncated)
145
150
  out.skillsTruncated = true;
@@ -152,7 +152,11 @@ export declare class PermissionFacts {
152
152
  * The project snapshot that decides the working root of the conversation tree rooted at
153
153
  * `rootConversationId` (project root spec §4.3): its latest `project_root` event, read only when
154
154
  * the conversation is bound to a project (a free conversation reads one row by its key). Null:
155
- * free, or bound with no snapshot recorded yet.
155
+ * free. A bound conversation with no snapshot recorded yet (its first run start could not ask
156
+ * the device: offline, or the read hit its time limit) works in the bound root: the binding was
157
+ * checked when the conversation was created and never changes, and `workingRootOf` still
158
+ * applies the mode, reach and home rules. Only a recorded `unavailable` snapshot (or one
159
+ * without a root) leaves the project for free mode (spec §4.3).
156
160
  */
157
161
  workingProject(orgId: string, rootConversationId: string): Promise<WorkingProject | null>;
158
162
  /** The workspace root of a conversation's latest `device_paths` event, or null. */
@@ -342,7 +342,11 @@ let PermissionFacts = class PermissionFacts {
342
342
  * The project snapshot that decides the working root of the conversation tree rooted at
343
343
  * `rootConversationId` (project root spec §4.3): its latest `project_root` event, read only when
344
344
  * the conversation is bound to a project (a free conversation reads one row by its key). Null:
345
- * free, or bound with no snapshot recorded yet.
345
+ * free. A bound conversation with no snapshot recorded yet (its first run start could not ask
346
+ * the device: offline, or the read hit its time limit) works in the bound root: the binding was
347
+ * checked when the conversation was created and never changes, and `workingRootOf` still
348
+ * applies the mode, reach and home rules. Only a recorded `unavailable` snapshot (or one
349
+ * without a root) leaves the project for free mode (spec §4.3).
346
350
  */
347
351
  async workingProject(orgId, rootConversationId) {
348
352
  const conv = await this.db
@@ -364,7 +368,9 @@ let PermissionFacts = class PermissionFacts {
364
368
  .orderBy("seq", "desc")
365
369
  .limit(1)
366
370
  .executeTakeFirst();
367
- if (row === undefined || typeof row.root !== "string")
371
+ if (row === undefined)
372
+ return { root: conv.project_path, unavailable: false };
373
+ if (typeof row.root !== "string")
368
374
  return null;
369
375
  return { root: row.root, unavailable: row.unavailable !== false };
370
376
  }
@@ -66,6 +66,11 @@ export interface SetupGuideDocument {
66
66
  kind: "channel-connection" | "connector";
67
67
  id: string;
68
68
  } | null;
69
+ /**
70
+ * The drift hash of this mode and audience: what `channels.guide-ack` takes (admin audience, the
71
+ * connection's mode) once the person confirms the app is updated.
72
+ */
73
+ hash: string;
69
74
  webPath: string;
70
75
  /** What stays with the person, and where they do it. */
71
76
  handover: string;
@@ -277,8 +277,9 @@ let SetupGuidesService = class SetupGuidesService {
277
277
  checks: g.checks.map((c) => ({ id: c.id, label: c.label })),
278
278
  unresolved: g.unresolved,
279
279
  target: g.target,
280
+ hash: g.hash,
280
281
  webPath,
281
- handover: `Secrets (tokens, signing secrets, client secrets) are typed by the person into their fields on ${webPath}; never ask for one in the conversation. Connecting a personal account and confirming the app was updated (the guide acknowledgement) also happen on that page.`,
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
283
  };
283
284
  }
284
285
  };
@@ -1042,7 +1042,7 @@ let ApprovalsService = class ApprovalsService {
1042
1042
  throw inputsNotExpected();
1043
1043
  const problems = person.flatMap((f) => {
1044
1044
  const v = Object.hasOwn(inputs, f.path) ? inputs[f.path] : undefined;
1045
- const problem = v === undefined ? `${f.label} is required.` : checkPersonValue(f, v);
1045
+ const problem = v === undefined ? `${f.label.en} is required.` : checkPersonValue(f, v);
1046
1046
  return problem === null ? [] : [{ path: f.path, problem }];
1047
1047
  });
1048
1048
  if (problems.length > 0) {
@@ -1,10 +1,11 @@
1
1
  import { ToolError } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
+ import { ToolViewSchema } from "../../conversations/events.js";
3
4
  import { availability, PLATFORM_UNAVAILABLE_OFF, } from "../../platform/availability.js";
4
5
  import { errorRoleOf, errorsFor, nextStepFor, OPERATION_ERROR_NEXT, resolveNext, sentence, toToolError, } from "../../platform/errors.js";
5
6
  import { PLATFORM_METHOD } from "../../platform/method.js";
6
7
  import { OPERATION_ID, operationDomain, PRECHECK_TIMEOUT_MS, } from "../../platform/operation.js";
7
- import { planPersonFields } from "../../platform/person-fields.js";
8
+ import { PersonFieldsRefused, planPersonFields, } from "../../platform/person-fields.js";
8
9
  import { SealedInputsExpiredError } from "../../platform/sealed-inputs.js";
9
10
  import { BUILTIN } from "../builtin-names.js";
10
11
  /**
@@ -144,6 +145,45 @@ const capped = (items) => ({
144
145
  hint: "Narrow the query or pass params.cursor where the operation pages.",
145
146
  }),
146
147
  });
148
+ /**
149
+ * The operation's link card for this result (platform web parity spec §6), or null. A throw or an
150
+ * invalid card leaves it out with a warning: the result stands either way.
151
+ */
152
+ function handoffOf(op, params, result, ctx, log) {
153
+ if (op.handoff === undefined)
154
+ return null;
155
+ try {
156
+ const view = op.handoff(params, result, ctx);
157
+ if (view === null)
158
+ return null;
159
+ const parsed = ToolViewSchema.safeParse(view);
160
+ if (parsed.success && parsed.data.kind === "handoff")
161
+ return parsed.data;
162
+ log?.warn("platform operation returned an invalid handoff card; left out", {
163
+ operation: op.id,
164
+ });
165
+ }
166
+ catch (e) {
167
+ log?.warn("platform operation handoff failed; card left out", {
168
+ operation: op.id,
169
+ error: e instanceof Error ? e.message : String(e),
170
+ });
171
+ }
172
+ return null;
173
+ }
174
+ /**
175
+ * A link card's path is in the result text for the model too (`reviewUrl`, spec §6), unless the
176
+ * operation already returned one.
177
+ */
178
+ function withReviewUrl(out, view) {
179
+ if (view === null || view.target.type !== "link")
180
+ return out;
181
+ if (typeof out !== "object" || out === null || Array.isArray(out))
182
+ return out;
183
+ if ("reviewUrl" in out)
184
+ return out;
185
+ return { ...out, reviewUrl: view.target.url };
186
+ }
147
187
  /** An operation's result as a JSON object: a bare list is capped, nothing becomes `{ ok: true }`. */
148
188
  function asResult(value) {
149
189
  if (Array.isArray(value))
@@ -304,6 +344,8 @@ export function platformTool(deps) {
304
344
  remember: personFields === null && cls === "personal" && op.rememberable !== false,
305
345
  summary,
306
346
  ...(personFields !== null && { personFields }),
347
+ // its result is shown once to the approver: only the person may confirm it
348
+ ...(op.revealsToApprover === true && { personOnly: true }),
307
349
  };
308
350
  }
309
351
  async function run(raw, ctx) {
@@ -466,14 +508,15 @@ export function platformTool(deps) {
466
508
  deps.log?.warn("platform operation did not use the person's values", { operation: op.id });
467
509
  lines.push(unusedValuesText(op.id));
468
510
  }
469
- if (lines.length === 0)
470
- return json(asResult(result), summary);
511
+ const view = handoffOf(op, params, result, octx, deps.log);
512
+ const out = withReviewUrl(asResult(result), view);
471
513
  return {
472
514
  content: [
473
- { type: "text", text: JSON.stringify(asResult(result)) },
474
- { type: "text", text: lines.join("\n") },
515
+ { type: "text", text: JSON.stringify(out) },
516
+ ...(lines.length === 0 ? [] : [{ type: "text", text: lines.join("\n") }]),
475
517
  ],
476
518
  display: { summary },
519
+ ...(view !== null && { view }),
477
520
  };
478
521
  }
479
522
  function read(topic) {
@@ -499,9 +542,6 @@ export function platformTool(deps) {
499
542
  },
500
543
  };
501
544
  }
502
- /** A person-field plan that refuses the call (model-visible English). */
503
- class PersonFieldsRefused extends Error {
504
- }
505
545
  /** The fields to enter differ from what the person confirmed ({@link PERSON_FIELDS_CHANGED_TEXT}). */
506
546
  class PersonFieldsChanged extends Error {
507
547
  }