@capybara-hq/kernel 0.1.0-rc.131 → 0.1.0-rc.133

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 (155) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/admin.schemas.d.ts +4 -0
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/admin/setup.service.js +6 -1
  7. package/dist/agents/agents.controller.js +3 -2
  8. package/dist/agents/agents.service.d.ts +2 -0
  9. package/dist/agents/agents.service.js +7 -0
  10. package/dist/catalog/catalog.service.d.ts +2 -0
  11. package/dist/catalog/catalog.service.js +28 -5
  12. package/dist/catalog/marketplace-fetch.d.ts +2 -0
  13. package/dist/catalog/marketplace-fetch.js +15 -0
  14. package/dist/catalog/marketplaces.service.d.ts +4 -4
  15. package/dist/catalog/marketplaces.service.js +3 -2
  16. package/dist/catalog/owned-items.d.ts +2 -0
  17. package/dist/catalog/owned-items.js +30 -31
  18. package/dist/catalog/ownership.js +40 -38
  19. package/dist/catalog/plugin-import.d.ts +6 -5
  20. package/dist/catalog/plugin-import.js +69 -16
  21. package/dist/catalog/plugin-upgrade.d.ts +8 -0
  22. package/dist/catalog/plugin-upgrade.js +95 -7
  23. package/dist/catalog/publisher-policy.d.ts +9 -0
  24. package/dist/catalog/publisher-policy.js +12 -0
  25. package/dist/catalog/unshare.js +66 -58
  26. package/dist/client/client-access.service.js +5 -3
  27. package/dist/config/schema.d.ts +1 -0
  28. package/dist/config/schema.js +9 -1
  29. package/dist/conversations/conversations.controller.js +4 -14
  30. package/dist/conversations/conversations.service.d.ts +14 -0
  31. package/dist/conversations/conversations.service.js +20 -2
  32. package/dist/ctx/create-ctx.d.ts +14 -4
  33. package/dist/ctx/create-ctx.js +131 -59
  34. package/dist/ctx/queue.js +7 -4
  35. package/dist/db/extension-db.d.ts +30 -0
  36. package/dist/db/extension-db.js +91 -0
  37. package/dist/db/extension-rls-predicate.d.ts +1 -0
  38. package/dist/db/extension-rls-predicate.js +8 -0
  39. package/dist/db/extension-schema-transfer.d.ts +6 -0
  40. package/dist/db/extension-schema-transfer.js +141 -0
  41. package/dist/db/kernel-schema.d.ts +50 -4
  42. package/dist/db/migrator.d.ts +6 -0
  43. package/dist/db/migrator.js +35 -7
  44. package/dist/db/pool.d.ts +6 -2
  45. package/dist/db/pool.js +37 -2
  46. package/dist/db/sql-statements.d.ts +3 -0
  47. package/dist/db/sql-statements.js +15 -5
  48. package/dist/device-access/device-access.module.js +12 -2
  49. package/dist/device-access/device-access.service.d.ts +30 -2
  50. package/dist/device-access/device-access.service.js +38 -4
  51. package/dist/device-access/host-gate.d.ts +45 -0
  52. package/dist/device-access/host-gate.js +92 -0
  53. package/dist/device-access/host-service-stop-sweep.d.ts +33 -0
  54. package/dist/device-access/host-service-stop-sweep.js +112 -0
  55. package/dist/device-access/host-service-stop.d.ts +78 -0
  56. package/dist/device-access/host-service-stop.js +144 -0
  57. package/dist/device-access/host-services.d.ts +211 -0
  58. package/dist/device-access/host-services.js +803 -0
  59. package/dist/device-access/person-handles.d.ts +10 -0
  60. package/dist/device-access/person-handles.js +25 -0
  61. package/dist/device-access/service-events.d.ts +199 -0
  62. package/dist/device-access/service-events.js +704 -0
  63. package/dist/device-access/token.d.ts +5 -0
  64. package/dist/device-access/token.js +5 -0
  65. package/dist/devices/devices.service.js +3 -0
  66. package/dist/dial-in/access.d.ts +5 -5
  67. package/dist/dial-in/access.js +19 -12
  68. package/dist/dial-in/gateway.js +6 -2
  69. package/dist/dial-in/machines.d.ts +9 -2
  70. package/dist/dial-in/machines.js +27 -4
  71. package/dist/erasure/device-cleanup.js +12 -0
  72. package/dist/erasure/org-catalog.js +2 -2
  73. package/dist/erasure/org-rules.js +9 -0
  74. package/dist/errors.d.ts +2 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/extensions/admin-ops.d.ts +3 -1
  77. package/dist/extensions/admin-ops.js +19 -9
  78. package/dist/extensions/deployed-snapshots.d.ts +4 -1
  79. package/dist/extensions/deployed-snapshots.js +7 -2
  80. package/dist/extensions/extensions.module.js +3 -0
  81. package/dist/extensions/host.d.ts +11 -3
  82. package/dist/extensions/host.js +40 -8
  83. package/dist/extensions/instance.d.ts +6 -0
  84. package/dist/extensions/instance.js +7 -1
  85. package/dist/extensions/ledger.d.ts +1 -1
  86. package/dist/extensions/lifecycle-hooks.js +3 -3
  87. package/dist/extensions/migrate-lock.d.ts +4 -1
  88. package/dist/extensions/migrate-lock.js +19 -2
  89. package/dist/extensions/org-config.js +6 -1
  90. package/dist/extensions/permission-set.d.ts +7 -0
  91. package/dist/extensions/permission-set.js +10 -0
  92. package/dist/extensions/permission-view.d.ts +1 -1
  93. package/dist/extensions/permission-view.js +10 -1
  94. package/dist/git/tickets.js +32 -27
  95. package/dist/http/app.js +5 -3
  96. package/dist/identity/accounts.d.ts +6 -1
  97. package/dist/identity/accounts.js +11 -2
  98. package/dist/identity/api-tokens.js +7 -6
  99. package/dist/identity/settings.d.ts +9 -1
  100. package/dist/identity/settings.js +16 -1
  101. package/dist/inbox/org-notices.js +3 -2
  102. package/dist/index.d.ts +1 -0
  103. package/dist/index.js +1 -0
  104. package/dist/infra/database/scoped-dialect.d.ts +3 -2
  105. package/dist/infra/database/scoped-dialect.js +260 -72
  106. package/dist/infra/database/startup-activation-transaction.d.ts +2 -0
  107. package/dist/infra/database/startup-activation-transaction.js +3 -2
  108. package/dist/infra/outbox/registry.d.ts +28 -14
  109. package/dist/infra/outbox/registry.js +30 -15
  110. package/dist/infra/queue/queue-names.d.ts +1 -1
  111. package/dist/infra/queue/queue-names.js +1 -0
  112. package/dist/infra/queue/run-job.d.ts +4 -1
  113. package/dist/infra/queue/run-job.js +10 -2
  114. package/dist/kernel.js +4 -0
  115. package/dist/kernel.module.js +3 -0
  116. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  117. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  118. package/dist/orgs/offboarding.js +18 -9
  119. package/dist/orgs/settings.service.js +3 -0
  120. package/dist/packages/npm-publish-keys.json +27 -0
  121. package/dist/packages/official-publisher.d.ts +19 -0
  122. package/dist/packages/official-publisher.js +152 -0
  123. package/dist/packages/provenance.d.ts +7 -0
  124. package/dist/packages/provenance.js +22 -19
  125. package/dist/packages/sigstore-trusted-root.json +126 -0
  126. package/dist/platform/ops/admin.ops.js +2 -1
  127. package/dist/platform/ops/orgs.ops.js +1 -0
  128. package/dist/roles/worker-role.d.ts +6 -3
  129. package/dist/roles/worker-role.js +12 -4
  130. package/dist/roles/worker.module.js +7 -6
  131. package/dist/runtime/maintenance.d.ts +5 -4
  132. package/dist/runtime/maintenance.js +16 -13
  133. package/dist/sandbox/device-reports.d.ts +4 -4
  134. package/dist/sandbox/device-reports.js +40 -30
  135. package/dist/sandbox/device-services.d.ts +2 -1
  136. package/dist/sandbox/device-services.js +5 -1
  137. package/dist/sandbox/permission-ceiling-writes.d.ts +8 -0
  138. package/dist/sandbox/permission-ceiling-writes.js +21 -0
  139. package/dist/sandbox/permission-config-publication.js +5 -1
  140. package/dist/themes/theme-state.js +24 -13
  141. package/dist/tools/call-scope.d.ts +6 -0
  142. package/dist/tools/call-scope.js +22 -0
  143. package/dist/tools/registry.js +20 -2
  144. package/dist/ui/views.js +36 -8
  145. package/package.json +9 -4
  146. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  147. package/src/migrations/0220_require_event_org.sql +18 -0
  148. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  149. package/src/migrations/0222_device_host_services.sql +27 -0
  150. package/src/migrations/0223_device_service_events.sql +54 -0
  151. package/src/migrations/0224_cache_conversation_rls_settings.sql +33 -0
  152. package/dist/conversations/event-org-backfill.d.ts +0 -111
  153. package/dist/conversations/event-org-backfill.js +0 -264
  154. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
  155. package/dist/conversations/event-org-backfill.module.js +0 -18
@@ -0,0 +1,803 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { DeviceAccessError, deviceServiceFilesDigest, deviceServiceId, isDeviceOfflineError, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { DeviceAccess } from "../devices/access.js";
14
+ import { DevicesService } from "../devices/devices.service.js";
15
+ import { ApiError } from "../errors.js";
16
+ import { isExtensionEnabled } from "../extensions/enabled.js";
17
+ import { audit } from "../identity/audit.js";
18
+ import { KernelDb } from "../infra/database/kernel-db.js";
19
+ import { withOrgScope } from "../infra/database/org-scope.js";
20
+ import { TransactionHost } from "../infra/database/transaction-host.js";
21
+ import { Transactional } from "../infra/database/transactional.decorator.js";
22
+ import { LockService } from "../infra/lock/lock.service.js";
23
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
24
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
25
+ import { rootConversationOf } from "../runtime/subagents/child.js";
26
+ import { assertServiceSpec, nameOnlySpec } from "../sandbox/device-services.js";
27
+ import { DeviceProviders, servesDialIn } from "../sandbox/providers.js";
28
+ import { SandboxService } from "../sandbox/sandbox.service.js";
29
+ import { SandboxProviderUnreachableError } from "../sandbox/unreachable.js";
30
+ import { mapSandboxError } from "../tools/builtins/sandbox/common.js";
31
+ import { callScopeOf, isLiveCall, whileDeviceStarting } from "../tools/call-scope.js";
32
+ import { HostServiceGate } from "./host-gate.js";
33
+ import { latestMark, owedMarkMicros, oweHostServicesDelivery, } from "./host-service-stop.js";
34
+ import { HOST_STOP_REOWE_AFTER_MS } from "./host-service-stop-sweep.js";
35
+ import { personOf } from "./person-handles.js";
36
+ /** The audit action of a host service start (local agents spec, call 4). */
37
+ export const HOST_SERVICE_STARTED_ACTION = "device.host_service.started";
38
+ /** What a tool call by anyone but the conversation's owner is refused with. */
39
+ export const HOST_NOT_OWNER_TEXT = "Host services only run for the conversation's owner, on their own personal device.";
40
+ /** What a scope the kernel did not issue is refused with. */
41
+ export const HOST_SCOPE_TEXT = "A host service call takes { call, deviceId } with the tool call the kernel passed to the running tool handler, or { person, deviceId } with the person handle the kernel passed to the running page action or query; neither is valid after its handler settles.";
42
+ /**
43
+ * The holder of a person-scoped use of the device (a page action before any conversation): no
44
+ * conversation holds it, and the use is silent (nothing it causes is marked seen).
45
+ */
46
+ const PERSON_SCOPE_HOLDER = "device-owner";
47
+ /** The budget of a person-scoped ensure or stop (no tool call signal bounds it). */
48
+ const PERSON_SCOPE_TIMEOUT_MS = 120_000;
49
+ /** What a person-scoped request adds to its own `timeoutMs` (the device's round trip). */
50
+ const PERSON_REQUEST_SLACK_MS = 30_000;
51
+ /** The budget of one owed stop's delivery in {@link HostServiceAccess.deliverOwedStops}. */
52
+ const STOP_JOB_DEVICE_TIMEOUT_MS = 60_000;
53
+ /** The lifetime of a placement lock without renewal (renewed while held). */
54
+ const PLACEMENT_LOCK_TTL_MS = 30_000;
55
+ /** How long a start, stop or delivery waits for another one of the same placement. */
56
+ const PLACEMENT_LOCK_WAIT_MS = 120_000;
57
+ /** The lock of one placement (no `:`; `LockService` adds its prefix). */
58
+ const placementLockKey = (deviceId, extension, service) => `host-service-${deviceId}-${extension}-${service}`;
59
+ /**
60
+ * Reads `at`: a tool scope (`{ call, deviceId }` with the kernel's tool call context) or a person
61
+ * scope (`{ person, deviceId }` with a live kernel-issued handle); anything else, a plain
62
+ * `{ orgId, accountId }` or a handle the kernel did not issue or already revoked, is refused.
63
+ */
64
+ function resolveAt(at) {
65
+ const deviceId = at?.deviceId;
66
+ if (typeof deviceId !== "string" || deviceId === "")
67
+ throw new DeviceAccessError("invalid_request", HOST_SCOPE_TEXT);
68
+ const call = at.call;
69
+ if (call !== undefined) {
70
+ // only the very context the kernel passed to a handler, while that handler runs: never a
71
+ // copy, a context kept past its handler, or one built from strings
72
+ if (!isLiveCall(call) || callScopeOf(call) === null)
73
+ throw new DeviceAccessError("invalid_request", HOST_SCOPE_TEXT);
74
+ return { orgId: call.orgId, accountId: call.accountId, deviceId, call };
75
+ }
76
+ const person = personOf(at.person);
77
+ if (person === null)
78
+ throw new DeviceAccessError("invalid_request", HOST_SCOPE_TEXT);
79
+ return { ...person, deviceId, call: null };
80
+ }
81
+ /**
82
+ * Host device services (local agents spec, Part 1): a service of a platform-trusted extension that
83
+ * runs on its owner's personal machine outside the device sandbox, with the machine user's rights.
84
+ * Admission, in this order, each refusal a `DeviceAccessError`:
85
+ * 1. `host_not_declared`: the service is not in the approved manifest's
86
+ * `permissions.deviceAccess.hostServices`, a start's spec is not `host: true`, or the extension
87
+ * came from an org-owned catalog item (org uploads with code are refused at import; this is the
88
+ * backstop); `invalid_request`: a scope the kernel did not issue ({@link resolveAt});
89
+ * 2. `capability_missing`: the extension is not enabled in the org;
90
+ * 3. `not_owner`: a tool call whose trigger account is not the conversation's owner (calls act for
91
+ * the owner, unattended runs included);
92
+ * 4. `not_personal_device`: the device is not a live personal device of the person (the
93
+ * conversation's owner for a tool call) served by a dial-in provider (a machine of theirs);
94
+ * 5. `host_gate_closed`: {@link HostServiceGate} (a platform or org project reach cap below
95
+ * `machine`, or running outside the sandbox is off for the device), read inside the device's
96
+ * use under the shared permission authority locks, the provider call dispatched before they
97
+ * are released (a cap narrowed meanwhile owes the stop of what this call starts);
98
+ * 6. `host_consent_missing`: the machine's owner has not allowed these files of the service on the
99
+ * machine (`capybara-device services allow <extension>.<service>`), reported by the provider.
100
+ * A start passes no command review: the on-machine consent to the exact files is the check, and
101
+ * each new process is audited {@link HOST_SERVICE_STARTED_ACTION}. Where a host service runs is
102
+ * state (`device_host_services`): the row is written before the machine is asked to start it and
103
+ * deleted on a confirmed stop; a switch-off of the extension, the host gate closing (a project
104
+ * reach cap narrowed below `machine` or outside-sandbox work switched off,
105
+ * `PermissionCeilingWrites.publishLocked`), the device's deletion, its person's removal from the
106
+ * org or their account's disabling marks its rows owed in the same transaction, and
107
+ * {@link deliverOwedStops} delivers them (again on the machine's next connect when it is away, and
108
+ * by `HostServiceStopSweepJob` while it stays connected).
109
+ * The provider gets each service by its id (`<extension>.<name>`). Every call goes through the
110
+ * device's use ({@link SandboxService.withDeviceServices}: the instance is resumed, the lease and
111
+ * fencing apply), silently: a host service's lifetime is not the sandbox's, the machine keeps it
112
+ * across suspension.
113
+ */
114
+ let HostServiceAccess = class HostServiceAccess {
115
+ kdb;
116
+ sandbox;
117
+ access;
118
+ devices;
119
+ providers;
120
+ gate;
121
+ log;
122
+ locks;
123
+ outbox;
124
+ txHost;
125
+ constructor(kdb, sandbox, access, devices, providers, gate, log,
126
+ /** The placement lock ({@link withPlacement}). */
127
+ locks,
128
+ /** The delivery of a stop owed again after a start ({@link oweIfOff}). */
129
+ outbox, txHost) {
130
+ this.kdb = kdb;
131
+ this.sandbox = sandbox;
132
+ this.access = access;
133
+ this.devices = devices;
134
+ this.providers = providers;
135
+ this.gate = gate;
136
+ this.log = log;
137
+ this.locks = locks;
138
+ this.outbox = outbox;
139
+ this.txHost = txHost;
140
+ }
141
+ get db() {
142
+ return this.kdb.db;
143
+ }
144
+ /**
145
+ * Starts the host service on the person's machine, or finds it running on these files. A
146
+ * service running other files (the extension was upgraded) is started again on the spec's
147
+ * files, which needs the owner's consent to them again. The placement row is written before the
148
+ * machine is asked to start anything, and the extension's enablement is read again after it,
149
+ * so a switch-off that commits meanwhile either marks the row owed or refuses this start. A
150
+ * start that made a new process writes one {@link HOST_SERVICE_STARTED_ACTION} audit row.
151
+ */
152
+ async ensure(caller, at, spec) {
153
+ const name = spec.name;
154
+ await this.assertDeclared(caller, name);
155
+ if (spec.host !== true)
156
+ throw new DeviceAccessError("host_not_declared", `The device service spec ${JSON.stringify(name)} is not a host service spec: set host: true.`);
157
+ if (spec.env !== undefined)
158
+ throw new DeviceAccessError("invalid_request", `The host service ${name} must not set env: a host service runs with the machine user's login environment.`);
159
+ const id = deviceServiceId(caller.extension, name);
160
+ const providerSpec = { ...spec, name: id };
161
+ assertServiceSpec(providerSpec);
162
+ const r = resolveAt(at);
163
+ if (r.call !== null && callScopeOf(r.call)?.watch === true)
164
+ throw new Error(`plugin ${caller.extension}: ctx.deviceAccess.ensureHostService is not allowed in a tool watcher; a watcher's requests only reach a running service`);
165
+ const start = async () => {
166
+ const a = await this.admit(caller, r, { gate: true });
167
+ const digest = deviceServiceFilesDigest(spec.files);
168
+ return this.withPlacement(a, caller.extension, name, async () => {
169
+ let found = await this.onDevice(caller, name, a, (h, p, sig) => ensureOf(p)(h, nameOnlySpec(id), sig, { ifRunning: true }));
170
+ // a stop is owed (the extension was switched off since): delivered first; only this
171
+ // confirmed stop clears the mark, and only the mark it read (a later switch-off's stays)
172
+ const owed = await this.owedMark(a, caller.extension, name);
173
+ if (owed !== null) {
174
+ await this.onDevice(caller, name, a, (h, p, sig) => p.stopService(h, id, sig));
175
+ if (!(await this.clearOwed(a, caller.extension, name, owed)))
176
+ throw notEnabled(caller.extension);
177
+ found = { ...found, state: "stopped", startedAt: null };
178
+ }
179
+ if (found.state === "running" && found.filesDigest === digest) {
180
+ // running on these files: its placement is recorded (a start whose row was lost too)
181
+ await this.place(a, caller.extension, name, { digest, startedAt: found.startedAt });
182
+ await this.oweIfOff(a, caller.extension, name);
183
+ return { ...found, name };
184
+ }
185
+ // intent first: the row exists before the machine is asked to start anything, so a
186
+ // switch-off committing from here on marks it owed; one committed before is seen below
187
+ await this.place(a, caller.extension, name, null);
188
+ if (!(await this.enabledNow(a.orgId, caller.extension))) {
189
+ if (found.state !== "running")
190
+ await this.unplace(a, caller.extension, name);
191
+ throw notEnabled(caller.extension);
192
+ }
193
+ let started;
194
+ try {
195
+ started = await this.onDevice(caller, name, a, (h, p, sig) => ensureOf(p)(h, providerSpec, sig));
196
+ }
197
+ catch (e) {
198
+ // refused before anything started (consent, gate): nothing runs where nothing ran
199
+ if (found.state !== "running" && e instanceof DeviceAccessError)
200
+ await this.unplace(a, caller.extension, name);
201
+ throw e;
202
+ }
203
+ if (started.state === "running") {
204
+ await this.place(a, caller.extension, name, { digest, startedAt: started.startedAt });
205
+ if (started.startedAt !== found.startedAt)
206
+ await this.auditStart(caller, a, name, id, digest, started);
207
+ }
208
+ // switched off while the machine started it: the stop is owed again
209
+ await this.oweIfOff(a, caller.extension, name);
210
+ return { ...started, name };
211
+ });
212
+ };
213
+ return r.call !== null ? whileDeviceStarting(r.call, start) : start();
214
+ }
215
+ /**
216
+ * One request to the host service. `ifRunning` (forced in a watcher's call scope): a service
217
+ * that is not running is refused `not_running` and nothing is started.
218
+ */
219
+ async request(caller, at, req) {
220
+ await this.assertDeclared(caller, req.service);
221
+ const id = deviceServiceId(caller.extension, req.service);
222
+ const r = resolveAt(at);
223
+ // a live call always carries the scope the kernel attached (resolveAt checked it)
224
+ const scope = r.call !== null ? callScopeOf(r.call) : null;
225
+ const ifRunning = req.ifRunning === true || scope?.watch === true;
226
+ const a = await this.admit(caller, r, {
227
+ gate: true,
228
+ timeoutMs: req.timeoutMs + PERSON_REQUEST_SLACK_MS,
229
+ });
230
+ if (ifRunning) {
231
+ const st = await this.onDevice(caller, req.service, a, (h, p, sig) => ensureOf(p)(h, nameOnlySpec(id), sig, { ifRunning: true }));
232
+ if (st.state !== "running")
233
+ throw new DeviceAccessError("not_running", `The host service ${req.service} is not running; nothing was started.`);
234
+ }
235
+ // from here the service may act: a timeout of this call never says nothing was sent
236
+ if (scope !== null)
237
+ scope.reached = true;
238
+ return this.onDevice(caller, req.service, a, (h, p, sig) => p.serviceRequest(h, id, req.body, {
239
+ timeoutMs: req.timeoutMs,
240
+ signal: sig,
241
+ }));
242
+ }
243
+ /**
244
+ * Stops the host service on the person's machine; a service that is not running is no error.
245
+ * No gate: a stop is always admitted for the person's own device. The placement row goes once
246
+ * the machine confirmed the stop.
247
+ */
248
+ async stop(caller, at, service) {
249
+ await this.assertDeclared(caller, service);
250
+ const id = deviceServiceId(caller.extension, service);
251
+ const a = await this.admit(caller, resolveAt(at), { gate: false });
252
+ await this.withPlacement(a, caller.extension, service, async () => {
253
+ await this.onDevice(caller, service, a, (h, p, sig) => p.stopService(h, id, sig));
254
+ await this.unplace(a, caller.extension, service);
255
+ });
256
+ }
257
+ /**
258
+ * The person's personal devices in the org, with what a host service needs on each: the machine
259
+ * is connected (`online`); it can run host services (`hostServices`: false off a machine of
260
+ * theirs or with its provider off, null otherwise, since the machine's announced features do
261
+ * not reach the kernel); the host gate is open (`outsideSandbox`, null while the machine's own
262
+ * setting is not known yet: it is read once the device has run). An admission reads the gate
263
+ * again inside the device's use.
264
+ */
265
+ async personalDevices(caller, args) {
266
+ await this.assertEnabled(caller, args.orgId);
267
+ if (!(await this.isMember(args.orgId, args.accountId)))
268
+ return [];
269
+ const { items } = await this.devices.list(args.orgId, args.accountId);
270
+ return Promise.all(items.map(async (d) => ({
271
+ deviceId: d.id,
272
+ name: d.name ?? "Personal",
273
+ online: d.online === true,
274
+ hostServices: d.dialIn && d.available ? null : false,
275
+ outsideSandbox: await this.gate.known(args.orgId, d.id),
276
+ })));
277
+ }
278
+ /**
279
+ * The {@link HOST_SERVICES_STOP_JOB} body: delivers the owed stops `data` narrows to
280
+ * (`device_host_services.stop_owed_at`), each through the machine's provider; a confirmed stop
281
+ * deletes the row. A machine that is away (offline, its provider off or unavailable) keeps its
282
+ * rows owed: its next connect owes the delivery again. A provider that cannot run device
283
+ * services (`capability_missing`) keeps them owed without a retry. Any other failure fails the
284
+ * job after the others were tried, so the queue retries it; the rows stay owed either way, and
285
+ * the sweep (`HostServiceStopSweepJob`) owes them again while the machine stays connected.
286
+ *
287
+ * Only a confirmed stop clears a row, with one exception: a deleted device's rows are settled
288
+ * (deleted) without one, because the device record is gone and no machine can ever confirm
289
+ * them. That rests on the device side: the deletion revokes the machine and closes it with 4003
290
+ * "deleted" at once; a member's removal deletes their devices and the connection's credential
291
+ * re-check closes it with 4003 within a minute; a later connect is refused with 401. On each of
292
+ * those terminal ends (and on SIGTERM / SIGINT) `capybara-device` stops every service it runs,
293
+ * host services included, before it exits (`serveStaged` disposes the device; packages/device,
294
+ * "start: the program's end stops host services"); only a network loss keeps them running, and
295
+ * the next connect then ends that way. A disabled account's devices are not deleted: their rows
296
+ * stay owed until a machine confirms the stop.
297
+ */
298
+ async deliverOwedStops(data) {
299
+ let q = this.db
300
+ .selectFrom("device_host_services as h")
301
+ .innerJoin("devices as d", (j) => j.onRef("d.id", "=", "h.device_id").onRef("d.org_id", "=", "h.org_id"))
302
+ .select([
303
+ "h.org_id",
304
+ "h.device_id",
305
+ "h.extension",
306
+ "h.service",
307
+ "d.owner_account_id",
308
+ "d.deleted_at",
309
+ ])
310
+ .where("h.stop_owed_at", "is not", null);
311
+ if (data.extension !== undefined)
312
+ q = q.where("h.extension", "=", data.extension);
313
+ if (data.orgId !== undefined)
314
+ q = q.where("h.org_id", "=", data.orgId);
315
+ if (data.deviceId !== undefined)
316
+ q = q.where("h.device_id", "=", data.deviceId);
317
+ // every org when the extension was disabled on the deployment (no orgId): the job then runs
318
+ // as the platform (runJob) and delivers each stop in its own org below
319
+ const rows = await q.execute();
320
+ const failed = [];
321
+ for (const r of rows) {
322
+ if (r.deleted_at !== null) {
323
+ // the device is gone: its machine is closed (4003) or refused (401), and capybara-device
324
+ // stops its host services at that terminal end (see above); nothing can confirm it here
325
+ await withOrgScope(r.org_id, () => this.settle(r));
326
+ continue;
327
+ }
328
+ if (r.owner_account_id === null)
329
+ continue;
330
+ const use = useOf(r.org_id, r.owner_account_id, r.device_id, null);
331
+ let err;
332
+ try {
333
+ // each stop in its device's org (a deployment-wide job reads every org's owed stops)
334
+ err = await withOrgScope(r.org_id, () => this.locks.run(placementLockKey(r.device_id, r.extension, r.service), { ttlMs: PLACEMENT_LOCK_TTL_MS, waitMs: PLACEMENT_LOCK_WAIT_MS }, () => this.deliverOne(r, use)));
335
+ }
336
+ catch (e) {
337
+ // a placement busy past the wait (a long start) stays owed; the others go on
338
+ err = e;
339
+ }
340
+ if (err !== null)
341
+ failed.push(err);
342
+ }
343
+ if (failed.length > 0)
344
+ throw new Error(`${failed.length} owed host service stop(s) failed; retried by the queue`, {
345
+ cause: failed[0],
346
+ });
347
+ }
348
+ /**
349
+ * One owed stop, under its placement lock: read again (an ensure may have delivered it), sent,
350
+ * and the row deleted once the machine confirmed it. Null when delivered or kept owed for an
351
+ * away machine; the error otherwise.
352
+ */
353
+ async deliverOne(r, use) {
354
+ const still = await this.db
355
+ .selectFrom("device_host_services")
356
+ .select("stop_owed_at")
357
+ .where("org_id", "=", r.org_id)
358
+ .where("device_id", "=", r.device_id)
359
+ .where("extension", "=", r.extension)
360
+ .where("service", "=", r.service)
361
+ .executeTakeFirst();
362
+ if (still?.stop_owed_at == null)
363
+ return null;
364
+ try {
365
+ await this.sandbox.withDeviceServices(use, requireHostServices, (h, p, sig) => p.stopService(h, deviceServiceId(r.extension, r.service), sig), AbortSignal.timeout(STOP_JOB_DEVICE_TIMEOUT_MS));
366
+ }
367
+ catch (err) {
368
+ // away: the stop stays owed, delivered on the machine's next connect
369
+ if (isDeviceOfflineError(err) ||
370
+ err instanceof SandboxProviderUnreachableError ||
371
+ (err instanceof ApiError &&
372
+ (err.code === "device.unavailable" || err.code === "sandbox.unavailable"))) {
373
+ this.log.info("host service stop stays owed until the machine is back", {
374
+ extension: r.extension,
375
+ orgId: r.org_id,
376
+ deviceId: r.device_id,
377
+ service: r.service,
378
+ });
379
+ return null;
380
+ }
381
+ // a provider that cannot run device services never will: no retry, the stop stays owed.
382
+ // Said once per mark: the sweep owes the delivery again every window while the machine
383
+ // stays connected, and those deliveries log at debug only
384
+ if (err instanceof DeviceAccessError && err.code === "capability_missing") {
385
+ const fields = {
386
+ extension: r.extension,
387
+ orgId: r.org_id,
388
+ deviceId: r.device_id,
389
+ service: r.service,
390
+ };
391
+ const msg = "host service stop stays owed: the device's provider cannot stop it";
392
+ if (Date.now() - still.stop_owed_at.getTime() < HOST_STOP_REOWE_AFTER_MS)
393
+ this.log.warn(msg, fields);
394
+ else
395
+ this.log.debug(msg, fields);
396
+ return null;
397
+ }
398
+ this.log.warn("owed host service stop not delivered", {
399
+ extension: r.extension,
400
+ orgId: r.org_id,
401
+ deviceId: r.device_id,
402
+ service: r.service,
403
+ err,
404
+ });
405
+ return err;
406
+ }
407
+ // confirmed: nothing of it runs (a later switch-off's mark has nothing left to stop)
408
+ await this.settle(r);
409
+ return null;
410
+ }
411
+ /** Deletes an owed placement whose stop was confirmed (or whose device is deleted). */
412
+ async settle(r) {
413
+ await this.db
414
+ .deleteFrom("device_host_services")
415
+ .where("org_id", "=", r.org_id)
416
+ .where("device_id", "=", r.device_id)
417
+ .where("extension", "=", r.extension)
418
+ .where("service", "=", r.service)
419
+ .where("stop_owed_at", "is not", null)
420
+ .execute();
421
+ }
422
+ /**
423
+ * Records the placement of the service on the admitted device: `null` writes the intent (the row
424
+ * as it is, or a new one with no start yet), a start its digest and time. It never touches an
425
+ * owed stop: only a confirmed stop clears that ({@link clearOwed}, {@link deliverOwedStops}).
426
+ * Its own transaction, under the placement lock taken outside it.
427
+ */
428
+ async place(a, extension, service, started) {
429
+ const startedAt = started?.startedAt != null && !Number.isNaN(Date.parse(started.startedAt))
430
+ ? new Date(started.startedAt)
431
+ : null;
432
+ await this.db
433
+ .insertInto("device_host_services")
434
+ .values({
435
+ org_id: a.orgId,
436
+ device_id: a.deviceId,
437
+ extension,
438
+ service,
439
+ digest: started?.digest ?? null,
440
+ started_at: started === null ? null : startedAt,
441
+ })
442
+ .onConflict((oc) => started === null
443
+ ? oc.columns(["device_id", "extension", "service"]).doNothing()
444
+ : oc
445
+ .columns(["device_id", "extension", "service"])
446
+ .doUpdateSet({ digest: started.digest, started_at: startedAt }))
447
+ .execute();
448
+ }
449
+ /**
450
+ * Runs `fn` under the placement lock of (device, extension, service): starts, explicit stops and
451
+ * owed stop deliveries of one placement never interleave. Taken outside any transaction, one at
452
+ * a time (never two placement locks at once).
453
+ */
454
+ withPlacement(a, extension, service, fn) {
455
+ return this.locks.run(placementLockKey(a.deviceId, extension, service), { ttlMs: PLACEMENT_LOCK_TTL_MS, waitMs: PLACEMENT_LOCK_WAIT_MS, signal: a.signal }, fn);
456
+ }
457
+ /** The owed stop mark of the placement, or null. */
458
+ async owedMark(a, extension, service) {
459
+ const row = await this.db
460
+ .selectFrom("device_host_services")
461
+ .select("stop_owed_at")
462
+ .where("org_id", "=", a.orgId)
463
+ .where("device_id", "=", a.deviceId)
464
+ .where("extension", "=", extension)
465
+ .where("service", "=", service)
466
+ .executeTakeFirst();
467
+ return row?.stop_owed_at ?? null;
468
+ }
469
+ /**
470
+ * After a confirmed stop: deletes the placement only while its owed mark is still `mark` (a
471
+ * switch-off that bumped it since keeps it). Whether it was deleted.
472
+ */
473
+ async clearOwed(a, extension, service, mark) {
474
+ const r = await this.db
475
+ .deleteFrom("device_host_services")
476
+ .where("org_id", "=", a.orgId)
477
+ .where("device_id", "=", a.deviceId)
478
+ .where("extension", "=", extension)
479
+ .where("service", "=", service)
480
+ // the mark as read back (milliseconds; PG keeps microseconds)
481
+ .where("stop_owed_at", ">=", mark)
482
+ .where("stop_owed_at", "<", new Date(mark.getTime() + 1))
483
+ .executeTakeFirst();
484
+ return Number(r.numDeletedRows) > 0;
485
+ }
486
+ /**
487
+ * Whether the extension is on in the org and on the deployment now, read in a short transaction
488
+ * of its own that takes `FOR SHARE` on the org's `extension_org_configs` row and the
489
+ * `extension_installs` row: every switch-off writes one of them before it marks placements owed,
490
+ * so a switch-off still open waits this read out and is then seen (never a stale "enabled" while
491
+ * its placement UPDATE missed a row inserted meanwhile). Called with the placement lock held,
492
+ * never the other way round.
493
+ */
494
+ async enabledNow(orgId, extension) {
495
+ await this.db
496
+ .selectFrom("extension_org_configs")
497
+ .select("enabled")
498
+ .where("org_id", "=", orgId)
499
+ .where("plugin", "=", extension)
500
+ .forShare()
501
+ .executeTakeFirst();
502
+ // deployment-wide: the extension's install record (none for a dev-loaded extension)
503
+ const install = await this.db
504
+ .selectFrom("extension_installs")
505
+ .select("desired_state")
506
+ .where("name", "=", extension)
507
+ .forShare()
508
+ .executeTakeFirst();
509
+ if (install !== undefined && install.desired_state !== "enabled")
510
+ return false;
511
+ return isExtensionEnabled(this.db, orgId, extension);
512
+ }
513
+ /**
514
+ * After a start or a found running service: when the extension is off now (switched off while
515
+ * the machine worked), the placement is marked owed and its delivery owed, so the switch-off's
516
+ * stop is never lost.
517
+ */
518
+ async oweIfOff(a, extension, service) {
519
+ if (await this.enabledNow(a.orgId, extension))
520
+ return;
521
+ await this.oweStop(a.orgId, a.deviceId, extension, service);
522
+ }
523
+ async oweStop(orgId, deviceId, extension, service) {
524
+ const rows = await this.db
525
+ .updateTable("device_host_services")
526
+ .set({ stop_owed_at: sql `now()` })
527
+ .where("org_id", "=", orgId)
528
+ .where("device_id", "=", deviceId)
529
+ .where("extension", "=", extension)
530
+ .where("service", "=", service)
531
+ .returning(owedMarkMicros.as("mark"))
532
+ .execute();
533
+ const mark = latestMark(rows);
534
+ if (mark !== null)
535
+ await oweHostServicesDelivery(this.outbox, { orgId, deviceId, extension }, mark);
536
+ }
537
+ /** Deletes the placement (a confirmed stop, or a start refused before anything ran). */
538
+ async unplace(a, extension, service) {
539
+ await this.db
540
+ .deleteFrom("device_host_services")
541
+ .where("org_id", "=", a.orgId)
542
+ .where("device_id", "=", a.deviceId)
543
+ .where("extension", "=", extension)
544
+ .where("service", "=", service)
545
+ .execute();
546
+ }
547
+ /**
548
+ * Admits a call (steps 2 to 5 of the class comment; step 1 is the caller's): the person, the
549
+ * device and the use the call works on.
550
+ */
551
+ async admit(caller, r, opts) {
552
+ await this.assertEnabled(caller, r.orgId);
553
+ const call = r.call;
554
+ if (call !== null) {
555
+ // the trigger account acts only when it is the conversation's owner (group threads,
556
+ // another member's message): never for the owner by anyone else's word
557
+ if (call.ownerAccountId === undefined || call.accountId !== call.ownerAccountId)
558
+ throw new DeviceAccessError("not_owner", HOST_NOT_OWNER_TEXT);
559
+ const root = callScopeOf(call)?.facts?.rootConversationId ??
560
+ (await rootConversationOf(this.db, call.conversationId));
561
+ const conv = await this.db
562
+ .selectFrom("conversations")
563
+ .select(["account_id"])
564
+ .where("id", "=", root)
565
+ .where("org_id", "=", call.orgId)
566
+ .where("deleted_at", "is", null)
567
+ .executeTakeFirst();
568
+ if (conv === undefined)
569
+ throw new DeviceAccessError("no_device", "The conversation does not exist.");
570
+ // the owner of the conversation itself, not only by the call's word
571
+ if (conv.account_id !== call.accountId)
572
+ throw new DeviceAccessError("not_owner", HOST_NOT_OWNER_TEXT);
573
+ }
574
+ else if (!(await this.isMember(r.orgId, r.accountId)))
575
+ throw notPersonal();
576
+ // the tool's chosen device must be a machine of the conversation's owner (the trigger account)
577
+ await this.assertPersonalMachine(r.orgId, r.accountId, r.deviceId);
578
+ return {
579
+ orgId: r.orgId,
580
+ accountId: r.accountId,
581
+ deviceId: r.deviceId,
582
+ use: useOf(r.orgId, r.accountId, r.deviceId, call),
583
+ signal: call?.signal ?? AbortSignal.timeout(opts.timeoutMs ?? PERSON_SCOPE_TIMEOUT_MS),
584
+ call,
585
+ gate: opts.gate,
586
+ };
587
+ }
588
+ /**
589
+ * The device is a live personal device of `accountId` in the org, on a dial-in provider (a
590
+ * machine of theirs) that serves the org now; `not_personal_device` otherwise (a device of
591
+ * someone else's reads the same as a missing one).
592
+ */
593
+ async assertPersonalMachine(orgId, accountId, deviceId) {
594
+ const row = await this.db
595
+ .selectFrom("devices")
596
+ .select(["provider"])
597
+ .where("id", "=", deviceId)
598
+ .where("org_id", "=", orgId)
599
+ .where("owner_kind", "=", "personal")
600
+ .where("owner_account_id", "=", accountId)
601
+ .where("deleted_at", "is", null)
602
+ .executeTakeFirst();
603
+ if (row === undefined)
604
+ throw notPersonal();
605
+ const provider = this.providers.forDevice(row.provider);
606
+ if (provider !== undefined && !servesDialIn(provider))
607
+ throw new DeviceAccessError("not_personal_device", "Host services run only on a device connected from the person's own machine (capybara-device); this device is not one.");
608
+ try {
609
+ await this.access.usable(orgId, accountId, deviceId);
610
+ }
611
+ catch (e) {
612
+ if (e instanceof ApiError && e.code === "device.not_found")
613
+ throw notPersonal(e);
614
+ throw deviceRefusal(e, this.log);
615
+ }
616
+ }
617
+ /**
618
+ * Runs `fn` on the admitted device's provider (a silent use of the device), after the host gate
619
+ * (step 5) when the call is gated: read inside the use, where the device's instance runs and its
620
+ * provider's support (the machine owner's outside-sandbox setting) is known, and before anything
621
+ * reaches the machine's services ({@link HostServiceGate.admit}: `fn` is dispatched under the
622
+ * gate's shared authority locks).
623
+ */
624
+ async onDevice(caller, service, a, fn) {
625
+ try {
626
+ return await this.sandbox.withDeviceServices(a.use, requireHostServices, (h, p, sig) => a.gate
627
+ ? this.gate.admit(a.orgId, a.deviceId, (closed) => {
628
+ throw gateClosed(closed);
629
+ }, () => fn(h, p, sig))
630
+ : fn(h, p, sig), a.signal);
631
+ }
632
+ catch (e) {
633
+ if (isConsentMissing(e))
634
+ throw new DeviceAccessError("host_consent_missing", `Allow it on the machine: capybara-device services allow ${caller.extension}.${service}`, { cause: e });
635
+ if (e instanceof DeviceAccessError)
636
+ throw e;
637
+ throw deviceRefusal(e, this.log);
638
+ }
639
+ }
640
+ /**
641
+ * One audit row per new process: whichever call saw the start first writes it (a check, then
642
+ * the insert, as `device.service_started` does), in one transaction.
643
+ */
644
+ async auditStart(caller, a, service, serviceId, digest, started) {
645
+ if (started.startedAt !== null) {
646
+ const seen = await this.db
647
+ .selectFrom("audit_events")
648
+ .select("id")
649
+ .where("org_id", "=", a.orgId)
650
+ .where("action", "=", HOST_SERVICE_STARTED_ACTION)
651
+ .where("target", "=", a.deviceId)
652
+ .where(sql `detail->>'serviceId'`, "=", serviceId)
653
+ .where(sql `detail->>'startedAt'`, "=", started.startedAt)
654
+ // the start just happened: the (org_id, at) index keeps the range tiny
655
+ .where("at", ">=", sql `now() - interval '10 minutes'`)
656
+ .executeTakeFirst();
657
+ if (seen !== undefined)
658
+ return;
659
+ }
660
+ await audit(this.db, {
661
+ actorAccountId: a.accountId,
662
+ orgId: a.orgId,
663
+ action: HOST_SERVICE_STARTED_ACTION,
664
+ target: a.deviceId,
665
+ detail: {
666
+ deviceId: a.deviceId,
667
+ extension: caller.extension,
668
+ service,
669
+ digest,
670
+ serviceId,
671
+ startedAt: started.startedAt,
672
+ },
673
+ });
674
+ }
675
+ /**
676
+ * Step 1 of the admission: the service is one of the approved manifest's host services, and the
677
+ * extension did not come from an org-owned catalog item.
678
+ */
679
+ async assertDeclared(caller, service) {
680
+ if (!(caller.hostServices ?? []).includes(service))
681
+ throw new DeviceAccessError("host_not_declared", `The device service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.hostServices of ${caller.extension}.`);
682
+ if (await this.orgOwned(caller.extension))
683
+ throw new DeviceAccessError("host_not_declared", `${caller.extension} is an organization's own plugin; only platform plugins may run host services.`);
684
+ }
685
+ /** Whether the extension came from an org-owned catalog item (its install's or a source's). */
686
+ async orgOwned(extension) {
687
+ const row = await this.db
688
+ .selectFrom("catalog_items as ci")
689
+ .select("ci.id")
690
+ .where("ci.owner_org_id", "is not", null)
691
+ .where((eb) => eb.or([
692
+ eb("ci.id", "in", eb
693
+ .selectFrom("extension_installs as ei")
694
+ .select("ei.catalog_item_id")
695
+ .where("ei.name", "=", extension)
696
+ .where("ei.catalog_item_id", "is not", null)),
697
+ eb("ci.id", "in", eb
698
+ .selectFrom("extension_catalog_sources as cs")
699
+ .select("cs.item_id")
700
+ .where("cs.plugin", "=", extension)),
701
+ ]))
702
+ .executeTakeFirst();
703
+ return row !== undefined;
704
+ }
705
+ async assertEnabled(caller, orgId) {
706
+ if (!(await isExtensionEnabled(this.db, orgId, caller.extension)))
707
+ throw notEnabled(caller.extension);
708
+ }
709
+ async isMember(orgId, accountId) {
710
+ const m = await this.db
711
+ .selectFrom("memberships")
712
+ .select("account_id")
713
+ .where("org_id", "=", orgId)
714
+ .where("account_id", "=", accountId)
715
+ .executeTakeFirst();
716
+ return m !== undefined;
717
+ }
718
+ };
719
+ __decorate([
720
+ Transactional()
721
+ ], HostServiceAccess.prototype, "settle", null);
722
+ __decorate([
723
+ Transactional()
724
+ ], HostServiceAccess.prototype, "place", null);
725
+ __decorate([
726
+ Transactional()
727
+ ], HostServiceAccess.prototype, "clearOwed", null);
728
+ __decorate([
729
+ Transactional()
730
+ ], HostServiceAccess.prototype, "enabledNow", null);
731
+ __decorate([
732
+ Transactional()
733
+ ], HostServiceAccess.prototype, "oweStop", null);
734
+ __decorate([
735
+ Transactional()
736
+ ], HostServiceAccess.prototype, "unplace", null);
737
+ __decorate([
738
+ Transactional()
739
+ ], HostServiceAccess.prototype, "auditStart", null);
740
+ HostServiceAccess = __decorate([
741
+ Injectable(),
742
+ __param(0, Inject(KernelDb)),
743
+ __param(1, Inject(SandboxService)),
744
+ __param(2, Inject(DeviceAccess)),
745
+ __param(3, Inject(DevicesService)),
746
+ __param(4, Inject(DeviceProviders)),
747
+ __param(5, Inject(HostServiceGate)),
748
+ __param(6, Inject(KERNEL_LOGGER)),
749
+ __param(7, Inject(LockService)),
750
+ __param(8, Inject(OutboxService)),
751
+ __param(9, Inject(TransactionHost))
752
+ ], HostServiceAccess);
753
+ export { HostServiceAccess };
754
+ /** The device use of a host service call: silent, held by the conversation or the person. */
755
+ function useOf(orgId, accountId, deviceId, call) {
756
+ const holder = call?.conversationId ?? PERSON_SCOPE_HOLDER;
757
+ return {
758
+ orgId,
759
+ deviceId,
760
+ holderConversationId: holder,
761
+ actor: { accountId, conversationId: holder },
762
+ silent: true,
763
+ };
764
+ }
765
+ function ensureOf(p) {
766
+ return p.ensureService;
767
+ }
768
+ /** Refuses a provider without the device service methods before the device is touched. */
769
+ function requireHostServices(p) {
770
+ if (!p.ensureService || !p.stopService || !p.serviceRequest)
771
+ throw new DeviceAccessError("capability_missing", "This device's provider cannot run device services, so it cannot run host services.");
772
+ }
773
+ /**
774
+ * A provider's refusal of a host start for want of the owner's consent: a `DeviceAccessError`
775
+ * with `host_consent_missing`, by name and code (a provider may carry its own SDK copy).
776
+ */
777
+ function isConsentMissing(e) {
778
+ return (typeof e === "object" &&
779
+ e !== null &&
780
+ e.name === "DeviceAccessError" &&
781
+ e.code === "host_consent_missing");
782
+ }
783
+ function notEnabled(extension) {
784
+ return new DeviceAccessError("capability_missing", `The extension ${extension} is not enabled in the organization.`);
785
+ }
786
+ function notPersonal(cause) {
787
+ return new DeviceAccessError("not_personal_device", "Host services run only on the person's own personal device; this device is not theirs.", cause === undefined ? undefined : { cause });
788
+ }
789
+ function gateClosed(why) {
790
+ return new DeviceAccessError("host_gate_closed", why === "outside_sandbox_off"
791
+ ? "Host services need running outside the sandbox, which is off for this device: the platform, the organization or the machine's owner keeps it off. A super admin, an org admin or the device's owner can allow it."
792
+ : "Host services need the whole machine in reach, which the platform or the organization caps for this device: its project reach is below machine. A super admin or an org admin can set project reach to machine.");
793
+ }
794
+ /** The device resolution's API errors as the extension's refusal codes (as `ctx.deviceAccess`). */
795
+ function deviceRefusal(e, log) {
796
+ if (e instanceof ApiError) {
797
+ if (e.code === "device.not_found" || e.code === "sandbox.unavailable")
798
+ return new DeviceAccessError("no_device", e.message, { cause: e });
799
+ if (e.code === "device.unavailable")
800
+ return new DeviceAccessError("provider_unavailable", e.message, { cause: e });
801
+ }
802
+ return mapSandboxError(e, log);
803
+ }