@opengeni/worker-bundle 0.17.2 → 0.20.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 (75) hide show
  1. package/dist/activities/agent-run-admission.d.ts +12 -0
  2. package/dist/activities/agent-turn.d.ts +25 -0
  3. package/dist/activities/browser-state-artifact-reaper.d.ts +29 -0
  4. package/dist/activities/capabilities.d.ts +6 -0
  5. package/dist/activities/codex-capacity.d.ts +1 -0
  6. package/dist/activities/environment.d.ts +7 -1
  7. package/dist/activities/packs.d.ts +8 -10
  8. package/dist/activities/session-state.d.ts +4 -2
  9. package/dist/activities/site-auth-maintenance.d.ts +27 -0
  10. package/dist/activities/types.d.ts +16 -0
  11. package/dist/activities/video-generation-admission.d.ts +9 -4
  12. package/dist/activities/video-generation-credential.d.ts +17 -0
  13. package/dist/activities/video-reference-staging.d.ts +7 -1
  14. package/dist/activities/xai-auth.d.ts +23 -0
  15. package/dist/activities/xai-image-generation.d.ts +26 -0
  16. package/dist/activities/xai-video-generation.d.ts +18 -0
  17. package/dist/{activities-control-44KBWLSM.js → activities-control-XURE4VKN.js} +387 -51
  18. package/dist/activities-control-XURE4VKN.js.map +1 -0
  19. package/dist/activities-control.d.ts +8 -0
  20. package/dist/{activities-turn-K4CEDEGJ.js → activities-turn-6EBXGGLS.js} +5312 -3951
  21. package/dist/activities-turn-6EBXGGLS.js.map +1 -0
  22. package/dist/activities.d.ts +9 -1
  23. package/dist/{chunk-KKCRGAGZ.js → chunk-5GRJIP5H.js} +99 -98
  24. package/dist/chunk-5GRJIP5H.js.map +1 -0
  25. package/dist/{chunk-E3RI3I33.js → chunk-TYNPCG4U.js} +88 -10
  26. package/dist/chunk-TYNPCG4U.js.map +1 -0
  27. package/dist/index.d.ts +13 -0
  28. package/dist/index.js +49 -2
  29. package/dist/index.js.map +1 -1
  30. package/dist/model-checkpoint-memory-collector.d.ts +1 -0
  31. package/dist/model-context-contributions.d.ts +40 -0
  32. package/dist/observability-metrics.d.ts +20 -1
  33. package/dist/sandbox-routing.d.ts +4 -0
  34. package/dist/workflow-bundle.js +59 -15
  35. package/dist/workflows/activities.d.ts +1 -1
  36. package/dist/workflows/site-auth-maintenance.d.ts +2 -0
  37. package/dist/workflows.d.ts +1 -0
  38. package/package.json +16 -15
  39. package/src/activities/agent-run-admission.ts +76 -0
  40. package/src/activities/agent-turn.ts +1178 -142
  41. package/src/activities/browser-state-artifact-reaper.ts +120 -0
  42. package/src/activities/capabilities.ts +10 -0
  43. package/src/activities/codex-capacity.ts +48 -1
  44. package/src/activities/environment.ts +14 -8
  45. package/src/activities/goals.ts +2 -1
  46. package/src/activities/packs.ts +45 -122
  47. package/src/activities/parent-wake.ts +13 -1
  48. package/src/activities/scheduled-tasks.ts +30 -73
  49. package/src/activities/session-state.ts +18 -0
  50. package/src/activities/site-auth-maintenance.ts +269 -0
  51. package/src/activities/types.ts +17 -0
  52. package/src/activities/video-generation-admission.ts +37 -4
  53. package/src/activities/video-generation-credential.ts +84 -6
  54. package/src/activities/video-generation-reconciliation.ts +212 -19
  55. package/src/activities/video-media-validation.ts +8 -2
  56. package/src/activities/video-reference-staging.ts +121 -34
  57. package/src/activities/xai-auth.ts +122 -0
  58. package/src/activities/xai-image-generation.ts +86 -0
  59. package/src/activities/xai-video-generation.ts +69 -0
  60. package/src/activities-control.ts +4 -0
  61. package/src/activities.ts +5 -0
  62. package/src/index.ts +51 -0
  63. package/src/model-checkpoint-memory-collector.ts +8 -1
  64. package/src/model-context-contributions.ts +159 -0
  65. package/src/observability-metrics.ts +98 -9
  66. package/src/sandbox-routing.ts +13 -0
  67. package/src/workflows/activities.ts +1 -0
  68. package/src/workflows/file-upload-reaper.ts +8 -2
  69. package/src/workflows/session.ts +20 -6
  70. package/src/workflows/site-auth-maintenance.ts +14 -0
  71. package/src/workflows.ts +1 -0
  72. package/dist/activities-control-44KBWLSM.js.map +0 -1
  73. package/dist/activities-turn-K4CEDEGJ.js.map +0 -1
  74. package/dist/chunk-E3RI3I33.js.map +0 -1
  75. package/dist/chunk-KKCRGAGZ.js.map +0 -1
@@ -23,7 +23,7 @@ import {
23
23
  settingsWithRigImage,
24
24
  withFirstPartyTools,
25
25
  workflowIdForSession
26
- } from "./chunk-KKCRGAGZ.js";
26
+ } from "./chunk-5GRJIP5H.js";
27
27
  import {
28
28
  recordCreditBalanceGauges,
29
29
  recordCreditMicros,
@@ -39,7 +39,91 @@ import {
39
39
  recordSandboxOrphansTerminated,
40
40
  recordSandboxRotationBacklogGauges,
41
41
  recordTurnsQueuedGauge
42
- } from "./chunk-E3RI3I33.js";
42
+ } from "./chunk-TYNPCG4U.js";
43
+
44
+ // src/activities/browser-state-artifact-reaper.ts
45
+ import {
46
+ claimBrowserStateArtifactCleanup,
47
+ claimBrowserStateUploadCleanup,
48
+ completeBrowserStateArtifactCleanup,
49
+ completeBrowserStateUploadCleanup
50
+ } from "@opengeni/db";
51
+ var BROWSER_STATE_ARTIFACT_CLAIM_TIMEOUT_MS = 10 * 60 * 1e3;
52
+ var BROWSER_STATE_ARTIFACT_CLEANUP_BATCH_SIZE = 100;
53
+ var SAFE_PROVIDER_ERROR_CODES = /* @__PURE__ */ new Set([
54
+ "aborted",
55
+ "conflict",
56
+ "network",
57
+ "not_found",
58
+ "permission_denied",
59
+ "provider",
60
+ "timeout",
61
+ "unavailable"
62
+ ]);
63
+ function createBrowserStateArtifactMaintenanceActivities(services, options = {}) {
64
+ const claimTimeoutMs = options.claimTimeoutMs ?? BROWSER_STATE_ARTIFACT_CLAIM_TIMEOUT_MS;
65
+ const batchSize = options.batchSize ?? BROWSER_STATE_ARTIFACT_CLEANUP_BATCH_SIZE;
66
+ const claimArtifacts = options.claimArtifacts ?? claimBrowserStateArtifactCleanup;
67
+ const completeArtifact = options.completeArtifact ?? completeBrowserStateArtifactCleanup;
68
+ const claimUploads = options.claimUploads ?? claimBrowserStateUploadCleanup;
69
+ const completeUpload = options.completeUpload ?? completeBrowserStateUploadCleanup;
70
+ const deleteObject = options.deleteObject ?? ((storage, key) => storage.deleteObject(key));
71
+ async function maintainBrowserStateArtifacts() {
72
+ const { db, objectStorage, observability } = await services();
73
+ if (!objectStorage) return { claimed: 0, deleted: 0, retryable: 0 };
74
+ const [artifactClaims, uploadClaims] = await Promise.all([
75
+ claimArtifacts(db, { claimTimeoutMs, limit: batchSize }),
76
+ claimUploads(db, { claimTimeoutMs, limit: batchSize })
77
+ ]);
78
+ const result = {
79
+ claimed: artifactClaims.length + uploadClaims.length,
80
+ deleted: 0,
81
+ retryable: 0
82
+ };
83
+ for (const cleanup of artifactClaims) {
84
+ try {
85
+ await deleteObject(objectStorage, cleanup.objectKey);
86
+ if (!await completeArtifact(db, cleanup)) {
87
+ throw new Error("browser state artifact cleanup claim was superseded");
88
+ }
89
+ result.deleted += 1;
90
+ } catch (error) {
91
+ result.retryable += 1;
92
+ observability.warn("browser state artifact cleanup failed; claim remains reclaimable", {
93
+ workspaceId: cleanup.workspaceId,
94
+ artifactId: cleanup.artifactId,
95
+ errorCategory: cleanupErrorCategory(error)
96
+ });
97
+ }
98
+ }
99
+ for (const cleanup of uploadClaims) {
100
+ try {
101
+ await deleteObject(objectStorage, cleanup.objectKey);
102
+ if (!await completeUpload(db, cleanup)) {
103
+ throw new Error("browser state upload cleanup claim was superseded");
104
+ }
105
+ result.deleted += 1;
106
+ } catch (error) {
107
+ result.retryable += 1;
108
+ observability.warn("browser state upload cleanup failed; claim remains reclaimable", {
109
+ workspaceId: cleanup.workspaceId,
110
+ uploadId: cleanup.uploadId,
111
+ errorCategory: cleanupErrorCategory(error)
112
+ });
113
+ }
114
+ }
115
+ if (result.claimed > 0) {
116
+ observability.info("browser state artifact maintenance swept", result);
117
+ }
118
+ return result;
119
+ }
120
+ return { maintainBrowserStateArtifacts };
121
+ }
122
+ function cleanupErrorCategory(error) {
123
+ if (!error || typeof error !== "object") return "unknown";
124
+ const code = error.code;
125
+ return typeof code === "string" && SAFE_PROVIDER_ERROR_CODES.has(code) ? code : "unknown";
126
+ }
43
127
 
44
128
  // src/activities/documents.ts
45
129
  import { configuredStaticUsageLimits } from "@opengeni/config";
@@ -5994,13 +6078,12 @@ import {
5994
6078
  createSession,
5995
6079
  createSessionGoal,
5996
6080
  enqueueSessionWorkflowWakeIfRunnable,
5997
- getBillingBalance as getBillingBalance3,
5998
6081
  getScheduledTask as getScheduledTask2,
5999
6082
  ensureKnowledgeSourceSyncState,
6000
6083
  getScheduledTaskPersonalConnectionDelegations,
6084
+ getScheduledTaskXaiProviderAccountAuthoritySnapshot,
6001
6085
  getRig as getRig2,
6002
6086
  getVariableSet,
6003
- isCodexBilledTurn,
6004
6087
  markScheduledTaskRunFailedIfQueued,
6005
6088
  recordKnowledgeSourceSyncWake,
6006
6089
  recordUsageEvent as recordUsageEvent3,
@@ -6009,17 +6092,74 @@ import {
6009
6092
  setTemporalWorkflowId,
6010
6093
  settleScheduledTaskRunInTransaction,
6011
6094
  SessionSpawnDeniedDbError,
6012
- sumUsageQuantity as sumUsageQuantity2,
6013
6095
  updateScheduledTask,
6014
6096
  updateScheduledTaskRun as updateScheduledTaskRun2,
6015
6097
  upsertSessionGoal
6016
6098
  } from "@opengeni/db";
6017
6099
  import { appendAndPublishEvents, publishDurableSessionEvents } from "@opengeni/events";
6100
+ import { resolveFirstPartyMcpToolPolicy } from "@opengeni/config";
6101
+
6102
+ // src/activities/agent-run-admission.ts
6018
6103
  import { configuredStaticUsageLimits as configuredStaticUsageLimits2 } from "@opengeni/config";
6104
+ import { getBillingBalance as getBillingBalance3, isCodexBilledTurn, sumUsageQuantity as sumUsageQuantity2 } from "@opengeni/db";
6105
+ async function agentRunAdmissionDenial(services, input) {
6106
+ const externallyBilled = await isCodexBilledTurn({
6107
+ db: services.db,
6108
+ settings: services.settings,
6109
+ workspaceId: input.workspaceId,
6110
+ model: input.model
6111
+ });
6112
+ if (!externallyBilled && (services.settings.billingMode === "stripe" || services.settings.usageLimitsMode === "managed")) {
6113
+ if (services.entitlements) {
6114
+ const decision = await services.entitlements.admitRun({
6115
+ accountId: input.accountId,
6116
+ workspaceId: input.workspaceId,
6117
+ action: "agent_run:create",
6118
+ quantity: input.requestedAgentRuns
6119
+ });
6120
+ if (!decision.allowed) return "insufficient_credits";
6121
+ } else {
6122
+ const balance = await getBillingBalance3(services.db, input.accountId);
6123
+ if (balance.balanceMicros <= 0) return "insufficient_credits";
6124
+ }
6125
+ }
6126
+ if (services.settings.usageLimitsMode !== "static" && services.settings.usageLimitsMode !== "managed") {
6127
+ return null;
6128
+ }
6129
+ const limits = configuredStaticUsageLimits2(services.settings);
6130
+ if (!externallyBilled && limits.maxMonthlyCostMicrosPerAccount) {
6131
+ const used = await sumUsageQuantity2(services.db, {
6132
+ accountId: input.accountId,
6133
+ eventType: "model.cost",
6134
+ since: startOfUtcMonth2()
6135
+ });
6136
+ if (used >= limits.maxMonthlyCostMicrosPerAccount) {
6137
+ return "monthly_model_cost_limit";
6138
+ }
6139
+ }
6140
+ if (limits.maxMonthlyAgentRunsPerWorkspace) {
6141
+ const used = await sumUsageQuantity2(services.db, {
6142
+ workspaceId: input.workspaceId,
6143
+ eventType: "agent_run.created",
6144
+ since: startOfUtcMonth2()
6145
+ });
6146
+ if (used + input.requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
6147
+ return "monthly_agent_run_limit";
6148
+ }
6149
+ }
6150
+ return null;
6151
+ }
6152
+ function startOfUtcMonth2() {
6153
+ const now = /* @__PURE__ */ new Date();
6154
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
6155
+ }
6156
+
6157
+ // src/activities/scheduled-tasks.ts
6019
6158
  function createScheduledTaskActivities(services) {
6020
6159
  return {
6021
6160
  dispatchScheduledTaskRun: async (input) => {
6022
- const { settings, db, bus, wakeSessionWorkflow } = await services();
6161
+ const service = await services();
6162
+ const { settings, db, bus, wakeSessionWorkflow } = service;
6023
6163
  if (input.triggerType !== "scheduled" && !input.initiator) {
6024
6164
  return { action: "blocked", reason: "malformed_manual_trigger" };
6025
6165
  }
@@ -6084,6 +6224,7 @@ function createScheduledTaskActivities(services) {
6084
6224
  task.workspaceId,
6085
6225
  task.id
6086
6226
  );
6227
+ const taskXaiProviderAccountAuthoritySnapshot = await getScheduledTaskXaiProviderAccountAuthoritySnapshot(db, task.workspaceId, task.id);
6087
6228
  const slackBotConnection = task.agentConfig.slackBotConnectionId ? await requireOpenGeniSlackBotConnection(
6088
6229
  db,
6089
6230
  task.workspaceId,
@@ -6094,20 +6235,12 @@ function createScheduledTaskActivities(services) {
6094
6235
  throw new Error("OpenGeni Slack bot connection metadata is invalid");
6095
6236
  }
6096
6237
  const model = task.agentConfig.model ?? settings.openaiModel;
6097
- const isCodexRun = await isCodexBilledTurn({
6098
- db,
6099
- settings,
6238
+ const admissionDenial = await agentRunAdmissionDenial(service, {
6239
+ accountId: task.accountId,
6100
6240
  workspaceId: task.workspaceId,
6101
- model
6241
+ model,
6242
+ requestedAgentRuns: input.agentRunUsageIdempotencyKey ? 0 : 1
6102
6243
  });
6103
- const admissionDenial = await scheduledRunAdmissionDenial(
6104
- settings,
6105
- db,
6106
- task.accountId,
6107
- task.workspaceId,
6108
- input.agentRunUsageIdempotencyKey ? 0 : 1,
6109
- isCodexRun
6110
- );
6111
6244
  if (admissionDenial) {
6112
6245
  return { action: "blocked", reason: admissionDenial };
6113
6246
  }
@@ -6209,6 +6342,7 @@ function createScheduledTaskActivities(services) {
6209
6342
  initialMessage: task.agentConfig.prompt,
6210
6343
  resources: task.agentConfig.resources,
6211
6344
  tools: taskTools,
6345
+ firstPartyMcpTools: resolveFirstPartyMcpToolPolicy(settings).default,
6212
6346
  metadata: {
6213
6347
  ...taskMetadata,
6214
6348
  model,
@@ -6234,6 +6368,7 @@ function createScheduledTaskActivities(services) {
6234
6368
  rigId: frozenRigId,
6235
6369
  rigVersionId: frozenRigVersionId,
6236
6370
  personalConnectionDelegations: taskPersonalConnectionDelegations,
6371
+ initialXaiProviderAccountAuthoritySnapshot: taskXaiProviderAccountAuthoritySnapshot,
6237
6372
  maxNestedAgentDepthOverride: task.agentConfig.maxNestedAgentDepth ?? null,
6238
6373
  // The durable agent config was privilege-checked when the task
6239
6374
  // was created/updated. Preserve that explicit policy if a broader
@@ -6316,8 +6451,13 @@ function createScheduledTaskActivities(services) {
6316
6451
  task.id,
6317
6452
  run.id
6318
6453
  ),
6319
- lineage: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
6320
- personalConnectionDelegations: taskPersonalConnectionDelegations
6454
+ lineage: {
6455
+ scheduledTaskId: task.id,
6456
+ scheduledTaskRunId: run.id,
6457
+ ...taskXaiProviderAccountAuthoritySnapshot.scope === "user" && task.createdBy.kind === "subject" ? { xaiAuthoritySubjectId: task.createdBy.subjectId } : {}
6458
+ },
6459
+ personalConnectionDelegations: taskPersonalConnectionDelegations,
6460
+ xaiProviderAccountAuthoritySnapshot: taskXaiProviderAccountAuthoritySnapshot
6321
6461
  },
6322
6462
  async (tx, wakeEventId) => {
6323
6463
  if (!wakeEventId) throw new Error("Scheduled delivery has no wake event");
@@ -6417,8 +6557,13 @@ function createScheduledTaskActivities(services) {
6417
6557
  task.id,
6418
6558
  run.id
6419
6559
  ),
6420
- lineage: { scheduledTaskId: task.id, scheduledTaskRunId: run.id },
6421
- personalConnectionDelegations: taskPersonalConnectionDelegations
6560
+ lineage: {
6561
+ scheduledTaskId: task.id,
6562
+ scheduledTaskRunId: run.id,
6563
+ ...taskXaiProviderAccountAuthoritySnapshot.scope === "user" && task.createdBy.kind === "subject" ? { xaiAuthoritySubjectId: task.createdBy.subjectId } : {}
6564
+ },
6565
+ personalConnectionDelegations: taskPersonalConnectionDelegations,
6566
+ xaiProviderAccountAuthoritySnapshot: taskXaiProviderAccountAuthoritySnapshot
6422
6567
  },
6423
6568
  async (tx, wakeEventId) => {
6424
6569
  if (task.runMode === "existing_session") {
@@ -6497,41 +6642,219 @@ function knowledgeSourceSyncEffectivelyPaused(task) {
6497
6642
  const control = value;
6498
6643
  return control.sourceEnabled === false || control.connectionPaused === true;
6499
6644
  }
6500
- async function scheduledRunAdmissionDenial(settings, db, accountId, workspaceId, requestedAgentRuns, isCodexRun) {
6501
- if (!isCodexRun && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
6502
- const balance = await getBillingBalance3(db, accountId);
6503
- if (balance.balanceMicros <= 0) {
6504
- return "insufficient_credits";
6645
+
6646
+ // src/activities/site-auth-maintenance.ts
6647
+ import { resolveTurnExecutionPolicyV1 } from "@opengeni/config";
6648
+ import {
6649
+ DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,
6650
+ SITE_AUTH_MAINTENANCE_CONNECTION_CONTEXT_KEY,
6651
+ SITE_AUTH_MAINTENANCE_OPERATION_CONTEXT_KEY
6652
+ } from "@opengeni/contracts";
6653
+ import {
6654
+ assertWorkspaceModelPolicyAllows,
6655
+ canonicalConfiguredModel,
6656
+ createAndStartSessionWithOutcome,
6657
+ recordWorkspaceUsage
6658
+ } from "@opengeni/core";
6659
+ import {
6660
+ claimSiteAuthMaintenance,
6661
+ confirmSiteAuthMaintenanceSessionInTransaction,
6662
+ deferSiteAuthMaintenance
6663
+ } from "@opengeni/db";
6664
+ var SITE_AUTH_MAINTENANCE_CLAIM_TIMEOUT_MS = 10 * 60 * 1e3;
6665
+ var SITE_AUTH_MAINTENANCE_BATCH_SIZE = 16;
6666
+ var MAINTENANCE_TOOLS = [
6667
+ "interaction_discover",
6668
+ "browser_open",
6669
+ "browser_tabs",
6670
+ "browser_observe",
6671
+ "browser_act",
6672
+ "browser_debug",
6673
+ "browser_auth",
6674
+ "interaction_request_human",
6675
+ "browser_identity",
6676
+ "browser_lifecycle"
6677
+ ];
6678
+ function createSiteAuthMaintenanceActivities(services, options = {}) {
6679
+ const claimTimeoutMs = options.claimTimeoutMs ?? SITE_AUTH_MAINTENANCE_CLAIM_TIMEOUT_MS;
6680
+ const batchSize = options.batchSize ?? SITE_AUTH_MAINTENANCE_BATCH_SIZE;
6681
+ const claim = options.claim ?? claimSiteAuthMaintenance;
6682
+ const confirm = options.confirm ?? confirmSiteAuthMaintenanceSessionInTransaction;
6683
+ const defer = options.defer ?? deferSiteAuthMaintenance;
6684
+ const createSession2 = options.createSession ?? createAndStartSessionWithOutcome;
6685
+ const admit = options.admit ?? agentRunAdmissionDenial;
6686
+ const recordUsage = options.recordUsage ?? recordWorkspaceUsage;
6687
+ const assertModelPolicy = options.assertModelPolicy ?? assertWorkspaceModelPolicyAllows;
6688
+ async function maintainSiteAuthConnections() {
6689
+ const service = await services();
6690
+ const claims = await claim(service.db, { claimTimeoutMs, limit: batchSize });
6691
+ const result = {
6692
+ claimed: claims.length,
6693
+ started: 0,
6694
+ deferred: 0
6695
+ };
6696
+ for (const maintenance of claims) {
6697
+ try {
6698
+ await dispatchMaintenanceSession(service, maintenance, {
6699
+ confirm,
6700
+ createSession: createSession2,
6701
+ admit,
6702
+ recordUsage,
6703
+ assertModelPolicy
6704
+ });
6705
+ result.started += 1;
6706
+ } catch (error) {
6707
+ const released = await defer(service.db, {
6708
+ accountId: maintenance.accountId,
6709
+ workspaceId: maintenance.workspaceId,
6710
+ siteAuthConnectionId: maintenance.siteAuthConnectionId,
6711
+ operationId: maintenance.operationId,
6712
+ sessionId: maintenance.sessionId,
6713
+ retryAt: maintenanceRetryAt(maintenance)
6714
+ }).catch(() => false);
6715
+ if (released) result.deferred += 1;
6716
+ service.observability.warn("site auth maintenance dispatch deferred", {
6717
+ workspaceId: maintenance.workspaceId,
6718
+ siteAuthConnectionId: maintenance.siteAuthConnectionId,
6719
+ action: maintenance.action,
6720
+ errorCategory: maintenanceErrorCategory(error),
6721
+ claimReleased: released
6722
+ });
6723
+ }
6505
6724
  }
6725
+ if (result.claimed > 0) {
6726
+ service.observability.info("site auth maintenance swept", result);
6727
+ }
6728
+ return result;
6506
6729
  }
6507
- if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
6508
- const limits = configuredStaticUsageLimits2(settings);
6509
- if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {
6510
- const used = await sumUsageQuantity2(db, {
6511
- accountId,
6512
- eventType: "model.cost",
6513
- since: startOfUtcMonth2()
6514
- });
6515
- if (used >= limits.maxMonthlyCostMicrosPerAccount) {
6516
- return "monthly_model_cost_limit";
6730
+ return { maintainSiteAuthConnections };
6731
+ }
6732
+ async function dispatchMaintenanceSession(service, maintenance, dependencies) {
6733
+ const model = canonicalConfiguredModel(service.settings, service.settings.openaiModel);
6734
+ if (!model) throw new Error("site auth maintenance has no configured model");
6735
+ await dependencies.assertModelPolicy(
6736
+ service.db,
6737
+ service.settings,
6738
+ maintenance.workspaceId,
6739
+ model
6740
+ );
6741
+ const denial = await dependencies.admit(service, {
6742
+ accountId: maintenance.accountId,
6743
+ workspaceId: maintenance.workspaceId,
6744
+ model,
6745
+ requestedAgentRuns: 1
6746
+ });
6747
+ if (denial) throw new Error(`site auth maintenance admission denied: ${denial}`);
6748
+ const reasoningEffort = service.settings.openaiReasoningEffort;
6749
+ const turnExecutionPolicy = resolveTurnExecutionPolicyV1(service.settings, {
6750
+ modelId: model,
6751
+ requestedModelId: null,
6752
+ modelSource: "deployment",
6753
+ reasoningEffort,
6754
+ reasoningSource: "deployment",
6755
+ latencyMode: "standard",
6756
+ latencyModeSource: "deployment"
6757
+ });
6758
+ const created = await dependencies.createSession({
6759
+ requestedSessionId: maintenance.sessionId,
6760
+ db: service.db,
6761
+ bus: service.bus,
6762
+ workflowClient: {
6763
+ wakeSessionWorkflow: async (input) => {
6764
+ await service.wakeSessionWorkflow?.(input);
6517
6765
  }
6518
- }
6519
- if (limits.maxMonthlyAgentRunsPerWorkspace) {
6520
- const used = await sumUsageQuantity2(db, {
6521
- workspaceId,
6522
- eventType: "agent_run.created",
6523
- since: startOfUtcMonth2()
6766
+ },
6767
+ beforeCreateCommit: async (tx, sessionId) => {
6768
+ const confirmed = await dependencies.confirm(tx, {
6769
+ accountId: maintenance.accountId,
6770
+ workspaceId: maintenance.workspaceId,
6771
+ siteAuthConnectionId: maintenance.siteAuthConnectionId,
6772
+ operationId: maintenance.operationId,
6773
+ sessionId
6524
6774
  });
6525
- if (used + requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
6526
- return "monthly_agent_run_limit";
6775
+ if (!confirmed) throw new Error("site auth maintenance claim changed before session start");
6776
+ },
6777
+ accountId: maintenance.accountId,
6778
+ workspaceId: maintenance.workspaceId,
6779
+ initialMessage: maintenancePrompt(maintenance),
6780
+ resources: [],
6781
+ tools: [{ kind: "mcp", id: "opengeni" }],
6782
+ toolPolicy: { mode: "explicit", inheritedFromSessionId: null },
6783
+ model,
6784
+ reasoningEffort,
6785
+ turnExecutionPolicy,
6786
+ sandboxBackend: service.settings.sandboxBackend,
6787
+ metadata: {
6788
+ role: "site_auth_maintenance",
6789
+ [SITE_AUTH_MAINTENANCE_CONNECTION_CONTEXT_KEY]: maintenance.siteAuthConnectionId,
6790
+ [SITE_AUTH_MAINTENANCE_OPERATION_CONTEXT_KEY]: maintenance.operationId
6791
+ },
6792
+ createdBy: {
6793
+ kind: "service",
6794
+ subjectId: "site-auth-maintenance",
6795
+ label: "OpenGeni authentication maintenance"
6796
+ },
6797
+ createdByContext: {
6798
+ [SITE_AUTH_MAINTENANCE_CONNECTION_CONTEXT_KEY]: maintenance.siteAuthConnectionId,
6799
+ [SITE_AUTH_MAINTENANCE_OPERATION_CONTEXT_KEY]: maintenance.operationId
6800
+ },
6801
+ instructions: "Complete only the exact browser-auth maintenance run in the initial request. Use the canonical browser/auth tools, preserve their causal fences, expose no secrets, never publish a BrowserIdentity revision, and do not perform unrelated work.",
6802
+ policyRole: "site_auth_maintenance",
6803
+ firstPartyMcpPermissions: [...DEFAULT_FIRST_PARTY_MCP_PERMISSIONS],
6804
+ firstPartyMcpTools: [...MAINTENANCE_TOOLS],
6805
+ createIdempotencyKey: `site-auth-maintenance:${maintenance.operationId}`,
6806
+ subjectId: "site-auth-maintenance"
6807
+ });
6808
+ try {
6809
+ await dependencies.recordUsage(
6810
+ { db: service.db, settings: service.settings },
6811
+ {
6812
+ accountId: maintenance.accountId,
6813
+ workspaceId: maintenance.workspaceId,
6814
+ subjectId: "site-auth-maintenance",
6815
+ eventType: "agent_run.created",
6816
+ quantity: 1,
6817
+ unit: "run",
6818
+ sourceResourceType: "site_auth_connection",
6819
+ sourceResourceId: maintenance.siteAuthConnectionId,
6820
+ sessionId: created.session.id,
6821
+ initiator: created.session.createdBy,
6822
+ initiatorContext: created.session.createdByContext,
6823
+ origin: "system",
6824
+ idempotencyKey: `agent_run.created:site-auth-maintenance:${maintenance.operationId}`
6527
6825
  }
6528
- }
6826
+ );
6827
+ } catch (error) {
6828
+ service.observability.warn("site auth maintenance usage recording failed", {
6829
+ workspaceId: maintenance.workspaceId,
6830
+ siteAuthConnectionId: maintenance.siteAuthConnectionId,
6831
+ errorCategory: maintenanceErrorCategory(error)
6832
+ });
6529
6833
  }
6530
- return null;
6531
6834
  }
6532
- function startOfUtcMonth2() {
6533
- const now = /* @__PURE__ */ new Date();
6534
- return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
6835
+ function maintenancePrompt(maintenance) {
6836
+ const action = maintenance.action === "repair" ? "repair authentication" : "check authentication";
6837
+ return [
6838
+ `Perform one scheduled SiteAuthConnection maintenance run: ${action}.`,
6839
+ `Connection id: ${maintenance.siteAuthConnectionId}`,
6840
+ `Connection: ${maintenance.name} (${maintenance.accountLabel})`,
6841
+ `Purpose: ${maintenance.action}`,
6842
+ maintenance.loginUrl ? `Login URL: ${maintenance.loginUrl}` : null,
6843
+ maintenance.verificationUrlPrefixes.length > 0 ? `Verification URL prefixes: ${maintenance.verificationUrlPrefixes.join(", ")}` : "No dedicated verification URL is configured; use the connection's allowed origins.",
6844
+ maintenance.preferredIdentityId ? `Preferred BrowserIdentity: ${maintenance.preferredIdentityId}` : "No preferred BrowserIdentity is configured.",
6845
+ maintenance.preferredPlacement ? `Preferred placement: ${JSON.stringify(maintenance.preferredPlacement)}` : "Use the normal managed-browser placement.",
6846
+ maintenance.preferredNetworkRouteId ? `Preferred NetworkRoute: ${maintenance.preferredNetworkRouteId}` : "No preferred NetworkRoute is configured.",
6847
+ "First call browser_auth get_connection and ensure this exact maintenance action is still active. Open a new browser (do not reuse an unrelated session) with the preferred identity, placement, and network route. Observe the current page, start one AuthRun with the exact purpose above, and settle it as verified, failed, cancelled, or a durable human intervention. For an external_provider authority use advance_external. If authentication is already valid, verify it without logging in again. If a health check finds invalid authentication, report it failed; automatic repair, when enabled, is a separate maintenance run. Never save/publish browser state in this run."
6848
+ ].filter((line) => line !== null).join("\n");
6849
+ }
6850
+ function maintenanceRetryAt(maintenance) {
6851
+ const retrySeconds = Math.min(maintenance.healthPolicy.intervalSeconds ?? 300, 15 * 60);
6852
+ return new Date(Date.now() + retrySeconds * 1e3);
6853
+ }
6854
+ function maintenanceErrorCategory(error) {
6855
+ if (!error || typeof error !== "object") return "unknown";
6856
+ const name = error.name;
6857
+ return typeof name === "string" && name.length <= 100 ? name : "unknown";
6535
6858
  }
6536
6859
 
6537
6860
  // src/activities/session-state.ts
@@ -6546,6 +6869,7 @@ import {
6546
6869
  getSessionAttemptActivityRef,
6547
6870
  getSessionEvent,
6548
6871
  getSessionTurnForAttempt,
6872
+ expireSessionInteractionIntervention as expireSessionInteractionInterventionDb,
6549
6873
  expireSessionHumanInputRequest,
6550
6874
  markSessionAttemptQuiesced,
6551
6875
  requireSession as requireSession2,
@@ -6565,6 +6889,7 @@ function createSessionStateActivities(services, overrides = {}) {
6565
6889
  const getSessionEventFn = overrides.getSessionEvent ?? getSessionEvent;
6566
6890
  const getSessionTurnForAttemptFn = overrides.getSessionTurnForAttempt ?? getSessionTurnForAttempt;
6567
6891
  const expireSessionHumanInputRequestFn = overrides.expireSessionHumanInputRequest ?? expireSessionHumanInputRequest;
6892
+ const expireSessionInteractionInterventionFn = overrides.expireSessionInteractionIntervention ?? expireSessionInteractionInterventionDb;
6568
6893
  const requireSessionFn = overrides.requireSession ?? requireSession2;
6569
6894
  const settleSessionIdleWithParentOutboxFn = overrides.settleSessionIdleWithParentOutbox ?? settleSessionIdleWithParentOutbox;
6570
6895
  const markSessionAttemptQuiescedFn = overrides.markSessionAttemptQuiesced ?? markSessionAttemptQuiesced;
@@ -6777,6 +7102,14 @@ function createSessionStateActivities(services, overrides = {}) {
6777
7102
  action: result.request.status === "expired" ? "expired" : "stale"
6778
7103
  };
6779
7104
  }
7105
+ async function expireSessionInteractionIntervention(input) {
7106
+ const { db, bus } = await services();
7107
+ const result = await expireSessionInteractionInterventionFn(db, input);
7108
+ if (result.events.length > 0) {
7109
+ await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);
7110
+ }
7111
+ return { action: result.action };
7112
+ }
6780
7113
  async function markSessionIdle(input) {
6781
7114
  const { db, bus, settings, observability, wakeSessionWorkflow } = await services();
6782
7115
  const settled = await settleSessionIdleWithParentOutboxFn(
@@ -6807,6 +7140,7 @@ function createSessionStateActivities(services, overrides = {}) {
6807
7140
  recoverEscapedMcpTimeout,
6808
7141
  peekSessionWork,
6809
7142
  expireSessionHumanInput,
7143
+ expireSessionInteractionIntervention,
6810
7144
  markSessionIdle
6811
7145
  };
6812
7146
  }
@@ -6858,9 +7192,11 @@ function createControlActivitiesFromServices(services, resolveDocumentServices)
6858
7192
  ...createKnowledgeSourceSyncActivities(services, resolveDocumentServices),
6859
7193
  ...createSessionStateActivities(services),
6860
7194
  ...createScheduledTaskActivities(services),
7195
+ ...createSiteAuthMaintenanceActivities(services),
6861
7196
  ...createGoalActivities(services),
6862
7197
  ...createCodexCapacityActivities(services),
6863
7198
  ...createRigVerificationActivities(services),
7199
+ ...createBrowserStateArtifactMaintenanceActivities(services),
6864
7200
  ...createFileUploadReaperActivities(services),
6865
7201
  ...createRetainedScreenshotMaintenanceActivities(services),
6866
7202
  ...createWorkflowWakeActivities(services),
@@ -6882,4 +7218,4 @@ export {
6882
7218
  createControlActivities,
6883
7219
  createControlActivitiesFromServices
6884
7220
  };
6885
- //# sourceMappingURL=activities-control-44KBWLSM.js.map
7221
+ //# sourceMappingURL=activities-control-XURE4VKN.js.map