@opengeni/core 0.4.10 → 0.10.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.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Settings } from '@opengeni/config';
2
- import { ScheduledTask, Document, Permission, AccessContext, AccessGrant, LimitAction, LimitDecision, CapabilityCatalogItem, CapabilityInstallation, CapabilityCatalogResponse, CreateCapabilityCatalogItemRequest, EnableCapabilityRequest, VariableSet, Rig, RigVersion, CreateRigRequest, RigDefinitionEditPayload, RigChange, ProposeRigChangeRequest, UpdateRigRequest, CapabilityPack, SocialConnection, ScheduledTaskAgentConfig, ToolRef, ResourceRef, CreateScheduledTaskRequest, UpdateScheduledTaskRequest, ReasoningEffort, SessionMcpCredentialUpdateInput, SessionEvent, SessionTurn, GoalSpec, SessionMcpServerMetadata, Session, WorkspaceMember, SessionControlRequest, SessionControlResponse, WorkspaceInferenceControlRequest, WorkspaceInferenceControlResponse, DeleteSessionQueueItemRequest, SessionQueueMutationResponse, EditSessionQueueItemRequest, ComposerDraft, MoveSessionQueueItemRequest, SaveComposerDraftRequest, SteerSessionQueueItemRequest } from '@opengeni/contracts';
2
+ import { ScheduledTask, Document, GitHubAppApiPort, ConnectionCredentialsPort, SessionAuthorizationPort, Permission, AccessContext, AccessGrant, SessionAuthorizationActor, SessionAuthorizationTarget, SessionAuthorizationOperation, SessionAuthorizationSurface, SessionAuthorizationListScope, LimitAction, LimitDecision, TurnInitiator, TurnInitiatorContext, SessionTurnSource, CapabilityCatalogItem, CapabilityInstallation, CapabilityCatalogResponse, CreateCapabilityCatalogItemRequest, EnableCapabilityRequest, VariableSet, Rig, RigVersion, CreateRigRequest, RigDefinitionEditPayload, RigChange, ProposeRigChangeRequest, UpdateRigRequest, CapabilityPack, SocialConnection, ScheduledTaskAgentConfig, ToolRef, ResourceRef, SessionEffectiveToolPolicy, SessionToolPolicy, Session, CreateScheduledTaskRequest, UpdateScheduledTaskRequest, ReasoningEffort, SessionMcpCredentialUpdateInput, SessionEvent, SessionTurn, TurnExecutionPolicyV1, GoalSpec, SessionMcpServerMetadata, CreateSessionResponse, SessionMcpApprovalPolicy, UpdateSessionMcpApprovalPolicyResponse, WorkspaceMember, SessionControlRequest, SessionControlResponse, WorkspaceInferenceControlRequest, WorkspaceInferenceControlResponse, DeleteSessionQueueItemRequest, SessionQueueMutationResponse, EditSessionQueueItemRequest, ComposerDraft, MoveSessionQueueItemRequest, SaveComposerDraftRequest, SteerSessionQueueItemRequest } from '@opengeni/contracts';
3
3
  export { mergeToolRefs, stableJson } from '@opengeni/contracts';
4
4
  import * as _opengeni_db from '@opengeni/db';
5
- import { Database, SandboxRecord, EnabledMcpCapabilityServer, UpdateScheduledTaskInput, CreateSessionMcpServerInput, UpdateSessionMcpServerCredentialsInput } from '@opengeni/db';
5
+ import { Database, SandboxRecord, EnabledMcpCapabilityServer, UpdateScheduledTaskInput, SessionCommandActor, CreateSessionMcpServerInput, UpdateSessionMcpServerCredentialsInput } from '@opengeni/db';
6
6
  import { DocumentServices } from '@opengeni/documents';
7
7
  import { EventBus } from '@opengeni/events';
8
8
  import { Observability } from '@opengeni/observability';
@@ -136,7 +136,27 @@ type AppDependencies = {
136
136
  observability?: Observability;
137
137
  readinessChecks?: Partial<Record<"db" | "nats" | "temporal", () => Promise<void> | void>>;
138
138
  githubStateSecret?: string;
139
+ /**
140
+ * Optional host-provided GitHub App API seam. Embedded hosts can authorize
141
+ * users, inspect installations, and list repositories with their own GitHub
142
+ * App credentials; standalone deployments fall back to @opengeni/github.
143
+ */
144
+ githubAppApi?: GitHubAppApiPort;
145
+ /**
146
+ * Optional host-owned connection credential seam. API-side consumers use
147
+ * the MCP leg for Toolspace/Code Mode; worker consumers bind the same port
148
+ * for model MCP, Git, and sandbox-secret resolution.
149
+ */
150
+ connectionCredentials?: ConnectionCredentialsPort | null;
151
+ /**
152
+ * Optional embedding-host session ACL. Unset preserves standalone workspace
153
+ * authorization; once bound, every session-addressed surface fails closed on
154
+ * an unavailable or invalid host decision.
155
+ */
156
+ sessionAuthorization?: SessionAuthorizationPort | null;
139
157
  managedAuth?: ManagedAuth | null;
158
+ /** Injectable Codex HTTP transport for deterministic API/provider tests. */
159
+ codexFetch?: typeof fetch;
140
160
  sandboxClient?: ApiSandboxClient;
141
161
  /**
142
162
  * Resume a box by id from a serialized resume_state envelope (the lease's
@@ -162,7 +182,7 @@ type ApiRouteDeps = AppDependencies & {
162
182
  * the canonical admission path without constructing unrelated HTTP, document,
163
183
  * or sandbox services. The public API still passes its `ApiRouteDeps` superset.
164
184
  */
165
- type AcceptSessionUserMessageDependencies = Pick<AppDependencies, "settings" | "db" | "bus"> & {
185
+ type AcceptSessionUserMessageDependencies = Pick<AppDependencies, "settings" | "db" | "bus" | "sessionAuthorization"> & {
166
186
  workflowClient: Pick<SessionWorkflowClient, "wakeSessionWorkflow">;
167
187
  objectStorage: ObjectStorageDependency;
168
188
  };
@@ -288,7 +308,7 @@ type RunOnResult = {
288
308
  };
289
309
  /**
290
310
  * Run a ONE-OFF op against a SPECIFIC target WITHOUT changing the active pointer
291
- * (the dossier `run_on`). Only selfhosted targets are routable as a one-off here
311
+ * (the design `run_on`). Only selfhosted targets are routable as a one-off here
292
312
  * (a Modal target is the session's group box, reached via the normal Channel-A /
293
313
  * turn path — `run_on` is for reaching a NON-active enrolled machine without
294
314
  * swapping). The op is fenced under the target's enrollment, addressed to its
@@ -315,7 +335,7 @@ type ProvisionResult = {
315
335
  * cannot click the loud whole-machine consent itself).
316
336
  * - modal → create a first-class named modal `sandboxes` record (a swap target).
317
337
  * NOTE: the Modal BOX is materialized lazily when first swapped-to (Modal
318
- * lifecycle is owned by the lease — unchanged per dossier §21).
338
+ * lifecycle is owned by the lease — unchanged per).
319
339
  */
320
340
  declare function provisionSandbox(services: FleetServices, ctx: FleetContext, input: {
321
341
  kind: "selfhosted" | "modal";
@@ -340,7 +360,7 @@ declare function relayConfigFromSettings(settings: Settings): SelfhostedRelayCon
340
360
  * the CONSUMER uses (`relayConfigFromSettings`) so producer + consumer always agree
341
361
  * on `/stream` — even when the configured URL omits it. An unconfigured relay maps to
342
362
  * `""` (graceful degrade: the agent reports no-relay rather than dialing a synthetic
343
- * host). Fixes preview AND managed prod with no agent rebuild (dossier §V5/§V6). */
363
+ * host). Fixes preview AND managed prod with no agent rebuild. */
344
364
  declare function relayDialBaseFromSettings(settings: Settings): string;
345
365
  /** Whether the routing proxy should wrap the Channel-A box: gated by the
346
366
  * selfhosted flag (the active pointer + swap are only meaningful then). */
@@ -367,6 +387,41 @@ declare function requireAccessGrant(c: Context, deps: AccessDeps, workspaceId: s
367
387
  declare function requirePermission(grant: AccessGrant, permission: Permission): void;
368
388
  declare function hasPermission(permissions: Permission[], permission: Permission): boolean;
369
389
 
390
+ type SessionAuthorizationDependencies = Pick<AppDependencies, "db" | "sessionAuthorization">;
391
+ /** Maximum time an omitted host hint leaves a live session stream unchecked. */
392
+ declare const SESSION_AUTHORIZATION_DEFAULT_REAUTHORIZE_MS = 15000;
393
+ declare class SessionAuthorizationDeniedError extends Error {
394
+ readonly reason: "not_found" | "forbidden" | "revoked" | "caller_stale";
395
+ readonly code = "SESSION_NOT_FOUND_OR_DENIED";
396
+ constructor(reason: "not_found" | "forbidden" | "revoked" | "caller_stale");
397
+ }
398
+ declare class SessionAuthorizationUnavailableError extends Error {
399
+ readonly code = "SESSION_AUTHORIZATION_UNAVAILABLE";
400
+ constructor(options?: ErrorOptions);
401
+ }
402
+ type ResolvedSessionAuthorization = {
403
+ actor: SessionAuthorizationActor;
404
+ target: SessionAuthorizationTarget;
405
+ relatedSessionAccess: "target" | "root";
406
+ reauthorizeAfterMs: number | null;
407
+ };
408
+ /**
409
+ * Resolve and enforce the host ACL for one session. The target and agent actor
410
+ * are reconstructed from workspace-scoped durable state. A request can supply
411
+ * an immediate target id and signed attempt claims, but can never nominate a
412
+ * lineage root or frozen initiator.
413
+ *
414
+ * Returns null when no host port is bound so standalone behavior stays byte-
415
+ * for-byte unchanged and pays no additional lineage lookup.
416
+ */
417
+ declare function requireSessionAuthorization(deps: SessionAuthorizationDependencies, grant: AccessGrant, input: {
418
+ sessionId: string;
419
+ operation: SessionAuthorizationOperation;
420
+ surface: SessionAuthorizationSurface;
421
+ }): Promise<ResolvedSessionAuthorization | null>;
422
+ /** Resolve the host's complete current list scope for an in-database query. */
423
+ declare function requireSessionAuthorizationListScope(deps: SessionAuthorizationDependencies, grant: AccessGrant, surface: SessionAuthorizationSurface): Promise<SessionAuthorizationListScope | null>;
424
+
370
425
  type LimitDependencies = Pick<ApiRouteDeps, "db" | "settings">;
371
426
  type LimitCheckInput = {
372
427
  accountId: string;
@@ -386,6 +441,12 @@ declare function recordWorkspaceUsage(deps: LimitDependencies, input: {
386
441
  unit: string;
387
442
  sourceResourceType: string;
388
443
  sourceResourceId: string;
444
+ sessionId?: string | null;
445
+ turnId?: string | null;
446
+ turnAttemptId?: string | null;
447
+ initiator?: TurnInitiator | null;
448
+ initiatorContext?: TurnInitiatorContext;
449
+ origin?: SessionTurnSource | null;
389
450
  idempotencyKey: string;
390
451
  }): Promise<void>;
391
452
 
@@ -554,16 +615,57 @@ declare function buildMarketingDailyAnalysisAgentConfig(input: {
554
615
  promptInstructions?: string;
555
616
  }): ScheduledTaskAgentConfig;
556
617
 
557
- declare function validateToolRefs(tools: ToolRef[], settings: Settings): ToolRef[];
618
+ declare function validateToolRefs(tools: ToolRef[], settings: McpSettings): ToolRef[];
558
619
  type McpSettings = Pick<Settings, "mcpServers">;
559
620
  declare function enabledCapabilityMcpToolRefs(settings: McpSettings, runtimeSettings: McpSettings): ToolRef[];
560
621
  declare function withDefaultEnabledCapabilityMcpTools(tools: ToolRef[], settings: McpSettings, runtimeSettings: McpSettings): ToolRef[];
622
+ /** Drop stored refs that are no longer present in the current runtime registry. */
623
+ declare function availableToolRefs(tools: ToolRef[], settings: McpSettings): ToolRef[];
624
+ /** A child or fixed-policy follow-up may narrow its allow-list, never widen it. */
625
+ declare function assertToolRefsSubset(requested: ToolRef[], allowed: ToolRef[], message?: string): void;
626
+ /** Validate runtime availability and then enforce the durable policy fence. */
627
+ declare function validateToolRefsForSessionPolicy(input: {
628
+ requested: ToolRef[];
629
+ settings: McpSettings;
630
+ allowedTools: ToolRef[];
631
+ message: string;
632
+ }): ToolRef[];
561
633
  declare function normalizeResources(resources: ResourceRef[]): ResourceRef[];
562
634
  declare function mergeResourceRefs(existing: ResourceRef[], additions: ResourceRef[]): ResourceRef[];
635
+ declare function validateGitHubRepositorySelectionShapes(resources: ResourceRef[]): number[];
636
+ /** @deprecated Use validateGitHubRepositorySelectionShapes for multi-installation sessions. */
563
637
  declare function validateGitHubRepositorySelectionShape(resources: ResourceRef[]): number | null;
564
638
  declare function validateGitHubRepositorySelection(db: Database, workspaceId: string, resources: ResourceRef[]): Promise<void>;
565
639
  declare function validateFileResources(db: Database, workspaceId: string, resources: ResourceRef[]): Promise<void>;
566
640
 
641
+ type ResolvedSessionToolPolicy = {
642
+ toolRefs: ToolRef[];
643
+ effectivePolicy: SessionEffectiveToolPolicy;
644
+ };
645
+ type SessionToolPolicyInput = {
646
+ toolPolicy?: SessionToolPolicy | null;
647
+ sessionTools: ToolRef[];
648
+ turnTools?: ToolRef[];
649
+ /** Undefined preserves the legacy merge path for pre-provenance callers. */
650
+ turnToolsProvided?: boolean;
651
+ availableMcpServerIds: Iterable<string>;
652
+ /** Current omitted-tools defaults, intentionally narrower than all servers. */
653
+ defaultMcpServerIds?: Iterable<string>;
654
+ };
655
+ /**
656
+ * Resolve the same ID-only policy used by API projections and worker turns.
657
+ * This function never receives endpoint URLs, credentials, schemas, or live
658
+ * probe results. `availableMcpServerIds` is the resolved runtime registry;
659
+ * `defaultMcpServerIds` is the capability-only omitted-tools set.
660
+ */
661
+ declare function resolveSessionToolPolicy(input: SessionToolPolicyInput): ResolvedSessionToolPolicy;
662
+ /** Current full runtime registry IDs, including configured static servers. */
663
+ declare function workspaceSessionToolPolicyServerIds(db: Database, workspaceId: string, settings: Settings): Promise<string[]>;
664
+ /** Current omitted-tools defaults; this preserves capability-first behavior. */
665
+ declare function workspaceSessionToolPolicyDefaultServerIds(db: Database, workspaceId: string, settings: Settings): Promise<string[]>;
666
+ /** Add a bounded, secret-safe effective projection to a session response. */
667
+ declare function sessionWithEffectiveToolPolicy(session: Session, workspaceServerIds: Iterable<string>, workspaceDefaultServerIds?: Iterable<string>): Session;
668
+
567
669
  /**
568
670
  * Whether a raw scheduled-task payload explicitly set agentConfig.tools.
569
671
  * Zod's `.default([])` erases the distinction between "absent" and
@@ -634,19 +736,28 @@ declare function manualScheduledTaskTriggerUsageKey(workspaceId: string, taskId:
634
736
 
635
737
  declare function settingsWithSessionMcpServerMetadata(settings: Settings, servers: SessionMcpServerMetadata[]): Settings;
636
738
  declare function createAndStartSession(input: {
739
+ requestedSessionId?: string;
637
740
  db: Database;
638
741
  bus: EventBus;
639
742
  workflowClient: SessionWorkflowClient;
640
743
  accountId: string;
641
744
  workspaceId: string;
642
745
  initialMessage: string;
746
+ turnInstructions?: string | null;
643
747
  resources: ResourceRef[];
644
748
  tools: ToolRef[];
749
+ toolPolicy?: SessionToolPolicy;
645
750
  clientEventId?: string;
646
751
  model: string;
647
752
  reasoningEffort: Settings["openaiReasoningEffort"];
753
+ turnExecutionPolicy: TurnExecutionPolicyV1;
648
754
  sandboxBackend: Settings["sandboxBackend"];
649
755
  metadata: Record<string, unknown>;
756
+ createdBy?: TurnInitiator;
757
+ createdByContext?: TurnInitiatorContext;
758
+ createdByActor?: Extract<SessionCommandActor, {
759
+ type: "agent_attempt";
760
+ }> | null;
650
761
  variableSet?: {
651
762
  id: string;
652
763
  name: string;
@@ -667,131 +778,7 @@ declare function createAndStartSession(input: {
667
778
  settings: Settings;
668
779
  workingDir?: string | null;
669
780
  } | null;
670
- }): Promise<{
671
- id: string;
672
- workspaceId: string;
673
- accountId: string;
674
- status: "queued" | "running" | "idle" | "requires_action" | "recovering" | "waiting_capacity" | "failed" | "cancelled";
675
- initialMessage: string;
676
- title: string | null;
677
- titleSource: "user" | "agent" | null;
678
- instructions: string | null;
679
- resources: ({
680
- kind: "repository";
681
- uri: string;
682
- ref: string;
683
- mountPath?: string | undefined;
684
- subpath?: string | undefined;
685
- provider?: "github" | "gitlab" | "azure_devops" | undefined;
686
- repositoryId?: string | number | undefined;
687
- installationId?: string | number | undefined;
688
- projectId?: string | number | undefined;
689
- connectionId?: string | undefined;
690
- githubInstallationId?: number | undefined;
691
- githubRepositoryId?: number | undefined;
692
- } | {
693
- kind: "file";
694
- fileId: string;
695
- mountPath?: string | undefined;
696
- })[];
697
- tools: {
698
- kind: "mcp";
699
- id: string;
700
- optional?: boolean | undefined;
701
- }[];
702
- metadata: Record<string, unknown>;
703
- model: string;
704
- sandboxBackend: "docker" | "modal" | "local" | "none" | "daytona" | "runloop" | "e2b" | "blaxel" | "cloudflare" | "vercel" | "selfhosted";
705
- sandboxOs: "linux" | "macos" | "windows";
706
- sandboxGroupId: string;
707
- activeSandboxId: string | null;
708
- activeEpoch: number;
709
- variableSetId: string | null;
710
- environmentId: string | null;
711
- rigId: string | null;
712
- rigVersionId: string | null;
713
- firstPartyMcpPermissions: ("account:read" | "account:admin" | "members:manage" | "workspace:create" | "billing:read" | "billing:manage" | "workspace:read" | "workspace:admin" | "sessions:create" | "sessions:read" | "sessions:control" | "stream:view" | "stream:control" | "stream:acknowledge" | "files:upload" | "files:read" | "files:write" | "terminal:attach" | "documents:manage" | "documents:search" | "scheduled_tasks:manage" | "scheduled_tasks:run" | "github:manage" | "github:use" | "api_keys:manage" | "connections:read" | "connections:write" | "environments:manage" | "environments:use" | "variable-sets:manage" | "variable-sets:use" | "mcp_servers:attach" | "toolspace:call" | "goals:manage" | "enrollments:read" | "enrollments:manage" | "rigs:use" | "rigs:manage")[] | null;
714
- mcpServers: {
715
- id: string;
716
- name: string | null;
717
- url: string;
718
- headerNames: string[];
719
- credentialVersion: number;
720
- }[];
721
- parentSessionId: string | null;
722
- createIdempotencyKey: string | null;
723
- temporalWorkflowId: string | null;
724
- activeTurnId: string | null;
725
- lastInputTokens: number | null;
726
- queueVersion: number;
727
- queueHeadPosition: number;
728
- queueTailPosition: number;
729
- effectiveControl: {
730
- state: "active" | "paused";
731
- controlVersion: number;
732
- controlEtag: string;
733
- directState: "active" | "paused";
734
- primaryBlocker: {
735
- kind: "workspace" | "session";
736
- displayName: string;
737
- actor: string | null;
738
- reason: string | null;
739
- changedAt: string | null;
740
- revision: number;
741
- sessionId?: string | undefined;
742
- } | null;
743
- additionalBlockerCount: number;
744
- blockers: {
745
- kind: "workspace" | "session";
746
- displayName: string;
747
- actor: string | null;
748
- reason: string | null;
749
- changedAt: string | null;
750
- revision: number;
751
- sessionId?: string | undefined;
752
- }[];
753
- resumeOptions: {
754
- scope: "workspace" | "session" | "selected";
755
- selectedStateAfter: "active" | "paused";
756
- impactCopy: string;
757
- targetId?: string | undefined;
758
- remainingPrimaryBlocker?: {
759
- kind: "workspace" | "session";
760
- displayName: string;
761
- actor: string | null;
762
- reason: string | null;
763
- changedAt: string | null;
764
- revision: number;
765
- sessionId?: string | undefined;
766
- } | undefined;
767
- }[];
768
- override: {
769
- rootSessionId: string;
770
- revision: number;
771
- } | null;
772
- settlement: {
773
- state: "stopping";
774
- attemptCount: number;
775
- } | null;
776
- };
777
- lastSequence: number;
778
- codexPinnedCredentialId: string | null;
779
- codexLastCredentialId: string | null;
780
- pinned: boolean;
781
- pinnedAt: string | null;
782
- pinVersion: number;
783
- createdAt: string;
784
- updatedAt: string;
785
- treeStats?: {
786
- directChildren: number;
787
- totalDescendants: number;
788
- runningDescendants: number;
789
- queuedDescendants: number;
790
- attentionDescendants: number;
791
- pausedDescendants: number;
792
- failedDescendants: number;
793
- } | undefined;
794
- }>;
781
+ }): Promise<CreateSessionResponse>;
795
782
  declare function workflowIdForSession(sessionId: string): string;
796
783
  /**
797
784
  * Reject an explicit model that the host does not expose. The set of usable
@@ -809,6 +796,7 @@ declare function workflowIdForSession(sessionId: string): string;
809
796
  * later) and the MCP surfaces that share them validate identically and cannot
810
797
  * drift.
811
798
  */
799
+ declare function canonicalConfiguredModel(settings: Settings, model: string | null | undefined): string | null | undefined;
812
800
  declare function assertConfiguredModel(settings: Settings, model: string | null | undefined): void;
813
801
  /**
814
802
  * Reject a model the WORKSPACE's model policy blocks, at the same choke points
@@ -840,8 +828,10 @@ declare function postUserMessageTurn(input: {
840
828
  workspaceId: string;
841
829
  sessionId: string;
842
830
  text: string;
831
+ turnInstructions?: string | null;
843
832
  resources: ResourceRef[];
844
833
  tools: ToolRef[];
834
+ toolsProvided: boolean;
845
835
  model?: string | null;
846
836
  reasoningEffort?: Settings["openaiReasoningEffort"] | null;
847
837
  clientEventId?: string;
@@ -849,8 +839,12 @@ declare function postUserMessageTurn(input: {
849
839
  delivery?: "send" | "steer";
850
840
  origin?: "human" | "operator";
851
841
  actor?: string;
842
+ actorLabel?: string;
843
+ commandActor?: SessionCommandActor;
852
844
  controlEtag?: string | null;
853
845
  expectedDraftRevision?: number | null;
846
+ reasoningEffortFallback?: Settings["openaiReasoningEffort"];
847
+ turnExecutionPolicy: TurnExecutionPolicyV1;
854
848
  }): Promise<{
855
849
  accepted: SessionEvent;
856
850
  turn: SessionTurn;
@@ -859,19 +853,23 @@ declare function postUserMessageTurn(input: {
859
853
  * Full create-session flow shared by `POST /sessions` and the first-party MCP
860
854
  * `session_create` tool: payload validation, resource/tool/variableSet
861
855
  * checks, usage limits, session start, and usage recording. `rawPayload` is
862
- * the unparsed request body so absent-vs-empty `tools` keeps its meaning
863
- * (absent applies the workspace's default capability MCP tools).
856
+ * the unparsed request body so absent-vs-empty execution-context fields keep
857
+ * their meaning: a child inherits omitted resources/tools/mcpServers from its
858
+ * trusted immediate parent, while explicit arrays (including []) win. A
859
+ * top-level create with omitted tools applies workspace-default capability MCPs.
864
860
  */
865
861
  declare function createSessionForRequest(deps: ApiRouteDeps, grant: AccessGrant, workspaceId: string, rawPayload: unknown): Promise<Session>;
866
862
  /**
867
863
  * Full accept-user-message flow shared by the `user.message` branch of
868
864
  * `POST /sessions/:id/events` and the first-party MCP `session_send_message`
869
865
  * tool: resource/tool validation, usage limits, the locked append + turn
870
- * enqueue, and usage recording. `toolsProvided: false` applies the
871
- * workspace's default capability MCP tools, matching an absent `tools` key.
866
+ * enqueue, and usage recording. `toolsProvided: false` durably preserves an
867
+ * absent `tools` key so execution inherits the session policy; an explicit
868
+ * empty array is a deliberate per-turn narrowing.
872
869
  */
873
870
  declare function acceptSessionUserMessage(deps: AcceptSessionUserMessageDependencies, grant: AccessGrant, workspaceId: string, sessionId: string, input: {
874
871
  text: string;
872
+ turnInstructions?: string | null;
875
873
  resources?: ResourceRef[];
876
874
  tools?: ToolRef[];
877
875
  toolsProvided: boolean;
@@ -899,11 +897,24 @@ declare function acceptSessionUserMessage(deps: AcceptSessionUserMessageDependen
899
897
  declare function updateSessionTitle(deps: {
900
898
  db: Database;
901
899
  bus: EventBus;
902
- }, workspaceId: string, sessionId: string, title: string, source: "user" | "agent"): Promise<{
900
+ sessionAuthorization?: SessionAuthorizationPort | null;
901
+ }, grant: AccessGrant, sessionId: string, title: string, source: "user" | "agent"): Promise<{
903
902
  updated: boolean;
904
903
  title: string | null;
904
+ relatedSessionAccess: "target" | "root";
905
905
  }>;
906
- declare function readSessionLineage(db: Database, workspaceId: string, sessionId: string): Promise<_opengeni_db.SessionLineage>;
906
+ /**
907
+ * Update one existing session MCP server's approval policy. The database
908
+ * serializes this write with attempt claim under the session lock: an already
909
+ * claimed attempt retains its immutable snapshot, while the next claim captures
910
+ * this value. No attempt is cancelled, restarted, or reinterpreted.
911
+ */
912
+ declare function updateSessionMcpApprovalPolicy(deps: {
913
+ db: Database;
914
+ bus: EventBus;
915
+ sessionAuthorization?: SessionAuthorizationPort | null;
916
+ }, grant: AccessGrant, sessionId: string, serverId: string, requireApproval: SessionMcpApprovalPolicy): Promise<UpdateSessionMcpApprovalPolicyResponse>;
917
+ declare function readSessionLineage(deps: Pick<ApiRouteDeps, "db" | "sessionAuthorization">, grant: AccessGrant, sessionId: string): Promise<_opengeni_db.SessionLineage>;
907
918
 
908
919
  /** A member can manage other members (directly or via the admin wildcard). */
909
920
  declare function memberCanAdminister(member: Pick<WorkspaceMember, "permissions">): boolean;
@@ -948,15 +959,21 @@ type HumanSessionCommandContext = {
948
959
  type AgentSessionCommandContext = {
949
960
  accountId: string;
950
961
  workspaceId: string;
962
+ subjectId: string;
951
963
  callerSessionId: string;
952
964
  callerTurnId: string;
953
965
  callerAttemptId: string;
954
966
  callerExecutionGeneration: number;
955
967
  };
968
+ type SessionAuthorizationCommandDeps = {
969
+ db: Database;
970
+ sessionAuthorization?: SessionAuthorizationPort | null;
971
+ };
956
972
  declare function sendAgentSessionMessage(deps: {
957
973
  db: Database;
958
974
  bus: EventBus;
959
975
  workflowClient: Pick<SessionWorkflowClient, "wakeSessionWorkflow">;
976
+ sessionAuthorization?: SessionAuthorizationPort | null;
960
977
  }, context: AgentSessionCommandContext, input: {
961
978
  targetSessionId: string;
962
979
  text: string;
@@ -966,6 +983,7 @@ declare function steerAgentSession(deps: {
966
983
  db: Database;
967
984
  bus: EventBus;
968
985
  workflowClient: Pick<SessionWorkflowClient, "wakeSessionWorkflow">;
986
+ sessionAuthorization?: SessionAuthorizationPort | null;
969
987
  }, context: AgentSessionCommandContext, input: {
970
988
  targetSessionId: string;
971
989
  instruction: string;
@@ -975,6 +993,7 @@ declare function controlAgentSessionWorkstream(deps: {
975
993
  db: Database;
976
994
  bus: EventBus;
977
995
  workflowClient: Pick<SessionWorkflowClient, "requestSessionWorkflowWakeDispatch">;
996
+ sessionAuthorization?: SessionAuthorizationPort | null;
978
997
  }, context: AgentSessionCommandContext, input: {
979
998
  targetSessionId: string;
980
999
  action: "pause" | "resume";
@@ -984,30 +1003,35 @@ declare function controlAgentSessionWorkstream(deps: {
984
1003
  declare function moveHumanQueuePrompt(deps: {
985
1004
  db: Database;
986
1005
  bus: EventBus;
1006
+ sessionAuthorization?: SessionAuthorizationPort | null;
987
1007
  }, context: HumanSessionCommandContext, turnId: string, input: MoveSessionQueueItemRequest): Promise<SessionQueueMutationResponse>;
988
1008
  declare function deleteHumanQueuePrompt(deps: {
989
1009
  db: Database;
990
1010
  bus: EventBus;
1011
+ sessionAuthorization?: SessionAuthorizationPort | null;
991
1012
  }, context: HumanSessionCommandContext, turnId: string, input: DeleteSessionQueueItemRequest): Promise<SessionQueueMutationResponse>;
992
1013
  declare function editHumanQueuePrompt(deps: {
993
1014
  db: Database;
994
1015
  bus: EventBus;
1016
+ sessionAuthorization?: SessionAuthorizationPort | null;
995
1017
  }, context: HumanSessionCommandContext, turnId: string, input: EditSessionQueueItemRequest): Promise<SessionQueueMutationResponse>;
996
1018
  declare function steerHumanQueuePrompt(deps: {
997
1019
  db: Database;
998
1020
  bus: EventBus;
1021
+ sessionAuthorization?: SessionAuthorizationPort | null;
999
1022
  }, context: HumanSessionCommandContext, turnId: string, input: SteerSessionQueueItemRequest): Promise<SessionQueueMutationResponse>;
1000
1023
  declare function controlHumanSessionWorkstream(deps: {
1001
1024
  db: Database;
1002
1025
  bus: EventBus;
1003
1026
  workflowClient: Pick<SessionWorkflowClient, "requestSessionWorkflowWakeDispatch">;
1027
+ sessionAuthorization?: SessionAuthorizationPort | null;
1004
1028
  }, context: HumanSessionCommandContext, input: SessionControlRequest): Promise<SessionControlResponse>;
1005
1029
  declare function controlHumanWorkspace(deps: {
1006
1030
  db: Database;
1007
1031
  bus: EventBus;
1008
1032
  workflowClient: Pick<SessionWorkflowClient, "requestSessionWorkflowWakeDispatch">;
1009
1033
  }, context: Omit<HumanSessionCommandContext, "sessionId">, input: WorkspaceInferenceControlRequest): Promise<WorkspaceInferenceControlResponse>;
1010
- declare function getHumanComposerDraft(db: Database, context: HumanSessionCommandContext): Promise<ComposerDraft>;
1011
- declare function saveHumanComposerDraft(db: Database, context: HumanSessionCommandContext, input: SaveComposerDraftRequest): Promise<ComposerDraft>;
1034
+ declare function getHumanComposerDraft(deps: SessionAuthorizationCommandDeps, context: HumanSessionCommandContext): Promise<ComposerDraft>;
1035
+ declare function saveHumanComposerDraft(deps: SessionAuthorizationCommandDeps, context: HumanSessionCommandContext, input: SaveComposerDraftRequest): Promise<ComposerDraft>;
1012
1036
 
1013
- export { type AcceptSessionUserMessageDependencies, type AccessDeps, type AgentSessionCommandContext, type ApiRouteDeps, type ApiSandboxClient, type ApiSandboxSession, type AppDependencies, type ChannelARoutingServices, type DocumentIndexClient, type FleetContext, type FleetListResult, type FleetLiveness, type FleetSandboxEntry, type FleetServices, type FleetSwapResult, type HumanSessionCommandContext, type LimitCheckInput, type LimitDependencies, MARKETING_SOCIAL_PACK_ID, MAX_CHECKS_PER_RIG, MAX_CREDENTIAL_HOOKS_PER_RIG, MAX_DEFAULT_VARIABLE_SETS_PER_RIG, MAX_ENVIRONMENTS_PER_WORKSPACE, MAX_RIGS_PER_WORKSPACE, MAX_VARIABLES_PER_ENVIRONMENT, type ManagedAuth, type McpCapabilityProbe, type McpCapabilityProbeInput, type McpCapabilityProbeResult, type ObjectStorageDependency, type ProvisionResult, type ResumeBoxByIdInput, type ResumedSandboxSession, type RigServices, type RigVerificationClassification, type RunOnOp, type RunOnResult, SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS, SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID, SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE, type SessionWorkflowClient, acceptSessionUserMessage, activateRigVersionForApi, appendRigSetupCommand, applyCapabilityEnablement, assertAllowedEnvironmentVariableName, assertAllowedVariableSetVariableName, assertConfiguredModel, assertPackSandboxImageCompatible, assertWorkspaceDeletable, assertWorkspaceMemberRemovable, assertWorkspaceModelPolicyAllows, buildCapabilityCatalog, buildFleetContextForSession, buildMarketingDailyAnalysisAgentConfig, checkLimit, classifyRigVerificationOutcome, controlAgentSessionWorkstream, controlHumanSessionWorkstream, controlHumanWorkspace, createAndStartSession, createCatalogItem, createRigForApi, createRigVersionForApi, createSessionForRequest, createValidatedScheduledTask, deleteHumanQueuePrompt, deleteRigForApi, disableCapability, discoverMcpRegistryCapabilities, editHumanQueuePrompt, enableCapability, enabledCapabilityMcpToolRefs, getCapabilityPack, getHumanComposerDraft, hasPermission, isBuiltInCapabilityPack, isUserMember, listCapabilityPacks, listFleet, listRigChangesForApi, listRigVersionsForApi, listWorkspaceCapabilityPacks, manualScheduledTaskTriggerUsageKey, manualScheduledTaskTriggerWorkflowId, memberCanAdminister, mergeResourceRefs, moveHumanQueuePrompt, normalizeResources, officialMcpRegistryUrl, postUserMessageTurn, promoteSetupAppendChange, promoteVerifiedDefinitionEditChangeForApi, proposeRigChangeForApi, provisionSandbox, readSessionLineage, reasoningEffortForSession, recordRigAuditEvent, recordVariableSetAuditEvent, recordWorkspaceUsage, relayConfigFromSettings, relayDialBaseFromSettings, requireAccessContext, requireAccessGrant, requireEnvironmentEncryption, requireLimit, requirePermission, requireQueuedTurnForApi, requireRigChangeForApi, requireRigForApi, requireScheduledTaskForApi, requireVariableSetEncryption, requireVariableSetForApi, resolveCapabilityPack, resolveMemberSubjectId, restoreScheduledTask, rigActorForGrant, routingEnabled, runOnSandbox, saveHumanComposerDraft, scheduledTaskTemporalScheduleId, scheduledTaskToolsProvided, scheduledTaskTriggerToken, sendAgentSessionMessage, settingsWithEnabledCapabilityMcpServers, settingsWithMcpCapabilityServers, settingsWithSessionMcpServerMetadata, steerAgentSession, steerHumanQueuePrompt, swapActiveSandbox, syncCreatedScheduledTask, syncUpdatedScheduledTask, updateRigForApi, updateSessionTitle, validateFileResources, validateGitHubRepositorySelection, validateGitHubRepositorySelectionShape, validateMcpCapabilityConnection, validateToolRefs, validateVariableSetAttachment, validatedScheduledTaskUpdate, withDefaultEnabledCapabilityMcpTools, workflowIdForSession, wrapChannelABoxWithRouting };
1037
+ export { type AcceptSessionUserMessageDependencies, type AccessDeps, type AgentSessionCommandContext, type ApiRouteDeps, type ApiSandboxClient, type ApiSandboxSession, type AppDependencies, type ChannelARoutingServices, type DocumentIndexClient, type FleetContext, type FleetListResult, type FleetLiveness, type FleetSandboxEntry, type FleetServices, type FleetSwapResult, type HumanSessionCommandContext, type LimitCheckInput, type LimitDependencies, MARKETING_SOCIAL_PACK_ID, MAX_CHECKS_PER_RIG, MAX_CREDENTIAL_HOOKS_PER_RIG, MAX_DEFAULT_VARIABLE_SETS_PER_RIG, MAX_ENVIRONMENTS_PER_WORKSPACE, MAX_RIGS_PER_WORKSPACE, MAX_VARIABLES_PER_ENVIRONMENT, type ManagedAuth, type McpCapabilityProbe, type McpCapabilityProbeInput, type McpCapabilityProbeResult, type ObjectStorageDependency, type ProvisionResult, type ResolvedSessionAuthorization, type ResolvedSessionToolPolicy, type ResumeBoxByIdInput, type ResumedSandboxSession, type RigServices, type RigVerificationClassification, type RunOnOp, type RunOnResult, SESSION_AUTHORIZATION_DEFAULT_REAUTHORIZE_MS, SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS, SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID, SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE, SessionAuthorizationDeniedError, type SessionAuthorizationDependencies, SessionAuthorizationUnavailableError, type SessionToolPolicyInput, type SessionWorkflowClient, acceptSessionUserMessage, activateRigVersionForApi, appendRigSetupCommand, applyCapabilityEnablement, assertAllowedEnvironmentVariableName, assertAllowedVariableSetVariableName, assertConfiguredModel, assertPackSandboxImageCompatible, assertToolRefsSubset, assertWorkspaceDeletable, assertWorkspaceMemberRemovable, assertWorkspaceModelPolicyAllows, availableToolRefs, buildCapabilityCatalog, buildFleetContextForSession, buildMarketingDailyAnalysisAgentConfig, canonicalConfiguredModel, checkLimit, classifyRigVerificationOutcome, controlAgentSessionWorkstream, controlHumanSessionWorkstream, controlHumanWorkspace, createAndStartSession, createCatalogItem, createRigForApi, createRigVersionForApi, createSessionForRequest, createValidatedScheduledTask, deleteHumanQueuePrompt, deleteRigForApi, disableCapability, discoverMcpRegistryCapabilities, editHumanQueuePrompt, enableCapability, enabledCapabilityMcpToolRefs, getCapabilityPack, getHumanComposerDraft, hasPermission, isBuiltInCapabilityPack, isUserMember, listCapabilityPacks, listFleet, listRigChangesForApi, listRigVersionsForApi, listWorkspaceCapabilityPacks, manualScheduledTaskTriggerUsageKey, manualScheduledTaskTriggerWorkflowId, memberCanAdminister, mergeResourceRefs, moveHumanQueuePrompt, normalizeResources, officialMcpRegistryUrl, postUserMessageTurn, promoteSetupAppendChange, promoteVerifiedDefinitionEditChangeForApi, proposeRigChangeForApi, provisionSandbox, readSessionLineage, reasoningEffortForSession, recordRigAuditEvent, recordVariableSetAuditEvent, recordWorkspaceUsage, relayConfigFromSettings, relayDialBaseFromSettings, requireAccessContext, requireAccessGrant, requireEnvironmentEncryption, requireLimit, requirePermission, requireQueuedTurnForApi, requireRigChangeForApi, requireRigForApi, requireScheduledTaskForApi, requireSessionAuthorization, requireSessionAuthorizationListScope, requireVariableSetEncryption, requireVariableSetForApi, resolveCapabilityPack, resolveMemberSubjectId, resolveSessionToolPolicy, restoreScheduledTask, rigActorForGrant, routingEnabled, runOnSandbox, saveHumanComposerDraft, scheduledTaskTemporalScheduleId, scheduledTaskToolsProvided, scheduledTaskTriggerToken, sendAgentSessionMessage, sessionWithEffectiveToolPolicy, settingsWithEnabledCapabilityMcpServers, settingsWithMcpCapabilityServers, settingsWithSessionMcpServerMetadata, steerAgentSession, steerHumanQueuePrompt, swapActiveSandbox, syncCreatedScheduledTask, syncUpdatedScheduledTask, updateRigForApi, updateSessionMcpApprovalPolicy, updateSessionTitle, validateFileResources, validateGitHubRepositorySelection, validateGitHubRepositorySelectionShape, validateGitHubRepositorySelectionShapes, validateMcpCapabilityConnection, validateToolRefs, validateToolRefsForSessionPolicy, validateVariableSetAttachment, validatedScheduledTaskUpdate, withDefaultEnabledCapabilityMcpTools, workflowIdForSession, workspaceSessionToolPolicyDefaultServerIds, workspaceSessionToolPolicyServerIds, wrapChannelABoxWithRouting };