@opengeni/worker-bundle 0.7.5 → 0.10.8

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 (44) hide show
  1. package/dist/chunk-BJUW5LCM.js +325 -0
  2. package/dist/chunk-BJUW5LCM.js.map +1 -0
  3. package/dist/host-export.d.ts +70 -0
  4. package/dist/host-export.js +7 -0
  5. package/dist/host-export.js.map +1 -0
  6. package/dist/index.d.ts +98 -6
  7. package/dist/index.js +4097 -1271
  8. package/dist/index.js.map +1 -1
  9. package/dist/workflow-bundle.js +12360 -0
  10. package/package.json +18 -12
  11. package/src/activities/agent-turn.ts +2674 -828
  12. package/src/activities/capabilities.ts +11 -2
  13. package/src/activities/codex-capacity.ts +6 -11
  14. package/src/activities/codex-rotation.ts +75 -86
  15. package/src/activities/context-compaction.ts +104 -24
  16. package/src/activities/environment.ts +503 -97
  17. package/src/activities/expiring-material-renewal.ts +143 -0
  18. package/src/activities/goals.ts +4 -0
  19. package/src/activities/mcp-credentials.ts +38 -0
  20. package/src/activities/packs.ts +115 -2
  21. package/src/activities/rig-verification.ts +897 -244
  22. package/src/activities/run-credential-renewal.ts +70 -0
  23. package/src/activities/run-credentials.ts +132 -0
  24. package/src/activities/run-input.ts +23 -0
  25. package/src/activities/sandbox-lease.ts +33 -2
  26. package/src/activities/scheduled-tasks.ts +21 -0
  27. package/src/activities/session-state.ts +72 -0
  28. package/src/activities/streaming.ts +1 -0
  29. package/src/activities/toolspace-token-renewal.ts +57 -0
  30. package/src/activities/types.ts +44 -6
  31. package/src/activities/workspace-capture.ts +113 -93
  32. package/src/activities.ts +10 -2
  33. package/src/host-export-pump.ts +416 -0
  34. package/src/host-export.ts +22 -0
  35. package/src/http.ts +77 -28
  36. package/src/index.ts +360 -156
  37. package/src/observability-metrics.ts +83 -15
  38. package/src/sandbox-resume.ts +47 -1
  39. package/src/sandbox-routing.ts +1 -1
  40. package/src/worker-service-lifecycle.ts +104 -0
  41. package/src/workflows/activities.ts +13 -7
  42. package/src/workflows/rig-verification.ts +3 -1
  43. package/src/workflows/session.ts +219 -23
  44. package/src/workflows.ts +1 -0
@@ -5,13 +5,19 @@ import {
5
5
  type Settings,
6
6
  } from "@opengeni/config";
7
7
  import {
8
+ gitCredentialBindingIdForRepository,
9
+ gitCredentialProviderForRepository,
8
10
  signDelegatedAccessToken,
9
11
  type ConnectionCredentialsPort,
10
12
  type GitCredentialProvider,
11
13
  type GitCredentialRepositoryRef,
14
+ type GitCredentialTransport,
12
15
  type GitCredentials,
13
16
  type ResourceRef,
14
17
  type SandboxSecrets,
18
+ type SessionTurn,
19
+ type TurnInitiator,
20
+ type TurnInitiatorContext,
15
21
  } from "@opengeni/contracts";
16
22
  import {
17
23
  loadVariableSetForRun as loadWorkspaceEnvironmentForRunFromDb,
@@ -29,8 +35,8 @@ export {
29
35
  type WorkspaceEnvironmentForRun,
30
36
  };
31
37
 
32
- // §7.6 P4a — the run's workspace identity, threaded so the connection-credential
33
- // provider can be called with the run's tenant context AND so the FORK-7
38
+ // §7.6 connection-credential provider — the run's workspace identity, threaded so the connection-credential
39
+ // provider can be called with the run's tenant context AND so the workspace-scope cross-check
34
40
  // cross-check has the run's workspace to assert the provider's echo against.
35
41
  export type ConnectionScope = {
36
42
  accountId: string;
@@ -39,12 +45,95 @@ export type ConnectionScope = {
39
45
 
40
46
  export type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;
41
47
  export type GitTokenExpiries = Partial<Record<GitCredentialProvider, string>>;
48
+ export type GitCredentialBindingSeed = {
49
+ credentialBindingId: string;
50
+ provider: GitCredentialProvider;
51
+ token: string;
52
+ transport?: GitCredentialTransport;
53
+ expiresAt?: string;
54
+ providerBindingCount?: number;
55
+ };
42
56
  export type MintedRunGitCredentials = {
57
+ bindings: GitCredentialBindingSeed[];
58
+ // Compatibility views exist only when a provider has exactly one binding.
59
+ // A multi-binding provider intentionally has no provider-level alias.
43
60
  gitTokens: GitTokenSeeds;
44
61
  expiresAt: GitTokenExpiries;
45
62
  };
46
63
 
47
- // §7.6 P4a — load the run's workspace environment, delegating the DECRYPT to a
64
+ export type GitHubTokenMintAuthorization = (selection: {
65
+ installationId: number;
66
+ repositoryIds: number[];
67
+ }) => Promise<void>;
68
+
69
+ export const TOOLSPACE_TOKEN_TTL_SECONDS = 60 * 60;
70
+
71
+ export type MintedSandboxToolspaceToken = {
72
+ token: string;
73
+ expiresAt: Date;
74
+ };
75
+
76
+ export type SandboxToolspaceAuthority = {
77
+ sessionId: string;
78
+ };
79
+
80
+ export async function mintSandboxToolspaceToken(
81
+ settings: Settings,
82
+ scope: ConnectionScope,
83
+ authority: SandboxToolspaceAuthority,
84
+ nowMs = Date.now(),
85
+ ): Promise<MintedSandboxToolspaceToken | undefined> {
86
+ if (!settings.toolspaceEnabled || !settings.delegationSecret) {
87
+ return undefined;
88
+ }
89
+ const expiresAtSeconds = Math.floor(nowMs / 1000) + TOOLSPACE_TOKEN_TTL_SECONDS;
90
+ const token = await signDelegatedAccessToken(settings.delegationSecret, {
91
+ accountId: scope.accountId,
92
+ workspaceId: scope.workspaceId,
93
+ subjectId: `sandbox:${authority.sessionId}`,
94
+ subjectLabel: "sandbox toolspace",
95
+ permissions: ["toolspace:call"],
96
+ sessionId: authority.sessionId,
97
+ exp: expiresAtSeconds,
98
+ });
99
+ return { token, expiresAt: new Date(expiresAtSeconds * 1000) };
100
+ }
101
+
102
+ export type GitCredentialAuthority = {
103
+ sessionId: string;
104
+ rootSessionId: string;
105
+ turnId: string;
106
+ attemptId: string;
107
+ executionGeneration: number;
108
+ initiator: TurnInitiator;
109
+ initiatorContext: TurnInitiatorContext;
110
+ };
111
+
112
+ export function gitCredentialAuthorityForTurn(input: {
113
+ sessionId: string;
114
+ rootSessionId: string;
115
+ attemptId: string;
116
+ turn: Pick<SessionTurn, "id" | "executionGeneration" | "initiator" | "initiatorContext">;
117
+ }): GitCredentialAuthority {
118
+ return {
119
+ sessionId: input.sessionId,
120
+ rootSessionId: input.rootSessionId,
121
+ turnId: input.turn.id,
122
+ attemptId: input.attemptId,
123
+ executionGeneration: input.turn.executionGeneration,
124
+ initiator: input.turn.initiator,
125
+ initiatorContext: input.turn.initiatorContext,
126
+ };
127
+ }
128
+
129
+ type RunGitCredentialOptions = {
130
+ scope?: ConnectionScope;
131
+ authority?: GitCredentialAuthority;
132
+ gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
133
+ authorizeGitHubTokenMint?: GitHubTokenMintAuthorization;
134
+ };
135
+
136
+ // §7.6 connection-credential provider — load the run's workspace environment, delegating the DECRYPT to a
48
137
  // host `sandboxSecrets` provider when one is bound (the host owns the secret
49
138
  // vault + encryption key in embedded/separate topologies) and otherwise running
50
139
  // today's local `environmentsEncryptionKeyBytes`-keyed decrypt byte-for-byte.
@@ -72,7 +161,7 @@ export async function loadWorkspaceEnvironmentForRunWithCredentials(
72
161
  workspaceId: scope.workspaceId,
73
162
  variableSetId: environmentId,
74
163
  });
75
- // FORK-7: the provider must echo THIS run's workspace before we apply its
164
+ // workspace-scope cross-check: the provider must echo THIS run's workspace before we apply its
76
165
  // decrypted values into the sandbox.
77
166
  assertWorkspaceEcho("sandboxSecrets", scope, secrets.workspaceId);
78
167
  return {
@@ -83,7 +172,7 @@ export async function loadWorkspaceEnvironmentForRunWithCredentials(
83
172
  };
84
173
  }
85
174
 
86
- // §7.6 FORK-7 cross-check. A credential provider echoes the workspace it scoped
175
+ // Workspace-scope cross-check. A credential provider echoes the workspace it scoped
87
176
  // the credential to; we ASSERT it equals the run's workspace BEFORE the caller
88
177
  // injects the credential. A host mapping bug returning tenant B's creds for a
89
178
  // tenant-A run hard-throws here instead of landing tenant B's token in tenant
@@ -104,26 +193,25 @@ export async function sandboxEnvironmentForRun(
104
193
  settings: Settings,
105
194
  resources: ResourceRef[],
106
195
  workspaceEnvironment: Record<string, string> = {},
107
- // §7.6 P4a - optional host git-credential provider + the run scope it needs
196
+ // §7.6 connection-credential provider - optional host git-credential provider + the run scope it needs
108
197
  // (unset, the standalone default → self-mint from `settings` byte-for-byte).
109
198
  // `skipGitHubToken` (Stage D): a connected-machine turn skips the inert platform
110
199
  // token mint entirely and returns the stable base env unchanged. `deferGitHubToken`
111
200
  // is the lazy CLOUD path: apply stable git-auth pointers now, mint only the token
112
201
  // value later. `= {}` default so the non-optional reads below are safe.
113
- options: {
202
+ options: RunGitCredentialOptions & {
114
203
  skipGitHubToken?: boolean;
115
204
  deferGitHubToken?: boolean;
116
- scope?: ConnectionScope;
117
- gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
118
- sessionId?: string;
119
- runId?: string;
205
+ toolspaceAuthority?: SandboxToolspaceAuthority;
120
206
  } = {},
121
207
  ): Promise<{
122
208
  environment: Record<string, string>;
123
209
  gitToken?: string;
124
210
  gitTokens?: GitTokenSeeds;
125
211
  gitTokenExpiresAt?: GitTokenExpiries;
212
+ gitCredentialBindings?: GitCredentialBindingSeed[];
126
213
  toolspaceToken?: string;
214
+ toolspaceTokenExpiresAt?: Date;
127
215
  }> {
128
216
  // Precedence: deployment allowlist < git identity < workspace environment
129
217
  // < backend-aware HOME (the STABLE base, shared with the API-direct attach
@@ -148,30 +236,20 @@ export async function sandboxEnvironmentForRun(
148
236
  // backend, including a connected machine. Unlike platform git provider tokens
149
237
  // (inert on selfhosted → skipped above), the toolspace token is the machine's
150
238
  // only path to programmatic tool calling, and it grants no more than the
151
- // machine owner's own authority (toolspace:call, own-session-bound, turn TTL,
152
- // budgeted, approval-tools excluded). Delivery mirrors the docker path: the
153
- // caller threads it OFF-MANIFEST as the seed the runtime writes to
239
+ // machine owner's own authority (toolspace:call, own-session-bound,
240
+ // short-lived and renewable, per-active-turn budgeted, approval-tools
241
+ // excluded). Delivery mirrors the docker path: the caller threads it
242
+ // OFF-MANIFEST as the seed the runtime writes to
154
243
  // $OPENGENI_TOOLSPACE_TOKEN_FILE over the box's exec channel.
155
- let toolspaceToken: string | undefined;
156
- if (
157
- settings.toolspaceEnabled &&
158
- settings.delegationSecret &&
159
- options.scope &&
160
- options.sessionId &&
161
- options.runId
162
- ) {
163
- toolspaceToken = await signDelegatedAccessToken(settings.delegationSecret, {
164
- accountId: options.scope.accountId,
165
- workspaceId: options.scope.workspaceId,
166
- subjectId: `sandbox:${options.runId}`,
167
- subjectLabel: "sandbox toolspace",
168
- permissions: ["toolspace:call"],
169
- sessionId: options.sessionId,
170
- exp: Math.floor(Date.now() / 1000) + 60 * 60,
171
- });
244
+ const toolspaceScope = options.scope;
245
+ const toolspaceToken =
246
+ toolspaceScope && options.toolspaceAuthority
247
+ ? await mintSandboxToolspaceToken(settings, toolspaceScope, options.toolspaceAuthority)
248
+ : undefined;
249
+ if (toolspaceToken && toolspaceScope) {
172
250
  environment.OPENGENI_TOOLSPACE_URL ??= firstPartyMcpWorkspaceUrl(
173
251
  settings,
174
- options.scope.workspaceId,
252
+ toolspaceScope.workspaceId,
175
253
  );
176
254
  }
177
255
  const selections = gitCredentialSelections(resources);
@@ -185,14 +263,30 @@ export async function sandboxEnvironmentForRun(
185
263
  // (validateNoEnvironmentDelta). The API-direct viewer attach path already drops the
186
264
  // token under this exact contract — proof a box runs fine without it.
187
265
  if (selections.length === 0 || options.skipGitHubToken) {
188
- return { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };
266
+ return {
267
+ environment,
268
+ ...(toolspaceToken
269
+ ? {
270
+ toolspaceToken: toolspaceToken.token,
271
+ toolspaceTokenExpiresAt: toolspaceToken.expiresAt,
272
+ }
273
+ : {}),
274
+ };
189
275
  }
190
276
  if (options.deferGitHubToken) {
191
277
  applyGitAuthPointerEnvironment(
192
278
  environment,
193
279
  await resolveRunGitIdentityWithSelections(settings, selections, options),
194
280
  );
195
- return { environment, ...(toolspaceToken ? { toolspaceToken } : {}) };
281
+ return {
282
+ environment,
283
+ ...(toolspaceToken
284
+ ? {
285
+ toolspaceToken: toolspaceToken.token,
286
+ toolspaceTokenExpiresAt: toolspaceToken.expiresAt,
287
+ }
288
+ : {}),
289
+ };
196
290
  }
197
291
  // Run-scoped sandbox preparation for repository resources. GitHub retains the
198
292
  // legacy request shape and standalone self-mint path. Non-GitHub providers are
@@ -215,46 +309,69 @@ export async function sandboxEnvironmentForRun(
215
309
  ...(minted.gitTokens.github ? { gitToken: minted.gitTokens.github } : {}),
216
310
  ...(Object.keys(minted.gitTokens).length > 0 ? { gitTokens: minted.gitTokens } : {}),
217
311
  ...(Object.keys(minted.expiresAt).length > 0 ? { gitTokenExpiresAt: minted.expiresAt } : {}),
218
- ...(toolspaceToken ? { toolspaceToken } : {}),
312
+ ...(minted.bindings.length > 0 ? { gitCredentialBindings: minted.bindings } : {}),
313
+ ...(toolspaceToken
314
+ ? {
315
+ toolspaceToken: toolspaceToken.token,
316
+ toolspaceTokenExpiresAt: toolspaceToken.expiresAt,
317
+ }
318
+ : {}),
219
319
  };
220
320
  }
221
321
 
222
322
  export async function mintRunGitCredentials(
223
323
  settings: Settings,
224
324
  resources: ResourceRef[],
225
- options: {
226
- scope?: ConnectionScope;
227
- gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
228
- } = {},
325
+ options: RunGitCredentialOptions = {},
229
326
  ): Promise<MintedRunGitCredentials | undefined> {
230
327
  const selections = gitCredentialSelections(resources);
231
328
  if (selections.length === 0) {
232
329
  return undefined;
233
330
  }
234
331
  const minted = await mintRunGitTokensWithIdentity(settings, selections, options);
235
- return Object.keys(minted.gitTokens).length > 0
236
- ? { gitTokens: minted.gitTokens, expiresAt: minted.expiresAt }
332
+ return minted.bindings.length > 0
333
+ ? { bindings: minted.bindings, gitTokens: minted.gitTokens, expiresAt: minted.expiresAt }
237
334
  : undefined;
238
335
  }
239
336
 
337
+ export async function mintRunGitCredentialBinding(
338
+ settings: Settings,
339
+ resources: ResourceRef[],
340
+ provider: GitCredentialProvider,
341
+ credentialBindingId: string,
342
+ options: RunGitCredentialOptions = {},
343
+ ): Promise<GitCredentialBindingSeed | undefined> {
344
+ const selections = gitCredentialSelections(resources);
345
+ const selection = selections.find(
346
+ (candidate) =>
347
+ candidate.provider === provider && candidate.credentialBindingId === credentialBindingId,
348
+ );
349
+ if (!selection) {
350
+ return undefined;
351
+ }
352
+ const minted = await mintRunGitTokensWithIdentity(settings, [selection], options);
353
+ const binding = minted.bindings[0];
354
+ if (binding) {
355
+ binding.providerBindingCount = selections.filter(
356
+ (candidate) => candidate.provider === selection.provider,
357
+ ).length;
358
+ }
359
+ return binding;
360
+ }
361
+
240
362
  export async function mintRunGitTokens(
241
363
  settings: Settings,
242
364
  resources: ResourceRef[],
243
- options: {
244
- scope?: ConnectionScope;
245
- gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
246
- } = {},
365
+ options: RunGitCredentialOptions = {},
247
366
  ): Promise<GitTokenSeeds | undefined> {
248
- return (await mintRunGitCredentials(settings, resources, options))?.gitTokens;
367
+ const tokens = (await mintRunGitCredentials(settings, resources, options))?.gitTokens;
368
+ return tokens && Object.keys(tokens).length > 0 ? tokens : undefined;
249
369
  }
250
370
 
251
371
  export async function mintRunGitToken(
252
372
  settings: Settings,
253
373
  resources: ResourceRef[],
254
- options: {
255
- scope?: ConnectionScope;
256
- gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
257
- } = {},
374
+ options: RunGitCredentialOptions = {},
258
375
  ): Promise<string | undefined> {
259
376
  return (await mintRunGitTokens(settings, resources, options))?.github;
260
377
  }
@@ -262,10 +379,7 @@ export async function mintRunGitToken(
262
379
  export async function resolveRunGitIdentity(
263
380
  settings: Settings,
264
381
  resources: ResourceRef[],
265
- options: {
266
- scope?: ConnectionScope;
267
- gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
268
- } = {},
382
+ options: RunGitCredentialOptions = {},
269
383
  ): Promise<{ name: string; email: string } | null> {
270
384
  const selections = gitCredentialSelections(resources);
271
385
  if (selections.length === 0) {
@@ -277,38 +391,56 @@ export async function resolveRunGitIdentity(
277
391
  async function mintRunGitTokensWithIdentity(
278
392
  settings: Settings,
279
393
  selections: GitCredentialSelection[],
280
- options: {
281
- scope?: ConnectionScope;
282
- gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
283
- },
394
+ options: RunGitCredentialOptions,
284
395
  ): Promise<{
396
+ bindings: GitCredentialBindingSeed[];
285
397
  gitTokens: GitTokenSeeds;
286
398
  expiresAt: GitTokenExpiries;
287
399
  identity: { name: string; email: string } | null;
288
400
  }> {
289
- const gitTokens: GitTokenSeeds = {};
290
- const expiresAt: GitTokenExpiries = {};
401
+ const bindings: GitCredentialBindingSeed[] = [];
291
402
  let identity: { name: string; email: string } | null = null;
292
403
  for (const selection of selections) {
293
404
  let token: string | null = null;
405
+ let transport: GitCredentialTransport | undefined;
406
+ let tokenExpiresAt: string | undefined;
407
+ if (
408
+ selection.provider === "github" &&
409
+ selection.installationId > 0 &&
410
+ selection.repositoryIds.length > 0
411
+ ) {
412
+ // This callback belongs immediately next to the side effect. Turn startup
413
+ // performs its own admission check, but lazy provisioning and proactive
414
+ // renewal can happen much later in an intentionally unbounded run. Recheck
415
+ // the current workspace binding before every host-brokered or built-in
416
+ // GitHub installation-token mint.
417
+ await options.authorizeGitHubTokenMint?.({
418
+ installationId: selection.installationId,
419
+ repositoryIds: selection.repositoryIds,
420
+ });
421
+ }
294
422
  if (options?.gitCredentials && options.scope) {
295
- const request = gitCredentialsRequestForSelection(options.scope, selection, "token");
423
+ const request = gitCredentialsRequestForSelection(
424
+ options.scope,
425
+ requireGitCredentialAuthority(options),
426
+ selection,
427
+ "token",
428
+ );
296
429
  const minted: GitCredentials = await options.gitCredentials(request);
297
- // FORK-7: assert the provider scoped the token to THIS run's workspace
430
+ // workspace-scope cross-check: assert the provider scoped the token to THIS run's workspace
298
431
  // before accepting the token for clone seeding.
299
432
  assertWorkspaceEcho("gitCredentials", options.scope, minted.workspaceId);
433
+ assertGitCredentialBindingEcho(selection, request, minted);
300
434
  if (!minted.token) {
301
435
  throw new Error(
302
436
  "connection-credential provider (gitCredentials) did not return a token for a token request",
303
437
  );
304
438
  }
305
439
  token = minted.token;
306
- if (minted.expiresAt) {
307
- expiresAt[selection.provider] = validatedGitCredentialExpiry(
308
- selection.provider,
309
- minted.expiresAt,
310
- );
311
- }
440
+ transport = validatedGitCredentialTransport(selection, minted);
441
+ tokenExpiresAt = minted.expiresAt
442
+ ? validatedGitCredentialExpiry(selection.provider, minted.expiresAt)
443
+ : undefined;
312
444
  if (minted.identity) {
313
445
  identity = minted.identity;
314
446
  } else if (selection.provider === "github") {
@@ -320,16 +452,35 @@ async function mintRunGitTokensWithIdentity(
320
452
  repositoryIds: selection.repositoryIds,
321
453
  });
322
454
  token = minted.token;
323
- if (minted.expiresAt) {
324
- expiresAt.github = validatedGitCredentialExpiry("github", minted.expiresAt);
325
- }
455
+ tokenExpiresAt = minted.expiresAt
456
+ ? validatedGitCredentialExpiry("github", minted.expiresAt)
457
+ : undefined;
326
458
  identity = githubAppBotIdentity(settings);
327
459
  }
328
460
  if (token) {
329
- gitTokens[selection.provider] = token;
461
+ bindings.push({
462
+ credentialBindingId: selection.credentialBindingId,
463
+ provider: selection.provider,
464
+ token,
465
+ ...(transport ? { transport } : {}),
466
+ ...(tokenExpiresAt ? { expiresAt: tokenExpiresAt } : {}),
467
+ });
330
468
  }
331
469
  }
332
- return { gitTokens, expiresAt, identity };
470
+ const gitTokens: GitTokenSeeds = {};
471
+ const expiresAt: GitTokenExpiries = {};
472
+ const counts = new Map<GitCredentialProvider, number>();
473
+ for (const binding of bindings) {
474
+ counts.set(binding.provider, (counts.get(binding.provider) ?? 0) + 1);
475
+ }
476
+ for (const binding of bindings) {
477
+ binding.providerBindingCount = counts.get(binding.provider) ?? 1;
478
+ if (binding.transport?.kind === "http_broker") continue;
479
+ if (counts.get(binding.provider) !== 1) continue;
480
+ gitTokens[binding.provider] = binding.token;
481
+ if (binding.expiresAt) expiresAt[binding.provider] = binding.expiresAt;
482
+ }
483
+ return { bindings, gitTokens, expiresAt, identity };
333
484
  }
334
485
 
335
486
  function validatedGitCredentialExpiry(provider: GitCredentialProvider, value: string): string {
@@ -340,21 +491,145 @@ function validatedGitCredentialExpiry(provider: GitCredentialProvider, value: st
340
491
  return new Date(timestamp).toISOString();
341
492
  }
342
493
 
494
+ const MAX_GIT_HTTP_BROKER_ROUTES = 256;
495
+ const MAX_GIT_HTTP_BROKER_URI_LENGTH = 4_096;
496
+
497
+ function validatedGitCredentialTransport(
498
+ selection: GitCredentialSelection,
499
+ minted: GitCredentials,
500
+ ): GitCredentialTransport | undefined {
501
+ const transport = minted.transport;
502
+ if (!transport) return undefined;
503
+
504
+ if (
505
+ typeof transport !== "object" ||
506
+ transport.kind !== "http_broker" ||
507
+ !Array.isArray(transport.repositories)
508
+ ) {
509
+ throw new Error(
510
+ `connection-credential provider (${selection.provider}) returned an invalid Git credential transport`,
511
+ );
512
+ }
513
+ const requestedUris = new Set(selection.repositoryRefs.map((repository) => repository.uri));
514
+ if (
515
+ requestedUris.size === 0 ||
516
+ requestedUris.size > MAX_GIT_HTTP_BROKER_ROUTES ||
517
+ transport.repositories.length !== requestedUris.size
518
+ ) {
519
+ throw new Error(
520
+ `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,
521
+ );
522
+ }
523
+
524
+ const echoedUris = new Set<string>();
525
+ const brokerUris = new Set<string>();
526
+ const repositories = transport.repositories.map((route) => {
527
+ if (
528
+ !route ||
529
+ typeof route !== "object" ||
530
+ typeof route.repositoryUri !== "string" ||
531
+ typeof route.brokerUri !== "string"
532
+ ) {
533
+ throw new Error(
534
+ `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker route`,
535
+ );
536
+ }
537
+ if (!requestedUris.has(route.repositoryUri) || echoedUris.has(route.repositoryUri)) {
538
+ throw new Error(
539
+ `connection-credential provider (${selection.provider}) returned an unexpected Git HTTP broker repository`,
540
+ );
541
+ }
542
+ echoedUris.add(route.repositoryUri);
543
+ if (
544
+ route.brokerUri.length === 0 ||
545
+ route.brokerUri.length > MAX_GIT_HTTP_BROKER_URI_LENGTH ||
546
+ route.brokerUri.trim() !== route.brokerUri
547
+ ) {
548
+ throw new Error(
549
+ `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,
550
+ );
551
+ }
552
+ let brokerUrl: URL;
553
+ try {
554
+ brokerUrl = new URL(route.brokerUri);
555
+ } catch {
556
+ throw new Error(
557
+ `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,
558
+ );
559
+ }
560
+ if (
561
+ brokerUrl.protocol !== "https:" ||
562
+ brokerUrl.username ||
563
+ brokerUrl.password ||
564
+ brokerUrl.search ||
565
+ brokerUrl.hash ||
566
+ brokerUris.has(brokerUrl.href) ||
567
+ brokerUrl.href === route.repositoryUri
568
+ ) {
569
+ throw new Error(
570
+ `connection-credential provider (${selection.provider}) returned an unsafe Git HTTP broker URI`,
571
+ );
572
+ }
573
+ brokerUris.add(brokerUrl.href);
574
+ return {
575
+ repositoryUri: route.repositoryUri,
576
+ brokerUri: brokerUrl.href,
577
+ };
578
+ });
579
+
580
+ if ([...requestedUris].some((uri) => !echoedUris.has(uri))) {
581
+ throw new Error(
582
+ `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,
583
+ );
584
+ }
585
+ return { kind: "http_broker", repositories };
586
+ }
587
+
588
+ export function assertGitCredentialRenewalTransportUnchanged(
589
+ initial: GitCredentialBindingSeed,
590
+ renewed: GitCredentialBindingSeed,
591
+ ): void {
592
+ if (!initial.transport && !renewed.transport) return;
593
+ if (
594
+ !initial.transport ||
595
+ !renewed.transport ||
596
+ initial.transport.kind !== renewed.transport.kind
597
+ ) {
598
+ throw new Error(
599
+ `renewed ${initial.provider} credential changed transport for binding ${initial.credentialBindingId}`,
600
+ );
601
+ }
602
+ const routeKey = (route: { repositoryUri: string; brokerUri: string }) =>
603
+ `${route.repositoryUri}\u0000${route.brokerUri}`;
604
+ const initialRoutes = initial.transport.repositories.map(routeKey).sort();
605
+ const renewedRoutes = renewed.transport.repositories.map(routeKey).sort();
606
+ if (
607
+ initialRoutes.length !== renewedRoutes.length ||
608
+ initialRoutes.some((route, index) => route !== renewedRoutes[index])
609
+ ) {
610
+ throw new Error(
611
+ `renewed ${initial.provider} credential changed Git HTTP broker routes for binding ${initial.credentialBindingId}`,
612
+ );
613
+ }
614
+ }
615
+
343
616
  async function resolveRunGitIdentityWithSelections(
344
617
  settings: Settings,
345
618
  selections: GitCredentialSelection[],
346
- options: {
347
- scope?: ConnectionScope;
348
- gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
349
- },
619
+ options: RunGitCredentialOptions,
350
620
  ): Promise<{ name: string; email: string } | null> {
351
621
  let identity: { name: string; email: string } | null = null;
352
622
  for (const selection of selections) {
353
623
  if (options.gitCredentials && options.scope) {
354
- const resolved: GitCredentials = await options.gitCredentials(
355
- gitCredentialsRequestForSelection(options.scope, selection, "identity"),
624
+ const request = gitCredentialsRequestForSelection(
625
+ options.scope,
626
+ requireGitCredentialAuthority(options),
627
+ selection,
628
+ "identity",
356
629
  );
630
+ const resolved: GitCredentials = await options.gitCredentials(request);
357
631
  assertWorkspaceEcho("gitCredentials", options.scope, resolved.workspaceId);
632
+ assertGitCredentialBindingEcho(selection, request, resolved);
358
633
  if (resolved.identity) {
359
634
  identity = resolved.identity;
360
635
  } else if (selection.provider === "github") {
@@ -369,6 +644,10 @@ async function resolveRunGitIdentityWithSelections(
369
644
 
370
645
  type GitCredentialSelection = {
371
646
  provider: GitCredentialProvider;
647
+ credentialBindingId: string;
648
+ explicitCredentialBinding: boolean;
649
+ requireBindingEcho: boolean;
650
+ providerHost?: string;
372
651
  installationId: number;
373
652
  repositoryIds: number[];
374
653
  repositoryRefs: GitCredentialRepositoryRef[];
@@ -376,31 +655,106 @@ type GitCredentialSelection = {
376
655
 
377
656
  function gitCredentialsRequestForSelection(
378
657
  scope: ConnectionScope,
658
+ authority: GitCredentialAuthority,
379
659
  selection: GitCredentialSelection,
380
660
  purpose?: "token" | "identity",
381
661
  ): Parameters<NonNullable<ConnectionCredentialsPort["gitCredentials"]>>[0] {
382
662
  const legacy = {
383
663
  accountId: scope.accountId,
384
664
  workspaceId: scope.workspaceId,
665
+ ...authority,
385
666
  ...(purpose ? { purpose } : {}),
386
667
  installationId: selection.installationId,
387
668
  repositoryIds: selection.repositoryIds,
388
669
  };
670
+ const bindingEcho = selection.requireBindingEcho
671
+ ? {
672
+ credentialBindingId: selection.credentialBindingId,
673
+ provider: selection.provider,
674
+ ...(selection.providerHost ? { providerHost: selection.providerHost } : {}),
675
+ }
676
+ : {};
389
677
  if (selection.provider === "github") {
390
678
  return {
391
679
  ...legacy,
680
+ ...bindingEcho,
392
681
  repositoryRefs: selection.repositoryRefs,
393
682
  };
394
683
  }
395
684
  return {
396
685
  ...legacy,
686
+ ...bindingEcho,
397
687
  provider: selection.provider,
398
688
  repositoryRefs: selection.repositoryRefs,
399
689
  };
400
690
  }
401
691
 
692
+ function requireGitCredentialAuthority(options: RunGitCredentialOptions): GitCredentialAuthority {
693
+ if (!options.authority) {
694
+ throw new Error("host git credential resolution requires immutable session turn authority");
695
+ }
696
+ return options.authority;
697
+ }
698
+
699
+ function assertGitCredentialBindingEcho(
700
+ selection: GitCredentialSelection,
701
+ request: Parameters<NonNullable<ConnectionCredentialsPort["gitCredentials"]>>[0],
702
+ minted: GitCredentials,
703
+ ): void {
704
+ if (!selection.requireBindingEcho) return;
705
+ if (minted.credentialBindingId !== request.credentialBindingId) {
706
+ throw new Error(
707
+ `connection-credential provider (${selection.provider}) returned the wrong credential binding`,
708
+ );
709
+ }
710
+ if (minted.provider !== selection.provider) {
711
+ throw new Error(
712
+ `connection-credential provider (${selection.provider}) returned the wrong provider echo`,
713
+ );
714
+ }
715
+ if (request.providerHost && minted.providerHost !== request.providerHost) {
716
+ throw new Error(
717
+ `connection-credential provider (${selection.provider}) returned the wrong provider host echo`,
718
+ );
719
+ }
720
+ }
721
+
722
+ /**
723
+ * The GitHub App installation + repository ids a run's git-credential mint
724
+ * would use for these resources, or null when no GitHub token would be minted.
725
+ * Derived from gitCredentialSelections so workspace-authorization rechecks
726
+ * cover exactly the ids that reach createGitHubAppInstallationToken —
727
+ * including legacy string-typed installationId/repositoryId refs, which the
728
+ * mint path coerces via positiveInteger.
729
+ */
730
+ export function gitHubTokenMintSelections(
731
+ resources: ResourceRef[],
732
+ ): Array<{ installationId: number; repositoryIds: number[] }> {
733
+ return gitCredentialSelections(resources)
734
+ .filter(
735
+ (candidate) =>
736
+ candidate.provider === "github" &&
737
+ candidate.installationId > 0 &&
738
+ candidate.repositoryIds.length > 0,
739
+ )
740
+ .map(({ installationId, repositoryIds }) => ({ installationId, repositoryIds }));
741
+ }
742
+
743
+ /** @deprecated Use gitHubTokenMintSelections for multi-installation sessions. */
744
+ export function gitHubTokenMintSelection(
745
+ resources: ResourceRef[],
746
+ ): { installationId: number; repositoryIds: number[] } | null {
747
+ const selections = gitHubTokenMintSelections(resources);
748
+ if (selections.length > 1) {
749
+ throw new Error("GitHub resources span multiple credential bindings");
750
+ }
751
+ return selections[0] ?? null;
752
+ }
753
+
402
754
  function gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelection[] {
403
- const byProvider = new Map<GitCredentialProvider, GitCredentialSelection>();
755
+ const byBinding = new Map<string, GitCredentialSelection>();
756
+ const remoteBindings = new Map<string, string>();
757
+ const bindingProviders = new Map<string, GitCredentialProvider>();
404
758
  for (const resource of resources) {
405
759
  if (resource.kind !== "repository") {
406
760
  continue;
@@ -409,45 +763,95 @@ function gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelecti
409
763
  if (!provider) {
410
764
  continue;
411
765
  }
412
- const entry = byProvider.get(provider) ?? {
766
+ const installationId =
767
+ provider === "github"
768
+ ? (positiveInteger(resource.githubInstallationId ?? resource.installationId) ?? 0)
769
+ : 0;
770
+ const credentialBindingId = gitCredentialBindingIdForRepository(resource, provider)!;
771
+ const bindingKey = `${provider}\u0000${credentialBindingId}`;
772
+ const boundProvider = bindingProviders.get(credentialBindingId);
773
+ if (boundProvider && boundProvider !== provider) {
774
+ throw new Error(
775
+ `credential binding ${credentialBindingId} is assigned to multiple Git providers`,
776
+ );
777
+ }
778
+ bindingProviders.set(credentialBindingId, provider);
779
+ const normalizedRemote = normalizedGitRemote(resource.uri);
780
+ const claimedBinding = remoteBindings.get(normalizedRemote);
781
+ if (claimedBinding && claimedBinding !== bindingKey) {
782
+ throw new Error(
783
+ `repository remote ${resource.uri} is claimed by multiple credential bindings`,
784
+ );
785
+ }
786
+ remoteBindings.set(normalizedRemote, bindingKey);
787
+ const entry = byBinding.get(bindingKey) ?? {
413
788
  provider,
789
+ credentialBindingId,
790
+ explicitCredentialBinding: Boolean(resource.credentialBindingId),
791
+ requireBindingEcho: false,
414
792
  installationId: 0,
415
793
  repositoryIds: [],
416
794
  repositoryRefs: [],
417
795
  };
796
+ entry.explicitCredentialBinding ||= Boolean(resource.credentialBindingId);
418
797
  const ref = gitCredentialRepositoryRef(resource, provider);
419
798
  entry.repositoryRefs.push(ref);
420
799
  if (provider === "github") {
421
- const installationId = positiveInteger(
422
- resource.githubInstallationId ?? resource.installationId,
423
- );
424
800
  const repositoryId = positiveInteger(resource.githubRepositoryId ?? resource.repositoryId);
425
801
  if (installationId && repositoryId) {
426
802
  if (entry.installationId > 0 && entry.installationId !== installationId) {
427
- throw new Error("GitHub App repository resources must belong to one installation");
803
+ throw new Error(
804
+ `GitHub credential binding ${credentialBindingId} spans multiple installations`,
805
+ );
428
806
  }
429
807
  entry.installationId = installationId;
430
808
  entry.repositoryIds.push(repositoryId);
431
809
  }
432
810
  }
433
- byProvider.set(provider, entry);
811
+ byBinding.set(bindingKey, entry);
812
+ }
813
+ const selections = [...byBinding.values()];
814
+ const providerCounts = new Map<GitCredentialProvider, number>();
815
+ for (const selection of selections) {
816
+ providerCounts.set(selection.provider, (providerCounts.get(selection.provider) ?? 0) + 1);
817
+ const hosts = new Set(
818
+ selection.repositoryRefs.map((ref) => normalizedGitHost(ref.uri)).filter(Boolean),
819
+ );
820
+ const [providerHost] = hosts;
821
+ if (hosts.size === 1 && providerHost) selection.providerHost = providerHost;
822
+ }
823
+ for (const selection of selections) {
824
+ selection.requireBindingEcho =
825
+ selection.explicitCredentialBinding || (providerCounts.get(selection.provider) ?? 0) > 1;
826
+ }
827
+ return selections;
828
+ }
829
+
830
+ function normalizedGitHost(uri: string): string {
831
+ try {
832
+ return new URL(uri).host.toLowerCase();
833
+ } catch {
834
+ return "";
835
+ }
836
+ }
837
+
838
+ function normalizedGitRemote(uri: string): string {
839
+ try {
840
+ const url = new URL(uri);
841
+ return `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}${url.pathname.replace(/\/+$/, "").replace(/\.git$/, "")}`;
842
+ } catch {
843
+ return uri
844
+ .trim()
845
+ .replace(/\/+$/, "")
846
+ .replace(/\.git$/, "")
847
+ .toLowerCase();
434
848
  }
435
- return [...byProvider.values()];
436
849
  }
437
850
 
438
851
  function repositoryCredentialProvider(
439
852
  resource: Extract<ResourceRef, { kind: "repository" }>,
440
853
  ): GitCredentialProvider | null {
441
- if (resource.provider) {
442
- return resource.provider;
443
- }
444
- if (
445
- positiveInteger(resource.githubInstallationId) &&
446
- positiveInteger(resource.githubRepositoryId)
447
- ) {
448
- return "github";
449
- }
450
- return null;
854
+ return gitCredentialProviderForRepository(resource);
451
855
  }
452
856
 
453
857
  function gitCredentialRepositoryRef(
@@ -456,6 +860,8 @@ function gitCredentialRepositoryRef(
456
860
  ): GitCredentialRepositoryRef {
457
861
  return {
458
862
  provider,
863
+ ...(resource.credentialBindingId ? { credentialBindingId: resource.credentialBindingId } : {}),
864
+ ...(resource.access ? { access: resource.access } : {}),
459
865
  uri: resource.uri,
460
866
  ref: resource.ref,
461
867
  ...(resource.repositoryId !== undefined