@capybara-hq/kernel 0.1.0-rc.117 → 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 (106) hide show
  1. package/dist/admin/usage.service.d.ts +4 -2
  2. package/dist/admin/usage.service.js +35 -15
  3. package/dist/automations/unattended.d.ts +2 -0
  4. package/dist/automations/unattended.js +10 -3
  5. package/dist/catalog/component-scope.service.js +2 -1
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/plugin-install.d.ts +1 -0
  8. package/dist/catalog/plugin-install.js +11 -1
  9. package/dist/channels/cards.d.ts +2 -4
  10. package/dist/channels/cards.js +11 -6
  11. package/dist/channels/phrases.d.ts +4 -0
  12. package/dist/channels/phrases.js +1 -0
  13. package/dist/conversations/conversations.controller.d.ts +1 -1
  14. package/dist/conversations/conversations.controller.js +1 -1
  15. package/dist/conversations/conversations.service.d.ts +4 -2
  16. package/dist/conversations/conversations.service.js +19 -3
  17. package/dist/conversations/events.d.ts +35 -1
  18. package/dist/conversations/events.js +29 -4
  19. package/dist/ctx/create-ctx.d.ts +1 -1
  20. package/dist/ctx/create-ctx.js +4 -0
  21. package/dist/db/kernel-schema.d.ts +31 -1
  22. package/dist/device-access/device-access.module.js +2 -0
  23. package/dist/device-access/device-access.service.d.ts +16 -2
  24. package/dist/device-access/device-access.service.js +59 -2
  25. package/dist/device-access/site-access-request.d.ts +14 -0
  26. package/dist/device-access/site-access-request.js +35 -0
  27. package/dist/device-access/site-grants.d.ts +53 -0
  28. package/dist/device-access/site-grants.js +268 -0
  29. package/dist/device-access/site-grants.module.d.ts +2 -0
  30. package/dist/device-access/site-grants.module.js +14 -0
  31. package/dist/devices/devices.controller.d.ts +5 -0
  32. package/dist/devices/devices.controller.js +20 -2
  33. package/dist/devices/devices.service.d.ts +3 -1
  34. package/dist/devices/devices.service.js +6 -0
  35. package/dist/evals/plan.d.ts +3 -1
  36. package/dist/evals/plan.js +25 -5
  37. package/dist/evals/runs.service.js +3 -2
  38. package/dist/evals/trajectory.js +1 -0
  39. package/dist/extensions/admin-ops.js +7 -0
  40. package/dist/extensions/org-config.js +4 -0
  41. package/dist/extensions/permission-set.d.ts +3 -0
  42. package/dist/extensions/permission-set.js +5 -0
  43. package/dist/extensions/permission-view.d.ts +1 -1
  44. package/dist/extensions/permission-view.js +7 -1
  45. package/dist/files/blob-references.d.ts +8 -0
  46. package/dist/files/blob-references.js +19 -0
  47. package/dist/files/blob-sweep.job.js +5 -23
  48. package/dist/files/library-files.service.js +8 -4
  49. package/dist/models/cache-write-usage.d.ts +3 -0
  50. package/dist/models/cache-write-usage.js +26 -0
  51. package/dist/models/images.js +5 -1
  52. package/dist/models/prices.d.ts +8 -6
  53. package/dist/models/prices.js +28 -3
  54. package/dist/orgs/offboarding.js +2 -0
  55. package/dist/orgs/settings.controller.d.ts +4 -17
  56. package/dist/orgs/settings.controller.js +5 -9
  57. package/dist/orgs/settings.service.d.ts +12 -0
  58. package/dist/orgs/settings.service.js +24 -0
  59. package/dist/platform/exclusions.js +6 -0
  60. package/dist/platform/ops/admin.ops.js +2 -2
  61. package/dist/platform/ops/conversations.ops.js +1 -1
  62. package/dist/platform/ops/devices.ops.js +7 -0
  63. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  64. package/dist/platform/ops/org-settings.ops.js +10 -10
  65. package/dist/roles/worker.module.js +2 -0
  66. package/dist/runtime/context/build.d.ts +2 -0
  67. package/dist/runtime/context/build.js +9 -1
  68. package/dist/runtime/usage-report.js +3 -0
  69. package/dist/sandbox/legacy-retirement.d.ts +15 -0
  70. package/dist/sandbox/legacy-retirement.js +243 -3
  71. package/dist/sandbox/loopback-expiry.job.d.ts +3 -1
  72. package/dist/sandbox/loopback-expiry.job.js +9 -3
  73. package/dist/sandbox/operation-authority.d.ts +1 -1
  74. package/dist/sandbox/operation-authority.js +14 -6
  75. package/dist/sandbox/permission-call-types.d.ts +2 -2
  76. package/dist/sandbox/permission-instance-writes.d.ts +4 -1
  77. package/dist/sandbox/permission-instance-writes.js +55 -1
  78. package/dist/sandbox/providers.d.ts +6 -1
  79. package/dist/sandbox/providers.js +15 -1
  80. package/dist/sandbox/review/classifier.d.ts +13 -4
  81. package/dist/sandbox/review/classifier.js +73 -22
  82. package/dist/sandbox/review/permission-candidate.d.ts +3 -3
  83. package/dist/sandbox/review/permission-candidate.js +10 -8
  84. package/dist/sandbox/review/review.service.d.ts +26 -19
  85. package/dist/sandbox/review/review.service.js +69 -15
  86. package/dist/sandbox/sandbox.service.d.ts +6 -3
  87. package/dist/sandbox/sandbox.service.js +116 -5
  88. package/dist/tools/approvals.service.d.ts +30 -4
  89. package/dist/tools/approvals.service.js +143 -12
  90. package/dist/tools/builtins/sandbox/common.js +10 -6
  91. package/dist/tools/call-scope.d.ts +3 -0
  92. package/dist/tools/call-scope.js +1 -0
  93. package/dist/tools/connector-tools-jobs.d.ts +3 -2
  94. package/dist/tools/connectors.service.d.ts +3 -1
  95. package/dist/tools/connectors.service.js +64 -12
  96. package/dist/tools/drift.d.ts +1 -1
  97. package/dist/tools/drift.js +13 -13
  98. package/dist/tools/network-asks.js +7 -0
  99. package/dist/tools/pipeline.d.ts +16 -5
  100. package/dist/tools/pipeline.js +314 -11
  101. package/dist/tools/tools.module.js +2 -0
  102. package/package.json +2 -2
  103. package/src/migrations/0202_connector_endpoint_changed_at.sql +1 -0
  104. package/src/migrations/0203_model_cache_write_pricing.sql +5 -0
  105. package/src/migrations/0204_device_instance_retirement_identities.sql +46 -0
  106. package/src/migrations/0205_device_site_grants.sql +30 -0
@@ -67,17 +67,18 @@ import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
67
67
  import { effectiveSandboxLimits, readOrgSettings } from "../orgs/settings.service.js";
68
68
  import { isStorageError } from "../runtime/permission-context-errors.js";
69
69
  import { canonicalJson } from "../tools/canonical-json.js";
70
+ import { untilAborted } from "../until-aborted.js";
70
71
  import { attachmentsDir } from "./attachments-path.js";
71
72
  import { CloudPermissionSnapshots, } from "./cloud-permission-snapshot.js";
72
73
  import { DeviceReports } from "./device-reports.js";
73
74
  import { isKernelReadMethod, KernelReadInstanceNotRunning, KernelReadNotAdmitted, KernelReadUnsupported, } from "./kernel-read.js";
74
75
  import { SandboxLeases, SandboxLockLostError, sandboxBusy, } from "./leases.js";
75
- import { isKnownProvider, LegacyRetirementStore } from "./legacy-retirement.js";
76
+ import { isKnownProvider, LegacyRetirementStore, } from "./legacy-retirement.js";
76
77
  import { ManagedDeviceContextFailed } from "./managed-device-context.js";
77
78
  import { appliedLacksHost, appliedOf, appliedWider, installedWider, instanceLimitsJson, orgEffectiveHosts, providerLimits, readInstanceLimits, sameApplied, sameAppliedExact, sameAppliedExactly, } from "./modes.js";
78
79
  import { PermissionFacts } from "./permission-facts.js";
79
80
  import { reportOwed, supportOf } from "./permission-runtime-reports.js";
80
- import { DeviceProviders, isInProcessName, servesDialIn, } from "./providers.js";
81
+ import { DeviceProviders, isInProcessName, LOCAL_RETIREMENT_PROVIDER, localRetirementGeneration, RETIREMENT_GENERATION, servesDialIn, } from "./providers.js";
81
82
  import { isDeviceRequestNotSent } from "./request-not-sent.js";
82
83
  import { SandboxProviderUnreachableError } from "./unreachable.js";
83
84
  // Moved to leases.ts (phase C); re-exported for existing importers
@@ -88,6 +89,7 @@ const HOLDER_TTL_MARGIN_MS = 10 * 60_000;
88
89
  const PATH_LEASE_WAIT_MS = 30_000;
89
90
  /** Time limit of one provider call in maintenance (suspend, destroy). */
90
91
  const SWEEP_OP_TIMEOUT_MS = 120_000;
92
+ const RETIREMENT_CHECK_TIMEOUT_MS = 15_000;
91
93
  /** How long a cloud device's lifecycle reconcile waits before the sweep tries it again (B-12). */
92
94
  const RECONCILE_RETRY_SECONDS = 600;
93
95
  /**
@@ -292,7 +294,9 @@ export const retirementPending = () => new RetirementPendingError("device.unavai
292
294
  * will ever cover it (an incarnation replaced without a recorded confirmed destruction, or an
293
295
  * unknown one it cannot clear) (503, 8.5): the owner deletes the device and creates it again.
294
296
  */
295
- export const recreateRequired = () => new RetirementPendingError("device.recreate_required", "Background work started by an earlier version may still be running on an earlier instance of this device, and that instance can no longer be verified as destroyed. Delete this device and create it again.");
297
+ export const recreateRequired = (local = false) => new RetirementPendingError("device.recreate_required", local
298
+ ? "Earlier background work on the connected machine has not been confirmed stopped. If you own this device, open its device page and choose Check again."
299
+ : "Background work started by an earlier version may still be running on an earlier instance of this device, and that instance can no longer be verified as destroyed. Delete this device and create it again.", local ? [{ reason: "local_retirement" }] : undefined);
296
300
  const isRetirementPending = (err) => err instanceof RetirementPendingError;
297
301
  const abortReason = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
298
302
  function sleep(ms, signal) {
@@ -2362,6 +2366,106 @@ let SandboxService = class SandboxService {
2362
2366
  await lease.release();
2363
2367
  }
2364
2368
  }
2369
+ /** The owner's proof-only pass of the retirement gate, with no provider lifecycle mutation. */
2370
+ async checkLocalRetirement(owner, requested) {
2371
+ const { orgId, deviceId, accountId } = owner;
2372
+ if (!(await this.ownerLocalProvider(owner)))
2373
+ return "blocked";
2374
+ const lease = await this.leases.tryExclusive(deviceId, { unlessStreams: true });
2375
+ if (!lease)
2376
+ return "busy";
2377
+ const signal = AbortSignal.any([
2378
+ requested,
2379
+ lease.signal,
2380
+ AbortSignal.timeout(RETIREMENT_CHECK_TIMEOUT_MS),
2381
+ ]);
2382
+ try {
2383
+ const p = await this.ownerLocalProvider(owner);
2384
+ const attest = p?.impl.retirement;
2385
+ if (!p || !attest || signal.aborted)
2386
+ return "blocked";
2387
+ if (!(await this.retirement.hasUnresolved(deviceId)))
2388
+ return "clear";
2389
+ const row = await this.readRow(owner);
2390
+ if (!row?.handle ||
2391
+ row.handle.id !== deviceId ||
2392
+ row.provider !== p.plugin ||
2393
+ !row.had_instance ||
2394
+ (row.status !== "running" && row.status !== "suspended"))
2395
+ return "blocked";
2396
+ const currentGeneration = String(row.created_at.getTime());
2397
+ const currentProviderGeneration = localRetirementGeneration(p, row.handle, deviceId);
2398
+ if (!RETIREMENT_GENERATION.test(currentGeneration) || currentProviderGeneration === undefined)
2399
+ return "blocked";
2400
+ const machine = await this.db
2401
+ .selectFrom("device_machines")
2402
+ .select("id")
2403
+ .where("org_id", "=", orgId)
2404
+ .where("device_id", "=", deviceId)
2405
+ .where("account_id", "=", accountId)
2406
+ .where("revoked_at", "is", null)
2407
+ .executeTakeFirst();
2408
+ if (!machine || signal.aborted)
2409
+ return "blocked";
2410
+ const fence = { gen: row.generation };
2411
+ await this.fenced(lease, deviceId, fence, {});
2412
+ const check = {
2413
+ ...owner,
2414
+ machineId: machine.id,
2415
+ currentGeneration,
2416
+ fence: fence.gen,
2417
+ };
2418
+ for (const o of await this.retirement.quarantinedLocal(check)) {
2419
+ if (signal.aborted)
2420
+ break;
2421
+ const recorded = await this.retirement.destructionRecorded(deviceId, o.provider, o.instanceGeneration);
2422
+ const providerGeneration = recorded
2423
+ ? undefined
2424
+ : await this.retirement.localProviderGeneration(o);
2425
+ if (!recorded) {
2426
+ if (providerGeneration === undefined ||
2427
+ BigInt(providerGeneration) >= BigInt(currentProviderGeneration))
2428
+ continue;
2429
+ const confirmed = await untilAborted(Promise.resolve().then(() => attest.attestRetired(deviceId, providerGeneration, signal)), signal).catch(() => false);
2430
+ if (confirmed !== true)
2431
+ continue;
2432
+ }
2433
+ if (signal.aborted || !(await lease.renew()))
2434
+ break;
2435
+ if (!(await this.selection.isOnInOrg(orgId, p.plugin)))
2436
+ break;
2437
+ await this.retirement.resolveLocalProof(check, o, providerGeneration, signal);
2438
+ }
2439
+ return (await this.retirement.hasUnresolved(deviceId)) ? "blocked" : "clear";
2440
+ }
2441
+ catch (err) {
2442
+ if (signal.aborted || err instanceof SandboxLockLostError)
2443
+ return "blocked";
2444
+ throw err;
2445
+ }
2446
+ finally {
2447
+ await lease.release();
2448
+ }
2449
+ }
2450
+ async ownerLocalProvider(owner) {
2451
+ const row = await this.db
2452
+ .selectFrom("devices")
2453
+ .select("provider")
2454
+ .where("org_id", "=", owner.orgId)
2455
+ .where("id", "=", owner.deviceId)
2456
+ .where("owner_kind", "=", "personal")
2457
+ .where("owner_account_id", "=", owner.accountId)
2458
+ .where("deleted_at", "is", null)
2459
+ .executeTakeFirst();
2460
+ if (!row)
2461
+ throw deviceNotFound();
2462
+ if (row.provider !== LOCAL_RETIREMENT_PROVIDER)
2463
+ return undefined;
2464
+ const p = this.providers.forDevice(row.provider);
2465
+ return p && servesDialIn(p) && (await this.selection.isOnInOrg(owner.orgId, p.plugin))
2466
+ ? p
2467
+ : undefined;
2468
+ }
2365
2469
  /**
2366
2470
  * The worker's retirement of a device's old incarnations (8.5, `RetireLegacyTasksJob`): one try
2367
2471
  * at the exclusive lifecycle lease, then the same gate as every acquisition. `busy`: a holder
@@ -2957,7 +3061,9 @@ let SandboxService = class SandboxService {
2957
3061
  else if (still !== null && resumed !== undefined)
2958
3062
  resumed.resumed = true;
2959
3063
  if (pending)
2960
- throw failed ? retirementPending() : recreateRequired();
3064
+ throw failed
3065
+ ? retirementPending()
3066
+ : recreateRequired(now?.provider === LOCAL_RETIREMENT_PROVIDER);
2961
3067
  return now;
2962
3068
  }
2963
3069
  /**
@@ -3287,6 +3393,11 @@ let SandboxService = class SandboxService {
3287
3393
  // instance has none yet (NULL): its first commit is no roots change (no consent reset, no
3288
3394
  // revoke)
3289
3395
  const committedRoots = row.permission_roots ?? (row.handle ? rootsOf(row.handle) : null);
3396
+ const previousGeneration = row.handle && row.had_instance && row.provider === p.plugin
3397
+ ? localRetirementGeneration(p, row.handle, id)
3398
+ : undefined;
3399
+ if (previousGeneration !== undefined)
3400
+ await runOutsideTransaction(() => this.instanceWrites.preserveRetirementIdentity(ctx.orgId, id, fence.gen, previousGeneration, held.signal));
3290
3401
  await this.fenced(held, id, fence, {
3291
3402
  org_id: ctx.orgId,
3292
3403
  provider: p.plugin,
@@ -3373,7 +3484,7 @@ let SandboxService = class SandboxService {
3373
3484
  running_since: sql `now()`,
3374
3485
  last_used_at: sql `now()`,
3375
3486
  ...(!atFileSystem && { instance_limits: record }),
3376
- }, held.signal, support));
3487
+ }, held.signal, support, localRetirementGeneration(p, handle, id)));
3377
3488
  fence.gen++;
3378
3489
  }
3379
3490
  catch (e) {
@@ -1,15 +1,18 @@
1
- import { type LocalizedName, type ToolDisplay } from "@capybara-hq/plugin-sdk";
1
+ import { type LocalizedName, type SiteAccessAction, type ToolDisplay } from "@capybara-hq/plugin-sdk";
2
2
  import { AutomationStore } from "../automations/store.js";
3
3
  import { EventLog } from "../conversations/event-log.js";
4
4
  import { type EventPayload, type ReviewRecord, type ToolView } from "../conversations/events.js";
5
5
  import { ConversationLeakCheck } from "../conversations/leak-check.js";
6
+ import { DeviceSiteGrants } from "../device-access/site-grants.js";
6
7
  import { DevicesService } from "../devices/devices.service.js";
8
+ import { ExtensionRegistry } from "../extensions/registry.js";
7
9
  import { type PersonRef } from "../identity/account-avatar.js";
8
10
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
9
11
  import { KernelDb } from "../infra/database/kernel-db.js";
10
12
  import { TransactionHost } from "../infra/database/transaction-host.js";
11
13
  import { KernelEvents } from "../infra/events/kernel-events.js";
12
14
  import { LockService } from "../infra/lock/lock.service.js";
15
+ import { OrgLock } from "../orgs/org-lock.js";
13
16
  import { type OrgRole } from "../orgs/roles.js";
14
17
  import type { FileCardDetail } from "../platform/file-ref.js";
15
18
  import { type PersonFieldSpec } from "../platform/person-fields.js";
@@ -128,14 +131,28 @@ export interface LoopbackAskDetail extends Omit<NetworkAskDetailBase, "appliesAt
128
131
  /** What took effect once approved: the root conversation's grant. */
129
132
  outcome?: "session";
130
133
  }
134
+ /** An owner decision for one site action of a device service. */
135
+ export interface SiteAskDetail extends Omit<NetworkAskDetailBase, "appliesAt" | "grantedHosts" | "outcome"> {
136
+ kind: "site";
137
+ extension: string;
138
+ rootConversationId: string;
139
+ service: string;
140
+ action: SiteAccessAction;
141
+ origin: string;
142
+ detail: string;
143
+ attempt: number;
144
+ toolSpecHash: string;
145
+ callInputHash: string;
146
+ outcome?: "once" | "session";
147
+ }
131
148
  /** A network ask's `detail`: a command's, a device service's, or a loopback port's. */
132
- export type NetworkAskDetail = CommandNetworkAskDetail | ServiceNetworkAskDetail | LoopbackAskDetail;
149
+ export type NetworkAskDetail = CommandNetworkAskDetail | ServiceNetworkAskDetail | LoopbackAskDetail | SiteAskDetail;
133
150
  /** `Omit` over each member of a union. */
134
151
  type OmitEach<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
135
152
  /** A network ask's detail as the API shows it: without the kept call result. */
136
153
  export type NetworkAskView = OmitEach<NetworkAskDetail, "result">;
137
154
  /** The hosts a network ask asked about, whichever kind it is (a loopback port ask: none). */
138
- export declare function networkAskHosts(detail: Pick<CommandNetworkAskDetail, "hosts" | "kind"> | Pick<ServiceNetworkAskDetail, "hosts" | "kind"> | Pick<LoopbackAskDetail, "kind">): string[];
155
+ export declare function networkAskHosts(detail: Pick<CommandNetworkAskDetail, "hosts" | "kind"> | Pick<ServiceNetworkAskDetail, "hosts" | "kind"> | Pick<LoopbackAskDetail, "kind"> | Pick<SiteAskDetail, "kind">): string[];
139
156
  /**
140
157
  * A git push ask's `detail` (sandbox git credentials spec §7): the host, the repository
141
158
  * (`<owner>/<repo>`, normalized) and the refs of the push the gateway held, the command that ran
@@ -448,6 +465,10 @@ export interface NetworkAskInput {
448
465
  export type LoopbackAskInput = Omit<NetworkAskInput, "detail" | "scopes"> & {
449
466
  detail: LoopbackAskDetail;
450
467
  };
468
+ export type SiteAskInput = Omit<NetworkAskInput, "detail" | "scopes"> & {
469
+ detail: SiteAskDetail;
470
+ scopes: ("once" | "session")[];
471
+ };
451
472
  /** The tool key a git ask is recorded under (the push ran in a `Bash` command). */
452
473
  export declare const GIT_ASK_TOOL_KEY = "Bash";
453
474
  /**
@@ -517,6 +538,9 @@ export declare class ApprovalsService {
517
538
  private readonly permissionGrants?;
518
539
  /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
519
540
  private readonly loopback?;
541
+ private readonly site?;
542
+ private readonly orgLock?;
543
+ private readonly extensions?;
520
544
  constructor(db: KernelDb, config: Pick<KernelConfigService, "get">, eventLog: Pick<EventLog, "appendIn" | "notify">, events: Pick<KernelEvents, "emit">, txHost: TransactionHost, automations: Pick<AutomationStore, "addGrant">,
521
545
  /** A trial approval is kept only for a tool the task may hold as a grant (its agent's tools). */
522
546
  registry: Pick<ToolRegistry, "forAgent">,
@@ -533,7 +557,7 @@ export declare class ApprovalsService {
533
557
  /** A network ask's "add to this device's list" writes the device's own network list. */
534
558
  devices: Pick<DevicesService, "lockNetworkAddSubject" | "addNetworkHostsIn">, permissionLocks?: PermissionAuthorityLock | undefined, permissionGrants?: PermissionCallGrants | undefined,
535
559
  /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
536
- loopback?: Pick<LoopbackGrants, "grantIn" | "refusalNow" | "liveLockedIn"> | undefined);
560
+ loopback?: Pick<LoopbackGrants, "grantIn" | "refusalNow" | "liveLockedIn"> | undefined, site?: DeviceSiteGrants | undefined, orgLock?: OrgLock | undefined, extensions?: Pick<ExtensionRegistry, "current"> | undefined);
537
561
  /**
538
562
  * 新建 pending 审批(`expires_at` = 现在 + `tools.approvalTimeoutHours`)并写 `approval_requested`,同一事务。
539
563
  * 按 (run_id, call_id, attempt) 幂等:已存在则返回已有记录(不覆盖),事件按 `approval_requested:<approvalId>` 幂等。
@@ -567,6 +591,7 @@ export declare class ApprovalsService {
567
591
  * second request returns the first (whatever its kind).
568
592
  */
569
593
  requestLoopback(input: LoopbackAskInput): Promise<ApprovalRecord>;
594
+ requestSiteAccess(input: SiteAskInput, recordReview: () => Promise<void>): Promise<ApprovalRecord>;
570
595
  private requestNetworkIn;
571
596
  /**
572
597
  * A git push ask (sandbox git credentials spec §7): a pending approval of kind `git` for the
@@ -612,6 +637,7 @@ export declare class ApprovalsService {
612
637
  * resumes the run in its transaction and is announced after the commit.
613
638
  */
614
639
  private decideNetwork;
640
+ private decideSiteIn;
615
641
  /**
616
642
  * A loopback port ask's decision (browser loopback port grants), under {@link decideNetwork}'s
617
643
  * lock and checks (the device owner, a signed-in session, still pending): an approval takes
@@ -15,24 +15,29 @@ import { normalizeStoredDefinition } from "../agents/definition.js";
15
15
  import { readAutomationSettings } from "../automations/effective-settings.js";
16
16
  import { GIT_GRANT_SPEC_HASH, gitGrantRefusal, gitPushGrantKey, grantRefusalOf, NETWORK_GRANT_PREFIX, NETWORK_GRANT_SPEC_HASH, networkGrantRefusal, normalizeGitRepo, } from "../automations/grant-rules.js";
17
17
  import { AutomationStore } from "../automations/store.js";
18
- import { unattendedTaskRunOf } from "../automations/unattended.js";
18
+ import { unattendedRunOf, unattendedTaskRunOf } from "../automations/unattended.js";
19
19
  import { EventLog } from "../conversations/event-log.js";
20
20
  import { COMMAND_ASK_TEXT_MAX_CHARS, GIT_ASK_MAX_REFS, GIT_REF_MAX_CHARS, NETWORK_ASK_MAX_HOSTS, NETWORK_HOST_MAX_CHARS, SECURE_INPUT_MAX_FIELDS, } from "../conversations/events.js";
21
21
  import { ConversationLeakCheck } from "../conversations/leak-check.js";
22
22
  import { conversationSourceOf } from "../conversations/source.js";
23
+ import { siteAccessDetailHash, siteAccessInstallActive, } from "../device-access/site-access-request.js";
24
+ import { DeviceSiteGrants } from "../device-access/site-grants.js";
23
25
  import { DevicesService } from "../devices/devices.service.js";
24
26
  import { ApiError } from "../errors.js";
27
+ import { isExtensionEnabled } from "../extensions/enabled.js";
25
28
  import { clipText } from "../extensions/hooks.js";
29
+ import { ExtensionRegistry } from "../extensions/registry.js";
26
30
  import { loadPeople } from "../identity/account-avatar.js";
27
31
  import { audit } from "../identity/audit.js";
28
32
  import { sha256Hex } from "../identity/hash.js";
29
33
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
30
34
  import { KernelDb } from "../infra/database/kernel-db.js";
31
- import { TransactionHost, withOrderedLocks, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
35
+ import { queueAfterCommit, TransactionHost, withOrderedLocks, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
32
36
  import { Transactional } from "../infra/database/transactional.decorator.js";
33
37
  import { KernelEvents } from "../infra/events/kernel-events.js";
34
38
  import { LockService } from "../infra/lock/lock.service.js";
35
39
  import { WithLock } from "../infra/lock/with-lock.decorator.js";
40
+ import { OrgLock } from "../orgs/org-lock.js";
36
41
  import { ORG_ROLES, roleAtLeast } from "../orgs/roles.js";
37
42
  import { checkPersonValue } from "../platform/person-fields.js";
38
43
  import { SealedInputs } from "../platform/sealed-inputs.js";
@@ -51,7 +56,7 @@ export { APPROVAL_DENY_REASON_MAX_CHARS } from "../conversations/events.js";
51
56
  export const APPROVALS_LIST_MAX = 100;
52
57
  /** The hosts a network ask asked about, whichever kind it is (a loopback port ask: none). */
53
58
  export function networkAskHosts(detail) {
54
- if (detail.kind === "loopback")
59
+ if (detail.kind === "loopback" || detail.kind === "site")
55
60
  return [];
56
61
  return detail.kind === "service"
57
62
  ? [...detail.hosts]
@@ -232,6 +237,9 @@ let ApprovalsService = class ApprovalsService {
232
237
  permissionLocks;
233
238
  permissionGrants;
234
239
  loopback;
240
+ site;
241
+ orgLock;
242
+ extensions;
235
243
  constructor(db, config, eventLog, events, txHost, automations,
236
244
  /** A trial approval is kept only for a tool the task may hold as a grant (its agent's tools). */
237
245
  registry,
@@ -248,7 +256,7 @@ let ApprovalsService = class ApprovalsService {
248
256
  /** A network ask's "add to this device's list" writes the device's own network list. */
249
257
  devices, permissionLocks, permissionGrants,
250
258
  /** A loopback port ask's approval writes the root conversation's grant (absent: refused). */
251
- loopback) {
259
+ loopback, site, orgLock, extensions) {
252
260
  this.db = db;
253
261
  this.config = config;
254
262
  this.eventLog = eventLog;
@@ -265,6 +273,9 @@ let ApprovalsService = class ApprovalsService {
265
273
  this.permissionLocks = permissionLocks;
266
274
  this.permissionGrants = permissionGrants;
267
275
  this.loopback = loopback;
276
+ this.site = site;
277
+ this.orgLock = orgLock;
278
+ this.extensions = extensions;
268
279
  }
269
280
  /**
270
281
  * 新建 pending 审批(`expires_at` = 现在 + `tools.approvalTimeoutHours`)并写 `approval_requested`,同一事务。
@@ -492,6 +503,13 @@ let ApprovalsService = class ApprovalsService {
492
503
  await this.eventLog.notify(record.conversationId, toSeq);
493
504
  return record;
494
505
  }
506
+ async requestSiteAccess(input, recordReview) {
507
+ await recordReview();
508
+ const { record, toSeq } = await this.requestNetworkIn(input);
509
+ if (toSeq !== null)
510
+ queueAfterCommit(() => this.eventLog.notify(record.conversationId, toSeq));
511
+ return record;
512
+ }
495
513
  async requestNetworkIn(input) {
496
514
  const hours = this.config.get().tools.approvalTimeoutHours;
497
515
  const t = this.db.db;
@@ -562,7 +580,15 @@ let ApprovalsService = class ApprovalsService {
562
580
  database: input.detail.database,
563
581
  },
564
582
  }
565
- : { network: { hosts: networkAskHosts(input.detail) } }),
583
+ : input.detail.kind === "site"
584
+ ? {
585
+ site: {
586
+ service: input.detail.service,
587
+ action: input.detail.action,
588
+ origin: input.detail.origin,
589
+ },
590
+ }
591
+ : { network: { hosts: networkAskHosts(input.detail) } }),
566
592
  requestedFor: rec.requestedFor,
567
593
  approverRole: null,
568
594
  },
@@ -974,6 +1000,21 @@ let ApprovalsService = class ApprovalsService {
974
1000
  throw new ApiError("approval.already_decided", "Approval has expired");
975
1001
  if (detail.kind === "loopback")
976
1002
  return this.decideLoopback(orgId, ask, detail, accountId, body, via, opts.panelGrantOnly);
1003
+ if (detail.kind === "site") {
1004
+ if (via !== "web") {
1005
+ throw new ApiError("auth.session_required", "Review this site action in the signed-in web app.");
1006
+ }
1007
+ const decided = await withOrderedLocks(async () => {
1008
+ if (body.decision === "approve") {
1009
+ if (!this.orgLock)
1010
+ throw new ApiError("conflict", "Site approval is unavailable");
1011
+ await this.orgLock.lock(orgId);
1012
+ await this.devices.lockNetworkAddSubject(orgId, accountId, detail.deviceId);
1013
+ }
1014
+ }, () => this.decideSiteIn(orgId, ask, detail, accountId, body, via));
1015
+ await this.announceDecided(decided.record, decided.toSeq);
1016
+ return decided.record;
1017
+ }
977
1018
  const asked = [...new Set(networkAskHosts(detail))];
978
1019
  let network;
979
1020
  if (body.decision === "approve") {
@@ -1024,6 +1065,61 @@ let ApprovalsService = class ApprovalsService {
1024
1065
  await this.announceDecided(decided.record, decided.toSeq);
1025
1066
  return decided.record;
1026
1067
  }
1068
+ async decideSiteIn(orgId, ask, detail, accountId, body, via) {
1069
+ if (body.hosts !== undefined) {
1070
+ throw new ApiError("validation_failed", "A site action takes no hosts");
1071
+ }
1072
+ const approved = body.decision === "approve";
1073
+ let scope = approved ? (body.scope ?? "once") : null;
1074
+ if (scope !== null &&
1075
+ ((scope !== "once" && scope !== "session") || !ask.scopes.includes(scope))) {
1076
+ throw new ApiError("approval.scope_not_allowed", "This site action does not offer that scope");
1077
+ }
1078
+ if (approved) {
1079
+ if (!this.site || !this.orgLock || !this.extensions) {
1080
+ throw new ApiError("conflict", "Site approval is unavailable");
1081
+ }
1082
+ const instance = this.extensions.current(detail.extension);
1083
+ const permissions = instance?.manifest.permissions?.deviceAccess;
1084
+ const active = instance !== undefined &&
1085
+ (await siteAccessInstallActive(this.db.db, detail.extension, instance.sha256, true));
1086
+ const root = await this.db
1087
+ .selectFrom("conversations")
1088
+ .select(["device_id", "account_id", "automation_id"])
1089
+ .where("org_id", "=", orgId)
1090
+ .where("id", "=", detail.rootConversationId)
1091
+ .where("deleted_at", "is", null)
1092
+ .forNoKeyUpdate()
1093
+ .executeTakeFirst();
1094
+ const unattended = await unattendedRunOf(this.db.db, this.config, orgId, ask.runId);
1095
+ if (root?.device_id !== detail.deviceId ||
1096
+ root.account_id !== accountId ||
1097
+ root.automation_id !== null ||
1098
+ (unattended !== null && !unattended.trial) ||
1099
+ !active ||
1100
+ permissions?.siteAccess !== true ||
1101
+ !permissions.services.some((name) => `${detail.extension}.${name}` === detail.service) ||
1102
+ !(await isExtensionEnabled(this.db.db, orgId, detail.extension))) {
1103
+ throw new ApiError("conflict", "This site action is no longer available");
1104
+ }
1105
+ if (scope === "session") {
1106
+ const granted = await this.site.grantIn({
1107
+ orgId,
1108
+ deviceId: detail.deviceId,
1109
+ serviceId: detail.service,
1110
+ rootConversationId: detail.rootConversationId,
1111
+ origin: detail.origin,
1112
+ action: detail.action,
1113
+ }, { approvalId: ask.id, actorAccountId: accountId });
1114
+ if (granted === null)
1115
+ scope = "once";
1116
+ }
1117
+ }
1118
+ const decision = await this.decideTx(orgId, ask.id, accountId, scope === null ? body : { ...body, scope }, undefined, { wanted: [], granted: [], outcome: scope, via });
1119
+ if ("leaked" in decision)
1120
+ throw new Error("Unexpected site approval leak outcome");
1121
+ return decision;
1122
+ }
1027
1123
  /**
1028
1124
  * A loopback port ask's decision (browser loopback port grants), under {@link decideNetwork}'s
1029
1125
  * lock and checks (the device owner, a signed-in session, still pending): an approval takes
@@ -1478,11 +1574,16 @@ let ApprovalsService = class ApprovalsService {
1478
1574
  // what took effect; run grants read grantedHosts (a loopback port ask: its grant row)
1479
1575
  detail: JSON.stringify((before.detail.kind === "loopback"
1480
1576
  ? { ...before.detail, outcome: "session" }
1481
- : {
1482
- ...before.detail,
1483
- grantedHosts: network.granted,
1484
- outcome: network.outcome === "always" ? "always" : "once",
1485
- })),
1577
+ : before.detail.kind === "site"
1578
+ ? {
1579
+ ...before.detail,
1580
+ outcome: network.outcome === "session" ? "session" : "once",
1581
+ }
1582
+ : {
1583
+ ...before.detail,
1584
+ grantedHosts: network.granted,
1585
+ outcome: network.outcome === "always" ? "always" : "once",
1586
+ })),
1486
1587
  }),
1487
1588
  ...(git?.outcome != null &&
1488
1589
  before.git !== null && {
@@ -1566,7 +1667,7 @@ let ApprovalsService = class ApprovalsService {
1566
1667
  if (git?.outcome === "once")
1567
1668
  await this.keepTrialGitGrant(before, accountId);
1568
1669
  // "Allow once" in a trial run: the task's grants (network ask-to-allow spec §8.1)
1569
- if (network?.outcome === "once") {
1670
+ if (network?.outcome === "once" && before.detail?.kind !== "site") {
1570
1671
  await this.keepTrialNetworkGrant(before, accountId, network.granted);
1571
1672
  }
1572
1673
  const written = await this.eventLog.appendIn(before.conversationId, [
@@ -1610,6 +1711,24 @@ let ApprovalsService = class ApprovalsService {
1610
1711
  await this.resumes.resumeIn(before.runId, id);
1611
1712
  return { record: toRecord(updated), toSeq: Math.max(...written.map((e) => e.seq)) };
1612
1713
  }
1714
+ if (network !== undefined && before.detail?.kind === "site") {
1715
+ await audit(t, {
1716
+ actorAccountId: accountId,
1717
+ orgId,
1718
+ action: "device.site_access_decided",
1719
+ target: before.detail.deviceId,
1720
+ detail: {
1721
+ approvalId: id,
1722
+ action: before.detail.action,
1723
+ origin: before.detail.origin,
1724
+ detailSha256: siteAccessDetailHash(before.detail.detail),
1725
+ outcome: approved ? network.outcome : "denied",
1726
+ source: "human",
1727
+ },
1728
+ });
1729
+ await this.resumes.resumeIn(before.runId, id);
1730
+ return { record: toRecord(updated), toSeq: Math.max(...written.map((e) => e.seq)) };
1731
+ }
1613
1732
  if (network !== undefined && before.detail !== null) {
1614
1733
  const asked = [...new Set(networkAskHosts(before.detail))];
1615
1734
  const refused = asked.filter((h) => !network.wanted.includes(h));
@@ -2351,6 +2470,9 @@ __decorate([
2351
2470
  __decorate([
2352
2471
  Transactional()
2353
2472
  ], ApprovalsService.prototype, "requestSecureInputIn", null);
2473
+ __decorate([
2474
+ Transactional()
2475
+ ], ApprovalsService.prototype, "requestSiteAccess", null);
2354
2476
  __decorate([
2355
2477
  Transactional()
2356
2478
  ], ApprovalsService.prototype, "requestNetworkIn", null);
@@ -2363,6 +2485,9 @@ __decorate([
2363
2485
  __decorate([
2364
2486
  WithLock({ key: "network-ask-#{1}", ttl: 60_000, waitTimeout: 45_000 })
2365
2487
  ], ApprovalsService.prototype, "decideNetwork", null);
2488
+ __decorate([
2489
+ Transactional({ propagation: "requires_new" })
2490
+ ], ApprovalsService.prototype, "decideSiteIn", null);
2366
2491
  __decorate([
2367
2492
  Transactional({ propagation: "requires_new" })
2368
2493
  ], ApprovalsService.prototype, "decideLoopbackIn", null);
@@ -2422,6 +2547,12 @@ ApprovalsService = __decorate([
2422
2547
  __param(14, Optional()),
2423
2548
  __param(14, Inject(PermissionCallGrants)),
2424
2549
  __param(15, Optional()),
2425
- __param(15, Inject(LoopbackGrants))
2550
+ __param(15, Inject(LoopbackGrants)),
2551
+ __param(16, Optional()),
2552
+ __param(16, Inject(DeviceSiteGrants)),
2553
+ __param(17, Optional()),
2554
+ __param(17, Inject(OrgLock)),
2555
+ __param(18, Optional()),
2556
+ __param(18, Inject(ExtensionRegistry))
2426
2557
  ], ApprovalsService);
2427
2558
  export { ApprovalsService };
@@ -280,11 +280,15 @@ export const OUTSIDE_SANDBOX_CEILING_TOOL_TEXT = "This device does not allow run
280
280
  const READ_BY_ID_HINT = "Attachments and artifacts of this conversation can still be read without the device: if Read is available to you, Read with file_id.";
281
281
  export const RETIREMENT_PENDING_TOOL_TEXT = `This device is unavailable: background work started by an earlier version may still run on its previous instance, which has not been confirmed destroyed yet, so nothing ran. Retry later (a cloud device becomes usable once its provider confirms the old instance destroyed), continue without the device, or ask the user to start a new conversation on another device. ${READ_BY_ID_HINT}`;
282
282
  export const RETIREMENT_RECREATE_TOOL_TEXT = `Background work started by an earlier version may still be running on an earlier instance of this device, which can no longer be verified as destroyed, so nothing ran. Ask the device's owner to delete the device and create it again, or ask the user to start a new conversation on another device. ${READ_BY_ID_HINT}`;
283
- /** The model-facing text of a retirement refusal's code (`device.unavailable` for any other). */
284
- function retirementToolText(code) {
285
- if (code === "device.recreate_required")
286
- return RETIREMENT_RECREATE_TOOL_TEXT;
287
- return RETIREMENT_PENDING_TOOL_TEXT;
283
+ const RETIREMENT_LOCAL_TOOL_TEXT = `Earlier background work on this device's connected machine has not been confirmed stopped, so nothing ran. Ask the device's owner to open the device page and choose Check again, or use another device. ${READ_BY_ID_HINT}`;
284
+ /** The model-facing text of a retirement refusal. */
285
+ function retirementToolText(error) {
286
+ if (error.code !== "device.recreate_required")
287
+ return RETIREMENT_PENDING_TOOL_TEXT;
288
+ const reason = error.details?.[0]?.reason;
289
+ if (reason === "local_retirement")
290
+ return RETIREMENT_LOCAL_TOOL_TEXT;
291
+ return RETIREMENT_RECREATE_TOOL_TEXT;
288
292
  }
289
293
  /**
290
294
  * A managed operation outside the admitted scope (`SandboxScopeDeniedError`): fixed text, never
@@ -415,7 +419,7 @@ export function mapSandboxError(e, log) {
415
419
  return new ToolError(SANDBOX_CONNECTION_DROPPED_TEXT, { kind: "unavailable" });
416
420
  }
417
421
  if (e instanceof RetirementPendingError) {
418
- return new ToolError(retirementToolText(e.code));
422
+ return new ToolError(retirementToolText(e));
419
423
  }
420
424
  if (e instanceof ApiError) {
421
425
  if (e.code === "sandbox.busy")
@@ -1,5 +1,6 @@
1
1
  import type { NetworkBlockLayer, ServiceBlockedHost, ToolCallContext } from "@capybara-hq/plugin-sdk";
2
2
  import type { ReviewRecord } from "../conversations/events.js";
3
+ import type { ReportedSiteAccess } from "../device-access/site-access-request.js";
3
4
  import type { ConversationKindForHooks } from "../runtime/hook-calls.js";
4
5
  /**
5
6
  * The call scope (browser use spec §7.1): what a tool handler's kernel services report about one
@@ -74,6 +75,8 @@ export interface CallScope {
74
75
  * says the device was still starting, not that the target failed.
75
76
  */
76
77
  starting: number;
78
+ /** The last bounded device service site action reported by the handler. */
79
+ siteAccess: ReportedSiteAccess | null;
77
80
  /**
78
81
  * Whether this call sent a request to a device service (`ctx.deviceAccess.request`): its target
79
82
  * may have acted, so a timeout never claims otherwise.
@@ -16,6 +16,7 @@ export function attachCallScope(ctx, facts, opts = {}) {
16
16
  review: null,
17
17
  blocked: null,
18
18
  starting: 0,
19
+ siteAccess: null,
19
20
  reached: false,
20
21
  ...(facts !== undefined && { facts }),
21
22
  ...(opts.watch === true && { watch: true }),
@@ -9,10 +9,11 @@ export declare const CONNECTOR_TOOLS_JOB = "connector-tools-list";
9
9
  * What owed the listing: the connector was `created` ready, it turned ready when an org admin
10
10
  * saved its missing input (`configured`), a member saved the first credential of a personal
11
11
  * connector with no tool list yet (`connected`), an org admin changed an editable endpoint
12
- * field of a ready template connector (`endpoint_changed`), or a platform update cleared the
12
+ * field of a ready template connector (`endpoint_changed`), a ready template connector with
13
+ * a stale list was enabled (`reactivated`), or a platform update cleared the
13
14
  * credentials of a template connector whose new auth leaves it ready (`template_updated`).
14
15
  */
15
- export type ConnectorToolsTrigger = "created" | "configured" | "connected" | "endpoint_changed" | "template_updated";
16
+ export type ConnectorToolsTrigger = "created" | "configured" | "connected" | "endpoint_changed" | "reactivated" | "template_updated";
16
17
  /** Data of a {@link CONNECTOR_TOOLS_JOB}; `accountId` is the member whose credential lists. */
17
18
  export interface ConnectorToolsJobData {
18
19
  orgId: string;
@@ -503,6 +503,8 @@ export declare class ConnectorsService {
503
503
  * runs in its transaction.
504
504
  */
505
505
  disableWithPluginIn(orgId: string, connectorId: string, itemId: string): Promise<void>;
506
+ /** Owe a listing before changing the row's status and legacy last-update timestamp. */
507
+ private oweStaleEndpointList;
506
508
  /**
507
509
  * Re-enables a connector the given plugin's switch-off disabled
508
510
  * ({@link disableWithPluginIn}) when the plugin is switched back on and its install takes the
@@ -564,7 +566,7 @@ export declare class ConnectorsService {
564
566
  listToolsForJob(data: ConnectorToolsJobData): Promise<"listed" | "skipped">;
565
567
  /**
566
568
  * The org-locked write of {@link listToolsForJob}; false (nothing written) when the org or the
567
- * connector is gone, disabled or `needs_config` by now.
569
+ * connector is gone, disabled, `needs_config`, or the endpoint changed.
568
570
  */
569
571
  private storeListedIn;
570
572
  /**