@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
@@ -7,6 +7,8 @@ const printable = (max) => z
7
7
  .min(1)
8
8
  .max(max)
9
9
  .regex(PRINTABLE_RE, { message: "Must contain only printable characters" });
10
+ /** The native apps that sign in this way: the desktop app and the mobile app (mobile spec §4.3). */
11
+ export const AppClientSchema = z.enum(["desktop", "mobile"]);
10
12
  /**
11
13
  * `POST /api/v1/app-auth/authorize` (desktop client spec §6.5): the person consents on the web to
12
14
  * sign a native app in. `codeChallenge` is BASE64URL(SHA-256(verifier)), always 43 characters;
@@ -14,7 +16,7 @@ const printable = (max) => z
14
16
  */
15
17
  export const AppAuthorizeBodySchema = z
16
18
  .object({
17
- client: z.literal("desktop"),
19
+ client: AppClientSchema,
18
20
  redirectUri: z.string().min(1).max(2048),
19
21
  codeChallenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/, {
20
22
  message: "Must be the base64url SHA-256 of the code verifier (43 characters)",
@@ -30,7 +32,8 @@ export class AppAuthorizeBodyDto extends createZodDto(AppAuthorizeBodySchema, "A
30
32
  }
31
33
  /**
32
34
  * `POST /api/v1/app-auth/token`: the app exchanges the one-time code with its PKCE verifier. Only
33
- * the shape is checked here; every content failure answers `app_auth.code_invalid` (the service).
35
+ * the shape is checked here; every content failure answers `app_auth.code_invalid` (the service),
36
+ * except a disabled account: `auth.account_disabled`.
34
37
  */
35
38
  export const AppTokenBodySchema = z
36
39
  .object({
@@ -207,7 +207,12 @@ let ExternalIdentities = class ExternalIdentities {
207
207
  async refreshIdentity(id) {
208
208
  await this.db
209
209
  .updateTable("identities")
210
- .set({ email: id.email ?? null, email_verified: id.emailVerified, profile: profileOf(id) })
210
+ .set({
211
+ email: id.email ?? null,
212
+ email_verified: id.emailVerified,
213
+ profile: profileOf(id),
214
+ updated_at: sql `now()`,
215
+ })
211
216
  .where("source", "=", id.source)
212
217
  .where("external_id", "=", id.externalId)
213
218
  .execute();
@@ -240,6 +245,7 @@ let ExternalIdentities = class ExternalIdentities {
240
245
  email_verified: id.emailVerified,
241
246
  profile: profileOf(id),
242
247
  linked_via: linkedVia,
248
+ updated_at: sql `now()`,
243
249
  })
244
250
  .onConflict((oc) => oc.columns(["source", "external_id"]).doNothing())
245
251
  .returning("account_id")
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Identity: accounts, sessions, API tokens, deployment settings and the super admin lock,
3
- * external identities with IM binding and third-party sign-in, native-app sign-in.
3
+ * external identities with IM binding and third-party sign-in, native-app sign-in, and the
4
+ * person's own avatar uploads.
4
5
  */
5
6
  export declare class IdentityModule {
6
7
  }
@@ -9,6 +9,8 @@ import { SetupLockModule } from "../admin/setup-lock.js";
9
9
  import { ExtensionRegistryModule } from "../extensions/registry.js";
10
10
  import { OrgLockModule } from "../orgs/org-lock.js";
11
11
  import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
12
+ import { StorageModule } from "../storage/storage.module.js";
13
+ import { AccountAvatarsService } from "./account-avatars.service.js";
12
14
  import { AccountsModule } from "./accounts.js";
13
15
  import { ApiTokenService } from "./api-tokens.js";
14
16
  import { AppAuthService } from "./app-auth.js";
@@ -22,7 +24,8 @@ import { SsoFlow } from "./sso.js";
22
24
  import { SuperAdminLockModule } from "./super-admin.js";
23
25
  /**
24
26
  * Identity: accounts, sessions, API tokens, deployment settings and the super admin lock,
25
- * external identities with IM binding and third-party sign-in, native-app sign-in.
27
+ * external identities with IM binding and third-party sign-in, native-app sign-in, and the
28
+ * person's own avatar uploads.
26
29
  */
27
30
  let IdentityModule = class IdentityModule {
28
31
  };
@@ -35,8 +38,10 @@ IdentityModule = __decorate([
35
38
  SetupLockModule,
36
39
  SuperAdminLockModule,
37
40
  ExtensionRegistryModule,
41
+ StorageModule,
38
42
  ],
39
43
  providers: [
44
+ AccountAvatarsService,
40
45
  SessionService,
41
46
  ApiTokenService,
42
47
  SettingsService,
@@ -49,6 +54,7 @@ IdentityModule = __decorate([
49
54
  ],
50
55
  exports: [
51
56
  AccountsModule,
57
+ AccountAvatarsService,
52
58
  SessionService,
53
59
  ApiTokenService,
54
60
  SettingsService,
@@ -1,12 +1,15 @@
1
- import type { Logger } from "@capybara-hq/plugin-sdk";
1
+ import type { Logger, PresignedUpload } from "@capybara-hq/plugin-sdk";
2
2
  import type { FastifyReply, FastifyRequest } from "fastify";
3
3
  import { z } from "zod";
4
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
5
6
  import { OrgsService } from "../orgs/orgs.service.js";
6
7
  import type { OrgRole } from "../orgs/roles.js";
7
- import { type Account, AccountsService } from "./accounts.js";
8
+ import { type AccountView } from "./account-avatar.js";
9
+ import { AccountAvatarsService } from "./account-avatars.service.js";
10
+ import { AccountsService } from "./accounts.js";
8
11
  import { type ApiTokenRecord, ApiTokenService } from "./api-tokens.js";
9
- import { type Preferences, type PreferencesSchema } from "./me.schemas.js";
12
+ import { type AvatarUploadSchema, type Preferences, type PreferencesSchema, type ProfilePatchSchema } from "./me.schemas.js";
10
13
  import { type Principal } from "./principal.js";
11
14
  import { SessionService } from "./sessions.js";
12
15
  import { SettingsService } from "./settings.js";
@@ -36,15 +39,36 @@ export declare class MeController {
36
39
  private readonly throttler;
37
40
  private readonly log;
38
41
  private readonly settings;
39
- constructor(accounts: AccountsService, sessions: SessionService, orgs: OrgsService, tokens: ApiTokenService, throttler: CredentialThrottler, log: Logger, settings: SettingsService);
42
+ private readonly db;
43
+ private readonly avatars;
44
+ constructor(accounts: AccountsService, sessions: SessionService, orgs: OrgsService, tokens: ApiTokenService, throttler: CredentialThrottler, log: Logger, settings: SettingsService, db: KernelDb, avatars: AccountAvatarsService);
40
45
  me(principal: Principal): Promise<{
41
- account: Account;
46
+ account: AccountView;
42
47
  via: "session" | "pat";
43
48
  currentOrgId: string | null;
44
49
  memberships: MembershipView[];
45
50
  /** Whether `POST /api/v1/orgs` would accept this account (the `orgCreation` setting). */
46
51
  canCreateOrg: boolean;
47
52
  }>;
53
+ /**
54
+ * Registers an upload of the person's avatar (png / jpeg / webp, at most 2 MB); the browser
55
+ * uploads to `upload`, then saves it with `PATCH /me/profile`. No object store → 503
56
+ * `storage.unavailable`.
57
+ */
58
+ createAvatarUpload(principal: Principal, body: z.infer<typeof AvatarUploadSchema>): Promise<{
59
+ uploadId: string;
60
+ upload: PresignedUpload;
61
+ expiresAt: string;
62
+ }>;
63
+ /**
64
+ * Changes the person's own name and avatar (a field left out keeps its value). An upload avatar
65
+ * is checked against the object store first (outside the transaction), then bound in the
66
+ * profile write's transaction; `avatar: null` removes it. A changed name over 64 characters →
67
+ * 400 `account.display_name_too_long`.
68
+ */
69
+ updateProfile(principal: Principal, body: z.infer<typeof ProfilePatchSchema>): Promise<{
70
+ account: AccountView;
71
+ }>;
48
72
  /**
49
73
  * The person's preferences: `timeZone` null = follow the browser's time zone sent with each
50
74
  * message, a set zone overrides it for the messages sent afterwards (run context spec §3.4);
@@ -7,19 +7,22 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
- import { Controller, Delete, Get, HttpCode, Inject, Param, Post, Put, Req, Res, } from "@nestjs/common";
10
+ import { Controller, Delete, Get, HttpCode, Inject, Param, Patch, Post, Put, Req, Res, } from "@nestjs/common";
11
11
  import { z } from "zod";
12
12
  import { ApiError } from "../errors.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
14
  import { CredentialThrottler } from "../infra/throttler/credential-throttler.js";
14
15
  import { KERNEL_LOGGER } from "../infra/tokens.js";
15
16
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
16
17
  import { ZBody } from "../infra/validation/zod-params.js";
17
18
  import { OrgsService } from "../orgs/orgs.service.js";
19
+ import { withAvatarUrl } from "./account-avatar.js";
20
+ import { AccountAvatarsService } from "./account-avatars.service.js";
18
21
  import { AccountsService } from "./accounts.js";
19
22
  import { ApiTokenService, FutureIsoDate } from "./api-tokens.js";
20
23
  import { MAX_PASSWORD_LENGTH } from "./login.js";
21
- import { PreferencesBody } from "./me.schemas.js";
22
- import { AllowPendingPasswordChange, CurrentPrincipal, requireUser, SessionOnly, } from "./principal.js";
24
+ import { AvatarUploadBody, PreferencesBody, ProfilePatchBody, } from "./me.schemas.js";
25
+ import { AllowPendingPasswordChange, CurrentPrincipal, patTokenId, requireUser, SessionOnly, } from "./principal.js";
23
26
  import { SessionService } from "./sessions.js";
24
27
  import { SettingsService } from "./settings.js";
25
28
  /** The credential throttlers of a password change (per account, per client IP). */
@@ -48,7 +51,9 @@ let MeController = class MeController {
48
51
  throttler;
49
52
  log;
50
53
  settings;
51
- constructor(accounts, sessions, orgs, tokens, throttler, log, settings) {
54
+ db;
55
+ avatars;
56
+ constructor(accounts, sessions, orgs, tokens, throttler, log, settings, db, avatars) {
52
57
  this.accounts = accounts;
53
58
  this.sessions = sessions;
54
59
  this.orgs = orgs;
@@ -56,6 +61,8 @@ let MeController = class MeController {
56
61
  this.throttler = throttler;
57
62
  this.log = log;
58
63
  this.settings = settings;
64
+ this.db = db;
65
+ this.avatars = avatars;
59
66
  }
60
67
  async me(principal) {
61
68
  const p = requireUser(principal);
@@ -71,7 +78,38 @@ let MeController = class MeController {
71
78
  const current = memberships.some((m) => m.orgId === currentOrgId) ? currentOrgId : null;
72
79
  const { orgCreation } = await this.settings.get();
73
80
  const canCreateOrg = orgCreation === "anyone" || p.account.isSuperAdmin;
74
- return { account: p.account, via: p.via, currentOrgId: current, memberships, canCreateOrg };
81
+ return {
82
+ account: await withAvatarUrl(this.db.db, p.account),
83
+ via: p.via,
84
+ currentOrgId: current,
85
+ memberships,
86
+ canCreateOrg,
87
+ };
88
+ }
89
+ /**
90
+ * Registers an upload of the person's avatar (png / jpeg / webp, at most 2 MB); the browser
91
+ * uploads to `upload`, then saves it with `PATCH /me/profile`. No object store → 503
92
+ * `storage.unavailable`.
93
+ */
94
+ async createAvatarUpload(principal, body) {
95
+ return this.avatars.createUpload(requireUser(principal).account.id, body);
96
+ }
97
+ /**
98
+ * Changes the person's own name and avatar (a field left out keeps its value). An upload avatar
99
+ * is checked against the object store first (outside the transaction), then bound in the
100
+ * profile write's transaction; `avatar: null` removes it. A changed name over 64 characters →
101
+ * 400 `account.display_name_too_long`.
102
+ */
103
+ async updateProfile(principal, body) {
104
+ const p = requireUser(principal);
105
+ const accountId = p.account.id;
106
+ if (body.avatar)
107
+ await this.avatars.prepare(accountId, body.avatar.uploadId);
108
+ const account = await this.accounts.updateProfile(accountId, {
109
+ ...(body.displayName !== undefined && { displayName: body.displayName }),
110
+ ...(body.avatar !== undefined && { avatar: body.avatar }),
111
+ }, patTokenId(p), { bindAvatar: (uploadId) => this.avatars.bind(accountId, uploadId) });
112
+ return { account };
75
113
  }
76
114
  /**
77
115
  * The person's preferences: `timeZone` null = follow the browser's time zone sent with each
@@ -149,6 +187,17 @@ __decorate([
149
187
  AllowPendingPasswordChange(),
150
188
  __param(0, CurrentPrincipal())
151
189
  ], MeController.prototype, "me", null);
190
+ __decorate([
191
+ Post("avatar/uploads"),
192
+ HttpCode(201),
193
+ __param(0, CurrentPrincipal()),
194
+ __param(1, ZBody(AvatarUploadBody))
195
+ ], MeController.prototype, "createAvatarUpload", null);
196
+ __decorate([
197
+ Patch("profile"),
198
+ __param(0, CurrentPrincipal()),
199
+ __param(1, ZBody(ProfilePatchBody))
200
+ ], MeController.prototype, "updateProfile", null);
152
201
  __decorate([
153
202
  Get("preferences"),
154
203
  __param(0, CurrentPrincipal())
@@ -201,6 +250,8 @@ MeController = __decorate([
201
250
  __param(3, Inject(ApiTokenService)),
202
251
  __param(4, Inject(CredentialThrottler)),
203
252
  __param(5, Inject(KERNEL_LOGGER)),
204
- __param(6, Inject(SettingsService))
253
+ __param(6, Inject(SettingsService)),
254
+ __param(7, Inject(KernelDb)),
255
+ __param(8, Inject(AccountAvatarsService))
205
256
  ], MeController);
206
257
  export { MeController };
@@ -19,6 +19,42 @@ declare const PreferencesBody_base: import("../infra/validation/create-zod-dto.j
19
19
  }, z.core.$strict>>;
20
20
  export declare class PreferencesBody extends PreferencesBody_base {
21
21
  }
22
+ /**
23
+ * `POST /me/avatar/uploads`: the image to upload. The type (png / jpeg / webp) and the 2 MB limit
24
+ * are checked by the service, so they answer `attachment.type_not_allowed` / `attachment.too_large`
25
+ * like the agent avatar's codes.
26
+ */
27
+ export declare const AvatarUploadSchema: z.ZodObject<{
28
+ contentType: z.ZodString;
29
+ size: z.ZodNumber;
30
+ }, z.core.$strict>;
31
+ declare const AvatarUploadBody_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
32
+ contentType: z.ZodString;
33
+ size: z.ZodNumber;
34
+ }, z.core.$strict>>;
35
+ export declare class AvatarUploadBody extends AvatarUploadBody_base {
36
+ }
37
+ /**
38
+ * `PATCH /me/profile`: a field left out keeps its value. `displayName` is trimmed; the 1000 bound
39
+ * is a body sanity bound, a changed name must have at most 64 code points (the service checks,
40
+ * `account.display_name_too_long`). `avatar: null` removes the own avatar.
41
+ */
42
+ export declare const ProfilePatchSchema: z.ZodObject<{
43
+ displayName: z.ZodOptional<z.ZodString>;
44
+ avatar: z.ZodOptional<z.ZodNullable<z.ZodObject<{
45
+ kind: z.ZodLiteral<"upload">;
46
+ uploadId: z.ZodString;
47
+ }, z.core.$strict>>>;
48
+ }, z.core.$strict>;
49
+ declare const ProfilePatchBody_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
50
+ displayName: z.ZodOptional<z.ZodString>;
51
+ avatar: z.ZodOptional<z.ZodNullable<z.ZodObject<{
52
+ kind: z.ZodLiteral<"upload">;
53
+ uploadId: z.ZodString;
54
+ }, z.core.$strict>>>;
55
+ }, z.core.$strict>>;
56
+ export declare class ProfilePatchBody extends ProfilePatchBody_base {
57
+ }
22
58
  /** The `/me` routes the Platform operations mirror (`check:platform-ops` keys). */
23
59
  export declare const ME_ROUTES: readonly RouteSchemas[];
24
60
  export {};
@@ -18,6 +18,36 @@ export const PreferencesSchema = z
18
18
  .strict();
19
19
  export class PreferencesBody extends createZodDto(PreferencesSchema, "PreferencesBody") {
20
20
  }
21
+ /**
22
+ * `POST /me/avatar/uploads`: the image to upload. The type (png / jpeg / webp) and the 2 MB limit
23
+ * are checked by the service, so they answer `attachment.type_not_allowed` / `attachment.too_large`
24
+ * like the agent avatar's codes.
25
+ */
26
+ export const AvatarUploadSchema = z
27
+ .object({
28
+ contentType: z.string().min(1).max(200),
29
+ size: z.number().int().min(1),
30
+ })
31
+ .strict();
32
+ export class AvatarUploadBody extends createZodDto(AvatarUploadSchema, "AccountAvatarUploadBody") {
33
+ }
34
+ /**
35
+ * `PATCH /me/profile`: a field left out keeps its value. `displayName` is trimmed; the 1000 bound
36
+ * is a body sanity bound, a changed name must have at most 64 code points (the service checks,
37
+ * `account.display_name_too_long`). `avatar: null` removes the own avatar.
38
+ */
39
+ export const ProfilePatchSchema = z
40
+ .object({
41
+ displayName: z.string().trim().min(1).max(1000).optional(),
42
+ avatar: z
43
+ .object({ kind: z.literal("upload"), uploadId: z.string().min(1).max(100) })
44
+ .strict()
45
+ .nullable()
46
+ .optional(),
47
+ })
48
+ .strict();
49
+ export class ProfilePatchBody extends createZodDto(ProfilePatchSchema, "ProfilePatchBody") {
50
+ }
21
51
  /** The `/me` routes the Platform operations mirror (`check:platform-ops` keys). */
22
52
  export const ME_ROUTES = [
23
53
  { route: "GET /api/v1/me/preferences" },
@@ -43,8 +43,8 @@ export declare const SuperAdmin: () => MethodDecorator & ClassDecorator;
43
43
  /**
44
44
  * Reachable by an account that must change its generated initial password first
45
45
  * (`Account.mustChangePassword`): the guard refuses every other route with
46
- * `auth.password_change_required`. Only `GET /me` and `PUT /me/password` carry it (public routes
47
- * such as logout are reachable anyway).
46
+ * `auth.password_change_required`. Only `GET /me`, `PUT /me/password` and the avatar image route
47
+ * (the account's own image only) carry it (public routes such as logout are reachable anyway).
48
48
  */
49
49
  export declare const AllowPendingPasswordChange: () => MethodDecorator;
50
50
  /**
@@ -17,8 +17,8 @@ export const SuperAdmin = () => SetMetadata(SUPER_ADMIN_KEY, true);
17
17
  /**
18
18
  * Reachable by an account that must change its generated initial password first
19
19
  * (`Account.mustChangePassword`): the guard refuses every other route with
20
- * `auth.password_change_required`. Only `GET /me` and `PUT /me/password` carry it (public routes
21
- * such as logout are reachable anyway).
20
+ * `auth.password_change_required`. Only `GET /me`, `PUT /me/password` and the avatar image route
21
+ * (the account's own image only) carry it (public routes such as logout are reachable anyway).
22
22
  */
23
23
  export const AllowPendingPasswordChange = () => SetMetadata(PASSWORD_CHANGE_KEY, true);
24
24
  /**
@@ -64,6 +64,8 @@ declare class DeviceConnection {
64
64
  */
65
65
  readonly connectionId: `${string}-${string}-${string}-${string}-${string}`;
66
66
  private effectiveCap;
67
+ /** The program run the hello named (`programRunId`), published with the capacity. */
68
+ private programRunId;
67
69
  private ready;
68
70
  /** Consecutive failed capacity publications on ping (this socket's own state). */
69
71
  private publishFailures;
@@ -133,6 +133,8 @@ class DeviceConnection {
133
133
  */
134
134
  connectionId = randomUUID();
135
135
  effectiveCap;
136
+ /** The program run the hello named (`programRunId`), published with the capacity. */
137
+ programRunId;
136
138
  ready = false;
137
139
  /** Consecutive failed capacity publications on ping (this socket's own state). */
138
140
  publishFailures = 0;
@@ -143,7 +145,11 @@ class DeviceConnection {
143
145
  await this.close(DEVICE_CLOSE.protocol, "Frame capacity changed; reconnect");
144
146
  return;
145
147
  }
146
- await this.gw.redis.set(deviceTransportKey(this.deviceId, this.token), JSON.stringify({ connectionId: this.connectionId, maxFrameBytes: this.effectiveCap }), "PX", Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3));
148
+ await this.gw.redis.set(deviceTransportKey(this.deviceId, this.token), JSON.stringify({
149
+ connectionId: this.connectionId,
150
+ maxFrameBytes: this.effectiveCap,
151
+ ...(this.programRunId !== undefined && { programRunId: this.programRunId }),
152
+ }), "PX", Math.max(this.gw.leaseTtlMs(), this.gw.pingIntervalMs * 3));
147
153
  }
148
154
  get deviceId() {
149
155
  return this.identity.deviceId;
@@ -207,6 +213,7 @@ class DeviceConnection {
207
213
  return;
208
214
  }
209
215
  clearTimeout(this.helloTimer);
216
+ this.programRunId = frame.programRunId;
210
217
  this.state = "claiming";
211
218
  // set before the first await: a policy frame that follows is recorded after the hello
212
219
  this.recorded = (async () => {
@@ -5,7 +5,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { LockService } from "../infra/lock/lock.service.js";
6
6
  import type { KernelLogger } from "../log.js";
7
7
  import { DeviceRequestNotSentError, isDeviceRequestNotSent } from "../sandbox/request-not-sent.js";
8
- import { DeviceTargets } from "./targets.js";
8
+ import { type DeviceConnectionInfo, DeviceTargets } from "./targets.js";
9
9
  /** The device's connected machine is not connected (no replica holds its lease). */
10
10
  export declare const deviceOffline: () => ApiError;
11
11
  export { machineRevoked } from "../devices/errors.js";
@@ -78,8 +78,10 @@ export interface DeviceCallOptions {
78
78
  * and once more before giving up (the run-abort pattern; a publish lost while the subscriber
79
79
  * reconnects is still found). It waits within its own call for at most `deadlineMs` plus
80
80
  * `devices.local.reconnectGraceSeconds`; when the lease disappears meanwhile (checked every
81
- * {@link HOLDER_POLL_MS}) the wait ends at most one grace later. A result produced while the
82
- * machine was disconnected arrives after it reconnects. Giving up (grace, abort, a bad result)
81
+ * {@link HOLDER_POLL_MS}) the wait ends at most one grace later, and when the machine is connected
82
+ * again as another run of its program (`programRunId`) it ends at that poll with
83
+ * {@link DeviceProgramRestartedError}: the old run's kept results died with it. A result produced
84
+ * while the machine was disconnected arrives after it reconnects. Giving up (grace, abort, a bad result)
83
85
  * removes the request from the list, or queues a `cancel` when the machine already took it
84
86
  * (ruling R15). Nothing is kept in process memory beyond the call.
85
87
  */
@@ -90,7 +92,7 @@ export declare class LocalDeviceRelay {
90
92
  private readonly config;
91
93
  private readonly log;
92
94
  private readonly targets;
93
- constructor(redis: Redis, bus: ExtensionContext["bus"], locks: Pick<LockService, "holderOf">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">, targets: Pick<DeviceTargets, "state" | "transport">);
95
+ constructor(redis: Redis, bus: ExtensionContext["bus"], locks: Pick<LockService, "holderOf">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">, targets: Pick<DeviceTargets, "state" | "current">);
94
96
  /** Whether a gateway replica holds the machine's connection now. */
95
97
  holderLive(deviceId: string): Promise<boolean>;
96
98
  /**
@@ -105,12 +107,11 @@ export declare class LocalDeviceRelay {
105
107
  /**
106
108
  * The negotiated transport of the machine's current connection, for a staged call. Liveness is
107
109
  * checked first (ruling R27): no holder throws `device.not_found` for a deleted device,
108
- * `device.forbidden` for a revoked machine and `device.offline` otherwise.
110
+ * `device.forbidden` for a revoked machine and `device.offline` otherwise. It carries the program
111
+ * run the connection's hello named (`programRunId`, when reported): kernel-internal evidence a
112
+ * staged call keeps, never put into a frame. Every staged call reads its connection here.
109
113
  */
110
- connection(deviceId: string): Promise<{
111
- connectionId: string;
112
- maxFrameBytes: number;
113
- }>;
114
+ connection(deviceId: string): Promise<DeviceConnectionInfo>;
114
115
  /**
115
116
  * Queues `stop` for the machine without waiting for an answer (ruling R14). The caller checks
116
117
  * {@link holderLive} first; the frame waits on the list for the grace like any request. It is
@@ -15,7 +15,7 @@ import { ApiError } from "../errors.js";
15
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { LockService } from "../infra/lock/lock.service.js";
17
17
  import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
18
- import { DeviceRequestNotSentError, isDeviceRequestNotSent } from "../sandbox/request-not-sent.js";
18
+ import { DeviceProgramRestartedError, DeviceRequestNotSentError, isDeviceRequestNotSent, } from "../sandbox/request-not-sent.js";
19
19
  import { deviceNotFound } from "../sandbox/sandbox.service.js";
20
20
  import { deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, } from "./keys.js";
21
21
  import { DeviceTargets } from "./targets.js";
@@ -136,8 +136,10 @@ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
136
136
  * and once more before giving up (the run-abort pattern; a publish lost while the subscriber
137
137
  * reconnects is still found). It waits within its own call for at most `deadlineMs` plus
138
138
  * `devices.local.reconnectGraceSeconds`; when the lease disappears meanwhile (checked every
139
- * {@link HOLDER_POLL_MS}) the wait ends at most one grace later. A result produced while the
140
- * machine was disconnected arrives after it reconnects. Giving up (grace, abort, a bad result)
139
+ * {@link HOLDER_POLL_MS}) the wait ends at most one grace later, and when the machine is connected
140
+ * again as another run of its program (`programRunId`) it ends at that poll with
141
+ * {@link DeviceProgramRestartedError}: the old run's kept results died with it. A result produced
142
+ * while the machine was disconnected arrives after it reconnects. Giving up (grace, abort, a bad result)
141
143
  * removes the request from the list, or queues a `cancel` when the machine already took it
142
144
  * (ruling R15). Nothing is kept in process memory beyond the call.
143
145
  */
@@ -171,13 +173,15 @@ let LocalDeviceRelay = class LocalDeviceRelay {
171
173
  /**
172
174
  * The negotiated transport of the machine's current connection, for a staged call. Liveness is
173
175
  * checked first (ruling R27): no holder throws `device.not_found` for a deleted device,
174
- * `device.forbidden` for a revoked machine and `device.offline` otherwise.
176
+ * `device.forbidden` for a revoked machine and `device.offline` otherwise. It carries the program
177
+ * run the connection's hello named (`programRunId`, when reported): kernel-internal evidence a
178
+ * staged call keeps, never put into a frame. Every staged call reads its connection here.
175
179
  */
176
180
  async connection(deviceId) {
177
181
  if (await this.holderLive(deviceId)) {
178
- const transport = await this.targets.transport(deviceId);
179
- if (transport)
180
- return transport;
182
+ const current = await this.targets.current(deviceId);
183
+ if (current)
184
+ return current;
181
185
  }
182
186
  throw this.goneError(await this.targetState(deviceId)) ?? deviceOffline();
183
187
  }
@@ -222,7 +226,14 @@ let LocalDeviceRelay = class LocalDeviceRelay {
222
226
  const { signal } = opts;
223
227
  signal.throwIfAborted();
224
228
  // liveness first: a deleted device or a revoked machine keeps its typed error (R27)
225
- const connection = staged ? await this.connection(deviceId) : undefined;
229
+ const current = staged ? await this.connection(deviceId) : undefined;
230
+ const connection = current && {
231
+ connectionId: current.connectionId,
232
+ maxFrameBytes: current.maxFrameBytes,
233
+ };
234
+ // the program run the request goes to: the drain sends it only on this connection (a newer
235
+ // one refuses it as not sent), so a later connection of another run proves its result lost
236
+ const sentToRun = current?.programRunId;
226
237
  if (!staged && !(await this.holderLive(deviceId))) {
227
238
  throw this.goneError(await this.targetState(deviceId)) ?? deviceOffline();
228
239
  }
@@ -282,7 +293,7 @@ let LocalDeviceRelay = class LocalDeviceRelay {
282
293
  const live = await this.leaseCheck(deviceId);
283
294
  if (fenced && connection && live === true) {
284
295
  // an output read never waits across a reconnect: its range was sized for this socket
285
- const current = await this.targets.transport(deviceId);
296
+ const current = await this.targets.current(deviceId);
286
297
  if (current &&
287
298
  (current.connectionId !== connection.connectionId ||
288
299
  current.maxFrameBytes !== connection.maxFrameBytes)) {
@@ -290,6 +301,18 @@ let LocalDeviceRelay = class LocalDeviceRelay {
290
301
  return;
291
302
  }
292
303
  }
304
+ if (!fenced && sentToRun !== undefined && live === true) {
305
+ // results a program keeps for a reconnect live in its memory: once the machine is
306
+ // connected as another run, this request's result can never arrive (unless it was
307
+ // stored before the old run went away, which the last look below still finds)
308
+ const now = await this.targets.current(deviceId).catch(() => null);
309
+ if (now?.programRunId !== undefined && now.programRunId !== sentToRun) {
310
+ this.redis.get(deviceResKey(id)).then((raw) => raw !== null
311
+ ? onStored(raw)
312
+ : settle({ error: new DeviceProgramRestartedError(op) }), () => settle({ error: new DeviceProgramRestartedError(op) }));
313
+ return;
314
+ }
315
+ }
293
316
  if (live === true && capped) {
294
317
  capped = false;
295
318
  giveUpAt = fullGiveUpAt;
@@ -8,6 +8,12 @@ import { LockService } from "../infra/lock/lock.service.js";
8
8
  * deleted, or its org deleted).
9
9
  */
10
10
  export type DeviceTargetState = "active" | "revoked" | "deleted";
11
+ /** A machine connection as {@link DeviceTargets.current} reads it. */
12
+ export interface DeviceConnectionInfo {
13
+ connectionId: string;
14
+ maxFrameBytes: number;
15
+ programRunId?: string;
16
+ }
11
17
  /** Whether two sets of roots name the same three directories. */
12
18
  export declare const sameRoots: (a: SandboxRoots, b: SandboxRoots) => boolean;
13
19
  /**
@@ -32,6 +38,12 @@ export declare class DeviceTargets {
32
38
  connectionId: string;
33
39
  maxFrameBytes: number;
34
40
  } | null>;
41
+ /**
42
+ * {@link transport} plus the program run the connection's hello named (`programRunId`, absent
43
+ * for a program that does not report one): the relay's evidence that the machine's program
44
+ * restarted since it sent a request. Never part of a frame.
45
+ */
46
+ current(deviceId: string): Promise<DeviceConnectionInfo | null>;
35
47
  state(deviceId: string): Promise<DeviceTargetState>;
36
48
  /** The org of a live device, or null (missing or deleted). */
37
49
  orgOf(deviceId: string): Promise<string | null>;
@@ -39,6 +39,18 @@ let DeviceTargets = class DeviceTargets {
39
39
  * throws while the holder has not published its capacity yet.
40
40
  */
41
41
  async transport(deviceId) {
42
+ const current = await this.current(deviceId);
43
+ if (!current)
44
+ return null;
45
+ const { connectionId, maxFrameBytes } = current;
46
+ return { connectionId, maxFrameBytes };
47
+ }
48
+ /**
49
+ * {@link transport} plus the program run the connection's hello named (`programRunId`, absent
50
+ * for a program that does not report one): the relay's evidence that the machine's program
51
+ * restarted since it sent a request. Never part of a frame.
52
+ */
53
+ async current(deviceId) {
42
54
  const lease = await this.locks.holderOf(deviceLeaseKey(deviceId));
43
55
  if (!lease)
44
56
  return null;
@@ -52,8 +64,12 @@ let DeviceTargets = class DeviceTargets {
52
64
  cap.maxFrameBytes >= 1024;
53
65
  if (!ok || (await this.locks.holderOf(deviceLeaseKey(deviceId))) !== lease)
54
66
  throw new Error("The machine's connection is not ready yet; retry once capybara-device has reconnected");
55
- const { connectionId, maxFrameBytes } = cap;
56
- return { connectionId, maxFrameBytes };
67
+ const { connectionId, maxFrameBytes, programRunId } = cap;
68
+ return {
69
+ connectionId,
70
+ maxFrameBytes,
71
+ ...(typeof programRunId === "string" && programRunId !== "" && { programRunId }),
72
+ };
57
73
  }
58
74
  async state(deviceId) {
59
75
  const row = await this.db
@@ -6,7 +6,9 @@ import { Offboarding } from "./offboarding.js";
6
6
  import { OrgLock } from "./org-lock.js";
7
7
  import type { OrgRole } from "./roles.js";
8
8
  export interface Member {
9
- account: Pick<Account, "id" | "displayName" | "email">;
9
+ account: Pick<Account, "id" | "displayName" | "email"> & {
10
+ avatarUrl: string | null;
11
+ };
10
12
  role: OrgRole;
11
13
  joinedAt: Date;
12
14
  /** 该组织的匿名访客(渠道连接的匿名策略用):不能改角色、移出、转让所有权或指派为 agent 负责人。 */