@capybara-hq/kernel 0.1.0-rc.66 → 0.1.0-rc.67

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 (139) hide show
  1. package/bootstrap.json +0 -8
  2. package/dist/admin/admin.schemas.d.ts +3 -0
  3. package/dist/agents/admin-agents.d.ts +2 -2
  4. package/dist/agents/admin-agents.js +2 -1
  5. package/dist/agents/agent-lookup.js +2 -1
  6. package/dist/agents/agent-profile.service.d.ts +5 -2
  7. package/dist/agents/agent-profile.service.js +13 -2
  8. package/dist/agents/agents.controller.d.ts +4 -3
  9. package/dist/agents/agents.controller.js +7 -3
  10. package/dist/agents/agents.module.js +3 -0
  11. package/dist/agents/agents.schemas.d.ts +6 -6
  12. package/dist/agents/agents.service.d.ts +23 -2
  13. package/dist/agents/agents.service.js +61 -6
  14. package/dist/agents/avatar-view.d.ts +8 -0
  15. package/dist/agents/avatar-view.js +12 -0
  16. package/dist/agents/profile.d.ts +38 -13
  17. package/dist/agents/profile.js +31 -20
  18. package/dist/background/poll.job.d.ts +1 -1
  19. package/dist/background/poll.job.js +8 -6
  20. package/dist/background/tasks.service.js +1 -1
  21. package/dist/catalog/marketplaces.service.d.ts +1 -1
  22. package/dist/channels/inbound.d.ts +2 -3
  23. package/dist/channels/inbound.js +2 -3
  24. package/dist/channels/phrases.d.ts +3 -3
  25. package/dist/channels/phrases.js +3 -3
  26. package/dist/config/schema.d.ts +1 -0
  27. package/dist/config/schema.js +14 -1
  28. package/dist/conversations/conversations.service.d.ts +4 -3
  29. package/dist/conversations/conversations.service.js +4 -2
  30. package/dist/ctx/create-ctx.js +5 -2
  31. package/dist/ctx/device-provider-check.d.ts +7 -0
  32. package/dist/ctx/device-provider-check.js +21 -0
  33. package/dist/db/kernel-schema.d.ts +7 -0
  34. package/dist/devices/access.d.ts +16 -46
  35. package/dist/devices/access.js +26 -62
  36. package/dist/devices/access.module.js +2 -2
  37. package/dist/devices/conversation-devices.d.ts +38 -18
  38. package/dist/devices/conversation-devices.js +69 -51
  39. package/dist/devices/default-provider-setting.d.ts +45 -0
  40. package/dist/devices/default-provider-setting.js +59 -0
  41. package/dist/devices/device-projects.service.js +7 -2
  42. package/dist/devices/device-provider-selection.d.ts +37 -0
  43. package/dist/devices/device-provider-selection.js +86 -0
  44. package/dist/devices/device-provider-selection.module.d.ts +3 -0
  45. package/dist/devices/device-provider-selection.module.js +22 -0
  46. package/dist/devices/devices.controller.d.ts +8 -5
  47. package/dist/devices/devices.controller.js +7 -4
  48. package/dist/devices/devices.module.js +3 -1
  49. package/dist/devices/devices.schemas.js +2 -2
  50. package/dist/devices/devices.service.d.ts +72 -83
  51. package/dist/devices/devices.service.js +139 -248
  52. package/dist/devices/dto.d.ts +9 -0
  53. package/dist/devices/dto.js +15 -2
  54. package/dist/devices/label.d.ts +3 -5
  55. package/dist/devices/label.js +3 -14
  56. package/dist/devices/legacy-cleanup.job.d.ts +2 -2
  57. package/dist/devices/legacy-cleanup.job.js +6 -6
  58. package/dist/errors.d.ts +15 -1
  59. package/dist/errors.js +15 -1
  60. package/dist/extensions/guide-places.d.ts +2 -1
  61. package/dist/extensions/guide-places.js +8 -2
  62. package/dist/extensions/locks.d.ts +1 -1
  63. package/dist/extensions/locks.js +1 -1
  64. package/dist/extensions/org-config.d.ts +20 -4
  65. package/dist/extensions/org-config.js +23 -6
  66. package/dist/extensions/permission-view.d.ts +2 -2
  67. package/dist/extensions/permission-view.js +2 -2
  68. package/dist/extensions/plugin-guides.d.ts +1 -1
  69. package/dist/extensions/plugin-guides.js +11 -3
  70. package/dist/extensions/point-defaults.d.ts +14 -0
  71. package/dist/extensions/point-defaults.js +70 -47
  72. package/dist/extensions/resolve.js +7 -2
  73. package/dist/identity/settings.d.ts +8 -0
  74. package/dist/identity/settings.js +24 -1
  75. package/dist/infra/config/kernel-config.service.js +2 -0
  76. package/dist/lifecycle/kernel-lifecycle.js +7 -6
  77. package/dist/local-devices/device-routes.d.ts +1 -1
  78. package/dist/local-devices/device-routes.js +1 -1
  79. package/dist/local-devices/local-device-provider.d.ts +14 -11
  80. package/dist/local-devices/local-device-provider.js +14 -0
  81. package/dist/local-devices/local-devices.module.d.ts +4 -4
  82. package/dist/local-devices/local-devices.module.js +5 -3
  83. package/dist/local-devices/owner-report.js +2 -1
  84. package/dist/local-devices/targets.d.ts +2 -0
  85. package/dist/local-devices/targets.js +10 -0
  86. package/dist/orgs/settings.service.d.ts +26 -1
  87. package/dist/orgs/settings.service.js +44 -3
  88. package/dist/platform/ops/admin.ops.js +8 -3
  89. package/dist/platform/ops/agents.ops.d.ts +6 -1
  90. package/dist/platform/ops/agents.ops.js +38 -11
  91. package/dist/platform/ops/devices.ops.js +25 -20
  92. package/dist/platform/ops/orgs.ops.js +1 -0
  93. package/dist/platform/ops/themes.ops.js +1 -1
  94. package/dist/runtime/plugin-context.service.js +1 -12
  95. package/dist/sandbox/cloud-permission-snapshot.d.ts +2 -2
  96. package/dist/sandbox/cloud-permission-snapshot.js +3 -3
  97. package/dist/sandbox/device-reports.d.ts +50 -0
  98. package/dist/sandbox/device-reports.js +157 -0
  99. package/dist/sandbox/held-operations.d.ts +8 -8
  100. package/dist/sandbox/leases.d.ts +1 -1
  101. package/dist/sandbox/leases.js +1 -1
  102. package/dist/sandbox/operation-authority.d.ts +5 -2
  103. package/dist/sandbox/operation-authority.js +12 -11
  104. package/dist/sandbox/operation-reconcile.job.d.ts +2 -2
  105. package/dist/sandbox/operation-reconcile.job.js +5 -5
  106. package/dist/sandbox/permission-availability.d.ts +2 -2
  107. package/dist/sandbox/permission-call-types.d.ts +5 -0
  108. package/dist/sandbox/permission-facts.d.ts +2 -2
  109. package/dist/sandbox/permission-facts.js +5 -5
  110. package/dist/sandbox/providers.d.ts +23 -24
  111. package/dist/sandbox/providers.js +38 -46
  112. package/dist/sandbox/providers.module.js +3 -3
  113. package/dist/sandbox/sandbox.module.d.ts +1 -1
  114. package/dist/sandbox/sandbox.module.js +7 -2
  115. package/dist/sandbox/sandbox.service.d.ts +95 -68
  116. package/dist/sandbox/sandbox.service.js +212 -208
  117. package/dist/setup/setup-guides.service.d.ts +4 -1
  118. package/dist/setup/setup-guides.service.js +6 -1
  119. package/dist/themes/avatar-preset-key.d.ts +6 -0
  120. package/dist/themes/avatar-preset-key.js +9 -0
  121. package/dist/themes/theme-state.d.ts +29 -1
  122. package/dist/themes/theme-state.js +40 -1
  123. package/dist/themes/themes.service.d.ts +28 -1
  124. package/dist/themes/themes.service.js +36 -2
  125. package/dist/tools/builtins/image/generate.d.ts +3 -0
  126. package/dist/tools/builtins/image/generate.js +21 -11
  127. package/dist/tools/builtins/image/index.d.ts +1 -1
  128. package/dist/tools/builtins/image/index.js +1 -1
  129. package/dist/tools/builtins/sandbox/common.d.ts +36 -12
  130. package/dist/tools/builtins/sandbox/common.js +62 -18
  131. package/dist/tools/builtins/sandbox/read.d.ts +5 -2
  132. package/dist/tools/builtins/sandbox/read.js +9 -6
  133. package/dist/tools/builtins/sandbox/task-output.d.ts +2 -2
  134. package/dist/tools/builtins/sandbox/task-output.js +6 -5
  135. package/dist/tools/builtins/skill-load.js +13 -4
  136. package/dist/until-aborted.d.ts +5 -0
  137. package/dist/until-aborted.js +16 -0
  138. package/package.json +4 -4
  139. package/src/migrations/0176_device_report.sql +6 -0
@@ -25,24 +25,41 @@ import { deviceLeaseKey } from "../local-devices/keys.js";
25
25
  import { MachinesService } from "../local-devices/machines.js";
26
26
  import { ownerFactsOf } from "../local-devices/owner-report.js";
27
27
  import { deviceFeaturesOf, localPolicyOf } from "../local-devices/policy-summary.js";
28
+ import { DeviceReports } from "../sandbox/device-reports.js";
28
29
  import { hostGrantable } from "../sandbox/device-sandbox.js";
29
30
  import { oweDeviceDestroy, SandboxJobs } from "../sandbox/jobs.js";
30
31
  import { coversHost, projectReachOf, } from "../sandbox/modes.js";
31
32
  import { hostsNarrowed, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
32
33
  import { cloudOwnNetwork, networkOfSandbox, PermissionFacts } from "../sandbox/permission-facts.js";
33
- import { isInternalProvider, LOCAL_PROVIDER, SandboxProviders } from "../sandbox/providers.js";
34
+ import { isInternalProvider, LOCAL_PROVIDER, } from "../sandbox/providers.js";
34
35
  import { deviceNotFound, SandboxService } from "../sandbox/sandbox.service.js";
35
- import { DeviceAccess, demotedProvider, deviceProvider, deviceUnavailable, inUseForDefault, } from "./access.js";
36
+ import { DeviceAccess } from "./access.js";
37
+ import { DeviceProviderSelection } from "./device-provider-selection.js";
36
38
  /** How many recent setting changes a device view lists. */
37
39
  export const RECENT_POLICY_CHANGES = 10;
38
40
  const isUniqueViolation = (e, constraint) => typeof e === "object" &&
39
41
  e !== null &&
40
42
  e.code === "23505" &&
41
43
  e.constraint === constraint;
44
+ /** The names of `on`, for a refusal's message; a hint when there are none. */
45
+ const providerChoices = (on) => on.length > 0
46
+ ? on.map((e) => e.plugin).join(", ")
47
+ : "none is on in this organization; ask an org admin to switch one on";
48
+ /** A new device names no provider and the org has no default one serving it (400). */
49
+ const providerRequired = (on) => new ApiError("device.provider_required", `Choose a device provider: ${providerChoices(on)}`);
50
+ /**
51
+ * A new device names a provider that does not serve the org (unknown, not loaded, off in the org,
52
+ * or kernel-internal): `validation_failed` at `provider`.
53
+ */
54
+ const providerNotOn = (provider, on) => {
55
+ const message = `Device provider ${provider} is not on in this organization; choose one of: ${providerChoices(on)}`;
56
+ return new ApiError("validation_failed", message, [{ path: "provider", message }]);
57
+ };
42
58
  const nameTaken = () => new ApiError("device.name_taken", "You already have a device with this name");
43
59
  /**
44
60
  * Personal devices (spec 2026-11-07-environments-design §4.2 items 7, 12, 13; §6; §9):
45
- * cloud ones on the deployment's sandbox provider and `device` ones on a connected machine; a
61
+ * cloud ones, each bound for life to the device provider it was created on (device-provider spec
62
+ * §6.1), and `local` ones on a connected machine; a
46
63
  * person's devices in an org, visible and usable only by their owner (anyone else gets
47
64
  * `device.not_found`). Deleting one soft-deletes it and owes the destruction of its instance and
48
65
  * files (a `sandbox-destroy-for` job) in the same transaction.
@@ -51,45 +68,56 @@ let DevicesService = class DevicesService {
51
68
  db;
52
69
  txHost;
53
70
  config;
54
- providers;
71
+ selection;
55
72
  sandbox;
56
73
  sandboxJobs;
57
74
  outbox;
58
75
  access;
59
- displayNames;
60
76
  locks;
61
77
  machines;
62
78
  policies;
63
79
  ceilings;
64
80
  facts;
65
- constructor(db, txHost, config, providers, sandbox, sandboxJobs,
81
+ displayNames;
82
+ reports;
83
+ constructor(db, txHost, config, selection, sandbox, sandboxJobs,
66
84
  /** Owes a deleted device's destruction in the delete's transaction. */
67
- outbox, access, displayNames,
85
+ outbox, access,
68
86
  /** Reads the device relay's lease (`online`). */
69
- locks, machines, policies, ceilings, facts) {
87
+ locks, machines, policies, ceilings, facts, displayNames,
88
+ /** Each device's stored provider report (read only; never asks the provider). */
89
+ reports) {
70
90
  this.db = db;
71
91
  this.txHost = txHost;
72
92
  this.config = config;
73
- this.providers = providers;
93
+ this.selection = selection;
74
94
  this.sandbox = sandbox;
75
95
  this.sandboxJobs = sandboxJobs;
76
96
  this.outbox = outbox;
77
97
  this.access = access;
78
- this.displayNames = displayNames;
79
98
  this.locks = locks;
80
99
  this.machines = machines;
81
100
  this.policies = policies;
82
101
  this.ceilings = ceilings;
83
102
  this.facts = facts;
103
+ this.displayNames = displayNames;
104
+ this.reports = reports;
84
105
  }
85
106
  /**
86
- * The person's live devices in the org, the default first, then by creation. With a
87
- * current sandbox provider the default device is created first if missing (its first need,
88
- * spec §4.2 item 7; an existing one is only read).
107
+ * The person's live devices in the org, the default first, then by creation, with the device
108
+ * providers on in the org and its default one. With a default provider serving the org the
109
+ * default device is created first if missing (its first need, spec §4.2 item 7; an existing one
110
+ * is only read, whatever its provider's state).
89
111
  */
90
112
  async list(orgId, accountId) {
91
- const cloudAvailable = this.providers.cloud() !== undefined;
92
- const defaultId = cloudAvailable ? await this.ensureDefault(orgId, accountId) : null;
113
+ const on = await this.selection.onInOrg(orgId);
114
+ const names = await this.displayNames.many(on.map((e) => e.plugin));
115
+ const providers = on.map((e) => ({
116
+ plugin: e.plugin,
117
+ displayName: names.get(e.plugin) ?? null,
118
+ }));
119
+ const defaultProvider = (await this.selection.defaultFor(orgId))?.plugin ?? null;
120
+ const defaultId = await this.ensureDefault(orgId, accountId);
93
121
  const items = await this.views(orgId, accountId);
94
122
  const last = await this.db
95
123
  .selectFrom("conversations as c")
@@ -108,7 +136,8 @@ let DevicesService = class DevicesService {
108
136
  items,
109
137
  defaultId: defaultId ?? items.find((v) => v.isDefault)?.id ?? null,
110
138
  lastUsedId: last?.device_id ?? null,
111
- cloudAvailable,
139
+ providers,
140
+ defaultProvider,
112
141
  };
113
142
  }
114
143
  /** One of the person's live devices; anyone else's (or a missing one) → `not_found`. */
@@ -119,26 +148,44 @@ let DevicesService = class DevicesService {
119
148
  return view;
120
149
  }
121
150
  /**
122
- * A new personal cloud device, ready at once (its instance and files are made on first
123
- * use). Needs a current sandbox provider (`device.unavailable`); a live name of the person's
124
- * (case-insensitive) → `device.name_taken`; `devices.maxPersonal` live ones (the
151
+ * A new personal cloud device, ready at once (its instance and files are made on first use),
152
+ * bound for life to `input.provider` or, without one, the org's default provider: a provider not
153
+ * on in the org (unknown, not loaded, off, kernel-internal) → `validation_failed` at `provider`;
154
+ * none named and no default serving the org → `device.provider_required`. A live name of the
155
+ * person's (case-insensitive) → `device.name_taken`; `devices.maxPersonal` live ones (the
125
156
  * default counts) → `device.limit_reached`. Serialized per person by their membership row.
157
+ * Nothing is written before every refusal is past.
126
158
  */
127
159
  async create(orgId, accountId, input, actorTokenId, auditDetail) {
128
- const id = await this.insert(orgId, accountId, input.name, actorTokenId, auditDetail);
160
+ const provider = await this.providerFor(orgId, input.provider);
161
+ const id = await this.insert(orgId, accountId, input.name, provider, actorTokenId, auditDetail);
129
162
  return this.get(orgId, accountId, id);
130
163
  }
131
- async insert(orgId, accountId, name, actorTokenId, auditDetail) {
132
- const current = this.providers.cloud();
133
- if (!current)
134
- throw deviceUnavailable(null);
135
- return this.insertNamed(orgId, accountId, name, "cloud", current.plugin, actorTokenId, auditDetail ?? {});
164
+ /**
165
+ * The provider a new cloud device of `orgId` is bound to: `named` when it serves the org now
166
+ * (one of {@link DeviceProviderSelection.onInOrg}), else the org's default
167
+ * ({@link DeviceProviderSelection.defaultFor}) when none is named; never another one.
168
+ */
169
+ async providerFor(orgId, named) {
170
+ const on = await this.selection.onInOrg(orgId);
171
+ if (named !== undefined) {
172
+ if (on.some((e) => e.plugin === named))
173
+ return named;
174
+ throw providerNotOn(named, on);
175
+ }
176
+ const fallback = await this.selection.defaultFor(orgId);
177
+ if (!fallback)
178
+ throw providerRequired(on);
179
+ return fallback.plugin;
180
+ }
181
+ async insert(orgId, accountId, name, provider, actorTokenId, auditDetail) {
182
+ return this.insertNamed(orgId, accountId, name, "cloud", provider, actorTokenId, auditDetail ?? {});
136
183
  }
137
184
  /**
138
185
  * A new personal local device for a machine being connected (provider `@local`; the
139
186
  * machine row is the caller's). Joins the caller's transaction (the device authorization's).
140
187
  * Counted against `devices.maxPersonal` (`device.limit_reached`); a live name of the
141
- * person's → `device.name_taken`. Needs no cloud provider.
188
+ * person's → `device.name_taken`. Needs no device provider on in the org.
142
189
  */
143
190
  async createLocal(orgId, accountId, name) {
144
191
  const id = await this.insertNamed(orgId, accountId, name, "local", LOCAL_PROVIDER, undefined, {
@@ -148,7 +195,8 @@ let DevicesService = class DevicesService {
148
195
  }
149
196
  /**
150
197
  * Inserts a named personal device under the person's membership lock, after the limit
151
- * and name checks, and audits `device.created`. Runs in the caller's transaction.
198
+ * and name checks, and audits `device.created` (with its provider). Runs in the caller's
199
+ * transaction.
152
200
  */
153
201
  async insertNamed(orgId, accountId, name, source, provider, actorTokenId, auditDetail) {
154
202
  await this.lockMember(orgId, accountId);
@@ -191,18 +239,18 @@ let DevicesService = class DevicesService {
191
239
  orgId,
192
240
  action: "device.created",
193
241
  target: id,
194
- detail: { name, ...auditDetail },
242
+ detail: { name, provider, ...auditDetail },
195
243
  });
196
244
  return id;
197
245
  }
198
246
  /**
199
247
  * The refusals {@link create} would raise, read without locks or writes (a precheck before a
200
- * confirmation card): no sandbox provider, the person's limit, a name already taken. Throws the
201
- * same {@link ApiError}s; a race still ends in `create`'s own refusal.
248
+ * confirmation card): the provider (named and not on in the org, or none and no default), the
249
+ * person's limit, a name already taken. Throws the same {@link ApiError}s; a race still ends in
250
+ * `create`'s own refusal.
202
251
  */
203
- async checkCreate(orgId, accountId, name) {
204
- if (!this.providers.cloud())
205
- throw deviceUnavailable(null);
252
+ async checkCreate(orgId, accountId, name, provider) {
253
+ await this.providerFor(orgId, provider);
206
254
  const { n } = await this.db
207
255
  .selectFrom("devices")
208
256
  .select((eb) => eb.fn.countAll().as("n"))
@@ -455,7 +503,7 @@ let DevicesService = class DevicesService {
455
503
  try {
456
504
  await this.db
457
505
  .updateTable("devices")
458
- .set({ name, demoted_from_provider: null, updated_at: sql `now()` })
506
+ .set({ name, updated_at: sql `now()` })
459
507
  .where("id", "=", id)
460
508
  .execute();
461
509
  }
@@ -584,78 +632,32 @@ let DevicesService = class DevicesService {
584
632
  });
585
633
  }
586
634
  /**
587
- * The person's default device in the org, created when missing (named by the UI, `name`
588
- * NULL). An existing usable one is read without locking. A live default whose files or
589
- * instance are kept by a provider that is not the current one (a provider switch, spec §4.2
590
- * item 13) is stranded: it is demoted (marked with the provider it was demoted from; the UI
591
- * names it 「个人设备(<provider display name>)」) and stays listed as unavailable and deletable.
592
- * Its replacement is the person's former default demoted from the current provider when there
593
- * is one (switching back restores it, with its files), else a fresh default. A live default
594
- * not in use yet (no healthy files, no instance, none being created: {@link inUseForDefault})
595
- * is likewise swapped for a former default holding healthy files at the current provider; it is
596
- * demoted (from the provider it was made under) so it can come back in turn. A former default
597
- * belongs to the provider holding its resources once it holds any, else to the one it was
598
- * demoted from ({@link demotedProvider}), so one swapped out empty and used afterwards is
599
- * labelled and restored by where its files are.
600
- * All of it in one transaction: switching back and forth never adds devices.
635
+ * The person's default device in the org: the live one if any, whatever its provider's state
636
+ * (a default whose provider is off stays the default, unavailable, never demoted or replaced),
637
+ * else a new default (named by the UI, `name` NULL) bound to the org's default provider
638
+ * ({@link DeviceProviderSelection.defaultFor}), else null (no default provider on in the org).
639
+ * An existing one is read without locking.
601
640
  *
602
- * Replacing one first takes the person's membership row (`FOR SHARE`, after the org row), so an
641
+ * Creating one first takes the person's membership row (`FOR SHARE`, after the org row), so an
603
642
  * offboarding that removes them cannot leave a live default behind; not a member (any more) →
604
- * `org.not_found`. Idempotent under concurrency: the live default row and the person's former
605
- * defaults of the current provider are locked (`FOR NO KEY UPDATE`) and the live default re-read
606
- * after them, the partial unique index on the live default makes a racing insert do nothing, and
607
- * the select that follows reads the winner. Needs a current sandbox provider
608
- * (`device.unavailable`). It is the person's baseline, so it is created even at
609
- * `devices.maxPersonal`.
643
+ * `org.not_found`. Idempotent under concurrency: the partial unique index on the live default
644
+ * makes a racing insert do nothing, and the select that follows reads the winner. It is the
645
+ * person's baseline, so it is created even at `devices.maxPersonal`.
610
646
  */
611
647
  async ensureDefault(orgId, accountId) {
612
648
  const live = await this.defaultOf(orgId, accountId);
613
- if (live && !this.stranded(live)) {
614
- const current = this.providers.cloud()?.plugin;
615
- if (inUseForDefault(live) || current === undefined)
616
- return live.id;
617
- const former = await this.formerDefaults(orgId, accountId, current);
618
- // Two unlocked reads: a swap committed between them leaves `live` demoted and the restored
619
- // default out of `former`. Only a default still live after `former` is the answer; else
620
- // the locked path decides.
621
- if (!former.some((f) => f.holdsFiles)) {
622
- if ((await this.defaultOf(orgId, accountId))?.id === live.id)
623
- return live.id;
624
- }
625
- }
626
- return this.insertDefault(orgId, accountId);
649
+ if (live)
650
+ return live.id;
651
+ const provider = await this.selection.defaultFor(orgId);
652
+ if (!provider)
653
+ return null;
654
+ return this.insertDefault(orgId, accountId, provider.plugin);
627
655
  }
628
- async insertDefault(orgId, accountId) {
629
- const current = this.providers.cloud();
630
- if (!current)
631
- throw deviceUnavailable(null);
656
+ async insertDefault(orgId, accountId, provider) {
632
657
  await this.lockMember(orgId, accountId, "share");
633
- const locked = await this.defaultOf(orgId, accountId, true);
634
- const former = await this.formerDefaults(orgId, accountId, current.plugin, true);
635
- // a racing replacement committed while this waited: its default is the answer
636
- const live = locked ?? (await this.defaultOf(orgId, accountId));
637
- if (live && live !== locked)
638
- return live.id;
639
- const stranded = live !== undefined && this.stranded(live);
640
- const withFiles = former.find((f) => f.holdsFiles);
641
- if (live && !stranded && (inUseForDefault(live) || withFiles === undefined))
658
+ const live = await this.defaultOf(orgId, accountId);
659
+ if (live)
642
660
  return live.id;
643
- // a default is needed (none, or a stranded one): any former default will do, files first
644
- const restore = withFiles ?? (live === undefined || stranded ? former[0] : undefined);
645
- if (live) {
646
- const from = stranded
647
- ? (deviceProvider(live, current.plugin) ?? "unknown")
648
- : (live.provider ?? current.plugin);
649
- await this.demote(live.id, from);
650
- }
651
- if (restore) {
652
- await this.db
653
- .updateTable("devices")
654
- .set({ is_default: true, demoted_from_provider: null, updated_at: sql `now()` })
655
- .where("id", "=", restore.id)
656
- .execute();
657
- return restore.id;
658
- }
659
661
  await this.db
660
662
  .insertInto("devices")
661
663
  .values({
@@ -666,7 +668,7 @@ let DevicesService = class DevicesService {
666
668
  name: null,
667
669
  is_default: true,
668
670
  source: "cloud",
669
- provider: current.plugin,
671
+ provider,
670
672
  })
671
673
  .onConflict((oc) => oc
672
674
  .columns(["org_id", "owner_account_id"])
@@ -678,71 +680,6 @@ let DevicesService = class DevicesService {
678
680
  throw new Error("the default device was not created");
679
681
  return row.id;
680
682
  }
681
- /**
682
- * Turns the live default into an ordinary device marked as demoted from `provider`; a name
683
- * the person gave it stays. Runs under the person's membership lock and the default row's lock,
684
- * before any other row becomes the default (the partial unique index).
685
- */
686
- async demote(id, provider) {
687
- await this.db
688
- .updateTable("devices")
689
- .set({ is_default: false, demoted_from_provider: provider, updated_at: sql `now()` })
690
- .where("id", "=", id)
691
- .execute();
692
- }
693
- /**
694
- * The person's live former defaults of `provider` ({@link demotedProvider}: files or an instance
695
- * kept by `provider`, or none and demoted from it), the ones holding healthy files first (lost
696
- * files count as none), then the most recently used, then the most recently demoted. `lock`
697
- * takes their rows (`FOR NO KEY UPDATE`, in id order, so racing replacements queue on the same
698
- * rows).
699
- */
700
- async formerDefaults(orgId, accountId, provider, lock = false) {
701
- const rows = await this.db
702
- .selectFrom("devices as e")
703
- .leftJoin("device_instances as i", "i.device_id", "e.id")
704
- .select([
705
- "e.id",
706
- "e.provider",
707
- "e.updated_at",
708
- "i.provider as instance_provider",
709
- "i.fs_status",
710
- "e.demoted_from_provider",
711
- "i.handle",
712
- "i.status",
713
- "i.last_used_at",
714
- ])
715
- .where("e.org_id", "=", orgId)
716
- .where("e.owner_kind", "=", "personal")
717
- .where("e.owner_account_id", "=", accountId)
718
- .where("e.is_default", "=", false)
719
- .where("e.demoted_from_provider", "is not", null)
720
- .where((eb) => eb.or([eb("e.demoted_from_provider", "=", provider), eb("i.provider", "=", provider)]))
721
- .where("e.deleted_at", "is", null)
722
- .orderBy("e.id")
723
- .$if(lock, (q) => q.forNoKeyUpdate("e"))
724
- .execute();
725
- const time = (d) => d?.getTime() ?? 0;
726
- return rows
727
- .map((r) => {
728
- const facts = {
729
- provider: r.provider,
730
- instanceProvider: r.instance_provider,
731
- fsStatus: r.fs_status,
732
- hasInstance: r.handle !== null,
733
- };
734
- return {
735
- r,
736
- holdsFiles: inUseForDefault({ ...facts, status: r.status }),
737
- belongs: demotedProvider(r.demoted_from_provider, facts) === provider,
738
- };
739
- })
740
- .filter(({ belongs }) => belongs)
741
- .sort((a, b) => Number(b.holdsFiles) - Number(a.holdsFiles) ||
742
- time(b.r.last_used_at) - time(a.r.last_used_at) ||
743
- time(b.r.updated_at) - time(a.r.updated_at))
744
- .map(({ r, holdsFiles }) => ({ id: r.id, holdsFiles }));
745
- }
746
683
  /**
747
684
  * The person's IM default (what `/device` set): the device their next new IM conversation
748
685
  * uses. Null when none was set, or the chosen one is deleted (the row is cleared with it).
@@ -792,46 +729,20 @@ let DevicesService = class DevicesService {
792
729
  if (Number(written.numInsertedOrUpdatedRows ?? 0) === 0)
793
730
  throw deviceNotFound();
794
731
  }
795
- /**
796
- * The person's live default device in the org, if any, with what decides its provider;
797
- * `lock` takes its row (`FOR NO KEY UPDATE`; a racing demotion makes it read none).
798
- */
799
- async defaultOf(orgId, accountId, lock = false) {
800
- const row = await this.db
801
- .selectFrom("devices as e")
802
- .leftJoin("device_instances as i", "i.device_id", "e.id")
803
- .select([
804
- "e.id",
805
- "e.provider",
806
- "i.provider as instance_provider",
807
- "i.fs_status",
808
- "i.handle",
809
- "i.status",
810
- ])
811
- .where("e.org_id", "=", orgId)
812
- .where("e.owner_kind", "=", "personal")
813
- .where("e.owner_account_id", "=", accountId)
814
- .where("e.is_default", "=", true)
815
- .where("e.deleted_at", "is", null)
816
- .$if(lock, (q) => q.forNoKeyUpdate("e"))
732
+ /** The person's live default device in the org, if any. */
733
+ async defaultOf(orgId, accountId) {
734
+ return await this.db
735
+ .selectFrom("devices")
736
+ .select("id")
737
+ .where("org_id", "=", orgId)
738
+ .where("owner_kind", "=", "personal")
739
+ .where("owner_account_id", "=", accountId)
740
+ .where("is_default", "=", true)
741
+ .where("deleted_at", "is", null)
817
742
  .executeTakeFirst();
818
- return (row && {
819
- id: row.id,
820
- provider: row.provider,
821
- instanceProvider: row.instance_provider,
822
- fsStatus: row.fs_status,
823
- hasInstance: row.handle !== null,
824
- status: row.status,
825
- });
826
- }
827
- /** Its files or instance are kept by a provider that is not the current one. */
828
- stranded(f) {
829
- const current = this.providers.cloud()?.plugin;
830
- return current !== undefined && deviceProvider(f, current) !== current;
831
743
  }
832
744
  /** The person's live devices (or the one `id`) as views. */
833
745
  async views(orgId, accountId, id) {
834
- // all of them even for one `id`: a former default's ordinal counts its siblings
835
746
  const all = await this.db
836
747
  .selectFrom("devices as e")
837
748
  .leftJoin("device_instances as i", "i.device_id", "e.id")
@@ -842,7 +753,6 @@ let DevicesService = class DevicesService {
842
753
  "e.is_default",
843
754
  "e.source",
844
755
  "e.provider",
845
- "e.demoted_from_provider",
846
756
  "e.network_mode",
847
757
  "e.network_hosts",
848
758
  "e.permission_reconcile_required",
@@ -874,69 +784,49 @@ let DevicesService = class DevicesService {
874
784
  const rows = id === undefined ? all : all.filter((r) => r.id === id);
875
785
  if (rows.length === 0)
876
786
  return [];
877
- const factsOf = (r) => ({
878
- provider: r.provider,
879
- instanceProvider: r.instance_provider,
880
- fsStatus: r.fs_status,
881
- hasInstance: r.handle !== null,
882
- });
883
- // a former default is labelled after the provider holding its resources, else its marker
884
- const demoted = new Map(all.map((r) => [r.id, demotedProvider(r.demoted_from_provider, factsOf(r))]));
885
- const ordinals = new Map();
886
- const seen = new Map();
887
- for (const r of [...all].sort((a, b) => a.created_at.getTime() - b.created_at.getTime() || a.id.localeCompare(b.id))) {
888
- const from = demoted.get(r.id) ?? null;
889
- if (from === null || r.name !== null)
890
- continue;
891
- const n = (seen.get(from) ?? 0) + 1;
892
- seen.set(from, n);
893
- ordinals.set(r.id, n);
894
- }
895
- const demotedProviders = [
896
- ...new Set(rows.flatMap((r) => (demoted.get(r.id) ? [demoted.get(r.id)] : []))),
897
- ];
898
- const [names, recent] = await Promise.all([
899
- this.displayNames.many(demotedProviders),
900
- this.recentChanges(orgId, rows.map((r) => r.id)),
901
- ]);
787
+ const recent = await this.recentChanges(orgId, rows.map((r) => r.id));
788
+ // whether each provider serves the org now: the org's providers are evaluated once per
789
+ // request; a kernel-internal provider (`@local`) is on while registered (`isOnInOrg`)
790
+ const providerNames = [...new Set(rows.flatMap((r) => (r.provider ? [r.provider] : [])))];
791
+ const served = providerNames.some((p) => !isInternalProvider(p))
792
+ ? new Set((await this.selection.onInOrg(orgId)).map((e) => e.plugin))
793
+ : new Set();
794
+ const on = new Map(await Promise.all(providerNames.map(async (p) => [
795
+ p,
796
+ isInternalProvider(p) ? await this.selection.isOnInOrg(orgId, p) : served.has(p),
797
+ ])));
902
798
  // each device's sandbox, limits and its instance's pending change
903
799
  const perDevice = new Map(await Promise.all(rows.map(async (r) => {
904
800
  const policy = await this.sandbox.devicePolicy({ orgId, deviceId: r.id });
905
- const [limits, state, facts] = await Promise.all([
801
+ const [limits, state, facts, report] = await Promise.all([
906
802
  this.sandbox.deviceLimits({ orgId, deviceId: r.id }, { policy, source: r.source }),
907
803
  r.source === "cloud"
908
804
  ? this.sandbox.limitsState({ orgId, deviceId: r.id }, { policy })
909
805
  : { pendingNextUse: false, pendingFilesReset: false },
910
806
  this.facts.deviceSandboxFacts(orgId, r.id),
807
+ this.reports.read(orgId, r.id),
911
808
  ]);
912
- return [r.id, { limits, state, box: facts.box }];
809
+ return [r.id, { limits, state, box: facts.box, report }];
913
810
  })));
914
- const current = this.providers.cloud()?.plugin;
915
811
  // a local device is online while a replica holds its machine's connection lease
916
812
  const online = new Map(await Promise.all(rows
917
813
  .filter((r) => r.source === "local")
918
814
  .map(async (r) => [r.id, (await this.locks.holderOf(deviceLeaseKey(r.id))) !== null])));
919
815
  return rows.map((r) => {
920
- const provider = deviceProvider(factsOf(r), current);
816
+ const provider = r.provider;
921
817
  const live = (r.status === "running" || r.status === "suspended") && r.last_used_at;
922
- const from = demoted.get(r.id) ?? null;
923
818
  return {
924
819
  id: r.id,
925
820
  name: r.name,
926
821
  isDefault: r.is_default,
927
- demotedFrom: from === null
928
- ? null
929
- : {
930
- provider: from,
931
- displayName: names.get(from) ?? null,
932
- ordinal: ordinals.get(r.id) ?? 1,
933
- },
934
822
  ownerKind: "personal",
935
823
  source: r.source,
936
824
  provider,
937
- available: provider !== null && isInternalProvider(provider)
938
- ? this.providers.forName(provider) !== undefined
939
- : current !== undefined && provider === current,
825
+ // an instance row of another provider (never written by this kernel) is refused on use
826
+ available: provider !== null &&
827
+ (on.get(provider) ?? false) &&
828
+ (r.instance_provider === null || r.instance_provider === provider),
829
+ report: perDevice.get(r.id)?.report ?? null,
940
830
  online: r.source === "local" ? (online.get(r.id) ?? false) : null,
941
831
  machine: r.machine_id !== null && r.machine_name !== null && r.machine_os !== null
942
832
  ? {
@@ -1117,17 +1007,18 @@ DevicesService = __decorate([
1117
1007
  __param(0, Inject(KernelDb)),
1118
1008
  __param(1, Inject(TransactionHost)),
1119
1009
  __param(2, Inject(KernelConfigService)),
1120
- __param(3, Inject(SandboxProviders)),
1010
+ __param(3, Inject(DeviceProviderSelection)),
1121
1011
  __param(4, Inject(SandboxService)),
1122
1012
  __param(5, Inject(SandboxJobs)),
1123
1013
  __param(6, Inject(OutboxService)),
1124
1014
  __param(7, Inject(DeviceAccess)),
1125
- __param(8, Inject(ExtensionDisplayNames)),
1126
- __param(9, Inject(LockService)),
1127
- __param(10, Inject(MachinesService)),
1128
- __param(11, Inject(DevicePolicyService)),
1129
- __param(12, Inject(PermissionCeilingWrites)),
1130
- __param(13, Inject(PermissionFacts))
1015
+ __param(8, Inject(LockService)),
1016
+ __param(9, Inject(MachinesService)),
1017
+ __param(10, Inject(DevicePolicyService)),
1018
+ __param(11, Inject(PermissionCeilingWrites)),
1019
+ __param(12, Inject(PermissionFacts)),
1020
+ __param(13, Inject(ExtensionDisplayNames)),
1021
+ __param(14, Inject(DeviceReports))
1131
1022
  ], DevicesService);
1132
1023
  export { DevicesService };
1133
1024
  /**
@@ -4,6 +4,14 @@ export declare const DeviceName: z.ZodString;
4
4
  export declare const DeviceNameBody: z.ZodObject<{
5
5
  name: z.ZodString;
6
6
  }, z.core.$strict>;
7
+ /**
8
+ * `POST /devices`: a name and the device provider (a plugin name) it is bound to for life, one on
9
+ * in the org (`GET /devices` lists them); absent, the org's default provider.
10
+ */
11
+ export declare const DeviceCreateBody: z.ZodObject<{
12
+ name: z.ZodString;
13
+ provider: z.ZodOptional<z.ZodString>;
14
+ }, z.core.$strict>;
7
15
  export declare const DeviceParams: z.ZodObject<{
8
16
  id: z.ZodString;
9
17
  }, z.core.$strip>;
@@ -76,6 +84,7 @@ export declare const DeviceProjectParams: z.ZodObject<{
76
84
  }, z.core.$strip>;
77
85
  declare const DeviceCreateBodyDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
78
86
  name: z.ZodString;
87
+ provider: z.ZodOptional<z.ZodString>;
79
88
  }, z.core.$strict>>;
80
89
  export declare class DeviceCreateBodyDto extends DeviceCreateBodyDto_base {
81
90
  }
@@ -1,9 +1,22 @@
1
- import { isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, validateAllowHost, } from "@capybara-hq/plugin-sdk";
1
+ import { EXTENSION_NAME_RE, isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, validateAllowHost, } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
4
4
  /** A device's name: trimmed, 1-64 characters (unique per person, case-insensitive). */
5
5
  export const DeviceName = z.string().trim().min(1).max(64);
6
6
  export const DeviceNameBody = z.object({ name: DeviceName }).strict();
7
+ /**
8
+ * `POST /devices`: a name and the device provider (a plugin name) it is bound to for life, one on
9
+ * in the org (`GET /devices` lists them); absent, the org's default provider.
10
+ */
11
+ export const DeviceCreateBody = z
12
+ .object({
13
+ name: DeviceName,
14
+ provider: z
15
+ .string()
16
+ .regex(EXTENSION_NAME_RE, "must be a device provider's plugin name")
17
+ .optional(),
18
+ })
19
+ .strict();
7
20
  export const DeviceParams = z.object({ id: z.string().min(1).max(100) });
8
21
  /** One host of a device's network allowlist (`validateAllowHost`: lowercase, `*.` allowed). */
9
22
  const PolicyHost = z
@@ -106,7 +119,7 @@ export const DeviceProjectAddBody = z
106
119
  .strict();
107
120
  /** `DELETE /devices/:id/projects/:name`. */
108
121
  export const DeviceProjectParams = DeviceParams.extend({ name: DeviceProjectName });
109
- export class DeviceCreateBodyDto extends createZodDto(DeviceNameBody, "DeviceCreateBody") {
122
+ export class DeviceCreateBodyDto extends createZodDto(DeviceCreateBody, "DeviceCreateBody") {
110
123
  }
111
124
  export class DevicePatchBodyDto extends createZodDto(DevicePatchBody, "DevicePatchBody") {
112
125
  }