@gebsecure01/sdk 0.2.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.
- package/CHANGELOG.md +64 -0
- package/README.md +188 -0
- package/dist/index.cjs +1241 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2378 -0
- package/dist/index.d.ts +2378 -0
- package/dist/index.js +1218 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/clock.ts","../src/errors.ts","../src/auth.ts","../src/version.ts","../src/http.ts","../src/client.ts","../src/spans.ts","../src/generated/models.ts"],"sourcesContent":["/** Time source used for token expiry, backoff and approval polling. Injectable for tests. */\nexport interface Clock {\n /** Milliseconds since the epoch. */\n now(): number;\n /** Resolves after `ms`; rejects with the signal's reason if aborted. */\n sleep(ms: number, signal?: AbortSignal): Promise<void>;\n}\n\nexport function abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException('The operation was aborted', 'AbortError');\n}\n\nexport const systemClock: Clock = {\n now: () => Date.now(),\n sleep: (ms, signal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(abortReason(signal));\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortReason(signal!));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, Math.max(0, ms));\n signal?.addEventListener('abort', onAbort, { once: true });\n }),\n};\n","import type { Approval, SimulationRun } from './generated/models.js';\n\n/** Fields shared by every GebSecure SDK error (see sdks/conformance/README.md §4). */\nexport interface ErrorInit {\n status?: number;\n code: string;\n detail?: string;\n requestId?: string | null;\n traceId?: string | null;\n details?: Record<string, unknown> | null;\n type?: string | null;\n cause?: unknown;\n}\n\n/** Base class of every error raised by the SDK. */\nexport class GebSecureError extends Error {\n /** HTTP status, or 0 for client-side errors (network, timeouts, approval waits). */\n readonly status: number;\n /** Machine-readable error code, e.g. `policy_denied`, `rate_limited`, `connection_error`. */\n readonly code: string;\n /** Human-readable detail from the server (or the SDK). */\n readonly detail: string;\n /** Server request id (`x-request-id`), when known. */\n readonly requestId: string | null;\n /** W3C trace id of the request, when known. */\n readonly traceId: string | null;\n /** Structured problem details (e.g. validation issues), when provided. */\n readonly details: Record<string, unknown> | null;\n /** Problem type URI, when provided. */\n readonly type: string | null;\n\n constructor(init: ErrorInit) {\n const detail = init.detail ?? init.code;\n super(`${init.code}: ${detail}${init.requestId ? ` (request ${init.requestId})` : ''}`, init.cause !== undefined ? { cause: init.cause } : undefined);\n this.name = new.target.name;\n this.status = init.status ?? 0;\n this.code = init.code;\n this.detail = detail;\n this.requestId = init.requestId ?? null;\n this.traceId = init.traceId ?? null;\n this.details = init.details ?? null;\n this.type = init.type ?? null;\n }\n}\n\n/** An error returned by the GebSecure API (RFC 9457 problem+json). Unknown codes use this class. */\nexport class ApiError extends GebSecureError {}\n/** 401 `unauthenticated`: missing, invalid, expired or revoked credentials. */\nexport class AuthenticationError extends ApiError {}\n/** 403 `forbidden`: the principal lacks a permission or scope. */\nexport class PermissionDeniedError extends ApiError {}\n/** 403 `policy_denied`: a policy denied the action. */\nexport class PolicyDeniedError extends ApiError {}\n/** 403 `approval_required`: the action requires human approval. */\nexport class ApprovalRequiredError extends ApiError {}\n/** 400 `bad_request` / 422 `validation_failed`. */\nexport class ValidationError extends ApiError {}\n/** 404 `not_found`. */\nexport class NotFoundError extends ApiError {}\n/** 409 `conflict` / 412 `precondition_failed`. */\nexport class ConflictError extends ApiError {}\n/** 502 `upstream_error`. */\nexport class UpstreamError extends ApiError {}\n/** 504 `timeout`, or a client-side per-attempt timeout (status 0). */\nexport class TimeoutError extends ApiError {}\n/** 503 `unavailable`. */\nexport class UnavailableError extends ApiError {}\n/** 500 `internal` and unknown 5xx. */\nexport class InternalError extends ApiError {}\n\n/** 429 `rate_limited` / `quota_exceeded`. */\nexport class RateLimitError extends ApiError {\n /** Server-requested wait before retrying, in milliseconds (from `Retry-After`), if any. */\n readonly retryAfterMs: number | null;\n constructor(init: ErrorInit & { retryAfterMs?: number | null }) {\n super(init);\n this.retryAfterMs = init.retryAfterMs ?? null;\n }\n}\n\n/** The request could not be delivered (DNS, connection refused/reset, TLS). */\nexport class ConnectionError extends GebSecureError {\n constructor(detail: string, cause?: unknown) {\n super({ code: 'connection_error', detail, cause });\n }\n}\n\n/** `waitForApproval` deadline passed while the approval was still pending. */\nexport class ApprovalTimeoutError extends GebSecureError {\n readonly approvalId: string;\n constructor(approvalId: string, timeoutMs: number) {\n super({ code: 'approval_timeout', detail: `Approval ${approvalId} still pending after ${timeoutMs} ms` });\n this.approvalId = approvalId;\n }\n}\n\n/** `executeWithApproval`: the approval ended rejected, expired or cancelled (not `approved`/`consumed`). */\nexport class ApprovalNotGrantedError extends GebSecureError {\n readonly approval: Approval;\n constructor(approval: Approval) {\n super({ code: 'approval_not_granted', detail: `Approval ${approval.id} was ${approval.status}${approval.resolutionComment ? `: ${approval.resolutionComment}` : ''}` });\n this.approval = approval;\n }\n}\n\n/**\n * `runSimulation({ failOnMismatch: true })`: the run failed or errored and the server answered 422 with\n * the full run, available as `run` (conformance §4).\n */\nexport class SimulationFailedError extends ApiError {\n readonly run: SimulationRun;\n constructor(run: SimulationRun, meta: { requestId?: string | null; traceId?: string | null } = {}) {\n const s = run.summary;\n super({\n status: 422,\n code: 'simulation_failed',\n detail: `Simulation ${run.id ?? run.name ?? ''} ${run.status}: ${s?.failed ?? 0} failed, ${s?.errors ?? 0} errors`.replace(' ', ' '),\n requestId: meta.requestId ?? null,\n traceId: meta.traceId ?? null,\n });\n this.run = run;\n }\n}\n\n/** Invalid SDK configuration (e.g. an unsupported key or an assertion lifetime above 300 s). */\nexport class ConfigurationError extends GebSecureError {\n constructor(detail: string) {\n super({ code: 'invalid_configuration', detail });\n }\n}\n\nconst STATUS_CODES: Record<number, string> = {\n 400: 'bad_request',\n 401: 'unauthenticated',\n 403: 'forbidden',\n 404: 'not_found',\n 409: 'conflict',\n 412: 'precondition_failed',\n 422: 'validation_failed',\n 429: 'rate_limited',\n 502: 'upstream_error',\n 503: 'unavailable',\n 504: 'timeout',\n};\n\nconst CODE_CLASSES: Record<string, typeof ApiError> = {\n unauthenticated: AuthenticationError,\n forbidden: PermissionDeniedError,\n policy_denied: PolicyDeniedError,\n approval_required: ApprovalRequiredError,\n validation_failed: ValidationError,\n bad_request: ValidationError,\n not_found: NotFoundError,\n conflict: ConflictError,\n precondition_failed: ConflictError,\n upstream_error: UpstreamError,\n timeout: TimeoutError,\n unavailable: UnavailableError,\n internal: InternalError,\n};\n\n/** Default error code for an HTTP status (conformance §4). */\nexport function codeForStatus(status: number): string {\n return STATUS_CODES[status] ?? (status >= 500 ? 'internal' : 'bad_request');\n}\n\n/** Builds the typed error for a non-2xx response. */\nexport function errorFromResponse(args: {\n status: number;\n body: unknown;\n text: string;\n requestId: string | null;\n traceId: string | null;\n retryAfterMs: number | null;\n}): ApiError {\n const p = (args.body && typeof args.body === 'object' ? args.body : {}) as Record<string, unknown>;\n const str = (v: unknown) => (typeof v === 'string' && v ? v : undefined);\n const typeUri = str(p.type);\n const code = str(p.title) ?? (typeUri ? typeUri.split('/').pop() : undefined) ?? codeForStatus(args.status);\n const init: ErrorInit & { retryAfterMs?: number | null } = {\n status: args.status,\n code: code!,\n detail: str(p.detail) ?? (args.text ? args.text.slice(0, 500) : `HTTP ${args.status}`),\n requestId: str(p.requestId) ?? args.requestId,\n traceId: str(p.traceId) ?? args.traceId,\n details: p.details && typeof p.details === 'object' ? (p.details as Record<string, unknown>) : null,\n type: typeUri ?? null,\n retryAfterMs: args.retryAfterMs,\n };\n if (code === 'rate_limited' || code === 'quota_exceeded') return new RateLimitError(init);\n const Cls = CODE_CLASSES[code!] ?? (args.status >= 500 ? InternalError : ApiError);\n return new Cls(init);\n}\n","import { abortReason } from './clock.js';\nimport { ConfigurationError } from './errors.js';\nimport type { AuthContext, TokenProvider } from './http.js';\nimport type { TokenResponse } from './generated/models.js';\n\nexport type { AuthContext, TokenProvider } from './http.js';\n\n// ─── Static credentials ─────────────────────────────────────────────────────\nclass StaticTokenProvider implements TokenProvider {\n readonly refreshable = false;\n constructor(private readonly token: string) {\n if (!token) throw new ConfigurationError('Token must be a non-empty string');\n }\n async getToken(): Promise<string> {\n return this.token;\n }\n invalidate(): void {}\n}\n\nclass UnauthenticatedProvider implements TokenProvider {\n readonly refreshable = false;\n async getToken(): Promise<string> {\n throw new ConfigurationError('This client is unauthenticated: only login() and refreshSession() are available. Create a client with credentials (e.g. staticToken(loginResult.accessToken)).');\n }\n invalidate(): void {}\n}\n\n/**\n * No credentials (conformance §2): for `login()` / `refreshSession()` before a token exists. Every other\n * call fails with `ConfigurationError` before sending a request.\n */\nexport function unauthenticated(): TokenProvider {\n return new UnauthenticatedProvider();\n}\n\n/** API key (`gsk_…`), sent directly as the Bearer token. */\nexport function apiKey(key: string): TokenProvider {\n return new StaticTokenProvider(key);\n}\n\n/** A pre-obtained access token (not refreshed). */\nexport function staticToken(token: string): TokenProvider {\n return new StaticTokenProvider(token);\n}\n\n// ─── OAuth providers with caching + single-flight ───────────────────────────\n/** A cached access token. */\nexport interface CachedToken {\n accessToken: string;\n /** Epoch ms after which the token must not be used (expiry minus skew). */\n refreshAt: number;\n scope: string | undefined;\n}\n\n/**\n * Base class for providers that obtain tokens from the token endpoint. Tokens are cached and refreshed\n * `min(60 s, expires_in / 2)` before expiry; concurrent callers share one in-flight request.\n */\nexport abstract class OAuthTokenProvider implements TokenProvider {\n readonly refreshable = true;\n private cached: CachedToken | null = null;\n private inflight: Promise<CachedToken> | null = null;\n private generation = 0;\n\n /** Builds the grant body. Called once per token request attempt. */\n protected abstract grant(ctx: AuthContext, signal?: AbortSignal): Promise<Record<string, unknown>>;\n /** Whether the grant may be retried on 5xx/network errors. */\n protected readonly idempotentGrant: boolean = true;\n\n async getToken(ctx: AuthContext, signal?: AbortSignal): Promise<string> {\n const now = ctx.clock.now();\n if (this.cached && now < this.cached.refreshAt) return this.cached.accessToken;\n if (!this.inflight) {\n const gen = this.generation;\n // The shared fetch is not bound to any single caller's signal; each caller can still abandon it.\n const p = this.fetchToken(ctx)\n .then((t) => {\n if (gen === this.generation) this.cached = t;\n return t;\n })\n .finally(() => {\n if (this.inflight === p) this.inflight = null;\n });\n this.inflight = p;\n }\n const token = await raceAbort(this.inflight, signal);\n return token.accessToken;\n }\n\n invalidate(): void {\n this.generation++;\n this.cached = null;\n this.inflight = null;\n }\n\n private async fetchToken(ctx: AuthContext): Promise<CachedToken> {\n const started = ctx.clock.now();\n const r: TokenResponse = await ctx.requestToken(() => this.grant(ctx), { idempotent: this.idempotentGrant });\n const ttlMs = Math.max(0, Number(r.expires_in ?? 0) * 1000);\n const skew = Math.min(60_000, ttlMs / 2);\n return { accessToken: r.access_token, refreshAt: started + ttlMs - skew, scope: r.scope };\n }\n}\n\nfunction raceAbort<T>(p: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(abortReason(signal));\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortReason(signal));\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\nexport interface ClientSecretOptions {\n /** The `gsa_…` client secret. */\n clientSecret: string;\n /** Optional credential or principal id (checked by the server when present). */\n clientId?: string;\n /** Space-separated scopes to request (narrowed to the credential's scopes). */\n scope?: string;\n}\n\nclass ClientSecretProvider extends OAuthTokenProvider {\n constructor(private readonly o: ClientSecretOptions) {\n super();\n if (!o.clientSecret) throw new ConfigurationError('clientSecret is required');\n }\n protected async grant(): Promise<Record<string, unknown>> {\n return {\n grant_type: 'client_credentials',\n client_secret: this.o.clientSecret,\n ...(this.o.clientId ? { client_id: this.o.clientId } : {}),\n ...(this.o.scope ? { scope: this.o.scope } : {}),\n };\n }\n}\n\n/** OAuth 2.0 client credentials with a client secret (`gsa_…`). */\nexport function clientSecret(options: ClientSecretOptions): TokenProvider {\n return new ClientSecretProvider(options);\n}\n\n// ─── private_key_jwt ────────────────────────────────────────────────────────\nexport type JwtAlgorithm = 'EdDSA' | 'ES256' | 'RS256';\n\n/** Custom signer (e.g. a KMS/HSM): signs the JWS signing input and returns the raw JOSE signature. */\nexport type AssertionSigner = (signingInput: Uint8Array) => Promise<Uint8Array>;\n\nexport interface PrivateKeyJwtOptions {\n /** The agent credential id (`cred_…`): the assertion `iss`, `sub` and `kid`. */\n credentialId: string;\n /** PKCS#8 PEM string, private JWK, WebCrypto CryptoKey, or omitted when `signer` is given. */\n privateKey?: string | JsonWebKey | CryptoKey;\n /** Required with `signer` or a CryptoKey whose algorithm cannot be inferred. */\n algorithm?: JwtAlgorithm;\n /** Custom signer instead of `privateKey`. */\n signer?: AssertionSigner;\n /** Assertion audience; defaults to the token URL. Must equal the server's `{PUBLIC_API_URL}/v1/auth/token`. */\n audience?: string;\n /** Assertion lifetime in seconds (default 60, max 300). */\n lifetimeSeconds?: number;\n /** Space-separated scopes to request. */\n scope?: string;\n}\n\nconst OID_ED25519 = [0x06, 0x03, 0x2b, 0x65, 0x70];\nconst OID_EC_PUBLIC_KEY = [0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01];\nconst OID_P256 = [0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07];\nconst OID_RSA = [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01];\n\nfunction contains(hay: Uint8Array, needle: number[]): boolean {\n outer: for (let i = 0; i + needle.length <= hay.length; i++) {\n for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;\n return true;\n }\n return false;\n}\n\nfunction pemToDer(pem: string): Uint8Array<ArrayBuffer> {\n if (/BEGIN (EC |RSA |ENCRYPTED )PRIVATE KEY/.test(pem)) throw new ConfigurationError('Private key must be an unencrypted PKCS#8 PEM (\"BEGIN PRIVATE KEY\"); convert with `openssl pkcs8 -topk8 -nocrypt`');\n const m = /-----BEGIN PRIVATE KEY-----([\\s\\S]+?)-----END PRIVATE KEY-----/.exec(pem);\n if (!m) throw new ConfigurationError('Private key must be a PKCS#8 PEM (\"BEGIN PRIVATE KEY\") or a private JWK');\n return base64Decode(m[1]!.replace(/\\s+/g, ''));\n}\n\nfunction base64Decode(b64: string): Uint8Array<ArrayBuffer> {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nexport function base64url(data: Uint8Array | string): string {\n const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;\n let bin = '';\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nconst ALGS: Record<JwtAlgorithm, { importParams: AlgorithmIdentifier | EcKeyImportParams | RsaHashedImportParams; signParams: AlgorithmIdentifier | EcdsaParams }> = {\n EdDSA: { importParams: { name: 'Ed25519' }, signParams: { name: 'Ed25519' } },\n ES256: { importParams: { name: 'ECDSA', namedCurve: 'P-256' } as EcKeyImportParams, signParams: { name: 'ECDSA', hash: 'SHA-256' } as EcdsaParams },\n RS256: { importParams: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' } as RsaHashedImportParams, signParams: { name: 'RSASSA-PKCS1-v1_5' } },\n};\n\n/** Infers the JWS algorithm of a private key. */\nexport function inferAlgorithm(key: string | JsonWebKey): JwtAlgorithm {\n if (typeof key === 'string') {\n const der = pemToDer(key);\n if (contains(der, OID_ED25519)) return 'EdDSA';\n if (contains(der, OID_EC_PUBLIC_KEY)) {\n if (!contains(der, OID_P256)) throw new ConfigurationError('Only the P-256 curve is supported for EC keys');\n return 'ES256';\n }\n if (contains(der, OID_RSA)) return 'RS256';\n throw new ConfigurationError('Unsupported private key type (use Ed25519, P-256 or RSA)');\n }\n if (key.kty === 'OKP' && key.crv === 'Ed25519') return 'EdDSA';\n if (key.kty === 'EC' && key.crv === 'P-256') return 'ES256';\n if (key.kty === 'RSA') return 'RS256';\n throw new ConfigurationError('Unsupported JWK (use OKP/Ed25519, EC/P-256 or RSA)');\n}\n\n/** Imports a PKCS#8 PEM or private JWK as a WebCrypto signing key. */\nexport async function importSigningKey(key: string | JsonWebKey, alg: JwtAlgorithm): Promise<CryptoKey> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new ConfigurationError('WebCrypto (globalThis.crypto.subtle) is required for private_key_jwt');\n if (typeof key === 'string') return subtle.importKey('pkcs8', pemToDer(key), ALGS[alg].importParams, false, ['sign']);\n if (!key.d) throw new ConfigurationError('JWK must contain the private key (\"d\")');\n const { kty, crv, x, y, d, n, e, p, q, dp, dq, qi } = key;\n const jwk = Object.fromEntries(Object.entries({ kty, crv, x, y, d, n, e, p, q, dp, dq, qi }).filter(([, v]) => v !== undefined)) as JsonWebKey;\n return subtle.importKey('jwk', jwk, ALGS[alg].importParams, false, ['sign']);\n}\n\n/** Creates a signed client assertion JWT (RFC 7523). Exposed for custom integrations and tests. */\nexport async function createClientAssertion(args: {\n credentialId: string;\n audience: string;\n algorithm: JwtAlgorithm;\n sign: AssertionSigner;\n nowMs: number;\n lifetimeSeconds?: number;\n}): Promise<string> {\n const lifetime = args.lifetimeSeconds ?? 60;\n if (!(lifetime > 0 && lifetime <= 300)) throw new ConfigurationError('Assertion lifetime must be between 1 and 300 seconds');\n const iat = Math.floor(args.nowMs / 1000);\n const header = { alg: args.algorithm, typ: 'JWT', kid: args.credentialId };\n const claims = { iss: args.credentialId, sub: args.credentialId, aud: args.audience, iat, exp: iat + lifetime, jti: globalThis.crypto.randomUUID() };\n const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(claims))}`;\n const sig = await args.sign(new TextEncoder().encode(signingInput));\n return `${signingInput}.${base64url(sig)}`;\n}\n\nclass PrivateKeyJwtProvider extends OAuthTokenProvider {\n private readonly alg: JwtAlgorithm;\n private signer: AssertionSigner;\n\n constructor(private readonly o: PrivateKeyJwtOptions) {\n super();\n if (!o.credentialId) throw new ConfigurationError('credentialId is required');\n const lifetime = o.lifetimeSeconds ?? 60;\n if (!(lifetime > 0 && lifetime <= 300)) throw new ConfigurationError('lifetimeSeconds must be between 1 and 300 (server maximum is 5 minutes)');\n if (o.signer) {\n if (!o.algorithm) throw new ConfigurationError('algorithm is required with a custom signer');\n this.alg = o.algorithm;\n this.signer = o.signer;\n return;\n }\n const key = o.privateKey;\n if (!key) throw new ConfigurationError('privateKey or signer is required');\n if (typeof key === 'string' || !('type' in key && 'algorithm' in key)) this.alg = o.algorithm ?? inferAlgorithm(key as string | JsonWebKey);\n else {\n const name = (key as CryptoKey).algorithm.name;\n this.alg = o.algorithm ?? (name === 'Ed25519' ? 'EdDSA' : name === 'ECDSA' ? 'ES256' : 'RS256');\n }\n let imported: Promise<CryptoKey> | null = null;\n this.signer = async (data) => {\n const k = typeof key === 'string' || !('algorithm' in key) ? await (imported ??= importSigningKey(key as string | JsonWebKey, this.alg)) : (key as CryptoKey);\n return new Uint8Array(await globalThis.crypto.subtle.sign(ALGS[this.alg].signParams, k, data as BufferSource));\n };\n }\n\n protected async grant(ctx: AuthContext): Promise<Record<string, unknown>> {\n const assertion = await createClientAssertion({\n credentialId: this.o.credentialId,\n audience: this.o.audience ?? ctx.tokenUrl,\n algorithm: this.alg,\n sign: this.signer,\n nowMs: ctx.clock.now(),\n ...(this.o.lifetimeSeconds ? { lifetimeSeconds: this.o.lifetimeSeconds } : {}),\n });\n return {\n grant_type: 'client_credentials',\n client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n client_assertion: assertion,\n ...(this.o.scope ? { scope: this.o.scope } : {}),\n };\n }\n}\n\n/** OAuth 2.0 client credentials with `private_key_jwt` (Ed25519 / ES256 / RS256). */\nexport function privateKeyJwt(options: PrivateKeyJwtOptions): TokenProvider {\n return new PrivateKeyJwtProvider(options);\n}\n\n// ─── Delegation (RFC 8693 token exchange) ───────────────────────────────────\nexport interface DelegationOptions {\n /** The delegation token (`gsd_…`) issued by `createDelegation` to this (delegate) agent. */\n subjectToken: string;\n /** The delegate agent's own credentials; its access token is sent as `actor_token`. */\n actor: TokenProvider;\n /** Subset of the delegated scopes to request. */\n scope?: string;\n}\n\nclass DelegationProvider extends OAuthTokenProvider {\n constructor(private readonly o: DelegationOptions) {\n super();\n if (!o.subjectToken) throw new ConfigurationError('subjectToken is required');\n }\n protected async grant(ctx: AuthContext, signal?: AbortSignal): Promise<Record<string, unknown>> {\n return {\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: this.o.subjectToken,\n actor_token: await this.o.actor.getToken(ctx, signal),\n ...(this.o.scope ? { scope: this.o.scope } : {}),\n };\n }\n}\n\n/** Exchanges a delegation token for an access token acting on behalf of the delegator. */\nexport function delegation(options: DelegationOptions): TokenProvider {\n return new DelegationProvider(options);\n}\n","/** SDK version (kept in sync with package.json by the release workflow check). */\nexport const VERSION = '0.2.1';\n","import { abortReason, type Clock } from './clock.js';\nimport { ConnectionError, errorFromResponse, GebSecureError, TimeoutError } from './errors.js';\nimport type { TokenResponse } from './generated/models.js';\nimport { VERSION } from './version.js';\n\n/** Minimal fetch signature (global fetch, undici, node-fetch, or a test double). */\nexport type FetchLike = (input: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<Response>;\n\n/** Everything a token provider needs from the client (conformance §2). */\nexport interface AuthContext {\n /** `{apiUrl}/v1/auth/token`. */\n readonly tokenUrl: string;\n readonly clock: Clock;\n /**\n * POSTs a grant to the token endpoint (with retries). `buildBody` is invoked once per attempt so\n * private_key_jwt assertions get a fresh `jti` on every retry.\n */\n requestToken(buildBody: () => Promise<Record<string, unknown>>, opts: { idempotent: boolean; signal?: AbortSignal }): Promise<TokenResponse>;\n}\n\n/** Supplies the Bearer token for API calls. */\nexport interface TokenProvider {\n /** Whether tokens can be re-obtained. If true, a 401 invalidates the cache and the request is replayed once. */\n readonly refreshable: boolean;\n getToken(ctx: AuthContext, signal?: AbortSignal): Promise<string>;\n invalidate(): void;\n}\n\n/** Retry configuration (conformance §3). */\nexport interface RetryOptions {\n /** Retries after the first attempt. Default 3. */\n maxRetries: number;\n /** Base backoff delay. Default 500 ms. */\n baseDelayMs: number;\n /** Backoff cap. Default 8 s. */\n maxDelayMs: number;\n /** Longest server-requested `Retry-After` the SDK will wait for. Default 60 s. */\n maxRetryAfterMs: number;\n}\n\nexport interface CoreOptions extends RetryOptions {\n gatewayUrl: string;\n apiUrl: string;\n tokenUrl: string;\n /** Per-attempt timeout. Default 30 s. */\n timeoutMs: number;\n fetch: FetchLike;\n clock: Clock;\n random: () => number;\n userAgent: string;\n headers: Record<string, string>;\n}\n\n/** Per-call options accepted by every client method. */\nexport interface RequestOptions {\n /** Cancels the call, including in-flight requests and backoff sleeps. */\n signal?: AbortSignal;\n /** W3C traceparent of the caller's span; its trace id is propagated. */\n traceparent?: string;\n /** Overrides the per-attempt timeout for this call. */\n timeoutMs?: number;\n /** Overrides maxRetries for this call. */\n maxRetries?: number;\n /** Extra headers for this call. */\n headers?: Record<string, string>;\n /**\n * Sent as the `Idempotency-Key` header on every attempt; the call is then retried like an idempotent\n * request (conformance §3.4). Set it only when repeating the request is safe.\n */\n idempotencyKey?: string;\n}\n\nexport interface RequestSpec extends RequestOptions {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n base: 'gateway' | 'api';\n path: string;\n query?: Record<string, unknown> | undefined;\n body?: unknown;\n /** Whether network errors and 502/503/504 may be retried (429 is always retried). */\n idempotent: boolean;\n /** Token provider for the Authorization header; omitted for token-endpoint calls. */\n auth?: TokenProvider;\n /** Never retried except on 429, even with an idempotency key (refresh-token rotation). */\n neverRetry?: boolean;\n /** Treat a non-2xx response whose JSON body satisfies this predicate as a successful result. */\n terminalBody?: (status: number, body: unknown) => boolean;\n /** Maps a non-2xx JSON body to a specific (non-retried) error instead of the problem+json mapping. */\n bodyError?: (status: number, body: unknown, meta: { requestId: string | null; traceId: string | null }) => Error | undefined;\n /** `text` returns the raw response body (exports); default parses JSON. */\n responseType?: 'json' | 'text';\n /** Re-evaluated per attempt (token endpoint private_key_jwt). */\n buildBody?: () => Promise<unknown>;\n /** Absolute URL overriding base/path (token endpoint). */\n url?: string;\n}\n\nexport interface CoreResponse<T> {\n status: number;\n body: T;\n headers: Headers;\n}\n\nconst hex = (bytes: number) => {\n const b = new Uint8Array(bytes);\n globalThis.crypto.getRandomValues(b);\n return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n};\nconst TRACEPARENT = /^[0-9a-f]{2}-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/;\n\n/** Parses a `Retry-After` header (delta-seconds or HTTP-date) into milliseconds. */\nexport function parseRetryAfter(value: string | null, now: number): number | null {\n if (!value) return null;\n const v = value.trim();\n if (/^\\d+(\\.\\d+)?$/.test(v)) return Math.round(Number(v) * 1000);\n const at = Date.parse(v);\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n}\n\n/** Equal-jitter exponential backoff: uniform in [d/2, d] with d = min(maxDelay, base·2ⁿ). */\nexport function backoffDelay(attempt: number, o: Pick<RetryOptions, 'baseDelayMs' | 'maxDelayMs'>, random: () => number): number {\n const d = Math.min(o.maxDelayMs, o.baseDelayMs * 2 ** attempt);\n return d / 2 + random() * (d / 2);\n}\n\nexport function joinUrl(base: string, path: string, query?: Record<string, unknown>): string {\n let url = base.replace(/\\/+$/, '') + path;\n if (query) {\n const qs = new URLSearchParams();\n for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null) qs.set(k, String(v));\n const s = qs.toString();\n if (s) url += `?${s}`;\n }\n return url;\n}\n\n/** HTTP engine: auth header, tracing, timeouts, retries/backoff, error mapping. */\nexport class HttpCore {\n readonly authContext: AuthContext;\n\n constructor(readonly o: CoreOptions) {\n this.authContext = {\n tokenUrl: o.tokenUrl,\n clock: o.clock,\n requestToken: async (buildBody, opts) =>\n (\n await this.request<TokenResponse>({\n method: 'POST',\n base: 'api',\n path: '',\n url: o.tokenUrl,\n idempotent: opts.idempotent,\n buildBody,\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n ).body,\n };\n }\n\n async request<T>(spec: RequestSpec): Promise<CoreResponse<T>> {\n const url = spec.url ?? joinUrl(spec.base === 'gateway' ? this.o.gatewayUrl : this.o.apiUrl, spec.path, spec.query);\n const maxRetries = spec.maxRetries ?? this.o.maxRetries;\n const incoming = spec.traceparent ? TRACEPARENT.exec(spec.traceparent) : null;\n const traceId = incoming?.[1] ?? hex(16);\n const idempotent = !spec.neverRetry && (spec.idempotent || !!spec.idempotencyKey);\n let attempt = 0;\n let replayed401 = false;\n\n for (;;) {\n if (spec.signal?.aborted) throw abortReason(spec.signal);\n const headers: Record<string, string> = { accept: 'application/json', ...this.o.headers, ...spec.headers, traceparent: `00-${traceId}-${hex(8)}-01` };\n if (spec.idempotencyKey) headers['idempotency-key'] = spec.idempotencyKey;\n if (this.o.userAgent) headers['user-agent'] = this.o.userAgent;\n if (spec.auth) headers.authorization = `Bearer ${await spec.auth.getToken(this.authContext, spec.signal)}`;\n const payload = spec.buildBody ? await spec.buildBody() : spec.body;\n if (payload !== undefined) headers['content-type'] = 'application/json';\n\n let res: Response;\n try {\n res = await this.fetchAttempt(url, spec.method, headers, payload === undefined ? undefined : JSON.stringify(payload), spec.timeoutMs ?? this.o.timeoutMs, spec.signal);\n } catch (err) {\n if (spec.signal?.aborted) throw abortReason(spec.signal);\n if (idempotent && attempt < maxRetries) {\n await this.o.clock.sleep(backoffDelay(attempt++, this.o, this.o.random), spec.signal);\n continue;\n }\n throw err;\n }\n\n const text = await res.text().catch(() => '');\n let body: unknown = undefined;\n if (text && /json/i.test(res.headers.get('content-type') ?? '')) {\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n }\n if (res.ok && spec.responseType === 'text') return { status: res.status, body: text as T, headers: res.headers };\n if (res.ok || (body !== undefined && spec.terminalBody?.(res.status, body))) return { status: res.status, body: body as T, headers: res.headers };\n\n if (res.status === 401 && spec.auth?.refreshable && !replayed401) {\n spec.auth.invalidate();\n replayed401 = true;\n continue;\n }\n const retryAfterMs = parseRetryAfter(res.headers.get('retry-after'), this.o.clock.now());\n const respTrace = TRACEPARENT.exec(res.headers.get('traceparent') ?? '');\n const special = body !== undefined ? spec.bodyError?.(res.status, body, { requestId: res.headers.get('x-request-id'), traceId: respTrace?.[1] ?? null }) : undefined;\n if (special) throw special;\n const error = errorFromResponse({ status: res.status, body, text, requestId: res.headers.get('x-request-id'), traceId: respTrace?.[1] ?? null, retryAfterMs });\n const retryable = res.status === 429 || (idempotent && (res.status === 502 || res.status === 503 || res.status === 504));\n if (!retryable || attempt >= maxRetries) throw error;\n if (retryAfterMs !== null && retryAfterMs > this.o.maxRetryAfterMs) throw error;\n await this.o.clock.sleep(retryAfterMs ?? backoffDelay(attempt, this.o, this.o.random), spec.signal);\n attempt++;\n }\n }\n\n private async fetchAttempt(url: string, method: string, headers: Record<string, string>, body: string | undefined, timeoutMs: number, signal?: AbortSignal): Promise<Response> {\n const ctrl = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n ctrl.abort();\n }, timeoutMs);\n const onAbort = () => ctrl.abort(signal!.reason);\n signal?.addEventListener('abort', onAbort, { once: true });\n try {\n const res = await this.o.fetch(url, { method, headers, ...(body !== undefined ? { body } : {}), signal: ctrl.signal });\n return res;\n } catch (err) {\n if (signal?.aborted) throw abortReason(signal);\n if (timedOut) throw new TimeoutError({ status: 0, code: 'timeout', detail: `No response within ${timeoutMs} ms`, cause: err });\n if (err instanceof GebSecureError) throw err;\n throw new ConnectionError(err instanceof Error ? err.message : String(err), err);\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n }\n }\n}\n\nexport const DEFAULT_USER_AGENT = `gebsecure-typescript/${VERSION}`;\n","import { apiKey, clientSecret, delegation, type TokenProvider } from './auth.js';\nimport { systemClock, type Clock } from './clock.js';\nimport { ApprovalNotGrantedError, ApprovalTimeoutError, ConfigurationError, SimulationFailedError, TimeoutError } from './errors.js';\nimport type {\n Agent,\n AgentCredential,\n AgentCredentialList,\n AgentPage,\n AgentSpan,\n AgentStatusRequest,\n Alert,\n AlertPage,\n Approval,\n ApprovalDecisionResult,\n ApprovalPage,\n AuditEvent,\n AuditExportParams,\n AuditPage,\n AuditSearchParams,\n AuditVerification,\n ClientCredentialsInstallRequest,\n Connection,\n ConnectionHealth,\n ConnectionList,\n Connector,\n ConnectorList,\n CreateConnectionRequest,\n CreateCredentialRequest,\n CreatedSecret,\n CreatePolicyRequest,\n CreateSecretRequest,\n DecideApprovalRequest,\n DeployPolicyRequest,\n DlpScanRequest,\n DlpScanResult,\n InspectRequest,\n InspectResult,\n IssuedCredential,\n JwtBearerInstallRequest,\n ListAlertsParams,\n ListConnectionsParams,\n ListSecretsParams,\n LoginRequest,\n LoginResult,\n Me,\n OAuthCallbackRequest,\n OAuthInstallResult,\n OAuthStartRequest,\n OAuthStartResult,\n PolicyDeployResult,\n PolicyDeploymentList,\n PolicyDetail,\n PolicyDiff,\n PolicyRollbackResult,\n PolicySimulateRequest,\n PolicySimulation,\n PolicyTest,\n PolicyTestCase,\n PolicyTestList,\n PolicyTestRun,\n PolicyValidation,\n PolicyVersion,\n PolicyVersionResult,\n RegisterAgentRequest,\n RegisteredAgent,\n ReplayParams,\n ReportSpansRequest,\n ReportSpansResult,\n RevokeSecretRequest,\n RevokeSecretResult,\n RollbackPolicyRequest,\n RotateCredentialRequest,\n RotatedCredential,\n RotatedSecret,\n RotateSecretRequest,\n Secret,\n SecretList,\n SessionReplay,\n SessionTokens,\n SimulationRun,\n SimulationRunRequest,\n Trace,\n TraceSearchParams,\n TraceSearchResult,\n UpdateAgentRequest,\n UpdateAlertRequest,\n UpdateConnectionRequest,\n UpdatePolicyRequest,\n UpdateSecretRequest,\n VerifyAuditRequest,\n AuthorizeBatchRequest,\n AuthorizeBatchResult,\n AuthorizeRequest,\n AuthorizeResult,\n CancelExecutionResult,\n CreateDelegationRequest,\n Delegation,\n ExecuteRequest,\n ExecuteResult,\n Execution,\n ListAgentsParams,\n ListApprovalsParams,\n ListExecutionsParams,\n ListPoliciesParams,\n PolicyList,\n ExecutionPage,\n} from './generated/models.js';\nimport { DEFAULT_USER_AGENT, HttpCore, type FetchLike, type RequestOptions, type RequestSpec } from './http.js';\n\nexport interface GebSecureOptions {\n /** Data-plane gateway base URL. Default `GEBSECURE_GATEWAY_URL` or `https://gateway.gebsecure.dev`. */\n gatewayUrl?: string;\n /** Control-plane API base URL. Default `GEBSECURE_API_URL` or `https://api.gebsecure.dev`. */\n apiUrl?: string;\n /** Token endpoint. Default `{apiUrl}/v1/auth/token`. */\n tokenUrl?: string;\n /** Token provider (`apiKey()`, `clientSecret()`, `privateKeyJwt()`, `delegation()`, `staticToken()`). */\n auth?: TokenProvider;\n /** Shorthand for `auth: apiKey(key)`. Defaults to `GEBSECURE_API_KEY`. */\n apiKey?: string;\n /** Retries after the first attempt (default 3). 0 disables retries and automatic idempotency keys. */\n maxRetries?: number;\n /** Per-attempt timeout in ms (default 30 000). */\n timeoutMs?: number;\n /** Backoff base delay in ms (default 500). */\n baseDelayMs?: number;\n /** Backoff cap in ms (default 8 000). */\n maxDelayMs?: number;\n /** Longest Retry-After (ms) the SDK will wait for (default 60 000). */\n maxRetryAfterMs?: number;\n /** Custom fetch implementation. Default: global fetch. */\n fetch?: FetchLike;\n /** Custom clock (tests). */\n clock?: Clock;\n /** Random source for jitter (tests). */\n random?: () => number;\n /** User-Agent header (Node only; browsers ignore it). */\n userAgent?: string;\n /** Headers added to every request. */\n headers?: Record<string, string>;\n}\n\nexport interface WaitOptions extends RequestOptions {\n /** Give up after this many ms (default 10 minutes). */\n timeoutMs?: number;\n /** Poll interval in ms (default 2 000). */\n pollIntervalMs?: number;\n}\n\n/** Result of `guard()`: whether the action may proceed right now, and the full decision. */\nexport interface GuardResult {\n allowed: boolean;\n decision: AuthorizeResult;\n}\n\nconst env = (name: string): string | undefined => {\n const p = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n return p?.env?.[name] || undefined;\n};\nconst isNode = () => typeof (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node === 'string';\nconst seg = (id: string) => {\n if (!id) throw new ConfigurationError('id must be a non-empty string');\n return encodeURIComponent(id);\n};\n/** Execution states that are still in progress. `awaiting_approval` counts: an approved execution keeps it until the worker resumes it. */\nconst ACTIVE_EXECUTION = new Set(['awaiting_approval', 'pending', 'running', 'cancelling']);\n/** Approval states that mean \"granted\": `consumed` = the server already resumed the execution with it. */\nconst GRANTED_APPROVAL = new Set(['approved', 'consumed']);\nconst isExecuteResult = (_status: number, body: unknown) =>\n !!body && typeof body === 'object' && typeof (body as Record<string, unknown>).status === 'string' && 'decision' in (body as Record<string, unknown>);\nconst newIdempotencyKey = () => `sdk-${globalThis.crypto.randomUUID()}`;\nconst isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\n/** 412 from deploy with a deploy report (`deployed: false`) is a result (conformance §5.2). */\nconst isDeployReport = (status: number, body: unknown) => status === 412 && isObject(body) && typeof body.deployed === 'boolean';\n/** 422 from `failOnMismatch` carries the whole run (conformance §4). */\nconst simulationFailure = (status: number, body: unknown, meta: { requestId: string | null; traceId: string | null }) =>\n status === 422 && isObject(body) && typeof body.status === 'string' && isObject(body.summary) && Array.isArray(body.results)\n ? new SimulationFailedError(body as unknown as SimulationRun, meta)\n : undefined;\n\n/**\n * GebSecure client. Data-plane calls go to the gateway, control-plane calls and token requests to\n * the API. All methods accept `RequestOptions` (AbortSignal, traceparent, timeout, retries).\n *\n * ```ts\n * const gs = new GebSecure({ auth: privateKeyJwt({ credentialId, privateKey }) });\n * const { allowed, decision } = await gs.guard('refunds:create', 'stripe:charge/ch_1', { amount: 250 });\n * ```\n */\nexport class GebSecure {\n readonly gatewayUrl: string;\n readonly apiUrl: string;\n private readonly core: HttpCore;\n private readonly auth: TokenProvider;\n private readonly clock: Clock;\n private readonly maxRetries: number;\n private readonly options: GebSecureOptions;\n\n constructor(options: GebSecureOptions = {}) {\n this.options = options;\n this.gatewayUrl = (options.gatewayUrl ?? env('GEBSECURE_GATEWAY_URL') ?? 'https://gateway.gebsecure.dev').replace(/\\/+$/, '');\n this.apiUrl = (options.apiUrl ?? env('GEBSECURE_API_URL') ?? 'https://api.gebsecure.dev').replace(/\\/+$/, '');\n const key = options.apiKey ?? (options.auth ? undefined : env('GEBSECURE_API_KEY'));\n const secret = options.auth || key ? undefined : env('GEBSECURE_CLIENT_SECRET');\n const auth = options.auth ?? (key ? apiKey(key) : secret ? clientSecret({ clientSecret: secret }) : undefined);\n if (!auth) throw new ConfigurationError('No credentials: pass `auth` or `apiKey`, or set GEBSECURE_API_KEY / GEBSECURE_CLIENT_SECRET');\n this.auth = auth;\n this.clock = options.clock ?? systemClock;\n this.maxRetries = options.maxRetries ?? 3;\n const fetchImpl = options.fetch ?? (globalThis.fetch?.bind(globalThis) as FetchLike | undefined);\n if (!fetchImpl) throw new ConfigurationError('No fetch implementation available; pass `fetch`');\n this.core = new HttpCore({\n gatewayUrl: this.gatewayUrl,\n apiUrl: this.apiUrl,\n tokenUrl: options.tokenUrl ?? `${this.apiUrl}/v1/auth/token`,\n timeoutMs: options.timeoutMs ?? 30_000,\n maxRetries: this.maxRetries,\n baseDelayMs: options.baseDelayMs ?? 500,\n maxDelayMs: options.maxDelayMs ?? 8_000,\n maxRetryAfterMs: options.maxRetryAfterMs ?? 60_000,\n fetch: fetchImpl,\n clock: this.clock,\n // eslint-disable-next-line no-restricted-properties -- retry jitter only; never security-relevant\n random: options.random ?? Math.random,\n userAgent: options.userAgent ?? (isNode() ? DEFAULT_USER_AGENT : ''),\n headers: options.headers ?? {},\n });\n }\n\n /** A client with the same configuration acting under a delegation token (RFC 8693 exchange). */\n withDelegation(subjectToken: string, opts: { scope?: string } = {}): GebSecure {\n return new GebSecure({ ...this.options, gatewayUrl: this.gatewayUrl, apiUrl: this.apiUrl, auth: delegation({ subjectToken, actor: this.auth, ...opts }) });\n }\n\n /** Returns a valid access token (cached/refreshed), e.g. to call GebSecure APIs not wrapped by the SDK. */\n getAccessToken(opts: RequestOptions = {}): Promise<string> {\n return this.auth.getToken(this.core.authContext, opts.signal);\n }\n\n private async call<T>(spec: Omit<RequestSpec, 'auth'>, opts: RequestOptions = {}): Promise<T> {\n return (await this.core.request<T>({ ...opts, ...spec, auth: this.auth })).body;\n }\n\n /** Calls an operation that returns no body (204); resolves to `undefined`. */\n private async callVoid(spec: Omit<RequestSpec, 'auth'>, opts: RequestOptions = {}): Promise<void> {\n await this.core.request<unknown>({ ...opts, ...spec, auth: this.auth });\n }\n\n /** Unauthenticated session endpoints (login/refresh): no Authorization header. */\n private async callAnonymous<T>(spec: Omit<RequestSpec, 'auth'>, opts: RequestOptions = {}): Promise<T> {\n return (await this.core.request<T>({ ...opts, ...spec })).body;\n }\n\n // ─── Decisions ──────────────────────────────────────────────────────────────\n /** Decides whether the principal may perform an action. DENY / APPROVAL_REQUIRED are results, not errors. */\n authorize(request: AuthorizeRequest, opts?: RequestOptions): Promise<AuthorizeResult> {\n return this.call({ method: 'POST', base: 'gateway', path: '/v1/authorize', body: request, idempotent: request.dryRun === true }, opts);\n }\n\n /** Evaluates up to 100 requests in one call. */\n authorizeBatch(request: AuthorizeBatchRequest, opts?: RequestOptions): Promise<AuthorizeBatchResult> {\n const idempotent = request.requests.length > 0 && request.requests.every((r) => r.dryRun === true);\n return this.call({ method: 'POST', base: 'gateway', path: '/v1/authorize/batch', body: request, idempotent }, opts);\n }\n\n /** Convenience around `authorize`: `allowed` is true only for ALLOW. Never throws on DENY. */\n async guard(action: string, resource: string, context?: Record<string, unknown>, opts?: RequestOptions & Partial<AuthorizeRequest>): Promise<GuardResult> {\n const { signal, traceparent, timeoutMs, maxRetries, headers, ...rest } = opts ?? {};\n const decision = await this.authorize({ ...rest, action, resource, ...(context ? { context } : {}) }, { signal, traceparent, timeoutMs, maxRetries, headers } as RequestOptions);\n return { allowed: decision.decision === 'ALLOW', decision };\n }\n\n // ─── Execution ──────────────────────────────────────────────────────────────\n /**\n * Authorizes and executes a connector action. Returns an `ExecuteResult` for succeeded, simulated,\n * awaiting_approval, running, denied (HTTP 403) and failed (HTTP 502/504) outcomes; problem+json errors throw.\n * With retries enabled, an idempotency key is generated when none is given.\n */\n execute(request: ExecuteRequest, opts: RequestOptions = {}): Promise<ExecuteResult> {\n const retries = opts.maxRetries ?? this.maxRetries;\n const body = !request.idempotencyKey && retries > 0 && !request.dryRun ? { ...request, idempotencyKey: newIdempotencyKey() } : request;\n return this.call({ method: 'POST', base: 'gateway', path: '/v1/execute', body, idempotent: !!body.idempotencyKey || body.dryRun === true, terminalBody: isExecuteResult }, opts);\n }\n\n /** Execution status, result and step logs. */\n getExecution(id: string, opts?: RequestOptions): Promise<Execution> {\n return this.call({ method: 'GET', base: 'gateway', path: `/v1/executions/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Lists executions visible to the caller. */\n listExecutions(params: ListExecutionsParams = {}, opts?: RequestOptions): Promise<ExecutionPage> {\n return this.call({ method: 'GET', base: 'gateway', path: '/v1/executions', query: { ...params }, idempotent: true }, opts);\n }\n\n /** Cancels a pending, awaiting-approval or running execution. */\n cancelExecution(id: string, opts?: RequestOptions): Promise<CancelExecutionResult> {\n return this.call({ method: 'POST', base: 'gateway', path: `/v1/executions/${seg(id)}/cancel`, idempotent: true }, opts);\n }\n\n // ─── Approvals ──────────────────────────────────────────────────────────────\n /** Status of an approval request (agent-facing, via the gateway). */\n getApproval(id: string, opts?: RequestOptions): Promise<Approval> {\n return this.call({ method: 'GET', base: 'gateway', path: `/v1/approvals/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Polls an approval until it leaves `pending`; returns it in its terminal state. */\n async waitForApproval(id: string, opts: WaitOptions = {}): Promise<Approval> {\n const { timeoutMs = 600_000, pollIntervalMs = 2_000, ...req } = opts;\n const deadline = this.clock.now() + timeoutMs;\n for (;;) {\n const a = await this.getApproval(id, req);\n if (a.status !== 'pending') return a;\n const remaining = deadline - this.clock.now();\n if (remaining <= 0) throw new ApprovalTimeoutError(id, timeoutMs);\n await this.clock.sleep(Math.min(pollIntervalMs, remaining), req.signal);\n }\n }\n\n /**\n * Executes; if human approval is required, waits for it and then follows the execution until it is\n * terminal. Once the approval is granted the platform resumes the stored execution itself (and consumes\n * the single-use approval), so this helper never re-executes (conformance §5).\n * Throws `ApprovalNotGrantedError` when the approval is rejected/expired/cancelled,\n * `ApprovalTimeoutError` when it stays pending past `timeoutMs`, and `TimeoutError` when the approved\n * execution has not finished by then. A resumed execution that fails is returned with `status: 'failed'`.\n */\n async executeWithApproval(request: ExecuteRequest, opts: WaitOptions = {}): Promise<ExecuteResult> {\n const { timeoutMs = 600_000, pollIntervalMs = 2_000, ...req } = opts;\n const deadline = this.clock.now() + timeoutMs;\n const base: ExecuteRequest = request.idempotencyKey || request.dryRun ? request : { ...request, idempotencyKey: newIdempotencyKey() };\n const first = await this.execute(base, req);\n if (first.status !== 'awaiting_approval' || !first.approval || !first.executionId) return first;\n\n const approval = await this.waitForApproval(first.approval.id, { ...req, timeoutMs: Math.max(0, deadline - this.clock.now()), pollIntervalMs });\n if (!GRANTED_APPROVAL.has(approval.status)) throw new ApprovalNotGrantedError(approval);\n\n for (;;) {\n const e = await this.getExecution(first.executionId, req);\n if (!ACTIVE_EXECUTION.has(e.status)) {\n return {\n executionId: e.id,\n status: e.status,\n decision: e.decision ?? first.decision,\n reason: e.error?.message ?? first.reason ?? '',\n output: e.output,\n outputTruncated: e.outputTruncated ?? false,\n error: e.error ?? null,\n approval: first.approval,\n risk: first.risk,\n durationMs: e.durationMs ?? 0,\n replayed: true,\n };\n }\n const remaining = deadline - this.clock.now();\n if (remaining <= 0) throw new TimeoutError({ status: 0, code: 'timeout', detail: `Execution ${first.executionId} still ${e.status} after ${timeoutMs} ms` });\n await this.clock.sleep(Math.min(pollIntervalMs, remaining), req.signal);\n }\n }\n\n // ─── Control plane ──────────────────────────────────────────────────────────\n /** Agent directory. */\n listAgents(params: ListAgentsParams = {}, opts?: RequestOptions): Promise<AgentPage> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/agents', query: { ...params }, idempotent: true }, opts);\n }\n\n /** One agent, including credential metadata. */\n getAgent(id: string, opts?: RequestOptions): Promise<Agent> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/agents/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Policies. */\n listPolicies(params: ListPoliciesParams = {}, opts?: RequestOptions): Promise<PolicyList> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/policies', query: { ...params }, idempotent: true }, opts);\n }\n\n /** Approval requests (`inbox: true` = those the caller can act on). */\n listApprovals(params: ListApprovalsParams = {}, opts?: RequestOptions): Promise<ApprovalPage> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/approvals', query: { ...params }, idempotent: true }, opts);\n }\n\n /** Delegates a subset of authority to another agent. The returned `token` (gsd_…) is shown once. */\n createDelegation(request: CreateDelegationRequest, opts?: RequestOptions): Promise<Delegation> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/delegations', body: request, idempotent: false }, opts);\n }\n\n // ─── Runtime: inspection, DLP, agent spans, simulation ──────────────────────\n /**\n * Inspects untrusted content (web page, email, RAG chunk, tool output) before the agent reads it:\n * prompt-injection score/level/action, a sanitized form, and inbound DLP. Hand `result.content`\n * (null when blocked) to the model instead of the original.\n */\n inspect(request: InspectRequest, opts?: RequestOptions): Promise<InspectResult> {\n return this.call({ method: 'POST', base: 'gateway', path: '/v1/inspect', body: request, idempotent: false }, opts);\n }\n\n /** Scans a payload for sensitive data and applies DLP rules. Retried like a read only when `dryRun` is true. */\n dlpScan(request: DlpScanRequest, opts?: RequestOptions): Promise<DlpScanResult> {\n return this.call({ method: 'POST', base: 'gateway', path: '/v1/dlp/scan', body: request, idempotent: request.dryRun === true }, opts);\n }\n\n /** Reports agent-side spans (see `buildSpan`) into the shared trace. Safe to retry: duplicates are ignored. */\n reportSpans(spans: AgentSpan[] | ReportSpansRequest, opts?: RequestOptions): Promise<ReportSpansResult> {\n const body: ReportSpansRequest = Array.isArray(spans) ? { spans } : spans;\n return this.call({ method: 'POST', base: 'gateway', path: '/v1/traces/spans', body, idempotent: true }, opts);\n }\n\n /**\n * Runs simulation scenarios (nothing is executed). With `failOnMismatch: true`, a failed or errored run\n * throws `SimulationFailedError` whose `run` is the full typed result.\n */\n runSimulation(request: SimulationRunRequest, opts?: RequestOptions): Promise<SimulationRun> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/simulations/run', body: request, idempotent: request.persist === false, bodyError: simulationFailure }, opts);\n }\n\n // ─── Session auth (users) ───────────────────────────────────────────────────\n /** Logs a user in (works on an `unauthenticated()` client). The refresh token is returned in the body. */\n login(request: LoginRequest, opts?: RequestOptions): Promise<LoginResult> {\n return this.callAnonymous({ method: 'POST', base: 'api', path: '/v1/auth/login', body: { ...request, refreshTokenDelivery: 'body' }, idempotent: false }, opts);\n }\n\n /** Exchanges a refresh token for new tokens. The refresh token rotates: persist the returned one. Never retried (except 429). */\n refreshSession(refreshToken: string, opts?: RequestOptions): Promise<SessionTokens> {\n return this.callAnonymous({ method: 'POST', base: 'api', path: '/v1/auth/refresh', body: { refreshToken }, idempotent: false, neverRetry: true }, opts);\n }\n\n /** Revokes the current user session. */\n logout(opts?: RequestOptions): Promise<void> {\n return this.callVoid({ method: 'POST', base: 'api', path: '/v1/auth/logout', idempotent: false }, opts);\n }\n\n /** The authenticated principal, its organizations and effective permissions. */\n me(opts?: RequestOptions): Promise<Me> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/auth/me', idempotent: true }, opts);\n }\n\n // ─── Policies ───────────────────────────────────────────────────────────────\n /** A policy with its versions, latest version and tests. */\n getPolicy(id: string, opts?: RequestOptions): Promise<PolicyDetail> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/policies/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Creates a policy (draft version 1) from GSL source or a template. */\n createPolicy(request: CreatePolicyRequest, opts?: RequestOptions): Promise<PolicyVersionResult> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/policies', body: request, idempotent: false }, opts);\n }\n\n /** Saves a new version. Not retried on 5xx/network errors: every call appends a version. */\n updatePolicy(id: string, request: UpdatePolicyRequest, opts?: RequestOptions): Promise<PolicyVersionResult> {\n return this.call({ method: 'PUT', base: 'api', path: `/v1/policies/${seg(id)}`, body: request, idempotent: false }, opts);\n }\n\n /** Archives a policy (stops enforcing it). */\n deletePolicy(id: string, opts?: RequestOptions): Promise<void> {\n return this.callVoid({ method: 'DELETE', base: 'api', path: `/v1/policies/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Validates, lints and formats GSL source. */\n validatePolicy(source: string, opts?: RequestOptions): Promise<PolicyValidation> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/policies/validate', body: { source }, idempotent: true }, opts);\n }\n\n /** One immutable policy version. */\n getPolicyVersion(id: string, versionId: string, opts?: RequestOptions): Promise<PolicyVersion> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/policies/${seg(id)}/versions/${seg(versionId)}`, idempotent: true }, opts);\n }\n\n /** Semantic and unified diff between two versions. */\n diffPolicyVersions(id: string, from: string, to: string, opts?: RequestOptions): Promise<PolicyDiff> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/policies/${seg(id)}/diff`, query: { from, to }, idempotent: true }, opts);\n }\n\n /** Deploy and rollback history. */\n listPolicyDeployments(id: string, opts?: RequestOptions): Promise<PolicyDeploymentList> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/policies/${seg(id)}/deployments`, idempotent: true }, opts);\n }\n\n /**\n * Deploys a version (default: latest). When tests fail or blocking conflicts exist the server answers\n * 412 with the deploy report; it is returned as a result with `deployed: false`.\n */\n deployPolicy(id: string, request: DeployPolicyRequest = {}, opts?: RequestOptions): Promise<PolicyDeployResult> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/policies/${seg(id)}/deploy`, body: request, idempotent: false, terminalBody: isDeployReport }, opts);\n }\n\n /** Rolls back to a version (default: the previously deployed one). */\n rollbackPolicy(id: string, request: RollbackPolicyRequest = {}, opts?: RequestOptions): Promise<PolicyRollbackResult> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/policies/${seg(id)}/rollback`, body: request, idempotent: false }, opts);\n }\n\n /** Adds one test case. */\n addPolicyTest(id: string, test: PolicyTestCase, opts?: RequestOptions): Promise<PolicyTest> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/policies/${seg(id)}/tests`, body: test, idempotent: false }, opts);\n }\n\n /** Replaces the whole test suite atomically (policy-as-code sync). */\n replacePolicyTests(id: string, tests: PolicyTestCase[], opts?: RequestOptions): Promise<PolicyTestList> {\n return this.call({ method: 'PUT', base: 'api', path: `/v1/policies/${seg(id)}/tests`, body: { tests }, idempotent: true }, opts);\n }\n\n /** Deletes one test case. */\n deletePolicyTest(id: string, testId: string, opts?: RequestOptions): Promise<void> {\n return this.callVoid({ method: 'DELETE', base: 'api', path: `/v1/policies/${seg(id)}/tests/${seg(testId)}`, idempotent: true }, opts);\n }\n\n /** Runs the policy's tests against a version (default: latest). */\n runPolicyTests(id: string, versionId?: string, opts?: RequestOptions): Promise<PolicyTestRun> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/policies/${seg(id)}/tests/run`, body: versionId ? { versionId } : {}, idempotent: true }, opts);\n }\n\n /** Evaluates requests against deployed vs candidate policies. */\n simulatePolicies(request: PolicySimulateRequest, opts?: RequestOptions): Promise<PolicySimulation> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/policies/simulate', body: request, idempotent: true }, opts);\n }\n\n // ─── Agents & credentials ───────────────────────────────────────────────────\n /** Registers an agent; with `credential`, its client secret is returned once in `credential.clientSecret`. */\n createAgent(request: RegisterAgentRequest, opts?: RequestOptions): Promise<RegisteredAgent> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/agents', body: request, idempotent: false }, opts);\n }\n\n /** Updates agent metadata. */\n updateAgent(id: string, request: UpdateAgentRequest, opts?: RequestOptions): Promise<Agent> {\n return this.call({ method: 'PATCH', base: 'api', path: `/v1/agents/${seg(id)}`, body: request, idempotent: false }, opts);\n }\n\n /** Activates, suspends, disables or quarantines an agent. */\n setAgentStatus(id: string, request: AgentStatusRequest, opts?: RequestOptions): Promise<Agent> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/agents/${seg(id)}/status`, body: request, idempotent: false }, opts);\n }\n\n /** Deletes an agent. */\n deleteAgent(id: string, opts?: RequestOptions): Promise<void> {\n return this.callVoid({ method: 'DELETE', base: 'api', path: `/v1/agents/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Credential metadata of an agent (never secrets). */\n listAgentCredentials(id: string, opts?: RequestOptions): Promise<AgentCredentialList> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/agents/${seg(id)}/credentials`, idempotent: true }, opts);\n }\n\n /** Issues an agent credential; the client secret is returned once. */\n createAgentCredential(id: string, request: CreateCredentialRequest = {}, opts?: RequestOptions): Promise<IssuedCredential> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/agents/${seg(id)}/credentials`, body: request, idempotent: false }, opts);\n }\n\n /** Rotates a credential; the previous one keeps working until `previous.graceUntil`. */\n rotateCredential(credentialId: string, request: RotateCredentialRequest = {}, opts?: RequestOptions): Promise<RotatedCredential> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/credentials/${seg(credentialId)}/rotate`, body: request, idempotent: false }, opts);\n }\n\n /** Revokes a credential immediately (idempotent). */\n revokeCredential(credentialId: string, reason?: string, opts?: RequestOptions): Promise<AgentCredential> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/credentials/${seg(credentialId)}/revoke`, body: reason !== undefined ? { reason } : {}, idempotent: true }, opts);\n }\n\n // ─── Secrets (values are write-only) ────────────────────────────────────────\n /** Stores a secret. The value is never returned by the API and never logged by the SDK. */\n createSecret(request: CreateSecretRequest, opts?: RequestOptions): Promise<CreatedSecret> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/secrets', body: request, idempotent: false }, opts);\n }\n\n /** Secret metadata and masks. */\n listSecrets(params: ListSecretsParams = {}, opts?: RequestOptions): Promise<SecretList> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/secrets', query: { ...params }, idempotent: true }, opts);\n }\n\n /** One secret's metadata and version history (never the value). */\n getSecret(id: string, opts?: RequestOptions): Promise<Secret> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/secrets/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Updates secret metadata, access policy, expiry, rotation policy or status. */\n updateSecret(id: string, request: UpdateSecretRequest, opts?: RequestOptions): Promise<Secret> {\n return this.call({ method: 'PATCH', base: 'api', path: `/v1/secrets/${seg(id)}`, body: request, idempotent: false }, opts);\n }\n\n /** Writes a new version (a value, or `generate`). */\n rotateSecret(id: string, request: RotateSecretRequest, opts?: RequestOptions): Promise<RotatedSecret> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/secrets/${seg(id)}/rotate`, body: request, idempotent: false }, opts);\n }\n\n /** Revokes one version or the whole secret. */\n revokeSecret(id: string, request: RevokeSecretRequest = {}, opts?: RequestOptions): Promise<RevokeSecretResult> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/secrets/${seg(id)}/revoke`, body: request, idempotent: false }, opts);\n }\n\n /** Deletes a secret. */\n deleteSecret(id: string, opts?: RequestOptions): Promise<void> {\n return this.callVoid({ method: 'DELETE', base: 'api', path: `/v1/secrets/${seg(id)}`, idempotent: true }, opts);\n }\n\n // ─── Connectors & connections ───────────────────────────────────────────────\n /** The connector catalog (actions, schemas, risk metadata, auth methods). */\n listConnectors(opts?: RequestOptions): Promise<ConnectorList> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/connectors', idempotent: true }, opts);\n }\n\n /** One connector of the catalog. */\n getConnector(key: string, opts?: RequestOptions): Promise<Connector> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/connectors/${seg(key)}`, idempotent: true }, opts);\n }\n\n /** Installed connections. */\n listConnections(params: ListConnectionsParams = {}, opts?: RequestOptions): Promise<ConnectionList> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/connections', query: { ...params }, idempotent: true }, opts);\n }\n\n /** One connection with its connector description and effective allowed hosts. */\n getConnection(id: string, opts?: RequestOptions): Promise<Connection> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/connections/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Installs a connector into a project. */\n createConnection(request: CreateConnectionRequest, opts?: RequestOptions): Promise<Connection> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/connections', body: request, idempotent: false }, opts);\n }\n\n /** Updates a connection. */\n updateConnection(id: string, request: UpdateConnectionRequest, opts?: RequestOptions): Promise<Connection> {\n return this.call({ method: 'PATCH', base: 'api', path: `/v1/connections/${seg(id)}`, body: request, idempotent: false }, opts);\n }\n\n /** Deletes a connection. */\n deleteConnection(id: string, opts?: RequestOptions): Promise<void> {\n return this.callVoid({ method: 'DELETE', base: 'api', path: `/v1/connections/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Runs the connection health check. */\n checkConnectionHealth(id: string, opts?: RequestOptions): Promise<ConnectionHealth> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/connections/${seg(id)}/health`, idempotent: true }, opts);\n }\n\n /** Begins an OAuth installation (authorization code + PKCE); redirect the user to `authorizationUrl`. */\n startConnectionOAuth(id: string, request: OAuthStartRequest, opts?: RequestOptions): Promise<OAuthStartResult> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/connections/${seg(id)}/oauth/start`, body: request, idempotent: false }, opts);\n }\n\n /** Completes an OAuth installation with the `state` and `code` from the redirect. */\n completeConnectionOAuth(request: OAuthCallbackRequest, opts?: RequestOptions): Promise<OAuthInstallResult> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/connections/oauth/callback', body: request, idempotent: false }, opts);\n }\n\n /** Installs with the OAuth client-credentials grant (machine-to-machine). */\n installClientCredentials(id: string, request: ClientCredentialsInstallRequest, opts?: RequestOptions): Promise<OAuthInstallResult> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/connections/${seg(id)}/oauth/client-credentials`, body: request, idempotent: false }, opts);\n }\n\n /** Installs with the RFC 7523 JWT-bearer grant (e.g. a Google service account). */\n installJwtBearer(id: string, request: JwtBearerInstallRequest, opts?: RequestOptions): Promise<OAuthInstallResult> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/connections/${seg(id)}/oauth/jwt-bearer`, body: request, idempotent: false }, opts);\n }\n\n // ─── Audit ──────────────────────────────────────────────────────────────────\n /** Searches audit events (newest first); with `afterSeq`, tails the events after that sequence number (oldest first). */\n searchAudit(params: AuditSearchParams = {}, opts?: RequestOptions): Promise<AuditPage> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/audit/events', query: { ...params }, idempotent: true }, opts);\n }\n\n /** One audit event. */\n getAuditEvent(id: string, opts?: RequestOptions): Promise<AuditEvent> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/audit/events/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Exports audit events; resolves to the raw body (ndjson by default, csv or json). */\n exportAudit(params: AuditExportParams = {}, opts?: RequestOptions): Promise<string> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/audit/export', query: { ...params }, idempotent: true, responseType: 'text' }, opts);\n }\n\n /** Verifies the integrity of the audit hash chain. */\n verifyAudit(request: VerifyAuditRequest = {}, opts?: RequestOptions): Promise<AuditVerification> {\n return this.call({ method: 'POST', base: 'api', path: '/v1/audit/verify', body: request, idempotent: true }, opts);\n }\n\n // ─── Approvals (reviewers) ──────────────────────────────────────────────────\n /** Full approval record (control plane): steps, decisions, comments, history and `canDecide`. */\n getApprovalDetails(id: string, opts?: RequestOptions): Promise<Approval> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/approvals/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Approves or rejects; `snapshotHash` must be the hash of the request snapshot the reviewer saw. */\n decideApproval(id: string, request: DecideApprovalRequest, opts?: RequestOptions): Promise<ApprovalDecisionResult> {\n return this.call({ method: 'POST', base: 'api', path: `/v1/approvals/${seg(id)}/decision`, body: request, idempotent: false }, opts);\n }\n\n // ─── Alerts ─────────────────────────────────────────────────────────────────\n /** Security alerts. */\n listAlerts(params: ListAlertsParams = {}, opts?: RequestOptions): Promise<AlertPage> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/alerts', query: { ...params }, idempotent: true }, opts);\n }\n\n /** One alert with its investigation context. */\n getAlert(id: string, opts?: RequestOptions): Promise<Alert> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/alerts/${seg(id)}`, idempotent: true }, opts);\n }\n\n /** Acknowledges, assigns, annotates, resolves or dismisses an alert. */\n updateAlert(id: string, request: UpdateAlertRequest, opts?: RequestOptions): Promise<Alert> {\n return this.call({ method: 'PATCH', base: 'api', path: `/v1/alerts/${seg(id)}`, body: request, idempotent: false }, opts);\n }\n\n // ─── Traces & session replay ────────────────────────────────────────────────\n /** Searches traces. */\n searchTraces(params: TraceSearchParams = {}, opts?: RequestOptions): Promise<TraceSearchResult> {\n return this.call({ method: 'GET', base: 'api', path: '/v1/traces', query: { ...params }, idempotent: true }, opts);\n }\n\n /** One trace: platform and agent spans, correlated records, timeline and performance breakdown. */\n getTrace(traceId: string, opts?: RequestOptions): Promise<Trace> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/traces/${seg(traceId)}`, idempotent: true }, opts);\n }\n\n /** Everything a principal (agent or user) did in a window, step by step. */\n replaySession(principalId: string, params: ReplayParams = {}, opts?: RequestOptions): Promise<SessionReplay> {\n return this.call({ method: 'GET', base: 'api', path: `/v1/replay/${seg(principalId)}`, query: { ...params }, idempotent: true }, opts);\n }\n}\n","import type { AgentSpan, SpanEvent, SpanKind, SpanStatus } from './generated/models.js';\n\n/** Options of {@link buildSpan} (conformance §5.1). */\nexport interface BuildSpanOptions {\n /** W3C traceparent of the enclosing span: its trace id is used and its span id becomes the parent. */\n traceparent?: string;\n /** Explicit parent span id (16 lowercase hex); wins over the traceparent's span id. */\n parentSpanId?: string;\n /** Span id to use (16 lowercase hex). Default: random. */\n spanId?: string;\n kind?: SpanKind;\n status?: SpanStatus;\n statusMessage?: string;\n attributes?: Record<string, string | number | boolean | null>;\n events?: SpanEvent[];\n}\n\nconst TRACEPARENT = /^[0-9a-f]{2}-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/;\n\nconst randomHex = (bytes: number) => {\n const b = new Uint8Array(bytes);\n globalThis.crypto.getRandomValues(b);\n return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n};\n\nconst ms = (t: number | Date) => (t instanceof Date ? t.getTime() : t);\n\n/**\n * Builds an agent-side span (LLM call, planning step, tool selection) for {@link GebSecure.reportSpans}.\n * With the `traceparent` of the current trace, the span joins the platform's spans for that trace.\n *\n * ```ts\n * const start = Date.now();\n * const answer = await llm.complete(prompt);\n * await gs.reportSpans([buildSpan('llm.complete', start, Date.now(), { traceparent, attributes: { model: 'x' } })]);\n * ```\n */\nexport function buildSpan(name: string, start: number | Date, end: number | Date, options: BuildSpanOptions = {}): AgentSpan {\n const parent = options.traceparent ? TRACEPARENT.exec(options.traceparent) : null;\n const startMs = ms(start);\n const span: AgentSpan = {\n traceId: parent?.[1] ?? randomHex(16),\n spanId: options.spanId ?? randomHex(8),\n name,\n startTime: new Date(startMs).toISOString(),\n durationMs: Math.max(0, ms(end) - startMs),\n };\n const parentSpanId = options.parentSpanId ?? parent?.[2];\n if (parentSpanId) span.parentSpanId = parentSpanId;\n if (options.kind) span.kind = options.kind;\n if (options.status) span.status = options.status;\n if (options.statusMessage !== undefined) span.statusMessage = options.statusMessage;\n if (options.attributes) span.attributes = options.attributes;\n if (options.events) span.events = options.events;\n return span;\n}\n\n/** The W3C traceparent that makes subsequent calls children of `span`. */\nexport function traceparentOf(span: Pick<AgentSpan, 'traceId' | 'spanId'>): string {\n return `00-${span.traceId}-${span.spanId}-01`;\n}\n","// Code generated by sdks/scripts/generate-models.mjs. DO NOT EDIT.\n// Source: docs/openapi (gateway 0.1.0, api 0.1.0) + sdks/spec/overlay.json\n/* eslint-disable */\n\n/** Agent lifecycle status. Unknown future values are preserved as plain strings. */\nexport const AgentStatus = {\n ACTIVE: 'active',\n SUSPENDED: 'suspended',\n DISABLED: 'disabled',\n QUARANTINED: 'quarantined',\n} as const;\nexport type AgentStatus = (typeof AgentStatus)[keyof typeof AgentStatus] | (string & {});\n\n/** Security alert lifecycle status. Unknown future values are preserved as plain strings. */\nexport const AlertStatus = {\n OPEN: 'open',\n ACKNOWLEDGED: 'acknowledged',\n INVESTIGATING: 'investigating',\n RESOLVED: 'resolved',\n DISMISSED: 'dismissed',\n} as const;\nexport type AlertStatus = (typeof AlertStatus)[keyof typeof AlertStatus] | (string & {});\n\n/** Approval request status. Unknown future values are preserved as plain strings. */\nexport const ApprovalStatus = {\n PENDING: 'pending',\n APPROVED: 'approved',\n REJECTED: 'rejected',\n EXPIRED: 'expired',\n CANCELLED: 'cancelled',\n CONSUMED: 'consumed',\n} as const;\nexport type ApprovalStatus = (typeof ApprovalStatus)[keyof typeof ApprovalStatus] | (string & {});\n\n/** An approver's verdict. Unknown future values are preserved as plain strings. */\nexport const ApprovalVerdict = {\n APPROVE: 'approve',\n REJECT: 'reject',\n} as const;\nexport type ApprovalVerdict = (typeof ApprovalVerdict)[keyof typeof ApprovalVerdict] | (string & {});\n\n/** Where inspected content came from (determines its trust level). Unknown future values are preserved as plain strings. */\nexport const ContentSource = {\n PROMPT: 'prompt',\n WEB: 'web',\n EMAIL: 'email',\n DOCUMENT: 'document',\n RAG: 'rag',\n MCP_RESPONSE: 'mcp_response',\n TOOL_OUTPUT: 'tool_output',\n} as const;\nexport type ContentSource = (typeof ContentSource)[keyof typeof ContentSource] | (string & {});\n\n/** Authorization decision. Unknown future values are preserved as plain strings. */\nexport const Decision = {\n ALLOW: 'ALLOW',\n DENY: 'DENY',\n APPROVAL_REQUIRED: 'APPROVAL_REQUIRED',\n} as const;\nexport type Decision = (typeof Decision)[keyof typeof Decision] | (string & {});\n\n/** Scopes that may be delegated to another agent. Unknown future values are preserved as plain strings. */\nexport const DelegationScope = {\n AUTHORIZE: 'authorize',\n EXECUTE: 'execute',\n MCP_CONNECT: 'mcp:connect',\n SECRETS_USE: 'secrets:use',\n BROWSER_USE: 'browser:use',\n DATABASE_USE: 'database:use',\n DELEGATIONS_MANAGE: 'delegations:manage',\n} as const;\nexport type DelegationScope = (typeof DelegationScope)[keyof typeof DelegationScope] | (string & {});\n\n/** DLP enforcement action. Unknown future values are preserved as plain strings. */\nexport const DlpAction = {\n ALLOW: 'ALLOW',\n MASK: 'MASK',\n REDACT: 'REDACT',\n BLOCK: 'BLOCK',\n REQUIRE_APPROVAL: 'REQUIRE_APPROVAL',\n} as const;\nexport type DlpAction = (typeof DlpAction)[keyof typeof DlpAction] | (string & {});\n\n/** Direction of data flow for DLP. Unknown future values are preserved as plain strings. */\nexport const DlpDirection = {\n INBOUND: 'inbound',\n OUTBOUND: 'outbound',\n} as const;\nexport type DlpDirection = (typeof DlpDirection)[keyof typeof DlpDirection] | (string & {});\n\n/** Execution mode. Unknown future values are preserved as plain strings. */\nexport const ExecuteMode = {\n SYNC: 'sync',\n ASYNC: 'async',\n} as const;\nexport type ExecuteMode = (typeof ExecuteMode)[keyof typeof ExecuteMode] | (string & {});\n\n/** Execution lifecycle status. Unknown future values are preserved as plain strings. */\nexport const ExecutionStatus = {\n PENDING: 'pending',\n RUNNING: 'running',\n SUCCEEDED: 'succeeded',\n FAILED: 'failed',\n DENIED: 'denied',\n AWAITING_APPROVAL: 'awaiting_approval',\n CANCELLED: 'cancelled',\n CANCELLING: 'cancelling',\n SIMULATED: 'simulated',\n} as const;\nexport type ExecutionStatus = (typeof ExecutionStatus)[keyof typeof ExecutionStatus] | (string & {});\n\n/** Prompt-injection severity level. Unknown future values are preserved as plain strings. */\nexport const InjectionLevel = {\n NONE: 'none',\n LOW: 'low',\n MEDIUM: 'medium',\n HIGH: 'high',\n CRITICAL: 'critical',\n} as const;\nexport type InjectionLevel = (typeof InjectionLevel)[keyof typeof InjectionLevel] | (string & {});\n\n/** Risk level. Unknown future values are preserved as plain strings. */\nexport const RiskLevel = {\n LOW: 'low',\n MEDIUM: 'medium',\n HIGH: 'high',\n CRITICAL: 'critical',\n} as const;\nexport type RiskLevel = (typeof RiskLevel)[keyof typeof RiskLevel] | (string & {});\n\n/** Risk engine recommendation. Unknown future values are preserved as plain strings. */\nexport const RiskRecommendation = {\n ALLOW: 'allow',\n APPROVAL_REQUIRED: 'approval_required',\n DENY: 'deny',\n} as const;\nexport type RiskRecommendation = (typeof RiskRecommendation)[keyof typeof RiskRecommendation] | (string & {});\n\n/** Agent risk tier. Unknown future values are preserved as plain strings. */\nexport const RiskTier = {\n LOW: 'low',\n STANDARD: 'standard',\n ELEVATED: 'elevated',\n CRITICAL: 'critical',\n} as const;\nexport type RiskTier = (typeof RiskTier)[keyof typeof RiskTier] | (string & {});\n\n/** Vault secret type. Unknown future values are preserved as plain strings. */\nexport const SecretType = {\n API_KEY: 'api_key',\n OAUTH_TOKEN: 'oauth_token',\n DATABASE: 'database',\n CERTIFICATE: 'certificate',\n CLOUD: 'cloud',\n SSH_KEY: 'ssh_key',\n GENERIC: 'generic',\n} as const;\nexport type SecretType = (typeof SecretType)[keyof typeof SecretType] | (string & {});\n\n/** Outcome of a simulation run. Unknown future values are preserved as plain strings. */\nexport const SimulationStatus = {\n PASSED: 'passed',\n FAILED: 'failed',\n ERROR: 'error',\n} as const;\nexport type SimulationStatus = (typeof SimulationStatus)[keyof typeof SimulationStatus] | (string & {});\n\n/** OpenTelemetry span kind. Unknown future values are preserved as plain strings. */\nexport const SpanKind = {\n SERVER: 'server',\n CLIENT: 'client',\n INTERNAL: 'internal',\n PRODUCER: 'producer',\n CONSUMER: 'consumer',\n} as const;\nexport type SpanKind = (typeof SpanKind)[keyof typeof SpanKind] | (string & {});\n\n/** Span status. Unknown future values are preserved as plain strings. */\nexport const SpanStatus = {\n UNSET: 'unset',\n OK: 'ok',\n ERROR: 'error',\n} as const;\nexport type SpanStatus = (typeof SpanStatus)[keyof typeof SpanStatus] | (string & {});\n\n/** Credential metadata of an agent (never the secret). */\nexport interface AgentCredential {\n id: string;\n type: string;\n name?: string;\n status?: string;\n scopes?: Array<string>;\n expiresAt?: string | null;\n graceUntil?: string | null;\n lastUsedAt?: string | null;\n createdAt?: string;\n revokedAt?: string | null;\n principalType?: string;\n principalId?: string;\n publicJwk?: Record<string, unknown> | null;\n rotatedFrom?: string | null;\n revokedReason?: string | null;\n createdBy?: string | null;\n}\n\n/** An agent identity (GET /v1/agents, GET /v1/agents/{id}). */\nexport interface Agent {\n id: string;\n name: string;\n description?: string;\n status: AgentStatus;\n statusReason?: string | null;\n projectId?: string;\n environmentId?: string;\n applicationId?: string | null;\n ownerUserId?: string | null;\n ownerTeamId?: string | null;\n ownerEmail?: string | null;\n framework?: string | null;\n model?: string | null;\n riskTier?: string;\n tags?: Array<string>;\n metadata?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n lastSeenAt?: string | null;\n credentials?: Array<AgentCredential>;\n}\n\n/** Response of GET /v1/agents/{id}/credentials. */\nexport interface AgentCredentialList {\n data: Array<AgentCredential>;\n}\n\n/** Response of GET /v1/agents. */\nexport interface AgentPage {\n data: Array<Agent>;\n nextCursor?: string | null;\n}\n\n/** */\nexport interface SpanEvent {\n name: string;\n time: string;\n /** Default: {}. */\n attributes?: Record<string, unknown>;\n}\n\n/** */\nexport interface AgentSpan {\n traceId: string;\n spanId: string;\n parentSpanId?: string | null;\n name: string;\n /** Default: \"internal\". */\n kind?: SpanKind;\n startTime: string;\n durationMs: number;\n /** Default: \"unset\". */\n status?: SpanStatus;\n statusMessage?: string | null;\n /** Default: {}. */\n attributes?: Record<string, unknown>;\n /** Default: []. */\n events?: Array<SpanEvent>;\n}\n\n/** Input to POST /v1/agents/{id}/status. (api: POST /v1/agents/{id}/status) */\nexport interface AgentStatusRequest {\n status: AgentStatus;\n reason?: string;\n}\n\n/** A security alert (GET /v1/alerts, GET/PATCH /v1/alerts/{id}). */\nexport interface Alert {\n id: string;\n projectId?: string | null;\n environmentId?: string | null;\n kind: string;\n severity: RiskLevel;\n score?: number;\n title?: string;\n summary?: string;\n principalType?: string | null;\n principalId?: string | null;\n status: AlertStatus;\n assigneeId?: string | null;\n dedupeKey?: string;\n occurrences?: number;\n evidence?: Array<unknown>;\n response?: Record<string, unknown>;\n resolution?: string | null;\n firstSeenAt?: string;\n lastSeenAt?: string;\n acknowledgedAt?: string | null;\n resolvedAt?: string | null;\n createdAt?: string;\n updatedAt?: string;\n notes?: Array<unknown>;\n investigation?: Record<string, unknown>;\n}\n\n/** Response of GET /v1/alerts. */\nexport interface AlertPage {\n data: Array<Alert>;\n nextCursor?: string | null;\n}\n\n/** An approval request. GET {gateway}/v1/approvals/{id} returns the agent-facing subset; the control-plane API returns the full record. */\nexport interface Approval {\n id: string;\n status: ApprovalStatus;\n action?: string;\n resource?: string;\n summary?: string;\n reason?: string;\n snapshotHash?: string;\n agentId?: string | null;\n projectId?: string;\n environmentId?: string;\n requesterType?: string;\n requesterId?: string;\n riskScore?: number | null;\n riskLevel?: string | null;\n expiresAt?: string;\n resolvedAt?: string | null;\n resolvedBy?: string | null;\n resolutionComment?: string | null;\n executionId?: string | null;\n createdAt?: string;\n signatureValid?: boolean;\n steps?: Array<unknown>;\n decisions?: Array<unknown>;\n comments?: Array<unknown>;\n history?: Array<unknown>;\n canDecide?: boolean;\n}\n\n/** Response of POST /v1/approvals/{id}/decision. */\nexport interface ApprovalDecisionResult {\n approvalId: string;\n status: ApprovalStatus;\n stepIndex?: number;\n}\n\n/** Response of GET /v1/approvals. */\nexport interface ApprovalPage {\n data: Array<Approval>;\n nextCursor?: string | null;\n}\n\n/** Approval request associated with a decision. */\nexport interface ApprovalRef {\n id: string;\n status: ApprovalStatus;\n expiresAt: string;\n snapshotHash: string;\n url: string;\n created: boolean;\n}\n\n/** An approval requirement contributed by a policy or risk threshold. */\nexport interface ApprovalRequirement {\n policyId: string;\n policyName: string;\n approvers?: Array<unknown>;\n min?: number;\n mode?: string;\n expiresMs?: number | null;\n}\n\n/** A broken link in the audit hash chain. */\nexport interface AuditChainError {\n seq: number;\n id?: string;\n problem?: string;\n}\n\n/** One tamper-evident audit record. */\nexport interface AuditEvent {\n id: string;\n seq: number;\n occurredAt?: string;\n category?: string;\n action?: string;\n outcome?: string;\n actorType?: string;\n actorId?: string | null;\n onBehalfOf?: string | null;\n agentId?: string | null;\n sessionId?: string | null;\n projectId?: string | null;\n environmentId?: string | null;\n resourceType?: string | null;\n resourceId?: string | null;\n decision?: string | null;\n policyIds?: Array<string>;\n riskScore?: number | null;\n approvalId?: string | null;\n executionId?: string | null;\n argsHash?: string | null;\n requestId?: string | null;\n traceId?: string | null;\n ip?: string | null;\n userAgent?: string | null;\n details?: Record<string, unknown>;\n prevHash?: string;\n hash?: string;\n}\n\n/** Query parameters for GET /v1/audit/export. (api: GET /v1/audit/export) */\nexport interface AuditExportParams {\n from?: string;\n to?: string;\n category?: string;\n action?: string;\n outcome?: string;\n actorId?: string;\n agentId?: string;\n resourceType?: string;\n resourceId?: string;\n projectId?: string;\n environmentId?: string;\n decision?: string;\n traceId?: string;\n approvalId?: string;\n executionId?: string;\n minRisk?: number;\n q?: string;\n afterSeq?: number;\n /** Default: 100. */\n limit?: number;\n cursor?: string;\n /** Default: \"ndjson\". */\n format?: string;\n}\n\n/** Response of GET /v1/audit/events. */\nexport interface AuditPage {\n data: Array<AuditEvent>;\n nextCursor?: string | null;\n}\n\n/** Query parameters for GET /v1/audit/events (afterSeq = tail: records after that sequence number, oldest first). (api: GET /v1/audit/events) */\nexport interface AuditSearchParams {\n from?: string;\n to?: string;\n category?: string;\n action?: string;\n outcome?: string;\n actorId?: string;\n agentId?: string;\n resourceType?: string;\n resourceId?: string;\n projectId?: string;\n environmentId?: string;\n decision?: string;\n traceId?: string;\n approvalId?: string;\n executionId?: string;\n minRisk?: number;\n q?: string;\n afterSeq?: number;\n /** Default: 100. */\n limit?: number;\n cursor?: string;\n}\n\n/** Response of POST /v1/audit/verify. */\nexport interface AuditVerification {\n valid: boolean;\n checked: number;\n firstSeq?: number | null;\n lastSeq?: number | null;\n headMatches?: boolean;\n errors?: Array<AuditChainError>;\n}\n\n/** A user account. */\nexport interface AuthUser {\n id: string;\n email?: string;\n name?: string;\n createdAt?: string;\n}\n\n/** Error for one entry of a batch authorization. */\nexport interface BatchError {\n code: string;\n message: string;\n}\n\n/** Environment the request was evaluated in. */\nexport interface EnvironmentRef {\n id: string;\n slug: string;\n tier: string;\n}\n\n/** One policy considered during evaluation. */\nexport interface TraceEntry {\n policyId: string;\n versionId?: string | null;\n name: string;\n effect: string;\n source?: string;\n scope?: unknown;\n outcome: string;\n detail?: string;\n}\n\n/** Why the decision was made. */\nexport interface Explanation {\n trace: Array<TraceEntry>;\n approvals: Array<ApprovalRequirement>;\n grantingPolicyId?: string | null;\n candidates: number;\n policyDecision: Decision;\n}\n\n/** A rate/amount limit of the granting policy and its current usage. */\nexport interface LimitState {\n policyId: string;\n key: string;\n measure: string;\n amount: number;\n max: number;\n windowMs: number;\n subject?: string;\n used: number;\n remaining: number;\n}\n\n/** The principal the decision applies to. */\nexport interface PrincipalRef {\n type: string;\n id: string;\n}\n\n/** One explainable contribution to a risk score. */\nexport interface RiskSignal {\n category: string;\n code: string;\n points: number;\n reason: string;\n}\n\n/** Risk thresholds in effect. */\nexport interface RiskThresholds {\n approvalAbove: number;\n denyAbove: number;\n}\n\n/** Risk assessment attached to a decision. */\nexport interface Risk {\n score: number;\n level: RiskLevel;\n recommendation: RiskRecommendation;\n signals: Array<RiskSignal>;\n thresholds: RiskThresholds;\n}\n\n/** One entry of POST /v1/authorize/batch: either a decision (all AuthorizeResult fields) or an error. */\nexport interface AuthorizeBatchEntry {\n decision?: Decision;\n decisionId?: string;\n reason?: string;\n risk?: Risk;\n approval?: ApprovalRef | null;\n explanation?: Explanation;\n limits?: Array<LimitState>;\n snapshotHash?: string;\n environment?: EnvironmentRef;\n principal?: PrincipalRef;\n dryRun?: boolean;\n evaluatedAt?: string;\n durationMs?: number;\n error?: BatchError;\n}\n\n/** */\nexport interface OnBehalfOf {\n agentId: string;\n}\n\n/** Input to POST /v1/authorize. (gateway: POST /v1/authorize) */\nexport interface AuthorizeRequest {\n action: string;\n resource: string;\n /** Default: {}. */\n resourceAttributes?: Record<string, unknown>;\n /** Default: {}. */\n context?: Record<string, unknown>;\n environmentId?: string;\n onBehalfOf?: OnBehalfOf;\n approvalId?: string;\n /** Default: false. */\n dryRun?: boolean;\n execution?: Record<string, unknown> | null;\n}\n\n/** Input to POST /v1/authorize/batch (1-100 requests). (gateway: POST /v1/authorize/batch) */\nexport interface AuthorizeBatchRequest {\n requests: Array<AuthorizeRequest>;\n}\n\n/** Response of POST /v1/authorize/batch (results are in request order). */\nexport interface AuthorizeBatchResult {\n results: Array<AuthorizeBatchEntry>;\n}\n\n/** Response of POST /v1/authorize. */\nexport interface AuthorizeResult {\n decision: Decision;\n decisionId: string;\n reason: string;\n risk: Risk;\n approval?: ApprovalRef | null;\n explanation?: Explanation;\n limits?: Array<LimitState>;\n snapshotHash?: string;\n environment?: EnvironmentRef;\n principal?: PrincipalRef;\n dryRun?: boolean;\n evaluatedAt?: string;\n durationMs?: number;\n}\n\n/** Response of POST /v1/executions/{id}/cancel. */\nexport interface CancelExecutionResult {\n executionId: string;\n status: ExecutionStatus;\n}\n\n/** Input to POST /v1/connections/{id}/oauth/client-credentials. (api: POST /v1/connections/{id}/oauth/client-credentials) */\nexport interface ClientCredentialsInstallRequest {\n clientId: string;\n clientSecret: string;\n scopes?: Array<string>;\n}\n\n/** An action a connector exposes. */\nexport interface ConnectorAction {\n name: string;\n action: string;\n title?: string;\n description?: string;\n risk?: unknown;\n idempotent?: boolean;\n input?: Record<string, unknown>;\n output?: Record<string, unknown> | null;\n}\n\n/** A connector in the catalog (GET /v1/connectors, GET /v1/connectors/{key}). */\nexport interface Connector {\n key: string;\n name: string;\n version?: string;\n description?: string;\n category?: string;\n homepage?: string | null;\n baseUrl?: string | null;\n allowedHosts?: Array<string>;\n publicHosts?: Array<string>;\n auth?: Array<unknown>;\n config?: Record<string, unknown>;\n resources?: unknown;\n securityTemplate?: unknown;\n actions?: Array<ConnectorAction>;\n}\n\n/** A connector installed into a project (signing secrets are never returned, except signingSecret once on create). */\nexport interface Connection {\n id: string;\n projectId?: string;\n environmentId?: string | null;\n connectorKey?: string;\n connectorVersion?: string;\n name: string;\n description?: string;\n authType?: string;\n secretId?: string | null;\n config?: Record<string, unknown>;\n allowedHosts?: Array<string>;\n signRequests?: boolean;\n timeoutMs?: number;\n maxRetries?: number;\n status?: string;\n health?: Record<string, unknown>;\n lastHealthAt?: string | null;\n createdBy?: string | null;\n createdAt?: string;\n updatedAt?: string;\n connector?: Connector | null;\n effectiveAllowedHosts?: Array<string>;\n securityTemplate?: unknown;\n /** Request-signing secret, returned once on create when signRequests=true. */\n signingSecret?: string;\n}\n\n/** */\nexport interface ConnectionCredential {\n type: string;\n value: Record<string, unknown>;\n /** Default: {}. */\n metadata?: Record<string, unknown>;\n}\n\n/** Response of POST /v1/connections/{id}/health. */\nexport interface ConnectionHealth {\n ok: boolean;\n detail?: string;\n latencyMs?: number;\n}\n\n/** Response of GET /v1/connections. */\nexport interface ConnectionList {\n data: Array<Connection>;\n}\n\n/** Response of GET /v1/connectors. */\nexport interface ConnectorList {\n data: Array<Connector>;\n}\n\n/** Provenance of inspected content. */\nexport interface ContentProvenance {\n source: string;\n origin?: string | null;\n trust: string;\n contentHash?: string;\n retrievedAt?: string;\n}\n\n/** Input to POST /v1/connections (install a connector into a project). (api: POST /v1/connections) */\nexport interface CreateConnectionRequest {\n projectId: string;\n environmentId?: string;\n connector: string;\n name: string;\n /** Default: \"\". */\n description?: string;\n /** Default: \"none\". */\n authType?: string;\n secretId?: string;\n credential?: ConnectionCredential;\n /** Default: {}. */\n config?: Record<string, unknown>;\n /** Default: []. */\n allowedHosts?: Array<string>;\n /** Default: false. */\n signRequests?: boolean;\n /** Default: 15000. */\n timeoutMs?: number;\n /** Default: 2. */\n maxRetries?: number;\n}\n\n/** Input to POST /v1/agents/{id}/credentials. (api: POST /v1/agents/{id}/credentials) */\nexport interface CreateCredentialRequest {\n /** Default: \"client_secret\". */\n type?: string;\n /** Default: \"default\". */\n name?: string;\n publicJwk?: Record<string, unknown>;\n /** Default: []. */\n scopes?: Array<string>;\n expiresInDays?: number;\n}\n\n/** */\nexport interface DelegationConstraints {\n maxAmount?: number;\n environments?: Array<string>;\n}\n\n/** Input to POST /v1/delegations (control plane). (api: POST /v1/delegations) */\nexport interface CreateDelegationRequest {\n delegateAgentId: string;\n scopes: Array<DelegationScope>;\n /** Default: []. */\n actions?: Array<string>;\n /** Default: []. */\n resources?: Array<string>;\n /** Default: {}. */\n constraints?: DelegationConstraints;\n /** Default: \"\". */\n purpose?: string;\n /** Default: 3600. */\n expiresInSeconds?: number;\n /** Default: 3. */\n maxDepth?: number;\n}\n\n/** Policy scope: {type: org} | {type: project, projectId} | {type: environment, environmentId}. */\nexport interface PolicyScope {\n /** org, project or environment. */\n type: string;\n projectId?: string;\n environmentId?: string;\n}\n\n/** Input to POST /v1/policies (exactly one of source or templateId). (api: POST /v1/policies) */\nexport interface CreatePolicyRequest {\n name: string;\n /** Default: \"\". */\n description?: string;\n /** Default: {\"type\":\"org\"}. */\n scope?: PolicyScope;\n source?: string;\n templateId?: string;\n templateParams?: Record<string, unknown>;\n /** Default: \"Initial version\". */\n message?: string;\n /** Default: []. */\n tags?: Array<string>;\n}\n\n/** */\nexport interface SecretAccessPolicy {\n agents?: Array<string>;\n agentTags?: Array<string>;\n connectors?: Array<string>;\n actions?: Array<string>;\n environments?: Array<string>;\n}\n\n/** */\nexport interface SecretRotationPolicy {\n intervalDays?: number;\n /** Default: \"manual\". */\n strategy?: string;\n}\n\n/** Input to POST /v1/secrets. `value` is write-only: it is never returned and SDKs never log it. (api: POST /v1/secrets) */\nexport interface CreateSecretRequest {\n name: string;\n type: SecretType;\n value: Record<string, unknown>;\n /** Default: \"\". */\n description?: string;\n /** Default: {}. */\n metadata?: Record<string, unknown>;\n projectId?: string;\n environmentId?: string;\n /** Default: {}. */\n accessPolicy?: SecretAccessPolicy;\n expiresAt?: string;\n /** Default: {\"strategy\":\"manual\"}. */\n rotationPolicy?: SecretRotationPolicy;\n}\n\n/** Response of POST /v1/secrets (metadata only; the value is never echoed). */\nexport interface CreatedSecret {\n id: string;\n name: string;\n type: SecretType;\n mask?: string;\n version?: number;\n}\n\n/** Input to POST /v1/approvals/{id}/decision. snapshotHash must be the hash the approver reviewed. (api: POST /v1/approvals/{id}/decision) */\nexport interface DecideApprovalRequest {\n decision: ApprovalVerdict;\n /** Default: \"\". */\n comment?: string;\n snapshotHash: string;\n /** Default: \"console\". */\n channel?: string;\n}\n\n/** Response of POST /v1/delegations. `token` (gsd_...) is shown once; hand it to the delegate agent. */\nexport interface Delegation {\n id: string;\n token: string;\n chain?: Array<unknown>;\n depth?: number;\n maxDepth?: number;\n scopes?: Array<string>;\n actions?: Array<string>;\n resources?: Array<string>;\n expiresAt?: string;\n originatingUserId?: string | null;\n}\n\n/** Input to POST /v1/policies/{id}/deploy (default: latest version). (api: POST /v1/policies/{id}/deploy) */\nexport interface DeployPolicyRequest {\n versionId?: string;\n /** Default: \"\". */\n comment?: string;\n}\n\n/** One sensitive-data finding (masked, never the raw value). */\nexport interface DlpFinding {\n detector: string;\n category: string;\n label?: string;\n confidence?: number;\n path?: string;\n masked?: string;\n enforcement?: DlpAction;\n}\n\n/** A DLP rule that matched. */\nexport interface DlpMatchedRule {\n ruleId: string;\n name: string;\n action: DlpAction;\n findings?: number;\n}\n\n/** Input to POST /v1/dlp/scan. (gateway: POST /v1/dlp/scan) */\nexport interface DlpScanRequest {\n content: unknown;\n direction: DlpDirection;\n action?: string;\n connector?: string;\n environmentId?: string;\n dryRun?: boolean;\n}\n\n/** Response of POST /v1/dlp/scan. */\nexport interface DlpScanResult {\n action: DlpAction;\n /** Transformed payload; null when blocked. */\n content?: unknown;\n findings: Array<DlpFinding>;\n rules?: Array<DlpMatchedRule>;\n eventId?: string | null;\n dryRun?: boolean;\n}\n\n/** Input to POST /v1/execute. (gateway: POST /v1/execute) */\nexport interface ExecuteRequest {\n connection: string;\n action: string;\n /** Default: {}. */\n input?: Record<string, unknown>;\n idempotencyKey?: string;\n approvalId?: string;\n /** Default: \"sync\". */\n mode?: ExecuteMode;\n timeoutMs?: number;\n /** Default: false. */\n dryRun?: boolean;\n environmentId?: string;\n onBehalfOf?: OnBehalfOf;\n}\n\n/** Error of a failed/denied execution. */\nexport interface ExecutionError {\n code: string;\n message: string;\n upstreamStatus?: number;\n}\n\n/** Response of POST /v1/execute (HTTP 200 succeeded/simulated, 202 awaiting_approval/running, 403 denied, 502/504 failed). */\nexport interface ExecuteResult {\n executionId?: string | null;\n status: ExecutionStatus;\n decision?: Decision;\n reason?: string;\n output?: unknown;\n outputTruncated?: boolean;\n error?: ExecutionError | null;\n approval?: ApprovalRef | null;\n risk?: Risk;\n durationMs?: number;\n replayed?: boolean;\n}\n\n/** One step log line of an execution. */\nexport interface ExecutionLog {\n step: string;\n level?: string;\n message?: string;\n data?: Record<string, unknown>;\n durationMs?: number | null;\n createdAt?: string;\n}\n\n/** Response of GET /v1/executions/{id} (execution record with step logs). */\nexport interface Execution {\n id: string;\n status: ExecutionStatus;\n projectId?: string;\n environmentId?: string;\n principalType?: string;\n principalId?: string;\n connectionId?: string | null;\n connectorKey?: string;\n action?: string;\n resource?: string;\n mode?: ExecuteMode;\n decision?: Decision | null;\n decisionId?: string | null;\n approvalId?: string | null;\n riskScore?: number | null;\n idempotencyKey?: string | null;\n output?: unknown;\n outputTruncated?: boolean;\n error?: ExecutionError | null;\n attempts?: number;\n traceId?: string | null;\n createdAt?: string;\n startedAt?: string | null;\n finishedAt?: string | null;\n durationMs?: number | null;\n logs?: Array<ExecutionLog>;\n}\n\n/** Response of GET /v1/executions. */\nexport interface ExecutionPage {\n data: Array<Execution>;\n nextCursor?: string | null;\n}\n\n/** One prompt-injection rule match. */\nexport interface InjectionFinding {\n rule: string;\n category: string;\n excerpt?: string;\n}\n\n/** ML classifier contribution (when configured). */\nexport interface InjectionModelResult {\n used: boolean;\n score?: number | null;\n error?: string | null;\n}\n\n/** Prompt-injection analysis of inspected content. */\nexport interface InjectionReport {\n /** 0-100. */\n score: number;\n level: InjectionLevel;\n /** ALLOW, FLAG, SANITIZE or BLOCK. */\n action: string;\n findings: Array<InjectionFinding>;\n provenance?: ContentProvenance;\n model?: InjectionModelResult;\n detectionId?: string | null;\n tainted?: boolean;\n}\n\n/** Inbound DLP outcome of an inspection. */\nexport interface InspectDlpReport {\n action: DlpAction;\n /** Finding label -> count. */\n summary?: Record<string, unknown>;\n rules?: Array<DlpMatchedRule>;\n eventId?: string | null;\n}\n\n/** Input to POST /v1/inspect: untrusted content an agent is about to read. (gateway: POST /v1/inspect) */\nexport interface InspectRequest {\n content: unknown;\n source: ContentSource;\n origin?: string;\n /** Default: true. */\n dlp?: boolean;\n environmentId?: string;\n}\n\n/** Response of POST /v1/inspect. */\nexport interface InspectResult {\n /** Overall action: ALLOW, FLAG, SANITIZE, MASK, REDACT, REQUIRE_APPROVAL or BLOCK. */\n action: string;\n /** Content safe to hand to the model (sanitized/masked); null when blocked. */\n content?: unknown;\n injection: InjectionReport;\n dlp?: InspectDlpReport | null;\n}\n\n/** A newly issued credential. clientSecret (gsa_...) is shown ONCE (null for public_key credentials); SDKs never log it. */\nexport interface IssuedCredential {\n credential: AgentCredential;\n clientId: string;\n clientSecret?: string | null;\n}\n\n/** Input to POST /v1/connections/{id}/oauth/jwt-bearer: either serviceAccountJson (Google) or issuer + privateKeyPem. */\nexport interface JwtBearerInstallRequest {\n serviceAccountJson?: string;\n issuer?: string;\n privateKeyPem?: string;\n keyId?: string;\n subject?: string;\n audience?: string;\n scopes?: Array<string>;\n}\n\n/** Query parameters for GET /v1/agents. (api: GET /v1/agents) */\nexport interface ListAgentsParams {\n projectId?: string;\n environmentId?: string;\n status?: AgentStatus;\n ownerUserId?: string;\n tag?: string;\n q?: string;\n /** Default: 50. */\n limit?: number;\n cursor?: string;\n}\n\n/** Query parameters for GET /v1/alerts. (api: GET /v1/alerts) */\nexport interface ListAlertsParams {\n status?: AlertStatus;\n severity?: RiskLevel;\n kind?: string;\n principalId?: string;\n active?: string;\n /** Default: 50. */\n limit?: number;\n cursor?: string;\n}\n\n/** Query parameters for GET /v1/approvals. (api: GET /v1/approvals) */\nexport interface ListApprovalsParams {\n status?: ApprovalStatus;\n inbox?: boolean;\n agentId?: string;\n projectId?: string;\n /** Default: 50. */\n limit?: number;\n cursor?: string;\n}\n\n/** Query parameters for GET /v1/connections. (api: GET /v1/connections) */\nexport interface ListConnectionsParams {\n projectId?: string;\n}\n\n/** Query parameters for GET /v1/executions. (gateway: GET /v1/executions) */\nexport interface ListExecutionsParams {\n status?: string;\n principalId?: string;\n connectionId?: string;\n /** Default: 50. */\n limit?: number;\n cursor?: string;\n}\n\n/** Query parameters for GET /v1/policies. (api: GET /v1/policies) */\nexport interface ListPoliciesParams {\n projectId?: string;\n environmentId?: string;\n status?: string;\n}\n\n/** Query parameters for GET /v1/secrets. (api: GET /v1/secrets) */\nexport interface ListSecretsParams {\n projectId?: string;\n environmentId?: string;\n type?: string;\n}\n\n/** Input to POST /v1/auth/login. SDKs send refreshTokenDelivery=body. (api: POST /v1/auth/login) */\nexport interface LoginRequest {\n email: string;\n password: string;\n orgId?: string;\n /** Default: \"cookie\". */\n refreshTokenDelivery?: string;\n}\n\n/** An organization the user belongs to. */\nexport interface OrgMembership {\n orgId: string;\n role?: string;\n name?: string;\n slug?: string;\n}\n\n/** Response of POST /v1/auth/login (refreshTokenDelivery=body). */\nexport interface LoginResult {\n accessToken: string;\n tokenType?: string;\n /** Access token lifetime in seconds. */\n expiresIn: number;\n refreshToken?: string;\n refreshExpiresAt?: string;\n familyId?: string;\n sessionId?: string;\n user?: AuthUser;\n orgId?: string | null;\n orgs?: Array<OrgMembership>;\n}\n\n/** The authenticated principal. */\nexport interface MePrincipal {\n type: string;\n id: string;\n orgId?: string | null;\n orgRole?: string | null;\n projectId?: string | null;\n environmentId?: string | null;\n scopes?: Array<string>;\n}\n\n/** Response of GET /v1/auth/me. */\nexport interface Me {\n principal: MePrincipal;\n user?: AuthUser | null;\n orgs?: Array<OrgMembership>;\n permissions?: Array<string>;\n}\n\n/** Input to POST /v1/connections/oauth/callback. (api: POST /v1/connections/oauth/callback) */\nexport interface OAuthCallbackRequest {\n state: string;\n code: string;\n clientSecret?: string;\n}\n\n/** Response of the OAuth callback and the client-credentials / jwt-bearer installs. */\nexport interface OAuthInstallResult {\n connectionId: string;\n secretId: string;\n scope?: string | null;\n expiresAt?: string | null;\n}\n\n/** Input to POST /v1/connections/{id}/oauth/start (authorization code + PKCE). (api: POST /v1/connections/{id}/oauth/start) */\nexport interface OAuthStartRequest {\n redirectUri: string;\n clientId: string;\n scopes?: Array<string>;\n}\n\n/** Response of POST /v1/connections/{id}/oauth/start: send the user to authorizationUrl. */\nexport interface OAuthStartResult {\n authorizationUrl: string;\n expiresInSeconds?: number;\n}\n\n/** A policy (GET /v1/policies). */\nexport interface Policy {\n id: string;\n name: string;\n description?: string;\n status: string;\n scopeType?: string;\n scopeId?: string;\n projectId?: string | null;\n environmentId?: string | null;\n latestVersion?: number;\n activeVersion?: number | null;\n activeVersionId?: string | null;\n tags?: Array<string>;\n createdAt?: string;\n updatedAt?: string;\n}\n\n/** Result of running a policy's tests (POST /v1/policies/{id}/tests/run; also embedded in deploy reports). */\nexport interface PolicyTestRun {\n versionId?: string;\n passed: number;\n failed: number;\n total: number;\n results?: Array<unknown>;\n}\n\n/** Response of POST /v1/policies/{id}/deploy. HTTP 200 when deployed; HTTP 412 with deployed=false when failing tests or blocking conflicts prevent it (returned as a result, not an error). */\nexport interface PolicyDeployResult {\n deployed: boolean;\n deploymentId?: string;\n versionId?: string;\n tests?: PolicyTestRun;\n conflicts?: Array<unknown>;\n}\n\n/** A deploy/rollback record. */\nexport interface PolicyDeployment {\n id: string;\n policyId?: string;\n action?: string;\n fromVersionId?: string | null;\n toVersionId?: string | null;\n testsPassed?: boolean | null;\n testReport?: Record<string, unknown>;\n simulation?: Record<string, unknown>;\n comment?: string;\n actorId?: string | null;\n createdAt?: string;\n}\n\n/** Response of GET /v1/policies/{id}/deployments. */\nexport interface PolicyDeploymentList {\n data: Array<PolicyDeployment>;\n}\n\n/** A stored policy test case. */\nexport interface PolicyTest {\n id: string;\n policyId?: string;\n name: string;\n request?: Record<string, unknown>;\n expect: Decision;\n createdBy?: string | null;\n createdAt?: string;\n}\n\n/** An immutable policy version. */\nexport interface PolicyVersion {\n id: string;\n policyId?: string;\n version: number;\n source?: string;\n ast?: Record<string, unknown>;\n checksum?: string;\n message?: string;\n diagnostics?: Array<unknown>;\n authorId?: string | null;\n createdAt?: string;\n}\n\n/** Response of GET /v1/policies/{id}: the policy with its versions, latest version and tests. */\nexport interface PolicyDetail {\n id: string;\n name: string;\n description?: string;\n status: string;\n scopeType?: string;\n scopeId?: string;\n projectId?: string | null;\n environmentId?: string | null;\n latestVersion?: number;\n activeVersion?: number | null;\n activeVersionId?: string | null;\n tags?: Array<string>;\n createdAt?: string;\n updatedAt?: string;\n templateId?: string | null;\n versions?: Array<PolicyVersion>;\n latest?: PolicyVersion | null;\n tests?: Array<PolicyTest>;\n}\n\n/** A policy whose clauses changed. */\nexport interface PolicyDiffChange {\n name: string;\n fields?: Array<unknown>;\n}\n\n/** Response of GET /v1/policies/{id}/diff. */\nexport interface PolicyDiff {\n from?: number;\n to?: number;\n added?: Array<string>;\n removed?: Array<string>;\n changed?: Array<PolicyDiffChange>;\n unified?: string;\n}\n\n/** Response of GET /v1/policies. */\nexport interface PolicyList {\n data: Array<Policy>;\n}\n\n/** */\nexport interface PolicyOverride {\n policyId: string;\n versionId?: string;\n source?: string;\n}\n\n/** Response of POST /v1/policies/{id}/rollback. */\nexport interface PolicyRollbackResult {\n rolledBack: boolean;\n versionId: string;\n previousVersionId?: string | null;\n}\n\n/** */\nexport interface PolicyTestEnvironment {\n slug: string;\n tier: string;\n}\n\n/** */\nexport interface PolicyTestPrincipal {\n type: string;\n id: string;\n refs?: Array<string>;\n attributes?: Record<string, unknown>;\n}\n\n/** */\nexport interface PolicyTestRisk {\n score: number;\n level: string;\n}\n\n/** */\nexport interface RelationshipTuple {\n subject: string;\n relation: string;\n object: string;\n}\n\n/** */\nexport interface PolicySimulationCase {\n principal: PolicyTestPrincipal;\n action: string;\n resource: string;\n resourceAttributes?: Record<string, unknown>;\n context?: Record<string, unknown>;\n environment?: PolicyTestEnvironment;\n risk?: PolicyTestRisk | null;\n delegation?: Record<string, unknown> | null;\n now?: string;\n relationships?: Array<RelationshipTuple>;\n limitUsage?: Record<string, unknown>;\n expect?: Decision;\n label?: string;\n}\n\n/** Input to POST /v1/policies/simulate (deployed vs candidate policies). (api: POST /v1/policies/simulate) */\nexport interface PolicySimulateRequest {\n environmentId: string;\n /** Default: []. */\n overrides?: Array<PolicyOverride>;\n requests: Array<PolicySimulationCase>;\n}\n\n/** Decision under one policy set. */\nexport interface PolicySimulationOutcome {\n decision: Decision;\n reason?: string;\n trace?: Array<unknown>;\n approvals?: Array<unknown>;\n}\n\n/** One request of a policy simulation. */\nexport interface PolicySimulationResult {\n index?: number;\n label?: string;\n baseline: PolicySimulationOutcome;\n candidate: PolicySimulationOutcome;\n changed?: boolean;\n expected?: string | null;\n matchesExpectation?: boolean | null;\n}\n\n/** Totals of a policy simulation. */\nexport interface PolicySimulationSummary {\n total: number;\n changed?: number;\n mismatches?: number;\n byDecision?: Record<string, unknown>;\n}\n\n/** Response of POST /v1/policies/simulate. */\nexport interface PolicySimulation {\n environment?: EnvironmentRef;\n summary: PolicySimulationSummary;\n results: Array<PolicySimulationResult>;\n}\n\n/** */\nexport interface PolicyTestRequest {\n principal: PolicyTestPrincipal;\n action: string;\n resource: string;\n resourceAttributes?: Record<string, unknown>;\n context?: Record<string, unknown>;\n environment?: PolicyTestEnvironment;\n risk?: PolicyTestRisk | null;\n delegation?: Record<string, unknown> | null;\n now?: string;\n relationships?: Array<RelationshipTuple>;\n limitUsage?: Record<string, unknown>;\n}\n\n/** A policy test case (POST /v1/policies/{id}/tests, PUT /v1/policies/{id}/tests). (api: POST /v1/policies/{id}/tests) */\nexport interface PolicyTestCase {\n name: string;\n request: PolicyTestRequest;\n expect: Decision;\n}\n\n/** Response of PUT /v1/policies/{id}/tests. */\nexport interface PolicyTestList {\n data: Array<PolicyTest>;\n}\n\n/** Response of POST /v1/policies/validate. */\nexport interface PolicyValidation {\n ok: boolean;\n diagnostics?: Array<unknown>;\n conflicts?: Array<unknown>;\n formatted?: string | null;\n}\n\n/** Response of POST /v1/policies and PUT /v1/policies/{id}: the saved version. */\nexport interface PolicyVersionResult {\n id: string;\n versionId: string;\n version: number;\n status?: string;\n source?: string;\n diagnostics?: Array<unknown>;\n}\n\n/** The rotated-out credential and when it stops working. */\nexport interface PreviousCredential {\n id: string;\n graceUntil?: string;\n}\n\n/** RFC 9457 problem details returned for every error. */\nexport interface Problem {\n type: string;\n /** Machine-readable error code (e.g. policy_denied). */\n title: string;\n status: number;\n detail?: string;\n instance?: string;\n details?: Record<string, unknown>;\n requestId?: string;\n traceId?: string;\n}\n\n/** Input to POST /v1/agents. (api: POST /v1/agents) */\nexport interface RegisterAgentRequest {\n environmentId: string;\n name: string;\n /** Default: \"\". */\n description?: string;\n ownerUserId?: string;\n ownerTeamId?: string;\n applicationId?: string;\n framework?: string;\n model?: string;\n /** Default: \"standard\". */\n riskTier?: RiskTier;\n /** Default: []. */\n tags?: Array<string>;\n /** Default: {}. */\n metadata?: Record<string, unknown>;\n credential?: CreateCredentialRequest;\n}\n\n/** Response of POST /v1/agents: the agent plus its initial credential (null unless requested). */\nexport interface RegisteredAgent {\n id: string;\n name: string;\n description?: string;\n status: AgentStatus;\n statusReason?: string | null;\n projectId?: string;\n environmentId?: string;\n applicationId?: string | null;\n ownerUserId?: string | null;\n ownerTeamId?: string | null;\n ownerEmail?: string | null;\n framework?: string | null;\n model?: string | null;\n riskTier?: string;\n tags?: Array<string>;\n metadata?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n lastSeenAt?: string | null;\n credentials?: Array<AgentCredential>;\n credential?: IssuedCredential | null;\n}\n\n/** Input to PUT /v1/policies/{id}/tests (replaces the whole suite atomically). (api: PUT /v1/policies/{id}/tests) */\nexport interface ReplacePolicyTestsRequest {\n tests: Array<PolicyTestCase>;\n}\n\n/** Query parameters for GET /v1/replay/{principalId}. (api: GET /v1/replay/{principalId}) */\nexport interface ReplayParams {\n from?: string;\n to?: string;\n /** Default: 200. */\n limit?: number;\n}\n\n/** Input to POST /v1/traces/spans (1-500 agent-side spans). (gateway: POST /v1/traces/spans) */\nexport interface ReportSpansRequest {\n spans: Array<AgentSpan>;\n}\n\n/** Response of POST /v1/traces/spans (spans outside +/-24h of now are rejected). */\nexport interface ReportSpansResult {\n accepted: number;\n rejected: number;\n}\n\n/** Input to POST /v1/secrets/{id}/revoke (one version, or the whole secret). (api: POST /v1/secrets/{id}/revoke) */\nexport interface RevokeSecretRequest {\n version?: number;\n reason?: string;\n}\n\n/** Response of POST /v1/secrets/{id}/revoke. */\nexport interface RevokeSecretResult {\n revoked: boolean;\n}\n\n/** Input to POST /v1/policies/{id}/rollback (default: the previously deployed version). (api: POST /v1/policies/{id}/rollback) */\nexport interface RollbackPolicyRequest {\n versionId?: string;\n comment?: string;\n}\n\n/** Input to POST /v1/credentials/{id}/rotate. (api: POST /v1/credentials/{id}/rotate) */\nexport interface RotateCredentialRequest {\n /** Default: 60. */\n gracePeriodMinutes?: number;\n publicJwk?: Record<string, unknown>;\n}\n\n/** */\nexport interface SecretGenerateOptions {\n length?: number;\n}\n\n/** Input to POST /v1/secrets/{id}/rotate (a new value, or generate one). (api: POST /v1/secrets/{id}/rotate) */\nexport interface RotateSecretRequest {\n value?: Record<string, unknown>;\n generate?: SecretGenerateOptions;\n}\n\n/** Response of POST /v1/credentials/{id}/rotate. */\nexport interface RotatedCredential {\n credential: AgentCredential;\n clientId: string;\n clientSecret?: string | null;\n previous: PreviousCredential;\n}\n\n/** Response of POST /v1/secrets/{id}/rotate. */\nexport interface RotatedSecret {\n id: string;\n version: number;\n mask?: string;\n}\n\n/** */\nexport interface ScenarioContent {\n source: string;\n text: string;\n origin?: string;\n}\n\n/** */\nexport interface ScenarioExecution {\n connectionId: string;\n action: string;\n /** Default: {}. */\n input?: Record<string, unknown>;\n}\n\n/** */\nexport interface ScenarioHistory {\n velocity1m?: number;\n velocity5m?: number;\n recentDenials?: number;\n openAlerts?: number;\n}\n\n/** Delegation context of a synthetic principal. */\nexport interface SyntheticDelegation {\n depth: number;\n chain: Array<string>;\n originatingUserId?: string;\n scopes?: Array<string>;\n}\n\n/** A principal that does not exist (simulation only). */\nexport interface SyntheticPrincipal {\n /** agent (default), user or service_account. */\n type?: string;\n id?: string;\n tags?: Array<string>;\n /** low, standard (default), high or critical. */\n riskTier?: string;\n ownerUserId?: string;\n ownerTeamId?: string;\n orgRole?: string;\n metadata?: Record<string, unknown>;\n delegation?: SyntheticDelegation;\n}\n\n/** Who the scenario runs as: exactly one of agentId (a real agent) or synthetic. */\nexport interface ScenarioPrincipal {\n agentId?: string;\n synthetic?: SyntheticPrincipal;\n}\n\n/** */\nexport interface ScenarioRequest {\n action: string;\n resource: string;\n /** Default: {}. */\n resourceAttributes?: Record<string, unknown>;\n /** Default: {}. */\n context?: Record<string, unknown>;\n outboundData?: unknown;\n}\n\n/** */\nexport interface ScenarioTaint {\n score: number;\n source: string;\n origin?: string;\n}\n\n/** Secret version metadata (never ciphertext or value). */\nexport interface SecretVersionInfo {\n id: string;\n version: number;\n status?: string;\n kmsKeyId?: string;\n expiresAt?: string | null;\n createdBy?: string | null;\n createdAt?: string;\n revokedAt?: string | null;\n}\n\n/** Secret metadata (GET /v1/secrets, GET/PATCH /v1/secrets/{id}). The value is never returned. */\nexport interface Secret {\n id: string;\n projectId?: string | null;\n environmentId?: string | null;\n name: string;\n type: SecretType;\n description?: string;\n metadata?: Record<string, unknown>;\n accessPolicy?: Record<string, unknown>;\n mask?: string;\n status?: string;\n currentVersion?: number;\n expiresAt?: string | null;\n rotationPolicy?: Record<string, unknown>;\n lastRotatedAt?: string | null;\n lastUsedAt?: string | null;\n useCount?: number;\n createdBy?: string | null;\n createdAt?: string;\n updatedAt?: string;\n versions?: Array<SecretVersionInfo>;\n}\n\n/** Response of GET /v1/secrets. */\nexport interface SecretList {\n data: Array<Secret>;\n}\n\n/** Response of GET /v1/replay/{principalId}: everything a principal did in a window. */\nexport interface SessionReplay {\n principalId: string;\n from?: string;\n to?: string;\n steps?: Array<unknown>;\n traces?: Array<string>;\n}\n\n/** Response of POST /v1/auth/refresh (refresh tokens rotate: store the new one). */\nexport interface SessionTokens {\n accessToken: string;\n tokenType?: string;\n /** Access token lifetime in seconds. */\n expiresIn: number;\n refreshToken?: string;\n refreshExpiresAt?: string;\n familyId?: string;\n}\n\n/** */\nexport interface SimulationExpectation {\n decision?: Decision;\n decisionIn?: Array<Decision>;\n riskLevel?: RiskLevel;\n minRiskScore?: number;\n maxRiskScore?: number;\n minApprovers?: number;\n dlp?: DlpAction;\n injectionAtLeast?: InjectionLevel;\n injectionAtMost?: InjectionLevel;\n reasonIncludes?: string;\n}\n\n/** A scenario that failed in the previous run and passes now. */\nexport interface SimulationFixed {\n key: string;\n label?: string;\n}\n\n/** A scenario that passed in the previous run and fails now. */\nexport interface SimulationRegression {\n key: string;\n label?: string;\n previous?: string | null;\n now?: string | null;\n}\n\n/** */\nexport interface SimulationScenario {\n key?: string;\n label: string;\n category?: string;\n description?: string;\n principal: ScenarioPrincipal;\n request?: ScenarioRequest;\n execution?: ScenarioExecution;\n content?: ScenarioContent;\n history?: ScenarioHistory;\n taint?: ScenarioTaint;\n expect?: SimulationExpectation;\n}\n\n/** Outcome of one scenario. */\nexport interface SimulationResult {\n index?: number;\n key?: string;\n label?: string;\n category?: string | null;\n scenario?: SimulationScenario;\n /** Decision, risk, approval plan, DLP/injection outcome (or error). */\n actual?: Record<string, unknown>;\n expected?: SimulationExpectation | null;\n passed?: boolean | null;\n failures?: Array<string>;\n}\n\n/** Totals of a simulation run. */\nexport interface SimulationSummary {\n total: number;\n withExpectations?: number;\n passed?: number;\n failed?: number;\n errors?: number;\n byDecision?: Record<string, unknown>;\n changedFromBaseline?: number;\n byCategory?: Array<unknown>;\n regressions?: number;\n fixed?: number;\n previousRunId?: string | null;\n}\n\n/** Response of POST /v1/simulations/run (also the body of its HTTP 422 with failOnMismatch). */\nexport interface SimulationRun {\n /** Null when persist=false. */\n id?: string | null;\n name?: string;\n status: SimulationStatus;\n environment?: EnvironmentRef;\n summary: SimulationSummary;\n regressions?: Array<SimulationRegression>;\n fixed?: Array<SimulationFixed>;\n results: Array<SimulationResult>;\n durationMs?: number;\n}\n\n/** Input to POST /v1/simulations/run. With failOnMismatch, a failed/errored run is returned with HTTP 422. (api: POST /v1/simulations/run) */\nexport interface SimulationRunRequest {\n environmentId: string;\n name?: string;\n /** Default: []. */\n scenarios?: Array<SimulationScenario>;\n scenarioSetId?: string;\n /** Default: []. */\n libraryIds?: Array<string>;\n /** Default: []. */\n policyOverrides?: Array<PolicyOverride>;\n riskOverride?: Record<string, unknown>;\n /** Default: true. */\n liveHistory?: boolean;\n /** Default: \"api\". */\n trigger?: string;\n /** Default: true. */\n persist?: boolean;\n /** Default: false. */\n failOnMismatch?: boolean;\n}\n\n/** OAuth 2.0 token endpoint response (POST {api}/v1/auth/token). */\nexport interface TokenResponse {\n access_token: string;\n token_type: string;\n /** Lifetime in seconds. */\n expires_in: number;\n scope?: string;\n refresh_token?: string;\n issued_token_type?: string;\n}\n\n/** A stored span (platform or agent-reported). */\nexport interface TraceSpan {\n traceId: string;\n spanId: string;\n parentSpanId?: string | null;\n name: string;\n kind?: SpanKind;\n service?: string;\n /** platform or agent. */\n source?: string;\n principalType?: string | null;\n principalId?: string | null;\n startTime?: string;\n durationMs?: number;\n status?: SpanStatus;\n statusMessage?: string | null;\n attributes?: Record<string, unknown>;\n events?: Array<unknown>;\n}\n\n/** Response of GET /v1/traces/{traceId}: span tree, correlated records, timeline and breakdown. */\nexport interface Trace {\n traceId: string;\n startedAt?: string | null;\n durationMs?: number | null;\n spans: Array<TraceSpan>;\n breakdown?: Record<string, unknown>;\n timeline?: Array<unknown>;\n records?: Record<string, unknown>;\n}\n\n/** Query parameters for GET /v1/traces. (api: GET /v1/traces) */\nexport interface TraceSearchParams {\n from?: string;\n to?: string;\n principalId?: string;\n name?: string;\n service?: string;\n status?: string;\n minDurationMs?: number;\n attribute?: string;\n /** Default: 50. */\n limit?: number;\n}\n\n/** One trace in GET /v1/traces. */\nexport interface TraceSummary {\n traceId: string;\n startedAt?: string;\n durationMs?: number;\n spanCount?: number;\n errorCount?: number;\n rootName?: string | null;\n principalId?: string | null;\n services?: Array<string>;\n}\n\n/** Response of GET /v1/traces. */\nexport interface TraceSearchResult {\n data: Array<TraceSummary>;\n}\n\n/** Input to PATCH /v1/agents/{id}. (api: PATCH /v1/agents/{id}) */\nexport interface UpdateAgentRequest {\n name?: string;\n description?: string;\n ownerUserId?: string | null;\n ownerTeamId?: string | null;\n framework?: string;\n model?: string;\n riskTier?: RiskTier;\n tags?: Array<string>;\n metadata?: Record<string, unknown>;\n}\n\n/** Input to PATCH /v1/alerts/{id}. (api: PATCH /v1/alerts/{id}) */\nexport interface UpdateAlertRequest {\n status?: AlertStatus;\n assigneeId?: string | null;\n resolution?: string;\n note?: string;\n}\n\n/** Input to PATCH /v1/connections/{id}. (api: PATCH /v1/connections/{id}) */\nexport interface UpdateConnectionRequest {\n description?: string;\n config?: Record<string, unknown>;\n allowedHosts?: Array<string>;\n secretId?: string | null;\n status?: string;\n timeoutMs?: number;\n maxRetries?: number;\n signRequests?: boolean;\n connectorVersion?: string;\n}\n\n/** Input to PUT /v1/policies/{id}: saves a new version (exactly one of source or ast). (api: PUT /v1/policies/{id}) */\nexport interface UpdatePolicyRequest {\n source?: string;\n ast?: Record<string, unknown>;\n /** Default: \"\". */\n message?: string;\n description?: string;\n}\n\n/** Input to PATCH /v1/secrets/{id} (metadata only). (api: PATCH /v1/secrets/{id}) */\nexport interface UpdateSecretRequest {\n description?: string;\n metadata?: Record<string, unknown>;\n accessPolicy?: SecretAccessPolicy;\n expiresAt?: string | null;\n /** Default: {\"strategy\":\"manual\"}. */\n rotationPolicy?: SecretRotationPolicy;\n status?: string;\n}\n\n/** Input to POST /v1/audit/verify (default: the whole chain). (api: POST /v1/audit/verify) */\nexport interface VerifyAuditRequest {\n fromSeq?: number;\n toSeq?: number;\n maxEvents?: number;\n}\n"],"mappings":";AAQO,SAAS,YAAY,QAA8B;AACxD,SAAO,OAAO,UAAU,IAAI,aAAa,6BAA6B,YAAY;AACpF;AAEO,IAAM,cAAqB;AAAA,EAChC,KAAK,MAAM,KAAK,IAAI;AAAA,EACpB,OAAO,CAACA,KAAI,WACV,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,QAAI,QAAQ,QAAS,QAAO,OAAO,YAAY,MAAM,CAAC;AACtD,UAAM,UAAU,MAAM;AACpB,mBAAa,KAAK;AAClB,aAAO,YAAY,MAAO,CAAC;AAAA,IAC7B;AACA,UAAM,QAAQ,WAAW,MAAM;AAC7B,cAAQ,oBAAoB,SAAS,OAAO;AAC5C,cAAQ;AAAA,IACV,GAAG,KAAK,IAAI,GAAGA,GAAE,CAAC;AAClB,YAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,EAC3D,CAAC;AACL;;;ACZO,IAAM,iBAAN,cAA6B,MAAM;AAAA;AAAA,EAE/B;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAAiB;AAC3B,UAAM,SAAS,KAAK,UAAU,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Q;AAAA,EACR,mBAAmB;AAAA,EACnB,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,WAAW;AACb;AAIO,IAAM,iBAAiB;AAAA,EAC5B,MAAM;AAAA,EACN,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AACZ;AAIO,IAAM,YAAY;AAAA,EACvB,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,UAAU;AACZ;AAIO,IAAM,qBAAqB;AAAA,EAChC,OAAO;AAAA,EACP,mBAAmB;AAAA,EACnB,MAAM;AACR;AAIO,IAAM,WAAW;AAAA,EACtB,KAAK;AAAA,EACL,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AACZ;AAIO,IAAM,aAAa;AAAA,EACxB,SAAS;AAAA,EACT,aAAa;AAAA,EACb,UAAU;AAAA,EACV,aAAa;AAAA,EACb,OAAO;AAAA,EACP,SAAS;AAAA,EACT,SAAS;AACX;AAIO,IAAM,mBAAmB;AAAA,EAC9B,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,OAAO;AACT;AAIO,IAAM,WAAW;AAAA,EACtB,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AACZ;AAIO,IAAM,aAAa;AAAA,EACxB,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,OAAO;AACT;","names":["ms","TRACEPARENT"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@gebsecure01/sdk",
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Official TypeScript/JavaScript SDK for the GebSecure AI Agent Security & Governance Platform",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.cjs",
|
|
9
|
+
"module": "./dist/index.js",
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"require": {
|
|
18
|
+
"types": "./dist/index.d.cts",
|
|
19
|
+
"default": "./dist/index.cjs"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"CHANGELOG.md"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=20"
|
|
31
|
+
},
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/gebsecure/gebsecure.git",
|
|
35
|
+
"directory": "sdks/typescript"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://docs.gebsecure.dev/sdks/typescript",
|
|
38
|
+
"keywords": [
|
|
39
|
+
"gebsecure",
|
|
40
|
+
"ai-agents",
|
|
41
|
+
"authorization",
|
|
42
|
+
"security",
|
|
43
|
+
"governance",
|
|
44
|
+
"sdk"
|
|
45
|
+
],
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsup",
|
|
51
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
52
|
+
"test": "vitest run --root ../.. --project unit sdks/typescript/test",
|
|
53
|
+
"prepublishOnly": "npm run build"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"tsup": "^8.5.1"
|
|
57
|
+
}
|
|
58
|
+
}
|