@capybara-hq/kernel 0.1.0-rc.59 → 0.1.0-rc.60

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/dist/admin/admin.controller.d.ts +10 -5
  2. package/dist/admin/admin.controller.js +16 -7
  3. package/dist/admin/admin.schemas.js +2 -1
  4. package/dist/admin/audit-log.service.d.ts +1 -0
  5. package/dist/admin/audit-log.service.js +4 -1
  6. package/dist/admin/extensions.schemas.js +2 -0
  7. package/dist/agents/admin-agents.d.ts +1 -0
  8. package/dist/agents/admin-agents.js +4 -1
  9. package/dist/agents/agents.controller.d.ts +1 -10
  10. package/dist/agents/agents.controller.js +2 -14
  11. package/dist/agents/agents.schemas.d.ts +10 -0
  12. package/dist/agents/agents.schemas.js +19 -0
  13. package/dist/background/tasks.service.d.ts +5 -0
  14. package/dist/background/tasks.service.js +10 -3
  15. package/dist/catalog/admin-catalog.schemas.js +2 -0
  16. package/dist/catalog/component-scope.schemas.js +2 -0
  17. package/dist/catalog/marketplaces.service.d.ts +1 -1
  18. package/dist/catalog/org-plugin-uploads.schemas.js +2 -0
  19. package/dist/catalog/requests.service.d.ts +2 -0
  20. package/dist/catalog/requests.service.js +4 -1
  21. package/dist/channels/cards.d.ts +9 -0
  22. package/dist/channels/cards.js +32 -1
  23. package/dist/channels/phrases.d.ts +5 -0
  24. package/dist/channels/phrases.js +5 -0
  25. package/dist/conversations/attachments.service.d.ts +34 -0
  26. package/dist/conversations/attachments.service.js +124 -21
  27. package/dist/conversations/conversations.controller.d.ts +5 -1
  28. package/dist/conversations/conversations.controller.js +11 -5
  29. package/dist/conversations/conversations.service.d.ts +5 -0
  30. package/dist/conversations/conversations.service.js +10 -0
  31. package/dist/conversations/event-people.d.ts +12 -0
  32. package/dist/conversations/event-people.js +28 -0
  33. package/dist/db/kernel-schema.d.ts +18 -0
  34. package/dist/devices/devices.service.d.ts +3 -2
  35. package/dist/devices/devices.service.js +17 -2
  36. package/dist/errors.d.ts +1 -0
  37. package/dist/errors.js +1 -0
  38. package/dist/evals/trajectory.service.d.ts +3 -0
  39. package/dist/evals/trajectory.service.js +2 -0
  40. package/dist/extensions/installs.d.ts +3 -0
  41. package/dist/extensions/installs.js +1 -0
  42. package/dist/http/api.module.js +2 -0
  43. package/dist/http/meta.controller.d.ts +1 -0
  44. package/dist/http/meta.controller.js +6 -1
  45. package/dist/identity/account-avatar.controller.d.ts +30 -0
  46. package/dist/identity/account-avatar.controller.js +117 -0
  47. package/dist/identity/account-avatar.d.ts +67 -0
  48. package/dist/identity/account-avatar.js +136 -0
  49. package/dist/identity/account-avatars.service.d.ts +77 -0
  50. package/dist/identity/account-avatars.service.js +321 -0
  51. package/dist/identity/accounts.d.ts +26 -0
  52. package/dist/identity/accounts.js +70 -2
  53. package/dist/identity/app-auth.controller.d.ts +2 -1
  54. package/dist/identity/app-auth.controller.js +2 -1
  55. package/dist/identity/app-auth.d.ts +24 -7
  56. package/dist/identity/app-auth.js +19 -9
  57. package/dist/identity/app-auth.schemas.d.ts +16 -3
  58. package/dist/identity/app-auth.schemas.js +5 -2
  59. package/dist/identity/external.js +7 -1
  60. package/dist/identity/identity.module.d.ts +2 -1
  61. package/dist/identity/identity.module.js +7 -1
  62. package/dist/identity/me.controller.d.ts +29 -5
  63. package/dist/identity/me.controller.js +57 -6
  64. package/dist/identity/me.schemas.d.ts +36 -0
  65. package/dist/identity/me.schemas.js +30 -0
  66. package/dist/identity/principal.d.ts +2 -2
  67. package/dist/identity/principal.js +2 -2
  68. package/dist/local-devices/local-device-gateway.d.ts +2 -0
  69. package/dist/local-devices/local-device-gateway.js +8 -1
  70. package/dist/local-devices/relay.d.ts +10 -9
  71. package/dist/local-devices/relay.js +32 -9
  72. package/dist/local-devices/targets.d.ts +12 -0
  73. package/dist/local-devices/targets.js +18 -2
  74. package/dist/orgs/members.service.d.ts +3 -1
  75. package/dist/orgs/members.service.js +9 -2
  76. package/dist/platform/exclusions.js +33 -57
  77. package/dist/platform/file-ref.d.ts +87 -0
  78. package/dist/platform/file-ref.js +164 -0
  79. package/dist/platform/operation.d.ts +26 -0
  80. package/dist/platform/ops/agent-skills.ops.d.ts +2 -0
  81. package/dist/platform/ops/agent-skills.ops.js +156 -4
  82. package/dist/platform/ops/agents.ops.d.ts +3 -1
  83. package/dist/platform/ops/agents.ops.js +75 -17
  84. package/dist/platform/ops/approvals.ops.js +5 -0
  85. package/dist/platform/ops/catalog-admin.ops.d.ts +9 -1
  86. package/dist/platform/ops/catalog-admin.ops.js +86 -3
  87. package/dist/platform/ops/components.ops.d.ts +3 -1
  88. package/dist/platform/ops/components.ops.js +61 -2
  89. package/dist/platform/ops/connectors.ops.js +15 -1
  90. package/dist/platform/ops/devices.ops.js +6 -1
  91. package/dist/platform/ops/extensions-admin.ops.d.ts +6 -4
  92. package/dist/platform/ops/extensions-admin.ops.js +109 -6
  93. package/dist/platform/ops/inbox.ops.js +10 -0
  94. package/dist/platform/ops/list-handoff.d.ts +10 -0
  95. package/dist/platform/ops/list-handoff.js +11 -0
  96. package/dist/platform/ops/marketplaces.ops.js +2 -1
  97. package/dist/platform/ops/org-plugins.ops.d.ts +12 -3
  98. package/dist/platform/ops/org-plugins.ops.js +97 -6
  99. package/dist/platform/ops/requests.ops.js +9 -0
  100. package/dist/platform/ops/skills.ops.d.ts +5 -1
  101. package/dist/platform/ops/skills.ops.js +98 -4
  102. package/dist/platform/ops/summary.d.ts +5 -0
  103. package/dist/platform/ops/summary.js +10 -0
  104. package/dist/platform/parity.d.ts +6 -4
  105. package/dist/platform/parity.js +94 -68
  106. package/dist/roles/worker.module.js +5 -0
  107. package/dist/sandbox/request-not-sent.d.ts +13 -0
  108. package/dist/sandbox/request-not-sent.js +18 -0
  109. package/dist/schedules/scheduled-tasks.service.d.ts +10 -6
  110. package/dist/schedules/scheduled-tasks.service.js +13 -16
  111. package/dist/shares/shares.service.d.ts +1 -0
  112. package/dist/shares/shares.service.js +9 -3
  113. package/dist/skills/changes.service.d.ts +1 -0
  114. package/dist/skills/changes.service.js +4 -7
  115. package/dist/skills/skills.controller.d.ts +3 -7
  116. package/dist/skills/skills.controller.js +3 -16
  117. package/dist/skills/skills.schemas.d.ts +5 -0
  118. package/dist/skills/skills.schemas.js +17 -0
  119. package/dist/skills/skills.service.d.ts +3 -1
  120. package/dist/skills/skills.service.js +13 -4
  121. package/dist/tools/admin-connectors.d.ts +1 -0
  122. package/dist/tools/admin-connectors.js +4 -1
  123. package/dist/tools/approvals.service.d.ts +16 -2
  124. package/dist/tools/approvals.service.js +13 -0
  125. package/dist/tools/builtins/builtin-tools.d.ts +3 -0
  126. package/dist/tools/builtins/builtin-tools.js +29 -9
  127. package/dist/tools/builtins/platform.d.ts +23 -0
  128. package/dist/tools/builtins/platform.js +95 -6
  129. package/dist/tools/builtins/sandbox/common.d.ts +5 -0
  130. package/dist/tools/builtins/sandbox/common.js +11 -0
  131. package/dist/tools/builtins/skill-load.js +4 -4
  132. package/dist/tools/pipeline.js +10 -3
  133. package/dist/tools/questions.controller.js +2 -2
  134. package/dist/tools/questions.service.d.ts +7 -1
  135. package/dist/tools/questions.service.js +9 -2
  136. package/dist/tools/registry.d.ts +6 -0
  137. package/dist/tools/tools.module.js +3 -0
  138. package/package.json +3 -3
  139. package/src/migrations/0171_account_avatar.sql +26 -0
@@ -193,6 +193,42 @@ let AttachmentsService = class AttachmentsService {
193
193
  */
194
194
  async create(orgId, accountId, input, purpose = "chat") {
195
195
  this.storage.assertAvailable();
196
+ const { contentType, ttlHours } = await this.admit(orgId, accountId, purpose, input, false);
197
+ const id = randomUUID();
198
+ const key = objectKey(id, purpose);
199
+ const upload = await this.storage.kernel(orgId).presignPut(key, {
200
+ contentType,
201
+ maxSize: input.size,
202
+ ttlSeconds: ATTACHMENT_UPLOAD_TTL_SECONDS,
203
+ });
204
+ await this.db
205
+ .insertInto("attachments")
206
+ .values({
207
+ id,
208
+ org_id: orgId,
209
+ account_id: accountId,
210
+ name: input.name,
211
+ content_type: contentType,
212
+ size: input.size,
213
+ object_key: key,
214
+ status: "pending",
215
+ purpose,
216
+ expires_at: sql `now() + make_interval(hours => ${ttlHours})`,
217
+ })
218
+ .execute();
219
+ return {
220
+ id,
221
+ upload,
222
+ expiresAt: new Date(Date.now() + ATTACHMENT_UPLOAD_TTL_SECONDS * 1000).toISOString(),
223
+ };
224
+ }
225
+ /**
226
+ * The checks of registering an upload of `purpose` (type, size, the account's unfinished uploads
227
+ * of that purpose) and its expiry. `countStored`: uploads already stored but not yet used (ready,
228
+ * still expiring, bound to no agent) count as unfinished too ({@link createFromBytes}'s rows do
229
+ * not stay pending).
230
+ */
231
+ async admit(orgId, accountId, purpose, input, countStored) {
196
232
  const cfg = this.config.get().attachments;
197
233
  const contentType = normalizeContentType(input.contentType);
198
234
  const skill = purpose === "skill-package";
@@ -217,8 +253,17 @@ let AttachmentsService = class AttachmentsService {
217
253
  .select((eb) => eb.fn.countAll().as("n"))
218
254
  .where("org_id", "=", orgId)
219
255
  .where("account_id", "=", accountId)
220
- .where("status", "=", "pending")
221
256
  .where("purpose", "=", purpose)
257
+ .where((eb) => countStored
258
+ ? eb.or([
259
+ eb("status", "=", "pending"),
260
+ eb.and([
261
+ eb("status", "=", "ready"),
262
+ eb("expires_at", "is not", null),
263
+ eb("agent_id", "is", null),
264
+ ]),
265
+ ])
266
+ : eb("status", "=", "pending"))
222
267
  .executeTakeFirst();
223
268
  const maxPending = skill
224
269
  ? MAX_PENDING_SKILL_PACKAGES
@@ -228,38 +273,87 @@ let AttachmentsService = class AttachmentsService {
228
273
  if (Number(pending?.n ?? 0) >= maxPending) {
229
274
  throw new ApiError("attachment.too_many_pending", `Too many unfinished uploads (at most ${maxPending}); finish or wait for them first`);
230
275
  }
231
- const id = randomUUID();
232
- const key = objectKey(id, purpose);
233
276
  const ttlHours = skill
234
277
  ? SKILL_PACKAGE_TTL_HOURS
235
278
  : avatar
236
279
  ? AGENT_AVATAR_TTL_HOURS
237
280
  : cfg.unboundTtlHours;
238
- const upload = await this.storage.kernel(orgId).presignPut(key, {
281
+ return { contentType, ttlHours };
282
+ }
283
+ /**
284
+ * Stores bytes the kernel already holds as an upload of `purpose`, as if a person had uploaded
285
+ * and finalized them (platform web parity spec §5: a `Platform` write takes a file in place of
286
+ * an upload), then the route's next step takes its id (the profile save, `POST /skills`). The
287
+ * checks, expiry and caps of {@link create} apply; no presigned URL is made. Intent first: the
288
+ * `pending` row is committed before the put (a failed put leaves it to expire and be cleaned
289
+ * up), then one update makes it `ready` with the stored size and etag. The type is not sniffed
290
+ * here: callers pass bytes they checked (the Platform tool sniffs a file reference).
291
+ */
292
+ async createFromBytes(orgId, accountId, purpose, file) {
293
+ this.storage.assertAvailable();
294
+ const size = file.bytes.byteLength;
295
+ const { contentType, ttlHours } = await this.admit(orgId, accountId, purpose, { contentType: file.contentType, size }, true);
296
+ const id = randomUUID();
297
+ const key = objectKey(id, purpose);
298
+ await this.insertUploadIntent({
299
+ id,
300
+ orgId,
301
+ accountId,
302
+ name: file.name,
239
303
  contentType,
240
- maxSize: input.size,
241
- ttlSeconds: ATTACHMENT_UPLOAD_TTL_SECONDS,
304
+ size,
305
+ key,
306
+ purpose,
307
+ ttlHours,
242
308
  });
243
- await this.db
309
+ const head = await this.storage.kernel(orgId).put(key, file.bytes, { contentType, size });
310
+ await this.markStored(id, head.size, head.etag ?? null);
311
+ return { id };
312
+ }
313
+ /**
314
+ * Gives up an upload {@link createFromBytes} stored when the write meant to take it failed: a
315
+ * `ready` upload of the account no agent uses becomes `deleting`, expiring now, so it no longer
316
+ * counts toward the cap and the cleanup job deletes it with its object. One already taken (a
317
+ * consumed skill package, an avatar bound to an agent) is left alone.
318
+ */
319
+ async discardUpload(orgId, accountId, id) {
320
+ await this.db.db
321
+ .updateTable("attachments")
322
+ .set({ status: "deleting", expires_at: sql `now()` })
323
+ .where("id", "=", id)
324
+ .where("org_id", "=", orgId)
325
+ .where("account_id", "=", accountId)
326
+ .where("purpose", "in", ["agent-avatar", "skill-package"])
327
+ .where("status", "=", "ready")
328
+ .where("agent_id", "is", null)
329
+ .execute();
330
+ }
331
+ /** The last step of {@link createFromBytes}: the stored object's size and etag, `ready`. */
332
+ async markStored(id, size, etag) {
333
+ await this.db.db
334
+ .updateTable("attachments")
335
+ .set({ status: "ready", size, etag })
336
+ .where("id", "=", id)
337
+ .where("status", "=", "pending")
338
+ .execute();
339
+ }
340
+ /** The `pending` row of {@link createFromBytes}, committed on its own before the put. */
341
+ async insertUploadIntent(r) {
342
+ await this.db.db
244
343
  .insertInto("attachments")
245
344
  .values({
246
- id,
247
- org_id: orgId,
248
- account_id: accountId,
249
- name: input.name,
250
- content_type: contentType,
251
- size: input.size,
252
- object_key: key,
345
+ id: r.id,
346
+ org_id: r.orgId,
347
+ account_id: r.accountId,
348
+ name: r.name,
349
+ content_type: r.contentType,
350
+ size: r.size,
351
+ object_key: r.key,
253
352
  status: "pending",
254
- purpose,
255
- expires_at: sql `now() + make_interval(hours => ${ttlHours})`,
353
+ purpose: r.purpose,
354
+ expires_at: sql `now() + make_interval(hours => ${r.ttlHours})`,
256
355
  })
257
356
  .execute();
258
- return {
259
- id,
260
- upload,
261
- expiresAt: new Date(Date.now() + ATTACHMENT_UPLOAD_TTL_SECONDS * 1000).toISOString(),
262
- };
263
357
  }
264
358
  /**
265
359
  * 上传完成后核对并标记为 `ready`(只有上传者能做;已 ready 时直接返回):
@@ -1035,6 +1129,15 @@ let AttachmentsService = class AttachmentsService {
1035
1129
  }
1036
1130
  }
1037
1131
  };
1132
+ __decorate([
1133
+ Transactional()
1134
+ ], AttachmentsService.prototype, "discardUpload", null);
1135
+ __decorate([
1136
+ Transactional()
1137
+ ], AttachmentsService.prototype, "markStored", null);
1138
+ __decorate([
1139
+ Transactional({ propagation: "requires_new" })
1140
+ ], AttachmentsService.prototype, "insertUploadIntent", null);
1038
1141
  __decorate([
1039
1142
  Transactional({ propagation: "mandatory" })
1040
1143
  ], AttachmentsService.prototype, "bindForMessage", null);
@@ -1,6 +1,7 @@
1
1
  import type { FastifyReply } from "fastify";
2
2
  import { z } from "zod";
3
3
  import type { DeviceView } from "../devices/devices.service.js";
4
+ import type { PersonRef } from "../identity/account-avatar.js";
4
5
  import { type Principal } from "../identity/principal.js";
5
6
  import { type OrgContext } from "../orgs/org.guard.js";
6
7
  import { ConversationToolInfo, type ToolInfo } from "../tools/info.js";
@@ -168,7 +169,9 @@ export declare class ConversationsController {
168
169
  archivedCount: number;
169
170
  }>;
170
171
  get(principal: Principal, org: OrgContext, id: string): Promise<{
171
- conversation: ConversationView;
172
+ conversation: ConversationView & {
173
+ owner: PersonRef | null;
174
+ };
172
175
  }>;
173
176
  /**
174
177
  * Events in ascending seq. `after`: those after it (at most `limit`; the client passes the last
@@ -178,6 +181,7 @@ export declare class ConversationsController {
178
181
  events(principal: Principal, org: OrgContext, id: string, q: z.infer<typeof EventsQuery>): Promise<{
179
182
  events: ConversationEvent[];
180
183
  turnsBefore?: number;
184
+ people: Record<string, PersonRef>;
181
185
  }>;
182
186
  /**
183
187
  * The conversation's sub-agents, newest first (sub-agents spec §14.3): `{ subagents, next }`,
@@ -272,7 +272,13 @@ let ConversationsController = class ConversationsController {
272
272
  }
273
273
  async get(principal, org, id) {
274
274
  const p = requireUser(principal);
275
- return { conversation: await this.conversations.get(org.orgId, id, p.account.id) };
275
+ const conversation = await this.conversations.get(org.orgId, id, p.account.id);
276
+ return {
277
+ conversation: {
278
+ ...conversation,
279
+ owner: await this.conversations.person(conversation.accountId),
280
+ },
281
+ };
276
282
  }
277
283
  /**
278
284
  * Events in ascending seq. `after`: those after it (at most `limit`; the client passes the last
@@ -283,11 +289,11 @@ let ConversationsController = class ConversationsController {
283
289
  const p = requireUser(principal);
284
290
  if (q.before !== undefined) {
285
291
  const before = q.before === "end" ? null : q.before;
286
- return this.conversations.listEventsBefore(org.orgId, id, p.account.id, before, q.limit);
292
+ const page = await this.conversations.listEventsBefore(org.orgId, id, p.account.id, before, q.limit);
293
+ return { ...page, people: await this.conversations.eventPeople(page.events) };
287
294
  }
288
- return {
289
- events: await this.conversations.listEvents(org.orgId, id, p.account.id, q.after ?? 0, q.limit),
290
- };
295
+ const events = await this.conversations.listEvents(org.orgId, id, p.account.id, q.after ?? 0, q.limit);
296
+ return { events, people: await this.conversations.eventPeople(events) };
291
297
  }
292
298
  /**
293
299
  * The conversation's sub-agents, newest first (sub-agents spec §14.3): `{ subagents, next }`,
@@ -5,6 +5,7 @@ import type { AgentAvatar } from "../agents/profile.js";
5
5
  import type { TitleSource } from "../db/kernel-schema.js";
6
6
  import { ConversationDevices, type NewConversationDevice } from "../devices/conversation-devices.js";
7
7
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
8
+ import { type PersonRef } from "../identity/account-avatar.js";
8
9
  import { KernelDb } from "../infra/database/kernel-db.js";
9
10
  import { TransactionHost } from "../infra/database/transaction-host.js";
10
11
  import { KernelEvents } from "../infra/events/kernel-events.js";
@@ -488,6 +489,10 @@ export declare class ConversationsService {
488
489
  * only after an access check.
489
490
  */
490
491
  sandboxConversationOf(orgId: string, conversationId: string): Promise<string>;
492
+ /** The `people` sidecar of an events response: every account the events name (read time). */
493
+ eventPeople(events: readonly ConversationEvent[]): Promise<Record<string, PersonRef>>;
494
+ /** The person behind an account id; null when the account is gone. */
495
+ person(accountId: string): Promise<PersonRef | null>;
491
496
  /**
492
497
  * 读事件(先做 `get` 的可见性判定). A read never changes run state (transactional outbox spec
493
498
  * §6): a run nobody runs is the `run-orphan-check`'s to repair.
@@ -15,6 +15,7 @@ import { unbindConversation } from "../channels/threads.js";
15
15
  import { ConversationDevices, } from "../devices/conversation-devices.js";
16
16
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
17
17
  import { ApiError } from "../errors.js";
18
+ import { loadPeople } from "../identity/account-avatar.js";
18
19
  import { afterCommit } from "../infra/database/after-commit.js";
19
20
  import { KernelDb } from "../infra/database/kernel-db.js";
20
21
  import { TransactionHost, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
@@ -36,6 +37,7 @@ import { ConversationAccess, parentReachable } from "./access.js";
36
37
  import { readAgentTree } from "./agent-tree.js";
37
38
  import { AttachmentsService } from "./attachments.service.js";
38
39
  import { EventLog } from "./event-log.js";
40
+ import { peopleOfEvents } from "./event-people.js";
39
41
  import { userMessageIdemKey } from "./idem-keys.js";
40
42
  import { readMessageContext, } from "./message-context.js";
41
43
  import { PermissionProfilesService } from "./permission-profiles.service.js";
@@ -827,6 +829,14 @@ let ConversationsService = class ConversationsService {
827
829
  return conversationId;
828
830
  return rootConversationOf(this.db.db, row.parent_conversation_id);
829
831
  }
832
+ /** The `people` sidecar of an events response: every account the events name (read time). */
833
+ eventPeople(events) {
834
+ return peopleOfEvents(this.db.db, events);
835
+ }
836
+ /** The person behind an account id; null when the account is gone. */
837
+ async person(accountId) {
838
+ return (await loadPeople(this.db.db, [accountId])).get(accountId) ?? null;
839
+ }
830
840
  /**
831
841
  * 读事件(先做 `get` 的可见性判定). A read never changes run state (transactional outbox spec
832
842
  * §6): a run nobody runs is the `run-orphan-check`'s to repair.
@@ -0,0 +1,12 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { KernelDatabase } from "../db/kernel-schema.js";
3
+ import { type PersonRef } from "../identity/account-avatar.js";
4
+ import type { ConversationEvent } from "./events.js";
5
+ /** Every account id the events name (an id may repeat; null is skipped). */
6
+ export declare function accountIdsOfEvents(events: readonly ConversationEvent[]): string[];
7
+ /**
8
+ * The `people` sidecar of an events or trajectory response (account profile spec §5.4): one
9
+ * query for every account the events name, plus `extraIds`. Computed at read time; the logged
10
+ * payloads keep their ids only. An account that no longer exists is absent.
11
+ */
12
+ export declare function peopleOfEvents(db: Kysely<KernelDatabase>, events: readonly ConversationEvent[], extraIds?: readonly string[]): Promise<Record<string, PersonRef>>;
@@ -0,0 +1,28 @@
1
+ import { loadPeople } from "../identity/account-avatar.js";
2
+ /**
3
+ * The payload keys that name a person: a message's author, a run's trigger, who decided or
4
+ * stopped, and whom an approval or sub-agent wait is for (`requestedFor`, a string or null).
5
+ */
6
+ const PERSON_KEYS = ["authorAccountId", "triggerAccountId", "byAccountId", "requestedFor"];
7
+ /** Every account id the events name (an id may repeat; null is skipped). */
8
+ export function accountIdsOfEvents(events) {
9
+ const ids = new Set();
10
+ for (const e of events) {
11
+ const payload = e.payload;
12
+ for (const key of PERSON_KEYS) {
13
+ const v = payload?.[key];
14
+ if (typeof v === "string")
15
+ ids.add(v);
16
+ }
17
+ }
18
+ return [...ids];
19
+ }
20
+ /**
21
+ * The `people` sidecar of an events or trajectory response (account profile spec §5.4): one
22
+ * query for every account the events name, plus `extraIds`. Computed at read time; the logged
23
+ * payloads keep their ids only. An account that no longer exists is absent.
24
+ */
25
+ export async function peopleOfEvents(db, events, extraIds = []) {
26
+ const people = await loadPeople(db, [...accountIdsOfEvents(events), ...extraIds]);
27
+ return Object.fromEntries(people);
28
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SkillInvocation } from "@capybara-hq/plugin-sdk";
2
2
  import type { ColumnType, Generated, Kysely } from "kysely";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
+ import type { AccountAvatar } from "../identity/account-avatar.js";
4
5
  import type { DeviceNetwork } from "../sandbox/modes.js";
5
6
  import type { StartingExecutionGrants } from "../sandbox/operation-authority-types.js";
6
7
  import type { AuthorityEpochVector } from "../sandbox/permission-authority-epochs.js";
@@ -98,6 +99,20 @@ export interface AccountsTable {
98
99
  must_change_password: Generated<boolean>;
99
100
  /** 0093: the person's theme id across all their orgs; null follows the org (themes spec §7). */
100
101
  theme: ColumnType<string | null, string | null | undefined, string | null>;
102
+ /** 0169: the person's own avatar; null shows the SSO avatar or the initial (account profile §5.1). */
103
+ avatar: ColumnType<AccountAvatar | null, string | null | undefined, string | null>;
104
+ }
105
+ /** 0169: an account's avatar uploads (bytes in the object store under `deployment/account-avatars/`). */
106
+ export interface AccountAvatarUploadsTable {
107
+ id: string;
108
+ account_id: string;
109
+ storage_key: string;
110
+ content_type: string;
111
+ size: ColumnType<string | null, number | string | null | undefined, number | string | null>;
112
+ status: Generated<"pending" | "ready">;
113
+ /** Null once bound to the account; an unbound upload expires and is swept. */
114
+ expires_at: TsNullable;
115
+ created_at: Ts;
101
116
  }
102
117
  /**
103
118
  * 0090: a generated initial password sealed for the person who approved the account's creation,
@@ -156,6 +171,8 @@ export interface IdentitiesTable {
156
171
  created_at: Ts;
157
172
  /** 0019:身份行如何建立(Ruling A18);null 为旧行,按 `sso` 处理。 */
158
173
  linked_via: ColumnType<LinkedVia | null, LinkedVia | null | undefined, LinkedVia | null>;
174
+ /** 0169: when the row was last written (insert or login refresh); null before 0169. */
175
+ updated_at: TsNullable;
159
176
  }
160
177
  /** 身份行的建立方式:IM 绑定链接、第三方登录、通讯录同步、本地登录名。 */
161
178
  export type LinkedVia = "bind" | "sso" | "directory" | "local";
@@ -1622,6 +1639,7 @@ export interface PermissionConfigPublicationTable {
1622
1639
  export interface KernelDatabase {
1623
1640
  permission_authority_epochs: PermissionAuthorityEpochsTable;
1624
1641
  accounts: AccountsTable;
1642
+ account_avatar_uploads: AccountAvatarUploadsTable;
1625
1643
  device_permission_reports: DevicePermissionReportsTable;
1626
1644
  /** Migration 0155: per-device generation high-water mark; outlives instance rows. */
1627
1645
  device_generation_high_water: DeviceGenerationHighWaterTable;
@@ -2,6 +2,7 @@ import type { DeviceLocalPolicySummary, LocalizedName, SandboxBrowseScope, Sandb
2
2
  import { type Selectable } from "kysely";
3
3
  import type { SandboxOperationIntentsTable } from "../db/kernel-schema.js";
4
4
  import { ExtensionDisplayNames } from "../extensions/display-name.js";
5
+ import { type PersonRef } from "../identity/account-avatar.js";
5
6
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
7
  import { KernelDb } from "../infra/database/kernel-db.js";
7
8
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -178,8 +179,8 @@ export interface DeviceSettingChangeView {
178
179
  from: DeviceNetworkSetting;
179
180
  to: DeviceNetworkSetting;
180
181
  } | null;
181
- /** The deciding account's display name (null when the account is gone). */
182
- by: string | null;
182
+ /** The deciding account (null when the account is gone). */
183
+ by: PersonRef | null;
183
184
  /**
184
185
  * `device`: made or reported on the machine itself; `token`: through an API token; `agent`: an
185
186
  * agent's Platform tool call.
@@ -12,6 +12,7 @@ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { ExtensionDisplayNames } from "../extensions/display-name.js";
15
+ import { avatarColumns, personAvatarUrl } from "../identity/account-avatar.js";
15
16
  import { audit } from "../identity/audit.js";
16
17
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
17
18
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -1000,7 +1001,15 @@ let DevicesService = class DevicesService {
1000
1001
  const rows = await this.db
1001
1002
  .selectFrom(ranked.as("r"))
1002
1003
  .leftJoin("accounts as ac", "ac.id", "r.actor_account_id")
1003
- .select(["r.target", "r.action", "r.at", "r.detail", "ac.display_name"])
1004
+ .select((eb) => [
1005
+ "r.target",
1006
+ "r.action",
1007
+ "r.at",
1008
+ "r.detail",
1009
+ "r.actor_account_id",
1010
+ "ac.display_name",
1011
+ ...avatarColumns(eb, "ac", "actor"),
1012
+ ])
1004
1013
  .where("r.n", "<=", RECENT_POLICY_CHANGES)
1005
1014
  .orderBy("r.at", "desc")
1006
1015
  .execute();
@@ -1008,7 +1017,13 @@ let DevicesService = class DevicesService {
1008
1017
  if (r.target === null)
1009
1018
  continue;
1010
1019
  const list = out.get(r.target) ?? [];
1011
- list.push(settingChangeOf(r.action, r.at, (r.detail ?? {}), r.display_name ?? null));
1020
+ list.push(settingChangeOf(r.action, r.at, (r.detail ?? {}), r.actor_account_id === null || r.display_name === null
1021
+ ? null
1022
+ : {
1023
+ id: r.actor_account_id,
1024
+ name: r.display_name,
1025
+ avatarUrl: personAvatarUrl(r, "actor", r.actor_account_id),
1026
+ }));
1012
1027
  out.set(r.target, list);
1013
1028
  }
1014
1029
  return out;
package/dist/errors.d.ts CHANGED
@@ -17,6 +17,7 @@ export declare const ERROR_CODES: {
17
17
  readonly "account.last_super_admin": 409;
18
18
  readonly "account.initial_password_unavailable": 404;
19
19
  readonly "account.create_needs_approval": 409;
20
+ readonly "account.display_name_too_long": 400;
20
21
  readonly "auth.account_disabled": 403;
21
22
  readonly "auth.required": 401;
22
23
  readonly "auth.token_expired": 401;
package/dist/errors.js CHANGED
@@ -17,6 +17,7 @@ export const ERROR_CODES = {
17
17
  "account.last_super_admin": 409,
18
18
  "account.initial_password_unavailable": 404,
19
19
  "account.create_needs_approval": 409,
20
+ "account.display_name_too_long": 400,
20
21
  "auth.account_disabled": 403,
21
22
  "auth.required": 401,
22
23
  "auth.token_expired": 401,
@@ -1,5 +1,6 @@
1
1
  import { EventLog } from "../conversations/event-log.js";
2
2
  import type { ConversationKind } from "../db/kernel-schema.js";
3
+ import type { PersonRef } from "../identity/account-avatar.js";
3
4
  import { SettingsService } from "../identity/settings.js";
4
5
  import { KernelDb } from "../infra/database/kernel-db.js";
5
6
  import { PricesService } from "../models/prices.js";
@@ -37,6 +38,8 @@ export interface TrajectoryDetail {
37
38
  };
38
39
  };
39
40
  runs: TrajectoryRun[];
41
+ /** Every account the events name (and the conversation's owner), by id; read time. */
42
+ people: Record<string, PersonRef>;
40
43
  /** 成本的币种(部署设置 `priceCurrency`)。 */
41
44
  currency: string;
42
45
  /**
@@ -12,6 +12,7 @@ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { isAgentVisibleTo } from "../agents/agent-lookup.js";
14
14
  import { EventLog } from "../conversations/event-log.js";
15
+ import { peopleOfEvents } from "../conversations/event-people.js";
15
16
  import { ApiError } from "../errors.js";
16
17
  import { audit } from "../identity/audit.js";
17
18
  import { SettingsService } from "../identity/settings.js";
@@ -257,6 +258,7 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
257
258
  ...(parent !== undefined && { parent }),
258
259
  },
259
260
  runs: buildTrajectory(events, table),
261
+ people: await peopleOfEvents(this.db.db, events, [conv.account_id]),
260
262
  currency: settings.priceCurrency,
261
263
  ...(next !== undefined && { next }),
262
264
  };
@@ -131,6 +131,8 @@ export declare class ExtensionInstalls {
131
131
  owner?: {
132
132
  orgId: string;
133
133
  };
134
+ /** Merged into the audit detail (a write made through the Platform tool: `via`, …). */
135
+ auditDetail?: Record<string, unknown>;
134
136
  }): Promise<PackageReview>;
135
137
  /**
136
138
  * The super admin re-check under its lock, in a transaction of its own (`requires_new`, as
@@ -149,6 +151,7 @@ export declare class ExtensionInstalls {
149
151
  ingestFile(actor: string | null, bytes: Uint8Array, opts?: {
150
152
  actorTokenId?: string;
151
153
  store?: "object" | "pg";
154
+ auditDetail?: Record<string, unknown>;
152
155
  }): Promise<PackageReview>;
153
156
  /**
154
157
  * Fetches one package from the configured npm registry (verified by `dist.integrity`, see
@@ -160,6 +160,7 @@ let ExtensionInstalls = class ExtensionInstalls {
160
160
  sha256: pkg.sha256,
161
161
  source: src.source,
162
162
  ...(opts.owner !== undefined && { orgId: opts.owner.orgId }),
163
+ ...opts.auditDetail,
163
164
  }, opts.owner);
164
165
  const set = permissionSetOfPackage(pkg);
165
166
  const snapshot = (await this.approvals.all()).get(m.name);
@@ -54,6 +54,7 @@ import { FilePreviewersController } from "../files/previewers.controller.js";
54
54
  import { GitModule } from "../git/git.module.js";
55
55
  import { HtmlModule } from "../html/html.module.js";
56
56
  import { HtmlDocumentController } from "../html/html-document.controller.js";
57
+ import { AccountAvatarController } from "../identity/account-avatar.controller.js";
57
58
  import { AppAuthController } from "../identity/app-auth.controller.js";
58
59
  import { AuthController } from "../identity/auth.controller.js";
59
60
  import { AuthGuard } from "../identity/auth.guard.js";
@@ -115,6 +116,7 @@ const CONTROLLERS = [
115
116
  AppAuthController,
116
117
  MetaController,
117
118
  MeController,
119
+ AccountAvatarController,
118
120
  InitialPasswordsController,
119
121
  // the invitation link an org admin's agent created, read once by its approver (web parity §7.2)
120
122
  SealedRevealsController,
@@ -20,6 +20,7 @@ export declare const MetaResponseSchema: z.ZodObject<{
20
20
  localDevices: z.ZodBoolean;
21
21
  appSignIn: z.ZodBoolean;
22
22
  }, z.core.$strip>;
23
+ appRedirectUris: z.ZodArray<z.ZodString>;
23
24
  }, z.core.$strip>;
24
25
  export type MetaResponse = z.infer<typeof MetaResponseSchema>;
25
26
  /** `GET /api/v1/meta`: public, never cached, reveals only what a client needs before signing in. */
@@ -26,6 +26,8 @@ export const MetaResponseSchema = z.object({
26
26
  device: z.object({ min: z.number().int(), max: z.number().int() }),
27
27
  }),
28
28
  features: z.object({ localDevices: z.boolean(), appSignIn: z.boolean() }),
29
+ /** The redirect URIs app sign-in accepts (`auth.appRedirectUris`); [] while appSignIn is off. */
30
+ appRedirectUris: z.array(z.string()),
29
31
  });
30
32
  /** `GET /api/v1/meta`: public, never cached, reveals only what a client needs before signing in. */
31
33
  let MetaController = class MetaController {
@@ -42,6 +44,7 @@ let MetaController = class MetaController {
42
44
  this.iconUrl("maskable"),
43
45
  this.iconUrl("favicon"),
44
46
  ]);
47
+ const appSignIn = Boolean(config.http.publicUrl);
45
48
  return {
46
49
  name: config.platform.name ?? null,
47
50
  icon: app,
@@ -50,8 +53,10 @@ let MetaController = class MetaController {
50
53
  features: {
51
54
  localDevices: true,
52
55
  // The authorize route answers app_auth.unavailable without http.publicUrl.
53
- appSignIn: Boolean(config.http.publicUrl),
56
+ appSignIn,
54
57
  },
58
+ // Not secret: an app that finds its own URI missing says so before opening the browser.
59
+ appRedirectUris: appSignIn ? [...config.auth.appRedirectUris] : [],
55
60
  };
56
61
  }
57
62
  /** A customised platform icon's versioned URL (the one the manifest uses); null for the default. */
@@ -0,0 +1,30 @@
1
+ import type { Logger } from "@capybara-hq/plugin-sdk";
2
+ import type { FastifyReply } from "fastify";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { AccountAvatarsService } from "./account-avatars.service.js";
5
+ import { type Principal } from "./principal.js";
6
+ /**
7
+ * A person's avatar image (account profile spec §5): readable by the account itself, a super
8
+ * admin, or anyone who shares an org with the person (any role, guests included; deleted orgs do
9
+ * not count). Default auth: a session or a personal token; service tokens and embed tokens never.
10
+ * An account that must change its password first still reads its own image (the shell draws it),
11
+ * and only its own.
12
+ */
13
+ export declare class AccountAvatarController {
14
+ private readonly db;
15
+ private readonly avatars;
16
+ private readonly log;
17
+ constructor(db: KernelDb, avatars: Pick<AccountAvatarsService, "objectUrl">, log: Logger);
18
+ /**
19
+ * 302 to a short-lived presigned URL of the person's own upload; else (no upload, its object
20
+ * gone, or no object store) 302 to their SSO `https:` avatar; else 404. The `v` query parameter
21
+ * only busts browser caches and is ignored. An object store failure never fails the route: it
22
+ * falls back like a missing object, with a warning.
23
+ */
24
+ avatar(principal: Principal, accountId: string, reply: FastifyReply): Promise<void>;
25
+ /**
26
+ * The presigned URL of the bound upload; null when it is gone, there is no object store, or the
27
+ * store failed (logged).
28
+ */
29
+ private uploadUrl;
30
+ }