@opengeni/worker-bundle 0.20.1 → 0.22.0-canary.0
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.
- package/dist/activities/agent-turn/admission.d.ts +52 -0
- package/dist/activities/agent-turn/agent-build.d.ts +89 -0
- package/dist/activities/agent-turn/claim.d.ts +67 -0
- package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
- package/dist/activities/agent-turn/codex.d.ts +32 -0
- package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
- package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
- package/dist/activities/agent-turn/errors.d.ts +253 -0
- package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
- package/dist/activities/agent-turn/file-resources.d.ts +37 -0
- package/dist/activities/agent-turn/finalization.d.ts +42 -0
- package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
- package/dist/activities/agent-turn/governance-model.d.ts +66 -0
- package/dist/activities/agent-turn/history-sink.d.ts +52 -0
- package/dist/activities/agent-turn/history.d.ts +63 -0
- package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
- package/dist/activities/agent-turn/model-usage.d.ts +218 -0
- package/dist/activities/agent-turn/quiescence.d.ts +135 -0
- package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
- package/dist/activities/agent-turn/run.d.ts +3 -0
- package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
- package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
- package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
- package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
- package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
- package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
- package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
- package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
- package/dist/activities/agent-turn/turn-context.d.ts +144 -0
- package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
- package/dist/activities/agent-turn.d.ts +12 -954
- package/dist/activities/automations.d.ts +16 -0
- package/dist/activities/common.d.ts +1 -1
- package/dist/activities/connector-attachments.d.ts +13 -0
- package/dist/activities/documents.d.ts +1 -0
- package/dist/activities/environment.d.ts +26 -15
- package/dist/activities/generated-images.d.ts +1 -1
- package/dist/activities/git-credential-renewal.d.ts +3 -1
- package/dist/activities/goals.d.ts +4 -1
- package/dist/activities/google-drive-provider.d.ts +29 -0
- package/dist/activities/google-drive-publication.d.ts +66 -0
- package/dist/activities/image-generation-references.d.ts +2 -0
- package/dist/activities/incident-telemetry-authority.d.ts +52 -0
- package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
- package/dist/activities/knowledge-source-sync-driver.d.ts +21 -0
- package/dist/activities/knowledge-source-sync.d.ts +33 -1
- package/dist/activities/mcp-credentials.d.ts +9 -3
- package/dist/activities/open-suffix-resume.d.ts +77 -0
- package/dist/activities/packs.d.ts +3 -11
- package/dist/activities/parent-wake.d.ts +19 -0
- package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
- package/dist/activities/retained-screenshots.d.ts +1 -1
- package/dist/activities/rig-verification.d.ts +1 -1
- package/dist/activities/run-input.d.ts +16 -7
- package/dist/activities/sandbox-images.d.ts +1 -14
- package/dist/activities/sandbox-lease.d.ts +21 -3
- package/dist/activities/scheduled-tasks.d.ts +47 -0
- package/dist/activities/types.d.ts +23 -2
- package/dist/activities/video-media-validation.d.ts +1 -1
- package/dist/activities/video-output-retention.d.ts +1 -2
- package/dist/activities/xai-auth.d.ts +3 -0
- package/dist/{activities-control-SMKF2OBE.js → activities-control-DKG22ONJ.js} +2946 -549
- package/dist/activities-control-DKG22ONJ.js.map +1 -0
- package/dist/activities-control.d.ts +6 -2
- package/dist/activities-turn-4IMC3MAA.js +21326 -0
- package/dist/activities-turn-4IMC3MAA.js.map +1 -0
- package/dist/activities.d.ts +7 -3
- package/dist/artifact-materializer-entry.js +41 -22
- package/dist/artifact-materializer-entry.js.map +1 -1
- package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
- package/dist/chunk-CE7TPKBS.js.map +1 -0
- package/dist/chunk-CNYGVRKF.js +4698 -0
- package/dist/chunk-CNYGVRKF.js.map +1 -0
- package/dist/connection-provider-use.d.ts +18 -0
- package/dist/editable-artifact-materializer.d.ts +4 -3
- package/dist/github-rest-mcp.d.ts +26 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.js +58 -14
- package/dist/index.js.map +1 -1
- package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
- package/dist/model-context-contributions.d.ts +8 -4
- package/dist/observability-metrics.d.ts +63 -4
- package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
- package/dist/personal-github-git-credentials.d.ts +9 -0
- package/dist/pr-review-credentials.d.ts +6 -0
- package/dist/sandbox-archive-storage.d.ts +45 -0
- package/dist/sandbox-resume.d.ts +65 -6
- package/dist/sandbox-routing.d.ts +38 -2
- package/dist/scheduled-alert-occurrence.d.ts +33 -0
- package/dist/workflow-bundle.js +87 -28
- package/dist/workflows/activities.d.ts +1 -0
- package/dist/workflows/automations.d.ts +6 -0
- package/dist/workflows/document-index.d.ts +1 -0
- package/dist/workflows.d.ts +1 -0
- package/package.json +17 -17
- package/src/activities/agent-turn/admission.ts +292 -0
- package/src/activities/agent-turn/agent-build.ts +802 -0
- package/src/activities/agent-turn/claim.ts +590 -0
- package/src/activities/agent-turn/codex-capacity.ts +720 -0
- package/src/activities/agent-turn/codex.ts +94 -0
- package/src/activities/agent-turn/compaction-prep.ts +722 -0
- package/src/activities/agent-turn/credential-leases.ts +240 -0
- package/src/activities/agent-turn/errors.ts +1068 -0
- package/src/activities/agent-turn/failure-settlement.ts +1436 -0
- package/src/activities/agent-turn/file-resources.ts +227 -0
- package/src/activities/agent-turn/finalization.ts +754 -0
- package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
- package/src/activities/agent-turn/governance-model.ts +465 -0
- package/src/activities/agent-turn/history-sink.ts +139 -0
- package/src/activities/agent-turn/history.ts +200 -0
- package/src/activities/agent-turn/media-artifacts.ts +359 -0
- package/src/activities/agent-turn/model-usage.ts +823 -0
- package/src/activities/agent-turn/quiescence.ts +353 -0
- package/src/activities/agent-turn/run-credentials.ts +761 -0
- package/src/activities/agent-turn/run.ts +1530 -0
- package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
- package/src/activities/agent-turn/sandbox-provision.ts +569 -0
- package/src/activities/agent-turn/sandbox-route.ts +358 -0
- package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
- package/src/activities/agent-turn/stream-attempt.ts +1670 -0
- package/src/activities/agent-turn/tool-environment.ts +729 -0
- package/src/activities/agent-turn/tool-policy.ts +216 -0
- package/src/activities/agent-turn/tool-result-spill.ts +265 -0
- package/src/activities/agent-turn/turn-context.ts +281 -0
- package/src/activities/agent-turn/xai-capacity.ts +229 -0
- package/src/activities/agent-turn.ts +12 -12575
- package/src/activities/api-integrations.ts +3 -0
- package/src/activities/automations.ts +214 -0
- package/src/activities/codemode-dispatcher.ts +12 -1
- package/src/activities/common.ts +1 -5
- package/src/activities/connector-attachments.ts +168 -0
- package/src/activities/context-compaction.ts +18 -0
- package/src/activities/documents.ts +6 -4
- package/src/activities/environment.ts +151 -55
- package/src/activities/generated-images.ts +26 -11
- package/src/activities/git-credential-renewal.ts +13 -3
- package/src/activities/goals.ts +85 -19
- package/src/activities/google-drive-provider.ts +178 -0
- package/src/activities/google-drive-publication.ts +938 -0
- package/src/activities/image-generation-references.ts +11 -2
- package/src/activities/incident-telemetry-authority.ts +327 -0
- package/src/activities/incident-telemetry-preflight.ts +317 -0
- package/src/activities/knowledge-source-sync-driver.ts +23 -0
- package/src/activities/knowledge-source-sync.ts +556 -40
- package/src/activities/mcp-credentials.ts +191 -17
- package/src/activities/open-suffix-resume.ts +422 -0
- package/src/activities/packs.ts +12 -60
- package/src/activities/parent-wake.ts +64 -14
- package/src/activities/retained-screenshot-reaper.ts +6 -3
- package/src/activities/retained-screenshots.ts +15 -47
- package/src/activities/rig-verification.ts +1 -1
- package/src/activities/run-input.ts +128 -136
- package/src/activities/sandbox-images.ts +7 -166
- package/src/activities/sandbox-lease.ts +406 -15
- package/src/activities/scheduled-tasks.ts +2103 -411
- package/src/activities/session-state.ts +10 -2
- package/src/activities/types.ts +32 -2
- package/src/activities/video-media-validation.ts +3 -3
- package/src/activities/video-output-retention.ts +2 -57
- package/src/activities/xai-auth.ts +8 -0
- package/src/activities-control.ts +2 -0
- package/src/activities.ts +3 -0
- package/src/activity-services.ts +13 -4
- package/src/connection-provider-use.ts +36 -0
- package/src/editable-artifact-materializer-subprocess.ts +25 -14
- package/src/editable-artifact-materializer.ts +29 -18
- package/src/github-rest-mcp.ts +713 -0
- package/src/http.ts +16 -6
- package/src/index.ts +40 -5
- package/src/knowledge-source-sync-activity-policy.ts +2 -0
- package/src/model-context-contributions.ts +33 -10
- package/src/observability-metrics.ts +357 -0
- package/src/opensandbox-kubernetes-inventory.ts +292 -0
- package/src/personal-github-git-credentials.ts +331 -0
- package/src/pr-review-credentials.ts +163 -0
- package/src/sandbox-archive-storage.ts +159 -0
- package/src/sandbox-resume.ts +449 -63
- package/src/sandbox-routing.ts +314 -16
- package/src/scheduled-alert-occurrence.ts +176 -0
- package/src/workflows/activities.ts +18 -2
- package/src/workflows/automations.ts +11 -0
- package/src/workflows/session.ts +13 -3
- package/src/workflows.ts +1 -0
- package/dist/activities-control-SMKF2OBE.js.map +0 -1
- package/dist/activities-turn-IDS3WEHA.js +0 -16532
- package/dist/activities-turn-IDS3WEHA.js.map +0 -1
- package/dist/chunk-N5TJIFCE.js.map +0 -1
- package/dist/chunk-P6Z2SLAA.js +0 -3092
- package/dist/chunk-P6Z2SLAA.js.map +0 -1
|
@@ -0,0 +1,938 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { AttemptToolApprovalRequiredError, type AttemptToolDefinition } from "@opengeni/codemode";
|
|
3
|
+
import type { McpPersonalConnectionDelegation } from "@opengeni/contracts";
|
|
4
|
+
import {
|
|
5
|
+
GOOGLE_DRIVE_FILE_SCOPE,
|
|
6
|
+
GOOGLE_DRIVE_FULL_SCOPE,
|
|
7
|
+
GOOGLE_DRIVE_PUBLICATION_CREATE_ACTION,
|
|
8
|
+
GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
|
|
9
|
+
GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
|
|
10
|
+
GOOGLE_DRIVE_PROVIDER_DOMAIN,
|
|
11
|
+
GoogleDriveConnectionMetadata,
|
|
12
|
+
GoogleDrivePublicationReceipt,
|
|
13
|
+
GoogleDrivePublicationToolInput,
|
|
14
|
+
googleDriveScopesAllowCapability,
|
|
15
|
+
type GoogleDriveOutputDestination,
|
|
16
|
+
type GoogleDrivePublicationReceipt as GoogleDrivePublicationReceiptValue,
|
|
17
|
+
type GoogleDrivePublicationToolInput as GoogleDrivePublicationToolInputValue,
|
|
18
|
+
} from "@opengeni/contracts/google-drive";
|
|
19
|
+
import {
|
|
20
|
+
beginConnectorActionExecution,
|
|
21
|
+
completeConnectorActionExecution,
|
|
22
|
+
getConnectionMetadata,
|
|
23
|
+
prepareConnectorActionApproval,
|
|
24
|
+
requireFile,
|
|
25
|
+
namedSubjectHasLiveWorkspaceAuthority,
|
|
26
|
+
type ConnectorActionAttemptIdentity,
|
|
27
|
+
type ConnectorActionInvocation,
|
|
28
|
+
type Database,
|
|
29
|
+
type ResolveConnectionCredentialInput,
|
|
30
|
+
type ResolveConnectionCredentialResult,
|
|
31
|
+
} from "@opengeni/db";
|
|
32
|
+
import {
|
|
33
|
+
readAuthorizedEditableArtifactMaterialization,
|
|
34
|
+
type PersistedEditableArtifactMaterializationJob,
|
|
35
|
+
} from "@opengeni/db/editable-artifact-durable-export";
|
|
36
|
+
import { readResponseJsonBounded, undiciFetch, type FetchLike } from "@opengeni/network";
|
|
37
|
+
import { retryWhileMissing, type ObjectStorage } from "@opengeni/storage";
|
|
38
|
+
|
|
39
|
+
const DRIVE_API = "https://www.googleapis.com/drive/v3";
|
|
40
|
+
const DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3";
|
|
41
|
+
const DRIVE_FOLDER_MIME = "application/vnd.google-apps.folder";
|
|
42
|
+
const RESPONSE_MAX_BYTES = 256 * 1024;
|
|
43
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
44
|
+
const FIRST_PARTY_MCP_SUBJECT_ID = "worker:first-party-mcp";
|
|
45
|
+
const 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;
|
|
46
|
+
|
|
47
|
+
class GoogleDrivePublicationAuthorizationError extends Error {}
|
|
48
|
+
|
|
49
|
+
export type GoogleDrivePublicationTarget = Readonly<{
|
|
50
|
+
ownerSubjectId: string;
|
|
51
|
+
connectionId: string;
|
|
52
|
+
originWorkspaceId: string;
|
|
53
|
+
destination: GoogleDriveOutputDestination;
|
|
54
|
+
credentialScope: typeof GOOGLE_DRIVE_FILE_SCOPE | typeof GOOGLE_DRIVE_FULL_SCOPE;
|
|
55
|
+
}>;
|
|
56
|
+
|
|
57
|
+
export type GoogleDrivePublicationPorts = {
|
|
58
|
+
getConnection: typeof getConnectionMetadata;
|
|
59
|
+
/**
|
|
60
|
+
* Live workspace authority for the frozen delegation owner. This must be the
|
|
61
|
+
* canonical resolver, not a bare `workspace_memberships` join: a managed
|
|
62
|
+
* human's personal workspace deliberately has no membership row (migration
|
|
63
|
+
* 0219), so a bare join denies the owner publication inside their own
|
|
64
|
+
* private workspace.
|
|
65
|
+
*/
|
|
66
|
+
getMembership: typeof namedSubjectHasLiveWorkspaceAuthority;
|
|
67
|
+
readMaterialization: typeof readAuthorizedEditableArtifactMaterialization;
|
|
68
|
+
requireFile: typeof requireFile;
|
|
69
|
+
prepare: typeof prepareConnectorActionApproval;
|
|
70
|
+
begin: typeof beginConnectorActionExecution;
|
|
71
|
+
complete: typeof completeConnectorActionExecution;
|
|
72
|
+
fetch: FetchLike;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const defaultPorts: GoogleDrivePublicationPorts = {
|
|
76
|
+
getConnection: getConnectionMetadata,
|
|
77
|
+
getMembership: namedSubjectHasLiveWorkspaceAuthority,
|
|
78
|
+
readMaterialization: readAuthorizedEditableArtifactMaterialization,
|
|
79
|
+
requireFile,
|
|
80
|
+
prepare: prepareConnectorActionApproval,
|
|
81
|
+
begin: beginConnectorActionExecution,
|
|
82
|
+
complete: completeConnectorActionExecution,
|
|
83
|
+
fetch: undiciFetch,
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export async function resolveGoogleDrivePublicationTarget(
|
|
87
|
+
db: Database,
|
|
88
|
+
workspace: { accountId: string; workspaceId: string },
|
|
89
|
+
delegations: readonly McpPersonalConnectionDelegation[],
|
|
90
|
+
ports: Pick<GoogleDrivePublicationPorts, "getConnection" | "getMembership"> = defaultPorts,
|
|
91
|
+
): Promise<GoogleDrivePublicationTarget | null> {
|
|
92
|
+
const { workspaceId } = workspace;
|
|
93
|
+
const frozen = delegations.filter(
|
|
94
|
+
(delegation) =>
|
|
95
|
+
delegation.serverId === GOOGLE_DRIVE_PUBLICATION_SERVER_ID &&
|
|
96
|
+
delegation.providerDomain.toLowerCase() === GOOGLE_DRIVE_PROVIDER_DOMAIN &&
|
|
97
|
+
delegation.kind === "oauth2",
|
|
98
|
+
);
|
|
99
|
+
if (frozen.length !== 1) return null;
|
|
100
|
+
const delegation = frozen[0]!;
|
|
101
|
+
const activated = delegation.userDelegation !== undefined;
|
|
102
|
+
if (
|
|
103
|
+
!activated &&
|
|
104
|
+
!(await ports.getMembership(db, {
|
|
105
|
+
accountId: workspace.accountId,
|
|
106
|
+
workspaceId,
|
|
107
|
+
subjectId: delegation.ownerSubjectId,
|
|
108
|
+
}))
|
|
109
|
+
) {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
const originWorkspaceId = activated ? delegation.originWorkspaceId : workspaceId;
|
|
113
|
+
if (!originWorkspaceId) return null;
|
|
114
|
+
const connection = await ports.getConnection(
|
|
115
|
+
db,
|
|
116
|
+
originWorkspaceId,
|
|
117
|
+
delegation.connectionId,
|
|
118
|
+
delegation.ownerSubjectId,
|
|
119
|
+
);
|
|
120
|
+
if (
|
|
121
|
+
!connection ||
|
|
122
|
+
connection.id !== delegation.connectionId ||
|
|
123
|
+
connection.workspaceId !== originWorkspaceId ||
|
|
124
|
+
connection.subjectId !== delegation.ownerSubjectId ||
|
|
125
|
+
connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN ||
|
|
126
|
+
connection.kind !== "oauth2" ||
|
|
127
|
+
connection.status !== "active" ||
|
|
128
|
+
!googleDriveScopesAllowCapability(connection.grantedScopes, "publish_file")
|
|
129
|
+
) {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
const metadata = GoogleDriveConnectionMetadata.safeParse(connection.metadata);
|
|
133
|
+
if (
|
|
134
|
+
!metadata.success ||
|
|
135
|
+
!metadata.data.outputDestination ||
|
|
136
|
+
metadata.data.lifecycle?.state === "paused" ||
|
|
137
|
+
(metadata.data.lifecycle && metadata.data.lifecycle.state !== "active")
|
|
138
|
+
) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
// The destination frozen on the accepted delegation is the authority. A
|
|
142
|
+
// live connection-settings change since acceptance fails the target closed
|
|
143
|
+
// (personal-authority warning path) instead of silently redirecting the
|
|
144
|
+
// publication; a pre-freeze delegation keeps the bounded legacy
|
|
145
|
+
// live-resolution behavior.
|
|
146
|
+
const frozenDestination = delegation.outputDestination;
|
|
147
|
+
if (frozenDestination && !sameDestination(metadata.data.outputDestination, frozenDestination)) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
return Object.freeze({
|
|
151
|
+
ownerSubjectId: delegation.ownerSubjectId,
|
|
152
|
+
connectionId: connection.id,
|
|
153
|
+
originWorkspaceId,
|
|
154
|
+
destination: frozenDestination ?? metadata.data.outputDestination,
|
|
155
|
+
credentialScope: connection.grantedScopes.includes(GOOGLE_DRIVE_FILE_SCOPE)
|
|
156
|
+
? GOOGLE_DRIVE_FILE_SCOPE
|
|
157
|
+
: GOOGLE_DRIVE_FULL_SCOPE,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function googleDrivePublicationConnectorCall(
|
|
162
|
+
target: GoogleDrivePublicationTarget,
|
|
163
|
+
rawRequest: unknown,
|
|
164
|
+
approvalId: string,
|
|
165
|
+
): ConnectorActionInvocation {
|
|
166
|
+
const request = GoogleDrivePublicationToolInput.parse(rawRequest);
|
|
167
|
+
return {
|
|
168
|
+
approvalId,
|
|
169
|
+
connectionId: target.connectionId,
|
|
170
|
+
serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
|
|
171
|
+
toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
|
|
172
|
+
arguments: {
|
|
173
|
+
action: GOOGLE_DRIVE_PUBLICATION_CREATE_ACTION,
|
|
174
|
+
destination: target.destination,
|
|
175
|
+
artifact: {
|
|
176
|
+
id: request.file.artifactId,
|
|
177
|
+
versionId: request.file.versionId,
|
|
178
|
+
title: request.title,
|
|
179
|
+
modality: request.modality,
|
|
180
|
+
sourceSha256: request.file.sha256,
|
|
181
|
+
},
|
|
182
|
+
canonicalReceipt: { ...request.file },
|
|
183
|
+
idempotencyKeyDigest: createHash("sha256")
|
|
184
|
+
.update(request.idempotencyKey, "utf8")
|
|
185
|
+
.digest("hex"),
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function createGoogleDrivePublicationAttemptTool(input: {
|
|
191
|
+
db: Database;
|
|
192
|
+
objectStorage: ObjectStorage;
|
|
193
|
+
identity: ConnectorActionAttemptIdentity;
|
|
194
|
+
subjectId: string;
|
|
195
|
+
target: GoogleDrivePublicationTarget;
|
|
196
|
+
resolveCredential: (
|
|
197
|
+
input: ResolveConnectionCredentialInput,
|
|
198
|
+
) => Promise<ResolveConnectionCredentialResult>;
|
|
199
|
+
signal?: AbortSignal;
|
|
200
|
+
ports?: GoogleDrivePublicationPorts;
|
|
201
|
+
}): AttemptToolDefinition {
|
|
202
|
+
const ports = input.ports ?? defaultPorts;
|
|
203
|
+
return {
|
|
204
|
+
identity: {
|
|
205
|
+
serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
|
|
206
|
+
toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
|
|
207
|
+
},
|
|
208
|
+
modelName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
|
|
209
|
+
codemodePath: ["google_drive", "publish_file"],
|
|
210
|
+
title: "Publish artifact to Google Drive",
|
|
211
|
+
description:
|
|
212
|
+
"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.",
|
|
213
|
+
inputSchema: {
|
|
214
|
+
type: "object",
|
|
215
|
+
properties: {
|
|
216
|
+
title: { type: "string", minLength: 1, maxLength: 512 },
|
|
217
|
+
modality: {
|
|
218
|
+
type: "string",
|
|
219
|
+
enum: ["document", "spreadsheet", "presentation"],
|
|
220
|
+
},
|
|
221
|
+
file: {
|
|
222
|
+
type: "object",
|
|
223
|
+
properties: {
|
|
224
|
+
fileId: { type: "string", format: "uuid" },
|
|
225
|
+
filename: { type: "string", minLength: 1, maxLength: 512 },
|
|
226
|
+
contentType: { type: "string", minLength: 1, maxLength: 256 },
|
|
227
|
+
sizeBytes: { type: "integer", minimum: 1 },
|
|
228
|
+
sha256: { type: "string", pattern: "^[0-9a-f]{64}$" },
|
|
229
|
+
artifactId: { type: "string", pattern: "^[0-9a-f]{32}$" },
|
|
230
|
+
versionId: { type: "string", pattern: "^[0-9a-f]{32}$" },
|
|
231
|
+
materializationJobId: { type: "string", pattern: "^[0-9a-f]{32}$" },
|
|
232
|
+
sourceHeadSequence: { type: "integer", minimum: 0 },
|
|
233
|
+
sourceStateHash: {
|
|
234
|
+
type: "string",
|
|
235
|
+
pattern: "^sha256:[0-9a-f]{64}$",
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
required: [
|
|
239
|
+
"fileId",
|
|
240
|
+
"filename",
|
|
241
|
+
"contentType",
|
|
242
|
+
"sizeBytes",
|
|
243
|
+
"sha256",
|
|
244
|
+
"artifactId",
|
|
245
|
+
"versionId",
|
|
246
|
+
"materializationJobId",
|
|
247
|
+
"sourceHeadSequence",
|
|
248
|
+
"sourceStateHash",
|
|
249
|
+
],
|
|
250
|
+
additionalProperties: false,
|
|
251
|
+
},
|
|
252
|
+
idempotencyKey: { type: "string", minLength: 1, maxLength: 200 },
|
|
253
|
+
},
|
|
254
|
+
required: ["title", "modality", "file", "idempotencyKey"],
|
|
255
|
+
additionalProperties: false,
|
|
256
|
+
},
|
|
257
|
+
outputSchema: {
|
|
258
|
+
type: "object",
|
|
259
|
+
properties: {
|
|
260
|
+
connectionId: { type: "string", format: "uuid" },
|
|
261
|
+
providerFileId: { type: "string" },
|
|
262
|
+
webViewLink: { type: "string", format: "uri" },
|
|
263
|
+
mimeType: {
|
|
264
|
+
type: "string",
|
|
265
|
+
enum: [
|
|
266
|
+
"application/vnd.google-apps.document",
|
|
267
|
+
"application/vnd.google-apps.spreadsheet",
|
|
268
|
+
"application/vnd.google-apps.presentation",
|
|
269
|
+
],
|
|
270
|
+
},
|
|
271
|
+
destination: {
|
|
272
|
+
type: "object",
|
|
273
|
+
properties: {
|
|
274
|
+
folderId: { type: "string" },
|
|
275
|
+
folderName: { type: "string" },
|
|
276
|
+
driveId: { type: ["string", "null"] },
|
|
277
|
+
location: { type: "string", enum: ["my_drive", "shared_drive"] },
|
|
278
|
+
selectedAt: { type: "string" },
|
|
279
|
+
},
|
|
280
|
+
required: ["folderId", "folderName", "driveId", "location", "selectedAt"],
|
|
281
|
+
additionalProperties: false,
|
|
282
|
+
},
|
|
283
|
+
replayed: { type: "boolean" },
|
|
284
|
+
},
|
|
285
|
+
required: [
|
|
286
|
+
"connectionId",
|
|
287
|
+
"providerFileId",
|
|
288
|
+
"webViewLink",
|
|
289
|
+
"mimeType",
|
|
290
|
+
"destination",
|
|
291
|
+
"replayed",
|
|
292
|
+
],
|
|
293
|
+
additionalProperties: false,
|
|
294
|
+
},
|
|
295
|
+
annotations: {
|
|
296
|
+
title: "Publish artifact to Google Drive",
|
|
297
|
+
readOnlyHint: false,
|
|
298
|
+
destructiveHint: false,
|
|
299
|
+
idempotentHint: true,
|
|
300
|
+
openWorldHint: true,
|
|
301
|
+
},
|
|
302
|
+
source: "mcp",
|
|
303
|
+
approval: "policy",
|
|
304
|
+
execute: async (raw, context) => {
|
|
305
|
+
const request = GoogleDrivePublicationToolInput.parse(raw);
|
|
306
|
+
const connectorCall = googleDrivePublicationConnectorCall(
|
|
307
|
+
input.target,
|
|
308
|
+
request,
|
|
309
|
+
context.operationId,
|
|
310
|
+
);
|
|
311
|
+
// Every caller is behind exactly one durable execute-once fence. Model
|
|
312
|
+
// callers arrive through the attempt connector-action wrapper, which has
|
|
313
|
+
// already registered this call under its durable SDK call id and moved
|
|
314
|
+
// the approved row to executing - a second inner begin here would mint a
|
|
315
|
+
// second row under an unrelated operation id and deadlock the default
|
|
316
|
+
// ask policy. Codemode callers bypass that wrapper, so the tool
|
|
317
|
+
// registers the fence itself with the shared Codemode operation id.
|
|
318
|
+
let requestId: string | null = null;
|
|
319
|
+
if (context.caller.kind === "codemode") {
|
|
320
|
+
const admission = await ports.begin(input.db, input.identity, connectorCall);
|
|
321
|
+
if (!admission.allowed) {
|
|
322
|
+
throw new Error(
|
|
323
|
+
admission.reason === "uncertain_retry" || admission.reason === "already_executed"
|
|
324
|
+
? "Google Drive publication outcome is unknown: a previous attempt may have already sent this publication to Google Drive. Verify in Drive before retrying with a new idempotency key."
|
|
325
|
+
: admission.reason === "not_executed"
|
|
326
|
+
? "Google Drive publication was not executed: the previous attempt failed before any request reached Google Drive. Retrying with a new call is safe."
|
|
327
|
+
: `Google Drive publication was not executed: ${admission.reason}. No request reached Google Drive.`,
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
if (!admission.managed) {
|
|
331
|
+
throw new Error("Google Drive publication has no explicit connector action policy");
|
|
332
|
+
}
|
|
333
|
+
requestId = admission.requestId;
|
|
334
|
+
}
|
|
335
|
+
let providerRequestStarted = false;
|
|
336
|
+
try {
|
|
337
|
+
const receipt = await executeGoogleDrivePublication(
|
|
338
|
+
{
|
|
339
|
+
db: input.db,
|
|
340
|
+
objectStorage: input.objectStorage,
|
|
341
|
+
identity: input.identity,
|
|
342
|
+
subjectId: input.subjectId,
|
|
343
|
+
target: input.target,
|
|
344
|
+
request,
|
|
345
|
+
resolveCredential: input.resolveCredential,
|
|
346
|
+
onProviderRequest: () => {
|
|
347
|
+
providerRequestStarted = true;
|
|
348
|
+
},
|
|
349
|
+
...((context.signal ?? input.signal) ? { signal: context.signal ?? input.signal } : {}),
|
|
350
|
+
},
|
|
351
|
+
ports,
|
|
352
|
+
);
|
|
353
|
+
if (requestId) {
|
|
354
|
+
await ports.complete(input.db, {
|
|
355
|
+
accountId: input.identity.accountId,
|
|
356
|
+
workspaceId: input.identity.workspaceId,
|
|
357
|
+
requestId,
|
|
358
|
+
attemptId: input.identity.attemptId,
|
|
359
|
+
outcome: "completed",
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
content: [{ type: "text", text: JSON.stringify(receipt) }],
|
|
364
|
+
structuredContent: receipt,
|
|
365
|
+
};
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (requestId) {
|
|
368
|
+
await ports.complete(input.db, {
|
|
369
|
+
accountId: input.identity.accountId,
|
|
370
|
+
workspaceId: input.identity.workspaceId,
|
|
371
|
+
requestId,
|
|
372
|
+
attemptId: input.identity.attemptId,
|
|
373
|
+
outcome: providerRequestStarted ? "uncertain" : "not_executed",
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
377
|
+
throw new Error(
|
|
378
|
+
providerRequestStarted
|
|
379
|
+
? `Google Drive publication outcome is unknown: a provider request may have been sent before the failure. Verify in Drive before retrying. Cause: ${detail}`
|
|
380
|
+
: `Google Drive publication was not executed: no request reached Google Drive. Cause: ${detail}`,
|
|
381
|
+
{ cause: error },
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
},
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export async function authorizeGoogleDrivePublicationAttempt(input: {
|
|
389
|
+
db: Database;
|
|
390
|
+
identity: ConnectorActionAttemptIdentity;
|
|
391
|
+
target: GoogleDrivePublicationTarget;
|
|
392
|
+
approvalId: string;
|
|
393
|
+
arguments: unknown;
|
|
394
|
+
ports?: Pick<GoogleDrivePublicationPorts, "prepare">;
|
|
395
|
+
}): Promise<void> {
|
|
396
|
+
const request = GoogleDrivePublicationToolInput.parse(input.arguments);
|
|
397
|
+
const preparation = await (input.ports ?? defaultPorts).prepare(
|
|
398
|
+
input.db,
|
|
399
|
+
input.identity,
|
|
400
|
+
googleDrivePublicationConnectorCall(input.target, request, input.approvalId),
|
|
401
|
+
);
|
|
402
|
+
if (!preparation.managed) {
|
|
403
|
+
throw new Error("Google Drive publication has no explicit connector action policy");
|
|
404
|
+
}
|
|
405
|
+
if (preparation.decision === "ask") throw new AttemptToolApprovalRequiredError();
|
|
406
|
+
if (preparation.decision === "block") {
|
|
407
|
+
throw new Error("Google Drive publication is blocked by connector action policy");
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export async function executeGoogleDrivePublication(
|
|
412
|
+
input: {
|
|
413
|
+
db: Database;
|
|
414
|
+
objectStorage: ObjectStorage;
|
|
415
|
+
identity: ConnectorActionAttemptIdentity;
|
|
416
|
+
subjectId: string;
|
|
417
|
+
target: GoogleDrivePublicationTarget;
|
|
418
|
+
request: GoogleDrivePublicationToolInputValue;
|
|
419
|
+
resolveCredential: (
|
|
420
|
+
input: ResolveConnectionCredentialInput,
|
|
421
|
+
) => Promise<ResolveConnectionCredentialResult>;
|
|
422
|
+
signal?: AbortSignal;
|
|
423
|
+
/** Invoked immediately before the first provider request is sent. */
|
|
424
|
+
onProviderRequest?: () => void;
|
|
425
|
+
},
|
|
426
|
+
ports: Pick<
|
|
427
|
+
GoogleDrivePublicationPorts,
|
|
428
|
+
"getConnection" | "readMaterialization" | "requireFile" | "fetch"
|
|
429
|
+
> = defaultPorts,
|
|
430
|
+
): Promise<GoogleDrivePublicationReceiptValue> {
|
|
431
|
+
const request = GoogleDrivePublicationToolInput.parse(input.request);
|
|
432
|
+
const connection = await ports.getConnection(
|
|
433
|
+
input.db,
|
|
434
|
+
input.target.originWorkspaceId,
|
|
435
|
+
input.target.connectionId,
|
|
436
|
+
input.subjectId,
|
|
437
|
+
);
|
|
438
|
+
if (!connection || connection.subjectId !== input.subjectId) {
|
|
439
|
+
throw new Error("Google Drive publication connection is unavailable");
|
|
440
|
+
}
|
|
441
|
+
assertPublicationConnection(input, connection);
|
|
442
|
+
const materialization = await ports.readMaterialization(input.db, {
|
|
443
|
+
scope: {
|
|
444
|
+
accountId: input.identity.accountId,
|
|
445
|
+
workspaceId: input.identity.workspaceId,
|
|
446
|
+
},
|
|
447
|
+
artifactId: request.file.artifactId,
|
|
448
|
+
jobId: request.file.materializationJobId,
|
|
449
|
+
actor: {
|
|
450
|
+
kind: "agent",
|
|
451
|
+
subjectId: FIRST_PARTY_MCP_SUBJECT_ID,
|
|
452
|
+
replicaId: publicationActorReplicaId(input.identity),
|
|
453
|
+
sessionId: input.identity.sessionId,
|
|
454
|
+
turnId: input.identity.turnId,
|
|
455
|
+
attemptId: input.identity.attemptId,
|
|
456
|
+
generation: input.identity.executionGeneration,
|
|
457
|
+
},
|
|
458
|
+
});
|
|
459
|
+
assertCanonicalMaterialization(input.identity, request, materialization);
|
|
460
|
+
const expected = expectedExportWorkspaceFile(input.identity.workspaceId, request);
|
|
461
|
+
if (request.file.fileId !== expected.fileId) {
|
|
462
|
+
throw new Error("Google Drive publication requires a canonical editable-artifact export file");
|
|
463
|
+
}
|
|
464
|
+
const sourceFile = await ports.requireFile(
|
|
465
|
+
input.db,
|
|
466
|
+
input.identity.workspaceId,
|
|
467
|
+
request.file.fileId,
|
|
468
|
+
);
|
|
469
|
+
if (
|
|
470
|
+
sourceFile.status !== "ready" ||
|
|
471
|
+
sourceFile.id !== expected.fileId ||
|
|
472
|
+
sourceFile.safeFilename !== expected.safeFilename ||
|
|
473
|
+
sourceFile.objectKey !== expected.objectKey ||
|
|
474
|
+
sourceFile.filename !== request.file.filename ||
|
|
475
|
+
sourceFile.contentType !== request.file.contentType ||
|
|
476
|
+
sourceFile.sizeBytes !== request.file.sizeBytes ||
|
|
477
|
+
sourceFile.sha256 !== request.file.sha256
|
|
478
|
+
) {
|
|
479
|
+
throw new Error("Editable artifact export file differs from its canonical receipt");
|
|
480
|
+
}
|
|
481
|
+
const object = await retryWhileMissing(async () =>
|
|
482
|
+
input.objectStorage.getObjectBytes(sourceFile.objectKey),
|
|
483
|
+
);
|
|
484
|
+
if (!object) throw new Error("Editable artifact export object is missing");
|
|
485
|
+
const bytes = object.bytes;
|
|
486
|
+
if (
|
|
487
|
+
bytes.byteLength !== request.file.sizeBytes ||
|
|
488
|
+
createHash("sha256").update(bytes).digest("hex") !== request.file.sha256
|
|
489
|
+
) {
|
|
490
|
+
throw new Error("Editable artifact export bytes failed verification");
|
|
491
|
+
}
|
|
492
|
+
const authorizedFetch: FetchLike = async (url, init) => {
|
|
493
|
+
const destinationUrl = url instanceof Request ? url.url : url.toString();
|
|
494
|
+
const credential = await input.resolveCredential({
|
|
495
|
+
workspaceId: input.identity.workspaceId,
|
|
496
|
+
subjectId: input.subjectId,
|
|
497
|
+
serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
|
|
498
|
+
toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
|
|
499
|
+
connectionRef: {
|
|
500
|
+
providerDomain: GOOGLE_DRIVE_PROVIDER_DOMAIN,
|
|
501
|
+
connectionId: input.target.connectionId,
|
|
502
|
+
kind: "oauth2",
|
|
503
|
+
subjectScope: "subject",
|
|
504
|
+
scopes: [input.target.credentialScope],
|
|
505
|
+
},
|
|
506
|
+
destinationUrl,
|
|
507
|
+
forceRefresh: false,
|
|
508
|
+
});
|
|
509
|
+
if (credential.status !== "ok" || credential.connectionId !== input.target.connectionId) {
|
|
510
|
+
throw new GoogleDrivePublicationAuthorizationError(
|
|
511
|
+
"Google Drive publication credential is unavailable",
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
const resolvedConnection = await ports.getConnection(
|
|
515
|
+
input.db,
|
|
516
|
+
input.target.originWorkspaceId,
|
|
517
|
+
input.target.connectionId,
|
|
518
|
+
input.subjectId,
|
|
519
|
+
);
|
|
520
|
+
if (!resolvedConnection) {
|
|
521
|
+
throw new GoogleDrivePublicationAuthorizationError(
|
|
522
|
+
"Google Drive publication authority changed; retry on a new turn",
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
try {
|
|
526
|
+
assertPublicationConnection(input, resolvedConnection);
|
|
527
|
+
} catch (error) {
|
|
528
|
+
throw new GoogleDrivePublicationAuthorizationError(
|
|
529
|
+
error instanceof Error ? error.message : "Google Drive publication authority changed",
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
if (credential.authorizeProviderRequest) {
|
|
533
|
+
let authorized = false;
|
|
534
|
+
try {
|
|
535
|
+
authorized = await credential.authorizeProviderRequest();
|
|
536
|
+
} catch {
|
|
537
|
+
authorized = false;
|
|
538
|
+
}
|
|
539
|
+
if (!authorized) {
|
|
540
|
+
throw new GoogleDrivePublicationAuthorizationError(
|
|
541
|
+
"Google Drive publication authority changed; retry on a new turn",
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
const headers = new Headers(credential.headers);
|
|
546
|
+
new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
|
|
547
|
+
// Only a mutating request can create the publication: read-only
|
|
548
|
+
// verify/lookup GETs stay retry-safe, while any later failure after the
|
|
549
|
+
// first mutation is an unknown outcome, never a safe retry.
|
|
550
|
+
const method = (init?.method ?? (url instanceof Request ? url.method : "GET")).toUpperCase();
|
|
551
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
552
|
+
input.onProviderRequest?.();
|
|
553
|
+
}
|
|
554
|
+
return await ports.fetch(url, { ...init, headers });
|
|
555
|
+
};
|
|
556
|
+
return await publishToGoogleDrive({
|
|
557
|
+
workspaceId: input.identity.workspaceId,
|
|
558
|
+
connectionId: input.target.connectionId,
|
|
559
|
+
destination: input.target.destination,
|
|
560
|
+
request,
|
|
561
|
+
bytes,
|
|
562
|
+
fetchImpl: authorizedFetch,
|
|
563
|
+
...(input.signal ? { signal: input.signal } : {}),
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function assertPublicationConnection(
|
|
568
|
+
input: { subjectId: string; target: GoogleDrivePublicationTarget },
|
|
569
|
+
connection: NonNullable<Awaited<ReturnType<typeof getConnectionMetadata>>>,
|
|
570
|
+
): void {
|
|
571
|
+
const metadata = GoogleDriveConnectionMetadata.parse(connection.metadata);
|
|
572
|
+
const credentialScope = connection.grantedScopes.includes(GOOGLE_DRIVE_FILE_SCOPE)
|
|
573
|
+
? GOOGLE_DRIVE_FILE_SCOPE
|
|
574
|
+
: GOOGLE_DRIVE_FULL_SCOPE;
|
|
575
|
+
if (
|
|
576
|
+
input.subjectId !== input.target.ownerSubjectId ||
|
|
577
|
+
connection.id !== input.target.connectionId ||
|
|
578
|
+
connection.workspaceId !== input.target.originWorkspaceId ||
|
|
579
|
+
connection.subjectId !== input.target.ownerSubjectId ||
|
|
580
|
+
connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN ||
|
|
581
|
+
connection.kind !== "oauth2" ||
|
|
582
|
+
connection.status !== "active" ||
|
|
583
|
+
metadata.lifecycle?.state === "paused" ||
|
|
584
|
+
(metadata.lifecycle && metadata.lifecycle.state !== "active") ||
|
|
585
|
+
!googleDriveScopesAllowCapability(connection.grantedScopes, "publish_file") ||
|
|
586
|
+
credentialScope !== input.target.credentialScope ||
|
|
587
|
+
!metadata.outputDestination ||
|
|
588
|
+
!sameDestination(metadata.outputDestination, input.target.destination)
|
|
589
|
+
) {
|
|
590
|
+
throw new Error("Google Drive publication authority changed; retry on a new turn");
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function publicationActorReplicaId(identity: ConnectorActionAttemptIdentity): string {
|
|
595
|
+
const value = createHash("sha256")
|
|
596
|
+
.update(
|
|
597
|
+
`google-drive-publication:${identity.sessionId}:${identity.turnId}:${identity.attemptId}:${identity.executionGeneration}`,
|
|
598
|
+
"utf8",
|
|
599
|
+
)
|
|
600
|
+
.digest("hex")
|
|
601
|
+
.slice(0, 16);
|
|
602
|
+
return /^0+$/u.test(value) ? `1${value.slice(1)}` : value;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function assertCanonicalMaterialization(
|
|
606
|
+
identity: ConnectorActionAttemptIdentity,
|
|
607
|
+
request: GoogleDrivePublicationToolInputValue,
|
|
608
|
+
job: PersistedEditableArtifactMaterializationJob | null,
|
|
609
|
+
): void {
|
|
610
|
+
const format = officeFormat(request.modality, request.file.contentType);
|
|
611
|
+
if (
|
|
612
|
+
!job ||
|
|
613
|
+
job.scope.accountId !== identity.accountId ||
|
|
614
|
+
job.scope.workspaceId !== identity.workspaceId ||
|
|
615
|
+
job.artifactId !== request.file.artifactId ||
|
|
616
|
+
job.id !== request.file.materializationJobId ||
|
|
617
|
+
job.versionId !== request.file.versionId ||
|
|
618
|
+
job.targetHeadSequence !== request.file.sourceHeadSequence ||
|
|
619
|
+
job.stateHash !== request.file.sourceStateHash ||
|
|
620
|
+
job.format !== format ||
|
|
621
|
+
job.state !== "succeeded" ||
|
|
622
|
+
!job.result ||
|
|
623
|
+
job.result.byteSize !== request.file.sizeBytes ||
|
|
624
|
+
job.result.mimeType !== request.file.contentType ||
|
|
625
|
+
job.result.contentHash !== `sha256:${request.file.sha256}`
|
|
626
|
+
) {
|
|
627
|
+
throw new Error("Google Drive publication receipt differs from its canonical materialization");
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function expectedExportWorkspaceFile(
|
|
632
|
+
workspaceId: string,
|
|
633
|
+
request: GoogleDrivePublicationToolInputValue,
|
|
634
|
+
): { fileId: string; safeFilename: string; objectKey: string } {
|
|
635
|
+
const format = officeFormat(request.modality, request.file.contentType);
|
|
636
|
+
const fileId = deterministicUuid(
|
|
637
|
+
`editable-artifact-export:file:${workspaceId}:${request.file.artifactId}:${request.file.versionId}:${request.file.materializationJobId}`,
|
|
638
|
+
);
|
|
639
|
+
const safeFilename = `artifact-${request.file.artifactId}-${request.file.materializationJobId}.${format}`;
|
|
640
|
+
return {
|
|
641
|
+
fileId,
|
|
642
|
+
safeFilename,
|
|
643
|
+
objectKey: `workspaces/${workspaceId}/files/${fileId}/artifact-exports/${safeFilename}`,
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function officeFormat(
|
|
648
|
+
modality: GoogleDrivePublicationToolInputValue["modality"],
|
|
649
|
+
contentType: string,
|
|
650
|
+
): "docx" | "xlsx" | "pptx" {
|
|
651
|
+
const expected = {
|
|
652
|
+
document: {
|
|
653
|
+
format: "docx" as const,
|
|
654
|
+
contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
655
|
+
},
|
|
656
|
+
spreadsheet: {
|
|
657
|
+
format: "xlsx" as const,
|
|
658
|
+
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
659
|
+
},
|
|
660
|
+
presentation: {
|
|
661
|
+
format: "pptx" as const,
|
|
662
|
+
contentType: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
663
|
+
},
|
|
664
|
+
}[modality];
|
|
665
|
+
if (contentType !== expected.contentType) {
|
|
666
|
+
throw new Error("Google Drive native publication requires the matching Office export format");
|
|
667
|
+
}
|
|
668
|
+
return expected.format;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function deterministicUuid(seed: string): string {
|
|
672
|
+
const bytes = createHash("sha256").update(seed, "utf8").digest().subarray(0, 16);
|
|
673
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50;
|
|
674
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
675
|
+
const hex = bytes.toString("hex");
|
|
676
|
+
const value = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
677
|
+
if (!UUID_PATTERN.test(value)) throw new Error("Generated workspace file identity is invalid");
|
|
678
|
+
return value;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
async function publishToGoogleDrive(input: {
|
|
682
|
+
workspaceId: string;
|
|
683
|
+
connectionId: string;
|
|
684
|
+
destination: GoogleDriveOutputDestination;
|
|
685
|
+
request: GoogleDrivePublicationToolInputValue;
|
|
686
|
+
bytes: Uint8Array;
|
|
687
|
+
fetchImpl: FetchLike;
|
|
688
|
+
signal?: AbortSignal;
|
|
689
|
+
}): Promise<GoogleDrivePublicationReceiptValue> {
|
|
690
|
+
await verifyDestinationAtWriteTime(input);
|
|
691
|
+
const operationKey = publicationOperationKey(input);
|
|
692
|
+
const existing = await findExistingPublication(input, operationKey);
|
|
693
|
+
if (existing) return driveReceipt(input, existing, true);
|
|
694
|
+
|
|
695
|
+
const mimeType = googleNativeMime(input.request.modality);
|
|
696
|
+
const boundary = `opengeni_${operationKey.slice(0, 32)}`;
|
|
697
|
+
const metadata = JSON.stringify({
|
|
698
|
+
name: input.request.title,
|
|
699
|
+
mimeType,
|
|
700
|
+
parents: [input.destination.folderId],
|
|
701
|
+
appProperties: {
|
|
702
|
+
opengeniPublicationKey: operationKey,
|
|
703
|
+
opengeniArtifactId: input.request.file.artifactId,
|
|
704
|
+
opengeniArtifactVersionId: input.request.file.versionId,
|
|
705
|
+
opengeniSourceSha256: input.request.file.sha256,
|
|
706
|
+
},
|
|
707
|
+
});
|
|
708
|
+
const prefix = new TextEncoder().encode(
|
|
709
|
+
`--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${metadata}\r\n--${boundary}\r\nContent-Type: ${input.request.file.contentType}\r\n\r\n`,
|
|
710
|
+
);
|
|
711
|
+
const suffix = new TextEncoder().encode(`\r\n--${boundary}--\r\n`);
|
|
712
|
+
const body = new Uint8Array(prefix.byteLength + input.bytes.byteLength + suffix.byteLength);
|
|
713
|
+
body.set(prefix, 0);
|
|
714
|
+
body.set(input.bytes, prefix.byteLength);
|
|
715
|
+
body.set(suffix, prefix.byteLength + input.bytes.byteLength);
|
|
716
|
+
const url = new URL(`${DRIVE_UPLOAD_API}/files`);
|
|
717
|
+
url.searchParams.set("uploadType", "multipart");
|
|
718
|
+
url.searchParams.set("supportsAllDrives", "true");
|
|
719
|
+
url.searchParams.set(
|
|
720
|
+
"fields",
|
|
721
|
+
"id,name,mimeType,parents,driveId,webViewLink,appProperties,trashed",
|
|
722
|
+
);
|
|
723
|
+
const created = parseDriveFile(
|
|
724
|
+
await requestJson(input.fetchImpl, url, {
|
|
725
|
+
method: "POST",
|
|
726
|
+
headers: {
|
|
727
|
+
accept: "application/json",
|
|
728
|
+
"content-type": `multipart/related; boundary=${boundary}`,
|
|
729
|
+
"content-length": String(body.byteLength),
|
|
730
|
+
},
|
|
731
|
+
body,
|
|
732
|
+
...(input.signal ? { signal: input.signal } : {}),
|
|
733
|
+
}),
|
|
734
|
+
);
|
|
735
|
+
assertPublicationMatch(input, created, operationKey);
|
|
736
|
+
return driveReceipt(input, created, false);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
async function verifyDestinationAtWriteTime(
|
|
740
|
+
input: Parameters<typeof publishToGoogleDrive>[0],
|
|
741
|
+
): Promise<void> {
|
|
742
|
+
const url = new URL(`${DRIVE_API}/files/${encodeURIComponent(input.destination.folderId)}`);
|
|
743
|
+
url.searchParams.set("supportsAllDrives", "true");
|
|
744
|
+
url.searchParams.set("fields", "id,name,mimeType,driveId,trashed,capabilities(canAddChildren)");
|
|
745
|
+
const folder = record(await requestJson(input.fetchImpl, url, {}));
|
|
746
|
+
const capabilities = record(folder.capabilities);
|
|
747
|
+
if (
|
|
748
|
+
folder.id !== input.destination.folderId ||
|
|
749
|
+
folder.name !== input.destination.folderName ||
|
|
750
|
+
folder.mimeType !== DRIVE_FOLDER_MIME ||
|
|
751
|
+
folder.trashed === true ||
|
|
752
|
+
capabilities.canAddChildren !== true ||
|
|
753
|
+
(folder.driveId ?? null) !== input.destination.driveId
|
|
754
|
+
) {
|
|
755
|
+
throw new Error("Google Drive output destination changed or is no longer writable");
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
async function findExistingPublication(
|
|
760
|
+
input: Parameters<typeof publishToGoogleDrive>[0],
|
|
761
|
+
operationKey: string,
|
|
762
|
+
): Promise<DriveFile | null> {
|
|
763
|
+
const url = new URL(`${DRIVE_API}/files`);
|
|
764
|
+
url.searchParams.set(
|
|
765
|
+
"q",
|
|
766
|
+
`trashed = false and '${driveQuery(input.destination.folderId)}' in parents and appProperties has { key='opengeniPublicationKey' and value='${operationKey}' }`,
|
|
767
|
+
);
|
|
768
|
+
url.searchParams.set("spaces", "drive");
|
|
769
|
+
url.searchParams.set("supportsAllDrives", "true");
|
|
770
|
+
url.searchParams.set("includeItemsFromAllDrives", "true");
|
|
771
|
+
if (input.destination.driveId) {
|
|
772
|
+
url.searchParams.set("corpora", "drive");
|
|
773
|
+
url.searchParams.set("driveId", input.destination.driveId);
|
|
774
|
+
} else {
|
|
775
|
+
url.searchParams.set("corpora", "user");
|
|
776
|
+
}
|
|
777
|
+
url.searchParams.set(
|
|
778
|
+
"fields",
|
|
779
|
+
"files(id,name,mimeType,parents,driveId,webViewLink,appProperties,trashed)",
|
|
780
|
+
);
|
|
781
|
+
const payload = record(await requestJson(input.fetchImpl, url, {}));
|
|
782
|
+
const files = Array.isArray(payload.files) ? payload.files.map(parseDriveFile) : [];
|
|
783
|
+
if (files.length > 1) throw new Error("Google Drive publication idempotency marker is ambiguous");
|
|
784
|
+
const existing = files[0] ?? null;
|
|
785
|
+
if (existing) assertPublicationMatch(input, existing, operationKey);
|
|
786
|
+
return existing;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
type DriveFile = {
|
|
790
|
+
id: string;
|
|
791
|
+
name: string;
|
|
792
|
+
mimeType: string;
|
|
793
|
+
parents: string[];
|
|
794
|
+
driveId: string | null;
|
|
795
|
+
webViewLink: string;
|
|
796
|
+
appProperties: Record<string, string>;
|
|
797
|
+
trashed: boolean;
|
|
798
|
+
};
|
|
799
|
+
|
|
800
|
+
function parseDriveFile(value: unknown): DriveFile {
|
|
801
|
+
const item = record(value);
|
|
802
|
+
const appProperties = record(item.appProperties);
|
|
803
|
+
if (
|
|
804
|
+
typeof item.id !== "string" ||
|
|
805
|
+
typeof item.name !== "string" ||
|
|
806
|
+
typeof item.mimeType !== "string" ||
|
|
807
|
+
!Array.isArray(item.parents) ||
|
|
808
|
+
!item.parents.every((entry) => typeof entry === "string") ||
|
|
809
|
+
(item.driveId !== undefined && item.driveId !== null && typeof item.driveId !== "string") ||
|
|
810
|
+
typeof item.webViewLink !== "string" ||
|
|
811
|
+
typeof item.trashed !== "boolean"
|
|
812
|
+
) {
|
|
813
|
+
throw new Error("Google Drive returned an invalid publication receipt");
|
|
814
|
+
}
|
|
815
|
+
return {
|
|
816
|
+
id: item.id,
|
|
817
|
+
name: item.name,
|
|
818
|
+
mimeType: item.mimeType,
|
|
819
|
+
parents: item.parents,
|
|
820
|
+
driveId: (item.driveId as string | null | undefined) ?? null,
|
|
821
|
+
webViewLink: item.webViewLink,
|
|
822
|
+
appProperties: Object.fromEntries(
|
|
823
|
+
Object.entries(appProperties).filter(
|
|
824
|
+
(entry): entry is [string, string] => typeof entry[1] === "string",
|
|
825
|
+
),
|
|
826
|
+
),
|
|
827
|
+
trashed: item.trashed,
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function assertPublicationMatch(
|
|
832
|
+
input: Parameters<typeof publishToGoogleDrive>[0],
|
|
833
|
+
file: DriveFile,
|
|
834
|
+
operationKey: string,
|
|
835
|
+
): void {
|
|
836
|
+
if (
|
|
837
|
+
file.trashed ||
|
|
838
|
+
file.name !== input.request.title ||
|
|
839
|
+
file.mimeType !== googleNativeMime(input.request.modality) ||
|
|
840
|
+
file.parents.length !== 1 ||
|
|
841
|
+
file.parents[0] !== input.destination.folderId ||
|
|
842
|
+
file.driveId !== input.destination.driveId ||
|
|
843
|
+
file.appProperties.opengeniPublicationKey !== operationKey ||
|
|
844
|
+
file.appProperties.opengeniArtifactId !== input.request.file.artifactId ||
|
|
845
|
+
file.appProperties.opengeniArtifactVersionId !== input.request.file.versionId ||
|
|
846
|
+
file.appProperties.opengeniSourceSha256 !== input.request.file.sha256
|
|
847
|
+
) {
|
|
848
|
+
throw new Error("Google Drive publication idempotency key conflicts with another file");
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function driveReceipt(
|
|
853
|
+
input: Parameters<typeof publishToGoogleDrive>[0],
|
|
854
|
+
file: DriveFile,
|
|
855
|
+
replayed: boolean,
|
|
856
|
+
): GoogleDrivePublicationReceiptValue {
|
|
857
|
+
return GoogleDrivePublicationReceipt.parse({
|
|
858
|
+
connectionId: input.connectionId,
|
|
859
|
+
providerFileId: file.id,
|
|
860
|
+
webViewLink: file.webViewLink,
|
|
861
|
+
mimeType: googleNativeMime(input.request.modality),
|
|
862
|
+
destination: input.destination,
|
|
863
|
+
replayed,
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function publicationOperationKey(input: Parameters<typeof publishToGoogleDrive>[0]): string {
|
|
868
|
+
return createHash("sha256")
|
|
869
|
+
.update(
|
|
870
|
+
JSON.stringify({
|
|
871
|
+
workspaceId: input.workspaceId,
|
|
872
|
+
connectionId: input.connectionId,
|
|
873
|
+
destination: input.destination,
|
|
874
|
+
artifactId: input.request.file.artifactId,
|
|
875
|
+
versionId: input.request.file.versionId,
|
|
876
|
+
materializationJobId: input.request.file.materializationJobId,
|
|
877
|
+
sourceSha256: input.request.file.sha256,
|
|
878
|
+
idempotencyKey: input.request.idempotencyKey,
|
|
879
|
+
}),
|
|
880
|
+
"utf8",
|
|
881
|
+
)
|
|
882
|
+
.digest("hex");
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function googleNativeMime(
|
|
886
|
+
modality: GoogleDrivePublicationToolInputValue["modality"],
|
|
887
|
+
): GoogleDrivePublicationReceiptValue["mimeType"] {
|
|
888
|
+
switch (modality) {
|
|
889
|
+
case "document":
|
|
890
|
+
return "application/vnd.google-apps.document";
|
|
891
|
+
case "spreadsheet":
|
|
892
|
+
return "application/vnd.google-apps.spreadsheet";
|
|
893
|
+
case "presentation":
|
|
894
|
+
return "application/vnd.google-apps.presentation";
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
function sameDestination(
|
|
899
|
+
left: GoogleDriveOutputDestination,
|
|
900
|
+
right: GoogleDriveOutputDestination,
|
|
901
|
+
): boolean {
|
|
902
|
+
return (
|
|
903
|
+
left.folderId === right.folderId &&
|
|
904
|
+
left.folderName === right.folderName &&
|
|
905
|
+
left.driveId === right.driveId &&
|
|
906
|
+
left.location === right.location &&
|
|
907
|
+
left.selectedAt === right.selectedAt
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
async function requestJson(fetchImpl: FetchLike, url: URL, init: RequestInit): Promise<unknown> {
|
|
912
|
+
let response: Response;
|
|
913
|
+
try {
|
|
914
|
+
response = await fetchImpl(url, {
|
|
915
|
+
...init,
|
|
916
|
+
redirect: "error",
|
|
917
|
+
signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
918
|
+
});
|
|
919
|
+
} catch (error) {
|
|
920
|
+
if (error instanceof GoogleDrivePublicationAuthorizationError) throw error;
|
|
921
|
+
throw new Error("Google Drive publication transport failed", { cause: error });
|
|
922
|
+
}
|
|
923
|
+
if (!response.ok) {
|
|
924
|
+
await response.body?.cancel().catch(() => undefined);
|
|
925
|
+
throw new Error(`Google Drive publication request failed with status ${response.status}`);
|
|
926
|
+
}
|
|
927
|
+
return await readResponseJsonBounded(response, RESPONSE_MAX_BYTES, "Google Drive publication");
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
function record(value: unknown): Record<string, unknown> {
|
|
931
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
932
|
+
? (value as Record<string, unknown>)
|
|
933
|
+
: {};
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
function driveQuery(value: string): string {
|
|
937
|
+
return value.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'");
|
|
938
|
+
}
|