@opengeni/db 3.6.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 (80) hide show
  1. package/dist/canonical-human-identities.js +3 -3
  2. package/dist/{chunk-744DFC65.js → chunk-4NAR7FBA.js} +92 -6
  3. package/dist/chunk-4NAR7FBA.js.map +1 -0
  4. package/dist/{chunk-IW6O6G7R.js → chunk-5NNCGFQY.js} +2 -2
  5. package/dist/{chunk-G3732M3T.js → chunk-DZCYW2WT.js} +2 -2
  6. package/dist/{chunk-WW7AJ5IC.js → chunk-F6PBS6WE.js} +5 -7
  7. package/dist/chunk-F6PBS6WE.js.map +1 -0
  8. package/dist/{chunk-UJ2EW3QI.js → chunk-O56DM5GZ.js} +340 -85
  9. package/dist/chunk-O56DM5GZ.js.map +1 -0
  10. package/dist/{chunk-CDMMSUWJ.js → chunk-S3TDDCS2.js} +3 -3
  11. package/dist/{chunk-Q5YUGQVK.js → chunk-SZAWDXQC.js} +3 -3
  12. package/dist/{chunk-UGDVSQ6U.js → chunk-U4WPPEBH.js} +2 -2
  13. package/dist/{chunk-2NT476HD.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 +382 -18
  21. package/dist/index.js +4513 -2065
  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 +5 -5
  28. package/dist/schema.d.ts +725 -4
  29. package/dist/schema.js +13 -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/drizzle/0369_local_human_personal_authority.sql +350 -0
  37. package/drizzle/0370_workspace_member_management_scope.sql +98 -0
  38. package/drizzle/0371_workspace_member_candidate_inventory.sql +128 -0
  39. package/drizzle/0372_ordered_variable_set_runtime_authority.sql +287 -0
  40. package/drizzle/0373_sandbox_shared_preparation.sql +59 -0
  41. package/drizzle/0374_session_event_cursors.sql +315 -0
  42. package/drizzle/0375_session_recovery_observability.sql +73 -0
  43. package/drizzle/0376_organization_workspace_inventory.sql +88 -0
  44. package/drizzle/0377_scoped_rig_health_projection.sql +80 -0
  45. package/drizzle/0378_scoped_rig_health_audit_timestamp.sql +77 -0
  46. package/drizzle/0379_session_event_raw_lane_activation.sql +518 -0
  47. package/drizzle/0380_autonomous_company_profile_agent_policy.sql +829 -0
  48. package/drizzle/0381_organization_codex_subscription_inheritance.sql +720 -0
  49. package/drizzle/0382_organization_api_key_provenance.sql +91 -0
  50. package/drizzle/0383_codex_cooldown_reconciliation.sql +51 -0
  51. package/drizzle/0384_codex_cooldown_revision_guard_privileges.sql +6 -0
  52. package/drizzle/0385_connected_machine_legacy_tilde_workdirs.sql +25 -0
  53. package/drizzle/0386_local_organization_administration.sql +157 -0
  54. package/package.json +6 -6
  55. package/src/codex-token-resolver.ts +26 -1
  56. package/src/company-brain-governed-writes.ts +30 -1
  57. package/src/company-profile-agent-admin.ts +68 -1
  58. package/src/company-profile-agent-policy.ts +126 -0
  59. package/src/company-profile-schema.ts +115 -1
  60. package/src/database.ts +3 -5
  61. package/src/index.ts +3626 -456
  62. package/src/managed-human-provisioning.ts +3 -3
  63. package/src/memory-domain.ts +9 -4
  64. package/src/organization-membership-lifecycle.ts +0 -1
  65. package/src/provision-roles.ts +83 -4
  66. package/src/runtime-posture.ts +22 -0
  67. package/src/schema.ts +161 -8
  68. package/src/session-control.ts +177 -59
  69. package/src/session-queue-commands.ts +146 -40
  70. package/src/session-tool-call-settlement.ts +34 -7
  71. package/src/user-resource-authority.ts +56 -0
  72. package/dist/chunk-744DFC65.js.map +0 -1
  73. package/dist/chunk-UJ2EW3QI.js.map +0 -1
  74. package/dist/chunk-WW7AJ5IC.js.map +0 -1
  75. /package/dist/{chunk-IW6O6G7R.js.map → chunk-5NNCGFQY.js.map} +0 -0
  76. /package/dist/{chunk-G3732M3T.js.map → chunk-DZCYW2WT.js.map} +0 -0
  77. /package/dist/{chunk-CDMMSUWJ.js.map → chunk-S3TDDCS2.js.map} +0 -0
  78. /package/dist/{chunk-Q5YUGQVK.js.map → chunk-SZAWDXQC.js.map} +0 -0
  79. /package/dist/{chunk-UGDVSQ6U.js.map → chunk-U4WPPEBH.js.map} +0 -0
  80. /package/dist/{chunk-2NT476HD.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, 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";
@@ -70,7 +71,7 @@ export * from "./memory-domain.js";
70
71
  import { type Database, type SessionActivityDatabase } from "./database.js";
71
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";
72
73
  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";
74
+ import { buildCodexTokenResolver as buildCodexTokenResolverCore, fetchCodexRateLimitResetCreditsForAccount as fetchCodexRateLimitResetCreditsForAccountCore, fetchCodexUsageForAccount as fetchCodexUsageForAccountCore, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialCooldownKind, type CodexCredentialForRun } from "./codex-token-resolver.js";
74
75
  import { buildConnectionTokenResolver as buildConnectionTokenResolverCore, type ConnectionBrokerDeps, type ConnectionCredentialForBroker, type ConnectionTokenResolverOptions } from "./connection-token-resolver.js";
75
76
  /** Raised when a durable session tool-policy write lost its version fence. */
76
77
  export declare class SessionToolPolicyVersionConflictError extends Error {
@@ -262,6 +263,18 @@ export declare const allWorkspacePermissions: Permission[];
262
263
  * with ambient access to the private workspace.
263
264
  */
264
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>;
265
278
  export declare const allAccountPermissions: Permission[];
266
279
  export type BootstrapWorkspaceInput = {
267
280
  accountExternalSource: string;
@@ -300,6 +313,14 @@ export declare function getWorkspace(db: Database, workspaceId: string): Promise
300
313
  export declare function getManagedAccount(db: Database, accountId: string): Promise<ManagedAccount | null>;
301
314
  export declare function requireWorkspace(db: Database, workspaceId: string): Promise<Workspace>;
302
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[]>;
303
324
  export declare function countWorkspacesForAccount(db: Database, accountId: string): Promise<number>;
304
325
  export declare function createWorkspace(db: Database, input: {
305
326
  accountId: string;
@@ -308,7 +329,36 @@ export declare function createWorkspace(db: Database, input: {
308
329
  externalSource?: string | null;
309
330
  externalId?: string | null;
310
331
  agentInstructions?: string | null;
332
+ maxWorkspacesPerAccount?: number | null;
311
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
+ }>;
312
362
  /**
313
363
  * Create one shared workspace through the direct managed-human organization
314
364
  * control plane. Organization authority is rechecked inside the lifecycle
@@ -331,6 +381,40 @@ export declare function grantWorkspaceAccess(db: Database, input: {
331
381
  role?: string;
332
382
  permissions: Permission[];
333
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[]>;
334
418
  /**
335
419
  * Organization control-plane metadata update for one shared workspace. This
336
420
  * capability never creates a workspace membership or an operational grant for
@@ -427,6 +511,18 @@ export type DeleteWorkspaceIfQuiescentResult = {
427
511
  } | {
428
512
  status: "not_found" | "only_workspace" | "active_sessions" | "active_video_generations" | "active_background_commands" | "live_sandboxes";
429
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
+ };
430
526
  /**
431
527
  * Atomically prove a workspace has no live runtime ownership and delete it.
432
528
  *
@@ -439,6 +535,7 @@ export type DeleteWorkspaceIfQuiescentResult = {
439
535
  export declare function deleteWorkspaceIfQuiescent(db: Database, input: {
440
536
  accountId: string;
441
537
  workspaceId: string;
538
+ observer?: WorkspaceDeleteObserver;
442
539
  }): Promise<DeleteWorkspaceIfQuiescentResult>;
443
540
  /** Claim a bounded cross-workspace batch after abandoned claims expire. */
444
541
  export declare function claimTemporalScheduleCleanups(db: Database, input: {
@@ -470,11 +567,37 @@ export declare function createApiKey(db: Database, input: {
470
567
  keyHash: string;
471
568
  permissions: Permission[];
472
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;
473
591
  }): Promise<ApiKey>;
474
592
  export declare function listApiKeys(db: Database, workspaceId: string): Promise<ApiKey[]>;
593
+ export declare function listOrganizationApiKeys(db: Database, accountId: string): Promise<ApiKey[]>;
475
594
  export declare function countActiveApiKeysForWorkspace(db: Database, workspaceId: string): Promise<number>;
595
+ export declare function countActiveOrganizationApiKeysForAccount(db: Database, accountId: string): Promise<number>;
476
596
  export declare function revokeApiKey(db: Database, workspaceId: string, apiKeyId: string): Promise<ApiKey>;
477
- 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>;
478
601
  export type GitHubInstallation = {
479
602
  id: string;
480
603
  accountId: string;
@@ -2479,6 +2602,7 @@ export type CorrectWorkspaceMemoryInput = {
2479
2602
  reason?: string | undefined;
2480
2603
  replacementText?: string | undefined;
2481
2604
  sessionId?: string | null | undefined;
2605
+ origin?: WorkspaceMemoryOrigin | undefined;
2482
2606
  };
2483
2607
  export type CorrectWorkspaceMemoryResult = {
2484
2608
  action: "archived" | "superseded" | "updated";
@@ -2701,6 +2825,43 @@ export declare function getScheduledTaskRevisionAuthority(db: Database, input: {
2701
2825
  } | null>;
2702
2826
  /** Failure settlement must not rewrite a source already committed as dispatched. */
2703
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>;
2704
2865
  export declare function markScheduledTaskRunSkippedIfQueued(db: Database, input: {
2705
2866
  workspaceId: string;
2706
2867
  runId: string;
@@ -3436,6 +3597,30 @@ export declare function loadVariableSetForRun(db: Database, settings: Settings,
3436
3597
  export declare const loadWorkspaceEnvironmentForRun: typeof loadVariableSetForRun;
3437
3598
  /** @deprecated use VariableSetForRun */
3438
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>;
3439
3624
  /**
3440
3625
  * Login / rotation write (multi-account P1). Caller passes the PRE-encrypted
3441
3626
  * credential blob. Keyed on the composite partial index (workspace, chatgpt
@@ -3469,6 +3654,65 @@ export declare function upsertCodexSubscriptionCredential(db: Database, input: {
3469
3654
  /** Direct managed-cookie human who most recently connected this row. */
3470
3655
  connectedBySubjectId?: string | null;
3471
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
+ }>;
3472
3716
  export type CodexAppsSettings = {
3473
3717
  credentialId: string | null;
3474
3718
  version: number;
@@ -3645,6 +3889,7 @@ export declare function isCodexBilledTurn(input: {
3645
3889
  }): Promise<boolean>;
3646
3890
  export type CodexAccountStatus = {
3647
3891
  id: string;
3892
+ source: Exclude<EffectiveCodexSubscriptionSource, "disabled">;
3648
3893
  chatgptAccountId: string | null;
3649
3894
  label: string | null;
3650
3895
  accountEmail: string | null;
@@ -3668,6 +3913,8 @@ export type CodexAccountStatus = {
3668
3913
  secondaryResetAt: Date | null;
3669
3914
  usageCheckedAt: Date | null;
3670
3915
  exhaustedUntil: Date | null;
3916
+ /** Typed provider-refusal provenance; null for legacy/cleared cooldowns. */
3917
+ exhaustedKind: CodexCredentialCooldownKind | null;
3671
3918
  };
3672
3919
  /**
3673
3920
  * A metadata-only scheduling candidate observed while the workspace's rotation
@@ -3675,7 +3922,7 @@ export type CodexAccountStatus = {
3675
3922
  * the selection cursor gives deterministic fairness after those holders drain.
3676
3923
  * None of these fields contains credential material.
3677
3924
  */
3678
- export type CodexLeaseAccountStatus = Omit<CodexAccountStatus, "allocatorVersion" | "allocatorUpdatedBySubjectId" | "allocatorUpdatedAt" | "resetCreditAvailableCount" | "resetCreditsCheckedAt" | "connectedBySubjectId"> & {
3925
+ export type CodexLeaseAccountStatus = Omit<CodexAccountStatus, "allocatorVersion" | "allocatorUpdatedBySubjectId" | "allocatorUpdatedAt" | "resetCreditAvailableCount" | "resetCreditsCheckedAt" | "connectedBySubjectId" | "source"> & {
3679
3926
  activeLeaseCount: number;
3680
3927
  selectionCount: number;
3681
3928
  lastSelectedAt: Date | null;
@@ -4059,6 +4306,7 @@ export type CodexCredentialLeaseQuarantine = {
4059
4306
  } | {
4060
4307
  kind: "cooldown";
4061
4308
  until: Date;
4309
+ cooldownKind: CodexCredentialCooldownKind;
4062
4310
  };
4063
4311
  /**
4064
4312
  * Quarantine the credential served by one exact live holder. The lease row is
@@ -4264,7 +4512,7 @@ export declare function completeCodexResetRedemption(db: Database, input: {
4264
4512
  }): Promise<CodexCapacityMutationResult<CodexResetRedemptionAttempt | null>>;
4265
4513
  /** The P2 usage-cache snapshot written by the refreshing usage wrapper. */
4266
4514
  /**
4267
- * 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
4268
4516
  * SPECIFIC credential row. NEVER touches credential_encrypted. RLS-scoped, guarded
4269
4517
  * by (id, workspace_id) so it can only write a row the workspace owns. Returns true
4270
4518
  * iff a row was updated (false ⇒ the credential was disconnected under us — the
@@ -4328,9 +4576,9 @@ export declare function setInitialActiveCodexCredential(db: Database, workspaceI
4328
4576
  * never race the (id, version) token-refresh CAS in recordCodexTokenRefresh / setCodexCredentialStatus.
4329
4577
  * Returns true iff a row was updated (false ⇒ the credential was disconnected under us).
4330
4578
  */
4331
- 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>;
4332
4580
  /** 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>>;
4581
+ export declare function setCodexCredentialExhaustedWithWakeTargets(db: Database, workspaceId: string, credentialId: string, until: Date | null, cooldownKind: CodexCredentialCooldownKind | null): Promise<CodexCapacityMutationResult<boolean>>;
4334
4582
  /**
4335
4583
  * P3 reactive-rotation boundedness (Finding 1b): the number of CONSECUTIVE rotated
4336
4584
  * 429-failover turns since the session last had a SUCCESSFUL turn. Counts
@@ -5528,6 +5776,25 @@ export declare function recordSkippedContextCompaction(db: Database, input: {
5528
5776
  recorded: false;
5529
5777
  reason: TurnAttemptFenceRejectReason | "request_not_pending";
5530
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>;
5531
5798
  /**
5532
5799
  * The next free WHOLE-NUMBER history position for a session: one past the
5533
5800
  * largest existing position (active or superseded), floored so the synthetic
@@ -5942,6 +6209,54 @@ export type AcquireLeaseResult = {
5942
6209
  reason: "superseded" | "capture_in_progress" | "rotation_in_progress" | "provider_recovery_in_progress";
5943
6210
  lease: LeaseSnapshot;
5944
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>;
5945
6260
  export declare class SandboxLeaseSupersededError extends Error {
5946
6261
  readonly sandboxGroupId: string;
5947
6262
  readonly leaseEpoch: number;
@@ -6648,6 +6963,8 @@ export declare function listMeterableWarmLeases(db: Database): Promise<Meterable
6648
6963
  * even after every affected sandbox lease has become cold. */
6649
6964
  export declare function listSandboxViewerForceDrainWorkspaceIds(db: Database): Promise<string[]>;
6650
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>>;
6651
6968
  export declare function countSandboxLeasesByLiveness(db: Database): Promise<Record<SandboxLeaseLiveness, number>>;
6652
6969
  export type CreditBalanceByAccount = {
6653
6970
  accountId: string;
@@ -6683,6 +7000,18 @@ export declare class SandboxWorkspaceMutationFencedError extends Error {
6683
7000
  readonly name: string;
6684
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);
6685
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
+ }
6686
7015
  export type SandboxWorkspaceMutationAdmission = {
6687
7016
  id: string;
6688
7017
  leaseId: string;
@@ -7004,7 +7333,8 @@ export declare function countActiveRetainedProcessesByOwnerState(db: Database):
7004
7333
  export declare function countExpiredDrainingSandboxLeases(db: Database): Promise<ExpiredDrainingSandboxLeaseCount[]>;
7005
7334
  /** Settle an exact retained process only after exit or definitive loss proof.
7006
7335
  * The process row, parent admission, non-TTL holder, and lease count transition
7007
- * 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
7008
7338
  * fails closed. */
7009
7339
  export declare function settleRetainedProcess(db: Database, input: {
7010
7340
  accountId: string;
@@ -8628,6 +8958,9 @@ export type InitializeSessionStartInput = {
8628
8958
  /** Trusted create-session policy. Omitted only by legacy low-level callers. */
8629
8959
  turnExecutionPolicy?: TurnExecutionPolicyV1;
8630
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;
8631
8964
  goal?: {
8632
8965
  text: string;
8633
8966
  successCriteria?: string | null;
@@ -8704,6 +9037,16 @@ export type ClaimSessionWorkForAttemptInput = {
8704
9037
  action: "reject";
8705
9038
  reason: string;
8706
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;
8707
9050
  };
8708
9051
  export type ClaimSessionWorkForAttemptResult = {
8709
9052
  action: "claimed";
@@ -9264,21 +9607,24 @@ export declare function claimPendingSessionWorkflowWakes(db: Database, limit?: n
9264
9607
  * accepted direction or an interrupted attempt awaiting writer-set proof.
9265
9608
  * Temporal accepting a signal is transport evidence, not proof that a closing
9266
9609
  * 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
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
9270
9614
  * revision because Resume commits a new one.
9271
9615
  *
9272
9616
  * 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.
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.
9276
9622
  */
9277
9623
  export type SessionWorkflowWakeDeliveryResult = {
9278
9624
  action: "acknowledged";
9279
9625
  } | {
9280
9626
  action: "pending_admission";
9281
- blocker: "pending_agent_steer" | "pending_quiescence";
9627
+ blocker: "pending_agent_steer" | "pending_prompt_turn" | "pending_quiescence";
9282
9628
  };
9283
9629
  export declare function markSessionWorkflowWakeDelivered(db: Database, input: Omit<SessionWorkflowWake, "interruptionRequested">): Promise<SessionWorkflowWakeDeliveryResult>;
9284
9630
  /** Record delivery failure; the claim already scheduled the bounded retry. */
@@ -9364,6 +9710,7 @@ export declare function childRequiresActionResolutionExists(db: Database, worksp
9364
9710
  export declare function listOutstandingSessionSystemUpdates(db: Database, workspaceId: string, sessionId: string): Promise<SessionSystemUpdate[]>;
9365
9711
  /** Internal updates atomically attached when this inference was claimed. */
9366
9712
  export declare function listSessionSystemUpdatesForTurn(db: Database, workspaceId: string, sessionId: string, turnId: string): Promise<SessionSystemUpdate[]>;
9713
+ export declare function sessionEventRawLaneEnabled(value?: string | undefined): boolean;
9367
9714
  export declare function appendSessionEvents(db: Database, workspaceId: string, sessionId: string, inputs: AppendEventInput[]): Promise<SessionEvent[]>;
9368
9715
  export type AcceptSessionApprovalDecisionResult = {
9369
9716
  action: "accepted";
@@ -9417,17 +9764,34 @@ export declare function expireSessionInteractionIntervention(db: Database, input
9417
9764
  * events remain associated with their producer in logs but are not admitted to
9418
9765
  * the current durable timeline once the turn row moved generation or terminal.
9419
9766
  */
9420
- 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<{
9421
9768
  events: SessionEvent[];
9422
9769
  accepted: boolean;
9423
9770
  canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];
9424
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;
9425
9789
  /**
9426
9790
  * Commit one exact-attempt mutation and its timeline projection together. The
9427
9791
  * mutation runs first so Codemode's operation-row lock order remains stable;
9428
9792
  * returning false leaves both the mutation and projection absent.
9429
9793
  */
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<{
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<{
9431
9795
  events: SessionEvent[];
9432
9796
  accepted: boolean;
9433
9797
  mutationApplied: boolean;
@@ -9508,7 +9872,7 @@ export declare function buildCodexTokenResolver(db: Database, settings: Settings
9508
9872
  export declare function fetchCodexUsageForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): ReturnType<typeof fetchCodexUsageForAccountCore>;
9509
9873
  export declare function fetchCodexRateLimitResetCreditsForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): ReturnType<typeof fetchCodexRateLimitResetCreditsForAccountCore>;
9510
9874
  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";
9875
+ export { withCodexTokenDeadline, type CodexAccountUsageSnapshot, type CodexAuthDeps, type CodexCredentialCooldownKind, type CodexCredentialForRun, type CodexCredentialTokens, type CodexRateLimitResetCreditsAccountResult, type CodexTokenDeadlineClock, type CodexTokenDeadlineOptions, } from "./codex-token-resolver.js";
9512
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";
9513
9877
  export { CapabilityComponentVersionConflictError, cleanupOrphanedCapabilityComponents, effectiveCapabilityOwnerSql, type CapabilityComponentOwnerIdentity, } from "./capability-components.js";
9514
9878
  export { adoptPackComponentReferences, finalizePackComponentOwnership, listPackInstallationComponents, PackComponentResolutionError, previewPackComponentRelease, recordPackInlineSkillComponent, releasePackComponents, resolvePackComponentReferences, resolvePackInlineSkillReferences, type PackInlineSkillRequirement, type StoredPackInstallationComponent, } from "./pack-components.js";