@opengeni/worker-bundle 0.20.1 → 0.20.3

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.
@@ -73,9 +73,11 @@ import {
73
73
  getRigName,
74
74
  getRigVersion,
75
75
  getSandbox,
76
+ getFilesForSubject as getFilesForSubject2,
76
77
  readActiveSandbox,
78
+ requireFileForSubject as requireFileForSubject3,
77
79
  setActiveSandbox,
78
- requireFile as requireFile3,
80
+ requireFile as requireFile2,
79
81
  getSessionEvent as getSessionEvent2,
80
82
  getSessionRootId as getSessionRootId2,
81
83
  getSessionGoal,
@@ -105,7 +107,7 @@ import {
105
107
  CODEX_CREDENTIAL_LEASE_TTL_MS,
106
108
  getCodexRotationSettings,
107
109
  getWorkspaceModelPolicy,
108
- getWorkspaceGrant,
110
+ getWorkspaceGrant as getWorkspaceGrant2,
109
111
  getWorkspace,
110
112
  listCodexAccountStatuses,
111
113
  fetchCodexUsageForAccount,
@@ -160,9 +162,9 @@ import {
160
162
  getOrCreatePreferenceRegistrySnapshot,
161
163
  getOrCreateWorkspaceInstructionPolicySnapshot,
162
164
  PreferenceRegistryInitiatorError,
163
- beginConnectorActionExecution,
164
- completeConnectorActionExecution,
165
- prepareConnectorActionApproval,
165
+ beginConnectorActionExecution as beginConnectorActionExecution2,
166
+ completeConnectorActionExecution as completeConnectorActionExecution2,
167
+ prepareConnectorActionApproval as prepareConnectorActionApproval2,
166
168
  withCodexAppsRequestAuthorization
167
169
  } from "@opengeni/db";
168
170
  import { appendAndPublishTurnEventsFenced as appendAndPublishTurnEventsFenced2, publishDurableSessionEvents as publishDurableSessionEvents2 } from "@opengeni/events";
@@ -219,6 +221,604 @@ import {
219
221
  stopRecording as stopRecordingOnBox2
220
222
  } from "@opengeni/runtime";
221
223
 
224
+ // src/activities/google-drive-publication.ts
225
+ import { createHash } from "crypto";
226
+ import { AttemptToolApprovalRequiredError } from "@opengeni/codemode";
227
+ import {
228
+ GOOGLE_DRIVE_FILE_SCOPE,
229
+ GOOGLE_DRIVE_FULL_SCOPE,
230
+ GOOGLE_DRIVE_PUBLICATION_CREATE_ACTION,
231
+ GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
232
+ GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
233
+ GOOGLE_DRIVE_PROVIDER_DOMAIN,
234
+ GoogleDriveConnectionMetadata,
235
+ GoogleDrivePublicationReceipt,
236
+ GoogleDrivePublicationToolInput,
237
+ googleDriveScopesAllowCapability
238
+ } from "@opengeni/contracts/google-drive";
239
+ import {
240
+ beginConnectorActionExecution,
241
+ completeConnectorActionExecution,
242
+ getConnectionMetadata,
243
+ getWorkspaceGrant,
244
+ prepareConnectorActionApproval,
245
+ requireFile
246
+ } from "@opengeni/db";
247
+ import {
248
+ readAuthorizedEditableArtifactMaterialization
249
+ } from "@opengeni/db/editable-artifact-durable-export";
250
+ import { readResponseJsonBounded, undiciFetch } from "@opengeni/network";
251
+ var DRIVE_API = "https://www.googleapis.com/drive/v3";
252
+ var DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3";
253
+ var DRIVE_FOLDER_MIME = "application/vnd.google-apps.folder";
254
+ var RESPONSE_MAX_BYTES = 256 * 1024;
255
+ var REQUEST_TIMEOUT_MS = 3e4;
256
+ var FIRST_PARTY_MCP_SUBJECT_ID = "worker:first-party-mcp";
257
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
258
+ var defaultPorts = {
259
+ getConnection: getConnectionMetadata,
260
+ getMembership: getWorkspaceGrant,
261
+ readMaterialization: readAuthorizedEditableArtifactMaterialization,
262
+ requireFile,
263
+ prepare: prepareConnectorActionApproval,
264
+ begin: beginConnectorActionExecution,
265
+ complete: completeConnectorActionExecution,
266
+ fetch: undiciFetch
267
+ };
268
+ async function resolveGoogleDrivePublicationTarget(db, workspaceId, delegations, ports = defaultPorts) {
269
+ const frozen = delegations.filter(
270
+ (delegation2) => delegation2.serverId === GOOGLE_DRIVE_PUBLICATION_SERVER_ID && delegation2.providerDomain.toLowerCase() === GOOGLE_DRIVE_PROVIDER_DOMAIN && delegation2.kind === "oauth2"
271
+ );
272
+ if (frozen.length !== 1) return null;
273
+ const delegation = frozen[0];
274
+ if (!await ports.getMembership(db, delegation.ownerSubjectId, workspaceId)) return null;
275
+ const connection = await ports.getConnection(
276
+ db,
277
+ workspaceId,
278
+ delegation.connectionId,
279
+ delegation.ownerSubjectId
280
+ );
281
+ if (!connection || connection.id !== delegation.connectionId || connection.subjectId !== delegation.ownerSubjectId || connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN || connection.kind !== "oauth2" || connection.status !== "active" || !googleDriveScopesAllowCapability(connection.grantedScopes, "publish_file")) {
282
+ return null;
283
+ }
284
+ const metadata = GoogleDriveConnectionMetadata.safeParse(connection.metadata);
285
+ if (!metadata.success || !metadata.data.outputDestination || metadata.data.lifecycle?.state === "paused" || metadata.data.lifecycle && metadata.data.lifecycle.state !== "active") {
286
+ return null;
287
+ }
288
+ return Object.freeze({
289
+ ownerSubjectId: delegation.ownerSubjectId,
290
+ connectionId: connection.id,
291
+ destination: metadata.data.outputDestination,
292
+ credentialScope: connection.grantedScopes.includes(GOOGLE_DRIVE_FILE_SCOPE) ? GOOGLE_DRIVE_FILE_SCOPE : GOOGLE_DRIVE_FULL_SCOPE
293
+ });
294
+ }
295
+ function googleDrivePublicationConnectorCall(target, rawRequest, approvalId) {
296
+ const request = GoogleDrivePublicationToolInput.parse(rawRequest);
297
+ return {
298
+ approvalId,
299
+ connectionId: target.connectionId,
300
+ serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
301
+ toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
302
+ arguments: {
303
+ action: GOOGLE_DRIVE_PUBLICATION_CREATE_ACTION,
304
+ destination: target.destination,
305
+ artifact: {
306
+ id: request.file.artifactId,
307
+ versionId: request.file.versionId,
308
+ title: request.title,
309
+ modality: request.modality,
310
+ sourceSha256: request.file.sha256
311
+ },
312
+ canonicalReceipt: { ...request.file },
313
+ idempotencyKeyDigest: createHash("sha256").update(request.idempotencyKey, "utf8").digest("hex")
314
+ }
315
+ };
316
+ }
317
+ function createGoogleDrivePublicationAttemptTool(input) {
318
+ const ports = input.ports ?? defaultPorts;
319
+ return {
320
+ identity: {
321
+ serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
322
+ toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME
323
+ },
324
+ modelName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
325
+ codemodePath: ["google_drive", "publish_file"],
326
+ title: "Publish artifact to Google Drive",
327
+ description: "Publish a completed editable-artifact Office export into the configured Google Drive output folder. First call editable_artifact_export and poll editable_artifact_export_status until it returns a file receipt, then pass that exact receipt here.",
328
+ inputSchema: {
329
+ type: "object",
330
+ properties: {
331
+ title: { type: "string", minLength: 1, maxLength: 512 },
332
+ modality: {
333
+ type: "string",
334
+ enum: ["document", "spreadsheet", "presentation"]
335
+ },
336
+ file: {
337
+ type: "object",
338
+ properties: {
339
+ fileId: { type: "string", format: "uuid" },
340
+ filename: { type: "string", minLength: 1, maxLength: 512 },
341
+ contentType: { type: "string", minLength: 1, maxLength: 256 },
342
+ sizeBytes: { type: "integer", minimum: 1 },
343
+ sha256: { type: "string", pattern: "^[0-9a-f]{64}$" },
344
+ artifactId: { type: "string", pattern: "^[0-9a-f]{32}$" },
345
+ versionId: { type: "string", pattern: "^[0-9a-f]{32}$" },
346
+ materializationJobId: { type: "string", pattern: "^[0-9a-f]{32}$" },
347
+ sourceHeadSequence: { type: "integer", minimum: 0 },
348
+ sourceStateHash: {
349
+ type: "string",
350
+ pattern: "^sha256:[0-9a-f]{64}$"
351
+ }
352
+ },
353
+ required: [
354
+ "fileId",
355
+ "filename",
356
+ "contentType",
357
+ "sizeBytes",
358
+ "sha256",
359
+ "artifactId",
360
+ "versionId",
361
+ "materializationJobId",
362
+ "sourceHeadSequence",
363
+ "sourceStateHash"
364
+ ],
365
+ additionalProperties: false
366
+ },
367
+ idempotencyKey: { type: "string", minLength: 1, maxLength: 200 }
368
+ },
369
+ required: ["title", "modality", "file", "idempotencyKey"],
370
+ additionalProperties: false
371
+ },
372
+ outputSchema: {
373
+ type: "object",
374
+ properties: {
375
+ connectionId: { type: "string", format: "uuid" },
376
+ providerFileId: { type: "string" },
377
+ webViewLink: { type: "string", format: "uri" },
378
+ mimeType: {
379
+ type: "string",
380
+ enum: [
381
+ "application/vnd.google-apps.document",
382
+ "application/vnd.google-apps.spreadsheet",
383
+ "application/vnd.google-apps.presentation"
384
+ ]
385
+ },
386
+ destination: {
387
+ type: "object",
388
+ properties: {
389
+ folderId: { type: "string" },
390
+ folderName: { type: "string" },
391
+ driveId: { type: ["string", "null"] },
392
+ location: { type: "string", enum: ["my_drive", "shared_drive"] },
393
+ selectedAt: { type: "string" }
394
+ },
395
+ required: ["folderId", "folderName", "driveId", "location", "selectedAt"],
396
+ additionalProperties: false
397
+ },
398
+ replayed: { type: "boolean" }
399
+ },
400
+ required: [
401
+ "connectionId",
402
+ "providerFileId",
403
+ "webViewLink",
404
+ "mimeType",
405
+ "destination",
406
+ "replayed"
407
+ ],
408
+ additionalProperties: false
409
+ },
410
+ annotations: {
411
+ title: "Publish artifact to Google Drive",
412
+ readOnlyHint: false,
413
+ destructiveHint: false,
414
+ idempotentHint: true,
415
+ openWorldHint: true
416
+ },
417
+ source: "mcp",
418
+ approval: "policy",
419
+ execute: async (raw, context) => {
420
+ const request = GoogleDrivePublicationToolInput.parse(raw);
421
+ const connectorCall = googleDrivePublicationConnectorCall(
422
+ input.target,
423
+ request,
424
+ context.operationId
425
+ );
426
+ let requestId = null;
427
+ if (context.caller.kind === "codemode") {
428
+ const admission = await ports.begin(input.db, input.identity, connectorCall);
429
+ if (!admission.allowed) {
430
+ throw new Error(`Google Drive publication was not executed: ${admission.reason}`);
431
+ }
432
+ if (!admission.managed) {
433
+ throw new Error("Google Drive publication has no explicit connector action policy");
434
+ }
435
+ requestId = admission.requestId;
436
+ }
437
+ try {
438
+ const receipt = await executeGoogleDrivePublication(
439
+ {
440
+ db: input.db,
441
+ objectStorage: input.objectStorage,
442
+ identity: input.identity,
443
+ subjectId: input.subjectId,
444
+ target: input.target,
445
+ request,
446
+ resolveCredential: input.resolveCredential,
447
+ ...context.signal ?? input.signal ? { signal: context.signal ?? input.signal } : {}
448
+ },
449
+ ports
450
+ );
451
+ if (requestId) {
452
+ await ports.complete(input.db, {
453
+ accountId: input.identity.accountId,
454
+ workspaceId: input.identity.workspaceId,
455
+ requestId,
456
+ attemptId: input.identity.attemptId,
457
+ outcome: "completed"
458
+ });
459
+ }
460
+ return {
461
+ content: [{ type: "text", text: JSON.stringify(receipt) }],
462
+ structuredContent: receipt
463
+ };
464
+ } catch (error) {
465
+ if (requestId) {
466
+ await ports.complete(input.db, {
467
+ accountId: input.identity.accountId,
468
+ workspaceId: input.identity.workspaceId,
469
+ requestId,
470
+ attemptId: input.identity.attemptId,
471
+ outcome: "uncertain"
472
+ });
473
+ }
474
+ throw error;
475
+ }
476
+ }
477
+ };
478
+ }
479
+ async function authorizeGoogleDrivePublicationAttempt(input) {
480
+ const request = GoogleDrivePublicationToolInput.parse(input.arguments);
481
+ const preparation = await (input.ports ?? defaultPorts).prepare(
482
+ input.db,
483
+ input.identity,
484
+ googleDrivePublicationConnectorCall(input.target, request, input.approvalId)
485
+ );
486
+ if (!preparation.managed) {
487
+ throw new Error("Google Drive publication has no explicit connector action policy");
488
+ }
489
+ if (preparation.decision === "ask") throw new AttemptToolApprovalRequiredError();
490
+ if (preparation.decision === "block") {
491
+ throw new Error("Google Drive publication is blocked by connector action policy");
492
+ }
493
+ }
494
+ async function executeGoogleDrivePublication(input, ports = defaultPorts) {
495
+ const request = GoogleDrivePublicationToolInput.parse(input.request);
496
+ const connection = await ports.getConnection(
497
+ input.db,
498
+ input.identity.workspaceId,
499
+ input.target.connectionId,
500
+ input.subjectId
501
+ );
502
+ if (!connection || connection.subjectId !== input.subjectId) {
503
+ throw new Error("Google Drive publication connection is unavailable");
504
+ }
505
+ assertPublicationConnection(input, connection);
506
+ const materialization = await ports.readMaterialization(input.db, {
507
+ scope: {
508
+ accountId: input.identity.accountId,
509
+ workspaceId: input.identity.workspaceId
510
+ },
511
+ artifactId: request.file.artifactId,
512
+ jobId: request.file.materializationJobId,
513
+ actor: {
514
+ kind: "agent",
515
+ subjectId: FIRST_PARTY_MCP_SUBJECT_ID,
516
+ replicaId: publicationActorReplicaId(input.identity),
517
+ sessionId: input.identity.sessionId,
518
+ turnId: input.identity.turnId,
519
+ attemptId: input.identity.attemptId,
520
+ generation: input.identity.executionGeneration
521
+ }
522
+ });
523
+ assertCanonicalMaterialization(input.identity, request, materialization);
524
+ const expected = expectedExportWorkspaceFile(input.identity.workspaceId, request);
525
+ if (request.file.fileId !== expected.fileId) {
526
+ throw new Error("Google Drive publication requires a canonical editable-artifact export file");
527
+ }
528
+ const sourceFile = await ports.requireFile(
529
+ input.db,
530
+ input.identity.workspaceId,
531
+ request.file.fileId
532
+ );
533
+ if (sourceFile.status !== "ready" || sourceFile.id !== expected.fileId || sourceFile.safeFilename !== expected.safeFilename || sourceFile.objectKey !== expected.objectKey || sourceFile.filename !== request.file.filename || sourceFile.contentType !== request.file.contentType || sourceFile.sizeBytes !== request.file.sizeBytes || sourceFile.sha256 !== request.file.sha256) {
534
+ throw new Error("Editable artifact export file differs from its canonical receipt");
535
+ }
536
+ const bytes = await input.objectStorage.getFileBytes(sourceFile);
537
+ if (bytes.byteLength !== request.file.sizeBytes || createHash("sha256").update(bytes).digest("hex") !== request.file.sha256) {
538
+ throw new Error("Editable artifact export bytes failed verification");
539
+ }
540
+ const credential = await input.resolveCredential({
541
+ workspaceId: input.identity.workspaceId,
542
+ subjectId: input.subjectId,
543
+ serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
544
+ toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
545
+ connectionRef: {
546
+ providerDomain: GOOGLE_DRIVE_PROVIDER_DOMAIN,
547
+ connectionId: input.target.connectionId,
548
+ kind: "oauth2",
549
+ subjectScope: "subject",
550
+ scopes: [input.target.credentialScope]
551
+ },
552
+ destinationUrl: `${DRIVE_UPLOAD_API}/files`,
553
+ forceRefresh: false
554
+ });
555
+ if (credential.status !== "ok" || credential.connectionId !== input.target.connectionId) {
556
+ throw new Error("Google Drive publication credential is unavailable");
557
+ }
558
+ const resolvedConnection = await ports.getConnection(
559
+ input.db,
560
+ input.identity.workspaceId,
561
+ input.target.connectionId,
562
+ input.subjectId
563
+ );
564
+ if (!resolvedConnection) {
565
+ throw new Error("Google Drive publication authority changed; retry on a new turn");
566
+ }
567
+ assertPublicationConnection(input, resolvedConnection);
568
+ return await publishToGoogleDrive({
569
+ workspaceId: input.identity.workspaceId,
570
+ connectionId: input.target.connectionId,
571
+ destination: input.target.destination,
572
+ request,
573
+ bytes,
574
+ headers: credential.headers,
575
+ fetchImpl: ports.fetch,
576
+ ...input.signal ? { signal: input.signal } : {}
577
+ });
578
+ }
579
+ function assertPublicationConnection(input, connection) {
580
+ const metadata = GoogleDriveConnectionMetadata.parse(connection.metadata);
581
+ const credentialScope = connection.grantedScopes.includes(GOOGLE_DRIVE_FILE_SCOPE) ? GOOGLE_DRIVE_FILE_SCOPE : GOOGLE_DRIVE_FULL_SCOPE;
582
+ if (input.subjectId !== input.target.ownerSubjectId || connection.id !== input.target.connectionId || connection.subjectId !== input.target.ownerSubjectId || connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN || connection.kind !== "oauth2" || connection.status !== "active" || metadata.lifecycle?.state === "paused" || metadata.lifecycle && metadata.lifecycle.state !== "active" || !googleDriveScopesAllowCapability(connection.grantedScopes, "publish_file") || credentialScope !== input.target.credentialScope || !metadata.outputDestination || !sameDestination(metadata.outputDestination, input.target.destination)) {
583
+ throw new Error("Google Drive publication authority changed; retry on a new turn");
584
+ }
585
+ }
586
+ function publicationActorReplicaId(identity) {
587
+ const value = createHash("sha256").update(
588
+ `google-drive-publication:${identity.sessionId}:${identity.turnId}:${identity.attemptId}:${identity.executionGeneration}`,
589
+ "utf8"
590
+ ).digest("hex").slice(0, 16);
591
+ return /^0+$/u.test(value) ? `1${value.slice(1)}` : value;
592
+ }
593
+ function assertCanonicalMaterialization(identity, request, job) {
594
+ const format = officeFormat(request.modality, request.file.contentType);
595
+ if (!job || job.scope.accountId !== identity.accountId || job.scope.workspaceId !== identity.workspaceId || job.artifactId !== request.file.artifactId || job.id !== request.file.materializationJobId || job.versionId !== request.file.versionId || job.targetHeadSequence !== request.file.sourceHeadSequence || job.stateHash !== request.file.sourceStateHash || job.format !== format || job.state !== "succeeded" || !job.result || job.result.byteSize !== request.file.sizeBytes || job.result.mimeType !== request.file.contentType || job.result.contentHash !== `sha256:${request.file.sha256}`) {
596
+ throw new Error("Google Drive publication receipt differs from its canonical materialization");
597
+ }
598
+ }
599
+ function expectedExportWorkspaceFile(workspaceId, request) {
600
+ const format = officeFormat(request.modality, request.file.contentType);
601
+ const fileId = deterministicUuid(
602
+ `editable-artifact-export:file:${workspaceId}:${request.file.artifactId}:${request.file.versionId}:${request.file.materializationJobId}`
603
+ );
604
+ const safeFilename = `artifact-${request.file.artifactId}-${request.file.materializationJobId}.${format}`;
605
+ return {
606
+ fileId,
607
+ safeFilename,
608
+ objectKey: `workspaces/${workspaceId}/files/${fileId}/artifact-exports/${safeFilename}`
609
+ };
610
+ }
611
+ function officeFormat(modality, contentType) {
612
+ const expected = {
613
+ document: {
614
+ format: "docx",
615
+ contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
616
+ },
617
+ spreadsheet: {
618
+ format: "xlsx",
619
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
620
+ },
621
+ presentation: {
622
+ format: "pptx",
623
+ contentType: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
624
+ }
625
+ }[modality];
626
+ if (contentType !== expected.contentType) {
627
+ throw new Error("Google Drive native publication requires the matching Office export format");
628
+ }
629
+ return expected.format;
630
+ }
631
+ function deterministicUuid(seed) {
632
+ const bytes = createHash("sha256").update(seed, "utf8").digest().subarray(0, 16);
633
+ bytes[6] = (bytes[6] ?? 0) & 15 | 80;
634
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
635
+ const hex = bytes.toString("hex");
636
+ const value = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
637
+ if (!UUID_PATTERN.test(value)) throw new Error("Generated workspace file identity is invalid");
638
+ return value;
639
+ }
640
+ async function publishToGoogleDrive(input) {
641
+ await verifyDestinationAtWriteTime(input);
642
+ const operationKey = publicationOperationKey(input);
643
+ const existing = await findExistingPublication(input, operationKey);
644
+ if (existing) return driveReceipt(input, existing, true);
645
+ const mimeType = googleNativeMime(input.request.modality);
646
+ const boundary = `opengeni_${operationKey.slice(0, 32)}`;
647
+ const metadata = JSON.stringify({
648
+ name: input.request.title,
649
+ mimeType,
650
+ parents: [input.destination.folderId],
651
+ appProperties: {
652
+ opengeniPublicationKey: operationKey,
653
+ opengeniArtifactId: input.request.file.artifactId,
654
+ opengeniArtifactVersionId: input.request.file.versionId,
655
+ opengeniSourceSha256: input.request.file.sha256
656
+ }
657
+ });
658
+ const prefix = new TextEncoder().encode(
659
+ `--${boundary}\r
660
+ Content-Type: application/json; charset=UTF-8\r
661
+ \r
662
+ ${metadata}\r
663
+ --${boundary}\r
664
+ Content-Type: ${input.request.file.contentType}\r
665
+ \r
666
+ `
667
+ );
668
+ const suffix = new TextEncoder().encode(`\r
669
+ --${boundary}--\r
670
+ `);
671
+ const body = new Uint8Array(prefix.byteLength + input.bytes.byteLength + suffix.byteLength);
672
+ body.set(prefix, 0);
673
+ body.set(input.bytes, prefix.byteLength);
674
+ body.set(suffix, prefix.byteLength + input.bytes.byteLength);
675
+ const url = new URL(`${DRIVE_UPLOAD_API}/files`);
676
+ url.searchParams.set("uploadType", "multipart");
677
+ url.searchParams.set("supportsAllDrives", "true");
678
+ url.searchParams.set(
679
+ "fields",
680
+ "id,name,mimeType,parents,driveId,webViewLink,appProperties,trashed"
681
+ );
682
+ const created = parseDriveFile(
683
+ await requestJson(input.fetchImpl, url, {
684
+ method: "POST",
685
+ headers: {
686
+ ...input.headers,
687
+ accept: "application/json",
688
+ "content-type": `multipart/related; boundary=${boundary}`,
689
+ "content-length": String(body.byteLength)
690
+ },
691
+ body,
692
+ ...input.signal ? { signal: input.signal } : {}
693
+ })
694
+ );
695
+ assertPublicationMatch(input, created, operationKey);
696
+ return driveReceipt(input, created, false);
697
+ }
698
+ async function verifyDestinationAtWriteTime(input) {
699
+ const url = new URL(`${DRIVE_API}/files/${encodeURIComponent(input.destination.folderId)}`);
700
+ url.searchParams.set("supportsAllDrives", "true");
701
+ url.searchParams.set("fields", "id,name,mimeType,driveId,trashed,capabilities(canAddChildren)");
702
+ const folder = record(await requestJson(input.fetchImpl, url, { headers: input.headers }));
703
+ const capabilities = record(folder.capabilities);
704
+ if (folder.id !== input.destination.folderId || folder.name !== input.destination.folderName || folder.mimeType !== DRIVE_FOLDER_MIME || folder.trashed === true || capabilities.canAddChildren !== true || (folder.driveId ?? null) !== input.destination.driveId) {
705
+ throw new Error("Google Drive output destination changed or is no longer writable");
706
+ }
707
+ }
708
+ async function findExistingPublication(input, operationKey) {
709
+ const url = new URL(`${DRIVE_API}/files`);
710
+ url.searchParams.set(
711
+ "q",
712
+ `trashed = false and '${driveQuery(input.destination.folderId)}' in parents and appProperties has { key='opengeniPublicationKey' and value='${operationKey}' }`
713
+ );
714
+ url.searchParams.set("spaces", "drive");
715
+ url.searchParams.set("supportsAllDrives", "true");
716
+ url.searchParams.set("includeItemsFromAllDrives", "true");
717
+ if (input.destination.driveId) {
718
+ url.searchParams.set("corpora", "drive");
719
+ url.searchParams.set("driveId", input.destination.driveId);
720
+ } else {
721
+ url.searchParams.set("corpora", "user");
722
+ }
723
+ url.searchParams.set(
724
+ "fields",
725
+ "files(id,name,mimeType,parents,driveId,webViewLink,appProperties,trashed)"
726
+ );
727
+ const payload = record(await requestJson(input.fetchImpl, url, { headers: input.headers }));
728
+ const files = Array.isArray(payload.files) ? payload.files.map(parseDriveFile) : [];
729
+ if (files.length > 1) throw new Error("Google Drive publication idempotency marker is ambiguous");
730
+ const existing = files[0] ?? null;
731
+ if (existing) assertPublicationMatch(input, existing, operationKey);
732
+ return existing;
733
+ }
734
+ function parseDriveFile(value) {
735
+ const item = record(value);
736
+ const appProperties = record(item.appProperties);
737
+ if (typeof item.id !== "string" || typeof item.name !== "string" || typeof item.mimeType !== "string" || !Array.isArray(item.parents) || !item.parents.every((entry) => typeof entry === "string") || item.driveId !== void 0 && item.driveId !== null && typeof item.driveId !== "string" || typeof item.webViewLink !== "string" || typeof item.trashed !== "boolean") {
738
+ throw new Error("Google Drive returned an invalid publication receipt");
739
+ }
740
+ return {
741
+ id: item.id,
742
+ name: item.name,
743
+ mimeType: item.mimeType,
744
+ parents: item.parents,
745
+ driveId: item.driveId ?? null,
746
+ webViewLink: item.webViewLink,
747
+ appProperties: Object.fromEntries(
748
+ Object.entries(appProperties).filter(
749
+ (entry) => typeof entry[1] === "string"
750
+ )
751
+ ),
752
+ trashed: item.trashed
753
+ };
754
+ }
755
+ function assertPublicationMatch(input, file, operationKey) {
756
+ if (file.trashed || file.name !== input.request.title || file.mimeType !== googleNativeMime(input.request.modality) || file.parents.length !== 1 || file.parents[0] !== input.destination.folderId || file.driveId !== input.destination.driveId || file.appProperties.opengeniPublicationKey !== operationKey || file.appProperties.opengeniArtifactId !== input.request.file.artifactId || file.appProperties.opengeniArtifactVersionId !== input.request.file.versionId || file.appProperties.opengeniSourceSha256 !== input.request.file.sha256) {
757
+ throw new Error("Google Drive publication idempotency key conflicts with another file");
758
+ }
759
+ }
760
+ function driveReceipt(input, file, replayed) {
761
+ return GoogleDrivePublicationReceipt.parse({
762
+ connectionId: input.connectionId,
763
+ providerFileId: file.id,
764
+ webViewLink: file.webViewLink,
765
+ mimeType: googleNativeMime(input.request.modality),
766
+ destination: input.destination,
767
+ replayed
768
+ });
769
+ }
770
+ function publicationOperationKey(input) {
771
+ return createHash("sha256").update(
772
+ JSON.stringify({
773
+ workspaceId: input.workspaceId,
774
+ connectionId: input.connectionId,
775
+ destination: input.destination,
776
+ artifactId: input.request.file.artifactId,
777
+ versionId: input.request.file.versionId,
778
+ materializationJobId: input.request.file.materializationJobId,
779
+ sourceSha256: input.request.file.sha256,
780
+ idempotencyKey: input.request.idempotencyKey
781
+ }),
782
+ "utf8"
783
+ ).digest("hex");
784
+ }
785
+ function googleNativeMime(modality) {
786
+ switch (modality) {
787
+ case "document":
788
+ return "application/vnd.google-apps.document";
789
+ case "spreadsheet":
790
+ return "application/vnd.google-apps.spreadsheet";
791
+ case "presentation":
792
+ return "application/vnd.google-apps.presentation";
793
+ }
794
+ }
795
+ function sameDestination(left, right) {
796
+ return left.folderId === right.folderId && left.folderName === right.folderName && left.driveId === right.driveId && left.location === right.location && left.selectedAt === right.selectedAt;
797
+ }
798
+ async function requestJson(fetchImpl, url, init) {
799
+ let response;
800
+ try {
801
+ response = await fetchImpl(url, {
802
+ ...init,
803
+ redirect: "error",
804
+ signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS)
805
+ });
806
+ } catch {
807
+ throw new Error("Google Drive publication transport failed");
808
+ }
809
+ if (!response.ok) {
810
+ await response.body?.cancel().catch(() => void 0);
811
+ throw new Error(`Google Drive publication request failed with status ${response.status}`);
812
+ }
813
+ return await readResponseJsonBounded(response, RESPONSE_MAX_BYTES, "Google Drive publication");
814
+ }
815
+ function record(value) {
816
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
817
+ }
818
+ function driveQuery(value) {
819
+ return value.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'");
820
+ }
821
+
222
822
  // src/activities/mcp-credentials.ts
223
823
  import {
224
824
  buildConnectionTokenResolver,
@@ -638,7 +1238,7 @@ function safeErrorName(error) {
638
1238
  // src/activities/codemode-dispatcher.ts
639
1239
  import { randomUUID } from "crypto";
640
1240
  import {
641
- AttemptToolApprovalRequiredError,
1241
+ AttemptToolApprovalRequiredError as AttemptToolApprovalRequiredError2,
642
1242
  AttemptToolCatalogStaleError,
643
1243
  AttemptToolNotFoundError,
644
1244
  codemodeDispatchSubject,
@@ -849,7 +1449,7 @@ var CodemodeAttemptDispatcher = class {
849
1449
  );
850
1450
  await this.settleWithOutput(operation, claimId, { state: "completed", result });
851
1451
  } catch (error) {
852
- const knownPreExecution = error instanceof AttemptToolApprovalRequiredError || error instanceof AttemptToolCatalogStaleError || error instanceof AttemptToolNotFoundError;
1452
+ const knownPreExecution = error instanceof AttemptToolApprovalRequiredError2 || error instanceof AttemptToolCatalogStaleError || error instanceof AttemptToolNotFoundError;
853
1453
  await this.settleWithOutput(operation, claimId, {
854
1454
  state: knownPreExecution ? "failed" : "outcome_unknown",
855
1455
  errorCode: errorCode(error, signal),
@@ -900,7 +1500,7 @@ function errorCode(error, signal) {
900
1500
  return "tool_outcome_unknown";
901
1501
  }
902
1502
  function safeErrorMessage(error) {
903
- if (error instanceof AttemptToolApprovalRequiredError || error instanceof AttemptToolCatalogStaleError || error instanceof AttemptToolNotFoundError) {
1503
+ if (error instanceof AttemptToolApprovalRequiredError2 || error instanceof AttemptToolCatalogStaleError || error instanceof AttemptToolNotFoundError) {
904
1504
  return error.message;
905
1505
  }
906
1506
  return "Codemode call failed before tool execution";
@@ -1039,7 +1639,7 @@ import {
1039
1639
  markImageGenerationOperationRetentionFailed,
1040
1640
  prepareImageGenerationOperation
1041
1641
  } from "@opengeni/db";
1042
- import { createHash as createHash3 } from "crypto";
1642
+ import { createHash as createHash4 } from "crypto";
1043
1643
 
1044
1644
  // src/activities/generated-images.ts
1045
1645
  import {
@@ -1055,7 +1655,7 @@ import {
1055
1655
  recordGeneratedImageArtifactError,
1056
1656
  settleGeneratedImageArtifactReady
1057
1657
  } from "@opengeni/db";
1058
- import { createHash as createHash2 } from "crypto";
1658
+ import { createHash as createHash3 } from "crypto";
1059
1659
 
1060
1660
  // src/activities/retained-screenshots.ts
1061
1661
  import {
@@ -1074,7 +1674,7 @@ import {
1074
1674
  recordRetainedScreenshotArtifactError,
1075
1675
  settleRetainedScreenshotArtifactReady
1076
1676
  } from "@opengeni/db";
1077
- import { createHash } from "crypto";
1677
+ import { createHash as createHash2 } from "crypto";
1078
1678
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
1079
1679
  var PNG_ALLOWED_CRITICAL_CHUNKS = /* @__PURE__ */ new Set(["IHDR", "PLTE", "IDAT", "IEND"]);
1080
1680
  var PNG_MAX_CHUNKS = 16384;
@@ -1134,10 +1734,10 @@ function imageBytesFromSdkToolOutput(output) {
1134
1734
  if (Array.isArray(output)) {
1135
1735
  for (const entry of output) {
1136
1736
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
1137
- const record4 = entry;
1138
- if (record4.type !== "input_image") continue;
1737
+ const record5 = entry;
1738
+ if (record5.type !== "input_image") continue;
1139
1739
  const decoded = imageBytesFromSdkImageSource(
1140
- record4.image ?? record4.image_url ?? record4.imageUrl
1740
+ record5.image ?? record5.image_url ?? record5.imageUrl
1141
1741
  );
1142
1742
  if (decoded) return decoded;
1143
1743
  }
@@ -1170,13 +1770,13 @@ function toolOutputContainsInlineImage(output) {
1170
1770
  if (Array.isArray(output)) {
1171
1771
  return output.some((entry) => {
1172
1772
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
1173
- const record5 = entry;
1174
- return record5.type === "input_image" && sdkImageSourceContainsInlineImage(record5.image ?? record5.image_url ?? record5.imageUrl);
1773
+ const record6 = entry;
1774
+ return record6.type === "input_image" && sdkImageSourceContainsInlineImage(record6.image ?? record6.image_url ?? record6.imageUrl);
1175
1775
  });
1176
1776
  }
1177
1777
  if (!output || typeof output !== "object") return false;
1178
- const record4 = output;
1179
- return record4.type === "image" && sdkImageSourceContainsInlineImage(record4.image);
1778
+ const record5 = output;
1779
+ return record5.type === "image" && sdkImageSourceContainsInlineImage(record5.image);
1180
1780
  }
1181
1781
  function decodeInlineImageDataUrl(value) {
1182
1782
  if (typeof value !== "string") return null;
@@ -1343,7 +1943,7 @@ function validateComputerScreenshot(input, limits = {}) {
1343
1943
  bytes: input.bytes,
1344
1944
  mediaType: "image/png",
1345
1945
  sizeBytes: input.bytes.byteLength,
1346
- sha256: createHash("sha256").update(input.bytes).digest("hex"),
1946
+ sha256: createHash2("sha256").update(input.bytes).digest("hex"),
1347
1947
  width,
1348
1948
  height
1349
1949
  };
@@ -1399,11 +1999,11 @@ function validateRetainableSessionImage(input, limits = {}) {
1399
1999
  bytes: input.bytes,
1400
2000
  ...identity,
1401
2001
  sizeBytes: input.bytes.byteLength,
1402
- sha256: createHash("sha256").update(input.bytes).digest("hex")
2002
+ sha256: createHash2("sha256").update(input.bytes).digest("hex")
1403
2003
  };
1404
2004
  }
1405
2005
  function retainedScreenshotIdentity(input) {
1406
- const settlementKey = createHash("sha256").update("opengeni:computer-screenshot:v1\0").update(input.sessionId).update("\0").update(input.turnId).update("\0").update(input.attemptId).update("\0").update(input.toolCallId).update("\0").update(input.toolOutputId).digest("hex");
2006
+ const settlementKey = createHash2("sha256").update("opengeni:computer-screenshot:v1\0").update(input.sessionId).update("\0").update(input.turnId).update("\0").update(input.attemptId).update("\0").update(input.toolCallId).update("\0").update(input.toolOutputId).digest("hex");
1407
2007
  const uuidBytes = Uint8Array.from(Buffer.from(settlementKey.slice(0, 32), "hex"));
1408
2008
  uuidBytes[6] = uuidBytes[6] & 15 | 128;
1409
2009
  uuidBytes[8] = uuidBytes[8] & 63 | 128;
@@ -1704,12 +2304,12 @@ function visitSerializedRunStateItemArrays(root, visitor) {
1704
2304
  if (Array.isArray(root.generatedItems)) {
1705
2305
  for (const wrapper of root.generatedItems) {
1706
2306
  if (!wrapper || typeof wrapper !== "object" || Array.isArray(wrapper)) continue;
1707
- const record4 = wrapper;
1708
- const rawItem = record4.rawItem;
2307
+ const record5 = wrapper;
2308
+ const rawItem = record5.rawItem;
1709
2309
  if (!rawItem || typeof rawItem !== "object" || Array.isArray(rawItem)) continue;
1710
2310
  const items = [rawItem];
1711
2311
  visitor(items);
1712
- if (items[0] !== rawItem) record4.rawItem = items[0];
2312
+ if (items[0] !== rawItem) record5.rawItem = items[0];
1713
2313
  }
1714
2314
  }
1715
2315
  if (Array.isArray(root.modelResponses)) {
@@ -1733,12 +2333,12 @@ async function visitSerializedRunStateItemArraysAsync(root, visitor) {
1733
2333
  if (Array.isArray(root.generatedItems)) {
1734
2334
  for (const wrapper of root.generatedItems) {
1735
2335
  if (!wrapper || typeof wrapper !== "object" || Array.isArray(wrapper)) continue;
1736
- const record4 = wrapper;
1737
- const rawItem = record4.rawItem;
2336
+ const record5 = wrapper;
2337
+ const rawItem = record5.rawItem;
1738
2338
  if (!rawItem || typeof rawItem !== "object" || Array.isArray(rawItem)) continue;
1739
2339
  const items = [rawItem];
1740
2340
  await visitor(items);
1741
- if (items[0] !== rawItem) record4.rawItem = items[0];
2341
+ if (items[0] !== rawItem) record5.rawItem = items[0];
1742
2342
  }
1743
2343
  }
1744
2344
  if (Array.isArray(root.modelResponses)) {
@@ -1836,8 +2436,8 @@ function retainedReceipt(value) {
1836
2436
  }
1837
2437
  function isInlineImageContent(entry) {
1838
2438
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
1839
- const record4 = entry;
1840
- return record4.type === "input_image" && typeof record4.image === "string" && record4.image.startsWith("data:image/");
2439
+ const record5 = entry;
2440
+ return record5.type === "input_image" && typeof record5.image === "string" && record5.image.startsWith("data:image/");
1841
2441
  }
1842
2442
  function historyCallId(item) {
1843
2443
  const value = item.callId ?? item.call_id;
@@ -2139,7 +2739,7 @@ function validateGeneratedImage(input) {
2139
2739
  }
2140
2740
  }
2141
2741
  function generatedImageIdentity(input) {
2142
- const hash = createHash2("sha256").update("opengeni:generated-image:v2\0").update(input.workspaceId).update("\0").update(input.sourceStrategy).update("\0").update(input.providerId).update("\0").update(input.providerBindingHash).update("\0");
2742
+ const hash = createHash3("sha256").update("opengeni:generated-image:v2\0").update(input.workspaceId).update("\0").update(input.sourceStrategy).update("\0").update(input.providerId).update("\0").update(input.providerBindingHash).update("\0");
2143
2743
  if (input.sourceStrategy === "native_hosted") {
2144
2744
  hash.update(input.providerItemId);
2145
2745
  } else {
@@ -2800,7 +3400,7 @@ async function recoverCompletedImage(input, identity) {
2800
3400
  return retainedGeneratedImageFromArtifact(recovered).receipt;
2801
3401
  }
2802
3402
  function digest(prefix, ...values) {
2803
- const hash = createHash3("sha256").update(prefix);
3403
+ const hash = createHash4("sha256").update(prefix);
2804
3404
  for (const value of values) hash.update(value).update("\0");
2805
3405
  return hash.digest("hex");
2806
3406
  }
@@ -2901,15 +3501,15 @@ import {
2901
3501
  FileResourceRef,
2902
3502
  resourceMountPath
2903
3503
  } from "@opengeni/contracts";
2904
- import { createHash as createHash4 } from "crypto";
3504
+ import { createHash as createHash5 } from "crypto";
2905
3505
  import {
2906
3506
  getActiveSessionHistoryItemsPaged,
2907
- getFiles,
3507
+ getFilesForSubject,
2908
3508
  getLatestRunState,
2909
3509
  getHumanInputResumeForEvent,
2910
3510
  getSandboxSessionEnvelope,
2911
3511
  listSessionSystemUpdatesForTurn,
2912
- requireFile
3512
+ requireFileForSubject
2913
3513
  } from "@opengeni/db";
2914
3514
  import {
2915
3515
  projectHistoryForProvider,
@@ -3018,7 +3618,7 @@ async function modelAttachmentContentForFiles(files, readFileBytes) {
3018
3618
  });
3019
3619
  continue;
3020
3620
  }
3021
- if (createHash4("sha256").update(bytes).digest("hex") !== checksum) {
3621
+ if (createHash5("sha256").update(bytes).digest("hex") !== checksum) {
3022
3622
  console.error("model attachment checksum did not match finalized metadata", {
3023
3623
  fileId: file.id
3024
3624
  });
@@ -3063,12 +3663,15 @@ function attachmentRefsFromItem(item) {
3063
3663
  return refs;
3064
3664
  }
3065
3665
  function attachmentUnavailableText(ref, file) {
3666
+ if (!file) {
3667
+ return `[Attachment unavailable or no longer authorized: ${ref.fileId}.]`;
3668
+ }
3066
3669
  const filename = file?.safeFilename ?? ref.fileId;
3067
3670
  const mediaType = file?.contentType ?? "unknown type";
3068
3671
  const path = file ? sandboxFilePath(ref, file) : `/workspace/${resourceMountPath(ref)}`;
3069
3672
  return `[Attachment not included directly because the selected model does not accept this input or it exceeded the safe inline limit: ${filename} (${mediaType}). It remains available to tools in the sandbox at ${path}.]`;
3070
3673
  }
3071
- function createModelHistoryAttachmentProjector(db, workspaceId, policy, readFileBytes) {
3674
+ function createModelHistoryAttachmentProjector(db, authority, policy, readFileBytes) {
3072
3675
  const fileById = /* @__PURE__ */ new Map();
3073
3676
  const missingFileIds = /* @__PURE__ */ new Set();
3074
3677
  const contentById = /* @__PURE__ */ new Map();
@@ -3090,7 +3693,10 @@ function createModelHistoryAttachmentProjector(db, workspaceId, policy, readFile
3090
3693
  if (refsByIndex.size === 0) return items;
3091
3694
  const unknownIds = orderedFileIds.filter((id) => !fileById.has(id) && !missingFileIds.has(id));
3092
3695
  if (unknownIds.length > 0) {
3093
- const files = await getFiles(db, workspaceId, unknownIds);
3696
+ const files = await getFilesForSubject(db, {
3697
+ ...authority,
3698
+ fileIds: unknownIds
3699
+ });
3094
3700
  for (const file of files) fileById.set(file.id, file);
3095
3701
  for (const id of unknownIds) {
3096
3702
  if (!fileById.has(id)) missingFileIds.add(id);
@@ -3179,7 +3785,8 @@ async function turnInput(db, runtime, agent, trigger, options) {
3179
3785
  "Continue the same inference from durable conversation and sandbox state. A previous execution stopped before it could finish. Do not repeat completed side effects; inspect actual state when uncertain."
3180
3786
  ].join("\n") : void 0,
3181
3787
  options.unavailableSandboxFilesNote,
3182
- options.runCredentialsNote
3788
+ options.runCredentialsNote,
3789
+ options.mcpAvailabilityNote
3183
3790
  );
3184
3791
  if (trigger.type === "user.message") {
3185
3792
  const payload = trigger.payload;
@@ -3191,7 +3798,13 @@ async function turnInput(db, runtime, agent, trigger, options) {
3191
3798
  const fileAttachments = await measureHistoryPreparationPhase(
3192
3799
  options,
3193
3800
  "current_attachment_resolution",
3194
- async () => await resolveUserMessageFileAttachments(db, trigger.workspaceId, resources)
3801
+ async () => await resolveUserMessageFileAttachments(
3802
+ db,
3803
+ options.fileAuthority.accountId,
3804
+ trigger.workspaceId,
3805
+ options.fileAuthority.subjectId,
3806
+ resources
3807
+ )
3195
3808
  );
3196
3809
  const attachmentContext = userMessageAttachmentsContext(fileAttachments);
3197
3810
  return await messageInput(
@@ -3359,11 +3972,16 @@ async function messageInput(db, runtime, agent, trigger, text, internalContext,
3359
3972
  providerArtifactCandidates
3360
3973
  };
3361
3974
  }
3362
- async function resolveUserMessageFileAttachments(db, workspaceId, resources) {
3975
+ async function resolveUserMessageFileAttachments(db, accountId, workspaceId, subjectId, resources) {
3363
3976
  const attachments = [];
3364
3977
  for (const resource of resources) {
3365
3978
  if (resource.kind !== "file") continue;
3366
- const file = await requireFile(db, workspaceId, resource.fileId);
3979
+ const file = await requireFileForSubject(db, {
3980
+ accountId,
3981
+ workspaceId,
3982
+ subjectId,
3983
+ fileId: resource.fileId
3984
+ });
3367
3985
  attachments.push({ resource, file });
3368
3986
  }
3369
3987
  return attachments;
@@ -3676,21 +4294,21 @@ function isContextWindowExceeded(error, seen = /* @__PURE__ */ new WeakSet()) {
3676
4294
  if (!error || typeof error !== "object") return false;
3677
4295
  if (seen.has(error)) return false;
3678
4296
  seen.add(error);
3679
- const record4 = error;
3680
- const code = typeof record4.code === "string" ? record4.code.toLowerCase() : "";
3681
- const message = typeof record4.message === "string" ? record4.message.toLowerCase() : error instanceof Error ? error.message.toLowerCase() : "";
4297
+ const record5 = error;
4298
+ const code = typeof record5.code === "string" ? record5.code.toLowerCase() : "";
4299
+ const message = typeof record5.message === "string" ? record5.message.toLowerCase() : error instanceof Error ? error.message.toLowerCase() : "";
3682
4300
  const direct = code === "context_length_exceeded" || code === "context_window_exceeded" || message.includes("context window") || message.includes("maximum context length") || message.includes("too many tokens");
3683
- return direct || isContextWindowExceeded(record4.cause, seen) || isContextWindowExceeded(record4.error, seen) || isContextWindowExceeded(record4.diagnostics, seen);
4301
+ return direct || isContextWindowExceeded(record5.cause, seen) || isContextWindowExceeded(record5.error, seen) || isContextWindowExceeded(record5.diagnostics, seen);
3684
4302
  }
3685
4303
  function isExactContextLengthExceeded(error, seen = /* @__PURE__ */ new WeakSet()) {
3686
4304
  if (!error || typeof error !== "object") return false;
3687
4305
  if (seen.has(error)) return false;
3688
4306
  seen.add(error);
3689
- const record4 = error;
3690
- if (record4.code === "context_length_exceeded") {
4307
+ const record5 = error;
4308
+ if (record5.code === "context_length_exceeded") {
3691
4309
  return true;
3692
4310
  }
3693
- return isExactContextLengthExceeded(record4.cause, seen) || isExactContextLengthExceeded(record4.error, seen) || isExactContextLengthExceeded(record4.diagnostics, seen);
4311
+ return isExactContextLengthExceeded(record5.cause, seen) || isExactContextLengthExceeded(record5.error, seen) || isExactContextLengthExceeded(record5.diagnostics, seen);
3694
4312
  }
3695
4313
 
3696
4314
  // src/activities/video-generation-admission.ts
@@ -3714,7 +4332,7 @@ import {
3714
4332
  calculateVideoGenerationCreditCostMicros,
3715
4333
  environmentsEncryptionKeyBytes as environmentsEncryptionKeyBytes3
3716
4334
  } from "@opengeni/config";
3717
- import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
4335
+ import { createHash as createHash7, randomUUID as randomUUID3 } from "crypto";
3718
4336
 
3719
4337
  // src/activities/video-reference-staging.ts
3720
4338
  import {
@@ -3722,7 +4340,7 @@ import {
3722
4340
  } from "@opengeni/contracts";
3723
4341
 
3724
4342
  // src/activities/video-media-validation.ts
3725
- import { createHash as createHash5, randomUUID as randomUUID2 } from "crypto";
4343
+ import { createHash as createHash6, randomUUID as randomUUID2 } from "crypto";
3726
4344
  import { open, mkdir, rm, stat } from "fs/promises";
3727
4345
  import { join } from "path";
3728
4346
  import { spawn } from "child_process";
@@ -3750,7 +4368,7 @@ async function copyVersionedObjectToVerifiedTemp(input) {
3750
4368
  const path = join(directory, "payload");
3751
4369
  await mkdir(directory, { recursive: false, mode: 448 });
3752
4370
  const handle = await open(path, "wx", 384);
3753
- const hash = createHash5("sha256");
4371
+ const hash = createHash6("sha256");
3754
4372
  let offset = 0;
3755
4373
  try {
3756
4374
  while (offset < input.expectedSizeBytes) {
@@ -3838,9 +4456,9 @@ async function probeBrowserCompatibleMp4(path, ffprobePath) {
3838
4456
  } catch {
3839
4457
  throw new Error("Media probe returned malformed metadata");
3840
4458
  }
3841
- const root = record(decoded);
3842
- const format = record(root?.format);
3843
- const streams = Array.isArray(root?.streams) ? root.streams.map(record).filter(Boolean) : [];
4459
+ const root = record2(decoded);
4460
+ const format = record2(root?.format);
4461
+ const streams = Array.isArray(root?.streams) ? root.streams.map(record2).filter(Boolean) : [];
3844
4462
  const video = streams.filter(
3845
4463
  (stream) => stream?.codec_type === "video" && !isAttachedPicture(stream)
3846
4464
  );
@@ -3863,7 +4481,7 @@ async function probeBrowserCompatibleMp4(path, ffprobePath) {
3863
4481
  };
3864
4482
  }
3865
4483
  function isAttachedPicture(stream) {
3866
- return Number(record(stream.disposition)?.attached_pic) === 1;
4484
+ return Number(record2(stream.disposition)?.attached_pic) === 1;
3867
4485
  }
3868
4486
  async function spawnBounded(command, args) {
3869
4487
  return await new Promise((resolve, reject) => {
@@ -3940,7 +4558,7 @@ function finitePositive(value) {
3940
4558
  function stringValue(value) {
3941
4559
  return typeof value === "string" && value.trim() ? value : null;
3942
4560
  }
3943
- function record(value) {
4561
+ function record2(value) {
3944
4562
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3945
4563
  }
3946
4564
  function assertSha256(value) {
@@ -4369,7 +4987,7 @@ async function admitVideoGenerationRequest(input) {
4369
4987
  toolCallId: input.toolCallId,
4370
4988
  admissionKey,
4371
4989
  requestDigest,
4372
- promptDigest: createHash6("sha256").update(canonical.prompt).digest("hex"),
4990
+ promptDigest: createHash7("sha256").update(canonical.prompt).digest("hex"),
4373
4991
  requestEncrypted: encryptEnvironmentValue2(encryptionKey, JSON.stringify(canonical)),
4374
4992
  modelId: canonical.modelId,
4375
4993
  sourceMode: canonical.sourceMode,
@@ -5717,7 +6335,7 @@ async function executeCodexImageGeneration(input) {
5717
6335
  }
5718
6336
 
5719
6337
  // src/activities/image-generation-references.ts
5720
- import { getGeneratedImageArtifact as getGeneratedImageArtifact2, requireFile as requireFile2 } from "@opengeni/db";
6338
+ import { getGeneratedImageArtifact as getGeneratedImageArtifact2, requireFileForSubject as requireFileForSubject2 } from "@opengeni/db";
5721
6339
  var IMAGE_GENERATION_REFERENCE_MAX_BYTES = 30 * 1024 * 1024;
5722
6340
  var IMAGE_GENERATION_REFERENCES_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
5723
6341
  async function resolveImageGenerationReferences(input) {
@@ -5752,7 +6370,12 @@ async function referenceBytes(input, reference2) {
5752
6370
  bytes: await input.readSandboxFile(reference2.path, IMAGE_GENERATION_REFERENCE_MAX_BYTES + 1)
5753
6371
  };
5754
6372
  }
5755
- const file = reference2.kind === "file" ? await requireFile2(input.db, input.workspaceId, reference2.fileId) : await artifactFile(input.db, input.workspaceId, reference2.artifactId);
6373
+ const file = reference2.kind === "file" ? await requireFileForSubject2(input.db, {
6374
+ accountId: input.accountId,
6375
+ workspaceId: input.workspaceId,
6376
+ subjectId: input.subjectId,
6377
+ fileId: reference2.fileId
6378
+ }) : await artifactFile(input.db, input.workspaceId, reference2.artifactId);
5756
6379
  if (file.status !== "ready" || !file.sha256) {
5757
6380
  throw new Error("Image reference file is not durably ready");
5758
6381
  }
@@ -5786,7 +6409,7 @@ function assertStoredFileMatches(file, image) {
5786
6409
  }
5787
6410
 
5788
6411
  // src/activities/workspace-capture.ts
5789
- import { createHash as createHash7 } from "crypto";
6412
+ import { createHash as createHash8 } from "crypto";
5790
6413
  import {
5791
6414
  deleteWorkspaceCaptureRows,
5792
6415
  insertFailedWorkspaceCapture,
@@ -6540,7 +7163,7 @@ function joinRepoPath(repoRoot, repoRelPath) {
6540
7163
  return `${repoRoot.replace(/\/+$/, "")}/${repoRelPath}`;
6541
7164
  }
6542
7165
  function sha256(bytes) {
6543
- return createHash7("sha256").update(bytes).digest("hex");
7166
+ return createHash8("sha256").update(bytes).digest("hex");
6544
7167
  }
6545
7168
  function utf8(s) {
6546
7169
  return new TextEncoder().encode(s);
@@ -6625,7 +7248,7 @@ import {
6625
7248
  resourceMountPath as resourceMountPath2,
6626
7249
  VideoGenerationRejectedResult
6627
7250
  } from "@opengeni/contracts";
6628
- import { createHash as createHash8, randomUUID as randomUUID4 } from "crypto";
7251
+ import { createHash as createHash9, randomUUID as randomUUID4 } from "crypto";
6629
7252
 
6630
7253
  // src/model-checkpoint-memory-collector.ts
6631
7254
  var MODEL_CHECKPOINT_GC_PRESSURE_BYTES = 512 * 1024 * 1024;
@@ -6810,7 +7433,7 @@ function providerRetryAfterMs(error, nowMs = Date.now()) {
6810
7433
  }
6811
7434
  return null;
6812
7435
  }
6813
- function unavailableMcpTurnInstructions(input) {
7436
+ function unavailableMcpOperationalContext(input) {
6814
7437
  if (input.droppedCount <= 0) {
6815
7438
  return void 0;
6816
7439
  }
@@ -6858,10 +7481,10 @@ function sandboxFileMaterializationOutcome(failures) {
6858
7481
  return failures.length === 0 ? "completed" : "failed";
6859
7482
  }
6860
7483
  function codexWorkspaceMetricKey(workspaceId) {
6861
- return createHash8("sha256").update(workspaceId).digest("hex").slice(0, 12);
7484
+ return createHash9("sha256").update(workspaceId).digest("hex").slice(0, 12);
6862
7485
  }
6863
7486
  function stableHumanInputRequestId(sessionId, turnId, toolCallId) {
6864
- const hex = createHash8("sha256").update("opengeni-human-input-v1\0").update(sessionId).update("\0").update(turnId).update("\0").update(toolCallId).digest("hex").slice(0, 32).split("");
7487
+ const hex = createHash9("sha256").update("opengeni-human-input-v1\0").update(sessionId).update("\0").update(turnId).update("\0").update(toolCallId).digest("hex").slice(0, 32).split("");
6865
7488
  hex[12] = "5";
6866
7489
  hex[16] = ["8", "9", "a", "b"][Number.parseInt(hex[16] ?? "0", 16) % 4] ?? "8";
6867
7490
  const value = hex.join("");
@@ -6884,7 +7507,7 @@ function stableInteractionInterventionOperationId(sessionId, turnId, toolCallId)
6884
7507
  );
6885
7508
  }
6886
7509
  function stableInteractionInterventionUuid(namespace, sessionId, turnId, toolCallId) {
6887
- const hex = createHash8("sha256").update(namespace).update("\0").update(sessionId).update("\0").update(turnId).update("\0").update(toolCallId).digest("hex").slice(0, 32).split("");
7510
+ const hex = createHash9("sha256").update(namespace).update("\0").update(sessionId).update("\0").update(turnId).update("\0").update(toolCallId).digest("hex").slice(0, 32).split("");
6888
7511
  hex[12] = "5";
6889
7512
  hex[16] = ["8", "9", "a", "b"][Number.parseInt(hex[16] ?? "0", 16) % 4] ?? "8";
6890
7513
  const value = hex.join("");
@@ -7141,15 +7764,15 @@ function collectErrorStrings(value, seen = /* @__PURE__ */ new WeakSet()) {
7141
7764
  }
7142
7765
  seen.add(value);
7143
7766
  const out = [];
7144
- const record4 = value;
7767
+ const record5 = value;
7145
7768
  for (const key of ["message", "code", "type", "name", "param"]) {
7146
- const field = record4[key];
7769
+ const field = record5[key];
7147
7770
  if (typeof field === "string" && field.length > 0) {
7148
7771
  out.push(field);
7149
7772
  }
7150
7773
  }
7151
7774
  for (const key of ["error", "cause", "response", "data"]) {
7152
- out.push(...collectErrorStrings(record4[key], seen));
7775
+ out.push(...collectErrorStrings(record5[key], seen));
7153
7776
  }
7154
7777
  return out;
7155
7778
  }
@@ -7542,18 +8165,18 @@ function sandboxEstablishPolicyDecision(input) {
7542
8165
  }
7543
8166
  return { policy: "on-demand", reason: "eligible" };
7544
8167
  }
7545
- function pointerReconcileReason(record4) {
7546
- if (!record4) {
8168
+ function pointerReconcileReason(record5) {
8169
+ if (!record5) {
7547
8170
  return "stale_pointer";
7548
8171
  }
7549
8172
  const establishable = swapTargetEstablishability({
7550
- kind: record4.kind,
8173
+ kind: record5.kind,
7551
8174
  isSessionGroup: false
7552
8175
  });
7553
8176
  if (!establishable.ok) {
7554
8177
  return establishable.code;
7555
8178
  }
7556
- if (record4.kind === "selfhosted" && !record4.enrollmentId) {
8179
+ if (record5.kind === "selfhosted" && !record5.enrollmentId) {
7557
8180
  return "offline_enrollment";
7558
8181
  }
7559
8182
  return null;
@@ -7562,15 +8185,15 @@ async function reconcileActiveSandboxPointer(db, ids, pointer, loadRecord, publi
7562
8185
  if (!pointer?.activeSandboxId) {
7563
8186
  return { pointer, record: null };
7564
8187
  }
7565
- let record4;
8188
+ let record5;
7566
8189
  try {
7567
- record4 = await loadRecord(pointer.activeSandboxId);
8190
+ record5 = await loadRecord(pointer.activeSandboxId);
7568
8191
  } catch {
7569
8192
  return { pointer, record: null };
7570
8193
  }
7571
- const reason = pointerReconcileReason(record4);
8194
+ const reason = pointerReconcileReason(record5);
7572
8195
  if (!reason) {
7573
- return { pointer, record: record4 };
8196
+ return { pointer, record: record5 };
7574
8197
  }
7575
8198
  const fromEpoch = pointer.activeEpoch;
7576
8199
  const reset = await setActiveSandbox(db, {
@@ -8544,7 +9167,7 @@ function createRunAgentTurnActivity(services) {
8544
9167
  if (!objectStorage) {
8545
9168
  throw new Error("Generated image sandbox materialization requires object storage");
8546
9169
  }
8547
- const file = await requireFile3(db, input.workspaceId, receipt.artifact.artifactId);
9170
+ const file = await requireFile2(db, input.workspaceId, receipt.artifact.artifactId);
8548
9171
  const downloadStorage = objectStorageForSandboxDownloads(modelRunSettings, objectStorage);
8549
9172
  const signed = await downloadStorage.createGetUrl({
8550
9173
  key: file.objectKey
@@ -8889,6 +9512,7 @@ function createRunAgentTurnActivity(services) {
8889
9512
  providerRecoveryCount = providerRecoveryCountFromMetadata(turn.metadata);
8890
9513
  let installedApiIntegrations = [];
8891
9514
  const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);
9515
+ const fileAuthoritySubjectId = turn.initiatingHumanSubjectId ?? null;
8892
9516
  const mcpSettings = await settingsWithEnabledCapabilityMcpServers(
8893
9517
  db,
8894
9518
  input.workspaceId,
@@ -9969,9 +10593,21 @@ function createRunAgentTurnActivity(services) {
9969
10593
  modelCanReceiveRetainedSessionImages = supportsImageInput;
9970
10594
  const attachmentProjector = createModelHistoryAttachmentProjector(
9971
10595
  db,
9972
- input.workspaceId,
10596
+ {
10597
+ accountId: input.accountId,
10598
+ workspaceId: input.workspaceId,
10599
+ subjectId: fileAuthoritySubjectId
10600
+ },
9973
10601
  modelInputPolicy,
9974
- objectStorage ? (file) => objectStorage.getFileBytes(file) : void 0
10602
+ objectStorage ? async (file) => {
10603
+ await requireFileForSubject3(db, {
10604
+ accountId: input.accountId,
10605
+ workspaceId: input.workspaceId,
10606
+ subjectId: fileAuthoritySubjectId,
10607
+ fileId: file.id
10608
+ });
10609
+ return await objectStorage.getFileBytes(file);
10610
+ } : void 0
9975
10611
  );
9976
10612
  const modelHistoryProjector = async (items) => projectModelInputForCapabilities(await attachmentProjector(items), modelInputPolicy);
9977
10613
  const generatedImageHistoryProjector = async (items) => {
@@ -10432,7 +11068,7 @@ function createRunAgentTurnActivity(services) {
10432
11068
  availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),
10433
11069
  defaultMcpServerIds: defaultSessionMcpServerIds(capabilitySettings.mcpServers)
10434
11070
  });
10435
- const mcpAvailabilityInstructions = unavailableMcpTurnInstructions({
11071
+ const mcpAvailabilityNote = unavailableMcpOperationalContext({
10436
11072
  droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,
10437
11073
  droppedCount: resolvedToolPolicy.effectivePolicy.counts.dropped
10438
11074
  });
@@ -10570,6 +11206,13 @@ function createRunAgentTurnActivity(services) {
10570
11206
  if (activeSandboxBackend !== "selfhosted") {
10571
11207
  await assertGitHubResourcesRemainAuthorized(db, input.workspaceId, turnResources);
10572
11208
  }
11209
+ await assertFileResourcesRemainAuthorized(
11210
+ db,
11211
+ input.accountId,
11212
+ input.workspaceId,
11213
+ fileAuthoritySubjectId,
11214
+ turnResources
11215
+ );
10573
11216
  const authorizeGitHubTokenMint = async (selection) => {
10574
11217
  await assertGitHubTokenMintSelectionAuthorized(
10575
11218
  db,
@@ -11130,7 +11773,9 @@ function createRunAgentTurnActivity(services) {
11130
11773
  runSettings,
11131
11774
  db,
11132
11775
  objectStorage,
11776
+ input.accountId,
11133
11777
  input.workspaceId,
11778
+ fileAuthoritySubjectId,
11134
11779
  turnResources,
11135
11780
  activeSandboxBackend ?? groupBoxBackend
11136
11781
  ),
@@ -11200,7 +11845,7 @@ function createRunAgentTurnActivity(services) {
11200
11845
  const delegatedOwnerHasMembership = async (subjectId) => {
11201
11846
  const existing = delegatedMembershipChecks.get(subjectId);
11202
11847
  if (existing) return await existing;
11203
- const check = getWorkspaceGrant(db, subjectId, input.workspaceId).then(Boolean);
11848
+ const check = getWorkspaceGrant2(db, subjectId, input.workspaceId).then(Boolean);
11204
11849
  delegatedMembershipChecks.set(subjectId, check);
11205
11850
  return await check;
11206
11851
  };
@@ -11216,6 +11861,32 @@ function createRunAgentTurnActivity(services) {
11216
11861
  }
11217
11862
  return result;
11218
11863
  };
11864
+ const connectorActionIdentity = {
11865
+ accountId: input.accountId,
11866
+ workspaceId: input.workspaceId,
11867
+ sessionId: input.sessionId,
11868
+ turnId: turn.id,
11869
+ attemptId: input.attemptId,
11870
+ executionGeneration,
11871
+ initiator: {
11872
+ kind: turn.initiator.kind,
11873
+ subjectId: turn.initiator.subjectId
11874
+ }
11875
+ };
11876
+ const googleDrivePublicationTarget = objectStorage ? await resolveGoogleDrivePublicationTarget(
11877
+ db,
11878
+ input.workspaceId,
11879
+ personalConnectionDelegations
11880
+ ) : null;
11881
+ const googleDrivePublicationTool = objectStorage && googleDrivePublicationTarget ? createGoogleDrivePublicationAttemptTool({
11882
+ db,
11883
+ objectStorage,
11884
+ identity: connectorActionIdentity,
11885
+ subjectId: googleDrivePublicationTarget.ownerSubjectId,
11886
+ target: googleDrivePublicationTarget,
11887
+ resolveCredential,
11888
+ ...runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {}
11889
+ }) : null;
11219
11890
  const publishToolAuthNeeded = async (payload) => {
11220
11891
  if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {
11221
11892
  return;
@@ -11266,6 +11937,36 @@ function createRunAgentTurnActivity(services) {
11266
11937
  runSettings,
11267
11938
  session.firstPartyMcpTools
11268
11939
  );
11940
+ const googleDrivePublicationAllowed = selectedFirstPartyMcpTools.includes("editable_artifact_export") && selectedFirstPartyMcpTools.includes("editable_artifact_export_status") && (!session.firstPartyMcpPermissions?.length || session.firstPartyMcpPermissions.includes("artifacts:read") && session.firstPartyMcpPermissions.includes("artifacts:publish"));
11941
+ const googleDriveConnectorBindings = googleDrivePublicationTool && googleDrivePublicationTarget && googleDrivePublicationAllowed ? [
11942
+ {
11943
+ modelName: googleDrivePublicationTool.modelName,
11944
+ call: (approvalId, arguments_) => googleDrivePublicationConnectorCall(
11945
+ googleDrivePublicationTarget,
11946
+ arguments_,
11947
+ approvalId
11948
+ )
11949
+ }
11950
+ ] : [];
11951
+ const attemptToolDefinitions = [
11952
+ ...createFirstPartyInteractionAttemptToolDefinitions({
11953
+ settings: runSettings,
11954
+ scope: {
11955
+ accountId: input.accountId,
11956
+ workspaceId: input.workspaceId,
11957
+ sessionId: input.sessionId,
11958
+ turnId: turn.id,
11959
+ attemptId: input.attemptId,
11960
+ executionGeneration
11961
+ },
11962
+ ...session.firstPartyMcpPermissions?.length ? { permissions: session.firstPartyMcpPermissions } : {},
11963
+ selectedTools: selectedFirstPartyMcpTools,
11964
+ subjectId: "worker:first-party-mcp",
11965
+ subjectLabel: "OpenGeni worker",
11966
+ ...interactionInterventionResume ? { interventionResume: interactionInterventionResume } : {}
11967
+ }),
11968
+ ...googleDrivePublicationTool && googleDrivePublicationAllowed ? [googleDrivePublicationTool] : []
11969
+ ];
11269
11970
  recordTurnStartupPhase(observability, {
11270
11971
  phase: "tool_context_preparation",
11271
11972
  provider: turnExecutionPolicy.providerId,
@@ -11314,22 +12015,21 @@ function createRunAgentTurnActivity(services) {
11314
12015
  firstPartyTools: selectedFirstPartyMcpTools,
11315
12016
  nestedAgentDepth: session.nestedAgentDepth,
11316
12017
  effectiveMaxNestedAgentDepth: session.effectiveMaxNestedAgentDepth,
11317
- attemptToolDefinitions: createFirstPartyInteractionAttemptToolDefinitions({
11318
- settings: runSettings,
11319
- scope: {
11320
- accountId: input.accountId,
11321
- workspaceId: input.workspaceId,
11322
- sessionId: input.sessionId,
11323
- turnId: turn.id,
11324
- attemptId: input.attemptId,
11325
- executionGeneration
11326
- },
11327
- ...session.firstPartyMcpPermissions?.length ? { permissions: session.firstPartyMcpPermissions } : {},
11328
- selectedTools: selectedFirstPartyMcpTools,
11329
- subjectId: "worker:first-party-mcp",
11330
- subjectLabel: "OpenGeni worker",
11331
- ...interactionInterventionResume ? { interventionResume: interactionInterventionResume } : {}
11332
- })
12018
+ attemptToolDefinitions,
12019
+ ...googleDrivePublicationTarget && googleDrivePublicationAllowed ? {
12020
+ attemptToolAuthorize: async ({ call }) => {
12021
+ if (call.caller.kind !== "codemode" || call.identity.serverId !== "google-drive-publishing" || call.identity.toolName !== "google_drive_publish_file") {
12022
+ return;
12023
+ }
12024
+ await authorizeGoogleDrivePublicationAttempt({
12025
+ db,
12026
+ identity: connectorActionIdentity,
12027
+ target: googleDrivePublicationTarget,
12028
+ approvalId: call.operationId,
12029
+ arguments: call.arguments
12030
+ });
12031
+ }
12032
+ } : {}
11333
12033
  }),
11334
12034
  cancellationSignal,
11335
12035
  async (latePreparedTools) => await latePreparedTools.close().catch(() => void 0)
@@ -11377,7 +12077,9 @@ function createRunAgentTurnActivity(services) {
11377
12077
  const resolveImageReferences = async (references) => await resolveImageGenerationReferences({
11378
12078
  db,
11379
12079
  objectStorage,
12080
+ accountId: input.accountId,
11380
12081
  workspaceId: input.workspaceId,
12082
+ subjectId: fileAuthoritySubjectId,
11381
12083
  references,
11382
12084
  readSandboxFile: async (path, maxBytes) => {
11383
12085
  const imageReferenceSession = setupBoxSession ?? sdkOwnedSandboxSession;
@@ -11655,22 +12357,10 @@ function createRunAgentTurnActivity(services) {
11655
12357
  turnExecutionPolicy.providerId,
11656
12358
  turnExecutionPolicy.latencyMode
11657
12359
  );
11658
- const connectorActionIdentity = {
11659
- accountId: input.accountId,
11660
- workspaceId: input.workspaceId,
11661
- sessionId: input.sessionId,
11662
- turnId,
11663
- attemptId: input.attemptId,
11664
- executionGeneration,
11665
- initiator: {
11666
- kind: turn.initiator.kind,
11667
- subjectId: turn.initiator.subjectId
11668
- }
11669
- };
11670
12360
  const connectorActionPolicy = {
11671
- prepare: async (call) => await prepareConnectorActionApproval(db, connectorActionIdentity, call),
11672
- begin: async (call) => await beginConnectorActionExecution(db, connectorActionIdentity, call),
11673
- complete: async ({ requestId, outcome }) => await completeConnectorActionExecution(db, {
12361
+ prepare: async (call) => await prepareConnectorActionApproval2(db, connectorActionIdentity, call),
12362
+ begin: async (call) => await beginConnectorActionExecution2(db, connectorActionIdentity, call),
12363
+ complete: async ({ requestId, outcome }) => await completeConnectorActionExecution2(db, {
11674
12364
  accountId: input.accountId,
11675
12365
  workspaceId: input.workspaceId,
11676
12366
  requestId,
@@ -11745,6 +12435,7 @@ function createRunAgentTurnActivity(services) {
11745
12435
  mcpServers: preparedTools.mcpServers,
11746
12436
  resolvedMcpConnectionIds: preparedTools.resolvedMcpConnectionIds,
11747
12437
  connectorActionPolicy,
12438
+ attemptConnectorActionBindings: googleDriveConnectorBindings,
11748
12439
  // LIVE by-reference connector namespaces (fills during this turn's
11749
12440
  // codex_apps tools/list): the codex tool_search description reads it per
11750
12441
  // model call so the model sees the account's real connected sources.
@@ -11815,11 +12506,6 @@ function createRunAgentTurnActivity(services) {
11815
12506
  // Composed system-level AFTER the workspace persona so it refines it for
11816
12507
  // this one session; absent ⇒ byte-identical to today's composition.
11817
12508
  ...session.instructions ? { sessionInstructions: session.instructions } : {},
11818
- // Exact host context captured when this turn was accepted. It is
11819
- // system-level and disappears with the turn rather than entering chat.
11820
- ...turn.turnInstructions || mcpAvailabilityInstructions ? {
11821
- turnInstructions: [turn.turnInstructions, mcpAvailabilityInstructions].filter((value) => Boolean(value)).join(" ")
11822
- } : {},
11823
12509
  ...workspaceEnvironmentOption,
11824
12510
  // RIG RUNTIME (M3): the doctrine block, the setup-script hook (only when
11825
12511
  // the frozen version carries a non-empty script), and the rig credential
@@ -12445,9 +13131,14 @@ function createRunAgentTurnActivity(services) {
12445
13131
  try {
12446
13132
  const prepared = await turnInput(db, runtime, agent, trigger, {
12447
13133
  turnId: activeTurnId,
13134
+ fileAuthority: {
13135
+ accountId: input.accountId,
13136
+ subjectId: fileAuthoritySubjectId
13137
+ },
12448
13138
  recovering: turn.executionGeneration > 1,
12449
13139
  ...unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {},
12450
13140
  ...runCredentialsNote ? { runCredentialsNote } : {},
13141
+ ...mcpAvailabilityNote ? { mcpAvailabilityNote } : {},
12451
13142
  providerApi,
12452
13143
  projectCanonicalHistory: generatedImageHistoryProjector,
12453
13144
  materializeModelHistory: materializeScreenshotHistory,
@@ -14817,6 +15508,21 @@ async function assertGitHubResourcesRemainAuthorized(db, workspaceId, resources)
14817
15508
  );
14818
15509
  }
14819
15510
  }
15511
+ async function assertFileResourcesRemainAuthorized(db, accountId, workspaceId, subjectId, resources) {
15512
+ const fileIds = resources.flatMap(
15513
+ (resource) => resource.kind === "file" ? [resource.fileId] : []
15514
+ );
15515
+ if (fileIds.length === 0) return;
15516
+ const authorized = await getFilesForSubject2(db, {
15517
+ accountId,
15518
+ workspaceId,
15519
+ subjectId,
15520
+ fileIds
15521
+ });
15522
+ if (authorized.length !== new Set(fileIds).size) {
15523
+ throw new Error("One or more file resources are unavailable or no longer authorized");
15524
+ }
15525
+ }
14820
15526
  async function assertGitHubTokenMintSelectionAuthorized(db, workspaceId, installationId, repositoryIds) {
14821
15527
  if (!await areGitHubRepositoriesAllowedForWorkspace(
14822
15528
  db,
@@ -15354,7 +16060,7 @@ function startOfUtcMonth() {
15354
16060
  const now = /* @__PURE__ */ new Date();
15355
16061
  return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
15356
16062
  }
15357
- async function sandboxFileDownloadsForRun(settings, db, objectStorage, workspaceId, resources, activeSandboxBackend = settings.sandboxBackend) {
16063
+ async function sandboxFileDownloadsForRun(settings, db, objectStorage, accountId, workspaceId, subjectId, resources, activeSandboxBackend = settings.sandboxBackend) {
15358
16064
  if (!requiresSignedFileResourceDownloads(settings, activeSandboxBackend)) {
15359
16065
  return [];
15360
16066
  }
@@ -15372,7 +16078,12 @@ async function sandboxFileDownloadsForRun(settings, db, objectStorage, workspace
15372
16078
  const downloadStorage = objectStorageForSandboxDownloads(settings, objectStorage);
15373
16079
  const downloads = [];
15374
16080
  for (const resource of fileResources) {
15375
- const file = await requireFile3(db, workspaceId, resource.fileId);
16081
+ const file = await requireFileForSubject3(db, {
16082
+ accountId,
16083
+ workspaceId,
16084
+ subjectId,
16085
+ fileId: resource.fileId
16086
+ });
15376
16087
  const url = await downloadStorage.createGetUrl({ key: file.objectKey });
15377
16088
  downloads.push({
15378
16089
  fileId: file.id,
@@ -15437,7 +16148,7 @@ var GATEWAY_VIDEO_START_URL = "https://ai-gateway.vercel.sh/v4/ai/video-model/st
15437
16148
  var GATEWAY_VIDEO_STATUS_URL = "https://ai-gateway.vercel.sh/v4/ai/video-model/status";
15438
16149
  var PROTOCOL_VERSION = "0.0.1";
15439
16150
  var VIDEO_SPECIFICATION_VERSION = "4";
15440
- var RESPONSE_MAX_BYTES = 1024 * 1024;
16151
+ var RESPONSE_MAX_BYTES2 = 1024 * 1024;
15441
16152
  var ERROR_MAX_BYTES = 64 * 1024;
15442
16153
  var GatewayVideoApiError = class extends Error {
15443
16154
  constructor(status, retryable, message) {
@@ -15460,7 +16171,7 @@ async function startGatewayVideoGenerationWithBody(input) {
15460
16171
  ...input.fetch ? { fetch: input.fetch } : {}
15461
16172
  });
15462
16173
  const parsed = await readGatewayJson(response, "AI Gateway video start", input.signal);
15463
- const operation = record2(parsed.operation);
16174
+ const operation = record3(parsed.operation);
15464
16175
  const providerJobId = stringValue2(operation?.gatewayJobId);
15465
16176
  if (!providerJobId || providerJobId.length > 1024) {
15466
16177
  throw new GatewayVideoApiError(null, true, "AI Gateway video start response is malformed");
@@ -15495,7 +16206,7 @@ async function getGatewayVideoGenerationStatus(input) {
15495
16206
  if (status !== "completed" || !Array.isArray(parsed.videos) || parsed.videos.length !== 1) {
15496
16207
  throw new GatewayVideoApiError(null, true, "AI Gateway video status response is malformed");
15497
16208
  }
15498
- const video = record2(parsed.videos[0]);
16209
+ const video = record3(parsed.videos[0]);
15499
16210
  const outputUrl = video?.type === "url" ? stringValue2(video.url) : null;
15500
16211
  const mediaType = stringValue2(video?.mediaType);
15501
16212
  if (!outputUrl || !mediaType || outputUrl.length > 8192 || mediaType.length > 128) {
@@ -15580,7 +16291,7 @@ async function gatewayFetch(input) {
15580
16291
  );
15581
16292
  }
15582
16293
  async function readGatewayJson(response, label, signal) {
15583
- const text = await readResponseTextBounded2(response, RESPONSE_MAX_BYTES, label, {
16294
+ const text = await readResponseTextBounded2(response, RESPONSE_MAX_BYTES2, label, {
15584
16295
  ...signal ? { signal } : {}
15585
16296
  });
15586
16297
  let parsed;
@@ -15589,7 +16300,7 @@ async function readGatewayJson(response, label, signal) {
15589
16300
  } catch {
15590
16301
  throw new GatewayVideoApiError(null, true, `${label} response is not JSON`);
15591
16302
  }
15592
- const value = record2(parsed);
16303
+ const value = record3(parsed);
15593
16304
  if (!value) throw new GatewayVideoApiError(null, true, `${label} response is malformed`);
15594
16305
  return value;
15595
16306
  }
@@ -15608,7 +16319,7 @@ function requireHttps(value) {
15608
16319
  }
15609
16320
  return url.toString();
15610
16321
  }
15611
- function record2(value) {
16322
+ function record3(value) {
15612
16323
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
15613
16324
  }
15614
16325
  function stringValue2(value) {
@@ -15617,8 +16328,8 @@ function stringValue2(value) {
15617
16328
  function boundedError(value) {
15618
16329
  let message = value;
15619
16330
  try {
15620
- const parsed = record2(JSON.parse(value));
15621
- const error = record2(parsed?.error);
16331
+ const parsed = record3(JSON.parse(value));
16332
+ const error = record3(parsed?.error);
15622
16333
  message = stringValue2(error?.message) ?? stringValue2(parsed?.message) ?? value;
15623
16334
  } catch {
15624
16335
  }
@@ -15626,14 +16337,14 @@ function boundedError(value) {
15626
16337
  }
15627
16338
  function publicProviderReason(error, cancelled) {
15628
16339
  if (cancelled) return "The video provider cancelled the generation.";
15629
- const message = typeof error === "string" ? error : stringValue2(record2(error)?.message) ?? "The video provider could not complete the generation.";
16340
+ const message = typeof error === "string" ? error : stringValue2(record3(error)?.message) ?? "The video provider could not complete the generation.";
15630
16341
  return message.replace(/\s+/gu, " ").trim().slice(0, 1e3);
15631
16342
  }
15632
16343
 
15633
16344
  // src/activities/video-output-retention.ts
15634
16345
  import { GENERATED_VIDEO_MAX_BYTES as GENERATED_VIDEO_MAX_BYTES2 } from "@opengeni/contracts";
15635
16346
  import { pinnedFetch } from "@opengeni/network";
15636
- import { createHash as createHash9, randomUUID as randomUUID5 } from "crypto";
16347
+ import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
15637
16348
  import { createReadStream } from "fs";
15638
16349
  import { mkdir as mkdir2, open as open2, rm as rm2 } from "fs/promises";
15639
16350
  import { join as join2 } from "path";
@@ -15671,7 +16382,7 @@ async function downloadGeneratedVideoToVerifiedTemp(input) {
15671
16382
  await mkdir2(directory, { recursive: false, mode: 448 });
15672
16383
  const handle = await open2(path, "wx", 384);
15673
16384
  const reader = response.body.getReader();
15674
- const digest2 = createHash9("sha256");
16385
+ const digest2 = createHash10("sha256");
15675
16386
  let sizeBytes = 0;
15676
16387
  try {
15677
16388
  for (; ; ) {
@@ -15797,7 +16508,7 @@ async function verifyStoredObject(input) {
15797
16508
  if (!head || head.ContentLength !== input.expectedSizeBytes || head.ContentType !== "video/mp4" || head.Metadata?.sha256 !== input.expectedSha256 || !head.VersionToken) {
15798
16509
  throw new Error("Retained video object metadata is inconsistent");
15799
16510
  }
15800
- const hash = createHash9("sha256");
16511
+ const hash = createHash10("sha256");
15801
16512
  let offset = 0;
15802
16513
  while (offset < input.expectedSizeBytes) {
15803
16514
  throwIfAborted3(input.signal);
@@ -16330,8 +17041,8 @@ function decryptCanonicalRequest(operation, key) {
16330
17041
  return request;
16331
17042
  }
16332
17043
  function validateCanonicalRequest(value) {
16333
- const row = record3(value);
16334
- const references = Array.isArray(row?.references) ? row.references.map(record3) : null;
17044
+ const row = record4(value);
17045
+ const references = Array.isArray(row?.references) ? row.references.map(record4) : null;
16335
17046
  if (row?.schemaVersion !== 1 || typeof row.modelId !== "string" || typeof row.prompt !== "string" || ![
16336
17047
  "text",
16337
17048
  "first_frame",
@@ -16349,7 +17060,7 @@ function validateCanonicalRequest(value) {
16349
17060
  }
16350
17061
  function decryptProviderBody(operation, key) {
16351
17062
  if (!operation.providerRequestEncrypted) throw new Error("Frozen provider request is missing");
16352
- const body = record3(JSON.parse(decryptEnvironmentValue2(key, operation.providerRequestEncrypted)));
17063
+ const body = record4(JSON.parse(decryptEnvironmentValue2(key, operation.providerRequestEncrypted)));
16353
17064
  if (!body || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) {
16354
17065
  throw new Error("Frozen provider request is malformed");
16355
17066
  }
@@ -16478,7 +17189,7 @@ function isPermanentProviderFailure(error) {
16478
17189
  function privateError(error) {
16479
17190
  return (error instanceof Error ? `${error.name}: ${error.message}` : String(error)).replace(/https?:\/\/\S+/gu, "[url omitted]").slice(0, RECONCILE_ERROR_MAX);
16480
17191
  }
16481
- function record3(value) {
17192
+ function record4(value) {
16482
17193
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
16483
17194
  }
16484
17195
  function isTerminal(status) {
@@ -16529,4 +17240,4 @@ export {
16529
17240
  createTurnActivities,
16530
17241
  createTurnActivitiesFromServices
16531
17242
  };
16532
- //# sourceMappingURL=activities-turn-IDS3WEHA.js.map
17243
+ //# sourceMappingURL=activities-turn-J5YO7XXX.js.map