@opengeni/worker-bundle 0.16.21 → 0.17.2

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 (180) hide show
  1. package/dist/activities/agent-turn.d.ts +145 -32
  2. package/dist/activities/api-integrations.d.ts +21 -0
  3. package/dist/activities/codemode-dispatcher.d.ts +35 -0
  4. package/dist/activities/codemode-token-renewal.d.ts +23 -0
  5. package/dist/activities/codex-capacity.d.ts +5 -5
  6. package/dist/activities/codex-image-generation.d.ts +21 -0
  7. package/dist/activities/context-compaction.d.ts +3 -0
  8. package/dist/activities/documents.d.ts +3 -2
  9. package/dist/activities/environment.d.ts +11 -7
  10. package/dist/activities/expiring-material-renewal.d.ts +5 -3
  11. package/dist/activities/file-upload-reaper.d.ts +7 -2
  12. package/dist/activities/gateway-image-generation.d.ts +39 -0
  13. package/dist/activities/gateway-video-generation.d.ts +53 -0
  14. package/dist/activities/generated-images.d.ts +112 -0
  15. package/dist/activities/git-credential-renewal.d.ts +2 -2
  16. package/dist/activities/goals.d.ts +2 -2
  17. package/dist/activities/google-drive-changes.d.ts +99 -0
  18. package/dist/activities/image-generation-operation.d.ts +74 -0
  19. package/dist/activities/image-generation-references.d.ts +25 -0
  20. package/dist/activities/knowledge-source-sync-driver.d.ts +23 -0
  21. package/dist/activities/knowledge-source-sync.d.ts +75 -0
  22. package/dist/activities/packs.d.ts +13 -26
  23. package/dist/activities/parent-wake.d.ts +1 -1
  24. package/dist/activities/retained-screenshot-reaper.d.ts +32 -0
  25. package/dist/activities/retained-screenshots.d.ts +129 -0
  26. package/dist/activities/rig-verification.d.ts +82 -5
  27. package/dist/activities/run-credential-renewal.d.ts +2 -2
  28. package/dist/activities/run-input.d.ts +5 -1
  29. package/dist/activities/sandbox-images.d.ts +14 -0
  30. package/dist/activities/sandbox-lease.d.ts +47 -9
  31. package/dist/activities/scheduled-tasks.d.ts +2 -2
  32. package/dist/activities/session-state.d.ts +4 -4
  33. package/dist/activities/streaming.d.ts +1 -1
  34. package/dist/activities/types.d.ts +71 -5
  35. package/dist/activities/video-generation-admission.d.ts +38 -0
  36. package/dist/activities/video-generation-credential.d.ts +7 -0
  37. package/dist/activities/video-generation-reconciliation.d.ts +13 -0
  38. package/dist/activities/video-media-validation.d.ts +34 -0
  39. package/dist/activities/video-output-retention.d.ts +36 -0
  40. package/dist/activities/video-reference-staging.d.ts +49 -0
  41. package/dist/activities/workflow-wake.d.ts +2 -2
  42. package/dist/activities/workspace-capture.d.ts +11 -1
  43. package/dist/activities-control-44KBWLSM.js +6885 -0
  44. package/dist/activities-control-44KBWLSM.js.map +1 -0
  45. package/dist/activities-control.d.ts +289 -0
  46. package/dist/activities-turn-K4CEDEGJ.js +14675 -0
  47. package/dist/activities-turn-K4CEDEGJ.js.map +1 -0
  48. package/dist/activities-turn.d.ts +17 -0
  49. package/dist/activities.d.ts +130 -147
  50. package/dist/activity-services.d.ts +10 -0
  51. package/dist/artifact-materializer-entry.d.ts +6 -0
  52. package/dist/artifact-materializer-entry.js +2662 -0
  53. package/dist/artifact-materializer-entry.js.map +1 -0
  54. package/dist/artifact-outbox-entry.d.ts +2 -0
  55. package/dist/artifact-outbox-entry.js +681 -0
  56. package/dist/artifact-outbox-entry.js.map +1 -0
  57. package/dist/chunk-E3RI3I33.js +828 -0
  58. package/dist/chunk-E3RI3I33.js.map +1 -0
  59. package/dist/chunk-GRFQTTSQ.js +448 -0
  60. package/dist/chunk-GRFQTTSQ.js.map +1 -0
  61. package/dist/chunk-KKCRGAGZ.js +3091 -0
  62. package/dist/chunk-KKCRGAGZ.js.map +1 -0
  63. package/dist/{chunk-BJUW5LCM.js → chunk-RAMNYSAW.js} +15 -12
  64. package/dist/chunk-RAMNYSAW.js.map +1 -0
  65. package/dist/concurrency.d.ts +108 -5
  66. package/dist/editable-artifact-hint-broker.d.ts +49 -0
  67. package/dist/editable-artifact-materializer-launcher.d.ts +49 -0
  68. package/dist/editable-artifact-materializer-service.d.ts +108 -0
  69. package/dist/editable-artifact-materializer-storage.d.ts +12 -0
  70. package/dist/editable-artifact-materializer-subprocess.d.ts +50 -0
  71. package/dist/editable-artifact-materializer.d.ts +262 -0
  72. package/dist/editable-artifact-outbox-dispatcher.d.ts +44 -0
  73. package/dist/editable-artifact-outbox-service.d.ts +70 -0
  74. package/dist/host-export.d.ts +1 -1
  75. package/dist/host-export.js +1 -1
  76. package/dist/index.d.ts +176 -10
  77. package/dist/index.js +675 -16460
  78. package/dist/index.js.map +1 -1
  79. package/dist/memory-pressure-guard.d.ts +57 -0
  80. package/dist/model-checkpoint-memory-collector.d.ts +22 -0
  81. package/dist/observability-metrics.d.ts +33 -0
  82. package/dist/sandbox-reaper-contract.d.ts +40 -0
  83. package/dist/sandbox-reaper-timeout.d.ts +14 -0
  84. package/dist/sandbox-resume.d.ts +40 -7
  85. package/dist/sandbox-routing.d.ts +13 -6
  86. package/dist/worker-service-lifecycle.d.ts +6 -2
  87. package/dist/workflow-bundle.js +1044 -363
  88. package/dist/workflows/activities.d.ts +7 -1
  89. package/dist/workflows/document-index.d.ts +1 -1
  90. package/dist/workflows/knowledge-source-sync.d.ts +13 -0
  91. package/dist/workflows/rig-verification.d.ts +1 -1
  92. package/dist/workflows/sandbox-reaper.d.ts +8 -0
  93. package/dist/workflows/scheduled-tasks.d.ts +1 -1
  94. package/dist/workflows/session.d.ts +2 -2
  95. package/dist/workflows/video-generation.d.ts +10 -0
  96. package/dist/workflows/workflow-wake.d.ts +1 -1
  97. package/dist/workflows.d.ts +9 -7
  98. package/package.json +34 -15
  99. package/src/activities/agent-turn.ts +1905 -559
  100. package/src/activities/api-integrations.ts +138 -0
  101. package/src/activities/codemode-dispatcher.ts +335 -0
  102. package/src/activities/codemode-token-renewal.ts +64 -0
  103. package/src/activities/codex-capacity.ts +16 -7
  104. package/src/activities/codex-image-generation.ts +56 -0
  105. package/src/activities/codex-rotation.ts +19 -5
  106. package/src/activities/context-compaction.ts +47 -6
  107. package/src/activities/documents.ts +14 -4
  108. package/src/activities/environment.ts +52 -60
  109. package/src/activities/expiring-material-renewal.ts +16 -7
  110. package/src/activities/file-upload-reaper.ts +34 -3
  111. package/src/activities/gateway-image-generation.ts +146 -0
  112. package/src/activities/gateway-video-generation.ts +298 -0
  113. package/src/activities/generated-images.ts +860 -0
  114. package/src/activities/git-credential-renewal.ts +3 -3
  115. package/src/activities/goals.ts +6 -2
  116. package/src/activities/google-drive-changes.ts +454 -0
  117. package/src/activities/image-generation-operation.ts +333 -0
  118. package/src/activities/image-generation-references.ts +118 -0
  119. package/src/activities/knowledge-source-sync-driver.ts +27 -0
  120. package/src/activities/knowledge-source-sync.ts +2840 -0
  121. package/src/activities/mcp-credentials.ts +1 -0
  122. package/src/activities/packs.ts +55 -55
  123. package/src/activities/recording.ts +4 -5
  124. package/src/activities/retained-screenshot-reaper.ts +202 -0
  125. package/src/activities/retained-screenshots.ts +1317 -0
  126. package/src/activities/rig-verification.ts +567 -77
  127. package/src/activities/run-credential-renewal.ts +9 -2
  128. package/src/activities/run-input.ts +40 -10
  129. package/src/activities/sandbox-images.ts +167 -0
  130. package/src/activities/sandbox-lease.ts +1065 -483
  131. package/src/activities/scheduled-tasks.ts +96 -7
  132. package/src/activities/session-state.ts +4 -4
  133. package/src/activities/streaming.ts +42 -3
  134. package/src/activities/types.ts +87 -5
  135. package/src/activities/video-generation-admission.ts +270 -0
  136. package/src/activities/video-generation-credential.ts +34 -0
  137. package/src/activities/video-generation-reconciliation.ts +578 -0
  138. package/src/activities/video-media-validation.ts +326 -0
  139. package/src/activities/video-output-retention.ts +314 -0
  140. package/src/activities/video-reference-staging.ts +263 -0
  141. package/src/activities/workflow-wake.ts +2 -2
  142. package/src/activities/workspace-capture.ts +77 -13
  143. package/src/activities-control.ts +54 -0
  144. package/src/activities-turn.ts +40 -0
  145. package/src/activities.ts +50 -118
  146. package/src/activity-services.ts +62 -0
  147. package/src/artifact-materializer-entry.ts +35 -0
  148. package/src/artifact-outbox-entry.ts +29 -0
  149. package/src/concurrency.ts +484 -6
  150. package/src/editable-artifact-hint-broker.ts +235 -0
  151. package/src/editable-artifact-materializer-launcher.ts +515 -0
  152. package/src/editable-artifact-materializer-service.ts +787 -0
  153. package/src/editable-artifact-materializer-storage.ts +413 -0
  154. package/src/editable-artifact-materializer-subprocess.ts +956 -0
  155. package/src/editable-artifact-materializer.ts +1289 -0
  156. package/src/editable-artifact-outbox-dispatcher.ts +244 -0
  157. package/src/editable-artifact-outbox-service.ts +438 -0
  158. package/src/host-export-pump.ts +28 -11
  159. package/src/http.ts +3 -6
  160. package/src/index.ts +277 -72
  161. package/src/memory-pressure-guard.ts +489 -0
  162. package/src/model-checkpoint-memory-collector.ts +116 -0
  163. package/src/observability-metrics.ts +202 -7
  164. package/src/sandbox-reaper-contract.ts +73 -0
  165. package/src/sandbox-reaper-timeout.ts +79 -0
  166. package/src/sandbox-resume.ts +331 -157
  167. package/src/sandbox-routing.ts +49 -39
  168. package/src/worker-service-lifecycle.ts +82 -12
  169. package/src/workflows/activities.ts +30 -0
  170. package/src/workflows/file-upload-reaper.ts +6 -1
  171. package/src/workflows/knowledge-source-sync.ts +83 -0
  172. package/src/workflows/sandbox-reaper.ts +183 -21
  173. package/src/workflows/scheduled-tasks.ts +42 -6
  174. package/src/workflows/video-generation.ts +36 -0
  175. package/src/workflows.ts +17 -1
  176. package/dist/activities/redaction.d.ts +0 -1
  177. package/dist/activities/toolspace-token-renewal.d.ts +0 -23
  178. package/dist/chunk-BJUW5LCM.js.map +0 -1
  179. package/src/activities/redaction.ts +0 -9
  180. package/src/activities/toolspace-token-renewal.ts +0 -57
@@ -34,5 +34,6 @@ export function connectionTokenResolverForTurn(input: {
34
34
  initiator: input.turn.initiator,
35
35
  initiatorContext: input.turn.initiatorContext,
36
36
  surface: "model",
37
+ allowOfficialGmailRestDestination: input.settings.gmailRestAdapterEnabled,
37
38
  });
38
39
  }
@@ -1,23 +1,30 @@
1
- import type { Settings } from "@opengeni/config";
2
- import { CapabilityPack } from "@opengeni/contracts";
1
+ import { CapabilityPack, type PackInstallation } from "@opengeni/contracts";
3
2
  import {
4
3
  getWorkspace,
5
4
  getWorkspacePack,
5
+ listInstalledPortableSkills,
6
6
  listCapabilityInstallations,
7
7
  listPackInstallations,
8
8
  type Database,
9
9
  } from "@opengeni/db";
10
10
  import {
11
+ buildPortableSkillArtifact,
11
12
  isSkillLibraryEntryId,
12
13
  loadSkillLibrarySkill,
13
14
  type EffectiveSkillSelection,
14
15
  type PackSkill,
15
16
  } from "@opengeni/runtime";
17
+ export {
18
+ resolveRigProviderImageSelection,
19
+ rigProviderImageSourceImage,
20
+ settingsWithPackSandboxImage,
21
+ settingsWithRigImage,
22
+ settingsWithRigProviderImage,
23
+ } from "./sandbox-images";
16
24
 
17
25
  /**
18
- * The pack-scoped runtime for a workspace: the sandbox image its sessions run
19
- * in (when an enabled pack declares one) and the pack skills that join the
20
- * sandbox skill index.
26
+ * Legacy pack-scoped runtime compatibility. V2 Pack installations own ordinary
27
+ * Skill components and select an explicit Rig; they contribute nothing here.
21
28
  */
22
29
  export type WorkspacePackRuntime = {
23
30
  sandboxImage: string | null;
@@ -45,11 +52,11 @@ type SkillLibraryInstallationMetadata = {
45
52
  };
46
53
 
47
54
  /**
48
- * Resolves the pack-scoped runtime from the workspace's active pack
49
- * installations. Only registered (manifest-backed) packs can contribute a
50
- * sandbox image or skills; built-in packs never declare either (enforced by a
51
- * test on the built-in catalog), so their installations are skipped here
52
- * without consulting the API's built-in pack list.
55
+ * Resolves only pre-V2 active Pack installations. A frozen manifest/digest is
56
+ * the protocol marker for V2: inline Skills were migrated into the ordinary
57
+ * Skill ledger and sandboxImage was resolved to selectedRigId during install,
58
+ * so reading either field directly here would duplicate ownership and silently
59
+ * override session compute.
53
60
  */
54
61
  export async function resolveWorkspacePackRuntime(
55
62
  db: Database,
@@ -62,6 +69,9 @@ export async function resolveWorkspacePackRuntime(
62
69
  }
63
70
  const packs: CapabilityPack[] = [];
64
71
  for (const installation of active) {
72
+ if (!packInstallationUsesLegacyRuntime(installation)) {
73
+ continue;
74
+ }
65
75
  const registration = await getWorkspacePack(db, workspaceId, installation.packId);
66
76
  if (!registration) {
67
77
  continue;
@@ -74,6 +84,12 @@ export async function resolveWorkspacePackRuntime(
74
84
  return workspacePackRuntimeFromPacks(packs);
75
85
  }
76
86
 
87
+ export function packInstallationUsesLegacyRuntime(
88
+ installation: Pick<PackInstallation, "manifestSnapshot" | "manifestDigest">,
89
+ ): boolean {
90
+ return installation.manifestSnapshot === null && installation.manifestDigest === null;
91
+ }
92
+
77
93
  /**
78
94
  * Resolves active immutable curated skills separately from pack skills. The
79
95
  * capability installation is the workspace selection boundary; it carries
@@ -139,6 +155,32 @@ export async function resolveWorkspaceSkillLibraryRuntime(
139
155
  reason: "enabled workspace capability installation",
140
156
  });
141
157
  }
158
+ const importedSkills = await listInstalledPortableSkills(db, workspaceId);
159
+ for (const imported of importedSkills) {
160
+ const artifact = buildPortableSkillArtifact(imported.files);
161
+ if (
162
+ artifact.name !== imported.name ||
163
+ artifact.description !== imported.description ||
164
+ artifact.contentSha256 !== imported.contentSha256
165
+ ) {
166
+ throw new Error(
167
+ `Imported Skill artifact verification failed for ${imported.capabilityId}; reinstall it from the pinned source`,
168
+ );
169
+ }
170
+ skillLibrarySkills.push({
171
+ name: artifact.name,
172
+ description: artifact.description,
173
+ files: artifact.files.map((file) => ({ path: file.path, content: file.content })),
174
+ });
175
+ skillLibrarySelections.push({
176
+ id: imported.capabilityId,
177
+ name: artifact.name,
178
+ source: "imported",
179
+ version: imported.sourceCommit,
180
+ contentSha256: artifact.contentSha256,
181
+ reason: `installed from ${imported.sourceUrl}`,
182
+ });
183
+ }
142
184
  return { skillLibrarySkills, skillLibrarySelections };
143
185
  }
144
186
 
@@ -164,10 +206,9 @@ function stringMetadata(value: unknown): string | null {
164
206
  }
165
207
 
166
208
  /**
167
- * Pure composition rule for enabled pack manifests. v1 keeps this small by
168
- * design: at most one enabled pack may declare a sandbox image (no image
169
- * layering or composition), and skill names must be unique across enabled
170
- * packs. Violations fail the turn with a plain error instead of guessing.
209
+ * Pure pre-V2 compatibility rule for enabled Pack manifests. At most one
210
+ * legacy Pack may declare a sandbox image, and legacy Skill names must be
211
+ * unique. V2 rows never reach this function through runtime resolution.
171
212
  */
172
213
  export function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): WorkspacePackRuntime {
173
214
  const imagePacks = packs.filter(
@@ -234,47 +275,6 @@ export async function resolveWorkspaceAgentInstructions(
234
275
  * the settings pass through untouched, so deployments without packs keep the
235
276
  * global OPENGENI_DOCKER_IMAGE / OPENGENI_MODAL_IMAGE_REF behavior exactly.
236
277
  */
237
- export function settingsWithPackSandboxImage(
238
- settings: Settings,
239
- sandboxImage: string | null,
240
- sandboxProviderImages: CapabilityPack["sandboxProviderImages"] | null = null,
241
- ): Settings {
242
- if (!sandboxImage) {
243
- return settings;
244
- }
245
- return {
246
- ...settings,
247
- dockerImage: sandboxImage,
248
- modalImageRef: sandboxImage,
249
- modalImageId: sandboxProviderImages?.modal?.imageId,
250
- };
251
- }
252
-
253
- /**
254
- * Applies the session's frozen rig-version image to run settings. Rig image is
255
- * the TOP of the image precedence chain (rig > pack > deployment default): when
256
- * the rig version pins an image it OVERRIDES both the deployment
257
- * dockerImage/modalImageRef AND any pack-declared sandboxImage. When the rig
258
- * pins no image (`null`), the settings pass through untouched so the pack /
259
- * deployment chain below still resolves exactly as today. Applied AFTER
260
- * settingsWithPackSandboxImage so it wins the collision; identical mechanics to
261
- * the pack equivalent (write both image fields so docker and modal agree).
262
- */
263
- export function settingsWithRigImage(settings: Settings, rigImage: string | null): Settings {
264
- if (!rigImage) {
265
- return settings;
266
- }
267
- return {
268
- ...settings,
269
- dockerImage: rigImage,
270
- modalImageRef: rigImage,
271
- // A rig image has no provider-native identity in the current rig contract.
272
- // Clear a lower-precedence pack/deployment ID so the rig cannot silently
273
- // run the wrong Modal image.
274
- modalImageId: undefined,
275
- };
276
- }
277
-
278
278
  /**
279
279
  * Layers the rig version's default variable sets BELOW the session's own set:
280
280
  * the session's values WIN on any key collision (explicit precedence). Both maps
@@ -270,11 +270,10 @@ export async function discardUnpublishedRecording(args: {
270
270
 
271
271
  export { DOWNLOAD_URL_TTL_SECONDS };
272
272
 
273
- // Agent/ffmpeg-controlled free text rides redact() like every payload, but we
274
- // also cap it here (defense in depth — a path/URL with creds shouldn't ride a
275
- // reason/detail field unbounded; the redactor scrubs known secret shapes).
273
+ // Recording diagnostics are canonical OpenGeni data. Preserve the exact text;
274
+ // transport-specific byte limits must reject or paginate rather than rewrite it.
276
275
  function scrubFreeText(value: string | null | undefined): string | null {
277
276
  if (value === null || value === undefined) return null;
278
- const trimmed = String(value).slice(0, 2_000);
279
- return trimmed.length === 0 ? null : trimmed;
277
+ const exact = String(value);
278
+ return exact.length === 0 ? null : exact;
280
279
  }
@@ -0,0 +1,202 @@
1
+ import type { FileAsset } from "@opengeni/contracts";
2
+ import {
3
+ claimRetainedScreenshotMaintenance,
4
+ completeRetainedScreenshotMaintenance,
5
+ promoteRetainedScreenshotMaintenanceCleanup,
6
+ type RetainedScreenshotMaintenanceClaim,
7
+ } from "@opengeni/db";
8
+ import type { ObjectHead, ObjectStorage } from "@opengeni/storage";
9
+ import type { ControlActivityServices } from "./types";
10
+
11
+ export const RETAINED_SCREENSHOT_PENDING_GRACE_MS = 15 * 60 * 1_000;
12
+ export const RETAINED_SCREENSHOT_CLAIM_TIMEOUT_MS = 10 * 60 * 1_000;
13
+ export const RETAINED_SCREENSHOT_MAINTENANCE_BATCH_SIZE = 100;
14
+
15
+ export type MaintainRetainedScreenshotsResult = {
16
+ claimed: number;
17
+ ready: number;
18
+ deleted: number;
19
+ failed: number;
20
+ retryable: number;
21
+ };
22
+
23
+ export type RetainedScreenshotMaintenanceActivityOptions = {
24
+ pendingGraceMs?: number;
25
+ claimTimeoutMs?: number;
26
+ batchSize?: number;
27
+ /** Provider seams used by deterministic unit tests. */
28
+ fileExists?: (storage: ObjectStorage, file: FileAsset) => Promise<boolean>;
29
+ headFile?: (storage: ObjectStorage, file: FileAsset) => Promise<ObjectHead>;
30
+ deleteObject?: (storage: ObjectStorage, key: string) => Promise<void>;
31
+ };
32
+
33
+ /**
34
+ * Reconcile interrupted screenshot writes and reap expired screenshot objects.
35
+ * Claims move rows out of the readable `ready`/writable `pending` states before
36
+ * provider access. Provider failures leave the durable claim reclaimable; DB
37
+ * completion happens only after exact metadata verification or an idempotent
38
+ * object delete.
39
+ */
40
+ export function createRetainedScreenshotMaintenanceActivities(
41
+ services: () => Promise<ControlActivityServices>,
42
+ options: RetainedScreenshotMaintenanceActivityOptions = {},
43
+ ) {
44
+ const pendingGraceMs = options.pendingGraceMs ?? RETAINED_SCREENSHOT_PENDING_GRACE_MS;
45
+ const claimTimeoutMs = options.claimTimeoutMs ?? RETAINED_SCREENSHOT_CLAIM_TIMEOUT_MS;
46
+ const batchSize = options.batchSize ?? RETAINED_SCREENSHOT_MAINTENANCE_BATCH_SIZE;
47
+ const fileExists = options.fileExists ?? ((storage, file) => storage.fileExists(file));
48
+ const headFile = options.headFile ?? ((storage, file) => storage.headFile(file));
49
+ const deleteObject = options.deleteObject ?? ((storage, key) => storage.deleteObject(key));
50
+
51
+ async function maintainRetainedScreenshots(): Promise<MaintainRetainedScreenshotsResult> {
52
+ const { db, objectStorage, observability } = await services();
53
+ if (!objectStorage) {
54
+ return { claimed: 0, ready: 0, deleted: 0, failed: 0, retryable: 0 };
55
+ }
56
+
57
+ const claims = await claimRetainedScreenshotMaintenance(db, {
58
+ pendingGraceMs,
59
+ claimTimeoutMs,
60
+ limit: batchSize,
61
+ });
62
+ const result: MaintainRetainedScreenshotsResult = {
63
+ claimed: claims.length,
64
+ ready: 0,
65
+ deleted: 0,
66
+ failed: 0,
67
+ retryable: 0,
68
+ };
69
+
70
+ for (const claim of claims) {
71
+ try {
72
+ if (claim.action === "reconcile") {
73
+ const outcome = await reconcileClaim(db, objectStorage, claim, {
74
+ fileExists,
75
+ headFile,
76
+ deleteObject,
77
+ });
78
+ if (outcome === "ready") {
79
+ result.ready += 1;
80
+ } else {
81
+ result.failed += 1;
82
+ }
83
+ continue;
84
+ }
85
+
86
+ await deleteObject(objectStorage, claim.objectKey);
87
+ const outcome = terminalDeleteOutcome(claim.cleanupReason);
88
+ const settled = await completeRetainedScreenshotMaintenance(db, {
89
+ accountId: claim.accountId,
90
+ workspaceId: claim.workspaceId,
91
+ artifactId: claim.artifactId,
92
+ claimId: claim.claimId,
93
+ outcome,
94
+ });
95
+ if (!settled) throw new Error("retained screenshot cleanup claim was superseded");
96
+ result.deleted += 1;
97
+ } catch (error) {
98
+ result.retryable += 1;
99
+ observability.warn("retained screenshot maintenance failed; claim remains reclaimable", {
100
+ workspaceId: claim.workspaceId,
101
+ sessionId: claim.sessionId,
102
+ artifactId: claim.artifactId,
103
+ action: claim.action,
104
+ error: error instanceof Error ? error.message : String(error),
105
+ });
106
+ }
107
+ }
108
+
109
+ if (claims.length > 0) {
110
+ observability.info("retained screenshot maintenance swept", result);
111
+ }
112
+ return result;
113
+ }
114
+
115
+ return { maintainRetainedScreenshots };
116
+ }
117
+
118
+ async function reconcileClaim(
119
+ db: Parameters<typeof completeRetainedScreenshotMaintenance>[0],
120
+ storage: ObjectStorage,
121
+ claim: RetainedScreenshotMaintenanceClaim,
122
+ provider: Required<
123
+ Pick<RetainedScreenshotMaintenanceActivityOptions, "fileExists" | "headFile" | "deleteObject">
124
+ >,
125
+ ): Promise<"ready" | "failed"> {
126
+ const observation = await observeClaimObject(storage, claim, provider);
127
+ if (observation === "matches") {
128
+ const settled = await completeRetainedScreenshotMaintenance(db, {
129
+ accountId: claim.accountId,
130
+ workspaceId: claim.workspaceId,
131
+ artifactId: claim.artifactId,
132
+ claimId: claim.claimId,
133
+ outcome: "ready",
134
+ });
135
+ if (!settled) throw new Error("retained screenshot reconcile claim was superseded");
136
+ return "ready";
137
+ }
138
+
139
+ // A mismatch/missing observation cannot authorize provider deletion while
140
+ // the artifact is still eligible for a concurrent ready settlement. Promote
141
+ // the exact claim first; a ready winner clears the claim and makes this stale.
142
+ const promoted = await promoteRetainedScreenshotMaintenanceCleanup(db, {
143
+ accountId: claim.accountId,
144
+ workspaceId: claim.workspaceId,
145
+ artifactId: claim.artifactId,
146
+ claimId: claim.claimId,
147
+ cleanupReason: "failed",
148
+ });
149
+ if (!promoted) throw new Error("retained screenshot reconcile claim was superseded");
150
+
151
+ // Deletes are idempotent. Calling it for an authoritative missing observation
152
+ // also closes a race with a late writer that began before cleanup ownership.
153
+ await provider.deleteObject(storage, claim.objectKey);
154
+ const settled = await completeRetainedScreenshotMaintenance(db, {
155
+ accountId: claim.accountId,
156
+ workspaceId: claim.workspaceId,
157
+ artifactId: claim.artifactId,
158
+ claimId: claim.claimId,
159
+ outcome: "failed",
160
+ });
161
+ if (!settled) throw new Error("retained screenshot reconcile claim was superseded");
162
+ return "failed";
163
+ }
164
+
165
+ async function observeClaimObject(
166
+ storage: ObjectStorage,
167
+ claim: RetainedScreenshotMaintenanceClaim,
168
+ provider: Required<Pick<RetainedScreenshotMaintenanceActivityOptions, "fileExists" | "headFile">>,
169
+ ): Promise<"matches" | "mismatch" | "missing"> {
170
+ const file = claimFile(storage, claim);
171
+ if (!(await provider.fileExists(storage, file))) return "missing";
172
+ const head = await provider.headFile(storage, file);
173
+ return head.ContentLength === claim.sizeBytes &&
174
+ head.ContentType === claim.mediaType &&
175
+ head.Metadata?.sha256 === claim.sha256
176
+ ? "matches"
177
+ : "mismatch";
178
+ }
179
+
180
+ function claimFile(storage: ObjectStorage, claim: RetainedScreenshotMaintenanceClaim): FileAsset {
181
+ const timestamp = new Date(0).toISOString();
182
+ return {
183
+ id: claim.artifactId,
184
+ workspaceId: claim.workspaceId,
185
+ status: "pending_upload",
186
+ filename: `computer-screenshot-${claim.artifactId}.png`,
187
+ safeFilename: `computer-screenshot-${claim.artifactId}.png`,
188
+ contentType: claim.mediaType,
189
+ sizeBytes: claim.sizeBytes,
190
+ sha256: claim.sha256,
191
+ bucket: storage.bucket,
192
+ objectKey: claim.objectKey,
193
+ createdAt: timestamp,
194
+ updatedAt: timestamp,
195
+ };
196
+ }
197
+
198
+ function terminalDeleteOutcome(reason: string | null): "failed" | "expired" | "deleted" {
199
+ if (reason === "expired") return "expired";
200
+ if (reason === "failed") return "failed";
201
+ return "deleted";
202
+ }