@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,292 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { request as httpsRequest } from "node:https";
3
+
4
+ const KUBERNETES_API_URL = "https://kubernetes.default.svc";
5
+ const KUBERNETES_TOKEN_FILE = "/var/run/secrets/opengeni.io/opensandbox-kubernetes-inventory/token";
6
+ const KUBERNETES_CA_FILE = "/var/run/secrets/opengeni.io/opensandbox-kubernetes-inventory/ca.crt";
7
+ const KUBERNETES_REQUEST_TIMEOUT_MS = 10_000;
8
+ const KUBERNETES_RESPONSE_MAX_BYTES = 64 * 1024 * 1024;
9
+ const KUBERNETES_LIST_PAGE_SIZE = 200;
10
+ const KUBERNETES_LIST_MAX_PAGES = 10_000;
11
+
12
+ export const OPENSANDBOX_CLEANUP_STUCK_SECONDS = 300;
13
+ export const OPENSANDBOX_EXPIRATION_OVERDUE_SECONDS = 180;
14
+
15
+ export const OPENSANDBOX_BATCHSANDBOX_PHASES = [
16
+ "pending",
17
+ "running",
18
+ "pausing",
19
+ "paused",
20
+ "resuming",
21
+ "failed",
22
+ "unknown",
23
+ ] as const;
24
+
25
+ export type OpenSandboxBatchSandboxPhase = (typeof OPENSANDBOX_BATCHSANDBOX_PHASES)[number];
26
+
27
+ export const OPENSANDBOX_WORKLOAD_POD_CONDITIONS = [
28
+ "pending",
29
+ "image_pull",
30
+ "unschedulable",
31
+ ] as const;
32
+
33
+ export type OpenSandboxWorkloadPodCondition = (typeof OPENSANDBOX_WORKLOAD_POD_CONDITIONS)[number];
34
+
35
+ export type OpenSandboxKubernetesInventory = {
36
+ batchSandboxPhases: Record<OpenSandboxBatchSandboxPhase, number>;
37
+ workloadPodConditions: Record<OpenSandboxWorkloadPodCondition, number>;
38
+ cleanupStuck: number;
39
+ expirationOverdue: number;
40
+ };
41
+
42
+ export type KubernetesJsonRequest = (url: URL) => Promise<unknown>;
43
+
44
+ type JsonRecord = Record<string, unknown>;
45
+
46
+ const IMAGE_PULL_REASONS = new Set(["ErrImagePull", "ImagePullBackOff", "InvalidImageName"]);
47
+
48
+ export async function inspectOpenSandboxKubernetesInventory(input: {
49
+ namespace: string;
50
+ nowMs?: number;
51
+ requestJson?: KubernetesJsonRequest;
52
+ apiUrl?: string;
53
+ tokenFile?: string;
54
+ caFile?: string;
55
+ }): Promise<OpenSandboxKubernetesInventory> {
56
+ const namespace = kubernetesNamespace(input.namespace);
57
+ const nowMs = input.nowMs ?? Date.now();
58
+ const requestJson =
59
+ input.requestJson ??
60
+ (await authenticatedKubernetesJsonRequest({
61
+ tokenFile: input.tokenFile ?? KUBERNETES_TOKEN_FILE,
62
+ caFile: input.caFile ?? KUBERNETES_CA_FILE,
63
+ }));
64
+ const apiUrl = new URL(input.apiUrl ?? KUBERNETES_API_URL);
65
+ if (apiUrl.protocol !== "https:") {
66
+ throw new Error("OpenSandbox Kubernetes inventory API must use HTTPS");
67
+ }
68
+
69
+ const inventory: OpenSandboxKubernetesInventory = {
70
+ batchSandboxPhases: zeroRecord(OPENSANDBOX_BATCHSANDBOX_PHASES),
71
+ workloadPodConditions: zeroRecord(OPENSANDBOX_WORKLOAD_POD_CONDITIONS),
72
+ cleanupStuck: 0,
73
+ expirationOverdue: 0,
74
+ };
75
+
76
+ await visitKubernetesList({
77
+ apiUrl,
78
+ requestJson,
79
+ path: `/apis/sandbox.opensandbox.io/v1alpha1/namespaces/${encodeURIComponent(namespace)}/batchsandboxes`,
80
+ visit: (item) => observeBatchSandbox(inventory, item, nowMs),
81
+ });
82
+ await visitKubernetesList({
83
+ apiUrl,
84
+ requestJson,
85
+ path: `/api/v1/namespaces/${encodeURIComponent(namespace)}/pods`,
86
+ query: { labelSelector: "opensandbox.io/id" },
87
+ visit: (item) => observeWorkloadPod(inventory, item),
88
+ });
89
+
90
+ return inventory;
91
+ }
92
+
93
+ function observeBatchSandbox(
94
+ inventory: OpenSandboxKubernetesInventory,
95
+ item: unknown,
96
+ nowMs: number,
97
+ ): void {
98
+ const resource = record(item);
99
+ const metadata = record(resource.metadata);
100
+ const spec = record(resource.spec);
101
+ const status = record(resource.status);
102
+
103
+ inventory.batchSandboxPhases[batchSandboxPhase(status.phase)] += 1;
104
+
105
+ const deletionTimestampMs = dateMilliseconds(metadata.deletionTimestamp);
106
+ const finalizers = Array.isArray(metadata.finalizers) ? metadata.finalizers : [];
107
+ if (
108
+ deletionTimestampMs !== null &&
109
+ finalizers.length > 0 &&
110
+ nowMs - deletionTimestampMs >= OPENSANDBOX_CLEANUP_STUCK_SECONDS * 1_000
111
+ ) {
112
+ inventory.cleanupStuck += 1;
113
+ }
114
+
115
+ const expirationMs = dateMilliseconds(spec.expireTime);
116
+ if (
117
+ expirationMs !== null &&
118
+ nowMs - expirationMs >= OPENSANDBOX_EXPIRATION_OVERDUE_SECONDS * 1_000
119
+ ) {
120
+ inventory.expirationOverdue += 1;
121
+ }
122
+ }
123
+
124
+ function observeWorkloadPod(inventory: OpenSandboxKubernetesInventory, item: unknown): void {
125
+ const pod = record(item);
126
+ const metadata = record(pod.metadata);
127
+ if (dateMilliseconds(metadata.deletionTimestamp) !== null) return;
128
+
129
+ const status = record(pod.status);
130
+ if (status.phase === "Pending") inventory.workloadPodConditions.pending += 1;
131
+ if (podHasImagePullFailure(status)) inventory.workloadPodConditions.image_pull += 1;
132
+ if (podIsUnschedulable(status)) inventory.workloadPodConditions.unschedulable += 1;
133
+ }
134
+
135
+ function podHasImagePullFailure(status: JsonRecord): boolean {
136
+ for (const key of ["initContainerStatuses", "containerStatuses", "ephemeralContainerStatuses"]) {
137
+ const statuses = Array.isArray(status[key]) ? status[key] : [];
138
+ for (const value of statuses) {
139
+ const waiting = record(record(record(value).state).waiting);
140
+ if (typeof waiting.reason === "string" && IMAGE_PULL_REASONS.has(waiting.reason)) return true;
141
+ }
142
+ }
143
+ return false;
144
+ }
145
+
146
+ function podIsUnschedulable(status: JsonRecord): boolean {
147
+ const conditions = Array.isArray(status.conditions) ? status.conditions : [];
148
+ return conditions.some((value) => {
149
+ const condition = record(value);
150
+ return (
151
+ condition.type === "PodScheduled" &&
152
+ condition.status === "False" &&
153
+ condition.reason === "Unschedulable"
154
+ );
155
+ });
156
+ }
157
+
158
+ function batchSandboxPhase(value: unknown): OpenSandboxBatchSandboxPhase {
159
+ switch (value) {
160
+ case "Pending":
161
+ return "pending";
162
+ case "Succeed":
163
+ case "Running":
164
+ return "running";
165
+ case "Pausing":
166
+ return "pausing";
167
+ case "Paused":
168
+ return "paused";
169
+ case "Resuming":
170
+ return "resuming";
171
+ case "Failed":
172
+ return "failed";
173
+ default:
174
+ return "unknown";
175
+ }
176
+ }
177
+
178
+ async function visitKubernetesList(input: {
179
+ apiUrl: URL;
180
+ requestJson: KubernetesJsonRequest;
181
+ path: string;
182
+ query?: Record<string, string>;
183
+ visit: (item: unknown) => void;
184
+ }): Promise<void> {
185
+ let continuation = "";
186
+ for (let page = 0; page < KUBERNETES_LIST_MAX_PAGES; page += 1) {
187
+ const url = new URL(input.path, input.apiUrl);
188
+ url.searchParams.set("limit", String(KUBERNETES_LIST_PAGE_SIZE));
189
+ for (const [key, value] of Object.entries(input.query ?? {})) {
190
+ url.searchParams.set(key, value);
191
+ }
192
+ if (continuation) url.searchParams.set("continue", continuation);
193
+
194
+ const payload = record(await input.requestJson(url));
195
+ if (!Array.isArray(payload.items)) {
196
+ throw new Error(`Kubernetes list ${input.path} returned no items array`);
197
+ }
198
+ for (const item of payload.items) input.visit(item);
199
+
200
+ const next = record(payload.metadata).continue;
201
+ if (typeof next !== "string" || next.length === 0) return;
202
+ if (next === continuation) {
203
+ throw new Error(`Kubernetes list ${input.path} repeated its continuation token`);
204
+ }
205
+ continuation = next;
206
+ }
207
+ throw new Error(`Kubernetes list ${input.path} exceeded its page safety bound`);
208
+ }
209
+
210
+ async function authenticatedKubernetesJsonRequest(input: {
211
+ tokenFile: string;
212
+ caFile: string;
213
+ }): Promise<KubernetesJsonRequest> {
214
+ const [tokenText, ca] = await Promise.all([
215
+ readFile(input.tokenFile, "utf8"),
216
+ readFile(input.caFile),
217
+ ]);
218
+ const token = tokenText.trim();
219
+ if (!token) throw new Error("OpenSandbox Kubernetes inventory token is empty");
220
+
221
+ return async (url) =>
222
+ await new Promise<unknown>((resolve, reject) => {
223
+ const request = httpsRequest(
224
+ url,
225
+ {
226
+ method: "GET",
227
+ ca,
228
+ headers: {
229
+ accept: "application/json",
230
+ authorization: `Bearer ${token}`,
231
+ },
232
+ },
233
+ (response) => {
234
+ const chunks: Buffer[] = [];
235
+ let bytes = 0;
236
+ response.on("data", (chunk: Buffer | string) => {
237
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
238
+ bytes += buffer.length;
239
+ if (bytes > KUBERNETES_RESPONSE_MAX_BYTES) {
240
+ request.destroy(new Error("Kubernetes inventory response exceeded its byte limit"));
241
+ return;
242
+ }
243
+ chunks.push(buffer);
244
+ });
245
+ response.on("end", () => {
246
+ const statusCode = response.statusCode ?? 0;
247
+ if (statusCode < 200 || statusCode >= 300) {
248
+ reject(new Error(`Kubernetes inventory request failed with HTTP ${statusCode}`));
249
+ return;
250
+ }
251
+ try {
252
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
253
+ } catch {
254
+ reject(new Error("Kubernetes inventory response was not valid JSON"));
255
+ }
256
+ });
257
+ response.on("error", reject);
258
+ },
259
+ );
260
+ request.setTimeout(KUBERNETES_REQUEST_TIMEOUT_MS, () => {
261
+ request.destroy(new Error("Kubernetes inventory request timed out"));
262
+ });
263
+ request.on("error", reject);
264
+ request.end();
265
+ });
266
+ }
267
+
268
+ function kubernetesNamespace(value: string): string {
269
+ const namespace = value.trim();
270
+ if (
271
+ namespace.length === 0 ||
272
+ namespace.length > 63 ||
273
+ !/^[a-z0-9](?:[-a-z0-9]*[a-z0-9])?$/u.test(namespace)
274
+ ) {
275
+ throw new Error("OpenSandbox Kubernetes inventory namespace is invalid");
276
+ }
277
+ return namespace;
278
+ }
279
+
280
+ function dateMilliseconds(value: unknown): number | null {
281
+ if (typeof value !== "string" || value.length === 0) return null;
282
+ const milliseconds = Date.parse(value);
283
+ return Number.isFinite(milliseconds) ? milliseconds : null;
284
+ }
285
+
286
+ function record(value: unknown): JsonRecord {
287
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
288
+ }
289
+
290
+ function zeroRecord<const T extends readonly string[]>(keys: T): Record<T[number], number> {
291
+ return Object.fromEntries(keys.map((key) => [key, 0])) as Record<T[number], number>;
292
+ }
@@ -0,0 +1,331 @@
1
+ import type { Settings } from "@opengeni/config";
2
+ import {
3
+ type ConnectionCredentialsPort,
4
+ type GitCredentialRepositoryRef,
5
+ type McpPersonalConnectionDelegation,
6
+ } from "@opengeni/contracts";
7
+ import {
8
+ isPersonalGitHubConnection,
9
+ PersonalGitHubConnectionMetadata,
10
+ } from "@opengeni/contracts/personal-github";
11
+ import {
12
+ getConnectionMetadata,
13
+ getPersonalGitHubRepositorySelectionState,
14
+ getSessionAuthorityProjection,
15
+ getSessionTurnForAttempt,
16
+ resolveAcceptedConnectionUse,
17
+ type Database,
18
+ } from "@opengeni/db";
19
+ import {
20
+ PERSONAL_GITHUB_GIT_BROKER_TOKEN_TTL_SECONDS,
21
+ personalGitHubGitBrokerRouteId,
22
+ sealPersonalGitHubGitBrokerClaims,
23
+ type PersonalGitHubGitBrokerClaims,
24
+ type PersonalGitHubGitBrokerRepositoryClaim,
25
+ } from "@opengeni/github";
26
+ import { randomBytes, randomUUID } from "node:crypto";
27
+ import { isDeepStrictEqual } from "node:util";
28
+
29
+ const PERSONAL_GITHUB_SERVER_ID = "github:personal";
30
+
31
+ /**
32
+ * Build the standalone personal-GitHub credential consumer. It returns only an
33
+ * OpenGeni broker bearer: the broad provider OAuth token remains encrypted in
34
+ * the API/database process and never crosses into a sandbox or worker result.
35
+ */
36
+ export function buildPersonalGitHubGitCredentials(
37
+ db: Database,
38
+ settings: Settings,
39
+ ): NonNullable<ConnectionCredentialsPort["gitCredentials"]> | null {
40
+ if (!settings.githubPersonalOauthEnabled) return null;
41
+ const secret = settings.integrationsStateSecret?.trim();
42
+ const publicOrigin = personalGitBrokerOrigin(settings.publicBaseUrl);
43
+ if (!secret || !publicOrigin) {
44
+ throw new Error("personal GitHub Git broker configuration is unavailable");
45
+ }
46
+
47
+ return async (request) => {
48
+ if (request.provider && request.provider !== "github") {
49
+ throw new Error("personal GitHub Git broker accepts only GitHub repositories");
50
+ }
51
+ if (!request.credentialBindingId || !request.repositoryRefs?.length) {
52
+ throw new Error("personal GitHub Git broker requires one exact credential binding");
53
+ }
54
+ const turn = await getSessionTurnForAttempt(
55
+ db,
56
+ request.workspaceId,
57
+ request.sessionId,
58
+ request.attemptId,
59
+ );
60
+ const session = await getSessionAuthorityProjection(db, request.workspaceId, request.sessionId);
61
+ if (
62
+ !turn ||
63
+ !session ||
64
+ turn.id !== request.turnId ||
65
+ turn.executionGeneration !== request.executionGeneration ||
66
+ !isDeepStrictEqual(turn.initiator, request.initiator) ||
67
+ !isDeepStrictEqual(turn.initiatorContext, request.initiatorContext) ||
68
+ session.rootSessionId !== request.rootSessionId
69
+ ) {
70
+ throw new Error("personal GitHub Git credential authority is no longer current");
71
+ }
72
+ const delegation = exactPersonalGitHubDelegation(
73
+ turn.personalConnectionDelegations,
74
+ request.credentialBindingId,
75
+ );
76
+ const snapshot = delegation.personalGitHubRepositorySelection!;
77
+ const repositories = exactRequestedRepositories(
78
+ request.repositoryRefs,
79
+ snapshot.credentialBindingId,
80
+ snapshot.repositories,
81
+ );
82
+
83
+ const resolution = await resolveAcceptedConnectionUse(db, {
84
+ accountId: request.accountId,
85
+ workspaceId: request.workspaceId,
86
+ sessionId: request.sessionId,
87
+ turnId: request.turnId,
88
+ attemptId: request.attemptId,
89
+ executionGeneration: request.executionGeneration,
90
+ physicalRequestId: randomUUID(),
91
+ usePhase: "credential_resolution",
92
+ serverId: PERSONAL_GITHUB_SERVER_ID,
93
+ connectionId: delegation.connectionId,
94
+ providerDomain: "github.com",
95
+ connectionKind: "oauth2",
96
+ subjectScope: "subject",
97
+ ownerSubjectId: delegation.ownerSubjectId,
98
+ });
99
+ if (
100
+ resolution.status !== "authorized" ||
101
+ resolution.originWorkspaceId !== delegation.originWorkspaceId ||
102
+ resolution.attribution.connectionId !== delegation.connectionId ||
103
+ resolution.attribution.connectionGeneration !== snapshot.connectionAuthorityGeneration ||
104
+ resolution.attribution.ownerSubjectId !== delegation.ownerSubjectId
105
+ ) {
106
+ throw new Error("personal GitHub Git connection authority is no longer current");
107
+ }
108
+
109
+ const connection = await getConnectionMetadata(
110
+ db,
111
+ delegation.originWorkspaceId!,
112
+ delegation.connectionId,
113
+ delegation.ownerSubjectId,
114
+ );
115
+ if (
116
+ !connection ||
117
+ connection.accountId !== request.accountId ||
118
+ connection.workspaceId !== delegation.originWorkspaceId ||
119
+ connection.subjectId !== delegation.ownerSubjectId ||
120
+ connection.status !== "active" ||
121
+ // connections.version is credential-refresh CAS, not use authority.
122
+ // resolveAcceptedConnectionUse above fences the independent common
123
+ // connection-authority generation carried by the accepted snapshot.
124
+ connection.grantedScopes.length !== 1 ||
125
+ connection.grantedScopes[0] !== "repo" ||
126
+ !isPersonalGitHubConnection(connection)
127
+ ) {
128
+ throw new Error("personal GitHub Git connection is unavailable");
129
+ }
130
+ const metadata = PersonalGitHubConnectionMetadata.parse(connection.metadata);
131
+ const currentSelection = await getPersonalGitHubRepositorySelectionState(db, {
132
+ accountId: request.accountId,
133
+ originWorkspaceId: delegation.originWorkspaceId!,
134
+ subjectId: delegation.ownerSubjectId,
135
+ connectionId: delegation.connectionId,
136
+ });
137
+ if (
138
+ !currentSelection ||
139
+ currentSelection.connectionAuthorityGeneration !== snapshot.connectionAuthorityGeneration ||
140
+ currentSelection.selectionGeneration !== snapshot.selectionGeneration ||
141
+ currentSelection.credentialBindingId !== snapshot.credentialBindingId ||
142
+ currentSelection.credentialBindingId !== metadata.credentialBindingId ||
143
+ currentSelection.providerPrincipalId !== metadata.providerPrincipalId ||
144
+ metadata.githubUserId !== metadata.providerPrincipalId
145
+ ) {
146
+ throw new Error("personal GitHub repository authority changed");
147
+ }
148
+ const currentById = new Map(
149
+ currentSelection.repositories.map((repository) => [repository.repositoryId, repository]),
150
+ );
151
+ for (const repository of repositories) {
152
+ const current = currentById.get(repository.repositoryId);
153
+ if (
154
+ !current ||
155
+ current.fullName !== repository.fullName ||
156
+ current.canonicalUrl !== repository.canonicalUrl ||
157
+ current.selectionGeneration !== repository.selectionGeneration ||
158
+ current.disabled ||
159
+ (repository.access === "write" &&
160
+ (current.selectedAccess !== "write" ||
161
+ current.archived ||
162
+ !personalGitHubCanWrite(current.permissions))) ||
163
+ !personalGitHubCanRead(current.permissions)
164
+ ) {
165
+ throw new Error("personal GitHub repository authority changed");
166
+ }
167
+ }
168
+
169
+ const identity = {
170
+ name: metadata.githubLogin,
171
+ email: `${metadata.githubUserId}+${metadata.githubLogin}@users.noreply.github.com`,
172
+ };
173
+ if (request.purpose === "identity") {
174
+ return {
175
+ workspaceId: request.workspaceId,
176
+ credentialBindingId: request.credentialBindingId,
177
+ provider: "github",
178
+ providerHost: "github.com",
179
+ identity,
180
+ };
181
+ }
182
+
183
+ const now = Math.floor(Date.now() / 1_000);
184
+ const baseClaims = {
185
+ version: 1 as const,
186
+ accountId: request.accountId,
187
+ workspaceId: request.workspaceId,
188
+ sessionId: request.sessionId,
189
+ rootSessionId: request.rootSessionId,
190
+ turnId: request.turnId,
191
+ attemptId: request.attemptId,
192
+ executionGeneration: request.executionGeneration,
193
+ originWorkspaceId: delegation.originWorkspaceId!,
194
+ connectionId: delegation.connectionId,
195
+ connectionAuthorityGeneration: snapshot.connectionAuthorityGeneration,
196
+ ownerSubjectId: delegation.ownerSubjectId,
197
+ credentialBindingId: snapshot.credentialBindingId,
198
+ selectionGeneration: snapshot.selectionGeneration,
199
+ };
200
+ const repositoryClaims: PersonalGitHubGitBrokerRepositoryClaim[] = repositories.map(
201
+ (repository) => ({
202
+ ...repository,
203
+ routeId: personalGitHubGitBrokerRouteId(secret, {
204
+ ...baseClaims,
205
+ repository,
206
+ }),
207
+ }),
208
+ );
209
+ const claims: PersonalGitHubGitBrokerClaims = {
210
+ ...baseClaims,
211
+ nonce: randomBytes(24).toString("base64url"),
212
+ issuedAt: now,
213
+ expiresAt: now + PERSONAL_GITHUB_GIT_BROKER_TOKEN_TTL_SECONDS,
214
+ };
215
+ return {
216
+ token: sealPersonalGitHubGitBrokerClaims(secret, claims),
217
+ expiresAt: new Date(claims.expiresAt * 1_000).toISOString(),
218
+ workspaceId: request.workspaceId,
219
+ credentialBindingId: request.credentialBindingId,
220
+ provider: "github",
221
+ providerHost: "github.com",
222
+ identity,
223
+ transport: {
224
+ kind: "http_broker",
225
+ repositories: repositoryClaims.map((repository) => ({
226
+ repositoryUri: repository.canonicalUrl,
227
+ brokerUri: `${publicOrigin}/v1/git/personal/${repository.routeId}`,
228
+ })),
229
+ },
230
+ };
231
+ };
232
+ }
233
+
234
+ function personalGitHubCanRead(permissions: {
235
+ pull: boolean;
236
+ triage: boolean;
237
+ push: boolean;
238
+ maintain: boolean;
239
+ admin: boolean;
240
+ }): boolean {
241
+ return (
242
+ permissions.pull ||
243
+ permissions.triage ||
244
+ permissions.push ||
245
+ permissions.maintain ||
246
+ permissions.admin
247
+ );
248
+ }
249
+
250
+ function personalGitHubCanWrite(permissions: {
251
+ push: boolean;
252
+ maintain: boolean;
253
+ admin: boolean;
254
+ }): boolean {
255
+ return permissions.push || permissions.maintain || permissions.admin;
256
+ }
257
+
258
+ function personalGitBrokerOrigin(value: string | undefined): string | null {
259
+ if (!value) return null;
260
+ const url = new URL(value);
261
+ if (
262
+ url.protocol !== "https:" ||
263
+ url.username ||
264
+ url.password ||
265
+ url.pathname !== "/" ||
266
+ url.search ||
267
+ url.hash
268
+ ) {
269
+ return null;
270
+ }
271
+ return url.origin;
272
+ }
273
+
274
+ function exactPersonalGitHubDelegation(
275
+ delegations: McpPersonalConnectionDelegation[],
276
+ credentialBindingId: string,
277
+ ): McpPersonalConnectionDelegation {
278
+ const matches = delegations.filter(
279
+ (delegation) =>
280
+ delegation.serverId === PERSONAL_GITHUB_SERVER_ID &&
281
+ delegation.connectionType === "github_personal" &&
282
+ delegation.personalGitHubRepositorySelection?.credentialBindingId === credentialBindingId,
283
+ );
284
+ const delegation = matches[0];
285
+ if (
286
+ matches.length !== 1 ||
287
+ !delegation ||
288
+ delegation.providerDomain !== "github.com" ||
289
+ delegation.kind !== "oauth2" ||
290
+ !delegation.originWorkspaceId ||
291
+ !delegation.userDelegation ||
292
+ !delegation.personalGitHubRepositorySelection
293
+ ) {
294
+ throw new Error("personal GitHub Git delegation is unavailable");
295
+ }
296
+ return delegation;
297
+ }
298
+
299
+ function exactRequestedRepositories(
300
+ refs: GitCredentialRepositoryRef[],
301
+ credentialBindingId: string,
302
+ snapshots: NonNullable<
303
+ McpPersonalConnectionDelegation["personalGitHubRepositorySelection"]
304
+ >["repositories"],
305
+ ): Array<Omit<PersonalGitHubGitBrokerRepositoryClaim, "routeId">> {
306
+ if (refs.length !== snapshots.length) {
307
+ throw new Error("personal GitHub Git request does not match the accepted repository set");
308
+ }
309
+ const byCanonicalUrl = new Map(
310
+ snapshots.map((repository) => [repository.canonicalUrl, repository]),
311
+ );
312
+ const seen = new Set<string>();
313
+ return refs.map((ref) => {
314
+ const snapshot = byCanonicalUrl.get(ref.uri);
315
+ if (
316
+ !snapshot ||
317
+ seen.has(ref.uri) ||
318
+ ref.provider !== "github" ||
319
+ ref.credentialBindingId !== credentialBindingId ||
320
+ ref.connectionId !== undefined ||
321
+ ref.installationId !== undefined ||
322
+ String(ref.repositoryId) !== snapshot.repositoryId ||
323
+ ref.ref !== snapshot.ref ||
324
+ ref.access !== snapshot.access
325
+ ) {
326
+ throw new Error("personal GitHub Git request exceeds the accepted repository authority");
327
+ }
328
+ seen.add(ref.uri);
329
+ return snapshot;
330
+ });
331
+ }