@capybara-hq/kernel 0.1.0-rc.118 → 0.1.0-rc.119

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 (52) hide show
  1. package/dist/automations/unattended.d.ts +2 -0
  2. package/dist/automations/unattended.js +10 -3
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/cards.d.ts +2 -4
  5. package/dist/channels/cards.js +11 -6
  6. package/dist/channels/phrases.d.ts +4 -0
  7. package/dist/channels/phrases.js +1 -0
  8. package/dist/conversations/conversations.service.js +2 -0
  9. package/dist/conversations/events.d.ts +26 -0
  10. package/dist/conversations/events.js +27 -4
  11. package/dist/ctx/create-ctx.d.ts +1 -1
  12. package/dist/ctx/create-ctx.js +4 -0
  13. package/dist/db/kernel-schema.d.ts +17 -1
  14. package/dist/device-access/device-access.module.js +2 -0
  15. package/dist/device-access/device-access.service.d.ts +16 -2
  16. package/dist/device-access/device-access.service.js +59 -2
  17. package/dist/device-access/site-access-request.d.ts +14 -0
  18. package/dist/device-access/site-access-request.js +35 -0
  19. package/dist/device-access/site-grants.d.ts +53 -0
  20. package/dist/device-access/site-grants.js +268 -0
  21. package/dist/device-access/site-grants.module.d.ts +2 -0
  22. package/dist/device-access/site-grants.module.js +14 -0
  23. package/dist/devices/devices.service.js +2 -0
  24. package/dist/extensions/admin-ops.js +7 -0
  25. package/dist/extensions/org-config.js +4 -0
  26. package/dist/extensions/permission-set.d.ts +3 -0
  27. package/dist/extensions/permission-set.js +5 -0
  28. package/dist/extensions/permission-view.d.ts +1 -1
  29. package/dist/extensions/permission-view.js +7 -1
  30. package/dist/orgs/offboarding.js +2 -0
  31. package/dist/roles/worker.module.js +2 -0
  32. package/dist/sandbox/loopback-expiry.job.d.ts +3 -1
  33. package/dist/sandbox/loopback-expiry.job.js +9 -3
  34. package/dist/sandbox/operation-authority.d.ts +1 -1
  35. package/dist/sandbox/operation-authority.js +14 -6
  36. package/dist/sandbox/permission-call-types.d.ts +2 -2
  37. package/dist/sandbox/review/classifier.d.ts +13 -4
  38. package/dist/sandbox/review/classifier.js +73 -22
  39. package/dist/sandbox/review/permission-candidate.d.ts +3 -3
  40. package/dist/sandbox/review/permission-candidate.js +10 -8
  41. package/dist/sandbox/review/review.service.d.ts +26 -19
  42. package/dist/sandbox/review/review.service.js +69 -15
  43. package/dist/tools/approvals.service.d.ts +30 -4
  44. package/dist/tools/approvals.service.js +143 -12
  45. package/dist/tools/call-scope.d.ts +3 -0
  46. package/dist/tools/call-scope.js +1 -0
  47. package/dist/tools/network-asks.js +7 -0
  48. package/dist/tools/pipeline.d.ts +16 -5
  49. package/dist/tools/pipeline.js +314 -11
  50. package/dist/tools/tools.module.js +2 -0
  51. package/package.json +2 -2
  52. package/src/migrations/0205_device_site_grants.sql +30 -0
@@ -74,6 +74,8 @@ export interface UnattendedRun {
74
74
  export declare const unattendedRules: (u: UnattendedRun | null | undefined) => u is UnattendedRun;
75
75
  /** In `fail` mode, an unattended run never waits for a person (§7). */
76
76
  export declare const unattendedFails: (u: UnattendedRun | null | undefined) => boolean;
77
+ /** An automation invocation with no person present, regardless of grant eligibility. */
78
+ export declare function hasUnattendedTaskRun(db: KernelSchemaDb, runId: string): Promise<boolean>;
77
79
  /**
78
80
  * The automation context of a run's tool calls (`PolicyContext.unattended`), or null when the
79
81
  * run is attended: it serves no task run, or a person's message joined it ({@link personJoined}).
@@ -150,6 +150,15 @@ async function personJoined(db, runId) {
150
150
  .executeTakeFirst();
151
151
  return row?.joined === true;
152
152
  }
153
+ async function taskRunWithAttendance(db, runId) {
154
+ const run = await unattendedTaskRunOf(db, runId);
155
+ return run !== null && !run.trial && (await personJoined(db, runId)) ? null : run;
156
+ }
157
+ /** An automation invocation with no person present, regardless of grant eligibility. */
158
+ export async function hasUnattendedTaskRun(db, runId) {
159
+ const run = await taskRunWithAttendance(db, runId);
160
+ return run !== null && !run.trial;
161
+ }
153
162
  /**
154
163
  * The automation context of a run's tool calls (`PolicyContext.unattended`), or null when the
155
164
  * run is attended: it serves no task run, or a person's message joined it ({@link personJoined}).
@@ -158,11 +167,9 @@ async function personJoined(db, runId) {
158
167
  * else the org's default.
159
168
  */
160
169
  export async function unattendedRunOf(db, config, orgId, runId) {
161
- const run = await unattendedTaskRunOf(db, runId);
170
+ const run = await taskRunWithAttendance(db, runId);
162
171
  if (run === null)
163
172
  return null;
164
- if (!run.trial && (await personJoined(db, runId)))
165
- return null;
166
173
  const s = await readAutomationSettings(db, config, orgId);
167
174
  // org-filter: the task id is read from the kernel run's own automation_run_id, never input
168
175
  const own = await db
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.93";
211
+ readonly sdk: "0.1.0-rc.94";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -97,10 +97,8 @@ export declare function commandCardText(detail: Pick<CommandAskDetail, "kind" |
97
97
  workingRoot?: string;
98
98
  }, scopes: readonly string[], locale: ChannelLocale, redact?: (s: string) => string): NetworkCardText;
99
99
  /**
100
- * The `bind` card of a secure input request (or an approval whose Platform call needs the person
101
- * to type secrets): the values pass only through the web, never an IM vendor, so IM gets a link to
102
- * the conversation instead of an approval card. Undefined when the approval does not exist or has
103
- * no person fields.
100
+ * The web handoff for approvals with person fields and for site approvals. The channel gets a
101
+ * link to the conversation and the sensitive request stays on the web.
104
102
  */
105
103
  export declare function personFieldsCard(d: CardDeps, approvalId: string, base: string, locale: ChannelLocale): Promise<Extract<ChannelCard, {
106
104
  kind: "bind";
@@ -325,13 +325,18 @@ export function commandCardText(detail, scopes, locale, redact = (s) => s) {
325
325
  };
326
326
  }
327
327
  /**
328
- * The `bind` card of a secure input request (or an approval whose Platform call needs the person
329
- * to type secrets): the values pass only through the web, never an IM vendor, so IM gets a link to
330
- * the conversation instead of an approval card. Undefined when the approval does not exist or has
331
- * no person fields.
328
+ * The web handoff for approvals with person fields and for site approvals. The channel gets a
329
+ * link to the conversation and the sensitive request stays on the web.
332
330
  */
333
331
  export async function personFieldsCard(d, approvalId, base, locale) {
334
332
  const v = await d.approvals.describe(approvalId);
333
+ if (v?.kind === "network" && v.detail?.kind === "site") {
334
+ return {
335
+ kind: "bind",
336
+ text: phrase("siteApprovalOnWeb", locale),
337
+ url: `${base}${v.conversationPath}`,
338
+ };
339
+ }
335
340
  const n = v?.personFields?.length ?? 0;
336
341
  if (!v || n === 0)
337
342
  return undefined;
@@ -352,8 +357,8 @@ export async function personFieldsCard(d, approvalId, base, locale) {
352
357
  */
353
358
  export async function approvalCard(d, approvalId, base, locale, redact) {
354
359
  const v = await d.approvals.describe(approvalId);
355
- // a secure input is web-only: never an approval card, only the bind link (personFieldsCard)
356
- if (!v || v.kind === "secure_input")
360
+ // Web-only approvals use the bind link from personFieldsCard.
361
+ if (!v || v.kind === "secure_input" || v.detail?.kind === "site")
357
362
  return undefined;
358
363
  const decidedBy = await displayName(d.db, v.decidedBy);
359
364
  // a network, git or command ask names what it asks about instead of a tool call (same shape)
@@ -92,6 +92,10 @@ export declare const CHANNEL_PHRASES: {
92
92
  readonly zh: "需要你的批准";
93
93
  readonly en: "Approval required";
94
94
  };
95
+ readonly siteApprovalOnWeb: {
96
+ readonly zh: "请在网页上审批此网站操作";
97
+ readonly en: "Review this site action on the web";
98
+ };
95
99
  /** A network ask's card title for one host (`{host}`; network ask-to-allow spec §6.5). */
96
100
  readonly networkTitleOne: {
97
101
  readonly zh: "智能体想访问 {host},允许吗?";
@@ -78,6 +78,7 @@ export const CHANNEL_PHRASES = {
78
78
  },
79
79
  /** 审批卡片的标题与随附文本。 */
80
80
  approvalTitle: { zh: "需要你的批准", en: "Approval required" },
81
+ siteApprovalOnWeb: { zh: "请在网页上审批此网站操作", en: "Review this site action on the web" },
81
82
  /** A network ask's card title for one host (`{host}`; network ask-to-allow spec §6.5). */
82
83
  networkTitleOne: {
83
84
  zh: "智能体想访问 {host},允许吗?",
@@ -14,6 +14,7 @@ import { AgentLookup, visibleTo } from "../agents/agent-lookup.js";
14
14
  import { avatarView } from "../agents/avatar-view.js";
15
15
  import { unbindConversation } from "../channels/threads.js";
16
16
  import { oweConversationDeletedNotice } from "../device-access/conversation-notices.js";
17
+ import { revokeSiteGrantsOfConversation } from "../device-access/site-grants.js";
17
18
  import { ConversationDevices, } from "../devices/conversation-devices.js";
18
19
  import { DeviceProjectFilesService } from "../devices/device-project-files.service.js";
19
20
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
@@ -669,6 +670,7 @@ let ConversationsService = class ConversationsService {
669
670
  orgId,
670
671
  rootConversationId: conversationId,
671
672
  });
673
+ await revokeSiteGrantsOfConversation(this.db.db, { orgId, rootConversationId: conversationId });
672
674
  }
673
675
  /** 读会话:非所有者、或 agent 已对所有者不可用 → `conversation.not_found`。 */
674
676
  async get(orgId, conversationId, viewerAccountId) {
@@ -367,6 +367,7 @@ export declare const ReviewRecordSchema: z.ZodObject<{
367
367
  "loopback-port": "loopback-port";
368
368
  "outside-sandbox": "outside-sandbox";
369
369
  sensitive: "sensitive";
370
+ "site-access": "site-access";
370
371
  }>>;
371
372
  }, z.core.$strict>;
372
373
  /** The display-only `approval_requested.command` facts of a `command` ask (auto mode spec §5.4). */
@@ -847,6 +848,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
847
848
  "directories-and-hosts": "directories-and-hosts";
848
849
  "loopback-port": "loopback-port";
849
850
  "sandbox-escalation": "sandbox-escalation";
851
+ "site-access": "site-access";
850
852
  }>;
851
853
  escalation: z.ZodOptional<z.ZodObject<{
852
854
  justification: z.ZodString;
@@ -870,8 +872,21 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
870
872
  host: "host";
871
873
  "loopback-port": "loopback-port";
872
874
  "outside-sandbox": "outside-sandbox";
875
+ "site-access": "site-access";
873
876
  }>>;
874
877
  sensitive: z.ZodOptional<z.ZodArray<z.ZodString>>;
878
+ site: z.ZodOptional<z.ZodObject<{
879
+ service: z.ZodString;
880
+ action: z.ZodEnum<{
881
+ evaluate: "evaluate";
882
+ "permission-grant": "permission-grant";
883
+ "storage-clear": "storage-clear";
884
+ "storage-read": "storage-read";
885
+ }>;
886
+ origin: z.ZodString;
887
+ detailSha256: z.ZodString;
888
+ attempt: z.ZodNumber;
889
+ }, z.core.$strip>>;
875
890
  loopback: z.ZodOptional<z.ZodObject<{
876
891
  service: z.ZodString;
877
892
  port: z.ZodNumber;
@@ -1527,6 +1542,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1527
1542
  "loopback-port": "loopback-port";
1528
1543
  "outside-sandbox": "outside-sandbox";
1529
1544
  sensitive: "sensitive";
1545
+ "site-access": "site-access";
1530
1546
  }>>;
1531
1547
  }, z.core.$strict>>;
1532
1548
  loadedTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -1696,6 +1712,16 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1696
1712
  sandbox: "sandbox";
1697
1713
  }>;
1698
1714
  }, z.core.$strict>>;
1715
+ site: z.ZodOptional<z.ZodObject<{
1716
+ service: z.ZodString;
1717
+ action: z.ZodEnum<{
1718
+ evaluate: "evaluate";
1719
+ "permission-grant": "permission-grant";
1720
+ "storage-clear": "storage-clear";
1721
+ "storage-read": "storage-read";
1722
+ }>;
1723
+ origin: z.ZodString;
1724
+ }, z.core.$strip>>;
1699
1725
  loopback: z.ZodOptional<z.ZodObject<{
1700
1726
  service: z.ZodString;
1701
1727
  port: z.ZodNumber;
@@ -1,5 +1,5 @@
1
1
  import { posix } from "node:path";
2
- import { CARD_BADGE_MAX, CARD_TEXT_MAX, CONTEXT_LIMITS, DOCUMENT_MEDIA_TYPES, hasControlChars, IMAGE_MEDIA_TYPES, isAttachmentId, isFileId, isSkillName, MEDIA_NAME_MAX_CHARS, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
+ import { CARD_BADGE_MAX, CARD_TEXT_MAX, CONTEXT_LIMITS, DOCUMENT_MEDIA_TYPES, hasControlChars, IMAGE_MEDIA_TYPES, isAttachmentId, isFileId, isSkillName, MEDIA_NAME_MAX_CHARS, SITE_ACCESS_ACTIONS, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
3
3
  import { z } from "zod";
4
4
  import { AgentDefinitionSchema, DisabledSkillRef, DisabledToolRef, ModelRef, } from "../agents/definition.js";
5
5
  import { ORG_ROLES } from "../orgs/roles.js";
@@ -456,7 +456,7 @@ export const ReviewRecordSchema = z
456
456
  * Not model-visible, so it needs no DriftReason.
457
457
  */
458
458
  crossing: z
459
- .enum(["directory", "host", "outside-sandbox", "sensitive", "loopback-port"])
459
+ .enum(["directory", "host", "outside-sandbox", "sensitive", "loopback-port", "site-access"])
460
460
  .optional(),
461
461
  })
462
462
  .strict();
@@ -852,7 +852,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
852
852
  binding: PermissionCallBindingSchema,
853
853
  permissionScope: PermissionExpansionSchema,
854
854
  targetPath: z.string().max(4096).optional(),
855
- scopeKind: z.enum(["directories-and-hosts", "sandbox-escalation", "loopback-port"]),
855
+ scopeKind: z.enum([
856
+ "directories-and-hosts",
857
+ "sandbox-escalation",
858
+ "loopback-port",
859
+ "site-access",
860
+ ]),
856
861
  /** A per-call sandbox escalation: the model's justification (its scope is empty). */
857
862
  escalation: PermissionEscalationSchema.optional(),
858
863
  candidateHash: z.string(),
@@ -864,13 +869,24 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
864
869
  */
865
870
  decisionSource: z.enum(["review-model", "rule", "full-access"]),
866
871
  /** The crossing reviewed (approval-only profiles design); not model-visible. */
867
- crossing: z.enum(["directory", "host", "outside-sandbox", "loopback-port"]).optional(),
872
+ crossing: z
873
+ .enum(["directory", "host", "outside-sandbox", "loopback-port", "site-access"])
874
+ .optional(),
868
875
  /** The sensitive-command consents (rule ids) a Full access auto-grant skipped; not model-visible. */
869
876
  sensitive: z.array(z.string()).optional(),
870
877
  /**
871
878
  * A loopback port grant's review (`scopeKind: "loopback-port"`): the device service and the
872
879
  * port it asked to reach on the person's own device. Not model-visible.
873
880
  */
881
+ site: z
882
+ .object({
883
+ service: z.string(),
884
+ action: z.enum(SITE_ACCESS_ACTIONS),
885
+ origin: z.string().max(300),
886
+ detailSha256: z.string().regex(/^[a-f0-9]{64}$/),
887
+ attempt: z.number().int().positive(),
888
+ })
889
+ .optional(),
874
890
  loopback: z
875
891
  .object({
876
892
  service: z.string(),
@@ -1546,6 +1562,13 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1546
1562
  * to reach on the person's own device and whether it is a well-known database port. Display
1547
1563
  * only, never model-visible, as `network`.
1548
1564
  */
1565
+ site: z
1566
+ .object({
1567
+ service: z.string(),
1568
+ action: z.enum(SITE_ACCESS_ACTIONS),
1569
+ origin: z.string().max(300),
1570
+ })
1571
+ .optional(),
1549
1572
  loopback: z
1550
1573
  .object({
1551
1574
  service: z.string(),
@@ -103,7 +103,7 @@ export interface KernelDeps {
103
103
  };
104
104
  }
105
105
  /** What `ctx.deviceAccess` calls through (`DeviceAccessService`). */
106
- export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "streamTicket" | "addNetworkHosts" | "answerHandoff" | "grantLoopbackPort" | "revokeLoopbackPort" | "loopbackPorts">;
106
+ export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "requestSiteAccess" | "siteGrants" | "revokeSiteGrant" | "streamTicket" | "addNetworkHosts" | "answerHandoff" | "grantLoopbackPort" | "revokeLoopbackPort" | "loopbackPorts">;
107
107
  /** What `ctx.triggers` calls through (`TriggerEventsService`). */
108
108
  export type TriggersBackend = Pick<TriggerEventsService, "emit" | "causeOf">;
109
109
  /** What `ctx.inbox` calls through (`InboxItemsService`). */
@@ -420,6 +420,7 @@ identity = { sha256: null }) {
420
420
  superseded: () => disposing || lifecycle.signal.aborted,
421
421
  // read from the approved manifest: an upgrade adding it waits for approval again
422
422
  loopbackPorts: perms.deviceAccess?.loopbackPorts === true,
423
+ siteAccess: perms.deviceAccess?.siteAccess === true,
423
424
  };
424
425
  const backend = () => {
425
426
  const b = deps.deviceAccess?.();
@@ -437,6 +438,9 @@ identity = { sha256: null }) {
437
438
  grantLoopbackPort: async (scope) => backend().grantLoopbackPort(caller, scope),
438
439
  revokeLoopbackPort: async (scope) => backend().revokeLoopbackPort(caller, scope),
439
440
  loopbackPorts: async (scope) => backend().loopbackPorts(caller, scope),
441
+ requestSiteAccess: (call, ask) => backend().requestSiteAccess(caller, call, ask),
442
+ siteGrants: async (scope) => backend().siteGrants(caller, scope),
443
+ revokeSiteGrant: async (scope) => backend().revokeSiteGrant(caller, scope),
440
444
  };
441
445
  })()
442
446
  : undefined;
@@ -1,4 +1,4 @@
1
- import type { CacheWriteByTtl, ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
1
+ import type { CacheWriteByTtl, ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SiteAccessAction, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
2
2
  import type { ColumnType, Generated, Kysely } from "kysely";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
4
  import type { AutomationChat, AutomationEventMarker, AutomationMode, AutomationOrigin, AutomationPauseReason, AutomationPrincipal, AutomationStatus, AutomationTrigger, AutomationUnattendedAsk, ScheduleMarker, TaskRunSkipReason, TaskRunStatus } from "../automations/types.js";
@@ -1323,6 +1323,21 @@ export interface DeviceLoopbackGrantsTable {
1323
1323
  revoked_at: TsNullable;
1324
1324
  revoke_reason: Generated<"revoked" | "expired" | "conversation-deleted" | "outside-sandbox-off" | null>;
1325
1325
  }
1326
+ /** Durable, human-approved consent for one origin and action in a conversation tree. */
1327
+ export interface DeviceSiteGrantsTable {
1328
+ id: string;
1329
+ org_id: string;
1330
+ device_id: string;
1331
+ service_id: string;
1332
+ /** The root conversation. */
1333
+ conversation_id: string;
1334
+ origin: string;
1335
+ action: SiteAccessAction;
1336
+ approval_id: ColumnType<string | null, string, string | null>;
1337
+ created_at: Ts;
1338
+ expires_at: ColumnType<Date, Date | string, Date | string>;
1339
+ revoked_at: TsNullable;
1340
+ }
1326
1341
  /** 0088_environments.sql, renamed in 0105: the device a member's new conversations use by default. */
1327
1342
  export interface DeviceDefaultsTable {
1328
1343
  org_id: string;
@@ -2067,6 +2082,7 @@ export interface KernelDatabase {
2067
2082
  device_projects: DeviceProjectsTable;
2068
2083
  device_conversation_notices: DeviceConversationNoticesTable;
2069
2084
  device_loopback_grants: DeviceLoopbackGrantsTable;
2085
+ device_site_grants: DeviceSiteGrantsTable;
2070
2086
  background_tasks: BackgroundTasksTable;
2071
2087
  automations: AutomationsTable;
2072
2088
  automation_runs: AutomationRunsTable;
@@ -11,6 +11,7 @@ import { SandboxProviderRegistryModule } from "../sandbox/providers.module.js";
11
11
  import { SandboxModule } from "../sandbox/sandbox.module.js";
12
12
  import { ToolsModule } from "../tools/tools.module.js";
13
13
  import { DeviceAccessService } from "./device-access.service.js";
14
+ import { DeviceSiteGrantsModule } from "./site-grants.module.js";
14
15
  import { DEVICE_ACCESS_BACKEND } from "./token.js";
15
16
  /**
16
17
  * `ctx.deviceAccess` (browser use spec §7): {@link DeviceAccessService}. The extension host finds
@@ -30,6 +31,7 @@ ExtensionDeviceAccessModule = __decorate([
30
31
  DevicesModule,
31
32
  ToolsModule,
32
33
  ExtensionRegistryModule,
34
+ DeviceSiteGrantsModule,
33
35
  ],
34
36
  providers: [
35
37
  DeviceAccessService,
@@ -1,4 +1,4 @@
1
- import { type DeviceAccessScope, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type LoopbackGrantView, type ServiceBlockedHost, type ToolCallContext } from "@capybara-hq/plugin-sdk";
1
+ import { type DeviceAccessScope, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type LoopbackGrantView, type ServiceBlockedHost, type SiteAccessAction, type SiteAccessAsk, type SiteGrantView, type ToolCallContext } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { DeviceAccess } from "../devices/access.js";
4
4
  import { ConversationDevices } from "../devices/conversation-devices.js";
@@ -13,6 +13,7 @@ import { DeviceProviders } from "../sandbox/providers.js";
13
13
  import { CommandReviewService } from "../sandbox/review/review.service.js";
14
14
  import { ApprovalsService } from "../tools/approvals.service.js";
15
15
  import { QuestionsService } from "../tools/questions.service.js";
16
+ import { DeviceSiteGrants } from "./site-grants.js";
16
17
  /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
17
18
  export declare const DEVICE_ACCESS_NOT_OWNER_TEXT = "Browser tools only run for the conversation's owner on their own device.";
18
19
  /** A viewer ticket's key prefix (`capk:device-stream-ticket:<id>`, single use, GETDEL). */
@@ -47,6 +48,7 @@ export interface DeviceAccessCaller {
47
48
  * be granted local ports of the device (browser loopback port grants design).
48
49
  */
49
50
  loopbackPorts: boolean;
51
+ siteAccess?: boolean;
50
52
  }
51
53
  /**
52
54
  * `ctx.deviceAccess` (browser use spec §7): an extension's device services in the conversation's
@@ -76,9 +78,10 @@ export declare class DeviceAccessService {
76
78
  private readonly loopback;
77
79
  /** A panel grant settles the agent's pending ask for the same port. */
78
80
  private readonly approvals;
81
+ private readonly site;
79
82
  constructor(kdb: KernelDb, redis: Redis, config: Pick<KernelConfigService, "get">, services: DeviceServices, review: Pick<CommandReviewService, "review">, devices: Pick<ConversationDevices, "forTool" | "reviewFacts">, access: Pick<DeviceAccess, "usable">, deviceWrites: Pick<DevicesService, "addNetworkHostsIn">, questions: Pick<QuestionsService, "answer">, providers: Pick<DeviceProviders, "forDevice">, log: Logger, registry: Pick<ExtensionRegistry, "current">, txHost: TransactionHost, loopback: Pick<LoopbackGrants, "grantIn" | "revoke" | "liveForRoot" | "refusalNow">,
80
83
  /** A panel grant settles the agent's pending ask for the same port. */
81
- approvals: Pick<ApprovalsService, "settleLoopbackAsks">);
84
+ approvals: Pick<ApprovalsService, "settleLoopbackAsks">, site: DeviceSiteGrants);
82
85
  private get db();
83
86
  /**
84
87
  * Starts the service in the call's device, or finds it running. An `ifRunning` ensure first
@@ -135,6 +138,17 @@ export declare class DeviceAccessService {
135
138
  url?: string;
136
139
  service?: string;
137
140
  }): void;
141
+ /** Report the daemon's refusal in the currently executing, owner-bound tool scope. */
142
+ requestSiteAccess(caller: DeviceAccessCaller, call: ToolCallContext, ask: SiteAccessAsk): void;
143
+ siteGrants(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
144
+ service: string;
145
+ }): Promise<SiteGrantView[]>;
146
+ revokeSiteGrant(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
147
+ service: string;
148
+ origin: string;
149
+ action: SiteAccessAction;
150
+ }): Promise<void>;
151
+ private siteGrantScope;
138
152
  /**
139
153
  * Grants the scope conversation's root a local port of its device for one service (the owner's
140
154
  * click in the panel, source `owner-panel`): owner only, refused with `loopback_unavailable`
@@ -34,6 +34,8 @@ import { ApprovalsService } from "../tools/approvals.service.js";
34
34
  import { mapSandboxError } from "../tools/builtins/sandbox/common.js";
35
35
  import { attachCallScope, callScopeOf, serviceHostKey, strongerLayer, whileDeviceStarting, } from "../tools/call-scope.js";
36
36
  import { QuestionsService } from "../tools/questions.service.js";
37
+ import { assertSiteAccessAction, siteAccessInstallActive } from "./site-access-request.js";
38
+ import { DeviceSiteGrants } from "./site-grants.js";
37
39
  /** The layers a service may report a refused host with (`ServiceBlockedHost.layer`). */
38
40
  const BLOCK_LAYERS = ["device", "org", "address", "unknown"];
39
41
  /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
@@ -113,9 +115,10 @@ let DeviceAccessService = class DeviceAccessService {
113
115
  txHost;
114
116
  loopback;
115
117
  approvals;
118
+ site;
116
119
  constructor(kdb, redis, config, services, review, devices, access, deviceWrites, questions, providers, log, registry, txHost, loopback,
117
120
  /** A panel grant settles the agent's pending ask for the same port. */
118
- approvals) {
121
+ approvals, site) {
119
122
  this.kdb = kdb;
120
123
  this.redis = redis;
121
124
  this.config = config;
@@ -131,6 +134,7 @@ let DeviceAccessService = class DeviceAccessService {
131
134
  this.txHost = txHost;
132
135
  this.loopback = loopback;
133
136
  this.approvals = approvals;
137
+ this.site = site;
134
138
  }
135
139
  get db() {
136
140
  return this.kdb.db;
@@ -457,6 +461,52 @@ let DeviceAccessService = class DeviceAccessService {
457
461
  port: entry.port,
458
462
  };
459
463
  }
464
+ /** Report the daemon's refusal in the currently executing, owner-bound tool scope. */
465
+ requestSiteAccess(caller, call, ask) {
466
+ assertCallOwner(call);
467
+ assertSiteAccessCaller(caller, ask?.service);
468
+ assertSiteAccessAction(ask.action, ask.origin);
469
+ if (typeof ask.detail !== "string" || ask.detail.length === 0 || ask.detail.length > 20_000) {
470
+ throw new DeviceAccessError("invalid_request", "Describe the site action within 20,000 characters.");
471
+ }
472
+ const scope = callScopeOf(call);
473
+ if (scope?.facts === undefined || scope.watch || scope.device === null)
474
+ return;
475
+ scope.siteAccess = {
476
+ service: ask.service,
477
+ serviceId: deviceServiceId(caller.extension, ask.service),
478
+ extension: caller.extension,
479
+ deviceId: scope.device,
480
+ origin: ask.origin,
481
+ action: ask.action,
482
+ detail: ask.detail,
483
+ };
484
+ }
485
+ async siteGrants(caller, scope) {
486
+ const { d, key } = await this.siteGrantScope(caller, scope);
487
+ if ((await this.unattendedTree(d)) ||
488
+ !(await siteAccessInstallActive(this.db, caller.extension, caller.sha256 ?? null)))
489
+ return [];
490
+ return this.site.liveForRoot(key);
491
+ }
492
+ async revokeSiteGrant(caller, scope) {
493
+ assertSiteAccessAction(scope.action, scope.origin);
494
+ const { key } = await this.siteGrantScope(caller, scope);
495
+ await this.site.revoke({ ...key, origin: scope.origin, action: scope.action }, scope.accountId);
496
+ }
497
+ async siteGrantScope(caller, scope) {
498
+ assertSiteAccessCaller(caller, scope.service);
499
+ const d = await this.scopedDevice(caller, scope);
500
+ return {
501
+ d,
502
+ key: {
503
+ orgId: d.orgId,
504
+ deviceId: d.deviceId,
505
+ rootConversationId: d.rootConversationId,
506
+ serviceId: deviceServiceId(caller.extension, scope.service),
507
+ },
508
+ };
509
+ }
460
510
  /**
461
511
  * Grants the scope conversation's root a local port of its device for one service (the owner's
462
512
  * click in the panel, source `owner-panel`): owner only, refused with `loopback_unavailable`
@@ -874,7 +924,8 @@ DeviceAccessService = __decorate([
874
924
  __param(11, Inject(ExtensionRegistry)),
875
925
  __param(12, Inject(TransactionHost)),
876
926
  __param(13, Inject(LoopbackGrants)),
877
- __param(14, Inject(ApprovalsService))
927
+ __param(14, Inject(ApprovalsService)),
928
+ __param(15, Inject(DeviceSiteGrants))
878
929
  ], DeviceAccessService);
879
930
  export { DeviceAccessService };
880
931
  /** A grant record as the extension sees it. */
@@ -903,6 +954,12 @@ function assertDeclared(caller, service) {
903
954
  if (!caller.services.includes(service))
904
955
  throw new DeviceAccessError("service_not_declared", `The device service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.services of ${caller.extension}.`);
905
956
  }
957
+ function assertSiteAccessCaller(caller, service) {
958
+ if (caller.siteAccess !== true || caller.superseded?.()) {
959
+ throw new DeviceAccessError("site_access_not_declared", "This extension does not have an active site access permission.");
960
+ }
961
+ assertDeclared(caller, service);
962
+ }
906
963
  function assertCallOwner(call) {
907
964
  if (call.ownerAccountId === undefined || call.accountId !== call.ownerAccountId)
908
965
  throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT);
@@ -0,0 +1,14 @@
1
+ import { type SiteAccessAction, type SiteAccessAsk } from "@capybara-hq/plugin-sdk";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ /** The request reported from a particular device service, bound to the call that sent it. */
4
+ export interface ReportedSiteAccess extends SiteAccessAsk {
5
+ extension: string;
6
+ serviceId: string;
7
+ deviceId: string;
8
+ }
9
+ export declare function isSiteAccessOrigin(origin: unknown): origin is string;
10
+ /** Refuse malformed requests before retaining any detail in the call or the approval. */
11
+ export declare function assertSiteAccessAction(action: SiteAccessAction, origin: string): void;
12
+ export declare const siteAccessDetailHash: (detail: string) => string;
13
+ /** Installed code can still be loaded after a deployment update. Bind to the desired package. */
14
+ export declare function siteAccessInstallActive(db: KernelSchemaDb, extension: string, sha256: string | null, lock?: boolean): Promise<boolean>;
@@ -0,0 +1,35 @@
1
+ import { createHash } from "node:crypto";
2
+ import { DeviceAccessError, isLoopbackGrantHost, SITE_ACCESS_ACTIONS, } from "@capybara-hq/plugin-sdk";
3
+ export function isSiteAccessOrigin(origin) {
4
+ if (typeof origin !== "string" || origin.length > 300)
5
+ return false;
6
+ try {
7
+ const parsed = new URL(origin);
8
+ return ((parsed.protocol === "https:" || parsed.protocol === "http:") &&
9
+ parsed.origin === origin &&
10
+ !isLoopbackGrantHost(parsed.hostname.replace(/^\[(.*)\]$/, "$1")));
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ /** Refuse malformed requests before retaining any detail in the call or the approval. */
17
+ export function assertSiteAccessAction(action, origin) {
18
+ if (!SITE_ACCESS_ACTIONS.includes(action) || !isSiteAccessOrigin(origin)) {
19
+ throw new DeviceAccessError("invalid_request", "Use a canonical HTTP(S) site origin and action.");
20
+ }
21
+ }
22
+ export const siteAccessDetailHash = (detail) => createHash("sha256").update(detail, "utf8").digest("hex");
23
+ /** Installed code can still be loaded after a deployment update. Bind to the desired package. */
24
+ export async function siteAccessInstallActive(db, extension, sha256, lock = false) {
25
+ let q = db
26
+ .selectFrom("extension_installs")
27
+ .select(["sha256", "desired_state"])
28
+ .where("name", "=", extension);
29
+ if (lock)
30
+ q = q.forShare();
31
+ const row = await q.executeTakeFirst();
32
+ return row === undefined
33
+ ? sha256 === null
34
+ : row.desired_state === "enabled" && row.sha256 === sha256;
35
+ }
@@ -0,0 +1,53 @@
1
+ import type { SiteAccessAction, SiteGrantView } from "@capybara-hq/plugin-sdk";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ export interface SiteGrantScope {
6
+ orgId: string;
7
+ deviceId: string;
8
+ /** The service id is `<extension>.<name>`. */
9
+ serviceId: string;
10
+ rootConversationId: string;
11
+ }
12
+ export interface SiteGrantKey extends SiteGrantScope {
13
+ origin: string;
14
+ action: SiteAccessAction;
15
+ }
16
+ /** Call in the deleting transaction, after locking the conversation. */
17
+ export declare function revokeSiteGrantsOfConversation(db: KernelSchemaDb, scope: {
18
+ orgId: string;
19
+ rootConversationId: string;
20
+ }): Promise<void>;
21
+ /** Call in the transaction that deletes the device, including its owner's offboarding. */
22
+ export declare function revokeSiteGrantsOfDevice(db: KernelSchemaDb, scope: {
23
+ orgId: string;
24
+ deviceId: string;
25
+ }): Promise<void>;
26
+ /** Call in the transaction disabling the extension in the org or removing its permission. */
27
+ export declare function revokeSiteGrantsOfExtension(db: KernelSchemaDb, scope: {
28
+ orgId: string;
29
+ extensionName: string;
30
+ }): Promise<void>;
31
+ /** Revoke an extension's grants when deployment state or its approved capability changes. */
32
+ export declare function revokeSiteGrantsOfExtensionEverywhere(db: KernelSchemaDb, extensionName: string): Promise<void>;
33
+ /** PostgreSQL is the only grant store. A device gets the live set with one request. */
34
+ export declare class DeviceSiteGrants {
35
+ private readonly db;
36
+ readonly txHost: TransactionHost;
37
+ constructor(db: KernelDb, txHost: TransactionHost);
38
+ /** Callers resolve the root and check the owner, service permission and attended status. */
39
+ liveForRoot(scope: SiteGrantScope): Promise<SiteGrantView[]>;
40
+ /** Advisory offer for an approval card; issuance rechecks the cap under the root row lock. */
41
+ canGrant(key: SiteGrantKey): Promise<boolean>;
42
+ /** Joins the human approval transaction. A full root can still approve the current call once. */
43
+ grantIn(key: SiteGrantKey, by: {
44
+ approvalId: string;
45
+ actorAccountId: string;
46
+ }): Promise<SiteGrantView | null>;
47
+ revoke(key: SiteGrantKey, actorAccountId: string): Promise<void>;
48
+ /** Expiry is enforced on reads; maintenance only removes old records. */
49
+ purgeEnded(): Promise<number>;
50
+ private purgeEndedIn;
51
+ private liveRootQuery;
52
+ private lockOwnedRoot;
53
+ }