@opengeni/db 3.6.0 → 3.7.4-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 (92) hide show
  1. package/dist/automations.d.ts +4 -0
  2. package/dist/canonical-human-identities.js +3 -3
  3. package/dist/{chunk-UGDVSQ6U.js → chunk-3ZMN4EXC.js} +2 -2
  4. package/dist/{chunk-744DFC65.js → chunk-6FIVOJ3V.js} +96 -6
  5. package/dist/chunk-6FIVOJ3V.js.map +1 -0
  6. package/dist/{chunk-UJ2EW3QI.js → chunk-DXJ2WY6W.js} +427 -85
  7. package/dist/chunk-DXJ2WY6W.js.map +1 -0
  8. package/dist/{chunk-CDMMSUWJ.js → chunk-JP6IYGYI.js} +3 -3
  9. package/dist/{chunk-Q5YUGQVK.js → chunk-JS3AWDKZ.js} +3 -3
  10. package/dist/{chunk-G3732M3T.js → chunk-LHKB62GC.js} +2 -2
  11. package/dist/{chunk-2NT476HD.js → chunk-QL4AHBYD.js} +2 -2
  12. package/dist/{chunk-IW6O6G7R.js → chunk-VDXHLVDE.js} +2 -2
  13. package/dist/{chunk-WW7AJ5IC.js → chunk-ZTSJPFDH.js} +5 -7
  14. package/dist/chunk-ZTSJPFDH.js.map +1 -0
  15. package/dist/codex-token-resolver.d.ts +12 -1
  16. package/dist/company-profile-agent-admin.d.ts +4 -2
  17. package/dist/company-profile-agent-policy.d.ts +20 -0
  18. package/dist/company-profile-schema.d.ts +573 -0
  19. package/dist/editable-artifact-durable-export.js +2 -2
  20. package/dist/editable-artifacts.js +3 -3
  21. package/dist/index.d.ts +487 -20
  22. package/dist/index.js +9489 -6041
  23. package/dist/index.js.map +1 -1
  24. package/dist/managed-auth-session-sets.js +3 -3
  25. package/dist/managed-human-provisioning.d.ts +3 -3
  26. package/dist/memory-domain.d.ts +5 -3
  27. package/dist/model-catalog.d.ts +153 -0
  28. package/dist/pr-review.d.ts +9 -0
  29. package/dist/provision-roles.js +1 -1
  30. package/dist/runtime-posture.d.ts +7 -7
  31. package/dist/schema.d.ts +1069 -6
  32. package/dist/schema.js +17 -1
  33. package/dist/session-background-commands.js +3 -3
  34. package/dist/session-control.d.ts +75 -5
  35. package/dist/session-queue-commands.d.ts +19 -0
  36. package/dist/session-tenancy.js +3 -3
  37. package/dist/user-resource-authority.d.ts +8 -0
  38. package/dist/video-generation.js +3 -3
  39. package/dist/xai-subscription.d.ts +8 -0
  40. package/drizzle/0369_local_human_personal_authority.sql +350 -0
  41. package/drizzle/0370_workspace_member_management_scope.sql +98 -0
  42. package/drizzle/0371_workspace_member_candidate_inventory.sql +128 -0
  43. package/drizzle/0372_ordered_variable_set_runtime_authority.sql +287 -0
  44. package/drizzle/0373_sandbox_shared_preparation.sql +59 -0
  45. package/drizzle/0374_session_event_cursors.sql +315 -0
  46. package/drizzle/0375_session_recovery_observability.sql +73 -0
  47. package/drizzle/0376_organization_workspace_inventory.sql +88 -0
  48. package/drizzle/0377_scoped_rig_health_projection.sql +80 -0
  49. package/drizzle/0378_scoped_rig_health_audit_timestamp.sql +77 -0
  50. package/drizzle/0379_session_event_raw_lane_activation.sql +518 -0
  51. package/drizzle/0380_autonomous_company_profile_agent_policy.sql +829 -0
  52. package/drizzle/0381_organization_codex_subscription_inheritance.sql +720 -0
  53. package/drizzle/0382_organization_api_key_provenance.sql +91 -0
  54. package/drizzle/0383_codex_cooldown_reconciliation.sql +51 -0
  55. package/drizzle/0384_codex_cooldown_revision_guard_privileges.sql +6 -0
  56. package/drizzle/0385_connected_machine_legacy_tilde_workdirs.sql +25 -0
  57. package/drizzle/0386_local_organization_administration.sql +157 -0
  58. package/drizzle/0387_bound_host_export_session_payloads.sql +165 -0
  59. package/drizzle/0388_sandbox_provider_deadline_interactions.sql +491 -0
  60. package/drizzle/0389_model_catalog_and_gateway_custom_models.sql +241 -0
  61. package/package.json +6 -6
  62. package/src/automations.ts +9 -1
  63. package/src/codex-token-resolver.ts +26 -1
  64. package/src/company-brain-governed-writes.ts +30 -1
  65. package/src/company-profile-agent-admin.ts +68 -1
  66. package/src/company-profile-agent-policy.ts +126 -0
  67. package/src/company-profile-schema.ts +115 -1
  68. package/src/database.ts +3 -5
  69. package/src/index.ts +4473 -570
  70. package/src/insights.ts +21 -7
  71. package/src/managed-human-provisioning.ts +3 -3
  72. package/src/memory-domain.ts +9 -4
  73. package/src/model-catalog.ts +682 -0
  74. package/src/organization-membership-lifecycle.ts +0 -1
  75. package/src/pr-review.ts +19 -0
  76. package/src/provision-roles.ts +83 -4
  77. package/src/runtime-posture.ts +26 -0
  78. package/src/schema.ts +259 -10
  79. package/src/session-control.ts +347 -59
  80. package/src/session-queue-commands.ts +303 -122
  81. package/src/session-tool-call-settlement.ts +34 -7
  82. package/src/user-resource-authority.ts +56 -0
  83. package/src/xai-subscription.ts +66 -14
  84. package/dist/chunk-744DFC65.js.map +0 -1
  85. package/dist/chunk-UJ2EW3QI.js.map +0 -1
  86. package/dist/chunk-WW7AJ5IC.js.map +0 -1
  87. /package/dist/{chunk-UGDVSQ6U.js.map → chunk-3ZMN4EXC.js.map} +0 -0
  88. /package/dist/{chunk-CDMMSUWJ.js.map → chunk-JP6IYGYI.js.map} +0 -0
  89. /package/dist/{chunk-Q5YUGQVK.js.map → chunk-JS3AWDKZ.js.map} +0 -0
  90. /package/dist/{chunk-G3732M3T.js.map → chunk-LHKB62GC.js.map} +0 -0
  91. /package/dist/{chunk-2NT476HD.js.map → chunk-QL4AHBYD.js.map} +0 -0
  92. /package/dist/{chunk-IW6O6G7R.js.map → chunk-VDXHLVDE.js.map} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ChildLifecycleSystemUpdateKind, type ChildRequiresActionRespondedByKind, SessionGoalSnapshot } from "@opengeni/contracts";
2
- import type { AccessContext, AccessGrant, AccessPrincipalKind, ApiKey, AttemptToolResult, BillingBalance, CapabilityCatalogItem, CapabilityInstallation, CapabilityPack, CapabilitySource, ConnectionKind, ConnectionMetadata, ConnectionStatus, DocumentAuthorityKind, McpServerConnectionRef, FileAsset, FileUploadStatus, FirstPartyMcpToolName, HumanInputQuestion, HumanInputResponse, KnowledgeMemory, KnowledgeMemoryKind, KnowledgeMemoryStatus, KnowledgeSourceRef, GitHubInstallationAuthorityKind, GitHubRepositoryScope, HostEventExportBatch, HostUsageExportBatch, ManagedAccount, ManagedOrganizationMembershipProjection, McpPersonalConnectionDelegation, ModelContextContributionSummary, Permission, PersonalResourceAttachmentIntent, PackInstallation, PackInstallationStatus, ResourceRef, SandboxBackend, SandboxOs, ScheduledTask, ScheduledTaskAction, ScheduledTaskActionKind, KnowledgeSourceSyncAction, ScheduledTaskAgentConfig, ScheduledTaskOverlapPolicy, ScheduledTaskRun, ScheduledTaskRunAcceptedExecution as ScheduledTaskRunAcceptedExecutionType, ScheduledTaskRunMode, ScheduledTaskRunStatus, ScheduledTaskScheduleSpec, ScheduledTaskStatus, ScheduledTaskTriggerType, SlackInstallationBinding, Session, SessionAuthorizationListScope, SessionListResponse, SessionEvent, SessionEventPayloadMode, SessionEventReadDirection, SessionEventSemanticClass, SessionEventType, SessionGoal, SessionGoalChangeKind, SessionGoalCreatedBy, SessionGoalMutationPolicy, SessionGoalRevision, SessionGoalStatus, SessionHumanInputRequest, LineageNode, SessionMcpApprovalPolicy, SessionSkill, SessionMcpServerMetadata, SessionStatus, SessionToolPolicy, SessionTurn, SessionQueueSnapshot, SessionSystemUpdate, SessionSystemUpdateKind, SystemUpdateClassification, SessionTurnSource, SessionTurnStatus, TurnInitiator, TurnInitiatorContext, SocialConnection, SocialConnectionStatus, SocialPost, SocialProvider, ToolRef, ReasoningEffort, UsageEvent, Workspace, WorkspaceControlEvent, VariableSet, VariableSetSecret, VariableSetVariableMetadata, WorkspaceMember, WorkspaceMemoryPromptMode, WorkspaceRegisteredPack, Channel, Rig, RigProviderImage, RigProviderImages, RigVersion, RigVerificationHealth, RigChange, RigChangeKind, RigChangeStatus, RigCheck, NativeSnapshotDescriptor, TarWorkspaceArchiveDescriptor, WorkspaceArchiveDescriptor, ModalCheckpointProviderBinding, SandboxProviderContinuityRecovery, WorkClaimSubjectFilter, WorkDiscoveryProjection } from "@opengeni/contracts";
2
+ import type { AccessContext, AccessGrant, AccessPrincipalKind, ApiKey, AttemptToolResult, BillingBalance, CapabilityCatalogItem, CapabilityInstallation, CapabilityPack, CapabilitySource, ConnectionKind, ConnectionMetadata, ConnectionStatus, DocumentAuthorityKind, McpServerConnectionRef, FileAsset, FileUploadStatus, FirstPartyMcpToolName, HumanInputQuestion, HumanInputResponse, KnowledgeMemory, KnowledgeMemoryKind, KnowledgeMemoryStatus, KnowledgeSourceRef, GitHubInstallationAuthorityKind, GitHubRepositoryScope, HostEventExportBatch, HostUsageExportBatch, ManagedAccount, ManagedOrganizationMembershipProjection, WorkspaceMemberCandidate, McpPersonalConnectionDelegation, ModelContextContributionSummary, Permission, PersonalResourceAttachmentIntent, PackInstallation, PackInstallationStatus, ResourceRef, SandboxBackend, SandboxOs, ScheduledTask, ScheduledTaskAction, ScheduledTaskActionKind, KnowledgeSourceSyncAction, ScheduledTaskAgentConfig, ScheduledTaskOverlapPolicy, ScheduledTaskRun, ScheduledTaskRunAcceptedExecution as ScheduledTaskRunAcceptedExecutionType, ScheduledTaskRunMode, ScheduledTaskRunStatus, ScheduledTaskScheduleSpec, ScheduledTaskStatus, ScheduledTaskTriggerType, SlackInstallationBinding, Session, SessionAuthorizationListScope, SessionListResponse, SessionEvent, SessionEventPayloadMode, SessionEventReadDirection, SessionEventSemanticClass, SessionEventType, SessionGoal, SessionGoalChangeKind, SessionGoalCreatedBy, SessionGoalMutationPolicy, SessionGoalRevision, SessionGoalStatus, SessionHumanInputRequest, LineageNode, SessionMcpApprovalPolicy, SessionSkill, SessionMcpServerMetadata, SessionStatus, SessionToolPolicy, SessionTurn, SessionQueueSnapshot, SessionSystemUpdate, SessionSystemUpdateKind, SystemUpdateClassification, SessionTurnSource, SessionTurnStatus, TurnInitiator, TurnInitiatorContext, SocialConnection, SocialConnectionStatus, SocialPost, SocialProvider, ToolRef, ReasoningEffort, UsageEvent, Workspace, WorkspaceControlEvent, VariableSet, VariableSetSecret, VariableSetVariableMetadata, WorkspaceMember, WorkspaceMemoryPromptMode, WorkspaceRegisteredPack, Channel, Rig, RigProviderImage, RigProviderImages, RigVersion, RigVerificationHealth, RigChange, RigChangeKind, RigChangeStatus, RigCheck, NativeSnapshotDescriptor, TarWorkspaceArchiveDescriptor, WorkspaceArchiveDescriptor, ModalCheckpointProviderBinding, SandboxProviderContinuityRecovery, WorkClaimSubjectFilter, WorkDiscoveryProjection } from "@opengeni/contracts";
3
3
  import { type WorkspaceArchiveObjectRef, RequestHumanInteractionToolInput, XaiProviderAccountAuthoritySnapshotV1, type TimelineAnnotation } from "@opengeni/contracts";
4
4
  import { type LatencyMode, SessionSystemUpdatePayload, TurnExecutionPolicyV1 } from "@opengeni/contracts";
5
5
  import { type Settings } from "@opengeni/config";
@@ -23,6 +23,7 @@ export * from "./session-realtime-ledger.js";
23
23
  export * from "./new-session-drafts.js";
24
24
  export * from "./workspace-instruction-policies.js";
25
25
  export * from "./company-profile.js";
26
+ export * from "./company-profile-agent-policy.js";
26
27
  export * from "./company-profile-agent-admin.js";
27
28
  export * from "./workspace-learning-policy.js";
28
29
  export * from "./governed-learning-evaluator.js";
@@ -67,10 +68,11 @@ export { memoryTextForStorage } from "./memory-domain.js";
67
68
  export { migrate, runMigrations } from "./migrate.js";
68
69
  export { provisionRoles, type ProvisionResult, type ProvisionRolesOptions, } from "./provision-roles.js";
69
70
  export * from "./memory-domain.js";
71
+ export * from "./model-catalog.js";
70
72
  import { type Database, type SessionActivityDatabase } from "./database.js";
71
73
  export { createDb, registerDbBinding, retrySessionActivityRls, rlsContextForWorkspace, rlsStrategyFor, setRlsContext, setSubjectRlsContext, withAccountRls, withDatabaseStatementTimeout, withRlsContext, withSessionActivityRlsContext, withSessionActivitySavepoint, withWorkspaceRls, withWorkspaceSessionActivityRls, withWorkspaceSubjectRls, withWorkspaceSubjectSessionActivityRls, withWorkspaceUsageLock, withSandboxProviderReadLock, SandboxProviderReadLockUnavailableError, type CreateDbOptions, type Database, type DbClient, type SessionActivityDatabase, type RlsContext, type SessionRlsActorContext, type RlsStrategy, type SandboxProviderReadLockIdentity, type ManagedUserProfile, type UserLookup, type UserProfileLookup, } from "./database.js";
72
74
  export { withSessionRlsActorContext } from "./database.js";
73
- import { buildCodexTokenResolver as buildCodexTokenResolverCore, fetchCodexRateLimitResetCreditsForAccount as fetchCodexRateLimitResetCreditsForAccountCore, fetchCodexUsageForAccount as fetchCodexUsageForAccountCore, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialForRun } from "./codex-token-resolver.js";
75
+ import { buildCodexTokenResolver as buildCodexTokenResolverCore, fetchCodexRateLimitResetCreditsForAccount as fetchCodexRateLimitResetCreditsForAccountCore, fetchCodexUsageForAccount as fetchCodexUsageForAccountCore, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialCooldownKind, type CodexCredentialForRun } from "./codex-token-resolver.js";
74
76
  import { buildConnectionTokenResolver as buildConnectionTokenResolverCore, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionTokenResolverOptions } from "./connection-token-resolver.js";
75
77
  /** Raised when a durable session tool-policy write lost its version fence. */
76
78
  export declare class SessionToolPolicyVersionConflictError extends Error {
@@ -262,6 +264,18 @@ export declare const allWorkspacePermissions: Permission[];
262
264
  * with ambient access to the private workspace.
263
265
  */
264
266
  export declare const managedPersonalWorkspacePermissions: Permission[];
267
+ /**
268
+ * Resolve the synthetic personal-workspace grant for a subject whose human
269
+ * identity was authenticated out of band (for example, in HMAC-signed OAuth
270
+ * state). This is intentionally narrower than ordinary access resolution:
271
+ * the requested workspace must still be the subject's current personal
272
+ * workspace pointer and its organization membership must remain active.
273
+ */
274
+ export declare function resolveNamedManagedPersonalWorkspaceGrant(db: Database, input: {
275
+ accountId: string;
276
+ workspaceId: string;
277
+ subjectId: string;
278
+ }): Promise<AccessGrant | null>;
265
279
  export declare const allAccountPermissions: Permission[];
266
280
  export type BootstrapWorkspaceInput = {
267
281
  accountExternalSource: string;
@@ -300,6 +314,14 @@ export declare function getWorkspace(db: Database, workspaceId: string): Promise
300
314
  export declare function getManagedAccount(db: Database, accountId: string): Promise<ManagedAccount | null>;
301
315
  export declare function requireWorkspace(db: Database, workspaceId: string): Promise<Workspace>;
302
316
  export declare function listWorkspacesForSubject(db: Database, subjectId: string, limit?: number): Promise<Workspace[]>;
317
+ /**
318
+ * Complete organization-workspace inventory for an account-scoped caller.
319
+ * Personal workspaces are excluded by the canonical organization-membership
320
+ * pointer through one narrowly granted set-based database capability; the
321
+ * public projection is therefore safely emitted as the current wire value
322
+ * `kind: "shared"`.
323
+ */
324
+ export declare function listSharedWorkspacesForAccount(db: Database, accountId: string): Promise<Workspace[]>;
303
325
  export declare function countWorkspacesForAccount(db: Database, accountId: string): Promise<number>;
304
326
  export declare function createWorkspace(db: Database, input: {
305
327
  accountId: string;
@@ -308,7 +330,36 @@ export declare function createWorkspace(db: Database, input: {
308
330
  externalSource?: string | null;
309
331
  externalId?: string | null;
310
332
  agentInstructions?: string | null;
333
+ maxWorkspacesPerAccount?: number | null;
311
334
  }): Promise<Workspace>;
335
+ export declare class WorkspaceExternalIdentityConflictError extends Error {
336
+ constructor();
337
+ }
338
+ export declare function findWorkspaceByExternalIdentity(db: Database, input: {
339
+ externalSource: string;
340
+ externalId: string;
341
+ }): Promise<Workspace | null>;
342
+ export declare class WorkspaceLimitExceededError extends Error {
343
+ readonly limit: number;
344
+ constructor(limit: number);
345
+ }
346
+ /**
347
+ * Create an organization workspace exactly once for a stable external tenant
348
+ * identity. The global unique index is the concurrency arbiter. A replay never
349
+ * mutates presentation fields supplied by the original create.
350
+ */
351
+ export declare function ensureWorkspaceByExternalIdentity(db: Database, input: {
352
+ accountId: string;
353
+ externalSource: string;
354
+ externalId: string;
355
+ name: string;
356
+ slug?: string | null;
357
+ agentInstructions?: string | null;
358
+ maxWorkspacesPerAccount?: number | null;
359
+ }): Promise<{
360
+ workspace: Workspace;
361
+ created: boolean;
362
+ }>;
312
363
  /**
313
364
  * Create one shared workspace through the direct managed-human organization
314
365
  * control plane. Organization authority is rechecked inside the lifecycle
@@ -331,6 +382,40 @@ export declare function grantWorkspaceAccess(db: Database, input: {
331
382
  role?: string;
332
383
  permissions: Permission[];
333
384
  }): Promise<void>;
385
+ export declare class WorkspaceMemberManagementError extends Error {
386
+ readonly code: "WORKSPACE_MEMBER_ALREADY_EXISTS" | "WORKSPACE_MEMBER_NOT_FOUND" | "WORKSPACE_MEMBER_SELF_UPDATE" | "WORKSPACE_MEMBER_LAST_ADMIN";
387
+ constructor(code: "WORKSPACE_MEMBER_ALREADY_EXISTS" | "WORKSPACE_MEMBER_NOT_FOUND" | "WORKSPACE_MEMBER_SELF_UPDATE" | "WORKSPACE_MEMBER_LAST_ADMIN");
388
+ }
389
+ /**
390
+ * Add or update one human workspace member under the same organization fence
391
+ * used by suspension, offboarding, organization-level grants, and removals.
392
+ * The SECURITY DEFINER candidate check runs after the fence is held, so a
393
+ * concurrent lifecycle transition cannot invalidate authority between the
394
+ * check and the membership write.
395
+ */
396
+ export declare function upsertWorkspaceMemberAsWorkspaceManager(db: Database, input: {
397
+ accountId: string;
398
+ workspaceId: string;
399
+ actorSubjectId: string;
400
+ targetSubjectId: string;
401
+ mode: "add" | "update";
402
+ subjectLabel?: string;
403
+ role: string;
404
+ permissions: Permission[];
405
+ }): Promise<void>;
406
+ /** Prove workspace-scoped management and same-organization active membership. */
407
+ export declare function assertWorkspaceMemberManagementCandidate(db: Database, input: {
408
+ accountId: string;
409
+ workspaceId: string;
410
+ actorSubjectId: string;
411
+ targetSubjectId: string;
412
+ }): Promise<void>;
413
+ /** List active same-organization humans who do not already have workspace access. */
414
+ export declare function listWorkspaceMemberManagementCandidates(db: Database, input: {
415
+ accountId: string;
416
+ workspaceId: string;
417
+ actorSubjectId: string;
418
+ }): Promise<WorkspaceMemberCandidate[]>;
334
419
  /**
335
420
  * Organization control-plane metadata update for one shared workspace. This
336
421
  * capability never creates a workspace membership or an operational grant for
@@ -427,6 +512,18 @@ export type DeleteWorkspaceIfQuiescentResult = {
427
512
  } | {
428
513
  status: "not_found" | "only_workspace" | "active_sessions" | "active_video_generations" | "active_background_commands" | "live_sandboxes";
429
514
  };
515
+ export type WorkspaceDeletePhase = "transaction" | "lifecycle_lock" | "account_workspace_lock" | "session_fence" | "runtime_ownership" | "external_cleanup" | "variable_set_detach" | "cascade";
516
+ export type WorkspaceDeleteOutcome = DeleteWorkspaceIfQuiescentResult["status"] | "ok" | "error";
517
+ export type WorkspaceDeleteInventoryKind = "workspaces" | "sessions" | "live_attempts" | "active_video_generations" | "active_background_commands" | "sandbox_leases" | "sandbox_holders" | "unsettled_sandbox_admissions" | "active_retained_processes" | "open_ptys" | "temporal_schedules";
518
+ export type WorkspaceDeleteObservation = {
519
+ phase: WorkspaceDeletePhase;
520
+ outcome: WorkspaceDeleteOutcome;
521
+ durationSeconds: number;
522
+ inventory?: Partial<Record<WorkspaceDeleteInventoryKind, number>>;
523
+ };
524
+ export type WorkspaceDeleteObserver = {
525
+ onPhase?: (observation: WorkspaceDeleteObservation) => void;
526
+ };
430
527
  /**
431
528
  * Atomically prove a workspace has no live runtime ownership and delete it.
432
529
  *
@@ -439,6 +536,7 @@ export type DeleteWorkspaceIfQuiescentResult = {
439
536
  export declare function deleteWorkspaceIfQuiescent(db: Database, input: {
440
537
  accountId: string;
441
538
  workspaceId: string;
539
+ observer?: WorkspaceDeleteObserver;
442
540
  }): Promise<DeleteWorkspaceIfQuiescentResult>;
443
541
  /** Claim a bounded cross-workspace batch after abandoned claims expire. */
444
542
  export declare function claimTemporalScheduleCleanups(db: Database, input: {
@@ -470,11 +568,37 @@ export declare function createApiKey(db: Database, input: {
470
568
  keyHash: string;
471
569
  permissions: Permission[];
472
570
  expiresAt?: Date | null;
571
+ credentialKind?: schema.ApiKeyCredentialKind;
572
+ }): Promise<ApiKey>;
573
+ export declare class OrganizationApiKeyLimitExceededError extends Error {
574
+ readonly limit: number;
575
+ constructor(limit: number);
576
+ }
577
+ /**
578
+ * Create an explicitly proven organization key under one account-scoped lock.
579
+ * An authenticating organization key may open exactly one temporary overlap
580
+ * slot at the configured cap so it can create a replacement before revocation.
581
+ */
582
+ export declare function createOrganizationApiKey(db: Database, input: {
583
+ accountId: string;
584
+ name: string;
585
+ description?: string | null;
586
+ prefix: string;
587
+ keyHash: string;
588
+ permissions: Permission[];
589
+ expiresAt?: Date | null;
590
+ maxActiveKeys?: number | null;
591
+ rotationSourceApiKeyId?: string | null;
473
592
  }): Promise<ApiKey>;
474
593
  export declare function listApiKeys(db: Database, workspaceId: string): Promise<ApiKey[]>;
594
+ export declare function listOrganizationApiKeys(db: Database, accountId: string): Promise<ApiKey[]>;
475
595
  export declare function countActiveApiKeysForWorkspace(db: Database, workspaceId: string): Promise<number>;
596
+ export declare function countActiveOrganizationApiKeysForAccount(db: Database, accountId: string): Promise<number>;
476
597
  export declare function revokeApiKey(db: Database, workspaceId: string, apiKeyId: string): Promise<ApiKey>;
477
- export declare function findActiveApiKeyByHash(db: Database, keyHash: string): Promise<ApiKey | null>;
598
+ export declare function revokeOrganizationApiKey(db: Database, accountId: string, apiKeyId: string): Promise<ApiKey | null>;
599
+ export declare function findActiveApiKeyByHash(db: Database, keyHash: string): Promise<(ApiKey & {
600
+ credentialKind: schema.ApiKeyCredentialKind;
601
+ }) | null>;
478
602
  export type GitHubInstallation = {
479
603
  id: string;
480
604
  accountId: string;
@@ -726,6 +850,8 @@ export type CreateScheduledTaskInput = {
726
850
  variableSetId?: string | null;
727
851
  rigId?: string | null;
728
852
  metadata: Record<string, unknown>;
853
+ /** Trusted database-only admission seam. Throwing rolls the task creation back. */
854
+ beforeCreateCommit?: (tx: Database) => Promise<void>;
729
855
  };
730
856
  export type UpdateScheduledTaskInput = Partial<{
731
857
  name: string;
@@ -747,6 +873,8 @@ export type UpdateScheduledTaskInput = Partial<{
747
873
  authorityUpdatedBy: TurnInitiator;
748
874
  authorityUpdatedByContext: TurnInitiatorContext;
749
875
  authorityUpdatedByActor: AgentSessionCreationActor | null;
876
+ /** Trusted database-only admission seam. Throwing rolls the task update back. */
877
+ beforeUpdateCommit: (tx: Database) => Promise<void>;
750
878
  }>;
751
879
  export type CreatePackInstallationInput = {
752
880
  accountId: string;
@@ -869,6 +997,43 @@ export type CreateConnectionInput = {
869
997
  createdBySubjectId?: string | null;
870
998
  updatedBySubjectId?: string | null;
871
999
  };
1000
+ type UpsertWorkspaceProviderApiKeyConnectionInput = {
1001
+ accountId: string;
1002
+ workspaceId: string;
1003
+ operationId: string;
1004
+ requestDigest: string;
1005
+ credentialEncrypted: string;
1006
+ grantedScopes?: string[];
1007
+ expiresAt?: Date | null;
1008
+ metadata?: Record<string, unknown>;
1009
+ updatedBySubjectId: string;
1010
+ };
1011
+ type RotateWorkspaceProviderApiKeyConnectionInput = {
1012
+ accountId: string;
1013
+ workspaceId: string;
1014
+ connectionId: string;
1015
+ expectedVersion: number;
1016
+ operationId: string;
1017
+ requestDigest: string;
1018
+ credentialEncrypted: string;
1019
+ grantedScopes?: string[];
1020
+ expiresAt?: Date | null;
1021
+ metadata?: Record<string, unknown>;
1022
+ updatedBySubjectId: string;
1023
+ };
1024
+ type RevokeWorkspaceProviderApiKeyConnectionsInput = {
1025
+ accountId: string;
1026
+ workspaceId: string;
1027
+ connectionId: string;
1028
+ expectedVersion: number;
1029
+ updatedBySubjectId: string;
1030
+ };
1031
+ export type UpsertWorkspaceVercelAiGatewayConnectionInput = UpsertWorkspaceProviderApiKeyConnectionInput;
1032
+ export type RotateWorkspaceVercelAiGatewayConnectionInput = RotateWorkspaceProviderApiKeyConnectionInput;
1033
+ export type RevokeWorkspaceVercelAiGatewayConnectionsInput = RevokeWorkspaceProviderApiKeyConnectionsInput;
1034
+ export type UpsertWorkspaceOpenRouterConnectionInput = UpsertWorkspaceProviderApiKeyConnectionInput;
1035
+ export type RotateWorkspaceOpenRouterConnectionInput = RotateWorkspaceProviderApiKeyConnectionInput;
1036
+ export type RevokeWorkspaceOpenRouterConnectionsInput = RevokeWorkspaceProviderApiKeyConnectionsInput;
872
1037
  export type UpdateConnectionInput = {
873
1038
  workspaceId: string;
874
1039
  connectionId: string;
@@ -1763,6 +1928,15 @@ export declare function decryptedCapabilityHeaders(server: EnabledMcpCapabilityS
1763
1928
  export declare function getStoredCapabilityHeaderCiphertext(db: Database, workspaceId: string, capabilityId: string): Promise<Record<string, string> | null>;
1764
1929
  export declare function mcpServerIdForCapability(capabilityId: string, metadata?: Record<string, unknown>): string;
1765
1930
  export declare function createConnection(db: Database, input: CreateConnectionInput): Promise<ConnectionMetadataWithVerification>;
1931
+ /** Compatibility wrapper for the existing Vercel AI Gateway create/replay contract. */
1932
+ export declare function upsertWorkspaceVercelAiGatewayConnection(db: Database, input: UpsertWorkspaceVercelAiGatewayConnectionInput): Promise<ConnectionMetadataWithVerification | null>;
1933
+ export declare function upsertWorkspaceOpenRouterConnection(db: Database, input: UpsertWorkspaceOpenRouterConnectionInput): Promise<ConnectionMetadataWithVerification | null>;
1934
+ /** Compatibility wrapper for the existing Vercel AI Gateway rotation contract. */
1935
+ export declare function rotateWorkspaceVercelAiGatewayConnection(db: Database, input: RotateWorkspaceVercelAiGatewayConnectionInput): Promise<ConnectionMetadataWithVerification | null>;
1936
+ export declare function rotateWorkspaceOpenRouterConnection(db: Database, input: RotateWorkspaceOpenRouterConnectionInput): Promise<ConnectionMetadataWithVerification | null>;
1937
+ /** Compatibility wrapper for the existing Vercel AI Gateway revoke contract. */
1938
+ export declare function revokeWorkspaceVercelAiGatewayConnections(db: Database, input: RevokeWorkspaceVercelAiGatewayConnectionsInput): Promise<ConnectionMetadataWithVerification | null>;
1939
+ export declare function revokeWorkspaceOpenRouterConnections(db: Database, input: RevokeWorkspaceOpenRouterConnectionsInput): Promise<ConnectionMetadataWithVerification | null>;
1766
1940
  /**
1767
1941
  * Serialize one provider-principal/owner connection generation. Distinct OAuth
1768
1942
  * starts for the same principal converge on one row, while an explicit
@@ -2394,14 +2568,21 @@ export declare function loadConnectionCredentialForBroker(db: Database, settings
2394
2568
  allowSubjectOwned?: boolean;
2395
2569
  expectedAuthorityGeneration?: number;
2396
2570
  }): Promise<ConnectionCredentialForBroker | null>;
2397
- export declare function workspaceVercelAiGatewayConnectionActive(db: Database, workspaceId: string): Promise<boolean>;
2398
2571
  /** Metadata-only capability revision input; never selects/decrypts the API key. */
2399
2572
  export declare function getWorkspaceVercelAiGatewayConnectionMetadata(db: Database, workspaceId: string): Promise<{
2400
2573
  connectionId: string;
2401
2574
  version: number;
2402
2575
  } | null>;
2576
+ export declare function getWorkspaceOpenRouterConnectionMetadata(db: Database, workspaceId: string): Promise<{
2577
+ connectionId: string;
2578
+ version: number;
2579
+ } | null>;
2580
+ export declare function workspaceVercelAiGatewayConnectionActive(db: Database, workspaceId: string): Promise<boolean>;
2581
+ export declare function workspaceOpenRouterConnectionActive(db: Database, workspaceId: string): Promise<boolean>;
2403
2582
  /** Resolve only the reviewed workspace-shared AI Gateway credential shape. */
2404
2583
  export declare function loadWorkspaceVercelAiGatewayApiKey(db: Database, settings: Settings, workspaceId: string): Promise<string | null>;
2584
+ /** Resolve only the reviewed workspace-shared OpenRouter credential shape. */
2585
+ export declare function loadWorkspaceOpenRouterApiKey(db: Database, settings: Settings, workspaceId: string): Promise<string | null>;
2405
2586
  /**
2406
2587
  * Worker-only immutable credential lease for an asynchronous video operation.
2407
2588
  * The operation copies the already-encrypted credential envelope before its
@@ -2479,6 +2660,7 @@ export type CorrectWorkspaceMemoryInput = {
2479
2660
  reason?: string | undefined;
2480
2661
  replacementText?: string | undefined;
2481
2662
  sessionId?: string | null | undefined;
2663
+ origin?: WorkspaceMemoryOrigin | undefined;
2482
2664
  };
2483
2665
  export type CorrectWorkspaceMemoryResult = {
2484
2666
  action: "archived" | "superseded" | "updated";
@@ -2629,6 +2811,11 @@ export declare function createScheduledTaskRun(db: Database, input: {
2629
2811
  scheduledAt?: Date | null;
2630
2812
  firedAt?: Date;
2631
2813
  acceptedExecutionSnapshot?: ScheduledTaskRunAcceptedExecutionType | null;
2814
+ /**
2815
+ * Trusted database-only admission seam for a fresh agent occurrence.
2816
+ * Throwing rolls back the run insert; exact producer replay skips it.
2817
+ */
2818
+ beforeFreshAgentRunCommit?: (tx: Database) => Promise<void>;
2632
2819
  }): Promise<ScheduledTaskRun>;
2633
2820
  export declare function getScheduledTaskRunAcceptedExecution(db: Database, input: {
2634
2821
  workspaceId: string;
@@ -2701,6 +2888,43 @@ export declare function getScheduledTaskRevisionAuthority(db: Database, input: {
2701
2888
  } | null>;
2702
2889
  /** Failure settlement must not rewrite a source already committed as dispatched. */
2703
2890
  export declare function markScheduledTaskRunFailedIfQueued(db: Database, workspaceId: string, runId: string, error: string): Promise<void>;
2891
+ export type FailScheduledGeneratedSessionRouteResult = {
2892
+ action: "failed";
2893
+ events: SessionEvent[];
2894
+ sessionReclaimed: boolean;
2895
+ error: string;
2896
+ } | {
2897
+ action: "terminal";
2898
+ events: [];
2899
+ sessionReclaimed: false;
2900
+ status: "failed" | "skipped";
2901
+ error: string | null;
2902
+ } | {
2903
+ action: "advanced";
2904
+ events: [];
2905
+ sessionReclaimed: false;
2906
+ status: "dispatched" | "succeeded";
2907
+ };
2908
+ /**
2909
+ * Fail a queued scheduled run after its selected Connected Machine could not be
2910
+ * established. If the exact scheduler-created session has not acquired any
2911
+ * turn, fail that otherwise-orphaned session in the same transaction. A user
2912
+ * cancellation wins for the session row, but the machine failure still owns
2913
+ * the run settlement in this one durable boundary.
2914
+ *
2915
+ * The external liveness probe and sandbox CAS must happen before this DB-only
2916
+ * seam. This transaction serializes the resulting failure with initialization,
2917
+ * cancellation, and a concurrent dispatcher under the canonical
2918
+ * control -> workspace -> session -> scheduled-run lock order.
2919
+ */
2920
+ export declare function failScheduledGeneratedSessionRoute(db: Database, input: {
2921
+ accountId: string;
2922
+ workspaceId: string;
2923
+ taskId: string;
2924
+ runId: string;
2925
+ sessionId: string;
2926
+ error: string;
2927
+ }): Promise<FailScheduledGeneratedSessionRouteResult>;
2704
2928
  export declare function markScheduledTaskRunSkippedIfQueued(db: Database, input: {
2705
2929
  workspaceId: string;
2706
2930
  runId: string;
@@ -3436,6 +3660,30 @@ export declare function loadVariableSetForRun(db: Database, settings: Settings,
3436
3660
  export declare const loadWorkspaceEnvironmentForRun: typeof loadVariableSetForRun;
3437
3661
  /** @deprecated use VariableSetForRun */
3438
3662
  export type WorkspaceEnvironmentForRun = VariableSetForRun;
3663
+ export type WorkspaceCodexSubscriptionMode = "automatic" | "workspace" | "organization" | "disabled";
3664
+ export type EffectiveCodexSubscriptionSource = "workspace" | "organization" | "disabled";
3665
+ export type WorkspaceCodexSubscriptionSource = {
3666
+ accountId: string;
3667
+ workspaceId: string;
3668
+ workspaceKind: "personal" | "shared";
3669
+ mode: WorkspaceCodexSubscriptionMode;
3670
+ effectiveSource: EffectiveCodexSubscriptionSource;
3671
+ workspaceAvailable: boolean;
3672
+ organizationAvailable: boolean;
3673
+ };
3674
+ export declare function getWorkspaceCodexSubscriptionSource(db: Database, workspaceId: string): Promise<WorkspaceCodexSubscriptionSource>;
3675
+ export declare function setWorkspaceCodexSubscriptionModeInTransaction(scopedDb: Database, input: {
3676
+ accountId: string;
3677
+ workspaceId: string;
3678
+ subjectId: string | null;
3679
+ mode: WorkspaceCodexSubscriptionMode;
3680
+ }): Promise<WorkspaceCodexSubscriptionSource>;
3681
+ export declare function setWorkspaceCodexSubscriptionMode(db: Database, input: {
3682
+ accountId: string;
3683
+ workspaceId: string;
3684
+ subjectId: string | null;
3685
+ mode: WorkspaceCodexSubscriptionMode;
3686
+ }): Promise<WorkspaceCodexSubscriptionSource>;
3439
3687
  /**
3440
3688
  * Login / rotation write (multi-account P1). Caller passes the PRE-encrypted
3441
3689
  * credential blob. Keyed on the composite partial index (workspace, chatgpt
@@ -3469,6 +3717,65 @@ export declare function upsertCodexSubscriptionCredential(db: Database, input: {
3469
3717
  /** Direct managed-cookie human who most recently connected this row. */
3470
3718
  connectedBySubjectId?: string | null;
3471
3719
  }): Promise<UpsertCodexSubscriptionCredentialResult>;
3720
+ export declare function ensureOrganizationCodexRotationSettings(db: Database, input: {
3721
+ organizationId: string;
3722
+ actorSubjectId: string;
3723
+ }): Promise<void>;
3724
+ export declare function upsertOrganizationCodexSubscriptionCredential(db: Database, input: {
3725
+ organizationId: string;
3726
+ actorSubjectId: string;
3727
+ credentialEncrypted: string;
3728
+ chatgptAccountId: string | null;
3729
+ scopes: string | null;
3730
+ planType: string | null;
3731
+ isFedramp: boolean;
3732
+ expiresAt: Date | null;
3733
+ lastRefreshAt: Date | null;
3734
+ accountEmail?: string | null;
3735
+ label?: string | null;
3736
+ }): Promise<{
3737
+ id: string;
3738
+ isNew: boolean;
3739
+ wakeTargets: CodexCapacityWakeTarget[];
3740
+ }>;
3741
+ export declare function listOrganizationCodexAccountStatuses(db: Database, input: {
3742
+ organizationId: string;
3743
+ actorSubjectId: string;
3744
+ }): Promise<CodexAccountStatus[]>;
3745
+ export declare function getOrganizationCodexRotationSettings(db: Database, input: {
3746
+ organizationId: string;
3747
+ actorSubjectId: string;
3748
+ }): Promise<CodexRotationSettings | null>;
3749
+ export declare function setActiveOrganizationCodexCredential(db: Database, input: {
3750
+ organizationId: string;
3751
+ actorSubjectId: string;
3752
+ credentialId: string;
3753
+ }): Promise<{
3754
+ activated: boolean;
3755
+ wakeTargets: CodexCapacityWakeTarget[];
3756
+ }>;
3757
+ export declare function updateOrganizationCodexRotationSettings(db: Database, input: {
3758
+ organizationId: string;
3759
+ actorSubjectId: string;
3760
+ rotationEnabled: boolean;
3761
+ }): Promise<(CodexRotationSettings & {
3762
+ wakeTargets: CodexCapacityWakeTarget[];
3763
+ }) | null>;
3764
+ export declare function renameOrganizationCodexAccount(db: Database, input: {
3765
+ organizationId: string;
3766
+ actorSubjectId: string;
3767
+ credentialId: string;
3768
+ label: string | null;
3769
+ }): Promise<boolean>;
3770
+ export declare function disconnectOrganizationCodexAccount(db: Database, input: {
3771
+ organizationId: string;
3772
+ actorSubjectId: string;
3773
+ credentialId: string;
3774
+ }): Promise<{
3775
+ removed: boolean;
3776
+ newActiveCredentialId: string | null;
3777
+ wakeTargets: CodexCapacityWakeTarget[];
3778
+ }>;
3472
3779
  export type CodexAppsSettings = {
3473
3780
  credentialId: string | null;
3474
3781
  version: number;
@@ -3645,6 +3952,7 @@ export declare function isCodexBilledTurn(input: {
3645
3952
  }): Promise<boolean>;
3646
3953
  export type CodexAccountStatus = {
3647
3954
  id: string;
3955
+ source: Exclude<EffectiveCodexSubscriptionSource, "disabled">;
3648
3956
  chatgptAccountId: string | null;
3649
3957
  label: string | null;
3650
3958
  accountEmail: string | null;
@@ -3668,6 +3976,8 @@ export type CodexAccountStatus = {
3668
3976
  secondaryResetAt: Date | null;
3669
3977
  usageCheckedAt: Date | null;
3670
3978
  exhaustedUntil: Date | null;
3979
+ /** Typed provider-refusal provenance; null for legacy/cleared cooldowns. */
3980
+ exhaustedKind: CodexCredentialCooldownKind | null;
3671
3981
  };
3672
3982
  /**
3673
3983
  * A metadata-only scheduling candidate observed while the workspace's rotation
@@ -3675,7 +3985,7 @@ export type CodexAccountStatus = {
3675
3985
  * the selection cursor gives deterministic fairness after those holders drain.
3676
3986
  * None of these fields contains credential material.
3677
3987
  */
3678
- export type CodexLeaseAccountStatus = Omit<CodexAccountStatus, "allocatorVersion" | "allocatorUpdatedBySubjectId" | "allocatorUpdatedAt" | "resetCreditAvailableCount" | "resetCreditsCheckedAt" | "connectedBySubjectId"> & {
3988
+ export type CodexLeaseAccountStatus = Omit<CodexAccountStatus, "allocatorVersion" | "allocatorUpdatedBySubjectId" | "allocatorUpdatedAt" | "resetCreditAvailableCount" | "resetCreditsCheckedAt" | "connectedBySubjectId" | "source"> & {
3679
3989
  activeLeaseCount: number;
3680
3990
  selectionCount: number;
3681
3991
  lastSelectedAt: Date | null;
@@ -4059,6 +4369,7 @@ export type CodexCredentialLeaseQuarantine = {
4059
4369
  } | {
4060
4370
  kind: "cooldown";
4061
4371
  until: Date;
4372
+ cooldownKind: CodexCredentialCooldownKind;
4062
4373
  };
4063
4374
  /**
4064
4375
  * Quarantine the credential served by one exact live holder. The lease row is
@@ -4264,7 +4575,7 @@ export declare function completeCodexResetRedemption(db: Database, input: {
4264
4575
  }): Promise<CodexCapacityMutationResult<CodexResetRedemptionAttempt | null>>;
4265
4576
  /** The P2 usage-cache snapshot written by the refreshing usage wrapper. */
4266
4577
  /**
4267
- * Cache-write for P2 quota bars: persist the five plaintext usage columns on a
4578
+ * Cache-write for P2 quota bars and revision-fenced quota cooldown repair on a
4268
4579
  * SPECIFIC credential row. NEVER touches credential_encrypted. RLS-scoped, guarded
4269
4580
  * by (id, workspace_id) so it can only write a row the workspace owns. Returns true
4270
4581
  * iff a row was updated (false ⇒ the credential was disconnected under us — the
@@ -4328,9 +4639,9 @@ export declare function setInitialActiveCodexCredential(db: Database, workspaceI
4328
4639
  * never race the (id, version) token-refresh CAS in recordCodexTokenRefresh / setCodexCredentialStatus.
4329
4640
  * Returns true iff a row was updated (false ⇒ the credential was disconnected under us).
4330
4641
  */
4331
- export declare function setCodexCredentialExhausted(db: Database, workspaceId: string, credentialId: string, until: Date | null): Promise<boolean>;
4642
+ export declare function setCodexCredentialExhausted(db: Database, workspaceId: string, credentialId: string, until: Date | null, cooldownKind: CodexCredentialCooldownKind | null): Promise<boolean>;
4332
4643
  /** Cooldown mutation plus its committed durable capacity-wake outbox. */
4333
- export declare function setCodexCredentialExhaustedWithWakeTargets(db: Database, workspaceId: string, credentialId: string, until: Date | null): Promise<CodexCapacityMutationResult<boolean>>;
4644
+ export declare function setCodexCredentialExhaustedWithWakeTargets(db: Database, workspaceId: string, credentialId: string, until: Date | null, cooldownKind: CodexCredentialCooldownKind | null): Promise<CodexCapacityMutationResult<boolean>>;
4334
4645
  /**
4335
4646
  * P3 reactive-rotation boundedness (Finding 1b): the number of CONSECUTIVE rotated
4336
4647
  * 429-failover turns since the session last had a SUCCESSFUL turn. Counts
@@ -4610,7 +4921,9 @@ export type SessionCreateInput = {
4610
4921
  /** Trusted, transaction-local linkage run after the exact session row and
4611
4922
  * MCP metadata exist but before either can commit. It must perform database
4612
4923
  * work only; throwing rolls the complete create/replay transaction back. */
4613
- beforeCreateCommit?: (tx: Database, sessionId: string) => Promise<void>;
4924
+ beforeCreateCommit?: (tx: Database, sessionId: string, context?: {
4925
+ created: boolean;
4926
+ }) => Promise<void>;
4614
4927
  };
4615
4928
  export declare function createSession(db: Database, input: SessionCreateInput): Promise<DbSession>;
4616
4929
  /**
@@ -4635,6 +4948,42 @@ export declare function createSessionWithIdempotencyKey(db: Database, input: Ses
4635
4948
  createIdempotencyKey: string;
4636
4949
  }): Promise<SessionCreateSuccessResult>;
4637
4950
  export declare function getSessionByCreateIdempotencyKey(db: Database, workspaceId: string, createIdempotencyKey: string): Promise<Session | null>;
4951
+ /**
4952
+ * Recover a keyed create before mutable create dependencies (notably the
4953
+ * current model catalog) are consulted. A fully initialized queued turn gets a
4954
+ * fresh durable wake revision from persisted state only; an uninitialized shell
4955
+ * returns its persisted model so the caller can reopen it strictly as retained
4956
+ * while the canonical keyed transaction repairs initialization. The same
4957
+ * request-identity checks as transactional create replay run before any session
4958
+ * or committed denial is returned.
4959
+ */
4960
+ export type InitializedSessionCreateReplay = {
4961
+ outcome: "session";
4962
+ session: Session & {
4963
+ initialTurnId: string | null;
4964
+ };
4965
+ temporalWorkflowId: string;
4966
+ workflowWakeRevision: number | null;
4967
+ changed: boolean;
4968
+ } | {
4969
+ outcome: "pending";
4970
+ session: Session;
4971
+ } | {
4972
+ outcome: "denied";
4973
+ denial: SessionSpawnDenial;
4974
+ };
4975
+ export declare function getInitializedSessionCreateReplay(db: Database, input: {
4976
+ accountId: string;
4977
+ workspaceId: string;
4978
+ subjectId: string;
4979
+ activeManagedHumanSubjectId?: string;
4980
+ createIdempotencyKey: string;
4981
+ requestedSessionId?: string;
4982
+ visibility?: "user_private" | "workspace_shared";
4983
+ variableSetIds: string[];
4984
+ initialPersonalResourceAttachmentIntent?: PersonalResourceAttachmentIntent | null;
4985
+ deferInitialTurn?: boolean;
4986
+ }): Promise<InitializedSessionCreateReplay | null>;
4638
4987
  export declare function getSession(db: Database, workspaceId: string, sessionId: string): Promise<Session | null>;
4639
4988
  export type DeleteSessionTreeIfQuiescentResult = {
4640
4989
  status: "deleted";
@@ -5528,6 +5877,25 @@ export declare function recordSkippedContextCompaction(db: Database, input: {
5528
5877
  recorded: false;
5529
5878
  reason: TurnAttemptFenceRejectReason | "request_not_pending";
5530
5879
  }>;
5880
+ /**
5881
+ * Read the durable handoff condition immediately after one exact compaction
5882
+ * landmark settles. Steer admission deliberately leaves the active attempt
5883
+ * unfenced while its latest compaction event is `started`; the worker calls
5884
+ * this at the first safe boundary after `compacted`/`skipped` and supersedes
5885
+ * the ordinary turn before another model request can begin.
5886
+ *
5887
+ * The later terminal settlement remains the authority fence. This read only
5888
+ * decides whether that settlement is needed, so a concurrent Pause/Cancel or a
5889
+ * Steer admitted after the landmark can still win and make the caller stale.
5890
+ */
5891
+ export declare function hasPendingSteerAfterContextCompaction(db: Database, input: {
5892
+ accountId: string;
5893
+ workspaceId: string;
5894
+ sessionId: string;
5895
+ turnId: string;
5896
+ executionGeneration: number;
5897
+ attemptId: string;
5898
+ }): Promise<boolean>;
5531
5899
  /**
5532
5900
  * The next free WHOLE-NUMBER history position for a session: one past the
5533
5901
  * largest existing position (active or superseded), floored so the synthetic
@@ -5942,6 +6310,54 @@ export type AcquireLeaseResult = {
5942
6310
  reason: "superseded" | "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress";
5943
6311
  lease: LeaseSnapshot;
5944
6312
  };
6313
+ export type SandboxSharedPreparationSnapshot = {
6314
+ status: "running" | "completed" | "failed";
6315
+ leaseEpoch: number;
6316
+ instanceId: string;
6317
+ specHash: string;
6318
+ claimId: string;
6319
+ ownerAttemptId: string;
6320
+ attempt: number;
6321
+ revision: number;
6322
+ startedAt: Date;
6323
+ deadlineAt: Date;
6324
+ settledAt: Date | null;
6325
+ };
6326
+ export type ClaimSandboxSharedPreparationInput = {
6327
+ accountId: string;
6328
+ workspaceId: string;
6329
+ sandboxGroupId: string;
6330
+ expectedLeaseEpoch: number;
6331
+ expectedInstanceId: string;
6332
+ specHash: string;
6333
+ holderId: string;
6334
+ claimId: string;
6335
+ ownerAttemptId: string;
6336
+ timeoutMs: number;
6337
+ };
6338
+ export type ClaimSandboxSharedPreparationResult = {
6339
+ role: "owner" | "joined" | "reused";
6340
+ preparation: SandboxSharedPreparationSnapshot;
6341
+ } | {
6342
+ role: "fenced";
6343
+ lease: LeaseSnapshot | null;
6344
+ };
6345
+ /**
6346
+ * Claim, join, or reuse immutable setup for one exact physical sandbox. The
6347
+ * provider operation remains outside the transaction; the claim deadline and
6348
+ * box-local idempotency marker make a lost owner recoverable without sharing
6349
+ * any turn-private credential or file material.
6350
+ */
6351
+ export declare function claimSandboxSharedPreparation(db: Database, input: ClaimSandboxSharedPreparationInput): Promise<ClaimSandboxSharedPreparationResult>;
6352
+ export declare function readSandboxSharedPreparation(db: Database, input: Omit<ClaimSandboxSharedPreparationInput, "claimId" | "ownerAttemptId" | "timeoutMs">): Promise<{
6353
+ status: "available";
6354
+ preparation: SandboxSharedPreparationSnapshot;
6355
+ } | {
6356
+ status: "fenced";
6357
+ }>;
6358
+ export declare function settleSandboxSharedPreparation(db: Database, input: Omit<ClaimSandboxSharedPreparationInput, "ownerAttemptId" | "timeoutMs"> & {
6359
+ outcome: "completed" | "failed";
6360
+ }): Promise<boolean>;
5945
6361
  export declare class SandboxLeaseSupersededError extends Error {
5946
6362
  readonly sandboxGroupId: string;
5947
6363
  readonly leaseEpoch: number;
@@ -6648,6 +7064,8 @@ export declare function listMeterableWarmLeases(db: Database): Promise<Meterable
6648
7064
  * even after every affected sandbox lease has become cold. */
6649
7065
  export declare function listSandboxViewerForceDrainWorkspaceIds(db: Database): Promise<string[]>;
6650
7066
  export declare function countQueuedTurns(db: Database): Promise<number>;
7067
+ export type SessionRecoveryBacklogState = "quiescence_missing" | "projection_stale";
7068
+ export declare function countSessionRecoveryBacklog(db: Database): Promise<Record<SessionRecoveryBacklogState, number>>;
6651
7069
  export declare function countSandboxLeasesByLiveness(db: Database): Promise<Record<SandboxLeaseLiveness, number>>;
6652
7070
  export type CreditBalanceByAccount = {
6653
7071
  accountId: string;
@@ -6683,6 +7101,18 @@ export declare class SandboxWorkspaceMutationFencedError extends Error {
6683
7101
  readonly name: string;
6684
7102
  constructor(code: "attempt_fenced" | "holder_fenced" | "lease_fenced" | "rotation_in_progress" | "route_fenced" | "process_fenced" | "capture_in_progress" | "admission_fenced" | "operation_invalid" | "generation_exhausted" | "authority_unattributed" | "authority_revoked", message: string);
6685
7103
  }
7104
+ /** An operation named a durable retained process that has already reached a
7105
+ * terminal state. This remains a fence—the provider must not be called again
7106
+ * and contradictory proof must not overwrite durable truth—but carries the
7107
+ * existing terminal result so routing can reconcile a concurrent settlement
7108
+ * or report completion/loss instead of presenting a retryable platform failure
7109
+ * for a handle that can never become active again. */
7110
+ export declare class SandboxRetainedProcessTerminalError extends SandboxWorkspaceMutationFencedError {
7111
+ readonly state: "exited" | "lost";
7112
+ readonly exitCode: number | null;
7113
+ readonly name = "SandboxRetainedProcessTerminalError";
7114
+ constructor(state: "exited" | "lost", exitCode: number | null);
7115
+ }
6686
7116
  export type SandboxWorkspaceMutationAdmission = {
6687
7117
  id: string;
6688
7118
  leaseId: string;
@@ -7004,7 +7434,8 @@ export declare function countActiveRetainedProcessesByOwnerState(db: Database):
7004
7434
  export declare function countExpiredDrainingSandboxLeases(db: Database): Promise<ExpiredDrainingSandboxLeaseCount[]>;
7005
7435
  /** Settle an exact retained process only after exit or definitive loss proof.
7006
7436
  * The process row, parent admission, non-TTL holder, and lease count transition
7007
- * commit atomically. Duplicate identical proof is idempotent; conflicting proof
7437
+ * commit atomically. A duplicate terminal state + exit code is idempotent and
7438
+ * preserves the first durable evidence reason; contradictory physical truth
7008
7439
  * fails closed. */
7009
7440
  export declare function settleRetainedProcess(db: Database, input: {
7010
7441
  accountId: string;
@@ -7256,6 +7687,7 @@ export type SandboxRotationBacklog = {
7256
7687
  turnBlocked: number;
7257
7688
  directBlocked: number;
7258
7689
  processBlocked: number;
7690
+ interactionBlocked: number;
7259
7691
  };
7260
7692
  export declare function readSandboxRotationBacklog(db: Database): Promise<SandboxRotationBacklog>;
7261
7693
  export type LegacyModalCheckpointSlot = {
@@ -8614,6 +9046,7 @@ export declare function materializeGoalContinuation(db: Database, input: {
8614
9046
  model: string;
8615
9047
  reasoningEffort: ReasoningEffort;
8616
9048
  latencyMode: LatencyMode;
9049
+ turnExecutionPolicy?: TurnExecutionPolicyV1;
8617
9050
  tools: ToolRef[];
8618
9051
  sandboxBackend: SandboxBackend;
8619
9052
  };
@@ -8628,6 +9061,9 @@ export type InitializeSessionStartInput = {
8628
9061
  /** Trusted create-session policy. Omitted only by legacy low-level callers. */
8629
9062
  turnExecutionPolicy?: TurnExecutionPolicyV1;
8630
9063
  createdEventPayload: Record<string, unknown>;
9064
+ /** Sensitive-safe semantic title supplied by the trusted agent-child create
9065
+ * path. It is committed with the initial timeline, never as a bare row edit. */
9066
+ initialAutomaticTitle?: string | null;
8631
9067
  goal?: {
8632
9068
  text: string;
8633
9069
  successCriteria?: string | null;
@@ -8704,6 +9140,16 @@ export type ClaimSessionWorkForAttemptInput = {
8704
9140
  action: "reject";
8705
9141
  reason: string;
8706
9142
  }>;
9143
+ /**
9144
+ * A requires-action resume first persists its open tool-call result, then
9145
+ * re-enters this exact attempt to attach machine input that arrived while the
9146
+ * session was blocked. The dispatch metadata freezes the session's durable
9147
+ * pending-event sequence at attempt claim; timestamps cannot own this fence
9148
+ * because a producer transaction may wait on the session lock. Keeping this
9149
+ * opt-in prevents an ordinary activity retry from inserting a system message
9150
+ * ahead of the required call/result pair in canonical history.
9151
+ */
9152
+ attachPendingUpdatesToRunningAttempt?: boolean;
8707
9153
  };
8708
9154
  export type ClaimSessionWorkForAttemptResult = {
8709
9155
  action: "claimed";
@@ -9264,21 +9710,24 @@ export declare function claimPendingSessionWorkflowWakes(db: Database, limit?: n
9264
9710
  * accepted direction or an interrupted attempt awaiting writer-set proof.
9265
9711
  * Temporal accepting a signal is transport evidence, not proof that a closing
9266
9712
  * workflow observed Postgres. While active control still has an actionable
9267
- * Agent Steer or pending quiescence, retain the revision so the bounded outbox
9268
- * dispatcher retries signalWithStart. The attempt-fenced claim consumes an
9269
- * Agent Steer once; a real Pause is the typed blocker and may acknowledge this
9713
+ * Agent Steer, a current wake still owns an accepted queued human/API turn, or
9714
+ * an attempt awaits quiescence, retain the revision so the bounded outbox
9715
+ * dispatcher retries signalWithStart. The attempt-fenced claim consumes each
9716
+ * direction once; a real Pause is the typed blocker and may acknowledge this
9270
9717
  * revision because Resume commits a new one.
9271
9718
  *
9272
9719
  * An older sender may advance only its own revision; it cannot clear a claim or
9273
- * failure state belonging to a newer revision. The control -> workspace ->
9274
- * session lock prefix serializes this decision with Steer, Pause/Resume, and
9275
- * claim without weakening physical-quiescence admission.
9720
+ * failure state belonging to a newer revision. Therefore queued prompt work
9721
+ * blocks acknowledgement only for the current coalesced revision: a stale
9722
+ * acknowledgement still leaves the newer revision outstanding. The control ->
9723
+ * workspace -> session lock prefix serializes this decision with Send, Steer,
9724
+ * Pause/Resume, and claim without weakening physical-quiescence admission.
9276
9725
  */
9277
9726
  export type SessionWorkflowWakeDeliveryResult = {
9278
9727
  action: "acknowledged";
9279
9728
  } | {
9280
9729
  action: "pending_admission";
9281
- blocker: "pending_agent_steer" | "pending_quiescence";
9730
+ blocker: "pending_agent_steer" | "pending_prompt_turn" | "pending_quiescence";
9282
9731
  };
9283
9732
  export declare function markSessionWorkflowWakeDelivered(db: Database, input: Omit<SessionWorkflowWake, "interruptionRequested">): Promise<SessionWorkflowWakeDeliveryResult>;
9284
9733
  /** Record delivery failure; the claim already scheduled the bounded retry. */
@@ -9364,6 +9813,7 @@ export declare function childRequiresActionResolutionExists(db: Database, worksp
9364
9813
  export declare function listOutstandingSessionSystemUpdates(db: Database, workspaceId: string, sessionId: string): Promise<SessionSystemUpdate[]>;
9365
9814
  /** Internal updates atomically attached when this inference was claimed. */
9366
9815
  export declare function listSessionSystemUpdatesForTurn(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise<SessionSystemUpdate[]>;
9816
+ export declare function sessionEventRawLaneEnabled(value?: string | undefined): boolean;
9367
9817
  export declare function appendSessionEvents(db: Database, workspaceId: string, sessionId: string, inputs: AppendEventInput[]): Promise<SessionEvent[]>;
9368
9818
  export type AcceptSessionApprovalDecisionResult = {
9369
9819
  action: "accepted";
@@ -9417,17 +9867,34 @@ export declare function expireSessionInteractionIntervention(db: Database, input
9417
9867
  * events remain associated with their producer in logs but are not admitted to
9418
9868
  * the current durable timeline once the turn row moved generation or terminal.
9419
9869
  */
9420
- export declare function appendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[]): Promise<{
9870
+ export declare function appendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[], observer?: SessionEventAppendObserver): Promise<{
9421
9871
  events: SessionEvent[];
9422
9872
  accepted: boolean;
9423
9873
  canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];
9424
9874
  }>;
9875
+ export type SessionEventAppendClass = "raw" | "semantic" | "mixed";
9876
+ export type SessionEventAppendPhase = "transaction" | "mutation" | "turn_attempt_fence" | "idempotency" | "event_insert" | "projection" | "sequence_update";
9877
+ export type SessionEventAppendPhaseOutcome = "ok" | "rejected" | "mutation_skipped" | "projection_skipped" | "escalated" | "error";
9878
+ export type SessionEventAppendPhaseObservation = {
9879
+ phase: SessionEventAppendPhase;
9880
+ eventClass: SessionEventAppendClass;
9881
+ eventCount: number;
9882
+ outcome: SessionEventAppendPhaseOutcome;
9883
+ durationSeconds: number;
9884
+ };
9885
+ export type SessionEventAppendObserver = {
9886
+ onPhase?: (observation: SessionEventAppendPhaseObservation) => void;
9887
+ };
9888
+ export declare function sessionEventAppendClass(inputs: ReadonlyArray<{
9889
+ type: string;
9890
+ }>): SessionEventAppendClass;
9891
+ export declare function observeSessionEventAppendPhase(observer: SessionEventAppendObserver | undefined, observation: SessionEventAppendPhaseObservation): void;
9425
9892
  /**
9426
9893
  * Commit one exact-attempt mutation and its timeline projection together. The
9427
9894
  * mutation runs first so Codemode's operation-row lock order remains stable;
9428
9895
  * returning false leaves both the mutation and projection absent.
9429
9896
  */
9430
- export declare function mutateAndAppendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[], mutate: (tx: Database) => Promise<boolean>): Promise<{
9897
+ export declare function mutateAndAppendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[], mutate: (tx: Database) => Promise<boolean>, observer?: SessionEventAppendObserver): Promise<{
9431
9898
  events: SessionEvent[];
9432
9899
  accepted: boolean;
9433
9900
  mutationApplied: boolean;
@@ -9508,7 +9975,7 @@ export declare function buildCodexTokenResolver(db: Database, settings: Settings
9508
9975
  export declare function fetchCodexUsageForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): ReturnType<typeof fetchCodexUsageForAccountCore>;
9509
9976
  export declare function fetchCodexRateLimitResetCreditsForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): ReturnType<typeof fetchCodexRateLimitResetCreditsForAccountCore>;
9510
9977
  export declare function buildConnectionTokenResolver(db: Database, settings: Settings, deps?: ConnectionBrokerDeps, options?: ConnectionTokenResolverOptions): ReturnType<typeof buildConnectionTokenResolverCore>;
9511
- export { withCodexTokenDeadline, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialForRun, type CodexCredentialTokens, type CodexRateLimitResetCreditsAccountResult, type CodexTokenDeadlineClock, type CodexTokenDeadlineOptions, } from "./codex-token-resolver.js";
9978
+ export { withCodexTokenDeadline, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialCooldownKind, type CodexCredentialForRun, type CodexCredentialTokens, type CodexRateLimitResetCreditsAccountResult, type CodexTokenDeadlineClock, type CodexTokenDeadlineOptions, } from "./codex-token-resolver.js";
9512
9979
  export { buildHostConnectionTokenResolver, ConnectionRefreshHttpError, HostMcpCredentialBindingError, HostMcpCredentialScopeError, isPrivateAddress, normalizeBearerScheme, refreshOAuthConnectionCredential, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionCredentialLookupInput, type ConnectionStatusGuard, type ConnectionTokenRefreshInput, type ConnectionTokenResolverOptions, type HostMcpCredentialResolverContext, type PermanentConnectionRefreshFailure, type RefreshTransportOptions, type ResolveConnectionCredentialInput, type ResolveConnectionCredentialResult, } from "./connection-token-resolver.js";
9513
9980
  export { CapabilityComponentVersionConflictError, cleanupOrphanedCapabilityComponents, effectiveCapabilityOwnerSql, type CapabilityComponentOwnerIdentity, } from "./capability-components.js";
9514
9981
  export { adoptPackComponentReferences, finalizePackComponentOwnership, listPackInstallationComponents, PackComponentResolutionError, previewPackComponentRelease, recordPackInlineSkillComponent, releasePackComponents, resolvePackComponentReferences, resolvePackInlineSkillReferences, type PackInlineSkillRequirement, type StoredPackInstallationComponent, } from "./pack-components.js";