@opengeni/db 3.5.2-canary.0 → 3.7.3-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 (88) hide show
  1. package/dist/canonical-human-identities.js +3 -3
  2. package/dist/{chunk-PERPE2UY.js → chunk-4NAR7FBA.js} +122 -6
  3. package/dist/chunk-4NAR7FBA.js.map +1 -0
  4. package/dist/{chunk-ORKVXHL2.js → chunk-5NNCGFQY.js} +2 -2
  5. package/dist/{chunk-TRCYF26N.js → chunk-DZCYW2WT.js} +2 -2
  6. package/dist/{chunk-X6T2P3L3.js → chunk-F6PBS6WE.js} +5 -7
  7. package/dist/chunk-F6PBS6WE.js.map +1 -0
  8. package/dist/{chunk-6NYKC5DD.js → chunk-O56DM5GZ.js} +5062 -4661
  9. package/dist/chunk-O56DM5GZ.js.map +1 -0
  10. package/dist/{chunk-FJHEWYV5.js → chunk-S3TDDCS2.js} +3 -3
  11. package/dist/{chunk-Y44FKTYU.js → chunk-SZAWDXQC.js} +3 -3
  12. package/dist/{chunk-U7NKCX5E.js → chunk-U4WPPEBH.js} +2 -2
  13. package/dist/{chunk-NRGUX3M5.js → chunk-US4IS6IV.js} +2 -2
  14. package/dist/codex-token-resolver.d.ts +12 -1
  15. package/dist/company-profile-agent-admin.d.ts +4 -2
  16. package/dist/company-profile-agent-policy.d.ts +20 -0
  17. package/dist/company-profile-schema.d.ts +573 -0
  18. package/dist/editable-artifact-durable-export.js +2 -2
  19. package/dist/editable-artifacts.js +3 -3
  20. package/dist/index.d.ts +404 -20
  21. package/dist/index.js +5433 -2309
  22. package/dist/index.js.map +1 -1
  23. package/dist/managed-auth-session-sets.js +3 -3
  24. package/dist/managed-human-provisioning.d.ts +3 -3
  25. package/dist/memory-domain.d.ts +5 -3
  26. package/dist/provision-roles.js +1 -1
  27. package/dist/runtime-posture.d.ts +7 -6
  28. package/dist/schema.d.ts +732 -10
  29. package/dist/schema.js +19 -1
  30. package/dist/session-background-commands.js +3 -3
  31. package/dist/session-control.d.ts +40 -5
  32. package/dist/session-queue-commands.d.ts +2 -0
  33. package/dist/session-tenancy.js +3 -3
  34. package/dist/user-resource-authority.d.ts +8 -0
  35. package/dist/video-generation.js +3 -3
  36. package/dist/work-claims-schema.d.ts +975 -0
  37. package/dist/work-claims.d.ts +83 -0
  38. package/drizzle/0365_permission_scoped_work_claims.sql +1306 -0
  39. package/drizzle/0366_session_discovery_title_search_index.sql +5 -0
  40. package/drizzle/0367_session_discovery_goal_search_index.sql +5 -0
  41. package/drizzle/0368_session_discovery_claim_search_index.sql +6 -0
  42. package/drizzle/0369_local_human_personal_authority.sql +350 -0
  43. package/drizzle/0370_workspace_member_management_scope.sql +98 -0
  44. package/drizzle/0371_workspace_member_candidate_inventory.sql +128 -0
  45. package/drizzle/0372_ordered_variable_set_runtime_authority.sql +287 -0
  46. package/drizzle/0373_sandbox_shared_preparation.sql +59 -0
  47. package/drizzle/0374_session_event_cursors.sql +315 -0
  48. package/drizzle/0375_session_recovery_observability.sql +73 -0
  49. package/drizzle/0376_organization_workspace_inventory.sql +88 -0
  50. package/drizzle/0377_scoped_rig_health_projection.sql +80 -0
  51. package/drizzle/0378_scoped_rig_health_audit_timestamp.sql +77 -0
  52. package/drizzle/0379_session_event_raw_lane_activation.sql +518 -0
  53. package/drizzle/0380_autonomous_company_profile_agent_policy.sql +829 -0
  54. package/drizzle/0381_organization_codex_subscription_inheritance.sql +720 -0
  55. package/drizzle/0382_organization_api_key_provenance.sql +91 -0
  56. package/drizzle/0383_codex_cooldown_reconciliation.sql +51 -0
  57. package/drizzle/0384_codex_cooldown_revision_guard_privileges.sql +6 -0
  58. package/drizzle/0385_connected_machine_legacy_tilde_workdirs.sql +25 -0
  59. package/drizzle/0386_local_organization_administration.sql +157 -0
  60. package/package.json +6 -6
  61. package/src/codex-token-resolver.ts +26 -1
  62. package/src/company-brain-governed-writes.ts +30 -1
  63. package/src/company-profile-agent-admin.ts +68 -1
  64. package/src/company-profile-agent-policy.ts +126 -0
  65. package/src/company-profile-schema.ts +115 -1
  66. package/src/database.ts +3 -5
  67. package/src/index.ts +4677 -786
  68. package/src/managed-human-provisioning.ts +3 -3
  69. package/src/memory-domain.ts +9 -4
  70. package/src/organization-membership-lifecycle.ts +0 -1
  71. package/src/provision-roles.ts +101 -4
  72. package/src/runtime-posture.ts +34 -0
  73. package/src/schema.ts +162 -8
  74. package/src/session-control.ts +177 -59
  75. package/src/session-queue-commands.ts +146 -40
  76. package/src/session-tool-call-settlement.ts +34 -7
  77. package/src/user-resource-authority.ts +56 -0
  78. package/src/work-claims-schema.ts +148 -0
  79. package/src/work-claims.ts +200 -0
  80. package/dist/chunk-6NYKC5DD.js.map +0 -1
  81. package/dist/chunk-PERPE2UY.js.map +0 -1
  82. package/dist/chunk-X6T2P3L3.js.map +0 -1
  83. /package/dist/{chunk-ORKVXHL2.js.map → chunk-5NNCGFQY.js.map} +0 -0
  84. /package/dist/{chunk-TRCYF26N.js.map → chunk-DZCYW2WT.js.map} +0 -0
  85. /package/dist/{chunk-FJHEWYV5.js.map → chunk-S3TDDCS2.js.map} +0 -0
  86. /package/dist/{chunk-Y44FKTYU.js.map → chunk-SZAWDXQC.js.map} +0 -0
  87. /package/dist/{chunk-U7NKCX5E.js.map → chunk-U4WPPEBH.js.map} +0 -0
  88. /package/dist/{chunk-NRGUX3M5.js.map → chunk-US4IS6IV.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 } 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";
@@ -36,6 +37,7 @@ export * from "./company-brain-governed-writes.js";
36
37
  export * from "./company-brain-context-selection.js";
37
38
  export * from "./knowledge-source-sync.js";
38
39
  export * from "./task-notes.js";
40
+ export * from "./work-claims.js";
39
41
  export * from "./managed-human-provisioning.js";
40
42
  export * from "./managed-user-setup.js";
41
43
  export * from "./organization-membership-backfill.js";
@@ -69,7 +71,7 @@ export * from "./memory-domain.js";
69
71
  import { type Database, type SessionActivityDatabase } from "./database.js";
70
72
  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";
71
73
  export { withSessionRlsActorContext } from "./database.js";
72
- import { buildCodexTokenResolver as buildCodexTokenResolverCore, fetchCodexRateLimitResetCreditsForAccount as fetchCodexRateLimitResetCreditsForAccountCore, fetchCodexUsageForAccount as fetchCodexUsageForAccountCore, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialForRun } from "./codex-token-resolver.js";
74
+ import { buildCodexTokenResolver as buildCodexTokenResolverCore, fetchCodexRateLimitResetCreditsForAccount as fetchCodexRateLimitResetCreditsForAccountCore, fetchCodexUsageForAccount as fetchCodexUsageForAccountCore, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialCooldownKind, type CodexCredentialForRun } from "./codex-token-resolver.js";
73
75
  import { buildConnectionTokenResolver as buildConnectionTokenResolverCore, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionTokenResolverOptions } from "./connection-token-resolver.js";
74
76
  /** Raised when a durable session tool-policy write lost its version fence. */
75
77
  export declare class SessionToolPolicyVersionConflictError extends Error {
@@ -261,6 +263,18 @@ export declare const allWorkspacePermissions: Permission[];
261
263
  * with ambient access to the private workspace.
262
264
  */
263
265
  export declare const managedPersonalWorkspacePermissions: Permission[];
266
+ /**
267
+ * Resolve the synthetic personal-workspace grant for a subject whose human
268
+ * identity was authenticated out of band (for example, in HMAC-signed OAuth
269
+ * state). This is intentionally narrower than ordinary access resolution:
270
+ * the requested workspace must still be the subject's current personal
271
+ * workspace pointer and its organization membership must remain active.
272
+ */
273
+ export declare function resolveNamedManagedPersonalWorkspaceGrant(db: Database, input: {
274
+ accountId: string;
275
+ workspaceId: string;
276
+ subjectId: string;
277
+ }): Promise<AccessGrant | null>;
264
278
  export declare const allAccountPermissions: Permission[];
265
279
  export type BootstrapWorkspaceInput = {
266
280
  accountExternalSource: string;
@@ -299,6 +313,14 @@ export declare function getWorkspace(db: Database, workspaceId: string): Promise
299
313
  export declare function getManagedAccount(db: Database, accountId: string): Promise<ManagedAccount | null>;
300
314
  export declare function requireWorkspace(db: Database, workspaceId: string): Promise<Workspace>;
301
315
  export declare function listWorkspacesForSubject(db: Database, subjectId: string, limit?: number): Promise<Workspace[]>;
316
+ /**
317
+ * Complete organization-workspace inventory for an account-scoped caller.
318
+ * Personal workspaces are excluded by the canonical organization-membership
319
+ * pointer through one narrowly granted set-based database capability; the
320
+ * public projection is therefore safely emitted as the current wire value
321
+ * `kind: "shared"`.
322
+ */
323
+ export declare function listSharedWorkspacesForAccount(db: Database, accountId: string): Promise<Workspace[]>;
302
324
  export declare function countWorkspacesForAccount(db: Database, accountId: string): Promise<number>;
303
325
  export declare function createWorkspace(db: Database, input: {
304
326
  accountId: string;
@@ -307,7 +329,36 @@ export declare function createWorkspace(db: Database, input: {
307
329
  externalSource?: string | null;
308
330
  externalId?: string | null;
309
331
  agentInstructions?: string | null;
332
+ maxWorkspacesPerAccount?: number | null;
310
333
  }): Promise<Workspace>;
334
+ export declare class WorkspaceExternalIdentityConflictError extends Error {
335
+ constructor();
336
+ }
337
+ export declare function findWorkspaceByExternalIdentity(db: Database, input: {
338
+ externalSource: string;
339
+ externalId: string;
340
+ }): Promise<Workspace | null>;
341
+ export declare class WorkspaceLimitExceededError extends Error {
342
+ readonly limit: number;
343
+ constructor(limit: number);
344
+ }
345
+ /**
346
+ * Create an organization workspace exactly once for a stable external tenant
347
+ * identity. The global unique index is the concurrency arbiter. A replay never
348
+ * mutates presentation fields supplied by the original create.
349
+ */
350
+ export declare function ensureWorkspaceByExternalIdentity(db: Database, input: {
351
+ accountId: string;
352
+ externalSource: string;
353
+ externalId: string;
354
+ name: string;
355
+ slug?: string | null;
356
+ agentInstructions?: string | null;
357
+ maxWorkspacesPerAccount?: number | null;
358
+ }): Promise<{
359
+ workspace: Workspace;
360
+ created: boolean;
361
+ }>;
311
362
  /**
312
363
  * Create one shared workspace through the direct managed-human organization
313
364
  * control plane. Organization authority is rechecked inside the lifecycle
@@ -330,6 +381,40 @@ export declare function grantWorkspaceAccess(db: Database, input: {
330
381
  role?: string;
331
382
  permissions: Permission[];
332
383
  }): Promise<void>;
384
+ export declare class WorkspaceMemberManagementError extends Error {
385
+ readonly code: "WORKSPACE_MEMBER_ALREADY_EXISTS" | "WORKSPACE_MEMBER_NOT_FOUND" | "WORKSPACE_MEMBER_SELF_UPDATE" | "WORKSPACE_MEMBER_LAST_ADMIN";
386
+ constructor(code: "WORKSPACE_MEMBER_ALREADY_EXISTS" | "WORKSPACE_MEMBER_NOT_FOUND" | "WORKSPACE_MEMBER_SELF_UPDATE" | "WORKSPACE_MEMBER_LAST_ADMIN");
387
+ }
388
+ /**
389
+ * Add or update one human workspace member under the same organization fence
390
+ * used by suspension, offboarding, organization-level grants, and removals.
391
+ * The SECURITY DEFINER candidate check runs after the fence is held, so a
392
+ * concurrent lifecycle transition cannot invalidate authority between the
393
+ * check and the membership write.
394
+ */
395
+ export declare function upsertWorkspaceMemberAsWorkspaceManager(db: Database, input: {
396
+ accountId: string;
397
+ workspaceId: string;
398
+ actorSubjectId: string;
399
+ targetSubjectId: string;
400
+ mode: "add" | "update";
401
+ subjectLabel?: string;
402
+ role: string;
403
+ permissions: Permission[];
404
+ }): Promise<void>;
405
+ /** Prove workspace-scoped management and same-organization active membership. */
406
+ export declare function assertWorkspaceMemberManagementCandidate(db: Database, input: {
407
+ accountId: string;
408
+ workspaceId: string;
409
+ actorSubjectId: string;
410
+ targetSubjectId: string;
411
+ }): Promise<void>;
412
+ /** List active same-organization humans who do not already have workspace access. */
413
+ export declare function listWorkspaceMemberManagementCandidates(db: Database, input: {
414
+ accountId: string;
415
+ workspaceId: string;
416
+ actorSubjectId: string;
417
+ }): Promise<WorkspaceMemberCandidate[]>;
333
418
  /**
334
419
  * Organization control-plane metadata update for one shared workspace. This
335
420
  * capability never creates a workspace membership or an operational grant for
@@ -426,6 +511,18 @@ export type DeleteWorkspaceIfQuiescentResult = {
426
511
  } | {
427
512
  status: "not_found" | "only_workspace" | "active_sessions" | "active_video_generations" | "active_background_commands" | "live_sandboxes";
428
513
  };
514
+ export type WorkspaceDeletePhase = "transaction" | "lifecycle_lock" | "account_workspace_lock" | "session_fence" | "runtime_ownership" | "external_cleanup" | "variable_set_detach" | "cascade";
515
+ export type WorkspaceDeleteOutcome = DeleteWorkspaceIfQuiescentResult["status"] | "ok" | "error";
516
+ 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";
517
+ export type WorkspaceDeleteObservation = {
518
+ phase: WorkspaceDeletePhase;
519
+ outcome: WorkspaceDeleteOutcome;
520
+ durationSeconds: number;
521
+ inventory?: Partial<Record<WorkspaceDeleteInventoryKind, number>>;
522
+ };
523
+ export type WorkspaceDeleteObserver = {
524
+ onPhase?: (observation: WorkspaceDeleteObservation) => void;
525
+ };
429
526
  /**
430
527
  * Atomically prove a workspace has no live runtime ownership and delete it.
431
528
  *
@@ -438,6 +535,7 @@ export type DeleteWorkspaceIfQuiescentResult = {
438
535
  export declare function deleteWorkspaceIfQuiescent(db: Database, input: {
439
536
  accountId: string;
440
537
  workspaceId: string;
538
+ observer?: WorkspaceDeleteObserver;
441
539
  }): Promise<DeleteWorkspaceIfQuiescentResult>;
442
540
  /** Claim a bounded cross-workspace batch after abandoned claims expire. */
443
541
  export declare function claimTemporalScheduleCleanups(db: Database, input: {
@@ -469,11 +567,37 @@ export declare function createApiKey(db: Database, input: {
469
567
  keyHash: string;
470
568
  permissions: Permission[];
471
569
  expiresAt?: Date | null;
570
+ credentialKind?: schema.ApiKeyCredentialKind;
571
+ }): Promise<ApiKey>;
572
+ export declare class OrganizationApiKeyLimitExceededError extends Error {
573
+ readonly limit: number;
574
+ constructor(limit: number);
575
+ }
576
+ /**
577
+ * Create an explicitly proven organization key under one account-scoped lock.
578
+ * An authenticating organization key may open exactly one temporary overlap
579
+ * slot at the configured cap so it can create a replacement before revocation.
580
+ */
581
+ export declare function createOrganizationApiKey(db: Database, input: {
582
+ accountId: string;
583
+ name: string;
584
+ description?: string | null;
585
+ prefix: string;
586
+ keyHash: string;
587
+ permissions: Permission[];
588
+ expiresAt?: Date | null;
589
+ maxActiveKeys?: number | null;
590
+ rotationSourceApiKeyId?: string | null;
472
591
  }): Promise<ApiKey>;
473
592
  export declare function listApiKeys(db: Database, workspaceId: string): Promise<ApiKey[]>;
593
+ export declare function listOrganizationApiKeys(db: Database, accountId: string): Promise<ApiKey[]>;
474
594
  export declare function countActiveApiKeysForWorkspace(db: Database, workspaceId: string): Promise<number>;
595
+ export declare function countActiveOrganizationApiKeysForAccount(db: Database, accountId: string): Promise<number>;
475
596
  export declare function revokeApiKey(db: Database, workspaceId: string, apiKeyId: string): Promise<ApiKey>;
476
- export declare function findActiveApiKeyByHash(db: Database, keyHash: string): Promise<ApiKey | null>;
597
+ export declare function revokeOrganizationApiKey(db: Database, accountId: string, apiKeyId: string): Promise<ApiKey | null>;
598
+ export declare function findActiveApiKeyByHash(db: Database, keyHash: string): Promise<(ApiKey & {
599
+ credentialKind: schema.ApiKeyCredentialKind;
600
+ }) | null>;
477
601
  export type GitHubInstallation = {
478
602
  id: string;
479
603
  accountId: string;
@@ -2478,6 +2602,7 @@ export type CorrectWorkspaceMemoryInput = {
2478
2602
  reason?: string | undefined;
2479
2603
  replacementText?: string | undefined;
2480
2604
  sessionId?: string | null | undefined;
2605
+ origin?: WorkspaceMemoryOrigin | undefined;
2481
2606
  };
2482
2607
  export type CorrectWorkspaceMemoryResult = {
2483
2608
  action: "archived" | "superseded" | "updated";
@@ -2700,6 +2825,43 @@ export declare function getScheduledTaskRevisionAuthority(db: Database, input: {
2700
2825
  } | null>;
2701
2826
  /** Failure settlement must not rewrite a source already committed as dispatched. */
2702
2827
  export declare function markScheduledTaskRunFailedIfQueued(db: Database, workspaceId: string, runId: string, error: string): Promise<void>;
2828
+ export type FailScheduledGeneratedSessionRouteResult = {
2829
+ action: "failed";
2830
+ events: SessionEvent[];
2831
+ sessionReclaimed: boolean;
2832
+ error: string;
2833
+ } | {
2834
+ action: "terminal";
2835
+ events: [];
2836
+ sessionReclaimed: false;
2837
+ status: "failed" | "skipped";
2838
+ error: string | null;
2839
+ } | {
2840
+ action: "advanced";
2841
+ events: [];
2842
+ sessionReclaimed: false;
2843
+ status: "dispatched" | "succeeded";
2844
+ };
2845
+ /**
2846
+ * Fail a queued scheduled run after its selected Connected Machine could not be
2847
+ * established. If the exact scheduler-created session has not acquired any
2848
+ * turn, fail that otherwise-orphaned session in the same transaction. A user
2849
+ * cancellation wins for the session row, but the machine failure still owns
2850
+ * the run settlement in this one durable boundary.
2851
+ *
2852
+ * The external liveness probe and sandbox CAS must happen before this DB-only
2853
+ * seam. This transaction serializes the resulting failure with initialization,
2854
+ * cancellation, and a concurrent dispatcher under the canonical
2855
+ * control -> workspace -> session -> scheduled-run lock order.
2856
+ */
2857
+ export declare function failScheduledGeneratedSessionRoute(db: Database, input: {
2858
+ accountId: string;
2859
+ workspaceId: string;
2860
+ taskId: string;
2861
+ runId: string;
2862
+ sessionId: string;
2863
+ error: string;
2864
+ }): Promise<FailScheduledGeneratedSessionRouteResult>;
2703
2865
  export declare function markScheduledTaskRunSkippedIfQueued(db: Database, input: {
2704
2866
  workspaceId: string;
2705
2867
  runId: string;
@@ -3435,6 +3597,30 @@ export declare function loadVariableSetForRun(db: Database, settings: Settings,
3435
3597
  export declare const loadWorkspaceEnvironmentForRun: typeof loadVariableSetForRun;
3436
3598
  /** @deprecated use VariableSetForRun */
3437
3599
  export type WorkspaceEnvironmentForRun = VariableSetForRun;
3600
+ export type WorkspaceCodexSubscriptionMode = "automatic" | "workspace" | "organization" | "disabled";
3601
+ export type EffectiveCodexSubscriptionSource = "workspace" | "organization" | "disabled";
3602
+ export type WorkspaceCodexSubscriptionSource = {
3603
+ accountId: string;
3604
+ workspaceId: string;
3605
+ workspaceKind: "personal" | "shared";
3606
+ mode: WorkspaceCodexSubscriptionMode;
3607
+ effectiveSource: EffectiveCodexSubscriptionSource;
3608
+ workspaceAvailable: boolean;
3609
+ organizationAvailable: boolean;
3610
+ };
3611
+ export declare function getWorkspaceCodexSubscriptionSource(db: Database, workspaceId: string): Promise<WorkspaceCodexSubscriptionSource>;
3612
+ export declare function setWorkspaceCodexSubscriptionModeInTransaction(scopedDb: Database, input: {
3613
+ accountId: string;
3614
+ workspaceId: string;
3615
+ subjectId: string | null;
3616
+ mode: WorkspaceCodexSubscriptionMode;
3617
+ }): Promise<WorkspaceCodexSubscriptionSource>;
3618
+ export declare function setWorkspaceCodexSubscriptionMode(db: Database, input: {
3619
+ accountId: string;
3620
+ workspaceId: string;
3621
+ subjectId: string | null;
3622
+ mode: WorkspaceCodexSubscriptionMode;
3623
+ }): Promise<WorkspaceCodexSubscriptionSource>;
3438
3624
  /**
3439
3625
  * Login / rotation write (multi-account P1). Caller passes the PRE-encrypted
3440
3626
  * credential blob. Keyed on the composite partial index (workspace, chatgpt
@@ -3468,6 +3654,65 @@ export declare function upsertCodexSubscriptionCredential(db: Database, input: {
3468
3654
  /** Direct managed-cookie human who most recently connected this row. */
3469
3655
  connectedBySubjectId?: string | null;
3470
3656
  }): Promise<UpsertCodexSubscriptionCredentialResult>;
3657
+ export declare function ensureOrganizationCodexRotationSettings(db: Database, input: {
3658
+ organizationId: string;
3659
+ actorSubjectId: string;
3660
+ }): Promise<void>;
3661
+ export declare function upsertOrganizationCodexSubscriptionCredential(db: Database, input: {
3662
+ organizationId: string;
3663
+ actorSubjectId: string;
3664
+ credentialEncrypted: string;
3665
+ chatgptAccountId: string | null;
3666
+ scopes: string | null;
3667
+ planType: string | null;
3668
+ isFedramp: boolean;
3669
+ expiresAt: Date | null;
3670
+ lastRefreshAt: Date | null;
3671
+ accountEmail?: string | null;
3672
+ label?: string | null;
3673
+ }): Promise<{
3674
+ id: string;
3675
+ isNew: boolean;
3676
+ wakeTargets: CodexCapacityWakeTarget[];
3677
+ }>;
3678
+ export declare function listOrganizationCodexAccountStatuses(db: Database, input: {
3679
+ organizationId: string;
3680
+ actorSubjectId: string;
3681
+ }): Promise<CodexAccountStatus[]>;
3682
+ export declare function getOrganizationCodexRotationSettings(db: Database, input: {
3683
+ organizationId: string;
3684
+ actorSubjectId: string;
3685
+ }): Promise<CodexRotationSettings | null>;
3686
+ export declare function setActiveOrganizationCodexCredential(db: Database, input: {
3687
+ organizationId: string;
3688
+ actorSubjectId: string;
3689
+ credentialId: string;
3690
+ }): Promise<{
3691
+ activated: boolean;
3692
+ wakeTargets: CodexCapacityWakeTarget[];
3693
+ }>;
3694
+ export declare function updateOrganizationCodexRotationSettings(db: Database, input: {
3695
+ organizationId: string;
3696
+ actorSubjectId: string;
3697
+ rotationEnabled: boolean;
3698
+ }): Promise<(CodexRotationSettings & {
3699
+ wakeTargets: CodexCapacityWakeTarget[];
3700
+ }) | null>;
3701
+ export declare function renameOrganizationCodexAccount(db: Database, input: {
3702
+ organizationId: string;
3703
+ actorSubjectId: string;
3704
+ credentialId: string;
3705
+ label: string | null;
3706
+ }): Promise<boolean>;
3707
+ export declare function disconnectOrganizationCodexAccount(db: Database, input: {
3708
+ organizationId: string;
3709
+ actorSubjectId: string;
3710
+ credentialId: string;
3711
+ }): Promise<{
3712
+ removed: boolean;
3713
+ newActiveCredentialId: string | null;
3714
+ wakeTargets: CodexCapacityWakeTarget[];
3715
+ }>;
3471
3716
  export type CodexAppsSettings = {
3472
3717
  credentialId: string | null;
3473
3718
  version: number;
@@ -3644,6 +3889,7 @@ export declare function isCodexBilledTurn(input: {
3644
3889
  }): Promise<boolean>;
3645
3890
  export type CodexAccountStatus = {
3646
3891
  id: string;
3892
+ source: Exclude<EffectiveCodexSubscriptionSource, "disabled">;
3647
3893
  chatgptAccountId: string | null;
3648
3894
  label: string | null;
3649
3895
  accountEmail: string | null;
@@ -3667,6 +3913,8 @@ export type CodexAccountStatus = {
3667
3913
  secondaryResetAt: Date | null;
3668
3914
  usageCheckedAt: Date | null;
3669
3915
  exhaustedUntil: Date | null;
3916
+ /** Typed provider-refusal provenance; null for legacy/cleared cooldowns. */
3917
+ exhaustedKind: CodexCredentialCooldownKind | null;
3670
3918
  };
3671
3919
  /**
3672
3920
  * A metadata-only scheduling candidate observed while the workspace's rotation
@@ -3674,7 +3922,7 @@ export type CodexAccountStatus = {
3674
3922
  * the selection cursor gives deterministic fairness after those holders drain.
3675
3923
  * None of these fields contains credential material.
3676
3924
  */
3677
- export type CodexLeaseAccountStatus = Omit<CodexAccountStatus, "allocatorVersion" | "allocatorUpdatedBySubjectId" | "allocatorUpdatedAt" | "resetCreditAvailableCount" | "resetCreditsCheckedAt" | "connectedBySubjectId"> & {
3925
+ export type CodexLeaseAccountStatus = Omit<CodexAccountStatus, "allocatorVersion" | "allocatorUpdatedBySubjectId" | "allocatorUpdatedAt" | "resetCreditAvailableCount" | "resetCreditsCheckedAt" | "connectedBySubjectId" | "source"> & {
3678
3926
  activeLeaseCount: number;
3679
3927
  selectionCount: number;
3680
3928
  lastSelectedAt: Date | null;
@@ -4058,6 +4306,7 @@ export type CodexCredentialLeaseQuarantine = {
4058
4306
  } | {
4059
4307
  kind: "cooldown";
4060
4308
  until: Date;
4309
+ cooldownKind: CodexCredentialCooldownKind;
4061
4310
  };
4062
4311
  /**
4063
4312
  * Quarantine the credential served by one exact live holder. The lease row is
@@ -4263,7 +4512,7 @@ export declare function completeCodexResetRedemption(db: Database, input: {
4263
4512
  }): Promise<CodexCapacityMutationResult<CodexResetRedemptionAttempt | null>>;
4264
4513
  /** The P2 usage-cache snapshot written by the refreshing usage wrapper. */
4265
4514
  /**
4266
- * Cache-write for P2 quota bars: persist the five plaintext usage columns on a
4515
+ * Cache-write for P2 quota bars and revision-fenced quota cooldown repair on a
4267
4516
  * SPECIFIC credential row. NEVER touches credential_encrypted. RLS-scoped, guarded
4268
4517
  * by (id, workspace_id) so it can only write a row the workspace owns. Returns true
4269
4518
  * iff a row was updated (false ⇒ the credential was disconnected under us — the
@@ -4327,9 +4576,9 @@ export declare function setInitialActiveCodexCredential(db: Database, workspaceI
4327
4576
  * never race the (id, version) token-refresh CAS in recordCodexTokenRefresh / setCodexCredentialStatus.
4328
4577
  * Returns true iff a row was updated (false ⇒ the credential was disconnected under us).
4329
4578
  */
4330
- export declare function setCodexCredentialExhausted(db: Database, workspaceId: string, credentialId: string, until: Date | null): Promise<boolean>;
4579
+ export declare function setCodexCredentialExhausted(db: Database, workspaceId: string, credentialId: string, until: Date | null, cooldownKind: CodexCredentialCooldownKind | null): Promise<boolean>;
4331
4580
  /** Cooldown mutation plus its committed durable capacity-wake outbox. */
4332
- export declare function setCodexCredentialExhaustedWithWakeTargets(db: Database, workspaceId: string, credentialId: string, until: Date | null): Promise<CodexCapacityMutationResult<boolean>>;
4581
+ export declare function setCodexCredentialExhaustedWithWakeTargets(db: Database, workspaceId: string, credentialId: string, until: Date | null, cooldownKind: CodexCredentialCooldownKind | null): Promise<CodexCapacityMutationResult<boolean>>;
4333
4582
  /**
4334
4583
  * P3 reactive-rotation boundedness (Finding 1b): the number of CONSECUTIVE rotated
4335
4584
  * 429-failover turns since the session last had a SUCCESSFUL turn. Counts
@@ -4906,9 +5155,11 @@ export declare function listSessions(db: Database, workspaceId: string, options?
4906
5155
  * result. The workspace filter remains authoritative under FORCE RLS.
4907
5156
  */
4908
5157
  export declare function getLatestSessionModelForSubject(db: Database, workspaceId: string, subjectId: string): Promise<string | null>;
4909
- export type SessionDiscoveryOrderBy = "createdAt" | "updatedAt";
5158
+ export type SessionDiscoveryOrderBy = "createdAt" | "updatedAt" | "relevance";
4910
5159
  export type SessionDiscoveryCursor = {
4911
5160
  orderBy: SessionDiscoveryOrderBy;
5161
+ /** Stable rank class for relevance order; null for chronological order. */
5162
+ sortRank: number | null;
4912
5163
  /** Decimal database activity revision; zero is the legacy/created-order bucket. */
4913
5164
  sortRevision: string;
4914
5165
  /** Exact PostgreSQL timestamp text (including microseconds), not a JS Date. */
@@ -4920,6 +5171,8 @@ export type SessionDiscoveryCursor = {
4920
5171
  snapshotRevision: string;
4921
5172
  /** Incremental revision scope is cursor-bound and cannot change on continuation. */
4922
5173
  updatedAfter: string | null;
5174
+ /** SHA-256 of normalized relevance filters; null for chronological order. */
5175
+ filterHash: string | null;
4923
5176
  };
4924
5177
  export declare const SESSION_DISCOVERY_GOAL_MAX_CHARS = 600;
4925
5178
  export declare const SESSION_DISCOVERY_MESSAGE_MAX_CHARS = 600;
@@ -4944,12 +5197,15 @@ export type SessionDiscoverySummary = {
4944
5197
  preview: string | null;
4945
5198
  previewOriginalChars: number | null;
4946
5199
  } | null;
5200
+ workDiscovery: WorkDiscoveryProjection;
4947
5201
  createdAt: string;
4948
5202
  updatedAt: string;
4949
5203
  /** Internal exact revision key; omitted from the MCP row projection. */
4950
5204
  sortRevision: string;
4951
5205
  /** Internal exact keyset timestamp; omitted from the MCP row projection. */
4952
5206
  sortAt: string;
5207
+ /** Internal stable relevance class; omitted from public row projections. */
5208
+ sortRank: number | null;
4953
5209
  };
4954
5210
  /**
4955
5211
  * Compact-by-construction discovery projection for the first-party
@@ -4963,7 +5219,17 @@ export declare function listSessionDiscoverySummaries(db: Database, workspaceId:
4963
5219
  orderBy?: SessionDiscoveryOrderBy;
4964
5220
  updatedAfter?: string;
4965
5221
  parentSessionId?: string | null;
5222
+ rootSessionId?: string;
5223
+ query?: string;
5224
+ /** @deprecated use query; retained for the existing topology route. */
4966
5225
  search?: string;
5226
+ statuses?: SessionStatus[];
5227
+ activeOnly?: boolean;
5228
+ recentHours?: number;
5229
+ subject?: WorkClaimSubjectFilter;
5230
+ claimLimit?: number;
5231
+ /** Skip advisory claim reads for an operator-disabled discovery rollout. */
5232
+ includeWorkDiscovery?: boolean;
4967
5233
  subjectId?: string;
4968
5234
  authorizationScope?: SessionAuthorizationListScope;
4969
5235
  }): Promise<{
@@ -4976,6 +5242,8 @@ export declare function listSessionDiscoverySummaries(db: Database, workspaceId:
4976
5242
  snapshotRevision: string;
4977
5243
  updatedThrough: string | null;
4978
5244
  updatedAfter: string | null;
5245
+ /** Internal relevance cursor binding; omitted from row projections. */
5246
+ filterHash: string | null;
4979
5247
  }>;
4980
5248
  export type SessionDiscoveryAncestor = {
4981
5249
  id: string;
@@ -4987,7 +5255,7 @@ export type SessionDiscoveryAncestor = {
4987
5255
  * Authorization is re-applied to every ancestor so exact-session grants never
4988
5256
  * acquire parent metadata merely by searching for their target.
4989
5257
  */
4990
- export declare function listSessionDiscoveryAncestorPaths(db: Database, workspaceId: string, sessionIds: string[], authorizationScope?: SessionAuthorizationListScope): Promise<Map<string, SessionDiscoveryAncestor[]>>;
5258
+ export declare function listSessionDiscoveryAncestorPaths(db: Database, workspaceId: string, sessionIds: string[], authorizationScope?: SessionAuthorizationListScope, subjectId?: string): Promise<Map<string, SessionDiscoveryAncestor[]>>;
4991
5259
  export type SessionLineage = {
4992
5260
  ancestors: Session[];
4993
5261
  children: LineageNode[];
@@ -5508,6 +5776,25 @@ export declare function recordSkippedContextCompaction(db: Database, input: {
5508
5776
  recorded: false;
5509
5777
  reason: TurnAttemptFenceRejectReason | "request_not_pending";
5510
5778
  }>;
5779
+ /**
5780
+ * Read the durable handoff condition immediately after one exact compaction
5781
+ * landmark settles. Steer admission deliberately leaves the active attempt
5782
+ * unfenced while its latest compaction event is `started`; the worker calls
5783
+ * this at the first safe boundary after `compacted`/`skipped` and supersedes
5784
+ * the ordinary turn before another model request can begin.
5785
+ *
5786
+ * The later terminal settlement remains the authority fence. This read only
5787
+ * decides whether that settlement is needed, so a concurrent Pause/Cancel or a
5788
+ * Steer admitted after the landmark can still win and make the caller stale.
5789
+ */
5790
+ export declare function hasPendingSteerAfterContextCompaction(db: Database, input: {
5791
+ accountId: string;
5792
+ workspaceId: string;
5793
+ sessionId: string;
5794
+ turnId: string;
5795
+ executionGeneration: number;
5796
+ attemptId: string;
5797
+ }): Promise<boolean>;
5511
5798
  /**
5512
5799
  * The next free WHOLE-NUMBER history position for a session: one past the
5513
5800
  * largest existing position (active or superseded), floored so the synthetic
@@ -5922,6 +6209,54 @@ export type AcquireLeaseResult = {
5922
6209
  reason: "superseded" | "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress";
5923
6210
  lease: LeaseSnapshot;
5924
6211
  };
6212
+ export type SandboxSharedPreparationSnapshot = {
6213
+ status: "running" | "completed" | "failed";
6214
+ leaseEpoch: number;
6215
+ instanceId: string;
6216
+ specHash: string;
6217
+ claimId: string;
6218
+ ownerAttemptId: string;
6219
+ attempt: number;
6220
+ revision: number;
6221
+ startedAt: Date;
6222
+ deadlineAt: Date;
6223
+ settledAt: Date | null;
6224
+ };
6225
+ export type ClaimSandboxSharedPreparationInput = {
6226
+ accountId: string;
6227
+ workspaceId: string;
6228
+ sandboxGroupId: string;
6229
+ expectedLeaseEpoch: number;
6230
+ expectedInstanceId: string;
6231
+ specHash: string;
6232
+ holderId: string;
6233
+ claimId: string;
6234
+ ownerAttemptId: string;
6235
+ timeoutMs: number;
6236
+ };
6237
+ export type ClaimSandboxSharedPreparationResult = {
6238
+ role: "owner" | "joined" | "reused";
6239
+ preparation: SandboxSharedPreparationSnapshot;
6240
+ } | {
6241
+ role: "fenced";
6242
+ lease: LeaseSnapshot | null;
6243
+ };
6244
+ /**
6245
+ * Claim, join, or reuse immutable setup for one exact physical sandbox. The
6246
+ * provider operation remains outside the transaction; the claim deadline and
6247
+ * box-local idempotency marker make a lost owner recoverable without sharing
6248
+ * any turn-private credential or file material.
6249
+ */
6250
+ export declare function claimSandboxSharedPreparation(db: Database, input: ClaimSandboxSharedPreparationInput): Promise<ClaimSandboxSharedPreparationResult>;
6251
+ export declare function readSandboxSharedPreparation(db: Database, input: Omit<ClaimSandboxSharedPreparationInput, "claimId" | "ownerAttemptId" | "timeoutMs">): Promise<{
6252
+ status: "available";
6253
+ preparation: SandboxSharedPreparationSnapshot;
6254
+ } | {
6255
+ status: "fenced";
6256
+ }>;
6257
+ export declare function settleSandboxSharedPreparation(db: Database, input: Omit<ClaimSandboxSharedPreparationInput, "ownerAttemptId" | "timeoutMs"> & {
6258
+ outcome: "completed" | "failed";
6259
+ }): Promise<boolean>;
5925
6260
  export declare class SandboxLeaseSupersededError extends Error {
5926
6261
  readonly sandboxGroupId: string;
5927
6262
  readonly leaseEpoch: number;
@@ -6628,6 +6963,8 @@ export declare function listMeterableWarmLeases(db: Database): Promise<Meterable
6628
6963
  * even after every affected sandbox lease has become cold. */
6629
6964
  export declare function listSandboxViewerForceDrainWorkspaceIds(db: Database): Promise<string[]>;
6630
6965
  export declare function countQueuedTurns(db: Database): Promise<number>;
6966
+ export type SessionRecoveryBacklogState = "quiescence_missing" | "projection_stale";
6967
+ export declare function countSessionRecoveryBacklog(db: Database): Promise<Record<SessionRecoveryBacklogState, number>>;
6631
6968
  export declare function countSandboxLeasesByLiveness(db: Database): Promise<Record<SandboxLeaseLiveness, number>>;
6632
6969
  export type CreditBalanceByAccount = {
6633
6970
  accountId: string;
@@ -6663,6 +7000,18 @@ export declare class SandboxWorkspaceMutationFencedError extends Error {
6663
7000
  readonly name: string;
6664
7001
  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);
6665
7002
  }
7003
+ /** An operation named a durable retained process that has already reached a
7004
+ * terminal state. This remains a fence—the provider must not be called again
7005
+ * and contradictory proof must not overwrite durable truth—but carries the
7006
+ * existing terminal result so routing can reconcile a concurrent settlement
7007
+ * or report completion/loss instead of presenting a retryable platform failure
7008
+ * for a handle that can never become active again. */
7009
+ export declare class SandboxRetainedProcessTerminalError extends SandboxWorkspaceMutationFencedError {
7010
+ readonly state: "exited" | "lost";
7011
+ readonly exitCode: number | null;
7012
+ readonly name = "SandboxRetainedProcessTerminalError";
7013
+ constructor(state: "exited" | "lost", exitCode: number | null);
7014
+ }
6666
7015
  export type SandboxWorkspaceMutationAdmission = {
6667
7016
  id: string;
6668
7017
  leaseId: string;
@@ -6984,7 +7333,8 @@ export declare function countActiveRetainedProcessesByOwnerState(db: Database):
6984
7333
  export declare function countExpiredDrainingSandboxLeases(db: Database): Promise<ExpiredDrainingSandboxLeaseCount[]>;
6985
7334
  /** Settle an exact retained process only after exit or definitive loss proof.
6986
7335
  * The process row, parent admission, non-TTL holder, and lease count transition
6987
- * commit atomically. Duplicate identical proof is idempotent; conflicting proof
7336
+ * commit atomically. A duplicate terminal state + exit code is idempotent and
7337
+ * preserves the first durable evidence reason; contradictory physical truth
6988
7338
  * fails closed. */
6989
7339
  export declare function settleRetainedProcess(db: Database, input: {
6990
7340
  accountId: string;
@@ -8608,6 +8958,9 @@ export type InitializeSessionStartInput = {
8608
8958
  /** Trusted create-session policy. Omitted only by legacy low-level callers. */
8609
8959
  turnExecutionPolicy?: TurnExecutionPolicyV1;
8610
8960
  createdEventPayload: Record<string, unknown>;
8961
+ /** Sensitive-safe semantic title supplied by the trusted agent-child create
8962
+ * path. It is committed with the initial timeline, never as a bare row edit. */
8963
+ initialAutomaticTitle?: string | null;
8611
8964
  goal?: {
8612
8965
  text: string;
8613
8966
  successCriteria?: string | null;
@@ -8684,6 +9037,16 @@ export type ClaimSessionWorkForAttemptInput = {
8684
9037
  action: "reject";
8685
9038
  reason: string;
8686
9039
  }>;
9040
+ /**
9041
+ * A requires-action resume first persists its open tool-call result, then
9042
+ * re-enters this exact attempt to attach machine input that arrived while the
9043
+ * session was blocked. The dispatch metadata freezes the session's durable
9044
+ * pending-event sequence at attempt claim; timestamps cannot own this fence
9045
+ * because a producer transaction may wait on the session lock. Keeping this
9046
+ * opt-in prevents an ordinary activity retry from inserting a system message
9047
+ * ahead of the required call/result pair in canonical history.
9048
+ */
9049
+ attachPendingUpdatesToRunningAttempt?: boolean;
8687
9050
  };
8688
9051
  export type ClaimSessionWorkForAttemptResult = {
8689
9052
  action: "claimed";
@@ -9244,21 +9607,24 @@ export declare function claimPendingSessionWorkflowWakes(db: Database, limit?: n
9244
9607
  * accepted direction or an interrupted attempt awaiting writer-set proof.
9245
9608
  * Temporal accepting a signal is transport evidence, not proof that a closing
9246
9609
  * workflow observed Postgres. While active control still has an actionable
9247
- * Agent Steer or pending quiescence, retain the revision so the bounded outbox
9248
- * dispatcher retries signalWithStart. The attempt-fenced claim consumes an
9249
- * Agent Steer once; a real Pause is the typed blocker and may acknowledge this
9610
+ * Agent Steer, a current wake still owns an accepted queued human/API turn, or
9611
+ * an attempt awaits quiescence, retain the revision so the bounded outbox
9612
+ * dispatcher retries signalWithStart. The attempt-fenced claim consumes each
9613
+ * direction once; a real Pause is the typed blocker and may acknowledge this
9250
9614
  * revision because Resume commits a new one.
9251
9615
  *
9252
9616
  * An older sender may advance only its own revision; it cannot clear a claim or
9253
- * failure state belonging to a newer revision. The control -> workspace ->
9254
- * session lock prefix serializes this decision with Steer, Pause/Resume, and
9255
- * claim without weakening physical-quiescence admission.
9617
+ * failure state belonging to a newer revision. Therefore queued prompt work
9618
+ * blocks acknowledgement only for the current coalesced revision: a stale
9619
+ * acknowledgement still leaves the newer revision outstanding. The control ->
9620
+ * workspace -> session lock prefix serializes this decision with Send, Steer,
9621
+ * Pause/Resume, and claim without weakening physical-quiescence admission.
9256
9622
  */
9257
9623
  export type SessionWorkflowWakeDeliveryResult = {
9258
9624
  action: "acknowledged";
9259
9625
  } | {
9260
9626
  action: "pending_admission";
9261
- blocker: "pending_agent_steer" | "pending_quiescence";
9627
+ blocker: "pending_agent_steer" | "pending_prompt_turn" | "pending_quiescence";
9262
9628
  };
9263
9629
  export declare function markSessionWorkflowWakeDelivered(db: Database, input: Omit<SessionWorkflowWake, "interruptionRequested">): Promise<SessionWorkflowWakeDeliveryResult>;
9264
9630
  /** Record delivery failure; the claim already scheduled the bounded retry. */
@@ -9344,6 +9710,7 @@ export declare function childRequiresActionResolutionExists(db: Database, worksp
9344
9710
  export declare function listOutstandingSessionSystemUpdates(db: Database, workspaceId: string, sessionId: string): Promise<SessionSystemUpdate[]>;
9345
9711
  /** Internal updates atomically attached when this inference was claimed. */
9346
9712
  export declare function listSessionSystemUpdatesForTurn(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise<SessionSystemUpdate[]>;
9713
+ export declare function sessionEventRawLaneEnabled(value?: string | undefined): boolean;
9347
9714
  export declare function appendSessionEvents(db: Database, workspaceId: string, sessionId: string, inputs: AppendEventInput[]): Promise<SessionEvent[]>;
9348
9715
  export type AcceptSessionApprovalDecisionResult = {
9349
9716
  action: "accepted";
@@ -9397,17 +9764,34 @@ export declare function expireSessionInteractionIntervention(db: Database, input
9397
9764
  * events remain associated with their producer in logs but are not admitted to
9398
9765
  * the current durable timeline once the turn row moved generation or terminal.
9399
9766
  */
9400
- export declare function appendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[]): Promise<{
9767
+ export declare function appendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[], observer?: SessionEventAppendObserver): Promise<{
9401
9768
  events: SessionEvent[];
9402
9769
  accepted: boolean;
9403
9770
  canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];
9404
9771
  }>;
9772
+ export type SessionEventAppendClass = "raw" | "semantic" | "mixed";
9773
+ export type SessionEventAppendPhase = "transaction" | "mutation" | "turn_attempt_fence" | "idempotency" | "event_insert" | "projection" | "sequence_update";
9774
+ export type SessionEventAppendPhaseOutcome = "ok" | "rejected" | "mutation_skipped" | "projection_skipped" | "escalated" | "error";
9775
+ export type SessionEventAppendPhaseObservation = {
9776
+ phase: SessionEventAppendPhase;
9777
+ eventClass: SessionEventAppendClass;
9778
+ eventCount: number;
9779
+ outcome: SessionEventAppendPhaseOutcome;
9780
+ durationSeconds: number;
9781
+ };
9782
+ export type SessionEventAppendObserver = {
9783
+ onPhase?: (observation: SessionEventAppendPhaseObservation) => void;
9784
+ };
9785
+ export declare function sessionEventAppendClass(inputs: ReadonlyArray<{
9786
+ type: string;
9787
+ }>): SessionEventAppendClass;
9788
+ export declare function observeSessionEventAppendPhase(observer: SessionEventAppendObserver | undefined, observation: SessionEventAppendPhaseObservation): void;
9405
9789
  /**
9406
9790
  * Commit one exact-attempt mutation and its timeline projection together. The
9407
9791
  * mutation runs first so Codemode's operation-row lock order remains stable;
9408
9792
  * returning false leaves both the mutation and projection absent.
9409
9793
  */
9410
- export declare function mutateAndAppendSessionEventsForTurnAttempt(db: Database, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, inputs: AppendEventInput[], mutate: (tx: Database) => Promise<boolean>): Promise<{
9794
+ 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<{
9411
9795
  events: SessionEvent[];
9412
9796
  accepted: boolean;
9413
9797
  mutationApplied: boolean;
@@ -9488,7 +9872,7 @@ export declare function buildCodexTokenResolver(db: Database, settings: Settings
9488
9872
  export declare function fetchCodexUsageForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): ReturnType<typeof fetchCodexUsageForAccountCore>;
9489
9873
  export declare function fetchCodexRateLimitResetCreditsForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): ReturnType<typeof fetchCodexRateLimitResetCreditsForAccountCore>;
9490
9874
  export declare function buildConnectionTokenResolver(db: Database, settings: Settings, deps?: ConnectionBrokerDeps, options?: ConnectionTokenResolverOptions): ReturnType<typeof buildConnectionTokenResolverCore>;
9491
- export { withCodexTokenDeadline, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialForRun, type CodexCredentialTokens, type CodexRateLimitResetCreditsAccountResult, type CodexTokenDeadlineClock, type CodexTokenDeadlineOptions, } from "./codex-token-resolver.js";
9875
+ export { withCodexTokenDeadline, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialCooldownKind, type CodexCredentialForRun, type CodexCredentialTokens, type CodexRateLimitResetCreditsAccountResult, type CodexTokenDeadlineClock, type CodexTokenDeadlineOptions, } from "./codex-token-resolver.js";
9492
9876
  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";
9493
9877
  export { CapabilityComponentVersionConflictError, cleanupOrphanedCapabilityComponents, effectiveCapabilityOwnerSql, type CapabilityComponentOwnerIdentity, } from "./capability-components.js";
9494
9878
  export { adoptPackComponentReferences, finalizePackComponentOwnership, listPackInstallationComponents, PackComponentResolutionError, previewPackComponentRelease, recordPackInlineSkillComponent, releasePackComponents, resolvePackComponentReferences, resolvePackInlineSkillReferences, type PackInlineSkillRequirement, type StoredPackInstallationComponent, } from "./pack-components.js";