@capybara-hq/kernel 0.1.0-rc.84 → 0.1.0-rc.86

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 (157) hide show
  1. package/dist/admin/admin.module.js +5 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +10 -2
  4. package/dist/catalog/admin-catalog.controller.d.ts +2 -1
  5. package/dist/catalog/admin-catalog.controller.js +2 -1
  6. package/dist/catalog/catalog-content.d.ts +5 -15
  7. package/dist/catalog/catalog-content.js +5 -56
  8. package/dist/catalog/catalog-scope.service.d.ts +3 -3
  9. package/dist/catalog/catalog-scope.service.js +4 -3
  10. package/dist/catalog/catalog.module.d.ts +3 -1
  11. package/dist/catalog/catalog.module.js +14 -1
  12. package/dist/catalog/component-scope.service.d.ts +6 -1
  13. package/dist/catalog/component-scope.service.js +16 -2
  14. package/dist/catalog/job-ids.d.ts +29 -0
  15. package/dist/catalog/job-ids.js +29 -0
  16. package/dist/catalog/jobs.d.ts +12 -3
  17. package/dist/catalog/jobs.js +28 -7
  18. package/dist/catalog/marketplaces.service.d.ts +1 -1
  19. package/dist/catalog/org-catalog.controller.d.ts +2 -30
  20. package/dist/catalog/org-catalog.controller.js +3 -29
  21. package/dist/catalog/org-catalog.schemas.d.ts +9 -46
  22. package/dist/catalog/org-catalog.schemas.js +9 -23
  23. package/dist/catalog/org-catalog.service.js +14 -23
  24. package/dist/catalog/plugin-import.d.ts +21 -0
  25. package/dist/catalog/plugin-import.js +33 -3
  26. package/dist/catalog/plugin-install.d.ts +69 -76
  27. package/dist/catalog/plugin-install.js +156 -234
  28. package/dist/catalog/plugin-upgrade.d.ts +71 -11
  29. package/dist/catalog/plugin-upgrade.js +222 -43
  30. package/dist/catalog/scope-sync.d.ts +22 -20
  31. package/dist/catalog/scope-sync.js +57 -42
  32. package/dist/catalog/template-connector-ensure.d.ts +100 -0
  33. package/dist/catalog/template-connector-ensure.js +285 -0
  34. package/dist/catalog/template-connector-jobs.d.ts +28 -0
  35. package/dist/catalog/template-connector-jobs.js +54 -0
  36. package/dist/catalog/template-connector-reconcile.d.ts +44 -0
  37. package/dist/catalog/template-connector-reconcile.js +114 -0
  38. package/dist/catalog/template-connectors.processor.d.ts +32 -0
  39. package/dist/catalog/template-connectors.processor.js +101 -0
  40. package/dist/channels/cards.d.ts +7 -3
  41. package/dist/channels/cards.js +9 -4
  42. package/dist/channels/phrases.d.ts +10 -0
  43. package/dist/channels/phrases.js +10 -0
  44. package/dist/config/docs.js +1 -1
  45. package/dist/config/schema.d.ts +3 -0
  46. package/dist/config/schema.js +18 -12
  47. package/dist/ctx/create-ctx.d.ts +10 -1
  48. package/dist/ctx/create-ctx.js +42 -2
  49. package/dist/db/kernel-schema.d.ts +2 -1
  50. package/dist/device-access/device-access.module.d.ts +7 -0
  51. package/dist/device-access/device-access.module.js +41 -0
  52. package/dist/device-access/device-access.service.d.ts +142 -0
  53. package/dist/device-access/device-access.service.js +464 -0
  54. package/dist/device-access/token.d.ts +6 -0
  55. package/dist/device-access/token.js +6 -0
  56. package/dist/device-access/viewer-routes.d.ts +45 -0
  57. package/dist/device-access/viewer-routes.js +81 -0
  58. package/dist/device-access/viewer.d.ts +244 -0
  59. package/dist/device-access/viewer.js +844 -0
  60. package/dist/dial-in/access.d.ts +19 -0
  61. package/dist/dial-in/access.js +23 -0
  62. package/dist/dial-in/gateway.d.ts +48 -6
  63. package/dist/dial-in/gateway.js +145 -10
  64. package/dist/dial-in/keys.d.ts +7 -0
  65. package/dist/dial-in/keys.js +7 -0
  66. package/dist/dial-in/routes.d.ts +11 -3
  67. package/dist/dial-in/routes.js +15 -4
  68. package/dist/dial-in/streams.d.ts +58 -0
  69. package/dist/dial-in/streams.js +283 -0
  70. package/dist/errors.d.ts +2 -0
  71. package/dist/errors.js +2 -0
  72. package/dist/extensions/host.d.ts +13 -1
  73. package/dist/extensions/host.js +20 -1
  74. package/dist/extensions/org-config.d.ts +6 -1
  75. package/dist/extensions/org-config.js +15 -2
  76. package/dist/extensions/permission-set.d.ts +15 -1
  77. package/dist/extensions/permission-set.js +13 -1
  78. package/dist/extensions/permission-view.d.ts +6 -4
  79. package/dist/extensions/permission-view.js +6 -1
  80. package/dist/git/gateway.js +3 -1
  81. package/dist/http/error.filter.js +2 -0
  82. package/dist/http/gateway-routes.d.ts +8 -4
  83. package/dist/http/gateway-routes.js +4 -3
  84. package/dist/infra/lock/lock.service.d.ts +5 -1
  85. package/dist/infra/lock/lock.service.js +10 -4
  86. package/dist/infra/outbox/registry.d.ts +28 -0
  87. package/dist/infra/outbox/registry.js +33 -0
  88. package/dist/infra/queue/queue-names.d.ts +1 -1
  89. package/dist/infra/queue/queue-names.js +2 -0
  90. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  91. package/dist/infra/throttler/named-throttlers.js +16 -0
  92. package/dist/kernel.module.js +3 -0
  93. package/dist/lifecycle/kernel-lifecycle.d.ts +8 -1
  94. package/dist/lifecycle/kernel-lifecycle.js +37 -11
  95. package/dist/orgs/org-owner.d.ts +7 -0
  96. package/dist/orgs/org-owner.js +16 -0
  97. package/dist/platform/operation.d.ts +3 -4
  98. package/dist/platform/ops/connectors.ops.js +8 -1
  99. package/dist/platform/ops/org-plugins.ops.d.ts +0 -9
  100. package/dist/platform/ops/org-plugins.ops.js +18 -235
  101. package/dist/platform/ops/plugins.ops.d.ts +0 -1
  102. package/dist/platform/ops/plugins.ops.js +3 -31
  103. package/dist/roles/gateway-role.d.ts +13 -6
  104. package/dist/roles/gateway-role.js +27 -9
  105. package/dist/roles/gateway.module.d.ts +2 -1
  106. package/dist/roles/gateway.module.js +13 -3
  107. package/dist/roles/worker-role.d.ts +9 -4
  108. package/dist/roles/worker-role.js +18 -5
  109. package/dist/roles/worker.module.d.ts +1 -1
  110. package/dist/roles/worker.module.js +8 -1
  111. package/dist/sandbox/device-services.d.ts +62 -0
  112. package/dist/sandbox/device-services.js +183 -0
  113. package/dist/sandbox/leases.d.ts +18 -1
  114. package/dist/sandbox/leases.js +75 -1
  115. package/dist/sandbox/network-grants.js +5 -2
  116. package/dist/sandbox/sandbox.module.d.ts +2 -1
  117. package/dist/sandbox/sandbox.module.js +5 -2
  118. package/dist/sandbox/sandbox.service.d.ts +44 -1
  119. package/dist/sandbox/sandbox.service.js +142 -5
  120. package/dist/setup/setup-guides.service.d.ts +9 -1
  121. package/dist/setup/setup-guides.service.js +38 -8
  122. package/dist/tools/admin-connectors.d.ts +3 -2
  123. package/dist/tools/admin-connectors.js +5 -4
  124. package/dist/tools/approvals.service.d.ts +45 -20
  125. package/dist/tools/approvals.service.js +19 -9
  126. package/dist/tools/call-scope.d.ts +60 -0
  127. package/dist/tools/call-scope.js +23 -0
  128. package/dist/tools/connector-setup.d.ts +28 -0
  129. package/dist/tools/connector-setup.js +33 -0
  130. package/dist/tools/connector-tools-jobs.d.ts +35 -0
  131. package/dist/tools/connector-tools-jobs.js +40 -0
  132. package/dist/tools/connector-tools.processor.d.ts +32 -0
  133. package/dist/tools/connector-tools.processor.js +97 -0
  134. package/dist/tools/connectors.controller.d.ts +1 -0
  135. package/dist/tools/connectors.schemas.d.ts +1 -0
  136. package/dist/tools/connectors.schemas.js +5 -0
  137. package/dist/tools/connectors.service.d.ts +138 -14
  138. package/dist/tools/connectors.service.js +410 -50
  139. package/dist/tools/credentials.d.ts +35 -0
  140. package/dist/tools/credentials.js +89 -1
  141. package/dist/tools/drift.d.ts +5 -0
  142. package/dist/tools/drift.js +21 -2
  143. package/dist/tools/editable-endpoint.d.ts +23 -0
  144. package/dist/tools/editable-endpoint.js +92 -0
  145. package/dist/tools/network-asks.d.ts +13 -0
  146. package/dist/tools/network-asks.js +26 -2
  147. package/dist/tools/oauth/flow.d.ts +1 -1
  148. package/dist/tools/oauth/flow.js +3 -2
  149. package/dist/tools/pipeline.d.ts +30 -1
  150. package/dist/tools/pipeline.js +299 -59
  151. package/dist/tools/questions.service.d.ts +24 -3
  152. package/dist/tools/questions.service.js +3 -1
  153. package/dist/tools/registry.d.ts +14 -2
  154. package/dist/tools/registry.js +27 -6
  155. package/dist/tools/tools.module.js +4 -0
  156. package/package.json +3 -3
  157. package/src/migrations/0183_connectors_created_by_nullable.sql +5 -0
@@ -78,6 +78,21 @@ interface Instance {
78
78
  export type TaggedProvider = Omit<DeviceProvider, "exec"> & {
79
79
  exec(h: SandboxHandle, args: Omit<ExecArgs, "tag">): Promise<ExecResult>;
80
80
  };
81
+ /** The device service methods of a provider ({@link SandboxService.withDeviceServices}), bound. */
82
+ export type DeviceServiceMethods = Pick<DeviceProvider, "ensureService" | "stopService" | "serviceRequest" | "openStream">;
83
+ /** A device held for a stream ({@link SandboxService.holdForStream}). */
84
+ export interface StreamHold {
85
+ h: SandboxHandle;
86
+ /** The provider's `openStream`, bound. */
87
+ p: Required<Pick<DeviceProvider, "openStream">>;
88
+ /**
89
+ * Aborts when the caller's signal aborts or the hold ends (a lifecycle change of the device);
90
+ * the hold is then released.
91
+ */
92
+ signal: AbortSignal;
93
+ /** Ends the hold (idempotent): holder record cleared, lease released, `last_used_at` moved. */
94
+ release(): Promise<void>;
95
+ }
81
96
  /** What {@link SandboxService.ifRunning} did. */
82
97
  export type IfRunningResult<T> = {
83
98
  kind: "ran";
@@ -472,6 +487,31 @@ export declare class SandboxService {
472
487
  * reconcile marker under the shared lease, before any provider call (B-11).
473
488
  */
474
489
  private ifRunningAs;
490
+ /**
491
+ * Holds the device's running instance for a stream to one of its services (browser use spec
492
+ * §6.2: an open viewer counts as device use). It never creates, resumes or rebuilds an
493
+ * instance: a device without a running instance, whose provider is off in `orgId`, or that is
494
+ * in a lifecycle change (an exclusive lease or a pending intent) is refused with
495
+ * `DeviceAccessError("provider_unavailable")`; a provider without `openStream` with
496
+ * `capability_missing`.
497
+ *
498
+ * A hold is not a lease ({@link SandboxLeases.streamHold}): it takes no
499
+ * `sandbox.maxConcurrentCommands` slot and never blocks a lifecycle change. Idle suspension and
500
+ * the inactivity destruction (on any replica) skip a device with a live hold; the forced
501
+ * suspension after `maxRunningMinutes` does not. A hold yields to every lifecycle change:
502
+ * an exclusive acquisition ends the device's holds, and a pending intent makes their next
503
+ * renewal fail, so the returned `signal` aborts (also when the caller's `signal` aborts or a
504
+ * renewal deadline passes) and the hold is released. `release()` is idempotent and moves
505
+ * `last_used_at` forward, so the idle clock starts when the viewer goes.
506
+ */
507
+ holdForStream(deviceId: string, orgId: string, signal: AbortSignal): Promise<StreamHold>;
508
+ /**
509
+ * Runs `fn` with the device service methods of the device's provider (browser use spec §5),
510
+ * as any use of the device does ({@link withSandbox}: the instance is created or resumed,
511
+ * `last_used_at` moves forward). `admit` sees the provider's methods first, before any lease
512
+ * or instance work, so a provider without services is refused without touching the device.
513
+ */
514
+ withDeviceServices<T>(ctx: SandboxUseContext, admit: (p: DeviceServiceMethods) => void, fn: (h: SandboxHandle, p: DeviceServiceMethods, signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T>;
475
515
  /**
476
516
  * A short lease on one path of the device around the kernel's own read-modify-write of
477
517
  * that file (spec §10.4); waits up to 30 s, then throws `SandboxPathBusyError`. Its `signal`
@@ -693,11 +733,14 @@ export declare class SandboxService {
693
733
  revokeDeadHolder(deviceId: string, token: string): Promise<void>;
694
734
  /**
695
735
  * Suspends running instances idle longer than `suspendAfterIdleMinutes` or running continuously
696
- * longer than `maxRunningMinutes`. Skips a device with any holder; one past
736
+ * longer than `maxRunningMinutes`. Skips a device with any holder, and one with an open stream
737
+ * hold ({@link holdForStream}) unless it is past `maxRunningMinutes`; one past
697
738
  * `maxRunningMinutes` gets the intent for one poll window (about a second) first. Returns how
698
739
  * many it suspended. Called every minute by the `sandbox-suspend-idle` cron.
699
740
  */
700
741
  suspendIdle(now: Date): Promise<number>;
742
+ /** Whether the device has a live stream hold; a Redis error counts as none (the sweep goes on). */
743
+ private streamHeld;
701
744
  /** {@link suspendIdle} for the rows of one provider. */
702
745
  private suspendIdleOf;
703
746
  /**
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { posix } from "node:path";
11
- import { isDeviceOfflineError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceAccessError, isDeviceOfflineError, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationScope, parseSandboxPreparationScope, SandboxOperationOutcomeUnknownError, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
12
12
  import { asPlatform } from "../infra/database/org-scope.js";
13
13
  import { runOutsideTransaction } from "../infra/database/transaction-host.js";
14
14
  import { createHeldOperations, withKernelGeneration, } from "./held-operations.js";
@@ -124,6 +124,15 @@ function parseDeferred(raw) {
124
124
  * holder's own last fenced write committed; null without a fence (nothing to compare).
125
125
  */
126
126
  const tokenOf = (fence) => fence === null ? null : { token: fence.gen };
127
+ function serviceMethodsOf(impl) {
128
+ return {
129
+ ...(impl.ensureService && { ensureService: impl.ensureService.bind(impl) }),
130
+ ...(impl.stopService && { stopService: impl.stopService.bind(impl) }),
131
+ ...(impl.serviceRequest && { serviceRequest: impl.serviceRequest.bind(impl) }),
132
+ ...(impl.openStream && { openStream: impl.openStream.bind(impl) }),
133
+ };
134
+ }
135
+ const streamUnavailable = (message = "The device is not running; use a device tool first to start it, then open the stream again.") => new DeviceAccessError("provider_unavailable", message);
127
136
  /** The signal of one provider call in maintenance: aborted on timeout or when the lease is lost. */
128
137
  const opSignal = (lease) => AbortSignal.any([lease.signal, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS)]);
129
138
  /** The provider-side name of a device's file system and instance. */
@@ -749,6 +758,110 @@ let SandboxService = class SandboxService {
749
758
  await sleep(this.pollMs + Math.floor(Math.random() * this.pollMs), signal);
750
759
  }
751
760
  }
761
+ /**
762
+ * Holds the device's running instance for a stream to one of its services (browser use spec
763
+ * §6.2: an open viewer counts as device use). It never creates, resumes or rebuilds an
764
+ * instance: a device without a running instance, whose provider is off in `orgId`, or that is
765
+ * in a lifecycle change (an exclusive lease or a pending intent) is refused with
766
+ * `DeviceAccessError("provider_unavailable")`; a provider without `openStream` with
767
+ * `capability_missing`.
768
+ *
769
+ * A hold is not a lease ({@link SandboxLeases.streamHold}): it takes no
770
+ * `sandbox.maxConcurrentCommands` slot and never blocks a lifecycle change. Idle suspension and
771
+ * the inactivity destruction (on any replica) skip a device with a live hold; the forced
772
+ * suspension after `maxRunningMinutes` does not. A hold yields to every lifecycle change:
773
+ * an exclusive acquisition ends the device's holds, and a pending intent makes their next
774
+ * renewal fail, so the returned `signal` aborts (also when the caller's `signal` aborts or a
775
+ * renewal deadline passes) and the hold is released. `release()` is idempotent and moves
776
+ * `last_used_at` forward, so the idle clock starts when the viewer goes.
777
+ */
778
+ async holdForStream(deviceId, orgId, signal) {
779
+ signal.throwIfAborted();
780
+ let p;
781
+ try {
782
+ p = await this.require(deviceId, orgId);
783
+ }
784
+ catch (err) {
785
+ if (err instanceof ApiError && err.code === "device.unavailable")
786
+ throw streamUnavailable(err.message);
787
+ if (err instanceof ApiError && err.code === "device.not_found")
788
+ throw new DeviceAccessError("no_device", err.message);
789
+ throw err;
790
+ }
791
+ const impl = p.impl;
792
+ if (!impl.openStream)
793
+ throw new DeviceAccessError("capability_missing", "This device's provider cannot open streams to device services; choose a device on a provider that supports them.");
794
+ const row = () => this.db
795
+ .selectFrom("device_instances")
796
+ .selectAll()
797
+ .where("device_id", "=", deviceId)
798
+ .where("org_id", "=", orgId)
799
+ .executeTakeFirst();
800
+ const before = await row();
801
+ if (!before || !this.usable(before, p, null))
802
+ throw streamUnavailable();
803
+ const lease = await this.leases.streamHold(deviceId);
804
+ if (!lease)
805
+ throw streamUnavailable();
806
+ // read again after the hold is recorded: a lifecycle change that finished before it was
807
+ // recorded shows in the row; one that starts later ends the hold
808
+ let after;
809
+ try {
810
+ after = await row();
811
+ }
812
+ catch (err) {
813
+ await lease.release();
814
+ throw err;
815
+ }
816
+ if (!after ||
817
+ !this.usable(after, p, null) ||
818
+ after.created_at.getTime() !== before.created_at.getTime()) {
819
+ await lease.release();
820
+ throw streamUnavailable();
821
+ }
822
+ // an open viewer is device use: its last use moves when the hold is taken and when it ends
823
+ const touch = () => this.db
824
+ .updateTable("device_instances")
825
+ .set({ last_used_at: sql `GREATEST(last_used_at, now())` })
826
+ .where("device_id", "=", deviceId)
827
+ .where("org_id", "=", orgId)
828
+ .where("status", "=", "running")
829
+ .execute()
830
+ .then(() => undefined, (err) => this.log.warn("cannot update sandbox last_used_at", { deviceId, err }));
831
+ await touch();
832
+ const sig = AbortSignal.any([signal, lease.lost]);
833
+ let released;
834
+ const onAbort = () => void release();
835
+ const release = () => {
836
+ released ??= (async () => {
837
+ sig.removeEventListener("abort", onAbort);
838
+ await lease.release();
839
+ await touch();
840
+ })();
841
+ return released;
842
+ };
843
+ sig.addEventListener("abort", onAbort, { once: true });
844
+ if (sig.aborted) {
845
+ await release();
846
+ throw abortReason(sig);
847
+ }
848
+ return {
849
+ h: after.handle,
850
+ p: { openStream: impl.openStream.bind(impl) },
851
+ signal: sig,
852
+ release,
853
+ };
854
+ }
855
+ /**
856
+ * Runs `fn` with the device service methods of the device's provider (browser use spec §5),
857
+ * as any use of the device does ({@link withSandbox}: the instance is created or resumed,
858
+ * `last_used_at` moves forward). `admit` sees the provider's methods first, before any lease
859
+ * or instance work, so a provider without services is refused without touching the device.
860
+ */
861
+ async withDeviceServices(ctx, admit, fn, signal) {
862
+ admit(serviceMethodsOf((await this.require(ctx.deviceId, ctx.orgId)).impl));
863
+ return this.withSandboxUse(ctx, { kind: "services", fn }, signal);
864
+ }
752
865
  /**
753
866
  * A short lease on one path of the device around the kernel's own read-modify-write of
754
867
  * that file (spec §10.4); waits up to 30 s, then throws `SandboxPathBusyError`. Its `signal`
@@ -1116,6 +1229,8 @@ let SandboxService = class SandboxService {
1116
1229
  const sig = AbortSignal.any([signal, e.lease.signal]);
1117
1230
  if (route.kind === "preparation")
1118
1231
  return route.run(e.handle, p.impl, { ...e.info, roots: rootsOf(e.handle) }, sig);
1232
+ if (route.kind === "services")
1233
+ return route.fn(e.handle, serviceMethodsOf(p.impl), sig);
1119
1234
  const env = ctx.deviceId;
1120
1235
  if (route.kind === "kernelRead")
1121
1236
  return route.fn(e.handle, this.kernelReadProvider(e, ctx, p, route.read, sig), { ...e.info, roots: rootsOf(e.handle) }, sig);
@@ -1791,7 +1906,8 @@ let SandboxService = class SandboxService {
1791
1906
  }
1792
1907
  /**
1793
1908
  * Suspends running instances idle longer than `suspendAfterIdleMinutes` or running continuously
1794
- * longer than `maxRunningMinutes`. Skips a device with any holder; one past
1909
+ * longer than `maxRunningMinutes`. Skips a device with any holder, and one with an open stream
1910
+ * hold ({@link holdForStream}) unless it is past `maxRunningMinutes`; one past
1795
1911
  * `maxRunningMinutes` gets the intent for one poll window (about a second) first. Returns how
1796
1912
  * many it suspended. Called every minute by the `sandbox-suspend-idle` cron.
1797
1913
  */
@@ -1803,6 +1919,16 @@ let SandboxService = class SandboxService {
1803
1919
  n += await this.suspendIdleOf(p, now);
1804
1920
  return n;
1805
1921
  }
1922
+ /** Whether the device has a live stream hold; a Redis error counts as none (the sweep goes on). */
1923
+ async streamHeld(deviceId) {
1924
+ try {
1925
+ return (await this.leases.streamHolds(deviceId)) > 0;
1926
+ }
1927
+ catch (err) {
1928
+ this.log.warn("cannot read the device's stream holds", { deviceId, err });
1929
+ return false;
1930
+ }
1931
+ }
1806
1932
  /** {@link suspendIdle} for the rows of one provider. */
1807
1933
  async suspendIdleOf(p, now) {
1808
1934
  const due = this.suspendDue(now, p.plugin);
@@ -1811,6 +1937,9 @@ let SandboxService = class SandboxService {
1811
1937
  let n = 0;
1812
1938
  await inPool(rows, SWEEP_CONCURRENCY, async (c) => {
1813
1939
  const overdue = c.running_since !== null && c.running_since < runningBefore;
1940
+ // an open viewer exempts the device from idle suspension only, never from the forced one
1941
+ if (!overdue && (await this.streamHeld(c.device_id)))
1942
+ return;
1814
1943
  const done = await this.tryLocked(c.device_id, async (lease) => {
1815
1944
  return asPlatform("deployment-wide suspension sweep", async () => {
1816
1945
  const id = c.device_id;
@@ -1837,7 +1966,10 @@ let SandboxService = class SandboxService {
1837
1966
  this.log.info("sandbox suspended", { deviceId: id });
1838
1967
  return true;
1839
1968
  });
1840
- }, overdue);
1969
+ }, overdue,
1970
+ // a hold taken since the first look (a viewer that opened meanwhile) refuses the lease:
1971
+ // an open viewer exempts the device from idle suspension, never from the forced one
1972
+ !overdue);
1841
1973
  if (done)
1842
1974
  n++;
1843
1975
  });
@@ -1872,6 +2004,9 @@ let SandboxService = class SandboxService {
1872
2004
  const mine = (eb) => eb.and([eb("provider", "=", p.plugin), due(eb)]);
1873
2005
  let n = 0;
1874
2006
  await inPool(await this.candidates(mine), SWEEP_CONCURRENCY, async ({ device_id: id }) => {
2007
+ // an open viewer is device use: the inactivity destruction waits (a deleted device does not)
2008
+ if (mode === "instance" && (await this.streamHeld(id)))
2009
+ return;
1875
2010
  const done = await this.tryLocked(id, async (lease) => {
1876
2011
  return asPlatform("deployment-wide destruction sweep", async () => {
1877
2012
  // org-filter: deployment-wide destruction sweep (worker) over every org's due instances,
@@ -2714,10 +2849,12 @@ let SandboxService = class SandboxService {
2714
2849
  * wait briefly and the sweep gets in if the running ones end. Failures are warned, recorded in
2715
2850
  * `sweep_failed_at` (sorted last next time) and return false.
2716
2851
  */
2717
- async tryLocked(deviceId, fn, overdue = false) {
2852
+ async tryLocked(deviceId, fn, overdue = false,
2853
+ /** Refused (false) while the device has a live stream hold ({@link holdForStream}). */
2854
+ unlessStreams = false) {
2718
2855
  let lease;
2719
2856
  try {
2720
- lease = await this.leases.tryExclusive(deviceId);
2857
+ lease = await this.leases.tryExclusive(deviceId, unlessStreams ? { unlessStreams } : {});
2721
2858
  if (!lease && overdue) {
2722
2859
  lease = await this.leases
2723
2860
  .acquireExclusive(deviceId, AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS), Math.max(this.pollMs * 2, SWEEP_INTENT_WAIT_MS), { intent: true })
@@ -82,7 +82,10 @@ export declare const setupWebPath: {
82
82
  connector: (id: string) => string;
83
83
  /** A member's connector section: the connector's row on their connections page (§9.3). */
84
84
  memberConnections: () => string;
85
- template: (itemId: string) => string;
85
+ /** A connector's configure page: its credentials tab (the guide, editable endpoint fields, credential). */
86
+ configure: (id: string) => string;
87
+ /** The connectors page: a template on in the org without a connector shows its card there. */
88
+ connectors: () => string;
86
89
  };
87
90
  /**
88
91
  * The blocks of a rendered guide as one Markdown document (checks as `- [check <id>]` lines).
@@ -124,6 +127,11 @@ export declare class SetupGuidesService {
124
127
  * in the org that have a guide and no connector yet.
125
128
  */
126
129
  private connectors;
130
+ /**
131
+ * The oldest live connector of the org made from one of the item's platform connector templates
132
+ * `templates` (a template id, or the ids a guide covers), if any.
133
+ */
134
+ private templateConnector;
127
135
  /**
128
136
  * One guide rendered for the caller as a Markdown document (`setup.read`): the guide route's
129
137
  * rendering (`PluginGuides.render`, its visibility, action and target rules), joined, with the
@@ -23,22 +23,29 @@ export const setupWebPath = {
23
23
  connector: (id) => `/connectors/${enc(id)}?tab=guide`,
24
24
  /** A member's connector section: the connector's row on their connections page (§9.3). */
25
25
  memberConnections: () => "/account/connections",
26
- template: (itemId) => `/connectors/install?template=${enc(itemId)}`,
26
+ /** A connector's configure page: its credentials tab (the guide, editable endpoint fields, credential). */
27
+ configure: (id) => `/connectors/${enc(id)}?tab=credentials`,
28
+ /** The connectors page: a template on in the org without a connector shows its card there. */
29
+ connectors: () => "/connectors",
27
30
  };
28
31
  /**
29
32
  * The page a rendered guide belongs on: a member's connections page for the member audience, else
30
- * its target's, else where a target is created.
33
+ * its target's, else where a target is created; a connector template's guide without a target goes
34
+ * to the configure page of `templateConnector` (a connector of the org made from the template) when there is
35
+ * one, else to the connectors page.
31
36
  */
32
- function webPathOf(g) {
37
+ function webPathOf(g, templateConnector) {
33
38
  if (g.audience === "member")
34
39
  return setupWebPath.memberConnections();
35
40
  if (g.target?.kind === "channel-connection")
36
41
  return setupWebPath.connection(g.target.id);
37
42
  if (g.target?.kind === "connector")
38
43
  return setupWebPath.connector(g.target.id);
39
- return g.place === "channel-connection"
40
- ? setupWebPath.newConnection()
41
- : setupWebPath.template(g.itemId);
44
+ if (g.place === "channel-connection")
45
+ return setupWebPath.newConnection();
46
+ return templateConnector !== undefined
47
+ ? setupWebPath.configure(templateConnector)
48
+ : setupWebPath.connectors();
42
49
  }
43
50
  /** A fence longer than any run of backticks in the text. */
44
51
  function fenceFor(text) {
@@ -250,13 +257,34 @@ let SetupGuidesService = class SetupGuidesService {
250
257
  id: t.name,
251
258
  name: t.displayName?.en ?? t.name,
252
259
  drift: null,
253
- webPath: setupWebPath.template(t.itemId),
260
+ webPath: setupWebPath.connectors(),
254
261
  checked: false,
255
262
  },
256
263
  });
257
264
  }
258
265
  return out;
259
266
  }
267
+ /**
268
+ * The oldest live connector of the org made from one of the item's platform connector templates
269
+ * `templates` (a template id, or the ids a guide covers), if any.
270
+ */
271
+ async templateConnector(orgId, itemId, templates) {
272
+ const ids = typeof templates === "string" ? [templates] : [...templates];
273
+ if (ids.length === 0)
274
+ return undefined;
275
+ const row = await this.db
276
+ .selectFrom("connectors as c")
277
+ .innerJoin("platform_connector_templates as t", "t.id", "c.platform_template_id")
278
+ .select("c.id")
279
+ .where("c.org_id", "=", orgId)
280
+ .where("c.deleted_at", "is", null)
281
+ .where("t.catalog_item_id", "=", itemId)
282
+ .where("t.template_id", "in", ids)
283
+ .orderBy("c.created_at")
284
+ .orderBy("c.id")
285
+ .executeTakeFirst();
286
+ return row?.id;
287
+ }
260
288
  /**
261
289
  * One guide rendered for the caller as a Markdown document (`setup.read`): the guide route's
262
290
  * rendering (`PluginGuides.render`, its visibility, action and target rules), joined, with the
@@ -264,7 +292,9 @@ let SetupGuidesService = class SetupGuidesService {
264
292
  */
265
293
  async read(caller, itemId, guideId, q) {
266
294
  const g = await this.guides.render({ orgId: caller.orgId, role: caller.role }, itemId, guideId, q);
267
- const webPath = webPathOf(g);
295
+ const webPath = webPathOf(g, g.audience !== "member" && g.target === null && g.place === "connector-template"
296
+ ? await this.templateConnector(caller.orgId, g.itemId, g.template ?? g.templates)
297
+ : undefined);
268
298
  return {
269
299
  itemId: g.itemId,
270
300
  plugin: g.plugin,
@@ -17,8 +17,9 @@ export interface AdminConnectorRow {
17
17
  /** Counts every tool row of the connector, pending and missing ones included. */
18
18
  toolCount: number;
19
19
  toolsSyncedAt: Date | null;
20
- createdBy: string;
21
- createdByName: string;
20
+ /** Null: the kernel created it as no person (a plugin scope sync). */
21
+ createdBy: string | null;
22
+ createdByName: string | null;
22
23
  createdByAvatarUrl: string | null;
23
24
  createdAt: Date;
24
25
  updatedAt: Date;
@@ -28,10 +28,11 @@ let AdminConnectors = class AdminConnectors {
28
28
  return this.kdb.db;
29
29
  }
30
30
  base() {
31
- return this.db
31
+ return (this.db
32
32
  .selectFrom("connectors as c")
33
33
  .innerJoin("orgs as o", "o.id", "c.org_id")
34
- .innerJoin("accounts as a", "a.id", "c.created_by")
34
+ // a connector the kernel created as no person has no creator (ruling R17)
35
+ .leftJoin("accounts as a", "a.id", "c.created_by")
35
36
  .leftJoin("platform_connector_templates as pt", "pt.id", "c.platform_template_id")
36
37
  .select((eb) => [
37
38
  "c.id",
@@ -54,7 +55,7 @@ let AdminConnectors = class AdminConnectors {
54
55
  WHERE t.connector_id = c.id)`.as("tool_count"),
55
56
  ])
56
57
  .where("c.deleted_at", "is", null)
57
- .where("o.deleted_at", "is", null);
58
+ .where("o.deleted_at", "is", null));
58
59
  }
59
60
  /** Live connectors of every live org by id, filtered; `next` is the last id when more follow. */
60
61
  async list(q) {
@@ -131,7 +132,7 @@ function toRow(r) {
131
132
  toolsSyncedAt: r.tools_synced_at,
132
133
  createdBy: r.created_by,
133
134
  createdByName: r.created_by_name,
134
- createdByAvatarUrl: personAvatarUrl(r, "creator", r.created_by),
135
+ createdByAvatarUrl: r.created_by === null ? null : personAvatarUrl(r, "creator", r.created_by),
135
136
  createdAt: r.created_at,
136
137
  updatedAt: r.updated_at,
137
138
  };
@@ -61,23 +61,12 @@ export interface KeptToolResult {
61
61
  * or after its files are rebuilt (a provider that fixes limits at its file system).
62
62
  */
63
63
  export type NetworkAppliesAt = "next-command" | "next-use" | "files-reset";
64
- /**
65
- * A network ask's `detail` (network ask-to-allow spec §6.1, P-D2): the device, the refused hosts,
66
- * the command and its kept `tool_result` (written with a note when the ask settles; the command is
67
- * never run again), when "add to this device's list" would apply, and once approved what took
68
- * effect.
69
- */
70
- export interface NetworkAskDetail {
64
+ /** What every network ask's `detail` holds ({@link NetworkAskDetail}). */
65
+ interface NetworkAskDetailBase {
71
66
  deviceId: string;
72
- hosts: {
73
- host: string;
74
- port: number;
75
- }[];
76
- command: string;
77
- description: string | null;
78
67
  /** When hosts added to the device's own list apply ({@link NetworkAppliesAt}). */
79
68
  appliesAt: NetworkAppliesAt;
80
- /** The formatted `tool_result` of the command and its display-only fields. */
69
+ /** The formatted `tool_result` of the call and its display-only fields. */
81
70
  result: KeptToolResult;
82
71
  /** The hosts the decision allowed (every approved decision writes them; none: nothing). */
83
72
  grantedHosts?: string[];
@@ -87,8 +76,44 @@ export interface NetworkAskDetail {
87
76
  */
88
77
  outcome?: "once" | "always";
89
78
  }
90
- /** A network ask's detail as the API shows it: without the kept command result. */
91
- export type NetworkAskView = Omit<NetworkAskDetail, "result">;
79
+ /**
80
+ * A command's network ask (network ask-to-allow spec §6.1, P-D2): the device, the refused hosts,
81
+ * the command and its kept `tool_result` (written with a note when the ask settles; the command is
82
+ * never run again), when "add to this device's list" would apply, and once approved what took
83
+ * effect. `kind` absent: a command too.
84
+ */
85
+ export interface CommandNetworkAskDetail extends NetworkAskDetailBase {
86
+ kind?: "command";
87
+ hosts: {
88
+ host: string;
89
+ port: number;
90
+ }[];
91
+ command: string;
92
+ description: string | null;
93
+ }
94
+ /**
95
+ * A device service's network ask (browser use spec §7.1): an extension's tool call whose service
96
+ * saw `hosts` refused by the device's allowlist. It offers only `always` (the device's own list:
97
+ * a run grant applies per exec and cannot reach a long-lived service); approved, the call runs
98
+ * again, otherwise its kept result is written with the outcome's note. `service` names the
99
+ * extension whose service asked; `url` is the page it was loading when known.
100
+ */
101
+ export interface ServiceNetworkAskDetail extends NetworkAskDetailBase {
102
+ kind: "service";
103
+ service: string;
104
+ url: string | null;
105
+ hosts: string[];
106
+ /** The call's attempt (`tool_call_started`) that asked: the re-run takes the next one. */
107
+ attempt: number;
108
+ }
109
+ /** A network ask's `detail`: a command's or a device service's. */
110
+ export type NetworkAskDetail = CommandNetworkAskDetail | ServiceNetworkAskDetail;
111
+ /** `Omit` over each member of a union. */
112
+ type OmitEach<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
113
+ /** A network ask's detail as the API shows it: without the kept call result. */
114
+ export type NetworkAskView = OmitEach<NetworkAskDetail, "result">;
115
+ /** The hosts a network ask asked about, whichever kind it is. */
116
+ export declare function networkAskHosts(detail: Pick<NetworkAskDetail, "hosts" | "kind">): string[];
92
117
  /**
93
118
  * A git push ask's `detail` (sandbox git credentials spec §7): the host, the repository
94
119
  * (`<owner>/<repo>`, normalized) and the refs of the push the gateway held, the command that ran
@@ -387,7 +412,9 @@ export interface NetworkAskInput {
387
412
  callId: string;
388
413
  /** The device owner: the only person who may decide. */
389
414
  requestedFor: string;
390
- detail: Omit<NetworkAskDetail, "grantedHosts" | "outcome">;
415
+ /** The tool key the ask is recorded under: the call's (`Bash` for a command). */
416
+ toolKey: string;
417
+ detail: OmitEach<NetworkAskDetail, "grantedHosts" | "outcome">;
391
418
  /**
392
419
  * What the device's provider enforces (device-provider spec §6.3, `networkAskOffer`): `once` (a
393
420
  * run grant) only with per-operation hosts, `always` (add to the device's own list) only when
@@ -395,8 +422,6 @@ export interface NetworkAskInput {
395
422
  */
396
423
  scopes: ("once" | "always")[];
397
424
  }
398
- /** The tool key a network ask is recorded under (the command ran in `Bash`). */
399
- export declare const NETWORK_ASK_TOOL_KEY = "Bash";
400
425
  /** The tool key a git ask is recorded under (the push ran in a `Bash` command). */
401
426
  export declare const GIT_ASK_TOOL_KEY = "Bash";
402
427
  /**
@@ -499,7 +524,7 @@ export declare class ApprovalsService {
499
524
  /**
500
525
  * A network ask (network ask-to-allow spec §6.2): a pending approval of kind `network` for the
501
526
  * device owner, expiring like a tool approval (`tools.approvalTimeoutHours`), and its
502
- * `approval_requested` (tool key `Bash`, the display-only `network.hosts`), in one transaction.
527
+ * `approval_requested` (the call's tool key, the display-only `network.hosts`), in one transaction.
503
528
  * It takes the attempt after the call's other approvals (P-D4: the command ran, so no tool
504
529
  * approval of the call follows it). One per call: a second request returns the first.
505
530
  */
@@ -48,6 +48,12 @@ import { ToolRegistry } from "./registry.js";
48
48
  export { APPROVAL_DENY_REASON_MAX_CHARS } from "../conversations/events.js";
49
49
  /** `list` 一次最多返回的审批数(收件箱据此判断这个来源是否取满)。 */
50
50
  export const APPROVALS_LIST_MAX = 100;
51
+ /** The hosts a network ask asked about, whichever kind it is. */
52
+ export function networkAskHosts(detail) {
53
+ return detail.kind === "service"
54
+ ? [...detail.hosts]
55
+ : detail.hosts.map((h) => h.host);
56
+ }
51
57
  /**
52
58
  * The model-visible note written after a network ask's kept result when its run is stopped before
53
59
  * the device owner answered (spec §6.7).
@@ -115,8 +121,6 @@ const NETWORK_APPLIES_AT = new Set([
115
121
  "next-use",
116
122
  "files-reset",
117
123
  ]);
118
- /** The tool key a network ask is recorded under (the command ran in `Bash`). */
119
- export const NETWORK_ASK_TOOL_KEY = "Bash";
120
124
  /** The spec hash of a network ask (no tool definition is approved). */
121
125
  const NETWORK_ASK_SPEC_HASH = "network";
122
126
  /** The tool key a git ask is recorded under (the push ran in a `Bash` command). */
@@ -427,18 +431,24 @@ let ApprovalsService = class ApprovalsService {
427
431
  /**
428
432
  * A network ask (network ask-to-allow spec §6.2): a pending approval of kind `network` for the
429
433
  * device owner, expiring like a tool approval (`tools.approvalTimeoutHours`), and its
430
- * `approval_requested` (tool key `Bash`, the display-only `network.hosts`), in one transaction.
434
+ * `approval_requested` (the call's tool key, the display-only `network.hosts`), in one transaction.
431
435
  * It takes the attempt after the call's other approvals (P-D4: the command ran, so no tool
432
436
  * approval of the call follows it). One per call: a second request returns the first.
433
437
  */
434
438
  async requestNetwork(input) {
435
- const hosts = input.detail.hosts;
439
+ const hosts = networkAskHosts(input.detail);
436
440
  if (hosts.length === 0 || hosts.length > NETWORK_ASK_MAX_HOSTS) {
437
441
  throw new Error(`a network ask lists 1 to ${NETWORK_ASK_MAX_HOSTS} hosts`);
438
442
  }
439
- if (hosts.some((h) => h.host.length === 0 || h.host.length > NETWORK_HOST_MAX_CHARS)) {
443
+ if (hosts.some((h) => h.length === 0 || h.length > NETWORK_HOST_MAX_CHARS)) {
440
444
  throw new Error("a network ask's host is 1 to 255 characters");
441
445
  }
446
+ if (input.toolKey.length === 0)
447
+ throw new Error("a network ask names its call's tool key");
448
+ // a service's ask offers only the device's own list (a run grant cannot reach its process)
449
+ if (input.detail.kind === "service" && input.scopes.some((k) => k !== "always")) {
450
+ throw new Error('a device service\'s network ask offers only "always"');
451
+ }
442
452
  const scopes = new Set(input.scopes);
443
453
  if (scopes.size === 0 ||
444
454
  scopes.size !== input.scopes.length ||
@@ -490,7 +500,7 @@ let ApprovalsService = class ApprovalsService {
490
500
  attempt: Number(last?.attempt ?? 0) + 1,
491
501
  kind: "network",
492
502
  detail: JSON.stringify(input.detail),
493
- tool_key: NETWORK_ASK_TOOL_KEY,
503
+ tool_key: input.toolKey,
494
504
  spec_hash: NETWORK_ASK_SPEC_HASH,
495
505
  connector_id: null,
496
506
  input: JSON.stringify({}),
@@ -515,7 +525,7 @@ let ApprovalsService = class ApprovalsService {
515
525
  approvalId: rec.id,
516
526
  toolKey: rec.toolKey,
517
527
  expiresAt: rec.expiresAt,
518
- network: { hosts: input.detail.hosts.map((h) => h.host) },
528
+ network: { hosts: networkAskHosts(input.detail) },
519
529
  requestedFor: rec.requestedFor,
520
530
  approverRole: null,
521
531
  },
@@ -923,7 +933,7 @@ let ApprovalsService = class ApprovalsService {
923
933
  }
924
934
  if (row.expired)
925
935
  throw new ApiError("approval.already_decided", "Approval has expired");
926
- const asked = [...new Set(detail.hosts.map((h) => h.host))];
936
+ const asked = [...new Set(networkAskHosts(detail))];
927
937
  let network;
928
938
  if (body.decision === "approve") {
929
939
  const scope = body.scope ?? "once";
@@ -1384,7 +1394,7 @@ let ApprovalsService = class ApprovalsService {
1384
1394
  },
1385
1395
  ]);
1386
1396
  if (network !== undefined && before.detail !== null) {
1387
- const asked = [...new Set(before.detail.hosts.map((h) => h.host))];
1397
+ const asked = [...new Set(networkAskHosts(before.detail))];
1388
1398
  const refused = asked.filter((h) => !network.wanted.includes(h));
1389
1399
  await audit(t, {
1390
1400
  actorAccountId: accountId,