@opengeni/db 0.14.3 → 0.17.1

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 (67) hide show
  1. package/dist/{chunk-Y5WZZVQK.js → chunk-SK7YYHBI.js} +5 -2
  2. package/dist/chunk-SK7YYHBI.js.map +1 -0
  3. package/dist/{chunk-ELMUCYZF.js → chunk-T6RSJT6C.js} +202 -43
  4. package/dist/chunk-T6RSJT6C.js.map +1 -0
  5. package/dist/chunk-TLAC622R.js +4990 -0
  6. package/dist/chunk-TLAC622R.js.map +1 -0
  7. package/dist/codex-token-resolver.d.ts +64 -0
  8. package/dist/connection-token-resolver.d.ts +90 -0
  9. package/dist/environment-crypto.d.ts +11 -0
  10. package/dist/event-payload-sanitizer.d.ts +32 -0
  11. package/dist/index.d.ts +6374 -10
  12. package/dist/index.js +8075 -2776
  13. package/dist/index.js.map +1 -1
  14. package/dist/insights.d.ts +157 -0
  15. package/dist/memory-domain.d.ts +44 -0
  16. package/dist/migrate.d.ts +5 -7
  17. package/dist/migrate.js +1 -1
  18. package/dist/new-session-drafts.d.ts +49 -0
  19. package/dist/persistence-errors.d.ts +69 -0
  20. package/dist/preference-registry-schema.d.ts +1147 -0
  21. package/dist/preference-registry.d.ts +878 -0
  22. package/dist/provision-roles.d.ts +4 -6489
  23. package/dist/provision-roles.js +1 -1
  24. package/dist/role-relationships.d.ts +35 -0
  25. package/dist/runtime-posture-cli.d.ts +1 -0
  26. package/dist/runtime-posture.d.ts +103 -0
  27. package/dist/schema.d.ts +25330 -3
  28. package/dist/schema.js +31 -1
  29. package/dist/session-control.d.ts +331 -0
  30. package/dist/session-queue-commands.d.ts +186 -0
  31. package/dist/session-tool-call-settlement.d.ts +32 -0
  32. package/dist/turn-initiator.d.ts +28 -0
  33. package/dist/workspace-artifacts.d.ts +62 -0
  34. package/dist/workspace-instruction-policies-schema.d.ts +735 -0
  35. package/dist/workspace-instruction-policies.d.ts +64 -0
  36. package/drizzle/0136_unified_session_tool_policy.sql +1 -1
  37. package/drizzle/0137_preference_registry.sql +1347 -0
  38. package/drizzle/0138_sandbox_checkpoint_artifacts_and_deadlines.sql +1074 -0
  39. package/drizzle/0139_codex_provider_artifact_invalidations.sql +51 -0
  40. package/drizzle/0140_sandbox_restore_and_reaper_fences.sql +276 -0
  41. package/drizzle/0142_sandbox_archive_capture_gate.sql +80 -0
  42. package/drizzle/0143_session_codex_compaction_mode.sql +20 -0
  43. package/drizzle/0144_sandbox_viewer_force_drain_gate.sql +95 -0
  44. package/drizzle/0145_model_call_facts.sql +96 -0
  45. package/drizzle/0146_slack_bot_delete_idempotency.sql +105 -0
  46. package/drizzle/0147_draft_latency_mode.sql +12 -0
  47. package/drizzle/0148_session_turn_latency_mode.sql +12 -0
  48. package/drizzle/0149_workspace_artifacts.sql +348 -0
  49. package/drizzle/0150_slack_task_interactions.sql +344 -0
  50. package/package.json +6 -6
  51. package/src/index.ts +5766 -275
  52. package/src/insights.ts +837 -0
  53. package/src/migrate.ts +9 -1
  54. package/src/new-session-drafts.ts +4 -0
  55. package/src/preference-registry-schema.ts +170 -0
  56. package/src/preference-registry.ts +1220 -0
  57. package/src/provision-roles.ts +95 -22
  58. package/src/role-relationships.ts +132 -0
  59. package/src/runtime-posture.ts +47 -27
  60. package/src/schema.ts +875 -19
  61. package/src/session-queue-commands.ts +39 -6
  62. package/src/workspace-artifacts.ts +751 -0
  63. package/dist/chunk-DW24CKCT.js +0 -4046
  64. package/dist/chunk-DW24CKCT.js.map +0 -1
  65. package/dist/chunk-ELMUCYZF.js.map +0 -1
  66. package/dist/chunk-Y5WZZVQK.js.map +0 -1
  67. package/dist/schema-DhkRhcuQ.d.ts +0 -22666
@@ -0,0 +1,64 @@
1
+ import { environmentsEncryptionKeyBytes, type Settings } from "@opengeni/config";
2
+ import { type CodexTokenSnapshot, type CodexUsagePayload, type CodexFetch, type CodexRateLimitResetCreditsDetails, type ResetCreditFetchFailureReason, refreshCodexToken } from "@opengeni/codex";
3
+ import { encryptEnvironmentValue } from "./environment-crypto";
4
+ import { loadCodexCredentialForRun, recordCodexTokenRefresh, setCodexCredentialStatus, withCodexCredentialRefreshLock, type Database } from "./index";
5
+ export type CodexTokenDeadlineClock = {
6
+ setTimeout: (callback: () => void, delayMs: number) => ReturnType<typeof globalThis.setTimeout>;
7
+ clearTimeout: (handle: ReturnType<typeof globalThis.setTimeout>) => void;
8
+ };
9
+ export type CodexTokenDeadlineOptions = {
10
+ timeoutMs?: number | undefined;
11
+ signal?: AbortSignal | undefined;
12
+ clock?: CodexTokenDeadlineClock | undefined;
13
+ };
14
+ /**
15
+ * Bound a refresh promise without abandoning its rejection handler when the
16
+ * deadline or cancellation wins. The provider promise is observed exactly
17
+ * once, while the observer itself always fulfills, so a late provider failure
18
+ * cannot become an unhandled rejection or replace the authoritative outcome.
19
+ */
20
+ export declare function withCodexTokenDeadline<T>(operation: Promise<T>, options?: CodexTokenDeadlineOptions): Promise<T>;
21
+ export type CodexAuthDeps = {
22
+ loadCredential: typeof loadCodexCredentialForRun;
23
+ recordRefresh: typeof recordCodexTokenRefresh;
24
+ setStatus: typeof setCodexCredentialStatus;
25
+ refresh: typeof refreshCodexToken;
26
+ encrypt: typeof encryptEnvironmentValue;
27
+ keyBytes: typeof environmentsEncryptionKeyBytes;
28
+ withRefreshLock: typeof withCodexCredentialRefreshLock;
29
+ };
30
+ export declare function buildCodexTokenResolver(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps?: CodexAuthDeps): {
31
+ getToken: () => Promise<CodexTokenSnapshot>;
32
+ refresh: () => Promise<CodexTokenSnapshot>;
33
+ };
34
+ /**
35
+ * THE single per-account usage path both the api route and an (optional) worker
36
+ * poll call, so the refresh discipline and the cache-write can never drift.
37
+ *
38
+ * 1. resolve a REFRESHING bearer for THIS account (proactive staleness refresh,
39
+ * single-flight, (id,version) CAS-persist) — this is what stops an idle
40
+ * account's expired JWT from 401-ing the usage read.
41
+ * 2. fetch GET /wham/usage with that bearer.
42
+ * 3. normalize (§3) into the P2/P3 contract.
43
+ * 4. on any windows present, write the five usage-cache columns (the TTL clock).
44
+ *
45
+ * A refresh that stamps needs_relogin returns { status:"error", reason } and never
46
+ * hits the provider; a transient refresh error returns a plain error payload.
47
+ */
48
+ export declare function fetchCodexUsageForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): Promise<CodexUsagePayload>;
49
+ export type CodexRateLimitResetCreditsAccountResult = {
50
+ ok: true;
51
+ status: number;
52
+ details: CodexRateLimitResetCreditsDetails;
53
+ } | {
54
+ ok: false;
55
+ status: number;
56
+ reason: ResetCreditFetchFailureReason | "needs_relogin";
57
+ };
58
+ /**
59
+ * Fresh detailed reset-credit inventory for one exact workspace credential.
60
+ * The token is refreshed through the same resolver as usage and never escapes
61
+ * this server-side function. Detailed rows are returned to the route only and
62
+ * are never persisted as redemption authority.
63
+ */
64
+ export declare function fetchCodexRateLimitResetCreditsForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, fetchImpl?: CodexFetch): Promise<CodexRateLimitResetCreditsAccountResult>;
@@ -0,0 +1,90 @@
1
+ import { environmentsEncryptionKeyBytes, type McpServerConnectionRef, type Settings } from "@opengeni/config";
2
+ import type { ConnectionCredentialsPort, McpConnectionResourceScope, McpCredentialAuthNeededReason, McpCredentialsRequest, TurnInitiator, TurnInitiatorContext } from "@opengeni/contracts";
3
+ import { type DnsLookup, type FetchLike } from "@opengeni/network";
4
+ export { isPrivateAddress } from "@opengeni/network";
5
+ import { encryptEnvironmentValue } from "./environment-crypto";
6
+ import { loadConnectionCredentialForBroker, recordConnectionTokenRefresh, recordConnectionUsed, setConnectionStatus, type ConnectionCredentialForBroker, type Database } from "./index";
7
+ export type ResolveConnectionCredentialResult = {
8
+ status: "ok";
9
+ headers: Record<string, string>;
10
+ connectionId: string;
11
+ expiresAt?: Date | null;
12
+ } | {
13
+ status: "auth_needed";
14
+ reason: McpCredentialAuthNeededReason;
15
+ providerDomain: string;
16
+ provider?: string;
17
+ connectionId?: string;
18
+ scopes?: string[];
19
+ resource?: string;
20
+ selectedResources?: McpConnectionResourceScope[];
21
+ authorizationUrl?: string;
22
+ };
23
+ export type ResolveConnectionCredentialInput = {
24
+ workspaceId: string;
25
+ subjectId?: string;
26
+ serverId: string;
27
+ toolName?: string;
28
+ /** @deprecated Use toolName. Retained for the API's pre-existing broker call shape. */
29
+ toolId?: string;
30
+ connectionRef: McpServerConnectionRef;
31
+ /** Exact MCP destination whose request would receive the resolved headers. */
32
+ destinationUrl: string;
33
+ forceRefresh?: boolean;
34
+ };
35
+ export type HostMcpCredentialResolverContext = {
36
+ accountId: string;
37
+ workspaceId: string;
38
+ sessionId: string;
39
+ rootSessionId: string;
40
+ turnId: string;
41
+ attemptId: string | null;
42
+ executionGeneration: number;
43
+ initiator: TurnInitiator;
44
+ initiatorContext: TurnInitiatorContext;
45
+ surface: McpCredentialsRequest["surface"];
46
+ };
47
+ export declare class HostMcpCredentialScopeError extends Error {
48
+ constructor(field: "accountId" | "workspaceId" | "sessionId");
49
+ }
50
+ export declare class HostMcpCredentialBindingError extends Error {
51
+ constructor(field: "provider" | "providerDomain" | "connectionId" | "scopes" | "resource" | "selectedResources" | "destinationUrl");
52
+ }
53
+ /**
54
+ * Adapts the public embedding credential port to the runtime's connection
55
+ * resolver contract. Scope echoes are checked before credential headers can
56
+ * reach a request; the returned object is a fresh copy so a host cannot mutate
57
+ * headers after resolution.
58
+ */
59
+ export declare function buildHostConnectionTokenResolver(resolve: NonNullable<ConnectionCredentialsPort["mcpCredentials"]>, context: HostMcpCredentialResolverContext): (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult>;
60
+ export type ConnectionBrokerDeps = {
61
+ loadCredential: typeof loadConnectionCredentialForBroker;
62
+ recordRefresh: typeof recordConnectionTokenRefresh;
63
+ setStatus: typeof setConnectionStatus;
64
+ recordUsed: typeof recordConnectionUsed;
65
+ refresh: typeof refreshOAuthConnectionCredential;
66
+ encrypt: typeof encryptEnvironmentValue;
67
+ keyBytes: typeof environmentsEncryptionKeyBytes;
68
+ now: () => Date;
69
+ };
70
+ export type RefreshTransportOptions = {
71
+ fetchImpl?: FetchLike;
72
+ dnsLookup?: DnsLookup;
73
+ };
74
+ export declare function buildConnectionTokenResolver(db: Database, settings: Settings, deps?: ConnectionBrokerDeps): (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult>;
75
+ export declare class ConnectionRefreshHttpError extends Error {
76
+ readonly httpStatus: number;
77
+ constructor(httpStatus: number);
78
+ }
79
+ /**
80
+ * Normalizes an OAuth token_type into the Authorization scheme to send. RFC 6750
81
+ * says the scheme is case-insensitive, but some MCP servers (e.g. Linear) reject
82
+ * a lowercase `bearer` — so a `bearer`/`BEARER` (or absent) token_type is sent as
83
+ * the canonical `Bearer`. A non-bearer scheme is passed through unchanged.
84
+ */
85
+ export declare function normalizeBearerScheme(tokenType: string | null | undefined): string;
86
+ export declare function refreshOAuthConnectionCredential(cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, settings: Settings, transportOptions?: RefreshTransportOptions): Promise<{
87
+ credential: Record<string, unknown>;
88
+ expiresAt: Date | null;
89
+ grantedScopes?: string[];
90
+ }>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Encrypts one workspace environment variable value with AES-256-GCM under an
3
+ * operator key held outside Postgres. Output format: `v1:<b64 iv>:<b64 ciphertext||tag>`.
4
+ */
5
+ export declare function encryptEnvironmentValue(key: Uint8Array, plaintext: string): string;
6
+ /**
7
+ * Decrypts a stored `v1:` value. Error messages never echo plaintext or
8
+ * ciphertext: unknown versions throw "unsupported environment value format",
9
+ * auth-tag mismatches throw "environment value decryption failed".
10
+ */
11
+ export declare function decryptEnvironmentValue(key: Uint8Array, stored: string): string;
@@ -0,0 +1,32 @@
1
+ import { type SecretForRedaction } from "@opengeni/contracts";
2
+ /**
3
+ * Strip NUL and repair invalid/lone UTF-16 surrogates in a single string.
4
+ * Returns the input unchanged (same reference) when it is already clean, so the
5
+ * common case allocates nothing.
6
+ */
7
+ export declare function sanitizeEventString(value: string): string;
8
+ /**
9
+ * Deep-walk a session event payload and sanitize every string value. Mirrors the
10
+ * shape of the worker redaction deep-walk: objects, arrays, and nested
11
+ * combinations are traversed; non-string leaves pass through untouched. Object
12
+ * keys are sanitized too -- they are jsonb-constrained the same as values.
13
+ */
14
+ export type SanitizeEventPayloadOptions = {
15
+ /**
16
+ * Separately trusted, server-created retained-output evidence. Never populate
17
+ * this from a producer-controlled payload field.
18
+ */
19
+ fullEvidence?: unknown;
20
+ /** Exact runtime credential provenance to remove from keys and values. */
21
+ knownSecrets?: readonly SecretForRedaction[];
22
+ };
23
+ export declare function sanitizeEventPayload<T>(payload: T, options?: SanitizeEventPayloadOptions): T;
24
+ /**
25
+ * Make model-facing conversation data safe for Postgres and secret-redacted.
26
+ *
27
+ * Conversation history is the replay source for the model, so this boundary
28
+ * retains protocol structure and non-sensitive diagnostics while removing
29
+ * credential-bearing fields and text before durable storage. It also performs
30
+ * the database-safety repair (NUL removal and UTF-16 repair).
31
+ */
32
+ export declare function sanitizeModelPayload<T>(payload: T, knownSecrets?: readonly SecretForRedaction[]): T;