@opengeni/worker-bundle 0.20.3 → 0.22.1-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.
Files changed (184) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +52 -0
  2. package/dist/activities/agent-turn/agent-build.d.ts +89 -0
  3. package/dist/activities/agent-turn/claim.d.ts +67 -0
  4. package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
  5. package/dist/activities/agent-turn/codex.d.ts +32 -0
  6. package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
  7. package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
  8. package/dist/activities/agent-turn/errors.d.ts +253 -0
  9. package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
  10. package/dist/activities/agent-turn/file-resources.d.ts +37 -0
  11. package/dist/activities/agent-turn/finalization.d.ts +42 -0
  12. package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
  13. package/dist/activities/agent-turn/governance-model.d.ts +66 -0
  14. package/dist/activities/agent-turn/history-sink.d.ts +52 -0
  15. package/dist/activities/agent-turn/history.d.ts +63 -0
  16. package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
  17. package/dist/activities/agent-turn/model-usage.d.ts +218 -0
  18. package/dist/activities/agent-turn/quiescence.d.ts +135 -0
  19. package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
  20. package/dist/activities/agent-turn/run.d.ts +3 -0
  21. package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
  22. package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
  23. package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
  24. package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
  25. package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
  26. package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
  27. package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
  28. package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
  29. package/dist/activities/agent-turn/turn-context.d.ts +144 -0
  30. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
  31. package/dist/activities/agent-turn.d.ts +12 -954
  32. package/dist/activities/automations.d.ts +16 -0
  33. package/dist/activities/common.d.ts +1 -1
  34. package/dist/activities/connector-attachments.d.ts +13 -0
  35. package/dist/activities/documents.d.ts +1 -0
  36. package/dist/activities/environment.d.ts +26 -15
  37. package/dist/activities/generated-images.d.ts +1 -1
  38. package/dist/activities/git-credential-renewal.d.ts +3 -1
  39. package/dist/activities/goals.d.ts +4 -1
  40. package/dist/activities/google-drive-provider.d.ts +29 -0
  41. package/dist/activities/google-drive-publication.d.ts +17 -4
  42. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  43. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  44. package/dist/activities/knowledge-source-sync.d.ts +4 -0
  45. package/dist/activities/mcp-credentials.d.ts +9 -3
  46. package/dist/activities/open-suffix-resume.d.ts +77 -0
  47. package/dist/activities/packs.d.ts +3 -11
  48. package/dist/activities/parent-wake.d.ts +19 -0
  49. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  50. package/dist/activities/retained-screenshots.d.ts +1 -1
  51. package/dist/activities/rig-verification.d.ts +1 -1
  52. package/dist/activities/run-input.d.ts +9 -10
  53. package/dist/activities/sandbox-images.d.ts +1 -14
  54. package/dist/activities/sandbox-lease.d.ts +21 -3
  55. package/dist/activities/scheduled-tasks.d.ts +47 -0
  56. package/dist/activities/types.d.ts +23 -2
  57. package/dist/activities/video-media-validation.d.ts +1 -1
  58. package/dist/activities/video-output-retention.d.ts +1 -2
  59. package/dist/activities/xai-auth.d.ts +3 -0
  60. package/dist/{activities-control-BJSDRSIP.js → activities-control-DKG22ONJ.js} +2646 -551
  61. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  62. package/dist/activities-control.d.ts +6 -2
  63. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  64. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  65. package/dist/activities.d.ts +7 -3
  66. package/dist/artifact-materializer-entry.js +41 -22
  67. package/dist/artifact-materializer-entry.js.map +1 -1
  68. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  69. package/dist/chunk-CE7TPKBS.js.map +1 -0
  70. package/dist/chunk-CNYGVRKF.js +4698 -0
  71. package/dist/chunk-CNYGVRKF.js.map +1 -0
  72. package/dist/connection-provider-use.d.ts +18 -0
  73. package/dist/editable-artifact-materializer.d.ts +4 -3
  74. package/dist/github-rest-mcp.d.ts +26 -0
  75. package/dist/index.d.ts +10 -2
  76. package/dist/index.js +58 -14
  77. package/dist/index.js.map +1 -1
  78. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  79. package/dist/model-context-contributions.d.ts +8 -4
  80. package/dist/observability-metrics.d.ts +63 -4
  81. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  82. package/dist/personal-github-git-credentials.d.ts +9 -0
  83. package/dist/pr-review-credentials.d.ts +6 -0
  84. package/dist/sandbox-archive-storage.d.ts +45 -0
  85. package/dist/sandbox-resume.d.ts +65 -6
  86. package/dist/sandbox-routing.d.ts +38 -2
  87. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  88. package/dist/workflow-bundle.js +87 -28
  89. package/dist/workflows/activities.d.ts +1 -0
  90. package/dist/workflows/automations.d.ts +6 -0
  91. package/dist/workflows/document-index.d.ts +1 -0
  92. package/dist/workflows.d.ts +1 -0
  93. package/package.json +17 -17
  94. package/src/activities/agent-turn/admission.ts +292 -0
  95. package/src/activities/agent-turn/agent-build.ts +802 -0
  96. package/src/activities/agent-turn/claim.ts +590 -0
  97. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  98. package/src/activities/agent-turn/codex.ts +94 -0
  99. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  100. package/src/activities/agent-turn/credential-leases.ts +240 -0
  101. package/src/activities/agent-turn/errors.ts +1068 -0
  102. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  103. package/src/activities/agent-turn/file-resources.ts +227 -0
  104. package/src/activities/agent-turn/finalization.ts +754 -0
  105. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  106. package/src/activities/agent-turn/governance-model.ts +465 -0
  107. package/src/activities/agent-turn/history-sink.ts +139 -0
  108. package/src/activities/agent-turn/history.ts +200 -0
  109. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  110. package/src/activities/agent-turn/model-usage.ts +823 -0
  111. package/src/activities/agent-turn/quiescence.ts +353 -0
  112. package/src/activities/agent-turn/run-credentials.ts +761 -0
  113. package/src/activities/agent-turn/run.ts +1530 -0
  114. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  115. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  116. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  117. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  118. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  119. package/src/activities/agent-turn/tool-environment.ts +729 -0
  120. package/src/activities/agent-turn/tool-policy.ts +216 -0
  121. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  122. package/src/activities/agent-turn/turn-context.ts +281 -0
  123. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  124. package/src/activities/agent-turn.ts +12 -12701
  125. package/src/activities/api-integrations.ts +3 -0
  126. package/src/activities/automations.ts +214 -0
  127. package/src/activities/codemode-dispatcher.ts +12 -1
  128. package/src/activities/common.ts +1 -5
  129. package/src/activities/connector-attachments.ts +168 -0
  130. package/src/activities/context-compaction.ts +18 -0
  131. package/src/activities/environment.ts +151 -55
  132. package/src/activities/generated-images.ts +26 -11
  133. package/src/activities/git-credential-renewal.ts +13 -3
  134. package/src/activities/goals.ts +85 -19
  135. package/src/activities/google-drive-provider.ts +178 -0
  136. package/src/activities/google-drive-publication.ts +147 -49
  137. package/src/activities/incident-telemetry-authority.ts +327 -0
  138. package/src/activities/incident-telemetry-preflight.ts +317 -0
  139. package/src/activities/knowledge-source-sync.ts +178 -37
  140. package/src/activities/mcp-credentials.ts +191 -17
  141. package/src/activities/open-suffix-resume.ts +422 -0
  142. package/src/activities/packs.ts +12 -60
  143. package/src/activities/parent-wake.ts +64 -14
  144. package/src/activities/retained-screenshot-reaper.ts +6 -3
  145. package/src/activities/retained-screenshots.ts +15 -47
  146. package/src/activities/rig-verification.ts +1 -1
  147. package/src/activities/run-input.ts +102 -142
  148. package/src/activities/sandbox-images.ts +7 -166
  149. package/src/activities/sandbox-lease.ts +406 -15
  150. package/src/activities/scheduled-tasks.ts +2103 -411
  151. package/src/activities/session-state.ts +10 -2
  152. package/src/activities/types.ts +32 -2
  153. package/src/activities/video-media-validation.ts +3 -3
  154. package/src/activities/video-output-retention.ts +2 -57
  155. package/src/activities/xai-auth.ts +8 -0
  156. package/src/activities-control.ts +2 -0
  157. package/src/activities.ts +3 -0
  158. package/src/activity-services.ts +13 -4
  159. package/src/connection-provider-use.ts +36 -0
  160. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  161. package/src/editable-artifact-materializer.ts +29 -18
  162. package/src/github-rest-mcp.ts +713 -0
  163. package/src/http.ts +16 -6
  164. package/src/index.ts +40 -5
  165. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  166. package/src/model-context-contributions.ts +33 -10
  167. package/src/observability-metrics.ts +357 -0
  168. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  169. package/src/personal-github-git-credentials.ts +331 -0
  170. package/src/pr-review-credentials.ts +163 -0
  171. package/src/sandbox-archive-storage.ts +159 -0
  172. package/src/sandbox-resume.ts +449 -63
  173. package/src/sandbox-routing.ts +314 -16
  174. package/src/scheduled-alert-occurrence.ts +176 -0
  175. package/src/workflows/activities.ts +18 -2
  176. package/src/workflows/automations.ts +11 -0
  177. package/src/workflows/session.ts +13 -3
  178. package/src/workflows.ts +1 -0
  179. package/dist/activities-control-BJSDRSIP.js.map +0 -1
  180. package/dist/activities-turn-J5YO7XXX.js +0 -17243
  181. package/dist/activities-turn-J5YO7XXX.js.map +0 -1
  182. package/dist/chunk-N5TJIFCE.js.map +0 -1
  183. package/dist/chunk-P6Z2SLAA.js +0 -3092
  184. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -0,0 +1,178 @@
1
+ import type { GoogleDriveProviderRetryOptions } from "@opengeni/config";
2
+ import type { FetchLike } from "@opengeni/network";
3
+ import type { Observability } from "@opengeni/observability";
4
+
5
+ export type GoogleDriveProviderOperation =
6
+ | "start_page_token"
7
+ | "list_changes"
8
+ | "get_file"
9
+ | "list_children"
10
+ | "list_permissions"
11
+ | "download"
12
+ | "export";
13
+
14
+ export type GoogleDriveProviderHeartbeat = (details: {
15
+ operation: GoogleDriveProviderOperation;
16
+ attempt: number;
17
+ phase: "request_start" | "request_end" | "retry_delay_start" | "retry_delay_end";
18
+ }) => void;
19
+
20
+ export class GoogleDriveProviderTransportError extends Error {
21
+ constructor() {
22
+ super("google_drive_provider_transport_failed");
23
+ this.name = "GoogleDriveProviderTransportError";
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Absorb only short, explicitly retryable Drive failures inside one bounded
29
+ * activity. Provider bodies, URLs, headers, and credentials never enter logs
30
+ * or metric labels. The caller's logical sync-request accounting remains
31
+ * unchanged; this helper exposes physical attempts separately as telemetry.
32
+ */
33
+ export async function fetchGoogleDriveProvider(input: {
34
+ fetchImpl: FetchLike;
35
+ url: string | URL;
36
+ init: RequestInit;
37
+ operation: GoogleDriveProviderOperation;
38
+ policy: GoogleDriveProviderRetryOptions;
39
+ observability: Observability;
40
+ heartbeat?: GoogleDriveProviderHeartbeat;
41
+ now?: () => number;
42
+ sleep?: (delayMs: number) => Promise<void>;
43
+ }): Promise<Response> {
44
+ const now = input.now ?? Date.now;
45
+ const sleep = input.sleep ?? Bun.sleep;
46
+ let retryDelaySpentMs = 0;
47
+
48
+ for (let attempt = 1; attempt <= input.policy.attempts; attempt += 1) {
49
+ let response: Response;
50
+ input.heartbeat?.({ operation: input.operation, attempt, phase: "request_start" });
51
+ try {
52
+ response = await input.fetchImpl(input.url, {
53
+ ...input.init,
54
+ redirect: "error",
55
+ signal: AbortSignal.timeout(input.policy.requestTimeoutMs),
56
+ });
57
+ } catch {
58
+ input.heartbeat?.({ operation: input.operation, attempt, phase: "request_end" });
59
+ recordRequest(input.observability, input.operation, "retryable_error");
60
+ const delayMs = retryDelayMs(input.policy, attempt, null);
61
+ if (!canRetry(input.policy, attempt, retryDelaySpentMs, delayMs)) {
62
+ throw new GoogleDriveProviderTransportError();
63
+ }
64
+ recordRetry(input.observability, input.operation, "transport", attempt, delayMs);
65
+ retryDelaySpentMs += delayMs;
66
+ input.heartbeat?.({ operation: input.operation, attempt, phase: "retry_delay_start" });
67
+ await sleep(delayMs);
68
+ input.heartbeat?.({ operation: input.operation, attempt, phase: "retry_delay_end" });
69
+ continue;
70
+ }
71
+ input.heartbeat?.({ operation: input.operation, attempt, phase: "request_end" });
72
+
73
+ if (!isRetryableStatus(response.status)) {
74
+ recordRequest(
75
+ input.observability,
76
+ input.operation,
77
+ response.ok ? "succeeded" : "terminal_error",
78
+ );
79
+ return response;
80
+ }
81
+
82
+ recordRequest(input.observability, input.operation, "retryable_error");
83
+ const delayMs = retryDelayMs(
84
+ input.policy,
85
+ attempt,
86
+ retryAfterDelayMs(response.headers.get("retry-after"), now()),
87
+ );
88
+ if (!canRetry(input.policy, attempt, retryDelaySpentMs, delayMs)) return response;
89
+ await response.body?.cancel().catch(() => undefined);
90
+ recordRetry(
91
+ input.observability,
92
+ input.operation,
93
+ response.status === 429 ? "rate_limited" : "provider_unavailable",
94
+ attempt,
95
+ delayMs,
96
+ );
97
+ retryDelaySpentMs += delayMs;
98
+ input.heartbeat?.({ operation: input.operation, attempt, phase: "retry_delay_start" });
99
+ await sleep(delayMs);
100
+ input.heartbeat?.({ operation: input.operation, attempt, phase: "retry_delay_end" });
101
+ }
102
+
103
+ throw new GoogleDriveProviderTransportError();
104
+ }
105
+
106
+ function canRetry(
107
+ policy: GoogleDriveProviderRetryOptions,
108
+ attempt: number,
109
+ retryDelaySpentMs: number,
110
+ delayMs: number,
111
+ ): boolean {
112
+ return attempt < policy.attempts && retryDelaySpentMs + delayMs <= policy.budgetMs;
113
+ }
114
+
115
+ function retryDelayMs(
116
+ policy: GoogleDriveProviderRetryOptions,
117
+ attempt: number,
118
+ retryAfterMs: number | null,
119
+ ): number {
120
+ const exponential = Math.min(
121
+ policy.maxDelayMs,
122
+ policy.initialDelayMs * 2 ** Math.max(0, attempt - 1),
123
+ );
124
+ return Math.min(policy.maxDelayMs, Math.max(exponential, retryAfterMs ?? 0));
125
+ }
126
+
127
+ function retryAfterDelayMs(value: string | null, nowMs: number): number | null {
128
+ if (!value) return null;
129
+ const seconds = Number(value);
130
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1_000);
131
+ const timestamp = Date.parse(value);
132
+ return Number.isFinite(timestamp) ? Math.max(0, timestamp - nowMs) : null;
133
+ }
134
+
135
+ function isRetryableStatus(status: number): boolean {
136
+ return status === 429 || status >= 500;
137
+ }
138
+
139
+ function recordRequest(
140
+ observability: Observability,
141
+ operation: GoogleDriveProviderOperation,
142
+ outcome: "succeeded" | "retryable_error" | "terminal_error",
143
+ ): void {
144
+ observability.incrementCounter({
145
+ name: "opengeni_google_drive_provider_requests_total",
146
+ help: "Google Drive provider request attempts by operation and bounded outcome.",
147
+ labels: { operation, outcome },
148
+ });
149
+ }
150
+
151
+ function recordRetry(
152
+ observability: Observability,
153
+ operation: GoogleDriveProviderOperation,
154
+ reason: "transport" | "rate_limited" | "provider_unavailable",
155
+ attempt: number,
156
+ delayMs: number,
157
+ ): void {
158
+ observability.incrementCounter({
159
+ name: "opengeni_google_drive_provider_retries_total",
160
+ help: "Bounded Google Drive provider retries by operation and reason.",
161
+ labels: { operation, reason },
162
+ });
163
+ observability.observeHistogram({
164
+ name: "opengeni_google_drive_provider_retry_delay_seconds",
165
+ help: "Delay applied before a bounded Google Drive provider retry.",
166
+ labels: { operation, reason },
167
+ value: delayMs / 1_000,
168
+ buckets: [0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60],
169
+ });
170
+ observability.warn("Google Drive provider request retry scheduled", {
171
+ provider: "google_drive",
172
+ operation,
173
+ outcome: "retry_scheduled",
174
+ reason,
175
+ attempt,
176
+ delayMs,
177
+ });
178
+ }
@@ -20,9 +20,9 @@ import {
20
20
  beginConnectorActionExecution,
21
21
  completeConnectorActionExecution,
22
22
  getConnectionMetadata,
23
- getWorkspaceGrant,
24
23
  prepareConnectorActionApproval,
25
24
  requireFile,
25
+ namedSubjectHasLiveWorkspaceAuthority,
26
26
  type ConnectorActionAttemptIdentity,
27
27
  type ConnectorActionInvocation,
28
28
  type Database,
@@ -34,7 +34,7 @@ import {
34
34
  type PersistedEditableArtifactMaterializationJob,
35
35
  } from "@opengeni/db/editable-artifact-durable-export";
36
36
  import { readResponseJsonBounded, undiciFetch, type FetchLike } from "@opengeni/network";
37
- import type { ObjectStorage } from "@opengeni/storage";
37
+ import { retryWhileMissing, type ObjectStorage } from "@opengeni/storage";
38
38
 
39
39
  const DRIVE_API = "https://www.googleapis.com/drive/v3";
40
40
  const DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3";
@@ -44,16 +44,26 @@ const REQUEST_TIMEOUT_MS = 30_000;
44
44
  const FIRST_PARTY_MCP_SUBJECT_ID = "worker:first-party-mcp";
45
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
46
 
47
+ class GoogleDrivePublicationAuthorizationError extends Error {}
48
+
47
49
  export type GoogleDrivePublicationTarget = Readonly<{
48
50
  ownerSubjectId: string;
49
51
  connectionId: string;
52
+ originWorkspaceId: string;
50
53
  destination: GoogleDriveOutputDestination;
51
54
  credentialScope: typeof GOOGLE_DRIVE_FILE_SCOPE | typeof GOOGLE_DRIVE_FULL_SCOPE;
52
55
  }>;
53
56
 
54
57
  export type GoogleDrivePublicationPorts = {
55
58
  getConnection: typeof getConnectionMetadata;
56
- getMembership: typeof getWorkspaceGrant;
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;
57
67
  readMaterialization: typeof readAuthorizedEditableArtifactMaterialization;
58
68
  requireFile: typeof requireFile;
59
69
  prepare: typeof prepareConnectorActionApproval;
@@ -64,7 +74,7 @@ export type GoogleDrivePublicationPorts = {
64
74
 
65
75
  const defaultPorts: GoogleDrivePublicationPorts = {
66
76
  getConnection: getConnectionMetadata,
67
- getMembership: getWorkspaceGrant,
77
+ getMembership: namedSubjectHasLiveWorkspaceAuthority,
68
78
  readMaterialization: readAuthorizedEditableArtifactMaterialization,
69
79
  requireFile,
70
80
  prepare: prepareConnectorActionApproval,
@@ -75,10 +85,11 @@ const defaultPorts: GoogleDrivePublicationPorts = {
75
85
 
76
86
  export async function resolveGoogleDrivePublicationTarget(
77
87
  db: Database,
78
- workspaceId: string,
88
+ workspace: { accountId: string; workspaceId: string },
79
89
  delegations: readonly McpPersonalConnectionDelegation[],
80
90
  ports: Pick<GoogleDrivePublicationPorts, "getConnection" | "getMembership"> = defaultPorts,
81
91
  ): Promise<GoogleDrivePublicationTarget | null> {
92
+ const { workspaceId } = workspace;
82
93
  const frozen = delegations.filter(
83
94
  (delegation) =>
84
95
  delegation.serverId === GOOGLE_DRIVE_PUBLICATION_SERVER_ID &&
@@ -87,16 +98,29 @@ export async function resolveGoogleDrivePublicationTarget(
87
98
  );
88
99
  if (frozen.length !== 1) return null;
89
100
  const delegation = frozen[0]!;
90
- if (!(await ports.getMembership(db, delegation.ownerSubjectId, workspaceId))) return null;
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;
91
114
  const connection = await ports.getConnection(
92
115
  db,
93
- workspaceId,
116
+ originWorkspaceId,
94
117
  delegation.connectionId,
95
118
  delegation.ownerSubjectId,
96
119
  );
97
120
  if (
98
121
  !connection ||
99
122
  connection.id !== delegation.connectionId ||
123
+ connection.workspaceId !== originWorkspaceId ||
100
124
  connection.subjectId !== delegation.ownerSubjectId ||
101
125
  connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN ||
102
126
  connection.kind !== "oauth2" ||
@@ -114,10 +138,20 @@ export async function resolveGoogleDrivePublicationTarget(
114
138
  ) {
115
139
  return null;
116
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
+ }
117
150
  return Object.freeze({
118
151
  ownerSubjectId: delegation.ownerSubjectId,
119
152
  connectionId: connection.id,
120
- destination: metadata.data.outputDestination,
153
+ originWorkspaceId,
154
+ destination: frozenDestination ?? metadata.data.outputDestination,
121
155
  credentialScope: connection.grantedScopes.includes(GOOGLE_DRIVE_FILE_SCOPE)
122
156
  ? GOOGLE_DRIVE_FILE_SCOPE
123
157
  : GOOGLE_DRIVE_FULL_SCOPE,
@@ -274,17 +308,31 @@ export function createGoogleDrivePublicationAttemptTool(input: {
274
308
  request,
275
309
  context.operationId,
276
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.
277
318
  let requestId: string | null = null;
278
319
  if (context.caller.kind === "codemode") {
279
320
  const admission = await ports.begin(input.db, input.identity, connectorCall);
280
321
  if (!admission.allowed) {
281
- throw new Error(`Google Drive publication was not executed: ${admission.reason}`);
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
+ );
282
329
  }
283
330
  if (!admission.managed) {
284
331
  throw new Error("Google Drive publication has no explicit connector action policy");
285
332
  }
286
333
  requestId = admission.requestId;
287
334
  }
335
+ let providerRequestStarted = false;
288
336
  try {
289
337
  const receipt = await executeGoogleDrivePublication(
290
338
  {
@@ -295,6 +343,9 @@ export function createGoogleDrivePublicationAttemptTool(input: {
295
343
  target: input.target,
296
344
  request,
297
345
  resolveCredential: input.resolveCredential,
346
+ onProviderRequest: () => {
347
+ providerRequestStarted = true;
348
+ },
298
349
  ...((context.signal ?? input.signal) ? { signal: context.signal ?? input.signal } : {}),
299
350
  },
300
351
  ports,
@@ -319,10 +370,16 @@ export function createGoogleDrivePublicationAttemptTool(input: {
319
370
  workspaceId: input.identity.workspaceId,
320
371
  requestId,
321
372
  attemptId: input.identity.attemptId,
322
- outcome: "uncertain",
373
+ outcome: providerRequestStarted ? "uncertain" : "not_executed",
323
374
  });
324
375
  }
325
- throw error;
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
+ );
326
383
  }
327
384
  },
328
385
  };
@@ -363,6 +420,8 @@ export async function executeGoogleDrivePublication(
363
420
  input: ResolveConnectionCredentialInput,
364
421
  ) => Promise<ResolveConnectionCredentialResult>;
365
422
  signal?: AbortSignal;
423
+ /** Invoked immediately before the first provider request is sent. */
424
+ onProviderRequest?: () => void;
366
425
  },
367
426
  ports: Pick<
368
427
  GoogleDrivePublicationPorts,
@@ -372,7 +431,7 @@ export async function executeGoogleDrivePublication(
372
431
  const request = GoogleDrivePublicationToolInput.parse(input.request);
373
432
  const connection = await ports.getConnection(
374
433
  input.db,
375
- input.identity.workspaceId,
434
+ input.target.originWorkspaceId,
376
435
  input.target.connectionId,
377
436
  input.subjectId,
378
437
  );
@@ -419,49 +478,88 @@ export async function executeGoogleDrivePublication(
419
478
  ) {
420
479
  throw new Error("Editable artifact export file differs from its canonical receipt");
421
480
  }
422
- const bytes = await input.objectStorage.getFileBytes(sourceFile);
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;
423
486
  if (
424
487
  bytes.byteLength !== request.file.sizeBytes ||
425
488
  createHash("sha256").update(bytes).digest("hex") !== request.file.sha256
426
489
  ) {
427
490
  throw new Error("Editable artifact export bytes failed verification");
428
491
  }
429
- const credential = await input.resolveCredential({
430
- workspaceId: input.identity.workspaceId,
431
- subjectId: input.subjectId,
432
- serverId: GOOGLE_DRIVE_PUBLICATION_SERVER_ID,
433
- toolName: GOOGLE_DRIVE_PUBLICATION_TOOL_NAME,
434
- connectionRef: {
435
- providerDomain: GOOGLE_DRIVE_PROVIDER_DOMAIN,
436
- connectionId: input.target.connectionId,
437
- kind: "oauth2",
438
- subjectScope: "subject",
439
- scopes: [input.target.credentialScope],
440
- },
441
- destinationUrl: `${DRIVE_UPLOAD_API}/files`,
442
- forceRefresh: false,
443
- });
444
- if (credential.status !== "ok" || credential.connectionId !== input.target.connectionId) {
445
- throw new Error("Google Drive publication credential is unavailable");
446
- }
447
- const resolvedConnection = await ports.getConnection(
448
- input.db,
449
- input.identity.workspaceId,
450
- input.target.connectionId,
451
- input.subjectId,
452
- );
453
- if (!resolvedConnection) {
454
- throw new Error("Google Drive publication authority changed; retry on a new turn");
455
- }
456
- assertPublicationConnection(input, resolvedConnection);
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
+ };
457
556
  return await publishToGoogleDrive({
458
557
  workspaceId: input.identity.workspaceId,
459
558
  connectionId: input.target.connectionId,
460
559
  destination: input.target.destination,
461
560
  request,
462
561
  bytes,
463
- headers: credential.headers,
464
- fetchImpl: ports.fetch,
562
+ fetchImpl: authorizedFetch,
465
563
  ...(input.signal ? { signal: input.signal } : {}),
466
564
  });
467
565
  }
@@ -477,6 +575,7 @@ function assertPublicationConnection(
477
575
  if (
478
576
  input.subjectId !== input.target.ownerSubjectId ||
479
577
  connection.id !== input.target.connectionId ||
578
+ connection.workspaceId !== input.target.originWorkspaceId ||
480
579
  connection.subjectId !== input.target.ownerSubjectId ||
481
580
  connection.providerDomain.toLowerCase() !== GOOGLE_DRIVE_PROVIDER_DOMAIN ||
482
581
  connection.kind !== "oauth2" ||
@@ -585,7 +684,6 @@ async function publishToGoogleDrive(input: {
585
684
  destination: GoogleDriveOutputDestination;
586
685
  request: GoogleDrivePublicationToolInputValue;
587
686
  bytes: Uint8Array;
588
- headers: Record<string, string>;
589
687
  fetchImpl: FetchLike;
590
688
  signal?: AbortSignal;
591
689
  }): Promise<GoogleDrivePublicationReceiptValue> {
@@ -626,7 +724,6 @@ async function publishToGoogleDrive(input: {
626
724
  await requestJson(input.fetchImpl, url, {
627
725
  method: "POST",
628
726
  headers: {
629
- ...input.headers,
630
727
  accept: "application/json",
631
728
  "content-type": `multipart/related; boundary=${boundary}`,
632
729
  "content-length": String(body.byteLength),
@@ -645,7 +742,7 @@ async function verifyDestinationAtWriteTime(
645
742
  const url = new URL(`${DRIVE_API}/files/${encodeURIComponent(input.destination.folderId)}`);
646
743
  url.searchParams.set("supportsAllDrives", "true");
647
744
  url.searchParams.set("fields", "id,name,mimeType,driveId,trashed,capabilities(canAddChildren)");
648
- const folder = record(await requestJson(input.fetchImpl, url, { headers: input.headers }));
745
+ const folder = record(await requestJson(input.fetchImpl, url, {}));
649
746
  const capabilities = record(folder.capabilities);
650
747
  if (
651
748
  folder.id !== input.destination.folderId ||
@@ -681,7 +778,7 @@ async function findExistingPublication(
681
778
  "fields",
682
779
  "files(id,name,mimeType,parents,driveId,webViewLink,appProperties,trashed)",
683
780
  );
684
- const payload = record(await requestJson(input.fetchImpl, url, { headers: input.headers }));
781
+ const payload = record(await requestJson(input.fetchImpl, url, {}));
685
782
  const files = Array.isArray(payload.files) ? payload.files.map(parseDriveFile) : [];
686
783
  if (files.length > 1) throw new Error("Google Drive publication idempotency marker is ambiguous");
687
784
  const existing = files[0] ?? null;
@@ -819,8 +916,9 @@ async function requestJson(fetchImpl: FetchLike, url: URL, init: RequestInit): P
819
916
  redirect: "error",
820
917
  signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS),
821
918
  });
822
- } catch {
823
- throw new Error("Google Drive publication transport failed");
919
+ } catch (error) {
920
+ if (error instanceof GoogleDrivePublicationAuthorizationError) throw error;
921
+ throw new Error("Google Drive publication transport failed", { cause: error });
824
922
  }
825
923
  if (!response.ok) {
826
924
  await response.body?.cancel().catch(() => undefined);