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

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 (174) hide show
  1. package/dist/admin/account-erasures.d.ts +37 -0
  2. package/dist/admin/account-erasures.js +119 -0
  3. package/dist/admin/admin.controller.d.ts +35 -2
  4. package/dist/admin/admin.controller.js +75 -18
  5. package/dist/admin/admin.module.js +10 -0
  6. package/dist/admin/admin.schemas.d.ts +51 -0
  7. package/dist/admin/admin.schemas.js +20 -0
  8. package/dist/admin/erasure-dispositions.d.ts +23 -0
  9. package/dist/admin/erasure-dispositions.js +76 -0
  10. package/dist/admin/health.service.d.ts +6 -0
  11. package/dist/admin/health.service.js +27 -1
  12. package/dist/admin/usage.service.d.ts +5 -0
  13. package/dist/admin/usage.service.js +21 -2
  14. package/dist/agents/agents.service.d.ts +1 -1
  15. package/dist/channels/connections.service.d.ts +1 -1
  16. package/dist/client/client-reports.service.js +12 -0
  17. package/dist/config/schema.d.ts +8 -1
  18. package/dist/config/schema.js +43 -1
  19. package/dist/conversations/conversations.service.d.ts +9 -1
  20. package/dist/conversations/conversations.service.js +112 -15
  21. package/dist/conversations/event-log.d.ts +2 -0
  22. package/dist/conversations/event-log.js +77 -0
  23. package/dist/conversations/events.d.ts +11 -0
  24. package/dist/conversations/events.js +13 -1
  25. package/dist/conversations/prompt-suggestions.js +4 -0
  26. package/dist/conversations/titles.js +3 -2
  27. package/dist/db/kernel-schema.d.ts +71 -8
  28. package/dist/devices/devices.service.d.ts +13 -1
  29. package/dist/devices/devices.service.js +122 -9
  30. package/dist/erasure/account-batches.d.ts +9 -0
  31. package/dist/erasure/account-batches.js +567 -0
  32. package/dist/erasure/account-files.d.ts +34 -0
  33. package/dist/erasure/account-files.js +217 -0
  34. package/dist/erasure/account-residual.d.ts +15 -0
  35. package/dist/erasure/account-residual.js +149 -0
  36. package/dist/erasure/account-worker.d.ts +32 -0
  37. package/dist/erasure/account-worker.js +392 -0
  38. package/dist/erasure/device-cleanup.d.ts +23 -0
  39. package/dist/erasure/device-cleanup.js +221 -0
  40. package/dist/erasure/erasure.module.d.ts +2 -0
  41. package/dist/erasure/erasure.module.js +14 -0
  42. package/dist/erasure/external-evidence.d.ts +4 -0
  43. package/dist/erasure/external-evidence.js +28 -0
  44. package/dist/erasure/jobs.d.ts +5 -0
  45. package/dist/erasure/jobs.js +20 -0
  46. package/dist/erasure/org-batches.d.ts +11 -0
  47. package/dist/erasure/org-batches.js +159 -0
  48. package/dist/erasure/org-catalog.d.ts +2 -0
  49. package/dist/erasure/org-catalog.js +34 -0
  50. package/dist/erasure/org-rules.d.ts +14 -0
  51. package/dist/erasure/org-rules.js +227 -0
  52. package/dist/erasure/org-worker.d.ts +38 -0
  53. package/dist/erasure/org-worker.js +501 -0
  54. package/dist/erasure/requests.d.ts +61 -0
  55. package/dist/erasure/requests.js +180 -0
  56. package/dist/erasure/sweep.job.d.ts +19 -0
  57. package/dist/erasure/sweep.job.js +130 -0
  58. package/dist/erasure/worker.d.ts +17 -0
  59. package/dist/erasure/worker.js +110 -0
  60. package/dist/errors.d.ts +4 -0
  61. package/dist/errors.js +4 -0
  62. package/dist/evals/judge.d.ts +5 -0
  63. package/dist/evals/judge.js +16 -1
  64. package/dist/evals/run-replay.js +12 -1
  65. package/dist/evals/step-replay.d.ts +5 -3
  66. package/dist/evals/step-replay.js +9 -5
  67. package/dist/evals/worker.d.ts +2 -0
  68. package/dist/evals/worker.js +60 -16
  69. package/dist/files/blob-objects.d.ts +7 -3
  70. package/dist/files/blob-objects.js +39 -22
  71. package/dist/files/blob-sweep.job.d.ts +11 -0
  72. package/dist/files/blob-sweep.job.js +67 -6
  73. package/dist/http/api.module.js +5 -1
  74. package/dist/identity/accounts.js +3 -0
  75. package/dist/identity/api-tokens.js +5 -0
  76. package/dist/identity/auth.guard.d.ts +1 -0
  77. package/dist/identity/auth.guard.js +1 -0
  78. package/dist/identity/erasure-admission.d.ts +3 -0
  79. package/dist/identity/erasure-admission.js +14 -0
  80. package/dist/identity/external.js +5 -0
  81. package/dist/identity/sessions.js +5 -0
  82. package/dist/identity/settings.d.ts +86 -1
  83. package/dist/identity/settings.js +38 -4
  84. package/dist/infra/config/kernel-config.service.js +1 -0
  85. package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
  86. package/dist/infra/metrics/kernel-metrics.js +54 -0
  87. package/dist/infra/metrics/operational-metrics.d.ts +31 -0
  88. package/dist/infra/metrics/operational-metrics.js +188 -0
  89. package/dist/infra/outbox/registry.d.ts +23 -0
  90. package/dist/infra/outbox/registry.js +12 -0
  91. package/dist/infra/throttler/credential-throttler.js +8 -1
  92. package/dist/infra/throttler/named-throttlers.d.ts +6 -0
  93. package/dist/infra/throttler/named-throttlers.js +6 -0
  94. package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
  95. package/dist/infra/throttler/principal-throttler.guard.js +50 -0
  96. package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
  97. package/dist/infra/throttler/redis-throttler-storage.js +27 -5
  98. package/dist/infra/throttler/throttler.guard.d.ts +2 -3
  99. package/dist/infra/throttler/throttler.guard.js +2 -3
  100. package/dist/infra/throttler/throttler.module.js +3 -2
  101. package/dist/models/budget-admission.d.ts +31 -0
  102. package/dist/models/budget-admission.js +149 -0
  103. package/dist/models/budget-counters.d.ts +28 -0
  104. package/dist/models/budget-counters.js +117 -0
  105. package/dist/models/budget-policy.d.ts +88 -0
  106. package/dist/models/budget-policy.js +78 -0
  107. package/dist/models/embeddings.js +13 -2
  108. package/dist/models/images.js +12 -2
  109. package/dist/models/purposes.d.ts +5 -2
  110. package/dist/models/purposes.js +9 -5
  111. package/dist/orgs/invitations.service.d.ts +1 -1
  112. package/dist/orgs/members.service.d.ts +28 -1
  113. package/dist/orgs/members.service.js +74 -11
  114. package/dist/orgs/offboarding.js +4 -6
  115. package/dist/orgs/org-owner.d.ts +2 -0
  116. package/dist/orgs/org-owner.js +21 -6
  117. package/dist/orgs/orgs.controller.d.ts +22 -0
  118. package/dist/orgs/orgs.controller.js +24 -0
  119. package/dist/orgs/orgs.module.js +4 -0
  120. package/dist/orgs/orgs.schemas.js +7 -0
  121. package/dist/orgs/orgs.service.d.ts +5 -1
  122. package/dist/orgs/orgs.service.js +28 -3
  123. package/dist/orgs/settings.controller.js +6 -1
  124. package/dist/orgs/settings.service.d.ts +58 -1
  125. package/dist/orgs/settings.service.js +74 -9
  126. package/dist/platform/exclusions.js +20 -1
  127. package/dist/platform/ops/accounts.ops.js +58 -1
  128. package/dist/platform/ops/admin.ops.js +13 -5
  129. package/dist/platform/ops/org-settings.ops.js +11 -4
  130. package/dist/platform/ops/orgs.ops.js +28 -0
  131. package/dist/platform/ops/retention.d.ts +16 -0
  132. package/dist/platform/ops/retention.js +21 -0
  133. package/dist/retention/jobs.d.ts +21 -0
  134. package/dist/retention/jobs.js +48 -0
  135. package/dist/retention/policy.d.ts +70 -0
  136. package/dist/retention/policy.js +103 -0
  137. package/dist/retention/purge-batch.d.ts +17 -0
  138. package/dist/retention/purge-batch.js +355 -0
  139. package/dist/retention/report-obligations.d.ts +12 -0
  140. package/dist/retention/report-obligations.js +71 -0
  141. package/dist/retention/sweep.job.d.ts +17 -0
  142. package/dist/retention/sweep.job.js +95 -0
  143. package/dist/retention/worker.d.ts +29 -0
  144. package/dist/retention/worker.js +306 -0
  145. package/dist/roles/worker.module.js +12 -2
  146. package/dist/runtime/maintenance.d.ts +5 -1
  147. package/dist/runtime/maintenance.js +20 -2
  148. package/dist/runtime/model-call.d.ts +3 -1
  149. package/dist/runtime/model-call.js +25 -3
  150. package/dist/runtime/providers.d.ts +7 -2
  151. package/dist/runtime/providers.js +76 -10
  152. package/dist/runtime/quota.d.ts +12 -12
  153. package/dist/runtime/quota.js +42 -37
  154. package/dist/runtime/run-finish.js +2 -0
  155. package/dist/runtime/run-principal.d.ts +9 -0
  156. package/dist/runtime/run-principal.js +18 -0
  157. package/dist/runtime/run-worker.js +48 -10
  158. package/dist/runtime/usage-report-jobs.d.ts +4 -1
  159. package/dist/runtime/usage-report-jobs.js +36 -13
  160. package/dist/runtime/usage-report.d.ts +5 -3
  161. package/dist/runtime/usage-report.js +37 -19
  162. package/dist/sandbox/review/classifier.d.ts +2 -2
  163. package/dist/sandbox/review/classifier.js +6 -2
  164. package/dist/sandbox/sandbox.service.js +18 -7
  165. package/dist/storage/purge.js +5 -1
  166. package/dist/storage/storage.service.d.ts +17 -1
  167. package/dist/storage/storage.service.js +75 -4
  168. package/dist/tools/builtins/vision/read-image.js +3 -0
  169. package/dist/tools/builtins/web/extract.js +3 -0
  170. package/dist/tools/pipeline.js +5 -1
  171. package/package.json +3 -1
  172. package/src/migrations/0216_model_budget_counters.sql +24 -0
  173. package/src/migrations/0217_retention.sql +44 -0
  174. package/src/migrations/0218_data_erasure.sql +41 -0
@@ -33,11 +33,14 @@ import { defineOperation } from "../operation.js";
33
33
  import { PlatformOperations } from "../registry.js";
34
34
  import { precheckBy, viaAgent } from "./errors.js";
35
35
  import { Cursor, pageOf, startOf } from "./paging.js";
36
+ import { retentionHandoff, retentionResult } from "./retention.js";
36
37
  import { localized, named } from "./summary.js";
37
38
  const PAGE = 50;
38
39
  /** The deployment-wide settings `admin.update-settings` changes (the per-org limits are orgs.set-limits). */
39
40
  const SettingsInput = DEPLOYMENT_SETTINGS_PATCH.pick({
40
41
  orgCreation: true,
42
+ modelBudgets: true,
43
+ retention: true,
41
44
  priceCurrency: true,
42
45
  customConnectors: true,
43
46
  customSkills: true,
@@ -254,7 +257,7 @@ let AdminOperations = class AdminOperations {
254
257
  }),
255
258
  defineOperation({
256
259
  id: "admin.update-settings",
257
- description: "Change deployment settings (super admin); give only the keys to change: orgCreation (anyone or super_admin), priceCurrency (ISO 4217 code), customConnectors / customSkills (allow or deny: whether orgs may create their own instead of installing from the catalog), orgMarketplaceBrowse (true or false), uiTheme ({ id }: the platform default theme, a platform theme whose scope is all, or null for the built-in theme; it is what every org falls back to and what the sign-in pages show), uiArrangement ({ <slot>: { hidden, order } } for a list slot, { <slot>: { use } } for a single slot: the platform default arrangement of UI slots, with contribution keys <extension>/<contribution>; hidden ones are not listed but still open by URL; use names the contribution that replaces the built-in, null for the built-in; null for a slot removes its entry), clientExtensions ({ enabled?, disabled? }: the kill switch of plugin client code; enabled false stops every plugin's interface code in every browser, disabled is the whole list of plugins whose interface code alone is stopped while their tools keep working; read the current list from admin.settings first), devicesOutsideSandbox ({ permission }: whether a device may be granted running a call outside its sandbox, allowed or off; null clears it back to the default, allowed; through this tool it may only be turned off, never allowed, and a value set in the startup config is read-only), devicesNetwork ({ default?, ceiling? }: the device sandbox network, open or allowlist; null clears a field back to the default, open; the default may not be above the ceiling; through this tool either may only be narrowed to allowlist, never opened, and a field set in the startup config is read-only), devicesAllowedProfiles ({ value }: choose a subset including request-approval), devicesProjectReach ({ ceiling }: workspace, paths or machine); these two may only narrow through this tool, null follows the default, and startup config is read-only. A super admin decides on wider profile or project reach ceilings in the web admin settings at /admin/settings. The other settings are devicesDefaultProvider ({ provider }: the device provider extension that makes a person's default device; null clears it back to none; read-only when set in the startup config), attribution ({ commit?, pr?, sessionUrl? }: the platform's defaults for agent-created git commits and pull requests; null clears a field back to its default, an empty string turns that line off, and fields set in the startup config are read-only), externalSharing (allow or deny: whether orgs may turn on public links to conversation files; null clears it back to the default, deny; externalSharing may only be turned off through this tool, and a value set in the startup config is read-only), shareMaxExpiryDays (1 to 365: the longest expiry a share may take, in days; null clears it back to 30; through this tool it may only be lowered, never raised, and it is read-only when set in the startup config), htmlRenderCdnAllowlist (the whole list of https origins, scheme and host with an optional port and nothing else, that a rendered HTML file may load from; at most 50; through this tool origins may only be removed, never added, so read the current list from admin.settings first and send it without the ones to drop). promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; an org's own promptSuggestions must be on too) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; an org may override it) may be set either way. Per-org limits are orgs.set-limits.",
260
+ description: "Change deployment settings (super admin); give only the keys to change: orgCreation (anyone or super_admin), priceCurrency (ISO 4217 code), customConnectors / customSkills (allow or deny: whether orgs may create their own instead of installing from the catalog), orgMarketplaceBrowse (true or false), uiTheme ({ id }: the platform default theme, a platform theme whose scope is all, or null for the built-in theme; it is what every org falls back to and what the sign-in pages show), uiArrangement ({ <slot>: { hidden, order } } for a list slot, { <slot>: { use } } for a single slot: the platform default arrangement of UI slots, with contribution keys <extension>/<contribution>; hidden ones are not listed but still open by URL; use names the contribution that replaces the built-in, null for the built-in; null for a slot removes its entry), clientExtensions ({ enabled?, disabled? }: the kill switch of plugin client code; enabled false stops every plugin's interface code in every browser, disabled is the whole list of plugins whose interface code alone is stopped while their tools keep working; read the current list from admin.settings first), devicesOutsideSandbox ({ permission }: whether a device may be granted running a call outside its sandbox, allowed or off; null clears it back to the default, allowed; through this tool it may only be turned off, never allowed, and a value set in the startup config is read-only), devicesNetwork ({ default?, ceiling? }: the device sandbox network, open or allowlist; null clears a field back to the default, open; the default may not be above the ceiling; through this tool either may only be narrowed to allowlist, never opened, and a field set in the startup config is read-only), devicesAllowedProfiles ({ value }: choose a subset including request-approval), devicesProjectReach ({ ceiling }: workspace, paths or machine); these two may only narrow through this tool, null follows the default, and startup config is read-only. A super admin decides on wider profile or project reach ceilings in the web admin settings at /admin/settings. The other settings are devicesDefaultProvider ({ provider }: the device provider extension that makes a person's default device; null clears it back to none; read-only when set in the startup config), attribution ({ commit?, pr?, sessionUrl? }: the platform's defaults for agent-created git commits and pull requests; null clears a field back to its default, an empty string turns that line off, and fields set in the startup config are read-only), externalSharing (allow or deny: whether orgs may turn on public links to conversation files; null clears it back to the default, deny; externalSharing may only be turned off through this tool, and a value set in the startup config is read-only), shareMaxExpiryDays (1 to 365: the longest expiry a share may take, in days; null clears it back to 30; through this tool it may only be lowered, never raised, and it is read-only when set in the startup config), htmlRenderCdnAllowlist (the whole list of https origins, scheme and host with an optional port and nothing else, that a rendered HTML file may load from; at most 50; through this tool origins may only be removed, never added, so read the current list from admin.settings first and send it without the ones to drop). promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; an org's own promptSuggestions must be on too) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; an org may override it) may be set either way. modelBudgets replaces the monthly orgDefault, orgCeiling, memberDefault and memberCeiling policy. Each accepts tokens and spend ({ amount: decimal string, currency: ISO code }); null clears the policy. Configure budgets after all model-serving replicas have upgraded. Per-org limits are orgs.set-limits. Retention accepts partial nullable day counts for conversations, audit and usage. Shortening requires a person to confirm in web settings before future sweeps remove eligible data. platformAuditDays applies to deployment-wide audit events.",
258
261
  input: SettingsInput.refine((b) => Object.keys(b).length > 0, {
259
262
  message: "at least one setting is required",
260
263
  }),
@@ -264,14 +267,18 @@ let AdminOperations = class AdminOperations {
264
267
  // the per-org override records are orgs.set-limits (one org at a time); compaction is
265
268
  // changed in the admin console's settings page
266
269
  omits: [
270
+ "confirmRetentionShortening",
267
271
  "runConcurrencyOverrides",
268
272
  "sandboxLimitOverrides",
269
273
  "subagentLimitOverrides",
270
274
  "compaction",
271
275
  ],
272
276
  confirm: "platform",
273
- noHandoff: "Widenings are refused before confirmation. A super admin makes a separate edit in web settings, where there is no pending operation to review.",
274
277
  errors: [
278
+ {
279
+ code: "retention.confirmation_required",
280
+ next: "Open the settings handoff to review the effect on the next sweep.",
281
+ },
275
282
  {
276
283
  code: "validation_failed",
277
284
  next: "Fix the values as the message says (admin.settings shows the current ones).",
@@ -327,7 +334,7 @@ let AdminOperations = class AdminOperations {
327
334
  },
328
335
  summary: async (i) => {
329
336
  const { uiTheme, uiArrangement, clientExtensions, devicesOutsideSandbox, devicesNetwork, devicesAllowedProfiles, devicesProjectReach, devicesDefaultProvider, attribution, htmlRenderCdnAllowlist, promptCache, ...rest } = i;
330
- const parts = Object.entries(rest).map(([k, v]) => `${k}=${String(v)}`);
337
+ const parts = Object.entries(rest).map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : String(v)}`);
331
338
  if (htmlRenderCdnAllowlist !== undefined) {
332
339
  parts.push(`htmlRenderCdnAllowlist=[${htmlRenderCdnAllowlist.join(", ")}]`);
333
340
  }
@@ -383,9 +390,10 @@ let AdminOperations = class AdminOperations {
383
390
  en: `Change the deployment settings: ${en.join(", ")}`,
384
391
  };
385
392
  },
386
- run: (input, ctx) => this.settings.update(input, ctx.actorAccountId, undefined, viaAgent("admin.update-settings", ctx),
393
+ run: (input, ctx) => retentionResult(() => this.settings.update(input, ctx.actorAccountId, undefined, viaAgent("admin.update-settings", ctx),
387
394
  // a person turns the platform's auto mode on, never an agent (auto mode spec §4.3)
388
- { onlyNarrows: true }),
395
+ { onlyNarrows: true })),
396
+ handoff: (_input, result) => retentionHandoff(result, "/admin/settings"),
389
397
  }),
390
398
  defineOperation({
391
399
  id: "login-sources.list",
@@ -17,6 +17,7 @@ import { ThemesService } from "../../themes/themes.service.js";
17
17
  import { defineOperation } from "../operation.js";
18
18
  import { PlatformOperations } from "../registry.js";
19
19
  import { precheckBy, viaAgent } from "./errors.js";
20
+ import { retentionHandoff, retentionResult } from "./retention.js";
20
21
  import { roleOf } from "./role.js";
21
22
  const PLATFORM_TOOL_NOTE = {
22
23
  off: "The Platform tool is now off for this org: from the next call on, no Platform operation is available, including this one. An org admin can switch it back on in the organization settings on the web.",
@@ -128,15 +129,20 @@ let OrgSettingsOperations = class OrgSettingsOperations {
128
129
  }),
129
130
  defineOperation({
130
131
  id: "org-settings.update",
131
- description: "Change this org's settings (org admins). Give only the settings to change; null clears outsideSandbox, deviceNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). outsideSandbox (allowed or off; the platform must allow it) and deviceNetwork ({ default?, ceiling?: open | allowlist, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep; neither default nor ceiling may be open where the platform's ceiling is allowlist, and the default may not be above the ceiling) may only narrow the org's devices here: allowing outside-sandbox runs where the org has them off, opening the default or the ceiling, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. navigation: { pluginPages: [{ contribution: <extension>/<contribution>, section: primary or more }] } replaces where the org's plugin pages sit in the navigation (at most 3 primary, so send the whole list you keep); null clears it. externalSharing (on or off; null clears it, off) may only be turned off through this tool: turning it on needs a person in the organization settings on the web, and the platform must allow it. promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) may be set either way through this tool. compaction ({ enabled?, threshold? (0.5 to 0.95), keepRecentTurns? (0 to 20), reserveTokens? (0 to 50000), maxOutputTokens? (1024 to 32000), idleEnabled? (compact idle conversations in the background: after idleDelayMinutes with a compaction model, else before a cache of 30 minutes or more expires), idleMinTokensFloor? (50000 to 2000000), idleMinWindowRatio? (0.1 to 0.9), idleDelayMinutes? (5 to 1440; minutes after a run before an idle compaction when a compaction model is set) }: the org's conversation compaction overrides, merged into the stored fields; null clears the override so the org follows the platform) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; null clears it so the org follows the platform) may be set either way. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org; an org admin switches it back on in the web settings.",
132
- input: OrgSettingsPatchSchema.refine((i) => Object.values(i).some((v) => v !== undefined), {
132
+ description: "Change this org's settings (org admins). Give only the settings to change; null clears outsideSandbox, deviceNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). outsideSandbox (allowed or off; the platform must allow it) and deviceNetwork ({ default?, ceiling?: open | allowlist, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep; neither default nor ceiling may be open where the platform's ceiling is allowlist, and the default may not be above the ceiling) may only narrow the org's devices here: allowing outside-sandbox runs where the org has them off, opening the default or the ceiling, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. navigation: { pluginPages: [{ contribution: <extension>/<contribution>, section: primary or more }] } replaces where the org's plugin pages sit in the navigation (at most 3 primary, so send the whole list you keep); null clears it. externalSharing (on or off; null clears it, off) may only be turned off through this tool: turning it on needs a person in the organization settings on the web, and the platform must allow it. promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) may be set either way through this tool. compaction ({ enabled?, threshold? (0.5 to 0.95), keepRecentTurns? (0 to 20), reserveTokens? (0 to 50000), maxOutputTokens? (1024 to 32000), idleEnabled? (compact idle conversations in the background: after idleDelayMinutes with a compaction model, else before a cache of 30 minutes or more expires), idleMinTokensFloor? (50000 to 2000000), idleMinWindowRatio? (0.1 to 0.9), idleDelayMinutes? (5 to 1440; minutes after a run before an idle compaction when a compaction model is set) }: the org's conversation compaction overrides, merged into the stored fields; null clears the override so the org follows the platform) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; null clears it so the org follows the platform) may be set either way. modelBudgets replaces the org and memberDefault monthly policies within platform ceilings. Each accepts tokens and spend ({ amount: decimal string, currency: ISO code }); null restores inheritance. memberRunConcurrency sets concurrent runs per member (zero disables the member cap; null follows the platform). Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org; an org admin switches it back on in the web settings. Retention accepts partial nullable day counts for conversations, audit and usage. Shortening requires a person to confirm in web settings before future sweeps remove eligible data.",
133
+ input: OrgSettingsPatchSchema.omit({ confirmRetentionShortening: true }).refine((i) => Object.values(i).some((v) => v !== undefined), {
133
134
  message: "give at least one setting",
134
135
  }),
135
136
  example: { toolSearch: "on" },
136
137
  authz: { orgAction: "org.update" },
137
138
  mirrors: ["PATCH /api/v1/orgs/:orgId/settings"],
139
+ omits: ["confirmRetentionShortening"],
138
140
  confirm: "org",
139
141
  errors: [
142
+ {
143
+ code: "retention.confirmation_required",
144
+ next: "Open the settings handoff to review the effect on the next sweep.",
145
+ },
140
146
  {
141
147
  code: "org.sandbox_egress_not_allowed",
142
148
  next: "Through this tool the org's device network hosts may only be narrowed: it may drop extra hosts, exclude platform hosts or move base to none, but never add an extra host or drop an exclusion. To widen them, ask an org admin to change them in the organization settings on the web. When the platform limits hosts to its allowlist (deployment.deviceNetwork.orgHosts within), a host outside it needs a super admin.",
@@ -201,7 +207,7 @@ let OrgSettingsOperations = class OrgSettingsOperations {
201
207
  : ""}`,
202
208
  };
203
209
  },
204
- run: async (input, ctx) => {
210
+ run: (input, ctx) => retentionResult(async () => {
205
211
  const settings = await this.settings.update(ctx.orgId, input, ctx.actorAccountId, undefined, viaAgent("org-settings.update", ctx),
206
212
  // a person widens the device sandbox settings, never an agent
207
213
  { onlyNarrows: true });
@@ -213,7 +219,8 @@ let OrgSettingsOperations = class OrgSettingsOperations {
213
219
  effectiveNetwork: this.settings.effectiveNetwork(settings),
214
220
  ...(note !== undefined && { note }),
215
221
  };
216
- },
222
+ }),
223
+ handoff: (_input, result) => retentionHandoff(result, "/settings/organization"),
217
224
  }),
218
225
  ]);
219
226
  }
@@ -19,6 +19,7 @@ import { AccountsService } from "../../identity/accounts.js";
19
19
  import { DEPLOYMENT_SETTINGS_PATCH, SettingsService } from "../../identity/settings.js";
20
20
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
21
21
  import { KernelDb } from "../../infra/database/kernel-db.js";
22
+ import { MemberBudgetBody } from "../../models/budget-policy.js";
22
23
  import { InvitationsService } from "../../orgs/invitations.service.js";
23
24
  import { MembersService } from "../../orgs/members.service.js";
24
25
  import { OrgNetworkAllowances } from "../../orgs/network-allowances.service.js";
@@ -280,6 +281,9 @@ let OrgsOperations = class OrgsOperations {
280
281
  "externalSharing",
281
282
  "shareMaxExpiryDays",
282
283
  "htmlRenderCdnAllowlist",
284
+ "modelBudgets",
285
+ "retention",
286
+ "confirmRetentionShortening",
283
287
  "promptSuggestions",
284
288
  ],
285
289
  extras: ["orgId", "runConcurrency", "sandbox", "subagents"],
@@ -604,6 +608,30 @@ let OrgsOperations = class OrgsOperations {
604
608
  return { id: input.invitationId, revoked: true };
605
609
  },
606
610
  }),
611
+ defineOperation({
612
+ id: "orgs.member-model-budget",
613
+ description: "Read one member's configured and effective monthly model budget in this organization.",
614
+ input: MemberParams.strict(),
615
+ example: { accountId: "00000000-0000-4000-8000-000000000000" },
616
+ authz: { orgAction: "org.members.manage" },
617
+ mirrors: ["GET /api/v1/orgs/:orgId/members/:accountId/model-budget"],
618
+ confirm: "read",
619
+ run: (i, ctx) => this.members.modelBudget(ctx.orgId, i.accountId),
620
+ }),
621
+ defineOperation({
622
+ id: "orgs.set-member-model-budget",
623
+ description: "Set one member's monthly token and spend budget. Supply null to inherit the organization default. An omitted constraint inherits its default.",
624
+ input: MemberParams.extend(MemberBudgetBody.shape).strict(),
625
+ example: { accountId: "00000000-0000-4000-8000-000000000000", budget: { tokens: 1000 } },
626
+ authz: { orgAction: "org.members.manage" },
627
+ mirrors: ["PATCH /api/v1/orgs/:orgId/members/:accountId/model-budget"],
628
+ confirm: "org",
629
+ summary: (i) => ({
630
+ en: `Change the monthly model budget for ${i.accountId}`,
631
+ zh: `修改成员 ${i.accountId} 的每月模型预算`,
632
+ }),
633
+ run: (i, ctx) => this.members.setModelBudget(ctx.orgId, i.accountId, i.budget, ctx.actorAccountId, undefined, viaAgent("orgs.set-member-model-budget", ctx)),
634
+ }),
607
635
  defineOperation({
608
636
  id: "orgs.set-member-role",
609
637
  description: "Change a member's role in this conversation's org (org admins): guest, member or admin, never above your own role. Never offered: changing your own role, changing an owner's role or making anyone an owner (an owner does that on the web).",
@@ -0,0 +1,16 @@
1
+ export declare function retentionResult<T>(write: () => Promise<T>): Promise<T | {
2
+ applied: boolean;
3
+ code: "retention.confirmation_required";
4
+ message: string;
5
+ }>;
6
+ export declare function retentionHandoff(result: unknown, url: string): {
7
+ kind: "handoff";
8
+ title: {
9
+ en: string;
10
+ zh: string;
11
+ };
12
+ target: {
13
+ type: "link";
14
+ url: string;
15
+ };
16
+ } | null;
@@ -0,0 +1,21 @@
1
+ import { ApiError } from "../../errors.js";
2
+ export async function retentionResult(write) {
3
+ try {
4
+ return await write();
5
+ }
6
+ catch (error) {
7
+ if (error instanceof ApiError && error.code === "retention.confirmation_required") {
8
+ return { applied: false, code: error.code, message: error.message };
9
+ }
10
+ throw error;
11
+ }
12
+ }
13
+ export function retentionHandoff(result, url) {
14
+ return result?.code === "retention.confirmation_required"
15
+ ? {
16
+ kind: "handoff",
17
+ title: { en: "Review shorter retention periods", zh: "确认缩短保留期限" },
18
+ target: { type: "link", url },
19
+ }
20
+ : null;
21
+ }
@@ -0,0 +1,21 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import type { OutboxService } from "../infra/outbox/outbox.service.js";
3
+ export declare const RETENTION_JOB = "retention-batch";
4
+ export declare const retentionJobId: (id: string, generation: number) => string;
5
+ export declare function enqueueRetention(outbox: Pick<OutboxService, "add">, row: {
6
+ id: string;
7
+ generation: number;
8
+ org_id: string | null;
9
+ }, runAt?: Date): Promise<boolean>;
10
+ /** Creates progress and owes its first delivery in the deletion transaction. */
11
+ export declare function oweConversationPurge(db: KernelSchemaDb, outbox: Pick<OutboxService, "add">, { orgId, conversationId }: {
12
+ orgId: string;
13
+ conversationId: string;
14
+ }): Promise<void>;
15
+ /** Records the earliest loss of each kind in the same transaction that removes detail. */
16
+ export declare function recordRetentionLoss(db: KernelSchemaDb, orgId: string, lost: {
17
+ usage?: Date;
18
+ runs?: Date;
19
+ usageThrough?: Date;
20
+ runsThrough?: Date;
21
+ }): Promise<void>;
@@ -0,0 +1,48 @@
1
+ import { sql } from "kysely";
2
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
3
+ export const RETENTION_JOB = "retention-batch";
4
+ export const retentionJobId = (id, generation) => `retention-${id}-${generation}`;
5
+ export function enqueueRetention(outbox, row, runAt) {
6
+ return outbox.add({
7
+ name: RETENTION_JOB,
8
+ queue: MAINTENANCE_QUEUE_NAME,
9
+ jobId: retentionJobId(row.id, row.generation),
10
+ data: { workId: row.id },
11
+ ...(row.org_id === null ? {} : { orgId: row.org_id }),
12
+ ...(runAt && { runAt }),
13
+ });
14
+ }
15
+ /** Creates progress and owes its first delivery in the deletion transaction. */
16
+ export async function oweConversationPurge(db, outbox, { orgId, conversationId }) {
17
+ const row = await db
18
+ .insertInto("retention_work")
19
+ .values({
20
+ org_id: orgId,
21
+ kind: "purge",
22
+ target: conversationId,
23
+ })
24
+ .onConflict((oc) => oc.columns(["kind", "target"]).doNothing())
25
+ .returning(["id", "org_id", "generation"])
26
+ .executeTakeFirst();
27
+ if (row)
28
+ await enqueueRetention(outbox, row);
29
+ }
30
+ /** Records the earliest loss of each kind in the same transaction that removes detail. */
31
+ export async function recordRetentionLoss(db, orgId, lost) {
32
+ await db
33
+ .insertInto("retention_coverage")
34
+ .values({
35
+ org_id: orgId,
36
+ usage_incomplete_since: lost.usage ?? null,
37
+ runs_incomplete_since: lost.runs ?? null,
38
+ runs_incomplete_through: lost.runsThrough ?? lost.runs ?? null,
39
+ usage_incomplete_through: lost.usageThrough ?? lost.usage ?? null,
40
+ })
41
+ .onConflict((oc) => oc.column("org_id").doUpdateSet({
42
+ usage_incomplete_since: sql `least(retention_coverage.usage_incomplete_since, excluded.usage_incomplete_since)`,
43
+ usage_incomplete_through: sql `greatest(retention_coverage.usage_incomplete_through, excluded.usage_incomplete_through)`,
44
+ runs_incomplete_through: sql `greatest(retention_coverage.runs_incomplete_through, excluded.runs_incomplete_through)`,
45
+ runs_incomplete_since: sql `least(retention_coverage.runs_incomplete_since, excluded.runs_incomplete_since)`,
46
+ }))
47
+ .execute();
48
+ }
@@ -0,0 +1,70 @@
1
+ import { z } from "zod";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ export declare const OrgRetentionSchema: z.ZodObject<{
4
+ conversationDays: z.ZodNullable<z.ZodNumber>;
5
+ auditDays: z.ZodNullable<z.ZodNumber>;
6
+ usageDays: z.ZodNullable<z.ZodNumber>;
7
+ }, z.core.$strict>;
8
+ export declare const PlatformRetentionSchema: z.ZodObject<{
9
+ conversationDays: z.ZodNullable<z.ZodNumber>;
10
+ auditDays: z.ZodNullable<z.ZodNumber>;
11
+ usageDays: z.ZodNullable<z.ZodNumber>;
12
+ platformAuditDays: z.ZodNullable<z.ZodNumber>;
13
+ }, z.core.$strict>;
14
+ export declare const OFF_RETENTION: {
15
+ conversationDays: null;
16
+ auditDays: null;
17
+ usageDays: null;
18
+ platformAuditDays: null;
19
+ };
20
+ export type OrgRetention = z.infer<typeof OrgRetentionSchema>;
21
+ type OrgRetentionPatch = {
22
+ [K in keyof OrgRetention]?: number | null | undefined;
23
+ };
24
+ type PolicyLock = "share" | "update";
25
+ /** An ordered transaction prelude locks the singleton before conversation rows. An absent
26
+ * row cannot be locked in PostgreSQL, so only its first locking reader or writer creates it. */
27
+ export declare function platformRetentionRow(db: KernelSchemaDb, lock?: PolicyLock): Promise<{
28
+ value: unknown;
29
+ } | undefined>;
30
+ export declare const StoredPlatformRetentionSchema: z.ZodPipe<z.ZodObject<{
31
+ conversationDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
32
+ auditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
33
+ usageDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
34
+ platformAuditDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
35
+ }, z.core.$strict>, z.ZodTransform<{
36
+ conversationDays: number | null;
37
+ auditDays: number | null;
38
+ usageDays: number | null;
39
+ platformAuditDays: number | null;
40
+ }, {
41
+ conversationDays?: number | null | undefined;
42
+ auditDays?: number | null | undefined;
43
+ usageDays?: number | null | undefined;
44
+ platformAuditDays?: number | null | undefined;
45
+ }>>;
46
+ export declare function readPlatformRetention(db: KernelSchemaDb, lock?: boolean): Promise<{
47
+ conversationDays: number | null;
48
+ auditDays: number | null;
49
+ usageDays: number | null;
50
+ platformAuditDays: number | null;
51
+ }>;
52
+ export declare function resolveRetention(platform: OrgRetention, override?: OrgRetentionPatch): OrgRetention;
53
+ export declare function readOrgRetention(db: KernelSchemaDb, orgId: string, opts?: {
54
+ lock?: boolean;
55
+ }): Promise<OrgRetention>;
56
+ export declare function mergeOrgRetention(platform: OrgRetention, before: OrgRetentionPatch | undefined, patch: OrgRetentionPatch): {
57
+ conversationDays?: number | null | undefined;
58
+ auditDays?: number | null | undefined;
59
+ usageDays?: number | null | undefined;
60
+ };
61
+ export declare function confirmRetentionChange<T extends OrgRetention>(before: T, after: T, confirmed: boolean, repairingPlatform?: boolean): {
62
+ retentionShortening?: never;
63
+ } | {
64
+ retentionShortening: {
65
+ before: T;
66
+ after: T;
67
+ repairedPlatformPolicy?: boolean;
68
+ };
69
+ };
70
+ export {};
@@ -0,0 +1,103 @@
1
+ import { z } from "zod";
2
+ import { ApiError } from "../errors.js";
3
+ // Keep cutoffs representable by both JavaScript Date and PostgreSQL timestamptz.
4
+ const days = z.number().int().min(1).max(2_000_000).nullable();
5
+ export const OrgRetentionSchema = z.strictObject({
6
+ conversationDays: days,
7
+ auditDays: days,
8
+ usageDays: days,
9
+ });
10
+ export const PlatformRetentionSchema = OrgRetentionSchema.extend({ platformAuditDays: days });
11
+ export const OFF_RETENTION = {
12
+ conversationDays: null,
13
+ auditDays: null,
14
+ usageDays: null,
15
+ platformAuditDays: null,
16
+ };
17
+ const keys = OrgRetentionSchema.keyof().options;
18
+ /** An ordered transaction prelude locks the singleton before conversation rows. An absent
19
+ * row cannot be locked in PostgreSQL, so only its first locking reader or writer creates it. */
20
+ export async function platformRetentionRow(db, lock) {
21
+ let query = db.selectFrom("deployment_settings").select("value").where("key", "=", "retention");
22
+ if (lock === "share")
23
+ query = query.forShare();
24
+ if (lock === "update")
25
+ query = query.forUpdate();
26
+ const row = await query.executeTakeFirst();
27
+ if (row || !lock)
28
+ return row;
29
+ await db
30
+ .insertInto("deployment_settings")
31
+ .values({ key: "retention", value: JSON.stringify(OFF_RETENTION) })
32
+ .onConflict((oc) => oc.column("key").doNothing())
33
+ .execute();
34
+ return query.executeTakeFirstOrThrow();
35
+ }
36
+ export const StoredPlatformRetentionSchema = PlatformRetentionSchema.partial().transform((stored) => ({
37
+ conversationDays: stored.conversationDays ?? null,
38
+ auditDays: stored.auditDays ?? null,
39
+ usageDays: stored.usageDays ?? null,
40
+ platformAuditDays: stored.platformAuditDays ?? null,
41
+ }));
42
+ export async function readPlatformRetention(db, lock = false) {
43
+ const row = await platformRetentionRow(db, lock ? "share" : undefined);
44
+ return StoredPlatformRetentionSchema.parse(row === undefined ? {} : row.value);
45
+ }
46
+ export function resolveRetention(platform, override) {
47
+ const { conversationDays, auditDays, usageDays } = platform;
48
+ const result = { conversationDays, auditDays, usageDays };
49
+ for (const key of keys) {
50
+ const value = override?.[key];
51
+ if (value != null)
52
+ result[key] = Math.min(value, platform[key] ?? Infinity);
53
+ }
54
+ return result;
55
+ }
56
+ export async function readOrgRetention(db, orgId, opts = {}) {
57
+ let query = db.selectFrom("orgs").select("settings").where("id", "=", orgId);
58
+ if (opts.lock)
59
+ query = query.forShare();
60
+ const row = await query.executeTakeFirstOrThrow();
61
+ const platform = await readPlatformRetention(db, opts.lock);
62
+ const { retention } = z
63
+ .object({ retention: OrgRetentionSchema.partial().optional() })
64
+ .parse(row.settings);
65
+ return resolveRetention(platform, retention);
66
+ }
67
+ export function mergeOrgRetention(platform, before, patch) {
68
+ const result = { ...before };
69
+ for (const key of keys) {
70
+ const value = patch[key];
71
+ if (value === undefined)
72
+ continue;
73
+ if (value === null)
74
+ delete result[key];
75
+ else {
76
+ const ceiling = platform[key];
77
+ if (ceiling !== null && value > ceiling)
78
+ throw new ApiError("validation_failed", `Retention ${key} may be at most ${ceiling} days under the platform policy.`);
79
+ result[key] = value;
80
+ }
81
+ }
82
+ return result;
83
+ }
84
+ export function confirmRetentionChange(before, after, confirmed, repairingPlatform = false) {
85
+ const shortened = Object.keys(before).some((key) => {
86
+ const a = before[key], b = after[key];
87
+ return typeof b === "number" && (a === null || (typeof a === "number" && b < a));
88
+ });
89
+ // Even a repair to all-null platform defaults resumes previously blocked explicit org policies.
90
+ if (!shortened && !repairingPlatform)
91
+ return {};
92
+ if (!confirmed)
93
+ throw new ApiError("retention.confirmation_required", repairingPlatform
94
+ ? "Confirm this platform retention repair in web settings. Future sweeps will resume existing organization retention policies, expire eligible conversations and permanently delete eligible audit or usage details."
95
+ : "Confirm this shorter retention period in web settings. Future sweeps will expire eligible conversations and permanently delete eligible audit or usage details.");
96
+ return {
97
+ retentionShortening: {
98
+ before,
99
+ after,
100
+ ...(repairingPlatform && { repairedPlatformPolicy: true }),
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,17 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import { type RetentionReportObligations } from "./report-obligations.js";
3
+ export declare const PURGE_BATCH_SIZE = 128;
4
+ type Target = {
5
+ orgId: string;
6
+ conversationId: string;
7
+ };
8
+ type Preparation = {
9
+ leaf: string;
10
+ checked: readonly string[];
11
+ clear: boolean;
12
+ };
13
+ /** Check the bounded Redis obligations before opening the write transaction. */
14
+ export declare function prepareConversationBatch(db: KernelSchemaDb, target: Target, reports: Pick<RetentionReportObligations, "clear">): Promise<Preparation | undefined>;
15
+ /** One slice under the worker's progress and root row locks. */
16
+ export declare function purgeConversationBatch(db: KernelSchemaDb, target: Target, prepared: Preparation | undefined): Promise<"more" | "done" | "blocked">;
17
+ export {};